Saturday, 12 December 2009

Fixing tabs and spaces in emacs

Tabs to spaces

Ever since I upgraded to Ubuntu Karmic I've had problems with tabs and spaces in emacs23. I have indent-tabs set to nil, but somehow a set of four spaces will still be saved as a tab. This is a pain when writing in languages like Python, where whitespace is semantically meaningful and mixing tabs and spaces can cause a syntax error.

To deal with this I wrote a small emacs-lisp function to convert all tabs in the active region (i.e. the currently selected text) to four spaces:

Spaces to tabs

Similarly, I have a set of generic Makefiles for LaTeX papers, OCaml programs and other things. These are all saved on github or on wikis and I copy them when starting a new project. Makefiles are very sensitive to changes in whitespace and characters which should be tabs may not be spaces. If you copy and paste this sort of code from a webpage you will always get spaces rather than tabs and so need to replace these. The following two functions convert each group of four spaces (or eight spaces) in the active region to a tab:

Using these functions

If you have been using emacs for a while you will probably already know how to customise it. If not, start by finding (or creating) your initialisation file. This will either be in ~/init.el or ~/.emacs.d/init.el Add the functions you want to use to that file, then make sure that Emacs re-evaluates the file by typing M-x eval-buffer. Then move to the buffer where you want to convert your tabs or spaces and use any of the above functions by typing M-x <function-name> just as if you were using a built-in function. That's all there is to extending emacs :-)

Posted via web from snim2's posterous