Showing posts with label Emacs. Show all posts
Showing posts with label Emacs. Show all posts

2014-11-19

Autocompletion for C and C++ with Emacs 24

I have already done a blog post on auto completion using Emacs. But that was back in Emacs 23 days. Long ago...

Since then a lot has happened. Emacs 24 has been released, package managers like MELPA or ELPA have become standard, and company-mode seems to be winning against auto-complete. Also, clang has made huge strides forward.

So it is time to revisit the task of developing C or C++ using Emacs. I have put online an easy-to-install Emacs init.el that you can use as a start for your own development environment. I am using the OS X version of Emacs, but this should also work on Linux, given that you have clang and git installed.

You can install this init.el by issuing the following commands:

cd
git clone https://github.com/root42/yet-another-emacs-init-el
mkdir ~/.emacs.d
cd ~/.emacs.d
ln -snf ../yet-another-emacs-init-el/init.el .

The file will make sure that upon startup of Emacs all necessary packages are installed, like company, magit but also LaTeX tools like aucTeX or refTeX. You can disable this check (or individual packages) in the init.el.

The code is up on github, so feel free to fork and/or contribute.

When doing simple C++ programming using only standard libraries, you should be ready to go. For more complex projects, you have to tweak the clang parameters, so that the compiler will find the header files. Completion happens automatically after ".", "->" and "::" but also when pressing M-/. You can rebind this key in the init.el, of course. This is what the completion looks like:


My most commonly used keys that I have re-bound are as follows:
  • f3 - Runs ff-find-other-file, trying to switch between header and implementation for C/C++ programs.
  • f4 - Toggles the last two used buffers.
  • f5, f6 - If tabbar is enabled (tabbar-mode), navigates back/forward through tabs.
  • f7 - Toggle ispell dictionaries (german/english).
  • f8 - Kill current buffer.
  • f9 - Run compile.
  • M-? - Run grep.
  • M-n - Go to next error in compilation buffer.
  • M-S-n - Go to previous error in compilation buffer.
  • M->, M-< - Go to next/previous Emacs frame.
  • M-/ - Run autocompletion using company mode.
  • C-x o, C-x C-o - Go to next/previous Emacs window
Very nice is also the magit-mode, which is a very sane interface to git for Emacs. It looks like this:
You can run it by executing M-x magit-status. Just type ? to get online help. Magit uses simple one-character-commands, like s for stage, c for commit, p for push and so on.

Currently I am evaluating the integration of lldb into Emacs, but haven't come far enough to say that I have found a powerful and flexible interface, apart from the standard command line. So there's more to come, hopefully!

2014-08-31

How to view clojure docs in Emacs Cider

Developing clojure with Emacs Cider is great. To be able to view summaries for clojure functions and special forms, type this in you Cider REPL:

