LaTeX 中的代码高亮(英文)

Tool link: Emacs Syntax Highlighting for LaTeX (ESH).

The tool does not really require understanding Emacs: one just needs a working installation! The tool seems well tested on GNU/Linux; however, I am mainly using macOS, so I find out an easy workflow that works for me. First, we need to install Cask, a project management tool for Emacs; such process should be easy and straightforward. Then we clone the esh repo and run cask build at the root of the repo. If nothing goes wrong, we are now able to use ESH!

Let us go to a LaTeX project where we want to highlight OCaml code. First, we create a file Cask with the following content:

(source gnu)
(source melpa)

(depends-on "tuareg") ;; for OCaml mode

Then we run cask install to install the required packages. Now we start to configure how we would like our code to be highlighted. We achieve this by creating a file esh-init.el, and below gives an example:

(load-theme 'tango t) ;; a color theme

(add-to-list 'auto-mode-alist '("\\.ml\\'" . tuareg-mode)) ;; .ml file extension

;; some custom prettification
(when (require 'tuareg nil t)
  (defun my-tuareg-setup ()
    (setq-local prettify-symbols-alist '(("fun" . ) ("->" . ?)))
    (prettify-symbols-mode))
  (add-hook 'tuareg-mode-hook #'my-tuareg-setup))

Next, we run ./path/to/esh/bin/esh2tex --write-preamble to create a file esh-preamble.tex. The generated TeX file implements functions to highlight code in TeX. Below presents an example LaTeX file:

\documentclass{article}
\usepackage[varqu]{zi4} % for inconsolata font

\input{esh-preamble}

\begin{document}
  \ESHInputBlock{test.ml}
\end{document}

And an example OCaml code file test.ml:

let rec append l1 l2 =
  match l1 with
  | [] -> l2
  | x :: xs -> x :: (append xs l2)

let rec partition f l =
  match l with
  | [] -> ([], [])
  | x :: xs ->
    let (cs, bs) = partition f xs in
    if f x then
      (cs, x :: bs)
    else
      (x :: cs, bs)

let rec quicksort le = function
  | [] -> []
  | x :: xs ->
    let (ys, zs) = partition (le x) xs in
    append (quicksort le ys) (x :: (quicksort le zs))

ESH needs to invoke Emacs to highlight the code and we have to perform this external operation manually. Fortunately, we just need to run ./path/to/esh/bin/esh2tex --standalone test.ml, which should generate a file test.ml.esh.tex. Finally, we can typeset our LaTeX project (e.g, pdflatex main) and should get something similar to the following screenshot:

Amazing!

王迪
王迪
助理教授

朝着思想自由、兼容并包的计算机科学前进!