regex - 在 Emacs 的 C/C++ 模式下,将 #if 0...#endif block 中的代码面更改为注释面

标签 regex emacs aquamacs emacs-faces

我正在尝试将其他一些代码编辑器中的功能添加到我的 Emacs 配置中,从而 #if 0...#endif block 中的 C/C++ 代码自动设置为注释面/字体。根据我的测试, cpp-highlight-mode 做了我想要的,但需要用户操作。似乎绑定(bind)字体锁定功能是使行为自动化的正确选项。

我已经成功地按照 GNU 文档中的示例更改了单行正则表达式的外观。例如:

(add-hook 'c-mode-common-hook
  (lambda ()
    (font-lock-add-keywords nil
      '(("\\<\\(FIXME\\|TODO\\|HACK\\|fixme\\|todo\\|hack\\)" 1 
        font-lock-warning-face t)))))

可以很好地突出显示文件中任何位置的调试相关关键字。但是,我在将 #if 0...#endif 匹配为多行正则表达式时遇到问题。我在这篇文章 (How to compose region like "<?php foo; bar; ?>") 中找到了一些有用的信息,这表明必须专门告知 Emacs 以允许多行匹配。但是这段代码:
(add-hook 'c-mode-common-hook
  (lambda ()
    '(progn
      (setq font-lock-multiline t)
      (font-lock-add-keywords nil
        '(("#if 0\\(.\\|\n\\)*?#endif" 1
          font-lock-comment-face t))))))

仍然不适合我。也许我的正则表达式是错误的(尽管它似乎可以使用 M-x re-builder 工作),我搞砸了我的语法,或者我完全遵循了错误的方法。我在 OS X 10.6.5 上使用 Aquamacs 2.1(基于 GNU Emacs 23.2.50.1),如果这会有所不同的话。

任何援助将不胜感激!

最佳答案

即使你让多行正则表达式工作,你仍然会遇到嵌套 #ifdef/#endif 的问题的,因为它会在第一个 #endif 处停止字体锁定.此代码有效,但我不确定大文件是否会明显变慢:

(defun my-c-mode-font-lock-if0 (limit)
  (save-restriction
    (widen)
    (save-excursion
      (goto-char (point-min))
      (let ((depth 0) str start start-depth)
        (while (re-search-forward "^\\s-*#\\s-*\\(if\\|else\\|endif\\)" limit 'move)
          (setq str (match-string 1))
          (if (string= str "if")
              (progn
                (setq depth (1+ depth))
                (when (and (null start) (looking-at "\\s-+0"))
                  (setq start (match-end 0)
                        start-depth depth)))
            (when (and start (= depth start-depth))
              (c-put-font-lock-face start (match-beginning 0) 'font-lock-comment-face)
              (setq start nil))
            (when (string= str "endif")
              (setq depth (1- depth)))))
        (when (and start (> depth 0))
          (c-put-font-lock-face start (point) 'font-lock-comment-face)))))
  nil)

(defun my-c-mode-common-hook ()
  (font-lock-add-keywords
   nil
   '((my-c-mode-font-lock-if0 (0 font-lock-comment-face prepend))) 'add-to-end))

(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

编辑:
考虑#else
编辑#2:
处理 if/else/endif 的任意嵌套的 Niftier 代码

关于regex - 在 Emacs 的 C/C++ 模式下,将 #if 0...#endif block 中的代码面更改为注释面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549015/

相关文章:

emacs - 创建 LaTeX 跳转到 PDF 的键绑定(bind) --synctex

javascript - 尝试匹配/测试完全合格的 sub.domain.com :1000 or 127. 0.0.1:1000

jquery - 电话验证正则表达式(TEXT 和 TEXTTWO 除外)

emacs - Aquamacs 2.4 -- WordWrap/Visual Line 模式 -- 错误解决方法?

node.js - Emacs - 加载模块后绑定(bind)键

python - 为什么这行 python 会破坏 emacs python-mode 缩进?

emacs - 在 Aquamacs 问题上使用 'lein swank' 运行 Clojure

c# - 使用正则表达式 C# 去除除 <b> 之外的 html 标签

regex - 转换正则表达式以用于 VBA

html - 在 Emacs 中编辑 HTML 时如何跳转到匹配的标签?