【问题标题】:How to do if condition with matching keywords in file name in emacs如何在emacs中的文件名中匹配关键字的条件
【发布时间】:2012-10-03 17:36:27
【问题描述】:

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

【问题讨论】:

    标签: emacs elisp


    【解决方案1】:

    函数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)
    

    【讨论】:

      猜你喜欢
      • 2013-06-01
      • 2013-01-13
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      相关资源
      最近更新 更多