Created
June 9, 2017 13:57
-
-
Save phdd/2506311fb3da0c204e2ef27b3347c062 to your computer and use it in GitHub Desktop.
Pandoc include filter
This file contains hidden or 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
#!/usr/bin/env python | |
""" | |
Include contents from other files, even recursively. | |
Examples: | |
- Include first chaper from markdown file | |
[](chapter1.md){.include .markdown} | |
- Include Java class skipping the packages. Furter attributes are preserved. | |
[AnyPojo Class Impl.](../src/AnyPojo.java){.include .java .code from=7} | |
""" | |
from pandocfilters import toJSONFilter, get_value, stringify | |
from pandocfilters import CodeBlock | |
from urllib import parse | |
from io import open | |
import pypandoc | |
import json | |
import sys | |
import os | |
def content_from(path, start, end): | |
with open(path, encoding = 'utf-8') as f: | |
lines = f.readlines() | |
start = int(start) - 1 | |
end = int(end) | |
return ''.join(lines[start:end]) | |
def links(key, value, format, meta): | |
if key != 'Para' or not value: | |
return None | |
firstChild = value[0] | |
key = firstChild['t'] | |
value = firstChild['c'] | |
if key != 'Link': | |
return None | |
[ident, classes, attributes], caption, [path, _] = value | |
if not 'include' in classes: | |
return None | |
start, attributes = get_value(attributes, 'from', 1) | |
end, attributes = get_value(attributes, 'to', sys.maxsize) | |
path = parse.unquote(path) | |
content = content_from(path, start, end) | |
classes.remove('include') | |
if 'code' in classes: | |
classes.remove('code') | |
if caption: | |
attributes += [['caption', stringify(caption)]] | |
return CodeBlock((ident, classes, attributes), content) | |
else: | |
if len(classes) != 1: | |
raise Exception('A direct include has the ' + | |
'input type as second class') | |
input_format = classes[0] | |
this_filter = os.path.realpath(__file__) | |
json_content = pypandoc.convert_text(content, | |
to = 'json', | |
format = input_format, | |
filters = [ this_filter ]) | |
content = json.loads(json_content) | |
return content['blocks'] | |
if __name__ == "__main__": | |
toJSONFilter(links) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment