Thursday, 4 August 2011

Hey Emacs! (an excursion on Emacs' tab-key)

One on main difficulties on Emacs is how it manages tab-key. A user whom comes from VI/VIM or another editor feels disoriented because Emacs ignores a tab and mantain stubbornly the selected line in the same place.
A bug? No. It's a feature. Hard to understand, but a feature. This is because there's three ways to manage a key-tab event:

  1. a way to insert a TAB (\t) character
  2. a way to insert 4 (or more) spaces
  3. a command to indent selected line(s)

VIM and other editors mean tab-key as 1 or 2. Emacs, instead, binds tab-key whith the "indent according to mode" command. This means a more sophisticated (and elegant) tool, but also means to understand it.


Emacs works with Modes. A C file will be interpreted with the c-mode; a Java file with java-mode, ecc. Every mode has its own configuration. E.g., a C file could be indented according to GNU style, BSD style, Kerningan and Ritchie style and others (a full list is avaiable on wikipedia).
But is an advantages? Well, yes, when you understand how a mode works. If it's properly configured, it helps programmer as no other editor. You can detect if you forget a parenthesis becaus Emacs will indent wrong a line. It's usefull.

But my colleagues uses VIM

If a VIM users sends you a C file, all new lines you'll add will be indented using current Emacs mode and style. It's boring, but there's a solution. You can change Emacs configuration just for a file writing on top of it the famous "Hey Emacs" line. If you write on top

/* Hey Emacs! -*- mode: java; c-basic-offset:4; indent-tabs-mode: t;default-tab-width:4 -*- */

Emacs will understand:
  • it's reading a Java file (enable Java mode)
  • indent lenght is 4 spaces (c-basic-offset)
  • tabs are 4 spaces long
  • when idents, Emacs must use a tab character (indent-tabs-mode:t)

This is just an example: there's many other variables you can set. I think adding this line it's a small price to pay. Emacs is really good.
And, if you want, there's always VIM ;)

There's a way to insert brutally a tab character: pressing META+i. But I suggest you to use it carefully.
Post a Comment