Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Python code for the web

Tags:

python

html

css

Until recently, I posted Python code (whitespace matters) to blogspot.com using something like this:

<div style="overflow-x: scroll "> 
<table bgcolor="#ffffb0" border="0" width="100%" padding="4"> 
<tbody><tr><td><pre style=" hidden;font-family:monaco;"> 
my code here 
</pre></table></div> 

About a week ago, the posts started acquiring additional newlines so all of this is double-spaced. Using a simple <pre> tag is no good (besides losing the color) b/c it also results in double newlines, while a <code> tag messes with the whitespace. I guess I could just add &nbsp;*4---but that's frowned upon or something by the HTML style gods.

The standard answer to this (like right here on SO) is to get syntax coloring or highlighting through the use of css (which I don't know much about), for example as discussed in a previous SO question here. The problem I have with that is that all such solutions require loading of a resource from a server on the web. But if (say 5 years from now) that resource is gone, the html version of the code will not render at all. If I knew Javascript I guess I could probably fix that.

The coloring problem itself is trivial, it could be solved through use of <style> tags with various definitions. But parsing is hard; at least I've not made much progress trying to parse Python myself. Multi-line strings are a particular pain. I could just ignore the hard cases and code the simple ones.

TextMate has a command Create HTML from Document. The result is fairly wordy but could just be pasted into a post. But say if you had 3 code segments, then it's like 1000 lines or something. And of course it's a document, so you have to actually cut before you paste.

Is there a simple Python parser? A better solution?

UPDATE: I wrote my own parser for syntax highlighting. Still a little buggy perhaps, but it is quite simple and a self-contained solution. I posted it here. Pygments is also a good choice as well.

like image 678
telliott99 Avatar asked Aug 20 '11 21:08

telliott99


1 Answers

Why don't you use pygments?

like image 159
Gabi Purcaru Avatar answered Oct 01 '22 03:10

Gabi Purcaru