Code templates with emacs

emacs

How can I configure emacs to generate some code skeleton?

For instance, for C files:

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

int main (int argc, char **argv) {

    return EXIT_SUCCESS;
}

or something more dynamic in Python:

#!<insert result of `which python` here>

def main():

if __name__ == "__main__":
    main()

I would like to define 2 modes for inserting the templates:

  • create a function insert-template (or something), binding it to a certain key combination (C-c C-t) that would insert the correct template according to the major mode.

  • create an option to automatically insert the template upon file creation, detecting the correct type by the filename suffix (similar to how major mode is detected). This option should be easily set on/off in the .emacs file.

Ideally I'd like to avoid 3rd party modules/packages. But I'm not completely against it.

Best Answer

Please check yasnippet. It is a great Emacs template system, easily installed and customizable to what you want to do. Also, check the documentation (with how to use sections and a video demo).