Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

795 linhas
38 KiB

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