emacs:使用regexp有选择地选择执行加料挂钩的缓冲区

时间:2014-07-08 02:24:44

标签: emacs

如何有选择地将文件/缓冲区名称添加到我的钩子中?在下面的示例中,我想满足condition,这样只有在我打开特别命名的文件时才会执行我的命令,例如“testLog.txt”。

(add-hook 'text-mode-hook
          (lambda ()
            (if (condition)
                ;; condition true:
                (font-lock-add-keywords nil '((regexp1 1 'font-lock-function-name-face)))
              ;; condition false:
              (font-lock-add-keywords nil   '((regexp2 1 'font-lock-function-name-face)))
              )
            ))

我尝试使用(string= (buffer-name) "contacts.txt")代替(condition),但我希望匹配更多文件名。

有什么建议吗?

此问题是a previous question

的后续问题

1 个答案:

答案 0 :(得分:3)

这样的事情怎么样? regexp可以是文件类型扩展,也可以是完整文件名(不带路径)或缓冲区名称。

  
(defvar text-mode-buffer-regexp '(
  "\\.txt" "\\.md" "\\.pm" "\\.conf" "\\.htaccess" "\\.html" "\\.tex" "\\.el"
  "\\.yasnippet" "user_prefs" "\\.shtml" "\\.cgi" "\\.pl" "\\.js" "\\.css"
  "\\*eshell\\*")
"Regexp of file / buffer names that will be matched using `regexp-match-p` function.")

;; https://github.com/kentaro/auto-save-buffers-enhanced
;; `regexp-match-p` function modified by @sds on stackoverflow
;; http://stackoverflow.com/a/20343715/2112489
(defun regexp-match-p (regexps string)
  (and string
       (catch 'matched
         (let ((inhibit-changing-match-data t)) ; small optimization
           (dolist (regexp regexps)
             (when (string-match regexp string)
               (throw 'matched t)))))))

(add-hook 'text-mode-hook (lambda ()
  (if (regexp-match-p text-mode-buffer-regexp (buffer-name))
      ;; condition true:
      (font-lock-add-keywords nil
        '((regexp1 1 'font-lock-function-name-face)))
    ;; condition false:
    (font-lock-add-keywords nil
      '((regexp2 1 'font-lock-function-name-face))) ) ))