Closed3

LaTeXのシンタックスハイライトにmintedを使う

nac-39nac-39

やりたいこと

LaTeXのシンタックスハイライトにMintedを使いたい

諸々の仕組み

  • Minted: LaTeXでシンタックスハイライトをしてくれるパッケージ。内部的にPygmentsを使っている。
  • Pygments: Python製のシンタックスハイライター。pipでインストールできる。

詰まりポイント

pygmentsのPATHがTeXから見えていない

[TeXコマンドのインストールディレクトリ]/pygmentizeがないとエラーになる
→自分の環境の場合、/Library/TeX/texbin/pygmentizeが必要
→pyenvを使ってpygmentizeをインストールしているので、シンボリックリンクを貼る

ln -s `which pigmentize` /Library/TeX/texbin
lrwxr-xr-x@   1 root  wheel         39  1 24 09:06 pygmentize@ -> /Users/xxxxx/.pyenv/shims/pygmentize

キャッシュ関係

私の環境では、setting.jsonでoutDirが/outに指定されています。そのため、cachediroutputdiroutに指定しなければなりません。

最終的にうまく行ったusepackage:

\usepackage[outputdir=out]{minted}

outputdirが指定されていない

TeXの出力先ディレクトリを.texと同じ階層にせず、別のディレクトリを指定しているとエラーになります。

このとき、次のようなエラーが出ます。

Error: cannot read infile: [Errno 2] No such file or directory: 'report.pyg'
Package minted Error: Missing Pygments output; \inputminted was
probably given a file that does not exist--otherwise, you may need 
the outputdir package option, or may be using an incompatible build tool,
or may be using frozencache with a missing file.

report.pygはpygmentが生成する中間ファイルのようです。
cachedir=outと指定してもoutディレクトリに保存されない(正確には、途中までは保存されるが、途中でプロジェクトルートを参照しようとしてエラーになってしまう)のですが、outdir=outと指定すればreport.pygoutディレクトリに保存されるようになります。

-shell-escapeオプション

ptex2pdfを使用した環境では、外部コマンドを実行するための-shell-escapeオプションを指定しないと行けないそうです。私はVSCode上でLaTeX Workshopを使っているので、settings.jsonに次のように追記しました。

  // ビルドのレシピの定義
  "latex-workshop.latex.tools": [
    {
      "name": "ptex2pdf",
      "command": "ptex2pdf",
      "args": [
        "-l",
        "-ot",
+      "-shell-escape", // mintedを使うために必要
        // PDFジャンプしたいからsynctexを有効にする
        "-kanji=utf8 -synctex=1",
        "-interaction=nonstopmode",
        "-file-line-error",
        "-output-directory",
        "%OUTDIR%",
        "%DOC%"
      ]
    }
  ],
nac-39nac-39

スニペット
パッケージのインポート

\usepackage[outputdir=out]{minted}

コードの埋め込み(ブロック)

\begin{minted}[]{python}
...
\end{minted}

コードの埋め込み(インライン)

\mintinline{c}|int hoge = 0;|

VSCodeのスニペット
latex.json:

{
		"source code": {
			"prefix": "code",
			"body": [
				"\\begin{minted}[${1:linenos}]{${2:python}}",
				"${3:code}",
				"\\end{minted}",
			],
			"description": "ソースコードを表示"
		},
}
このスクラップは3ヶ月前にクローズされました