Anonymous avatar Anonymous committed 1864bff

[svn] Use the Punctuation token type everywhere.

Comments (0)

Files changed (8)

 - tell the PHP and DelphiLexer how to differ between Operators and
   text.
 
-- add a `Punctuation` token type for symbols that are not text
-  but also not a symbol (blocks in ruby etc)
-
 - add support for function name highlighting to c++ lexer
 
 - readd property support for C# lexer

pygments/cmdline.py

      get_formatter_for_filename, TerminalFormatter
 
 
-def main(args):
-    """
-    Main command line entry point.
-    """
-
-    USAGE = """\
+USAGE = """\
 Usage: %s [-l <lexer>] [-f <formatter>] [-O <options>] [-o <outfile>] [<infile>]
        %s -S <style> -f <formatter> [-a <arg>] [-O <options>]
        %s -L | -h | -V
 The -L option lists all available lexers and formatters.
 The -h option prints this help.
 The -V option prints the package version.
-""" % ((args[0],)*3)
+"""
+
+
+def _parse_options(o_str):
+    opts = {}
+    if not o_str:
+        return opts
+    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:
+            O_opts[o_arg] = True
+        else:
+            O_opts[o_key] = o_val
+    return opts
+
+
+def _print_lflist():
+    # print version
+    main(['', '-V'])
+
+    print
+    print "Lexers:"
+    print "~~~~~~~"
+
+    info = []
+    maxlen = 0
+    for _, fullname, names, exts, _ in LEXERS.itervalues():
+        tup = (', '.join(names)+':', fullname,
+               exts and '(extensions ' + ', '.join(exts) + ')' or '')
+        info.append(tup)
+        if len(tup[0]) > maxlen: maxlen = len(tup[0])
+    info.sort()
+    for i in info:
+        print ('%-'+str(maxlen)+'s %s %s') % i
+
+    print
+    print "Formatters:"
+    print "~~~~~~~~~~~"
+
+    info = []
+    maxlen = 0
+    for fullname, names, exts, doc in FORMATTERS.itervalues():
+        tup = (', '.join(names)+':', doc,
+               exts and '(extensions ' + ', '.join(exts) + ')' or '')
+        info.append(tup)
+        if len(tup[0]) > maxlen: maxlen = len(tup[0])
+    info.sort()
+    for i in info:
+        print ('%-'+str(maxlen)+'s %s %s') % i
+
+
+def main(args):
+    """
+    Main command line entry point.
+    """
+    usage = USAGE % ((args[0],) * 3)
 
     try:
         opts, args = getopt.getopt(args[1:], "l:f:o:O:LhVS:a:")
     except getopt.GetoptError:
-        print >>sys.stderr, USAGE
+        print >>sys.stderr, usage
         return 2
     opts = dict(opts)
 
     if not opts and not args:
-        print USAGE
+        print usage
         return 0
 
     if opts.pop('-h', None) is not None:
-        print USAGE
+        print usage
         return 0
 
     if opts.pop('-V', None) is not None:
         print 'Pygments version %s, (c) 2006 by %s.' % (__version__, __author__)
         return 0
 
+    # handle ``pygmentize -L``
     L_opt = opts.pop('-L', None)
     if L_opt is not None:
         if opts or args:
-            print >>sys.stderr, USAGE
+            print >>sys.stderr, usage
             return 2
 
-        # print version
-        main(['', '-V'])
-        print
-        print "Lexers:"
-        print "~~~~~~~"
-
-        info = []
-        maxlen = 0
-        for _, fullname, names, exts, _ in LEXERS.itervalues():
-            tup = (', '.join(names)+':', fullname,
-                   exts and '(extensions ' + ', '.join(exts) + ')' or '')
-            info.append(tup)
-            if len(tup[0]) > maxlen: maxlen = len(tup[0])
-        info.sort()
-        for i in info:
-            print ('%-'+str(maxlen)+'s %s %s') % i
-
-        print
-        print "Formatters:"
-        print "~~~~~~~~~~~"
-
-        info = []
-        maxlen = 0
-        for fullname, names, exts, doc in FORMATTERS.itervalues():
-            tup = (', '.join(names)+':', doc,
-                   exts and '(extensions ' + ', '.join(exts) + ')' or '')
-            info.append(tup)
-            if len(tup[0]) > maxlen: maxlen = len(tup[0])
-        info.sort()
-        for i in info:
-            print ('%-'+str(maxlen)+'s %s %s') % i
+        _print_lflist()
         return 0
 
-    O_opts = {}
-    o_str = opts.pop('-O', None)
-    if o_str:
-        try:
-            o_args = o_str.split(',')
-            for o_arg in o_args:
-                try:
-                    o_key, o_val = o_arg.split('=')
-                except ValueError:
-                    O_opts[o_arg] = True
-                else:
-                    O_opts[o_key] = o_val
-        except ValueError:
-            print >>sys.stderr, 'Error in -O specification.'
-            return 2
+    # parse -O options
+    O_opts = _parse_options(opts.pop('-O', None))
 
