
我使用\ifdefstring
作為條件定義的一部分,該定義取決於環境變量,如圖所示在這個問題中。
它大部分工作正常,除了在 定義的塊內\ifdefstring
,如果我有一個\lstinline
包含反斜杠,我需要轉義它們,否則它將不起作用。
我希望能夠添加\ifdefstring
區塊而不必轉義/取消轉義裡面的內容,特別是因為錯誤訊息不是很清楚:缺少反斜線會導致區塊末尾出現神秘的錯誤訊息。有辦法這樣做嗎?
這是一個 MVE,在每種情況下(在 的內部和外部\ifdefstring
)都必須列印一個反斜線。
\documentclass{article}
\usepackage{listings}
\usepackage{etoolbox}
% catchfile block copied from other question
\usepackage{catchfile}
\newcommand{\getenv}[2][]{%
\CatchFileEdef{\temp}{"|kpsewhich --var-value #2"}{\endlinechar=-1\relax}%
\if\relax\detokenize{#1}\relax\temp\else\edef#1{\temp}\fi}
\getenv[\VAR]{VAR}%
\begin{document}
\ifdefstring{\VAR}{yes}{
\lstinline|\\must_be_escaped_yes|
}{
\lstinline|\\must_be_escaped_not_yes|
}
\lstinline|\must_not_be_escaped|
\end{document}
輸出(此處為VAR != yes
)是:
但為了使其可解析,我必須手動在區塊內的部分\
中添加額外的內容,這是我想避免的。\lstinline
\ifdefstring
答案1
\lstinline
與其他逐字指令有點不同,所以它能進入另一個命令的參數,但有限制。
您可以定義\else
-\fi
形式,\ifdefstring
以便可以使用未轉義的版本。
\documentclass{article}
\usepackage{listings}
\usepackage{etoolbox}
% catchfile block copied from other question
\usepackage{catchfile}
\newcommand{\getenv}[2][]{%
\CatchFileEdef{\temp}{"|kpsewhich --var-value #2"}{\endlinechar=-1\relax}%
\if\relax\detokenize{#1}\relax\temp\else\edef#1{\temp}\fi}
\newcommand{\defstring}[2]{%
TT\fi
\ifdefstring{#1}{#2}{\iftrue}{\iffalse}%
\ignorespaces
}
\getenv[\VAR]{VAR}
\begin{document}
\if\defstring{\VAR}{yes}
\lstinline|\must_be_escaped_yes|
\else
\lstinline|\must_be_escaped_not_yes|
\fi
\lstinline|\must_not_be_escaped|
\end{document}