[Tex/LaTex] Right aligned left side margin notes on same line as content

marginparmargins

I'm trying to write a command that I can use to set up right-aligned left margin notes easily, and not be worried about the flow of content. Basically I would like the margin note to be on the same line as the next block of text in the content. Here's what I have so far:

\documentclass{article}
\usepackage[utf8]{inputenc}

\DeclareRobustCommand{\mymarginpar}[1]{%
 \mbox{}\marginpar[\raggedleft#1]{\raggedright#1}}

\begin{document}

\reversemarginpar
\mymarginpar{\textit{Consider}}
\begin{verbatim}
a = 1/5  
while True: { 
    print(a) 
    a = (1+a) / 2 
} 
\end{verbatim}

\mymarginpar{\textit{Prints}}
\begin{verbatim}
1/5 
3/5 
4/5 
9/10 
\end{verbatim}

\end{document}

Which produces:

output

Whereas I would like:

desired output

(Assuming I aligned perfectly with my eye)
Thanks!

Best Answer

As egreg points out at control vertical space before and after verbatim environment?, the verbatim environment adds space at the top and bottom of the list, and he shows how to turn that off. In addition, because a new line is started, I also had to \vspace{-\baselineskip} to undo the new line. Finally, I added extra space between your two examples with a \bigskip.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{etoolbox}
\makeatletter
\preto{\@verbatim}{\topsep=0pt \partopsep=0pt }
\makeatother

\DeclareRobustCommand{\mymarginpar}[1]{%
 \mbox{}\marginpar[\raggedleft#1]{\raggedright#1}}

\begin{document}

\reversemarginpar
\mymarginpar{\textit{Consider}}
\vspace{-\baselineskip}
\begin{verbatim}
a = 1/5  
while True: { 
    print(a) 
    a = (1+a) / 2 
} 
\end{verbatim}

\bigskip
\mymarginpar{\textit{Prints}}
\vspace{-\baselineskip}
\begin{verbatim}
1/5 
3/5 
4/5 
9/10 
\end{verbatim}

\end{document}

enter image description here

If your verbatim lists don't have to break across page boundaries, here is another approach that stuffs the verbatim material into a verbbox, and then the box can be used just like any other LaTeX box. Because the box has the baseline at the bottom, one must shift the box downward by all of its height except for the height of a \strutbox, in order to make the top line of the verbatim align with the marginpar. I do the downward shift with the \belowbaseline macro of the stackengine package.

I don't show the output because it is, essentially, identical to the above.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{verbatimbox,stackengine}

\DeclareRobustCommand{\mymarginpar}[1]{%
 \noindent\mbox{}\marginpar[\raggedleft#1]{\raggedright#1}}

\begin{document}

\reversemarginpar
\mymarginpar{\textit{Consider}}
\begin{verbbox}[\strut]
a = 1/5  
while True: { 
    print(a) 
    a = (1+a) / 2 
} 
\end{verbbox}
\belowbaseline[-\ht\strutbox]{\theverbbox}

\bigskip
\mymarginpar{\textit{Prints}}
\begin{verbbox}[\strut]
1/5 
3/5 
4/5 
9/10 
\end{verbbox}
\belowbaseline[-\ht\strutbox]{\theverbbox}
\end{document}