title: Formatting Python code for the web
body: <p>Until recently, I posted Python code (whitespace matters) to blogspot.com using something like this:</p>
  
  <pre><code>&lt;div style="overflow-x: scroll "&gt; 
  &lt;table bgcolor="#ffffb0" border="0" width="100%" padding="4"&gt; 
  &lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;pre style=" hidden;font-family:monaco;"&gt; 
  my code here 
  &lt;/pre&gt;&lt;/table&gt;&lt;/div&gt; 
  </code></pre>
  
  <p>About a week ago, the posts started acquiring additional newlines so all of this is double-spaced.  Using a simple <code>&lt;pre&gt;</code> tag is no good (besides losing the color) b/c it also results in double newlines, while a <code>&lt;code&gt;</code> tag messes with the whitespace.  I guess I could just add <code>&amp;nbsp;</code>*4---but that's frowned upon or something by the HTML style gods.</p>
  
  <p>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 <a href="https://stackoverflow.com/questions/1852537/how-to-use-prettify-with-blogger-blogspot">here</a>.  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.</p>
  
  <p>The coloring problem itself is trivial, it could be solved through use of <code>&lt;style&gt;</code> 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. </p>
  
  <p>TextMate has a command <code>Create HTML from Document</code>.  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.</p>
  
  <p>Is there a simple Python parser?  A better solution?</p>
  
  <p>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 <a href="http://telliott99.blogspot.com/2011/08/pretty-code-4.html" rel="noreferrer">here</a>.  Pygments is also a good choice as well.</p>