You can use the tabbing
environment, together with a personal environment:
\documentclass[a4paper]{article}
\usepackage{amsmath}
\newenvironment{boxedcode}
{\setlength{\fboxsep}{1em}%
\begin{lrbox}{\boxedcodebox}
\begin{minipage}{\dimexpr\textwidth-2\fboxsep-2\fboxrule\relax}
\begin{tabbing}}
{\end{tabbing}
\end{minipage}
\end{lrbox}%
\fbox{\usebox{\boxedcodebox}}}
\newsavebox{\boxedcodebox}
\begin{document}
\begin{figure}
\centering
\begin{boxedcode}
Inputs: $s_{j}{k}$, \= $j=1,\dots,M-i$, $k=1,\dots,d$ as in \eqref{whatever}\\
\> and $h_1,\dots,h_M$ ($h_l=t_l-t_{l-1}$)\\[\baselineskip]
$A_\mathrm{prev}(k)\leftarrow 0$, $k=1,\dots,d$\\
for \= $j=1,\dots,M-i$\\
\> $B_\mathrm{next}\leftarrow 0$\\
\> for \= $k=1,\dots,d$\\
\> \> $A_\mathrm{next}(k)\leftarrow A_\mathrm{prev}(k)+s_j(k)*h_{i+j}$\\
\> \> $B_\mathrm{next}\leftarrow B_\mathrm{next}+A_\mathrm{next}(k)*A_\mathrm{next}(k)$\\
\> \> $A_\mathrm{prev}(k)\leftarrow A_\mathrm{next}(k)$\\
\> end\\
\> $m_j\leftarrow (B_\mathrm{next}-B_\mathrm{prev})/(2h_{i+j})$\\
\> $B_\mathrm{prev}\leftarrow B_\mathrm{next}$\\
end\\
return $m_1,\dots,m_{M-i}$
\end{boxedcode}
\caption{Calculation of discrete drift parameters}\label{algo:drift}
\end{figure}
\end{document}
As Martin Scharrer points out, the code for the environment can be simplified by loading the adjustbox
package:
\usepackage{adjustbox}
\newenvironment{boxedcode}
{\setlength{\fboxsep}{1em}%
\begin{adjustbox}{minipage=\textwidth-2\fboxsep-2\fboxrule,fbox}
\begin{tabbing}}
{\end{tabbing}
\end{adjustbox}}
This avoids the need to allocate a box bin.
Here is a version that allows page breaks (of course it shouldn't be set in a figure
environment):
\usepackage{mdframed}
\newenvironment{boxedcode}
{\setbox\boxedcodebox=\vbox\bgroup
\begin{tabbing}}
{\end{tabbing}\egroup
\begin{mdframed}[
leftmargin=\dimexpr(\textwidth-1em-\fboxrule-\wd\boxedcodebox)/2\relax,
rightmargin=\dimexpr(\textwidth-1em-\fboxrule-\wd\boxedcodebox)/2\relax,
innerleftmargin=1em,
innerrightmargin=1em,
innertopmargin=1em,
innerbottommargin=1em,
skipabove=\topsep,
]
\vskip-\baselineskip\unvbox\boxedcodebox
\end{mdframed}
}
\newsavebox{\boxedcodebox}
\newlength{\boxedcodewd}
The environment should be always preceded and followed by blank lines and not put inside a center
environment, because the centering is already taken care of by the set parameters.
If the class used is book
the keys leftmargin
and rightmargin
should be replaced by innermargin
and outermargin
.
Please, keep the inner padding space.