From c1c7d23c0b5caaec3b495cc5f27a8fab66a90197 Mon Sep 17 00:00:00 2001 From: Jim Hague Date: Wed, 2 Nov 2016 14:06:25 +0000 Subject: [PATCH] Implement custom markdown to reference tune. Also ensure filename matches are not greedy, and so work if there are two filenames on a line. --- abcfield.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/abcfield.py b/abcfield.py index 6cc88ab..8511620 100755 --- a/abcfield.py +++ b/abcfield.py @@ -18,6 +18,7 @@ # import optparse +import pathlib import re import subprocess import sys @@ -164,11 +165,22 @@ def convertMarkdown(t, latex): target = "--to=html" res = subprocess.check_output(['pandoc', '--from=markdown', target], input=t, universal_newlines=True) if latex: - res = re.sub(r'\\href{(.*).abc}', r'\\hyperlink{\1}', res) + res = re.sub(r'\\href{(.*?).abc}', r'\\hyperlink{\1}', res) else: - res = re.sub(r'href="(.*).abc"', r'href="\1.html"', res) + res = re.sub(r'href="(.*?).abc"', r'href="\1.html"', res) return res +# Implement a custom Markdown shorthand for referencing ABC files. +# will expand to ['title of foo'](foo.abc). +def expandCustomMarkdown(t, latex): + # Given a match to (foo.abc), return a markdown link to the tune with the + # title of the tune as the text of the link. + def getTitle(m): + fname = m.group(1) + ".abc" + with pathlib.Path(fname).open() as f: + return "[" + getFieldDisplayText(f, "T", latex) + "](" + fname + ")" + return re.sub(r'<(.*?).abc>', getTitle, t) + # Return the raw text for a given field. Optionally the nth field is taken, # or the field data must start with a designated string to be recognised. def getFieldText(inf, field, n = 1, starts = None): @@ -209,7 +221,7 @@ def getFieldDisplayText(inf, field, n = 1, starts = None, latex = False): elif field.upper() == "K": res = convertKeyToDisplay(res) elif field.upper() in ["H", "N"]: - res = convertMarkdown(res, latex) + res = convertMarkdown(expandCustomMarkdown(res, latex), latex) return res if __name__ == "__main__":