Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I often use the command pygmentize filename.py to show color source files with code formatting. This works like a charm. I now also want to show line numbers like cat -n filename.py 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!

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can add line numbers using perl like this:

pygmentize file.py | 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 file.py.

share|improve this answer
    
Awesome, that seems to work. Just one last question: would you know how to change this in an alias so that I can do something like this myalias thefile.py? –  kramer65 Jul 11 at 11:43
    
@kramer65: I've added a function to copy/paste in your .bashrc –  Sylvain Pineau Jul 11 at 12:04
    
Awesome! I didn't expect to be ever using perl, but this works like a charm! Thanks a million! –  kramer65 Jul 11 at 13:02

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

share|improve this answer
    
Thanks for the tip. That indeed gives some numbers. Unfortunately it doesn't count the empty lines, which causes the line numbers not to be correct with what is given in stacktraces of errors I get. Any other ideas? –  kramer65 Jul 10 at 10:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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