diff options
author | Georg Brandl <georg@python.org> | 2021-01-17 11:18:17 +0100 |
---|---|---|
committer | Georg Brandl <georg@python.org> | 2021-01-17 11:18:17 +0100 |
commit | b4594169025485f7d64d5ffd71f42673e7a5972d (patch) | |
tree | e5307a559bfde2a5f317d416180193acf86980f4 | |
parent | 7e6dbb20ce189022f1b0a058f44bd1c0b9d529a5 (diff) | |
download | pygments-git-b4594169025485f7d64d5ffd71f42673e7a5972d.tar.gz |
Added `pygmentize -C` option to guess a lexer from content
-rw-r--r-- | CHANGES | 2 | ||||
-rw-r--r-- | pygments/cmdline.py | 20 | ||||
-rw-r--r-- | tests/test_cmdline.py | 7 |
3 files changed, 27 insertions, 2 deletions
@@ -11,6 +11,8 @@ Version 2.8.0 ------------- (not released yet) +- Added `pygmentize -C` option to guess a lexer from content + - Fix escapes in JavaScript backtick strings (#1679) - Make guessing prefer Python 3 lexer - Do not guess MIME or SQL without reason diff --git a/pygments/cmdline.py b/pygments/cmdline.py index 6a8a307a..cbd9d552 100644 --- a/pygments/cmdline.py +++ b/pygments/cmdline.py @@ -37,6 +37,7 @@ Usage: %s [-l <lexer> | -g] [-F <filter>[:<options>]] [-f <formatter>] %s -S <style> -f <formatter> [-a <arg>] [-O <options>] [-P <option=value>] %s -L [<which> ...] %s -N <filename> + %s -C %s -H <type> <name> %s -h | -V @@ -92,6 +93,9 @@ The -N option guesses and prints out a lexer name based solely on the given filename. It does not take input or highlight anything. If no specific lexer can be determined "text" is returned. +The -C option is like -N, but prints out a lexer name based solely on +a given content from standard input. + The -H option prints detailed help for the object <name> of type <type>, where <type> is one of "lexer", "formatter" or "filter". @@ -292,6 +296,18 @@ def main_inner(popts, args, usage): print(lexer.aliases[0]) return 0 + # handle ``pygmentize -C`` + infc = opts.pop('-C', None) + if infc is not None: + inp = sys.stdin.buffer.read() + try: + lexer = guess_lexer(inp, inencoding=inencoding) + except ClassNotFound: + lexer = TextLexer + + print(lexer.aliases[0]) + return 0 + # handle ``pygmentize -S`` S_opt = opts.pop('-S', None) a_opt = opts.pop('-a', None) @@ -545,10 +561,10 @@ def main(args=sys.argv): """ Main command line entry point. """ - usage = USAGE % ((args[0],) * 6) + usage = USAGE % ((args[0],) * 7) try: - popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:vhVHgsx") + popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:CvhVHgsx") except getopt.GetoptError: print(usage, file=sys.stderr) return 2 diff --git a/tests/test_cmdline.py b/tests/test_cmdline.py index d740fccb..731729d9 100644 --- a/tests/test_cmdline.py +++ b/tests/test_cmdline.py @@ -220,6 +220,13 @@ def test_N_opt(): assert 'text' == o.strip() +def test_C_opt(): + o = check_success('-C', stdin='#!python3\n') + assert 'python' == o.strip() + o = check_success('-C', stdin='x') + assert 'text' == o.strip() + + def test_invalid_opts(): for opts in [ ('-X',), |