如果在emacs中文件名中包含匹配关键字的条件,该怎么办?

jca*_*dam 2 emacs elisp

如何检测当前缓冲区或打开文件的文件名是否包含关键字?或者在emacs中匹配正则表达式?

我想根据文件名设置不同c源的样式,例如

if <pathname contains "linux">
   c-set-style "linux"
else if <pathname contains "kernel">
   c-set-style "linux"
else
   c-set-style "free-group-style"
Run Code Online (Sandbox Code Playgroud)

Gar*_*ees 6

该函数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)
Run Code Online (Sandbox Code Playgroud)