+    # 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
+            print >>sys.stderr, usage
             return 2
         if opts or args:
-            print >>sys.stderr, USAGE
+            print >>sys.stderr, usage
             return 2
 
         try:
         print fmter.get_style_defs(arg)
         return 0
 
+    # if no -S is given, -a is not allowed
     if a_opt is not None:
-        print >>sys.stderr, USAGE
+        print >>sys.stderr, usage
         return 2
 
+    # select formatter
     outfn = opts.pop('-o', None)
     fmter = opts.pop('-f', None)
     if fmter:
             fmter = TerminalFormatter(**O_opts)
         outfile = sys.stdout
 
+    # select lexer
     lexer = opts.pop('-l', None)
     if lexer:
         try:
             return 1
 
     if args:
+        if len(args) > 1:
+            print >>sys.stderr, usage
+            return 2
+
         infn = args[0]
         if not lexer:
             try:
             return 2
         code = sys.stdin.read()
 
+    # ... and do it!
     try:
         highlight(code, lexer, fmter, outfile)
     except Exception, err:
         print >>sys.stderr, 'Error while highlighting:'
         print >>sys.stderr, traceback.format_exc(0).splitlines()[-1]
         return 1
+
     return 0

pygments/lexers/agile.py

             (r'(\[\]|\*\*|::|<<|>>|>=|<=|<=>|={3}|!=|=~|'
              r'!~|&&?|\|\||\.{1,3})', Operator),
             (r'[-+/*%=<>&^|!\\~]=?', Operator),
-            (r'[\(\)\[\]:;,<>/\?\{\}]', Text),
+            (r'[\(\)\[\]:;,<>/\?\{\}]', Punctuation), # yes, there's no shortage
+                                                      # of punctuation in Perl!
             (r'(?=\w)', Name, 'name'),
         ],
         'varname': [
             (r'\s+', Text),
-            (r'\{', Text, '#pop'), # hash syntax?
-            (r'\)|,', Text, '#pop'), # argument specifier
+            (r'\{', Punctuation, '#pop'), # hash syntax?
+            (r'\)|,', Punctuation, '#pop'), # argument specifier
             (r'[a-zA-Z0-9_]+::', Name.Namespace),
             (r'[a-zA-Z0-9_:]+', Name.Variable, '#pop'),
         ],
             (r'[a-zA-Z_][\w_]*[\!\?]?', Name.Function),
             (r'\s+', Text),
             # argument declaration
