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

时间:2012-10-02 22:15:55

标签: 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"

1 个答案:

答案 0 :(得分: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)