First Issue

I'm using the listings package to present some algorithms using pseudocode. The problem is that sometimes the lines of my pseudocode are too "long" and listings breaks them in 2 lines. For example, you can see the following screenshots:

enter image description here


enter image description here

in which in the first case the line is broken into 3 other lines while in the second example the ) is moved to the next line.

Is there any way to fix that? E.g. by making a specific line inside listing have smaller letters?

Second Issue

Also I use \lstinline{} for keywords that appear in the pseudocode inside my document. The problem is that sometimes it doesn't work "fine" as can be seen below:

enter image description here

counter in the document is inside a \lstinline{} snippet and the . is after it but the created document moves the . to the next line which isn't that nice (in appearance). Any ideas how to solve it?


Package listings uses in its default setting a fixed width for each letter. The width is quite large, because letter such as M must fit in. For source code listings the requirements for the vertical alignment are not very high. Thus a flexible columns layout often looks much better. See 2.10 Fixed and flexible columns of the documentation. Flexible settings use a column width of 0.4em instead of 0.6em for setting flexible.

Source code also contains lots of words. Setting the words in a font with variable glyph widths improve the look of the words. Even for typewriter fonts there are variable width fonts. For example, the Latin Modern font family (successor of Computer Modern) contains such a variable typewriter font, see the examples below. The line length usually shrinks, because letters with smaller widths (e.g. i) need less space as in a font with equal width for all glyphs.

The following shows an example with non-variable/variable typewriter font and the three settings for the columns. It also shows the problematic alignment cases for the flexible column layouts.


% use variable width typewriter font

      language  = {[LaTeX]TeX},
      literate  = {TeX}{\TeX}3
      moretexcs = {NeedsTeXFormat,lstset,lstinputlisting},
      columns   = {#1},
  \renewcommand*{\ttdefault}{lmtt}% not variable
  \renewcommand*{\ttdefault}{lmvtt}% variable

The following images contains the source code listings in the following settings

fixed/non-variable        fixed/variable
flexible/non-variable     flexible/variable
fullflexible/non-variable fullflexible/variable


Another possibilty is the use of a smaller font size for the listings to reduce the line width.

| improve this answer | |

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