Initial import for public release...
[archweb_dev-nj.git] / wiki / templatetags / wikitags.py
blobbdf8df611d0bf2e9edde1177d3f76a3639f4e701
1 from django.template import Library
2 from django.conf import settings
3 from archlinux.lib import markdown
4 import re
6 register = Library()
8 class WikiProcessor:
9 def run(self, lines):
10 in_table = False
11 for i in range(len(lines)):
12 # Linebreaks
13 lines[i] = re.sub("%%", "<br />", lines[i])
14 # Internal Links
15 lines[i] = re.sub("\(\(([A-z0-9 :/-]+)\)\)", "<a href=\"/wiki/\\1\">\\1</a>", lines[i])
16 # Small Text
17 lines[i] = re.sub("----([^----]+)----", "<span style=\"font-size:x-small\">\\1</span>", lines[i])
18 lines[i] = re.sub("--([^--]+)--", "<span style=\"font-size:small\">\\1</span>", lines[i])
19 # TT text
20 lines[i] = re.sub("\{\{([^}\}]+)\}\}", "<tt>\\1</tt>", lines[i])
21 # Tables
22 m = re.match("(\|\|)", lines[i])
23 if m:
24 count = len(re.findall("(\|\|+)", lines[i]))
25 first = True
26 m2 = re.search("(\|\|+)", lines[i])
27 while m2 and count:
28 count -= 1
29 colspan = len(m2.group(1)) / 2
30 if first:
31 repl = "<td colspan=\"%d\">" % (colspan)
32 first = False
33 elif count == 0:
34 repl = "</td>"
35 else:
36 repl = "</td><td colspan=\"%d\">" % (colspan)
37 lines[i] = re.sub("(\|\|+)", repl, lines[i], 1)
38 # find the next chunk
39 m2 = re.search("(\|\|+)", lines[i])
40 lines[i] = "<tr>" + lines[i] + "</tr>"
41 if not in_table:
42 lines[i] = "<table>" + lines[i]
43 in_table = True
44 elif in_table:
45 lines[i] = "</table>" + lines[i]
46 in_table = False
47 # close leftover table, if open
48 if in_table:
49 lines[len(lines)] = lines[len(lines)] + "</table>"
50 return lines
52 @register.filter
53 def wikify(value):
54 md = markdown.Markdown(value)
55 md.preprocessors.insert(0, WikiProcessor())
56 html = md.toString()
57 return html