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.
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
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With