
該newverbs
套件允許使用者定義verb
命令的變體,可用於將顏色應用於逐字文字等操作。就像舊的一樣verb
,使用者定義的變體在數學模式下運作得很好。但是,在數學模式下使用使用者定義的變體會在編譯時出現以下錯誤:
LaTeX Error: Command \ttfamily invalid in math mode.
如果我想定義verb
沒有錯誤的編譯變體,我該怎麼辦?
微量元素:
\documentclass{article}
\usepackage{newverbs}
\newverbcommand{\myverb}{}{}
\begin{document}
Old \verb|verb|, works in math: $+\verb|foo|+$.
New \myverb|verb|, gives error in math: $+\myverb|foo|+$.
\end{document}
當我們忽略編譯錯誤時,這會給出所需的輸出,即:
答案1
不同的是,\verb
確實如此\ifmmode\hbox
;更確切地說
% latex.ltx, line 5775:
\def\verb{\relax\ifmmode\hbox\else\leavevmode\null\fi
\bgroup
\verb@eol@error \let\do\@makeother \dospecials
\verbatim@font\@noligs
\language\l@nohyphenation
\@ifstar\@sverb\@verb}
用 定義的命令\newverbcommand
不執行此檢查。您可以透過修補相關命令並\hbox
在數學模式下添加包絡來修復它。
\documentclass{article}
\usepackage{newverbs}
\usepackage{etoolbox}
\makeatletter
\patchcmd{\new@@verbcommand}
{\bgroup}
{\ifmmode\hbox\fi\bgroup}
{}{}
\makeatother
\newverbcommand{\myverb}{}{}
\begin{document}
Old \verb|verb|, works in math: $+\verb|foo|+$.
New \myverb|verb|, gives error in math: $+\myverb|foo\\|+$.
\end{document}
答案2
您可以將逐字詞放入框中:
\documentclass{article}
\usepackage{newverbs}
\newverbcommand{\myverb}{\hbox\bgroup}{\egroup}
\begin{document}
Old \verb|verb|, works in math: $+\verb|foo|+$.
New \myverb|verb|, gives error in math: $+\myverb|foo|+$.
\end{document}
結果和你的一樣,但是沒有錯誤。
更正:正如egreg 所指出的,這種方法不適用於較新的newverbs
版本。對於 1.3a (2012/05/08) 有效,對於 1.4 (2019/09/09) 無效。