本文整理汇总了Python中pygments.lexers.TextLexer类的典型用法代码示例。如果您正苦于以下问题:Python TextLexer类的具体用法?Python TextLexer怎么用?Python TextLexer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TextLexer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_line_types
def get_line_types(repo, repo_uri, rev, path):
"""Returns an array, where each item means a line of code.
Each item is labled 'code', 'comment' or 'empty'"""
#profiler_start("Processing LineTypes for revision %s:%s", (self.rev, self.file_path))
uri = os.path.join(repo_uri, path) # concat repo_uri and file_path for full path
file_content = _get_file_content(repo, uri, rev) # get file_content
if file_content is None or file_content == '':
printerr("[get_line_types] Error: No file content for " + str(rev) + ":" + str(path) + " found! Skipping.")
line_types = None
else:
try:
lexer = get_lexer_for_filename(path)
except ClassNotFound:
try:
printdbg("[get_line_types] Guessing lexer for" + str(rev) + ":" + str(path) + ".")
lexer = guess_lexer(file_content)
except ClassNotFound:
printdbg("[get_line_types] No guess or lexer found for " + str(rev) + ":" + str(path) + ". Using TextLexer instead.")
lexer = TextLexer()
if isinstance(lexer, NemerleLexer):
# this lexer is broken and yield an unstoppable process
# see https://bitbucket.org/birkenfeld/pygments-main/issue/706/nemerle-lexer-ends-in-an-infinite-loop
lexer = TextLexer()
# Not shure if this should be skipped, when the language uses off-side rules (e.g. python,
# see http://en.wikipedia.org/wiki/Off-side_rule for list)
stripped_code = _strip_lines(file_content)
lexer_output = _iterate_lexer_output(lexer.get_tokens(stripped_code))
line_types_str = _comment_empty_or_code(lexer_output)
line_types = line_types_str.split("\n")
return line_types
示例2: print_lines
def print_lines(console_printer,
file_dict,
sourcerange):
"""
Prints the lines between the current and the result line. If needed
they will be shortened.
:param console_printer: Object to print messages on the console.
:param file_dict: A dictionary containing all files as values with
filenames as key.
:param sourcerange: The SourceRange object referring to the related
lines to print.
"""
no_color = not console_printer.print_colored
for i in range(sourcerange.start.line, sourcerange.end.line + 1):
# Print affected file's line number in the sidebar.
console_printer.print(format_lines(lines='', line_nr=i, symbol='['),
color=FILE_LINES_COLOR,
end='')
line = file_dict[sourcerange.file][i - 1].rstrip('\n')
try:
lexer = get_lexer_for_filename(sourcerange.file)
except ClassNotFound:
lexer = TextLexer()
lexer.add_filter(VisibleWhitespaceFilter(
spaces=True, tabs=True,
tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
# highlight() combines lexer and formatter to output a ``str``
# object.
printed_chars = 0
if i == sourcerange.start.line and sourcerange.start.column:
console_printer.print(highlight_text(
no_color, line[:sourcerange.start.column - 1],
BackgroundMessageStyle, lexer), end='')
printed_chars = sourcerange.start.column - 1
if i == sourcerange.end.line and sourcerange.end.column:
console_printer.print(highlight_text(
no_color, line[printed_chars:sourcerange.end.column - 1],
BackgroundSourceRangeStyle, lexer), end='')
console_printer.print(highlight_text(
no_color, line[sourcerange.end.column - 1:],
BackgroundSourceRangeStyle, lexer), end='')
console_printer.print('')
else:
console_printer.print(highlight_text(
no_color, line[printed_chars:], BackgroundMessageStyle, lexer),
end='')
console_printer.print('')
示例3: setUp
def setUp(self):
self.log_printer = ListLogPrinter()
self.console_printer = ConsolePrinter(print_colored=False)
self.no_color = not self.console_printer.print_colored
self.file_diff_dict = {}
self.section = Section('t')
self.local_bears = OrderedDict([('default', [SomelocalBear]),
('test', [SomelocalBear])])
self.global_bears = OrderedDict([('default', [SomeglobalBear]),
('test', [SomeglobalBear])])
self.old_open_editor_applicable = OpenEditorAction.is_applicable
OpenEditorAction.is_applicable = staticmethod(
lambda *args: 'OpenEditorAction cannot be applied')
self.old_apply_patch_applicable = ApplyPatchAction.is_applicable
ApplyPatchAction.is_applicable = staticmethod(
lambda *args: 'ApplyPatchAction cannot be applied')
self.lexer = TextLexer()
self.lexer.add_filter(VisibleWhitespaceFilter(
spaces=True,
tabs=True,
tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
patcher = patch('coalib.results.result_actions.OpenEditorAction.'
'subprocess')
self.addCleanup(patcher.stop)
patcher.start()
示例4: run
def run(self):
self.assert_has_content()
try:
lexer = get_lexer_by_name(self.arguments[0])
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
lexer.add_filter(ctypes_types_highlighter)
lexer.add_filter(custom_highlighters)
# take an arbitrary option if more than one is given
formatter = self.options and \
VARIANTS[self.options.keys()[0]] or \
DEFAULT
print >>open('pygments.css', 'w'), formatter.get_style_defs('.highlight')
parsed = highlight(u'\n'.join(self.content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
示例5: _parse_src
def _parse_src(cls, src_contents, src_filename):
"""
Return a stream of `(token_type, value)` tuples
parsed from `src_contents` (str)
Uses `src_filename` to guess the type of file
so it can highlight syntax correctly.
"""
# Parse the source into tokens
try:
lexer = guess_lexer_for_filename(src_filename, src_contents)
except ClassNotFound:
lexer = TextLexer()
# Ensure that we don't strip newlines from
# the source file when lexing.
lexer.stripnl = False
return pygments.lex(src_contents, lexer)
示例6: setUp
def setUp(self):
self.log_printer = LogPrinter(ConsolePrinter(print_colored=False))
self.console_printer = ConsolePrinter(print_colored=False)
self.file_diff_dict = {}
self.section = Section("t")
self.local_bears = OrderedDict([("default", [SomelocalBear]),
("test", [SomelocalBear])])
self.global_bears = OrderedDict([("default", [SomeglobalBear]),
("test", [SomeglobalBear])])
self.old_open_editor_applicable = OpenEditorAction.is_applicable
OpenEditorAction.is_applicable = staticmethod(lambda *args: False)
self.old_apply_patch_applicable = ApplyPatchAction.is_applicable
ApplyPatchAction.is_applicable = staticmethod(lambda *args: False)
self.lexer = TextLexer()
self.lexer.add_filter(VisibleWhitespaceFilter(
spaces="•",
tabs=True,
tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
示例7: main
def main(args=sys.argv):
"""
Main command line entry point.
"""
# pylint: disable-msg=R0911,R0912,R0915
usage = USAGE % ((args[0],) * 6)
try:
popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHgs")
except getopt.GetoptError:
print(usage, file=sys.stderr)
return 2
opts = {}
O_opts = []
P_opts = []
F_opts = []
for opt, arg in popts:
if opt == "-O":
O_opts.append(arg)
elif opt == "-P":
P_opts.append(arg)
elif opt == "-F":
F_opts.append(arg)
opts[opt] = arg
if opts.pop("-h", None) is not None:
print(usage)
return 0
if opts.pop("-V", None) is not None:
print("Pygments version %s, (c) 2006-2014 by Georg Brandl." % __version__)
return 0
# handle ``pygmentize -L``
L_opt = opts.pop("-L", None)
if L_opt is not None:
if opts:
print(usage, file=sys.stderr)
return 2
# print version
main(["", "-V"])
if not args:
args = ["lexer", "formatter", "filter", "style"]
for arg in args:
_print_list(arg.rstrip("s"))
return 0
# handle ``pygmentize -H``
H_opt = opts.pop("-H", None)
if H_opt is not None:
if opts or len(args) != 2:
print(usage, file=sys.stderr)
return 2
what, name = args
if what not in ("lexer", "formatter", "filter"):
print(usage, file=sys.stderr)
return 2
_print_help(what, name)
return 0
# parse -O options
parsed_opts = _parse_options(O_opts)
opts.pop("-O", None)
# parse -P options
for p_opt in P_opts:
try:
name, value = p_opt.split("=", 1)
except ValueError:
parsed_opts[p_opt] = True
else:
parsed_opts[name] = value
opts.pop("-P", None)
# encodings
inencoding = parsed_opts.get("inencoding", parsed_opts.get("encoding"))
outencoding = parsed_opts.get("outencoding", parsed_opts.get("encoding"))
# handle ``pygmentize -N``
infn = opts.pop("-N", None)
if infn is not None:
try:
lexer = get_lexer_for_filename(infn, **parsed_opts)
except ClassNotFound as err:
lexer = TextLexer()
except OptionError as err:
print("Error:", err, file=sys.stderr)
return 1
print(lexer.aliases[0])
return 0
# handle ``pygmentize -S``
S_opt = opts.pop("-S", None)
a_opt = opts.pop("-a", None)
if S_opt is not None:
#.........这里部分代码省略.........
示例8: ConsoleInteractionTest
class ConsoleInteractionTest(unittest.TestCase):
def setUp(self):
self.log_printer = ListLogPrinter()
self.console_printer = ConsolePrinter(print_colored=False)
self.no_color = not self.console_printer.print_colored
self.file_diff_dict = {}
self.section = Section('t')
self.local_bears = OrderedDict([('default', [SomelocalBear]),
('test', [SomelocalBear])])
self.global_bears = OrderedDict([('default', [SomeglobalBear]),
('test', [SomeglobalBear])])
self.old_open_editor_applicable = OpenEditorAction.is_applicable
OpenEditorAction.is_applicable = staticmethod(
lambda *args: 'OpenEditorAction cannot be applied')
self.old_apply_patch_applicable = ApplyPatchAction.is_applicable
ApplyPatchAction.is_applicable = staticmethod(
lambda *args: 'ApplyPatchAction cannot be applied')
self.lexer = TextLexer()
self.lexer.add_filter(VisibleWhitespaceFilter(
spaces=True,
tabs=True,
tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
def tearDown(self):
OpenEditorAction.is_applicable = self.old_open_editor_applicable
ApplyPatchAction.is_applicable = self.old_apply_patch_applicable
def test_require_settings(self):
curr_section = Section('')
self.assertRaises(TypeError, acquire_settings,
self.log_printer, 0, curr_section)
with simulate_console_inputs(0, 1, 2) as generator:
self.assertEqual(acquire_settings(self.log_printer,
{'setting': ['help text',
'SomeBear']},
curr_section),
{'setting': 0})
self.assertEqual(acquire_settings(self.log_printer,
{'setting': ['help text',
'SomeBear',
'AnotherBear']},
curr_section),
{'setting': 1})
self.assertEqual(acquire_settings(self.log_printer,
{'setting': ['help text',
'SomeBear',
'AnotherBear',
'YetAnotherBear']},
curr_section),
{'setting': 2})
self.assertEqual(generator.last_input, 2)
def test_print_diffs_info(self):
file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']}
diff_dict = {'a': Diff(file_dict['a']),
'b': Diff(file_dict['b'])}
diff_dict['a'].add_lines(1, ['test\n'])
diff_dict['a'].delete_line(3)
diff_dict['b'].add_lines(0, ['first\n'])
previous_diffs = {'a': Diff(file_dict['a'])}
previous_diffs['a'].change_line(2, 'b\n', 'b_changed\n')
with retrieve_stdout() as stdout:
print_diffs_info(diff_dict, self.console_printer)
self.assertEqual(stdout.getvalue(),
'| | +1 -1 in a\n'
'| | +1 -0 in b\n')
@patch('coalib.output.ConsoleInteraction.acquire_actions_and_apply')
@patch('coalib.output.ConsoleInteraction.ShowPatchAction.'
'apply_from_section')
def test_print_result_interactive_small_patch(self, apply_from_section, _):
file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']}
diff_dict = {'a': Diff(file_dict['a']),
'b': Diff(file_dict['b'])}
diff_dict['a'].add_lines(1, ['test\n'])
diff_dict['a'].delete_line(3)
result = Result('origin', 'msg', diffs=diff_dict)
section = Section('test')
print_result(self.console_printer,
section,
self.file_diff_dict,
result,
file_dict,
True)
apply_from_section.assert_called_once_with(
result, file_dict, self.file_diff_dict, section)
@patch('coalib.output.ConsoleInteraction.acquire_actions_and_apply')
@patch('coalib.output.ConsoleInteraction.print_diffs_info')
def test_print_result_interactive_big_patch(self, diffs_info, _):
file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']}
#.........这里部分代码省略.........
示例9: file
infn = args[0]
try:
code = file(infn).read()
except Exception, err:
print >>sys.stderr, 'Error: cannot read infile:', err
return 1
if not lexer:
try:
lexer = get_lexer_for_filename(infn, **parsed_opts)
except ClassNotFound, err:
if '-g' in opts:
try:
lexer = guess_lexer(code)
except ClassNotFound:
lexer = TextLexer()
else:
print >>sys.stderr, 'Error:', err
return 1
except OptionError, err:
print >>sys.stderr, 'Error:', err
return 1
else:
if '-g' in opts:
code = sys.stdin.read()
try:
lexer = guess_lexer(code)
except ClassNotFound:
lexer = TextLexer()
elif not lexer:
示例10: main
def main(args=sys.argv):
"""
Main command line entry point.
"""
# pylint: disable-msg=R0911,R0912,R0915
usage = USAGE % ((args[0],) * 6)
if sys.platform in ['win32', 'cygwin']:
try:
# Provide coloring under Windows, if possible
import colorama
colorama.init()
except ImportError:
pass
try:
popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
except getopt.GetoptError:
print(usage, file=sys.stderr)
return 2
opts = {}
O_opts = []
P_opts = []
F_opts = []
for opt, arg in popts:
if opt == '-O':
O_opts.append(arg)
elif opt == '-P':
P_opts.append(arg)
elif opt == '-F':
F_opts.append(arg)
opts[opt] = arg
if not opts and not args:
print(usage)
return 0
if opts.pop('-h', None) is not None:
print(usage)
return 0
if opts.pop('-V', None) is not None:
print('Pygments version %s, (c) 2006-2014 by Georg Brandl.' % __version__)
return 0
# handle ``pygmentize -L``
L_opt = opts.pop('-L', None)
if L_opt is not None:
if opts:
print(usage, file=sys.stderr)
return 2
# print version
main(['', '-V'])
if not args:
args = ['lexer', 'formatter', 'filter', 'style']
for arg in args:
_print_list(arg.rstrip('s'))
return 0
# handle ``pygmentize -H``
H_opt = opts.pop('-H', None)
if H_opt is not None:
if opts or len(args) != 2:
print(usage, file=sys.stderr)
return 2
what, name = args
if what not in ('lexer', 'formatter', 'filter'):
print(usage, file=sys.stderr)
return 2
_print_help(what, name)
return 0
# parse -O options
parsed_opts = _parse_options(O_opts)
opts.pop('-O', None)
# parse -P options
for p_opt in P_opts:
try:
name, value = p_opt.split('=', 1)
except ValueError:
parsed_opts[p_opt] = True
else:
parsed_opts[name] = value
opts.pop('-P', None)
# handle ``pygmentize -N``
infn = opts.pop('-N', None)
if infn is not None:
try:
lexer = get_lexer_for_filename(infn, **parsed_opts)
except ClassNotFound as err:
lexer = TextLexer()
except OptionError as err:
print('Error:', err, file=sys.stderr)
return 1
#.........这里部分代码省略.........
示例11: len
args = sys.argv[1:]
if len(args) == 1:
filename = args[0]
content = codecs.open(args[0], "r", "utf-8").read()
elif len(args) == 2:
filename = args[0]
assert args[1] == "-"
content = sys.stdin.read()
# Cheesy hack for override some false guesses by Pygments.
# A better answer might be to look at lexing errors and try a secondary
# guess.
overrides = {"Makefile.py": ".py"}
basename = basename(filename)
try:
lexer = get_lexer_for_filename(overrides.get(basename, filename), content)
except ClassNotFound:
try:
lexer = guess_lexer(content)
except ClassNotFound:
lexer = TextLexer()
sys.stderr.write("lexer: %r\n" % lexer)
fmter = get_formatter_by_name("html")
fmter.encoding = "utf-8"
lexer.encoding = "utf-8"
outfile = sys.stdout
highlight(content, lexer, fmter, outfile)
示例12: get_lexer_for_filename
for p_opt in P_opts:
try:
name, value = p_opt.split("=", 1)
except ValueError:
parsed_opts[p_opt] = True
else:
parsed_opts[name] = value
opts.pop("-P", None)
# handle ``pygmentize -N``
infn = opts.pop("-N", None)
if infn is not None:
try:
lexer = get_lexer_for_filename(infn, **parsed_opts)
except ClassNotFound, err:
lexer = TextLexer()
except OptionError, err:
print >> sys.stderr, "Error:", err
return 1
print lexer.aliases[0]
return 0
# handle ``pygmentize -S``
S_opt = opts.pop("-S", None)
a_opt = opts.pop("-a", None)
if S_opt is not None:
f_opt = opts.pop("-f", None)
if not f_opt:
print >> sys.stderr, usage
return 2
示例13: ConsoleInteractionTest
class ConsoleInteractionTest(unittest.TestCase):
def setUp(self):
self.log_printer = LogPrinter(ConsolePrinter(print_colored=False))
self.console_printer = ConsolePrinter(print_colored=False)
self.file_diff_dict = {}
self.section = Section("t")
self.local_bears = OrderedDict([("default", [SomelocalBear]),
("test", [SomelocalBear])])
self.global_bears = OrderedDict([("default", [SomeglobalBear]),
("test", [SomeglobalBear])])
self.old_open_editor_applicable = OpenEditorAction.is_applicable
OpenEditorAction.is_applicable = staticmethod(lambda *args: False)
self.old_apply_patch_applicable = ApplyPatchAction.is_applicable
ApplyPatchAction.is_applicable = staticmethod(lambda *args: False)
self.lexer = TextLexer()
self.lexer.add_filter(VisibleWhitespaceFilter(
spaces="•",
tabs=True,
tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
def tearDown(self):
OpenEditorAction.is_applicable = self.old_open_editor_applicable
ApplyPatchAction.is_applicable = self.old_apply_patch_applicable
def test_require_settings(self):
self.assertRaises(TypeError, acquire_settings, self.log_printer, 0)
with simulate_console_inputs(0, 1, 2) as generator:
self.assertEqual(acquire_settings(self.log_printer,
{"setting": ["help text",
"SomeBear"]}),
{"setting": 0})
self.assertEqual(acquire_settings(self.log_printer,
{"setting": ["help text",
"SomeBear",
"AnotherBear"]}),
{"setting": 1})
self.assertEqual(acquire_settings(self.log_printer,
{"setting": ["help text",
"SomeBear",
"AnotherBear",
"YetAnotherBear"]}),
{"setting": 2})
self.assertEqual(generator.last_input, 2)
def test_print_diffs_info(self):
file_dict = {"a": ["a\n", "b\n", "c\n"], "b": ["old_first\n"]}
diff_dict = {"a": Diff(file_dict['a']),
"b": Diff(file_dict['b'])}
diff_dict["a"].add_lines(1, ["test\n"])
diff_dict["a"].delete_line(3)
diff_dict["b"].add_lines(0, ["first\n"])
previous_diffs = {"a": Diff(file_dict['a'])}
previous_diffs["a"].change_line(2, "b\n", "b_changed\n")
with retrieve_stdout() as stdout:
print_diffs_info(diff_dict, self.console_printer)
self.assertEqual(stdout.getvalue(),
"| | +1 -1 in a\n"
"| | +1 -0 in b\n")
@patch("coalib.output.ConsoleInteraction.acquire_actions_and_apply")
@patch("coalib.output.ConsoleInteraction.ShowPatchAction."
"apply_from_section")
def test_print_result_interactive_small_patch(self, apply_from_section, _):
file_dict = {"a": ["a\n", "b\n", "c\n"], "b": ["old_first\n"]}
diff_dict = {"a": Diff(file_dict['a']),
"b": Diff(file_dict['b'])}
diff_dict["a"].add_lines(1, ["test\n"])
diff_dict["a"].delete_line(3)
result = Result("origin", "msg", diffs=diff_dict)
section = Section("test")
print_result(self.console_printer,
self.log_printer,
section,
self.file_diff_dict,
result,
file_dict,
True)
apply_from_section.assert_called_once_with(
result, file_dict, self.file_diff_dict, section)
@patch("coalib.output.ConsoleInteraction.acquire_actions_and_apply")
@patch("coalib.output.ConsoleInteraction.print_diffs_info")
def test_print_result_interactive_big_patch(self, diffs_info, _):
file_dict = {"a": ["a\n", "b\n", "c\n"], "b": ["old_first\n"]}
diff_dict = {"a": Diff(file_dict['a']),
"b": Diff(file_dict['b'])}
diff_dict["a"].add_lines(1, ["test\n", "test1\n", "test2\n"])
diff_dict["a"].delete_line(3)
diff_dict["a"].add_lines(3, ["3test\n"])
result = Result("origin", "msg", diffs=diff_dict)
section = Section("test")
#.........这里部分代码省略.........
示例14: main_inner
def main_inner(popts, args, usage):
opts = {}
O_opts = []
P_opts = []
F_opts = []
for opt, arg in popts:
if opt == '-O':
O_opts.append(arg)
elif opt == '-P':
P_opts.append(arg)
elif opt == '-F':
F_opts.append(arg)
opts[opt] = arg
if opts.pop('-h', None) is not None:
print(usage)
return 0
if opts.pop('-V', None) is not None:
print('Pygments version %s, (c) 2006-2014 by Georg Brandl.' % __version__)
return 0
# handle ``pygmentize -L``
L_opt = opts.pop('-L', None)
if L_opt is not None:
if opts:
print(usage, file=sys.stderr)
return 2
# print version
main(['', '-V'])
if not args:
args = ['lexer', 'formatter', 'filter', 'style']
for arg in args:
_print_list(arg.rstrip('s'))
return 0
# handle ``pygmentize -H``
H_opt = opts.pop('-H', None)
if H_opt is not None:
if opts or len(args) != 2:
print(usage, file=sys.stderr)
return 2
what, name = args
if what not in ('lexer', 'formatter', 'filter'):
print(usage, file=sys.stderr)
return 2
return _print_help(what, name)
# parse -O options
parsed_opts = _parse_options(O_opts)
opts.pop('-O', None)
# parse -P options
for p_opt in P_opts:
try:
name, value = p_opt.split('=', 1)
except ValueError:
parsed_opts[p_opt] = True
else:
parsed_opts[name] = value
opts.pop('-P', None)
# encodings
inencoding = parsed_opts.get('inencoding', parsed_opts.get('encoding'))
outencoding = parsed_opts.get('outencoding', parsed_opts.get('encoding'))
# handle ``pygmentize -N``
infn = opts.pop('-N', None)
if infn is not None:
lexer = find_lexer_class_for_filename(infn)
if lexer is None:
lexer = TextLexer
print(lexer.aliases[0])
return 0
# handle ``pygmentize -S``
S_opt = opts.pop('-S', None)
a_opt = opts.pop('-a', None)
if S_opt is not None:
f_opt = opts.pop('-f', None)
if not f_opt:
print(usage, file=sys.stderr)
return 2
if opts or args:
print(usage, file=sys.stderr)
return 2
try:
parsed_opts['style'] = S_opt
fmter = get_formatter_by_name(f_opt, **parsed_opts)
except ClassNotFound as err:
print(err, file=sys.stderr)
return 1
print(fmter.get_style_defs(a_opt or ''))
return 0
#.........这里部分代码省略.........
示例15: main
def main(args=sys.argv):
"""
Main command line entry point.
"""
# pylint: disable-msg=R0911,R0912,R0915
usage = USAGE % ((args[0],) * 6)
if sys.platform in ["win32", "cygwin"]:
try:
# Provide coloring under Windows, if possible
import colorama
colorama.init()
except ImportError:
pass
try:
popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
except getopt.GetoptError as err:
print(usage, file=sys.stderr)
return 2
opts = {}
O_opts = []
P_opts = []
F_opts = []
for opt, arg in popts:
if opt == "-O":
O_opts.append(arg)
elif opt == "-P":
P_opts.append(arg)
elif opt == "-F":
F_opts.append(arg)
opts[opt] = arg
if not opts and not args:
print(usage)
return 0
if opts.pop("-h", None) is not None:
print(usage)
return 0
if opts.pop("-V", None) is not None:
print("Pygments version %s, (c) 2006-2013 by Georg Brandl." % __version__)
return 0
# handle ``pygmentize -L``
L_opt = opts.pop("-L", None)
if L_opt is not None:
if opts:
print(usage, file=sys.stderr)
return 2
# print version
main(["", "-V"])
if not args:
args = ["lexer", "formatter", "filter", "style"]
for arg in args:
_print_list(arg.rstrip("s"))
return 0
# handle ``pygmentize -H``
H_opt = opts.pop("-H", None)
if H_opt is not None:
if opts or len(args) != 2:
print(usage, file=sys.stderr)
return 2
what, name = args
if what not in ("lexer", "formatter", "filter"):
print(usage, file=sys.stderr)
return 2
_print_help(what, name)
return 0
# parse -O options
parsed_opts = _parse_options(O_opts)
opts.pop("-O", None)
# parse -P options
for p_opt in P_opts:
try:
name, value = p_opt.split("=", 1)
except ValueError:
parsed_opts[p_opt] = True
else:
parsed_opts[name] = value
opts.pop("-P", None)
# handle ``pygmentize -N``
infn = opts.pop("-N", None)
if infn is not None:
try:
lexer = get_lexer_for_filename(infn, **parsed_opts)
except ClassNotFound as err:
lexer = TextLexer()
except OptionError as err:
print("Error:", err, file=sys.stderr)
#.........这里部分代码省略.........