Skip to content

Instantly share code, notes, and snippets.

@charlesdaniels
Created March 17, 2018 16:55
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 charlesdaniels/ac5fa6e3e77aef5ff5c85fa2d95e9fba to your computer and use it in GitHub Desktop.
Save charlesdaniels/ac5fa6e3e77aef5ff5c85fa2d95e9fba to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# This script consumes Markdown preformatted code blocks delimited by ``` and
# replaces them by inline HTML with line numbers. This would be a good way to
# add syntax hilighting later,
import sys
import pygments
import pygments.formatters
# from pygments.lexers import PythonLexer
import pygments.lexers
fmt = pygments.formatters.HtmlFormatter(linenos="table", noclasses=True)
# When state is true, we are inside of a codeblock
state = False
code = ""
language = ""
for line in sys.stdin:
if line.strip()[0:3] == '```':
# state transition edge
state = not state
if not state:
# state transition from in code block to not in code block
lexer = None
try:
lexer = pygments.lexers.get_lexer_by_name(language)
except Exception:
# the user-provided language was unknown, guess instead
lexer = pygments.lexers.guess_lexer(code)
h = pygments.highlight(code, lexer, fmt)
sys.stdout.write(h)
language = ""
code = ""
else:
# state transition from not code block to code block
language = line[3:].strip()
elif state:
# we are not in a state transition, and we are reading a codeblock
code += line
else:
# pass lines through unmodified
sys.stdout.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment