Sunday, March 22, 2009

Using "Abbreviated Skeletons" in Emacs

In Emacs, you can use code templates (using 'skeleton's in emacs) as abbreviations to speed up your coding. Here is an example:

Suppose I want to create a code-template for the for loop in c-mode in Emacs. To create the template, I can put the following function in my .emacs file:

(define-skeleton c-for
"Inserts a C for loop template."
nil
> "for (;;){" \n
> _ \n
"}" > \n
)

(see the Autotype section of the emacs info)

After that, I can edit the abbreviation table by using the command M-x edit-abbrevs (i.e., Press Alt+x, and then give the command edit-abbrevs and press enter).

Then, under the heading (c-mode-abbrev-table), leaving a blank line, I can enter the following line:

"forst" 0 "" c-for


Then, I can save the changes by pressing C-c C-c (i.e., press Control+c twice). That's it.

Now, whenever I am writing a C program, if I need to use the template, I will just type "forst" (without the quotes), and if the abbrev-mode is turned on, then as soon as I enter a space, my template for the for statement gets entered with the cursor inside the for loop as follows:

for (;;){
_
}


(If the abbrev-mode is turned off, "forst" can still be expanded to the template by pressing "C-x a e", which basically stands for "abbreviation expand".

Oh, of course I need to save my abbreviations using M-x write-abbrevs-file if I want to use them in future emacs sessions. But that is obvious... although I have forgotten that on many occassions :-)

2 comments:

roby said...

Your emacs-fu is much better than me, I must admit.
But have you ever tried yasnippet?
It is powerful and I really use it all the time.

The for loop in yasnippet is already predefined, you just need to type for then press tab.

Santanu's Linux Log said...

Yeah. Just after a few days of learning about skeleton mode, I found yasnippet. Handling it is easier than skeleton mode. Very nice.

But one thing that bugs me about it is the indentation. In case of yasnippet, the indentation seems to be hard coded, unlike the one provided by skeleton-mode. Of course that's not much of a big deal, I can always press tabs.