如何让Emacs cc-mode将Mako模板的%指令按C预处理指令处理?
Absolutely! You can tweak cc-mode's configuration to treat Mako's %-prefixed lines just like C preprocessor # lines. Here's how to do it step by step:
Update the preprocessor symbol regex
cc-mode usesc-preprocessor-symbol-regexpto identify which lines count as preprocessor directives. By default, it only matches lines starting with#. We'll extend it to include%as well:(setq c-preprocessor-symbol-regexp "^[ \t]*[%#]")This regex matches lines that start with optional whitespace followed by either
%or#, so cc-mode will now recognize Mako directives as preprocessor-style lines.Adjust indentation behavior
To ensure%lines use the same indentation rules as#preprocessor lines, set thecpp-macrooffset inc-offsets-alist. For example, to keep them aligned with the current indentation level:(setq c-offsets-alist '((cpp-macro . 0)))If you prefer them indented like regular code, you can use values like
+(indent one level) or-(outdent one level) instead of0.Apply the configuration automatically
To make these settings stick every time you open a C file (or Mako C template), add the code to your Emacs init file (~/.emacsor~/.emacs.d/init.el) using a mode hook:(add-hook 'c-mode-hook (lambda () (setq c-preprocessor-symbol-regexp "^[ \t]*[%#]") (setq c-offsets-alist '((cpp-macro . 0)))))If your Mako templates have a specific extension (like
.mako.c), you can also auto-associate them with c-mode:(add-to-list 'auto-mode-alist '("\\.mako\\.c\\'" . c-mode))
After setting this up, restart Emacs or reload your config (M-x eval-buffer if you edited the init file directly). Your Mako % directives should now get the same syntax highlighting and automatic indentation as standard C preprocessor lines!
内容的提问来源于stack exchange,提问作者Jmb

