Skip to content

Instantly share code, notes, and snippets.

@timothymillar
Last active June 28, 2020 07:49
Show Gist options
  • Save timothymillar/1233a4cce6ca98a4242b3c9ef8604820 to your computer and use it in GitHub Desktop.
Save timothymillar/1233a4cce6ca98a4242b3c9ef8604820 to your computer and use it in GitHub Desktop.
A pandoc filter for converting jupytext or similar markdown to a codebraid notebook
#!/usr/bin/env python
"""A Pandoc filter to convert jupytext (or similar)
markdown to a codebraid "notebook".
"""
from pandocfilters import toJSONFilter, CodeBlock
def get_jupyter_kernel(data):
keys = [
'jupyter',
'c',
'kernelspec',
'c',
'name',
]
for key in keys:
data = data.get(key)
if isinstance(data, dict):
pass
else:
return None
data = data['c']
while True:
if isinstance(data, dict):
data = data['c']
elif isinstance(data, list):
data = data[0]
else:
return data
class CBNoteBookFilter(object):
def __init__(self):
self.first_code_block = True
def __call__(self, key, value, format, meta):
"""replace code block classes with '.cb.nb' and add
jupyter kernelspec to first code block if a kerel
is specified in metadata.
"""
if key == 'CodeBlock':
[[ident, classes, keyvals], code] = value
# add notebook class if language specified
if len(classes) > 0:
classes = [classes[0], 'cb.nb']
# look for a jupyter kernel if this is the first block
if self.first_code_block:
kernel = get_jupyter_kernel(meta)
if kernel:
keyvals.append(['jupyter_kernel', kernel])
self.first_code_block = False
return CodeBlock([ident, classes, keyvals], code)
if __name__ == "__main__":
toJSONFilter(CBNoteBookFilter())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment