Is there any way to define some custom command using the \verb|| environment? As an example, I want to write {\color{SteelBlue4} \verb|my_data.txt|} since using the _ will cause an error if I only use \texttt{}. So I tried writing \newcommand{\Rcode}[1]{{\color{SteelBlue4} \verb|#1|}}, but this does not work. Is there any way to do this, or is it just not possible?


3 Answers 3


The problem with \verb is that it processes its input in a special way that prevents it from appearing inside of other commands or inside command arguments. For example, these two will give you an error

\newcommand\x{\verb|x|} % will only error once \x is used

However, the command \verb itself is allowed to appear inside another command. This example is legal:

\newcommand\x{y: \verb}

That is because the argument of \verb does not appear inside of another command. Together with the knowledge that the font of \verb is determined by \verbatim@font, we can patch the \verb macro such that is accepts an optional argument and appends it to the font settings. With this we can then define the requested \Rcode command in the same manner. We pass the optional argument to \verb but the other argument we leave out and let \verb scan ahead by itself.










enter image description here


This is a task for newverbs:




Standard \verb+\verb+: \verb+my_data.txt+ and text after

With \verb+\Rcode+: \Rcode+my_data.txt+ and text after


enter image description here


Disclaimer: this answer is similar to my other answer in https://tex.stackexchange.com/a/638992/250119 except that the code is tailored to this specific question

Using Ulrich Diez's \DefineVerbatimToScantokens macro from the answer https://tex.stackexchange.com/a/629173/250119 (note. go to that answer to read on how to use that macro & maybe upvote if you find the answer useful. Unfortunately as far as I know it's not in any package at the moment so you have to copy paste the code), we can do the following:


%=== Code of \DefineVerbatimToScantokens ========================
% ... <copy the code from that answer>
%=== End of code of \DefineVerbatimToScantokens =================

\DefineVerbatimToScantokens{\Rcode}{v}{\color{SteelBlue4} \verb|#1|}





Also read documentation of xparse.pdf to see what does it mean to specify v here and that it allows % etc. except literal TAB to be included in the argument.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .