Hyphenation for words with underscore locally
Perhaps something like this would help, without using the underscore
package, which you would seem to prefer (not using it). It activates the hyphenability with \newuson
and restores the original definition of \_
with \newusoff
. Through this on/off mechanism, you can control the scope of the modifications.
Also, the "hyphenation" of the underscore is without the dash, which also seemed to be desired, if I understood the question properly.
In any case, to get the first word of a paragraph to hyphenate, a \hspace{0pt}
is required to start the paragraph.
\documentclass{article}
%\usepackage{underscore}
\textwidth0pt
\let\svus\_
\newcommand\newuson{\def\_{\svus\allowbreak\hspace{0pt}}}
\newcommand\newusoff{\let\_\svus}
\begin{document}
TESTSTRING\_TESTSTRING\_HYPHENATION
\newuson
\hspace{0pt}TESTSTRING\_TESTSTRING\_HYPHENATION
\newusoff
TESTSTRING\_TESTSTRING\_HYPHENATION
\end{document}
If you are keen to keep your long strings with underscore as the argument to a macro, it's easy:
\documentclass[10pt]{article}
\DeclareRobustCommand\Name[1]{{%
\let\_\hyphenationunderscore#1%
}}
\newcommand{\hyphenationunderscore}{%
\textunderscore\nobreak\hspace{0pt}%
}
\begin{document}
\pagestyle{empty}
\parbox{1pt}{
\hspace{0pt}%
\Name{TESTSTRING\_TESTSTRING\_HYPHENATION}
}
\end{document}
You could also redefine \_
globally:
\documentclass[10pt]{article}
\renewcommand{\_}{%
\textunderscore\nobreak\hspace{0pt}%
}
\begin{document}
\pagestyle{empty}
\parbox{1pt}{
\hspace{0pt}%
TESTSTRING\_TESTSTRING\_HYPHENATION
}
\end{document}
Alternatively, you can make _
active:
\documentclass[10pt]{article}
\newcommand{\hyphenationunderscore}{%
\textunderscore\nobreak\hspace{0pt}%
}
\catcode`_=\active
\protected\def_{\ifmmode\sb\else\hyphenationunderscore\fi}
\begin{document}
\pagestyle{empty}
\parbox{1pt}{
\hspace{0pt}%
TESTSTRING_TESTSTRING_HYPHENATION
}
\end{document}
Note that without \hspace{0pt}
you get no hyphenation in the \parbox
, because TeX doesn't hyphenate a word that's not preceded by glue.
If you want to break also after the underscore, change \nobreak
into \linebreak[0]
throughout. For instance, the second solution becomes
\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\renewcommand{\_}{%
\textunderscore\linebreak[0]\hspace{0pt}%
}
\begin{document}
\pagestyle{empty}
TESTSTRING\_TESTSTRING\_HYPHENATION
\parbox{1pt}{
\hspace{0pt}%
TESTSTRING\_TESTSTRING\_HYPHENATION
}
\end{document}
The output here also shows what happens with T1.