# Strategy for listings next to code comments

I'm looking for strategies to produce listings of code with comments on what's happening next to it. I've found other similar questions, but not quite what I'm looking for. See for example:

However, what I'm really looking to do is reproduce a result similar to the notes in my Finite Elements text by Thompson shown below:

Things that come to mind are creating minipages, or using a tabular format. I know brute force could be employed here, but I reckon there is a more elegant solution. Any pointers on where I can look would be greatly appreciated as my searches are all coming up with "almost there" results.

• There are other solutions listed here. I can think of problems if you want to adjust the listing-lines with those on the right hand (e.g., the last 2 lines right) – Arash Esbati May 18 '15 at 15:35

You could use the minipage environment coupled with the mdframed package. Of course, there's also the listings package for the code.

This example answer is tweaked for margins of 1.5cm on each. If you increase the margin (reducing the available space for the content) you should also fix the \textwidths of the minipages.

Since the minipage on the right is not verbatim, you'll need to manually add space between the text blocks so they match the other side. There are examples of how to do it in the code below.

## Code

\documentclass[a4paper]{article}
\usepackage[margin=1.5cm]{geometry}
\usepackage{listings,mdframed}
\usepackage{booktabs}

\lstset{basicstyle=\footnotesize\ttfamily,breaklines=true}

\begin{document}\footnotesize%
\begin{minipage}[t]{0.47\textwidth}%
\begin{mdframed}

% ----------------------
% BOUNDARY CONDITIONS
% ----------------------
B = 1.0E+06;
for I=1:NUMNP
if NPBC(I) == 1 | NPBC(I) == 3
I1 = 2*I-1;
SK(I1,1)=SK(I1,1)*B;
RHS(I1)=LHS(I1)*SK(I1,1);
end
if NPBC(I) == 2 | NPBC(I) == 3
I2=2*I;
SK(I2,1)=SK(I2,1)*B;
RHS(I2)=LHS(I2)*SK(I2,1),
end
end

% ----------------------
% CALL EQUATION SOLVER
% ----------------------
LHS = sGAUSS(SK,RHS,NUMEQ,IB);

% --------------------------
% Nodal values for w and dw/dx are now
% in LSH. Use this values to calculate
% shear and moment at center of element.
%
% First calculate shape functions
% and their derivatives. Ic is
% counter for number elements used
% --------------------------
\end{lstlisting}
\end{mdframed}
\end{minipage}%
\hspace{1mm}
\begin{minipage}[t]{0.45\textwidth}
\begin{mdframed}
\vspace{2mm}
Specify boundary conditions.\\

\begin{tabular}{ccccc}
NPBC & $w$ & $dw/dx$ & $V$ & $M$ \\ \midrule
0 & U & U & K & K \\
1 & K & U & U & K \\
2 & U & K & K & U \\
3 & K & K & U & U \\
\end{tabular}
\\[5mm]
where\\
K = known\\
U = unknown
\\[2cm]
Call equation solver for symmetric, banded storage.
\\[1cm]
Begin calculations of shear and bending moments at center of each element.
\end{mdframed}
\end{minipage}%
\hfill\null
\end{document}