Posts Tagged ‘emacs’

CC and Java Customizations

Wednesday, August 26th, 2009

My job involves a lot of Java coding, so I have a few customizations for cc-mode and java-mode in order to make them easier to work with. While I don’t have too many at this time, they make working in Java a little more pleasant.

(require 'cc-mode)
(add-hook 'java-mode-hook 'c-subword-mode)
(add-hook 'c-mode-common-hook
          '(lambda ()
             (c-toggle-syntactic-indentation 1)
             (setq c-basic-offset 4)
	     (c-toggle-hungry-state 1)
             (c-toggle-electric-state 1)))

cc-mode, for those of you who don’t know, is emac’s base mode for c, c++, java, and a few other languages. It has a lot of keybindings in this mode for various movement commands, so you may want to look over the functions it gives. The manual is exhaustive and tells all the possible options you can do to modify it, but these are the ones I like the most. Java-mode is just a derived mode of cc-mode, so all hooks in c-mode-common-hook will be run for a java buffer.

C-subword-mode is a mode that treats changes of case to be word boundaries. This is often what I want, since Java uses camelcase by convention. If I want to change getBufferedReader() to getReader(), all I would have to do is place the point under ‘B’ and M-d to kill-word. Since Reader starts a new word, it will not be deleted. This can make it a bit less efficient to move past variables defined in camelcase, but if you’re traveling a long way you can probably get closer by searching for whatever it is.

