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) |