具有指定宽度的逐字环境(以字符为单位)

具有指定宽度的逐字环境(以字符为单位)

我想verbatim通过提供字符宽度来指定盒装环境的尺寸(例如以适合终端尺寸)。

fancyvrb这可能吗?最好使用解决方案。

答案1

由于正常verbatim环境不会以太大的宽度进行换行,因此最简单的解决方案是在逐字环境中插入手动换行符:

\documentclass[]{scrartcl}

\begin{document}
\begin{verbatim}
This is an
awful lot of verbatim text, just to check whether the verbatim
environment linebreaks or not if the total width of the text is to big (which it doesn't at all)
\end{verbatim}
\end{document}

第一个代码片段结果

另一种方法是使用经过修改的动词命令并将其放入小页面中(修改自这里

\documentclass[]{scrartcl}

\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

\setbox1\hbox{\verb|l|}
\newlength{\vcharwidth}
\setlength{\vcharwidth}{\wd1}

\begin{document}

\raggedright
\begin{minipage}[t]{38\vcharwidth}
    \verb|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
\end{minipage}

\verb|`?<<---|

\verb|`?<<---ooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|

\end{document}

第二段代码的结果

我不知道fancyvrb,所以我无法帮助你。

编辑:如果需要在逐字文本周围添加框架,则可以使用-package framed

\documentclass[]{scrartcl}

\usepackage{framed}

\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

\setbox1\hbox{\verb|l|}
\newlength{\vcharwidth}
\setlength{\vcharwidth}{\wd1}

\begin{document}

\raggedright
\begin{minipage}[t]{\dimexpr38\vcharwidth+2\FrameSep+1pt}%the width has to be adapted to include the framebox around the desired character count
\begin{framed}
    \verb|lllllllllllllllllllllloooooooooooooooooonnnnnnnnnnnnnggggggg$$$$$$$$$$$$$$$$llllllllllllloooooooooooooooonnnnnnnnnnnnnnnngggggggg$$$$$$$|
\end{framed}
\end{minipage}
\end{document}

答案2

您可以根据以下内容创建新环境BVerbatim

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{lipsum}

\newenvironment{FVerbatim}
 {\VerbatimEnvironment
  \begin{lrbox}{\FVerbatimbox}%
  \begin{BVerbatim}}
 {\end{BVerbatim}\end{lrbox}%
  \framebox[\FVerbatimwidth][l]{\usebox{\FVerbatimbox}}}

\newsavebox{\FVerbatimbox}
\newlength{\FVerbatimwidth}
\AtBeginDocument{%
  \sbox0{\ttfamily X}%
  \setlength{\FVerbatimwidth}{60\wd0}%
  \addtolength{\FVerbatimwidth}{2\fboxsep}% for framebox
}

\begin{document}

\lipsum[2]
\begin{center}
\begin{FVerbatim}
123456789012345678901234567890123456789012345678901234567890
\newenvironment{FVerbatim}
 {\VerbatimEnvironment
  \begin{lrbox}{\FVerbatimbox}%
  \begin{BVerbatim}}
 {\end{BVerbatim}\end{lrbox}%
  \makebox[\FVerbatimwidth][l]{\usebox{\FVerbatimbox}}}

\newsavebox{\FVerbatimbox}
\newlength{\FVerbatimwidth}
\AtBeginDocument{%
  \sbox0{\ttfamily X}%
  \setlength{\FVerbatimwidth}{60\wd0}%
  \addtolength{\FVerbatimwidth}{2\fboxsep}% for framebox
}
\end{FVerbatim}
\end{center}
\lipsum[3]

\end{document}

在此处输入图片描述

相关内容