如何在有 bash 詞法分析器的 minted 環境中使用 escapeinside?

如何在有 bash 詞法分析器的 minted 環境中使用 escapeinside?

escapeinside 功能無法與 bash 詞法分析器一起正常運作。有沒有辦法解決這問題?

微量元素:

\documentclass{article}
\usepackage{minted}

\begin{document}

\begin{minted}[escapeinside=||]{bash}
#!/bin/bash
echo "Hello world!"
|\textrm{Some commentary here}|
\end{minted}

\end{document}

範例影像的輸出

答案1

發生這種情況是因為 Bash 詞法分析器重新定義了反斜線的 catcode\以處理 shell 轉義序列。這意味著它不能在 escapeinside 序列中使用來啟動命令。

幸運的是,可以透過以下方式解決此問題:其他字元處於活動狀態並使用 csname 定義它以啟動其參數。所選字元不會出現在您建立的程式碼中的任何其他位置,這一點至關重要。對於這個例子,我使用問號?。當調用命令時,例如\textrm{arg},您將改為調用?{textrm}{arg},並用您選擇的字元替換問號。

\begingroup重要的是用/將整個內容括起來,\endgroup以確保 catcode 重新定義不會影響文件的其餘部分。

\documentclass{article}
\usepackage{minted}

\begin{document}

\begingroup
% REPLACE THE ? WITH YOUR CHOSEN CHARACTER ON BOTH OF THE FOLLOWING LINES
\catcode`\?=\active
\def?#1{\csname #1\endcsname}

\begin{minted}[escapeinside=||]{bash}
#!/bin/bash
echo "Hello world!"
|?{textrm}{Some commentary here}|
\end{minted}
\endgroup

\end{document}

修復後的結果

相關內容