(use 'clojure.repl)

Afterwards, you can do stuff like this:
my.repl> (doc conj)
-------------------------
clojure.core/conj
([coll x] [coll x & xs])
  conj[oin]. Returns a new collection with the xs
    'added'. (conj nil item) returns (item).  The 'addition' may
    happen at different 'places' depending on the concrete type.
nil

2014-08-20

How to automatically refresh Cider when saving a clojure file in Emacs

Emacs has a great mode for using Clojure called Cider. Cider comes with an interactive REPL. The REPL allows you to test your code, start web apps, if you are using Luminus, and all in all accelerates  development. One annoying thing though is that you have to refresh Cider every time you saved your sources. The good thing is that you can do this automatically. Just add the following to your init.el. I took the function from a blog post by Kris Jenkins:

  (add-hook 'cider-mode-hook 
     '(lambda () (add-hook 'after-save-hook 
      '(lambda () 
         (if (and (boundp 'cider-mode) cider-mode)
      (cider-namespace-refresh)
           )))))

  (defun cider-namespace-refresh ()
    (interactive)
    (cider-interactive-eval
     "(require 'clojure.tools.namespace.repl)
    (clojure.tools.namespace.repl/refresh)"))

  (define-key clojure-mode-map (kbd "C-c C-r") 'cider-namespace-refresh)

Additionally, you can now run the refresh command manually, by hitting C-c C-r.

Update: I changed the after-save-hook to only trigger if we are in a buffer that has cider-mode enabled. Otherwise every save command in Emacs would have triggered the refresh!

2014-03-16

Getting Emacs for Mac OS X to honour the shell environment

If your are using the excellent Emacs for Mac OS X distribution, you may have noticed that it does not use the environment you may have defined in your ~/.bashrc. This can be a problem if you are using MacPorts, for example to install clojure and Leiningen. You will get an error message like this, when trying to run inferior-lisp in clojure-mode:

apply: Searching for program: No such file or directory, lein

This can be avoided by using the excellent exec-path-from-shell package for Emacs. It is available via (M)ELPA, just install it using list-packages, or download it from github. You can enable it, especially for OS X, by putting this in your init.el:

(when (memq window-system '(mac ns))
    (exec-path-from-shell-initialize))

2013-09-18

Working around connection problems with Emacs Tramp

From time to time I have to edit files on a SunOS 5.10 server. I use Emacs with tramp for this. However, after some time I get this error message from tramp:

File error: Couldn't find exit status of `test -e ...

It seems that the ssh connection goes bad for some reason. After this you won't be able to save the file anymore. You can work around this by running M-x tramp-cleanup-all-connections and then saving again.

2013-01-22

How to determine if current buffer is tramp buffer in Emacs

Tramp is Emacs' way to access remote files, e.g. via SSH. To determine if the current buffer is accessing a tramp file (e.g. to not try to run gtags or similar), try this:
(not (tramp-tramp-file-p (buffer-file-name (current-buffer))))

2012-10-29

Improved handling of background GNU Global update

Earlier this year I detailed how to run gtags of GNU Global when Emacs is idle. However, this collides with some special Emacs modes, like ediff. That mode makes its own Emacs frame layout, which can be destroyed by the xgtags incremental update buffer. So I conceived a way to disable gtags temporarily as long as ediff is active:
;; This stuff is only needed, if you haven't got xgtags loaded yet
(autoload 'gtags-mode "gtags" "" t)
(require 'xgtags)
(add-hook 'c-mode-common-hook (lambda () (xgtags-mode 1)))
(defun global-update-incrementally () (shell-command "global -u -q" "*Messages*" "*Messages*") )

;; Call gtags update when idle for some time
(defcustom my-gtags-update-idle-time 60
  "Number of idle seconds before an incremental gtags update is launched"
  :group 'my-group
  :type 'integer
  )

;; initially allow gtags updates
(setq my-gtags-update-active t)

(run-with-idle-timer my-gtags-update-idle-time t
                     (lambda ()
                       (if (and my-gtags-update-active
                                (not (minibufferp) )
                                )
                           (progn
                             (message "Running gtags...")
                             (global-update-incrementally)
                             )
                         )
                       )
                     )

(add-hook 'ediff-quit-hook 
          (lambda () 
            (message "Activating gtags update.")
            (setq my-gtags-update-active t) 
            )
          )

(add-hook 'ediff-before-setup-hook 
          (lambda () 
            (message "Deactivating gtags update.")
            (setq my-gtags-update-active nil) 
            )
          )

2012-08-31

Java Autocompletion for Emacs

The past few weeks I have been using the great eclim, and the corresponding emacs-eclim package. It allows you to use many of Eclipse's features in your favourite editor. The installation of emacs-eclim is rather easy, and the one for eclim is even easier, since it comes with a simple clickety-click-installer.

I use emacs-eclim for Java development, and it works rather well. I use the two functions ac-complete-emacs-eclim and ac-complete-eclim-c-dot for auto-completion, which is the most important aspect when using such heavily object oriented languages and when developing large projects. Also useful are the functions eclim-java-import-missing, and eclim-java-remove-unused-imports. The current project can be compiled by calling eclim-project-build.

In theory, you can also use eclim with CDT for C++ development and auto-completion, but I rather stick with my earlier clang based solution, which is very fast and accurate.

2012-08-09

An argument for Emacs window-local variables

The Emacs developers used argue that window-local variables are not neccessary, since there are indirect buffers, which can do mostly the same thing. In recent Emacs releases, the window state is anyway mostly hidden from Lisp. However, I think sometimes it is useful to have window-local variables, instead of buffer-local variables. Emacs is very buffer-centric, but sometimes the UI and the user's view is rather window-centric. Two use-cases for window-local variables are:
I am using ECB, and it would be neat to enable or disable minor modes according to the ECB window I am in. This is also useful for people who manually tile their Emacs frame. In the main edit window, I like to have the tabbar, but in my compilation window, I'd rather not.

The buffer stack for a navigation history definitely should be window specific. Everything else would be very confusing. If a window is split, the new window will inherit its parents history.

2012-08-07

Updating GNU Global GTAGS file when Emacs is idle

GNU Global is a very useful code navigation tool. In order for it to work well, it needs to be run regularly. Until now, I used the after-save-hook, to keep it up to date. However, when using emacs-eclim (also see Eclim), saving becomes so frequent that performance takes a massive hit. So I whipped up this small code snippet to run Global only when Emacs is idle for some number of seconds (default is 10):
(defcustom my-gtags-update-idle-time 10
  "Number of idle seconds before an incremental gtags update is launched"
  :group 'my-group ;; Put whatever customization group you like here
  :type 'integer
  )
(run-with-idle-timer my-gtags-update-idle-time t
                     (lambda ()
                       (if (not (minibufferp) )
                           (progn
                             (message "Running gtags...")
                             (global-update-incrementally)
                             )
                         ) 
                       )
                     )

2012-07-31

Switching to a Java package implementation in Emacs

There already quite a few methods to switch between header and implementation of C and C++ sources in Emacs. Maybe I will put one of those here as well later. But now I needed something different: In a big project, I would like to point at a line like import com.foo.tech.implementation.SomeClass; and Emacs automatically visits the file where this class has been implemented. I wrote two small Elisp functions to perform this:
(defun my-switch-to-java-implementation (packagename classname)
  "Tries to switch to the java source file containing the package packagename and
the class classname."
  (with-temp-buffer
    (shell-command-to-string
     (format "%s %s -iname '*.java' | xargs egrep -l '%s' | sort -u | xargs egrep -l 'class %s' | head -n 1" 
             "find"
             "path/to/your/java/sources"
             packagename
             classname
             )
     (current-buffer) )
    (if (= (count-lines (point-min) (point-max) ) 1)
        (progn
          (search-forward "\n")
          (replace-match "")
          (find-file (buffer-string))
          )
      (message "Could not find suitable implementation.")
      )
    )
  )

(defun my-switch-to-java-implementation-at-point ()
  "Tries to switch to the java source file which contains the package and class imported
in the current line."
  (interactive)
  (save-excursion
    (beginning-of-line)
    (if (looking-at "^import \\(.*\\)\\.\\(.+\\);$")
        (let ( (packagename (buffer-substring (match-beginning 1) (match-end 1) ) )
               (classname (buffer-substring (match-beginning 2) (match-end 2) ) ) )
          (my-switch-to-java-implementation packagename classname)
          )
      (message "This is not an import")
      )
    )
  )
You basically call my-switch-to-java-implementation-at-point (e.g. by binding it to a key) when you are on the import line. Emacs then launches find and grep to look for the definition of your class. Of course, using something like GNU Global would be faster, but also a bit more tricky, since it does not use the packagename, but rather only the class name, which might be used multiple times in your project.
Also note that you have to set the path to your Java source files. I suggest you make a customizable variable of that, or use your ede-project-root or something similar.

2012-07-17

Commenting out line or region in Emacs

What I always wanted: commenting or uncommenting a line or region using emacs. Of course, there is comment-region, but this is much nicer:

(defun comment-or-uncomment-line-or-region ()
  "Comments or uncomments the current line or region."
  (interactive)
  (if (region-active-p)
      (comment-or-uncomment-region (region-beginning) (region-end))
    (comment-or-uncomment-region (line-beginning-position) (line-end-position))
    )
  )

(define-key c-mode-base-map (kbd "C-/") 'comment-or-uncomment-line-or-region)
See also the corresponding Stackoverflow question.

2012-07-02

A nice C++ autocomplete configuration for Emacs

Update: I have written a new blog post about this, with updated information and using new and current packages.

Autocompletion for C++ in Emacs is a hot topic -- at least for Emacs users. At least for Emacs users who code C++... So here is my setup that I use, and which works reasonably well. I use the autocomplete package with the autocomplete-clang extension.



You can get the autocomplete package at github and the clang extension is available also on many repositories on github I used the one by brianjcj. Under OS X I use clang 3.1, under Linux I use clang 3.0. You may have to point autocomplete to the correct binary via the customizable variable ac-clang-executable.

So basically you have to clone the autocomplete package, clone the clang extension and copy the auto-complete-clang.el file into the same folder. I used ~/bin/emacs/auto-complete, but you can choose any directory. Maybe you have your own site-lisp folder.

(defcustom mycustom-system-include-paths '("./include/" "/opt/local/include" "/usr/include" )
  "This is a list of include paths that are used by the clang auto completion."
  :group 'mycustom
  :type '(repeat directory)
  )

(add-to-list 'load-path "~/bin/emacs/auto-complete")
(require 'auto-complete-config)
(add-to-list 'ac-dictionary-directories "~/bin/emacs/auto-complete/ac-dict")
(ac-config-default)
(require 'auto-complete-clang)
(setq clang-completion-suppress-error 't)
(setq ac-clang-flags
      (mapcar (lambda (item)(concat "-I" item))
              (append 
               mycustom-system-include-paths
               )
              )
      )

(defun my-ac-clang-mode-common-hook()
  (define-key c-mode-base-map (kbd "M-/") 'ac-complete-clang)
)

(add-hook 'c-mode-common-hook 'my-ac-clang-mode-common-hook)

The key binding to M-/ is useful on US-keyboard, you may change that to your liking. So to start autocompletion, just type something and hit M-/. Clang will try to parse your file up to point and give useful completions. If it cannot parse your source, the cursor at point will turn red, and the minibuffer will show the error message. Most likely you forgot to add some include paths to mycustom-system-include-paths, or you really do have a syntax error.

The customizable variable mycustom-system-include-paths can be named arbitrarily. Many thanks to the helpful people over at stackoverflow for supplying me with the answer how to make a directory list nicely customizable.

2012-06-28

Limiting the number of lines in the compilation window

For large projects, the output in the compilation window can become quite large. Furthermore, I use the ANSI coloring functionality, so that colored build systems look nice. These two things together can slow down Emacs significantly. However, when the compilation buffer gets so long, the output is most probably only success messages anyway. The errors would already have stopped the compilation process. So I wrote the following function to trim the compilation buffer:
(defun my-limit-compilation-buffer ()
  "This function limits the length of the compilation buffer.
It uses the variable my-compilation-buffer-length to determine
the maximum allowed number of lines. It will then delete the first 
N+50 lines of the buffer, where N is the number of lines that the 
buffer is longer than the above mentioned variable allows."
  (toggle-read-only)
  (buffer-disable-undo)
  (let ((num-lines (count-lines (point-min) (point-max))))
    (if (> num-lines my-compilation-buffer-length)
        (let ((beg (point)))
          (goto-char (point-min))
          (forward-line 
           (+ 
            (- num-lines my-compilation-buffer-length)
            (/ my-compilation-buffer-length 10) ) )
          (delete-region (point-min) (point))
          (goto-char beg)
          )
      )
    )
  (buffer-enable-undo)
  (toggle-read-only)
  )
Of course, now you still have to register this function to be actually applied to the compilation buffer, so I read about customization variables. And out came this, to introduce a customizable variable for toggling the compilation-trimming behaviour:
(defun set-my-compilation-buffer-length (symbol value)
  (set-default symbol value)
  (if value
      (add-hook 'compilation-filter-hook 'my-limit-compilation-buffer)
    (remove-hook 'compilation-filter-hook 'my-limit-compilation-buffer)
    )
  )

(defcustom my-compilation-buffer-length 2500 
  "The maximum number of lines that the compilation buffer is allowed to store"
  :set 'set-my-compilation-buffer-length)
This is my first shot at such "complex" Emacs Lisp functions, so maybe it's not optimal, and I don't know much about the Emacs Lisp API either. Improvement suggestions are welcome!
Update: Over at Stackoverflow someone pointed me to a function that is already built into Emacs. So here's the alternative solution:
(add-hook 'compilation-filter-hook 'comint-truncate-buffer)
(setq comint-buffer-maximum-size 2000)
This function is used for other comint buffers as well, such as the shell.

2012-06-26

Emacs whitespace-mode

I just found out about whitespace-mode. Very useful if whitespaces are of syntactic value. For example in Makefiles. Emacs' makefile-mode already shows leading spaces as pink, but leading and trailing spaces might be problematic in other cases as well. The whitespace-mode shows all kinds of spaces, eight spaces are highlighted in bright yellow ("no tab"), tabs are also visualized, as are newline characters.


2012-05-18

Make emacsclient work with raise-frame

Emacs has the wonderful emacsclient for quickly editing files in Emacs from external tools, e.g. the shell. I am using the following alias to edit a file using emacsclient:
alias ec='emacsclient -n'
However, then Emacs's window does not get raised, nor activated. There is also a bug in Emacs' raise-frame function, which hinders any efforts. The best solution so far for this is described here, which uses wmctrl to activate and raise Emacs. My Emacs runs on Desktop 1, so I use wmctrl also to first switch to my Emacs desktop. You could probably make a more elaborate function which first finds the desktop that Emacs is running on, but this is good enough for me. So here is the slightly adjusted code snippet from the above link:
;;
;; Start emacs server
;;
(server-start)
(defadvice raise-frame (after make-it-work (&optional frame) activate)
    "Work around some bug? in raise-frame/Emacs/GTK/Metacity/something.
     Katsumi Yamaoka posted this in 
     http://article.gmane.org/gmane.emacs.devel:39702"
     (call-process
     "wmctrl" nil nil nil "-s" "1")
     (call-process
     "wmctrl" nil nil nil "-i" "-R"
     (frame-parameter (or frame (selected-frame)) 'outer-window-id)))
(add-hook 'server-switch-hook 'raise-frame)

2012-05-14

Quickly toggle last two buffers in Emacs

I don't have much interesting stuff to post this month, so I'll just go with one little snippet for Emacs. Next months will be better, I promise!
In Emacs, you can switch buffers by hitting C-x b and typing a buffer name. If you just hit C-x b RET, Emacs will just go to the last buffer. This is an awful lot of keys for such a simple function. So quite a long time ago, I found this useful small function, but I forgot where. In my config I've bound it to F4. I use the function keys quite a bit for file and buffer operations, maybe because I am a big fan of the Midnight Commander...

(global-set-key [f4] (lambda () 
                      (interactive) 
                      (switch-to-buffer
                         (other-buffer 
                             (current-buffer) nil)
                      )))

2011-12-06

Emacs: Convert current buffer to utf-8

I just opened an old TeX file, which was still encoded in latin1. Now I wanted to re-save it as utf-8 in Emacs. This turns out to be very simple, as someone on #emacs at freenode told me. Just hit C-x RET f, and type utf-8 RET. On the next save (C-x C-s), the file will be written as utf-8.

2011-08-10

Emacs other-window backwards

I am currently writing a lot of text in Emacs, and I need to work on multiple files in parallel. So I use the split window functionality a lot. With C-x o you can switch to the next split window. However, it would be nice to go backward as well. The solution is simple, and is given on Stackoverflow and some other blogs:

(defun prev-window ()
  (interactive)
  (other-window -1))
(global-set-key (kbd "C-x p") 'prev-window)

Just put this in you init.el, and you can cycle backwards using C-x p.

2011-01-18

Note to self: C/C++/ObjC code completion for Emacs using CLang

I have to try this out some time: There is an Emacs mode for code completion using CLang. It is mentioned in a blog entry by some guy. The nice thing here would be, that it enables ObjC code completion, which is a good thing™. Especially if your are coding for OS X or iOS.