[Tex/LaTex] Changing all single quotes to be straight when within texttt

typewriter

I have a document with many ' characters inside of texttt. Is there a way to make them all appear straight when in texttt?

I know that I can search/replace all ' with \textquotesingle:

Perhaps there is some preamble declaration to tell texttt to render all ' as \textquotesingle?

Best Answer

Here is an approach using active characters, but still allowing \texttt usage inside arguments of other macros. (because it uses \scantokens).

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{upquote}
\usepackage{etoolbox} % for robustify

\robustify{\texttt}
\let\originaltexttt\texttt

\begingroup
\catcode`'=\active
\catcode``=\active
\globaldefs1
\makeatletter
\renewrobustcmd{\texttt}[1]{%
   {%
   \everyeof{\noexpand}\endlinechar-1
   \expandafter\catcode\string``=\active
   \expandafter\catcode\string`'=\active
   \let'\textquotesingle
   \let`\textasciigrave
   \ifx\encodingdefault\upquote@OTone
    \ifx\ttdefault\upquote@cmtt
     \def'{\char13 }\def`{\char18 }%
    \fi
   \fi
   \scantokens{\originaltexttt{#1}}%
   }%
}%
\endgroup


\begin{document}

\null\vfill
abc'def---\texttt{abc'def}---abc'def 
\footnote{\texttt{This is a footnote ``''}}

\textit{\texttt{abc`def'ghi}}---\texttt{\textit{abc`def'ghi}}
\footnote{\textit{\texttt{This is another footnote ``''}}}

\end{document}

The advantage compared to my other answer is that it makes do with the document typewriter font, it does not modify it. The disadvantage is that \scantokens may reserve some surprises. Concretely the main issue coming to my mind is that one should not use it in a context where the space character has been made active, and the main case will be the alltt environment (of course verbatim is no issue, as \texttt macro does not get executed). But that's already a bit specialized context, so generally speaking it will be fine.

enter image description here

Notice that my approach loads package upquote so verbatim environment will be with straight single quotes too.