5

I was looking for a way to enable hyphenation within \texttt. I found this answer and it seemed perfect: simple and useful to many people.

I chose to enable hyphenation globally in \texttt and as suggested there, I added the following line:

\DeclareFontFamily{\encodingdefault}{\ttdefault}{\hyphenchar\font=`\-}

Unfortunately, it did not work and had an undesired side-effect: the typewriter font was no longer used inside \texttt and the following error appeared in the console output:

LaTeX Font Warning: Some font shapes were not available, defaults substituted.

This error pointed me right on track: I always use the T1 encoding and lmodern fonts in my LaTeX documents:

\usepackage[T1]{fontenc}
\usepackage{lmodern}

and as soon as I commented out those lines, everything worked fine.

Is there a way to adapt the original answer to this case as well? I'd have added a comment to that post, but unfortunately I still haven't sufficient reputation to do that.

Thank you very much.

2 Answers2

5

The problem can be solved in a different way, which requires loading the font definition file manually and changing the hyphenchar before any font of that family is used:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}

\makeatletter
\input{t1lmtt.fd}
\@namedef{T1+lmtt}{}
\makeatother

\begin{document}
\parbox{0pt}{\ttfamily
  \hspace{0pt}hyphenation in typewriter type 
}
\end{document}

enter image description here

One of the duties of \DeclareFontFamily{enc}{fam}{code} is to define \enc+fam to expand to code. The control sequence \enc+fam is not directly usable because of +, so \@namedef (which is \expandafter\def\csname#1\endcsname) can be used. Since the normal declaration is

\DeclareFontFamily{T1}{lmtt}{\hyphenchar=-1 }

which does

\@namedef{T1+lmtt}{\hyphenchar=-1 }

we counteract it by doing

\@namedef{T1+lmtt}{}

The code is used as soon as a font shape relative to font family is selected and permanently attached to the chosen font. So it's important that the redefinition happens before any font is actually selected.

egreg
  • 1,121,712
4

Franks answer is missing an important point: When you declare a font family in your preamble latex no longer tries to input the .fd-file and so all other font declarations are lost. You can input them before doing the change:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{lipsum}
\makeatletter
\input{t1lmtt.fd}
\makeatother
\DeclareFontFamily{\encodingdefault}{\ttdefault}{\hyphenchar\font=`\-}


\begin{document}
\ttfamily abc \lipsum
\end{document}

Or alternatively:

\ttfamily
\hyphenchar\font=`\-
\DeclareFontFamily{\encodingdefault}{\ttdefault}{\hyphenchar\font=`\-}
Ulrike Fischer
  • 327,261