Created
September 7, 2012 08:34
-
-
Save puterleat/3664375 to your computer and use it in GitHub Desktop.
citation preprocessor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import markdown | |
import re | |
from publications import models | |
MIXED_CITATION_RE = re.compile(r'\[@([;-@\w\s;]+)\]') | |
class CitationExtension(markdown.Extension): | |
""" Citation Extension for Python-Markdown. """ | |
def extendMarkdown(self, md, md_globals): | |
""" Insert AbbrPreprocessor before ReferencePreprocessor. """ | |
md.preprocessors.add('dw-citations', CitationPreprocessor(md), '>html_block') | |
class CitationPreprocessor(markdown.preprocessors.Preprocessor): | |
"""django-wiki citation preprocessor - parse [@citekey] references. """ | |
def run(self, lines): | |
filtercitekey = lambda x: "".join(i for i in x if i not in ["[", "]", "@", " "]) | |
formatpub = lambda x: """[%s](/publications/%s)""" % (x.id, x.id) | |
mixed_matches = [list(MIXED_CITATION_RE.finditer(line)) for line in lines] | |
citekey_lists = [[[filtercitekey(citekey) for citekey in i.group(0).split(";")] | |
for i in j] for j in mixed_matches] | |
cited_pubs = [[", ".join([formatpub(p) | |
for p in models.Publication.objects.filter(citekey__in=i)]) | |
for i in j] for j in citekey_lists] | |
newlines = [] | |
for matches, in_text_citations, line in zip(mixed_matches, cited_pubs, lines): | |
nline = line | |
for m, c in zip(matches, in_text_citations): | |
nline = nline.replace(m.group(0), """(%s)""" % c,) | |
newlines.append(nline) | |
return newlines |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good!! :)
Line #23 : I would suggest a reverse lookup, but it's just an example right -- there is no view yet?