Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Last active February 3, 2019 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flying-sheep/e584eea34dfe06c6ebf3d8580f2e5e6e to your computer and use it in GitHub Desktop.
Save flying-sheep/e584eea34dfe06c6ebf3d8580f2e5e6e to your computer and use it in GitHub Desktop.
Just add some css for `.interactive-block > table`

Example

first(code, 'block')

And

>>> second(code, 'block')
this is not highlighted ('even if it looks like code')
>>> def test():
...     also(works, 'with', ...)
...
>>> 

Neat!

#!/bin/bash
pandoc -s --filter=pandocfilter_interactive.py example.md >! example.htm
#/usr/bin/env python3
import re
from pandocfilters import toJSONFilter, Div, Table, CodeBlock
re_cont = re.compile(r'^\.\.\. ?(.*)')
def interactive_session(key, value, format, meta):
if key == 'CodeBlock':
((ident, classes, keyvals), code) = value
if 'python' not in classes or not code.startswith('>>>'):
return CodeBlock((ident, classes, keyvals), code)
blocks = code.split('>>>')[1:]
rows = []
for block in blocks:
# remove initial space if available
block = block.lstrip(' ').split('\n')
input = [block[0]]
output = []
block_it = iter(block[1:])
for l in block_it:
m = re_cont.match(l)
# Only add lines until the first output
if m:
input.append(m[1])
else:
if l: output.append(l)
break
output += list(block_it)
prompts = '>>> \n' + '\n'.join('... ' for i in input[1:])
rows.append([
[CodeBlock(['', [], keyvals], prompts)],
[CodeBlock([ident, classes, keyvals], '\n'.join(input))],
])
if output:
rows.append([
[], # There’s no colspan so we need an empty cell here
[CodeBlock(['', [], keyvals], '\n'.join(output))],
])
ident = ''
kvs = []
caption = []
alignments = [dict(t='AlignDefault', c=[])] * 2
width = [0, 0]
headers = [[], []]
return Div(
[ident, ['interactive-block'], kvs],
[Table(caption, alignments, width, headers, rows)],
)
if __name__ == '__main__':
toJSONFilter(interactive_session)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment