
このnewverbs
パッケージを使用すると、ユーザーはverb
コマンドのバリアントを定義できます。これは、逐語テキストに色を適用するなどの用途に使用できます。古い と同様にverb
、ユーザー定義のバリアントは数式モードで正常に動作します。ただし、数式モードでユーザー定義のバリアントを使用すると、コンパイル時に次のエラーが発生します。
LaTeX Error: Command \ttfamily invalid in math mode.
verb
エラーなしでコンパイルされるバリアントを定義したい場合はどうすればよいでしょうか?
MWE:
\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) では機能しません。