Plain TeX and underscores

We have a bunch of scripts to generate invoices for our customers. It creates plain TeX files from CSV and then PDF files (using the pdftex program). This "black box" was created by one of our former employee. Frankly, I don't understand TeX or plain TeX at all.

Recently, we added customer that has underscore character in his address. The "black box" stopped working until I googled up, that I have to escape underscore characters like this: \_

Scripts are working well again, but a new problem occurred. When I copy & paste the text from final PDF (to email or text editor or somewhere else), the underscore characters disappears (they are replaced with spaces 0x20).

In Acroread or other PDF viewers they are displayed properly. They just cannot be "copied out". It looks like in PDF it is some other character than in other fonts.

-
Welcome to TeX.SX! –  egreg Sep 4 '14 at 9:22
Thank you very much ;) –  Jan Sep 4 '14 at 9:29

You can avoid escaping the underscore by making it active (and doing its usual job in math):

% define the active underscore
\def\activeunderscore{\relax\ifmmode\sb\else\expandafter\copyableunderscore\fi}
\def\copyableunderscore{{\ectenrm\char\_}}

\catcode_=\active
\let_\activeunderscore
\font\ectenrm=ecrm1000 % this has the underscore that's mapped to its usual meaning

Here's a copyable_underscore.

In math it makes a subscript: $a_1$

\bye


-
Good Lord! Looks like black magic. But works! Thank you ;) –  Jan Sep 4 '14 at 9:48
@Jan VoodooTeX. ;-) –  egreg Sep 4 '14 at 9:50
There is one redundant \expandafter in your code. And the EC font need not to be loaded because the \tentt does similar work. –  wipet Sep 4 '14 at 12:10
@wipet It's possibly redundant, yes, but one might want a cleverer \copyableunderscore macro that tests what comes along, so I prefer to get rid of \fi before expanding \copyableunderscore. The \tentt font makes a rather different underscore. –  egreg Sep 4 '14 at 12:27

With the standard plain TeX font definitions, an underscore is produced by putting a rule in the document. This can't be copy-pasted, as you've font. In LaTeX this problem can be avoided by switching to the 'T1' font encoding, where a _ is available. The same can be done in plain, but needs a bit more work. Assuming you want to avoid altering anything else in your document and that it's currently using standard Computer Modern at 10pt, I'd try something like

\font\underscorefont=ecrm1000
\def\_{{\underscorefont\char"5F}}
a\_b
\bye

-

The definition of \_ in plain is

\def\_{\leavevmode \kern.06em \vbox{\hrule width.3em}}


There is no underscore glyph in the default Computer Modern Roman -font, but instead you could use the glyph from the typewriter font instead, like:

\def\_{{\tt \char\_ }}
here's some\_ text
\bye
`

-