# string of non-breaking spaces spilling into margin

I have a string of expressions that should not be split across lines, so I have placed non-breaking spaces between them. However, they spill over into the margin. How do I fix this? Here is my MWE:

\documentclass{book}
\usepackage{lipsum}
\begin{document}
This text shows that non-breaking spaces are not working properly: a:a~b:b~c:d~e:e~f:f~g:h''. \lipsum
\end{document}


If the expression is too long, I want it to be moved to start the next line. I have tried placing \allowbreak before the expression, but it does not change the result.

• ~ never breaks, as far as I know, even with \allowbreak – user31729 Jul 24 '15 at 9:07
• Not sure I follow your question. Either you want it to break or you do not.... Do you want to force a linebreak before such a long construction if and only if it will not fit on the line. That may be possible. – Aubrey Blumsohn Jul 24 '15 at 9:18
• the only approach i can see here is to end the first line short. you can force the paragraph to re-flow by wrapping it in the environment \begin{sloppypar) ... \end{sloppypar}. it won't look so good though. – barbara beeton Jul 24 '15 at 9:24
• This may be useful to create a macro that automatically breaks if word will not fit. tex.stackexchange.com/questions/62333/… – Aubrey Blumsohn Jul 24 '15 at 9:25

This steals directly from David's answer at Push long words in a new line

\documentclass{book}
\usepackage{lipsum}
\newcommand\lword[1]{\leavevmode\nobreak\hskip0pt plus\linewidth\penalty50\hskip0pt plus-\linewidth\nobreak\textbf{#1}}
\begin{document}
This text shows that non-breaking spaces are not working properly: \lword{a:a~b:b~c:d~e:e~f:f~g:h''.} This is some lipsum

This shows that non-breaking spaces are not working properly: \lword{a:a~b:b~c:d~e:e~f:f~g:h''.} This is some lipsum

This that non-breaking spaces are not working properly: \lword{a:a~b:b~c:d~e:e~f:f~g:h''.} This is some lipsum

This spaces are not working properly: \lword{a:a~b:b~c:d~e:e~f:f~g:h''.} This is some lipsum

This are not working properly: \lword{a:a~b:b~c:d~e:e~f:f~g:h''.} This is some lipsum
\end{document}


• protip: change \textbf{#1} to #1 if you don't want it to be bolded in the output. ;-) – reynoldsnlp Nov 5 '15 at 14:11