Login

Another pygments for ReST

Author:
limodou
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Tags:
pygments rest
Score:
1 (after 1 ratings)

This is like snippet 36. And it'll return css also. And it's not a filter.If the code parameter is skip, it'll test the code first, and if there is not a suiable lexer for the code, then use default python lexer to render the code. The code lanauage parameter is comes from pygments lexer alias.

How to use it

html = to_html(rest_text)

And there is a level parameter in to_html function, default is 2, it's the sections level. And the html will be css style + body

How to write ReST

Below is a example.

This is a test.

.. code::

   def code(name, arguments, options, content, lineno,
             content_offset, block_text, state, state_machine):
       opt = {'display':'on'}
       opt.update(options)

       docnodes.Node(content, ''.join(arguments), **opt)
       if opt['display'].lower() == 'on':
           return [nodes.literal_block('', '\n'.join(content))]
       else:
           return []

.. code:: html+django

   <h1 id="title">通讯录</h1>
   <hr>
   <div>
   <table border="0" width="500">
   <tr align="right">
     <td>{% if has_previous %}
       <a href="/address?page={{ previous }}">上一页</a>
       {% endif %} {% if has_next %}
       <a href="/address?page={{ next }}">下一页</a>
       {% endif %}</td></tr>
   </table>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from docutils.core import publish_parts
from docutils import nodes
from docutils.parsers.rst import directives
import re
import threading

g_data = threading.local()
g_data.g_style = {}

class highlight_block(nodes.General, nodes.Text):pass

from docutils.writers.html4css1 import Writer, HTMLTranslator

class SimpleWrite(Writer):
    def __init__(self):
        Writer.__init__(self)
        self.translator_class = SimpleHTMLTranslator
        
class SimpleHTMLTranslator(HTMLTranslator):
    def visit_highlight_block(self, node):
        self.body.append(node.astext())
    
    def depart_highlight_block(self, node):
        pass

def r_space(m):
    return len(m.group()) * '&nbsp;'

re_space = re.compile(r'^[ ]+', re.MULTILINE)
def code(name, arguments, options, content, lineno,
          content_offset, block_text, state, state_machine):
    global g_data
    
    if len(arguments) > 0:
        lang = arguments[0]
    else:
        lang = ''
    style, text = highlight('\n'.join(content), lang)
    text = re_space.sub(r_space, text)
    g_data.g_style[lang] = style
    return [highlight_block(text)]

code.content = 1
code.arguments = (0, 1, 1)
directives.register_directive('code', code)

def to_html(text, level=2):
    global g_data
    g_data.g_style = {}
    source = text
    parts = publish_parts(source, writer=SimpleWrite(), settings_overrides={'initial_header_level':level})
    if g_data.g_style:
        style = '<style>' + '\n'.join(g_data.g_style.values()) + '</style>'
    else:
        style = ''
    return  style + '\n' + parts['body']

def parts(file):
    fo = open(file, 'r')
    source = fo.read()
    fo.close()
    parts = publish_parts(source, source_path=file, writer_name='html')
    for k, v in parts.items():
        parts[k] = (v)
    return parts

def highlight(code, lang):
    from pygments import highlight
    from pygments.lexers import get_lexer_by_name, guess_lexer, PythonLexer
    from pygments.formatters import HtmlFormatter
    try:
        lexer = get_lexer_by_name(lang)
    except:
        try:
            lexer = guess_lexer(code)
            lang = lexer.aliases[0]
        except:
            lexer = PythonLexer()
            lang = 'python'
    lang = lang.replace('+', '_')
    return HtmlFormatter().get_style_defs('.highlight_'+lang), highlight(code, lexer, HtmlFormatter(cssclass='highlight_'+lang))

More like this

  1. Sort Table Headers by insin 7 years, 10 months ago
  2. Functional Filters by waterson 7 years, 7 months ago
  3. FieldAccessForm (per-field user access for forms derived from models) by Killarny 6 years, 7 months ago
  4. grouper tag by visgean 3 years, 9 months ago
  5. Yet another SQL debugging facility by miracle2k 7 years, 9 months ago

Comments

limodou (on February 27, 2007):

ok, I see.

#

Please login first before commenting.