この関数buffer-file-name
は、現在のバッファの名前を返すnil
か、現在のバッファがファイルを訪問していない場合に返します。
この関数string-match
は、文字列に対して正規表現を照合し、最初の一致の開始点のインデックスを返しますnil
。一致がない場合は、そのインデックスを返します。
したがって、次のようにファイル名に基づいてスタイルを設定できます。
(require 'cl)
(defvar c-style-pattern-alist '(("linux" . "linux\\|kernel"))
"Association list of pairs (STYLE . PATTERN) where STYLE is the C style to
be used in buffers whose file name matches the regular expression PATTERN.")
(defvar c-style-default "free-group-style"
"Default C style for buffers whose file names do not match any of the
patterns in c-style-pattern-alist.")
(defun c-set-style-for-file-name ()
"Set the C style based on the file name of the current buffer."
(c-set-style
(loop with file-name = (buffer-file-name)
for (style . pattern) in c-style-pattern-alist
when (string-match pattern file-name) return style
finally return c-style-default)))
(add-hook 'c-mode-hook #'c-set-style-for-file-name)