Created
February 26, 2019 21:51
-
-
Save lebedov/bf24781b891de609f1a930132941211e to your computer and use it in GitHub Desktop.
Add syntax highlighting to nbshow output.
This file contains 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 | |
""" | |
Add syntax highlighting to nbshow output. | |
""" | |
import argparse | |
import re | |
import pygments | |
import pygments.lexers | |
import pygments.formatters | |
import sarge | |
parser = argparse.ArgumentParser(description='nbshow with syntax highlighting') | |
parser.add_argument('input') | |
args = parser.parse_args() | |
# Only show source cells: | |
p = sarge.capture_stdout('nbdime show -O -A -M -D %s' % args.input) | |
def pad(text, n_cols): | |
return '\n'.join([' '*n_cols+line for line in text.split('\n')]) | |
def unpad(text, n_cols): | |
return '\n'.join([line[n_cols:] for line in text.split('\n')]) | |
def find_offset(text): | |
return len(re.search('^(\s+)', text).group(1)) | |
s = re.split('(^\w+ cell \d+:\n\s+source:\n)', p.stdout.text, | |
flags=re.MULTILINE)[1:] | |
markdown_lexer = pygments.lexers.MarkdownLexer() | |
python3_lexer = pygments.lexers.Python3Lexer() | |
terminal_formatter = pygments.formatters.Terminal256Formatter() | |
for title, content in zip(s[::2], s[1::2]): | |
print(title) | |
n_cols = find_offset(content) | |
content_unpad = unpad(content, n_cols) | |
if 'markdown' in title: | |
tmp = pygments.highlight(content_unpad, | |
markdown_lexer, terminal_formatter) | |
elif 'code' in title: | |
tmp = pygments.highlight(content_unpad, | |
python3_lexer, terminal_formatter) | |
else: | |
raise ValueError | |
print(pad(tmp, n_cols)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment