Thursday, June 25, 2009

Emacs: linux-c-mode and Line numbers

Tired of the slow ssh access to one of the servers located outside India, I finally figured it was time to start playing with emacs to reduce the number of keystrokes needed.

First on, I wanted the linux-c-mode enabled *by default* whenever I open a file whose extension is ".c" (Yeah Yeah, I know extensions are meaningless for Linux.. but emacs is intelligent :) ). For all the other type of files, linux-c-mode should be OFF, because it will mess-up their indentation.
Second, line numbers should be displayed on the left-hand-side panel of each file I open. Then to go a particular line I just "M-g g". Simple.
Third, All this should be accessible to my user account as well as root user.

So, I edit the ~/.emacs file (create if not already present) like this (for the first goal):
(defun linux-c-mode ()
  "C mode with adjusted defaults for use with the Linux kernel."
  (c-set-style "K&R")
  (setq tab-width 8)
  (setq indent-tabs-mode t)
  (setq c-basic-offset 8))

(add-to-list 'auto-mode-alist '("\\.c$" . linux-c-mode))

The first chunk defines the linux-c-mode (from Documentation/CodingStyle) and the last line enables it by default ONLY for *.c files. Simple!

For the second part, I got a script linum.el from google (Vedang says it has been integrated into emacs)
You can find the script here:
Drop this script at /usr/share/emacs/site-lisp/

There's a problem with this script. It doesn't print a space after the line number. Sad!
Here is a patch I wrote to fix it:

Now I want to display line numbers for EACH file I open in emacs. So, I add the following lines in the .emacs file:
(require 'linum)
(global-linum-mode 1)

(First line is needed to autoload linum.el. The second line enables it by default)
To toggle the linum mode, use "M-x linum-mode"

Finally, I wanted to give access to root user too.
A simple solution would be to make a symlink/hardlink from /root/.emacs to /home/jitesh/.emacs.
However, I wasn't too concerned about the other users on the system :) .So, I simply copied to .emacs file to /usr/share/emacs/site-lisp/site-start.d/ and renamed it as So, now, these things get enabled by default for *all* users.

Now that everything is setup (and steps documented via this blog), let me go back to coding peacefully in emacs!

No comments: