Wiki

PygmentsHighlighter: dotnet.py

File dotnet.py, 22.5 KB (added by todd.a, 13 years ago)

Moved operators to a group and included this group in the root and matches within open/close parens like initializations and method calls.

Line 
1# -*- coding: utf-8 -*-
2"""
3    pygments.lexers.dotnet
4    ~~~~~~~~~~~~~~~~~~~~~~
5
6    Lexers for .net languages.
7
8    :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
9    :license: BSD, see LICENSE for details.
10"""
11import re
12
13from pygments.lexer import Lexer, RegexLexer, DelegatingLexer, bygroups, using, this, include
14from pygments.token import Punctuation, \
15     Text, Comment, Generic, Operator, Keyword, Name, String, Number, Literal, Other
16from pygments.util import get_choice_opt
17from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
18     make_analysator
19from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
20     make_analysator
21from pygments import unistring as uni
22
23from pygments.lexers.web import XmlLexer
24
25__all__ = ['CobraLexer', 'CSharpLexer', 'BooLexer', 'VbNetLexer', 'CSharpAspxLexer',
26           'VbNetAspxLexer']
27
28
29def _escape(st):
30    return st.replace(u'\\', ur'\\').replace(u'-', ur'\-').\
31           replace(u'[', ur'\[').replace(u']', ur'\]')
32
33class CobraLexer(RegexLexer):
34    """
35    For `Cobra <http://www.cobra-language.org/>`_ source code.
36    """
37
38    def __init__(self, **options):
39        Lexer.__init__(self, **options)
40        self.tabsize = get_int_opt(options, 'tabsize', 4)
41
42    name = 'Cobra'
43    aliases = ['cobra']
44    filenames = ['*.cobra']
45    mimetypes = ['text/x-cobra']
46    flags = re.X | re.M | re.S
47
48    tokens = {
49        'root': [
50            (r'\s*"""', Comment.Multiline, 'doublequote-multiline-comment'),
51            (r"\s*'''", Comment.Multiline, 'singlequote-multiline-comment'),
52            (r'/\#', Comment.Multiline, 'arbitrary-comment'),
53            (r'\s*\#\s*', Comment, 'singleline-comment'),
54            (r'^\s*(@args\s+) (?:\-([^\s]+?) (:) ([^:]+?))+?$', bygroups(Name.Decorator, Name.Label, Text, Name.Variable)),
55            (r'[]{}:@($!),.;[]', Punctuation), 
56        include('operators'),
57            (r'^(use|namespace) (\s+) ([\w_.]+)', bygroups(Keyword, Text, Name.Namespace)),
58            (r'(cue|def|sig) (\s+) ([a-zA-Z_][\w_]*)', 
59                bygroups(Keyword, Text, Name.Function)),
60            (r'(pro|get|set) (\s+) ([A-Za-z_][\w_]+) (\s*?)', bygroups(Keyword, Text, Name.Function, Text)),
61            (r'(class|enum|interface|mixin|struct) (\s+) ([a-zA-Z_][\w_.]*) (<) (of\s+)', 
62                bygroups(Keyword, Text, Name.Class, Punctuation, Keyword), 'generics'),
63            (r'(class|enum|interface|mixin|struct) (\s+) ([a-zA-Z_][\w_.]*)', bygroups(Keyword, Text, Name.Class)),
64            (r'^(\s+) (var) (\s+) ([a-zA-Z_][\w_]*?) (\s*)(=)?(\s*)', 
65                bygroups(Text, Keyword, Text, Name.Variable, Text, Operator, Text)),           
66            (r'(\s*) (as|to) (inout|out|vari)? (\s+) ([A-Za-z][\w_.]*) (<) (of) (\s+)', 
67                bygroups(Text, Keyword, Keyword, Text, Name.Class, Punctuation, Keyword, Text), 'generics'),
68            (r'(\s*) (as|to) (inout|out|vari)? (\s+) ([A-Za-z][\w_.]* \?? | !) (\s*)', 
69                bygroups(Text, Keyword, Keyword, Text, Name.Class, Text)),
70            (r'(from) (\s+) (var)', bygroups(Keyword, Text, Name.Variable)),
71            (r'(?<!def|get|pro|set)\s*[\w]+\s+?(?=as|,)', Name.Variable),
72            (r'(has|implements|inherits)(\s+)', bygroups(Keyword, Text), 'typelist'),
73            (r'([A-Z][\w_.]+) (<) (of) (\s+)', bygroups(Name.Class, Punctuation, Keyword, Text), 'generics'),
74            (r'(\.|_) ([a-zA-Z][\w_.]*) ([(])', bygroups(Punctuation, Text, Punctuation), 'initialization'),
75            (r'(?<!\.) \b([A-Z][\w_.]*) ([(])', bygroups(Name.Class, Punctuation), 'initialization'),
76            (r'\b(in|is|and|or|not)\b', Operator.Word),
77            ((r'\b(?: (abstract|base|internal|is|false|nil|nonvirtual|par|private|protected|'
78              r'public|shared|override|partial|this|true|virtual) | '
79              r'(adds|all|any|assert|body|branch|break|callable|' 
80              r'catch|class|const|continue|do|dynamiceach|else|end|'
81              r'ensure|enum|event|every|except|expect|extend|finally|'
82              r'for|from|get|has|if|ignore|implements|implies|inherits|'
83              r'inlined|interface|invariant|is|listen|lock|mixin|must|namespace|'
84              r'objc|of|off|old|on|out|pass|passthrough|post|'
85              r'print|pro|raise|ref|require|return|same|set|step|stop|struct|'
86              r'success|test|throw|to|trace|try|use|using|var|vari|'
87              r'where|while|yield) )\b'), bygroups(Keyword.Type, Keyword)),
88            (r'(?: (\.|_)? ([A-Za-z_][\w_.]*) )', bygroups(Punctuation, Name)),
89            (r'[\s\t]+(\n)?', Text),
90            include('literals'),
91        ],
92    'operators': [
93            (r'[&|=~<>!\-\+*%?/^]{1,3}', Operator),
94    ],
95        'literals': [
96            (r'(\d+\.\d*|\d*\.\d+) [fF]? ([eE][+-]?[\d]+)?', Number.Float),
97            (r'[0-9][0-9\.]*(f|m|ms|d|h|s)', Number),
98            (r'0[0-7_]+', Number.Oct),
99            (r'0x[a-fA-F0-9_]+', Number.Hex),
100            (r'[\d_]+L', Number.Integer.Long),
101            (r'[\d][\d_]*', Number.Integer),
102            (r"([cnrsu]*|[CNRSU]*) ('')", bygroups(String.Symbol, String)),
103            (r'([cnrsu]*|[CNRSU]*) ("")', bygroups(String.Symbol, String)),
104            (r'([cnrsu]*|[CNRSU]*) (?<!") (") (?!")', bygroups(String.Symbol, String), 'doublequote-string'),
105            (r"([cnrsu]*|[CNRSU]*) (?<!') (') (?!')", bygroups(String.Symbol, String), 'singlequote-string'),
106        ],
107        'doublequote-multiline-comment' : [
108            include('in-comment'),
109            (r'(?<!")"(?!")', Comment.Multiline),
110            (r'[^"]+?', Comment),
111            (r'"""\s*?$', Comment.Multiline, '#pop')
112        ],
113        'singlequote-multiline-comment' : [
114            include('in-comment'),
115            (r"(<?!') ' (?!')", Comment.Multiline),
116            (r"'''\s*?$", Comment.Multiline, '#pop'),
117            (r"[^']+?", Comment.Multiline)
118        ],
119        'arbitrary-comment' : [
120            (r'\#/', Comment.Multiline, '#pop'),
121            include('in-comment'),
122            (r'\#(?!/)', Comment.Multiline),
123            (r'(?<!\#) /', Comment.Multiline),
124            (r'[^#]+?', Comment.Multiline)
125        ],
126        'singleline-comment' : [
127            (r'\.(?:warning|error|require|args|compile\-only|no\-warnings|skip)\.\s+', Generic.Emph),
128            (r'.*?$', Comment.Single, '#pop')
129        ],
130        'in-comment' : [
131            include('hyperlinks'),
132            include('action-items')
133        ],
134        'hyperlinks' : [
135            (r'\b(?:http://)[^\s]+', Generic.Emph)
136        ],
137        'action-items' : [
138            (r'^\s*(?:TODO|NOTE)\b', Generic.Emph)
139        ],
140        'method' : [
141            (r'(as) (\s+)', bygroups(Keyword, Text), 'typespecifier'),
142            (r'\)\s+', Text, '#pop')
143        ],
144        'string-interpolation': [
145            (r'(?<!\\) \[.*?\]', String.Interpol),
146            (r'\\ \[.*?\]', String)
147        ],
148        'char-escape' : [
149            (r'\\[\w]', String.Escape),
150        ],
151        'doublequote-string' : [
152            include('string-interpolation'),
153            include('char-escape'),
154            (r'[^"]', String),
155            (r'(?<!\\)"', String, '#pop'),
156        ],
157        'singlequote-string' : [
158            include('string-interpolation'),
159            include('char-escape'),
160            (r"[^']", String),
161            (r"(?<!\\)'", String, '#pop')
162        ],
163        'typespecifier' : [
164            (r'(inout|out|vari) (\s+)', bygroups(Keyword, Text)),
165            (r'([A-Za-z_][\w_.]+) (<) (of) (\s+)', bygroups(Name.Class, Punctuation, Keyword, Text), ('root', 'generics')),
166            (r'([A-Za-z_][\w_.]+ [?]?) (\s*?)', bygroups(Name.Class, Text), '#pop'),
167            (r'(,) (\s*)', bygroups(Punctuation, Text), '#pop'),
168            (r'\s*$', Text, '#pop')
169        ],
170        'typelist': [
171            (r'([a-zA-Z_][\w_]*) (\<) (of) (\s+)', bygroups(Name.Class, Punctuation, Keyword, Text), 'generics'),
172            (r'(,) (\s*)', bygroups(Punctuation, Text)),
173            (r'([a-zA-Z_][\w_.]*) (\[\])? (\s*) (?=,)', bygroups(Name.Class, Punctuation, Text)),
174            (r'([a-zA-Z_][\w_.]*) (\[\])? (\s*)', bygroups(Name.Class, Punctuation, Text), '#pop'),
175            (r'$', Text, '#pop')
176        ],
177        'initialization': [
178            (r'(?<!\.) ([A-Z][\w_.]+) ([(])', bygroups(Name.Class, Punctuation), '#push'),
179            (r'(\s*) (as|to) (inout|out|vari)? (\s+) ([A-Za-z][\w_.]* \?? | !) (\s*)', 
180                bygroups(Text, Keyword, Keyword, Text, Name.Class, Text)),
181        include('operators'),
182            include('literals'),
183            (r'(?<!\.) ([A-Z_][\w._]+) (<) (of) (\s+)', bygroups(Name.Class, Punctuation, Keyword, Text), 'generics'),
184            (r'(\.|_) ([a-zA-Z_][\w._]+) (<) (of) (\s+)', bygroups(Punctuation, Name, Punctuation, Keyword, Text), 'generics'),
185            (r'[\[\],\s=\-?:]+', Punctuation),
186            (r'([>._]) ([a-zA-Z][\w_.]) ([(])', bygroups(Punctuation, Text, Punctuation), '#push'),
187            (r'\(', Punctuation, '#push'),
188            (r'[\w._]+', Text),
189            (r'\)\s*', Punctuation, '#pop')
190        ],
191        'generics': [
192            (r'([a-zA-Z_][\w._]*) (<) (of) (\s+)', bygroups(Name.Class, Punctuation, Keyword, Text), '#push'),
193            (r'(,) (\s)*', bygroups(Punctuation, Text)),
194            (r'([a-zA-Z_][\w_.]*[?]?) (\s*)', bygroups(Name.Class, Text)),
195            (r'(>) ([?])? (\s*)', bygroups(Punctuation, Punctuation, Text), '#pop')
196        ],
197        'hasorimplementsorinherits': [
198            (r'(\s+)(has|implements|inherits|where)(\s+)', bygroups(Text, Keyword.Declaration, Text), 'typelist'),
199            (include('([\t ]*)([),])?([\t ]*)'), bygroups(Text, Punctuation, Text), 'root')
200        ],
201    }
202
203
204
205class CSharpLexer(RegexLexer):
206    """
207    For `C# <http://msdn2.microsoft.com/en-us/vcsharp/default.aspx>`_
208    source code.
209
210    Additional options accepted:
211
212    `unicodelevel`
213      Determines which Unicode characters this lexer allows for identifiers.
214      The possible values are:
215
216      * ``none`` -- only the ASCII letters and numbers are allowed. This
217        is the fastest selection.
218      * ``basic`` -- all Unicode characters from the specification except
219        category ``Lo`` are allowed.
220      * ``full`` -- all Unicode characters as specified in the C# specs
221        are allowed.  Note that this means a considerable slowdown since the
222        ``Lo`` category has more than 40,000 characters in it!
223
224      The default value is ``basic``.
225
226      *New in Pygments 0.8.*
227    """
228
229    name = 'C#'
230    aliases = ['csharp', 'c#']
231    filenames = ['*.cs']
232    mimetypes = ['text/x-csharp'] # inferred
233
234    flags = re.MULTILINE | re.DOTALL | re.UNICODE
235
236    # for the range of allowed unicode characters in identifiers,
237    # see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
238
239    levels = {
240        'none': '@?[_a-zA-Z][a-zA-Z0-9_]*',
241        'basic': ('@?[_' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + ']' +
242                  '[' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl +
243                  uni.Nd + uni.Pc + uni.Cf + uni.Mn + uni.Mc + ']*'),
244        'full': ('@?(?:_|[^' +
245                 _escape(uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl')) + '])'
246                 + '[^' + _escape(uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo',
247                                                'Nl', 'Nd', 'Pc', 'Cf', 'Mn',
248                                                'Mc')) + ']*'),
249    }
250
251    tokens = {}
252    token_variants = True
253
254    for levelname, cs_ident in levels.items():
255        tokens[levelname] = {
256            'root': [
257                # method names
258                (r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type
259                 r'(' + cs_ident + ')'                           # method name
260                 r'(\s*)(\()',                               # signature start
261                 bygroups(using(this), Name.Function, Text, Punctuation)),
262                (r'^\s*\[.*?\]', Name.Attribute),
263                (r'[^\S\n]+', Text),
264                (r'\\\n', Text), # line continuation
265                (r'//.*?\n', Comment.Single),
266                (r'/[*](.|\n)*?[*]/', Comment.Multiline),
267                (r'\n', Text),
268                (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
269                (r'[{}]', Punctuation),
270                (r'@"(\\\\|\\"|[^"])*"', String),
271                (r'"(\\\\|\\"|[^"\n])*["\n]', String),
272                (r"'\\.'|'[^\\]'", String.Char),
273                (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?"
274                 r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number),
275                (r'#[ \t]*(if|endif|else|elif|define|undef|'
276                 r'line|error|warning|region|endregion|pragma)\b.*?\n',
277                 Comment.Preproc),
278                (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text,
279                 Keyword)),
280                (r'(abstract|as|base|break|case|catch|'
281                 r'checked|const|continue|default|delegate|'
282                 r'do|else|enum|event|explicit|extern|false|finally|'
283                 r'fixed|for|foreach|goto|if|implicit|in|interface|'
284                 r'internal|is|lock|new|null|operator|'
285                 r'out|override|params|private|protected|public|readonly|'
286                 r'ref|return|sealed|sizeof|stackalloc|static|'
287                 r'switch|this|throw|true|try|typeof|'
288                 r'unchecked|unsafe|virtual|void|while|'
289                 r'get|set|new|partial|yield|add|remove|value)\b', Keyword),
290                (r'(global)(::)', bygroups(Keyword, Punctuation)),
291                (r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|'
292                 r'short|string|uint|ulong|ushort)\b\??', Keyword.Type),
293                (r'(class|struct)(\s+)', bygroups(Keyword, Text), 'class'),
294                (r'(namespace|using)(\s+)', bygroups(Keyword, Text), 'namespace'),
295                (cs_ident, Name),
296            ],
297            'class': [
298                (cs_ident, Name.Class, '#pop')
299            ],
300            'namespace': [
301                (r'(?=\()', Text, '#pop'), # using (resource)
302                ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop')
303            ]
304        }
305
306    def __init__(self, **options):
307        level = get_choice_opt(options, 'unicodelevel', self.tokens.keys(), 'basic')
308        if level not in self._all_tokens:
309            # compile the regexes now
310            self._tokens = self.__class__.process_tokendef(level)
311        else:
312            self._tokens = self._all_tokens[level]
313
314        RegexLexer.__init__(self, **options)
315
316
317class BooLexer(RegexLexer):
318    """
319    For `Boo <http://boo.codehaus.org/>`_ source code.
320    """
321
322    name = 'Boo'
323    aliases = ['boo']
324    filenames = ['*.boo']
325    mimetypes = ['text/x-boo']
326
327    tokens = {
328        'root': [
329            (r'\s+', Text),
330            (r'(#|//).*$', Comment.Single),
331            (r'/[*]', Comment.Multiline, 'comment'),
332            (r'[]{}:(),.;[]', Punctuation),
333            (r'\\\n', Text),
334            (r'\\', Text),
335            (r'(in|is|and|or|not)\b', Operator.Word),
336            (r'/(\\\\|\\/|[^/\s])/', String.Regex),
337            (r'@/(\\\\|\\/|[^/])*/', String.Regex),
338            (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator),
339            (r'(as|abstract|callable|constructor|destructor|do|import|'
340             r'enum|event|final|get|interface|internal|of|override|'
341             r'partial|private|protected|public|return|set|static|'
342             r'struct|transient|virtual|yield|super|and|break|cast|'
343             r'continue|elif|else|ensure|except|for|given|goto|if|in|'
344             r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|'
345             r'while|from|as)\b', Keyword),
346            (r'def(?=\s+\(.*?\))', Keyword),
347            (r'(def)(\s+)', bygroups(Keyword, Text), 'funcname'),
348            (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'),
349            (r'(namespace)(\s+)', bygroups(Keyword, Text), 'namespace'),
350            (r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|'
351             r'assert|checked|enumerate|filter|getter|len|lock|map|'
352             r'matrix|max|min|normalArrayIndexing|print|property|range|'
353             r'rawArrayIndexing|required|typeof|unchecked|using|'
354             r'yieldAll|zip)\b', Name.Builtin),
355            ('"""(\\\\|\\"|.*?)"""', String.Double),
356            ('"(\\\\|\\"|[^"]*?)"', String.Double),
357            ("'(\\\\|\\'|[^']*?)'", String.Single),
358            ('[a-zA-Z_][a-zA-Z0-9_]*', Name),
359            (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float),
360            (r'[0-9][0-9\.]*(m|ms|d|h|s)', Number),
361            (r'0\d+', Number.Oct),
362            (r'0x[a-fA-F0-9]+', Number.Hex),
363            (r'\d+L', Number.Integer.Long),
364            (r'\d+', Number.Integer),
365        ],
366        'comment': [
367            ('/[*]', Comment.Multiline, '#push'),
368            ('[*]/', Comment.Multiline, '#pop'),
369            ('[^/*]', Comment.Multiline),
370            ('[*/]', Comment.Multiline)
371        ],
372        'funcname': [
373            ('[a-zA-Z_][a-zA-Z0-9_]*', Name.Function, '#pop')
374        ],
375        'classname': [
376            ('[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop')
377        ],
378        'namespace': [
379            ('[a-zA-Z_][a-zA-Z0-9_.]*', Name.Namespace, '#pop')
380        ]
381    }
382
383
384class VbNetLexer(RegexLexer):
385    """
386    For
387    `Visual Basic.NET <http://msdn2.microsoft.com/en-us/vbasic/default.aspx>`_
388    source code.
389    """
390
391    name = 'VB.net'
392    aliases = ['vb.net', 'vbnet']
393    filenames = ['*.vb', '*.bas']
394    mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?)
395
396    flags = re.MULTILINE | re.IGNORECASE
397    tokens = {
398        'root': [
399            (r'^\s*<.*?>', Name.Attribute),
400            (r'\s+', Text),
401            (r'\n', Text),
402            (r'rem\b.*?\n', Comment),
403            (r"'.*?\n", Comment),
404            (r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#End\s+If|#Const|'
405             r'#ExternalSource.*?\n|#End\s+ExternalSource|'
406             r'#Region.*?\n|#End\s+Region|#ExternalChecksum',
407             Comment.Preproc),
408            (r'[\(\){}!#,.:]', Punctuation),
409            (r'Option\s+(Strict|Explicit|Compare)\s+'
410             r'(On|Off|Binary|Text)', Keyword.Declaration),
411            (r'(?<!\.)(AddHandler|Alias|'
412             r'ByRef|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|'
413             r'CDec|CDbl|CInt|CLng|CObj|Const|Continue|CSByte|CShort|'
414             r'CSng|CStr|CType|CUInt|CULng|CUShort|Declare|'
415             r'Default|Delegate|Dim|DirectCast|Do|Each|Else|ElseIf|'
416             r'End|EndIf|Enum|Erase|Error|Event|Exit|False|Finally|For|'
417             r'Friend|Function|Get|Global|GoSub|GoTo|Handles|If|'
418             r'Implements|Imports|Inherits|Interface|'
419             r'Let|Lib|Loop|Me|Module|MustInherit|'
420             r'MustOverride|MyBase|MyClass|Namespace|Narrowing|New|Next|'
421             r'Not|Nothing|NotInheritable|NotOverridable|Of|On|'
422             r'Operator|Option|Optional|Overloads|Overridable|'
423             r'Overrides|ParamArray|Partial|Private|Property|Protected|'
424             r'Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|'
425             r'Return|Select|Set|Shadows|Shared|Single|'
426             r'Static|Step|Stop|Structure|Sub|SyncLock|Then|'
427             r'Throw|To|True|Try|TryCast|Wend|'
428             r'Using|When|While|Widening|With|WithEvents|'
429             r'WriteOnly)\b', Keyword),
430            (r'(?<!\.)(Function|Sub|Property)(\s+)',
431             bygroups(Keyword, Text), 'funcname'),
432            (r'(?<!\.)(Class|Structure|Enum)(\s+)',
433             bygroups(Keyword, Text), 'classname'),
434            (r'(?<!\.)(Namespace|Imports)(\s+)',
435             bygroups(Keyword, Text), 'namespace'),
436            (r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|'
437             r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|'
438             r'UShort)\b', Keyword.Type),
439            (r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|'
440             r'Or|OrElse|TypeOf|Xor)\b', Operator.Word),
441            (r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|'
442             r'<=|>=|<>|[-&*/\\^+=<>]',
443             Operator),
444            ('"', String, 'string'),
445            ('[a-zA-Z_][a-zA-Z0-9_]*[%&@!#$]?', Name),
446            ('#.*?#', Literal.Date),
447            (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float),
448            (r'\d+([SILDFR]|US|UI|UL)?', Number.Integer),
449            (r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer),
450            (r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer),
451            (r'_\n', Text), # Line continuation
452        ],
453        'string': [
454            (r'""', String),
455            (r'"C?', String, '#pop'),
456            (r'[^"]+', String),
457        ],
458        'funcname': [
459            (r'[a-z_][a-z0-9_]*', Name.Function, '#pop')
460        ],
461        'classname': [
462            (r'[a-z_][a-z0-9_]*', Name.Class, '#pop')
463        ],
464        'namespace': [
465            (r'[a-z_][a-z0-9_.]*', Name.Namespace, '#pop')
466        ],
467    }
468
469class GenericAspxLexer(RegexLexer):
470    """
471    Lexer for ASP.NET pages.
472    """
473
474    name = 'aspx-gen'
475    filenames = []
476    mimetypes = []
477
478    flags = re.DOTALL
479
480    tokens = {
481        'root': [
482            (r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)),
483            (r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer),
484                                                        Other,
485                                                        using(XmlLexer))),
486            (r'(.+?)(?=<)', using(XmlLexer)),
487            (r'.+', using(XmlLexer)),
488        ],
489    }
490
491#TODO support multiple languages within the same source file
492class CSharpAspxLexer(DelegatingLexer):
493    """
494    Lexer for highligting C# within ASP.NET pages.
495    """
496
497    name = 'aspx-cs'
498    aliases = ['aspx-cs']
499    filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
500    mimetypes = []
501
502    def __init__(self, **options):
503        super(CSharpAspxLexer, self).__init__(CSharpLexer,GenericAspxLexer,
504                                              **options)
505
506    def analyse_text(text):
507        if re.search(r'Page\s*Language="C#"', text, re.I) is not None:
508            return 0.2
509        elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None:
510            return 0.15
511        return 0.001 # TODO really only for when filename matched...
512
513class VbNetAspxLexer(DelegatingLexer):
514    """
515    Lexer for highligting Visual Basic.net within ASP.NET pages.
516    """
517
518    name = 'aspx-vb'
519    aliases = ['aspx-vb']
520    filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
521    mimetypes = []
522
523    def __init__(self, **options):
524        super(VbNetAspxLexer, self).__init__(VbNetLexer,GenericAspxLexer,
525                                              **options)
526
527    def analyse_text(text):
528        if re.search(r'Page\s*Language="Vb"', text, re.I) is not None:
529            return 0.2
530        elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None:
531            return 0.15