improve `highlight` with #:lines option

pull/139/head
Matthew Butterick 8 years ago
parent 146d95b49c
commit 3972173eac

@ -2,6 +2,7 @@
# continuously. Input format is:
#
# <lexer-name>
# <list-of-highlighted-lines>
# <code>
# ...
# __END__
@ -28,12 +29,9 @@ parser.add_option('--linenos', action="store_true", dest="linenos")
parser.add_option('--cssclass', default="source", dest="cssclass")
(options, _) = parser.parse_args()
formatter = HtmlFormatter(linenos=options.linenos,
cssclass=options.cssclass,
encoding="utf-8")
lexer = ""
code = ""
lines-to-highlight = ""
py_version = sys.version_info.major
sys.stdout.write("ready\n")
sys.stdout.flush()
@ -47,6 +45,10 @@ while 1:
break
elif line == '__END__':
# Lex input finished. Lex it.
formatter = HtmlFormatter(linenos=options.linenos,
cssclass=options.cssclass,
encoding="utf-8",
hl_lines=lines-to-highlight)
if py_version >= 3:
sys.stdout.write(highlight(code, lexer, formatter).decode("utf-8"))
else:
@ -55,12 +57,17 @@ while 1:
sys.stdout.flush()
lexer = ""
code = ""
lines-to-highlight = ""
elif lexer == "":
# Starting another lex. First line is the lexer name.
try:
lexer = get_lexer_by_name(line, encoding="guess")
except ClassNotFound:
lexer = get_lexer_by_name("text", encoding="guess")
elif lines-to-highlight == "":
# Starting another lex. Second line is list of lines to highlight,
# formatted as string of whitespace-separated integers
lines-to-highlight = [int(str) for str in line.split()]
else:
# Accumulate more code
# Use `line_raw`: Do want trailing space, \n, \r

@ -1 +1 @@
1488121531
1488160788

@ -128,13 +128,15 @@ if zero is False:
(stop)
(old-exit-handler v))))
(define (pygmentize code lang) ;; string? string? -> (listof xexpr?)
(define (pygmentize code lang [hl-lines null]) ;; string? string? (listof number?) -> (listof xexpr?)
(define (default code)
`((pre () (code () ,code))))
(unless (running?)
(start))
(cond [(running?)
;; order of writing arguments is significant: cooperates with pipe.py
(displayln lang pyg-out)
(displayln (string-join (map number->string hl-lines) " ") pyg-out)
(displayln code pyg-out)
(displayln "__END__" pyg-out)
(let loop ([s ""])
@ -149,10 +151,11 @@ if zero is False:
;;;;;;;;;;;;;;;;;;
(define (highlight lang . codelines)
(define (highlight #:lines [hl-lines null]
lang . codelines)
(define code (string-append* codelines))
`(div ((class "highlight"))
,@(strip-empty-attrs (pygmentize code lang))))
,@(strip-empty-attrs (pygmentize code lang hl-lines))))
;; Other CSS options available from http://richleland.github.io/pygments-css/

Loading…
Cancel
Save