2

如何检测当前缓冲区或打开文件的文件名是否包含关键字?或匹配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"
4

1 回答 1

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)
于 2012-10-02T23:10:48.087 回答