The other hooks are all common to all cc-derived modes, since they are general utility functions. c-toggle-syntactic-indentatation will turn on indentation based on context; otherwise, all new lines will be aligned with the previous line. This also reindents the line on pressing of an ‘electric’ key, such as ‘;’, ‘(’, and many others. Without this command, creating a new line after opening a method would leave the point right below the first character in the function definition, instead of indenting it. the variable c-basic-offset just determines how large indentations should be; I like 4.

c-toggle-hungry-state and c-toggle-electric state turn on hungry deletion and eletric-mode, respectively. Hungry deletion is when backspacing or killing a character when on whitespace will delete not only one character, but to the next non-whitespace character. This is just very handy why you need to format code by deleting whitespace. Electric-mode will just turn on indentation when ‘electric’ keys are pressed.

Some people may be wondering why I don’t have CEDET or JDE in here. The problem with those packages is that they are incredibly slow and lag my emacs to the point of being unusable on most of my codebases - which is really annoying, since it makes programming in Java much better when it allows me to type. It provides some nice refactoring tools, automatic package importation, providing completion for the variable at point, and all sorts of nice stuff. I believe CEDET is being put into Emacs 23.2, so maybe when that comes out I’ll try it again and see if it’s gotten better.

The last thing you should know about if you are coding in emacs is M-x compile and M-x recompile. These commands give you nice buffers of the compile output with errors in red, linked to the location in the file in which they occur. You can cycle through the errors with next-error and previous-error (C-x ` and M-g p) without going into that buffer, making fixing your compile issues much easier.

Python-mode Customizations

Monday, August 24th, 2009

I do some Python coding on my own, and so I have a few python customizations. Python-mode now comes with GNU Emacs, and so these work pretty much out-of-the-box. However, this does not get autoloaded, so you have to put the following before modifying python-mode-map or python-mode-hook.

(require 'python)

Before you start modifying python-mode-hook or python-mode-map or you get void-variable errors. Python-mode-hook is a collection of functions that gets run whenever python is entered, and python-mode-map is the list of keybindings that python-mode provides. Anyway, on to the customizations:

(add-hook 'python-mode-hook
          '(lambda () (eldoc-mode 1)) t)

I’ve talked about eldoc-mode before here. It is still one of my favourite minor modes, and I am greatly saddened whenever I realize a programming mode doesn’t have it. Fortunately, Python does, so I always know the arguments to my functions.

(defun my-insert-self ()
  "Insert self. at the beginning of the current expression."
  (interactive)
  (save-excursion
    (search-backward-regexp "[ \n\t,(-]\\|^")
    (if (not (looking-at "^"))
        (forward-char))
    (insert "self.")))
(define-key	python-mode-map	(kbd "C-;")	'my-insert-self)

I forget to type ’self.’ in front of my variables a lot. If this happens, I can use this function to insert it at the beginning of the variable name I’m currently typing. This ends up saving me a ton of keypresses; I no longer have to navigate to the start of the name and back. This is even more efficient then typing ’self.’ in front of variable names; Two key presses instead of five, if you include the Control.

(defun python-self-insert-command ()
  "appends __ to the string if it should"
  (interactive)
  (save-excursion
    (let ((cur (point)))
      (search-backward-regexp "[\n\t .(-]\\|^" 0 t)
      (if (not (looking-at "^"))
          (forward-char 1))
      (if (looking-at "\\s\__")
          (setq my-temp-var t)
        (setq my-temp-var nil))))
  (save-excursion
    (when (> (point) 2 )
      (backward-char 2)
      (if (looking-at "__")
          (setq my-temp-var nil))))
  (if my-temp-var (insert "__"))
  (self-insert-command 1))
(define-key	python-mode-map (kbd ".")	'python-self-insert-command)
(define-key	python-mode-map " "	        'python-self-insert-command)
(define-key	python-mode-map (kbd "(")	'python-self-insert-command)

This function similarly helps when I forget to append ‘__’ to private variables. I usually remember to put them at the beginning of a variable or function name, but often forgot the end. This function will check to see if the current function/variable starts with __, and if so append __ to it. This only occurs, of course, if __ is not already appended to the variable. I bind this function to space, period, and paren, so that I don’t have to actively think about this for it to happen. This function is more complicated than it seems it should be, but I haven’t quite figured out how to simplify it.

I haven’t investigated python-mode very much, since I’ve recently been using Python only lightly. Looking over it’s documentation, it looks like there are a few commands that could be quite useful, and the next time I write a significant project in Python I’ll definitely look through the manual, but these functions should tide me over until then. If you know of any cool commands in python-mode, don’t hesitate to let me know.

One final thing I was playing with that sounded very useful was ropemacs, an emacs integration of a python refactoring library. This provides refactoring and intellisense, but I could never get it to work. Ropemacs requires pymacs in order to run. Pymacs is a package for Emacs that attempts to enable you to use Python to modify Emacs instead of elisp, which I’d certainly be on board with. However, loading it into my emacs ended up installing a lot of hooks that didn’t work, making it difficult to even quit. I tried getting it to work, but never managed to. I also had a few philosophical problems with it, in that it used python’s egg system and did not allow me to specify where I wanted everything installed; this makes it hard to keep under version control so all of my computers can easily obtain it. If you know an easy way of getting it configured and working, please let me know; I’d love to be able to play around with it.

Learning GNU Emacs

Friday, August 21st, 2009

I recently read a copy of O’Reilly’s Learning GNU Emacs. While fairly out-of-date(I read the 2nd edition, making it worse), it was still a valuable book for emacs beginners. Pretty much all of the items in the book are still around; the book may miss newer stuff than came in versions 20, but it covers the basics quite well. I didn’t learn a huge amount of useful things from it, since most of it I either already knew or didn’t care about, but it did tell me about some things I hadn’t known and was a great refresher. I think it would be great if you were just learning how to use emacs and wanted to get more proficient at it.

The book covers a wide range of topics, starting with basic editing tasks. It covers moving around the buffer, buffer and window management, and searching. These tasks are what Emacs novices need to know to start using Emacs, and the book does a very good job of introducing them. Even I learned about a few things, such as the various different kinds of searches and recursive edits. The book then quickly gets into more topics: file and directory management, as well as using a shell inside Emacs. Since I use Emacs almost exclusively for shell use, it’s nice to know other people thought this was rather important as well.

The next few chapters focused on a few things I don’t use Emacs for - email and browsing the Internet. It covers several different email setups, as well as GNUs. I, however, prefer gmail conversation threading to anything else I’ve used, so I’m going to stick with that. The section on browsing the Web and working remotely was out of date, mentioning ange-ftp and W3 instead of the newer Tramp and W3m. While Tramp is very useful, I actually haven’t liked web browsing with emadcs due to how slow it is. Until Emacs gets a faster browser, I’m going to have to stick with Firefox.

The section with more advanced text editing techniques unfortunately doesn’t cover some of the newer additions to Emacs, obviously. For example, the section on rectangle-editing does not cover the not-yet-developed(or at least included) cua-mode, which has the best rectangle implementation so far. There is also a chapter about various markup language modes, such as troff and noff. While these are probably not used much today(I hadn’t even heard of them before), the chapter also covers latex and html editing, which are still widely used. If you need to edit these types of documents, you should probably read the sections on them; otherwise, they aren’t going to contain any information you need.

The next few chapters got into the real meat of Emacs. Keyboard macros were covered extensively, including some tricks I didn’t know about. Since macros are essential to efficient use of Emacs, I’m very happy that they were covered so thoroughly. Customizing emacs is also covered, and some common customization options are discussed. For more advanced customizations, there is also a chapter on elisp that covers developing your own modes. The elisp chapter also covers elisp as a language, and while not complete is a good introduction to developing in elisp.

The next section covered programming modes, such as cc-mode and fortran. While Fortran isn’t used too much anymore, c and c++ definitely are, and the tutorial for cc-mode is pretty good. The chapter not only covers the modes, but how to integrate compiling into emacs, which is often quite useful. There is also a chapter on using Emacs in X, which is usually set up for you in modern emacs distributions

The chapter on version control showed the book’s age a bit, but was still very useful. I don’t use version control from emacs as much as I should, usually just opening up a shell buffer and executing commands from that, so this chapter was quite useful in explaining how to execute these commands using keyboard shortcuts. The three VC systems that emacs was said to support were SCCS, RCS, and CVS - not exactly in widespread use today. However, the commands that the book mentioned still work with the newer VCS’s that emacs comes with nowadays, so this section is still relevant with newer VCS’s like SVN and Git, the two I mainly use.

The book ends with a chapter on emac’s help commands, like describe-variable, describe-key, and apropos. I already knew about these options, but for a new user this section would be great - It gives them all the resources they need in order to get help on any new modes or problems they encounter. I’m not sure it should be at the end, as it is one of Emacs’ most important features, but at least it’s in the book.

All in all, this is a good book that is unfortunately rather dated. I wish it was updated to cover newer versions of emacs; as it is, it’s probably mostly useful only for newer users of emacs who need a introduction to the basic features that are in every release.

Top 10 Emacs Commands

Monday, August 17th, 2009

Last post, I talked about command-frequency-mode - both how to set it up and what it does. After I executed approximately 150000 commands, I found the most frequent ones, hoping to discover inefficiencies among my editing style that I could fix. This post has the top 10 different types of commands I tend to use, as long as subcommands and default keybindings. If you’re looking for a list of possible commands to use, you can just use these tables to increase your emacs knowledge. You can find more about these commands with C-h f, describe-function, and entering the command name.

Insertion

72045 46.17% self-insert-command Many
896 0.57% comint-send-input RET
629 0.40% newline-and-indent C-j
406 0.26% newline RET
323 0.21% slime-space SPACE
215 0.14% c-electric-paren (,)
176 0.11% c-indent-new-comment-line C-M-j
138 0.09% slime-repl-return RET
118 0.08% indent-new-comment-line C-M-j

The most frequent type of commands I use are, of course, related to inserting text. Self-insert-command is the basic command that insertion keys are bound to, which merely inserts the character pressed into the current location. The other input commands on the list are related either to inserting newlines, or special insert commands that do things such as indent the current line as well as insertion. Comint-send-input, for example, will execute the command you typed in as well as entering a blank line. Many of these commands will indent as well as adding a newline. indent-new-comment-line will also continue comments.

Movement

-

-

18034 11.56% next-line C-n
16036 10.28% previous-line C-p
1565 1.00% forward-char C-f
2099 1.35% backward-char C-b
1497 0.96% backward-paragraph M-{
1461 0.94% move-end-of-line C-e
1454 0.93% dired-previous-line p
1270 0.81% dired-next-line n
1162 0.74% back-to-indentation M-m
982 0.63% backward-word M-b
875 0.56% forward-paragraph M-}
525 0.34% end-of-buffer M->
497 0.32% forward-word M-f
370 0.24% end-of-visual-line C-e
308 0.20% beginning-of-buffer M-<

Movement commands are next frequent. These are mostly standard movement keys - either moving to the next of previous line, word, character, or paragraph are all standard commands that are some of the first you learn. Back-to-indentation I use probably more than most people, since I have it rebound to C-a instead of having that be the default key beginning-of-line. I tend to go to the end and beginning of buffer quite a bit, so these showed up.

Deletion

-

8218 5.27% delete-backward-char DEL
3498 2.24% backward-delete-char-untabify DEL
666 0.43% c-electric-backspace DEL
452 0.29% kill-and-join-forward C-k
333 0.21% kill-line C-k
329 0.21% backward-kill-word C-DEL
139 0.09% kill-word M-d
118 0.08% kill-visual-line C-k
176 0.11% delete-char DEL

Various ways of deleting text came in as the next most popular character. Most of these are more standard commands that everyone should know, and the various equivalents in other modes. Kill-line does sometimes act differently than most people expect, not killing newlines by default, but I prefer it’s default behaviour in most cases. It will kill from point to end of line, allowing you to replace whatever you just deleted.

Buffer Control

2069 1.33% other-window C-x o
1376 0.88% ido-exit-minibuffer C-g
769 0.49% ido-switch-buffer C-x b
613 0.39% ido-delete-backward-updir DEL
426 0.27% ido-kill-buffer C-x k
312 0.20% ido-find-file C-x C-f
212 0.14% ido-next-match RIGHT
111 0.07% dired-advertised-find-file v

These commands all relate to switching buffers and opening new windows. This allows you to have multiple buffers open and displayed at a time, to switch which buffers are displated, and create and kill existing buffers. These are not commands I’d expect beginning emacs users to learn, but I’d recommend anyone using emacs seriously to learn how to at least split the screen and use multiple buffers at a time. Most of these are Ido commands, which I talk about in my blog post here, but worse versions of the commands are available with the same keybindings if you haven’t enabled Ido.

Search

1155 0.74% isearch-printing-char Many
659 0.42% abort-recursive-edit C-]
273 0.17% isearch-other-control-char Many
196 0.13% isearch-repeat-forward C-s
174 0.11% isearch-repeat-backward C-r
164 0.11% isearch-forward C-s
121 0.08% isearch-backward C-r

Incremental search is just amazing. If you want to search for a word in your buffer, you can just press ‘C-s’ and start typing, and it will search as you type. C-s will go to the next match, and C-r will reverse direction and search backwards. You can also grab the word under point with C-w once you have entered isearch-mode by pressing C-s. The one thing that suprised me here was the large portion of abort-recursive-edits, since I almost never intentionally enter recursive edits.Recursive edits allow you to essentially suspend a search, edit the buffer some, and then resume the search. I should probably use these more than I do, but aborting recursive edit’s shouldn’t account for .42% of my commands.

History

554 0.36% undo C-/
291 0.19% comint-previous-input M-p
108 0.07% slime-repl-backward-input M-p

Now we’re getting to categories that are less than 1% of my total editing commands. These commands all involve using previously-entered data, either by undoing or using previous history. Undo works differently in emacs than most editors; in emacs, you can undo to any point in your editing of a buffer, one command at a time. However, there is no redo; if you want to redo, you need to perform a command and then undo twice after undoing. This will first perform the command, undo the command, and then undo the first undo. I really think there should be some type of redo command, but I’ve tried to implement it and it’s unfortunately rather difficult to get one that works well. The other two commands are all more standard terminal history commands, with shell-mode and slime specifically.

Completion

382 0.24% minibuffer-complete-word SPACE
573 0.37% pabbrev-expand-maybe TAB
197 0.13% comint-dynamic-complete TAB

Completion is another task I use a fair amount. One thing that immediately springs to mind is that yasnippet isn’t used at all here; I should make more extensive use of this. Pabbrev I’ve talked about here, and the other two commands in this category are fairly standard completion commands - comint-dynamic-complete is standard terminal tab-completion, whereas most people have probalby encountered minibuffer completion.

Miscellaneous

1063 0.68% save-buffer C-x C-s
568 0.36% cua-set-mark C-SPACE
418 0.27% execute-extended-command M-x
373 0.24% eval-last-sexp C-x C-e
312 0.20% keyboard-quit C-g
423 0.27% cua-paste C-y
165 0.11% slime-eval-last-expression C-x C-e
122 0.08% cua-copy-region M-w
107 0.07% dired-mark m

These are just miscellaneous commands that didn’t really fit into any category. Saving the buffer, setting the mark, M-x, C-y, and M-w are all command any basic emacs user should know. The cua-paste and cua-copy-region are just cua’s rebindings of kill-ring-save and yank, which function in pretty much the same way. Eval-last-sexp and slime-eval-last-expression are commands that are very useful for editing lisp; they will evaluate the expression right before point. Dired-mark is a dired command I’ve blogged about here.

Conclusions

Looking over these, there are several inefficiencies I noticed in the way I use emacs.
1) I use next-line and previous-line far too much. These should not be 10% of the commands I issue each. If I am moving around the buffer this much, I should learn more efficient ways to do so - either by using search more, or prefix keys, or just using forward-paragraph more.

2) My most frequent deletion command is by far deleting a single character. I find it hard to believe that this is the most common situation by that much, which means I should be using either kill-word more, or being more efficient at learning when i should mark a region and kill a region that way instead of just backspacing over it.

3) For someone who doesn’t consciously remember *ever* using a recursive edit in the time period I was recording this, I use way too many abort-recursive-edit calls. I need to find out how I’m entering recursive edits, and do that less. I’m not precisely sure how I’ll do this - maybe by defadvicing the recursive edit entry to notify me when it happens - but it really is something I should work on.

Even fixing just these three things seems likely to increase my editing proficiency with emacs by around 5%, so I think this was a valuable exercise. I highly recommend you doing the same - the process is described in my last blog entry, and it is quite simple to have runing for a few weeks while it gathers statistics. I’m probably going to do this again in a few months, hopefully once I’ve fixed or at least improved upon the three issues mentioned above.

Command-Frequency-Mode

Friday, August 14th, 2009

I’m going to do periodic analysis of my Emacs use, to better determine how I might more efficiently use it. I expect the frequency of command to change dramatically every few months, as what I use emacs for changes. For example, right now I mostly use emacs for writing blog posts, customizing emacs itself, and a small amount of programming that I do on my free time. This will no doubt change when I go back for my school term and will have many more programming projects.

To analyze my frequency, I need to keep track of what commands I am executing. Searching around found the comnmand-frequency package, originally used to develop an ergonomic keybinding set for emacs. This package can be found here. To enable command tracking, put the following in your initialization file:

(setq-default command-frequency-table-file "~/.emacs.d/frequencies")
(require 'command-frequency)
(command-frequency-table-load)
(command-frequency-mode 1)
(command-frequency-autosave-mode 1)

This will make the command frequency tracking persistent across your emacs sessions, as well. If you want this to happen, you need to set the command-frequency-table-file before loading the table and do that before enabling autosave-mode; otherwise, as I’ve found out, you’ll probably lose your old history. There are a few additional customizations you can make to specify where various files are saved and what format they are written in, but I find this sufficient.

Once you’re enabled command-frequency-mode, it’s very simple to use. M-x command-frequency will take you to a buffer showing the relative frequencies of all your commands. M-x command-frequency-insert will insert this table into the current document. M-x write-file will *theoretically* write this information to a file, but unless called non-interactively it fails for me. I haven’t fixed this, since I haven’t ever had a need for it, but it would probably be a relatively simple fix.

Yet Another Emacs Post

Monday, August 10th, 2009

There’s been a lot of random emacs customizations I’ve added to my init file, so it’s time to document them all here. There are also a few additions to customizations I’ve talked about in previous blogs; when this occurs, I’ll link back to those.

The first category is just emacs options, that effect every buffer. I save often enough to find auto-saving, which can clutter my directories, annoying, so I disable it. While I personally don’t mind tabs, pretty much every place I work requires the use for spaces for indentation, so I just set indent-tabs-mode to nil so that they are happy. x-enable-clipboard determines whether you want emacs to be able to interact with the system clipboard under X, which of course you do. I like having the time displayed in the mode line, so I enable that. Blink-cursor-mode is responsible for determining whether the cursor blinks, as in many applications, or is just constant highlighting. I prefer the constant highlight, so I turn the mode off. The visible bell, which most people prefer, alerts you to errors by blinking the top and bottom lines instead of giving an annoying beep. I enabled one of the commands that I end up using, so that Emacs doesn’t complain when I do use it, and then gave query-replace-regexp a convenience alias since I use it a fair amount.

(setq auto-save-default nil)
(setq-default indent-tabs-mode nil)
(setq x-select-enable-clipboard t)
(display-time)
(blink-cursor-mode nil)
(setq visible-bell t)
(put 'erase-buffer 'disabled nil)
(defalias 'qrr 'query-replace-regexp)

There are a few modes that I’ve added back in but blogged about before restarting my .emacs file: pabbrev and cua. The links for those posts are here and here respectively. Pabbrev is a mode for predictive expansion, which is incredibly useful. Cua is a mode that does several things, the two main ones being adding windows-friendly keybindings when the region is visible and adding much better rectangle support. I only really like the rectangle support, as I’ve mentioned before.

(require 'pabbrev)
(global-pabbrev-mode t)
(setq pabbrev-read-only-error nil)
 
(setq cua-enable-cua-keys nil) ;
(cua-mode t)

The next category is for customizations for other modes that I’ve talked about but ended up changing. comint-process-echoes makes M-x shell behave more like a real terminal in some cases, stripping extraneous output. This isn’t necessary on my home computer, but it is on my work one so I missed it in my initial post here. I added a few more customizations for ido, which I wrote about here: one that moves the location of one of it’s files to centralize it in .emacs.d, and one that removes the prompt asking if you want to create a new buffer when you switch to one that doesn’t exist.

I also add a few additional keybindings to make my life easier:

(global-set-key (kbd "C-w") 'backward-kill-word)
(global-set-key (kbd "C-x C-k") 'kill-region)
(define-key visual-line-mode-map (kbd "C-a") 'beginning-of-visual-line)
(global-set-key (kbd"C-x \\") 'align-regexp)

The following function I had in my old setup, and it was much better than M-x rgrep in a lot of cases I wanted so I ended up pulling it back. It prompts you for an expression, defaulting to the symbol that your cursor is on, and greps for that in the current directory and all subdirectories. Very useful.

(defun my-grep ()
  "grep the whole directory for something defaults to term at cursor position"
  (interactive)
  (setq default (thing-at-point 'symbol))
  (setq needle (or (read-string (concat "grep for <" default "> ")) default))
  (setq needle (if (equal needle "") default needle))
  (grep (concat "egrep -s -i -n -r " needle " *")))
(global-set-key (kbd "C-x g") 'my-grep)

The last few things in this batch are just things that I have emacs do on startup. I almost always want to be able to look at my init file, so I load it up here. I also start a server, so I can connect to it with emacsclient and save on startup times when doing things from the command-line that need an editor.

(find-file "~/.emacs.d/init.el")
(server-start)

Autoindentation

Friday, August 7th, 2009

Indenting code is very important, even if you are not programming in Python. It makes the structure of the code much clearer if everything is properly indented. Most editors nowadays will properly indent your code for you, and emacs is no exception. Most of the following customizations were gotten from the emacs-wiki page on autoindentation.

The first set of utilities is advice for yank and yank-pop to indent whatever they just pasted. This is useful if, for example, you copy some code from another file at a different indentation level than you want to paste it at. With these advice, the code will be indented properly relative to wherever you paste it.

(defadvice yank (after indent-region activate)
  (if (member major-mode
              '(emacs-lisp-mode scheme-mode lisp-mode
                                c-mode c++-mode objc-mode
                                latex-mode plain-tex-mode))
      (let ((mark-even-if-inactive t))
        (indent-region (region-beginning) (region-end) nil))))
 
(defadvice yank-pop (after indent-region activate)
  (if (member major-mode
              '(emacs-lisp-mode scheme-mode lisp-mode
                                c-mode c++-mode objc-mode
                                latex-mode plain-tex-mode))
      (let ((mark-even-if-inactive t))
        (indent-region (region-beginning) (region-end) nil))))

The next function, also from the emacs-wiki, is a replacement for kill-line. Normally, if you kill a newline and the next line is indented, you will have to execute just-one-space or something similar to get rid of all the extra indentation. This will do that automatically for you, saving some time. I just rebind it to C-k, overriding kill-line, since this is almost always the behavior I want.

(defun kill-and-join-forward (&optional arg)
  "If at end of line, join with following; otherwise kill line.
    Deletes whitespace at join."
  (interactive "P")
  (if (and (eolp) (not (bolp)))
      (delete-indentation t)
    (kill-line arg)))
(global-set-key (kbd "C-k") 'kill-and-join-forward)

The last customization I have is a keybinding for a function that is already pretty accessible. C-j will perform a newline and indent, but I often just use the return key instead and then have to indent myself(admittedly, only a tab character, but it’s still annoying). Since the times I’ve needed to just insert a newline without indenting are very rare, I just set RET to newline-and-indent. The other option I considered was binding RET to indent-new-comment-line, but after trying that for a while I decided I preffered newline-and-indent.

(global-set-key (kbd "RET") 'newline-and-indent)

Persistent Emacs

Wednesday, August 5th, 2009

Having persistent emacs sessions - where your data remains when you load up emacs - is supposed to be handled by desktop.el, a library that comes with emacs. However, I’ve never actually gotten it to work - I’m not sure why, the installation seems fairly easy. It’s just never loaded my state properly. But since I like some of my settings persisting across sessions, I use several other, more specific modes that come with Emacs, and a mode I wrote to save and load currently-opened files.

Saveplace is a built-in emacs package for saving your location in files. If you have a file open in emacs and then close it, with saveplace enabled the file will be opened with point at it’s last location. This is often what I want - just to pick up where I left off - so of course I enabled it.

 save-place-file "~/.emacs.d/.saveplace")
(setq-default save-place t)
(require 'saveplace)

Another similar mode is savehist, which will save your minibuffer history across sessions. I don’t actually use the minibuffer history very much, but it does occasionally help so I just save it across sessions.

(setq savehist-file "~/.emacs.d/.savehist")
(savehist-mode 1)

The other mode I wrote, save-visited-files.el, is available here. It is a lightweight replacement to the part of desktop that persists files across sessions. At the moment, it is very simple, though if you want any features added or have any bug reports feel free to contact me. It have three functions: save-visited-files, open-visited-files, and save-visited-files-mode. save-visited-files will just save a list of all the files you have opened. open-visited-files will open every file in this list. save-visited-files-mode will set up a timer that runs every 60 seconds by default and saves what files you have opened(unless you are currently in the minibuffer).

There are currently only two configuration options: save-visited-files-location, which will change what file to use to save and load file lists, and save-visited-files-interval, which controls how often the list of visited files are saved. To enable this mode and load your previous opened files, add the following to your initialization file:

(require 'save-visited-files)
(open-visited-files)
(save-visited-files-mode 1)

This is actually the second revision of this mode; In the first, instead of using a timer, I advised kill-buffer-hook and find-file-hook to maintain completely up-to-date file lists, instead of just saving every 60 seconds. This had some problems, however. It had to ensure that the file it was opening/closing wasn’t from another instance of save-visited-files. There were performance issues when the entire list was written whenever a buffer was killed, since it turns out temporary background buffers are always popping up, and attempting to just delete the specific line started getting complicated, so I decided saving every 60 seconds was good enough.

New Features in Emacs23

Monday, August 3rd, 2009

Emacs 23.1 was released earlier this week, and if you haven’t upgraded yet you should. It comes with all sorts of new goodies. I’ve been working off of the emacs-snapshot package for Ubuntu, which has many of these new features, but the final version is much more polished. While I won’t cover all of the new features in this blog, I will cover the ones that seem most interesting to me. For the full list of enhancements, use ‘C-h n’ to view the NEWS file.

The big improvement many people are talking about is the new font antialiasing. If you compile with the Xft library, your emacs fonts will be antialiased, making it much prettier and more readable. Support for internationalization was also increased, with the Emacs character set now having 4 times the space that Unicode does.

Emacs can now also be started as a daemon, with emacs –daemon. This will start emacs in the background and allow you to connect to it with emacsclient for very fast load times without having to load your initializations. While you could run a server in emacs before this, you had to have an open instance of emacs - you coulnd’t have one running in the background like you can now. If you have a fairly stable configuration his would be great - I change mine all the time, sometimes to states that require me to restart, so I’m not sure how much I’ll use it.

Visual-line-mode is a new addition that is set on by default. It is something of a replacement for longlines-mode. It doesn’t insert soft line breaks, so it works better on larger files, and it wraps to whatever your screen is, so if you are using longlines-mode you should switch to using visual-line-mode. C-n and C-p will move by visual lines, which may screw up some macros, but mostly it seems to work quite well.

Transient-mark-mode is now enabled by default. I used to not like this mode, but it’s grown on
me. Transient-mark-mode is a mode that highlights the region between point and mark(most of the time) and has many commands operate on the highlighted region instead of the entire buffer. I think transient-mark-mode being on is a good default, since people new to emacs will be used to their old editors highlighting their selection.

The VC system, which integrates with many different version control systems, now has support for changelists. Previously, each file was checked in individually, which isn’t what you want for systems such as SVN or GIT. I’m going to need to play with this a bit more before I understand quite how it works; I’m working on a few posts about a few different version control systems, so I’ll probably discuss this more then. A new command was also added, vc-dir, which shows you the VC status for the directory and subdirectory. This will tell you which files need updates, which were added, etc.

C-l, which previously just recentered the screen to have the point in the center, has been slightly improved. While C-l once will act the old way, pressing it again will then scroll the buffer so that the point is at the top of the screen, and then C-l a third time will scroll the buffer so that the point is at the bottom of the screen.

Lots of new modes were added to Emacs-23. Doc-view is one useful one, which allows displaying PDF, PS, and DVI files in emacs buffers. You can even search through the pages, although this only gets you to the correct page. While useful, I find this mode suffers from some inherent limitations caused by Emacs’ display system, which requires the PDFs to be converted to PNG files first. This means you can’t select text in it, highlight the actual match for your search, etc. Another cool addition is EasyPG support. A library I used to use for numbering lines, linum.el, is now in Emacs proper. nXML, a very mode for editing and validating XML documents, and ruby-mode are also included. The last mode I’m going to mention is proced, which is like dired for processes. I find it very useful, allowing you to do things like mark arbitrary processes and send a signal to all of them.

Another new feature is directory-local-variables. You could previously have file-local-variables by adding text to your file, but if you wanted many variables applied to everything in a directory you had to implement this on your own. You can now just have a .dir-locals.el, with a specially-formatted list such as:

     ((nil . ((indent-tabs-mode . t)
              (fill-column . 80)))
      (c-mode . ((c-file-style . "BSD")))
      (java-mode . ((c-file-style . "BSD")))
      ("src/imported"
       . ((nil . ((change-log-default-name . "ChangeLog.local"))))))

Which is a list specifying that in indent-tabs-mode should be t and fill-column should be 80 in every mode.  In c- and java-mode, c-file-style should be “BSD”, and in and that any file in the “src/imported” subdirectory should have the change-log-default-name of “ChangeLog.local”.

Then of course we come to emacs-uptime. It does pretty much what you’d expect: run this function and it tells you how long your Emacs session has been running. Mine’s only at about 14 hours right now, due to having to restart due to some issues when I tried to install ropemacs.

That’s all I’m going to cover in this post, but there is much more that was changed and added to. I highly recommend upgrading to emacs23 and reading the NEWS file to find out all the other changes that you may not know about. You can access this file by using ‘C-h n’.

Icomplete

Friday, July 31st, 2009

I like being able to see all the possible inputs in the minibuffer. It’s one of the reasons I like ido - being able to see the possible completions inline when accessing files or buffers is just incredibly helpful. Another package I use to show minibuffer completion options is icomplete, a package that comes built-in with GNU Emacs. Icomplete will display completions in the minibuffer for all the frequently-used minibuffer commands: M-x, C-h v, C-h f, and probably a lot more that I just don’t use as much.

Icomplete will display all the possible completions you can enter in the minibuffer, much as Ido does. To enable it, you call the icomplete-mode function. The re aren’t many customizations for it: The main one you want to change is either icomplete-max-delay-chars or icomplete-compute-delay. Setting either of these to 0 will force icomplete to display completions as soon as a letter is typed. Without setting one of these, for small number of typed characters icomplete will wait for some time before displaying completions. You may want this if you have a very slow computer, but for the most part the computation is inexpensive enough you don’t notice any lag.

Icomplete+ is an third-party enhancement to icomplete. Since it doesn’t come with Emacs, you’ll have to download it from here. Icomplete+ doesn’t add new functionality; rather, it enhances the display of icomplete. It does this by changing faces for the stem and the completion candidates, as well as for the keybinding for a command you are selected. It also displays the number of completions, which can be nice to know. All in all, it makes icomplete look much nicer and I’d recommend getting it. To enable what I’ve described here, just put this in your initialization:

(icomplete-mode 1)
(setq icomplete-compute-delay 0)
(require 'icomplete+)