-            (r'\([$@%]*\)\s*', Text),
-            (r'.*?{', Text, '#pop'),
+            (r'(\([$@%]*\))(\s*)', bygroups(Punctuation, Text)),
+            (r'.*?{', Punctuation, '#pop'),
         ],
         'cb-string': [
             (r'\\[\{\}\\]', String.Other),
 
             (r'\n', Text),
             (r'[^\S\n]', Text),
-            (r'[\[\]\{\}\(\)\.,:;]', Text),
+            (r'[\[\]\{\}\(\)\.,:;]', Punctuation),
 
             (r'(==|~=|<=|>=|\.\.|\.\.\.|[=+\-*/%^<>#])', Operator),
             (r'(and|or|not)\b', Operator.Word),
         'funcname': [
             ('[A-Za-z_][A-Za-z0-9_]*', Name.Function, '#pop'),
             # inline function
-            ('\(', Text, '#pop'),
+            ('\(', Punctuation, '#pop'),
         ],
 
         'classname': [
                 elif '.' in value:
                     a, b = value.split('.')
                     yield index, Name, a
-                    yield index + len(a), Text, u'.'
+                    yield index + len(a), Punctuation, u'.'
                     yield index + len(a) + 1, Name, b
                     continue
             yield index, token, value
 
+
 class SchemeLexer(RegexLexer):
     """
     A Scheme lexer, parsing a stream and outputting the tokens

pygments/lexers/compiled.py

             (r'0[0-7]+[Ll]?', Number.Oct),
             (r'(\d+\.\d*|\.\d+)', Number.Float),
             (r'\d+', Number.Integer),
-            (r'[~!%^&*()+=|\[\]:,.<>/?-]', Text),
+            (r'[~!%^&*()+=|\[\]:,.<>/?-]', Punctuation), # missing: Operators
             (r'(auto|break|case|const|continue|default|do|else|enum|extern|'
              r'for|goto|if|register|restricted|return|sizeof|static|struct|'
              r'switch|typedef|union|volatile|virtual|while)\b', Keyword),
              r'([a-zA-Z_][a-zA-Z0-9_]*)'             # method name
              r'(\s*\([^;]*?\))'                      # signature
              r'(' + _ws + r')(;)',
-             bygroups(using(this), Name.Function, using(this), Text, Text)),
+             bygroups(using(this), Name.Function, using(this), Text, Punctuation)),
             ('', Text, 'statement'),
         ],
         'statement' : [
             include('whitespace'),
             include('statements'),
             ('[{}]', Keyword),
-            (';', Text, '#pop'),
+            (';', Punctuation, '#pop'),
         ],
         'function': [
             include('whitespace'),
             include('statements'),
-            (';', Text),
+            (';', Punctuation),
             ('{', Keyword, '#push'),
             ('}', Keyword, '#pop'),
         ],
             (r'0[0-7]+[Ll]?', Number.Oct),
             (r'(\d+\.\d*|\.\d+)', Number.Float),
             (r'\d+', Number.Integer),
-            (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Text),
+            (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
             (r'(asm|auto|break|case|catch|const|const_cast|continue|'
              r'default|delete|do|dynamic_cast|else|enum|explicit|export|'
              r'extern|for|friend|goto|if|mutable|namespace|new|operator|'

pygments/lexers/dotnet.py

 import re
 
 from pygments.lexer import RegexLexer, bygroups, using, this
-from pygments.token import \
+from pygments.token import Punctuation, \
      Text, Comment, Operator, Keyword, Name, String, Number, Literal
 
 __all__ = ['CSharpLexer', 'BooLexer', 'VbNetLexer']
             (r'//.*?\n', Comment),
             (r'/[*](.|\n)*?[*]/', Comment),
             (r'\n', Text),
-            (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Text),
+            (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
             (r'[{}]', Keyword),
             (r'@"(\\\\|\\"|[^"])*"', String),
             (r'"(\\\\|\\"|[^"\n])*["\n]', String),
             (r'\s+', Text),
             (r'(#|//).*$', Comment),
             (r'/[*]', Comment, 'comment'),
-            (r'[]{}:(),.;[]', Text),
+            (r'[]{}:(),.;[]', Punctuation),
             (r'\\\n', Text),
             (r'\\', Text),
             (r'(in|is|and|or|not)\b', Operator.Word),
              r'#ExternalSource.*?\n|#End\s+ExternalSource|'
              r'#Region.*?\n|#End\s+Region|#ExternalChecksum',
              Comment.Preproc),
-            (r'[\(\){}!#,.:]', Text),
+            (r'[\(\){}!#,.:]', Punctuation),
             (r'Option\s+(Strict|Explicit|Compare)\s+'
              r'(On|Off|Binary|Text)', Keyword.Declaration),
             (r'(?<!\.)(AddHandler|Alias|'

pygments/lexers/other.py

 import re
 
 from pygments.lexer import RegexLexer, include, bygroups, using
-from pygments.token import Error, \
+from pygments.token import Error, Punctuation, \
      Text, Comment, Operator, Keyword, Name, String, Number
 from pygments.util import shebang_matches
 
             (r'[0-9]+', Number.Integer),
             (r"'(''|[^'])*'", String),
             (r'[a-zA-Z_][a-zA-Z0-9_]*', Name),
-            (r'[;:()\[\],\.]', Text)
+            (r'[;:()\[\],\.]', Punctuation)
         ],
         'multiline-comments': [
             (r'/\*', Comment.Multiline, 'multiline-comments'),
         'curly': [
             (r'}', Keyword, '#pop'),
             (r':-', Keyword),
-            (r'[^}:]+', Text),
-            (r':', Text),
+            (r'[^}:]+', Punctuation),
+            (r':', Punctuation),
         ],
         'paren': [
             (r'\)', Keyword, '#pop'),
-            (r'[^)]*', Text),
+            (r'[^)]*', Punctuation),
         ],
     }
 

pygments/lexers/templates.py

 from pygments.lexers.agile import PythonLexer
 from pygments.lexer import Lexer, DelegatingLexer, RegexLexer, bygroups, \
      include, using, this
-from pygments.token import Error, \
+from pygments.token import Error, Punctuation, \
      Text, Comment, Operator, Keyword, Name, String, Number, Other
 from pygments.util import html_doctype_matches, looks_like_xml
 
              Keyword),
             include('varnames'),
             (r'\%\}', Comment.Preproc, '#pop'),
-            (r'.', Text)
+            (r'.', Punctuation)
         ]
     }
 

pygments/lexers/text.py

 import re
 
 from pygments.lexer import RegexLexer, bygroups, include
-from pygments.token import \
+from pygments.token import Punctuation, \
     Text, Comment, Keyword, Name, String, Generic, Operator, Number
 
 
         ],
         'block-header': [
             (r'[^,\n]', String),
-            (r',', Text),
+            (r',', Punctuation),
             (r'\n[\t ]+', Text, 'block'),
             (r'\n', Text, '#pop')
         ],
     tokens = {
         'root': [
             (r'(?i)(\.)(\w+)', bygroups(Text, Keyword), 'request'),
-            (r'\.', Text, 'request'),
+            (r'\.', Punctuation, 'request'),
             # Regular characters, slurp till we find a backslash or newline
             (r'[^\\\n]*', Text, 'textline'),
         ],
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.