As a non-web programmer, almost everything that has to do with CSS is beyond me. For some reason, I find CSS to be one of the most difficult things I ever saw.
I’m not confortable working with styles on this blog either. It used to take me about 30 minutes just to put some color in my code and to format it so that it would look right. I think there’s a way to do this from the plugins somehow, but I’m afraid that if I start to change the code, I’d do more harm than good.
So, I started to search for an alternative solution…
… and this is how I stumbled upon pygments. For me, this is the greatest python library I’ve ever used. The capacity to color almost any type of syntax is amazing, and the lexers it provides are great. I’ve even wrote a java source indenter based on the java lexer pygments provides ( I’ll talk about this in another post ).
You know the old saying, Two hours of debugging can save 10 minutes of reading? Unfortunately for me, I kind of keep living by this quote. Coding and reading documentation provided me with a very nasty habit: skimming. So, after skimming through the documentation, I found a sample code that made use of pygments.
I ran a script’s source through that code, and it outputted html. The only downside ( at least for me ) was that in order for it to work, I would have had to use a CSS file. Being the CSS guru that I am, that solution was unacceptable to me. I needed to use internal styles. One of the steps I took to fix that, was to write a script that would color python files, that made use of the python lexer. I had no problem with the script, but I would have had to write scripts for each type of programming language I wanted to use. Not a difficult task, but a time consuming one.
So, after reading the documentation again ( while not skimming ), I found that by setting the noclasses attribute to True, I would get the output I want. Here’s the code I’m using:
import pygments import pygments.lexers from pygments.formatters import HtmlFormatter import sys try: file = sys.argv except: sys.exit("you must supply a source file") content = open(file).read() first_line = content.splitlines() lexer = pygments.lexers.guess_lexer_for_filename(file,first_line) if not lexer is None: formatter = HtmlFormatter() formatter.noclasses = True print pygments.highlight(content,lexer,formatter) else: print content sys.exit("could not provide highlighting for this type of source file")
You can use this code for almost any type of source file you may have ( as long as pygments has a lexer for it ). The way it works is that pygments will try to guess what lexer to use with your source file. It will try to do that based on the filename you provide it, but, it is my believe that by supplying another argument ( as the first line of your code ) you can help pygments a lot more in deciding what lexer to use.
pygments is a great library, one that I like very much. I warmly recommend it!Advertisements