MCPcopy Create free account
hub / github.com/ronreiter/interactive-tutorials / CodeHilite

Class CodeHilite

markdown/extensions/codehilite.py:34–173  ·  view source on GitHub ↗

Determine language of source code, and pass it into the pygments hilighter. Basic Usage: >>> code = CodeHilite(src = 'some text') >>> html = code.hilite() * src: Source string or any object with a .readline attribute. * linenos: (Boolen) Turn line number

Source from the content-addressed store, hash-verified

32
33# ------------------ The Main CodeHilite Class ----------------------
34class CodeHilite:
35 """
36 Determine language of source code, and pass it into the pygments hilighter.
37
38 Basic Usage:
39 >>> code = CodeHilite(src = 'some text')
40 >>> html = code.hilite()
41
42 * src: Source string or any object with a .readline attribute.
43
44 * linenos: (Boolen) Turn line numbering 'on' or 'off' (off by default).
45
46 * css_class: Set class name of wrapper div ('codehilite' by default).
47
48 Low Level Usage:
49 >>> code = CodeHilite()
50 >>> code.src = 'some text' # String or anything with a .readline attr.
51 >>> code.linenos = True # True or False; Turns line numbering on or of.
52 >>> html = code.hilite()
53
54 """
55
56 def __init__(self, src=None, linenos=False, css_class="codehilite"):
57 self.src = src
58 self.lang = None
59 self.linenos = linenos
60 self.css_class = css_class
61
62 def hilite(self):
63 """
64 Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with
65 optional line numbers. The output should then be styled with css to
66 your liking. No styles are applied by default - only styling hooks
67 (i.e.: <span class="k">).
68
69 returns : A string of html.
70
71 """
72
73 self.src = self.src.strip('\n')
74
75 self._getLang()
76
77 try:
78 from pygments import highlight
79 from pygments.lexers import get_lexer_by_name, guess_lexer, \
80 TextLexer
81 from pygments.formatters import HtmlFormatter
82 except ImportError:
83 # just escape and pass through
84 txt = self._escape(self.src)
85 if self.linenos:
86 txt = self._number(txt)
87 else :
88 txt = '<div class="%s"><pre>%s</pre></div>\n'% \
89 (self.css_class, txt)
90 return txt
91 else:

Callers 1

runMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected