fnwiya's quine

自分自身を出力するブログ

emacsのautoinsertで楽する

いつも書く決まったテンプレート。
そんなものを書くことは人間のすべきことじゃありません。

以下を設定して

(require 'autoinsert)

(setq auto-insert-query nil)
(setq auto-insert-directory "~/.emacs.d/insert-tmp/")

(setq auto-insert-alist
      (append  '(
               ("\\.cpp$" . ["template.cpp" my-template])
               ("\\.h$"   . ["template.h" my-template])
               ("\\.html$"   . ["template.html" my-template])
               ("\\.sh$" . ["template.sh"
                            (lambda() (my-template-exec "/bin/sh"))
                            my-template])
               ("\\.py$" . ["template.sh"
                            (lambda() (my-template-exec "/usr/bin/python"))
                            my-template])
               ("\\.rb$" . ["template.sh"
                            (lambda() (my-template-exec "/usr/bin/ruby"))
                            my-template])
               ("\\.pl$" . ["template.sh"
                            (lambda() (my-template-exec "/usr/bin/perl"))
                            my-template])
               ) auto-insert-alist))

(require 'cl)

(defvar template-replacements-alists
  '(("%file%"             . (lambda () (file-name-nondirectory (buffer-file-name))))
    ("%file-without-ext%" . (lambda () (file-name-sans-extension (file-name-nondirectory (buffer-file-name)))))
    ("%include-guard%"    . (lambda () (format "__SCHEME_%s__" (upcase (file-name-sans-extension (file-name-nondirectory buffer-file-name))))))
    ))

(defmacro defreplace (name replace-string)
  `(defun ,name (str)
     (goto-char (point-min))
     (replace-string ,replace-string str)))

(defreplace my-template-exec "%exec%")

(defun my-template ()
  (time-stamp)
  (mapc #'(lambda(c)
            (progn
              (goto-char (point-min))
              (replace-string (car c) (funcall (cdr c)) nil)))
        template-replacements-alists)
  (goto-char (point-max))
  (message "done."))

(add-hook 'find-file-not-found-hooks 'auto-insert)

このようなテンプレートファイルを作れば(~/.emacs.d/insert-tmp/template.h)
ファイル名に合わせて自動でインクルードガードを挿入してくれます。

/*
 * %file%
 *
 */

#ifndef %include-guard%
#define %include-guard%


#endif // %include-guard%

(参考)

Emacs の auto-insert 用のテンプレートを作って楽をしよう - Higepon’s blog

autoinsert mode - Yasuto Takenaka 's