[Tex/LaTex] Formatting the Listing


The listing I have in my paper is Java Code. When it is displayed through TeX I lose some of the formatting that I did inside my .java files. For example, all of my comments in my code were lined up, but now after incorporating the Java code in TeX the comments are no longer lined up. Here is a visual of this dilemna:

enter image description here

Notice how all the comments are lined up except the first few at the top. Clearly there is room to the right for all of the comments to be shifted.

Here is my TeX code for the listing:


\lstset{language=Java, basicstyle=\tiny\ttfamily,
    numbersep=5pt,      % Abstand der Nummern zum Text
  1. Are there ways to edit my code inside TeX manually?
  2. How can I get page-breaks at certain points in the code? For example, if I wanted to see the for-loop that is at the bottom of the page in the picture what would I do?
  3. Please give all related suggestions to formatting code inside TeX.

Best Answer

If your comments are aligned in the source code, but not in a lstlisting environment, the reason usually is that in the source code there are TABs and spaces and that the TAB width of your source code editor is not in line with the one used by listings. You can change the latter with the tabsize=<number> option.

Nevertheless it is also possible to automatically align all comments. In the following, I overwrite the // delimiter with morecomment to "format" the comment with a \lstCom[<indent length>] command. The \lstCom command uses the tabto package to typeset all comments a fixed position from the left, resulting in perfectly alligned comments no matter what the source code looks like:






\lstset{ morecomment=**[l][{\lstCom[10cm]}]{//} }
public class HelloWorld { // We may have  many classes
  public static void main(String[] args) { // but only one main() method!
    System.out.println("Hello, World");
  } // here we terminate
} // end of the world


enter image description here

You have to play a bit around with the parameter given to \lstCom in the morecomment= line to get a suitable indentation. If a source line is larger than the indent, the comment will be inserted as an extra line. However, comments itself are not broken across lines if they exceed the available space. This should be possible, but would require some extra work.

Related Question