Wednesday, August 10, 2005

Emacs and templates

We all know GNU Emacs is a powerful editor. But when I see the editor used in the rails movie I really think that there are missing some things (or maybe they're there and I'm not aware of it). The editor that is used is TextMate and it does things that I would like to do more often with Emacs.

The most obvious missing thing in the movie is the template based code insertion. Sometimes only the method name or a class name is typed. And with a push of a button the rest of the code is inserted. I think it is easy to do this with emacs.

With some research I found two template system that enable me to create a similar piece of functionality. The first is skeleton and the other is tempo. Both libraries do the same thing: create a function that asks questions and inserts text.

I will show how to create a template that inserts a method definition for ruby. The inserted code should look like this:

def method_name|
end

The cursor should be where the | is, because you may want to insert arguments instead of just a body and no arguments.

The code for the skeleton library is:

(define-skeleton ruby-insert-def-method
  "Inserts a ruby function"
  "Method Name: "
  "def " str _ \n
  "end" \n \n)

When you call the function, it will ask you for a method name. Then it will insert the text using you answer for str and putting point at the place of _.

The tempo version of this same template looks like this:

(tempo-define-template "ruby-def-method"
   '("def " (p "Method Name: ") ~ n "end" n))

But the name of this function will be tempo-template-ruby-def-method. A problem with this code is that the ~ won't work in the standard version. You should take a look at EmacsWiki TempoMode page for a solution to this problem. Also be sure to require the tempo library before you try to use this code.

There are probably more templates that would be useful. Maybe I will show some more later.

0 Comments:

Post a Comment

<< Home