-#!/usr/bin/python2.6
-# -*- coding: iso-8859-15 -*-
+#!/usr/bin/python3.4
# $Id$
# $HeadURL$
-"""This module contains general functions that help parsing the mediawiki markup.
-I looked for an already existing MediaWiki parser in Python but I didn't find anything
-that convinced me. However, here are the links:
+"""For parsing MediaWiki text, we rely on the package mwparserfromhell (https://github.com/earwig/mwparserfromhell).
+This module just contains a few additional useful functions.
+Other Python MediaWiki parsers:
* py-wikimarkup https://github.com/dcramer/py-wikimarkup
* mwlib http://code.pediapress.com/wiki/wiki
+* https://www.mediawiki.org/wiki/Alternative_parsers
"""
+class ParseError(RuntimeError):
+ """Exception used by some of the functions"""
+ pass
+
+
+def format_template_table(template, keylen=None):
+ """Reformat the given template to be tabular.
+
+ >>> template
+ {{foo|bar|bazz=7}}
+ >>> format_template_table(template)
+ {{foo
+ | bar
+ | bazz = 7
+ }}
+
+ :param keylen: length of the keys or None for automatic determination
+ """
+ if keylen is None:
+ shown_keys = [len(param.name.strip()) for param in template.params if param.showkey]
+ keylen = max(shown_keys) if shown_keys else 0
+ template.name = '{}\n'.format(template.name.strip())
+ for param in template.params:
+ if param.showkey:
+ param.name = ' {{:{}}} '.format(keylen).format(param.name.strip())
+ value = param.value.strip()
+ if len(value) > 0:
+ param.value = ' {}\n'.format(value)
+ else:
+ param.value = '\n'
+
+
+def format_template_oneline(template):
+ """Formats a template like this: {{template_name|param| }}
+ (whitespace is stripped and empty parameters are replaced with one space)."""
+ template.name = template.name.strip()
+ for param in template.params:
+ if param.showkey:
+ param.name = param.name.strip()
+ value = param.value.strip()
+ if value == '':
+ value = ' '
+ param.value = value
+
+
+def dbkey_to_title(value):
+ """Converts a article database key to a article title. Private function secureAndSplit() of the Title class
+ on line 3316 of includes/Title.php says:
+ $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform );
+ No check for None because a missing title is an error."""
+ return value.replace('_', ' ')