Return to Snippet

Revision: 17063
at August 21, 2009 15:50 by bigfaceworm

Initial Code
(defvar insert-code-template-templates
  '(((c-mode c++-mode) ".h$" "/* copyright 2001 */\n#ifndef __SOMETHING_H\n#define __SOMETHING_H\n\n#endif /* # __SOMETHING_H */\n")
    ((c-mode c++-mode) nil "int\nmain(int argc, char **argv)\n{\n\n}\n")
    ((cperl-mode perl-mode) nil "#!/usr/bin/perl -w\n\nuse strict;\n"))
  "A list of triples, used for inserting code.
A triplet is composed of a symbol for the major mode (or a list of symbols),
a regular expression to match against the buffer's file name,
and the text to insert when both the major mode and regular expression match.")

(defun insert-code-template ()
  "insert a code template, based on major mode
when called interactively, always do insertion
otherwise, only do so when the buffer is empty"
  (let ((l insert-code-template-templates))
    (when (or (called-interactively-p)
              (eq (point-min) (point-max)))
      (while l
        (let* ((elt (car l))
               (modes (if (listp (car elt)) (car elt) (list (car elt))))
               (re (cadr elt))
               (template (caddr elt)))
          (when (and (member major-mode modes)
                     (or (null re)
                         (string-match re (buffer-file-name))))
            (insert template)
            (setq l nil)))
        (setq l (cdr l))))))

(add-hook 'find-file-hook 'insert-code-template)

Initial URL

Initial Description
An example solution for the 'insert-code-template exercise listed here:

Initial Title

Initial Tags

Initial Language
Emacs Lisp