graphics.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.lexers.graphics
  4. ~~~~~~~~~~~~~~~~~~~~~~~~
  5. Lexers for computer graphics and plotting related languages.
  6. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  7. :license: BSD, see LICENSE for details.
  8. """
  9. from pygments.lexer import RegexLexer, words, include, bygroups, using, \
  10. this, default
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, \
  12. Number, Punctuation, String
  13. __all__ = ['GLShaderLexer', 'PostScriptLexer', 'AsymptoteLexer', 'GnuplotLexer',
  14. 'PovrayLexer', 'HLSLShaderLexer']
  15. class GLShaderLexer(RegexLexer):
  16. """
  17. GLSL (OpenGL Shader) lexer.
  18. .. versionadded:: 1.1
  19. """
  20. name = 'GLSL'
  21. aliases = ['glsl']
  22. filenames = ['*.vert', '*.frag', '*.geo']
  23. mimetypes = ['text/x-glslsrc']
  24. tokens = {
  25. 'root': [
  26. (r'^#.*', 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+', Text),
  140. ],
  141. }
  142. class HLSLShaderLexer(RegexLexer):
  143. """
  144. HLSL (Microsoft Direct3D Shader) lexer.
  145. .. versionadded:: 2.3
  146. """
  147. name = 'HLSL'
  148. aliases = ['hlsl']
  149. filenames = ['*.hlsl', '*.hlsli']
  150. mimetypes = ['text/x-hlsl']
  151. tokens = {
  152. 'root': [
  153. (r'^#.*', Comment.Preproc),
  154. (r'//.*', Comment.Single),
  155. (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
  156. (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?',
  157. Operator),
  158. (r'[?:]', Operator), # quick hack for ternary
  159. (r'\bdefined\b', Operator),
  160. (r'[;{}(),.\[\]]', Punctuation),
  161. # FIXME when e is present, no decimal point needed
  162. (r'[+-]?\d*\.\d+([eE][-+]?\d+)?f?', Number.Float),
  163. (r'[+-]?\d+\.\d*([eE][-+]?\d+)?f?', Number.Float),
  164. (r'0[xX][0-9a-fA-F]*', Number.Hex),
  165. (r'0[0-7]*', Number.Oct),
  166. (r'[1-9][0-9]*', Number.Integer),
  167. (r'"', String, 'string'),
  168. (words((
  169. 'asm','asm_fragment','break','case','cbuffer','centroid','class',
  170. 'column_major','compile','compile_fragment','const','continue',
  171. 'default','discard','do','else','export','extern','for','fxgroup',
  172. 'globallycoherent','groupshared','if','in','inline','inout',
  173. 'interface','line','lineadj','linear','namespace','nointerpolation',
  174. 'noperspective','NULL','out','packoffset','pass','pixelfragment',
  175. 'point','precise','return','register','row_major','sample',
  176. 'sampler','shared','stateblock','stateblock_state','static',
  177. 'struct','switch','tbuffer','technique','technique10',
  178. 'technique11','texture','typedef','triangle','triangleadj',
  179. 'uniform','vertexfragment','volatile','while'),
  180. prefix=r'\b', suffix=r'\b'),
  181. Keyword),
  182. (words(('true','false'), prefix=r'\b', suffix=r'\b'),
  183. Keyword.Constant),
  184. (words((
  185. 'auto','catch','char','const_cast','delete','dynamic_cast','enum',
  186. 'explicit','friend','goto','long','mutable','new','operator',
  187. 'private','protected','public','reinterpret_cast','short','signed',
  188. 'sizeof','static_cast','template','this','throw','try','typename',
  189. 'union','unsigned','using','virtual'),
  190. prefix=r'\b', suffix=r'\b'),
  191. Keyword.Reserved),
  192. (words((
  193. 'dword','matrix','snorm','string','unorm','unsigned','void','vector',
  194. 'BlendState','Buffer','ByteAddressBuffer','ComputeShader',
  195. 'DepthStencilState','DepthStencilView','DomainShader',
  196. 'GeometryShader','HullShader','InputPatch','LineStream',
  197. 'OutputPatch','PixelShader','PointStream','RasterizerState',
  198. 'RenderTargetView','RasterizerOrderedBuffer',
  199. 'RasterizerOrderedByteAddressBuffer',
  200. 'RasterizerOrderedStructuredBuffer','RasterizerOrderedTexture1D',
  201. 'RasterizerOrderedTexture1DArray','RasterizerOrderedTexture2D',
  202. 'RasterizerOrderedTexture2DArray','RasterizerOrderedTexture3D',
  203. 'RWBuffer','RWByteAddressBuffer','RWStructuredBuffer',
  204. 'RWTexture1D','RWTexture1DArray','RWTexture2D','RWTexture2DArray',
  205. 'RWTexture3D','SamplerState','SamplerComparisonState',
  206. 'StructuredBuffer','Texture1D','Texture1DArray','Texture2D',
  207. 'Texture2DArray','Texture2DMS','Texture2DMSArray','Texture3D',
  208. 'TextureCube','TextureCubeArray','TriangleStream','VertexShader'),
  209. prefix=r'\b', suffix=r'\b'),
  210. Keyword.Type),
  211. (words((
  212. 'bool','double','float','int','half','min16float','min10float',
  213. 'min16int','min12int','min16uint','uint'),
  214. prefix=r'\b', suffix=r'([1-4](x[1-4])?)?\b'),
  215. Keyword.Type), # vector and matrix types
  216. (words((
  217. 'abort','abs','acos','all','AllMemoryBarrier',
  218. 'AllMemoryBarrierWithGroupSync','any','AppendStructuredBuffer',
  219. 'asdouble','asfloat','asin','asint','asuint','asuint','atan',
  220. 'atan2','ceil','CheckAccessFullyMapped','clamp','clip',
  221. 'CompileShader','ConsumeStructuredBuffer','cos','cosh','countbits',
  222. 'cross','D3DCOLORtoUBYTE4','ddx','ddx_coarse','ddx_fine','ddy',
  223. 'ddy_coarse','ddy_fine','degrees','determinant',
  224. 'DeviceMemoryBarrier','DeviceMemoryBarrierWithGroupSync','distance',
  225. 'dot','dst','errorf','EvaluateAttributeAtCentroid',
  226. 'EvaluateAttributeAtSample','EvaluateAttributeSnapped','exp',
  227. 'exp2','f16tof32','f32tof16','faceforward','firstbithigh',
  228. 'firstbitlow','floor','fma','fmod','frac','frexp','fwidth',
  229. 'GetRenderTargetSampleCount','GetRenderTargetSamplePosition',
  230. 'GlobalOrderedCountIncrement','GroupMemoryBarrier',
  231. 'GroupMemoryBarrierWithGroupSync','InterlockedAdd','InterlockedAnd',
  232. 'InterlockedCompareExchange','InterlockedCompareStore',
  233. 'InterlockedExchange','InterlockedMax','InterlockedMin',
  234. 'InterlockedOr','InterlockedXor','isfinite','isinf','isnan',
  235. 'ldexp','length','lerp','lit','log','log10','log2','mad','max',
  236. 'min','modf','msad4','mul','noise','normalize','pow','printf',
  237. 'Process2DQuadTessFactorsAvg','Process2DQuadTessFactorsMax',
  238. 'Process2DQuadTessFactorsMin','ProcessIsolineTessFactors',
  239. 'ProcessQuadTessFactorsAvg','ProcessQuadTessFactorsMax',
  240. 'ProcessQuadTessFactorsMin','ProcessTriTessFactorsAvg',
  241. 'ProcessTriTessFactorsMax','ProcessTriTessFactorsMin',
  242. 'QuadReadLaneAt','QuadSwapX','QuadSwapY','radians','rcp',
  243. 'reflect','refract','reversebits','round','rsqrt','saturate',
  244. 'sign','sin','sincos','sinh','smoothstep','sqrt','step','tan',
  245. 'tanh','tex1D','tex1D','tex1Dbias','tex1Dgrad','tex1Dlod',
  246. 'tex1Dproj','tex2D','tex2D','tex2Dbias','tex2Dgrad','tex2Dlod',
  247. 'tex2Dproj','tex3D','tex3D','tex3Dbias','tex3Dgrad','tex3Dlod',
  248. 'tex3Dproj','texCUBE','texCUBE','texCUBEbias','texCUBEgrad',
  249. 'texCUBElod','texCUBEproj','transpose','trunc','WaveAllBitAnd',
  250. 'WaveAllMax','WaveAllMin','WaveAllBitOr','WaveAllBitXor',
  251. 'WaveAllEqual','WaveAllProduct','WaveAllSum','WaveAllTrue',
  252. 'WaveAnyTrue','WaveBallot','WaveGetLaneCount','WaveGetLaneIndex',
  253. 'WaveGetOrderedIndex','WaveIsHelperLane','WaveOnce',
  254. 'WavePrefixProduct','WavePrefixSum','WaveReadFirstLane',
  255. 'WaveReadLaneAt'),
  256. prefix=r'\b', suffix=r'\b'),
  257. Name.Builtin), # built-in functions
  258. (words((
  259. 'SV_ClipDistance','SV_ClipDistance0','SV_ClipDistance1',
  260. 'SV_Culldistance','SV_CullDistance0','SV_CullDistance1',
  261. 'SV_Coverage','SV_Depth','SV_DepthGreaterEqual',
  262. 'SV_DepthLessEqual','SV_DispatchThreadID','SV_DomainLocation',
  263. 'SV_GroupID','SV_GroupIndex','SV_GroupThreadID','SV_GSInstanceID',
  264. 'SV_InnerCoverage','SV_InsideTessFactor','SV_InstanceID',
  265. 'SV_IsFrontFace','SV_OutputControlPointID','SV_Position',
  266. 'SV_PrimitiveID','SV_RenderTargetArrayIndex','SV_SampleIndex',
  267. 'SV_StencilRef','SV_TessFactor','SV_VertexID',
  268. 'SV_ViewportArrayIndex'),
  269. prefix=r'\b', suffix=r'\b'),
  270. Name.Decorator), # system-value semantics
  271. (r'\bSV_Target[0-7]?\b', Name.Decorator),
  272. (words((
  273. 'allow_uav_condition','branch','call','domain','earlydepthstencil',
  274. 'fastopt','flatten','forcecase','instance','loop','maxtessfactor',
  275. 'numthreads','outputcontrolpoints','outputtopology','partitioning',
  276. 'patchconstantfunc','unroll'),
  277. prefix=r'\b', suffix=r'\b'),
  278. Name.Decorator), # attributes
  279. (r'[a-zA-Z_]\w*', Name),
  280. (r'\\$', Comment.Preproc), # backslash at end of line -- usually macro continuation
  281. (r'\s+', Text),
  282. ],
  283. 'string': [
  284. (r'"', String, '#pop'),
  285. (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|'
  286. r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),
  287. (r'[^\\"\n]+', String), # all other characters
  288. (r'\\\n', String), # line continuation
  289. (r'\\', String), # stray backslash
  290. ],
  291. }
  292. class PostScriptLexer(RegexLexer):
  293. """
  294. Lexer for PostScript files.
  295. The PostScript Language Reference published by Adobe at
  296. <http://partners.adobe.com/public/developer/en/ps/PLRM.pdf>
  297. is the authority for this.
  298. .. versionadded:: 1.4
  299. """
  300. name = 'PostScript'
  301. aliases = ['postscript', 'postscr']
  302. filenames = ['*.ps', '*.eps']
  303. mimetypes = ['application/postscript']
  304. delimiter = r'()<>\[\]{}/%\s'
  305. delimiter_end = r'(?=[%s])' % delimiter
  306. valid_name_chars = r'[^%s]' % delimiter
  307. valid_name = r"%s+%s" % (valid_name_chars, delimiter_end)
  308. tokens = {
  309. 'root': [
  310. # All comment types
  311. (r'^%!.+\n', Comment.Preproc),
  312. (r'%%.*\n', Comment.Special),
  313. (r'(^%.*\n){2,}', Comment.Multiline),
  314. (r'%.*\n', Comment.Single),
  315. # String literals are awkward; enter separate state.
  316. (r'\(', String, 'stringliteral'),
  317. (r'[{}<>\[\]]', Punctuation),
  318. # Numbers
  319. (r'<[0-9A-Fa-f]+>' + delimiter_end, Number.Hex),
  320. # Slight abuse: use Oct to signify any explicit base system
  321. (r'[0-9]+\#(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)'
  322. r'((e|E)[0-9]+)?' + delimiter_end, Number.Oct),
  323. (r'(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)((e|E)[0-9]+)?'
  324. + delimiter_end, Number.Float),
  325. (r'(\-|\+)?[0-9]+' + delimiter_end, Number.Integer),
  326. # References
  327. (r'\/%s' % valid_name, Name.Variable),
  328. # Names
  329. (valid_name, Name.Function), # Anything else is executed
  330. # These keywords taken from
  331. # <http://www.math.ubc.ca/~cass/graphics/manual/pdf/a1.pdf>
  332. # Is there an authoritative list anywhere that doesn't involve
  333. # trawling documentation?
  334. (r'(false|true)' + delimiter_end, Keyword.Constant),
  335. # Conditionals / flow control
  336. (r'(eq|ne|g[et]|l[et]|and|or|not|if(?:else)?|for(?:all)?)'
  337. + delimiter_end, Keyword.Reserved),
  338. (words((
  339. 'abs', 'add', 'aload', 'arc', 'arcn', 'array', 'atan', 'begin',
  340. 'bind', 'ceiling', 'charpath', 'clip', 'closepath', 'concat',
  341. 'concatmatrix', 'copy', 'cos', 'currentlinewidth', 'currentmatrix',
  342. 'currentpoint', 'curveto', 'cvi', 'cvs', 'def', 'defaultmatrix',
  343. 'dict', 'dictstackoverflow', 'div', 'dtransform', 'dup', 'end',
  344. 'exch', 'exec', 'exit', 'exp', 'fill', 'findfont', 'floor', 'get',
  345. 'getinterval', 'grestore', 'gsave', 'gt', 'identmatrix', 'idiv',
  346. 'idtransform', 'index', 'invertmatrix', 'itransform', 'length',
  347. 'lineto', 'ln', 'load', 'log', 'loop', 'matrix', 'mod', 'moveto',
  348. 'mul', 'neg', 'newpath', 'pathforall', 'pathbbox', 'pop', 'print',
  349. 'pstack', 'put', 'quit', 'rand', 'rangecheck', 'rcurveto', 'repeat',
  350. 'restore', 'rlineto', 'rmoveto', 'roll', 'rotate', 'round', 'run',
  351. 'save', 'scale', 'scalefont', 'setdash', 'setfont', 'setgray',
  352. 'setlinecap', 'setlinejoin', 'setlinewidth', 'setmatrix',
  353. 'setrgbcolor', 'shfill', 'show', 'showpage', 'sin', 'sqrt',
  354. 'stack', 'stringwidth', 'stroke', 'strokepath', 'sub', 'syntaxerror',
  355. 'transform', 'translate', 'truncate', 'typecheck', 'undefined',
  356. 'undefinedfilename', 'undefinedresult'), suffix=delimiter_end),
  357. Name.Builtin),
  358. (r'\s+', Text),
  359. ],
  360. 'stringliteral': [
  361. (r'[^()\\]+', String),
  362. (r'\\', String.Escape, 'escape'),
  363. (r'\(', String, '#push'),
  364. (r'\)', String, '#pop'),
  365. ],
  366. 'escape': [
  367. (r'[0-8]{3}|n|r|t|b|f|\\|\(|\)', String.Escape, '#pop'),
  368. default('#pop'),
  369. ],
  370. }
  371. class AsymptoteLexer(RegexLexer):
  372. """
  373. For `Asymptote <http://asymptote.sf.net/>`_ source code.
  374. .. versionadded:: 1.2
  375. """
  376. name = 'Asymptote'
  377. aliases = ['asy', 'asymptote']
  378. filenames = ['*.asy']
  379. mimetypes = ['text/x-asymptote']
  380. #: optional Comment or Whitespace
  381. _ws = r'(?:\s|//.*?\n|/\*.*?\*/)+'
  382. tokens = {
  383. 'whitespace': [
  384. (r'\n', Text),
  385. (r'\s+', Text),
  386. (r'\\\n', Text), # 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 <http://gnuplot.info/>`_ plotting scripts.
  491. .. versionadded:: 0.11
  492. """
  493. name = 'Gnuplot'
  494. aliases = ['gnuplot']
  495. filenames = ['*.plot', '*.plt']
  496. mimetypes = ['text/x-gnuplot']
  497. tokens = {
  498. 'root': [
  499. include('whitespace'),
  500. (_shortened('bi$nd'), Keyword, 'bind'),
  501. (_shortened_many('ex$it', 'q$uit'), Keyword, 'quit'),
  502. (_shortened('f$it'), Keyword, 'fit'),
  503. (r'(if)(\s*)(\()', bygroups(Keyword, Text, Punctuation), 'if'),
  504. (r'else\b', Keyword),
  505. (_shortened('pa$use'), Keyword, 'pause'),
  506. (_shortened_many('p$lot', 'rep$lot', 'sp$lot'), Keyword, 'plot'),
  507. (_shortened('sa$ve'), Keyword, 'save'),
  508. (_shortened('se$t'), Keyword, ('genericargs', 'optionarg')),
  509. (_shortened_many('sh$ow', 'uns$et'),
  510. Keyword, ('noargs', 'optionarg')),
  511. (_shortened_many('low$er', 'ra$ise', 'ca$ll', 'cd$', 'cl$ear',
  512. 'h$elp', '\\?$', 'hi$story', 'l$oad', 'pr$int',
  513. 'pwd$', 're$read', 'res$et', 'scr$eendump',
  514. 'she$ll', 'sy$stem', 'up$date'),
  515. Keyword, 'genericargs'),
  516. (_shortened_many('pwd$', 're$read', 'res$et', 'scr$eendump',
  517. 'she$ll', 'test$'),
  518. Keyword, 'noargs'),
  519. (r'([a-zA-Z_]\w*)(\s*)(=)',
  520. bygroups(Name.Variable, Text, Operator), 'genericargs'),
  521. (r'([a-zA-Z_]\w*)(\s*\(.*?\)\s*)(=)',
  522. bygroups(Name.Function, Text, Operator), 'genericargs'),
  523. (r'@[a-zA-Z_]\w*', Name.Constant), # macros
  524. (r';', Keyword),
  525. ],
  526. 'comment': [
  527. (r'[^\\\n]', Comment),
  528. (r'\\\n', Comment),
  529. (r'\\', Comment),
  530. # don't add the newline to the Comment token
  531. default('#pop'),
  532. ],
  533. 'whitespace': [
  534. ('#', Comment, 'comment'),
  535. (r'[ \t\v\f]+', Text),
  536. ],
  537. 'noargs': [
  538. include('whitespace'),
  539. # semicolon and newline end the argument list
  540. (r';', Punctuation, '#pop'),
  541. (r'\n', Text, '#pop'),
  542. ],
  543. 'dqstring': [
  544. (r'"', String, '#pop'),
  545. (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),
  546. (r'[^\\"\n]+', String), # all other characters
  547. (r'\\\n', String), # line continuation
  548. (r'\\', String), # stray backslash
  549. (r'\n', String, '#pop'), # newline ends the string too
  550. ],
  551. 'sqstring': [
  552. (r"''", String), # escaped single quote
  553. (r"'", String, '#pop'),
  554. (r"[^\\'\n]+", String), # all other characters
  555. (r'\\\n', String), # line continuation
  556. (r'\\', String), # normal backslash
  557. (r'\n', String, '#pop'), # newline ends the string too
  558. ],
  559. 'genericargs': [
  560. include('noargs'),
  561. (r'"', String, 'dqstring'),
  562. (r"'", String, 'sqstring'),
  563. (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float),
  564. (r'(\d+\.\d*|\.\d+)', Number.Float),
  565. (r'-?\d+', Number.Integer),
  566. ('[,.~!%^&*+=|?:<>/-]', Operator),
  567. (r'[{}()\[\]]', Punctuation),
  568. (r'(eq|ne)\b', Operator.Word),
  569. (r'([a-zA-Z_]\w*)(\s*)(\()',
  570. bygroups(Name.Function, Text, Punctuation)),
  571. (r'[a-zA-Z_]\w*', Name),
  572. (r'@[a-zA-Z_]\w*', Name.Constant), # macros
  573. (r'\\\n', Text),
  574. ],
  575. 'optionarg': [
  576. include('whitespace'),
  577. (_shortened_many(
  578. "a$ll", "an$gles", "ar$row", "au$toscale", "b$ars", "bor$der",
  579. "box$width", "cl$abel", "c$lip", "cn$trparam", "co$ntour", "da$ta",
  580. "data$file", "dg$rid3d", "du$mmy", "enc$oding", "dec$imalsign",
  581. "fit$", "font$path", "fo$rmat", "fu$nction", "fu$nctions", "g$rid",
  582. "hid$den3d", "his$torysize", "is$osamples", "k$ey", "keyt$itle",
  583. "la$bel", "li$nestyle", "ls$", "loa$dpath", "loc$ale", "log$scale",
  584. "mac$ros", "map$ping", "map$ping3d", "mar$gin", "lmar$gin",
  585. "rmar$gin", "tmar$gin", "bmar$gin", "mo$use", "multi$plot",
  586. "mxt$ics", "nomxt$ics", "mx2t$ics", "nomx2t$ics", "myt$ics",
  587. "nomyt$ics", "my2t$ics", "nomy2t$ics", "mzt$ics", "nomzt$ics",
  588. "mcbt$ics", "nomcbt$ics", "of$fsets", "or$igin", "o$utput",
  589. "pa$rametric", "pm$3d", "pal$ette", "colorb$ox", "p$lot",
  590. "poi$ntsize", "pol$ar", "pr$int", "obj$ect", "sa$mples", "si$ze",
  591. "st$yle", "su$rface", "table$", "t$erminal", "termo$ptions", "ti$cs",
  592. "ticsc$ale", "ticsl$evel", "timef$mt", "tim$estamp", "tit$le",
  593. "v$ariables", "ve$rsion", "vi$ew", "xyp$lane", "xda$ta", "x2da$ta",
  594. "yda$ta", "y2da$ta", "zda$ta", "cbda$ta", "xl$abel", "x2l$abel",
  595. "yl$abel", "y2l$abel", "zl$abel", "cbl$abel", "xti$cs", "noxti$cs",
  596. "x2ti$cs", "nox2ti$cs", "yti$cs", "noyti$cs", "y2ti$cs", "noy2ti$cs",
  597. "zti$cs", "nozti$cs", "cbti$cs", "nocbti$cs", "xdti$cs", "noxdti$cs",
  598. "x2dti$cs", "nox2dti$cs", "ydti$cs", "noydti$cs", "y2dti$cs",
  599. "noy2dti$cs", "zdti$cs", "nozdti$cs", "cbdti$cs", "nocbdti$cs",
  600. "xmti$cs", "noxmti$cs", "x2mti$cs", "nox2mti$cs", "ymti$cs",
  601. "noymti$cs", "y2mti$cs", "noy2mti$cs", "zmti$cs", "nozmti$cs",
  602. "cbmti$cs", "nocbmti$cs", "xr$ange", "x2r$ange", "yr$ange",
  603. "y2r$ange", "zr$ange", "cbr$ange", "rr$ange", "tr$ange", "ur$ange",
  604. "vr$ange", "xzeroa$xis", "x2zeroa$xis", "yzeroa$xis", "y2zeroa$xis",
  605. "zzeroa$xis", "zeroa$xis", "z$ero"), Name.Builtin, '#pop'),
  606. ],
  607. 'bind': [
  608. ('!', Keyword, '#pop'),
  609. (_shortened('all$windows'), Name.Builtin),
  610. include('genericargs'),
  611. ],
  612. 'quit': [
  613. (r'gnuplot\b', Keyword),
  614. include('noargs'),
  615. ],
  616. 'fit': [
  617. (r'via\b', Name.Builtin),
  618. include('plot'),
  619. ],
  620. 'if': [
  621. (r'\)', Punctuation, '#pop'),
  622. include('genericargs'),
  623. ],
  624. 'pause': [
  625. (r'(mouse|any|button1|button2|button3)\b', Name.Builtin),
  626. (_shortened('key$press'), Name.Builtin),
  627. include('genericargs'),
  628. ],
  629. 'plot': [
  630. (_shortened_many('ax$es', 'axi$s', 'bin$ary', 'ev$ery', 'i$ndex',
  631. 'mat$rix', 's$mooth', 'thru$', 't$itle',
  632. 'not$itle', 'u$sing', 'w$ith'),
  633. Name.Builtin),
  634. include('genericargs'),
  635. ],
  636. 'save': [
  637. (_shortened_many('f$unctions', 's$et', 't$erminal', 'v$ariables'),
  638. Name.Builtin),
  639. include('genericargs'),
  640. ],
  641. }
  642. class PovrayLexer(RegexLexer):
  643. """
  644. For `Persistence of Vision Raytracer <http://www.povray.org/>`_ files.
  645. .. versionadded:: 0.11
  646. """
  647. name = 'POVRay'
  648. aliases = ['pov']
  649. filenames = ['*.pov', '*.inc']
  650. mimetypes = ['text/x-povray']
  651. tokens = {
  652. 'root': [
  653. (r'/\*[\w\W]*?\*/', Comment.Multiline),
  654. (r'//.*\n', Comment.Single),
  655. (r'(?s)"(?:\\.|[^"\\])+"', String.Double),
  656. (words((
  657. 'break', 'case', 'debug', 'declare', 'default', 'define', 'else',
  658. 'elseif', 'end', 'error', 'fclose', 'fopen', 'for', 'if', 'ifdef',
  659. 'ifndef', 'include', 'local', 'macro', 'range', 'read', 'render',
  660. 'statistics', 'switch', 'undef', 'version', 'warning', 'while',
  661. 'write'), prefix=r'#', suffix=r'\b'),
  662. Comment.Preproc),
  663. (words((
  664. 'aa_level', 'aa_threshold', 'abs', 'acos', 'acosh', 'adaptive', 'adc_bailout',
  665. 'agate', 'agate_turb', 'all', 'alpha', 'ambient', 'ambient_light', 'angle',
  666. 'aperture', 'arc_angle', 'area_light', 'asc', 'asin', 'asinh', 'assumed_gamma',
  667. 'atan', 'atan2', 'atanh', 'atmosphere', 'atmospheric_attenuation',
  668. 'attenuating', 'average', 'background', 'black_hole', 'blue', 'blur_samples',
  669. 'bounded_by', 'box_mapping', 'bozo', 'break', 'brick', 'brick_size',
  670. 'brightness', 'brilliance', 'bumps', 'bumpy1', 'bumpy2', 'bumpy3', 'bump_map',
  671. 'bump_size', 'case', 'caustics', 'ceil', 'checker', 'chr', 'clipped_by', 'clock',
  672. 'color', 'color_map', 'colour', 'colour_map', 'component', 'composite', 'concat',
  673. 'confidence', 'conic_sweep', 'constant', 'control0', 'control1', 'cos', 'cosh',
  674. 'count', 'crackle', 'crand', 'cube', 'cubic_spline', 'cylindrical_mapping',
  675. 'debug', 'declare', 'default', 'degrees', 'dents', 'diffuse', 'direction',
  676. 'distance', 'distance_maximum', 'div', 'dust', 'dust_type', 'eccentricity',
  677. 'else', 'emitting', 'end', 'error', 'error_bound', 'exp', 'exponent',
  678. 'fade_distance', 'fade_power', 'falloff', 'falloff_angle', 'false',
  679. 'file_exists', 'filter', 'finish', 'fisheye', 'flatness', 'flip', 'floor',
  680. 'focal_point', 'fog', 'fog_alt', 'fog_offset', 'fog_type', 'frequency', 'gif',
  681. 'global_settings', 'glowing', 'gradient', 'granite', 'gray_threshold',
  682. 'green', 'halo', 'hexagon', 'hf_gray_16', 'hierarchy', 'hollow', 'hypercomplex',
  683. 'if', 'ifdef', 'iff', 'image_map', 'incidence', 'include', 'int', 'interpolate',
  684. 'inverse', 'ior', 'irid', 'irid_wavelength', 'jitter', 'lambda', 'leopard',
  685. 'linear', 'linear_spline', 'linear_sweep', 'location', 'log', 'looks_like',
  686. 'look_at', 'low_error_factor', 'mandel', 'map_type', 'marble', 'material_map',
  687. 'matrix', 'max', 'max_intersections', 'max_iteration', 'max_trace_level',
  688. 'max_value', 'metallic', 'min', 'minimum_reuse', 'mod', 'mortar',
  689. 'nearest_count', 'no', 'normal', 'normal_map', 'no_shadow', 'number_of_waves',
  690. 'octaves', 'off', 'offset', 'omega', 'omnimax', 'on', 'once', 'onion', 'open',
  691. 'orthographic', 'panoramic', 'pattern1', 'pattern2', 'pattern3',
  692. 'perspective', 'pgm', 'phase', 'phong', 'phong_size', 'pi', 'pigment',
  693. 'pigment_map', 'planar_mapping', 'png', 'point_at', 'pot', 'pow', 'ppm',
  694. 'precision', 'pwr', 'quadratic_spline', 'quaternion', 'quick_color',
  695. 'quick_colour', 'quilted', 'radial', 'radians', 'radiosity', 'radius', 'rainbow',
  696. 'ramp_wave', 'rand', 'range', 'reciprocal', 'recursion_limit', 'red',
  697. 'reflection', 'refraction', 'render', 'repeat', 'rgb', 'rgbf', 'rgbft', 'rgbt',
  698. 'right', 'ripples', 'rotate', 'roughness', 'samples', 'scale', 'scallop_wave',
  699. 'scattering', 'seed', 'shadowless', 'sin', 'sine_wave', 'sinh', 'sky', 'sky_sphere',
  700. 'slice', 'slope_map', 'smooth', 'specular', 'spherical_mapping', 'spiral',
  701. 'spiral1', 'spiral2', 'spotlight', 'spotted', 'sqr', 'sqrt', 'statistics', 'str',
  702. 'strcmp', 'strength', 'strlen', 'strlwr', 'strupr', 'sturm', 'substr', 'switch', 'sys',
  703. 't', 'tan', 'tanh', 'test_camera_1', 'test_camera_2', 'test_camera_3',
  704. 'test_camera_4', 'texture', 'texture_map', 'tga', 'thickness', 'threshold',
  705. 'tightness', 'tile2', 'tiles', 'track', 'transform', 'translate', 'transmit',
  706. 'triangle_wave', 'true', 'ttf', 'turbulence', 'turb_depth', 'type',
  707. 'ultra_wide_angle', 'up', 'use_color', 'use_colour', 'use_index', 'u_steps',
  708. 'val', 'variance', 'vaxis_rotate', 'vcross', 'vdot', 'version', 'vlength',
  709. 'vnormalize', 'volume_object', 'volume_rendered', 'vol_with_light',
  710. 'vrotate', 'v_steps', 'warning', 'warp', 'water_level', 'waves', 'while', 'width',
  711. 'wood', 'wrinkles', 'yes'), prefix=r'\b', suffix=r'\b'),
  712. Keyword),
  713. (words((
  714. 'bicubic_patch', 'blob', 'box', 'camera', 'cone', 'cubic', 'cylinder', 'difference',
  715. 'disc', 'height_field', 'intersection', 'julia_fractal', 'lathe',
  716. 'light_source', 'merge', 'mesh', 'object', 'plane', 'poly', 'polygon', 'prism',
  717. 'quadric', 'quartic', 'smooth_triangle', 'sor', 'sphere', 'superellipsoid',
  718. 'text', 'torus', 'triangle', 'union'), suffix=r'\b'),
  719. Name.Builtin),
  720. # TODO: <=, etc
  721. (r'[\[\](){}<>;,]', Punctuation),
  722. (r'[-+*/=]', Operator),
  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.Float),
  727. (r'[0-9]+', Number.Integer),
  728. (r'"(\\\\|\\"|[^"])*"', String),
  729. (r'\s+', Text),
  730. ]
  731. }