Skip to content

Commit

Permalink
version 0.0.2 - update to match upstream python-markdown library changes
Browse files Browse the repository at this point in the history
- replace from `markdown.util import etree` with `import xml.etree.ElementTree as etree`
- black formatting
- update README.md
  • Loading branch information
btbytes committed Apr 6, 2023
1 parent b8848d4 commit 825436e
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 55 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,8 @@ If a matching reference definition cannot be found, then the extension looks in
[R Markdown]: http://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html
## Changelog
### 2023-04-05
- replace from `markdown.util import etree` with `import xml.etree.ElementTree as etree` per this [Python-Markdown 3.2 changelog](https://github.com/Python-Markdown/markdown/blob/master/docs/change_log/release-3.2.md)
97 changes: 49 additions & 48 deletions mdx_bib.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,37 @@
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
from markdown.postprocessors import Postprocessor
from markdown.inlinepatterns import Pattern
from markdown.util import etree

import xml.etree.ElementTree as etree
from pybtex.database.input import bibtex

from collections import OrderedDict
import re

BRACKET_RE = re.compile(r'\[([^\[]+)\]')
CITE_RE = re.compile(r'@(\w+)')
DEF_RE = re.compile(r'\A {0,3}\[@(\w+)\]:\s*(.*)')
INDENT_RE = re.compile(r'\A\t| {4}(.*)')
BRACKET_RE = re.compile(r"\[([^\[]+)\]")
CITE_RE = re.compile(r"@(\w+)")
DEF_RE = re.compile(r"\A {0,3}\[@(\w+)\]:\s*(.*)")
INDENT_RE = re.compile(r"\A\t| {4}(.*)")

CITATION_RE = r"@(\w+)"

CITATION_RE = r'@(\w+)'

class Bibliography(object):
""" Keep track of document references and citations for exporting """
"""Keep track of document references and citations for exporting"""

def __init__(self, extension, bibtex_file, order):
self.extension = extension
self.order = order

self.citations = OrderedDict()
self.references = dict()

if bibtex_file:
try:
parser = bibtex.Parser()
self.bibsource = parser.parse_file(bibtex_file).entries
except:
print("Error loading bibtex file")
except Exception as e:
print(f"Error loading bibtex file - {e}")
self.bibsource = dict()
else:
self.bibsource = dict()
Expand All @@ -50,9 +49,9 @@ def referenceID(self, citekey):
return "ref-" + citekey

def formatAuthor(self, author):
out = "%s %s."%(author.last()[0], author.first()[0][0])
out = "%s %s." % (author.last()[0], author.first()[0][0])
if author.middle():
out += "%s."%(author.middle()[0][0])
out += "%s." % (author.middle()[0][0])
return out

def formatReference(self, ref):
Expand All @@ -62,19 +61,19 @@ def formatReference(self, ref):
volume = ref.fields.get("volume", "")
year = ref.fields.get("year")

reference = "<p>%s: <i>%s</i>."%(authors, title)
reference = "<p>%s: <i>%s</i>." % (authors, title)
if journal:
reference += " %s."%journal
reference += " %s." % journal
if volume:
reference += " <b>%s</b>,"%volume
reference += " (%s)</p>"%year
reference += " <b>%s</b>," % volume

reference += " (%s)</p>" % year

return reference

def makeBibliography(self, root):
if self.order == 'alphabetical':
raise(NotImplementedError)
if self.order == "alphabetical":
raise (NotImplementedError)

div = etree.Element("div")
div.set("class", "references")
Expand All @@ -99,14 +98,15 @@ def makeBibliography(self, root):

return div


class CitationsPreprocessor(Preprocessor):
""" Gather reference definitions and citation keys """
"""Gather reference definitions and citation keys"""

def __init__(self, bibliography):
self.bib = bibliography

def subsequentIndents(self, lines, i):
""" Concatenate consecutive indented lines """
"""Concatenate consecutive indented lines"""
linesOut = []
while i < len(lines):
m = INDENT_RE.match(lines[i])
Expand All @@ -127,8 +127,8 @@ def run(self, lines):
if m:
key = m.group(1)
reference = m.group(2)
indents, i = self.subsequentIndents(lines, i+1)
reference += ' ' + indents
indents, i = self.subsequentIndents(lines, i + 1)
reference += " " + indents

self.bib.setReference(key, reference)
continue
Expand All @@ -141,9 +141,10 @@ def run(self, lines):
i += 1

return linesOut



class CitationsPattern(Pattern):
""" Handles converting citations keys into links """
"""Handles converting citations keys into links"""

def __init__(self, pattern, bibliography):
super(CitationsPattern, self).__init__(pattern)
Expand All @@ -153,51 +154,51 @@ def handleMatch(self, m):
id = m.group(2)
if id in self.bib.citations:
a = etree.Element("a")
a.set('id', self.bib.citationID(id))
a.set('href', '#' + self.bib.referenceID(id))
a.set('class', 'citation')
a.set("id", self.bib.citationID(id))
a.set("href", "#" + self.bib.referenceID(id))
a.set("class", "citation")
a.text = id

return a
else:
return None

return None


class CitationsTreeprocessor(Treeprocessor):
""" Add a bibliography/reference section to the end of the document """
"""Add a bibliography/reference section to the end of the document"""

def __init__(self, bibliography):
self.bib = bibliography

def run(self, root):
citations = self.bib.makeBibliography(root)
root.append(citations)

class CitationsExtension(Extension):

def __init__(self, *args, **kwargs):

class CitationsExtension(Extension):
def __init__(self, *args, **kwargs):
self.config = {
"bibtex_file": ["",
"Bibtex file path"],
'order': [
"unsorted",
"Order of the references (unsorted, alphabetical)"]
"bibtex_file": ["", "Bibtex file path"],
"order": ["unsorted", "Order of the references (unsorted, alphabetical)"],
}
super(CitationsExtension, self).__init__(*args, **kwargs)
self.bib = Bibliography(
self,
self.getConfig('bibtex_file'),
self.getConfig('order'),
self.getConfig("bibtex_file"),
self.getConfig("order"),
)

def extendMarkdown(self, md, md_globals):
md.registerExtension(self)
self.parser = md.parser
self.md = md

md.preprocessors.add("mdx_bib", CitationsPreprocessor(self.bib), "<reference")
md.inlinePatterns.add("mdx_bib", CitationsPattern(CITATION_RE, self.bib), "<reference")
md.preprocessors.add("mdx_bib", CitationsPreprocessor(self.bib), "<reference")
md.inlinePatterns.add(
"mdx_bib", CitationsPattern(CITATION_RE, self.bib), "<reference"
)
md.treeprocessors.add("mdx_bib", CitationsTreeprocessor(self.bib), "_begin")


def makeExtension(*args, **kwargs):
return CitationsExtension(*args, **kwargs)
16 changes: 9 additions & 7 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from setuptools import setup

setup(name='mdx_bib',
description="A Python markdown extension for handling citations.",
version='0.0.1',
author = 'Darwin Darakananda',
py_modules=['mdx_bib'],
install_requires = ['markdown', 'pybtex'],
license='MIT')
setup(
name="mdx_bib",
description="A Python markdown extension for handling citations.",
version="0.0.2",
author="Darwin Darakananda",
py_modules=["mdx_bib"],
install_requires=["markdown", "pybtex"],
license="MIT",
)

0 comments on commit 825436e

Please sign in to comment.