latexhyphenationtexttt

Preventing \texttt LaTeX tag from letting its content passing over the margin


In my report, I'm writing some class names or variable names inside of a paragraph, and I want these names to be rendered in a monospace font.

Example:

This is my class name: \texttt{baseAdminConfiguration}.

Sometimes when the single word inside of the \texttt tag is rendered at the end of a line, the word does not go to the next line, and there is no break in it neither: the end of the word passes over the margin.

How should I handle such a case?

Cheers.


Solution

  • This hasn’t got much to do with \texttt. The word is simply too long, and LaTeX doesn’t know how to hyphenate it. You can tell it how to do this manually, by declaring hyphenation rules:

    \hyphenation{base-Admin-Configuration}
    

    The \hyphenation command may take arbitrarily many words, separated by whitespace.

    Alternatively, if this doesn’t do the trick, you can introduce manual hypenation hints in the text:

    This is a long text that uses the word \texttt{base\-Admin\-Configuration} …
    

    Only the actual hyphenation will be displayed; unused so-called discretionary hyphens (\-) will not be displayed so you can freely sprinkle your text with them, if necessary.

    [Read more about hyphenation in LaTeX]

    To prevent LaTeX from overflowing lines in principle, the whole paragraph can be wrapped in a sloppypar environment (thanks to Will for pointing this out in the comments):

    \begin{sloppypar}
      Some text …
    \end{sloppypar}
    

    This manipulates the parameters of the line-breaking algorithm (in particular, \tolerance). The downside: this can lead to very ugly spacing. Alternatively, \tolerance and other internal parameters can be manipulated directly – the TeX FAQ shows how.