# [Tex/LaTex] Automatic linebreak on specific character

hyphenationline-breaking

Based on my old question Push long words in a new line, I search for a possibility to allow linebreak on specific character.

For example in my case I want to break on "_" (underscore).

\documentclass{scrartcl}

\begin{document}
\section{Test}
Finally there is a simple solution using \textsc{\textbf{XMLResource.OPTION\_RECORD\_UNKNOWN\_FEATURE}} option. And the
text must go on \ldots.
\par
\end{document}


I suggest you use the \discretionary command for hyphens.

\documentclass{scrartcl}

\let\underscore\_
\renewcommand{\_}{\discretionary{\underscore}{}{\underscore}}

\begin{document}
\section{Test}
Finally there is a simple solution using
\textsc{\textbf{XMLResource.OPTION\_RECORD\_UNKNOWN\_FEATURE}} option. And the
text must go on \ldots.
\par
\end{document}


Use \discretionary{}{\underscore}{\underscore} instead if you wish the underscore to be placed on the next line, or \discretionary{\underscore}{\underscore}{\underscore} to get the character both before and after the line break.

\discretionary is the hook in to TeX's hyphenation scheme. In some languages, including German, words can change spelling when they are hyphenated, and this command was introduced by Knuth to help cover such situations. \discretionary{a}{b}{c} prints c if there is no linebreak, otherwise it prints a before the linebreak and b after.

If you want to limit this to one particular type of phrase then I suggest you use

\newcommand{\resource}[1]{\textbf{\let\underscore\_
\renewcommand{\_}{\discretionary{\underscore}{}{\underscore}} #1}}


and write \resource{XMLResource.OPTION\_RECORD\_UNKNOWN\_FEATURE} in your text. (I have removed the \textsc from your example as it had no effect.)

If you wish to use it in one section of the document, then you can similarly define an environment which inserts these definitions at the start, e.g.

\newenvironment{underscoresplit}{\let\underscore\_
\renewcommand{\_}{\discretionary{\underscore}{}{\underscore}}}{}


used as

\begin{underscoresplit}
Finally there is a simple solution using
\textsc{\textbf{XMLResource.OPTION\_RECORD\_UNKNOWN\_FEATURE}} option. And the
text must go on \ldots.
\end{underscoresplit}