给 EWW 中的代码块添加代码高亮

Emacs China 论坛不支持 Emacs Lisp 代码高亮,是因为所用的 highlight.js 不支持,大家写的 Emacs Lisp 代码有高亮的,一般都被识别成了 Clojure 或者 Common Lisp。(我个人觉得不好看,所以宁愿不要高亮)。但是用 EWW 浏览论坛的话,就能直接用 Emacs 做代码高亮了:

(defun chunyang-eww-tag-pre (dom)
  "Add Emacs Lisp syntax highlighting.
Alternative to `shr-tag-pre'."
  (let ((shr-folding-mode 'none)
        (shr-current-font 'default))
    (shr-ensure-newline)
    (insert
     (chunyang-eww-fontify-code
      (with-temp-buffer
        (shr-generic dom)
        (buffer-string))
      'emacs-lisp-mode))
    (shr-ensure-newline)))

(defun chunyang-eww-fontify-code (string mode)
  "Fontify CODE in major-mode MODE."
  (with-temp-buffer
    (insert string)
    (delay-mode-hooks (funcall mode))
    (if (fboundp 'font-lock-ensure)
        (font-lock-ensure)
      (with-no-warnings
        (font-lock-fontify-buffer)))
    (buffer-string)))

(setq shr-external-rendering-functions
      '((pre . chunyang-eww-tag-pre)))

效果图(图中所用主题为 sanityinc-tomorrow-eighties

我上面假设所有的代码块都是 Emacs Lisp,实际情况并非如此,大家可以用各种方法得到(或者猜 GitHub - andreasjansson/language-detection.el: Automatic programming language detection of code snippets, in Emacs Lisp )编程语言,进而支持更多的编程语言。

7 个赞

我把这个想法写成了一个 Package(shr-tag-pre-highlight),如果你使用 MELPA 的话,可以通过它安装。

3 个赞