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."
> "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 :-)
Post a Comment