Parsing and Highlighting <code> Blocks

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from BeautifulSoup import BeautifulSoup

from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer, get_lexer_by_name

import re 

def Parse ( content ): 

    tree    = BeautifulSoup ( content )

    for code in tree.findAll ( 'code' ): 
        
        if not code['class']: code['class'] = 'text'

        lexer = get_lexer_by_name(code['class'])

        new_content = highlight ( code.contents[0], lexer, HtmlFormatter() )
        code.replaceWith ( "%s\n%s" % (info,new_content) )
   
    content = str(tree)
    return content

More like this

  1. Pygments Rendering Template Filter by ericflo 7 years, 1 month ago
  2. Code syntax highlighting templatetag by badrunner 6 years, 7 months ago
  3. Markdown and Syntax Highlighting in Django by blinks 7 years, 1 month ago
  4. typygmentdown by ubernostrum 6 years, 7 months ago
  5. Text Highlighting Filter by girasquid 5 years, 4 months ago

Comments

kaikuehne (on March 4, 2007):

What is "info"?

#

ludvig.ericson (on March 7, 2007):

Might be a good idea to mention that it requires two libraries, BeautifulSoup and pygments. Also on line 20, you pass the format string an info variable which, from what I can see, isn't set.

Both content and new_content are excessive variables, especially content.

#

alexdong (on March 8, 2007):

This is a good idea. But how am I supposed to use this feature? ie where does the content come from?

#

(Forgotten your password?)