Syntax Highlightining in Python

Posted at 9:13 pm in rapache, ubuntu

Working on Rapache, it’s been a while I wanted to add syntax highlightining, but I didn’t dare too loose time on a “side feature” like that. Last night though, Jason came in chat, and pasted me the code to do that straight away. That was nice, I only needed to paste that code in the source and make little adjustments.

Some little glitches arose though, so I eventually had to work a little more on it. I just thought I’d share what I had to do with other people.

My problems:

  • I had to put together a language definition for Apache config files, since no one currently exists
  • I had to find out how to read if from a non system dir (ie. from my program data directory)

This is the Apache .lang file (needs more love, but that’s a start) ended up with.

Here’s the code:

import gtksourceview2

custom_langs_path = '/home/myuser/mydir/datafiles'
bufferS = gtksourceview2.Buffer()
manager = gtksourceview2.LanguageManager()
manager.set_search_path( [ custom_langs_path ] + manager.get_search_path() )
language = manager.get_language('apache')
bufferS.set_language(language)
bufferS.set_highlight_syntax(True)
sourceview = gtksourceview2.View(bufferS)
sourceview.set_show_line_numbers(True)
#TODO sniff gnome default monospace font
sourceview.modify_font(pango.FontDescription("monospace 10"))

This is how the final result looks like:

Everything looks nicer now ! :-)

 

Written by Stefano Forenza on July 21st, 2008

3 Responses to 'Syntax Highlightining in Python'

Subscribe to comments with RSS or TrackBack to 'Syntax Highlightining in Python'.

  1. Markus Majer | 22 Jul 08 at 5:32 pm

    It seems to be a nice tool, have to try it out if I do a new server installation with good old apache (using lighty most of the time right now)..

    Perhaps you want to have a look at a very good piece of python code, a module called pygments, which has highlightning support for really, really much programming languages and config files (it even does highlight Brainfuck *g*)..

    Trac uses it also, and of course it also have a highlightning for an Apache Conf..

  2. Markus Majer | 22 Jul 08 at 5:32 pm

    Oh, forgot the link *g*

    http://pygments.org/

  3. Stefano Forenza | 22 Jul 08 at 6:27 pm

    Thank you for your suggestion Markus. Having source highlighting already built-in into a gtk control is quite handy at this time.

    I should also point that the their lexer seems good enough to support fully Apache confs. I just need to add the list of directives to it, then we’re done with it.

    Oh, if you try rapache let us know in the irc channel (#rapache-devel), we’d love to hear your experience :)

Leave a Reply