graphics.py 38 KB

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