Lstlisting and indentation lines

I am using lstlisting and I try to add vertical lines on identation, like you can do using the package algorithm, but I do not find a way to do it.

Is it actually possible? Because I did not find any post about that.

• Welcome to TeX.SX. If you post a question, which is not a fundamental question like "what is better: bibtex or biber", then add a MWE. What is also very helpful, is a picture of the desired output. – MaestroGlanz Feb 17 '17 at 16:12
• Ok ! :) I meant something like this upload.wikimedia.org/wikipedia/commons/thumb/6/6d/… Their is a line between the "while" and the "end" and I wish I could do the same using lstlisting: drawing a vertical line when there is identations. – Viridya Feb 20 '17 at 11:24

It is possible to do this, but I haven't found any way of doing it automatically.

Here's an example listing from a paper I'm working on:

What I did to achieve this is define a custom command to add in the vertical ruler and then manually insert it in the code after every indentation. This is a lot of work, but it does achieve the desired result.

The code inside the listing is formatted like this:

new Thread(new Runnable() {
?\indentrule?@Override
?\indentrule?public void run() {
?\indentrule?   ?\indentrule?System.out.println("Hello world!");
?\indentrule?}
}).start();


I defined the indentrule command with a simple vrule and 2pt of horizontal spacing after it, to move the ruler just a tiny distance away from the actual code. Here I also use a customcolor for the rulers so they don't cause too much noise in the listing. This results in the following command:

\newcommand{\indentrule}{\color{code_indent}\vrule\hspace{2pt}}


The color is defined using the color package as:

\definecolor{code_indent}{HTML}{CCCCCC}


When defining your listing, you need to make sure you have an escape character set up, which allows you to use latex commands in the listing. In this case i used the question mark character, but any valid escape character can be used to replace it. To set up the escape character, you should use the escapechar parameter of the lstlisting environment. Such as in this case: escapechar=?.