Skip to content

Instantly share code, notes, and snippets.

@puterleat
Created September 7, 2012 08:34
Show Gist options
  • Save puterleat/3664375 to your computer and use it in GitHub Desktop.
Save puterleat/3664375 to your computer and use it in GitHub Desktop.
citation preprocessor
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
@benjaoming
Copy link

Looks good!! :)

Line #23 : I would suggest a reverse lookup, but it's just an example right -- there is no view yet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment