source: trac/trunk/wiki-macros/TOC.py @ 3059

Revision 2591, 1.9 KB checked in by moschny, 8 years ago (diff)

Adding conf and wiki-macros directories

Line 
1# vim: expandtab tabstop=4
2from StringIO import StringIO
3import re
4import string
5
6rules = re.compile(r"""(?P<heading>^\s*(?P<hdepth>=+)\s(?P<header>.*)\s(?P=hdepth)\s*$)""")
7anchor = re.compile('[^\w\d]+')
8
9def parse_toc(env, out, page, body):
10    depth = 1
11    for line in body.splitlines():
12        match = rules.match(line)
13        if match:
14            header = match.group('header')
15            new_depth = len(match.group('hdepth'))
16            if new_depth < depth:
17                while new_depth < depth:
18                    depth -= 1
19                    out.write("</li></ol><li>\n")
20            elif new_depth > depth:
21                while new_depth > depth:
22                    depth += 1
23                    out.write("<ol><li>\n")
24            else:
25                out.write("</li><li>\n")
26            link = page + "#" + anchor.sub("", header)
27            out.write('<a href="%s">%s</a>' % (env.href.wiki(link), header))
28    while depth > 1:
29        out.write("</li></ol>\n")
30        depth -= 1
31
32def execute(hdf, args, env):
33    db = env.get_db_cnx()
34    out = StringIO()
35    # Has the user supplied a list of pages?
36    if args:
37        pages = re.split('\s*,\s*', args)
38        out.write("<ol>\n")
39        for page in pages:
40            cursor = db.cursor()
41            cursor.execute("select text from wiki where name='%s' order by version desc" % page)
42            row = cursor.fetchone()
43            if row:
44                parse_toc(env, out, page, row[0])
45            else:
46                out.write('<div class="system-message"><strong>Error: Page %s does not exists</strong></div>' % page)
47        out.write("</ol>\n")
48        return out.getvalue()
49    else:
50        # return current page
51        out.write("<ol>\n")
52        page = hdf.getValue("args.page", "")
53        parse_toc(env, out, page, hdf.getValue("wiki.page_source", ""))
54        out.write("</ol>\n")
55        return out.getvalue()# + "<pre>" + hdf.dump() + "</pre>"
Note: See TracBrowser for help on using the repository browser.