One possibility would be to use the accsupp
package, which allows us to define alternate texts for use by screen readers. A side-effect of this is that the text stream that is copied/searched from the PDF is also modified.
accsupp
can be used ad-hoc (second paragraph of my document below) or wrapped in a command if you have many such patterns throughout the document. The accsupp
method is not suitable for anything that could be expected to be split by a page break, but that should not occur for your usage here.
The highlighting in the PDF viewer can get weird (I noticed this in Adobe Acrobat DC), but the correct text is found by the search function when I tested in SumatraPDF and Adobe Acrobat DC on Windows 7. I do not know if this approach will work for all viewers.
\documentclass{article}
\usepackage{accsupp}
\newcommand*\mycommand[2]{%
\BeginAccSupp{ActualText=#1#2}%
\texttt{\textit{#1}#2}\EndAccSupp{}%
}
\begin{document}
\texttt{\textit{C}D}
\BeginAccSupp{ActualText=CD}\texttt{\textit{C}D}\EndAccSupp{}
\mycommand{C}{D}
\end{document}
Added after request for section headings:
For use in headings, the command must be robust (I used etoolbox
for this, but there are other ways to accomplish it). I'm guessing you're probably also using hyperref
, so I checked the bookmark list: this also functions correctly. The ActualText
value is used for the bookmark text.
\documentclass{article}
\usepackage{accsupp}
\usepackage{etoolbox}
\usepackage{hyperref}
\newrobustcmd*\mycommand[2]{%
\BeginAccSupp{ActualText=#1#2}%
\texttt{\textit{#1}#2}\EndAccSupp{}%
}
\begin{document}
\texttt{\textit{C}D}
\BeginAccSupp{ActualText=CD}\texttt{\textit{C}D}\EndAccSupp{}
\mycommand{C}{D}
\section{\mycommand{C}{D}}
\end{document}