Emacsのautoinsert.elを使うぐらいならfile-template.elを使うべき

Emacs には標準で autoinsert.el (auto-insert-mode) がありますが,file-template.el のほうがもっと便利です

初期設定

file-template.el をダウンロードします
www.emacswiki.org

ダウンロードした file-template.el は emacs のload-pathが通ったディレクトリにコピーしておきます

使い方(基本)

.emacs などに以下の設定を書きます

(use-package file-template
    :config
  (setq file-template-insert-automatically t)
  (setq file-template-paths '("~/.emacs.d/template/"))
  (setq file-template-mapping-alist
        '(("\\.el$" . ".template.el")
          ("\\.c$" . ".template.c")
          ("\\.\\(cpp\\|cc\\)$" . ".template.cpp")
          ("\\.h\\(pp\\)?$" . ".template.h")
          ("\\.sh$"  . ".template.sh")
          ("\\.py$"  . ".template.py"))
        )
)
(add-hook 'find-file-not-found-hooks 'file-template-find-file-not-found-hook)

これで C-x C-f などで新規ファイルを開くと

  1. カレントディレクト
  2. file-template-paths で指定したディレクト

の順番でテンプレートファイルを探し,テンプレートファイルを雛形にしたバッファを生成してくれます.

テンプレートファイルは拡張子ごとに定義できます.上記の例だと例えばC言語ソースコード *.c のテンプレートは .template.c になります


これで

プロジェクト専用のテンプレートファイルがある場合
プロジェクトのディレクトリに .template.c などを用意.git でバージョン管理
プロジェクトのテンプレートファイルがない場合
デフォルトのテンプレートとしてfile-template-paths にある .template.c を使う

という運用ができます


autoinsert.elは,テンプレートファイルの検索パスという概念が存在しないため,このような使い方ができません.この一点だけでもfile-template.elのほうが使い勝手が良いです

使い方(日付やファイル名の展開)

file-template.el は簡単にテンプレートに日付やユーザ名を埋め込むことができます

例えば .temaplate.c に

/**
 * @file   %b
 * @author %U <%a>
 * @date   %Y%m%d
*/

と書いておくと

  • %b がファイル名
  • %U がユーザ名
  • %a がメールアドレス
  • ファイル作成日 (%Y が年,%m が月,%d 日付)

に自動展開されます

これで doxygenjavadoc や numpydoc 形式のコメントが自動挿入できます

またヘッダファイルの2重インクルード回避のコード、例えばC言語

#if ! defined __HOGEHOGE_H_INCLUDED__
#define __FILENAME_H_INCLUDED__
#endif

というコードも

#if ! defined __%N_%E_INCLUDED__
#define __%N_%E_INCLUDED__

#endif // #if ! defined __%N_%E_INCLUDED__

と簡単にテンプレート化できます.コードを説明すると

  • %E がファイル名の拡張子部分
  • %N がファイル名から拡張子を取り除いた部分

に置換されます

file-temaplte.el が展開するキーワードの一覧は,file-temaplte.el のコメントにまとめて書いてあります.

引用すると以下の通り

 %u       user's login name
 %U       user's full name
 %a       user's mail address (from the variable `user-mail-address')
 %f       file name with path
 %b       file name without path
 %n       file name without path and extension
 %N       file name without path and extension, capitalized
 %e       file extension
 %E       file extension capitalized
 %p       file directory
 %d       day
 %m       month
 %M       abbreviated month name
 %y       last two digits of year
 %Y       year
 %q       `fill-paragraph'
 %[ %]    prompt user for a string
 %1-%9    refer to the nth strings prompted for with %[ %]
 %( %)    elisp form to be evaluated
 %%       inserts %
 %@       sets the final position of `point'")

"%( %)" でevalも使えるので、これで不足することは無いでしょう


キーワードの置換処理はautoinsert.elでも自作関数を組み合わせることで無理やり実現することはできますが,こちらもfile-template.el のほうが楽です

まとめ

autoinsert.el は捨てて file-template.el に乗り換えましょう