Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting any Emacs buffer with a .c extension with a template

I write a lot of short throwaway programs, and one of the things I find myself doing repeatedly is typing out code like

#include <stdio.h>
#include <stdlib.h>

int main(void){

}

To save some tendon hits I was wondering if it was possible to insert a simple template above whenever I create a buffer with the extension of .c.

like image 226
vinc456 Avatar asked Jan 11 '09 16:01

vinc456


3 Answers

Put somthing like this in .emacs

(define-skeleton c-throwaway
  "Throwaway C skeleton"
  nil
  "#include <stdio.h>\n"
  "#include <stdlib.h>\n"
  "\n"
  "int main(void){\n"
  "\n"
  "}\n")

And eval (C-x C-e) it. That'll give you a function (c-throwaway) that inserts your template.

To get this inserting automaticly you'll need to activate auto-insert-mode. Once you do this you can describe-variable auto-mode-alist and read up on how emacs does some of its open file magic. Then define auto-insert-alist to apply it when you find a new file.

Maybe something like this

(define-auto-insert "\\.\\([Cc]\\|cc\\|cpp\\)\\'" 'c-throwaway)

More detail:

  • Auto Insert Mode

  • Autotype

like image 190
Tom Dunham Avatar answered Nov 11 '22 23:11

Tom Dunham


I use template.el from http://emacs-template.sourceforge.net/

Basically, I create a file called ~/.templates/TEMPLATE.c, and then that gets inserted into my .c files. You can also use special markup and arbitrary lisp expressions, if you don't just want to dump text into the buffer. I use this feature so that Perl modules start with "package Foo::Bar" when they are named lib/Foo/Bar.pm. Very handy.

like image 10
jrockway Avatar answered Nov 11 '22 21:11

jrockway


The following function will ask for a filename and then insert a file and change to c-mode. The only problem is that you have to call this function to create the buffer instead of your normal way.

(defun defaultCtemplate(cfilename)
    (interactive "sFilename: ")
    (switch-to-buffer (generate-new-buffer cfilename))
    (insert-file-contents "~/Desktop/test.c")
    (c-mode)
)

P.S Thanks for the question, now I know how to do this for myself :)

like image 4
Andrew Cox Avatar answered Nov 11 '22 21:11

Andrew Cox