[Tex/LaTex] How to get straight single quotes in a custom Verbatim command

fancyvrb

I use the \Verb command from the fancyvrb pacakge for in-text verbatim fragments. To get straight single quotes, I also loaded the upquote package. Unfortunately, this does not work when I use a custom command of the form

\newcommand\textcode[1]{\Verb[<options>]|#1|}

I tried adapting @egreg's solution to How can I change a glyph in a Verbatim environment?, but this was not successful. How can I create a \textcode macro that produces straight single quotes (without having to type \textquotesingle every time)?

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{upquote}
\usepackage{fancyvrb}

\newcommand\textcode[1]{\Verb|#1|}

\newcommand\makequotestraight{% 
  \begingroup\lccode`~=`'
  \lowercase{\endgroup\let~}\textquotesingle
  \catcode`'=\active
}
\newcommand\textcodeii[1]{\Verb[codes={\makequotestraight},]|#1|}

\begin{document}
\Verb|'a = b'|
\textcode{'a = b'}
\textcodeii{'a = b'}
\textcode{\textquotesingle a = b\textquotesingle}
\end{document}

quotes

Best Answer

I think the reason why egreg's trick doesn't work here is that, once the argument has been passed to your \textcodeii command, the catcodes of the characters in that argument are immutable; at that stage, they're set in stone, and it's too late to change them. Therefore, your \makequotestraight macro won't help you.

Anyway, there's no need for such a trick, here. Simply define your custom \textcode command to take no argument, like so

\newcommand\textcode\Verb

Then quotes in

 \textcode|'a = b'|

will be straight, as desired.

enter image description here

For more details on the rationale behind this definition, see Why doesn’t verbatim work within...?

The LaTeX verbatim commands work by changing category codes. Knuth says of this sort of thing "Some care is needed to get the timing right...", since once the category code has been assigned to a character, it doesn’t change. So \verb and \begin{verbatim} have to assume that they are getting the first look at the parameter text; if they aren’t, TeX has already assigned category codes so that the verbatim command doesn’t have a chance.

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{upquote}
\usepackage{fancyvrb}

\newcommand\textcode{\Verb}

\begin{document}

\textcode|'a = b'|

\end{document}