
Estou tentando descobrir uma maneira de ter uma macro onde demonstre a saída de um comando e depois mostre o comando por meio de um lstinline
comando. Eu li que preciso escapar dos caracteres especiais (como {
e }
) e agora estou me perguntando se existe uma maneira de fazer isso automaticamente. Não tenho certeza se isso é possível.
Idealmente, o \commandExample{\qty{1.2}{\meter}}
comando produziriaOutput:1.2 m - Code:\qty{1.2}{\meter}
MWE:
\documentclass{report}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{siunitx}
\usepackage{listings}
\definecolor{lightgrey}{rgb}{0.9,0.9,0.9}
\definecolor{darkgreen}{rgb}{0,0.6,0}
\lstset{language=[LaTeX]TeX,
caption = {Missing Caption}
,label = {lst:missingLabel}
,basicstyle = \footnotesize\ttfamily %\footnotesize % \small\ttfamily
,frame = shadowbox%
,numbers = left%
,breaklines = true%
,keywordstyle = \color{darkgreen}%
,commentstyle = \color{red}%
,tabsize = 2%
,backgroundcolor = \color{lightgrey}%
%,texcsstyle = {*\bf\color{blue}}%
%,otherkeywords = $, \{, \}, \[, \]%
,morekeywords = {includegraphics }%
,moretexcs = {graphicspath}%
}
\NewDocumentCommand{\commandExample}{m}{%
Output:#1 - Code:\lstinline{#1}}
\begin{document}
\commandExample{begin}.
\unit{\meter}
%\commandExample{\unit{\meter}} % This line causes it to crash
\end{document}
Responder1
Eu absorveria o argumento literalmente e usaria \tl_rescan:nn
para digitá-lo.
\documentclass{report}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{siunitx}
\usepackage{listings}
\definecolor{lightgrey}{rgb}{0.9,0.9,0.9}
\definecolor{darkgreen}{rgb}{0,0.6,0}
\lstset{language=[LaTeX]TeX,
caption = {Missing Caption}
,label = {lst:missingLabel}
,basicstyle = \footnotesize\ttfamily
,frame = shadowbox
,numbers = left
,breaklines = true
,keywordstyle = \color{darkgreen}
,commentstyle = \color{red}
,tabsize = 2
,backgroundcolor = \color{lightgrey}
,texcsstyle = {*\bfseries\color{blue}}
%,otherkeywords = {$, \{, \}, \[, \]}
,morekeywords = {includegraphics,unit}
,moretexcs = {graphicspath}%
}
\ExplSyntaxOn
\NewDocumentCommand{\commandExample}{v}
{
Output:~\tl_rescan:nn {} {#1} ~ - ~ Code:~\lstinline{#1}
}
\ExplSyntaxOff
\begin{document}
\commandExample{\unit{\meter}}
\commandExample{\textit{word}}
\end{document}
Responder2
Geralmenteo código fornecido por egregdeve ser preferido ao meu código.
Mas o mecanismo mathescape, que deve ser habilitado via \mathescape=true
inside \lstset
e que permite escapar para o modo matemático dentro do argumento \lstinline
via aninhando coisas entre $...$
, é quebrado quando aplicado \lstinline
diretamente ao argumento do tipo v.
Com o mathescape habilitado, o comando \lstinline{$x^2+y^2=2^2$}
fornece muitas mensagens de erro de padrão ! Undefined control sequence. \lst@arg ->$x
caso $x^2+y^2=2^2$
tenha sido tokenizado como um argumento tipo v.
Portanto, se no cenário da vida real você não precisar do recurso mathescape, recomendo usar o código do egreg.
Se no cenário da vida real você precisar do recurso mathescape, modifique a resposta do egreg para que \commandExample
leia e tokenize seu argumento no regime de código de categoria apropriado ou tente uma abordagem onde \scantokens
ou \tl_rescan:nn
seja aplicado aos tokens passados \lstinline
também.
Um pequeno problema é: com distribuições LaTeX menos recentes, seu código não fornece nenhuma definição para \unit
e \meter
. Portanto, no exemplo abaixo, os comandos \si
e \metre
são usados.
Um problema é: uma peculiaridade de \lstinline
é que o argumento de \lstinline
geralmente não pode ser aninhado entre {
e }
se ele próprio também contém {
. Neste caso, o argumento precisa ser aninhado entre um caractere que não ocorre dentro do argumento. Então \lstinline{\unit{\meter}}
não funcionaria, mas você precisaria fazer algo como \lstinline|\unit{\meter}|
. (Outro truque, que é feito na resposta do egreg, é ter o argumento de \lstinline
tokenizado sob o regime verbatim-catcode para que, em qualquer caso, ele não contenha {
a categoria 1 ou }
a categoria 2. Mas v
-type-category-code-régime quebra alguns recursos de \lstinline
- pelo menos o recurso mathescape.)
Outro problema é que o TeX espera que o argumento \lstinline
seja tokenizado sob diferentes regimes de código de categoria. Portanto, \lstinline
altera temporariamente o regime do código de categoria para capturar os tokens pertencentes ao seu argumento do token-stream. \lstinline
depende da necessidade do TeX ler o arquivo de entrada .tex e tokenizar os tokens pertencentes ao argumento sob o regime de código de categoria alterado para que possam ser obtidos do fluxo de tokens. Portanto, \lstinline
funciona apenas no nível do usuário/nível superior. \lstinline
não funciona quando os argumentos são passados após tokenizá-los sob o regime de código de categoria inalterado, como seria o caso, por exemplo, ao colocar chamadas \lstinline
nos textos de definição de outras macros que capturam argumentos sob o regime de código de categoria inalterado e os passam para \lstinline
.
Esse problema pode ser contornado até certo ponto fazendo com que sua \commandExample
própria macro altere o regime do código da categoria antes de capturar os argumentos e depois passá-los para \lstinline
, aninhados em \scantokens{...%}
.
Mas aqui surge outro problema: nem o LaTeX 2ε, nem o expl3, nem o xparse fornecem um tipo de argumento literal que permite preservar e transmitir o delimitador literal.
Portanto, no exemplo abaixo, \UDcollectverbarg
é fornecido o comando que muda para o regime de catcode literal e captura o argumento sem e aninhado entre o delimitador literal para que essas coisas possam ser transmitidas adequadamente para processamento posterior.
\makeatletter
%%======================Code for \UDcollectverbarg=============================
%% \UDcollectverbarg{<mandatory 1>}{<mandatory 2>}|<verbatim arg>|
%%
%% reads <verbatim arg> under verbatim-catcode-regime and delivers:
%%
%% <mandatory 1>{<mandatory 2>{<verbatim arg>}{|<verbatim arg>|}}
%%
%% Instead of verbatim-delimiter | the <verbatim arg> can be nested in braces.
%% You cannot use percent or spaces or horizontal tab as verbatim-delimiter.
%%
%% You can use <mandatory 1> for nesting calls to \UDcollectverbarg.
%% <mandatory 2> gets the <verbatim arg> twice: Once without verbatim-delimiters/braces,
%% once surrounded by verbatim-delimiters/braces.
%% Reason: When you feed it to \scantokens you don't need the verbatim-delimiters.
%% When you use it for writing to temporary files and reading back,
%% you need them.
%%=============================================================================
%% Check whether argument is empty:
%%=============================================================================
\@ifdefinable\UD@stopromannumeral{\chardef\UD@stopromannumeral=`\^^00}%
%%
%% \UD@CheckWhetherNull{<Argument which is to be checked>}%
%% {<Tokens to be delivered in case that argument
%% which is to be checked is empty>}%
%% {<Tokens to be delivered in case that argument
%% which is to be checked is not empty>}%
%%
%% The gist of this macro comes from Robert R. Schneck's \ifempty-macro:
%% <https://groups.google.com/forum/#!original/comp.text.tex/kuOEIQIrElc/lUg37FmhA74J>
\newcommand\UD@CheckWhetherNull[1]{%
\romannumeral\expandafter\@secondoftwo\string{\expandafter
\@secondoftwo\expandafter{\expandafter{\string#1}\expandafter
\@secondoftwo\string}\expandafter\@firstoftwo\expandafter{\expandafter
\@secondoftwo\string}\expandafter\UD@stopromannumeral\@secondoftwo}{%
\expandafter\UD@stopromannumeral\@firstoftwo}%
}%
%%=============================================================================
\newcommand\UDcollectverbarg[2]{%
\begingroup
\let\do\@makeother % <- this and the next line switch to
\dospecials % verbatim-category-code-régime.
\catcode`\{=1 % <- give opening curly brace the usual catcode so a
% curly-brace-balanced argument can be gathered in
% case of the first thing of the verbatimized-argument
% being a curly opening brace.
\catcode`\ =10 % <- give space and horizontal tab the usual catcode so \UD@collectverbarg
\catcode`\^^I=10 % cannot catch a space or a horizontal tab as its 4th undelimited argument.
% (Its 4th undelimited argument denotes the verbatim-
% syntax-delimiter in case of not gathering a
% curly-brace-nested argument.)
\catcode`\%=14 % <- make percent comment.
\kernel@ifnextchar\bgroup
{% seems a curly-brace-nested argument is to be caught:
\catcode`\}=2 % <- give closing curly brace the usual catcode also.
\UD@collectverbarg{#1}{#2}{}%
}{% seems an argument with verbatim-syntax-delimiter is to be caught:
\do\{% <- give opening curly brace the verbatim-catcode again.
\UD@collectverbarg{#1}{#2}%
}%
}%
\newcommand\UD@collectverbarg[3]{%
\do\ % <- Now that \UD@collectverbarg has the delimiter or
\do\^^I% emptiness in its 4th arg, give space and horizontal tab
% the verbatim-catcode again.
\do\^^M% <- Give the carriage-return-character the verbatim-catcode.
\do\%% <- Give the percent-character the verbatim-catcode.
\long\def\@tempb##1#3{%
\def\@tempb{##1}%
\UD@CheckWhetherNull{#3}{%
\def\@tempc{{##1}}%
}{%
\def\@tempc{#3##1#3}%
}%
\@onelevel@sanitize\@tempb % <- Turn characters into their "12/other"-pendants.
% This may be important with things like the
% inputenc-package which may make characters
% active/which give them catcode 13(active).
\@onelevel@sanitize\@tempc
\expandafter\expandafter\expandafter\UD@@collectverbarg% <- this "spits out the result.
\expandafter\expandafter\expandafter{%
\expandafter\@tempb\expandafter}%
\expandafter{\@tempc}{#1}{#2}%
}%
\@tempb
}%
\newcommand\UD@@collectverbarg[4]{%
\endgroup
#3{#4{#1}{#2}}%
}%
%%================= End of code for \UDcollectverbarg =========================
\makeatother
%%
\documentclass{report}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{siunitx}
\usepackage{listings}
\definecolor{lightgrey}{rgb}{0.9,0.9,0.9}
\definecolor{darkgreen}{rgb}{0,0.6,0}
\lstset{language=[LaTeX]TeX,
% !!! Let's enable the mathescape-feature to test if it works:
mathescape=true,
%
caption = {Missing Caption}
,label = {lst:missingLabel}
,basicstyle = \footnotesize\ttfamily %\footnotesize % \small\ttfamily
,frame = shadowbox%
,numbers = left%
,breaklines = true%
,keywordstyle = \color{darkgreen}%
,commentstyle = \color{red}%
,tabsize = 2%
,backgroundcolor = \color{lightgrey}%
%,texcsstyle = {*\bf\color{blue}}%
%,otherkeywords = $, \{, \}, \[, \]%
,morekeywords = {includegraphics }%
,moretexcs = {graphicspath}%
}
\makeatletter
\NewDocumentCommand{\commandExample}{}{%
\UDcollectverbarg{\@firstofone}{\@commandExample}%
}%
\begingroup
\catcode`\X=14 %
\catcode`\%=12 X
\csname @firstofone\endcsname{X
\endgroup
\NewDocumentCommand{\@commandExample}{mm}{X
\scantokens{Output: #1 - Code: \lstinline#2%}X
}X
}%
\makeatother
\begin{document}
\verb:\commandExample{begin}: yields:
\commandExample{begin}
\medskip\hrule\medskip
\noindent Both with \verb|\lstinline| and thus with this variant of \verb|\commandExample| you can't have
\verb|{| within arguments that are nested between \verb|{...}|. Use some verbatim-delimiter instead:
\medskip
\verb:\commandExample|\si{\metre}|: yields:
\commandExample|\si{\metre}|
\medskip\hrule\medskip
\noindent \verb|mathescape|-thingies in the code seem to work, too:
\medskip
\verb:\commandExample|$x^2+y^2=z^2$|: yields:
\commandExample|$x^2+y^2=z^2$|
\medskip\hrule\medskip
\verb:\commandExample{$x^2+y^2=z^2$}: yields:
\commandExample{$x^2+y^2=z^2$}
\end{document}