Anonymous committed c97ce1d

#372: add -N option to guess lexer name based on file name.

  • Participants
  • Parent commits aeb0be1
  • Branches trunk

Comments (0)

Files changed (3)

   because that doesn't keep all newlines at the end when the
   ``stripnl`` lexer option is False.
+- Add ``-N`` option to command-line interface to get a lexer name
+  for a given filename.
 - Add Tango style, written by Andre Roberge for the Crunchy project.
 - Add Python3TracebackLexer and ``python3`` option to 

File docs/src/cmdline.txt

     $ pygmentize -o test.html
 Options and filters
 the `arg` argument for the formatter's `get_style_defs()` method.
+Getting lexer names
+*New in Pygments 1.0.*
+The ``-N`` option guesses a lexer name for a given filename, so that ::
+    $ pygmentize -N
+will print out ``python``.  It won't highlight anything yet.  If no specific
+lexer is known for that filename, ``text`` is printed.
 Getting help

File pygments/

        %s -S <style> -f <formatter> [-a <arg>] [-O <options>] [-P <option=value>]
        %s -L [<which> ...]
+       %s -N <filename>
        %s -H <type> <name>
        %s -h | -V
 `which` to the thing you want to list (e.g. "styles"), or omit it to
 list everything.
+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 -H option prints detailed help for the object <name> of type <type>,
 where <type> is one of "lexer", "formatter" or "filter".
     # pylint: disable-msg=R0911,R0912,R0915
-    usage = USAGE % ((args[0],) * 5)
+    usage = USAGE % ((args[0],) * 6)
-        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:hVHg")
+        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
     except getopt.GetoptError, err:
         print >>sys.stderr, usage
         return 2
             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)