Converted encoding from ISO8859-15 to UTF-8.
[philipp/winterrodeln/wrpylib.git] / wrpylib / mwmarkup.py
1 #!/usr/bin/python3.4
2 # coding=utf-8
3 # $Id$
4 # $HeadURL$
5 """For parsing MediaWiki text, we rely on the package mwparserfromhell (https://github.com/earwig/mwparserfromhell).
6 This module just contains a few additional useful functions.
7
8 Other Python MediaWiki parsers:
9 * py-wikimarkup https://github.com/dcramer/py-wikimarkup
10 * mwlib http://code.pediapress.com/wiki/wiki
11 * https://www.mediawiki.org/wiki/Alternative_parsers
12 """
13
14 class ParseError(RuntimeError):
15     """Exception used by some of the functions"""
16     pass
17
18
19 def template_to_table(template, keylen=None):
20     """Reformat the given template to be tabular.
21
22     >>> template
23     {{foo|bar|bazz=7}}
24     >>> template_to_table(template)
25     {{foo
26     | bar
27     | bazz = 7
28     }}
29
30     :param keylen: length of the keys or None for automatic determination
31     """
32     if keylen is None:
33         shown_keys = [len(param.name.strip()) for param in template.params if param.showkey]
34         keylen = max(shown_keys) if shown_keys else 0
35     template.name = '{}\n'.format(template.name.strip())
36     for param in template.params:
37         if param.showkey:
38             param.name = ' {{:{}}} '.format(keylen).format(param.name.strip())
39         value = param.value.strip()
40         if len(value) > 0:
41             param.value = ' {}\n'.format(value)
42         else:
43             param.value = '\n'