22

I would like latex to break long text inside \texttt{} that does not contain any whitespaces. Currently the text just runs off the page.

The latex document is generated from a reStructureText document (I have to use reStructuredText). Therefore I prefer not to use these solutions:

  • replacing \texttt{} by \path{} or \url{} (unless someone could tell me how to have Docutils do that)
  • inserting \allowbreak{} / soft hyphens (feasable but it destroys the readability of the reStructuredText document)

Is there some global configuration in the latex document that would cause breaking of texttt strings? Is there some other good way to get a printable document that shows all the text?

Here a minimal example for my problem:

\documentclass[a4paper]{article}
\begin{document}
If an unrecoverable error occurs during the transformation, then a
\texttt{javax.xml.transform.TransformerException} is thrown.
\end{document}

When I try to create a pdf (using "pdflatex a.tex") then only "TranformerEx" is visible of "TranformerException".

Peter Grill
  • 223,288
Ferdinand
  • 223
  • 3
    Welcome to TeX.SX! Please help us to help you and add a minimal working example (MWE) that illustrates your problem. It will be much easier for us to reproduce your situation and find out what the issue is when we see compilable code, starting with \documentclass{...} and ending with \end{document}. – Henri Menke Dec 25 '14 at 14:30
  • 1
    Though the accepted answer of http://tex.stackexchange.com/questions/299/how-to-get-long-texttt-sections-to-break is not what you want (since it uses \path), you can find alternative answers there which might help you (especially the one by Stefan Kottwitz). – cryingshadow Dec 25 '14 at 15:18
  • 3
    @cryingshadow as you already had a solution posted, you might consider that, since the OP's concern lies with the body of the document, you might suggest, after loading the url package, the following \let\oldtexttt\texttt\let\texttt\path as a possible work around which can be made from the preamble. – A.Ellett Dec 25 '14 at 15:24
  • 1
  • 2
    @PeterGrill Is this really a question about hyphenation? I like the link you're pointing to, but it seems that for what the OP is asking a bit more needs to be done than to automate hyphenation. It would seem that taking the linked solution and showing how to adapt it to this situation could be helpful. – A.Ellett Dec 25 '14 at 17:17
  • 1
    @A.Ellett: Point taken. Have retracted close vote. – Peter Grill Dec 25 '14 at 17:36

4 Answers4

19

Stealing egreg's answer at How to emulate \url hyphenating without using the url package?, wherein he redefined \url, I start with that same redefinition to instead redefine \texttt instead of \url. In egreg's original incarnation, it allowed linebreaks at . and / characters.

