I'm need to annotate source code line by line using the listings package. Here's an example of what I'm looking for (made in MS Word): Example 1

Example 2

These particular examples display price of executing each line (left column) and how many times it is being called (right column).

Here's what I got going on so far (nothing done on annotations, as I'm not sure where to even start):






\begin{lstlisting}[language=c++,caption=Insertion sort realizacija masyve]
std::vector<int> insertion_sort_array::sort(const std::vector<int> &in) {
    std::vector<int> res(in);

    for (std::vector<int>::size_type i = 1; i < res.size(); i++) {
        for (std::size_t j = i; j > 0 && res[j - 1] > res[j]; j--) {
            int tmp = res[j - 1];
            res[j - 1] = res[j];
            res[j] = tmp;

    return res;
  • 3
    In addition to the screenshot of the code listing, please post the LaTeX code that gives rise to the screenshot. Also, please indicate which document class you employ and which packages you load. – Mico May 6 '18 at 15:03
  • Thanks for the suggestion, I made the changes you requested but I'm afraid they're not going to be of much help. – PoVa May 8 '18 at 16:13
  • 3
    Maybe one can use a three-column table and imitate the look of a listing?! – Dr. Manuel Kuehner May 8 '18 at 16:21
  • 4
    Sounds like a job for tikzmark. See tex.stackexchange.com/q/86309/86 for how tikzmark and listings integrate. – Loop Space May 13 '18 at 16:58

This follows up on the linked answer for tikzmark and listings. In your example's preamble, add

 \node at ( {pic cs:line-texcode-#1-end} -| {current page marginpar area.east}) [left] {#2};
 \node at ( {pic cs:line-texcode-#1-end} -| {current page marginpar area.east}) [right] {#3};
% usage: \annot{line-number}{left remark}{right remark}

Then after the listing environment:

\begin{tikzpicture}[remember picture,overlay]
 % draw the vertical line
 \draw ( {pic cs:line-texcode-1-start} -| {current page marginpar area.east})
  -- ( {pic cs:line-texcode-13-end} -| {current page marginpar area.east});
 \annot{7}{$c_3$}{$\sum_{i=1}^{\mathrm{res.length}}\sum_{j=0}^i 1$}

Resulting in:

screen shot of output

I'm not entirely satisfied with the spacing, but I don't know enough about geometry, listings, and tikz.

  • 1
    It's a good start for a complete answer. – gvgramazio May 18 '18 at 8:33
  • Instead of left and right you may work with anchors and in addition use xshift but I also think the answer is quite nice. (+1) – user121799 May 18 '18 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.