读了一些资料后,我认为 listings 包可以处理这个问题,但我没有成功。我有一些较长的代码字符串需要包含在文档的段落中,我希望这些代码字符串换行,或者根据需要简单地留下空格并换行。目前,我只能说服 listings 包在代码字符串中有空格时换行。
\documentclass{article}
\usepackage{listings}
\lstset{breaklines=true}
\begin{document}
\verb|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
\lstinline|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
\lstinline|lllllllllllllllllllllloooooooooooooooooonnnn nnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnn nnnnnnnngggggggg$$$$$$$|
\end{document}
答案1
您可以遍历动词,并在每个字符后添加一个断点。
\documentclass{article}
\makeatletter
\let\old@sverb\@sverb
\def\@sverb#1{\old@sverb{#1}\zz}
\def\zz#1{#1\ifx\@undefined#1\else\penalty\z@\expandafter\zz\fi}
\makeatother
\begin{document}
\raggedright
\verb|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
\verb|`?<<---|
\verb|`?<<---ooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
\end{document}
答案2
解决方案如下xparse
:
\documentclass[draft]{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\splitverb}{v}
{
\group_begin:
\use:c { verbatim@font }
\seq_set_split:Nnn \l_tmpa_seq {} {#1}
\seq_use:Nn \l_tmpa_seq { \hspace{0pt plus .2em}\penalty\c_zero\hspace{0pt plus -.2em} }
\group_end:
}
\ExplSyntaxOff
\begin{document}
Some text \splitverb|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
Let's see that ligatures are not formed: \splitverb|`?<<---|
\end{document}
\hspace
和的组合\penalty
可确保您不会得到过满的箱子。
您可能想添加一些柔韧性较小的胶水。
\documentclass[draft]{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\splitverb}{v}
{
\group_begin:
\use:c { verbatim@font }
\seq_set_split:Nnn \l_tmpa_seq {} {#1}
\seq_use:Nn \l_tmpa_seq { \hspace{0pt plus 0.1pt} }
\group_end:
}
\ExplSyntaxOff
\begin{document}
Some text \splitverb|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
Let's see that ligatures are not formed: \splitverb|`?<<---|
\end{document}
答案3
您可以创建一个宏,使用以下命令自行排版每个字符\string
:
\documentclass{article}
\makeatletter
\def\mycode|#1#2|{%
\texttt{\string#1}\penalty\z@%
\ifx&%
\else%
\mycode|#2|%
\fi%
}
\makeatother
\begin{document}
\mycode|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
\end{document}
但大卫卡莱尔的回答可能更好。