But other breakpoint symbols can be added, for example, below I also make [ a breakpoint:

\documentclass[a4paper]{article}
\renewcommand{\texttt}[1]{%
  \begingroup
  \ttfamily
  \begingroup\lccode`~=`/\lowercase{\endgroup\def~}{/\discretionary{}{}{}}%
  \begingroup\lccode`~=`[\lowercase{\endgroup\def~}{[\discretionary{}{}{}}%
  \begingroup\lccode`~=`.\lowercase{\endgroup\def~}{.\discretionary{}{}{}}%
  \catcode`/=\active\catcode`[=\active\catcode`.=\active
  \scantokens{#1\noexpand}%
  \endgroup
}
\usepackage{lipsum}
\begin{document}
\lipsum[4]
If an unrecoverable error occurs during the transformation, then a
\texttt{javax.xml.transform.TransformerException} is thrown.

If an unrecoverable error occurs during the transformation, then a \texttt{$GLOBALS['TCA']['tt_address']['feInterface']['fe_admin_fieldList']} \end{document}

enter image description here

If you need to use this solution in section or other headings, or other places written to and read back from .aux files, you will need to replace \renewcommand with \DeclareRobustCommand - see this answer for more info: Combining Wrapping \texttt{} with Sections and TOC - Improper alphabetic constant


SUPPLEMENT

Lemdan asks (and Joey asked a long time ago) in a comment how to do this to make the underscore _ a breakpoint? Because the underscore is usually catcode 8, one has to absorb the argument to \texttt using instead the catcode of _ set to 12. Of course, this will prevent the use of subscripts inside of math inside of a \texttt, but that should not be too difficult to live with. This will also remove the need to escape underscores in \texttt.

\documentclass[a4paper]{article}

\catcode_=12 % \renewcommand{\texttt}[1]{% \begingroup \ttfamily \begingroup\lccode~=/\lowercase{\endgroup\def~}{/\discretionary{}{}{}}% \begingroup\lccode~=[\lowercase{\endgroup\def~}{[\discretionary{}{}{}}% \begingroup\lccode~=.\lowercase{\endgroup\def~}{.\discretionary{}{}{}}% \begingroup\lccode~=_\lowercase{\endgroup\def~}{_\discretionary{}{}{}}% \catcode/=\active\catcode[=\active\catcode.=\active\catcode_=\active \scantokens{#1\noexpand}% \endgroup } \catcode_=8 %

\usepackage{lipsum} \begin{document} \lipsum[4] If an unrecoverable error occurs during the transformation, then a \texttt{javax.xml.transform.TransformerException} is thrown.

If an unrecoverable error occurs during the transformation, then a \texttt{$GLOBALS_'TCA']['tt_address']['feInterface']['fe_admin_fieldList']} \end{document}

enter image description here

  • This completely baffles and amazes me. Seems @egreg didn't explain how or why this works.... do you or he care to elaborate? – A.Ellett Dec 26 '14 at 18:14
  • @A.Ellett It is the famous "lowercase trick", http://tex.stackexchange.com/questions/156759/the-lowercase-trick, but I would not do justice trying to explain it. – Steven B. Segletes Dec 26 '14 at 18:48
  • I have tried it out and it seems to work really well. Also thank you for the link. – Ferdinand Dec 27 '14 at 00:25
  • Is it possible to enable highlighting with this function? I posted a question on this topic as I couldn't re-discover this answer until now. – Cloud Jan 29 '19 at 17:47
  • @DevNull With \usepackage{soul,xcolor}, you can certainly do \texttt{\hl{\$GLOBALS['TCA']}['tt\_address']['feInterface']\hl{['fe\_admin\_fieldList']}} and have it autobreak and highlight at the same time. – Steven B. Segletes Jan 29 '19 at 18:03
  • @StevenB.Segletes Is it possible to modify the texttt definition above so all texttt{} calls have the highlighting enabled by default? Thank you. – Cloud Jan 29 '19 at 18:05
  • @DevNull First, you should link your question to this answer, since it is relevant. But as to your question, it is unclear what you mean by "enabled". Are you asking that the complete argument to \texttt always get highlighted? – Steven B. Segletes Jan 29 '19 at 18:08
  • 1
    This seems to work for "regular" characters, but how about breaking on underscores? Adding either _ or _ doesn't seem to work. – Joey Dumont Jan 30 '19 at 13:16
  • Hi! How would you go on about adding underscores as a character that allows line breaks? I tried adding both the lines \begingroup\lccode`~=`_\lowercase{\endgroup\def~}{_\discretionary{}{}{}}%` and \begingroup\lccode`~=`\_\lowercase{\endgroup\def~}{\_\discretionary{}{}{}}%, but to no avail – mivkov Apr 13 '20 at 00:25
  • 1
    @lemdan Please see the SUPPLEMENT in my edited answer. – Steven B. Segletes Apr 13 '20 at 00:40
  • 2
    @JoeyDumont Sorry it took so long, but I have addressed your question. – Steven B. Segletes Apr 13 '20 at 00:43
  • @StevenB.Segletes excellent, thank you for the extremely quick reply! May I suggest one minor change though: The line breaks are added for underscores _, but not for escaped underscores \_. Since both appear in the second to last line of your MWE, could you maybe mention that or remove the backslashes? It took me a minute to understand why your MWE worked, but mine that still contained backslashes didn't. – mivkov Apr 13 '20 at 00:59
  • 1
    @lemdan I have removed the backslashes and noted that \_ are no longer needed in \texttt...one can directly use underscores. – Steven B. Segletes Apr 13 '20 at 01:04
  • @StevenB.Segletes - this is a great solution, and works perfectly, except in sections/subsections etc. when using a TOC, see my question below with MWE - any thoughts?

    https://tex.stackexchange.com/questions/579789/combining-wrapping-texttt-with-sections-and-toc-improper-alphabetic-constan

    – Charles Angus Jan 21 '21 at 04:56
  • Using this solution in section headings is solved here: https://tex.stackexchange.com/questions/579789/combining-wrapping-texttt-with-sections-and-toc-improper-alphabetic-constan – Charles Angus Jan 22 '21 at 22:36
  • @CharlesAngus Yes, thank you. I upvoted it the other day :^) – Steven B. Segletes Jan 23 '21 at 00:21
6

I'm not sure how much you're willing to do from the preamble, but here's a suggestion:

\documentclass{article}

\begingroup
  \catcode`\.=\active
  \gdef.{\normalperiod\allowbreak}%
\endgroup

\newcommand\aepath[1]{%%
  \bgroup 
    \let\normalperiod=.%%
    \catcode`\.=\active
    \everyeof{\noexpand}%%
    \endlinechar=-1%%
    \ttfamily\scantokens{#1}%%
  \egroup}

\let\oldtexttt\texttt
\let\texttt\aepath

\begin{document}

If an unrecoverable error occurs during the transformation, then a
\texttt{javax.xml.transform.TransformerException} is thrown.

\end{document}

From your MWE, I assumed that you want your code to be breakable at points where a . occurs. Assuming that all situations where you might run into longish text involves such . separated names and that you do not need \texttt for any other purposes in your document, this might be a solution for you.

In case you might be concerned that another package might desire . to be active but defined differently, you could take the following approach:

\documentclass{article}

\begingroup
  \catcode`\.=\active
  \gdef\redefineperiod{\def.{\normalperiod\allowbreak}}%%
\endgroup

\newcommand\aepath[1]{%%
  \bgroup 
    \let\normalperiod=.%%
    \catcode`\.=\active
    \redefineperiod
    \everyeof{\noexpand}%%
    \endlinechar=-1%%
    \ttfamily\scantokens{#1}%%
  \egroup}

\let\oldtexttt\texttt
\let\texttt\aepath

\begin{document}

If an unrecoverable error occurs during the transformation, then a
\texttt{javax.xml.transform.TransformerException} is thrown.  Followed
by more text which is just to fill to the ned of the line.

\end{document}

Naively (ie: this is what I initially thought I could do), you might try

\documentclass{article}

\newcommand\aepath[1]{%%
  \bgroup 
    \let\normalperiod=.%%
    \catcode`\.=\active
    \def.{\normalperiod\allowbreak}%%
    \everyeof{\noexpand}%%
    \endlinechar=-1%%
    \ttfamily\scantokens{#1}%%
  \egroup}

\let\oldtexttt\texttt
\let\texttt\aepath

\begin{document}

If an unrecoverable error occurs during the transformation, then a
\texttt{javax.xml.transform.TransformerException} is thrown.  Followed
by more text which is just to fill to the ned of the line.

\end{document}

But this will fail because the period following \def has already been tokenized an is not active. So, LaTeX will throw an error about a missing control sequence.

UPDATE

If you're not particularly concerned about where the breaks occur then you can use something like:

\documentclass{article}

\makeatletter
\newcommand\aepath[1]{%%
  \bgroup
    \ttfamily
    \ae@path#1\relax\@nil
  \egroup}
\def\ae@path#1#2\@nil{%%
  \def\ae@continue{}%%
  \detokenize{#1}\unskip\penalty\z@  
  \ifx\relax#2%%
  \else 
    \def\ae@continue{\ae@path#2\@nil}%%
  \fi
  \ae@continue}
\makeatother

\let\texttt\aepath

\begin{document}

If an unrecoverable error occurs during the transformation, then a
\texttt{javax.xml.transform.TransformerException} is thrown.

\end{document}

though this seems a bit suboptimal to me. I think it would be better to decide where breakpoints should be and follow the example with . to make those characters (such as /, -, etc) into active characters within the context of the command and smuggle in the penalty to allow a break following them.

egreg
  • 1,121,712
A.Ellett
  • 50,533
  • 1
    This is very helpful. It resolves 90% of my problems. It still fails for example at $GLOBALS['TCA']['tt_address']['feInterface']['fe_admin_fieldList'] or chains separated by -> or file paths separated by /. To me it is much more important that no text is hidden than where exactly it is broken. – Ferdinand Dec 25 '14 at 17:36
  • 1
    @Ferdinand Then I think loading url package and going with my suggestion in the comments above about \let\texttt\path in the preamble might work best for you. – A.Ellett Dec 25 '14 at 17:56
6

Following from Steven's answer, in my document I was using \texttt in Figures to show paths and urls but also I was using \texttt in my text to highlight small pieces of code.

While the code Steven's provided works with my figures it still overflows the margins when writing \texttt commands for normal text that doesn't use symbols. Like the below image shows, \texttt works just fine for figures but for normal text does not work well.

enter image description here

To fix this, I have borrowed the code for \justify from this tex.se post and just added that to existing code.

\newcommand*\justify{%
  \fontdimen2\font=0.4em% interword space
  \fontdimen3\font=0.2em% interword stretch
  \fontdimen4\font=0.1em% interword shrink
  \fontdimen7\font=0.1em% extra space
  \hyphenchar\font=`\-% allowing hyphenation
}

\renewcommand{\texttt}[1]{%
  \begingroup
  \ttfamily
  \begingroup\lccode`~=`/\lowercase{\endgroup\def~}{/\discretionary{}{}{}}%
  \begingroup\lccode`~=`[\lowercase{\endgroup\def~}{[\discretionary{}{}{}}%
  \begingroup\lccode`~=`.\lowercase{\endgroup\def~}{.\discretionary{}{}{}}%
  \catcode`/=\active\catcode`[=\active\catcode`.=\active
  \justify\scantokens{#1\noexpand}%
  \endgroup
}

This produces a much better output, and works for my case where I am using typewriter in different places.

enter image description here

px06
  • 161
  • 1
  • 3
  • 1
    Mmmhh… In normal text, you don’t want periods and slashes to behave as discretionary breaks. Allowing (ordinary) hyphenation is good in normal text, @egreg’s solution is good for filenames, but these two approaches should not be mixed. – GuM Apr 25 '18 at 01:44
  • 1
    See also here and here for some related questions. – ShreevatsaR Apr 25 '18 at 02:06
3

This is a late reply, but I posted a question with an answer here, here it is again, verbatim:

Use \seqsplit.

\documentclass[9pt,oneside]{amsart}

\usepackage{seqsplit}

\begin{document}

Filler text. Filler text. Filler text. Filler text. \seqsplit{0xcf416c536ec1a19ed1fb89e4ec7ffb3cf73aa413b3aa9b77d60e4fd81a4296ba}

\end{document}

Using seqsplit to split long text.

James Ray
  • 261
  • 2
    seqsplit doesn't provide a font like \texttt – bmv Jan 26 '18 at 14:52
  • 2
    @bmv It should be noted that \seqsplit does the job if it is wrapped in \texttt: \texttt{\seqsplit{javax.xml.transform.TransformerException}} will work and display as expected. – Siphalor Dec 04 '20 at 22:25
  • 1
    This is the best answer by far and should be selected as the answer for this question. I had to scroll to the bottom to find it... – Mateus Felipe Mar 05 '21 at 19:01