How to display line numbers with pygmentize

I often use the command pygmentize to show color source files with code formatting. This works like a charm. I now also want to show line numbers like cat -n does.

I read around and found some suggestions like adding -O linenos=1 or -O linenos=True. None of this seems to work though.

Does anybody have any idea how I can show line numbers when viewing source files on the command line with pygments? All tips are welcome!

Asked By: kramer65


Have you tried piping the output to nl --body-numbering=a? As for most shell tools, you can find more information in man nl.

Answered By: l0b0

You can add line numbers using perl like this:

pygmentize | perl -e 'print ++$i." $_" for <>'

Update (to alias the previous command):

To create an alias, just define the following bash function somewhere in your ~/.bashrc:

pyg() {
pygmentize $1 | perl -e 'print ++$i." $_" for <>'

Open a new terminal and call the command with pyg

Answered By: Sylvain Pineau

Using cat with piping:

pygmentize | cat -n

Sylvain’s answer is somehow better since it doesn’t generates additional cat’s trailing whitespaces at the beginning of each line. But at some point you may not have pearl installed 🙂

Try also:

pygmentize -g | cat -n | sed "s/^[ t]*//"

It gives you nice space between line numbers and the code.

Answered By: cereberus
pygmentize < hello.go | awk '{print i++ + 1 "   " $0}'

This works for me. Note +1 is there because you want first line to be labelled 1 not 0.

Answered By: Varun Narayanan

I added some formatting tweaks to the accepted answer to suit my needs

ccatn() {
        pygmentize -g -O full,style=monokai $1 | perl -e 'for(<>){print sprintf("%3s %s", ++$i,$_);}'

use it like
ccatn helloworld.go

Answered By: puppawubba

For me this here worked without needing any other command:

pygmentize -g -O full,style=monokai,linenos=1

I still put the command in my ~/.bash_aliases as an "alias":

alias ccat='pygmentize -g -O full,style=monokay,lineos=1'

Now I can use it as a ccat command 🙂

I hope it helps.

Answered By: Breno Cruz

As an alternative to Varun Narayanan’s awk answer, and with a pygments old version whose Terminal256Formatter doesn’t support the linenos option:

pygmentize | awk '{printf("%5d │ %sn",++i,$0)}'

This one has a better line number padding and uses the same lineno/code separator as the bat formatter (Box Drawings Light Vertical = = u2502 = &boxv;).

Answered By: franferrax