Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pygments/lexers/graphics.py: 76%
72 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-18 06:13 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-18 06:13 +0000
1"""
2 pygments.lexers.graphics
3 ~~~~~~~~~~~~~~~~~~~~~~~~
5 Lexers for computer graphics and plotting related languages.
7 :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8 :license: BSD, see LICENSE for details.
9"""
11from pygments.lexer import RegexLexer, words, include, bygroups, using, \
12 this, default
13from pygments.token import Text, Comment, Operator, Keyword, Name, \
14 Number, Punctuation, String, Whitespace
16__all__ = ['GLShaderLexer', 'PostScriptLexer', 'AsymptoteLexer', 'GnuplotLexer',
17 'PovrayLexer', 'HLSLShaderLexer']
20class GLShaderLexer(RegexLexer):
21 """
22 GLSL (OpenGL Shader) lexer.
24 .. versionadded:: 1.1
25 """
26 name = 'GLSL'
27 aliases = ['glsl']
28 filenames = ['*.vert', '*.frag', '*.geo']
29 mimetypes = ['text/x-glslsrc']
31 tokens = {
32 'root': [
33 (r'#(?:.*\\\n)*.*$', Comment.Preproc),
34 (r'//.*$', Comment.Single),
35 (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
36 (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?',
37 Operator),
38 (r'[?:]', Operator), # quick hack for ternary
39 (r'\bdefined\b', Operator),
40 (r'[;{}(),\[\]]', Punctuation),
41 # FIXME when e is present, no decimal point needed
42 (r'[+-]?\d*\.\d+([eE][-+]?\d+)?', Number.Float),
43 (r'[+-]?\d+\.\d*([eE][-+]?\d+)?', Number.Float),
44 (r'0[xX][0-9a-fA-F]*', Number.Hex),
45 (r'0[0-7]*', Number.Oct),
46 (r'[1-9][0-9]*', Number.Integer),
47 (words((
48 # Storage qualifiers
49 'attribute', 'const', 'uniform', 'varying',
50 'buffer', 'shared', 'in', 'out',
51 # Layout qualifiers
52 'layout',
53 # Interpolation qualifiers
54 'flat', 'smooth', 'noperspective',
55 # Auxiliary qualifiers
56 'centroid', 'sample', 'patch',
57 # Parameter qualifiers. Some double as Storage qualifiers
58 'inout',
59 # Precision qualifiers
60 'lowp', 'mediump', 'highp', 'precision',
61 # Invariance qualifiers
62 'invariant',
63 # Precise qualifiers
64 'precise',
65 # Memory qualifiers
66 'coherent', 'volatile', 'restrict', 'readonly', 'writeonly',
67 # Statements
68 'break', 'continue', 'do', 'for', 'while', 'switch',
69 'case', 'default', 'if', 'else', 'subroutine',
70 'discard', 'return', 'struct'),
71 prefix=r'\b', suffix=r'\b'),
72 Keyword),
73 (words((
74 # Boolean values
75 'true', 'false'),
76 prefix=r'\b', suffix=r'\b'),
77 Keyword.Constant),
78 (words((
79 # Miscellaneous types
80 'void', 'atomic_uint',
81 # Floating-point scalars and vectors
82 'float', 'vec2', 'vec3', 'vec4',
83 'double', 'dvec2', 'dvec3', 'dvec4',
84 # Integer scalars and vectors
85 'int', 'ivec2', 'ivec3', 'ivec4',
86 'uint', 'uvec2', 'uvec3', 'uvec4',
87 # Boolean scalars and vectors
88 'bool', 'bvec2', 'bvec3', 'bvec4',
89 # Matrices
90 'mat2', 'mat3', 'mat4', 'dmat2', 'dmat3', 'dmat4',
91 'mat2x2', 'mat2x3', 'mat2x4', 'dmat2x2', 'dmat2x3', 'dmat2x4',
92 'mat3x2', 'mat3x3', 'mat3x4', 'dmat3x2', 'dmat3x3',
93 'dmat3x4', 'mat4x2', 'mat4x3', 'mat4x4', 'dmat4x2', 'dmat4x3', 'dmat4x4',
94 # Floating-point samplers
95 'sampler1D', 'sampler2D', 'sampler3D', 'samplerCube',
96 'sampler1DArray', 'sampler2DArray', 'samplerCubeArray',
97 'sampler2DRect', 'samplerBuffer',
98 'sampler2DMS', 'sampler2DMSArray',
99 # Shadow samplers
100 'sampler1DShadow', 'sampler2DShadow', 'samplerCubeShadow',
101 'sampler1DArrayShadow', 'sampler2DArrayShadow',
102 'samplerCubeArrayShadow', 'sampler2DRectShadow',
103 # Signed integer samplers
104 'isampler1D', 'isampler2D', 'isampler3D', 'isamplerCube',
105 'isampler1DArray', 'isampler2DArray', 'isamplerCubeArray',
106 'isampler2DRect', 'isamplerBuffer',
107 'isampler2DMS', 'isampler2DMSArray',
108 # Unsigned integer samplers
109 'usampler1D', 'usampler2D', 'usampler3D', 'usamplerCube',
110 'usampler1DArray', 'usampler2DArray', 'usamplerCubeArray',
111 'usampler2DRect', 'usamplerBuffer',
112 'usampler2DMS', 'usampler2DMSArray',
113 # Floating-point image types
114 'image1D', 'image2D', 'image3D', 'imageCube',
115 'image1DArray', 'image2DArray', 'imageCubeArray',
116 'image2DRect', 'imageBuffer',
117 'image2DMS', 'image2DMSArray',
118 # Signed integer image types
119 'iimage1D', 'iimage2D', 'iimage3D', 'iimageCube',
120 'iimage1DArray', 'iimage2DArray', 'iimageCubeArray',
121 'iimage2DRect', 'iimageBuffer',
122 'iimage2DMS', 'iimage2DMSArray',
123 # Unsigned integer image types
124 'uimage1D', 'uimage2D', 'uimage3D', 'uimageCube',
125 'uimage1DArray', 'uimage2DArray', 'uimageCubeArray',
126 'uimage2DRect', 'uimageBuffer',
127 'uimage2DMS', 'uimage2DMSArray'),
128 prefix=r'\b', suffix=r'\b'),
129 Keyword.Type),
130 (words((
131 # Reserved for future use.
132 'common', 'partition', 'active', 'asm', 'class',
133 'union', 'enum', 'typedef', 'template', 'this',
134 'resource', 'goto', 'inline', 'noinline', 'public',
135 'static', 'extern', 'external', 'interface', 'long',
136 'short', 'half', 'fixed', 'unsigned', 'superp', 'input',
137 'output', 'hvec2', 'hvec3', 'hvec4', 'fvec2', 'fvec3',
138 'fvec4', 'sampler3DRect', 'filter', 'sizeof', 'cast',
139 'namespace', 'using'),
140 prefix=r'\b', suffix=r'\b'),
141 Keyword.Reserved),
142 # All names beginning with "gl_" are reserved.
143 (r'gl_\w*', Name.Builtin),
144 (r'[a-zA-Z_]\w*', Name),
145 (r'\.', Punctuation),
146 (r'\s+', Whitespace),
147 ],
148 }
151class HLSLShaderLexer(RegexLexer):
152 """
153 HLSL (Microsoft Direct3D Shader) lexer.
155 .. versionadded:: 2.3
156 """
157 name = 'HLSL'
158 aliases = ['hlsl']
159 filenames = ['*.hlsl', '*.hlsli']
160 mimetypes = ['text/x-hlsl']
162 tokens = {
163 'root': [
164 (r'#(?:.*\\\n)*.*$', Comment.Preproc),
165 (r'//.*$', Comment.Single),
166 (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
167 (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?',
168 Operator),
169 (r'[?:]', Operator), # quick hack for ternary
170 (r'\bdefined\b', Operator),
171 (r'[;{}(),.\[\]]', Punctuation),
172 # FIXME when e is present, no decimal point needed
173 (r'[+-]?\d*\.\d+([eE][-+]?\d+)?f?', Number.Float),
174 (r'[+-]?\d+\.\d*([eE][-+]?\d+)?f?', Number.Float),
175 (r'0[xX][0-9a-fA-F]*', Number.Hex),
176 (r'0[0-7]*', Number.Oct),
177 (r'[1-9][0-9]*', Number.Integer),
178 (r'"', String, 'string'),
179 (words((
180 'asm','asm_fragment','break','case','cbuffer','centroid','class',
181 'column_major','compile','compile_fragment','const','continue',
182 'default','discard','do','else','export','extern','for','fxgroup',
183 'globallycoherent','groupshared','if','in','inline','inout',
184 'interface','line','lineadj','linear','namespace','nointerpolation',
185 'noperspective','NULL','out','packoffset','pass','pixelfragment',
186 'point','precise','return','register','row_major','sample',
187 'sampler','shared','stateblock','stateblock_state','static',
188 'struct','switch','tbuffer','technique','technique10',
189 'technique11','texture','typedef','triangle','triangleadj',
190 'uniform','vertexfragment','volatile','while'),
191 prefix=r'\b', suffix=r'\b'),
192 Keyword),
193 (words(('true','false'), prefix=r'\b', suffix=r'\b'),
194 Keyword.Constant),
195 (words((
196 'auto','catch','char','const_cast','delete','dynamic_cast','enum',
197 'explicit','friend','goto','long','mutable','new','operator',
198 'private','protected','public','reinterpret_cast','short','signed',
199 'sizeof','static_cast','template','this','throw','try','typename',
200 'union','unsigned','using','virtual'),
201 prefix=r'\b', suffix=r'\b'),
202 Keyword.Reserved),
203 (words((
204 'dword','matrix','snorm','string','unorm','unsigned','void','vector',
205 'BlendState','Buffer','ByteAddressBuffer','ComputeShader',
206 'DepthStencilState','DepthStencilView','DomainShader',
207 'GeometryShader','HullShader','InputPatch','LineStream',
208 'OutputPatch','PixelShader','PointStream','RasterizerState',
209 'RenderTargetView','RasterizerOrderedBuffer',
210 'RasterizerOrderedByteAddressBuffer',
211 'RasterizerOrderedStructuredBuffer','RasterizerOrderedTexture1D',
212 'RasterizerOrderedTexture1DArray','RasterizerOrderedTexture2D',
213 'RasterizerOrderedTexture2DArray','RasterizerOrderedTexture3D',
214 'RWBuffer','RWByteAddressBuffer','RWStructuredBuffer',
215 'RWTexture1D','RWTexture1DArray','RWTexture2D','RWTexture2DArray',
216 'RWTexture3D','SamplerState','SamplerComparisonState',
217 'StructuredBuffer','Texture1D','Texture1DArray','Texture2D',
218 'Texture2DArray','Texture2DMS','Texture2DMSArray','Texture3D',
219 'TextureCube','TextureCubeArray','TriangleStream','VertexShader'),
220 prefix=r'\b', suffix=r'\b'),
221 Keyword.Type),
222 (words((
223 'bool','double','float','int','half','min16float','min10float',
224 'min16int','min12int','min16uint','uint'),
225 prefix=r'\b', suffix=r'([1-4](x[1-4])?)?\b'),
226 Keyword.Type), # vector and matrix types
227 (words((
228 'abort','abs','acos','all','AllMemoryBarrier',
229 'AllMemoryBarrierWithGroupSync','any','AppendStructuredBuffer',
230 'asdouble','asfloat','asin','asint','asuint','asuint','atan',
231 'atan2','ceil','CheckAccessFullyMapped','clamp','clip',
232 'CompileShader','ConsumeStructuredBuffer','cos','cosh','countbits',
233 'cross','D3DCOLORtoUBYTE4','ddx','ddx_coarse','ddx_fine','ddy',
234 'ddy_coarse','ddy_fine','degrees','determinant',
235 'DeviceMemoryBarrier','DeviceMemoryBarrierWithGroupSync','distance',
236 'dot','dst','errorf','EvaluateAttributeAtCentroid',
237 'EvaluateAttributeAtSample','EvaluateAttributeSnapped','exp',
238 'exp2','f16tof32','f32tof16','faceforward','firstbithigh',
239 'firstbitlow','floor','fma','fmod','frac','frexp','fwidth',
240 'GetRenderTargetSampleCount','GetRenderTargetSamplePosition',
241 'GlobalOrderedCountIncrement','GroupMemoryBarrier',
242 'GroupMemoryBarrierWithGroupSync','InterlockedAdd','InterlockedAnd',
243 'InterlockedCompareExchange','InterlockedCompareStore',
244 'InterlockedExchange','InterlockedMax','InterlockedMin',
245 'InterlockedOr','InterlockedXor','isfinite','isinf','isnan',
246 'ldexp','length','lerp','lit','log','log10','log2','mad','max',
247 'min','modf','msad4','mul','noise','normalize','pow','printf',
248 'Process2DQuadTessFactorsAvg','Process2DQuadTessFactorsMax',
249 'Process2DQuadTessFactorsMin','ProcessIsolineTessFactors',
250 'ProcessQuadTessFactorsAvg','ProcessQuadTessFactorsMax',
251 'ProcessQuadTessFactorsMin','ProcessTriTessFactorsAvg',
252 'ProcessTriTessFactorsMax','ProcessTriTessFactorsMin',
253 'QuadReadLaneAt','QuadSwapX','QuadSwapY','radians','rcp',
254 'reflect','refract','reversebits','round','rsqrt','saturate',
255 'sign','sin','sincos','sinh','smoothstep','sqrt','step','tan',
256 'tanh','tex1D','tex1D','tex1Dbias','tex1Dgrad','tex1Dlod',
257 'tex1Dproj','tex2D','tex2D','tex2Dbias','tex2Dgrad','tex2Dlod',
258 'tex2Dproj','tex3D','tex3D','tex3Dbias','tex3Dgrad','tex3Dlod',
259 'tex3Dproj','texCUBE','texCUBE','texCUBEbias','texCUBEgrad',
260 'texCUBElod','texCUBEproj','transpose','trunc','WaveAllBitAnd',
261 'WaveAllMax','WaveAllMin','WaveAllBitOr','WaveAllBitXor',
262 'WaveAllEqual','WaveAllProduct','WaveAllSum','WaveAllTrue',
263 'WaveAnyTrue','WaveBallot','WaveGetLaneCount','WaveGetLaneIndex',
264 'WaveGetOrderedIndex','WaveIsHelperLane','WaveOnce',
265 'WavePrefixProduct','WavePrefixSum','WaveReadFirstLane',
266 'WaveReadLaneAt'),
267 prefix=r'\b', suffix=r'\b'),
268 Name.Builtin), # built-in functions
269 (words((
270 'SV_ClipDistance','SV_ClipDistance0','SV_ClipDistance1',
271 'SV_Culldistance','SV_CullDistance0','SV_CullDistance1',
272 'SV_Coverage','SV_Depth','SV_DepthGreaterEqual',
273 'SV_DepthLessEqual','SV_DispatchThreadID','SV_DomainLocation',
274 'SV_GroupID','SV_GroupIndex','SV_GroupThreadID','SV_GSInstanceID',
275 'SV_InnerCoverage','SV_InsideTessFactor','SV_InstanceID',
276 'SV_IsFrontFace','SV_OutputControlPointID','SV_Position',
277 'SV_PrimitiveID','SV_RenderTargetArrayIndex','SV_SampleIndex',
278 'SV_StencilRef','SV_TessFactor','SV_VertexID',
279 'SV_ViewportArrayIndex'),
280 prefix=r'\b', suffix=r'\b'),
281 Name.Decorator), # system-value semantics
282 (r'\bSV_Target[0-7]?\b', Name.Decorator),
283 (words((
284 'allow_uav_condition','branch','call','domain','earlydepthstencil',
285 'fastopt','flatten','forcecase','instance','loop','maxtessfactor',
286 'numthreads','outputcontrolpoints','outputtopology','partitioning',
287 'patchconstantfunc','unroll'),
288 prefix=r'\b', suffix=r'\b'),
289 Name.Decorator), # attributes
290 (r'[a-zA-Z_]\w*', Name),
291 (r'\\$', Comment.Preproc), # backslash at end of line -- usually macro continuation
292 (r'\s+', Whitespace),
293 ],
294 'string': [
295 (r'"', String, '#pop'),
296 (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|'
297 r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),
298 (r'[^\\"\n]+', String), # all other characters
299 (r'\\\n', String), # line continuation
300 (r'\\', String), # stray backslash
301 ],
302 }
305class PostScriptLexer(RegexLexer):
306 """
307 Lexer for PostScript files.
309 .. versionadded:: 1.4
310 """
311 name = 'PostScript'
312 url = 'https://en.wikipedia.org/wiki/PostScript'
313 aliases = ['postscript', 'postscr']
314 filenames = ['*.ps', '*.eps']
315 mimetypes = ['application/postscript']
317 delimiter = r'()<>\[\]{}/%\s'
318 delimiter_end = r'(?=[%s])' % delimiter
320 valid_name_chars = r'[^%s]' % delimiter
321 valid_name = r"%s+%s" % (valid_name_chars, delimiter_end)
323 tokens = {
324 'root': [
325 # All comment types
326 (r'^%!.+$', Comment.Preproc),
327 (r'%%.*$', Comment.Special),
328 (r'(^%.*\n){2,}', Comment.Multiline),
329 (r'%.*$', Comment.Single),
331 # String literals are awkward; enter separate state.
332 (r'\(', String, 'stringliteral'),
334 (r'[{}<>\[\]]', Punctuation),
336 # Numbers
337 (r'<[0-9A-Fa-f]+>' + delimiter_end, Number.Hex),
338 # Slight abuse: use Oct to signify any explicit base system
339 (r'[0-9]+\#(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)'
340 r'((e|E)[0-9]+)?' + delimiter_end, Number.Oct),
341 (r'(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)((e|E)[0-9]+)?'
342 + delimiter_end, Number.Float),
343 (r'(\-|\+)?[0-9]+' + delimiter_end, Number.Integer),
345 # References
346 (r'\/%s' % valid_name, Name.Variable),
348 # Names
349 (valid_name, Name.Function), # Anything else is executed
351 # These keywords taken from
352 # <http://www.math.ubc.ca/~cass/graphics/manual/pdf/a1.pdf>
353 # Is there an authoritative list anywhere that doesn't involve
354 # trawling documentation?
356 (r'(false|true)' + delimiter_end, Keyword.Constant),
358 # Conditionals / flow control
359 (r'(eq|ne|g[et]|l[et]|and|or|not|if(?:else)?|for(?:all)?)'
360 + delimiter_end, Keyword.Reserved),
362 (words((
363 'abs', 'add', 'aload', 'arc', 'arcn', 'array', 'atan', 'begin',
364 'bind', 'ceiling', 'charpath', 'clip', 'closepath', 'concat',
365 'concatmatrix', 'copy', 'cos', 'currentlinewidth', 'currentmatrix',
366 'currentpoint', 'curveto', 'cvi', 'cvs', 'def', 'defaultmatrix',
367 'dict', 'dictstackoverflow', 'div', 'dtransform', 'dup', 'end',
368 'exch', 'exec', 'exit', 'exp', 'fill', 'findfont', 'floor', 'get',
369 'getinterval', 'grestore', 'gsave', 'gt', 'identmatrix', 'idiv',
370 'idtransform', 'index', 'invertmatrix', 'itransform', 'length',
371 'lineto', 'ln', 'load', 'log', 'loop', 'matrix', 'mod', 'moveto',
372 'mul', 'neg', 'newpath', 'pathforall', 'pathbbox', 'pop', 'print',
373 'pstack', 'put', 'quit', 'rand', 'rangecheck', 'rcurveto', 'repeat',
374 'restore', 'rlineto', 'rmoveto', 'roll', 'rotate', 'round', 'run',
375 'save', 'scale', 'scalefont', 'setdash', 'setfont', 'setgray',
376 'setlinecap', 'setlinejoin', 'setlinewidth', 'setmatrix',
377 'setrgbcolor', 'shfill', 'show', 'showpage', 'sin', 'sqrt',
378 'stack', 'stringwidth', 'stroke', 'strokepath', 'sub', 'syntaxerror',
379 'transform', 'translate', 'truncate', 'typecheck', 'undefined',
380 'undefinedfilename', 'undefinedresult'), suffix=delimiter_end),
381 Name.Builtin),
383 (r'\s+', Whitespace),
384 ],
386 'stringliteral': [
387 (r'[^()\\]+', String),
388 (r'\\', String.Escape, 'escape'),
389 (r'\(', String, '#push'),
390 (r'\)', String, '#pop'),
391 ],
393 'escape': [
394 (r'[0-8]{3}|n|r|t|b|f|\\|\(|\)', String.Escape, '#pop'),
395 default('#pop'),
396 ],
397 }
400class AsymptoteLexer(RegexLexer):
401 """
402 For Asymptote source code.
404 .. versionadded:: 1.2
405 """
406 name = 'Asymptote'
407 url = 'http://asymptote.sf.net/'
408 aliases = ['asymptote', 'asy']
409 filenames = ['*.asy']
410 mimetypes = ['text/x-asymptote']
412 #: optional Comment or Whitespace
413 _ws = r'(?:\s|//.*?\n|/\*.*?\*/)+'
415 tokens = {
416 'whitespace': [
417 (r'\n', Whitespace),
418 (r'\s+', Whitespace),
419 (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation
420 (r'//(\n|(.|\n)*?[^\\]\n)', Comment),
421 (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment),
422 ],
423 'statements': [
424 # simple string (TeX friendly)
425 (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
426 # C style string (with character escapes)
427 (r"'", String, 'string'),
428 (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float),
429 (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
430 (r'0x[0-9a-fA-F]+[Ll]?', Number.Hex),
431 (r'0[0-7]+[Ll]?', Number.Oct),
432 (r'\d+[Ll]?', Number.Integer),
433 (r'[~!%^&*+=|?:<>/-]', Operator),
434 (r'[()\[\],.]', Punctuation),
435 (r'\b(case)(.+?)(:)', bygroups(Keyword, using(this), Text)),
436 (r'(and|controls|tension|atleast|curl|if|else|while|for|do|'
437 r'return|break|continue|struct|typedef|new|access|import|'
438 r'unravel|from|include|quote|static|public|private|restricted|'
439 r'this|explicit|true|false|null|cycle|newframe|operator)\b', Keyword),
440 # Since an asy-type-name can be also an asy-function-name,
441 # in the following we test if the string " [a-zA-Z]" follows
442 # the Keyword.Type.
443 # Of course it is not perfect !
444 (r'(Braid|FitResult|Label|Legend|TreeNode|abscissa|arc|arrowhead|'
445 r'binarytree|binarytreeNode|block|bool|bool3|bounds|bqe|circle|'
446 r'conic|coord|coordsys|cputime|ellipse|file|filltype|frame|grid3|'
447 r'guide|horner|hsv|hyperbola|indexedTransform|int|inversion|key|'
448 r'light|line|linefit|marginT|marker|mass|object|pair|parabola|path|'
449 r'path3|pen|picture|point|position|projection|real|revolution|'
450 r'scaleT|scientific|segment|side|slice|splitface|string|surface|'
451 r'tensionSpecifier|ticklocate|ticksgridT|tickvalues|transform|'
452 r'transformation|tree|triangle|trilinear|triple|vector|'
453 r'vertex|void)(?=\s+[a-zA-Z])', Keyword.Type),
454 # Now the asy-type-name which are not asy-function-name
455 # except yours !
456 # Perhaps useless
457 (r'(Braid|FitResult|TreeNode|abscissa|arrowhead|block|bool|bool3|'
458 r'bounds|coord|frame|guide|horner|int|linefit|marginT|pair|pen|'
459 r'picture|position|real|revolution|slice|splitface|ticksgridT|'
460 r'tickvalues|tree|triple|vertex|void)\b', Keyword.Type),
461 (r'[a-zA-Z_]\w*:(?!:)', Name.Label),
462 (r'[a-zA-Z_]\w*', Name),
463 ],
464 'root': [
465 include('whitespace'),
466 # functions
467 (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments
468 r'([a-zA-Z_]\w*)' # method name
469 r'(\s*\([^;]*?\))' # signature
470 r'(' + _ws + r')(\{)',
471 bygroups(using(this), Name.Function, using(this), using(this),
472 Punctuation),
473 'function'),
474 # function declarations
475 (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments
476 r'([a-zA-Z_]\w*)' # method name
477 r'(\s*\([^;]*?\))' # signature
478 r'(' + _ws + r')(;)',
479 bygroups(using(this), Name.Function, using(this), using(this),
480 Punctuation)),
481 default('statement'),
482 ],
483 'statement': [
484 include('whitespace'),
485 include('statements'),
486 ('[{}]', Punctuation),
487 (';', Punctuation, '#pop'),
488 ],
489 'function': [
490 include('whitespace'),
491 include('statements'),
492 (';', Punctuation),
493 (r'\{', Punctuation, '#push'),
494 (r'\}', Punctuation, '#pop'),
495 ],
496 'string': [
497 (r"'", String, '#pop'),
498 (r'\\([\\abfnrtv"\'?]|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),
499 (r'\n', String),
500 (r"[^\\'\n]+", String), # all other characters
501 (r'\\\n', String),
502 (r'\\n', String), # line continuation
503 (r'\\', String), # stray backslash
504 ],
505 }
507 def get_tokens_unprocessed(self, text):
508 from pygments.lexers._asy_builtins import ASYFUNCNAME, ASYVARNAME
509 for index, token, value in \
510 RegexLexer.get_tokens_unprocessed(self, text):
511 if token is Name and value in ASYFUNCNAME:
512 token = Name.Function
513 elif token is Name and value in ASYVARNAME:
514 token = Name.Variable
515 yield index, token, value
518def _shortened(word):
519 dpos = word.find('$')
520 return '|'.join(word[:dpos] + word[dpos+1:i] + r'\b'
521 for i in range(len(word), dpos, -1))
524def _shortened_many(*words):
525 return '|'.join(map(_shortened, words))
528class GnuplotLexer(RegexLexer):
529 """
530 For Gnuplot plotting scripts.
532 .. versionadded:: 0.11
533 """
535 name = 'Gnuplot'
536 url = 'http://gnuplot.info/'
537 aliases = ['gnuplot']
538 filenames = ['*.plot', '*.plt']
539 mimetypes = ['text/x-gnuplot']
541 tokens = {
542 'root': [
543 include('whitespace'),
544 (_shortened('bi$nd'), Keyword, 'bind'),
545 (_shortened_many('ex$it', 'q$uit'), Keyword, 'quit'),
546 (_shortened('f$it'), Keyword, 'fit'),
547 (r'(if)(\s*)(\()', bygroups(Keyword, Text, Punctuation), 'if'),
548 (r'else\b', Keyword),
549 (_shortened('pa$use'), Keyword, 'pause'),
550 (_shortened_many('p$lot', 'rep$lot', 'sp$lot'), Keyword, 'plot'),
551 (_shortened('sa$ve'), Keyword, 'save'),
552 (_shortened('se$t'), Keyword, ('genericargs', 'optionarg')),
553 (_shortened_many('sh$ow', 'uns$et'),
554 Keyword, ('noargs', 'optionarg')),
555 (_shortened_many('low$er', 'ra$ise', 'ca$ll', 'cd$', 'cl$ear',
556 'h$elp', '\\?$', 'hi$story', 'l$oad', 'pr$int',
557 'pwd$', 're$read', 'res$et', 'scr$eendump',
558 'she$ll', 'sy$stem', 'up$date'),
559 Keyword, 'genericargs'),
560 (_shortened_many('pwd$', 're$read', 'res$et', 'scr$eendump',
561 'she$ll', 'test$'),
562 Keyword, 'noargs'),
563 (r'([a-zA-Z_]\w*)(\s*)(=)',
564 bygroups(Name.Variable, Whitespace, Operator), 'genericargs'),
565 (r'([a-zA-Z_]\w*)(\s*)(\()(.*?)(\))(\s*)(=)',
566 bygroups(Name.Function, Whitespace, Punctuation,
567 Text, Punctuation, Whitespace, Operator), 'genericargs'),
568 (r'@[a-zA-Z_]\w*', Name.Constant), # macros
569 (r';', Keyword),
570 ],
571 'comment': [
572 (r'[^\\\n]+', Comment),
573 (r'\\\n', Comment),
574 (r'\\', Comment),
575 # don't add the newline to the Comment token
576 default('#pop'),
577 ],
578 'whitespace': [
579 ('#', Comment, 'comment'),
580 (r'[ \t\v\f]+', Whitespace),
581 ],
582 'noargs': [
583 include('whitespace'),
584 # semicolon and newline end the argument list
585 (r';', Punctuation, '#pop'),
586 (r'\n', Whitespace, '#pop'),
587 ],
588 'dqstring': [
589 (r'"', String, '#pop'),
590 (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),
591 (r'[^\\"\n]+', String), # all other characters
592 (r'\\\n', String), # line continuation
593 (r'\\', String), # stray backslash
594 (r'\n', Whitespace, '#pop'), # newline ends the string too
595 ],
596 'sqstring': [
597 (r"''", String), # escaped single quote
598 (r"'", String, '#pop'),
599 (r"[^\\'\n]+", String), # all other characters
600 (r'\\\n', String), # line continuation
601 (r'\\', String), # normal backslash
602 (r'\n', Whitespace, '#pop'), # newline ends the string too
603 ],
604 'genericargs': [
605 include('noargs'),
606 (r'"', String, 'dqstring'),
607 (r"'", String, 'sqstring'),
608 (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float),
609 (r'(\d+\.\d*|\.\d+)', Number.Float),
610 (r'-?\d+', Number.Integer),
611 ('[,.~!%^&*+=|?:<>/-]', Operator),
612 (r'[{}()\[\]]', Punctuation),
613 (r'(eq|ne)\b', Operator.Word),
614 (r'([a-zA-Z_]\w*)(\s*)(\()',
615 bygroups(Name.Function, Text, Punctuation)),
616 (r'[a-zA-Z_]\w*', Name),
617 (r'@[a-zA-Z_]\w*', Name.Constant), # macros
618 (r'(\\)(\n)', bygroups(Text, Whitespace)),
619 ],
620 'optionarg': [
621 include('whitespace'),
622 (_shortened_many(
623 "a$ll", "an$gles", "ar$row", "au$toscale", "b$ars", "bor$der",
624 "box$width", "cl$abel", "c$lip", "cn$trparam", "co$ntour", "da$ta",
625 "data$file", "dg$rid3d", "du$mmy", "enc$oding", "dec$imalsign",
626 "fit$", "font$path", "fo$rmat", "fu$nction", "fu$nctions", "g$rid",
627 "hid$den3d", "his$torysize", "is$osamples", "k$ey", "keyt$itle",
628 "la$bel", "li$nestyle", "ls$", "loa$dpath", "loc$ale", "log$scale",
629 "mac$ros", "map$ping", "map$ping3d", "mar$gin", "lmar$gin",
630 "rmar$gin", "tmar$gin", "bmar$gin", "mo$use", "multi$plot",
631 "mxt$ics", "nomxt$ics", "mx2t$ics", "nomx2t$ics", "myt$ics",
632 "nomyt$ics", "my2t$ics", "nomy2t$ics", "mzt$ics", "nomzt$ics",
633 "mcbt$ics", "nomcbt$ics", "of$fsets", "or$igin", "o$utput",
634 "pa$rametric", "pm$3d", "pal$ette", "colorb$ox", "p$lot",
635 "poi$ntsize", "pol$ar", "pr$int", "obj$ect", "sa$mples", "si$ze",
636 "st$yle", "su$rface", "table$", "t$erminal", "termo$ptions", "ti$cs",
637 "ticsc$ale", "ticsl$evel", "timef$mt", "tim$estamp", "tit$le",
638 "v$ariables", "ve$rsion", "vi$ew", "xyp$lane", "xda$ta", "x2da$ta",
639 "yda$ta", "y2da$ta", "zda$ta", "cbda$ta", "xl$abel", "x2l$abel",
640 "yl$abel", "y2l$abel", "zl$abel", "cbl$abel", "xti$cs", "noxti$cs",
641 "x2ti$cs", "nox2ti$cs", "yti$cs", "noyti$cs", "y2ti$cs", "noy2ti$cs",
642 "zti$cs", "nozti$cs", "cbti$cs", "nocbti$cs", "xdti$cs", "noxdti$cs",
643 "x2dti$cs", "nox2dti$cs", "ydti$cs", "noydti$cs", "y2dti$cs",
644 "noy2dti$cs", "zdti$cs", "nozdti$cs", "cbdti$cs", "nocbdti$cs",
645 "xmti$cs", "noxmti$cs", "x2mti$cs", "nox2mti$cs", "ymti$cs",
646 "noymti$cs", "y2mti$cs", "noy2mti$cs", "zmti$cs", "nozmti$cs",
647 "cbmti$cs", "nocbmti$cs", "xr$ange", "x2r$ange", "yr$ange",
648 "y2r$ange", "zr$ange", "cbr$ange", "rr$ange", "tr$ange", "ur$ange",
649 "vr$ange", "xzeroa$xis", "x2zeroa$xis", "yzeroa$xis", "y2zeroa$xis",
650 "zzeroa$xis", "zeroa$xis", "z$ero"), Name.Builtin, '#pop'),
651 ],
652 'bind': [
653 ('!', Keyword, '#pop'),
654 (_shortened('all$windows'), Name.Builtin),
655 include('genericargs'),
656 ],
657 'quit': [
658 (r'gnuplot\b', Keyword),
659 include('noargs'),
660 ],
661 'fit': [
662 (r'via\b', Name.Builtin),
663 include('plot'),
664 ],
665 'if': [
666 (r'\)', Punctuation, '#pop'),
667 include('genericargs'),
668 ],
669 'pause': [
670 (r'(mouse|any|button1|button2|button3)\b', Name.Builtin),
671 (_shortened('key$press'), Name.Builtin),
672 include('genericargs'),
673 ],
674 'plot': [
675 (_shortened_many('ax$es', 'axi$s', 'bin$ary', 'ev$ery', 'i$ndex',
676 'mat$rix', 's$mooth', 'thru$', 't$itle',
677 'not$itle', 'u$sing', 'w$ith'),
678 Name.Builtin),
679 include('genericargs'),
680 ],
681 'save': [
682 (_shortened_many('f$unctions', 's$et', 't$erminal', 'v$ariables'),
683 Name.Builtin),
684 include('genericargs'),
685 ],
686 }
689class PovrayLexer(RegexLexer):
690 """
691 For Persistence of Vision Raytracer files.
693 .. versionadded:: 0.11
694 """
695 name = 'POVRay'
696 url = 'http://www.povray.org/'
697 aliases = ['pov']
698 filenames = ['*.pov', '*.inc']
699 mimetypes = ['text/x-povray']
701 tokens = {
702 'root': [
703 (r'/\*[\w\W]*?\*/', Comment.Multiline),
704 (r'//.*$', Comment.Single),
705 (r'(?s)"(?:\\.|[^"\\])+"', String.Double),
706 (words((
707 'break', 'case', 'debug', 'declare', 'default', 'define', 'else',
708 'elseif', 'end', 'error', 'fclose', 'fopen', 'for', 'if', 'ifdef',
709 'ifndef', 'include', 'local', 'macro', 'range', 'read', 'render',
710 'statistics', 'switch', 'undef', 'version', 'warning', 'while',
711 'write'), prefix=r'#', suffix=r'\b'),
712 Comment.Preproc),
713 (words((
714 'aa_level', 'aa_threshold', 'abs', 'acos', 'acosh', 'adaptive', 'adc_bailout',
715 'agate', 'agate_turb', 'all', 'alpha', 'ambient', 'ambient_light', 'angle',
716 'aperture', 'arc_angle', 'area_light', 'asc', 'asin', 'asinh', 'assumed_gamma',
717 'atan', 'atan2', 'atanh', 'atmosphere', 'atmospheric_attenuation',
718 'attenuating', 'average', 'background', 'black_hole', 'blue', 'blur_samples',
719 'bounded_by', 'box_mapping', 'bozo', 'break', 'brick', 'brick_size',
720 'brightness', 'brilliance', 'bumps', 'bumpy1', 'bumpy2', 'bumpy3', 'bump_map',
721 'bump_size', 'case', 'caustics', 'ceil', 'checker', 'chr', 'clipped_by', 'clock',
722 'color', 'color_map', 'colour', 'colour_map', 'component', 'composite', 'concat',
723 'confidence', 'conic_sweep', 'constant', 'control0', 'control1', 'cos', 'cosh',
724 'count', 'crackle', 'crand', 'cube', 'cubic_spline', 'cylindrical_mapping',
725 'debug', 'declare', 'default', 'degrees', 'dents', 'diffuse', 'direction',
726 'distance', 'distance_maximum', 'div', 'dust', 'dust_type', 'eccentricity',
727 'else', 'emitting', 'end', 'error', 'error_bound', 'exp', 'exponent',
728 'fade_distance', 'fade_power', 'falloff', 'falloff_angle', 'false',
729 'file_exists', 'filter', 'finish', 'fisheye', 'flatness', 'flip', 'floor',
730 'focal_point', 'fog', 'fog_alt', 'fog_offset', 'fog_type', 'frequency', 'gif',
731 'global_settings', 'glowing', 'gradient', 'granite', 'gray_threshold',
732 'green', 'halo', 'hexagon', 'hf_gray_16', 'hierarchy', 'hollow', 'hypercomplex',
733 'if', 'ifdef', 'iff', 'image_map', 'incidence', 'include', 'int', 'interpolate',
734 'inverse', 'ior', 'irid', 'irid_wavelength', 'jitter', 'lambda', 'leopard',
735 'linear', 'linear_spline', 'linear_sweep', 'location', 'log', 'looks_like',
736 'look_at', 'low_error_factor', 'mandel', 'map_type', 'marble', 'material_map',
737 'matrix', 'max', 'max_intersections', 'max_iteration', 'max_trace_level',
738 'max_value', 'metallic', 'min', 'minimum_reuse', 'mod', 'mortar',
739 'nearest_count', 'no', 'normal', 'normal_map', 'no_shadow', 'number_of_waves',
740 'octaves', 'off', 'offset', 'omega', 'omnimax', 'on', 'once', 'onion', 'open',
741 'orthographic', 'panoramic', 'pattern1', 'pattern2', 'pattern3',
742 'perspective', 'pgm', 'phase', 'phong', 'phong_size', 'pi', 'pigment',
743 'pigment_map', 'planar_mapping', 'png', 'point_at', 'pot', 'pow', 'ppm',
744 'precision', 'pwr', 'quadratic_spline', 'quaternion', 'quick_color',
745 'quick_colour', 'quilted', 'radial', 'radians', 'radiosity', 'radius', 'rainbow',
746 'ramp_wave', 'rand', 'range', 'reciprocal', 'recursion_limit', 'red',
747 'reflection', 'refraction', 'render', 'repeat', 'rgb', 'rgbf', 'rgbft', 'rgbt',
748 'right', 'ripples', 'rotate', 'roughness', 'samples', 'scale', 'scallop_wave',
749 'scattering', 'seed', 'shadowless', 'sin', 'sine_wave', 'sinh', 'sky', 'sky_sphere',
750 'slice', 'slope_map', 'smooth', 'specular', 'spherical_mapping', 'spiral',
751 'spiral1', 'spiral2', 'spotlight', 'spotted', 'sqr', 'sqrt', 'statistics', 'str',
752 'strcmp', 'strength', 'strlen', 'strlwr', 'strupr', 'sturm', 'substr', 'switch', 'sys',
753 't', 'tan', 'tanh', 'test_camera_1', 'test_camera_2', 'test_camera_3',
754 'test_camera_4', 'texture', 'texture_map', 'tga', 'thickness', 'threshold',
755 'tightness', 'tile2', 'tiles', 'track', 'transform', 'translate', 'transmit',
756 'triangle_wave', 'true', 'ttf', 'turbulence', 'turb_depth', 'type',
757 'ultra_wide_angle', 'up', 'use_color', 'use_colour', 'use_index', 'u_steps',
758 'val', 'variance', 'vaxis_rotate', 'vcross', 'vdot', 'version', 'vlength',
759 'vnormalize', 'volume_object', 'volume_rendered', 'vol_with_light',
760 'vrotate', 'v_steps', 'warning', 'warp', 'water_level', 'waves', 'while', 'width',
761 'wood', 'wrinkles', 'yes'), prefix=r'\b', suffix=r'\b'),
762 Keyword),
763 (words((
764 'bicubic_patch', 'blob', 'box', 'camera', 'cone', 'cubic', 'cylinder', 'difference',
765 'disc', 'height_field', 'intersection', 'julia_fractal', 'lathe',
766 'light_source', 'merge', 'mesh', 'object', 'plane', 'poly', 'polygon', 'prism',
767 'quadric', 'quartic', 'smooth_triangle', 'sor', 'sphere', 'superellipsoid',
768 'text', 'torus', 'triangle', 'union'), suffix=r'\b'),
769 Name.Builtin),
770 (r'\b(x|y|z|u|v)\b', Name.Builtin.Pseudo),
771 (r'[a-zA-Z_]\w*', Name),
772 (r'[0-9]*\.[0-9]+', Number.Float),
773 (r'[0-9]+', Number.Integer),
774 (r'[\[\](){}<>;,]', Punctuation),
775 (r'[-+*/=.|&]|<=|>=|!=', Operator),
776 (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
777 (r'\s+', Whitespace),
778 ]
779 }
781 def analyse_text(text):
782 """POVRAY is similar to JSON/C, but the combination of camera and
783 light_source is probably not very likely elsewhere. HLSL or GLSL
784 are similar (GLSL even has #version), but they miss #declare, and
785 light_source/camera are not keywords anywhere else -- it's fair
786 to assume though that any POVRAY scene must have a camera and
787 lightsource."""
788 result = 0
789 if '#version' in text:
790 result += 0.05
791 if '#declare' in text:
792 result += 0.05
793 if 'camera' in text:
794 result += 0.05
795 if 'light_source' in text:
796 result += 0.1
798 return result