Emacs:非代码文件的语法高亮

Emacs: syntax highlight for non-code files

让我们假设我想创建一个文件(使用 emacs)来解释一些关于编程的事情。比如一个mylib-tutorial.txt.

有没有办法在包含代码的文件的特定部分打开语法高亮显示?

例如:

Tutorial
---------
This call behaves as follow:

  void foo(&resource);

This call will provoke a huge stack overflow and all of your 
personal files will be permanent lost (a copy to the police
will be sent, though).

有没有办法为代码示例打开语法高亮?也许是组织模式?

Enable org-src-fontify-natively:

(eval-after-load "org"
  '(setq org-src-fontify-natively t))

然后使用org-mode:

* Tutorial

This call behaves as follows:

#+BEGIN_SRC c
  void foo(&resource);
#+END_SRC

This call will provoke a huge stack overflow and all of your 
personal files will be permanent lost (a copy to the police
will be sent, though).

您还可以使用 org-edit-special 编辑 c-mode 中的 SRC 块,默认绑定到 C-c '。再次使用 C-c ' 关闭 c-mode 缓冲区并更新 Org 缓冲区。

你甚至可以做得比仅仅将区域字体化更好:使用 nxhtml-mode 你可以在代码区域中启用适当的模式。

这是一个基本的 nxhtml 设置:

;; nxhtml-mode:
(load "~/.emacs.d/site-lisp/nxhtml/autostart.el")
;; Mumamo is making emacs 23.3 freak out:
(when (and (equal emacs-major-version 23)
           (equal emacs-minor-version 3))
  (eval-after-load "bytecomp"
    '(add-to-list 'byte-compile-not-obsolete-vars
                  'font-lock-beginning-of-syntax-function))
  ;; tramp-compat.el clobbers this variable!
  (eval-after-load "tramp-compat"
    '(add-to-list 'byte-compile-not-obsolete-vars
                  'font-lock-beginning-of-syntax-function)))
(require 'mumamo)
(require 'mumamo-fun)

例如,让我们为 rst-mode 添加一个 css 代码规则。在 reStructuredText css 代码中用

标记

..代码块:: css

p { 文本对齐:右; }

现在让我们编写规则,指定它应该处于 css 模式。为此,打开 nxhtml/util/mumamo-fun.el 并在其中添加:

(defun rst-bk-mumamo-css-regexp-chunk-start (pos max)
  (let ((where (mumamo-chunk-start-fw-re pos max "\.\. code-block:: css\(.\|\n\)*?\n\n")))
    (when where
      (list where 'css-mode))))

(defun rst-bk-mumamo-css-regexp-chunk-end (pos max)
  (save-match-data
    (mumamo-chunk-end-fw-re pos max "\(^[[:blank:]]+$\|\n\)+[^[:blank:]\n]")))

(defun rst-bk-mumamo-css-quick-regexp-chunk (pos
                                  min
                                  max)
  (save-match-data
    (mumamo-possible-chunk-forward pos max 'rst-bk-mumamo-css-regexp-chunk-start
                                           'rst-bk-mumamo-css-regexp-chunk-end)))

(defun rst-bk-mumamo-css-directive (pos min max)
  "Find css chunks. Return range and 'css-mode.
   See `mumamo-find-possible-chunk' for POS, MIN and MAX."
  (rst-bk-mumamo-css-quick-regexp-chunk pos min max))

现在让我们将其注册为新的第一模式:

;;;###autoload
(define-mumamo-multi-major-mode rst-bk-mumamo-mode
  "Turn on multiple major modes for RestructuredText."
  ("ReST" rst-mode (
                    rst-bk-mumamo-css-directive
                    )))

并将第一个文件与这个新的第一个模式相关联:

(add-to-list 'auto-mode-alist '("\.rst\'" . rst-bk-mumamo-mode))

现在您在第一个文件的 css 代码块中有了 css-模式: