如果我在\texttt
块内有长单词,在我写变量名的情况下,有时自动换行不太有效,导致行稍微太长。
\documentclass{report}
\begin{document}
Most of the time, LaTeX line-wrapping works fine. However, sometimes when I'm writing about code with lots of \texttt{long\_monospace\_variables}, \texttt{the\_line\_wrapping} doesn't quite get the position correct resulting in slightly-too-long lines.
\end{document}
答案1
根据您希望如何中断变量,您可以定义一个允许按照某些规则中断的宏。这里我只允许在之后中断_
。除此之外,您还可以使用更具语义的命令,您可以灵活地重新定义它。
\documentclass{report}
\newcommand*\ttvar[1]{\texttt{\expandafter\dottvar\detokenize{#1}\relax}}
\newcommand*\dottvar[1]{\ifx\relax#1\else
\expandafter\ifx\string_#1\string_\allowbreak\else#1\fi
\expandafter\dottvar\fi}
\begin{document}
Most of the time, \LaTeX{} line-wrapping works fine. However, sometimes when
I'm writing about code with lots of \ttvar{long_monospace_variables},
\ttvar{the_line_wrapping} doesn't quite get the position correct resulting in
slightly-too-long lines.
\end{document}
答案2
根据这个问题的答案
看来,最好的办法就是将有问题的段落包装在sloppypar
环境中。
\documentclass{report}
\begin{document}
\begin{sloppypar}
Most of the time, LaTeX line-wrapping works fine. However, sometimes when I'm writing about code with lots of \texttt{long\_monospace\_variables}, \texttt{the\_line\_wrapping} doesn't quite get the position correct resulting in slightly-too-long lines.
\end{sloppypar}
\end{document}
使用\sloppy
命令对整个文档有类似的效果,但这似乎有点危险,因为它可能会破坏其他地方的格式。
答案3
使用包很容易做到这一点url
。我定义了一个\longvar
执行此工作的命令:
\documentclass{report}
\usepackage{url}
\newcommand\longvar[1]{\mathchardef\UrlBreakPenalty=100
\mathchardef\UrlBigBreakPenalty=100\url{#1}}
\begin{document}
Most of the time, LaTeX line-wrapping works fine. However, sometimes when I'm writing about code with lots and lots of \longvar{very_long_monospace_variables}, \texttt{the\_line\_wrapping} doesn't quite get the position correct resulting in slightly-too-long lines.
\end{document}
答案4
我遇到了同样的问题,有人建议我重新措辞该行,以便 stexttt
不会出现在同一行上。
有另一种解决方法也就是……
\emergencystretch 5em%
…但需要注意的是,5 em 已经非常大了。这是用来对齐文本的额外拉伸,以使其适合,因此基本上,在紧急情况下,行上单词之间的空白可以更大。
但是,如果太大,看起来就不好,因此使用较小的值并手动重新措辞以使其适合是可行的方法。(有点遗憾在 2019 年必须这样做,但我承认我也不知道如何以编程方式做到这一点。)为简单情况部署一个小型紧急拉伸,然后校对文档。