from pygments.util import ClassNotFound, OptionError, docstring_headline
from pygments.lexers import get_all_lexers, get_lexer_by_name, get_lexer_for_filename, find_lexer_class, guess_lexer, TextLexer
from pygments.formatters import get_all_formatters, get_formatter_by_name, get_formatter_for_filename, find_formatter_class, TerminalFormatter
from pygments.filters import get_all_filters, find_filter_class
from pygments.styles import get_all_styles, get_style_by_name
USAGE = 'Usage: %s [-l <lexer> | -g] [-F <filter>[:<options>]] [-f <formatter>]\n [-O <options>] [-P <option=value>] [-o <outfile>] [<infile>]\n\n %s -S <style> -f <formatter> [-a <arg>] [-O <options>] [-P <option=value>]\n %s -L [<which> ...]\n %s -N <filename>\n %s -H <type> <name>\n %s -h | -V\n\nHighlight the input file and write the result to <outfile>.\n\nIf no input file is given, use stdin, if -o is not given, use stdout.\n\n<lexer> is a lexer name (query all lexer names with -L). If -l is not\ngiven, the lexer is guessed from the extension of the input file name\n(this obviously doesn\'t work if the input is stdin). If -g is passed,\nattempt to guess the lexer from the file contents, or pass through as\nplain text if this fails (this can work for stdin).\n\nLikewise, <formatter> is a formatter name, and will be guessed from\nthe extension of the output file name. If no output file is given,\nthe terminal formatter will be used by default.\n\nWith the -O option, you can give the lexer and formatter a comma-\nseparated list of options, e.g. ``-O bg=light,python=cool``.\n\nThe -P option adds lexer and formatter options like the -O option, but\nyou can only give one option per -P. That way, the option value may\ncontain commas and equals signs, which it can\'t with -O, e.g.\n``-P "heading=Pygments, the Python highlighter".\n\nWith the -F option, you can add filters to the token stream, you can\ngive options in the same way as for -O after a colon (note: there must\nnot be spaces around the colon).\n\nThe -O, -P and -F options can be given multiple times.\n\nWith the -S option, print out style definitions for style <style>\nfor formatter <formatter>. The argument given by -a is formatter\ndependent.\n\nThe -L option lists lexers, formatters, styles or filters -- set\n`which` to the thing you want to list (e.g. "styles"), or omit it to\nlist everything.\n\nThe -N option guesses and prints out a lexer name based solely on\nthe given filename. It does not take input or highlight anything.\nIf no specific lexer can be determined "text" is returned.\n\nThe -H option prints detailed help for the object <name> of type <type>,\nwhere <type> is one of "lexer", "formatter" or "filter".\n\nThe -h option prints this help.\nThe -V option prints the package version.\n'
def _parse_options(o_strs):
opts = { }
if not o_strs:
return opts
for o_str in o_strs:
if not o_str:
continue
o_args = o_str.split(',')
for o_arg in o_args:
o_arg = o_arg.strip()
try:
(o_key, o_val) = o_arg.split('=')
o_key = o_key.strip()
o_val = o_val.strip()
except ValueError:
opts[o_arg] = True
continue
opts[o_key] = o_val
return opts
def _parse_filters(f_strs):
filters = []
if not f_strs:
return filters
for f_str in f_strs:
if ':' in f_str:
(fname, fopts) = f_str.split(':', 1)
filters.append((fname, _parse_options([
fopts])))
continue
f_strs
filters.append((f_str, { }))
return filters
def _print_help(what, name):
try:
if what == 'lexer':
cls = find_lexer_class(name)
print 'Help on the %s lexer:' % cls.name
print dedent(cls.__doc__)
elif what == 'formatter':
cls = find_formatter_class(name)
print 'Help on the %s formatter:' % cls.name
print dedent(cls.__doc__)
elif what == 'filter':
cls = find_filter_class(name)
print 'Help on the %s filter:' % name
print dedent(cls.__doc__)
except AttributeError:
print >>sys.stderr, '%s not found!' % what
def _print_list(what):
if what == 'lexer':
print
print 'Lexers:'
print '~~~~~~~'
info = []
for fullname, names, exts, _ in get_all_lexers():
if not exts or '(filenames ' + ', '.join(exts) + ')':
pass
tup = (', '.join(names) + ':', fullname, '')
info.append(tup)
info.sort()
for i in info:
print '* %s\n %s %s' % i
elif what == 'formatter':
print
print 'Formatters:'
print '~~~~~~~~~~~'
info = []
for cls in get_all_formatters():
doc = docstring_headline(cls)
if not cls.filenames or '(filenames ' + ', '.join(cls.filenames) + ')':
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None
if '-g' in opts:
try:
lexer = guess_lexer(code)
except ClassNotFound:
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None
opts.pop('-h', None) is not None
lexer = TextLexer()
except:
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None<EXCEPTION MATCH>ClassNotFound
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None<EXCEPTION MATCH>ClassNotFound
print >>sys.stderr, 'Error:', err
return 1
except OptionError:
len(args) > 1
err = len(args) > 1
len(args) > 1
print >>sys.stderr, 'Error:', err
return 1
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None
len(args) > 1<EXCEPTION MATCH>ClassNotFound
elif '-g' in opts:
code = sys.stdin.read()
try:
lexer = guess_lexer(code)
except ClassNotFound:
len(args) > 1
len(args) > 1
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None
lexer = TextLexer()
except:
len(args) > 1<EXCEPTION MATCH>ClassNotFound
len(args) > 1
if not lexer:
print >>sys.stderr, 'Error: no lexer name given and reading ' + 'from stdin (try using -g or -l <lexer>)'
return 2
code = sys.stdin.read()
try:
for fname, fopts in F_opts:
lexer.add_filter(fname, **fopts)
highlight(code, lexer, fmter, outfile)
except Exception:
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None if 'encoding' not in parsed_opts and 'outencoding' not in parsed_opts else len(args) > 1
err = opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None if 'encoding' not in parsed_opts and 'outencoding' not in parsed_opts else len(args) > 1
opts.pop('-V', None) is not None if not fmter else opts.pop('-V', None) is not None
import traceback
info = traceback.format_exception(*sys.exc_info())
msg = info[-1].strip()
print >>sys.stderr
print >>sys.stderr, '*** Error while highlighting:'