c++emacselispcode-templates

Adding some comments to the C/C++ header file automatically or manually


I add the following preprocessor code in header files all the time.

#ifdef _HELLO_H_
#define _HELLO_H_

#endif

Is there a way to do this automatically (I mean, when I load the header file for the first time, the emacs just adds the code), or manually (I mean, I have some M-x SOMETHING)?

If none exists, how can I program the elisp code to this?


Solution

  • I use YaSnippet and it works just great. It comes default with a lot of snippets for different languages and modes, not only for C++. Plus, you can write your own templates (snippets) and even use Lisp inside them (i.e. generate file header with copyright information including current year). There is also a good documentation.

    Here is a an example of "once" snippet which is being expanded when you type "once" and hit "tab" button in cc-mode:

    #name : #ifndef XXX; #define XXX; #endif
    # --
    #ifndef ${1:_`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_H_}
    #define $1
    
    $0
    
    #endif
    

    And here is my "license" snippet for c++-mode which adds a copyright information with a current year:

    #name : C++ source file license
    # --
    //
    // Copyright (C) `(format-time-string "%Y" (current-time))` Bueller? Bueller?
    //
    // $Id$
    //