2008-12-15

modes

Emacs has special modes for many different types of files; a mode might colorize the file in some useful way, or add some functions or keybindings to easily manipulate them. Each buffer has one specific mode called the major mode. In addition, each buffer can have multiple minor modes, which enhance the major mode in some way. You can get information about the major and minor modes for the current buffer with M-x describe-mode or C-h m.

As a practical example, let's look at text files. Text files are (by default) opened in text-mode; we can add some useful minor modes to that, by using a hook in your .emacs:

(add-hook 'text-mode-hook
  (lambda()
    (blink-cursor-mode -1) ; don't blink the cursor
    (set-fill-column 78)   ; buffer-local variable; wrap at col 78
    (auto-fill-mode t)))   ; wrap around automagically
This will activate two minor modes when we use text-mode. First, we turn off cursor blinking with (blink-cursor-mode -1) (because, obviously, we don't want a blinking cursor when editing text files...). Second, it activates auto-fill-mode, a minor mode that makes emacs automatically wrap long lines ('filling' is emacs terminology for wrapping). Neither of these two minor modes is specific for text-mode, and can be used with other modes as well.

Emacs recognizes many files already, but sometimes, you need to tell it to use some specific mode for a file. To do this, there is auto-mode-alist. Suppose, we want to use text-mode for all files with extension .foo or .bar; we add to our .emacs:

(add-to-list 'auto-mode-alist
        '("\\.foo$\\|.bar$" . text-mode))
Now, whenever we open a file which matches that pattern (ends in .foo or .bar, text-mode will be activated. Please refer to the emacs documentation for details on the regular expression (the "\\.foo$\\|.bar$" pattern).

Some final notes:

  • For more information on installing modes (and other packages), see the installing packages-entry;
  • with some tricks you can actually have multiple major modes in a buffer at the same time; this can be useful for example when editing web documents that contain HTML and Javascript; see MultipleModes. It can be a bit tricky to set up though;
  • not all modes are buffer-specific; for example tool-bar-mode and menu-bar-mode (which determine whether your emacs window has a toolbar, menubar, respectively) are global for your emacs-session;
  • an interesting question is "where do I find interesting modes?"; well, you can search the Emacs documentation, or look through the Emacs Lisp List. And of course in this blog I am trying to show which ones I found particularly useful.

1 comment:

Anonymous said...

Another gem! I casually spent half an hour trying to figure out how to set default minor modes with a major mode (I took the wrong approach and was trying to set default minor modes the same way you set default major modes for buffers). Thanks!