1
# -*- coding: utf-8 -*-
6
Lexers for .net languages.
8
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
9
:license: BSD, see LICENSE for details.
13
from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, using, this
14
from pygments.token import Punctuation, \
15
Text, Comment, Operator, Keyword, Name, String, Number, Literal, Other
16
from pygments.util import get_choice_opt
17
from pygments import unistring as uni
19
from pygments.lexers.web import XmlLexer
21
__all__ = ['CSharpLexer', 'BooLexer', 'VbNetLexer', 'CSharpAspxLexer',
26
return st.replace(u'\\', ur'\\').replace(u'-', ur'\-').\
27
replace(u'[', ur'\[').replace(u']', ur'\]')
29
class CSharpLexer(RegexLexer):
31
For `C# <http://msdn2.microsoft.com/en-us/vcsharp/default.aspx>`_
34
Additional options accepted:
37
Determines which Unicode characters this lexer allows for identifiers.
38
The possible values are:
40
* ``none`` -- only the ASCII letters and numbers are allowed. This
41
is the fastest selection.
42
* ``basic`` -- all Unicode characters from the specification except
43
category ``Lo`` are allowed.
44
* ``full`` -- all Unicode characters as specified in the C# specs
45
are allowed. Note that this means a considerable slowdown since the
46
``Lo`` category has more than 40,000 characters in it!
48
The default value is ``basic``.
50
*New in Pygments 0.8.*
54
aliases = ['csharp', 'c#']
56
mimetypes = ['text/x-csharp'] # inferred
58
flags = re.MULTILINE | re.DOTALL | re.UNICODE
60
# for the range of allowed unicode characters in identifiers,
61
# see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
64
'none': '@?[_a-zA-Z][a-zA-Z0-9_]*',
65
'basic': ('@?[_' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + ']' +
66
'[' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl +
67
uni.Nd + uni.Pc + uni.Cf + uni.Mn + uni.Mc + ']*'),
68
'full': ('@?(?:_|[^' +
69
_escape(uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl')) + '])'
70
+ '[^' + _escape(uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo',
71
'Nl', 'Nd', 'Pc', 'Cf', 'Mn',
78
for levelname, cs_ident in levels.items():
82
(r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type
83
r'(' + cs_ident + ')' # method name
84
r'(\s*)(\()', # signature start
85
bygroups(using(this), Name.Function, Text, Punctuation)),
86
(r'^\s*\[.*?\]', Name.Attribute),
88
(r'\\\n', Text), # line continuation
89
(r'//.*?\n', Comment.Single),
90
(r'/[*](.|\n)*?[*]/', Comment.Multiline),
92
(r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
93
(r'[{}]', Punctuation),
94
(r'@"(\\\\|\\"|[^"])*"', String),
95
(r'"(\\\\|\\"|[^"\n])*["\n]', String),
96
(r"'\\.'|'[^\\]'", String.Char),
97
(r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?"
98
r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number),
99
(r'#[ \t]*(if|endif|else|elif|define|undef|'
100
r'line|error|warning|region|endregion|pragma)\b.*?\n',
102
(r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text,
104
(r'(abstract|as|base|break|case|catch|'
105
r'checked|const|continue|default|delegate|'
106
r'do|else|enum|event|explicit|extern|false|finally|'
107
r'fixed|for|foreach|goto|if|implicit|in|interface|'
108
r'internal|is|lock|new|null|operator|'
109
r'out|override|params|private|protected|public|readonly|'
110
r'ref|return|sealed|sizeof|stackalloc|static|'
111
r'switch|this|throw|true|try|typeof|'
112
r'unchecked|unsafe|virtual|void|while|'
113
r'get|set|new|partial|yield|add|remove|value)\b', Keyword),
114
(r'(global)(::)', bygroups(Keyword, Punctuation)),
115
(r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|'
116
r'short|string|uint|ulong|ushort)\b\??', Keyword.Type),
117
(r'(class|struct)(\s+)', bygroups(Keyword, Text), 'class'),
118
(r'(namespace|using)(\s+)', bygroups(Keyword, Text), 'namespace'),
122
(cs_ident, Name.Class, '#pop')
125
(r'(?=\()', Text, '#pop'), # using (resource)
126
('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop')
130
def __init__(self, **options):
131
level = get_choice_opt(options, 'unicodelevel', self.tokens.keys(), 'basic')
132
if level not in self._all_tokens:
133
# compile the regexes now
134
self._tokens = self.__class__.process_tokendef(level)
136
self._tokens = self._all_tokens[level]
138
RegexLexer.__init__(self, **options)
141
class BooLexer(RegexLexer):
143
For `Boo <http://boo.codehaus.org/>`_ source code.
148
filenames = ['*.boo']
149
mimetypes = ['text/x-boo']
154
(r'(#|//).*$', Comment.Single),
155
(r'/[*]', Comment.Multiline, 'comment'),
156
(r'[]{}:(),.;[]', Punctuation),
159
(r'(in|is|and|or|not)\b', Operator.Word),
160
(r'/(\\\\|\\/|[^/\s])/', String.Regex),
161
(r'@/(\\\\|\\/|[^/])*/', String.Regex),
162
(r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator),
163
(r'(as|abstract|callable|constructor|destructor|do|import|'
164
r'enum|event|final|get|interface|internal|of|override|'
165
r'partial|private|protected|public|return|set|static|'
166
r'struct|transient|virtual|yield|super|and|break|cast|'
167
r'continue|elif|else|ensure|except|for|given|goto|if|in|'
168
r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|'
169
r'while|from|as)\b', Keyword),
170
(r'def(?=\s+\(.*?\))', Keyword),
171
(r'(def)(\s+)', bygroups(Keyword, Text), 'funcname'),
172
(r'(class)(\s+)', bygroups(Keyword, Text), 'classname'),
173
(r'(namespace)(\s+)', bygroups(Keyword, Text), 'namespace'),
174
(r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|'
175
r'assert|checked|enumerate|filter|getter|len|lock|map|'
176
r'matrix|max|min|normalArrayIndexing|print|property|range|'
177
r'rawArrayIndexing|required|typeof|unchecked|using|'
178
r'yieldAll|zip)\b', Name.Builtin),
179
('"""(\\\\|\\"|.*?)"""', String.Double),
180
('"(\\\\|\\"|[^"]*?)"', String.Double),
181
("'(\\\\|\\'|[^']*?)'", String.Single),
182
('[a-zA-Z_][a-zA-Z0-9_]*', Name),
183
(r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float),
184
(r'[0-9][0-9\.]*(m|ms|d|h|s)', Number),
185
(r'0\d+', Number.Oct),
186
(r'0x[a-fA-F0-9]+', Number.Hex),
187
(r'\d+L', Number.Integer.Long),
188
(r'\d+', Number.Integer),
191
('/[*]', Comment.Multiline, '#push'),
192
('[*]/', Comment.Multiline, '#pop'),
193
('[^/*]', Comment.Multiline),
194
('[*/]', Comment.Multiline)
197
('[a-zA-Z_][a-zA-Z0-9_]*', Name.Function, '#pop')
200
('[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop')
203
('[a-zA-Z_][a-zA-Z0-9_.]*', Name.Namespace, '#pop')
208
class VbNetLexer(RegexLexer):
211
`Visual Basic.NET <http://msdn2.microsoft.com/en-us/vbasic/default.aspx>`_
216
aliases = ['vb.net', 'vbnet']
217
filenames = ['*.vb', '*.bas']
218
mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?)
220
flags = re.MULTILINE | re.IGNORECASE
223
(r'^\s*<.*?>', Name.Attribute),
226
(r'rem\b.*?\n', Comment),
227
(r"'.*?\n", Comment),
228
(r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#End\s+If|#Const|'
229
r'#ExternalSource.*?\n|#End\s+ExternalSource|'
230
r'#Region.*?\n|#End\s+Region|#ExternalChecksum',
232
(r'[\(\){}!#,.:]', Punctuation),
233
(r'Option\s+(Strict|Explicit|Compare)\s+'
234
r'(On|Off|Binary|Text)', Keyword.Declaration),
235
(r'(?<!\.)(AddHandler|Alias|'
236
r'ByRef|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|'
237
r'CDec|CDbl|CInt|CLng|CObj|Const|Continue|CSByte|CShort|'
238
r'CSng|CStr|CType|CUInt|CULng|CUShort|Declare|'
239
r'Default|Delegate|Dim|DirectCast|Do|Each|Else|ElseIf|'
240
r'End|EndIf|Enum|Erase|Error|Event|Exit|False|Finally|For|'
241
r'Friend|Function|Get|Global|GoSub|GoTo|Handles|If|'
242
r'Implements|Imports|Inherits|Interface|'
243
r'Let|Lib|Loop|Me|Module|MustInherit|'
244
r'MustOverride|MyBase|MyClass|Namespace|Narrowing|New|Next|'
245
r'Not|Nothing|NotInheritable|NotOverridable|Of|On|'
246
r'Operator|Option|Optional|Overloads|Overridable|'
247
r'Overrides|ParamArray|Partial|Private|Property|Protected|'
248
r'Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|'
249
r'Return|Select|Set|Shadows|Shared|Single|'
250
r'Static|Step|Stop|Structure|Sub|SyncLock|Then|'
251
r'Throw|To|True|Try|TryCast|Wend|'
252
r'Using|When|While|Widening|With|WithEvents|'
253
r'WriteOnly)\b', Keyword),
254
(r'(?<!\.)(Function|Sub|Property)(\s+)',
255
bygroups(Keyword, Text), 'funcname'),
256
(r'(?<!\.)(Class|Structure|Enum)(\s+)',
257
bygroups(Keyword, Text), 'classname'),
258
(r'(?<!\.)(Namespace|Imports)(\s+)',
259
bygroups(Keyword, Text), 'namespace'),
260
(r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|'
261
r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|'
262
r'UShort)\b', Keyword.Type),
263
(r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|'
264
r'Or|OrElse|TypeOf|Xor)\b', Operator.Word),
265
(r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|'
266
r'<=|>=|<>|[-&*/\\^+=<>]',
268
('"', String, 'string'),
269
('[a-zA-Z_][a-zA-Z0-9_]*[%&@!#$]?', Name),
270
('#.*?#', Literal.Date),
271
(r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float),
272
(r'\d+([SILDFR]|US|UI|UL)?', Number.Integer),
273
(r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer),
274
(r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer),
275
(r'_\n', Text), # Line continuation
279
(r'"C?', String, '#pop'),
283
(r'[a-z_][a-z0-9_]*', Name.Function, '#pop')
286
(r'[a-z_][a-z0-9_]*', Name.Class, '#pop')
289
(r'[a-z_][a-z0-9_.]*', Name.Namespace, '#pop')
293
class GenericAspxLexer(RegexLexer):
295
Lexer for ASP.NET pages.
306
(r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)),
307
(r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer),
310
(r'(.+?)(?=<)', using(XmlLexer)),
311
(r'.+', using(XmlLexer)),
315
#TODO support multiple languages within the same source file
316
class CSharpAspxLexer(DelegatingLexer):
318
Lexer for highligting C# within ASP.NET pages.
322
aliases = ['aspx-cs']
323
filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
326
def __init__(self, **options):
327
super(CSharpAspxLexer, self).__init__(CSharpLexer,GenericAspxLexer,
330
def analyse_text(text):
331
if re.search(r'Page\s*Language="C#"', text, re.I) is not None:
333
elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None:
335
return 0.001 # TODO really only for when filename matched...
337
class VbNetAspxLexer(DelegatingLexer):
339
Lexer for highligting Visual Basic.net within ASP.NET pages.
343
aliases = ['aspx-vb']
344
filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
347
def __init__(self, **options):
348
super(VbNetAspxLexer, self).__init__(VbNetLexer,GenericAspxLexer,
351
def analyse_text(text):
352
if re.search(r'Page\s*Language="Vb"', text, re.I) is not None:
354
elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None: