我试图在一个algortihm2e
结构周围画一个框,如下所示:
我尝试使用该varwidth
包来获取具有内容自然宽度的盒子:
\documentclass{article}
\usepackage{algorithm2e}
\usepackage{varwidth}
\begin{document}
\fbox{\begin{varwidth}{10cm}
\If{condition}{
loop content
}
\end{varwidth}}
\end{document}
不幸的是,结果如下:
看起来当内部使用或构造varwidth
时会占用最大宽度。我怎样才能获得具有自然宽度的框?\If
\For
答案1
同时,我自己想出了一个办法:覆盖algorithm2e
绘制块的内部宏并varwidth
在那里使用环境。
以下是该选项的解决方案vlined
:
\documentclass{article}
\usepackage[vlined]{algorithm2e}
\usepackage{varwidth}
\makeatletter
\renewcommand{\algocf@Vline}[1]{% no vskip in between boxes but a strut to separate them,
\strut\par\nointerlineskip% then interblock space stay the same whatever is inside it
\algocf@push{\skiprule}% move to the right before the vertical rule
\vbox{\hbox{\vrule%
\begin{varwidth}{\hsize}%
\vbox{\algocf@push{\skiptext}%move the right after the rule
\hbox{%
\algocf@addskiptotal%
\begin{varwidth}{\hsize}%
#1% inside the block
\end{varwidth}%
}%
\Hlne}%
\end{varwidth}%
}\vskip\skiphlne}%
\algocf@pop{\skiprule}%\algocf@subskiptotal% restore indentation
\nointerlineskip}% no vskip after
\renewcommand{\algocf@Vsline}[1]{% no vskip in between boxes but a strut to separate them,
\strut\par\nointerlineskip% then interblock space stay the same whatever is inside it
\algocf@bblockcode%
\algocf@push{\skiprule}% move to the right before the vertical rule
\hbox{\vrule% the vertical rule
\begin{varwidth}{\hsize}%
\vbox{\algocf@push{\skiptext}%move the right after the rule
\hbox{\algocf@addskiptotal%
\begin{varwidth}{\hsize}%
#1% inside the block
\end{varwidth}%
}}%
\end{varwidth}%
}%
\algocf@pop{\skiprule}% restore indentation
\algocf@eblockcode%
}
\makeatother
\begin{document}
\fbox{\begin{varwidth}{\hsize}
\If{condition}{
loop content
a line longer than the loop header
}
\end{varwidth}}
\end{document}
对于块样式的其他选项\algocf@Noline
可能必须进行类似的调整(未经测试)。
答案2
这是一个使用\tikzmark
s 来定位顶部、底部和右侧(或多或少)的临时解决方案。
请注意,如果没有 minipage,algorithm2e 将使用边距外的空间。
\documentclass{article}
\usepackage{algorithm2e}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\begin{document}
\begin{minipage}{\textwidth}
\tikzmark{A}\If{condition\tikzmark{B}}{
loop content
}\tikzmark{C}
\end{minipage}%
\begin{tikzpicture}[overlay, remember picture]
%\draw[red] (pic cs:A) -- (pic cs:B) -- (pic cs:C);
\path (pic cs:B) node[right, inner sep=0pt] (BB) {\phantom{ \textbf{then}}};
\path (pic cs:C) ++(0,\baselineskip) coordinate (CC);
\draw (pic cs:A) ++(0, \ht\strutbox) rectangle (BB.east |- CC);
\end{tikzpicture}
\end{document}