Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/c_like.pyAdded+738
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/cddl.pyAdded+172
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/clean.pyAdded+180
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/codeql.pyAdded+80
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/comal.pyAdded+81
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/compiled.pyAdded+35
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/configs.pyAdded+1433
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/console.pyAdded+114
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/cplint.pyAdded+43
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/crystal.pyAdded+364
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/csound.pyAdded+466
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/css.pyAdded+632
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/d.pyAdded+259
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dalvik.pyAdded+126
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/data.pyAdded+763
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dax.pyAdded+135
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/devicetree.pyAdded+120
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/diff.pyAdded+169
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dns.pyAdded+109
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dotnet.pyAdded+873
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dsls.pyAdded+970
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dylan.pyAdded+279
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ecl.pyAdded+144
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/eiffel.pyAdded+68
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/elm.pyAdded+123
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/elpi.pyAdded+201
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/email.pyAdded+132
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/erlang.pyAdded+526
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/esoteric.pyAdded+300
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ezhil.pyAdded+76
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/factor.pyAdded+363
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/fantom.pyAdded+251
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/felix.pyAdded+275
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/fift.pyAdded+68
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/floscript.pyAdded+81
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/forth.pyAdded+178
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/fortran.pyAdded+212
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/foxpro.pyAdded+427
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/freefem.pyAdded+893
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/func.pyAdded+110
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/functional.pyAdded+21
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/futhark.pyAdded+105
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/gcodelexer.pyAdded+35
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/gdscript.pyAdded+189
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/gleam.pyAdded+74
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/go.pyAdded+97
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/grammar_notation.pyAdded+262
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/graph.pyAdded+108
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/graphics.pyAdded+794
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/graphql.pyAdded+176
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738""" pygments.lexers.c_like ~~~~~~~~~~~~~~~~~~~~~~
Lexers for other C-like languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, inherit, words, \ defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
from pygments.lexers.c_cpp import CLexer, CppLexerfrom pygments.lexers import _mql_builtins
__all__ = ['PikeLexer', 'NesCLexer', 'ClayLexer', 'ECLexer', 'ValaLexer', 'CudaLexer', 'SwigLexer', 'MqlLexer', 'ArduinoLexer', 'CharmciLexer', 'OmgIdlLexer', 'PromelaLexer']
class PikeLexer(CppLexer): """ For `Pike <http://pike.lysator.liu.se/>`_ source code. """ name = 'Pike' aliases = ['pike'] filenames = ['*.pike', '*.pmod'] mimetypes = ['text/x-pike'] version_added = '2.0'
tokens = { 'statements': [ (words(( 'catch', 'new', 'private', 'protected', 'public', 'gauge', 'throw', 'throws', 'class', 'interface', 'implement', 'abstract', 'extends', 'from', 'this', 'super', 'constant', 'final', 'static', 'import', 'use', 'extern', 'inline', 'proto', 'break', 'continue', 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'as', 'in', 'version', 'return', 'true', 'false', 'null', '__VERSION__', '__MAJOR__', '__MINOR__', '__BUILD__', '__REAL_VERSION__', '__REAL_MAJOR__', '__REAL_MINOR__', '__REAL_BUILD__', '__DATE__', '__TIME__', '__FILE__', '__DIR__', '__LINE__', '__AUTO_BIGNUM__', '__NT__', '__PIKE__', '__amigaos__', '_Pragma', 'static_assert', 'defined', 'sscanf'), suffix=r'\b'), Keyword), (r'(bool|int|long|float|short|double|char|string|object|void|mapping|' r'array|multiset|program|function|lambda|mixed|' r'[a-z_][a-z0-9_]*_t)\b', Keyword.Type), (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'[~!%^&*+=|?:<>/@-]', Operator), inherit, ], 'classname': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop'), # template specification (r'\s*(?=>)', Whitespace, '#pop'), ], }
class NesCLexer(CLexer): """ For `nesC <https://github.com/tinyos/nesc>`_ source code with preprocessor directives. """ name = 'nesC' aliases = ['nesc'] filenames = ['*.nc'] mimetypes = ['text/x-nescsrc'] version_added = '2.0'
tokens = { 'statements': [ (words(( 'abstract', 'as', 'async', 'atomic', 'call', 'command', 'component', 'components', 'configuration', 'event', 'extends', 'generic', 'implementation', 'includes', 'interface', 'module', 'new', 'norace', 'post', 'provides', 'signal', 'task', 'uses'), suffix=r'\b'), Keyword), (words(('nx_struct', 'nx_union', 'nx_int8_t', 'nx_int16_t', 'nx_int32_t', 'nx_int64_t', 'nx_uint8_t', 'nx_uint16_t', 'nx_uint32_t', 'nx_uint64_t'), suffix=r'\b'), Keyword.Type), inherit, ], }
class ClayLexer(RegexLexer): """ For Clay source. """ name = 'Clay' filenames = ['*.clay'] aliases = ['clay'] mimetypes = ['text/x-clay'] url = 'http://claylabs.com/clay' version_added = '2.0'
tokens = { 'root': [ (r'\s+', Whitespace), (r'//.*?$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'\b(public|private|import|as|record|variant|instance' r'|define|overload|default|external|alias' r'|rvalue|ref|forward|inline|noinline|forceinline' r'|enum|var|and|or|not|if|else|goto|return|while' r'|switch|case|break|continue|for|in|true|false|try|catch|throw' r'|finally|onerror|staticassert|eval|when|newtype' r'|__FILE__|__LINE__|__COLUMN__|__ARG__' r')\b', Keyword), (r'[~!%^&*+=|:<>/-]', Operator), (r'[#(){}\[\],;.]', Punctuation), (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex), (r'\d+[LlUu]*', Number.Integer), (r'\b(true|false)\b', Name.Builtin), (r'(?i)[a-z_?][\w?]*', Name), (r'"""', String, 'tdqs'), (r'"', String, 'dqs'), ], 'strings': [ (r'(?i)\\(x[0-9a-f]{2}|.)', String.Escape), (r'[^\\"]+', String), ], 'nl': [ (r'\n', String), ], 'dqs': [ (r'"', String, '#pop'), include('strings'), ], 'tdqs': [ (r'"""', String, '#pop'), include('strings'), include('nl'), ], }
class ECLexer(CLexer): """ For eC source code with preprocessor directives. """ name = 'eC' aliases = ['ec'] filenames = ['*.ec', '*.eh'] mimetypes = ['text/x-echdr', 'text/x-ecsrc'] url = 'https://ec-lang.org' version_added = '1.5'
tokens = { 'statements': [ (words(( 'virtual', 'class', 'private', 'public', 'property', 'import', 'delete', 'new', 'new0', 'renew', 'renew0', 'define', 'get', 'set', 'remote', 'dllexport', 'dllimport', 'stdcall', 'subclass', '__on_register_module', 'namespace', 'using', 'typed_object', 'any_object', 'incref', 'register', 'watch', 'stopwatching', 'firewatchers', 'watchable', 'class_designer', 'class_fixed', 'class_no_expansion', 'isset', 'class_default_property', 'property_category', 'class_data', 'class_property', 'thisclass', 'dbtable', 'dbindex', 'database_open', 'dbfield'), suffix=r'\b'), Keyword), (words(('uint', 'uint16', 'uint32', 'uint64', 'bool', 'byte', 'unichar', 'int64'), suffix=r'\b'), Keyword.Type), (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(null|value|this)\b', Name.Builtin), inherit, ] }
class ValaLexer(RegexLexer): """ For Vala source code with preprocessor directives. """ name = 'Vala' aliases = ['vala', 'vapi'] filenames = ['*.vala', '*.vapi'] mimetypes = ['text/x-vala'] url = 'https://vala.dev' version_added = '1.1'
tokens = { 'whitespace': [ (r'^\s*#if\s+0', Comment.Preproc, 'if0'), (r'\n', Whitespace), (r'\s+', Whitespace), (r'\\\n', Text), # line continuation (r'//(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), ], 'statements': [ (r'[L@]?"', String, 'string'), (r"L?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'(?s)""".*?"""', String), # verbatim strings (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'0x[0-9a-fA-F]+[Ll]?', Number.Hex), (r'0[0-7]+[Ll]?', Number.Oct), (r'\d+[Ll]?', Number.Integer), (r'[~!%^&*+=|?:<>/-]', Operator), (r'(\[)(Compact|Immutable|(?:Boolean|Simple)Type)(\])', bygroups(Punctuation, Name.Decorator, Punctuation)), # TODO: "correctly" parse complex code attributes (r'(\[)(CCode|(?:Integer|Floating)Type)', bygroups(Punctuation, Name.Decorator)), (r'[()\[\],.]', Punctuation), (words(( 'as', 'base', 'break', 'case', 'catch', 'construct', 'continue', 'default', 'delete', 'do', 'else', 'enum', 'finally', 'for', 'foreach', 'get', 'if', 'in', 'is', 'lock', 'new', 'out', 'params', 'return', 'set', 'sizeof', 'switch', 'this', 'throw', 'try', 'typeof', 'while', 'yield'), suffix=r'\b'), Keyword), (words(( 'abstract', 'const', 'delegate', 'dynamic', 'ensures', 'extern', 'inline', 'internal', 'override', 'owned', 'private', 'protected', 'public', 'ref', 'requires', 'signal', 'static', 'throws', 'unowned', 'var', 'virtual', 'volatile', 'weak', 'yields'), suffix=r'\b'), Keyword.Declaration), (r'(namespace|using)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'namespace'), (r'(class|errordomain|interface|struct)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'(\.)([a-zA-Z_]\w*)', bygroups(Operator, Name.Attribute)), # void is an actual keyword, others are in glib-2.0.vapi (words(( 'void', 'bool', 'char', 'double', 'float', 'int', 'int8', 'int16', 'int32', 'int64', 'long', 'short', 'size_t', 'ssize_t', 'string', 'time_t', 'uchar', 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'ulong', 'unichar', 'ushort'), suffix=r'\b'), Keyword.Type), (r'(true|false|null)\b', Name.Builtin), (r'[a-zA-Z_]\w*', Name), ], 'root': [ include('whitespace'), default('statement'), ], 'statement': [ include('whitespace'), include('statements'), ('[{}]', Punctuation), (';', Punctuation, '#pop'), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ], 'if0': [ (r'^\s*#if.*?(?<!\\)\n', Comment.Preproc, '#push'), (r'^\s*#el(?:se|if).*\n', Comment.Preproc, '#pop'), (r'^\s*#endif.*?(?<!\\)\n', Comment.Preproc, '#pop'), (r'.*?\n', Comment), ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'namespace': [ (r'[a-zA-Z_][\w.]*', Name.Namespace, '#pop') ], }
class CudaLexer(CLexer): """ For NVIDIA CUDA™ source. """ name = 'CUDA' filenames = ['*.cu', '*.cuh'] aliases = ['cuda', 'cu'] mimetypes = ['text/x-cuda'] url = 'https://developer.nvidia.com/category/zone/cuda-zone' version_added = '1.6'
function_qualifiers = {'__device__', '__global__', '__host__', '__noinline__', '__forceinline__'} variable_qualifiers = {'__device__', '__constant__', '__shared__', '__restrict__'} vector_types = {'char1', 'uchar1', 'char2', 'uchar2', 'char3', 'uchar3', 'char4', 'uchar4', 'short1', 'ushort1', 'short2', 'ushort2', 'short3', 'ushort3', 'short4', 'ushort4', 'int1', 'uint1', 'int2', 'uint2', 'int3', 'uint3', 'int4', 'uint4', 'long1', 'ulong1', 'long2', 'ulong2', 'long3', 'ulong3', 'long4', 'ulong4', 'longlong1', 'ulonglong1', 'longlong2', 'ulonglong2', 'float1', 'float2', 'float3', 'float4', 'double1', 'double2', 'dim3'} variables = {'gridDim', 'blockIdx', 'blockDim', 'threadIdx', 'warpSize'} functions = {'__threadfence_block', '__threadfence', '__threadfence_system', '__syncthreads', '__syncthreads_count', '__syncthreads_and', '__syncthreads_or'} execution_confs = {'<<<', '>>>'}
def get_tokens_unprocessed(self, text, stack=('root',)): for index, token, value in CLexer.get_tokens_unprocessed(self, text, stack): if token is Name: if value in self.variable_qualifiers: token = Keyword.Type elif value in self.vector_types: token = Keyword.Type elif value in self.variables: token = Name.Builtin elif value in self.execution_confs: token = Keyword.Pseudo elif value in self.function_qualifiers: token = Keyword.Reserved elif value in self.functions: token = Name.Function yield index, token, value
class SwigLexer(CppLexer): """ For `SWIG <http://www.swig.org/>`_ source code. """ name = 'SWIG' aliases = ['swig'] filenames = ['*.swg', '*.i'] mimetypes = ['text/swig'] version_added = '2.0' priority = 0.04 # Lower than C/C++ and Objective C/C++
tokens = { 'root': [ # Match it here so it won't be matched as a function in the rest of root (r'\$\**\&?\w+', Name), inherit ], 'statements': [ # SWIG directives (r'(%[a-z_][a-z0-9_]*)', Name.Function), # Special variables (r'\$\**\&?\w+', Name), # Stringification / additional preprocessor directives (r'##*[a-zA-Z_]\w*', Comment.Preproc), inherit, ], }
# This is a far from complete set of SWIG directives swig_directives = { # Most common directives '%apply', '%define', '%director', '%enddef', '%exception', '%extend', '%feature', '%fragment', '%ignore', '%immutable', '%import', '%include', '%inline', '%insert', '%module', '%newobject', '%nspace', '%pragma', '%rename', '%shared_ptr', '%template', '%typecheck', '%typemap', # Less common directives '%arg', '%attribute', '%bang', '%begin', '%callback', '%catches', '%clear', '%constant', '%copyctor', '%csconst', '%csconstvalue', '%csenum', '%csmethodmodifiers', '%csnothrowexception', '%default', '%defaultctor', '%defaultdtor', '%defined', '%delete', '%delobject', '%descriptor', '%exceptionclass', '%exceptionvar', '%extend_smart_pointer', '%fragments', '%header', '%ifcplusplus', '%ignorewarn', '%implicit', '%implicitconv', '%init', '%javaconst', '%javaconstvalue', '%javaenum', '%javaexception', '%javamethodmodifiers', '%kwargs', '%luacode', '%mutable', '%naturalvar', '%nestedworkaround', '%perlcode', '%pythonabc', '%pythonappend', '%pythoncallback', '%pythoncode', '%pythondynamic', '%pythonmaybecall', '%pythonnondynamic', '%pythonprepend', '%refobject', '%shadow', '%sizeof', '%trackobjects', '%types', '%unrefobject', '%varargs', '%warn', '%warnfilter'}
def analyse_text(text): rv = 0 # Search for SWIG directives, which are conventionally at the beginning of # a line. The probability of them being within a line is low, so let another # lexer win in this case. matches = re.findall(r'^\s*(%[a-z_][a-z0-9_]*)', text, re.M) for m in matches: if m in SwigLexer.swig_directives: rv = 0.98 break else: rv = 0.91 # Fraction higher than MatlabLexer return rv
class MqlLexer(CppLexer): """ For `MQL4 <http://docs.mql4.com/>`_ and `MQL5 <http://www.mql5.com/en/docs>`_ source code. """ name = 'MQL' aliases = ['mql', 'mq4', 'mq5', 'mql4', 'mql5'] filenames = ['*.mq4', '*.mq5', '*.mqh'] mimetypes = ['text/x-mql'] version_added = '2.0'
tokens = { 'statements': [ (words(_mql_builtins.keywords, suffix=r'\b'), Keyword), (words(_mql_builtins.c_types, suffix=r'\b'), Keyword.Type), (words(_mql_builtins.types, suffix=r'\b'), Name.Function), (words(_mql_builtins.constants, suffix=r'\b'), Name.Constant), (words(_mql_builtins.colors, prefix='(clr)?', suffix=r'\b'), Name.Constant), inherit, ], }
class ArduinoLexer(CppLexer): """ For `Arduino(tm) <https://arduino.cc/>`_ source.
This is an extension of the CppLexer, as the Arduino® Language is a superset of C++ """
name = 'Arduino' aliases = ['arduino'] filenames = ['*.ino'] mimetypes = ['text/x-arduino'] version_added = '2.1'
# Language sketch main structure functions structure = {'setup', 'loop'}
# Language operators operators = {'not', 'or', 'and', 'xor'}
# Language 'variables' variables = { 'DIGITAL_MESSAGE', 'FIRMATA_STRING', 'ANALOG_MESSAGE', 'REPORT_DIGITAL', 'REPORT_ANALOG', 'INPUT_PULLUP', 'SET_PIN_MODE', 'INTERNAL2V56', 'SYSTEM_RESET', 'LED_BUILTIN', 'INTERNAL1V1', 'SYSEX_START', 'INTERNAL', 'EXTERNAL', 'HIGH', 'LOW', 'INPUT', 'OUTPUT', 'INPUT_PULLUP', 'LED_BUILTIN', 'true', 'false', 'void', 'boolean', 'char', 'unsigned char', 'byte', 'int', 'unsigned int', 'word', 'long', 'unsigned long', 'short', 'float', 'double', 'string', 'String', 'array', 'static', 'volatile', 'const', 'boolean', 'byte', 'word', 'string', 'String', 'array', 'int', 'float', 'private', 'char', 'virtual', 'operator', 'sizeof', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'dynamic_cast', 'typedef', 'const_cast', 'const', 'struct', 'static_cast', 'union', 'unsigned', 'long', 'volatile', 'static', 'protected', 'bool', 'public', 'friend', 'auto', 'void', 'enum', 'extern', 'class', 'short', 'reinterpret_cast', 'double', 'register', 'explicit', 'signed', 'inline', 'delete', '_Bool', 'complex', '_Complex', '_Imaginary', 'atomic_bool', 'atomic_char', 'atomic_schar', 'atomic_uchar', 'atomic_short', 'atomic_ushort', 'atomic_int', 'atomic_uint', 'atomic_long', 'atomic_ulong', 'atomic_llong', 'atomic_ullong', 'PROGMEM'}
# Language shipped functions and class ( ) functions = { 'KeyboardController', 'MouseController', 'SoftwareSerial', 'EthernetServer', 'EthernetClient', 'LiquidCrystal', 'RobotControl', 'GSMVoiceCall', 'EthernetUDP', 'EsploraTFT', 'HttpClient', 'RobotMotor', 'WiFiClient', 'GSMScanner', 'FileSystem', 'Scheduler', 'GSMServer', 'YunClient', 'YunServer', 'IPAddress', 'GSMClient', 'GSMModem', 'Keyboard', 'Ethernet', 'Console', 'GSMBand', 'Esplora', 'Stepper', 'Process', 'WiFiUDP', 'GSM_SMS', 'Mailbox', 'USBHost', 'Firmata', 'PImage', 'Client', 'Server', 'GSMPIN', 'FileIO', 'Bridge', 'Serial', 'EEPROM', 'Stream', 'Mouse', 'Audio', 'Servo', 'File', 'Task', 'GPRS', 'WiFi', 'Wire', 'TFT', 'GSM', 'SPI', 'SD', 'runShellCommandAsynchronously', 'analogWriteResolution', 'retrieveCallingNumber', 'printFirmwareVersion', 'analogReadResolution', 'sendDigitalPortPair', 'noListenOnLocalhost', 'readJoystickButton', 'setFirmwareVersion', 'readJoystickSwitch', 'scrollDisplayRight', 'getVoiceCallStatus', 'scrollDisplayLeft', 'writeMicroseconds', 'delayMicroseconds', 'beginTransmission', 'getSignalStrength', 'runAsynchronously', 'getAsynchronously', 'listenOnLocalhost', 'getCurrentCarrier', 'readAccelerometer', 'messageAvailable', 'sendDigitalPorts', 'lineFollowConfig', 'countryNameWrite', 'runShellCommand', 'readStringUntil', 'rewindDirectory', 'readTemperature', 'setClockDivider', 'readLightSensor', 'endTransmission', 'analogReference', 'detachInterrupt', 'countryNameRead', 'attachInterrupt', 'encryptionType', 'readBytesUntil', 'robotNameWrite', 'readMicrophone', 'robotNameRead', 'cityNameWrite', 'userNameWrite', 'readJoystickY', 'readJoystickX', 'mouseReleased', 'openNextFile', 'scanNetworks', 'noInterrupts', 'digitalWrite', 'beginSpeaker', 'mousePressed', 'isActionDone', 'mouseDragged', 'displayLogos', 'noAutoscroll', 'addParameter', 'remoteNumber', 'getModifiers', 'keyboardRead', 'userNameRead', 'waitContinue', 'processInput', 'parseCommand', 'printVersion', 'readNetworks', 'writeMessage', 'blinkVersion', 'cityNameRead', 'readMessage', 'setDataMode', 'parsePacket', 'isListening', 'setBitOrder', 'beginPacket', 'isDirectory', 'motorsWrite', 'drawCompass', 'digitalRead', 'clearScreen', 'serialEvent', 'rightToLeft', 'setTextSize', 'leftToRight', 'requestFrom', 'keyReleased', 'compassRead', 'analogWrite', 'interrupts', 'WiFiServer', 'disconnect', 'playMelody', 'parseFloat', 'autoscroll', 'getPINUsed', 'setPINUsed', 'setTimeout', 'sendAnalog', 'readSlider', 'analogRead', 'beginWrite', 'createChar', 'motorsStop', 'keyPressed', 'tempoWrite', 'readButton', 'subnetMask', 'debugPrint', 'macAddress', 'writeGreen', 'randomSeed', 'attachGPRS', 'readString', 'sendString', 'remotePort', 'releaseAll', 'mouseMoved', 'background', 'getXChange', 'getYChange', 'answerCall', 'getResult', 'voiceCall', 'endPacket', 'constrain', 'getSocket', 'writeJSON', 'getButton', 'available', 'connected', 'findUntil', 'readBytes', 'exitValue', 'readGreen', 'writeBlue', 'startLoop', 'IPAddress', 'isPressed', 'sendSysex', 'pauseMode', 'gatewayIP', 'setCursor', 'getOemKey', 'tuneWrite', 'noDisplay', 'loadImage', 'switchPIN', 'onRequest', 'onReceive', 'changePIN', 'playFile', 'noBuffer', 'parseInt', 'overflow', 'checkPIN', 'knobRead', 'beginTFT', 'bitClear', 'updateIR', 'bitWrite', 'position', 'writeRGB', 'highByte', 'writeRed', 'setSpeed', 'readBlue', 'noStroke', 'remoteIP', 'transfer', 'shutdown', 'hangCall', 'beginSMS', 'endWrite', 'attached', 'maintain', 'noCursor', 'checkReg', 'checkPUK', 'shiftOut', 'isValid', 'shiftIn', 'pulseIn', 'connect', 'println', 'localIP', 'pinMode', 'getIMEI', 'display', 'noBlink', 'process', 'getBand', 'running', 'beginSD', 'drawBMP', 'lowByte', 'setBand', 'release', 'bitRead', 'prepare', 'pointTo', 'readRed', 'setMode', 'noFill', 'remove', 'listen', 'stroke', 'detach', 'attach', 'noTone', 'exists', 'buffer', 'height', 'bitSet', 'circle', 'config', 'cursor', 'random', 'IRread', 'setDNS', 'endSMS', 'getKey', 'micros', 'millis', 'begin', 'print', 'write', 'ready', 'flush', 'width', 'isPIN', 'blink', 'clear', 'press', 'mkdir', 'rmdir', 'close', 'point', 'yield', 'image', 'BSSID', 'click', 'delay', 'read', 'text', 'move', 'peek', 'beep', 'rect', 'line', 'open', 'seek', 'fill', 'size', 'turn', 'stop', 'home', 'find', 'step', 'tone', 'sqrt', 'RSSI', 'SSID', 'end', 'bit', 'tan', 'cos', 'sin', 'pow', 'map', 'abs', 'max', 'min', 'get', 'run', 'put', 'isAlphaNumeric', 'isAlpha', 'isAscii', 'isWhitespace', 'isControl', 'isDigit', 'isGraph', 'isLowerCase', 'isPrintable', 'isPunct', 'isSpace', 'isUpperCase', 'isHexadecimalDigit'}
# do not highlight suppress_highlight = { 'namespace', 'template', 'mutable', 'using', 'asm', 'typeid', 'typename', 'this', 'alignof', 'constexpr', 'decltype', 'noexcept', 'static_assert', 'thread_local', 'restrict'}
def get_tokens_unprocessed(self, text, stack=('root',)): for index, token, value in CppLexer.get_tokens_unprocessed(self, text, stack): if value in self.structure: yield index, Name.Builtin, value elif value in self.operators: yield index, Operator, value elif value in self.variables: yield index, Keyword.Reserved, value elif value in self.suppress_highlight: yield index, Name, value elif value in self.functions: yield index, Name.Function, value else: yield index, token, value
class CharmciLexer(CppLexer): """ For `Charm++ <https://charm.cs.illinois.edu>`_ interface files (.ci). """
name = 'Charmci' aliases = ['charmci'] filenames = ['*.ci'] version_added = '2.4'
mimetypes = []
tokens = { 'keywords': [ (r'(module)(\s+)', bygroups(Keyword, Text), 'classname'), (words(('mainmodule', 'mainchare', 'chare', 'array', 'group', 'nodegroup', 'message', 'conditional')), Keyword), (words(('entry', 'aggregate', 'threaded', 'sync', 'exclusive', 'nokeep', 'notrace', 'immediate', 'expedited', 'inline', 'local', 'python', 'accel', 'readwrite', 'writeonly', 'accelblock', 'memcritical', 'packed', 'varsize', 'initproc', 'initnode', 'initcall', 'stacksize', 'createhere', 'createhome', 'reductiontarget', 'iget', 'nocopy', 'mutable', 'migratable', 'readonly')), Keyword), inherit, ], }
class OmgIdlLexer(CLexer): """ Lexer for Object Management Group Interface Definition Language. """
name = 'OMG Interface Definition Language' url = 'https://www.omg.org/spec/IDL/About-IDL/' aliases = ['omg-idl'] filenames = ['*.idl', '*.pidl'] mimetypes = [] version_added = '2.9'
scoped_name = r'((::)?\w+)+'
tokens = { 'values': [ (words(('true', 'false'), prefix=r'(?i)', suffix=r'\b'), Number), (r'([Ll]?)(")', bygroups(String.Affix, String.Double), 'string'), (r'([Ll]?)(\')(\\[^\']+)(\')', bygroups(String.Affix, String.Char, String.Escape, String.Char)), (r'([Ll]?)(\')(\\\')(\')', bygroups(String.Affix, String.Char, String.Escape, String.Char)), (r'([Ll]?)(\'.\')', bygroups(String.Affix, String.Char)), (r'[+-]?\d+(\.\d*)?[Ee][+-]?\d+', Number.Float), (r'[+-]?(\d+\.\d*)|(\d*\.\d+)([Ee][+-]?\d+)?', Number.Float), (r'(?i)[+-]?0x[0-9a-f]+', Number.Hex), (r'[+-]?[1-9]\d*', Number.Integer), (r'[+-]?0[0-7]*', Number.Oct), (r'[\+\-\*\/%^&\|~]', Operator), (words(('<<', '>>')), Operator), (scoped_name, Name), (r'[{};:,<>\[\]]', Punctuation), ], 'annotation_params': [ include('whitespace'), (r'\(', Punctuation, '#push'), include('values'), (r'=', Punctuation), (r'\)', Punctuation, '#pop'), ], 'annotation_params_maybe': [ (r'\(', Punctuation, 'annotation_params'), include('whitespace'), default('#pop'), ], 'annotation_appl': [ (r'@' + scoped_name, Name.Decorator, 'annotation_params_maybe'), ], 'enum': [ include('whitespace'), (r'[{,]', Punctuation), (r'\w+', Name.Constant), include('annotation_appl'), (r'\}', Punctuation, '#pop'), ], 'root': [ include('whitespace'), (words(( 'typedef', 'const', 'in', 'out', 'inout', 'local', ), prefix=r'(?i)', suffix=r'\b'), Keyword.Declaration), (words(( 'void', 'any', 'native', 'bitfield', 'unsigned', 'boolean', 'char', 'wchar', 'octet', 'short', 'long', 'int8', 'uint8', 'int16', 'int32', 'int64', 'uint16', 'uint32', 'uint64', 'float', 'double', 'fixed', 'sequence', 'string', 'wstring', 'map', ), prefix=r'(?i)', suffix=r'\b'), Keyword.Type), (words(( '@annotation', 'struct', 'union', 'bitset', 'interface', 'exception', 'valuetype', 'eventtype', 'component', ), prefix=r'(?i)', suffix=r'(\s+)(\w+)'), bygroups(Keyword, Whitespace, Name.Class)), (words(( 'abstract', 'alias', 'attribute', 'case', 'connector', 'consumes', 'context', 'custom', 'default', 'emits', 'factory', 'finder', 'getraises', 'home', 'import', 'manages', 'mirrorport', 'multiple', 'Object', 'oneway', 'primarykey', 'private', 'port', 'porttype', 'provides', 'public', 'publishes', 'raises', 'readonly', 'setraises', 'supports', 'switch', 'truncatable', 'typeid', 'typename', 'typeprefix', 'uses', 'ValueBase', ), prefix=r'(?i)', suffix=r'\b'), Keyword), (r'(?i)(enum|bitmask)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Class), 'enum'), (r'(?i)(module)(\s+)(\w+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r'(\w+)(\s*)(=)', bygroups(Name.Constant, Whitespace, Operator)), (r'[\(\)]', Punctuation), include('values'), include('annotation_appl'), ], }
class PromelaLexer(CLexer): """ For the Promela language used with SPIN. """ name = 'Promela' aliases = ['promela'] filenames = ['*.pml', '*.prom', '*.prm', '*.promela', '*.pr', '*.pm'] mimetypes = ['text/x-promela'] url = 'https://spinroot.com/spin/whatispin.html' version_added = '2.18'
# Promela's language reference: # https://spinroot.com/spin/Man/promela.html # Promela's grammar definition: # https://spinroot.com/spin/Man/grammar.html
tokens = { 'statements': [ (r'(\[\]|<>|/\\|\\/)|(U|W|V)\b', Operator), # LTL Operators (r'@', Punctuation), #remoterefs (r'(\.)([a-zA-Z_]\w*)', bygroups(Operator, Name.Attribute)), inherit ], 'types': [ # Predefined (data types) (words(( 'bit', 'bool', 'byte', 'pid', 'short', 'int', 'unsigned'), suffix=r'\b'), Keyword.Type), ], 'keywords': [ # ControlFlow (words(( 'atomic', 'break', 'd_step', 'do', 'od', 'for', 'in', 'goto', 'if', 'fi', 'unless'), suffix=r'\b'), Keyword), # BasicStatements (words(( 'assert', 'get_priority', 'printf', 'printm', 'set_priority'), suffix=r'\b'), Name.Function), # Embedded C Code (words(( 'c_code', 'c_decl', 'c_expr', 'c_state', 'c_track'), suffix=r'\b'), Keyword), # Predefined (local/global variables) (words(( '_', '_last', '_nr_pr', '_pid', '_priority', 'else', 'np_', 'STDIN'), suffix=r'\b'), Name.Builtin), # Predefined (functions) (words(( 'empty', 'enabled', 'eval', 'full', 'len', 'nempty', 'nfull', 'pc_value'), suffix=r'\b'), Name.Function), # Predefined (operators) (r'run\b', Operator.Word), # Declarators (words(( 'active', 'chan', 'D_proctype', 'hidden', 'init', 'local', 'mtype', 'never', 'notrace', 'proctype', 'show', 'trace', 'typedef', 'xr', 'xs'), suffix=r'\b'), Keyword.Declaration), # Declarators (suffixes) (words(( 'priority', 'provided'), suffix=r'\b'), Keyword), # MetaTerms (declarators) (words(( 'inline', 'ltl', 'select'), suffix=r'\b'), Keyword.Declaration), # MetaTerms (keywords) (r'skip\b', Keyword), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172""" pygments.lexers.cddl ~~~~~~~~~~~~~~~~~~~~
Lexer for the Concise data definition language (CDDL), a notational convention to express CBOR and JSON data structures.
More information: https://datatracker.ietf.org/doc/rfc8610/
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, wordsfrom pygments.token import Comment, Error, Keyword, Name, Number, Operator, \ Punctuation, String, Whitespace
__all__ = ['CddlLexer']
class CddlLexer(RegexLexer): """ Lexer for CDDL definitions. """ name = "CDDL" url = 'https://datatracker.ietf.org/doc/rfc8610/' aliases = ["cddl"] filenames = ["*.cddl"] mimetypes = ["text/x-cddl"] version_added = '2.8'
_prelude_types = [ "any", "b64legacy", "b64url", "bigfloat", "bigint", "bignint", "biguint", "bool", "bstr", "bytes", "cbor-any", "decfrac", "eb16", "eb64legacy", "eb64url", "encoded-cbor", "false", "float", "float16", "float16-32", "float32", "float32-64", "float64", "int", "integer", "mime-message", "nil", "nint", "null", "number", "regexp", "tdate", "text", "time", "true", "tstr", "uint", "undefined", "unsigned", "uri", ]
_controls = [ ".and", ".bits", ".cbor", ".cborseq", ".default", ".eq", ".ge", ".gt", ".le", ".lt", ".ne", ".regexp", ".size", ".within", ]
_re_id = ( r"[$@A-Z_a-z]" r"(?:[\-\.]+(?=[$@0-9A-Z_a-z])|[$@0-9A-Z_a-z])*"
)
# While the spec reads more like "an int must not start with 0" we use a # lookahead here that says "after a 0 there must be no digit". This makes the # '0' the invalid character in '01', which looks nicer when highlighted. _re_uint = r"(?:0b[01]+|0x[0-9a-fA-F]+|[1-9]\d*|0(?!\d))" _re_int = r"-?" + _re_uint
tokens = { "commentsandwhitespace": [(r"\s+", Whitespace), (r";.+$", Comment.Single)], "root": [ include("commentsandwhitespace"), # tag types (rf"#(\d\.{_re_uint})?", Keyword.Type), # type or any # occurrence ( rf"({_re_uint})?(\*)({_re_uint})?", bygroups(Number, Operator, Number), ), (r"\?|\+", Operator), # occurrence (r"\^", Operator), # cuts (r"(\.\.\.|\.\.)", Operator), # rangeop (words(_controls, suffix=r"\b"), Operator.Word), # ctlops # into choice op (rf"&(?=\s*({_re_id}|\())", Operator), (rf"~(?=\s*{_re_id})", Operator), # unwrap op (r"//|/(?!/)", Operator), # double und single slash (r"=>|/==|/=|=", Operator), (r"[\[\]{}\(\),<>:]", Punctuation), # Bytestrings (r"(b64)(')", bygroups(String.Affix, String.Single), "bstrb64url"), (r"(h)(')", bygroups(String.Affix, String.Single), "bstrh"), (r"'", String.Single, "bstr"), # Barewords as member keys (must be matched before values, types, typenames, # groupnames). # Token type is String as barewords are always interpreted as such. (rf"({_re_id})(\s*)(:)", bygroups(String, Whitespace, Punctuation)), # predefined types (words(_prelude_types, prefix=r"(?![\-_$@])\b", suffix=r"\b(?![\-_$@])"), Name.Builtin), # user-defined groupnames, typenames (_re_id, Name.Class), # values (r"0b[01]+", Number.Bin), (r"0o[0-7]+", Number.Oct), (r"0x[0-9a-fA-F]+(\.[0-9a-fA-F]+)?p[+-]?\d+", Number.Hex), # hexfloat (r"0x[0-9a-fA-F]+", Number.Hex), # hex # Float (rf"{_re_int}(?=(\.\d|e[+-]?\d))(?:\.\d+)?(?:e[+-]?\d+)?", Number.Float), # Int (_re_int, Number.Integer), (r'"(\\\\|\\"|[^"])*"', String.Double), ], "bstrb64url": [ (r"'", String.Single, "#pop"), include("commentsandwhitespace"), (r"\\.", String.Escape), (r"[0-9a-zA-Z\-_=]+", String.Single), (r".", Error), # (r";.+$", Token.Other), ], "bstrh": [ (r"'", String.Single, "#pop"), include("commentsandwhitespace"), (r"\\.", String.Escape), (r"[0-9a-fA-F]+", String.Single), (r".", Error), ], "bstr": [ (r"'", String.Single, "#pop"), (r"\\.", String.Escape), (r"[^'\\]+", String.Single), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180""" pygments.lexers.clean ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Clean language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import ExtendedRegexLexer, words, default, include, bygroupsfrom pygments.token import Comment, Error, Keyword, Literal, Name, Number, \ Operator, Punctuation, String, Whitespace
__all__ = ['CleanLexer']
class CleanLexer(ExtendedRegexLexer): """ Lexer for the general purpose, state-of-the-art, pure and lazy functional programming language Clean.
.. versionadded: 2.2 """ name = 'Clean' url = 'http://clean.cs.ru.nl/Clean' aliases = ['clean'] filenames = ['*.icl', '*.dcl'] version_added = ''
keywords = ( 'case', 'ccall', 'class', 'code', 'code inline', 'derive', 'export', 'foreign', 'generic', 'if', 'in', 'infix', 'infixl', 'infixr', 'instance', 'let', 'of', 'otherwise', 'special', 'stdcall', 'where', 'with')
modulewords = ('implementation', 'definition', 'system')
lowerId = r'[a-z`][\w`]*' upperId = r'[A-Z`][\w`]*' funnyId = r'[~@#$%\^?!+\-*<>\\/|&=:]+' scoreUpperId = r'_' + upperId scoreLowerId = r'_' + lowerId moduleId = r'[a-zA-Z_][a-zA-Z0-9_.`]+' classId = '|'.join([lowerId, upperId, funnyId])
tokens = { 'root': [ include('comments'), include('keywords'), include('module'), include('import'), include('whitespace'), include('literals'), include('operators'), include('delimiters'), include('names'), ], 'whitespace': [ (r'\s+', Whitespace), ], 'comments': [ (r'//.*\n', Comment.Single), (r'/\*', Comment.Multiline, 'comments.in'), (r'/\*\*', Comment.Special, 'comments.in'), ], 'comments.in': [ (r'\*\/', Comment.Multiline, '#pop'), (r'/\*', Comment.Multiline, '#push'), (r'[^*/]+', Comment.Multiline), (r'\*(?!/)', Comment.Multiline), (r'/', Comment.Multiline), ], 'keywords': [ (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword), ], 'module': [ (words(modulewords, prefix=r'\b', suffix=r'\b'), Keyword.Namespace), (r'\bmodule\b', Keyword.Namespace, 'module.name'), ], 'module.name': [ include('whitespace'), (moduleId, Name.Class, '#pop'), ], 'import': [ (r'\b(import)\b(\s*)', bygroups(Keyword, Whitespace), 'import.module'), (r'\b(from)\b(\s*)\b(' + moduleId + r')\b(\s*)\b(import)\b', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Keyword), 'import.what'), ], 'import.module': [ (r'\b(qualified)\b(\s*)', bygroups(Keyword, Whitespace)), (r'(\s*)\b(as)\b', bygroups(Whitespace, Keyword), ('#pop', 'import.module.as')), (moduleId, Name.Class), (r'(\s*)(,)(\s*)', bygroups(Whitespace, Punctuation, Whitespace)), (r'\s+', Whitespace), default('#pop'), ], 'import.module.as': [ include('whitespace'), (lowerId, Name.Class, '#pop'), (upperId, Name.Class, '#pop'), ], 'import.what': [ (r'\b(class)\b(\s+)(' + classId + r')', bygroups(Keyword, Whitespace, Name.Class), 'import.what.class'), (r'\b(instance)(\s+)(' + classId + r')(\s+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace), 'import.what.instance'), (r'(::)(\s*)\b(' + upperId + r')\b', bygroups(Punctuation, Whitespace, Name.Class), 'import.what.type'), (r'\b(generic)\b(\s+)\b(' + lowerId + '|' + upperId + r')\b', bygroups(Keyword, Whitespace, Name)), include('names'), (r'(,)(\s+)', bygroups(Punctuation, Whitespace)), (r'$', Whitespace, '#pop'), include('whitespace'), ], 'import.what.class': [ (r',', Punctuation, '#pop'), (r'\(', Punctuation, 'import.what.class.members'), (r'$', Whitespace, '#pop:2'), include('whitespace'), ], 'import.what.class.members': [ (r',', Punctuation), (r'\.\.', Punctuation), (r'\)', Punctuation, '#pop'), include('names'), ], 'import.what.instance': [ (r'[,)]', Punctuation, '#pop'), (r'\(', Punctuation, 'import.what.instance'), (r'$', Whitespace, '#pop:2'), include('whitespace'), include('names'), ], 'import.what.type': [ (r',', Punctuation, '#pop'), (r'[({]', Punctuation, 'import.what.type.consesandfields'), (r'$', Whitespace, '#pop:2'), include('whitespace'), ], 'import.what.type.consesandfields': [ (r',', Punctuation), (r'\.\.', Punctuation), (r'[)}]', Punctuation, '#pop'), include('names'), ], 'literals': [ (r'\'([^\'\\]|\\(x[\da-fA-F]+|\d+|.))\'', Literal.Char), (r'[+~-]?0[0-7]+\b', Number.Oct), (r'[+~-]?\d+\.\d+(E[+-]?\d+)?', Number.Float), (r'[+~-]?\d+\b', Number.Integer), (r'[+~-]?0x[\da-fA-F]+\b', Number.Hex), (r'True|False', Literal), (r'"', String.Double, 'literals.stringd'), ], 'literals.stringd': [ (r'[^\\"\n]+', String.Double), (r'"', String.Double, '#pop'), (r'\\.', String.Double), (r'[$\n]', Error, '#pop'), ], 'operators': [ (r'[-~@#$%\^?!+*<>\\/|&=:.]+', Operator), (r'\b_+\b', Operator), ], 'delimiters': [ (r'[,;(){}\[\]]', Punctuation), (r'(\')([\w`.]+)(\')', bygroups(Punctuation, Name.Class, Punctuation)), ], 'names': [ (lowerId, Name), (scoreLowerId, Name), (funnyId, Name.Function), (upperId, Name.Class), (scoreUpperId, Name.Class), ] }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980""" pygments.lexers.codeql ~~~~~~~~~~~~~~~~~~~~~~
Lexer for CodeQL query language.
The grammar is originating from: https://github.com/github/vscode-codeql/blob/main/syntaxes/README.md
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
__all__ = ['CodeQLLexer']
import re
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
class CodeQLLexer(RegexLexer): name = 'CodeQL' aliases = ['codeql', 'ql'] filenames = ['*.ql', '*.qll'] mimetypes = [] url = 'https://github.com/github/codeql' version_added = '2.19'
flags = re.MULTILINE | re.UNICODE
tokens = { 'root': [ # Whitespace and comments (r'\s+', Whitespace), (r'//.*?\n', Comment.Single), (r'/\*', Comment.Multiline, 'multiline-comments'),
# Keywords (words(( 'module', 'import', 'class', 'extends', 'implements', 'predicate', 'select', 'where', 'from', 'as', 'and', 'or', 'not', 'in', 'if', 'then', 'else', 'exists', 'forall', 'instanceof', 'private', 'predicate', 'abstract', 'cached', 'external', 'final', 'library', 'override', 'query' ), suffix=r'\b'), Keyword.Builtin),
# Special Keywords (words(('this'), # class related keywords prefix=r'\b', suffix=r'\b\??:?'), Name.Builtin.Pseudo),
# Types (words(( 'boolean', 'date', 'float', 'int', 'string' ), suffix=r'\b'), Keyword.Type),
# Literals (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r'[0-9]+\.[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), # Operators (r'<=|>=|<|>|=|!=|\+|-|\*|/', Operator),
# Punctuation (r'[.,;:\[\]{}()]+', Punctuation),
# Identifiers (r'@[a-zA-Z_]\w*', Name.Variable), # Variables with @ prefix (r'[A-Z][a-zA-Z0-9_]*', Name.Class), # Types and classes (r'[a-z][a-zA-Z0-9_]*', Name.Variable), # Variables and predicates ], 'multiline-comments': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ],
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081""" pygments.lexers.comal ~~~~~~~~~~~~~~~~~~~~~
Lexer for COMAL-80.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Whitespace, Operator, Keyword, String, \ Number, Name, Punctuation
__all__ = ["Comal80Lexer"]
class Comal80Lexer(RegexLexer): """ For COMAL-80 source code. """
name = 'COMAL-80' url = 'https://en.wikipedia.org/wiki/COMAL' aliases = ['comal', 'comal80'] filenames = ['*.cml', '*.comal'] version_added = '' flags = re.IGNORECASE # # COMAL allows for some strange characters in names which we list here so # keywords and word operators will not be recognized at the start of an # identifier. # _suffix = r"\b(?!['\[\]←£\\])" _identifier = r"[a-z]['\[\]←£\\\w]*"
tokens = { 'root': [ (r'//.*\n', Comment.Single), (r'\s+', Whitespace), (r':[=+-]|\<\>|[-+*/^↑<>=]', Operator), (r'(and +then|or +else)' + _suffix, Operator.Word), (words([ 'and', 'bitand', 'bitor', 'bitxor', 'div', 'in', 'mod', 'not', 'or'], suffix=_suffix,), Operator.Word), (words([ 'append', 'at', 'case', 'chain', 'close', 'copy', 'create', 'cursor', 'data', 'delete', 'dir', 'do', 'elif', 'else', 'end', 'endcase', 'endif', 'endfor', 'endloop', 'endtrap', 'endwhile', 'exec', 'exit', 'file', 'for', 'goto', 'handler', 'if', 'input', 'let', 'loop', 'mount', 'null', 'of', 'open', 'otherwise', 'output', 'page', 'pass', 'poke', 'print', 'random', 'read', 'repeat', 'report', 'return', 'rename', 'restore', 'select', 'step', 'stop', 'sys', 'then', 'to', 'trap', 'unit', 'unit$', 'until', 'using', 'when', 'while', 'write', 'zone'], suffix=_suffix), Keyword.Reserved), (words([ 'closed', 'dim', 'endfunc', 'endproc', 'external', 'func', 'import', 'proc', 'ref', 'use'], suffix=_suffix), Keyword.Declaration), (words([ 'abs', 'atn', 'chr$', 'cos', 'eod', 'eof', 'err', 'errfile', 'errtext', 'esc', 'exp', 'int', 'key$', 'len', 'log', 'ord', 'peek', 'randomize', 'rnd', 'sgn', 'sin', 'spc$', 'sqr', 'status$', 'str$', 'tab', 'tan', 'time', 'val'], suffix=_suffix), Name.Builtin), (words(['false', 'pi', 'true'], suffix=_suffix), Keyword.Constant), (r'"', String, 'string'), (_identifier + r":(?=[ \n/])", Name.Label), (_identifier + r"[$#]?", Name), (r'%[01]+', Number.Bin), (r'\$[0-9a-f]+', Number.Hex), (r'\d*\.\d*(e[-+]?\d+)?', Number.Float), (r'\d+', Number.Integer), (r'[(),:;]', Punctuation), ], 'string': [ (r'[^"]+', String), (r'"[0-9]*"', String.Escape), (r'"', String, '#pop'), ], }1234567891011121314151617181920212223242526272829303132333435""" pygments.lexers.compiled ~~~~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
# ruff: noqa: F401from pygments.lexers.jvm import JavaLexer, ScalaLexerfrom pygments.lexers.c_cpp import CLexer, CppLexerfrom pygments.lexers.d import DLexerfrom pygments.lexers.objective import ObjectiveCLexer, \ ObjectiveCppLexer, LogosLexerfrom pygments.lexers.go import GoLexerfrom pygments.lexers.rust import RustLexerfrom pygments.lexers.c_like import ECLexer, ValaLexer, CudaLexerfrom pygments.lexers.pascal import DelphiLexer, PortugolLexer, Modula2Lexerfrom pygments.lexers.ada import AdaLexerfrom pygments.lexers.business import CobolLexer, CobolFreeformatLexerfrom pygments.lexers.fortran import FortranLexerfrom pygments.lexers.prolog import PrologLexerfrom pygments.lexers.python import CythonLexerfrom pygments.lexers.graphics import GLShaderLexerfrom pygments.lexers.ml import OcamlLexerfrom pygments.lexers.basic import BlitzBasicLexer, BlitzMaxLexer, MonkeyLexerfrom pygments.lexers.dylan import DylanLexer, DylanLidLexer, DylanConsoleLexerfrom pygments.lexers.ooc import OocLexerfrom pygments.lexers.felix import FelixLexerfrom pygments.lexers.nimrod import NimrodLexerfrom pygments.lexers.crystal import CrystalLexer
__all__ = []12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433""" pygments.lexers.configs ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for configuration file formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, RegexLexer, default, words, \ bygroups, include, using, line_refrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace, Literal, Error, Genericfrom pygments.lexers.shell import BashLexerfrom pygments.lexers.data import JsonLexer
__all__ = ['IniLexer', 'SystemdLexer', 'DesktopLexer', 'RegeditLexer', 'PropertiesLexer', 'KconfigLexer', 'Cfengine3Lexer', 'ApacheConfLexer', 'SquidConfLexer', 'NginxConfLexer', 'LighttpdConfLexer', 'DockerLexer', 'TerraformLexer', 'TermcapLexer', 'TerminfoLexer', 'PkgConfigLexer', 'PacmanConfLexer', 'AugeasLexer', 'TOMLLexer', 'NestedTextLexer', 'SingularityLexer', 'UnixConfigLexer']
class IniLexer(RegexLexer): """ Lexer for configuration files in INI style. """
name = 'INI' aliases = ['ini', 'cfg', 'dosini'] filenames = [ '*.ini', '*.cfg', '*.inf', '.editorconfig', ] mimetypes = ['text/x-ini', 'text/inf'] url = 'https://en.wikipedia.org/wiki/INI_file' version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace), (r'[;#].*', Comment.Single), (r'(\[.*?\])([ \t]*)$', bygroups(Keyword, Whitespace)), (r'''(.*?)([ \t]*)([=:])([ \t]*)(["'])''', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String), "quoted_value"), (r'(.*?)([ \t]*)([=:])([ \t]*)([^;#\n]*)(\\)(\s+)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, Text, Whitespace), "value"), (r'(.*?)([ \t]*)([=:])([ \t]*)([^ ;#\n]*(?: +[^ ;#\n]+)*)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), # standalone option, supported by some INI parsers (r'(.+?)$', Name.Attribute), ], 'quoted_value': [ (r'''([^"'\n]*)(["'])(\s*)''', bygroups(String, String, Whitespace), "#pop"), (r'[;#].*', Comment.Single), (r'$', String, "#pop"), ], 'value': [ # line continuation (r'\s+', Whitespace), (r'(\s*)(.*)(\\)([ \t]*)', bygroups(Whitespace, String, Text, Whitespace)), (r'.*$', String, "#pop"), ], }
def analyse_text(text): npos = text.find('\n') if npos < 3: return False if text[0] == '[' and text[npos-1] == ']': return 0.8 return False
class DesktopLexer(RegexLexer): """ Lexer for .desktop files. """
name = 'Desktop file' url = "https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html" aliases = ['desktop'] filenames = ['*.desktop'] mimetypes = ['application/x-desktop'] version_added = '2.16'
tokens = { 'root': [ (r'^[ \t]*\n', Whitespace), (r'^(#.*)(\n)', bygroups(Comment.Single, Whitespace)), (r'(\[[^\]\n]+\])(\n)', bygroups(Keyword, Whitespace)), (r'([-A-Za-z0-9]+)(\[[^\] \t=]+\])?([ \t]*)(=)([ \t]*)([^\n]*)([ \t\n]*\n)', bygroups(Name.Attribute, Name.Namespace, Whitespace, Operator, Whitespace, String, Whitespace)), ], }
def analyse_text(text): if text.startswith("[Desktop Entry]"): return 1.0 if re.search(r"^\[Desktop Entry\][ \t]*$", text[:500], re.MULTILINE) is not None: return 0.9 return 0.0
class SystemdLexer(RegexLexer): """ Lexer for systemd unit files. """
name = 'Systemd' url = "https://www.freedesktop.org/software/systemd/man/systemd.syntax.html" aliases = ['systemd'] filenames = [ '*.service', '*.socket', '*.device', '*.mount', '*.automount', '*.swap', '*.target', '*.path', '*.timer', '*.slice', '*.scope', ] version_added = '2.16'
tokens = { 'root': [ (r'^[ \t]*\n', Whitespace), (r'^([;#].*)(\n)', bygroups(Comment.Single, Whitespace)), (r'(\[[^\]\n]+\])(\n)', bygroups(Keyword, Whitespace)), (r'([^=]+)([ \t]*)(=)([ \t]*)([^\n]*)(\\)(\n)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, Text, Whitespace), "value"), (r'([^=]+)([ \t]*)(=)([ \t]*)([^\n]*)(\n)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, Whitespace)), ], 'value': [ # line continuation (r'^([;#].*)(\n)', bygroups(Comment.Single, Whitespace)), (r'([ \t]*)([^\n]*)(\\)(\n)', bygroups(Whitespace, String, Text, Whitespace)), (r'([ \t]*)([^\n]*)(\n)', bygroups(Whitespace, String, Whitespace), "#pop"), ], }
def analyse_text(text): if text.startswith("[Unit]"): return 1.0 if re.search(r"^\[Unit\][ \t]*$", text[:500], re.MULTILINE) is not None: return 0.9 return 0.0
class RegeditLexer(RegexLexer): """ Lexer for Windows Registry files produced by regedit. """
name = 'reg' url = 'http://en.wikipedia.org/wiki/Windows_Registry#.REG_files' aliases = ['registry'] filenames = ['*.reg'] mimetypes = ['text/x-windows-registry'] version_added = '1.6'
tokens = { 'root': [ (r'Windows Registry Editor.*', Text), (r'\s+', Whitespace), (r'[;#].*', Comment.Single), (r'(\[)(-?)(HKEY_[A-Z_]+)(.*?\])$', bygroups(Keyword, Operator, Name.Builtin, Keyword)), # String keys, which obey somewhat normal escaping (r'("(?:\\"|\\\\|[^"])+")([ \t]*)(=)([ \t]*)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace), 'value'), # Bare keys (includes @) (r'(.*?)([ \t]*)(=)([ \t]*)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace), 'value'), ], 'value': [ (r'-', Operator, '#pop'), # delete value (r'(dword|hex(?:\([0-9a-fA-F]\))?)(:)([0-9a-fA-F,]+)', bygroups(Name.Variable, Punctuation, Number), '#pop'), # As far as I know, .reg files do not support line continuation. (r'.+', String, '#pop'), default('#pop'), ] }
def analyse_text(text): return text.startswith('Windows Registry Editor')
class PropertiesLexer(RegexLexer): """ Lexer for configuration files in Java's properties format.
Note: trailing whitespace counts as part of the value as per spec """
name = 'Properties' aliases = ['properties', 'jproperties'] filenames = ['*.properties'] mimetypes = ['text/x-java-properties'] url = 'https://en.wikipedia.org/wiki/.properties' version_added = '1.4'
tokens = { 'root': [ # comments (r'[!#].*|/{2}.*', Comment.Single), # ending a comment or whitespace-only line (r'\n', Whitespace), # eat whitespace at the beginning of a line (r'^[^\S\n]+', Whitespace), # start lexing a key default('key'), ], 'key': [ # non-escaped key characters (r'[^\\:=\s]+', Name.Attribute), # escapes include('escapes'), # separator is the first non-escaped whitespace or colon or '=' on the line; # if it's whitespace, = and : are gobbled after it (r'([^\S\n]*)([:=])([^\S\n]*)', bygroups(Whitespace, Operator, Whitespace), ('#pop', 'value')), (r'[^\S\n]+', Whitespace, ('#pop', 'value')), # maybe we got no value after all (r'\n', Whitespace, '#pop'), ], 'value': [ # non-escaped value characters (r'[^\\\n]+', String), # escapes include('escapes'), # end the value on an unescaped newline (r'\n', Whitespace, '#pop'), ], 'escapes': [ # line continuations; these gobble whitespace at the beginning of the next line (r'(\\\n)([^\S\n]*)', bygroups(String.Escape, Whitespace)), # other escapes (r'\\(.|\n)', String.Escape), ], }
def _rx_indent(level): # Kconfig *always* interprets a tab as 8 spaces, so this is the default. # Edit this if you are in an environment where KconfigLexer gets expanded # input (tabs expanded to spaces) and the expansion tab width is != 8, # e.g. in connection with Trac (trac.ini, [mimeviewer], tab_width). # Value range here is 2 <= {tab_width} <= 8. tab_width = 8 # Regex matching a given indentation {level}, assuming that indentation is # a multiple of {tab_width}. In other cases there might be problems. if tab_width == 2: space_repeat = '+' else: space_repeat = '{1,%d}' % (tab_width - 1) if level == 1: level_repeat = '' else: level_repeat = f'{{{level}}}' return rf'(?:\t| {space_repeat}\t| {{{tab_width}}}){level_repeat}.*\n'
class KconfigLexer(RegexLexer): """ For Linux-style Kconfig files. """
name = 'Kconfig' aliases = ['kconfig', 'menuconfig', 'linux-config', 'kernel-config'] version_added = '1.6' # Adjust this if new kconfig file names appear in your environment filenames = ['Kconfig*', '*Config.in*', 'external.in*', 'standard-modules.in'] mimetypes = ['text/x-kconfig'] url = 'https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html'
# No re.MULTILINE, indentation-aware help text needs line-by-line handling flags = 0
def call_indent(level): # If indentation >= {level} is detected, enter state 'indent{level}' return (_rx_indent(level), String.Doc, f'indent{level}')
def do_indent(level): # Print paragraphs of indentation level >= {level} as String.Doc, # ignoring blank lines. Then return to 'root' state. return [ (_rx_indent(level), String.Doc), (r'\s*\n', Text), default('#pop:2') ]
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*?\n', Comment.Single), (words(( 'mainmenu', 'config', 'menuconfig', 'choice', 'endchoice', 'comment', 'menu', 'endmenu', 'visible if', 'if', 'endif', 'source', 'prompt', 'select', 'depends on', 'default', 'range', 'option'), suffix=r'\b'), Keyword), (r'(---help---|help)[\t ]*\n', Keyword, 'help'), (r'(bool|tristate|string|hex|int|defconfig_list|modules|env)\b', Name.Builtin), (r'[!=&|]', Operator), (r'[()]', Punctuation), (r'[0-9]+', Number.Integer), (r"'(''|[^'])*'", String.Single), (r'"(""|[^"])*"', String.Double), (r'\S+', Text), ], # Help text is indented, multi-line and ends when a lower indentation # level is detected. 'help': [ # Skip blank lines after help token, if any (r'\s*\n', Text), # Determine the first help line's indentation level heuristically(!). # Attention: this is not perfect, but works for 99% of "normal" # indentation schemes up to a max. indentation level of 7. call_indent(7), call_indent(6), call_indent(5), call_indent(4), call_indent(3), call_indent(2), call_indent(1), default('#pop'), # for incomplete help sections without text ], # Handle text for indentation levels 7 to 1 'indent7': do_indent(7), 'indent6': do_indent(6), 'indent5': do_indent(5), 'indent4': do_indent(4), 'indent3': do_indent(3), 'indent2': do_indent(2), 'indent1': do_indent(1), }
class Cfengine3Lexer(RegexLexer): """ Lexer for CFEngine3 policy files. """
name = 'CFEngine3' url = 'http://cfengine.org' aliases = ['cfengine3', 'cf3'] filenames = ['*.cf'] mimetypes = [] version_added = '1.5'
tokens = { 'root': [ (r'#.*?\n', Comment), (r'(body)(\s+)(\S+)(\s+)(control)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)(\()', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function, Punctuation), 'arglist'), (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function)), (r'(")([^"]+)(")(\s+)(string|slist|int|real)(\s*)(=>)(\s*)', bygroups(Punctuation, Name.Variable, Punctuation, Whitespace, Keyword.Type, Whitespace, Operator, Whitespace)), (r'(\S+)(\s*)(=>)(\s*)', bygroups(Keyword.Reserved, Whitespace, Operator, Text)), (r'"', String, 'string'), (r'(\w+)(\()', bygroups(Name.Function, Punctuation)), (r'([\w.!&|()]+)(::)', bygroups(Name.Class, Punctuation)), (r'(\w+)(:)', bygroups(Keyword.Declaration, Punctuation)), (r'@[{(][^)}]+[})]', Name.Variable), (r'[(){},;]', Punctuation), (r'=>', Operator), (r'->', Operator), (r'\d+\.\d+', Number.Float), (r'\d+', Number.Integer), (r'\w+', Name.Function), (r'\s+', Whitespace), ], 'string': [ (r'\$[{(]', String.Interpol, 'interpol'), (r'\\.', String.Escape), (r'"', String, '#pop'), (r'\n', String), (r'.', String), ], 'interpol': [ (r'\$[{(]', String.Interpol, '#push'), (r'[})]', String.Interpol, '#pop'), (r'[^${()}]+', String.Interpol), ], 'arglist': [ (r'\)', Punctuation, '#pop'), (r',', Punctuation), (r'\w+', Name.Variable), (r'\s+', Whitespace), ], }
class ApacheConfLexer(RegexLexer): """ Lexer for configuration files following the Apache config file format. """
name = 'ApacheConf' aliases = ['apacheconf', 'aconf', 'apache'] filenames = ['.htaccess', 'apache.conf', 'apache2.conf'] mimetypes = ['text/x-apacheconf'] url = 'https://httpd.apache.org/docs/current/configuring.html' version_added = '0.6' flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ (r'\s+', Whitespace), (r'#(.*\\\n)+.*$|(#.*?)$', Comment), (r'(<[^\s>/][^\s>]*)(?:(\s+)(.*))?(>)', bygroups(Name.Tag, Whitespace, String, Name.Tag)), (r'(</[^\s>]+)(>)', bygroups(Name.Tag, Name.Tag)), (r'[a-z]\w*', Name.Builtin, 'value'), (r'\.+', Text), ], 'value': [ (r'\\\n', Text), (r'\n+', Whitespace, '#pop'), (r'\\', Text), (r'[^\S\n]+', Whitespace), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'\d+', Number), (r'/([*a-z0-9][*\w./-]+)', String.Other), (r'(on|off|none|any|all|double|email|dns|min|minimal|' r'os|productonly|full|emerg|alert|crit|error|warn|' r'notice|info|debug|registry|script|inetd|standalone|' r'user|group)\b', Keyword), (r'"([^"\\]*(?:\\(.|\n)[^"\\]*)*)"', String.Double), (r'[^\s"\\]+', Text) ], }
class SquidConfLexer(RegexLexer): """ Lexer for squid configuration files. """
name = 'SquidConf' url = 'http://www.squid-cache.org/' aliases = ['squidconf', 'squid.conf', 'squid'] filenames = ['squid.conf'] mimetypes = ['text/x-squidconf'] version_added = '0.9' flags = re.IGNORECASE
keywords = ( "access_log", "acl", "always_direct", "announce_host", "announce_period", "announce_port", "announce_to", "anonymize_headers", "append_domain", "as_whois_server", "auth_param_basic", "authenticate_children", "authenticate_program", "authenticate_ttl", "broken_posts", "buffered_logs", "cache_access_log", "cache_announce", "cache_dir", "cache_dns_program", "cache_effective_group", "cache_effective_user", "cache_host", "cache_host_acl", "cache_host_domain", "cache_log", "cache_mem", "cache_mem_high", "cache_mem_low", "cache_mgr", "cachemgr_passwd", "cache_peer", "cache_peer_access", "cache_replacement_policy", "cache_stoplist", "cache_stoplist_pattern", "cache_store_log", "cache_swap", "cache_swap_high", "cache_swap_log", "cache_swap_low", "client_db", "client_lifetime", "client_netmask", "connect_timeout", "coredump_dir", "dead_peer_timeout", "debug_options", "delay_access", "delay_class", "delay_initial_bucket_level", "delay_parameters", "delay_pools", "deny_info", "dns_children", "dns_defnames", "dns_nameservers", "dns_testnames", "emulate_httpd_log", "err_html_text", "fake_user_agent", "firewall_ip", "forwarded_for", "forward_snmpd_port", "fqdncache_size", "ftpget_options", "ftpget_program", "ftp_list_width", "ftp_passive", "ftp_user", "half_closed_clients", "header_access", "header_replace", "hierarchy_stoplist", "high_response_time_warning", "high_page_fault_warning", "hosts_file", "htcp_port", "http_access", "http_anonymizer", "httpd_accel", "httpd_accel_host", "httpd_accel_port", "httpd_accel_uses_host_header", "httpd_accel_with_proxy", "http_port", "http_reply_access", "icp_access", "icp_hit_stale", "icp_port", "icp_query_timeout", "ident_lookup", "ident_lookup_access", "ident_timeout", "incoming_http_average", "incoming_icp_average", "inside_firewall", "ipcache_high", "ipcache_low", "ipcache_size", "local_domain", "local_ip", "logfile_rotate", "log_fqdn", "log_icp_queries", "log_mime_hdrs", "maximum_object_size", "maximum_single_addr_tries", "mcast_groups", "mcast_icp_query_timeout", "mcast_miss_addr", "mcast_miss_encode_key", "mcast_miss_port", "memory_pools", "memory_pools_limit", "memory_replacement_policy", "mime_table", "min_http_poll_cnt", "min_icp_poll_cnt", "minimum_direct_hops", "minimum_object_size", "minimum_retry_timeout", "miss_access", "negative_dns_ttl", "negative_ttl", "neighbor_timeout", "neighbor_type_domain", "netdb_high", "netdb_low", "netdb_ping_period", "netdb_ping_rate", "never_direct", "no_cache", "passthrough_proxy", "pconn_timeout", "pid_filename", "pinger_program", "positive_dns_ttl", "prefer_direct", "proxy_auth", "proxy_auth_realm", "query_icmp", "quick_abort", "quick_abort_max", "quick_abort_min", "quick_abort_pct", "range_offset_limit", "read_timeout", "redirect_children", "redirect_program", "redirect_rewrites_host_header", "reference_age", "refresh_pattern", "reload_into_ims", "request_body_max_size", "request_size", "request_timeout", "shutdown_lifetime", "single_parent_bypass", "siteselect_timeout", "snmp_access", "snmp_incoming_address", "snmp_port", "source_ping", "ssl_proxy", "store_avg_object_size", "store_objects_per_bucket", "strip_query_terms", "swap_level1_dirs", "swap_level2_dirs", "tcp_incoming_address", "tcp_outgoing_address", "tcp_recv_bufsize", "test_reachability", "udp_hit_obj", "udp_hit_obj_size", "udp_incoming_address", "udp_outgoing_address", "unique_hostname", "unlinkd_program", "uri_whitespace", "useragent_log", "visible_hostname", "wais_relay", "wais_relay_host", "wais_relay_port", )
opts = ( "proxy-only", "weight", "ttl", "no-query", "default", "round-robin", "multicast-responder", "on", "off", "all", "deny", "allow", "via", "parent", "no-digest", "heap", "lru", "realm", "children", "q1", "q2", "credentialsttl", "none", "disable", "offline_toggle", "diskd", )
actions = ( "shutdown", "info", "parameter", "server_list", "client_list", r'squid.conf', )
actions_stats = ( "objects", "vm_objects", "utilization", "ipcache", "fqdncache", "dns", "redirector", "io", "reply_headers", "filedescriptors", "netdb", )
actions_log = ("status", "enable", "disable", "clear")
acls = ( "url_regex", "urlpath_regex", "referer_regex", "port", "proto", "req_mime_type", "rep_mime_type", "method", "browser", "user", "src", "dst", "time", "dstdomain", "ident", "snmp_community", )
ipv4_group = r'(\d+|0x[0-9a-f]+)' ipv4 = rf'({ipv4_group}(\.{ipv4_group}){{3}})' ipv6_group = r'([0-9a-f]{0,4})' ipv6 = rf'({ipv6_group}(:{ipv6_group}){{1,7}})' bare_ip = rf'({ipv4}|{ipv6})' # XXX: /integer is a subnet mark, but what is /IP ? # There is no test where it is used. ip = rf'{bare_ip}(/({bare_ip}|\d+))?'
tokens = { 'root': [ (r'\s+', Whitespace), (r'#', Comment, 'comment'), (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword), (words(opts, prefix=r'\b', suffix=r'\b'), Name.Constant), # Actions (words(actions, prefix=r'\b', suffix=r'\b'), String), (words(actions_stats, prefix=r'stats/', suffix=r'\b'), String), (words(actions_log, prefix=r'log/', suffix=r'='), String), (words(acls, prefix=r'\b', suffix=r'\b'), Keyword), (ip, Number.Float), (r'(?:\b\d+\b(?:-\b\d+|%)?)', Number), (r'\S+', Text), ], 'comment': [ (r'\s*TAG:.*', String.Escape, '#pop'), (r'.+', Comment, '#pop'), default('#pop'), ], }
class NginxConfLexer(RegexLexer): """ Lexer for Nginx configuration files. """ name = 'Nginx configuration file' url = 'http://nginx.net/' aliases = ['nginx'] filenames = ['nginx.conf'] mimetypes = ['text/x-nginx-conf'] version_added = '0.11'
tokens = { 'root': [ (r'(include)(\s+)([^\s;]+)', bygroups(Keyword, Whitespace, Name)), (r'[^\s;#]+', Keyword, 'stmt'), include('base'), ], 'block': [ (r'\}', Punctuation, '#pop:2'), (r'[^\s;#]+', Keyword.Namespace, 'stmt'), include('base'), ], 'stmt': [ (r'\{', Punctuation, 'block'), (r';', Punctuation, '#pop'), include('base'), ], 'base': [ (r'#.*\n', Comment.Single), (r'on|off', Name.Constant), (r'\$[^\s;#()]+', Name.Variable), (r'([a-z0-9.-]+)(:)([0-9]+)', bygroups(Name, Punctuation, Number.Integer)), (r'[a-z-]+/[a-z-+]+', String), # mimetype # (r'[a-zA-Z._-]+', Keyword), (r'[0-9]+[km]?\b', Number.Integer), (r'(~)(\s*)([^\s{]+)', bygroups(Punctuation, Whitespace, String.Regex)), (r'[:=~]', Punctuation), (r'[^\s;#{}$]+', String), # catch all (r'/[^\s;#]*', Name), # pathname (r'\s+', Whitespace), (r'[$;]', Text), # leftover characters ], }
class LighttpdConfLexer(RegexLexer): """ Lexer for Lighttpd configuration files. """ name = 'Lighttpd configuration file' url = 'http://lighttpd.net/' aliases = ['lighttpd', 'lighty'] filenames = ['lighttpd.conf'] mimetypes = ['text/x-lighttpd-conf'] version_added = '0.11'
tokens = { 'root': [ (r'#.*\n', Comment.Single), (r'/\S*', Name), # pathname (r'[a-zA-Z._-]+', Keyword), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'[0-9]+', Number), (r'=>|=~|\+=|==|=|\+', Operator), (r'\$[A-Z]+', Name.Builtin), (r'[(){}\[\],]', Punctuation), (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double), (r'\s+', Whitespace), ],
}
class DockerLexer(RegexLexer): """ Lexer for Docker configuration files. """ name = 'Docker' url = 'http://docker.io' aliases = ['docker', 'dockerfile'] filenames = ['Dockerfile', '*.docker'] mimetypes = ['text/x-dockerfile-config'] version_added = '2.0'
_keywords = (r'(?:MAINTAINER|EXPOSE|WORKDIR|USER|STOPSIGNAL)') _bash_keywords = (r'(?:RUN|CMD|ENTRYPOINT|ENV|ARG|LABEL|ADD|COPY)') _lb = r'(?:\s*\\?\s*)' # dockerfile line break regex flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'#.*', Comment), (r'(FROM)([ \t]*)(\S*)([ \t]*)(?:(AS)([ \t]*)(\S*))?', bygroups(Keyword, Whitespace, String, Whitespace, Keyword, Whitespace, String)), (rf'(ONBUILD)(\s+)({_lb})', bygroups(Keyword, Whitespace, using(BashLexer))), (rf'(HEALTHCHECK)(\s+)(({_lb}--\w+=\w+{_lb})*)', bygroups(Keyword, Whitespace, using(BashLexer))), (rf'(VOLUME|ENTRYPOINT|CMD|SHELL)(\s+)({_lb})(\[.*?\])', bygroups(Keyword, Whitespace, using(BashLexer), using(JsonLexer))), (rf'(LABEL|ENV|ARG)(\s+)(({_lb}\w+=\w+{_lb})*)', bygroups(Keyword, Whitespace, using(BashLexer))), (rf'({_keywords}|VOLUME)\b(\s+)(.*)', bygroups(Keyword, Whitespace, String)), (rf'({_bash_keywords})(\s+)', bygroups(Keyword, Whitespace)), (r'(.*\\\n)*.+', using(BashLexer)), ] }
class TerraformLexer(ExtendedRegexLexer): """ Lexer for terraformi ``.tf`` files. """
name = 'Terraform' url = 'https://www.terraform.io/' aliases = ['terraform', 'tf', 'hcl'] filenames = ['*.tf', '*.hcl'] mimetypes = ['application/x-tf', 'application/x-terraform'] version_added = '2.1'
classes = ('backend', 'data', 'module', 'output', 'provider', 'provisioner', 'resource', 'variable') classes_re = "({})".format(('|').join(classes))
types = ('string', 'number', 'bool', 'list', 'tuple', 'map', 'set', 'object', 'null')
numeric_functions = ('abs', 'ceil', 'floor', 'log', 'max', 'mix', 'parseint', 'pow', 'signum')
string_functions = ('chomp', 'format', 'formatlist', 'indent', 'join', 'lower', 'regex', 'regexall', 'replace', 'split', 'strrev', 'substr', 'title', 'trim', 'trimprefix', 'trimsuffix', 'trimspace', 'upper' )
collection_functions = ('alltrue', 'anytrue', 'chunklist', 'coalesce', 'coalescelist', 'compact', 'concat', 'contains', 'distinct', 'element', 'flatten', 'index', 'keys', 'length', 'list', 'lookup', 'map', 'matchkeys', 'merge', 'range', 'reverse', 'setintersection', 'setproduct', 'setsubtract', 'setunion', 'slice', 'sort', 'sum', 'transpose', 'values', 'zipmap' )
encoding_functions = ('base64decode', 'base64encode', 'base64gzip', 'csvdecode', 'jsondecode', 'jsonencode', 'textdecodebase64', 'textencodebase64', 'urlencode', 'yamldecode', 'yamlencode')
filesystem_functions = ('abspath', 'dirname', 'pathexpand', 'basename', 'file', 'fileexists', 'fileset', 'filebase64', 'templatefile')
date_time_functions = ('formatdate', 'timeadd', 'timestamp')
hash_crypto_functions = ('base64sha256', 'base64sha512', 'bcrypt', 'filebase64sha256', 'filebase64sha512', 'filemd5', 'filesha1', 'filesha256', 'filesha512', 'md5', 'rsadecrypt', 'sha1', 'sha256', 'sha512', 'uuid', 'uuidv5')
ip_network_functions = ('cidrhost', 'cidrnetmask', 'cidrsubnet', 'cidrsubnets')
type_conversion_functions = ('can', 'defaults', 'tobool', 'tolist', 'tomap', 'tonumber', 'toset', 'tostring', 'try')
builtins = numeric_functions + string_functions + collection_functions + encoding_functions +\ filesystem_functions + date_time_functions + hash_crypto_functions + ip_network_functions +\ type_conversion_functions builtins_re = "({})".format(('|').join(builtins))
def heredoc_callback(self, match, ctx): # Parse a terraform heredoc # match: 1 = <<[-]?, 2 = name 3 = rest of line
start = match.start(1) yield start, Operator, match.group(1) # <<[-]? yield match.start(2), String.Delimiter, match.group(2) # heredoc name
ctx.pos = match.start(3) ctx.end = match.end(3) yield ctx.pos, String.Heredoc, match.group(3) ctx.pos = match.end()
hdname = match.group(2) tolerant = True # leading whitespace is always accepted
lines = []
for match in line_re.finditer(ctx.text, ctx.pos): if tolerant: check = match.group().strip() else: check = match.group().rstrip() if check == hdname: for amatch in lines: yield amatch.start(), String.Heredoc, amatch.group() yield match.start(), String.Delimiter, match.group() ctx.pos = match.end() break else: lines.append(match) else: # end of heredoc not found -- error! for amatch in lines: yield amatch.start(), Error, amatch.group() ctx.end = len(ctx.text)
tokens = { 'root': [ include('basic'), include('whitespace'),
# Strings (r'(".*")', bygroups(String.Double)),
# Constants (words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Name.Constant),
# Types (words(types, prefix=r'\b', suffix=r'\b'), Keyword.Type),
include('identifier'), include('punctuation'), (r'[0-9]+', Number), ], 'basic': [ (r'\s*/\*', Comment.Multiline, 'comment'), (r'\s*(#|//).*\n', Comment.Single), include('whitespace'),
# e.g. terraform { # e.g. egress { (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=?)(\s*)(\{)', bygroups(Whitespace, Name.Builtin, Whitespace, Operator, Whitespace, Punctuation)),
# Assignment with attributes, e.g. something = ... (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=)(\s*)', bygroups(Whitespace, Name.Attribute, Whitespace, Operator, Whitespace)),
# Assignment with environment variables and similar, e.g. "something" = ... # or key value assignment, e.g. "SlotName" : ... (r'(\s*)("\S+")(\s*)([=:])(\s*)', bygroups(Whitespace, Literal.String.Double, Whitespace, Operator, Whitespace)),
# Functions, e.g. jsonencode(element("value")) (builtins_re + r'(\()', bygroups(Name.Function, Punctuation)),
# List of attributes, e.g. ignore_changes = [last_modified, filename] (r'(\[)([a-z_,\s]+)(\])', bygroups(Punctuation, Name.Builtin, Punctuation)),
# e.g. resource "aws_security_group" "allow_tls" { # e.g. backend "consul" { (classes_re + r'(\s+)("[0-9a-zA-Z-_]+")?(\s*)("[0-9a-zA-Z-_]+")(\s+)(\{)', bygroups(Keyword.Reserved, Whitespace, Name.Class, Whitespace, Name.Variable, Whitespace, Punctuation)),
# here-doc style delimited strings (r'(<<-?)\s*([a-zA-Z_]\w*)(.*?\n)', heredoc_callback), ], 'identifier': [ (r'\b(var\.[0-9a-zA-Z-_\.\[\]]+)\b', bygroups(Name.Variable)), (r'\b([0-9a-zA-Z-_\[\]]+\.[0-9a-zA-Z-_\.\[\]]+)\b', bygroups(Name.Variable)), ], 'punctuation': [ (r'[\[\]()\{\},.?:!=]', Punctuation), ], 'comment': [ (r'[^*/]', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), ], }
class TermcapLexer(RegexLexer): """ Lexer for termcap database source.
This is very simple and minimal. """ name = 'Termcap' aliases = ['termcap'] filenames = ['termcap', 'termcap.src'] mimetypes = [] url = 'https://en.wikipedia.org/wiki/Termcap' version_added = '2.1'
# NOTE: # * multiline with trailing backslash # * separator is ':' # * to embed colon as data, we must use \072 # * space after separator is not allowed (mayve) tokens = { 'root': [ (r'^#.*', Comment), (r'^[^\s#:|]+', Name.Tag, 'names'), (r'\s+', Whitespace), ], 'names': [ (r'\n', Whitespace, '#pop'), (r':', Punctuation, 'defs'), (r'\|', Punctuation), (r'[^:|]+', Name.Attribute), ], 'defs': [ (r'(\\)(\n[ \t]*)', bygroups(Text, Whitespace)), (r'\n[ \t]*', Whitespace, '#pop:2'), (r'(#)([0-9]+)', bygroups(Operator, Number)), (r'=', Operator, 'data'), (r':', Punctuation), (r'[^\s:=#]+', Name.Class), ], 'data': [ (r'\\072', Literal), (r':', Punctuation, '#pop'), (r'[^:\\]+', Literal), # for performance (r'.', Literal), ], }
class TerminfoLexer(RegexLexer): """ Lexer for terminfo database source.
This is very simple and minimal. """ name = 'Terminfo' aliases = ['terminfo'] filenames = ['terminfo', 'terminfo.src'] mimetypes = [] url = 'https://en.wikipedia.org/wiki/Terminfo' version_added = '2.1'
# NOTE: # * multiline with leading whitespace # * separator is ',' # * to embed comma as data, we can use \, # * space after separator is allowed tokens = { 'root': [ (r'^#.*$', Comment), (r'^[^\s#,|]+', Name.Tag, 'names'), (r'\s+', Whitespace), ], 'names': [ (r'\n', Whitespace, '#pop'), (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), 'defs'), (r'\|', Punctuation), (r'[^,|]+', Name.Attribute), ], 'defs': [ (r'\n[ \t]+', Whitespace), (r'\n', Whitespace, '#pop:2'), (r'(#)([0-9]+)', bygroups(Operator, Number)), (r'=', Operator, 'data'), (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace)), (r'[^\s,=#]+', Name.Class), ], 'data': [ (r'\\[,\\]', Literal), (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), '#pop'), (r'[^\\,]+', Literal), # for performance (r'.', Literal), ], }
class PkgConfigLexer(RegexLexer): """ Lexer for pkg-config (see also `manual page <http://linux.die.net/man/1/pkg-config>`_). """
name = 'PkgConfig' url = 'http://www.freedesktop.org/wiki/Software/pkg-config/' aliases = ['pkgconfig'] filenames = ['*.pc'] mimetypes = [] version_added = '2.1'
tokens = { 'root': [ (r'#.*$', Comment.Single),
# variable definitions (r'^(\w+)(=)', bygroups(Name.Attribute, Operator)),
# keyword lines (r'^([\w.]+)(:)', bygroups(Name.Tag, Punctuation), 'spvalue'),
# variable references include('interp'),
# fallback (r'\s+', Whitespace), (r'[^${}#=:\n.]+', Text), (r'.', Text), ], 'interp': [ # you can escape literal "$" as "$$" (r'\$\$', Text),
# variable references (r'\$\{', String.Interpol, 'curly'), ], 'curly': [ (r'\}', String.Interpol, '#pop'), (r'\w+', Name.Attribute), ], 'spvalue': [ include('interp'),
(r'#.*$', Comment.Single, '#pop'), (r'\n', Whitespace, '#pop'),
# fallback (r'\s+', Whitespace), (r'[^${}#\n\s]+', Text), (r'.', Text), ], }
class PacmanConfLexer(RegexLexer): """ Lexer for pacman.conf.
Actually, IniLexer works almost fine for this format, but it yield error token. It is because pacman.conf has a form without assignment like:
UseSyslog Color TotalDownload CheckSpace VerbosePkgLists
These are flags to switch on. """
name = 'PacmanConf' url = 'https://www.archlinux.org/pacman/pacman.conf.5.html' aliases = ['pacmanconf'] filenames = ['pacman.conf'] mimetypes = [] version_added = '2.1'
tokens = { 'root': [ # comment (r'#.*$', Comment.Single),
# section header (r'^(\s*)(\[.*?\])(\s*)$', bygroups(Whitespace, Keyword, Whitespace)),
# variable definitions # (Leading space is allowed...) (r'(\w+)(\s*)(=)', bygroups(Name.Attribute, Whitespace, Operator)),
# flags to on (r'^(\s*)(\w+)(\s*)$', bygroups(Whitespace, Name.Attribute, Whitespace)),
# built-in special values (words(( '$repo', # repository '$arch', # architecture '%o', # outfile '%u', # url ), suffix=r'\b'), Name.Variable),
# fallback (r'\s+', Whitespace), (r'.', Text), ], }
class AugeasLexer(RegexLexer): """ Lexer for Augeas. """ name = 'Augeas' url = 'http://augeas.net' aliases = ['augeas'] filenames = ['*.aug'] version_added = '2.4'
tokens = { 'root': [ (r'(module)(\s*)([^\s=]+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r'(let)(\s*)([^\s=]+)', bygroups(Keyword.Declaration, Whitespace, Name.Variable)), (r'(del|store|value|counter|seq|key|label|autoload|incl|excl|transform|test|get|put)(\s+)', bygroups(Name.Builtin, Whitespace)), (r'(\()([^:]+)(\:)(unit|string|regexp|lens|tree|filter)(\))', bygroups(Punctuation, Name.Variable, Punctuation, Keyword.Type, Punctuation)), (r'\(\*', Comment.Multiline, 'comment'), (r'[*+\-.;=?|]', Operator), (r'[()\[\]{}]', Operator), (r'"', String.Double, 'string'), (r'\/', String.Regex, 'regex'), (r'([A-Z]\w*)(\.)(\w+)', bygroups(Name.Namespace, Punctuation, Name.Variable)), (r'.', Name.Variable), (r'\s+', Whitespace), ], 'string': [ (r'\\.', String.Escape), (r'[^"]', String.Double), (r'"', String.Double, '#pop'), ], 'regex': [ (r'\\.', String.Escape), (r'[^/]', String.Regex), (r'\/', String.Regex, '#pop'), ], 'comment': [ (r'[^*)]', Comment.Multiline), (r'\(\*', Comment.Multiline, '#push'), (r'\*\)', Comment.Multiline, '#pop'), (r'[)*]', Comment.Multiline) ], }
class TOMLLexer(RegexLexer): """ Lexer for TOML, a simple language for config files. """
name = 'TOML' aliases = ['toml'] filenames = ['*.toml', 'Pipfile', 'poetry.lock'] mimetypes = ['application/toml'] url = 'https://toml.io' version_added = '2.4'
# Based on the TOML spec: https://toml.io/en/v1.0.0
# The following is adapted from CPython's tomllib: _time = r"\d\d:\d\d(:\d\d(\.\d+)?)?" _datetime = rf"""(?x) \d\d\d\d-\d\d-\d\d # date, e.g., 1988-10-27 ( [Tt ] {_time} # optional time ( [Zz]|[+-]\d\d:\d\d # optional time offset )? )? """
tokens = { 'root': [ # Note that we make an effort in order to distinguish # moments at which we're parsing a key and moments at # which we're parsing a value. In the TOML code # # 1234 = 1234 # # the first "1234" should be Name, the second Integer.
# Whitespace (r'\s+', Whitespace),
# Comment (r'#.*', Comment.Single),
# Assignment keys include('key'),
# After "=", find a value (r'(=)(\s*)', bygroups(Operator, Whitespace), 'value'),
# Table header (r'\[\[?', Keyword, 'table-key'), ], 'key': [ # Start of bare key (only ASCII is allowed here). (r'[A-Za-z0-9_-]+', Name), # Quoted key (r'"', String.Double, 'basic-string'), (r"'", String.Single, 'literal-string'), # Dots act as separators in keys (r'\.', Punctuation), ], 'table-key': [ # This is like 'key', but highlights the name components # and separating dots as Keyword because it looks better # when the whole table header is Keyword. We do highlight # strings as strings though. # Start of bare key (only ASCII is allowed here). (r'[A-Za-z0-9_-]+', Keyword), (r'"', String.Double, 'basic-string'), (r"'", String.Single, 'literal-string'), (r'\.', Keyword), (r'\]\]?', Keyword, '#pop'),
# Inline whitespace allowed (r'[ \t]+', Whitespace), ], 'value': [ # Datetime, baretime (_datetime, Literal.Date, '#pop'), (_time, Literal.Date, '#pop'),
# Recognize as float if there is a fractional part # and/or an exponent. (r'[+-]?\d[0-9_]*[eE][+-]?\d[0-9_]*', Number.Float, '#pop'), (r'[+-]?\d[0-9_]*\.\d[0-9_]*([eE][+-]?\d[0-9_]*)?', Number.Float, '#pop'),
# Infinities and NaN (r'[+-]?(inf|nan)', Number.Float, '#pop'),
# Integers (r'-?0b[01_]+', Number.Bin, '#pop'), (r'-?0o[0-7_]+', Number.Oct, '#pop'), (r'-?0x[0-9a-fA-F_]+', Number.Hex, '#pop'), (r'[+-]?[0-9_]+', Number.Integer, '#pop'),
# Strings (r'"""', String.Double, ('#pop', 'multiline-basic-string')), (r'"', String.Double, ('#pop', 'basic-string')), (r"'''", String.Single, ('#pop', 'multiline-literal-string')), (r"'", String.Single, ('#pop', 'literal-string')),
# Booleans (r'true|false', Keyword.Constant, '#pop'),
# Start of array (r'\[', Punctuation, ('#pop', 'array')),
# Start of inline table (r'\{', Punctuation, ('#pop', 'inline-table')), ], 'array': [ # Whitespace, including newlines, is ignored inside arrays, # and comments are allowed. (r'\s+', Whitespace), (r'#.*', Comment.Single),
# Delimiters (r',', Punctuation),
# End of array (r'\]', Punctuation, '#pop'),
# Parse a value and come back default('value'), ], 'inline-table': [ # Whitespace (since TOML 1.1.0, same as in array) (r'\s+', Whitespace), (r'#.*', Comment.Single),
# Keys include('key'),
# Values (r'(=)(\s*)', bygroups(Punctuation, Whitespace), 'value'),
# Delimiters (r',', Punctuation),
# End of inline table (r'\}', Punctuation, '#pop'), ], 'basic-string': [ (r'"', String.Double, '#pop'), include('escapes'), (r'[^"\\]+', String.Double), ], 'literal-string': [ (r".*?'", String.Single, '#pop'), ], 'multiline-basic-string': [ (r'"""', String.Double, '#pop'), (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), include('escapes'), (r'[^"\\]+', String.Double), (r'"', String.Double), ], 'multiline-literal-string': [ (r"'''", String.Single, '#pop'), (r"[^']+", String.Single), (r"'", String.Single), ], 'escapes': [ (r'\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}', String.Escape), (r'\\.', String.Escape), ], }
class NestedTextLexer(RegexLexer): """ Lexer for *NextedText*, a human-friendly data format.
.. versionchanged:: 2.16 Added support for *NextedText* v3.0. """
name = 'NestedText' url = 'https://nestedtext.org' aliases = ['nestedtext', 'nt'] filenames = ['*.nt'] version_added = '2.9'
tokens = { 'root': [ # Comment: # ... (r'^([ ]*)(#.*)$', bygroups(Whitespace, Comment)),
# Inline dictionary: {...} (r'^([ ]*)(\{)', bygroups(Whitespace, Punctuation), 'inline_dict'),
# Inline list: [...] (r'^([ ]*)(\[)', bygroups(Whitespace, Punctuation), 'inline_list'),
# empty multiline string item: > (r'^([ ]*)(>)$', bygroups(Whitespace, Punctuation)),
# multiline string item: > ... (r'^([ ]*)(>)( )(.*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Text, Whitespace)),
# empty list item: - (r'^([ ]*)(-)$', bygroups(Whitespace, Punctuation)),
# list item: - ... (r'^([ ]*)(-)( )(.*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Text, Whitespace)),
# empty multiline key item: : (r'^([ ]*)(:)$', bygroups(Whitespace, Punctuation)),
# multiline key item: : ... (r'^([ ]*)(:)( )([^\n]*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Name.Tag, Whitespace)),
# empty dict key item: ...: (r'^([ ]*)([^\{\[\s].*?)(:)$', bygroups(Whitespace, Name.Tag, Punctuation)),
# dict key item: ...: ... (r'^([ ]*)([^\{\[\s].*?)(:)( )(.*?)([ \t]*)$', bygroups(Whitespace, Name.Tag, Punctuation, Whitespace, Text, Whitespace)), ], 'inline_list': [ include('whitespace'), (r'[^\{\}\[\],\s]+', Text), include('inline_value'), (r',', Punctuation), (r'\]', Punctuation, '#pop'), (r'\n', Error, '#pop'), ], 'inline_dict': [ include('whitespace'), (r'[^\{\}\[\],:\s]+', Name.Tag), (r':', Punctuation, 'inline_dict_value'), (r'\}', Punctuation, '#pop'), (r'\n', Error, '#pop'), ], 'inline_dict_value': [ include('whitespace'), (r'[^\{\}\[\],:\s]+', Text), include('inline_value'), (r',', Punctuation, '#pop'), (r'\}', Punctuation, '#pop:2'), ], 'inline_value': [ include('whitespace'), (r'\{', Punctuation, 'inline_dict'), (r'\[', Punctuation, 'inline_list'), ], 'whitespace': [ (r'[ \t]+', Whitespace), ], }
class SingularityLexer(RegexLexer): """ Lexer for Singularity definition files. """
name = 'Singularity' url = 'https://www.sylabs.io/guides/3.0/user-guide/definition_files.html' aliases = ['singularity'] filenames = ['*.def', 'Singularity'] version_added = '2.6' flags = re.IGNORECASE | re.MULTILINE | re.DOTALL
_headers = r'^(\s*)(bootstrap|from|osversion|mirrorurl|include|registry|namespace|includecmd)(:)' _section = r'^(%(?:pre|post|setup|environment|help|labels|test|runscript|files|startscript))(\s*)' _appsect = r'^(%app(?:install|help|run|labels|env|test|files))(\s*)'
tokens = { 'root': [ (_section, bygroups(Generic.Heading, Whitespace), 'script'), (_appsect, bygroups(Generic.Heading, Whitespace), 'script'), (_headers, bygroups(Whitespace, Keyword, Text)), (r'\s*#.*?\n', Comment), (r'\b(([0-9]+\.?[0-9]*)|(\.[0-9]+))\b', Number), (r'[ \t]+', Whitespace), (r'(?!^\s*%).', Text), ], 'script': [ (r'(.+?(?=^\s*%))|(.*)', using(BashLexer), '#pop'), ], }
def analyse_text(text): """This is a quite simple script file, but there are a few keywords which seem unique to this language.""" result = 0 if re.search(r'\b(?:osversion|includecmd|mirrorurl)\b', text, re.IGNORECASE): result += 0.5
if re.search(SingularityLexer._section[1:], text): result += 0.49
return result
class UnixConfigLexer(RegexLexer): """ Lexer for Unix/Linux config files using colon-separated values, e.g.
* ``/etc/group`` * ``/etc/passwd`` * ``/etc/shadow`` """
name = 'Unix/Linux config files' aliases = ['unixconfig', 'linuxconfig'] filenames = [] url = 'https://en.wikipedia.org/wiki/Configuration_file#Unix_and_Unix-like_operating_systems' version_added = '2.12'
tokens = { 'root': [ (r'^#.*', Comment), (r'\n', Whitespace), (r':', Punctuation), (r'[0-9]+', Number), (r'((?!\n)[a-zA-Z0-9\_\-\s\(\),]){2,}', Text), (r'[^:\n]+', String), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114""" pygments.lexers.console ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for misc console output.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Generic, Comment, String, Text, Keyword, Name, \ Punctuation, Number, Whitespace
__all__ = ['VCTreeStatusLexer', 'PyPyLogLexer']
class VCTreeStatusLexer(RegexLexer): """ For colorizing output of version control status commands, like "hg status" or "svn status". """ name = 'VCTreeStatus' aliases = ['vctreestatus'] filenames = [] mimetypes = [] url = "" version_added = '2.0'
tokens = { 'root': [ (r'^A \+ C\s+', Generic.Error), (r'^A\s+\+?\s+', String), (r'^M\s+', Generic.Inserted), (r'^C\s+', Generic.Error), (r'^D\s+', Generic.Deleted), (r'^[?!]\s+', Comment.Preproc), (r' >\s+.*\n', Comment.Preproc), (r'\S+', Text), (r'\s+', Whitespace), ] }
class PyPyLogLexer(RegexLexer): """ Lexer for PyPy log files. """ name = "PyPy Log" aliases = ["pypylog", "pypy"] filenames = ["*.pypylog"] mimetypes = ['application/x-pypylog'] url = 'pypy.org' version_added = '1.5'
tokens = { "root": [ (r"\[\w+\] \{jit-log-.*?$", Keyword, "jit-log"), (r"\[\w+\] \{jit-backend-counts$", Keyword, "jit-backend-counts"), include("extra-stuff"), ], "jit-log": [ (r"\[\w+\] jit-log-.*?}$", Keyword, "#pop"), (r"^\+\d+: ", Comment), (r"--end of the loop--", Comment), (r"[ifp]\d+", Name), (r"ptr\d+", Name), (r"(\()(\w+(?:\.\w+)?)(\))", bygroups(Punctuation, Name.Builtin, Punctuation)), (r"[\[\]=,()]", Punctuation), (r"(\d+\.\d+|inf|-inf)", Number.Float), (r"-?\d+", Number.Integer), (r"'.*'", String), (r"(None|descr|ConstClass|ConstPtr|TargetToken)", Name), (r"<.*?>+", Name.Builtin), (r"(label|debug_merge_point|jump|finish)", Name.Class), (r"(int_add_ovf|int_add|int_sub_ovf|int_sub|int_mul_ovf|int_mul|" r"int_floordiv|int_mod|int_lshift|int_rshift|int_and|int_or|" r"int_xor|int_eq|int_ne|int_ge|int_gt|int_le|int_lt|int_is_zero|" r"int_is_true|" r"uint_floordiv|uint_ge|uint_lt|" r"float_add|float_sub|float_mul|float_truediv|float_neg|" r"float_eq|float_ne|float_ge|float_gt|float_le|float_lt|float_abs|" r"ptr_eq|ptr_ne|instance_ptr_eq|instance_ptr_ne|" r"cast_int_to_float|cast_float_to_int|" r"force_token|quasiimmut_field|same_as|virtual_ref_finish|" r"virtual_ref|mark_opaque_ptr|" r"call_may_force|call_assembler|call_loopinvariant|" r"call_release_gil|call_pure|call|" r"new_with_vtable|new_array|newstr|newunicode|new|" r"arraylen_gc|" r"getarrayitem_gc_pure|getarrayitem_gc|setarrayitem_gc|" r"getarrayitem_raw|setarrayitem_raw|getfield_gc_pure|" r"getfield_gc|getinteriorfield_gc|setinteriorfield_gc|" r"getfield_raw|setfield_gc|setfield_raw|" r"strgetitem|strsetitem|strlen|copystrcontent|" r"unicodegetitem|unicodesetitem|unicodelen|" r"guard_true|guard_false|guard_value|guard_isnull|" r"guard_nonnull_class|guard_nonnull|guard_class|guard_no_overflow|" r"guard_not_forced|guard_no_exception|guard_not_invalidated)", Name.Builtin), include("extra-stuff"), ], "jit-backend-counts": [ (r"\[\w+\] jit-backend-counts}$", Keyword, "#pop"), (r":", Punctuation), (r"\d+", Number), include("extra-stuff"), ], "extra-stuff": [ (r"\s+", Whitespace), (r"#.*?$", Comment), ], }12345678910111213141516171819202122232425262728293031323334353637383940414243""" pygments.lexers.cplint ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the cplint language
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import bygroups, inherit, wordsfrom pygments.lexers import PrologLexerfrom pygments.token import Operator, Keyword, Name, String, Punctuation
__all__ = ['CplintLexer']
class CplintLexer(PrologLexer): """ Lexer for cplint files, including CP-logic, Logic Programs with Annotated Disjunctions, Distributional Clauses syntax, ProbLog, DTProbLog. """ name = 'cplint' url = 'https://cplint.eu' aliases = ['cplint'] filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl', '*.P', '*.lpad', '*.cpl'] mimetypes = ['text/x-cplint'] version_added = '2.12'
tokens = { 'root': [ (r'map_query', Keyword), (words(('gaussian', 'uniform_dens', 'dirichlet', 'gamma', 'beta', 'poisson', 'binomial', 'geometric', 'exponential', 'pascal', 'multinomial', 'user', 'val', 'uniform', 'discrete', 'finite')), Name.Builtin), # annotations of atoms (r'([a-z]+)(:)', bygroups(String.Atom, Punctuation)), (r':(-|=)|::?|~=?|=>', Operator), (r'\?', Name.Builtin), inherit, ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364""" pygments.lexers.crystal ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Crystal.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, include, bygroups, default, \ words, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Error, Whitespace
__all__ = ['CrystalLexer']
CRYSTAL_OPERATORS = [ '!=', '!~', '!', '%', '&&', '&', '**', '*', '+', '-', '/', '<=>', '<<', '<=', '<', '===', '==', '=~', '=', '>=', '>>', '>', '[]=', '[]?', '[]', '^', '||', '|', '~']
class CrystalLexer(ExtendedRegexLexer): """ For Crystal source code. """
name = 'Crystal' url = 'https://crystal-lang.org' aliases = ['cr', 'crystal'] filenames = ['*.cr'] mimetypes = ['text/x-crystal'] version_added = '2.2'
flags = re.DOTALL | re.MULTILINE
def heredoc_callback(self, match, ctx): # okay, this is the hardest part of parsing Crystal... # match: 1 = <<-?, 2 = quote? 3 = name 4 = quote? 5 = rest of line
start = match.start(1) yield start, Operator, match.group(1) # <<-? yield match.start(2), String.Heredoc, match.group(2) # quote ", ', ` yield match.start(3), String.Delimiter, match.group(3) # heredoc name yield match.start(4), String.Heredoc, match.group(4) # quote again
heredocstack = ctx.__dict__.setdefault('heredocstack', []) outermost = not bool(heredocstack) heredocstack.append((match.group(1) == '<<-', match.group(3)))
ctx.pos = match.start(5) ctx.end = match.end(5) # this may find other heredocs, so limit the recursion depth if len(heredocstack) < 100: yield from self.get_tokens_unprocessed(context=ctx) else: yield ctx.pos, String.Heredoc, match.group(5) ctx.pos = match.end()
if outermost: # this is the outer heredoc again, now we can process them all for tolerant, hdname in heredocstack: lines = [] for match in line_re.finditer(ctx.text, ctx.pos): if tolerant: check = match.group().strip() else: check = match.group().rstrip() if check == hdname: for amatch in lines: yield amatch.start(), String.Heredoc, amatch.group() yield match.start(), String.Delimiter, match.group() ctx.pos = match.end() break else: lines.append(match) else: # end of heredoc not found -- error! for amatch in lines: yield amatch.start(), Error, amatch.group() ctx.end = len(ctx.text) del heredocstack[:]
def gen_crystalstrings_rules(): states = {} states['strings'] = [ (r'\:\w+[!?]?', String.Symbol), (words(CRYSTAL_OPERATORS, prefix=r'\:'), String.Symbol), (r":'(\\\\|\\[^\\]|[^'\\])*'", String.Symbol), # This allows arbitrary text after '\ for simplicity (r"'(\\\\|\\'|[^']|\\[^'\\]+)'", String.Char), (r':"', String.Symbol, 'simple-sym'), # Crystal doesn't have "symbol:"s but this simplifies function args (r'([a-zA-Z_]\w*)(:)(?!:)', bygroups(String.Symbol, Punctuation)), (r'"', String.Double, 'simple-string'), (r'(?<!\.)`', String.Backtick, 'simple-backtick'), ]
# double-quoted string and symbol for name, ttype, end in ('string', String.Double, '"'), \ ('sym', String.Symbol, '"'), \ ('backtick', String.Backtick, '`'): states['simple-'+name] = [ include('string-escaped' if name == 'sym' else 'string-intp-escaped'), (rf'[^\\{end}#]+', ttype), (r'[\\#]', ttype), (end, ttype, '#pop'), ]
# https://crystal-lang.org/docs/syntax_and_semantics/literals/string.html#percent-string-literals for lbrace, rbrace, bracecc, name in \ ('\\{', '\\}', '{}', 'cb'), \ ('\\[', '\\]', '\\[\\]', 'sb'), \ ('\\(', '\\)', '()', 'pa'), \ ('<', '>', '<>', 'ab'), \ ('\\|', '\\|', '\\|', 'pi'): states[name+'-intp-string'] = [ (r'\\' + lbrace, String.Other), ] + (lbrace != rbrace) * [ (lbrace, String.Other, '#push'), ] + [ (rbrace, String.Other, '#pop'), include('string-intp-escaped'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] states['strings'].append((r'%Q?' + lbrace, String.Other, name+'-intp-string')) states[name+'-string'] = [ (r'\\[\\' + bracecc + ']', String.Other), ] + (lbrace != rbrace) * [ (lbrace, String.Other, '#push'), ] + [ (rbrace, String.Other, '#pop'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] # https://crystal-lang.org/docs/syntax_and_semantics/literals/array.html#percent-array-literals states['strings'].append((r'%[qwi]' + lbrace, String.Other, name+'-string')) states[name+'-regex'] = [ (r'\\[\\' + bracecc + ']', String.Regex), ] + (lbrace != rbrace) * [ (lbrace, String.Regex, '#push'), ] + [ (rbrace + '[imsx]*', String.Regex, '#pop'), include('string-intp'), (r'[\\#' + bracecc + ']', String.Regex), (r'[^\\#' + bracecc + ']+', String.Regex), ] states['strings'].append((r'%r' + lbrace, String.Regex, name+'-regex'))
return states
tokens = { 'root': [ (r'#.*?$', Comment.Single), # keywords (words(''' abstract asm begin break case do else elsif end ensure extend if in include next of private protected require rescue return select self super then unless until when while with yield '''.split(), suffix=r'\b'), Keyword), (words(''' previous_def forall out uninitialized __DIR__ __FILE__ __LINE__ __END_LINE__ '''.split(), prefix=r'(?<!\.)', suffix=r'\b'), Keyword.Pseudo), # https://crystal-lang.org/docs/syntax_and_semantics/is_a.html (r'\.(is_a\?|nil\?|responds_to\?|as\?|as\b)', Keyword.Pseudo), (words(['true', 'false', 'nil'], suffix=r'\b'), Keyword.Constant), # start of function, class and module names (r'(module|lib)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(def|fun|macro)(\s+)((?:[a-zA-Z_]\w*::)*)', bygroups(Keyword, Whitespace, Name.Namespace), 'funcname'), (r'def(?=[*%&^`~+-/\[<>=])', Keyword, 'funcname'), (r'(annotation|class|struct|union|type|alias|enum)(\s+)((?:[a-zA-Z_]\w*::)*)', bygroups(Keyword, Whitespace, Name.Namespace), 'classname'), # https://crystal-lang.org/api/toplevel.html (words(''' instance_sizeof offsetof pointerof sizeof typeof '''.split(), prefix=r'(?<!\.)', suffix=r'\b'), Keyword.Pseudo), # macros (r'(?<!\.)(debugger\b|p!|pp!|record\b|spawn\b)', Name.Builtin.Pseudo), # builtins (words(''' abort at_exit caller exit gets loop main p pp print printf puts raise rand read_line sleep spawn sprintf system '''.split(), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), # https://crystal-lang.org/api/Object.html#macro-summary (r'(?<!\.)(((class_)?((getter|property)\b[!?]?|setter\b))|' r'(def_(clone|equals|equals_and_hash|hash)|delegate|forward_missing_to)\b)', Name.Builtin.Pseudo), # normal heredocs (r'(?<!\w)(<<-?)(["`\']?)([a-zA-Z_]\w*)(\2)(.*?\n)', heredoc_callback), # empty string heredocs (r'(<<-?)("|\')()(\2)(.*?\n)', heredoc_callback), (r'__END__', Comment.Preproc, 'end-part'), # multiline regex (after keywords or assignments) (r'(?:^|(?<=[=<>~!:])|' r'(?<=(?:\s|;)when\s)|' r'(?<=(?:\s|;)or\s)|' r'(?<=(?:\s|;)and\s)|' r'(?<=\.index\s)|' r'(?<=\.scan\s)|' r'(?<=\.sub\s)|' r'(?<=\.sub!\s)|' r'(?<=\.gsub\s)|' r'(?<=\.gsub!\s)|' r'(?<=\.match\s)|' r'(?<=(?:\s|;)if\s)|' r'(?<=(?:\s|;)elsif\s)|' r'(?<=^when\s)|' r'(?<=^index\s)|' r'(?<=^scan\s)|' r'(?<=^sub\s)|' r'(?<=^gsub\s)|' r'(?<=^sub!\s)|' r'(?<=^gsub!\s)|' r'(?<=^match\s)|' r'(?<=^if\s)|' r'(?<=^elsif\s)' r')(\s*)(/)', bygroups(Whitespace, String.Regex), 'multiline-regex'), # multiline regex (in method calls or subscripts) (r'(?<=\(|,|\[)/', String.Regex, 'multiline-regex'), # multiline regex (this time the funny no whitespace rule) (r'(\s+)(/)(?![\s=])', bygroups(Whitespace, String.Regex), 'multiline-regex'), # lex numbers and ignore following regular expressions which # are division operators in fact (grrrr. i hate that. any # better ideas?) # since pygments 0.7 we also eat a "?" operator after numbers # so that the char operator does not work. Chars are not allowed # there so that you can use the ternary operator. # stupid example: # x>=0?n[x]:"" (r'(0o[0-7]+(?:_[0-7]+)*(?:_?[iu][0-9]+)?)\b(\s*)([/?])?', bygroups(Number.Oct, Whitespace, Operator)), (r'(0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*(?:_?[iu][0-9]+)?)\b(\s*)([/?])?', bygroups(Number.Hex, Whitespace, Operator)), (r'(0b[01]+(?:_[01]+)*(?:_?[iu][0-9]+)?)\b(\s*)([/?])?', bygroups(Number.Bin, Whitespace, Operator)), # 3 separate expressions for floats because any of the 3 optional # parts makes it a float (r'((?:0(?![0-9])|[1-9][\d_]*)(?:\.\d[\d_]*)(?:e[+-]?[0-9]+)?' r'(?:_?f[0-9]+)?)(\s*)([/?])?', bygroups(Number.Float, Whitespace, Operator)), (r'((?:0(?![0-9])|[1-9][\d_]*)(?:\.\d[\d_]*)?(?:e[+-]?[0-9]+)' r'(?:_?f[0-9]+)?)(\s*)([/?])?', bygroups(Number.Float, Whitespace, Operator)), (r'((?:0(?![0-9])|[1-9][\d_]*)(?:\.\d[\d_]*)?(?:e[+-]?[0-9]+)?' r'(?:_?f[0-9]+))(\s*)([/?])?', bygroups(Number.Float, Whitespace, Operator)), (r'(0\b|[1-9][\d]*(?:_\d+)*(?:_?[iu][0-9]+)?)\b(\s*)([/?])?', bygroups(Number.Integer, Whitespace, Operator)), # Names (r'@@[a-zA-Z_]\w*', Name.Variable.Class), (r'@[a-zA-Z_]\w*', Name.Variable.Instance), (r'\$\w+', Name.Variable.Global), (r'\$[!@&`\'+~=/\\,;.<>_*$?:"^-]', Name.Variable.Global), (r'\$-[0adFiIlpvw]', Name.Variable.Global), (r'::', Operator), include('strings'), # https://crystal-lang.org/reference/syntax_and_semantics/literals/char.html (r'\?(\\[MC]-)*' # modifiers r'(\\([\\abefnrtv#"\']|[0-7]{1,3}|x[a-fA-F0-9]{2}|u[a-fA-F0-9]{4}|u\{[a-fA-F0-9 ]+\})|\S)' r'(?!\w)', String.Char), (r'[A-Z][A-Z_]+\b(?!::|\.)', Name.Constant), # macro expansion (r'\{%', String.Interpol, 'in-macro-control'), (r'\{\{', String.Interpol, 'in-macro-expr'), # annotations (r'(@\[)(\s*)([A-Z]\w*(::[A-Z]\w*)*)', bygroups(Operator, Whitespace, Name.Decorator), 'in-annot'), # this is needed because Crystal attributes can look # like keywords (class) or like this: ` ?!? (words(CRYSTAL_OPERATORS, prefix=r'(\.|::)'), bygroups(Operator, Name.Operator)), (r'(\.|::)([a-zA-Z_]\w*[!?]?|[*%&^`~+\-/\[<>=])', bygroups(Operator, Name)), # Names can end with [!?] unless it's "!=" (r'[a-zA-Z_]\w*(?:[!?](?!=))?', Name), (r'(\[|\]\??|\*\*|<=>?|>=|<<?|>>?|=~|===|' r'!~|&&?|\|\||\.{1,3})', Operator), (r'[-+/*%=<>&!^|~]=?', Operator), (r'[(){};,/?:\\]', Punctuation), (r'\s+', Whitespace) ], 'funcname': [ (r'(?:([a-zA-Z_]\w*)(\.))?' r'([a-zA-Z_]\w*[!?]?|\*\*?|[-+]@?|' r'[/%&|^`~]|\[\]=?|<<|>>|<=?>|>=?|===?)', bygroups(Name.Class, Operator, Name.Function), '#pop'), default('#pop') ], 'classname': [ (r'[A-Z_]\w*', Name.Class), (r'(\()(\s*)([A-Z_]\w*)(\s*)(\))', bygroups(Punctuation, Whitespace, Name.Class, Whitespace, Punctuation)), default('#pop') ], 'in-intp': [ (r'\{', String.Interpol, '#push'), (r'\}', String.Interpol, '#pop'), include('root'), ], 'string-intp': [ (r'#\{', String.Interpol, 'in-intp'), ], 'string-escaped': [ # https://crystal-lang.org/reference/syntax_and_semantics/literals/string.html (r'\\([\\abefnrtv#"\']|[0-7]{1,3}|x[a-fA-F0-9]{2}|u[a-fA-F0-9]{4}|u\{[a-fA-F0-9 ]+\})', String.Escape) ], 'string-intp-escaped': [ include('string-intp'), include('string-escaped'), ], 'interpolated-regex': [ include('string-intp'), (r'[\\#]', String.Regex), (r'[^\\#]+', String.Regex), ], 'interpolated-string': [ include('string-intp'), (r'[\\#]', String.Other), (r'[^\\#]+', String.Other), ], 'multiline-regex': [ include('string-intp'), (r'\\\\', String.Regex), (r'\\/', String.Regex), (r'[\\#]', String.Regex), (r'[^\\/#]+', String.Regex), (r'/[imsx]*', String.Regex, '#pop'), ], 'end-part': [ (r'.+', Comment.Preproc, '#pop') ], 'in-macro-control': [ (r'\{%', String.Interpol, '#push'), (r'%\}', String.Interpol, '#pop'), (r'(for|verbatim)\b', Keyword), include('root'), ], 'in-macro-expr': [ (r'\{\{', String.Interpol, '#push'), (r'\}\}', String.Interpol, '#pop'), include('root'), ], 'in-annot': [ (r'\[', Operator, '#push'), (r'\]', Operator, '#pop'), include('root'), ], } tokens.update(gen_crystalstrings_rules())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466""" pygments.lexers.csound ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Csound languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroups, default, include, using, wordsfrom pygments.token import Comment, Error, Keyword, Name, Number, Operator, Punctuation, \ String, Text, Whitespacefrom pygments.lexers._csound_builtins import OPCODES, DEPRECATED_OPCODES, REMOVED_OPCODESfrom pygments.lexers.html import HtmlLexerfrom pygments.lexers.python import PythonLexerfrom pygments.lexers.scripting import LuaLexer
__all__ = ['CsoundScoreLexer', 'CsoundOrchestraLexer', 'CsoundDocumentLexer']
newline = (r'((?:(?:;|//).*)*)(\n)', bygroups(Comment.Single, Text))
class CsoundLexer(RegexLexer): url = 'https://csound.com/'
tokens = { 'whitespace': [ (r'[ \t]+', Whitespace), (r'/[*](?:.|\n)*?[*]/', Comment.Multiline), (r'(?:;|//).*$', Comment.Single), (r'(\\)(\n)', bygroups(Text, Whitespace)) ],
'preprocessor directives': [ (r'#(?:e(?:nd(?:if)?|lse)\b|##)|@@?[ \t]*\d+', Comment.Preproc), (r'#includestr', Comment.Preproc, 'includestr directive'), (r'#include', Comment.Preproc, 'include directive'), (r'#[ \t]*define', Comment.Preproc, 'define directive'), (r'#(?:ifn?def|undef)\b', Comment.Preproc, 'macro directive') ],
'include directive': [ include('whitespace'), (r'([^ \t]).*?\1', String, '#pop') ], 'includestr directive': [ include('whitespace'), (r'"', String, ('#pop', 'quoted string')) ],
'define directive': [ (r'\n', Whitespace), include('whitespace'), (r'([A-Z_a-z]\w*)(\()', bygroups(Comment.Preproc, Punctuation), ('#pop', 'macro parameter name list')), (r'[A-Z_a-z]\w*', Comment.Preproc, ('#pop', 'before macro body')) ], 'macro parameter name list': [ include('whitespace'), (r'[A-Z_a-z]\w*', Comment.Preproc), (r"['#]", Punctuation), (r'\)', Punctuation, ('#pop', 'before macro body')) ], 'before macro body': [ (r'\n', Whitespace), include('whitespace'), (r'#', Punctuation, ('#pop', 'macro body')) ], 'macro body': [ (r'(?:\\(?!#)|[^#\\]|\n)+', Comment.Preproc), (r'\\#', Comment.Preproc), (r'(?<!\\)#', Punctuation, '#pop') ],
'macro directive': [ include('whitespace'), (r'[A-Z_a-z]\w*', Comment.Preproc, '#pop') ],
'macro uses': [ (r'(\$[A-Z_a-z]\w*\.?)(\()', bygroups(Comment.Preproc, Punctuation), 'macro parameter value list'), (r'\$[A-Z_a-z]\w*(?:\.|\b)', Comment.Preproc) ], 'macro parameter value list': [ (r'(?:[^\'#"{()]|\{(?!\{))+', Comment.Preproc), (r"['#]", Punctuation), (r'"', String, 'macro parameter value quoted string'), (r'\{\{', String, 'macro parameter value braced string'), (r'\(', Comment.Preproc, 'macro parameter value parenthetical'), (r'\)', Punctuation, '#pop') ], 'macro parameter value quoted string': [ (r"\\[#'()]", Comment.Preproc), (r"[#'()]", Error), include('quoted string') ], 'macro parameter value braced string': [ (r"\\[#'()]", Comment.Preproc), (r"[#'()]", Error), include('braced string') ], 'macro parameter value parenthetical': [ (r'(?:[^\\()]|\\\))+', Comment.Preproc), (r'\(', Comment.Preproc, '#push'), (r'\)', Comment.Preproc, '#pop') ],
'whitespace and macro uses': [ include('whitespace'), include('macro uses') ],
'numbers': [ (r'\d+[Ee][+-]?\d+|(\d+\.\d*|\d*\.\d+)([Ee][+-]?\d+)?', Number.Float), (r'(0[Xx])([0-9A-Fa-f]+)', bygroups(Keyword.Type, Number.Hex)), (r'\d+', Number.Integer) ],
'quoted string': [ (r'"', String, '#pop'), (r'[^"$]+', String), include('macro uses'), (r'[$]', String) ],
'braced string': [ # Do nothing. This must be defined in subclasses. ] }
class CsoundScoreLexer(CsoundLexer): """ For `Csound <https://csound.com>`_ scores. """
name = 'Csound Score' aliases = ['csound-score', 'csound-sco'] filenames = ['*.sco'] version_added = '2.1'
tokens = { 'root': [ (r'\n', Whitespace), include('whitespace and macro uses'), include('preprocessor directives'),
(r'[aBbCdefiqstvxy]', Keyword), # There is also a w statement that is generated internally and should not be # used; see https://github.com/csound/csound/issues/750.
(r'z', Keyword.Constant), # z is a constant equal to 800,000,000,000. 800 billion seconds is about # 25,367.8 years. See also # https://csound.com/docs/manual/ScoreTop.html and # https://github.com/csound/csound/search?q=stof+path%3AEngine+filename%3Asread.c.
(r'([nNpP][pP])(\d+)', bygroups(Keyword, Number.Integer)),
(r'[mn]', Keyword, 'mark statement'),
include('numbers'), (r'[!+\-*/^%&|<>#~.]', Operator), (r'[()\[\]]', Punctuation), (r'"', String, 'quoted string'), (r'\{', Comment.Preproc, 'loop after left brace'), ],
'mark statement': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', Name.Label), (r'\n', Whitespace, '#pop') ],
'loop after left brace': [ include('whitespace and macro uses'), (r'\d+', Number.Integer, ('#pop', 'loop after repeat count')), ], 'loop after repeat count': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', Comment.Preproc, ('#pop', 'loop')) ], 'loop': [ (r'\}', Comment.Preproc, '#pop'), include('root') ],
# Braced strings are not allowed in Csound scores, but this is needed because the # superclass includes it. 'braced string': [ (r'\}\}', String, '#pop'), (r'[^}]|\}(?!\})', String) ] }
class CsoundOrchestraLexer(CsoundLexer): """ For `Csound <https://csound.com>`_ orchestras. """
name = 'Csound Orchestra' aliases = ['csound', 'csound-orc'] filenames = ['*.orc', '*.udo'] version_added = '2.1'
user_defined_opcodes = set()
def opcode_name_callback(lexer, match): opcode = match.group(0) lexer.user_defined_opcodes.add(opcode) yield match.start(), Name.Function, opcode
def name_callback(lexer, match): type_annotation_token = Keyword.Type
name = match.group(1) if name in OPCODES or name in DEPRECATED_OPCODES or name in REMOVED_OPCODES: yield match.start(), Name.Builtin, name elif name in lexer.user_defined_opcodes: yield match.start(), Name.Function, name else: type_annotation_token = Name name_match = re.search(r'^(g?[afikSw])(\w+)', name) if name_match: yield name_match.start(1), Keyword.Type, name_match.group(1) yield name_match.start(2), Name, name_match.group(2) else: yield match.start(), Name, name
if match.group(2): yield match.start(2), Punctuation, match.group(2) yield match.start(3), type_annotation_token, match.group(3)
tokens = { 'root': [ (r'\n', Whitespace),
(r'^([ \t]*)(\w+)(:)([ \t]+|$)', bygroups(Whitespace, Name.Label, Punctuation, Whitespace)),
include('whitespace and macro uses'), include('preprocessor directives'),
(r'\binstr\b', Keyword.Declaration, 'instrument numbers and identifiers'), (r'\bopcode\b', Keyword.Declaration, 'after opcode keyword'), (r'\b(?:end(?:in|op))\b', Keyword.Declaration),
include('partial statements') ],
'partial statements': [ (r'\b(?:0dbfs|A4|k(?:r|smps)|nchnls(?:_i)?|sr)\b', Name.Variable.Global),
include('numbers'),
(r'\+=|-=|\*=|/=|<<|>>|<=|>=|==|!=|&&|\|\||[~¬]|[=!+\-*/^%&|<>#?:]', Operator), (r'[(),\[\]]', Punctuation),
(r'"', String, 'quoted string'), (r'\{\{', String, 'braced string'),
(words(( 'do', 'else', 'elseif', 'endif', 'enduntil', 'fi', 'if', 'ithen', 'kthen', 'od', 'then', 'until', 'while', ), prefix=r'\b', suffix=r'\b'), Keyword), (words(('return', 'rireturn'), prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
(r'\b[ik]?goto\b', Keyword, 'goto label'), (r'\b(r(?:einit|igoto)|tigoto)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), 'goto label'), (r'\b(c(?:g|in?|k|nk?)goto)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument')), (r'\b(timout)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument', 'goto argument')), (r'\b(loop_[gl][et])(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument', 'goto argument', 'goto argument')),
(r'\bprintk?s\b', Name.Builtin, 'prints opcode'), (r'\b(?:readscore|scoreline(?:_i)?)\b', Name.Builtin, 'Csound score opcode'), (r'\bpyl?run[it]?\b', Name.Builtin, 'Python opcode'), (r'\blua_(?:exec|opdef)\b', Name.Builtin, 'Lua opcode'), (r'\bp\d+\b', Name.Variable.Instance), (r'\b([A-Z_a-z]\w*)(?:(:)([A-Za-z]))?\b', name_callback) ],
'instrument numbers and identifiers': [ include('whitespace and macro uses'), (r'\d+|[A-Z_a-z]\w*', Name.Function), (r'[+,]', Punctuation), (r'\n', Whitespace, '#pop') ],
'after opcode keyword': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', opcode_name_callback, ('#pop', 'opcode type signatures')), (r'\n', Whitespace, '#pop') ], 'opcode type signatures': [ include('whitespace and macro uses'),
# https://github.com/csound/csound/search?q=XIDENT+path%3AEngine+filename%3Acsound_orc.lex (r'0|[afijkKoOpPStV\[\]]+', Keyword.Type),
(r',', Punctuation), (r'\n', Whitespace, '#pop') ],
'quoted string': [ (r'"', String, '#pop'), (r'[^\\"$%)]+', String), include('macro uses'), include('escape sequences'), include('format specifiers'), (r'[\\$%)]', String) ], 'braced string': [ (r'\}\}', String, '#pop'), (r'(?:[^\\%)}]|\}(?!\}))+', String), include('escape sequences'), include('format specifiers'), (r'[\\%)]', String) ], 'escape sequences': [ # https://github.com/csound/csound/search?q=unquote_string+path%3AEngine+filename%3Acsound_orc_compile.c (r'\\(?:[\\abnrt"]|[0-7]{1,3})', String.Escape) ], # Format specifiers are highlighted in all strings, even though only # fprintks https://csound.com/docs/manual/fprintks.html # fprints https://csound.com/docs/manual/fprints.html # printf/printf_i https://csound.com/docs/manual/printf.html # printks https://csound.com/docs/manual/printks.html # prints https://csound.com/docs/manual/prints.html # sprintf https://csound.com/docs/manual/sprintf.html # sprintfk https://csound.com/docs/manual/sprintfk.html # work with strings that contain format specifiers. In addition, these opcodes’ # handling of format specifiers is inconsistent: # - fprintks and fprints accept %a and %A specifiers, and accept %s specifiers # starting in Csound 6.15.0. # - printks and prints accept %a and %A specifiers, but don’t accept %s # specifiers. # - printf, printf_i, sprintf, and sprintfk don’t accept %a and %A specifiers, # but accept %s specifiers. # See https://github.com/csound/csound/issues/747 for more information. 'format specifiers': [ (r'%[#0\- +]*\d*(?:\.\d+)?[AE-GXac-giosux]', String.Interpol), (r'%%', String.Escape) ],
'goto argument': [ include('whitespace and macro uses'), (r',', Punctuation, '#pop'), include('partial statements') ], 'goto label': [ include('whitespace and macro uses'), (r'\w+', Name.Label, '#pop'), default('#pop') ],
'prints opcode': [ include('whitespace and macro uses'), (r'"', String, 'prints quoted string'), default('#pop') ], 'prints quoted string': [ (r'\\\\[aAbBnNrRtT]', String.Escape), (r'%[!nNrRtT]|[~^]{1,2}', String.Escape), include('quoted string') ],
'Csound score opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Csound score'), (r'\n', Whitespace, '#pop') ], 'Csound score': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(CsoundScoreLexer)) ],
'Python opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Python'), (r'\n', Whitespace, '#pop') ], 'Python': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(PythonLexer)) ],
'Lua opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Lua'), (r'\n', Whitespace, '#pop') ], 'Lua': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(LuaLexer)) ] }
class CsoundDocumentLexer(RegexLexer): """ For Csound documents. """
name = 'Csound Document' aliases = ['csound-document', 'csound-csd'] filenames = ['*.csd'] url = 'https://csound.com' version_added = '2.1'
# These tokens are based on those in XmlLexer in pygments/lexers/html.py. Making # CsoundDocumentLexer a subclass of XmlLexer rather than RegexLexer may seem like a # better idea, since Csound Document files look like XML files. However, Csound # Documents can contain Csound comments (preceded by //, for example) before and # after the root element, unescaped bitwise AND & and less than < operators, etc. In # other words, while Csound Document files look like XML files, they may not actually # be XML files. tokens = { 'root': [ (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'(?:;|//).*$', Comment.Single), (r'[^/;<]+|/(?!/)', Text),
(r'<\s*CsInstruments', Name.Tag, ('orchestra', 'tag')), (r'<\s*CsScore', Name.Tag, ('score', 'tag')), (r'<\s*[Hh][Tt][Mm][Ll]', Name.Tag, ('HTML', 'tag')),
(r'<\s*[\w:.-]+', Name.Tag, 'tag'), (r'<\s*/\s*[\w:.-]+\s*>', Name.Tag) ],
'orchestra': [ (r'<\s*/\s*CsInstruments\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*CsInstruments\s*>)', using(CsoundOrchestraLexer)) ], 'score': [ (r'<\s*/\s*CsScore\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*CsScore\s*>)', using(CsoundScoreLexer)) ], 'HTML': [ (r'<\s*/\s*[Hh][Tt][Mm][Ll]\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*[Hh][Tt][Mm][Ll]\s*>)', using(HtmlLexer)) ],
'tag': [ (r'\s+', Whitespace), (r'[\w.:-]+\s*=', Name.Attribute, 'attr'), (r'/?\s*>', Name.Tag, '#pop') ], 'attr': [ (r'\s+', Whitespace), (r'".*?"', String, '#pop'), (r"'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop') ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632""" pygments.lexers.css ~~~~~~~~~~~~~~~~~~~
Lexers for CSS and related stylesheet formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import reimport copy
from pygments.lexer import ExtendedRegexLexer, RegexLexer, include, bygroups, \ default, words, inheritfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespacefrom pygments.lexers._css_builtins import _css_properties
__all__ = ['CssLexer', 'SassLexer', 'ScssLexer', 'LessCssLexer']
# List of vendor prefixes obtained from:# https://www.w3.org/TR/CSS21/syndata.html#vendor-keyword-history_vendor_prefixes = ( '-ms-', 'mso-', '-moz-', '-o-', '-xv-', '-atsc-', '-wap-', '-khtml-', '-webkit-', 'prince-', '-ah-', '-hp-', '-ro-', '-rim-', '-tc-',)
# List of extended color keywords obtained from:# https://drafts.csswg.org/css-color/#named-colors_color_keywords = ( 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'rebeccapurple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen',) + ('transparent',)
# List of keyword values obtained from:# http://cssvalues.com/_keyword_values = ( 'absolute', 'alias', 'all', 'all-petite-caps', 'all-scroll', 'all-small-caps', 'allow-end', 'alpha', 'alternate', 'alternate-reverse', 'always', 'armenian', 'auto', 'avoid', 'avoid-column', 'avoid-page', 'backwards', 'balance', 'baseline', 'below', 'blink', 'block', 'bold', 'bolder', 'border-box', 'both', 'bottom', 'box-decoration', 'break-word', 'capitalize', 'cell', 'center', 'circle', 'clip', 'clone', 'close-quote', 'col-resize', 'collapse', 'color', 'color-burn', 'color-dodge', 'column', 'column-reverse', 'compact', 'condensed', 'contain', 'container', 'content-box', 'context-menu', 'copy', 'cover', 'crisp-edges', 'crosshair', 'currentColor', 'cursive', 'darken', 'dashed', 'decimal', 'decimal-leading-zero', 'default', 'descendants', 'difference', 'digits', 'disc', 'distribute', 'dot', 'dotted', 'double', 'double-circle', 'e-resize', 'each-line', 'ease', 'ease-in', 'ease-in-out', 'ease-out', 'edges', 'ellipsis', 'end', 'ew-resize', 'exclusion', 'expanded', 'extra-condensed', 'extra-expanded', 'fantasy', 'fill', 'fill-box', 'filled', 'first', 'fixed', 'flat', 'flex', 'flex-end', 'flex-start', 'flip', 'force-end', 'forwards', 'from-image', 'full-width', 'geometricPrecision', 'georgian', 'groove', 'hanging', 'hard-light', 'help', 'hidden', 'hide', 'horizontal', 'hue', 'icon', 'infinite', 'inherit', 'initial', 'ink', 'inline', 'inline-block', 'inline-flex', 'inline-table', 'inset', 'inside', 'inter-word', 'invert', 'isolate', 'italic', 'justify', 'large', 'larger', 'last', 'left', 'lighten', 'lighter', 'line-through', 'linear', 'list-item', 'local', 'loose', 'lower-alpha', 'lower-greek', 'lower-latin', 'lower-roman', 'lowercase', 'ltr', 'luminance', 'luminosity', 'mandatory', 'manipulation', 'manual', 'margin-box', 'match-parent', 'medium', 'mixed', 'monospace', 'move', 'multiply', 'n-resize', 'ne-resize', 'nesw-resize', 'no-close-quote', 'no-drop', 'no-open-quote', 'no-repeat', 'none', 'normal', 'not-allowed', 'nowrap', 'ns-resize', 'nw-resize', 'nwse-resize', 'objects', 'oblique', 'off', 'on', 'open', 'open-quote', 'optimizeLegibility', 'optimizeSpeed', 'outset', 'outside', 'over', 'overlay', 'overline', 'padding-box', 'page', 'pan-down', 'pan-left', 'pan-right', 'pan-up', 'pan-x', 'pan-y', 'paused', 'petite-caps', 'pixelated', 'pointer', 'preserve-3d', 'progress', 'proximity', 'relative', 'repeat', 'repeat no-repeat', 'repeat-x', 'repeat-y', 'reverse', 'revert', 'ridge', 'right', 'round', 'row', 'row-resize', 'row-reverse', 'rtl', 'ruby', 'ruby-base', 'ruby-base-container', 'ruby-text', 'ruby-text-container', 'run-in', 'running', 's-resize', 'sans-serif', 'saturation', 'scale-down', 'screen', 'scroll', 'se-resize', 'semi-condensed', 'semi-expanded', 'separate', 'serif', 'sesame', 'show', 'sideways', 'sideways-left', 'sideways-right', 'slice', 'small', 'small-caps', 'smaller', 'smooth', 'snap', 'soft-light', 'solid', 'space', 'space-around', 'space-between', 'spaces', 'square', 'start', 'static', 'step-end', 'step-start', 'sticky', 'stretch', 'strict', 'stroke-box', 'style', 'sw-resize', 'table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row', 'table-row-group', 'text', 'thick', 'thin', 'titling-caps', 'to', 'top', 'triangle', 'ultra-condensed', 'ultra-expanded', 'under', 'underline', 'unicase', 'unset', 'upper-alpha', 'upper-latin', 'upper-roman', 'uppercase', 'upright', 'use-glyph-orientation', 'vertical', 'vertical-text', 'view-box', 'visible', 'w-resize', 'wait', 'wavy', 'weight', 'weight style', 'wrap', 'wrap-reverse', 'x-large', 'x-small', 'xx-large', 'xx-small', 'zoom-in', 'zoom-out',)
# List of other keyword values from other sources:_other_keyword_values = ( 'above', 'aural', 'behind', 'bidi-override', 'center-left', 'center-right', 'cjk-ideographic', 'continuous', 'crop', 'cross', 'embed', 'far-left', 'far-right', 'fast', 'faster', 'hebrew', 'high', 'higher', 'hiragana', 'hiragana-iroha', 'katakana', 'katakana-iroha', 'landscape', 'left-side', 'leftwards', 'level', 'loud', 'low', 'lower', 'message-box', 'middle', 'mix', 'narrower', 'once', 'portrait', 'right-side', 'rightwards', 'silent', 'slow', 'slower', 'small-caption', 'soft', 'spell-out', 'status-bar', 'super', 'text-bottom', 'text-top', 'wider', 'x-fast', 'x-high', 'x-loud', 'x-low', 'x-soft', 'yes', 'pre', 'pre-wrap', 'pre-line',)
# List of functional notation and function keyword values:_functional_notation_keyword_values = ( 'attr', 'blackness', 'blend', 'blenda', 'blur', 'brightness', 'calc', 'circle', 'color-mod', 'contrast', 'counter', 'cubic-bezier', 'device-cmyk', 'drop-shadow', 'ellipse', 'gray', 'grayscale', 'hsl', 'hsla', 'hue', 'hue-rotate', 'hwb', 'image', 'inset', 'invert', 'lightness', 'linear-gradient', 'matrix', 'matrix3d', 'opacity', 'perspective', 'polygon', 'radial-gradient', 'rect', 'repeating-linear-gradient', 'repeating-radial-gradient', 'rgb', 'rgba', 'rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'saturate', 'saturation', 'scale', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'sepia', 'shade', 'skewX', 'skewY', 'steps', 'tint', 'toggle', 'translate', 'translate3d', 'translateX', 'translateY', 'translateZ', 'whiteness',)# Note! Handle url(...) separately.
# List of units obtained from:# https://www.w3.org/TR/css3-values/_angle_units = ( 'deg', 'grad', 'rad', 'turn',)_frequency_units = ( 'Hz', 'kHz',)_length_units = ( 'em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax', 'px', 'mm', 'cm', 'in', 'pt', 'pc', 'q',)_resolution_units = ( 'dpi', 'dpcm', 'dppx',)_time_units = ( 's', 'ms',)_all_units = _angle_units + _frequency_units + _length_units + \ _resolution_units + _time_units
class CssLexer(RegexLexer): """ For CSS (Cascading Style Sheets). """
name = 'CSS' url = 'https://www.w3.org/TR/CSS/#css' aliases = ['css'] filenames = ['*.css'] mimetypes = ['text/css'] version_added = ''
tokens = { 'root': [ include('basics'), ], 'basics': [ (r'\s+', Whitespace), (r'/\*(?:.|\n)*?\*/', Comment), (r'\{', Punctuation, 'content'), (r'(\:{1,2})([\w-]+)', bygroups(Punctuation, Name.Decorator)), (r'(\.)([\w-]+)', bygroups(Punctuation, Name.Class)), (r'(\#)([\w-]+)', bygroups(Punctuation, Name.Namespace)), (r'(@)([\w-]+)', bygroups(Punctuation, Keyword), 'atrule'), (r'[\w-]+', Name.Tag), (r'[~^*!%&$\[\]()<>|+=@:;,./?-]', Operator), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ], 'atrule': [ (r'\{', Punctuation, 'atcontent'), (r';', Punctuation, '#pop'), include('basics'), ], 'atcontent': [ include('basics'), (r'\}', Punctuation, '#pop:2'), ], 'content': [ (r'\s+', Whitespace), (r'\}', Punctuation, '#pop'), (r';', Punctuation), (r'^@.*?$', Comment.Preproc),
(words(_vendor_prefixes,), Keyword.Pseudo), (r'('+r'|'.join(_css_properties)+r')(\s*)(\:)', bygroups(Keyword, Whitespace, Punctuation), 'value-start'), (r'([-]+[a-zA-Z_][\w-]*)(\s*)(\:)', bygroups(Name.Variable, Whitespace, Punctuation), 'value-start'), (r'([a-zA-Z_][\w-]*)(\s*)(\:)', bygroups(Name, Whitespace, Punctuation), 'value-start'),
(r'/\*(?:.|\n)*?\*/', Comment), ], 'value-start': [ (r'\s+', Whitespace), (words(_vendor_prefixes,), Name.Builtin.Pseudo), include('urls'), (r'('+r'|'.join(_functional_notation_keyword_values)+r')(\()', bygroups(Name.Builtin, Punctuation), 'function-start'), (r'([a-zA-Z_][\w-]+)(\()', bygroups(Name.Function, Punctuation), 'function-start'), (words(_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_other_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_color_keywords, suffix=r'\b'), Keyword.Constant), # for transition-property etc. (words(_css_properties, suffix=r'\b'), Keyword), (r'\!important', Comment.Preproc), (r'/\*(?:.|\n)*?\*/', Comment),
include('numeric-values'),
(r'[~^*!%&<>|+=@:./?-]+', Operator), (r'[\[\](),]+', Punctuation), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_][\w-]*', Name), (r';', Punctuation, '#pop'), (r'\}', Punctuation, '#pop:2'), ], 'function-start': [ (r'\s+', Whitespace), (r'[-]+([A-Za-z][\w+]*[-]*)+', Name.Variable), include('urls'), (words(_vendor_prefixes,), Keyword.Pseudo), (words(_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_other_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_color_keywords, suffix=r'\b'), Keyword.Constant),
# function-start may be entered recursively (r'(' + r'|'.join(_functional_notation_keyword_values) + r')(\()', bygroups(Name.Builtin, Punctuation), 'function-start'), (r'([a-zA-Z_][\w-]+)(\()', bygroups(Name.Function, Punctuation), 'function-start'),
(r'/\*(?:.|\n)*?\*/', Comment), include('numeric-values'), (r'[*+/-]', Operator), (r',', Punctuation), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_-]\w*', Name), (r'\)', Punctuation, '#pop'), ], 'urls': [ (r'(url)(\()(".*?")(\))', bygroups(Name.Builtin, Punctuation, String.Double, Punctuation)), (r"(url)(\()('.*?')(\))", bygroups(Name.Builtin, Punctuation, String.Single, Punctuation)), (r'(url)(\()(.*?)(\))', bygroups(Name.Builtin, Punctuation, String.Other, Punctuation)), ], 'numeric-values': [ (r'\#[a-zA-Z0-9]{1,6}', Number.Hex), (r'[+\-]?[0-9]*[.][0-9]+', Number.Float, 'numeric-end'), (r'[+\-]?[0-9]+', Number.Integer, 'numeric-end'), ], 'numeric-end': [ (words(_all_units, suffix=r'\b'), Keyword.Type), (r'%', Keyword.Type), default('#pop'), ], }
common_sass_tokens = { 'value': [ (r'[ \t]+', Whitespace), (r'[!$][\w-]+', Name.Variable), (r'url\(', String.Other, 'string-url'), (r'[a-z_-][\w-]*(?=\()', Name.Function), (words(_css_properties + ( 'above', 'absolute', 'always', 'armenian', 'aural', 'auto', 'avoid', 'baseline', 'behind', 'below', 'bidi-override', 'blink', 'block', 'bold', 'bolder', 'both', 'capitalize', 'center-left', 'center-right', 'center', 'circle', 'cjk-ideographic', 'close-quote', 'collapse', 'condensed', 'continuous', 'crosshair', 'cross', 'cursive', 'dashed', 'decimal-leading-zero', 'decimal', 'default', 'digits', 'disc', 'dotted', 'double', 'e-resize', 'embed', 'extra-condensed', 'extra-expanded', 'expanded', 'fantasy', 'far-left', 'far-right', 'faster', 'fast', 'fixed', 'georgian', 'groove', 'hebrew', 'help', 'hidden', 'hide', 'higher', 'high', 'hiragana-iroha', 'hiragana', 'icon', 'inherit', 'inline-table', 'inline', 'inset', 'inside', 'invert', 'italic', 'justify', 'katakana-iroha', 'katakana', 'landscape', 'larger', 'large', 'left-side', 'leftwards', 'level', 'lighter', 'line-through', 'list-item', 'loud', 'lower-alpha', 'lower-greek', 'lower-roman', 'lowercase', 'ltr', 'lower', 'low', 'medium', 'message-box', 'middle', 'mix', 'monospace', 'n-resize', 'narrower', 'ne-resize', 'no-close-quote', 'no-open-quote', 'no-repeat', 'none', 'normal', 'nowrap', 'nw-resize', 'oblique', 'once', 'open-quote', 'outset', 'outside', 'overline', 'pointer', 'portrait', 'px', 'relative', 'repeat-x', 'repeat-y', 'repeat', 'rgb', 'ridge', 'right-side', 'rightwards', 's-resize', 'sans-serif', 'scroll', 'se-resize', 'semi-condensed', 'semi-expanded', 'separate', 'serif', 'show', 'silent', 'slow', 'slower', 'small-caps', 'small-caption', 'smaller', 'soft', 'solid', 'spell-out', 'square', 'static', 'status-bar', 'super', 'sw-resize', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row', 'table-row-group', 'text', 'text-bottom', 'text-top', 'thick', 'thin', 'transparent', 'ultra-condensed', 'ultra-expanded', 'underline', 'upper-alpha', 'upper-latin', 'upper-roman', 'uppercase', 'url', 'visible', 'w-resize', 'wait', 'wider', 'x-fast', 'x-high', 'x-large', 'x-loud', 'x-low', 'x-small', 'x-soft', 'xx-large', 'xx-small', 'yes'), suffix=r'\b'), Name.Constant), (words(_color_keywords, suffix=r'\b'), Name.Entity), (words(( 'black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua'), suffix=r'\b'), Name.Builtin), (r'\!(important|default)', Name.Exception), (r'(true|false)', Name.Pseudo), (r'(and|or|not)', Operator.Word), (r'/\*', Comment.Multiline, 'inline-comment'), (r'//[^\n]*', Comment.Single), (r'\#[a-z0-9]{1,6}', Number.Hex), (r'(-?\d+)(\%|[a-z]+)?', bygroups(Number.Integer, Keyword.Type)), (r'(-?\d*\.\d+)(\%|[a-z]+)?', bygroups(Number.Float, Keyword.Type)), (r'#\{', String.Interpol, 'interpolation'), (r'[~^*!&%<>|+=@:,./?-]+', Operator), (r'[\[\]()]+', Punctuation), (r'"', String.Double, 'string-double'), (r"'", String.Single, 'string-single'), (r'[a-z_-][\w-]*', Name), ],
'interpolation': [ (r'\}', String.Interpol, '#pop'), include('value'), ],
'selector': [ (r'[ \t]+', Whitespace), (r'\:', Name.Decorator, 'pseudo-class'), (r'\.', Name.Class, 'class'), (r'\#', Name.Namespace, 'id'), (r'[\w-]+', Name.Tag), (r'#\{', String.Interpol, 'interpolation'), (r'&', Keyword), (r'[~^*!&\[\]()<>|+=@:;,./?-]', Operator), (r'"', String.Double, 'string-double'), (r"'", String.Single, 'string-single'), ],
'string-double': [ (r'(\\.|#(?=[^\n{])|[^\n"#])+', String.Double), (r'#\{', String.Interpol, 'interpolation'), (r'"', String.Double, '#pop'), ],
'string-single': [ (r"(\\.|#(?=[^\n{])|[^\n'#])+", String.Single), (r'#\{', String.Interpol, 'interpolation'), (r"'", String.Single, '#pop'), ],
'string-url': [ (r'(\\#|#(?=[^\n{])|[^\n#)])+', String.Other), (r'#\{', String.Interpol, 'interpolation'), (r'\)', String.Other, '#pop'), ],
'pseudo-class': [ (r'[\w-]+', Name.Decorator), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'class': [ (r'[\w-]+', Name.Class), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'id': [ (r'[\w-]+', Name.Namespace), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'for': [ (r'(from|to|through)', Operator.Word), include('value'), ],}
def _indentation(lexer, match, ctx): indentation = match.group(0) yield match.start(), Whitespace, indentation ctx.last_indentation = indentation ctx.pos = match.end()
if hasattr(ctx, 'block_state') and ctx.block_state and \ indentation.startswith(ctx.block_indentation) and \ indentation != ctx.block_indentation: ctx.stack.append(ctx.block_state) else: ctx.block_state = None ctx.block_indentation = None ctx.stack.append('content')
def _starts_block(token, state): def callback(lexer, match, ctx): yield match.start(), token, match.group(0)
if hasattr(ctx, 'last_indentation'): ctx.block_indentation = ctx.last_indentation else: ctx.block_indentation = ''
ctx.block_state = state ctx.pos = match.end()
return callback
class SassLexer(ExtendedRegexLexer): """ For Sass stylesheets. """
name = 'Sass' url = 'https://sass-lang.com/' aliases = ['sass'] filenames = ['*.sass'] mimetypes = ['text/x-sass'] version_added = '1.3'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'[ \t]*\n', Whitespace), (r'[ \t]*', _indentation), ],
'content': [ (r'//[^\n]*', _starts_block(Comment.Single, 'single-comment'), 'root'), (r'/\*[^\n]*', _starts_block(Comment.Multiline, 'multi-comment'), 'root'), (r'@import', Keyword, 'import'), (r'@for', Keyword, 'for'), (r'@(debug|warn|if|while)', Keyword, 'value'), (r'(@mixin)( )([\w-]+)', bygroups(Keyword, Whitespace, Name.Function), 'value'), (r'(@include)( )([\w-]+)', bygroups(Keyword, Whitespace, Name.Decorator), 'value'), (r'@extend', Keyword, 'selector'), (r'@[\w-]+', Keyword, 'selector'), (r'=[\w-]+', Name.Function, 'value'), (r'\+[\w-]+', Name.Decorator, 'value'), (r'([!$][\w-]\w*)([ \t]*(?:(?:\|\|)?=|:))', bygroups(Name.Variable, Operator), 'value'), (r':', Name.Attribute, 'old-style-attr'), (r'(?=.+?[=:]([^a-z]|$))', Name.Attribute, 'new-style-attr'), default('selector'), ],
'single-comment': [ (r'.+', Comment.Single), (r'\n', Whitespace, 'root'), ],
'multi-comment': [ (r'.+', Comment.Multiline), (r'\n', Whitespace, 'root'), ],
'import': [ (r'[ \t]+', Whitespace), (r'\S+', String), (r'\n', Whitespace, 'root'), ],
'old-style-attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'([ \t]*)(=)', bygroups(Whitespace, Operator), 'value'), default('value'), ],
'new-style-attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'([ \t]*)([=:])', bygroups(Whitespace, Operator), 'value'), ],
'inline-comment': [ (r"(\\#|#(?=[^\n{])|\*(?=[^\n/])|[^\n#*])+", Comment.Multiline), (r'#\{', String.Interpol, 'interpolation'), (r"\*/", Comment, '#pop'), ], } for group, common in common_sass_tokens.items(): tokens[group] = copy.copy(common) tokens['value'].append((r'\n', Whitespace, 'root')) tokens['selector'].append((r'\n', Whitespace, 'root'))
class ScssLexer(RegexLexer): """ For SCSS stylesheets. """
name = 'SCSS' url = 'https://sass-lang.com/' aliases = ['scss'] filenames = ['*.scss'] mimetypes = ['text/x-scss'] version_added = ''
flags = re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'\s+', Whitespace), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@import', Keyword, 'value'), (r'@for', Keyword, 'for'), (r'@(debug|warn|if|while)', Keyword, 'value'), (r'(@mixin)( [\w-]+)', bygroups(Keyword, Name.Function), 'value'), (r'(@include)( [\w-]+)', bygroups(Keyword, Name.Decorator), 'value'), (r'@extend', Keyword, 'selector'), (r'(@media)(\s+)', bygroups(Keyword, Whitespace), 'value'), (r'@[\w-]+', Keyword, 'selector'), (r'(\$[\w-]*\w)([ \t]*:)', bygroups(Name.Variable, Operator), 'value'), # TODO: broken, and prone to infinite loops. # (r'(?=[^;{}][;}])', Name.Attribute, 'attr'), # (r'(?=[^;{}:]+:[^a-z])', Name.Attribute, 'attr'), default('selector'), ],
'attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'[ \t]*:', Operator, 'value'), default('#pop'), ],
'inline-comment': [ (r"(\\#|#(?=[^{])|\*(?=[^/])|[^#*])+", Comment.Multiline), (r'#\{', String.Interpol, 'interpolation'), (r"\*/", Comment, '#pop'), ], } for group, common in common_sass_tokens.items(): tokens[group] = copy.copy(common) tokens['value'].extend([(r'\n', Whitespace), (r'[;{}]', Punctuation, '#pop')]) tokens['selector'].extend([(r'\n', Whitespace), (r'[;{}]', Punctuation, '#pop')])
class LessCssLexer(CssLexer): """ For LESS styleshets. """
name = 'LessCss' url = 'http://lesscss.org/' aliases = ['less'] filenames = ['*.less'] mimetypes = ['text/x-less-css'] version_added = '2.1'
tokens = { # FIXME: It's not currently possible to simply do the following, # as `include('basics')` doesn't take overrides into account: # 'basics': [ # (r'//.*\n', Comment.Single), # (r'/\*(?:.|\n)*?\*/', Comment.Multiline), # inherit, # ], 'root': [ (r'@\w+', Name.Variable), (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'atcontent': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'atrule': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'content': [ (r'\{', Punctuation, '#push'), (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'value-start': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'function-start': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259""" pygments.lexers.d ~~~~~~~~~~~~~~~~~
Lexers for D languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Keyword, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['DLexer', 'CrocLexer', 'MiniDLexer']
class DLexer(RegexLexer): """ For D source. """ name = 'D' url = 'https://dlang.org/' filenames = ['*.d', '*.di'] aliases = ['d'] mimetypes = ['text/x-dsrc'] version_added = '1.2'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), # (r'\\\n', Text), # line continuations # Comments (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'/\+', Comment.Multiline, 'nested_comment'), # Keywords (words(( 'abstract', 'alias', 'align', 'asm', 'assert', 'auto', 'body', 'break', 'case', 'cast', 'catch', 'class', 'const', 'continue', 'debug', 'default', 'delegate', 'delete', 'deprecated', 'do', 'else', 'enum', 'export', 'extern', 'finally', 'final', 'foreach_reverse', 'foreach', 'for', 'function', 'goto', 'if', 'immutable', 'import', 'interface', 'invariant', 'inout', 'in', 'is', 'lazy', 'mixin', 'module', 'new', 'nothrow', 'out', 'override', 'package', 'pragma', 'private', 'protected', 'public', 'pure', 'ref', 'return', 'scope', 'shared', 'static', 'struct', 'super', 'switch', 'synchronized', 'template', 'this', 'throw', 'try', 'typeid', 'typeof', 'union', 'unittest', 'version', 'volatile', 'while', 'with', '__gshared', '__traits', '__vector', '__parameters'), suffix=r'\b'), Keyword), (words(( # Removed in 2.072 'typedef', ), suffix=r'\b'), Keyword.Removed), (words(( 'bool', 'byte', 'cdouble', 'cent', 'cfloat', 'char', 'creal', 'dchar', 'double', 'float', 'idouble', 'ifloat', 'int', 'ireal', 'long', 'real', 'short', 'ubyte', 'ucent', 'uint', 'ulong', 'ushort', 'void', 'wchar'), suffix=r'\b'), Keyword.Type), (r'(false|true|null)\b', Keyword.Constant), (words(( '__FILE__', '__FILE_FULL_PATH__', '__MODULE__', '__LINE__', '__FUNCTION__', '__PRETTY_FUNCTION__', '__DATE__', '__EOF__', '__TIME__', '__TIMESTAMP__', '__VENDOR__', '__VERSION__'), suffix=r'\b'), Keyword.Pseudo), (r'macro\b', Keyword.Reserved), (r'(string|wstring|dstring|size_t|ptrdiff_t)\b', Name.Builtin), # FloatLiteral # -- HexFloat (r'0[xX]([0-9a-fA-F_]*\.[0-9a-fA-F_]+|[0-9a-fA-F_]+)' r'[pP][+\-]?[0-9_]+[fFL]?[i]?', Number.Float), # -- DecimalFloat (r'[0-9_]+(\.[0-9_]+[eE][+\-]?[0-9_]+|' r'\.[0-9_]*|[eE][+\-]?[0-9_]+)[fFL]?[i]?', Number.Float), (r'\.(0|[1-9][0-9_]*)([eE][+\-]?[0-9_]+)?[fFL]?[i]?', Number.Float), # IntegerLiteral # -- Binary (r'0[Bb][01_]+', Number.Bin), # -- Octal (r'0[0-7_]+', Number.Oct), # -- Hexadecimal (r'0[xX][0-9a-fA-F_]+', Number.Hex), # -- Decimal (r'(0|[1-9][0-9_]*)([LUu]|Lu|LU|uL|UL)?', Number.Integer), # CharacterLiteral (r"""'(\\['"?\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\&\w+;|.)'""", String.Char), # StringLiteral # -- WysiwygString (r'r"[^"]*"[cwd]?', String), # -- AlternateWysiwygString (r'`[^`]*`[cwd]?', String), # -- DoubleQuotedString (r'"(\\\\|\\[^\\]|[^"\\])*"[cwd]?', String), # -- EscapeSequence (r"\\(['\"?\\abfnrtv]|x[0-9a-fA-F]{2}|[0-7]{1,3}" r"|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|&\w+;)", String), # -- HexString (r'x"[0-9a-fA-F_\s]*"[cwd]?', String), # -- DelimitedString (r'q"\[', String, 'delimited_bracket'), (r'q"\(', String, 'delimited_parenthesis'), (r'q"<', String, 'delimited_angle'), (r'q"\{', String, 'delimited_curly'), (r'q"([a-zA-Z_]\w*)\n.*?\n\1"', String), (r'q"(.).*?\1"', String), # -- TokenString (r'q\{', String, 'token_string'), # Attributes (r'@([a-zA-Z_]\w*)?', Name.Decorator), # Tokens (r'(~=|\^=|%=|\*=|==|!>=|!<=|!<>=|!<>|!<|!>|!=|>>>=|>>>|>>=|>>|>=' r'|<>=|<>|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.\.|\.\.|/=)' r'|[/.&|\-+<>!()\[\]{}?,;:$=*%^~]', Punctuation), # Identifier (r'[a-zA-Z_]\w*', Name), # Line (r'(#line)(\s)(.*)(\n)', bygroups(Comment.Special, Whitespace, Comment.Special, Whitespace)), ], 'nested_comment': [ (r'[^+/]+', Comment.Multiline), (r'/\+', Comment.Multiline, '#push'), (r'\+/', Comment.Multiline, '#pop'), (r'[+/]', Comment.Multiline), ], 'token_string': [ (r'\{', Punctuation, 'token_string_nest'), (r'\}', String, '#pop'), include('root'), ], 'token_string_nest': [ (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), include('root'), ], 'delimited_bracket': [ (r'[^\[\]]+', String), (r'\[', String, 'delimited_inside_bracket'), (r'\]"', String, '#pop'), ], 'delimited_inside_bracket': [ (r'[^\[\]]+', String), (r'\[', String, '#push'), (r'\]', String, '#pop'), ], 'delimited_parenthesis': [ (r'[^()]+', String), (r'\(', String, 'delimited_inside_parenthesis'), (r'\)"', String, '#pop'), ], 'delimited_inside_parenthesis': [ (r'[^()]+', String), (r'\(', String, '#push'), (r'\)', String, '#pop'), ], 'delimited_angle': [ (r'[^<>]+', String), (r'<', String, 'delimited_inside_angle'), (r'>"', String, '#pop'), ], 'delimited_inside_angle': [ (r'[^<>]+', String), (r'<', String, '#push'), (r'>', String, '#pop'), ], 'delimited_curly': [ (r'[^{}]+', String), (r'\{', String, 'delimited_inside_curly'), (r'\}"', String, '#pop'), ], 'delimited_inside_curly': [ (r'[^{}]+', String), (r'\{', String, '#push'), (r'\}', String, '#pop'), ], }
class CrocLexer(RegexLexer): """ For Croc source. """ name = 'Croc' url = 'http://jfbillingsley.com/croc' filenames = ['*.croc'] aliases = ['croc'] mimetypes = ['text/x-crocsrc'] version_added = ''
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), # Comments (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*', Comment.Multiline, 'nestedcomment'), # Keywords (words(( 'as', 'assert', 'break', 'case', 'catch', 'class', 'continue', 'default', 'do', 'else', 'finally', 'for', 'foreach', 'function', 'global', 'namespace', 'if', 'import', 'in', 'is', 'local', 'module', 'return', 'scope', 'super', 'switch', 'this', 'throw', 'try', 'vararg', 'while', 'with', 'yield'), suffix=r'\b'), Keyword), (r'(false|true|null)\b', Keyword.Constant), # FloatLiteral (r'([0-9][0-9_]*)(?=[.eE])(\.[0-9][0-9_]*)?([eE][+\-]?[0-9_]+)?', Number.Float), # IntegerLiteral # -- Binary (r'0[bB][01][01_]*', Number.Bin), # -- Hexadecimal (r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex), # -- Decimal (r'([0-9][0-9_]*)(?![.eE])', Number.Integer), # CharacterLiteral (r"""'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-9]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|.)'""", String.Char), # StringLiteral # -- WysiwygString (r'@"(""|[^"])*"', String), (r'@`(``|[^`])*`', String), (r"@'(''|[^'])*'", String), # -- DoubleQuotedString (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # Tokens (r'(~=|\^=|%=|\*=|==|!=|>>>=|>>>|>>=|>>|>=|<=>|\?=|-\>' r'|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.|/=)' r'|[-/.&$@|\+<>!()\[\]{}?,;:=*%^~#\\]', Punctuation), # Identifier (r'[a-zA-Z_]\w*', Name), ], 'nestedcomment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], }
class MiniDLexer(CrocLexer): """ For MiniD source. MiniD is now known as Croc. """ name = 'MiniD' filenames = [] # don't lex .md as MiniD, reserve for Markdown aliases = ['minid'] mimetypes = ['text/x-minidsrc'] version_added = ''123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126""" pygments.lexers.dalvik ~~~~~~~~~~~~~~~~~~~~~~
Pygments lexers for Dalvik VM-related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Keyword, Text, Comment, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['SmaliLexer']
class SmaliLexer(RegexLexer): """ For Smali (Android/Dalvik) assembly code. """ name = 'Smali' url = 'http://code.google.com/p/smali/' aliases = ['smali'] filenames = ['*.smali'] mimetypes = ['text/smali'] version_added = '1.6'
tokens = { 'root': [ include('comment'), include('label'), include('field'), include('method'), include('class'), include('directive'), include('access-modifier'), include('instruction'), include('literal'), include('punctuation'), include('type'), include('whitespace') ], 'directive': [ (r'^([ \t]*)(\.(?:class|super|implements|field|subannotation|annotation|' r'enum|method|registers|locals|array-data|packed-switch|' r'sparse-switch|catchall|catch|line|parameter|local|prologue|' r'epilogue|source))', bygroups(Whitespace, Keyword)), (r'^([ \t]*)(\.end)( )(field|subannotation|annotation|method|array-data|' 'packed-switch|sparse-switch|parameter|local)', bygroups(Whitespace, Keyword, Whitespace, Keyword)), (r'^([ \t]*)(\.restart)( )(local)', bygroups(Whitespace, Keyword, Whitespace, Keyword)), ], 'access-modifier': [ (r'(public|private|protected|static|final|synchronized|bridge|' r'varargs|native|abstract|strictfp|synthetic|constructor|' r'declared-synchronized|interface|enum|annotation|volatile|' r'transient)', Keyword), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), ], 'instruction': [ (r'\b[vp]\d+\b', Name.Builtin), # registers (r'(\b[a-z][A-Za-z0-9/-]+)(\s+)', bygroups(Text, Whitespace)), # instructions ], 'literal': [ (r'".*"', String), (r'0x[0-9A-Fa-f]+t?', Number.Hex), (r'[0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'[0-9]+L?', Number.Integer), ], 'field': [ (r'(\$?\b)([\w$]*)(:)', bygroups(Punctuation, Name.Variable, Punctuation)), ], 'method': [ (r'<(?:cl)?init>', Name.Function), # constructor (r'(\$?\b)([\w$]*)(\()', bygroups(Punctuation, Name.Function, Punctuation)), ], 'label': [ (r':\w+', Name.Label), ], 'class': [ # class names in the form Lcom/namespace/ClassName; # I only want to color the ClassName part, so the namespace part is # treated as 'Text' (r'(L)((?:[\w$]+/)*)([\w$]+)(;)', bygroups(Keyword.Type, Text, Name.Class, Text)), ], 'punctuation': [ (r'->', Punctuation), (r'[{},():=.-]', Punctuation), ], 'type': [ (r'[ZBSCIJFDV\[]+', Keyword.Type), ], 'comment': [ (r'#.*?\n', Comment), ], }
def analyse_text(text): score = 0 if re.search(r'^\s*\.class\s', text, re.MULTILINE): score += 0.5 if re.search(r'\b((check-cast|instance-of|throw-verification-error' r')\b|(-to|add|[ais]get|[ais]put|and|cmpl|const|div|' r'if|invoke|move|mul|neg|not|or|rem|return|rsub|shl|' r'shr|sub|ushr)[-/])|{|}', text, re.MULTILINE): score += 0.3 if re.search(r'(\.(catchall|epilogue|restart local|prologue)|' r'\b(array-data|class-change-error|declared-synchronized|' r'(field|inline|vtable)@0x[0-9a-fA-F]|generic-error|' r'illegal-class-access|illegal-field-access|' r'illegal-method-access|instantiation-error|no-error|' r'no-such-class|no-such-field|no-such-method|' r'packed-switch|sparse-switch))\b', text, re.MULTILINE): score += 0.6 return score123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763""" pygments.lexers.data ~~~~~~~~~~~~~~~~~~~~
Lexers for data file format.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import Lexer, ExtendedRegexLexer, LexerContext, \ include, bygroupsfrom pygments.token import Comment, Error, Keyword, Literal, Name, Number, \ Punctuation, String, Whitespace
__all__ = ['YamlLexer', 'JsonLexer', 'JsonBareObjectLexer', 'JsonLdLexer']
class YamlLexerContext(LexerContext): """Indentation context for the YAML lexer."""
def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.indent_stack = [] self.indent = -1 self.next_indent = 0 self.block_scalar_indent = None
class YamlLexer(ExtendedRegexLexer): """ Lexer for YAML, a human-friendly data serialization language. """
name = 'YAML' url = 'http://yaml.org/' aliases = ['yaml'] filenames = ['*.yaml', '*.yml'] mimetypes = ['text/x-yaml'] version_added = '0.11'
def something(token_class): """Do not produce empty tokens.""" def callback(lexer, match, context): text = match.group() if not text: return yield match.start(), token_class, text context.pos = match.end() return callback
def reset_indent(token_class): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), token_class, text context.pos = match.end() return callback
def save_indent(token_class, start=False): """Save a possible indentation level.""" def callback(lexer, match, context): text = match.group() extra = '' if start: context.next_indent = len(text) if context.next_indent < context.indent: while context.next_indent < context.indent: context.indent = context.indent_stack.pop() if context.next_indent > context.indent: extra = text[context.indent:] text = text[:context.indent] else: context.next_indent += len(text) if text: yield match.start(), token_class, text if extra: yield match.start()+len(text), token_class.Error, extra context.pos = match.end() return callback
def set_indent(token_class, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_indent if not implicit: context.next_indent += len(text) yield match.start(), token_class, text context.pos = match.end() return callback
def set_block_scalar_indent(token_class): """Set an explicit indentation level for a block scalar.""" def callback(lexer, match, context): text = match.group() context.block_scalar_indent = None if not text: return increment = match.group(1) if increment: current_indent = max(context.indent, 0) increment = int(increment) context.block_scalar_indent = current_indent + increment if text: yield match.start(), token_class, text context.pos = match.end() return callback
def parse_block_scalar_empty_line(indent_token_class, content_token_class): """Process an empty line in a block scalar.""" def callback(lexer, match, context): text = match.group() if (context.block_scalar_indent is None or len(text) <= context.block_scalar_indent): if text: yield match.start(), indent_token_class, text else: indentation = text[:context.block_scalar_indent] content = text[context.block_scalar_indent:] yield match.start(), indent_token_class, indentation yield (match.start()+context.block_scalar_indent, content_token_class, content) context.pos = match.end() return callback
def parse_block_scalar_indent(token_class): """Process indentation spaces in a block scalar.""" def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() context.stack.pop() return context.block_scalar_indent = len(text) else: if len(text) < context.block_scalar_indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback
def parse_plain_scalar_indent(token_class): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback
tokens = { # the root rules 'root': [ # ignored whitespaces (r'[ ]+(?=#|$)', Whitespace), # line breaks (r'\n+', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # the '%YAML' directive (r'^%YAML(?=[ ]|$)', reset_indent(Name.Tag), 'yaml-directive'), # the %TAG directive (r'^%TAG(?=[ ]|$)', reset_indent(Name.Tag), 'tag-directive'), # document start and document end indicators (r'^(?:---|\.\.\.)(?=[ ]|$)', reset_indent(Name.Namespace), 'block-line'), # indentation spaces (r'[ ]*(?!\s|$)', save_indent(Whitespace, start=True), ('block-line', 'indentation')), ],
# trailing whitespaces after directives or a block scalar indicator 'ignored-line': [ # ignored whitespaces (r'[ ]+(?=#|$)', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # line break (r'\n', Whitespace, '#pop:2'), ],
# the %YAML directive 'yaml-directive': [ # the version number (r'([ ]+)([0-9]+\.[0-9]+)', bygroups(Whitespace, Number), 'ignored-line'), ],
# the %TAG directive 'tag-directive': [ # a tag handle and the corresponding prefix (r'([ ]+)(!|![\w-]*!)' r'([ ]+)(!|!?[\w;/?:@&=+$,.!~*\'()\[\]%-]+)', bygroups(Whitespace, Keyword.Type, Whitespace, Keyword.Type), 'ignored-line'), ],
# block scalar indicators and indentation spaces 'indentation': [ # trailing whitespaces are ignored (r'[ ]*$', something(Whitespace), '#pop:2'), # whitespaces preceding block collection indicators (r'[ ]+(?=[?:-](?:[ ]|$))', save_indent(Whitespace)), # block collection indicators (r'[?:-](?=[ ]|$)', set_indent(Punctuation.Indicator)), # the beginning a block line (r'[ ]*', save_indent(Whitespace), '#pop'), ],
# an indented line in the block context 'block-line': [ # the line end (r'[ ]*(?=#|$)', something(Whitespace), '#pop'), # whitespaces separating tokens (r'[ ]+', Whitespace), # key with colon (r'''([^#,?\[\]{}"'\n]+)(:)(?=[ ]|$)''', bygroups(Name.Tag, set_indent(Punctuation, implicit=True))), # tags, anchors and aliases, include('descriptors'), # block collections and scalars include('block-nodes'), # flow collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`-]|[?:-]\S)', something(Name.Variable), 'plain-scalar-in-block-context'), ],
# tags, anchors, aliases 'descriptors': [ # a full-form tag (r'!<[\w#;/?:@&=+$,.!~*\'()\[\]%-]+>', Keyword.Type), # a tag in the form '!', '!suffix' or '!handle!suffix' (r'!(?:[\w-]+!)?' r'[\w#;/?:@&=+$,.!~*\'()\[\]%-]*', Keyword.Type), # an anchor (r'&[\w-]+', Name.Label), # an alias (r'\*[\w-]+', Name.Variable), ],
# block collections and scalars 'block-nodes': [ # implicit key (r':(?=[ ]|$)', set_indent(Punctuation.Indicator, implicit=True)), # literal and folded scalars (r'[|>]', Punctuation.Indicator, ('block-scalar-content', 'block-scalar-header')), ],
# flow collections and quoted scalars 'flow-nodes': [ # a flow sequence (r'\[', Punctuation.Indicator, 'flow-sequence'), # a flow mapping (r'\{', Punctuation.Indicator, 'flow-mapping'), # a single-quoted scalar (r'\'', String, 'single-quoted-scalar'), # a double-quoted scalar (r'\"', String, 'double-quoted-scalar'), ],
# the content of a flow collection 'flow-collection': [ # whitespaces (r'[ ]+', Whitespace), # line breaks (r'\n+', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # simple indicators (r'[?:,]', Punctuation.Indicator), # tags, anchors and aliases include('descriptors'), # nested collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`])', something(Name.Variable), 'plain-scalar-in-flow-context'), ],
# a flow sequence indicated by '[' and ']' 'flow-sequence': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\]', Punctuation.Indicator, '#pop'), ],
# a flow mapping indicated by '{' and '}' 'flow-mapping': [ # key with colon (r'''([^,:?\[\]{}"'\n]+)(:)(?=[ ]|$)''', bygroups(Name.Tag, Punctuation)), # include flow collection rules include('flow-collection'), # the closing indicator (r'\}', Punctuation.Indicator, '#pop'), ],
# block scalar lines 'block-scalar-content': [ # line break (r'\n', Whitespace), # empty line (r'^[ ]+$', parse_block_scalar_empty_line(Whitespace, Name.Constant)), # indentation spaces (we may leave the state here) (r'^[ ]*', parse_block_scalar_indent(Whitespace)), # line content (r'[\S\t ]+', Name.Constant), ],
# the content of a literal or folded scalar 'block-scalar-header': [ # indentation indicator followed by chomping flag (r'([1-9])?[+-]?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), # chomping flag followed by indentation indicator (r'[+-]?([1-9])?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), ],
# ignored and regular whitespaces in quoted scalars 'quoted-scalar-whitespaces': [ # leading and trailing whitespaces are ignored (r'^[ ]+', Whitespace), (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), ],
# single-quoted scalars 'single-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of the quote character (r'\'\'', String.Escape), # regular non-whitespace characters (r'[^\s\']+', String), # the closing quote (r'\'', String, '#pop'), ],
# double-quoted scalars 'double-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of special characters (r'\\[0abt\tn\nvfre "\\N_LP]', String), # escape codes (r'\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})', String.Escape), # regular non-whitespace characters (r'[^\s"\\]+', String), # the closing quote (r'"', String, '#pop'), ],
# the beginning of a new line while scanning a plain scalar 'plain-scalar-in-block-context-new-line': [ # empty lines (r'^[ ]+$', Whitespace), # line breaks (r'\n+', Whitespace), # document start and document end indicators (r'^(?=---|\.\.\.)', something(Name.Namespace), '#pop:3'), # indentation spaces (we may leave the block line state here) (r'^[ ]*', parse_plain_scalar_indent(Whitespace), '#pop'), ],
# a plain scalar in the block context 'plain-scalar-in-block-context': [ # the scalar ends with the ':' indicator (r'[ ]*(?=:[ ]|:$)', something(Whitespace), '#pop'), # the scalar ends with whitespaces followed by a comment (r'[ ]+(?=#)', Whitespace, '#pop'), # trailing whitespaces are ignored (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace, 'plain-scalar-in-block-context-new-line'), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Plain), # regular non-whitespace characters (r'(?::(?!\s)|[^\s:])+', Literal.Scalar.Plain), ],
# a plain scalar is the flow context 'plain-scalar-in-flow-context': [ # the scalar ends with an indicator character (r'[ ]*(?=[,:?\[\]{}])', something(Whitespace), '#pop'), # the scalar ends with a comment (r'[ ]+(?=#)', Whitespace, '#pop'), # leading and trailing whitespaces are ignored (r'^[ ]+', Whitespace), (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), # regular non-whitespace characters (r'[^\s,:?\[\]{}]+', Name.Variable), ],
}
def get_tokens_unprocessed(self, text=None, context=None): if context is None: context = YamlLexerContext(text, 0) return super().get_tokens_unprocessed(text, context)
class JsonLexer(Lexer): """ For JSON data structures.
Javascript-style comments are supported (like ``/* */`` and ``//``), though comments are not part of the JSON specification. This allows users to highlight JSON as it is used in the wild.
No validation is performed on the input JSON document. """
name = 'JSON' url = 'https://www.json.org' aliases = ['json', 'json-object'] filenames = ['*.json', '*.jsonl', '*.ndjson', 'Pipfile.lock', '*.module', '*.xc'] mimetypes = ['application/json', 'application/json-object', 'application/x-ndjson', 'application/jsonl', 'application/json-seq'] version_added = '1.5'
# No validation of integers, floats, or constants is done. # As long as the characters are members of the following # sets, the token will be considered valid. For example, # # "--1--" is parsed as an integer # "1...eee" is parsed as a float # "trustful" is parsed as a constant # integers = set('-0123456789') floats = set('.eE+') constants = set('truefalsenull') # true|false|null hexadecimals = set('0123456789abcdefABCDEF') punctuations = set('{}[],') whitespaces = {'\u0020', '\u000a', '\u000d', '\u0009'}
def get_tokens_unprocessed(self, text): """Parse JSON data."""
in_string = False in_escape = False in_unicode_escape = 0 in_whitespace = False in_constant = False in_number = False in_float = False in_punctuation = False in_comment_single = False in_comment_multiline = False expecting_second_comment_opener = False # // or /* expecting_second_comment_closer = False # */
start = 0
# The queue is used to store data that may need to be tokenized # differently based on what follows. In particular, JSON object # keys are tokenized differently than string values, but cannot # be distinguished until punctuation is encountered outside the # string. # # A ":" character after the string indicates that the string is # an object key; any other character indicates the string is a # regular string value. # # The queue holds tuples that contain the following data: # # (start_index, token_type, text) # # By default the token type of text in double quotes is # String.Double. The token type will be replaced if a colon # is encountered after the string closes. # queue = []
for stop, character in enumerate(text): if in_string: if in_unicode_escape: if character in self.hexadecimals: in_unicode_escape -= 1 if not in_unicode_escape: in_escape = False else: in_unicode_escape = 0 in_escape = False
elif in_escape: if character == 'u': in_unicode_escape = 4 else: in_escape = False
elif character == '\\': in_escape = True
elif character == '"': queue.append((start, String.Double, text[start:stop + 1])) in_string = False in_escape = False in_unicode_escape = 0
continue
elif in_whitespace: if character in self.whitespaces: continue
if queue: queue.append((start, Whitespace, text[start:stop])) else: yield start, Whitespace, text[start:stop] in_whitespace = False # Fall through so the new character can be evaluated.
elif in_constant: if character in self.constants: continue
yield start, Keyword.Constant, text[start:stop] in_constant = False # Fall through so the new character can be evaluated.
elif in_number: if character in self.integers: continue elif character in self.floats: in_float = True continue
if in_float: yield start, Number.Float, text[start:stop] else: yield start, Number.Integer, text[start:stop] in_number = False in_float = False # Fall through so the new character can be evaluated.
elif in_punctuation: if character in self.punctuations: continue
yield start, Punctuation, text[start:stop] in_punctuation = False # Fall through so the new character can be evaluated.
elif in_comment_single: if character != '\n': continue
if queue: queue.append((start, Comment.Single, text[start:stop])) else: yield start, Comment.Single, text[start:stop]
in_comment_single = False # Fall through so the new character can be evaluated.
elif in_comment_multiline: if character == '*': expecting_second_comment_closer = True elif expecting_second_comment_closer: expecting_second_comment_closer = False if character == '/': if queue: queue.append((start, Comment.Multiline, text[start:stop + 1])) else: yield start, Comment.Multiline, text[start:stop + 1]
in_comment_multiline = False
continue
elif expecting_second_comment_opener: expecting_second_comment_opener = False if character == '/': in_comment_single = True continue elif character == '*': in_comment_multiline = True continue
# Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
yield start, Error, text[start:stop] # Fall through so the new character can be evaluated.
start = stop
if character == '"': in_string = True
elif character in self.whitespaces: in_whitespace = True
elif character in {'f', 'n', 't'}: # The first letters of true|false|null # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_constant = True
elif character in self.integers: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_number = True
elif character == ':': # Yield from the queue. Replace string token types. for _start, _token, _text in queue: # There can be only three types of tokens before a ':': # Whitespace, Comment, or a quoted string. # # If it's a quoted string we emit Name.Tag. # Otherwise, we yield the original token. # # In all other cases this would be invalid JSON, # but this is not a validating JSON lexer, so it's OK. if _token is String.Double: yield _start, Name.Tag, _text else: yield _start, _token, _text queue.clear()
in_punctuation = True
elif character in self.punctuations: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_punctuation = True
elif character == '/': # This is the beginning of a comment. expecting_second_comment_opener = True
else: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
yield start, Error, character
# Yield any remaining text. yield from queue if in_string: yield start, Error, text[start:] elif in_float: yield start, Number.Float, text[start:] elif in_number: yield start, Number.Integer, text[start:] elif in_constant: yield start, Keyword.Constant, text[start:] elif in_whitespace: yield start, Whitespace, text[start:] elif in_punctuation: yield start, Punctuation, text[start:] elif in_comment_single: yield start, Comment.Single, text[start:] elif in_comment_multiline: yield start, Error, text[start:] elif expecting_second_comment_opener: yield start, Error, text[start:]
class JsonBareObjectLexer(JsonLexer): """ For JSON data structures (with missing object curly braces).
.. deprecated:: 2.8.0
Behaves the same as `JsonLexer` now. """
name = 'JSONBareObject' aliases = [] filenames = [] mimetypes = [] version_added = '2.2'
class JsonLdLexer(JsonLexer): """ For JSON-LD linked data. """
name = 'JSON-LD' url = 'https://json-ld.org/' aliases = ['jsonld', 'json-ld'] filenames = ['*.jsonld'] mimetypes = ['application/ld+json'] version_added = '2.0'
json_ld_keywords = { f'"@{keyword}"' for keyword in ( 'base', 'container', 'context', 'direction', 'graph', 'id', 'import', 'included', 'index', 'json', 'language', 'list', 'nest', 'none', 'prefix', 'propagate', 'protected', 'reverse', 'set', 'type', 'value', 'version', 'vocab', ) }
def get_tokens_unprocessed(self, text): for start, token, value in super().get_tokens_unprocessed(text): if token is Name.Tag and value in self.json_ld_keywords: yield start, Name.Decorator, value else: yield start, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135""" pygments.lexers.dax ~~~~~~~~~~~~~~~~~~~
Lexer for LilyPond.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Punctuation, Whitespace,\ Name, Operator, String, Number, Text
__all__ = ['DaxLexer']
class DaxLexer(RegexLexer): """ Lexer for Power BI DAX Referenced from: https://github.com/sql-bi/SyntaxHighlighterBrushDax """ name = 'Dax' aliases = ['dax'] filenames = ['*.dax'] url = 'https://learn.microsoft.com/en-us/dax/dax-function-reference' mimetypes = [] version_added = '2.15'
tokens = { 'root': [ (r'\s+', Whitespace), (r"--.*\n?", Comment.Single), # Comment: Double dash comment (r"//.*\n?", Comment.Single), # Comment: Double backslash comment (r'/\*', Comment.Multiline, 'multiline-comments'), (words(('abs', 'accrint', 'accrintm', 'acos', 'acosh', 'acot', 'acoth', 'addcolumns', 'addmissingitems', 'all', 'allcrossfiltered', 'allexcept', 'allnoblankrow', 'allselected', 'amordegrc', 'amorlinc', 'and','approximatedistinctcount', 'asin', 'asinh', 'atan', 'atanh', 'average', 'averagea', 'averagex', 'beta.dist', 'beta.inv', 'bitand', 'bitlshift', 'bitor', 'bitrshift', 'bitxor', 'blank', 'calculate', 'calculatetable', 'calendar', 'calendarauto', 'ceiling', 'chisq.dist', 'chisq.dist.rt', 'chisq.inv', 'chisq.inv.rt', 'closingbalancemonth', 'closingbalancequarter', 'closingbalanceyear', 'coalesce', 'columnstatistics', 'combin', 'combina', 'combinevalues', 'concatenate', 'concatenatex', 'confidence.norm', 'confidence.t', 'contains', 'containsrow', 'containsstring', 'containsstringexact', 'convert', 'cos', 'cosh', 'cot', 'coth', 'count', 'counta', 'countax', 'countblank', 'countrows', 'countx', 'coupdaybs', 'coupdays', 'coupdaysnc', 'coupncd', 'coupnum', 'couppcd', 'crossfilter', 'crossjoin', 'cumipmt', 'cumprinc', 'currency', 'currentgroup', 'customdata', 'datatable', 'date', 'dateadd', 'datediff', 'datesbetween', 'datesinperiod', 'datesmtd', 'datesqtd', 'datesytd', 'datevalue', 'day', 'db', 'ddb', 'degrees', 'detailrows', 'disc', 'distinct', 'distinctcount', 'distinctcountnoblank', 'divide', 'dollarde', 'dollarfr', 'duration', 'earlier', 'earliest', 'edate', 'effect', 'endofmonth', 'endofquarter', 'endofyear', 'eomonth', 'error', 'evaluateandlog', 'even', 'exact', 'except', 'exp', 'expon.dist', 'fact', 'false', 'filter', 'filters', 'find', 'firstdate', 'firstnonblank', 'firstnonblankvalue', 'fixed', 'floor', 'format', 'fv', 'gcd', 'generate', 'generateall', 'generateseries', 'geomean', 'geomeanx', 'groupby', 'hash', 'hasonefilter', 'hasonevalue', 'hour', 'if', 'if.eager', 'iferror', 'ignore', 'index', 'int', 'intersect', 'intrate', 'ipmt', 'isafter', 'isblank', 'iscrossfiltered', 'isempty', 'iserror', 'iseven', 'isfiltered', 'isinscope', 'islogical', 'isnontext', 'isnumber', 'iso.ceiling', 'isodd', 'isonorafter', 'ispmt', 'isselectedmeasure', 'issubtotal', 'istext', 'keepfilters', 'keywordmatch', 'lastdate', 'lastnonblank', 'lastnonblankvalue', 'lcm', 'left', 'len', 'linest', 'linestx', 'ln', 'log', 'log10', 'lookupvalue', 'lower', 'max', 'maxa', 'maxx', 'mduration', 'median', 'medianx', 'mid', 'min', 'mina', 'minute', 'minx', 'mod', 'month', 'mround', 'nameof', 'naturalinnerjoin', 'naturalleftouterjoin', 'networkdays', 'nextday', 'nextmonth', 'nextquarter', 'nextyear', 'nominal', 'nonvisual', 'norm.dist', 'norm.inv', 'norm.s.dist', 'norm.s.inv', 'not', 'now', 'nper', 'odd', 'oddfprice', 'oddfyield', 'oddlprice', 'oddlyield', 'offset', 'openingbalancemonth', 'openingbalancequarter', 'openingbalanceyear', 'or', 'orderby', 'parallelperiod', 'partitionby', 'path', 'pathcontains', 'pathitem', 'pathitemreverse', 'pathlength', 'pduration', 'percentile.exc', 'percentile.inc', 'percentilex.exc', 'percentilex.inc', 'permut', 'pi', 'pmt', 'poisson.dist', 'power', 'ppmt', 'previousday', 'previousmonth', 'previousquarter', 'previousyear', 'price', 'pricedisc', 'pricemat', 'product', 'productx', 'pv', 'quarter', 'quotient', 'radians', 'rand', 'randbetween', 'rank.eq', 'rankx', 'rate', 'received', 'related', 'relatedtable', 'removefilters', 'replace', 'rept', 'right', 'rollup', 'rollupaddissubtotal', 'rollupgroup', 'rollupissubtotal', 'round', 'rounddown', 'roundup', 'row', 'rri', 'sameperiodlastyear', 'sample', 'sampleaxiswithlocalminmax', 'search', 'second', 'selectcolumns', 'selectedmeasure', 'selectedmeasureformatstring', 'selectedmeasurename', 'selectedvalue', 'sign', 'sin', 'sinh', 'sln', 'sqrt', 'sqrtpi', 'startofmonth', 'startofquarter', 'startofyear', 'stdev.p', 'stdev.s', 'stdevx.p', 'stdevx.s', 'substitute', 'substitutewithindex', 'sum', 'summarize', 'summarizecolumns', 'sumx', 'switch', 'syd', 't.dist', 't.dist.2t', 't.dist.rt', 't.inv', 't.inv.2t', 'tan', 'tanh', 'tbilleq', 'tbillprice', 'tbillyield', 'time', 'timevalue', 'tocsv', 'today', 'tojson', 'topn', 'topnperlevel', 'topnskip', 'totalmtd', 'totalqtd', 'totalytd', 'treatas', 'trim', 'true', 'trunc', 'unichar', 'unicode', 'union', 'upper', 'userculture', 'userelationship', 'username', 'userobjectid', 'userprincipalname', 'utcnow', 'utctoday', 'value', 'values', 'var.p', 'var.s', 'varx.p', 'varx.s', 'vdb', 'weekday', 'weeknum', 'window', 'xirr', 'xnpv', 'year', 'yearfrac', 'yield', 'yielddisc', 'yieldmat'), prefix=r'(?i)', suffix=r'\b'), Name.Function), #Functions
(words(('at','asc','boolean','both','by','create','currency', 'datetime','day','define','desc','double', 'evaluate','false','integer','measure', 'month','none','order','return','single','start','string', 'table','true','var','year'), prefix=r'(?i)', suffix=r'\b'), Name.Builtin), # Keyword
(r':=|[-+*\/=^]', Operator), (r'\b(IN|NOT)\b', Operator.Word), (r'"', String, 'string'), #StringLiteral (r"'(?:[^']|'')*'(?!')(?:\[[ \w]+\])?|\w+\[[ \w]+\]", Name.Attribute), # Column reference (r"\[[ \w]+\]", Name.Attribute), #Measure reference (r'(?<!\w)(\d+\.?\d*|\.\d+\b)', Number),# Number (r'[\[\](){}`,.]', Punctuation), #Parenthesis (r'.*\n', Text),
], 'multiline-comments': [ (r'/\*', Comment.Multiline, 'multiline-comments'), (r'\*/', Comment.Multiline, '#pop'), (r'[^/*]+', Comment.Multiline), (r'[/*]', Comment.Multiline) ], 'string': [ (r'""', String.Escape), (r'"', String, '#pop'), (r'[^"]+', String), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120""" pygments.lexers.devicetree ~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Devicetree language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, default, wordsfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace
__all__ = ['DevicetreeLexer']
class DevicetreeLexer(RegexLexer): """ Lexer for Devicetree files. """
name = 'Devicetree' url = 'https://www.devicetree.org/' aliases = ['devicetree', 'dts'] filenames = ['*.dts', '*.dtsi'] mimetypes = ['text/x-c'] version_added = '2.7'
#: optional Whitespace or /*...*/ style comment _ws = r'\s*(?:/[*][^*/]*?[*]/\s*)*'
tokens = { 'macro': [ # Include preprocessor directives (C style): (r'(#include)(' + _ws + r')([^\n]+)', bygroups(Comment.Preproc, Comment.Multiline, Comment.PreprocFile)), # Define preprocessor directives (C style): (r'(#define)(' + _ws + r')([^\n]+)', bygroups(Comment.Preproc, Comment.Multiline, Comment.Preproc)), # devicetree style with file: (r'(/[^*/{]+/)(' + _ws + r')("[^\n{]+")', bygroups(Comment.Preproc, Comment.Multiline, Comment.PreprocFile)), # devicetree style with property: (r'(/[^*/{]+/)(' + _ws + r')([^\n;{]*)([;]?)', bygroups(Comment.Preproc, Comment.Multiline, Comment.Preproc, Punctuation)), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'\\\n', Text), # line continuation (r'//(\n|[\w\W]*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*][\w\W]*?[*](\\\n)?/', Comment.Multiline), # Open until EOF, so no ending delimiter (r'/(\\\n)?[*][\w\W]*', Comment.Multiline), ], 'statements': [ (r'(L?)(")', bygroups(String.Affix, String), 'string'), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (r'([^\s{}/*]*)(\s*)(:)', bygroups(Name.Label, Text, Punctuation), '#pop'), (words(('compatible', 'model', 'phandle', 'status', '#address-cells', '#size-cells', 'reg', 'virtual-reg', 'ranges', 'dma-ranges', 'device_type', 'name'), suffix=r'\b'), Keyword.Reserved), (r'([~!%^&*+=|?:<>/#-])', Operator), (r'[(){},.\]]', Punctuation), (r'\[', Punctuation, 'bytestring'), (r'[a-zA-Z_][\w-]*(?=(?:\s*,' + _ws + r'[a-zA-Z_][\w-]*)*' + _ws + r'[=;])', Name), (r'[a-zA-Z_]\w*', Name.Attribute), ], 'root': [ include('whitespace'), include('macro'), # Overlay/fragment: &label { ... } or &{/path/to/node} { ... } (r'(&)(?:([A-Za-z_]\w*)|(\{)([^}]+)(\}))(' + _ws + r')(\{)', bygroups(Operator, Name.Function, Punctuation, Name.Namespace, Punctuation, Comment.Multiline, Punctuation), 'node'), # Nodes (r'([^/*@\s&]+|/)(@?)((?:0x)?[0-9a-fA-F,]*)(' + _ws + r')(\{)', bygroups(Name.Function, Operator, Number.Integer, Comment.Multiline, Punctuation), 'node'),
default('statement'), ], 'statement': [ include('whitespace'), include('statements'), (';', Punctuation, '#pop'), ], 'node': [ include('whitespace'), include('macro'), # Overlay/fragment: &label { ... } or &{/path/to/node} { ... } (r'(&)(?:([A-Za-z_]\w*)|(\{)([^}]+)(\}))(' + _ws + r')(\{)', bygroups(Operator, Name.Function, Punctuation, Name.Namespace, Punctuation, Comment.Multiline, Punctuation), '#push'), (r'([^/*@\s&]+|/)(@?)((?:0x)?[0-9a-fA-F,]*)(' + _ws + r')(\{)', bygroups(Name.Function, Operator, Number.Integer, Comment.Multiline, Punctuation), '#push'),
include('statements'),
(r'\};', Punctuation, '#pop'), (';', Punctuation), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ], 'bytestring': [ (r'\]', Punctuation, '#pop'), (r'[0-9a-fA-F]{2}', Number.Hex), (r'\s+', Whitespace), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169""" pygments.lexers.diff ~~~~~~~~~~~~~~~~~~~~
Lexers for diff/patch formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, Generic, \ Literal, Whitespace
__all__ = ['DiffLexer', 'DarcsPatchLexer', 'WDiffLexer']
class DiffLexer(RegexLexer): """ Lexer for unified or context-style diffs or patches. """
name = 'Diff' aliases = ['diff', 'udiff'] filenames = ['*.diff', '*.patch'] mimetypes = ['text/x-diff', 'text/x-patch'] url = 'https://en.wikipedia.org/wiki/Diff' version_added = ''
tokens = { 'root': [ (r'( )(.*)(\n)', bygroups(Whitespace, Text, Whitespace)), (r'(!.*|---)(\n)', bygroups(Generic.Strong, Whitespace)), (r'((?:< |-).*)(\n)', bygroups(Generic.Deleted, Whitespace)), (r'((?:> |\+).*)(\n)', bygroups(Generic.Inserted, Whitespace)), ( r'(@.*|\d(?:,\d+)?(?:a|c|d)\d+(?:,\d+)?)(\n)', bygroups(Generic.Subheading, Whitespace), ), (r'((?:[Ii]ndex|diff).*)(\n)', bygroups(Generic.Heading, Whitespace)), (r'(=.*)(\n)', bygroups(Generic.Heading, Whitespace)), (r'(.*)(\n)', bygroups(Text, Whitespace)), ] }
def analyse_text(text): if text[:7] == 'Index: ': return True if text[:5] == 'diff ': return True if text[:4] == '--- ': return 0.9
class DarcsPatchLexer(RegexLexer): """ DarcsPatchLexer is a lexer for the various versions of the darcs patch format. Examples of this format are derived by commands such as ``darcs annotate --patch`` and ``darcs send``. """
name = 'Darcs Patch' aliases = ['dpatch'] filenames = ['*.dpatch', '*.darcspatch'] url = 'https://darcs.net' version_added = '0.10'
DPATCH_KEYWORDS = ('hunk', 'addfile', 'adddir', 'rmfile', 'rmdir', 'move', 'replace')
tokens = { 'root': [ (r'<', Operator), (r'>', Operator), (r'\{', Operator), (r'\}', Operator), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)(\])', bygroups(Operator, Keyword, Name, Whitespace, Name, Operator, Literal.Date, Whitespace, Operator)), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)', bygroups(Operator, Keyword, Name, Whitespace, Name, Operator, Literal.Date, Whitespace), 'comment'), (r'New patches:', Generic.Heading), (r'Context:', Generic.Heading), (r'Patch bundle hash:', Generic.Heading), (r'(\s*)({})(.*)(\n)'.format('|'.join(DPATCH_KEYWORDS)), bygroups(Whitespace, Keyword, Text, Whitespace)), (r'\+', Generic.Inserted, "insert"), (r'-', Generic.Deleted, "delete"), (r'(.*)(\n)', bygroups(Text, Whitespace)), ], 'comment': [ (r'[^\]].*\n', Comment), (r'\]', Operator, "#pop"), ], 'specialText': [ # darcs add [_CODE_] special operators for clarity (r'\n', Whitespace, "#pop"), # line-based (r'\[_[^_]*_]', Operator), ], 'insert': [ include('specialText'), (r'\[', Generic.Inserted), (r'[^\n\[]+', Generic.Inserted), ], 'delete': [ include('specialText'), (r'\[', Generic.Deleted), (r'[^\n\[]+', Generic.Deleted), ], }
class WDiffLexer(RegexLexer): """ A wdiff lexer.
Note that:
* It only works with normal output (without options like ``-l``). * If the target files contain "[-", "-]", "{+", or "+}", especially they are unbalanced, the lexer will get confused. """
name = 'WDiff' url = 'https://www.gnu.org/software/wdiff/' aliases = ['wdiff'] filenames = ['*.wdiff'] mimetypes = [] version_added = '2.2'
flags = re.MULTILINE | re.DOTALL
# We can only assume "[-" after "[-" before "-]" is `nested`, # for instance wdiff to wdiff outputs. We have no way to # distinct these marker is of wdiff output from original text.
ins_op = r"\{\+" ins_cl = r"\+\}" del_op = r"\[\-" del_cl = r"\-\]" normal = r'[^{}[\]+-]+' # for performance tokens = { 'root': [ (ins_op, Generic.Inserted, 'inserted'), (del_op, Generic.Deleted, 'deleted'), (normal, Text), (r'.', Text), ], 'inserted': [ (ins_op, Generic.Inserted, '#push'), (del_op, Generic.Inserted, '#push'), (del_cl, Generic.Inserted, '#pop'),
(ins_cl, Generic.Inserted, '#pop'), (normal, Generic.Inserted), (r'.', Generic.Inserted), ], 'deleted': [ (del_op, Generic.Deleted, '#push'), (ins_op, Generic.Deleted, '#push'), (ins_cl, Generic.Deleted, '#pop'),
(del_cl, Generic.Deleted, '#pop'), (normal, Generic.Deleted), (r'.', Generic.Deleted), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109""" pygments.lexers.dns ~~~~~~~~~~~~~~~~~~~
Pygments lexers for DNS
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace, Literalfrom pygments.lexer import RegexLexer, bygroups, include
__all__ = ['DnsZoneLexer']
CLASSES = [ "IN", "CS", "CH", "HS",]
CLASSES_RE = "(" + "|".join(CLASSES) + ')'
class DnsZoneLexer(RegexLexer):
""" Lexer for DNS zone file """
flags = re.MULTILINE
name = 'Zone' aliases = ['zone'] filenames = [ "*.zone" ] url = "https://datatracker.ietf.org/doc/html/rfc1035" mimetypes = ['text/dns'] version_added = '2.16'
tokens = { 'root': [ # Empty/comment line: (r'([ \t]*)(;.*)(\n)', bygroups(Whitespace, Comment.Single, Whitespace)), # Special directives: (r'^\$ORIGIN\b', Keyword, 'values'), (r'^\$TTL\b', Keyword, 'values'), (r'^\$INCLUDE\b', Comment.Preproc, 'include'), # TODO, $GENERATE https://bind9.readthedocs.io/en/v9.18.14/chapter3.html#soa-rr (r'^\$[A-Z]+\b', Keyword, 'values'), # Records: # <domain-name> [<TTL>] [<class>] <type> <RDATA> [<comment>] (r'^(@)([ \t]+)(?:([0-9]+[smhdw]?)([ \t]+))?(?:' + CLASSES_RE + "([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Operator, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), (r'^([^ \t\n]*)([ \t]+)(?:([0-9]+[smhdw]?)([ \t]+))?(?:' + CLASSES_RE + "([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), # <domain-name> [<class>] [<TTL>] <type> <RDATA> [<comment>] (r'^(Operator)([ \t]+)(?:' + CLASSES_RE + "([ \t]+))?(?:([0-9]+[smhdw]?)([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), (r'^([^ \t\n]*)([ \t]+)(?:' + CLASSES_RE + "([ \t]+))?(?:([0-9]+[smhdw]?)([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), ], # Parsing values: 'values': [ (r'\n', Whitespace, "#pop"), (r'\(', Punctuation, 'nested'), include('simple-value'), ], # Parsing nested values (...): 'nested': [ (r'\)', Punctuation, "#pop"), include('multiple-simple-values'), ], # Parsing values: 'simple-value': [ (r'(;.*)', bygroups(Comment.Single)), (r'[ \t]+', Whitespace), (r"@\b", Operator), ('"', String, 'string'), (r'[0-9]+[smhdw]?$', Number.Integer), (r'([0-9]+[smhdw]?)([ \t]+)', bygroups(Number.Integer, Whitespace)), (r'\S+', Literal), ], 'multiple-simple-values': [ include('simple-value'), (r'[\n]+', Whitespace), ], 'include': [ (r'([ \t]+)([^ \t\n]+)([ \t]+)([-\._a-zA-Z]+)([ \t]+)(;.*)?$', bygroups(Whitespace, Comment.PreprocFile, Whitespace, Name, Whitespace, Comment.Single), '#pop'), (r'([ \t]+)([^ \t\n]+)([ \t\n]+)$', bygroups(Whitespace, Comment.PreprocFile, Whitespace), '#pop'), ], "string": [ (r'\\"', String), (r'"', String, "#pop"), (r'[^"]+', String), ] }
def analyse_text(text): return text.startswith("$ORIGIN")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873""" pygments.lexers.dotnet ~~~~~~~~~~~~~~~~~~~~~~
Lexers for .net languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""import re
from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \ using, this, default, wordsfrom pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ Name, String, Number, Literal, Other, Whitespacefrom pygments.util import get_choice_optfrom pygments import unistring as uni
from pygments.lexers.html import XmlLexer
__all__ = ['CSharpLexer', 'NemerleLexer', 'BooLexer', 'VbNetLexer', 'CSharpAspxLexer', 'VbNetAspxLexer', 'FSharpLexer', 'XppLexer']
class CSharpLexer(RegexLexer): """ For C# source code.
Additional options accepted:
`unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``.
.. versionadded:: 0.8 """
name = 'C#' url = 'https://docs.microsoft.com/en-us/dotnet/csharp/' aliases = ['csharp', 'c#', 'cs'] filenames = ['*.cs'] mimetypes = ['text/x-csharp'] # inferred version_added = ''
flags = re.MULTILINE | re.DOTALL
# for the range of allowed unicode characters in identifiers, see # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = { 'none': r'@?[_a-zA-Z]\w*', 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), }
tokens = {} token_variants = True
for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ include('numbers'), # method names (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, Punctuation)), (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Whitespace), (words(( '>>>=', '>>=', '<<=', '<=', '>=', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '??=', '=>', '??', '?.', '!=', '==', '&&', '||', '>>>', '>>', '<<', '++', '--', '+', '-', '*', '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', )), Operator), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'[()\[\];:,.]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b(.*?)(\n)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Comment.Preproc, Whitespace)), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)), (words(( 'abstract', 'as', 'async', 'await', 'base', 'break', 'by', 'case', 'catch', 'checked', 'const', 'continue', 'default', 'delegate', 'do', 'else', 'enum', 'event', 'explicit', 'extern', 'false', 'finally', 'fixed', 'for', 'foreach', 'goto', 'if', 'implicit', 'in', 'interface', 'internal', 'is', 'let', 'lock', 'new', 'null', 'on', 'operator', 'out', 'override', 'params', 'private', 'protected', 'public', 'readonly', 'ref', 'return', 'sealed', 'sizeof', 'stackalloc', 'static', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'unchecked', 'unsafe', 'virtual', 'void', 'while', 'get', 'set', 'new', 'partial', 'yield', 'add', 'remove', 'value', 'alias', 'ascending', 'descending', 'from', 'group', 'into', 'orderby', 'select', 'thenby', 'where', 'join', 'equals', 'record', 'allows', 'and', 'init', 'managed', 'nameof', 'nint', 'not', 'notnull', 'nuint', 'or', 'scoped', 'unmanaged', 'when', 'with' ), suffix=r'\b'), Keyword), # version 1: assumes that 'file' is the only contextual keyword # that is a class modifier (r'(file)(\s+)(record|class|abstract|enum|new|sealed|static)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|dynamic|float|int|long|object|' r'sbyte|short|string|uint|ulong|ushort|var)\b\??', Keyword.Type), (r'(class|struct)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (cs_ident, Name), ], 'numbers_int': [ (r"0[xX][0-9a-fA-F]+(([uU][lL]?)|[lL][uU]?)?", Number.Hex), (r"0[bB][01]+(([uU][lL]?)|[lL][uU]?)?", Number.Bin), (r"[0-9]+(([uU][lL]?)|[lL][uU]?)?", Number.Integer), ], 'numbers_float': [ (r"([0-9]+\.[0-9]+([eE][+-]?[0-9]+)?[fFdDmM]?)|" r"(\.[0-9]+([eE][+-]?[0-9]+)?[fFdDmM]?)|" r"([0-9]+([eE][+-]?[0-9]+)[fFdDmM]?)|" r"([0-9]+[fFdDmM])", Number.Float), ], 'numbers': [ include('numbers_float'), include('numbers_int'), ], 'class': [ (cs_ident, Name.Class, '#pop'), default('#pop'), ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop'), ] }
def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
class NemerleLexer(RegexLexer): """ For Nemerle source code.
Additional options accepted:
`unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``. """
name = 'Nemerle' url = 'http://nemerle.org' aliases = ['nemerle'] filenames = ['*.n'] mimetypes = ['text/x-nemerle'] # inferred version_added = '1.5'
flags = re.MULTILINE | re.DOTALL
# for the range of allowed unicode characters in identifiers, see # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = { 'none': r'@?[_a-zA-Z]\w*', 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), }
tokens = {} token_variants = True
for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ # method names (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, \ Punctuation)), (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Whitespace), (r'(\$)(\s*)(")', bygroups(String, Whitespace, String), 'splice-string'), (r'(\$)(\s*)(<#)', bygroups(String, Whitespace, String), 'splice-string2'), (r'<#', String, 'recursive-string'),
(r'(<\[)(\s*)(' + cs_ident + ':)?', bygroups(Keyword, Whitespace, Keyword)), (r'\]\>', Keyword),
# quasiquotation only (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'),
(r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number), (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b', bygroups(Comment.Preproc, Whitespace, Comment.Preproc), 'preproc'), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(abstract|and|as|base|catch|def|delegate|' r'enum|event|extern|false|finally|' r'fun|implements|interface|internal|' r'is|macro|match|matches|module|mutable|new|' r'null|out|override|params|partial|private|' r'protected|public|ref|sealed|static|' r'syntax|this|throw|true|try|type|typeof|' r'virtual|volatile|when|where|with|' r'assert|assert2|async|break|checked|continue|do|else|' r'ensures|for|foreach|if|late|lock|new|nolate|' r'otherwise|regexp|repeat|requires|return|surroundwith|' r'unchecked|unless|using|while|yield)\b', Keyword), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|' r'short|string|uint|ulong|ushort|void|array|list)\b\??', Keyword.Type), (r'(:>?)(\s*)(' + cs_ident + r'\??)', bygroups(Punctuation, Whitespace, Keyword.Type)), (r'(class|struct|variant|module)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (cs_ident, Name), ], 'class': [ (cs_ident, Name.Class, '#pop') ], 'preproc': [ (r'\w+', Comment.Preproc), (r'[ \t]+', Whitespace), (r'\n', Whitespace, '#pop') ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop') ], 'splice-string': [ (r'[^"$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'\\"', String), (r'"', String, '#pop') ], 'splice-string2': [ (r'[^#<>$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'recursive-string': [ (r'[^#<>]', String), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'splice-string-content': [ (r'if|match', Keyword), (r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation), (cs_ident, Name), (r'\d+', Number), (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop') ] }
def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
def analyse_text(text): """Nemerle is quite similar to Python, but @if is relatively uncommon elsewhere.""" result = 0
if '@if' in text: result += 0.1
return result
class BooLexer(RegexLexer): """ For Boo source code. """
name = 'Boo' url = 'https://github.com/boo-lang/boo' aliases = ['boo'] filenames = ['*.boo'] mimetypes = ['text/x-boo'] version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace), (r'(#|//).*$', Comment.Single), (r'/[*]', Comment.Multiline, 'comment'), (r'[]{}:(),.;[]', Punctuation), (r'(\\)(\n)', bygroups(Text, Whitespace)), (r'\\', Text), (r'(in|is|and|or|not)\b', Operator.Word), (r'/(\\\\|\\[^\\]|[^/\\\s])/', String.Regex), (r'@/(\\\\|\\[^\\]|[^/\\])*/', String.Regex), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'(as|abstract|callable|constructor|destructor|do|import|' r'enum|event|final|get|interface|internal|of|override|' r'partial|private|protected|public|return|set|static|' r'struct|transient|virtual|yield|super|and|break|cast|' r'continue|elif|else|ensure|except|for|given|goto|if|in|' r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|' r'while|from|as)\b', Keyword), (r'def(?=\s+\(.*?\))', Keyword), (r'(def)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(namespace)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|' r'assert|checked|enumerate|filter|getter|len|lock|map|' r'matrix|max|min|normalArrayIndexing|print|property|range|' r'rawArrayIndexing|required|typeof|unchecked|using|' r'yieldAll|zip)\b', Name.Builtin), (r'"""(\\\\|\\"|.*?)"""', String.Double), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_]\w*', Name), (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float), (r'[0-9][0-9.]*(ms?|d|h|s)', Number), (r'0\d+', Number.Oct), (r'0x[a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+', Number.Integer), ], 'comment': [ ('/[*]', Comment.Multiline, '#push'), ('[*]/', Comment.Multiline, '#pop'), ('[^/*]', Comment.Multiline), ('[*/]', Comment.Multiline) ], 'funcname': [ (r'[a-zA-Z_]\w*', Name.Function, '#pop') ], 'classname': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'namespace': [ (r'[a-zA-Z_][\w.]*', Name.Namespace, '#pop') ] }
class VbNetLexer(RegexLexer): """ For Visual Basic.NET source code. Also LibreOffice Basic, OpenOffice Basic, and StarOffice Basic. """
name = 'VB.net' url = 'https://docs.microsoft.com/en-us/dotnet/visual-basic/' aliases = ['vb.net', 'vbnet', 'lobas', 'oobas', 'sobas', 'visual-basic', 'visualbasic'] filenames = ['*.vb', '*.bas'] mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?) version_added = ''
uni_name = '[_' + uni.combine('Ll', 'Lt', 'Lm', 'Nl') + ']' + \ '[' + uni.combine('Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'
flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'^\s*<.*?>', Name.Attribute), (r'\s+', Whitespace), (r'\n', Whitespace), (r'(rem\b.*?)(\n)', bygroups(Comment, Whitespace)), (r"('.*?)(\n)", bygroups(Comment, Whitespace)), (r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#Else|#End\s+If|#Const|' r'#ExternalSource.*?\n|#End\s+ExternalSource|' r'#Region.*?\n|#End\s+Region|#ExternalChecksum', Comment.Preproc), (r'[(){}!#,.:]', Punctuation), (r'(Option)(\s+)(Strict|Explicit|Compare)(\s+)' r'(On|Off|Binary|Text)', bygroups(Keyword.Declaration, Whitespace, Keyword.Declaration, Whitespace, Keyword.Declaration)), (words(( 'AddHandler', 'Alias', 'ByRef', 'ByVal', 'Call', 'Case', 'Catch', 'CBool', 'CByte', 'CChar', 'CDate', 'CDec', 'CDbl', 'CInt', 'CLng', 'CObj', 'Continue', 'CSByte', 'CShort', 'CSng', 'CStr', 'CType', 'CUInt', 'CULng', 'CUShort', 'Declare', 'Default', 'Delegate', 'DirectCast', 'Do', 'Each', 'Else', 'ElseIf', 'EndIf', 'Erase', 'Error', 'Event', 'Exit', 'False', 'Finally', 'For', 'Friend', 'Get', 'Global', 'GoSub', 'GoTo', 'Handles', 'If', 'Implements', 'Inherits', 'Interface', 'Let', 'Lib', 'Loop', 'Me', 'MustInherit', 'MustOverride', 'MyBase', 'MyClass', 'Narrowing', 'New', 'Next', 'Not', 'Nothing', 'NotInheritable', 'NotOverridable', 'Of', 'On', 'Operator', 'Option', 'Optional', 'Overloads', 'Overridable', 'Overrides', 'ParamArray', 'Partial', 'Private', 'Protected', 'Public', 'RaiseEvent', 'ReadOnly', 'ReDim', 'RemoveHandler', 'Resume', 'Return', 'Select', 'Set', 'Shadows', 'Shared', 'Single', 'Static', 'Step', 'Stop', 'SyncLock', 'Then', 'Throw', 'To', 'True', 'Try', 'TryCast', 'Wend', 'Using', 'When', 'While', 'Widening', 'With', 'WithEvents', 'WriteOnly'), prefix=r'(?<!\.)', suffix=r'\b'), Keyword), (r'(?<!\.)End\b', Keyword, 'end'), (r'(?<!\.)(Dim|Const)\b', Keyword, 'dim'), (r'(?<!\.)(Function|Sub|Property)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(?<!\.)(Class|Structure|Enum)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(?<!\.)(Module|Namespace|Imports)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|' r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|' r'UShort)\b', Keyword.Type), (r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|' r'Or|OrElse|TypeOf|Xor)\b', Operator.Word), (r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|' r'<=|>=|<>|[-&*/\\^+=<>\[\]]', Operator), ('"', String, 'string'), (r'(_)(\n)', bygroups(Text, Whitespace)), # Line continuation (must be before Name) (uni_name + '[%&@!#$]?', Name), ('#.*?#', Literal.Date), (r'(\d+\.\d*|\d*\.\d+)(F[+-]?[0-9]+)?', Number.Float), (r'\d+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer), ], 'string': [ (r'""', String), (r'"C?', String, '#pop'), (r'[^"]+', String), ], 'dim': [ (uni_name, Name.Variable, '#pop'), default('#pop'), # any other syntax ], 'funcname': [ (uni_name, Name.Function, '#pop'), ], 'classname': [ (uni_name, Name.Class, '#pop'), ], 'namespace': [ (uni_name, Name.Namespace), (r'\.', Name.Namespace), default('#pop'), ], 'end': [ (r'\s+', Whitespace), (r'(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b', Keyword, '#pop'), default('#pop'), ] }
def analyse_text(text): if re.search(r'^\s*(#If|Module|Namespace)', text, re.MULTILINE): return 0.5
class GenericAspxLexer(RegexLexer): """ Lexer for ASP.NET pages. """
name = 'aspx-gen' filenames = [] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet'
flags = re.DOTALL
tokens = { 'root': [ (r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)), (r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer), Other, using(XmlLexer))), (r'(.+?)(?=<)', using(XmlLexer)), (r'.+', using(XmlLexer)), ], }
# TODO support multiple languages within the same source fileclass CSharpAspxLexer(DelegatingLexer): """ Lexer for highlighting C# within ASP.NET pages. """
name = 'aspx-cs' aliases = ['aspx-cs'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet' version_added = ''
def __init__(self, **options): super().__init__(CSharpLexer, GenericAspxLexer, **options)
def analyse_text(text): if re.search(r'Page\s*Language="C#"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None: return 0.15
class VbNetAspxLexer(DelegatingLexer): """ Lexer for highlighting Visual Basic.net within ASP.NET pages. """
name = 'aspx-vb' aliases = ['aspx-vb'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet' version_added = ''
def __init__(self, **options): super().__init__(VbNetLexer, GenericAspxLexer, **options)
def analyse_text(text): if re.search(r'Page\s*Language="Vb"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None: return 0.15
# Very close to functional.OcamlLexerclass FSharpLexer(RegexLexer): """ For the F# language (version 3.0). """
name = 'F#' url = 'https://fsharp.org/' aliases = ['fsharp', 'f#'] filenames = ['*.fs', '*.fsi', '*.fsx'] mimetypes = ['text/x-fsharp'] version_added = '1.5'
keywords = [ 'abstract', 'as', 'assert', 'base', 'begin', 'class', 'default', 'delegate', 'do!', 'do', 'done', 'downcast', 'downto', 'elif', 'else', 'end', 'exception', 'extern', 'false', 'finally', 'for', 'function', 'fun', 'global', 'if', 'inherit', 'inline', 'interface', 'internal', 'in', 'lazy', 'let!', 'let', 'match', 'member', 'module', 'mutable', 'namespace', 'new', 'null', 'of', 'open', 'override', 'private', 'public', 'rec', 'return!', 'return', 'select', 'static', 'struct', 'then', 'to', 'true', 'try', 'type', 'upcast', 'use!', 'use', 'val', 'void', 'when', 'while', 'with', 'yield!', 'yield', ] # Reserved words; cannot hurt to color them as keywords too. keywords += [ 'atomic', 'break', 'checked', 'component', 'const', 'constraint', 'constructor', 'continue', 'eager', 'event', 'external', 'fixed', 'functor', 'include', 'method', 'mixin', 'object', 'parallel', 'process', 'protected', 'pure', 'sealed', 'tailcall', 'trait', 'virtual', 'volatile', ] keyopts = [ '!=', '#', '&&', '&', r'\(', r'\)', r'\*', r'\+', ',', r'-\.', '->', '-', r'\.\.', r'\.', '::', ':=', ':>', ':', ';;', ';', '<-', r'<\]', '<', r'>\]', '>', r'\?\?', r'\?', r'\[<', r'\[\|', r'\[', r'\]', '_', '`', r'\{', r'\|\]', r'\|', r'\}', '~', '<@@', '<@', '=', '@>', '@@>', ]
operators = r'[!$%&*+\./:<=>?@^|~-]' word_operators = ['and', 'or', 'not'] prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]' primitives = [ 'sbyte', 'byte', 'char', 'nativeint', 'unativeint', 'float32', 'single', 'float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'decimal', 'unit', 'bool', 'string', 'list', 'exn', 'obj', 'enum', ]
# See http://msdn.microsoft.com/en-us/library/dd233181.aspx and/or # http://fsharp.org/about/files/spec.pdf for reference. Good luck.
tokens = { 'escape-sequence': [ (r'\\[\\"\'ntbrafv]', String.Escape), (r'\\[0-9]{3}', String.Escape), (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\U[0-9a-fA-F]{8}', String.Escape), ], 'root': [ (r'\s+', Whitespace), (r'\(\)|\[\]', Name.Builtin.Pseudo), (r'\b(?<!\.)([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][\w\']*)', Name), (r'(///.*?)(\n)', bygroups(String.Doc, Whitespace)), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'\(\*(?!\))', Comment, 'comment'),
(r'@"', String, 'lstring'), (r'"""', String, 'tqs'), (r'"', String, 'string'),
(r'\b(open|module)(\s+)([\w.]+)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'\b(let!?)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Variable)), (r'\b(type)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Class)), (r'\b(member|override)(\s+)(\w+)(\.)(\w+)', bygroups(Keyword, Whitespace, Name, Punctuation, Name.Function)), (r'\b({})\b'.format('|'.join(keywords)), Keyword), (r'``([^`\n\r\t]|`[^`\n\r\t])+``', Name), (r'({})'.format('|'.join(keyopts)), Operator), (rf'({infix_syms}|{prefix_syms})?{operators}', Operator), (r'\b({})\b'.format('|'.join(word_operators)), Operator.Word), (r'\b({})\b'.format('|'.join(primitives)), Keyword.Type), (r'(#)([ \t]*)(if|endif|else|line|nowarn|light|\d+)\b(.*?)(\n)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Comment.Preproc, Whitespace)),
(r"[^\W\d][\w']*", Name),
(r'\d[\d_]*[uU]?[yslLnQRZINGmM]?', Number.Integer), (r'0[xX][\da-fA-F][\da-fA-F_]*[uU]?[yslLn]?[fF]?', Number.Hex), (r'0[oO][0-7][0-7_]*[uU]?[yslLn]?', Number.Oct), (r'0[bB][01][01_]*[uU]?[yslLn]?', Number.Bin), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)[fFmM]?', Number.Float),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'B?", String.Char), (r"'.'", String.Char), (r"'", Keyword), # a stray quote is another syntax element
(r'@?"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name.Variable), ], 'dotted': [ (r'\s+', Whitespace), (r'\.', Punctuation), (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace), (r'[A-Z][\w\']*', Name, '#pop'), (r'[a-z_][\w\']*', Name, '#pop'), # e.g. dictionary index access default('#pop'), ], 'comment': [ (r'[^(*)@"]+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), # comments cannot be closed within strings in comments (r'@"', String, 'lstring'), (r'"""', String, 'tqs'), (r'"', String, 'string'), (r'[(*)@]', Comment), ], 'string': [ (r'[^\\"]+', String), include('escape-sequence'), (r'\\\n', String), (r'\n', String), # newlines are allowed in any string (r'"B?', String, '#pop'), ], 'lstring': [ (r'[^"]+', String), (r'\n', String), (r'""', String), (r'"B?', String, '#pop'), ], 'tqs': [ (r'[^"]+', String), (r'\n', String), (r'"""B?', String, '#pop'), (r'"', String), ], }
def analyse_text(text): """F# doesn't have that many unique features -- |> and <| are weak indicators.""" result = 0 if '|>' in text: result += 0.05 if '<|' in text: result += 0.05
return result
class XppLexer(RegexLexer):
""" For X++ source code. This is based loosely on the CSharpLexer """
name = 'X++' url = 'https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/dev-ref/xpp-language-reference' aliases = ['xpp', 'x++'] filenames = ['*.xpp'] version_added = '2.15'
flags = re.MULTILINE
XPP_CHARS = ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*') # Temporary, see # https://github.com/thatch/regexlint/pull/49 XPP_CHARS = XPP_CHARS.replace('\x00', '\x01')
OPERATORS = ( '<=', '>=', '+=', '-=', '*=', '/=', '!=', '==', '&&', '||', '>>', '<<', '++', '--', '+', '-', '*', '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', ) KEYWORDS = ('abstract','anytype','as','async','asc','at','avg','break','breakpoint','by','byref','case','catch', 'changecompany','client','container','continue','count','crosscompany','default','delegate', 'delete_from','desc','display','div','do','edit','else','element','eventhandler','exists','false','final', 'firstfast','firstonly','firstonly10','firstonly100','firstonly1000','flush','for','forceliterals', 'forcenestedloop','forceplaceholders','forceselectorder','forupdate','from','group','if','insert_recordset', 'interface','is','join','like','maxof','minof','mod','new','next','nofetch','notexists','null','optimisticlock','order', 'outer','pause','pessimisticlock','print','private','protected','public','repeatableread','retry','return', 'reverse','select','server','setting','static','sum','super','switch','tablelock','this','throw','true','try','ttsabort','ttsbegin', 'ttscommit','update_recordset','validtimestate','void','where','while','window') RUNTIME_FUNCTIONS = ('_duration','abs','acos','any2Date','any2Enum','any2Guid','any2Int','any2Int64','any2Real','any2Str','anytodate', 'anytoenum','anytoguid','anytoint','anytoint64','anytoreal','anytostr','asin','atan','beep','cTerm','char2Num','classIdGet', 'corrFlagGet','corrFlagSet','cos','cosh','curExt','curUserId','date2Num','date2Str','datetime2Str','dayName','dayOfMth', 'dayOfWk','dayOfYr','ddb','decRound','dg','dimOf','endMth','enum2str','exp','exp10','fV','fieldId2Name','fieldId2PName', 'fieldName2Id','frac','funcName','getCurrentPartition','getCurrentPartitionRecId','getPrefix','guid2Str','idg','indexId2Name', 'indexName2Id','int2Str','int642Str','intvMax','intvName','intvNo','intvNorm','log10','logN','match','max','min','mkDate','mthName', 'mthOfYr','newGuid','nextMth','nextQtr','nextYr','num2Char','num2Date','num2Str','pmt','power','prevMth','prevQtr','prevYr', 'prmIsDefault','pt','pv','rate','refPrintAll','round','runAs','sessionId','setPrefix','sin','sinh','sleep','sln','str2Date', 'str2Datetime','str2Enum','str2Guid','str2Int','str2Int64','str2Num','str2Time','strAlpha','strCmp','strColSeq','strDel', 'strFind','strFmt','strIns','strKeep','strLTrim','strLen','strLine','strLwr','strNFind','strPoke','strPrompt','strRTrim', 'strRem','strRep','strScan','strUpr','subStr','syd','systemDateGet','systemDateSet','tableId2Name', 'tableId2PName','tableName2Id','tan','tanh','term','time2Str','timeNow','today','trunc','typeOf','uint2Str','wkOfYr','year') COMPILE_FUNCTIONS = ('attributeStr','classNum','classStr','configurationKeyNum','configurationKeyStr','dataEntityDataSourceStr','delegateStr', 'dimensionHierarchyLevelStr','dimensionHierarchyStr','dimensionReferenceStr','dutyStr','enumCnt','enumLiteralStr','enumNum','enumStr', 'extendedTypeNum','extendedTypeStr','fieldNum','fieldPName','fieldStr','formControlStr','formDataFieldStr','formDataSourceStr', 'formMethodStr','formStr','identifierStr','indexNum','indexStr','licenseCodeNum','licenseCodeStr','literalStr','maxDate','maxInt', 'measureStr','measurementStr','menuItemActionStr','menuItemDisplayStr','menuItemOutputStr','menuStr','methodStr','minInt','privilegeStr', 'queryDatasourceStr','queryMethodStr','queryStr','reportStr','resourceStr','roleStr','ssrsReportStr','staticDelegateStr','staticMethodStr', 'tableCollectionStr','tableFieldGroupStr','tableMethodStr','tableNum','tablePName','tableStaticMethodStr','tableStr','tileStr','varStr', 'webActionItemStr','webDisplayContentItemStr','webFormStr','webMenuStr','webOutputContentItemStr','webReportStr','webSiteTempStr', 'webStaticFileStr','webUrlItemStr','webWebPartStr','webletItemStr','webpageDefStr','websiteDefStr','workflowApprovalStr', 'workflowCategoryStr','workflowTaskStr','workflowTypeStr')
tokens = {}
tokens = { 'root': [ # method names (r'(\s*)\b(else|if)\b([^\n])', bygroups(Whitespace, Keyword, using(this))), # ensure that if is not treated like a function (r'^([ \t]*)((?:' + XPP_CHARS + r'(?:\[\])?\s+)+?)' # return type r'(' + XPP_CHARS + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, Punctuation)), (r'^(\s*)(\[)([^\n]*?)(\])', bygroups(Whitespace, Name.Attribute, Name.Variable.Class, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//[^\n]*?\n', Comment.Single), (r'/[*][^\n]*?[*]/', Comment.Multiline), (r'\n', Whitespace), (words(OPERATORS), Operator), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'[()\[\];:,.#@]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (words(KEYWORDS, suffix=r'\b'), Keyword), (r'(boolean|int|int64|str|real|guid|date)\b\??', Keyword.Type), (r'(class|struct|extends|implements)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'('+XPP_CHARS+')(::)', bygroups(Name.Variable.Class, Punctuation)), (r'(\s*)(\w+)(\s+\w+(,|=)?[^\n]*;)', bygroups(Whitespace, Name.Variable.Class, using(this))), # declaration # x++ specific function to get field should highlight the classname (r'(fieldNum\()('+XPP_CHARS+r')(\s*,\s*)('+XPP_CHARS+r')(\s*\))', bygroups(using(this), Name.Variable.Class, using(this), Name.Property, using(this))), # x++ specific function to get table should highlight the classname (r'(tableNum\()('+XPP_CHARS+r')(\s*\))', bygroups(using(this), Name.Variable.Class, using(this))), (words(RUNTIME_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), (words(COMPILE_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), (XPP_CHARS, Name), ], 'class': [ (XPP_CHARS, Name.Class, '#pop'), default('#pop'), ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + XPP_CHARS + r'|\.)+', Name.Namespace, '#pop'), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970""" pygments.lexers.dsls ~~~~~~~~~~~~~~~~~~~~
Lexers for various domain-specific languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, RegexLexer, bygroups, words, \ include, default, this, using, combinedfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ProtoBufLexer', 'ZeekLexer', 'PuppetLexer', 'RslLexer', 'MscgenLexer', 'VGLLexer', 'AlloyLexer', 'PanLexer', 'CrmshLexer', 'ThriftLexer', 'FlatlineLexer', 'SnowballLexer']
class ProtoBufLexer(RegexLexer): """ Lexer for Protocol Buffer definition files. """
name = 'Protocol Buffer' url = 'https://developers.google.com/protocol-buffers/' aliases = ['protobuf', 'proto'] filenames = ['*.proto'] version_added = '1.4'
tokens = { 'root': [ (r'[ \t]+', Whitespace), (r'[,;{}\[\]()<>]', Punctuation), (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline), (words(( 'import', 'option', 'optional', 'required', 'repeated', 'reserved', 'default', 'packed', 'ctype', 'extensions', 'to', 'max', 'rpc', 'returns', 'oneof', 'syntax'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'fixed32', 'fixed64', 'sfixed32', 'sfixed64', 'float', 'double', 'bool', 'string', 'bytes'), suffix=r'\b'), Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'package'), (r'(message|extend)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'message'), (r'(enum|group|service)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'type'), (r'\".*?\"', String), (r'\'.*?\'', String), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'(\-?(inf|nan))\b', Number.Float), (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex), (r'0[0-7]+[LlUu]*', Number.Oct), (r'\d+[LlUu]*', Number.Integer), (r'[+-=]', Operator), (r'([a-zA-Z_][\w.]*)([ \t]*)(=)', bygroups(Name.Attribute, Whitespace, Operator)), (r'[a-zA-Z_][\w.]*', Name), ], 'package': [ (r'[a-zA-Z_][\w\.]*', Name.Namespace, '#pop'), default('#pop'), ], 'message': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop'), default('#pop'), ], 'type': [ (r'[a-zA-Z_]\w*', Name, '#pop'), default('#pop'), ], }
class ThriftLexer(RegexLexer): """ For Thrift interface definitions. """ name = 'Thrift' url = 'https://thrift.apache.org/' aliases = ['thrift'] filenames = ['*.thrift'] mimetypes = ['application/x-thrift'] version_added = '2.1'
tokens = { 'root': [ include('whitespace'), include('comments'), (r'"', String.Double, combined('stringescape', 'dqs')), (r'\'', String.Single, combined('stringescape', 'sqs')), (r'(namespace)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'namespace'), (r'(enum|union|struct|service|exception)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'((?:(?:[^\W\d]|\$)[\w.\[\]$<>]*\s+)+?)' # return arguments r'((?:[^\W\d]|\$)[\w$]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), include('keywords'), include('numbers'), (r'[&=]', Operator), (r'[:;,{}()<>\[\]]', Punctuation), (r'[a-zA-Z_](\.\w|\w)*', Name), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), ], 'comments': [ (r'#.*$', Comment), (r'//.*?\n', Comment), (r'/\*[\w\W]*?\*/', Comment.Multiline), ], 'stringescape': [ (r'\\([\\nrt"\'])', String.Escape), ], 'dqs': [ (r'"', String.Double, '#pop'), (r'[^\\"\n]+', String.Double), ], 'sqs': [ (r"'", String.Single, '#pop'), (r'[^\\\'\n]+', String.Single), ], 'namespace': [ (r'[a-z*](\.\w|\w)*', Name.Namespace, '#pop'), default('#pop'), ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop'), default('#pop'), ], 'keywords': [ (r'(async|oneway|extends|throws|required|optional)\b', Keyword), (r'(true|false)\b', Keyword.Constant), (r'(const|typedef)\b', Keyword.Declaration), (words(( 'cpp_namespace', 'cpp_include', 'cpp_type', 'java_package', 'cocoa_prefix', 'csharp_namespace', 'delphi_namespace', 'php_namespace', 'py_module', 'perl_package', 'ruby_namespace', 'smalltalk_category', 'smalltalk_prefix', 'xsd_all', 'xsd_optional', 'xsd_nillable', 'xsd_namespace', 'xsd_attrs', 'include'), suffix=r'\b'), Keyword.Namespace), (words(( 'void', 'bool', 'byte', 'i16', 'i32', 'i64', 'double', 'string', 'binary', 'map', 'list', 'set', 'slist', 'senum'), suffix=r'\b'), Keyword.Type), (words(( 'BEGIN', 'END', '__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', 'abstract', 'alias', 'and', 'args', 'as', 'assert', 'begin', 'break', 'case', 'catch', 'class', 'clone', 'continue', 'declare', 'def', 'default', 'del', 'delete', 'do', 'dynamic', 'elif', 'else', 'elseif', 'elsif', 'end', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'ensure', 'except', 'exec', 'finally', 'float', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'import', 'in', 'inline', 'instanceof', 'interface', 'is', 'lambda', 'module', 'native', 'new', 'next', 'nil', 'not', 'or', 'pass', 'public', 'print', 'private', 'protected', 'raise', 'redo', 'rescue', 'retry', 'register', 'return', 'self', 'sizeof', 'static', 'super', 'switch', 'synchronized', 'then', 'this', 'throw', 'transient', 'try', 'undef', 'unless', 'unsigned', 'until', 'use', 'var', 'virtual', 'volatile', 'when', 'while', 'with', 'xor', 'yield'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), ], 'numbers': [ (r'[+-]?(\d+\.\d+([eE][+-]?\d+)?|\.?\d+[eE][+-]?\d+)', Number.Float), (r'[+-]?0x[0-9A-Fa-f]+', Number.Hex), (r'[+-]?[0-9]+', Number.Integer), ], }
class ZeekLexer(RegexLexer): """ For Zeek scripts. """ name = 'Zeek' url = 'https://www.zeek.org/' aliases = ['zeek', 'bro'] filenames = ['*.zeek', '*.bro'] version_added = '2.5'
_hex = r'[0-9a-fA-F]' _float = r'((\d*\.?\d+)|(\d+\.?\d*))([eE][-+]?\d+)?' _h = r'[A-Za-z0-9][-A-Za-z0-9]*'
tokens = { 'root': [ include('whitespace'), include('comments'), include('directives'), include('attributes'), include('types'), include('keywords'), include('literals'), include('operators'), include('punctuation'), (r'((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(?=\s*\()', Name.Function), include('identifiers'), ],
'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), ],
'comments': [ (r'#.*$', Comment), ],
'directives': [ (r'@(load-plugin|load-sigs|load|unload)\b.*$', Comment.Preproc), (r'@(DEBUG|DIR|FILENAME|deprecated|if|ifdef|ifndef|else|endif)\b', Comment.Preproc), (r'(@prefixes)(\s*)((\+?=).*)$', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)), ],
'attributes': [ (words(('redef', 'priority', 'log', 'optional', 'default', 'add_func', 'delete_func', 'expire_func', 'read_expire', 'write_expire', 'create_expire', 'synchronized', 'persistent', 'rotate_interval', 'rotate_size', 'encrypt', 'raw_output', 'mergeable', 'error_handler', 'type_column', 'deprecated'), prefix=r'&', suffix=r'\b'), Keyword.Pseudo), ],
'types': [ (words(('any', 'enum', 'record', 'set', 'table', 'vector', 'function', 'hook', 'event', 'addr', 'bool', 'count', 'double', 'file', 'int', 'interval', 'pattern', 'port', 'string', 'subnet', 'time'), suffix=r'\b'), Keyword.Type),
(r'(opaque)(\s+)(of)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b', bygroups(Keyword.Type, Whitespace, Operator.Word, Whitespace, Keyword.Type)),
(r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)(\s*)\b(record|enum)\b', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Operator, Whitespace, Keyword.Type)),
(r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)', bygroups(Keyword, Whitespace, Name, Whitespace, Operator)),
(r'(redef)(\s+)(record|enum)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b', bygroups(Keyword, Whitespace, Keyword.Type, Whitespace, Name.Class)), ],
'keywords': [ (words(('redef', 'export', 'if', 'else', 'for', 'while', 'return', 'break', 'next', 'continue', 'fallthrough', 'switch', 'default', 'case', 'add', 'delete', 'when', 'timeout', 'schedule'), suffix=r'\b'), Keyword), (r'(print)\b', Keyword), (r'(global|local|const|option)\b', Keyword.Declaration), (r'(module)(\s+)(([A-Za-z_]\w*)(?:::([A-Za-z_]\w*))*)\b', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), ],
'literals': [ (r'"', String, 'string'),
# Not the greatest match for patterns, but generally helps # disambiguate between start of a pattern and just a division # operator. (r'/(?=.*/)', String.Regex, 'regex'),
(r'(T|F)\b', Keyword.Constant),
# Port (r'\d{1,5}/(udp|tcp|icmp|unknown)\b', Number),
# IPv4 Address (r'(\d{1,3}.){3}(\d{1,3})\b', Number),
# IPv6 Address (r'\[([0-9a-fA-F]{0,4}:){2,7}([0-9a-fA-F]{0,4})?((\d{1,3}.){3}(\d{1,3}))?\]', Number),
# Numeric (r'0[xX]' + _hex + r'+\b', Number.Hex), (_float + r'\s*(day|hr|min|sec|msec|usec)s?\b', Number.Float), (_float + r'\b', Number.Float), (r'(\d+)\b', Number.Integer),
# Hostnames (_h + r'(\.' + _h + r')+', String), ],
'operators': [ (r'[!%*/+<=>~|&^-]', Operator), (r'([-+=&|]{2}|[+=!><-]=)', Operator), (r'(in|as|is|of)\b', Operator.Word), (r'\??\$', Operator), ],
'punctuation': [ (r'[{}()\[\],;.]', Punctuation), # The "ternary if", which uses '?' and ':', could instead be # treated as an Operator, but colons are more frequently used to # separate field/identifier names from their types, so the (often) # less-prominent Punctuation is used even with '?' for consistency. (r'[?:]', Punctuation), ],
'identifiers': [ (r'([a-zA-Z_]\w*)(::)', bygroups(Name, Punctuation)), (r'[a-zA-Z_]\w*', Name) ],
'string': [ (r'\\.', String.Escape), (r'%-?[0-9]*(\.[0-9]+)?[DTd-gsx]', String.Escape), (r'"', String, '#pop'), (r'.', String), ],
'regex': [ (r'\\.', String.Escape), (r'/', String.Regex, '#pop'), (r'.', String.Regex), ], }
BroLexer = ZeekLexer
class PuppetLexer(RegexLexer): """ For Puppet configuration DSL. """ name = 'Puppet' url = 'https://puppet.com/' aliases = ['puppet'] filenames = ['*.pp'] version_added = '1.6'
tokens = { 'root': [ include('comments'), include('keywords'), include('names'), include('numbers'), include('operators'), include('strings'),
(r'[]{}:(),;[]', Punctuation), (r'\s+', Whitespace), ],
'comments': [ (r'(\s*)(#.*)$', bygroups(Whitespace, Comment)), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), ],
'operators': [ (r'(=>|\?|<|>|=|\+|-|/|\*|~|!|\|)', Operator), (r'(in|and|or|not)\b', Operator.Word), ],
'names': [ (r'[a-zA-Z_]\w*', Name.Attribute), (r'(\$\S+)(\[)(\S+)(\])', bygroups(Name.Variable, Punctuation, String, Punctuation)), (r'\$\S+', Name.Variable), ],
'numbers': [ # Copypasta from the Python lexer (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float), (r'\d+[eE][+-]?[0-9]+j?', Number.Float), (r'0[0-7]+j?', Number.Oct), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+j?', Number.Integer) ],
'keywords': [ # Left out 'group' and 'require' # Since they're often used as attributes (words(( 'absent', 'alert', 'alias', 'audit', 'augeas', 'before', 'case', 'check', 'class', 'computer', 'configured', 'contained', 'create_resources', 'crit', 'cron', 'debug', 'default', 'define', 'defined', 'directory', 'else', 'elsif', 'emerg', 'err', 'exec', 'extlookup', 'fail', 'false', 'file', 'filebucket', 'fqdn_rand', 'generate', 'host', 'if', 'import', 'include', 'info', 'inherits', 'inline_template', 'installed', 'interface', 'k5login', 'latest', 'link', 'loglevel', 'macauthorization', 'mailalias', 'maillist', 'mcx', 'md5', 'mount', 'mounted', 'nagios_command', 'nagios_contact', 'nagios_contactgroup', 'nagios_host', 'nagios_hostdependency', 'nagios_hostescalation', 'nagios_hostextinfo', 'nagios_hostgroup', 'nagios_service', 'nagios_servicedependency', 'nagios_serviceescalation', 'nagios_serviceextinfo', 'nagios_servicegroup', 'nagios_timeperiod', 'node', 'noop', 'notice', 'notify', 'package', 'present', 'purged', 'realize', 'regsubst', 'resources', 'role', 'router', 'running', 'schedule', 'scheduled_task', 'search', 'selboolean', 'selmodule', 'service', 'sha1', 'shellquote', 'split', 'sprintf', 'ssh_authorized_key', 'sshkey', 'stage', 'stopped', 'subscribe', 'tag', 'tagged', 'template', 'tidy', 'true', 'undef', 'unmounted', 'user', 'versioncmp', 'vlan', 'warning', 'yumrepo', 'zfs', 'zone', 'zpool'), prefix='(?i)', suffix=r'\b'), Keyword), ],
'strings': [ (r'"([^"])*"', String), (r"'(\\'|[^'])*'", String), ],
}
class RslLexer(RegexLexer): """ RSL is the formal specification language used in RAISE (Rigorous Approach to Industrial Software Engineering) method. """ name = 'RSL' url = 'http://en.wikipedia.org/wiki/RAISE' aliases = ['rsl'] filenames = ['*.rsl'] mimetypes = ['text/rsl'] version_added = '2.0'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ (words(( 'Bool', 'Char', 'Int', 'Nat', 'Real', 'Text', 'Unit', 'abs', 'all', 'always', 'any', 'as', 'axiom', 'card', 'case', 'channel', 'chaos', 'class', 'devt_relation', 'dom', 'elems', 'else', 'elif', 'end', 'exists', 'extend', 'false', 'for', 'hd', 'hide', 'if', 'in', 'is', 'inds', 'initialise', 'int', 'inter', 'isin', 'len', 'let', 'local', 'ltl_assertion', 'object', 'of', 'out', 'post', 'pre', 'read', 'real', 'rng', 'scheme', 'skip', 'stop', 'swap', 'then', 'theory', 'test_case', 'tl', 'transition_system', 'true', 'type', 'union', 'until', 'use', 'value', 'variable', 'while', 'with', 'write', '~isin', '-inflist', '-infset', '-list', '-set'), prefix=r'\b', suffix=r'\b'), Keyword), (r'(variable|value)\b', Keyword.Declaration), (r'--.*?\n', Comment), (r'<:.*?:>', Comment), (r'\{!.*?!\}', Comment), (r'/\*.*?\*/', Comment), (r'^([ \t]*)([\w]+)([ \t]*)(:[^:])', bygroups(Whitespace, Name.Function, Whitespace, Name.Function)), (r'(^[ \t]*)([\w]+)([ \t]*)(\([\w\s,]*\))([ \t]*)(is|as)', bygroups(Whitespace, Name.Function, Whitespace, Text, Whitespace, Keyword)), (r'\b[A-Z]\w*\b', Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'".*"', String), (r'\'.\'', String.Char), (r'(><|->|-m->|/\\|<=|<<=|<\.|\|\||\|\^\||-~->|-~m->|\\/|>=|>>|' r'\.>|\+\+|-\\|<->|=>|:-|~=|\*\*|<<|>>=|\+>|!!|\|=\||#)', Operator), (r'[0-9]+\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-f]+', Number.Hex), (r'[0-9]+', Number.Integer), (r'\s+', Whitespace), (r'.', Text), ], }
def analyse_text(text): """ Check for the most common text in the beginning of a RSL file. """ if re.search(r'scheme\s*.*?=\s*class\s*type', text, re.I) is not None: return 1.0
class MscgenLexer(RegexLexer): """ For Mscgen files. """ name = 'Mscgen' url = 'http://www.mcternan.me.uk/mscgen/' aliases = ['mscgen', 'msc'] filenames = ['*.msc'] version_added = '1.6'
_var = r'(\w+|"(?:\\"|[^"])*")'
tokens = { 'root': [ (r'msc\b', Keyword.Type), # Options (r'(hscale|HSCALE|width|WIDTH|wordwraparcs|WORDWRAPARCS' r'|arcgradient|ARCGRADIENT)\b', Name.Property), # Operators (r'(abox|ABOX|rbox|RBOX|box|BOX|note|NOTE)\b', Operator.Word), (r'(\.|-|\|){3}', Keyword), (r'(?:-|=|\.|:){2}' r'|<<=>>|<->|<=>|<<>>|<:>' r'|->|=>>|>>|=>|:>|-x|-X' r'|<-|<<=|<<|<=|<:|x-|X-|=', Operator), # Names (r'\*', Name.Builtin), (_var, Name.Variable), # Other (r'\[', Punctuation, 'attrs'), (r'\{|\}|,|;', Punctuation), include('comments') ], 'attrs': [ (r'\]', Punctuation, '#pop'), (_var + r'(\s*)(=)(\s*)' + _var, bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), (r',', Punctuation), include('comments') ], 'comments': [ (r'(?://|#).*?\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), (r'[ \t\r\n]+', Whitespace) ] }
class VGLLexer(RegexLexer): """ For SampleManager VGL source code. """ name = 'VGL' url = 'http://www.thermoscientific.com/samplemanager' aliases = ['vgl'] filenames = ['*.rpf'] version_added = '1.6'
flags = re.MULTILINE | re.DOTALL | re.IGNORECASE
tokens = { 'root': [ (r'\{[^}]*\}', Comment.Multiline), (r'declare', Keyword.Constant), (r'(if|then|else|endif|while|do|endwhile|and|or|prompt|object' r'|create|on|line|with|global|routine|value|endroutine|constant' r'|global|set|join|library|compile_option|file|exists|create|copy' r'|delete|enable|windows|name|notprotected)(?! *[=<>.,()])', Keyword), (r'(true|false|null|empty|error|locked)', Keyword.Constant), (r'[~^*#!%&\[\]()<>|+=:;,./?-]', Operator), (r'"[^"]*"', String), (r'(\.)([a-z_$][\w$]*)', bygroups(Operator, Name.Attribute)), (r'[0-9][0-9]*(\.[0-9]+(e[+\-]?[0-9]+)?)?', Number), (r'[a-z_$][\w$]*', Name), (r'[\r\n]+', Whitespace), (r'\s+', Whitespace) ] }
class AlloyLexer(RegexLexer): """ For Alloy source code. """
name = 'Alloy' url = 'http://alloy.mit.edu' aliases = ['alloy'] filenames = ['*.als'] mimetypes = ['text/x-alloy'] version_added = '2.0'
flags = re.MULTILINE | re.DOTALL
iden_rex = r'[a-zA-Z_][\w]*"*' string_rex = r'"\b(\\\\|\\[^\\]|[^"\\])*"' text_tuple = (r'[^\S\n]+', Whitespace)
tokens = { 'sig': [ (r'(extends)\b', Keyword, '#pop'), (iden_rex, Name), text_tuple, (r',', Punctuation), (r'\{', Operator, '#pop'), ], 'module': [ text_tuple, (iden_rex, Name, '#pop'), ], 'fun': [ text_tuple, (r'\{', Operator, '#pop'), (iden_rex, Name, '#pop'), ], 'fact': [ include('fun'), (string_rex, String, '#pop'), ], 'root': [ (r'--.*?$', Comment.Single), (r'//.*?$', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), text_tuple, (r'(module|open)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'module'), (r'(sig|enum)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'sig'), (r'(iden|univ|none)\b', Keyword.Constant), (r'(int|Int)\b', Keyword.Type), (r'(var|this|abstract|extends|set|seq|one|lone|let)\b', Keyword), (r'(all|some|no|sum|disj|when|else)\b', Keyword), (r'(run|check|for|but|exactly|expect|as|steps)\b', Keyword), (r'(always|after|eventually|until|release)\b', Keyword), # future time operators (r'(historically|before|once|since|triggered)\b', Keyword), # past time operators (r'(and|or|implies|iff|in)\b', Operator.Word), (r'(fun|pred|assert)(\s+)', bygroups(Keyword, Whitespace), 'fun'), (r'(fact)(\s+)', bygroups(Keyword, Whitespace), 'fact'), (r'!|#|&&|\+\+|<<|>>|>=|<=>|<=|\.\.|\.|->', Operator), (r'[-+/*%=<>&!^|~{}\[\]().\';]', Operator), (iden_rex, Name), (r'[:,]', Punctuation), (r'[0-9]+', Number.Integer), (string_rex, String), (r'\n', Whitespace), ] }
class PanLexer(RegexLexer): """ Lexer for pan source files.
Based on tcsh lexer. """
name = 'Pan' url = 'https://github.com/quattor/pan/' aliases = ['pan'] filenames = ['*.pan'] version_added = '2.0'
tokens = { 'root': [ include('basic'), (r'\(', Keyword, 'paren'), (r'\{', Keyword, 'curly'), include('data'), ], 'basic': [ (words(( 'if', 'for', 'with', 'else', 'type', 'bind', 'while', 'valid', 'final', 'prefix', 'unique', 'object', 'foreach', 'include', 'template', 'function', 'variable', 'structure', 'extensible', 'declaration'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'file_contents', 'format', 'index', 'length', 'match', 'matches', 'replace', 'splice', 'split', 'substr', 'to_lowercase', 'to_uppercase', 'debug', 'error', 'traceback', 'deprecated', 'base64_decode', 'base64_encode', 'digest', 'escape', 'unescape', 'append', 'create', 'first', 'nlist', 'key', 'list', 'merge', 'next', 'prepend', 'is_boolean', 'is_defined', 'is_double', 'is_list', 'is_long', 'is_nlist', 'is_null', 'is_number', 'is_property', 'is_resource', 'is_string', 'to_boolean', 'to_double', 'to_long', 'to_string', 'clone', 'delete', 'exists', 'path_exists', 'if_exists', 'return', 'value'), prefix=r'\b', suffix=r'\b'), Name.Builtin), (r'#.*', Comment), (r'\\[\w\W]', String.Escape), (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Whitespace, Operator)), (r'[\[\]{}()=]+', Operator), (r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String), (r';', Punctuation), ], 'data': [ (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double), (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single), (r'\s+', Whitespace), (r'[^=\s\[\]{}()$"\'`\\;#]+', Text), (r'\d+(?= |\Z)', Number), ], 'curly': [ (r'\}', Keyword, '#pop'), (r':-', Keyword), (r'\w+', Name.Variable), (r'[^}:"\'`$]+', Punctuation), (r':', Punctuation), include('root'), ], 'paren': [ (r'\)', Keyword, '#pop'), include('root'), ], }
class CrmshLexer(RegexLexer): """ Lexer for crmsh configuration files for Pacemaker clusters. """ name = 'Crmsh' url = 'http://crmsh.github.io/' aliases = ['crmsh', 'pcmk'] filenames = ['*.crmsh', '*.pcmk'] mimetypes = [] version_added = '2.1'
elem = words(( 'node', 'primitive', 'group', 'clone', 'ms', 'location', 'colocation', 'order', 'fencing_topology', 'rsc_ticket', 'rsc_template', 'property', 'rsc_defaults', 'op_defaults', 'acl_target', 'acl_group', 'user', 'role', 'tag'), suffix=r'(?![\w#$-])') sub = words(( 'params', 'meta', 'operations', 'op', 'rule', 'attributes', 'utilization'), suffix=r'(?![\w#$-])') acl = words(('read', 'write', 'deny'), suffix=r'(?![\w#$-])') bin_rel = words(('and', 'or'), suffix=r'(?![\w#$-])') un_ops = words(('defined', 'not_defined'), suffix=r'(?![\w#$-])') date_exp = words(('in_range', 'date', 'spec', 'in'), suffix=r'(?![\w#$-])') acl_mod = (r'(?:tag|ref|reference|attribute|type|xpath)') bin_ops = (r'(?:lt|gt|lte|gte|eq|ne)') val_qual = (r'(?:string|version|number)') rsc_role_action = (r'(?:Master|Started|Slave|Stopped|' r'start|promote|demote|stop)')
tokens = { 'root': [ (r'^(#.*)(\n)?', bygroups(Comment, Whitespace)), # attr=value (nvpair) (r'([\w#$-]+)(=)("(?:""|[^"])*"|\S+)', bygroups(Name.Attribute, Punctuation, String)), # need this construct, otherwise numeric node ids # are matched as scores # elem id: (r'(node)(\s+)([\w#$-]+)(:)', bygroups(Keyword, Whitespace, Name, Punctuation)), # scores (r'([+-]?([0-9]+|inf)):', Number), # keywords (elements and other) (elem, Keyword), (sub, Keyword), (acl, Keyword), # binary operators (rf'(?:{val_qual}:)?({bin_ops})(?![\w#$-])', Operator.Word), # other operators (bin_rel, Operator.Word), (un_ops, Operator.Word), (date_exp, Operator.Word), # builtin attributes (e.g. #uname) (r'#[a-z]+(?![\w#$-])', Name.Builtin), # acl_mod:blah (rf'({acl_mod})(:)("(?:""|[^"])*"|\S+)', bygroups(Keyword, Punctuation, Name)), # rsc_id[:(role|action)] # NB: this matches all other identifiers (rf'([\w#$-]+)(?:(:)({rsc_role_action}))?(?![\w#$-])', bygroups(Name, Punctuation, Operator.Word)), # punctuation (r'(\\(?=\n)|[\[\](){}/:@])', Punctuation), (r'\s+|\n', Whitespace), ], }
class FlatlineLexer(RegexLexer): """ Lexer for Flatline expressions. """ name = 'Flatline' url = 'https://github.com/bigmlcom/flatline' aliases = ['flatline'] filenames = [] mimetypes = ['text/x-flatline'] version_added = '2.2'
special_forms = ('let',)
builtins = ( "!=", "*", "+", "-", "<", "<=", "=", ">", ">=", "abs", "acos", "all", "all-but", "all-with-defaults", "all-with-numeric-default", "and", "asin", "atan", "avg", "avg-window", "bin-center", "bin-count", "call", "category-count", "ceil", "cond", "cond-window", "cons", "cos", "cosh", "count", "diff-window", "div", "ensure-value", "ensure-weighted-value", "epoch", "epoch-day", "epoch-fields", "epoch-hour", "epoch-millisecond", "epoch-minute", "epoch-month", "epoch-second", "epoch-weekday", "epoch-year", "exp", "f", "field", "field-prop", "fields", "filter", "first", "floor", "head", "if", "in", "integer", "language", "length", "levenshtein", "linear-regression", "list", "ln", "log", "log10", "map", "matches", "matches?", "max", "maximum", "md5", "mean", "median", "min", "minimum", "missing", "missing-count", "missing?", "missing_count", "mod", "mode", "normalize", "not", "nth", "occurrences", "or", "percentile", "percentile-label", "population", "population-fraction", "pow", "preferred", "preferred?", "quantile-label", "rand", "rand-int", "random-value", "re-quote", "real", "replace", "replace-first", "rest", "round", "row-number", "segment-label", "sha1", "sha256", "sin", "sinh", "sqrt", "square", "standard-deviation", "standard_deviation", "str", "subs", "sum", "sum-squares", "sum-window", "sum_squares", "summary", "summary-no", "summary-str", "tail", "tan", "tanh", "to-degrees", "to-radians", "variance", "vectorize", "weighted-random-value", "window", "winnow", "within-percentiles?", "z-score", )
valid_name = r'(?!#)[\w!$%*+<=>?/.#-]+'
tokens = { 'root': [ # whitespaces - usually not relevant (r'[,]+', Text), (r'\s+', Whitespace),
# numbers (r'-?\d+\.\d+', Number.Float), (r'-?\d+', Number.Integer), (r'0x-?[a-f\d]+', Number.Hex),
# strings, symbols and characters (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r"\\(.|[a-z]+)", String.Char),
# expression template placeholder (r'_', String.Symbol),
# highlight the special forms (words(special_forms, suffix=' '), Keyword),
# highlight the builtins (words(builtins, suffix=' '), Name.Builtin),
# the remaining functions (r'(?<=\()' + valid_name, Name.Function),
# find the remaining variables (valid_name, Name.Variable),
# parentheses (r'(\(|\))', Punctuation), ], }
class SnowballLexer(ExtendedRegexLexer): """ Lexer for Snowball source code. """
name = 'Snowball' url = 'https://snowballstem.org/' aliases = ['snowball'] filenames = ['*.sbl'] version_added = '2.2'
_ws = r'\n\r\t '
def __init__(self, **options): self._reset_stringescapes() ExtendedRegexLexer.__init__(self, **options)
def _reset_stringescapes(self): self._start = "'" self._end = "'"
def _string(do_string_first): def callback(lexer, match, ctx): s = match.start() text = match.group() string = re.compile(rf'([^{re.escape(lexer._start)}]*)(.)').match escape = re.compile(rf'([^{re.escape(lexer._end)}]*)(.)').match pos = 0 do_string = do_string_first while pos < len(text): if do_string: match = string(text, pos) yield s + match.start(1), String.Single, match.group(1) if match.group(2) == "'": yield s + match.start(2), String.Single, match.group(2) ctx.stack.pop() break yield s + match.start(2), String.Escape, match.group(2) pos = match.end() match = escape(text, pos) yield s + match.start(), String.Escape, match.group() if match.group(2) != lexer._end: ctx.stack[-1] = 'escape' break pos = match.end() do_string = True ctx.pos = s + match.end() return callback
def _stringescapes(lexer, match, ctx): lexer._start = match.group(3) lexer._end = match.group(5) return bygroups(Keyword.Reserved, Whitespace, String.Escape, Whitespace, String.Escape)(lexer, match, ctx)
tokens = { 'root': [ (r'len\b', Name.Builtin), (r'lenof\b', Operator.Word), include('root1'), ], 'root1': [ (rf'[{_ws}]+', Whitespace), (r'\d+', Number.Integer), (r"'", String.Single, 'string'), (r'[()]', Punctuation), (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'//.*', Comment.Single), (r'[!*+\-/<=>]=|[-=]>|<[+-]|[$*+\-/<=>?\[\]]', Operator), (words(('as', 'get', 'hex', 'among', 'define', 'decimal', 'backwardmode'), suffix=r'\b'), Keyword.Reserved), (words(('strings', 'booleans', 'integers', 'routines', 'externals', 'groupings'), suffix=r'\b'), Keyword.Reserved, 'declaration'), (words(('do', 'or', 'and', 'for', 'hop', 'non', 'not', 'set', 'try', 'fail', 'goto', 'loop', 'next', 'test', 'true', 'false', 'unset', 'atmark', 'attach', 'delete', 'gopast', 'insert', 'repeat', 'sizeof', 'tomark', 'atleast', 'atlimit', 'reverse', 'setmark', 'tolimit', 'setlimit', 'backwards', 'substring'), suffix=r'\b'), Operator.Word), (words(('size', 'limit', 'cursor', 'maxint', 'minint'), suffix=r'\b'), Name.Builtin), (rf'(stringdef\b)([{_ws}]*)([^{_ws}]+)', bygroups(Keyword.Reserved, Whitespace, String.Escape)), (rf'(stringescapes\b)([{_ws}]*)(.)([{_ws}]*)(.)', _stringescapes), (r'[A-Za-z]\w*', Name), ], 'declaration': [ (r'\)', Punctuation, '#pop'), (words(('len', 'lenof'), suffix=r'\b'), Name, ('root1', 'declaration')), include('root1'), ], 'string': [ (r"[^']*'", _string(True)), ], 'escape': [ (r"[^']*'", _string(False)), ], }
def get_tokens_unprocessed(self, text=None, context=None): self._reset_stringescapes() return ExtendedRegexLexer.get_tokens_unprocessed(self, text, context)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279""" pygments.lexers.dylan ~~~~~~~~~~~~~~~~~~~~~
Lexers for the Dylan language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, bygroups, do_insertions, \ default, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Literal, Whitespace
__all__ = ['DylanLexer', 'DylanConsoleLexer', 'DylanLidLexer']
class DylanLexer(RegexLexer): """ For the Dylan language. """
name = 'Dylan' url = 'http://www.opendylan.org/' aliases = ['dylan'] filenames = ['*.dylan', '*.dyl', '*.intr'] mimetypes = ['text/x-dylan'] version_added = '0.7'
flags = re.IGNORECASE
builtins = { 'subclass', 'abstract', 'block', 'concrete', 'constant', 'class', 'compiler-open', 'compiler-sideways', 'domain', 'dynamic', 'each-subclass', 'exception', 'exclude', 'function', 'generic', 'handler', 'inherited', 'inline', 'inline-only', 'instance', 'interface', 'import', 'keyword', 'library', 'macro', 'method', 'module', 'open', 'primary', 'required', 'sealed', 'sideways', 'singleton', 'slot', 'thread', 'variable', 'virtual'}
keywords = { 'above', 'afterwards', 'begin', 'below', 'by', 'case', 'cleanup', 'create', 'define', 'else', 'elseif', 'end', 'export', 'finally', 'for', 'from', 'if', 'in', 'let', 'local', 'otherwise', 'rename', 'select', 'signal', 'then', 'to', 'unless', 'until', 'use', 'when', 'while'}
operators = { '~', '+', '-', '*', '|', '^', '=', '==', '~=', '~==', '<', '<=', '>', '>=', '&', '|'}
functions = { 'abort', 'abs', 'add', 'add!', 'add-method', 'add-new', 'add-new!', 'all-superclasses', 'always', 'any?', 'applicable-method?', 'apply', 'aref', 'aref-setter', 'as', 'as-lowercase', 'as-lowercase!', 'as-uppercase', 'as-uppercase!', 'ash', 'backward-iteration-protocol', 'break', 'ceiling', 'ceiling/', 'cerror', 'check-type', 'choose', 'choose-by', 'complement', 'compose', 'concatenate', 'concatenate-as', 'condition-format-arguments', 'condition-format-string', 'conjoin', 'copy-sequence', 'curry', 'default-handler', 'dimension', 'dimensions', 'direct-subclasses', 'direct-superclasses', 'disjoin', 'do', 'do-handlers', 'element', 'element-setter', 'empty?', 'error', 'even?', 'every?', 'false-or', 'fill!', 'find-key', 'find-method', 'first', 'first-setter', 'floor', 'floor/', 'forward-iteration-protocol', 'function-arguments', 'function-return-values', 'function-specializers', 'gcd', 'generic-function-mandatory-keywords', 'generic-function-methods', 'head', 'head-setter', 'identity', 'initialize', 'instance?', 'integral?', 'intersection', 'key-sequence', 'key-test', 'last', 'last-setter', 'lcm', 'limited', 'list', 'logand', 'logbit?', 'logior', 'lognot', 'logxor', 'make', 'map', 'map-as', 'map-into', 'max', 'member?', 'merge-hash-codes', 'min', 'modulo', 'negative', 'negative?', 'next-method', 'object-class', 'object-hash', 'odd?', 'one-of', 'pair', 'pop', 'pop-last', 'positive?', 'push', 'push-last', 'range', 'rank', 'rcurry', 'reduce', 'reduce1', 'remainder', 'remove', 'remove!', 'remove-duplicates', 'remove-duplicates!', 'remove-key!', 'remove-method', 'replace-elements!', 'replace-subsequence!', 'restart-query', 'return-allowed?', 'return-description', 'return-query', 'reverse', 'reverse!', 'round', 'round/', 'row-major-index', 'second', 'second-setter', 'shallow-copy', 'signal', 'singleton', 'size', 'size-setter', 'slot-initialized?', 'sort', 'sort!', 'sorted-applicable-methods', 'subsequence-position', 'subtype?', 'table-protocol', 'tail', 'tail-setter', 'third', 'third-setter', 'truncate', 'truncate/', 'type-error-expected-type', 'type-error-value', 'type-for-copy', 'type-union', 'union', 'values', 'vector', 'zero?'}
valid_name = '\\\\?[\\w!&*<>|^$%@\\-+~?/=]+'
def get_tokens_unprocessed(self, text): for index, token, value in RegexLexer.get_tokens_unprocessed(self, text): if token is Name: lowercase_value = value.lower() if lowercase_value in self.builtins: yield index, Name.Builtin, value continue if lowercase_value in self.keywords: yield index, Keyword, value continue if lowercase_value in self.functions: yield index, Name.Builtin, value continue if lowercase_value in self.operators: yield index, Operator, value continue yield index, token, value
tokens = { 'root': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'//.*?\n', Comment.Single),
# lid header (r'([a-z0-9-]+)(:)([ \t]*)(.*(?:\n[ \t].+)*)', bygroups(Name.Attribute, Operator, Whitespace, String)),
default('code') # no header match, switch to code ], 'code': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# multi-line comment (r'/\*', Comment.Multiline, 'comment'),
# strings and characters (r'"', String, 'string'), (r"'(\\.|\\[0-7]{1,3}|\\x[a-f0-9]{1,2}|[^\\\'\n])'", String.Char),
# binary integer (r'#b[01]+', Number.Bin),
# octal integer (r'#o[0-7]+', Number.Oct),
# floating point (r'[-+]?(\d*\.\d+(e[-+]?\d+)?|\d+(\.\d*)?e[-+]?\d+)', Number.Float),
# decimal integer (r'[-+]?\d+', Number.Integer),
# hex integer (r'#x[0-9a-f]+', Number.Hex),
# Macro parameters (r'(\?' + valid_name + ')(:)' r'(token|name|variable|expression|body|case-body|\*)', bygroups(Name.Tag, Operator, Name.Builtin)), (r'(\?)(:)(token|name|variable|expression|body|case-body|\*)', bygroups(Name.Tag, Operator, Name.Builtin)), (r'\?' + valid_name, Name.Tag),
# Punctuation (r'(=>|::|#\(|#\[|##|\?\?|\?=|\?|[(){}\[\],.;])', Punctuation),
# Most operators are picked up as names and then re-flagged. # This one isn't valid in a name though, so we pick it up now. (r':=', Operator),
# Pick up #t / #f before we match other stuff with #. (r'#[tf]', Literal),
# #"foo" style keywords (r'#"', String.Symbol, 'keyword'),
# #rest, #key, #all-keys, etc. (r'#[a-z0-9-]+', Keyword),
# required-init-keyword: style keywords. (valid_name + ':', Keyword),
# class names ('<' + valid_name + '>', Name.Class),
# define variable forms. (r'\*' + valid_name + r'\*', Name.Variable.Global),
# define constant forms. (r'\$' + valid_name, Name.Constant),
# everything else. We re-flag some of these in the method above. (valid_name, Name), ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'keyword': [ (r'"', String.Symbol, '#pop'), (r'[^\\"]+', String.Symbol), # all other characters ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-f0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ] }
class DylanLidLexer(RegexLexer): """ For Dylan LID (Library Interchange Definition) files. """
name = 'DylanLID' aliases = ['dylan-lid', 'lid'] filenames = ['*.lid', '*.hdp'] mimetypes = ['text/x-dylan-lid'] url = 'http://www.opendylan.org/' version_added = '1.6' flags = re.IGNORECASE
tokens = { 'root': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# lid header (r'(.*?)(:)([ \t]*)(.*(?:\n[ \t].+)*)', bygroups(Name.Attribute, Operator, Whitespace, String)), ] }
class DylanConsoleLexer(Lexer): """ For Dylan interactive console output.
This is based on a copy of the ``RubyConsoleLexer``. """ name = 'Dylan session' aliases = ['dylan-console', 'dylan-repl'] filenames = ['*.dylan-console'] mimetypes = ['text/x-dylan-console'] url = 'http://www.opendylan.org/' version_added = '1.6' _example = 'dylan-console/console.dylan-console'
_prompt_re = re.compile(r'\?| ')
def get_tokens_unprocessed(self, text): dylexer = DylanLexer(**self.options)
curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() m = self._prompt_re.match(line) if m is not None: end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: yield from do_insertions(insertions, dylexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, dylexer.get_tokens_unprocessed(curcode))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144""" pygments.lexers.ecl ~~~~~~~~~~~~~~~~~~~
Lexers for the ECL language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ECLLexer']
class ECLLexer(RegexLexer): """ Lexer for the declarative big-data ECL language. """
name = 'ECL' url = 'https://hpccsystems.com/training/documentation/ecl-language-reference/html' aliases = ['ecl'] filenames = ['*.ecl'] mimetypes = ['application/x-ecl'] version_added = '1.5'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ include('whitespace'), include('statements'), ], 'whitespace': [ (r'\s+', Whitespace), (r'\/\/.*', Comment.Single), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline), ], 'statements': [ include('types'), include('keywords'), include('functions'), include('hash'), (r'"', String, 'string'), (r'\'', String, 'string'), (r'(\d+\.\d*|\.\d+|\d+)e[+-]?\d+[lu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+f)f?', Number.Float), (r'0x[0-9a-f]+[lu]*', Number.Hex), (r'0[0-7]+[lu]*', Number.Oct), (r'\d+[lu]*', Number.Integer), (r'[~!%^&*+=|?:<>/-]+', Operator), (r'[{}()\[\],.;]', Punctuation), (r'[a-z_]\w*', Name), ], 'hash': [ (r'^#.*$', Comment.Preproc), ], 'types': [ (r'(RECORD|END)\D', Keyword.Declaration), (r'((?:ASCII|BIG_ENDIAN|BOOLEAN|DATA|DECIMAL|EBCDIC|INTEGER|PATTERN|' r'QSTRING|REAL|RECORD|RULE|SET OF|STRING|TOKEN|UDECIMAL|UNICODE|' r'UNSIGNED|VARSTRING|VARUNICODE)\d*)(\s+)', bygroups(Keyword.Type, Whitespace)), ], 'keywords': [ (words(( 'APPLY', 'ASSERT', 'BUILD', 'BUILDINDEX', 'EVALUATE', 'FAIL', 'KEYDIFF', 'KEYPATCH', 'LOADXML', 'NOTHOR', 'NOTIFY', 'OUTPUT', 'PARALLEL', 'SEQUENTIAL', 'SOAPCALL', 'CHECKPOINT', 'DEPRECATED', 'FAILCODE', 'FAILMESSAGE', 'FAILURE', 'GLOBAL', 'INDEPENDENT', 'ONWARNING', 'PERSIST', 'PRIORITY', 'RECOVERY', 'STORED', 'SUCCESS', 'WAIT', 'WHEN'), suffix=r'\b'), Keyword.Reserved), # These are classed differently, check later (words(( 'ALL', 'AND', 'ANY', 'AS', 'ATMOST', 'BEFORE', 'BEGINC++', 'BEST', 'BETWEEN', 'CASE', 'CONST', 'COUNTER', 'CSV', 'DESCEND', 'ENCRYPT', 'ENDC++', 'ENDMACRO', 'EXCEPT', 'EXCLUSIVE', 'EXPIRE', 'EXPORT', 'EXTEND', 'FALSE', 'FEW', 'FIRST', 'FLAT', 'FULL', 'FUNCTION', 'GROUP', 'HEADER', 'HEADING', 'HOLE', 'IFBLOCK', 'IMPORT', 'IN', 'JOINED', 'KEEP', 'KEYED', 'LAST', 'LEFT', 'LIMIT', 'LOAD', 'LOCAL', 'LOCALE', 'LOOKUP', 'MACRO', 'MANY', 'MAXCOUNT', 'MAXLENGTH', 'MIN SKEW', 'MODULE', 'INTERFACE', 'NAMED', 'NOCASE', 'NOROOT', 'NOSCAN', 'NOSORT', 'NOT', 'OF', 'ONLY', 'OPT', 'OR', 'OUTER', 'OVERWRITE', 'PACKED', 'PARTITION', 'PENALTY', 'PHYSICALLENGTH', 'PIPE', 'QUOTE', 'RELATIONSHIP', 'REPEAT', 'RETURN', 'RIGHT', 'SCAN', 'SELF', 'SEPARATOR', 'SERVICE', 'SHARED', 'SKEW', 'SKIP', 'SQL', 'STORE', 'TERMINATOR', 'THOR', 'THRESHOLD', 'TOKEN', 'TRANSFORM', 'TRIM', 'TRUE', 'TYPE', 'UNICODEORDER', 'UNSORTED', 'VALIDATE', 'VIRTUAL', 'WHOLE', 'WILD', 'WITHIN', 'XML', 'XPATH', '__COMPRESSED__'), suffix=r'\b'), Keyword.Reserved), ], 'functions': [ (words(( 'ABS', 'ACOS', 'ALLNODES', 'ASCII', 'ASIN', 'ASSTRING', 'ATAN', 'ATAN2', 'AVE', 'CASE', 'CHOOSE', 'CHOOSEN', 'CHOOSESETS', 'CLUSTERSIZE', 'COMBINE', 'CORRELATION', 'COS', 'COSH', 'COUNT', 'COVARIANCE', 'CRON', 'DATASET', 'DEDUP', 'DEFINE', 'DENORMALIZE', 'DISTRIBUTE', 'DISTRIBUTED', 'DISTRIBUTION', 'EBCDIC', 'ENTH', 'ERROR', 'EVALUATE', 'EVENT', 'EVENTEXTRA', 'EVENTNAME', 'EXISTS', 'EXP', 'FAILCODE', 'FAILMESSAGE', 'FETCH', 'FROMUNICODE', 'GETISVALID', 'GLOBAL', 'GRAPH', 'GROUP', 'HASH', 'HASH32', 'HASH64', 'HASHCRC', 'HASHMD5', 'HAVING', 'IF', 'INDEX', 'INTFORMAT', 'ISVALID', 'ITERATE', 'JOIN', 'KEYUNICODE', 'LENGTH', 'LIBRARY', 'LIMIT', 'LN', 'LOCAL', 'LOG', 'LOOP', 'MAP', 'MATCHED', 'MATCHLENGTH', 'MATCHPOSITION', 'MATCHTEXT', 'MATCHUNICODE', 'MAX', 'MERGE', 'MERGEJOIN', 'MIN', 'NOLOCAL', 'NONEMPTY', 'NORMALIZE', 'PARSE', 'PIPE', 'POWER', 'PRELOAD', 'PROCESS', 'PROJECT', 'PULL', 'RANDOM', 'RANGE', 'RANK', 'RANKED', 'REALFORMAT', 'RECORDOF', 'REGEXFIND', 'REGEXREPLACE', 'REGROUP', 'REJECTED', 'ROLLUP', 'ROUND', 'ROUNDUP', 'ROW', 'ROWDIFF', 'SAMPLE', 'SET', 'SIN', 'SINH', 'SIZEOF', 'SOAPCALL', 'SORT', 'SORTED', 'SQRT', 'STEPPED', 'STORED', 'SUM', 'TABLE', 'TAN', 'TANH', 'THISNODE', 'TOPN', 'TOUNICODE', 'TRANSFER', 'TRIM', 'TRUNCATE', 'TYPEOF', 'UNGROUP', 'UNICODEORDER', 'VARIANCE', 'WHICH', 'WORKUNIT', 'XMLDECODE', 'XMLENCODE', 'XMLTEXT', 'XMLUNICODE'), suffix=r'\b'), Name.Function), ], 'string': [ (r'"', String, '#pop'), (r'\'', String, '#pop'), (r'[^"\']+', String), ], }
def analyse_text(text): """This is very difficult to guess relative to other business languages. -> in conjunction with BEGIN/END seems relatively rare though.""" result = 0
if '->' in text: result += 0.01 if 'BEGIN' in text: result += 0.01 if 'END' in text: result += 0.01
return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768""" pygments.lexers.eiffel ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Eiffel language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['EiffelLexer']
class EiffelLexer(RegexLexer): """ For Eiffel source code. """ name = 'Eiffel' url = 'https://www.eiffel.com' aliases = ['eiffel'] filenames = ['*.e'] mimetypes = ['text/x-eiffel'] version_added = '2.0'
tokens = { 'root': [ (r'[^\S\n]+', Whitespace), (r'--.*?$', Comment.Single), (r'[^\S\n]+', Whitespace), # Please note that keyword and operator are case insensitive. (r'(?i)(true|false|void|current|result|precursor)\b', Keyword.Constant), (r'(?i)(not|xor|implies|or)\b', Operator.Word), (r'(?i)(and)(?:(\s+)(then))?\b', bygroups(Operator.Word, Whitespace, Operator.Word)), (r'(?i)(or)(?:(\s+)(else))?\b', bygroups(Operator.Word, Whitespace, Operator.Word)), (words(( 'across', 'agent', 'alias', 'all', 'as', 'assign', 'attached', 'attribute', 'check', 'class', 'convert', 'create', 'debug', 'deferred', 'detachable', 'do', 'else', 'elseif', 'end', 'ensure', 'expanded', 'export', 'external', 'feature', 'from', 'frozen', 'if', 'inherit', 'inspect', 'invariant', 'like', 'local', 'loop', 'none', 'note', 'obsolete', 'old', 'once', 'only', 'redefine', 'rename', 'require', 'rescue', 'retry', 'select', 'separate', 'then', 'undefine', 'until', 'variant', 'when'), prefix=r'(?i)\b', suffix=r'\b'), Keyword.Reserved), (r'"\[([^\]%]|%(.|\n)|\][^"])*?\]"', String), (r'"([^"%\n]|%.)*?"', String), include('numbers'), (r"'([^'%]|%'|%%)'", String.Char), (r"(//|\\\\|>=|<=|:=|/=|~|/~|[\\?!#%&@|+/\-=>*$<^\[\]])", Operator), (r"([{}():;,.])", Punctuation), (r'([a-z]\w*)|([A-Z][A-Z0-9_]*[a-z]\w*)', Name), (r'([A-Z][A-Z0-9_]*)', Name.Class), (r'\n+', Whitespace), ], 'numbers': [ (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'0[bB][01]+', Number.Bin), (r'0[cC][0-7]+', Number.Oct), (r'([0-9]+\.[0-9]*)|([0-9]*\.[0-9]+)', Number.Float), (r'[0-9]+', Number.Integer), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123""" pygments.lexers.elm ~~~~~~~~~~~~~~~~~~~
Lexer for the Elm programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, include, bygroupsfrom pygments.token import Comment, Keyword, Name, Number, Punctuation, \ String, Whitespace
__all__ = ['ElmLexer']
class ElmLexer(RegexLexer): """ For Elm source code. """
name = 'Elm' url = 'https://elm-lang.org/' aliases = ['elm'] filenames = ['*.elm'] mimetypes = ['text/x-elm'] version_added = '2.1'
validName = r'[a-z_][a-zA-Z0-9_\']*'
specialName = r'^main '
builtinOps = ( '~', '||', '|>', '|', '`', '^', '\\', '\'', '>>', '>=', '>', '==', '=', '<~', '<|', '<=', '<<', '<-', '<', '::', ':', '/=', '//', '/', '..', '.', '->', '-', '++', '+', '*', '&&', '%', )
reservedWords = words(( 'alias', 'as', 'case', 'else', 'if', 'import', 'in', 'let', 'module', 'of', 'port', 'then', 'type', 'where', ), suffix=r'\b')
tokens = { 'root': [
# Comments (r'\{-', Comment.Multiline, 'comment'), (r'--.*', Comment.Single),
# Whitespace (r'\s+', Whitespace),
# Strings (r'"', String, 'doublequote'),
# Modules (r'^(\s*)(module)(\s*)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'imports'),
# Imports (r'^(\s*)(import)(\s*)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'imports'),
# Shaders (r'\[glsl\|.*', Name.Entity, 'shader'),
# Keywords (reservedWords, Keyword.Reserved),
# Types (r'[A-Z][a-zA-Z0-9_]*', Keyword.Type),
# Main (specialName, Keyword.Reserved),
# Prefix Operators (words((builtinOps), prefix=r'\(', suffix=r'\)'), Name.Function),
# Infix Operators (words(builtinOps), Name.Function),
# Numbers include('numbers'),
# Variable Names (validName, Name.Variable),
# Parens (r'[,()\[\]{}]', Punctuation),
],
'comment': [ (r'-(?!\})', Comment.Multiline), (r'\{-', Comment.Multiline, 'comment'), (r'[^-}]', Comment.Multiline), (r'-\}', Comment.Multiline, '#pop'), ],
'doublequote': [ (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\[nrfvb\\"]', String.Escape), (r'[^"]', String), (r'"', String, '#pop'), ],
'imports': [ (r'\w+(\.\w+)*', Name.Class, '#pop'), ],
'numbers': [ (r'_?\d+\.(?=\d+)', Number.Float), (r'_?\d+', Number.Integer), ],
'shader': [ (r'\|(?!\])', Name.Entity), (r'\|\]', Name.Entity, '#pop'), (r'(.*)(\n)', bygroups(Name.Entity, Whitespace)), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201""" pygments.lexers.elpi ~~~~~~~~~~~~~~~~~~~~
Lexer for the `Elpi <http://github.com/LPCIC/elpi>`_ programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, usingfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['ElpiLexer']
from pygments.lexers.theorem import RocqLexer
class ElpiLexer(RegexLexer): """ Lexer for the Elpi programming language. """
name = 'Elpi' url = 'http://github.com/LPCIC/elpi' aliases = ['elpi'] filenames = ['*.elpi'] mimetypes = ['text/x-elpi'] version_added = '2.11'
lcase_re = r"[a-z]" ucase_re = r"[A-Z]" digit_re = r"[0-9]" schar2_re = r"([+*^?/<>`'@#~=&!])" schar_re = rf"({schar2_re}|-|\$|_)" idchar_re = rf"({lcase_re}|{ucase_re}|{digit_re}|{schar_re})" idcharstarns_re = rf"({idchar_re}*(\.({lcase_re}|{ucase_re}){idchar_re}*)*)" symbchar_re = rf"({lcase_re}|{ucase_re}|{digit_re}|{schar_re}|:)" constant_re = rf"({ucase_re}{idchar_re}*|{lcase_re}{idcharstarns_re}|{schar2_re}{symbchar_re}*|_{idchar_re}+)" symbol_re = r"(,|<=>|->|:-|;|\?-|->|&|=>|\bas\b|\buvar\b|<|=<|=|==|>=|>|\bi<|\bi=<|\bi>=|\bi>|\bis\b|\br<|\br=<|\br>=|\br>|\bs<|\bs=<|\bs>=|\bs>|@|::|\[\]|`->|`:|`:=|\^|-|\+|\bi-|\bi\+|r-|r\+|/|\*|\bdiv\b|\bi\*|\bmod\b|\br\*|~|\bi~|\br~)" escape_re = rf"\(({constant_re}|{symbol_re})\)" const_sym_re = rf"({constant_re}|{symbol_re}|{escape_re})"
tokens = { 'root': [ include('elpi') ],
'elpi': [ include('_elpi-comment'),
(r"(:before|:after|:if|:name)(\s*)(\")", bygroups(Keyword.Mode, Text.Whitespace, String.Double), 'elpi-string'), (r"(:index)(\s*)(\()", bygroups(Keyword.Mode, Text.Whitespace, Punctuation), 'elpi-indexing-expr'), (rf"\b(external pred|pred)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-pred-item'), (rf"\b(func)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-func-item'), (rf"\b(external type|type)(\s+)(({const_sym_re}(,\s*)?)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (rf"\b(kind)(\s+)(({const_sym_re}|,)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (rf"\b(typeabbrev)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (r"\b(typeabbrev)(\s+)(\([^)]+\))", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (r"\b(accumulate)(\s+)(\")", bygroups(Keyword.Declaration, Text.Whitespace, String.Double), 'elpi-string'), (rf"\b(accumulate|namespace|local)(\s+)({constant_re})", bygroups(Keyword.Declaration, Text.Whitespace, Text)), (rf"\b(shorten)(\s+)({constant_re}\.)", bygroups(Keyword.Declaration, Text.Whitespace, Text)), (r"\b(pi|sigma)(\s+)([a-zA-Z][A-Za-z0-9_ ]*)(\\)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Variable, Text)), (rf"\b(constraint)(\s+)(({const_sym_re}(\s+)?)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-chr-rule-start'),
(rf"(?=[A-Z_]){constant_re}", Name.Variable), (rf"(?=[a-z_])({constant_re}|_)\\", Name.Variable), (r"_", Name.Variable), (rf"({symbol_re}|!|=>|;)", Keyword.Declaration), (constant_re, Text), (r"\[|\]|\||=>", Keyword.Declaration), (r'"', String.Double, 'elpi-string'), (r'`', String.Double, 'elpi-btick'), (r'\'', String.Double, 'elpi-tick'), (r'\{\{', Punctuation, 'elpi-quote'), (r'\{[^\{]', Text, 'elpi-spill'), (r"\(", Punctuation, 'elpi-in-parens'), (r'\d[\d_]*', Number.Integer), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float), (r"[\+\*\-/\^\.]", Operator), ], '_elpi-comment': [ (r'%[^\n]*\n', Comment), (r'/(?:\\\n)?[*](?:[^*]|[*](?!(?:\\\n)?/))*[*](?:\\\n)?/', Comment), (r"\s+", Text.Whitespace), ], 'elpi-indexing-expr':[ (r'[0-9 _]+', Number.Integer), (r'\)', Punctuation, '#pop'), ], 'elpi-type': [ (r"(ctype\s+)(\")", bygroups(Keyword.Type, String.Double), 'elpi-string'), (r'->', Keyword.Type), (r'prop', Keyword.Mode), (constant_re, Keyword.Type), (r"\(|\)", Keyword.Type), (r"\.", Text, '#pop'), include('_elpi-comment'), ], 'elpi-chr-rule-start': [ (r"\{", Punctuation, 'elpi-chr-rule'), include('_elpi-comment'), ], 'elpi-chr-rule': [ (r"\brule\b", Keyword.Declaration), (r"\\", Keyword.Declaration), (r"\}", Punctuation, '#pop:2'), include('elpi'), ], 'elpi-pred-item': [ (r"[io]:", Keyword.Mode), (r"\.", Text, '#pop'), (r",", Keyword.Mode), include('_elpi-inner-pred-fun'), (r"\)", Keyword.Mode, '#pop'), (r"\(", Keyword.Type, '_elpi-type-item'), include('_elpi-comment'), include('_elpi-type-item'), ], 'elpi-func-item': [ (constant_re, Keyword.Type), (r"\.", Text, '#pop'), (r",", Keyword.Mode), (r'->', Keyword.Mode), include('_elpi-inner-pred-fun'), (r"\)", Keyword.Mode, '#pop'), (r"\(", Keyword.Type, '_elpi-type-item'), include('_elpi-comment'), include('_elpi-type-item'), ], '_elpi-inner-pred-fun': [ (r"(\()(\s*)(pred)", bygroups(Keyword.Mode,Text.Whitespace,Keyword.Declaration), 'elpi-pred-item'), (r"(\()(\s*)(func)", bygroups(Keyword.Mode,Text.Whitespace,Keyword.Declaration), 'elpi-func-item'), ], '_elpi-type-item': [ (r'->', Keyword.Type), (constant_re, Keyword.Type), include('_elpi-inner-pred-fun'), (r"\(", Keyword.Type, '#push'), (r"\)", Keyword.Type, '#pop'), include('_elpi-comment'), ],
''
'elpi-btick': [ (r'[^` ]+', String.Double), (r'`', String.Double, '#pop'), ], 'elpi-tick': [ (r'[^\' ]+', String.Double), (r'\'', String.Double, '#pop'), ], 'elpi-string': [ (r'[^\"]+', String.Double), (r'"', String.Double, '#pop'), ], 'elpi-quote': [ (r'\}\}', Punctuation, '#pop'), (r"\s+", Text.Whitespace), (r"(lp:)(\{\{)", bygroups(Number, Punctuation), 'elpi-quote-exit'), (rf"(lp:)((?=[A-Z_]){constant_re})", bygroups(Number, Name.Variable)), (r"((?!lp:|\}\}).)+", using(RocqLexer)), ], 'elpi-quote-exit': [ include('elpi'), (r'\}\}', Punctuation, '#pop'), ], 'elpi-spill': [ (r'\{[^\{]', Text, '#push'), (r'\}[^\}]', Text, '#pop'), include('elpi'), ], 'elpi-in-parens': [ (r"\(", Punctuation, '#push'), include('elpi'), (r"\)", Punctuation, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132""" pygments.lexers.email ~~~~~~~~~~~~~~~~~~~~~
Lexer for the raw E-mail.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, DelegatingLexer, bygroupsfrom pygments.lexers.mime import MIMELexerfrom pygments.token import Text, Keyword, Name, String, Number, Commentfrom pygments.util import get_bool_opt
__all__ = ["EmailLexer"]
class EmailHeaderLexer(RegexLexer): """ Sub-lexer for raw E-mail. This lexer only process header part of e-mail.
.. versionadded:: 2.5 """
def __init__(self, **options): super().__init__(**options) self.highlight_x = get_bool_opt(options, "highlight-X-header", False)
def get_x_header_tokens(self, match): if self.highlight_x: # field yield match.start(1), Name.Tag, match.group(1)
# content default_actions = self.get_tokens_unprocessed( match.group(2), stack=("root", "header")) yield from default_actions else: # lowlight yield match.start(1), Comment.Special, match.group(1) yield match.start(2), Comment.Multiline, match.group(2)
tokens = { "root": [ (r"^(?:[A-WYZ]|X400)[\w\-]*:", Name.Tag, "header"), (r"^(X-(?:\w[\w\-]*:))([\s\S]*?\n)(?![ \t])", get_x_header_tokens), ], "header": [ # folding (r"\n[ \t]", Text.Whitespace), (r"\n(?![ \t])", Text.Whitespace, "#pop"),
# keywords (r"\bE?SMTPS?\b", Keyword), (r"\b(?:HE|EH)LO\b", Keyword),
# mailbox (r"[\w\.\-\+=]+@[\w\.\-]+", Name.Label), (r"<[\w\.\-\+=]+@[\w\.\-]+>", Name.Label),
# domain (r"\b(\w[\w\.-]*\.[\w\.-]*\w[a-zA-Z]+)\b", Name.Function),
# IPv4 (r"(?<=\b)(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(?:25[0" r"-5]|2[0-4][0-9]|1?[0-9][0-9]?)(?=\b)", Number.Integer),
# IPv6 (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,7}:(?!\b)", Number.Hex), (r"(?<=\b):((:[0-9a-fA-F]{1,4}){1,7}|:)(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}(?=\b)", Number.Hex), (r"(?<=\b)[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})(?=\b)", Number.Hex), (r"(?<=\b)fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}(?=\b)", Number.Hex), (r"(?<=\b)::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}" r"[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}" r"[0-9])(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9])" r"{0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])(?=\b)", Number.Hex),
# Date time (r"(?:(Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s+)?(0[1-9]|[1-2]?[0-9]|3[" r"01])\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(" r"19[0-9]{2}|[2-9][0-9]{3})\s+(2[0-3]|[0-1][0-9]):([0-5][0-9])" r"(?::(60|[0-5][0-9]))?(?:\.\d{1,5})?\s+([-\+][0-9]{2}[0-5][0-" r"9]|\(?(?:UTC?|GMT|(?:E|C|M|P)(?:ST|ET|DT)|[A-IK-Z])\)?)", Name.Decorator),
# RFC-2047 encoded string (r"(=\?)([\w-]+)(\?)([BbQq])(\?)([\[\w!\"#$%&\'()*+,-./:;<=>@[\\" r"\]^_`{|}~]+)(\?=)", bygroups(String.Affix, Name.Constant, String.Affix, Keyword.Constant, String.Affix, Number.Hex, String.Affix)),
# others (r'[\s]+', Text.Whitespace), (r'[\S]', Text), ], }
class EmailLexer(DelegatingLexer): """ Lexer for raw E-mail.
Additional options accepted:
`highlight-X-header` Highlight the fields of ``X-`` user-defined email header. (default: ``False``). """
name = "E-mail" aliases = ["email", "eml"] filenames = ["*.eml"] mimetypes = ["message/rfc822"] url = "https://en.wikipedia.org/wiki/Email#Message_format" version_added = '2.5'
def __init__(self, **options): super().__init__(EmailHeaderLexer, MIMELexer, Comment, **options)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526""" pygments.lexers.erlang ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Erlang.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions, \ include, default, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace
__all__ = ['ErlangLexer', 'ErlangShellLexer', 'ElixirConsoleLexer', 'ElixirLexer']
class ErlangLexer(RegexLexer): """ For the Erlang functional programming language. """
name = 'Erlang' url = 'https://www.erlang.org/' aliases = ['erlang'] filenames = ['*.erl', '*.hrl', '*.es', '*.escript'] mimetypes = ['text/x-erlang'] version_added = '0.9'
keywords = ( 'after', 'begin', 'case', 'catch', 'cond', 'end', 'fun', 'if', 'let', 'of', 'query', 'receive', 'try', 'when', )
builtins = ( # See erlang(3) man page 'abs', 'append_element', 'apply', 'atom_to_list', 'binary_to_list', 'bitstring_to_list', 'binary_to_term', 'bit_size', 'bump_reductions', 'byte_size', 'cancel_timer', 'check_process_code', 'delete_module', 'demonitor', 'disconnect_node', 'display', 'element', 'erase', 'exit', 'float', 'float_to_list', 'fun_info', 'fun_to_list', 'function_exported', 'garbage_collect', 'get', 'get_keys', 'group_leader', 'hash', 'hd', 'integer_to_list', 'iolist_to_binary', 'iolist_size', 'is_atom', 'is_binary', 'is_bitstring', 'is_boolean', 'is_builtin', 'is_float', 'is_function', 'is_integer', 'is_list', 'is_number', 'is_pid', 'is_port', 'is_process_alive', 'is_record', 'is_reference', 'is_tuple', 'length', 'link', 'list_to_atom', 'list_to_binary', 'list_to_bitstring', 'list_to_existing_atom', 'list_to_float', 'list_to_integer', 'list_to_pid', 'list_to_tuple', 'load_module', 'localtime_to_universaltime', 'make_tuple', 'md5', 'md5_final', 'md5_update', 'memory', 'module_loaded', 'monitor', 'monitor_node', 'node', 'nodes', 'open_port', 'phash', 'phash2', 'pid_to_list', 'port_close', 'port_command', 'port_connect', 'port_control', 'port_call', 'port_info', 'port_to_list', 'process_display', 'process_flag', 'process_info', 'purge_module', 'put', 'read_timer', 'ref_to_list', 'register', 'resume_process', 'round', 'send', 'send_after', 'send_nosuspend', 'set_cookie', 'setelement', 'size', 'spawn', 'spawn_link', 'spawn_monitor', 'spawn_opt', 'split_binary', 'start_timer', 'statistics', 'suspend_process', 'system_flag', 'system_info', 'system_monitor', 'system_profile', 'term_to_binary', 'tl', 'trace', 'trace_delivered', 'trace_info', 'trace_pattern', 'trunc', 'tuple_size', 'tuple_to_list', 'universaltime_to_localtime', 'unlink', 'unregister', 'whereis' )
operators = r'(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)' word_operators = ( 'and', 'andalso', 'band', 'bnot', 'bor', 'bsl', 'bsr', 'bxor', 'div', 'not', 'or', 'orelse', 'rem', 'xor' )
atom_re = r"(?:[a-z]\w*|'[^\n']*[^\\]')"
variable_re = r'(?:[A-Z_]\w*)'
esc_char_re = r'[bdefnrstv\'"\\]' esc_octal_re = r'[0-7][0-7]?[0-7]?' esc_hex_re = r'(?:x[0-9a-fA-F]{2}|x\{[0-9a-fA-F]+\})' esc_ctrl_re = r'\^[a-zA-Z]' escape_re = r'(?:\\(?:'+esc_char_re+r'|'+esc_octal_re+r'|'+esc_hex_re+r'|'+esc_ctrl_re+r'))'
macro_re = r'(?:'+variable_re+r'|'+atom_re+r')'
base_re = r'(?:[2-9]|[12][0-9]|3[0-6])'
tokens = { 'root': [ (r'\s+', Whitespace), (r'(%.*)(\n)', bygroups(Comment, Whitespace)), (words(keywords, suffix=r'\b'), Keyword), (words(builtins, suffix=r'\b'), Name.Builtin), (words(word_operators, suffix=r'\b'), Operator.Word), (r'^-', Punctuation, 'directive'), (operators, Operator), (r'"', String, 'string'), (r'<<', Name.Label), (r'>>', Name.Label), ('(' + atom_re + ')(:)', bygroups(Name.Namespace, Punctuation)), ('(?:^|(?<=:))(' + atom_re + r')(\s*)(\()', bygroups(Name.Function, Whitespace, Punctuation)), (r'[+-]?' + base_re + r'#[0-9a-zA-Z]+', Number.Integer), (r'[+-]?\d+', Number.Integer), (r'[+-]?\d+.\d+', Number.Float), (r'[]\[:_@\".{}()|;,]', Punctuation), (variable_re, Name.Variable), (atom_re, Name), (r'\?'+macro_re, Name.Constant), (r'\$(?:'+escape_re+r'|\\[ %]|[^\\])', String.Char), (r'#'+atom_re+r'(:?\.'+atom_re+r')?', Name.Label),
# Erlang script shebang (r'\A#!.+\n', Comment.Hashbang),
# EEP 43: Maps # http://www.erlang.org/eeps/eep-0043.html (r'#\{', Punctuation, 'map_key'), ], 'string': [ (escape_re, String.Escape), (r'"', String, '#pop'), (r'~[0-9.*]*[~#+BPWXb-ginpswx]', String.Interpol), (r'[^"\\~]+', String), (r'~', String), ], 'directive': [ (r'(define)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Whitespace, Punctuation, Name.Constant), '#pop'), (r'(record)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Whitespace, Punctuation, Name.Label), '#pop'), (atom_re, Name.Entity, '#pop'), ], 'map_key': [ include('root'), (r'=>', Punctuation, 'map_val'), (r':=', Punctuation, 'map_val'), (r'\}', Punctuation, '#pop'), ], 'map_val': [ include('root'), (r',', Punctuation, '#pop'), (r'(?=\})', Punctuation, '#pop'), ], }
class ErlangShellLexer(Lexer): """ Shell sessions in erl (for Erlang code). """ name = 'Erlang erl session' aliases = ['erl'] filenames = ['*.erl-sh'] mimetypes = ['text/x-erl-shellsession'] url = 'https://www.erlang.org/' version_added = '1.1'
_prompt_re = re.compile(r'(?:\([\w@_.]+\))?\d+>(?=\s|\Z)')
def get_tokens_unprocessed(self, text): erlexer = ErlangLexer(**self.options)
curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() m = self._prompt_re.match(line) if m is not None: end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: yield from do_insertions(insertions, erlexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] if line.startswith('*'): yield match.start(), Generic.Traceback, line else: yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, erlexer.get_tokens_unprocessed(curcode))
def gen_elixir_string_rules(name, symbol, token): states = {} states['string_' + name] = [ (rf'[^#{symbol}\\]+', token), include('escapes'), (r'\\.', token), (rf'({symbol})', bygroups(token), "#pop"), include('interpol') ] return states
def gen_elixir_sigstr_rules(term, term_class, token, interpol=True): if interpol: return [ (rf'[^#{term_class}\\]+', token), include('escapes'), (r'\\.', token), (rf'{term}[a-zA-Z]*', token, '#pop'), include('interpol') ] else: return [ (rf'[^{term_class}\\]+', token), (r'\\.', token), (rf'{term}[a-zA-Z]*', token, '#pop'), ]
class ElixirLexer(RegexLexer): """ For the Elixir language. """
name = 'Elixir' url = 'https://elixir-lang.org' aliases = ['elixir', 'ex', 'exs'] filenames = ['*.ex', '*.eex', '*.exs', '*.leex'] mimetypes = ['text/x-elixir'] version_added = '1.5'
KEYWORD = ('fn', 'do', 'end', 'after', 'else', 'rescue', 'catch') KEYWORD_OPERATOR = ('not', 'and', 'or', 'when', 'in') BUILTIN = ( 'case', 'cond', 'for', 'if', 'unless', 'try', 'receive', 'raise', 'quote', 'unquote', 'unquote_splicing', 'throw', 'super', ) BUILTIN_DECLARATION = ( 'def', 'defp', 'defmodule', 'defprotocol', 'defmacro', 'defmacrop', 'defdelegate', 'defexception', 'defstruct', 'defimpl', 'defcallback', )
BUILTIN_NAMESPACE = ('import', 'require', 'use', 'alias') CONSTANT = ('nil', 'true', 'false')
PSEUDO_VAR = ('_', '__MODULE__', '__DIR__', '__ENV__', '__CALLER__')
OPERATORS3 = ( '<<<', '>>>', '|||', '&&&', '^^^', '~~~', '===', '!==', '~>>', '<~>', '|~>', '<|>', ) OPERATORS2 = ( '==', '!=', '<=', '>=', '&&', '||', '<>', '++', '--', '|>', '=~', '->', '<-', '|', '.', '=', '~>', '<~', ) OPERATORS1 = ('<', '>', '+', '-', '*', '/', '!', '^', '&')
PUNCTUATION = ( '\\\\', '<<', '>>', '=>', '(', ')', ':', ';', ',', '[', ']', )
def get_tokens_unprocessed(self, text): for index, token, value in RegexLexer.get_tokens_unprocessed(self, text): if token is Name: if value in self.KEYWORD: yield index, Keyword, value elif value in self.KEYWORD_OPERATOR: yield index, Operator.Word, value elif value in self.BUILTIN: yield index, Keyword, value elif value in self.BUILTIN_DECLARATION: yield index, Keyword.Declaration, value elif value in self.BUILTIN_NAMESPACE: yield index, Keyword.Namespace, value elif value in self.CONSTANT: yield index, Name.Constant, value elif value in self.PSEUDO_VAR: yield index, Name.Builtin.Pseudo, value else: yield index, token, value else: yield index, token, value
def gen_elixir_sigil_rules(): # all valid sigil terminators (excluding heredocs) terminators = [ (r'\{', r'\}', '}', 'cb'), (r'\[', r'\]', r'\]', 'sb'), (r'\(', r'\)', ')', 'pa'), ('<', '>', '>', 'ab'), ('/', '/', '/', 'slas'), (r'\|', r'\|', '|', 'pipe'), ('"', '"', '"', 'quot'), ("'", "'", "'", 'apos'), ]
# heredocs have slightly different rules triquotes = [(r'"""', 'triquot'), (r"'''", 'triapos')]
token = String.Other states = {'sigils': []}
for term, name in triquotes: states['sigils'] += [ (rf'(~[a-z])({term})', bygroups(token, String.Heredoc), (name + '-end', name + '-intp')), (rf'(~[A-Z])({term})', bygroups(token, String.Heredoc), (name + '-end', name + '-no-intp')), ]
states[name + '-end'] = [ (r'[a-zA-Z]+', token, '#pop'), default('#pop'), ] states[name + '-intp'] = [ (r'^(\s*)(' + term + ')', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_interpol'), ] states[name + '-no-intp'] = [ (r'^(\s*)(' + term +')', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_no_interpol'), ]
for lterm, rterm, rterm_class, name in terminators: states['sigils'] += [ (r'~[a-z]' + lterm, token, name + '-intp'), (r'~[A-Z]' + lterm, token, name + '-no-intp'), ] states[name + '-intp'] = \ gen_elixir_sigstr_rules(rterm, rterm_class, token) states[name + '-no-intp'] = \ gen_elixir_sigstr_rules(rterm, rterm_class, token, interpol=False)
return states
op3_re = "|".join(re.escape(s) for s in OPERATORS3) op2_re = "|".join(re.escape(s) for s in OPERATORS2) op1_re = "|".join(re.escape(s) for s in OPERATORS1) ops_re = rf'(?:{op3_re}|{op2_re}|{op1_re})' punctuation_re = "|".join(re.escape(s) for s in PUNCTUATION) alnum = r'\w' name_re = rf'(?:\.\.\.|[a-z_]{alnum}*[!?]?)' modname_re = rf'[A-Z]{alnum}*(?:\.[A-Z]{alnum}*)*' complex_name_re = rf'(?:{name_re}|{modname_re}|{ops_re})' special_atom_re = r'(?:\.\.\.|<<>>|%\{\}|%|\{\})'
long_hex_char_re = r'(\\x\{)([\da-fA-F]+)(\})' hex_char_re = r'(\\x[\da-fA-F]{1,2})' escape_char_re = r'(\\[abdefnrstv])'
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*$', Comment.Single),
# Various kinds of characters (r'(\?)' + long_hex_char_re, bygroups(String.Char, String.Escape, Number.Hex, String.Escape)), (r'(\?)' + hex_char_re, bygroups(String.Char, String.Escape)), (r'(\?)' + escape_char_re, bygroups(String.Char, String.Escape)), (r'\?\\?.', String.Char),
# '::' has to go before atoms (r':::', String.Symbol), (r'::', Operator),
# atoms (r':' + special_atom_re, String.Symbol), (r':' + complex_name_re, String.Symbol), (r':"', String.Symbol, 'string_double_atom'), (r":'", String.Symbol, 'string_single_atom'),
# [keywords: ...] (rf'({special_atom_re}|{complex_name_re})(:)(?=\s|\n)', bygroups(String.Symbol, Punctuation)),
# @attributes (r'@' + name_re, Name.Attribute),
# identifiers (name_re, Name), (rf'(%?)({modname_re})', bygroups(Punctuation, Name.Class)),
# operators and punctuation (op3_re, Operator), (op2_re, Operator), (punctuation_re, Punctuation), (r'&\d', Name.Entity), # anon func arguments (op1_re, Operator),
# numbers (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[\da-fA-F]+', Number.Hex), (r'\d(_?\d)*\.\d(_?\d)*([eE][-+]?\d(_?\d)*)?', Number.Float), (r'\d(_?\d)*', Number.Integer),
# strings and heredocs (r'(""")(\s*)', bygroups(String.Heredoc, Whitespace), 'heredoc_double'), (r"(''')(\s*)$", bygroups(String.Heredoc, Whitespace), 'heredoc_single'), (r'"', String.Double, 'string_double'), (r"'", String.Single, 'string_single'),
include('sigils'),
(r'%\{', Punctuation, 'map_key'), (r'\{', Punctuation, 'tuple'), ], 'heredoc_double': [ (r'^(\s*)(""")', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_interpol'), ], 'heredoc_single': [ (r"^\s*'''", String.Heredoc, '#pop'), include('heredoc_interpol'), ], 'heredoc_interpol': [ (r'[^#\\\n]+', String.Heredoc), include('escapes'), (r'\\.', String.Heredoc), (r'\n+', String.Heredoc), include('interpol'), ], 'heredoc_no_interpol': [ (r'[^\\\n]+', String.Heredoc), (r'\\.', String.Heredoc), (r'\n+', Whitespace), ], 'escapes': [ (long_hex_char_re, bygroups(String.Escape, Number.Hex, String.Escape)), (hex_char_re, String.Escape), (escape_char_re, String.Escape), ], 'interpol': [ (r'#\{', String.Interpol, 'interpol_string'), ], 'interpol_string': [ (r'\}', String.Interpol, "#pop"), include('root') ], 'map_key': [ include('root'), (r':', Punctuation, 'map_val'), (r'=>', Punctuation, 'map_val'), (r'\}', Punctuation, '#pop'), ], 'map_val': [ include('root'), (r',', Punctuation, '#pop'), (r'(?=\})', Punctuation, '#pop'), ], 'tuple': [ include('root'), (r'\}', Punctuation, '#pop'), ], } tokens.update(gen_elixir_string_rules('double', '"', String.Double)) tokens.update(gen_elixir_string_rules('single', "'", String.Single)) tokens.update(gen_elixir_string_rules('double_atom', '"', String.Symbol)) tokens.update(gen_elixir_string_rules('single_atom', "'", String.Symbol)) tokens.update(gen_elixir_sigil_rules())
class ElixirConsoleLexer(Lexer): """ For Elixir interactive console (iex) output like:
.. sourcecode:: iex
iex> [head | tail] = [1,2,3] [1,2,3] iex> head 1 iex> tail [2,3] iex> [head | tail] [1,2,3] iex> length [head | tail] 3 """
name = 'Elixir iex session' aliases = ['iex'] mimetypes = ['text/x-elixir-shellsession'] url = 'https://elixir-lang.org' version_added = '1.5'
_prompt_re = re.compile(r'(iex|\.{3})((?:\([\w@_.]+\))?\d+|\(\d+\))?> ')
def get_tokens_unprocessed(self, text): exlexer = ElixirLexer(**self.options)
curcode = '' in_error = False insertions = [] for match in line_re.finditer(text): line = match.group() if line.startswith('** '): in_error = True insertions.append((len(curcode), [(0, Generic.Error, line[:-1])])) curcode += line[-1:] else: m = self._prompt_re.match(line) if m is not None: in_error = False end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: yield from do_insertions( insertions, exlexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] token = Generic.Error if in_error else Generic.Output yield match.start(), token, line if curcode: yield from do_insertions( insertions, exlexer.get_tokens_unprocessed(curcode))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300""" pygments.lexers.esoteric ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for esoteric languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Error, Whitespace
__all__ = ['BrainfuckLexer', 'BefungeLexer', 'RedcodeLexer', 'CAmkESLexer', 'CapDLLexer', 'AheuiLexer']
class BrainfuckLexer(RegexLexer): """ Lexer for the esoteric BrainFuck language. """
name = 'Brainfuck' url = 'http://www.muppetlabs.com/~breadbox/bf/' aliases = ['brainfuck', 'bf'] filenames = ['*.bf', '*.b'] mimetypes = ['application/x-brainfuck'] version_added = ''
tokens = { 'common': [ # use different colors for different instruction types (r'[.,]+', Name.Tag), (r'[+-]+', Name.Builtin), (r'[<>]+', Name.Variable), (r'[^.,+\-<>\[\]]+', Comment), ], 'root': [ (r'\[', Keyword, 'loop'), (r'\]', Error), include('common'), ], 'loop': [ (r'\[', Keyword, '#push'), (r'\]', Keyword, '#pop'), include('common'), ] }
def analyse_text(text): """It's safe to assume that a program which mostly consists of + - and < > is brainfuck.""" plus_minus_count = 0 greater_less_count = 0
range_to_check = max(256, len(text))
for c in text[:range_to_check]: if c == '+' or c == '-': plus_minus_count += 1 if c == '<' or c == '>': greater_less_count += 1
if plus_minus_count > (0.25 * range_to_check): return 1.0 if greater_less_count > (0.25 * range_to_check): return 1.0
result = 0 if '[-]' in text: result += 0.5
return result
class BefungeLexer(RegexLexer): """ Lexer for the esoteric Befunge language. """ name = 'Befunge' url = 'http://en.wikipedia.org/wiki/Befunge' aliases = ['befunge'] filenames = ['*.befunge'] mimetypes = ['application/x-befunge'] version_added = '0.7'
tokens = { 'root': [ (r'[0-9a-f]', Number), (r'[+*/%!`-]', Operator), # Traditional math (r'[<>^v?\[\]rxjk]', Name.Variable), # Move, imperatives (r'[:\\$.,n]', Name.Builtin), # Stack ops, imperatives (r'[|_mw]', Keyword), (r'[{}]', Name.Tag), # Befunge-98 stack ops (r'".*?"', String.Double), # Strings don't appear to allow escapes (r'\'.', String.Single), # Single character (r'[#;]', Comment), # Trampoline... depends on direction hit (r'[pg&~=@iotsy]', Keyword), # Misc (r'[()A-Z]', Comment), # Fingerprints (r'\s+', Whitespace), # Whitespace doesn't matter ], }
class CAmkESLexer(RegexLexer): """ Basic lexer for the input language for the CAmkES component platform. """ name = 'CAmkES' url = 'https://sel4.systems/CAmkES/' aliases = ['camkes', 'idl4'] filenames = ['*.camkes', '*.idl4'] version_added = '2.1'
tokens = { 'root': [ # C pre-processor directive (r'^(\s*)(#.*)(\n)', bygroups(Whitespace, Comment.Preproc, Whitespace)),
# Whitespace, comments (r'\s+', Whitespace), (r'/\*(.|\n)*?\*/', Comment), (r'//.*$', Comment),
(r'[\[(){},.;\]]', Punctuation), (r'[~!%^&*+=|?:<>/-]', Operator),
(words(('assembly', 'attribute', 'component', 'composition', 'configuration', 'connection', 'connector', 'consumes', 'control', 'dataport', 'Dataport', 'Dataports', 'emits', 'event', 'Event', 'Events', 'export', 'from', 'group', 'hardware', 'has', 'interface', 'Interface', 'maybe', 'procedure', 'Procedure', 'Procedures', 'provides', 'template', 'thread', 'threads', 'to', 'uses', 'with'), suffix=r'\b'), Keyword),
(words(('bool', 'boolean', 'Buf', 'char', 'character', 'double', 'float', 'in', 'inout', 'int', 'int16_6', 'int32_t', 'int64_t', 'int8_t', 'integer', 'mutex', 'out', 'real', 'refin', 'semaphore', 'signed', 'string', 'struct', 'uint16_t', 'uint32_t', 'uint64_t', 'uint8_t', 'uintptr_t', 'unsigned', 'void'), suffix=r'\b'), Keyword.Type),
# Recognised attributes (r'[a-zA-Z_]\w*_(priority|domain|buffer)', Keyword.Reserved), (words(('dma_pool', 'from_access', 'to_access'), suffix=r'\b'), Keyword.Reserved),
# CAmkES-level include (r'(import)(\s+)((?:<[^>]*>|"[^"]*");)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)),
# C-level include (r'(include)(\s+)((?:<[^>]*>|"[^"]*");)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)),
# Literals (r'0[xX][\da-fA-F]+', Number.Hex), (r'-?[\d]+', Number), (r'-?[\d]+\.[\d]+', Number.Float), (r'"[^"]*"', String), (r'[Tt]rue|[Ff]alse', Name.Builtin),
# Identifiers (r'[a-zA-Z_]\w*', Name), ], }
class CapDLLexer(RegexLexer): """ Basic lexer for CapDL.
The source of the primary tool that reads such specifications is available at https://github.com/seL4/capdl/tree/master/capDL-tool. Note that this lexer only supports a subset of the grammar. For example, identifiers can shadow type names, but these instances are currently incorrectly highlighted as types. Supporting this would need a stateful lexer that is considered unnecessarily complex for now. """ name = 'CapDL' url = 'https://ssrg.nicta.com.au/publications/nictaabstracts/Kuz_KLW_10.abstract.pml' aliases = ['capdl'] filenames = ['*.cdl'] version_added = '2.2'
tokens = { 'root': [ # C pre-processor directive (r'^(\s*)(#.*)(\n)', bygroups(Whitespace, Comment.Preproc, Whitespace)),
# Whitespace, comments (r'\s+', Whitespace), (r'/\*(.|\n)*?\*/', Comment), (r'(//|--).*$', Comment),
(r'[<>\[(){},:;=\]]', Punctuation), (r'\.\.', Punctuation),
(words(('arch', 'arm11', 'caps', 'child_of', 'ia32', 'irq', 'maps', 'objects'), suffix=r'\b'), Keyword),
(words(('aep', 'asid_pool', 'cnode', 'ep', 'frame', 'io_device', 'io_ports', 'io_pt', 'notification', 'pd', 'pt', 'tcb', 'ut', 'vcpu'), suffix=r'\b'), Keyword.Type),
# Properties (words(('asid', 'addr', 'badge', 'cached', 'dom', 'domainID', 'elf', 'fault_ep', 'G', 'guard', 'guard_size', 'init', 'ip', 'prio', 'sp', 'R', 'RG', 'RX', 'RW', 'RWG', 'RWX', 'W', 'WG', 'WX', 'level', 'masked', 'master_reply', 'paddr', 'ports', 'reply', 'uncached'), suffix=r'\b'), Keyword.Reserved),
# Literals (r'0[xX][\da-fA-F]+', Number.Hex), (r'\d+(\.\d+)?(k|M)?', Number), (words(('bits',), suffix=r'\b'), Number), (words(('cspace', 'vspace', 'reply_slot', 'caller_slot', 'ipc_buffer_slot'), suffix=r'\b'), Number),
# Identifiers (r'[a-zA-Z_][-@\.\w]*', Name), ], }
class RedcodeLexer(RegexLexer): """ A simple Redcode lexer based on ICWS'94. Contributed by Adam Blinkinsop <blinks@acm.org>. """ name = 'Redcode' aliases = ['redcode'] filenames = ['*.cw'] url = 'https://en.wikipedia.org/wiki/Core_War' version_added = '0.8'
opcodes = ('DAT', 'MOV', 'ADD', 'SUB', 'MUL', 'DIV', 'MOD', 'JMP', 'JMZ', 'JMN', 'DJN', 'CMP', 'SLT', 'SPL', 'ORG', 'EQU', 'END') modifiers = ('A', 'B', 'AB', 'BA', 'F', 'X', 'I')
tokens = { 'root': [ # Whitespace: (r'\s+', Whitespace), (r';.*$', Comment.Single), # Lexemes: # Identifiers (r'\b({})\b'.format('|'.join(opcodes)), Name.Function), (r'\b({})\b'.format('|'.join(modifiers)), Name.Decorator), (r'[A-Za-z_]\w+', Name), # Operators (r'[-+*/%]', Operator), (r'[#$@<>]', Operator), # mode (r'[.,]', Punctuation), # mode # Numbers (r'[-+]?\d+', Number.Integer), ], }
class AheuiLexer(RegexLexer): """ Aheui is esoteric language based on Korean alphabets. """
name = 'Aheui' url = 'http://aheui.github.io/' aliases = ['aheui'] filenames = ['*.aheui'] version_added = ''
tokens = { 'root': [ ('[' '나-낳냐-냫너-넣녀-녛노-놓뇨-눟뉴-닇' '다-닿댜-댷더-덯뎌-뎧도-돟됴-둫듀-딓' '따-땋땨-떃떠-떻뗘-뗳또-똫뚀-뚷뜌-띟' '라-랗랴-럏러-렇려-렿로-롷료-뤃류-릫' '마-맣먀-먛머-멓며-몋모-뫃묘-뭏뮤-믷' '바-밯뱌-뱧버-벟벼-볗보-봏뵤-붛뷰-빃' '빠-빻뺘-뺳뻐-뻫뼈-뼣뽀-뽛뾰-뿧쀼-삏' '사-샇샤-샿서-섷셔-셯소-솧쇼-숳슈-싛' '싸-쌓쌰-썋써-쎃쎠-쎻쏘-쏳쑈-쑿쓔-씧' '자-잫쟈-쟣저-젛져-졓조-좋죠-줗쥬-즿' '차-챃챠-챻처-첳쳐-쳫초-촣쵸-춯츄-칗' '카-캏캬-컇커-컿켜-켷코-콯쿄-쿻큐-킣' '타-탛탸-턓터-텋텨-톃토-톻툐-퉇튜-틯' '파-팧퍄-퍟퍼-펗펴-폏포-퐇표-풓퓨-픻' '하-핳햐-햫허-헣혀-혛호-홓효-훟휴-힇' ']', Operator), ('.', Comment), ], }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576""" pygments.lexers.ezhil ~~~~~~~~~~~~~~~~~~~~~
Pygments lexers for Ezhil language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Keyword, Comment, Name, String, Number, \ Punctuation, Operator, Whitespace
__all__ = ['EzhilLexer']
class EzhilLexer(RegexLexer): """ Lexer for Ezhil, a Tamil script-based programming language. """ name = 'Ezhil' url = 'http://ezhillang.org' aliases = ['ezhil'] filenames = ['*.n'] mimetypes = ['text/x-ezhil'] version_added = '2.1' # Refer to tamil.utf8.tamil_letters from open-tamil for a stricter version of this. # This much simpler version is close enough, and includes combining marks. _TALETTERS = '[a-zA-Z_]|[\u0b80-\u0bff]' tokens = { 'root': [ include('keywords'), (r'#.*$', Comment.Single), (r'[@+/*,^\-%]|[!<>=]=?|&&?|\|\|?', Operator), ('இல்', Operator.Word), (words(('assert', 'max', 'min', 'நீளம்', 'சரம்_இடமாற்று', 'சரம்_கண்டுபிடி', 'பட்டியல்', 'பின்இணை', 'வரிசைப்படுத்து', 'எடு', 'தலைகீழ்', 'நீட்டிக்க', 'நுழைக்க', 'வை', 'கோப்பை_திற', 'கோப்பை_எழுது', 'கோப்பை_மூடு', 'pi', 'sin', 'cos', 'tan', 'sqrt', 'hypot', 'pow', 'exp', 'log', 'log10', 'exit', ), suffix=r'\b'), Name.Builtin), (r'(True|False)\b', Keyword.Constant), (r'[^\S\n]+', Whitespace), include('identifier'), include('literal'), (r'[(){}\[\]:;.]', Punctuation), ], 'keywords': [ ('பதிப்பி|தேர்ந்தெடு|தேர்வு|ஏதேனில்|ஆனால்|இல்லைஆனால்|இல்லை|ஆக|ஒவ்வொன்றாக|இல்|வரை|செய்|முடியேனில்|பின்கொடு|முடி|நிரல்பாகம்|தொடர்|நிறுத்து|நிரல்பாகம்', Keyword), ], 'identifier': [ ('(?:'+_TALETTERS+')(?:[0-9]|'+_TALETTERS+')*', Name), ], 'literal': [ (r'".*?"', String), (r'\d+((\.\d*)?[eE][+-]?\d+|\.\d*)', Number.Float), (r'\d+', Number.Integer), ] }
def analyse_text(text): """This language uses Tamil-script. We'll assume that if there's a decent amount of Tamil-characters, it's this language. This assumption is obviously horribly off if someone uses string literals in tamil in another language.""" if len(re.findall(r'[\u0b80-\u0bff]', text)) > 10: return 0.25
def __init__(self, **options): super().__init__(**options) self.encoding = options.get('encoding', 'utf-8')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363""" pygments.lexers.factor ~~~~~~~~~~~~~~~~~~~~~~
Lexers for the Factor language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, default, wordsfrom pygments.token import Text, Comment, Keyword, Name, String, Number, \ Whitespace, Punctuation
__all__ = ['FactorLexer']
class FactorLexer(RegexLexer): """ Lexer for the Factor language. """ name = 'Factor' url = 'http://factorcode.org' aliases = ['factor'] filenames = ['*.factor'] mimetypes = ['text/x-factor'] version_added = '1.4'
builtin_kernel = words(( '-rot', '2bi', '2bi@', '2bi*', '2curry', '2dip', '2drop', '2dup', '2keep', '2nip', '2over', '2tri', '2tri@', '2tri*', '3bi', '3curry', '3dip', '3drop', '3dup', '3keep', '3tri', '4dip', '4drop', '4dup', '4keep', '<wrapper>', '=', '>boolean', 'clone', '?', '?execute', '?if', 'and', 'assert', 'assert=', 'assert?', 'bi', 'bi-curry', 'bi-curry@', 'bi-curry*', 'bi@', 'bi*', 'boa', 'boolean', 'boolean?', 'both?', 'build', 'call', 'callstack', 'callstack>array', 'callstack?', 'clear', '(clone)', 'compose', 'compose?', 'curry', 'curry?', 'datastack', 'die', 'dip', 'do', 'drop', 'dup', 'dupd', 'either?', 'eq?', 'equal?', 'execute', 'hashcode', 'hashcode*', 'identity-hashcode', 'identity-tuple', 'identity-tuple?', 'if', 'if*', 'keep', 'loop', 'most', 'new', 'nip', 'not', 'null', 'object', 'or', 'over', 'pick', 'prepose', 'retainstack', 'rot', 'same?', 'swap', 'swapd', 'throw', 'tri', 'tri-curry', 'tri-curry@', 'tri-curry*', 'tri@', 'tri*', 'tuple', 'tuple?', 'unless', 'unless*', 'until', 'when', 'when*', 'while', 'with', 'wrapper', 'wrapper?', 'xor'), suffix=r'(\s+)')
builtin_assocs = words(( '2cache', '<enum>', '>alist', '?at', '?of', 'assoc', 'assoc-all?', 'assoc-any?', 'assoc-clone-like', 'assoc-combine', 'assoc-diff', 'assoc-diff!', 'assoc-differ', 'assoc-each', 'assoc-empty?', 'assoc-filter', 'assoc-filter!', 'assoc-filter-as', 'assoc-find', 'assoc-hashcode', 'assoc-intersect', 'assoc-like', 'assoc-map', 'assoc-map-as', 'assoc-partition', 'assoc-refine', 'assoc-size', 'assoc-stack', 'assoc-subset?', 'assoc-union', 'assoc-union!', 'assoc=', 'assoc>map', 'assoc?', 'at', 'at+', 'at*', 'cache', 'change-at', 'clear-assoc', 'delete-at', 'delete-at*', 'enum', 'enum?', 'extract-keys', 'inc-at', 'key?', 'keys', 'map>assoc', 'maybe-set-at', 'new-assoc', 'of', 'push-at', 'rename-at', 'set-at', 'sift-keys', 'sift-values', 'substitute', 'unzip', 'value-at', 'value-at*', 'value?', 'values', 'zip'), suffix=r'(\s+)')
builtin_combinators = words(( '2cleave', '2cleave>quot', '3cleave', '3cleave>quot', '4cleave', '4cleave>quot', 'alist>quot', 'call-effect', 'case', 'case-find', 'case>quot', 'cleave', 'cleave>quot', 'cond', 'cond>quot', 'deep-spread>quot', 'execute-effect', 'linear-case-quot', 'no-case', 'no-case?', 'no-cond', 'no-cond?', 'recursive-hashcode', 'shallow-spread>quot', 'spread', 'to-fixed-point', 'wrong-values', 'wrong-values?'), suffix=r'(\s+)')
builtin_math = words(( '-', '/', '/f', '/i', '/mod', '2/', '2^', '<', '<=', '<fp-nan>', '>', '>=', '>bignum', '>fixnum', '>float', '>integer', '(all-integers?)', '(each-integer)', '(find-integer)', '*', '+', '?1+', 'abs', 'align', 'all-integers?', 'bignum', 'bignum?', 'bit?', 'bitand', 'bitnot', 'bitor', 'bits>double', 'bits>float', 'bitxor', 'complex', 'complex?', 'denominator', 'double>bits', 'each-integer', 'even?', 'find-integer', 'find-last-integer', 'fixnum', 'fixnum?', 'float', 'float>bits', 'float?', 'fp-bitwise=', 'fp-infinity?', 'fp-nan-payload', 'fp-nan?', 'fp-qnan?', 'fp-sign', 'fp-snan?', 'fp-special?', 'if-zero', 'imaginary-part', 'integer', 'integer>fixnum', 'integer>fixnum-strict', 'integer?', 'log2', 'log2-expects-positive', 'log2-expects-positive?', 'mod', 'neg', 'neg?', 'next-float', 'next-power-of-2', 'number', 'number=', 'number?', 'numerator', 'odd?', 'out-of-fixnum-range', 'out-of-fixnum-range?', 'power-of-2?', 'prev-float', 'ratio', 'ratio?', 'rational', 'rational?', 'real', 'real-part', 'real?', 'recip', 'rem', 'sgn', 'shift', 'sq', 'times', 'u<', 'u<=', 'u>', 'u>=', 'unless-zero', 'unordered?', 'when-zero', 'zero?'), suffix=r'(\s+)')
builtin_sequences = words(( '1sequence', '2all?', '2each', '2map', '2map-as', '2map-reduce', '2reduce', '2selector', '2sequence', '3append', '3append-as', '3each', '3map', '3map-as', '3sequence', '4sequence', '<repetition>', '<reversed>', '<slice>', '?first', '?last', '?nth', '?second', '?set-nth', 'accumulate', 'accumulate!', 'accumulate-as', 'all?', 'any?', 'append', 'append!', 'append-as', 'assert-sequence', 'assert-sequence=', 'assert-sequence?', 'binary-reduce', 'bounds-check', 'bounds-check?', 'bounds-error', 'bounds-error?', 'but-last', 'but-last-slice', 'cartesian-each', 'cartesian-map', 'cartesian-product', 'change-nth', 'check-slice', 'check-slice-error', 'clone-like', 'collapse-slice', 'collector', 'collector-for', 'concat', 'concat-as', 'copy', 'count', 'cut', 'cut-slice', 'cut*', 'delete-all', 'delete-slice', 'drop-prefix', 'each', 'each-from', 'each-index', 'empty?', 'exchange', 'filter', 'filter!', 'filter-as', 'find', 'find-from', 'find-index', 'find-index-from', 'find-last', 'find-last-from', 'first', 'first2', 'first3', 'first4', 'flip', 'follow', 'fourth', 'glue', 'halves', 'harvest', 'head', 'head-slice', 'head-slice*', 'head*', 'head?', 'if-empty', 'immutable', 'immutable-sequence', 'immutable-sequence?', 'immutable?', 'index', 'index-from', 'indices', 'infimum', 'infimum-by', 'insert-nth', 'interleave', 'iota', 'iota-tuple', 'iota-tuple?', 'join', 'join-as', 'last', 'last-index', 'last-index-from', 'length', 'lengthen', 'like', 'longer', 'longer?', 'longest', 'map', 'map!', 'map-as', 'map-find', 'map-find-last', 'map-index', 'map-integers', 'map-reduce', 'map-sum', 'max-length', 'member-eq?', 'member?', 'midpoint@', 'min-length', 'mismatch', 'move', 'new-like', 'new-resizable', 'new-sequence', 'non-negative-integer-expected', 'non-negative-integer-expected?', 'nth', 'nths', 'pad-head', 'pad-tail', 'padding', 'partition', 'pop', 'pop*', 'prefix', 'prepend', 'prepend-as', 'produce', 'produce-as', 'product', 'push', 'push-all', 'push-either', 'push-if', 'reduce', 'reduce-index', 'remove', 'remove!', 'remove-eq', 'remove-eq!', 'remove-nth', 'remove-nth!', 'repetition', 'repetition?', 'replace-slice', 'replicate', 'replicate-as', 'rest', 'rest-slice', 'reverse', 'reverse!', 'reversed', 'reversed?', 'second', 'selector', 'selector-for', 'sequence', 'sequence-hashcode', 'sequence=', 'sequence?', 'set-first', 'set-fourth', 'set-last', 'set-length', 'set-nth', 'set-second', 'set-third', 'short', 'shorten', 'shorter', 'shorter?', 'shortest', 'sift', 'slice', 'slice-error', 'slice-error?', 'slice?', 'snip', 'snip-slice', 'start', 'start*', 'subseq', 'subseq?', 'suffix', 'suffix!', 'sum', 'sum-lengths', 'supremum', 'supremum-by', 'surround', 'tail', 'tail-slice', 'tail-slice*', 'tail*', 'tail?', 'third', 'trim', 'trim-head', 'trim-head-slice', 'trim-slice', 'trim-tail', 'trim-tail-slice', 'unclip', 'unclip-last', 'unclip-last-slice', 'unclip-slice', 'unless-empty', 'virtual-exemplar', 'virtual-sequence', 'virtual-sequence?', 'virtual@', 'when-empty'), suffix=r'(\s+)')
builtin_namespaces = words(( '+@', 'change', 'change-global', 'counter', 'dec', 'get', 'get-global', 'global', 'inc', 'init-namespaces', 'initialize', 'is-global', 'make-assoc', 'namespace', 'namestack', 'off', 'on', 'set', 'set-global', 'set-namestack', 'toggle', 'with-global', 'with-scope', 'with-variable', 'with-variables'), suffix=r'(\s+)')
builtin_arrays = words(( '1array', '2array', '3array', '4array', '<array>', '>array', 'array', 'array?', 'pair', 'pair?', 'resize-array'), suffix=r'(\s+)')
builtin_io = words(( '(each-stream-block-slice)', '(each-stream-block)', '(stream-contents-by-block)', '(stream-contents-by-element)', '(stream-contents-by-length-or-block)', '(stream-contents-by-length)', '+byte+', '+character+', 'bad-seek-type', 'bad-seek-type?', 'bl', 'contents', 'each-block', 'each-block-size', 'each-block-slice', 'each-line', 'each-morsel', 'each-stream-block', 'each-stream-block-slice', 'each-stream-line', 'error-stream', 'flush', 'input-stream', 'input-stream?', 'invalid-read-buffer', 'invalid-read-buffer?', 'lines', 'nl', 'output-stream', 'output-stream?', 'print', 'read', 'read-into', 'read-partial', 'read-partial-into', 'read-until', 'read1', 'readln', 'seek-absolute', 'seek-absolute?', 'seek-end', 'seek-end?', 'seek-input', 'seek-output', 'seek-relative', 'seek-relative?', 'stream-bl', 'stream-contents', 'stream-contents*', 'stream-copy', 'stream-copy*', 'stream-element-type', 'stream-flush', 'stream-length', 'stream-lines', 'stream-nl', 'stream-print', 'stream-read', 'stream-read-into', 'stream-read-partial', 'stream-read-partial-into', 'stream-read-partial-unsafe', 'stream-read-unsafe', 'stream-read-until', 'stream-read1', 'stream-readln', 'stream-seek', 'stream-seekable?', 'stream-tell', 'stream-write', 'stream-write1', 'tell-input', 'tell-output', 'with-error-stream', 'with-error-stream*', 'with-error>output', 'with-input-output+error-streams', 'with-input-output+error-streams*', 'with-input-stream', 'with-input-stream*', 'with-output-stream', 'with-output-stream*', 'with-output>error', 'with-output+error-stream', 'with-output+error-stream*', 'with-streams', 'with-streams*', 'write', 'write1'), suffix=r'(\s+)')
builtin_strings = words(( '1string', '<string>', '>string', 'resize-string', 'string', 'string?'), suffix=r'(\s+)')
builtin_vectors = words(( '1vector', '<vector>', '>vector', '?push', 'vector', 'vector?'), suffix=r'(\s+)')
builtin_continuations = words(( '<condition>', '<continuation>', '<restart>', 'attempt-all', 'attempt-all-error', 'attempt-all-error?', 'callback-error-hook', 'callcc0', 'callcc1', 'cleanup', 'compute-restarts', 'condition', 'condition?', 'continuation', 'continuation?', 'continue', 'continue-restart', 'continue-with', 'current-continuation', 'error', 'error-continuation', 'error-in-thread', 'error-thread', 'ifcc', 'ignore-errors', 'in-callback?', 'original-error', 'recover', 'restart', 'restart?', 'restarts', 'rethrow', 'rethrow-restarts', 'return', 'return-continuation', 'thread-error-hook', 'throw-continue', 'throw-restarts', 'with-datastack', 'with-return'), suffix=r'(\s+)')
tokens = { 'root': [ # factor allows a file to start with a shebang (r'#!.*$', Comment.Preproc), default('base'), ], 'base': [ (r'\s+', Whitespace),
# defining words (r'((?:MACRO|MEMO|TYPED)?:[:]?)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(M:[:]?)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Name.Function)), (r'(C:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Name.Class)), (r'(GENERIC:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(HOOK:|GENERIC#)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Name.Function)), (r'(\()(\s)', bygroups(Name.Function, Whitespace), 'stackeffect'), (r'(;)(\s)', bygroups(Keyword, Whitespace)),
# imports and namespaces (r'(USING:)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'vocabs'), (r'(USE:|UNUSE:|IN:|QUALIFIED:)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r'(QUALIFIED-WITH:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace, Whitespace, Name.Namespace)), (r'(FROM:|EXCLUDE:)(\s+)(\S+)(\s+=>\s)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace, Whitespace), 'words'), (r'(RENAME:)(\s+)(\S+)(\s+)(\S+)(\s+)(=>)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Function, Whitespace, Name.Namespace, Whitespace, Punctuation, Whitespace, Name.Function)), (r'(ALIAS:|TYPEDEF:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Function, Whitespace, Name.Function)), (r'(DEFER:|FORGET:|POSTPONE:)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Function)),
# tuples and classes (r'(TUPLE:|ERROR:)(\s+)(\S+)(\s+)(<)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Punctuation, Whitespace, Name.Class), 'slots'), (r'(TUPLE:|ERROR:|BUILTIN:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class), 'slots'), (r'(MIXIN:|UNION:|INTERSECTION:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class)), (r'(PREDICATE:)(\s+)(\S+)(\s+)(<)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Punctuation, Whitespace, Name.Class)), (r'(C:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Name.Class)), (r'(INSTANCE:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Name.Class)), (r'(SLOT:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(SINGLETON:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class)), (r'SINGLETONS:', Keyword, 'classes'),
# other syntax (r'(CONSTANT:|SYMBOL:|MAIN:|HELP:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(SYMBOLS:)(\s+)', bygroups(Keyword, Whitespace), 'words'), (r'(SYNTAX:)(\s+)', bygroups(Keyword, Whitespace)), (r'(ALIEN:)(\s+)', bygroups(Keyword, Whitespace)), (r'(STRUCT:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class)), (r'(FUNCTION:)(\s+)' r'(\S+)(\s+)(\S+)(\s+)' r'(\()(\s+)([^)]+)(\))(\s)', bygroups(Keyword.Namespace, Whitespace, Text, Whitespace, Name.Function, Whitespace, Punctuation, Whitespace, Text, Punctuation, Whitespace)), (r'(FUNCTION-ALIAS:)(\s+)' r'(\S+)(\s+)(\S+)(\s+)' r'(\S+)(\s+)' r'(\()(\s+)([^)]+)(\))(\s)', bygroups(Keyword.Namespace, Whitespace, Text, Whitespace, Name.Function, Whitespace, Name.Function, Whitespace, Punctuation, Whitespace, Text, Punctuation, Whitespace)),
# vocab.private (r'(<PRIVATE|PRIVATE>)(\s)', bygroups(Keyword.Namespace, Whitespace)),
# strings (r'"""\s(?:.|\n)*?\s"""', String), (r'"(?:\\\\|\\"|[^"])*"', String), (r'(\S+")(\s+)((?:\\\\|\\"|[^"])*")', bygroups(String, Whitespace, String)), (r'(CHAR:)(\s+)(\\[\\abfnrstv]|[^\\]\S*)(\s)', bygroups(String.Char, Whitespace, String.Char, Whitespace)),
# comments (r'!\s+.*$', Comment), (r'#!\s+.*$', Comment), (r'/\*\s+(?:.|\n)*?\s\*/', Comment),
# boolean constants (r'[tf]\b', Name.Constant),
# symbols and literals (r'[\\$]\s+\S+', Name.Constant), (r'M\\\s+\S+\s+\S+', Name.Constant),
# numbers (r'[+-]?(?:[\d,]*\d)?\.(?:\d([\d,]*\d)?)?(?:[eE][+-]?\d+)?\s', Number), (r'[+-]?\d(?:[\d,]*\d)?(?:[eE][+-]?\d+)?\s', Number), (r'0x[a-fA-F\d](?:[a-fA-F\d,]*[a-fA-F\d])?(?:p\d([\d,]*\d)?)?\s', Number), (r'NAN:\s+[a-fA-F\d](?:[a-fA-F\d,]*[a-fA-F\d])?(?:p\d([\d,]*\d)?)?\s', Number), (r'0b[01]+\s', Number.Bin), (r'0o[0-7]+\s', Number.Oct), (r'(?:\d([\d,]*\d)?)?\+\d(?:[\d,]*\d)?/\d(?:[\d,]*\d)?\s', Number), (r'(?:\-\d([\d,]*\d)?)?\-\d(?:[\d,]*\d)?/\d(?:[\d,]*\d)?\s', Number),
# keywords (r'(?:deprecated|final|foldable|flushable|inline|recursive)\s', Keyword),
# builtins (builtin_kernel, bygroups(Name.Builtin, Whitespace)), (builtin_assocs, bygroups(Name.Builtin, Whitespace)), (builtin_combinators, bygroups(Name.Builtin, Whitespace)), (builtin_math, bygroups(Name.Builtin, Whitespace)), (builtin_sequences, bygroups(Name.Builtin, Whitespace)), (builtin_namespaces, bygroups(Name.Builtin, Whitespace)), (builtin_arrays, bygroups(Name.Builtin, Whitespace)), (builtin_io, bygroups(Name.Builtin, Whitespace)), (builtin_strings, bygroups(Name.Builtin, Whitespace)), (builtin_vectors, bygroups(Name.Builtin, Whitespace)), (builtin_continuations, bygroups(Name.Builtin, Whitespace)),
# everything else is text (r'\S+', Text), ], 'stackeffect': [ (r'\s+', Whitespace), (r'(\()(\s+)', bygroups(Name.Function, Whitespace), 'stackeffect'), (r'(\))(\s+)', bygroups(Name.Function, Whitespace), '#pop'), (r'(--)(\s+)', bygroups(Name.Function, Whitespace)), (r'\S+', Name.Variable), ], 'slots': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'(\{)(\s+)(\S+)(\s+)([^}]+)(\s+)(\})(\s+)', bygroups(Text, Whitespace, Name.Variable, Whitespace, Text, Whitespace, Text, Whitespace)), (r'\S+', Name.Variable), ], 'vocabs': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'\S+', Name.Namespace), ], 'classes': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'\S+', Name.Class), ], 'words': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'\S+', Name.Function), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251""" pygments.lexers.fantom ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Fantom language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from string import Template
from pygments.lexer import RegexLexer, include, bygroups, using, \ this, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Literal, Whitespace
__all__ = ['FantomLexer']
class FantomLexer(RegexLexer): """ For Fantom source code. """ name = 'Fantom' aliases = ['fan'] filenames = ['*.fan'] mimetypes = ['application/x-fantom'] url = 'https://www.fantom.org' version_added = '1.5'
# often used regexes def s(str): return Template(str).substitute( dict( pod=r'[\"\w\.]+', eos=r'\n|;', id=r'[a-zA-Z_]\w*', # all chars which can be part of type definition. Starts with # either letter, or [ (maps), or | (funcs) type=r'(?:\[|[a-zA-Z_]|\|)[:\w\[\]|\->?]*?', ) )
tokens = { 'comments': [ (r'(?s)/\*.*?\*/', Comment.Multiline), # Multiline (r'//.*?$', Comment.Single), # Single line # TODO: highlight references in fandocs (r'\*\*.*?$', Comment.Special), # Fandoc (r'#.*$', Comment.Single) # Shell-style ], 'literals': [ (r'\b-?[\d_]+(ns|ms|sec|min|hr|day)', Number), # Duration (r'\b-?[\d_]*\.[\d_]+(ns|ms|sec|min|hr|day)', Number), # Duration with dot (r'\b-?(\d+)?\.\d+(f|F|d|D)?', Number.Float), # Float/Decimal (r'\b-?0x[0-9a-fA-F_]+', Number.Hex), # Hex (r'\b-?[\d_]+', Number.Integer), # Int (r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char), # Char (r'"', Punctuation, 'insideStr'), # Opening quote (r'`', Punctuation, 'insideUri'), # Opening accent (r'\b(true|false|null)\b', Keyword.Constant), # Bool & null (r'(?:(\w+)(::))?(\w+)(<\|)(.*?)(\|>)', # DSL bygroups(Name.Namespace, Punctuation, Name.Class, Punctuation, String, Punctuation)), (r'(?:(\w+)(::))?(\w+)?(#)(\w+)?', # Type/slot literal bygroups(Name.Namespace, Punctuation, Name.Class, Punctuation, Name.Function)), (r'\[,\]', Literal), # Empty list (s(r'($type)(\[,\])'), # Typed empty list bygroups(using(this, state='inType'), Literal)), (r'\[:\]', Literal), # Empty Map (s(r'($type)(\[:\])'), bygroups(using(this, state='inType'), Literal)), ], 'insideStr': [ (r'\\\\', String.Escape), # Escaped backslash (r'\\"', String.Escape), # Escaped " (r'\\`', String.Escape), # Escaped ` (r'\$\w+', String.Interpol), # Subst var (r'\$\{.*?\}', String.Interpol), # Subst expr (r'"', Punctuation, '#pop'), # Closing quot (r'.', String) # String content ], 'insideUri': [ # TODO: remove copy/paste str/uri (r'\\\\', String.Escape), # Escaped backslash (r'\\"', String.Escape), # Escaped " (r'\\`', String.Escape), # Escaped ` (r'\$\w+', String.Interpol), # Subst var (r'\$\{.*?\}', String.Interpol), # Subst expr (r'`', Punctuation, '#pop'), # Closing tick (r'.', String.Backtick) # URI content ], 'protectionKeywords': [ (r'\b(public|protected|private|internal)\b', Keyword), ], 'typeKeywords': [ (r'\b(abstract|final|const|native|facet|enum)\b', Keyword), ], 'methodKeywords': [ (r'\b(abstract|native|once|override|static|virtual|final)\b', Keyword), ], 'fieldKeywords': [ (r'\b(abstract|const|final|native|override|static|virtual|' r'readonly)\b', Keyword) ], 'otherKeywords': [ (words(( 'try', 'catch', 'throw', 'finally', 'for', 'if', 'else', 'while', 'as', 'is', 'isnot', 'switch', 'case', 'default', 'continue', 'break', 'do', 'return', 'get', 'set'), prefix=r'\b', suffix=r'\b'), Keyword), (r'\b(it|this|super)\b', Name.Builtin.Pseudo), ], 'operators': [ (r'\+\+|\-\-|\+|\-|\*|/|\|\||&&|<=>|<=|<|>=|>|=|!|\[|\]', Operator) ], 'inType': [ (r'[\[\]|\->:?]', Punctuation), (s(r'$id'), Name.Class), default('#pop'),
], 'root': [ include('comments'), include('protectionKeywords'), include('typeKeywords'), include('methodKeywords'), include('fieldKeywords'), include('literals'), include('otherKeywords'), include('operators'), (r'using\b', Keyword.Namespace, 'using'), # Using stmt (r'@\w+', Name.Decorator, 'facet'), # Symbol (r'(class|mixin)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Class), 'inheritance'), # Inheritance list
# Type var := val (s(r'($type)([ \t]+)($id)(\s*)(:=)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Operator)),
# var := val (s(r'($id)(\s*)(:=)'), bygroups(Name.Variable, Whitespace, Operator)),
# .someId( or ->someId( ### (s(r'(\.|(?:\->))($id)(\s*)(\()'), bygroups(Operator, Name.Function, Whitespace, Punctuation), 'insideParen'),
# .someId or ->someId (s(r'(\.|(?:\->))($id)'), bygroups(Operator, Name.Function)),
# new makeXXX ( (r'(new)(\s+)(make\w*)(\s*)(\()', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Punctuation), 'insideMethodDeclArgs'),
# Type name ( (s(r'($type)([ \t]+)' # Return type and whitespace r'($id)(\s*)(\()'), # method name + open brace bygroups(using(this, state='inType'), Whitespace, Name.Function, Whitespace, Punctuation), 'insideMethodDeclArgs'),
# ArgType argName, (s(r'($type)(\s+)($id)(\s*)(,)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation)),
# ArgType argName) # Covered in 'insideParen' state
# ArgType argName -> ArgType| (s(r'($type)(\s+)($id)(\s*)(\->)(\s*)($type)(\|)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation, Whitespace, using(this, state='inType'), Punctuation)),
# ArgType argName| (s(r'($type)(\s+)($id)(\s*)(\|)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation)),
# Type var (s(r'($type)([ \t]+)($id)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable)),
(r'\(', Punctuation, 'insideParen'), (r'\{', Punctuation, 'insideBrace'), (r'\s+', Whitespace), (r'.', Text) ], 'insideParen': [ (r'\)', Punctuation, '#pop'), include('root'), ], 'insideMethodDeclArgs': [ (r'\)', Punctuation, '#pop'), (s(r'($type)(\s+)($id)(\s*)(\))'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation), '#pop'), include('root'), ], 'insideBrace': [ (r'\}', Punctuation, '#pop'), include('root'), ], 'inheritance': [ (r'\s+', Whitespace), # Whitespace (r':|,', Punctuation), (r'(?:(\w+)(::))?(\w+)', bygroups(Name.Namespace, Punctuation, Name.Class)), (r'\{', Punctuation, '#pop') ], 'using': [ (r'[ \t]+', Whitespace), # consume whitespaces (r'(\[)(\w+)(\])', bygroups(Punctuation, Comment.Special, Punctuation)), # ffi (r'(\")?([\w.]+)(\")?', bygroups(Punctuation, Name.Namespace, Punctuation)), # podname (r'::', Punctuation, 'usingClass'), default('#pop') ], 'usingClass': [ (r'[ \t]+', Whitespace), # consume whitespaces (r'(as)(\s+)(\w+)', bygroups(Keyword.Declaration, Whitespace, Name.Class), '#pop:2'), (r'[\w$]+', Name.Class), default('#pop:2') # jump out to root state ], 'facet': [ (r'\s+', Whitespace), (r'\{', Punctuation, 'facetFields'), default('#pop') ], 'facetFields': [ include('comments'), include('literals'), include('operators'), (r'\s+', Whitespace), (r'(\s*)(\w+)(\s*)(=)', bygroups(Whitespace, Name, Whitespace, Operator)), (r'\}', Punctuation, '#pop'), (r'\s+', Whitespace), (r'.', Text) ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275""" pygments.lexers.felix ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Felix language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroups, default, words, \ combinedfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['FelixLexer']
class FelixLexer(RegexLexer): """ For Felix source code. """
name = 'Felix' url = 'http://www.felix-lang.org' aliases = ['felix', 'flx'] filenames = ['*.flx', '*.flxh'] mimetypes = ['text/x-felix'] version_added = '1.2'
preproc = ( 'elif', 'else', 'endif', 'if', 'ifdef', 'ifndef', )
keywords = ( '_', '_deref', 'all', 'as', 'assert', 'attempt', 'call', 'callback', 'case', 'caseno', 'cclass', 'code', 'compound', 'ctypes', 'do', 'done', 'downto', 'elif', 'else', 'endattempt', 'endcase', 'endif', 'endmatch', 'enum', 'except', 'exceptions', 'expect', 'finally', 'for', 'forall', 'forget', 'fork', 'functor', 'goto', 'ident', 'if', 'incomplete', 'inherit', 'instance', 'interface', 'jump', 'lambda', 'loop', 'match', 'module', 'namespace', 'new', 'noexpand', 'nonterm', 'obj', 'of', 'open', 'parse', 'raise', 'regexp', 'reglex', 'regmatch', 'rename', 'return', 'the', 'then', 'to', 'type', 'typecase', 'typedef', 'typematch', 'typeof', 'upto', 'when', 'whilst', 'with', 'yield', )
keyword_directives = ( '_gc_pointer', '_gc_type', 'body', 'comment', 'const', 'export', 'header', 'inline', 'lval', 'macro', 'noinline', 'noreturn', 'package', 'private', 'pod', 'property', 'public', 'publish', 'requires', 'todo', 'virtual', 'use', )
keyword_declarations = ( 'def', 'let', 'ref', 'val', 'var', )
keyword_types = ( 'unit', 'void', 'any', 'bool', 'byte', 'offset', 'address', 'caddress', 'cvaddress', 'vaddress', 'tiny', 'short', 'int', 'long', 'vlong', 'utiny', 'ushort', 'vshort', 'uint', 'ulong', 'uvlong', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float', 'double', 'ldouble', 'complex', 'dcomplex', 'lcomplex', 'imaginary', 'dimaginary', 'limaginary', 'char', 'wchar', 'uchar', 'charp', 'charcp', 'ucharp', 'ucharcp', 'string', 'wstring', 'ustring', 'cont', 'array', 'varray', 'list', 'lvalue', 'opt', 'slice', )
keyword_constants = ( 'false', 'true', )
operator_words = ( 'and', 'not', 'in', 'is', 'isin', 'or', 'xor', )
name_builtins = ( '_svc', 'while', )
name_pseudo = ( 'root', 'self', 'this', )
decimal_suffixes = '([tTsSiIlLvV]|ll|LL|([iIuU])(8|16|32|64))?'
tokens = { 'root': [ include('whitespace'),
# Keywords (words(('axiom', 'ctor', 'fun', 'gen', 'proc', 'reduce', 'union'), suffix=r'\b'), Keyword, 'funcname'), (words(('class', 'cclass', 'cstruct', 'obj', 'struct'), suffix=r'\b'), Keyword, 'classname'), (r'(instance|module|typeclass)\b', Keyword, 'modulename'),
(words(keywords, suffix=r'\b'), Keyword), (words(keyword_directives, suffix=r'\b'), Name.Decorator), (words(keyword_declarations, suffix=r'\b'), Keyword.Declaration), (words(keyword_types, suffix=r'\b'), Keyword.Type), (words(keyword_constants, suffix=r'\b'), Keyword.Constant),
# Operators include('operators'),
# Float Literal # -- Hex Float (r'0[xX]([0-9a-fA-F_]*\.[0-9a-fA-F_]+|[0-9a-fA-F_]+)' r'[pP][+\-]?[0-9_]+[lLfFdD]?', Number.Float), # -- DecimalFloat (r'[0-9_]+(\.[0-9_]+[eE][+\-]?[0-9_]+|' r'\.[0-9_]*|[eE][+\-]?[0-9_]+)[lLfFdD]?', Number.Float), (r'\.(0|[1-9][0-9_]*)([eE][+\-]?[0-9_]+)?[lLfFdD]?', Number.Float),
# IntegerLiteral # -- Binary (rf'0[Bb][01_]+{decimal_suffixes}', Number.Bin), # -- Octal (rf'0[0-7_]+{decimal_suffixes}', Number.Oct), # -- Hexadecimal (rf'0[xX][0-9a-fA-F_]+{decimal_suffixes}', Number.Hex), # -- Decimal (rf'(0|[1-9][0-9_]*){decimal_suffixes}', Number.Integer),
# Strings ('([rR][cC]?|[cC][rR])"""', String, 'tdqs'), ("([rR][cC]?|[cC][rR])'''", String, 'tsqs'), ('([rR][cC]?|[cC][rR])"', String, 'dqs'), ("([rR][cC]?|[cC][rR])'", String, 'sqs'), ('[cCfFqQwWuU]?"""', String, combined('stringescape', 'tdqs')), ("[cCfFqQwWuU]?'''", String, combined('stringescape', 'tsqs')), ('[cCfFqQwWuU]?"', String, combined('stringescape', 'dqs')), ("[cCfFqQwWuU]?'", String, combined('stringescape', 'sqs')),
# Punctuation (r'[\[\]{}:(),;?]', Punctuation),
# Labels (r'[a-zA-Z_]\w*:>', Name.Label),
# Identifiers (r'({})\b'.format('|'.join(name_builtins)), Name.Builtin), (r'({})\b'.format('|'.join(name_pseudo)), Name.Builtin.Pseudo), (r'[a-zA-Z_]\w*', Name), ], 'whitespace': [ (r'\s+', Whitespace),
include('comment'),
# Preprocessor (r'(#)(\s*)(if)(\s+)(0)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Whitespace, Comment.Preproc), 'if0'), (r'#', Comment.Preproc, 'macro'), ], 'operators': [ (r'({})\b'.format('|'.join(operator_words)), Operator.Word), (r'!=|==|<<|>>|\|\||&&|[-~+/*%=<>&^|.$]', Operator), ], 'comment': [ (r'//(.*?)$', Comment.Single), (r'/[*]', Comment.Multiline, 'comment2'), ], 'comment2': [ (r'[^/*]', Comment.Multiline), (r'/[*]', Comment.Multiline, '#push'), (r'[*]/', Comment.Multiline, '#pop'), (r'[/*]', Comment.Multiline), ], 'if0': [ (r'^(\s*)(#if.*?(?<!\\))(\n)', bygroups(Whitespace, Comment, Whitespace), '#push'), (r'^(\s*)(#endif.*?(?<!\\))(\n)', bygroups(Whitespace, Comment, Whitespace), '#pop'), (r'(.*?)(\n)', bygroups(Comment, Whitespace)), ], 'macro': [ include('comment'), (r'(import|include)(\s+)(<[^>]*?>)', bygroups(Comment.Preproc, Whitespace, String), '#pop'), (r'(import|include)(\s+)("[^"]*?")', bygroups(Comment.Preproc, Whitespace, String), '#pop'), (r"(import|include)(\s+)('[^']*?')", bygroups(Comment.Preproc, Whitespace, String), '#pop'), (r'[^/\n]+', Comment.Preproc), # (r'/[*](.|\n)*?[*]/', Comment), # (r'//.*?\n', Comment, '#pop'), (r'/', Comment.Preproc), (r'(?<=\\)\n', Comment.Preproc), (r'\n', Whitespace, '#pop'), ], 'funcname': [ include('whitespace'), (r'[a-zA-Z_]\w*', Name.Function, '#pop'), # anonymous functions (r'(?=\()', Text, '#pop'), ], 'classname': [ include('whitespace'), (r'[a-zA-Z_]\w*', Name.Class, '#pop'), # anonymous classes (r'(?=\{)', Text, '#pop'), ], 'modulename': [ include('whitespace'), (r'\[', Punctuation, ('modulename2', 'tvarlist')), default('modulename2'), ], 'modulename2': [ include('whitespace'), (r'([a-zA-Z_]\w*)', Name.Namespace, '#pop:2'), ], 'tvarlist': [ include('whitespace'), include('operators'), (r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), (r',', Punctuation), (r'(with|where)\b', Keyword), (r'[a-zA-Z_]\w*', Name), ], 'stringescape': [ (r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|' r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], 'strings': [ (r'%(\([a-zA-Z0-9]+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' '[hlL]?[E-GXc-giorsux%]', String.Interpol), (r'[^\\\'"%\n]+', String), # quotes, percents and backslashes must be parsed one at a time (r'[\'"\\]', String), # unhandled string formatting sign (r'%', String) # newlines are an error (use "nl" state) ], 'nl': [ (r'\n', String) ], 'dqs': [ (r'"', String, '#pop'), # included here again for raw strings (r'\\\\|\\"|\\\n', String.Escape), include('strings') ], 'sqs': [ (r"'", String, '#pop'), # included here again for raw strings (r"\\\\|\\'|\\\n", String.Escape), include('strings') ], 'tdqs': [ (r'"""', String, '#pop'), include('strings'), include('nl') ], 'tsqs': [ (r"'''", String, '#pop'), include('strings'), include('nl') ], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768""" pygments.lexers.fift ~~~~~~~~~~~~~~~~~~~~
Lexers for fift.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, includefrom pygments.token import Literal, Comment, Name, String, Number, Whitespace
__all__ = ['FiftLexer']
class FiftLexer(RegexLexer): """ For Fift source code. """
name = 'Fift' aliases = ['fift', 'fif'] filenames = ['*.fif'] url = 'https://ton-blockchain.github.io/docs/fiftbase.pdf' version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace),
include('comments'),
(r'[\.+]?\"', String, 'string'),
# numbers (r'0x[0-9a-fA-F]+', Number.Hex), (r'0b[01]+', Number.Bin), (r'-?[0-9]+("/"-?[0-9]+)?', Number.Decimal),
# slices (r'b\{[01]+\}', Literal), (r'x\{[0-9a-fA-F_]+\}', Literal),
# byte literal (r'B\{[0-9a-fA-F_]+\}', Literal),
# treat anything as word (r'\S+', Name) ],
'string': [ (r'\\.', String.Escape), (r'\"', String, '#pop'), (r'[^\"\r\n\\]+', String) ],
'comments': [ (r'//.*', Comment.Singleline), (r'/\*', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081""" pygments.lexers.floscript ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for FloScript
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['FloScriptLexer']
class FloScriptLexer(RegexLexer): """ For FloScript configuration language source code. """
name = 'FloScript' url = 'https://github.com/ioflo/ioflo' aliases = ['floscript', 'flo'] filenames = ['*.flo'] version_added = '2.4'
def innerstring_rules(ttype): return [ # the old style '%s' % (...) string formatting (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' '[hlL]?[E-GXc-giorsux%]', String.Interpol), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"%\n]+', ttype), (r'[\'"\\]', ttype), # unhandled string formatting sign (r'%', ttype), # newlines are an error (use "nl" state) ]
tokens = { 'root': [ (r'\s+', Whitespace),
(r'[]{}:(),;[]', Punctuation), (r'(\\)(\n)', bygroups(Text, Whitespace)), (r'\\', Text), (r'(to|by|with|from|per|for|cum|qua|via|as|at|in|of|on|re|is|if|be|into|' r'and|not)\b', Operator.Word), (r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator), (r'(load|init|server|logger|log|loggee|first|over|under|next|done|timeout|' r'repeat|native|benter|enter|recur|exit|precur|renter|rexit|print|put|inc|' r'copy|set|aux|rear|raze|go|let|do|bid|ready|start|stop|run|abort|use|flo|' r'give|take)\b', Name.Builtin), (r'(frame|framer|house)\b', Keyword), ('"', String, 'string'),
include('name'), include('numbers'), (r'#.+$', Comment.Single), ], 'string': [ ('[^"]+', String), ('"', String, '#pop'), ], 'numbers': [ (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float), (r'\d+[eE][+-]?[0-9]+j?', Number.Float), (r'0[0-7]+j?', Number.Oct), (r'0[bB][01]+', Number.Bin), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+j?', Number.Integer) ],
'name': [ (r'@[\w.]+', Name.Decorator), (r'[a-zA-Z_]\w*', Name), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178""" pygments.lexers.forth ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Forth language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Text, Comment, Keyword, Name, String, Number, \ Whitespace
__all__ = ['ForthLexer']
class ForthLexer(RegexLexer): """ Lexer for Forth files. """ name = 'Forth' url = 'https://www.forth.com/forth/' aliases = ['forth'] filenames = ['*.frt', '*.fs'] mimetypes = ['application/x-forth'] version_added = '2.2'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'\s+', Whitespace), # All comment types (r'\\.*?$', Comment.Single), (r'\([\s].*?\)', Comment.Single), # defining words. The next word is a new command name (r'(:|variable|constant|value|buffer:)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'worddef'), # strings are rather simple (r'([.sc]")(\s+?)', bygroups(String, Whitespace), 'stringdef'), # keywords from the various wordsets # *** Wordset BLOCK (r'(blk|block|buffer|evaluate|flush|load|save-buffers|update|' # *** Wordset BLOCK-EXT r'empty-buffers|list|refill|scr|thru|' # *** Wordset CORE r'\#s|\*\/mod|\+loop|\/mod|0<|0=|1\+|1-|2!|' r'2\*|2\/|2@|2drop|2dup|2over|2swap|>body|' r'>in|>number|>r|\?dup|abort|abort\"|abs|' r'accept|align|aligned|allot|and|base|begin|' r'bl|c!|c,|c@|cell\+|cells|char|char\+|' r'chars|constant|count|cr|create|decimal|' r'depth|do|does>|drop|dup|else|emit|environment\?|' r'evaluate|execute|exit|fill|find|fm\/mod|' r'here|hold|i|if|immediate|invert|j|key|' r'leave|literal|loop|lshift|m\*|max|min|' r'mod|move|negate|or|over|postpone|quit|' r'r>|r@|recurse|repeat|rot|rshift|s\"|s>d|' r'sign|sm\/rem|source|space|spaces|state|swap|' r'then|type|u\.|u\<|um\*|um\/mod|unloop|until|' r'variable|while|word|xor|\[char\]|\[\'\]|' r'@|!|\#|<\#|\#>|:|;|\+|-|\*|\/|,|<|>|\|1\+|1-|\.|' # *** Wordset CORE-EXT r'\.r|0<>|' r'0>|2>r|2r>|2r@|:noname|\?do|again|c\"|' r'case|compile,|endcase|endof|erase|false|' r'hex|marker|nip|of|pad|parse|pick|refill|' r'restore-input|roll|save-input|source-id|to|' r'true|tuck|u\.r|u>|unused|value|within|' r'\[compile\]|' # *** Wordset CORE-EXT-obsolescent r'\#tib|convert|expect|query|span|' r'tib|' # *** Wordset DOUBLE r'2constant|2literal|2variable|d\+|d-|' r'd\.|d\.r|d0<|d0=|d2\*|d2\/|d<|d=|d>s|' r'dabs|dmax|dmin|dnegate|m\*\/|m\+|' # *** Wordset DOUBLE-EXT r'2rot|du<|' # *** Wordset EXCEPTION r'catch|throw|' # *** Wordset EXCEPTION-EXT r'abort|abort\"|' # *** Wordset FACILITY r'at-xy|key\?|page|' # *** Wordset FACILITY-EXT r'ekey|ekey>char|ekey\?|emit\?|ms|time&date|' # *** Wordset FILE r'BIN|CLOSE-FILE|CREATE-FILE|DELETE-FILE|FILE-POSITION|' r'FILE-SIZE|INCLUDE-FILE|INCLUDED|OPEN-FILE|R\/O|' r'R\/W|READ-FILE|READ-LINE|REPOSITION-FILE|RESIZE-FILE|' r'S\"|SOURCE-ID|W/O|WRITE-FILE|WRITE-LINE|' # *** Wordset FILE-EXT r'FILE-STATUS|FLUSH-FILE|REFILL|RENAME-FILE|' # *** Wordset FLOAT r'>float|d>f|' r'f!|f\*|f\+|f-|f\/|f0<|f0=|f<|f>d|f@|' r'falign|faligned|fconstant|fdepth|fdrop|fdup|' r'fliteral|float\+|floats|floor|fmax|fmin|' r'fnegate|fover|frot|fround|fswap|fvariable|' r'represent|' # *** Wordset FLOAT-EXT r'df!|df@|dfalign|dfaligned|dfloat\+|' r'dfloats|f\*\*|f\.|fabs|facos|facosh|falog|' r'fasin|fasinh|fatan|fatan2|fatanh|fcos|fcosh|' r'fe\.|fexp|fexpm1|fln|flnp1|flog|fs\.|fsin|' r'fsincos|fsinh|fsqrt|ftan|ftanh|f~|precision|' r'set-precision|sf!|sf@|sfalign|sfaligned|sfloat\+|' r'sfloats|' # *** Wordset LOCAL r'\(local\)|to|' # *** Wordset LOCAL-EXT r'locals\||' # *** Wordset MEMORY r'allocate|free|resize|' # *** Wordset SEARCH r'definitions|find|forth-wordlist|get-current|' r'get-order|search-wordlist|set-current|set-order|' r'wordlist|' # *** Wordset SEARCH-EXT r'also|forth|only|order|previous|' # *** Wordset STRING r'-trailing|\/string|blank|cmove|cmove>|compare|' r'search|sliteral|' # *** Wordset TOOLS r'.s|dump|see|words|' # *** Wordset TOOLS-EXT r';code|' r'ahead|assembler|bye|code|cs-pick|cs-roll|' r'editor|state|\[else\]|\[if\]|\[then\]|' # *** Wordset TOOLS-EXT-obsolescent r'forget|' # Forth 2012 r'defer|defer@|defer!|action-of|begin-structure|field:|buffer:|' r'parse-name|buffer:|traverse-wordlist|n>r|nr>|2value|fvalue|' r'name>interpret|name>compile|name>string|' r'cfield:|end-structure)(?!\S)', Keyword),
# Numbers (r'(\$[0-9A-F]+)', Number.Hex), (r'(\#|%|&|\-|\+)?[0-9]+', Number.Integer), (r'(\#|%|&|\-|\+)?[0-9.]+', Keyword.Type), # amforth specific (r'(@i|!i|@e|!e|pause|noop|turnkey|sleep|' r'itype|icompare|sp@|sp!|rp@|rp!|up@|up!|' r'>a|a>|a@|a!|a@+|a@-|>b|b>|b@|b!|b@+|b@-|' r'find-name|1ms|' r'sp0|rp0|\(evaluate\)|int-trap|int!)(?!\S)', Name.Constant), # a proposal (r'(do-recognizer|r:fail|recognizer:|get-recognizers|' r'set-recognizers|r:float|r>comp|r>int|r>post|' r'r:name|r:word|r:dnum|r:num|recognizer|forth-recognizer|' r'rec:num|rec:float|rec:word)(?!\S)', Name.Decorator), # defining words. The next word is a new command name (r'(Evalue|Rvalue|Uvalue|Edefer|Rdefer|Udefer)(\s+)', bygroups(Keyword.Namespace, Text), 'worddef'),
(r'\S+', Name.Function), # Anything else is executed
], 'worddef': [ (r'\S+', Name.Class, '#pop'), ], 'stringdef': [ (r'[^"]+', String, '#pop'), ], }
def analyse_text(text): """Forth uses : COMMAND ; quite a lot in a single line, so we're trying to find that.""" if re.search('\n:[^\n]+;\n', text): return 0.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212""" pygments.lexers.fortran ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Fortran languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroups, include, words, using, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic
__all__ = ['FortranLexer', 'FortranFixedLexer']
class FortranLexer(RegexLexer): """ Lexer for FORTRAN 90 code. """ name = 'Fortran' url = 'https://fortran-lang.org/' aliases = ['fortran', 'f90'] filenames = ['*.f03', '*.f90', '*.F03', '*.F90'] mimetypes = ['text/x-fortran'] version_added = '0.10' flags = re.IGNORECASE | re.MULTILINE
# Data Types: INTEGER, REAL, COMPLEX, LOGICAL, CHARACTER and DOUBLE PRECISION # Operators: **, *, +, -, /, <, >, <=, >=, ==, /= # Logical (?): NOT, AND, OR, EQV, NEQV
# Builtins: # http://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Table-of-Intrinsic-Functions.html
tokens = { 'root': [ (r'^#.*\n', Comment.Preproc), (r'!.*\n', Comment), include('strings'), include('core'), (r'[a-z][\w$]*', Name), include('nums'), (r'[\s]+', Text.Whitespace), ], 'core': [ # Statements
(r'\b(DO)(\s+)(CONCURRENT)\b', bygroups(Keyword, Text.Whitespace, Keyword)), (r'\b(GO)(\s*)(TO)\b', bygroups(Keyword, Text.Whitespace, Keyword)),
(words(( 'ABSTRACT', 'ACCEPT', 'ALL', 'ALLSTOP', 'ALLOCATABLE', 'ALLOCATE', 'ARRAY', 'ASSIGN', 'ASSOCIATE', 'ASYNCHRONOUS', 'BACKSPACE', 'BIND', 'BLOCK', 'BLOCKDATA', 'BYTE', 'CALL', 'CASE', 'CLASS', 'CLOSE', 'CODIMENSION', 'COMMON', 'CONTIGUOUS', 'CONTAINS', 'CONTINUE', 'CRITICAL', 'CYCLE', 'DATA', 'DEALLOCATE', 'DECODE', 'DEFERRED', 'DIMENSION', 'DO', 'ELEMENTAL', 'ELSE', 'ELSEIF', 'ENCODE', 'END', 'ENDASSOCIATE', 'ENDBLOCK', 'ENDDO', 'ENDENUM', 'ENDFORALL', 'ENDFUNCTION', 'ENDIF', 'ENDINTERFACE', 'ENDMODULE', 'ENDPROGRAM', 'ENDSELECT', 'ENDSUBMODULE', 'ENDSUBROUTINE', 'ENDTYPE', 'ENDWHERE', 'ENTRY', 'ENUM', 'ENUMERATOR', 'EQUIVALENCE', 'ERROR STOP', 'EXIT', 'EXTENDS', 'EXTERNAL', 'EXTRINSIC', 'FILE', 'FINAL', 'FORALL', 'FORMAT', 'FUNCTION', 'GENERIC', 'IF', 'IMAGES', 'IMPLICIT', 'IMPORT', 'IMPURE', 'INCLUDE', 'INQUIRE', 'INTENT', 'INTERFACE', 'INTRINSIC', 'IS', 'LOCK', 'MEMORY', 'MODULE', 'NAMELIST', 'NULLIFY', 'NONE', 'NON_INTRINSIC', 'NON_OVERRIDABLE', 'NOPASS', 'ONLY', 'OPEN', 'OPTIONAL', 'OPTIONS', 'PARAMETER', 'PASS', 'PAUSE', 'POINTER', 'PRINT', 'PRIVATE', 'PROGRAM', 'PROCEDURE', 'PROTECTED', 'PUBLIC', 'PURE', 'READ', 'RECURSIVE', 'RESULT', 'RETURN', 'REWIND', 'SAVE', 'SELECT', 'SEQUENCE', 'STOP', 'SUBMODULE', 'SUBROUTINE', 'SYNC', 'SYNCALL', 'SYNCIMAGES', 'SYNCMEMORY', 'TARGET', 'THEN', 'TYPE', 'UNLOCK', 'USE', 'VALUE', 'VOLATILE', 'WHERE', 'WRITE', 'WHILE'), prefix=r'\b', suffix=r'\s*\b'), Keyword),
# Data Types (words(( 'CHARACTER', 'COMPLEX', 'DOUBLE PRECISION', 'DOUBLE COMPLEX', 'INTEGER', 'LOGICAL', 'REAL', 'C_INT', 'C_SHORT', 'C_LONG', 'C_LONG_LONG', 'C_SIGNED_CHAR', 'C_SIZE_T', 'C_INT8_T', 'C_INT16_T', 'C_INT32_T', 'C_INT64_T', 'C_INT_LEAST8_T', 'C_INT_LEAST16_T', 'C_INT_LEAST32_T', 'C_INT_LEAST64_T', 'C_INT_FAST8_T', 'C_INT_FAST16_T', 'C_INT_FAST32_T', 'C_INT_FAST64_T', 'C_INTMAX_T', 'C_INTPTR_T', 'C_FLOAT', 'C_DOUBLE', 'C_LONG_DOUBLE', 'C_FLOAT_COMPLEX', 'C_DOUBLE_COMPLEX', 'C_LONG_DOUBLE_COMPLEX', 'C_BOOL', 'C_CHAR', 'C_PTR', 'C_FUNPTR'), prefix=r'\b', suffix=r'\s*\b'), Keyword.Type),
# Operators (r'(\*\*|\*|\+|-|\/|<|>|<=|>=|==|\/=|=)', Operator),
(r'(::)', Keyword.Declaration),
(r'[()\[\],:&%;.]', Punctuation), # Intrinsics (words(( 'Abort', 'Abs', 'Access', 'AChar', 'ACos', 'ACosH', 'AdjustL', 'AdjustR', 'AImag', 'AInt', 'Alarm', 'All', 'Allocated', 'ALog', 'AMax', 'AMin', 'AMod', 'And', 'ANInt', 'Any', 'ASin', 'ASinH', 'Associated', 'ATan', 'ATanH', 'Atomic_Define', 'Atomic_Ref', 'BesJ', 'BesJN', 'Bessel_J0', 'Bessel_J1', 'Bessel_JN', 'Bessel_Y0', 'Bessel_Y1', 'Bessel_YN', 'BesY', 'BesYN', 'BGE', 'BGT', 'BLE', 'BLT', 'Bit_Size', 'BTest', 'CAbs', 'CCos', 'Ceiling', 'CExp', 'Char', 'ChDir', 'ChMod', 'CLog', 'Cmplx', 'Command_Argument_Count', 'Complex', 'Conjg', 'Cos', 'CosH', 'Count', 'CPU_Time', 'CShift', 'CSin', 'CSqRt', 'CTime', 'C_Loc', 'C_Associated', 'C_Null_Ptr', 'C_Null_Funptr', 'C_F_Pointer', 'C_F_ProcPointer', 'C_Null_Char', 'C_Alert', 'C_Backspace', 'C_Form_Feed', 'C_FunLoc', 'C_Sizeof', 'C_New_Line', 'C_Carriage_Return', 'C_Horizontal_Tab', 'C_Vertical_Tab', 'DAbs', 'DACos', 'DASin', 'DATan', 'Date_and_Time', 'DbesJ', 'DbesJN', 'DbesY', 'DbesYN', 'Dble', 'DCos', 'DCosH', 'DDiM', 'DErF', 'DErFC', 'DExp', 'Digits', 'DiM', 'DInt', 'DLog', 'DMax', 'DMin', 'DMod', 'DNInt', 'Dot_Product', 'DProd', 'DSign', 'DSinH', 'DShiftL', 'DShiftR', 'DSin', 'DSqRt', 'DTanH', 'DTan', 'DTime', 'EOShift', 'Epsilon', 'ErF', 'ErFC', 'ErFC_Scaled', 'ETime', 'Execute_Command_Line', 'Exit', 'Exp', 'Exponent', 'Extends_Type_Of', 'FDate', 'FGet', 'FGetC', 'FindLoc', 'Float', 'Floor', 'Flush', 'FNum', 'FPutC', 'FPut', 'Fraction', 'FSeek', 'FStat', 'FTell', 'Gamma', 'GError', 'GetArg', 'Get_Command', 'Get_Command_Argument', 'Get_Environment_Variable', 'GetCWD', 'GetEnv', 'GetGId', 'GetLog', 'GetPId', 'GetUId', 'GMTime', 'HostNm', 'Huge', 'Hypot', 'IAbs', 'IAChar', 'IAll', 'IAnd', 'IAny', 'IArgC', 'IBClr', 'IBits', 'IBSet', 'IChar', 'IDate', 'IDiM', 'IDInt', 'IDNInt', 'IEOr', 'IErrNo', 'IFix', 'Imag', 'ImagPart', 'Image_Index', 'Index', 'Int', 'IOr', 'IParity', 'IRand', 'IsaTty', 'IShft', 'IShftC', 'ISign', 'Iso_C_Binding', 'Is_Contiguous', 'Is_Iostat_End', 'Is_Iostat_Eor', 'ITime', 'Kill', 'Kind', 'LBound', 'LCoBound', 'Len', 'Len_Trim', 'LGe', 'LGt', 'Link', 'LLe', 'LLt', 'LnBlnk', 'Loc', 'Log', 'Log_Gamma', 'Logical', 'Long', 'LShift', 'LStat', 'LTime', 'MaskL', 'MaskR', 'MatMul', 'Max', 'MaxExponent', 'MaxLoc', 'MaxVal', 'MClock', 'Merge', 'Merge_Bits', 'Move_Alloc', 'Min', 'MinExponent', 'MinLoc', 'MinVal', 'Mod', 'Modulo', 'MvBits', 'Nearest', 'New_Line', 'NInt', 'Norm2', 'Not', 'Null', 'Num_Images', 'Or', 'Pack', 'Parity', 'PError', 'Precision', 'Present', 'Product', 'Radix', 'Rand', 'Random_Number', 'Random_Seed', 'Range', 'Real', 'RealPart', 'Rename', 'Repeat', 'Reshape', 'RRSpacing', 'RShift', 'Same_Type_As', 'Scale', 'Scan', 'Second', 'Selected_Char_Kind', 'Selected_Int_Kind', 'Selected_Real_Kind', 'Set_Exponent', 'Shape', 'ShiftA', 'ShiftL', 'ShiftR', 'Short', 'Sign', 'Signal', 'SinH', 'Sin', 'Sleep', 'Sngl', 'Spacing', 'Spread', 'SqRt', 'SRand', 'Stat', 'Storage_Size', 'Sum', 'SymLnk', 'System', 'System_Clock', 'Tan', 'TanH', 'Time', 'This_Image', 'Tiny', 'TrailZ', 'Transfer', 'Transpose', 'Trim', 'TtyNam', 'UBound', 'UCoBound', 'UMask', 'Unlink', 'Unpack', 'Verify', 'XOr', 'ZAbs', 'ZCos', 'ZExp', 'ZLog', 'ZSin', 'ZSqRt'), prefix=r'\b', suffix=r'\s*\b'), Name.Builtin),
# Booleans (r'\.(true|false)\.', Name.Builtin), # Comparing Operators (r'\.(eq|ne|lt|le|gt|ge|not|and|or|eqv|neqv)\.', Operator.Word), ],
'strings': [ (r'"(\\[0-7]+|\\[^0-7]|[^"\\])*"', String.Double), (r"'(\\[0-7]+|\\[^0-7]|[^'\\])*'", String.Single), ],
'nums': [ (r'\d+(?![.e])(_([1-9]|[a-z]\w*))?', Number.Integer), (r'[+-]?\d*\.\d+([ed][-+]?\d+)?(_([1-9]|[a-z]\w*))?', Number.Float), (r'[+-]?\d+\.\d*([ed][-+]?\d+)?(_([1-9]|[a-z]\w*))?', Number.Float), (r'[+-]?\d+(\.\d*)?[ed][-+]?\d+(_([1-9]|[a-z]\w*))?', Number.Float), ], }
class FortranFixedLexer(RegexLexer): """ Lexer for fixed format Fortran. """ name = 'FortranFixed' aliases = ['fortranfixed'] filenames = ['*.f', '*.F'] url = 'https://fortran-lang.org/' version_added = '2.1'
flags = re.IGNORECASE
def _lex_fortran(self, match, ctx=None): """Lex a line just as free form fortran without line break.""" lexer = FortranLexer() text = match.group(0) + "\n" for index, token, value in lexer.get_tokens_unprocessed(text): value = value.replace('\n', '') if value != '': yield index, token, value
tokens = { 'root': [ (r'[C*].*\n', Comment), (r'#.*\n', Comment.Preproc), (r' {0,4}!.*\n', Comment), (r'(.{5})', Name.Label, 'cont-char'), (r'.*\n', using(FortranLexer)), ], 'cont-char': [ (' ', Text, 'code'), ('0', Comment, 'code'), ('.', Generic.Strong, 'code'), ], 'code': [ (r'(.{66})(.*)(\n)', bygroups(_lex_fortran, Comment, Text.Whitespace), 'root'), (r'(.*)(\n)', bygroups(_lex_fortran, Text.Whitespace), 'root'), default('root'), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427""" pygments.lexers.foxpro ~~~~~~~~~~~~~~~~~~~~~~
Simple lexer for Microsoft Visual FoxPro source code.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexerfrom pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ Name, String
__all__ = ['FoxProLexer']
class FoxProLexer(RegexLexer): """Lexer for Microsoft Visual FoxPro language.
FoxPro syntax allows to shorten all keywords and function names to 4 characters. Shortened forms are not recognized by this lexer. """
name = 'FoxPro' aliases = ['foxpro', 'vfp', 'clipper', 'xbase'] filenames = ['*.PRG', '*.prg'] version_added = '1.6' mimetype = [] url = 'https://learn.microsoft.com/en-us/previous-versions/visualstudio/foxpro'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r';\s*\n', Punctuation), # consume newline (r'(^|\n)\s*', Text, 'newline'),
# Square brackets may be used for array indices # and for string literal. Look for arrays # before matching string literals. (r'(?<=\w)\[[0-9, ]+\]', Text), (r'\'[^\'\n]*\'|"[^"\n]*"|\[[^]*]\]', String), (r'(^\s*\*|&&|&&).*?\n', Comment.Single),
(r'(ABS|ACLASS|ACOPY|ACOS|ADATABASES|ADBOBJECTS|ADDBS|' r'ADDPROPERTY|ADEL|ADIR|ADLLS|ADOCKSTATE|AELEMENT|AERROR|' r'AEVENTS|AFIELDS|AFONT|AGETCLASS|AGETFILEVERSION|AINS|' r'AINSTANCE|ALANGUAGE|ALEN|ALIAS|ALINES|ALLTRIM|' r'AMEMBERS|AMOUSEOBJ|ANETRESOURCES|APRINTERS|APROCINFO|' r'ASC|ASCAN|ASELOBJ|ASESSIONS|ASIN|ASORT|ASQLHANDLES|' r'ASTACKINFO|ASUBSCRIPT|AT|AT_C|ATAGINFO|ATAN|ATC|ATCC|' r'ATCLINE|ATLINE|ATN2|AUSED|AVCXCLASSES|BAR|BARCOUNT|' r'BARPROMPT|BETWEEN|BINDEVENT|BINTOC|BITAND|BITCLEAR|' r'BITLSHIFT|BITNOT|BITOR|BITRSHIFT|BITSET|BITTEST|BITXOR|' r'BOF|CANDIDATE|CAPSLOCK|CAST|CDOW|CDX|CEILING|CHR|CHRSAW|' r'CHRTRAN|CHRTRANC|CLEARRESULTSET|CMONTH|CNTBAR|CNTPAD|COL|' r'COM|Functions|COMARRAY|COMCLASSINFO|COMPOBJ|COMPROP|' r'COMRETURNERROR|COS|CPCONVERT|CPCURRENT|CPDBF|CREATEBINARY|' r'CREATEOBJECT|CREATEOBJECTEX|CREATEOFFLINE|CTOBIN|CTOD|' r'CTOT|CURDIR|CURSORGETPROP|CURSORSETPROP|CURSORTOXML|' r'CURVAL|DATE|DATETIME|DAY|DBC|DBF|DBGETPROP|DBSETPROP|' r'DBUSED|DDEAbortTrans|DDEAdvise|DDEEnabled|DDEExecute|' r'DDEInitiate|DDELastError|DDEPoke|DDERequest|DDESetOption|' r'DDESetService|DDESetTopic|DDETerminate|DEFAULTEXT|' r'DELETED|DESCENDING|DIFFERENCE|DIRECTORY|DISKSPACE|' r'DisplayPath|DMY|DODEFAULT|DOW|DRIVETYPE|DROPOFFLINE|' r'DTOC|DTOR|DTOS|DTOT|EDITSOURCE|EMPTY|EOF|ERROR|EVAL(UATE)?|' r'EVENTHANDLER|EVL|EXECSCRIPT|EXP|FCHSIZE|FCLOSE|FCOUNT|' r'FCREATE|FDATE|FEOF|FERROR|FFLUSH|FGETS|FIELD|FILE|' r'FILETOSTR|FILTER|FKLABEL|FKMAX|FLDLIST|FLOCK|FLOOR|' r'FONTMETRIC|FOPEN|FOR|FORCEEXT|FORCEPATH|FOUND|FPUTS|' r'FREAD|FSEEK|FSIZE|FTIME|FULLPATH|FV|FWRITE|' r'GETAUTOINCVALUE|GETBAR|GETCOLOR|GETCP|GETDIR|GETENV|' r'GETFILE|GETFLDSTATE|GETFONT|GETINTERFACE|' r'GETNEXTMODIFIED|GETOBJECT|GETPAD|GETPEM|GETPICT|' r'GETPRINTER|GETRESULTSET|GETWORDCOUNT|GETWORDNUM|' r'GETCURSORADAPTER|GOMONTH|HEADER|HOME|HOUR|ICASE|' r'IDXCOLLATE|IIF|IMESTATUS|INDBC|INDEXSEEK|INKEY|INLIST|' r'INPUTBOX|INSMODE|INT|ISALPHA|ISBLANK|ISCOLOR|ISDIGIT|' r'ISEXCLUSIVE|ISFLOCKED|ISLEADBYTE|ISLOWER|ISMEMOFETCHED|' r'ISMOUSE|ISNULL|ISPEN|ISREADONLY|ISRLOCKED|' r'ISTRANSACTABLE|ISUPPER|JUSTDRIVE|JUSTEXT|JUSTFNAME|' r'JUSTPATH|JUSTSTEM|KEY|KEYMATCH|LASTKEY|LEFT|LEFTC|LEN|' r'LENC|LIKE|LIKEC|LINENO|LOADPICTURE|LOCFILE|LOCK|LOG|' r'LOG10|LOOKUP|LOWER|LTRIM|LUPDATE|MAKETRANSACTABLE|MAX|' r'MCOL|MDOWN|MDX|MDY|MEMLINES|MEMORY|MENU|MESSAGE|' r'MESSAGEBOX|MIN|MINUTE|MLINE|MOD|MONTH|MRKBAR|MRKPAD|' r'MROW|MTON|MWINDOW|NDX|NEWOBJECT|NORMALIZE|NTOM|NUMLOCK|' r'NVL|OBJNUM|OBJTOCLIENT|OBJVAR|OCCURS|OEMTOANSI|OLDVAL|' r'ON|ORDER|OS|PAD|PADL|PARAMETERS|PAYMENT|PCOL|PCOUNT|' r'PEMSTATUS|PI|POPUP|PRIMARY|PRINTSTATUS|PRMBAR|PRMPAD|' r'PROGRAM|PROMPT|PROPER|PROW|PRTINFO|PUTFILE|PV|QUARTER|' r'RAISEEVENT|RAND|RAT|RATC|RATLINE|RDLEVEL|READKEY|RECCOUNT|' r'RECNO|RECSIZE|REFRESH|RELATION|REPLICATE|REQUERY|RGB|' r'RGBSCHEME|RIGHT|RIGHTC|RLOCK|ROUND|ROW|RTOD|RTRIM|' r'SAVEPICTURE|SCHEME|SCOLS|SEC|SECONDS|SEEK|SELECT|SET|' r'SETFLDSTATE|SETRESULTSET|SIGN|SIN|SKPBAR|SKPPAD|SOUNDEX|' r'SPACE|SQLCANCEL|SQLCOLUMNS|SQLCOMMIT|SQLCONNECT|' r'SQLDISCONNECT|SQLEXEC|SQLGETPROP|SQLIDLEDISCONNECT|' r'SQLMORERESULTS|SQLPREPARE|SQLROLLBACK|SQLSETPROP|' r'SQLSTRINGCONNECT|SQLTABLES|SQRT|SROWS|STR|STRCONV|' r'STREXTRACT|STRTOFILE|STRTRAN|STUFF|STUFFC|SUBSTR|' r'SUBSTRC|SYS|SYSMETRIC|TABLEREVERT|TABLEUPDATE|TAG|' r'TAGCOUNT|TAGNO|TAN|TARGET|TEXTMERGE|TIME|TRANSFORM|' r'TRIM|TTOC|TTOD|TXNLEVEL|TXTWIDTH|TYPE|UNBINDEVENTS|' r'UNIQUE|UPDATED|UPPER|USED|VAL|VARREAD|VARTYPE|VERSION|' r'WBORDER|WCHILD|WCOLS|WDOCKABLE|WEEK|WEXIST|WFONT|WLAST|' r'WLCOL|WLROW|WMAXIMUM|WMINIMUM|WONTOP|WOUTPUT|WPARENT|' r'WREAD|WROWS|WTITLE|WVISIBLE|XMLTOCURSOR|XMLUPDATEGRAM|' r'YEAR)(?=\s*\()', Name.Function),
(r'_ALIGNMENT|_ASCIICOLS|_ASCIIROWS|_ASSIST|_BEAUTIFY|_BOX|' r'_BROWSER|_BUILDER|_CALCMEM|_CALCVALUE|_CLIPTEXT|_CONVERTER|' r'_COVERAGE|_CUROBJ|_DBLCLICK|_DIARYDATE|_DOS|_FOXDOC|_FOXREF|' r'_GALLERY|_GENGRAPH|_GENHTML|_GENMENU|_GENPD|_GENSCRN|' r'_GENXTAB|_GETEXPR|_INCLUDE|_INCSEEK|_INDENT|_LMARGIN|_MAC|' r'_MENUDESIGNER|_MLINE|_PADVANCE|_PAGENO|_PAGETOTAL|_PBPAGE|' r'_PCOLNO|_PCOPIES|_PDRIVER|_PDSETUP|_PECODE|_PEJECT|_PEPAGE|' r'_PLENGTH|_PLINENO|_PLOFFSET|_PPITCH|_PQUALITY|_PRETEXT|' r'_PSCODE|_PSPACING|_PWAIT|_RMARGIN|_REPORTBUILDER|' r'_REPORTOUTPUT|_REPORTPREVIEW|_SAMPLES|_SCCTEXT|_SCREEN|' r'_SHELL|_SPELLCHK|_STARTUP|_TABS|_TALLY|_TASKPANE|_TEXT|' r'_THROTTLE|_TOOLBOX|_TOOLTIPTIMEOUT|_TRANSPORT|_TRIGGERLEVEL|' r'_UNIX|_VFP|_WINDOWS|_WIZARD|_WRAP', Keyword.Pseudo),
(r'THISFORMSET|THISFORM|THIS', Name.Builtin),
(r'Application|CheckBox|Collection|Column|ComboBox|' r'CommandButton|CommandGroup|Container|Control|CursorAdapter|' r'Cursor|Custom|DataEnvironment|DataObject|EditBox|' r'Empty|Exception|Fields|Files|File|FormSet|Form|FoxCode|' r'Grid|Header|Hyperlink|Image|Label|Line|ListBox|Objects|' r'OptionButton|OptionGroup|PageFrame|Page|ProjectHook|Projects|' r'Project|Relation|ReportListener|Separator|Servers|Server|' r'Session|Shape|Spinner|Tables|TextBox|Timer|ToolBar|' r'XMLAdapter|XMLField|XMLTable', Name.Class),
(r'm\.[a-z_]\w*', Name.Variable), (r'\.(F|T|AND|OR|NOT|NULL)\.|\b(AND|OR|NOT|NULL)\b', Operator.Word),
(r'\.(ActiveColumn|ActiveControl|ActiveForm|ActivePage|' r'ActiveProject|ActiveRow|AddLineFeeds|ADOCodePage|Alias|' r'Alignment|Align|AllowAddNew|AllowAutoColumnFit|' r'AllowCellSelection|AllowDelete|AllowHeaderSizing|' r'AllowInsert|AllowModalMessages|AllowOutput|AllowRowSizing|' r'AllowSimultaneousFetch|AllowTabs|AllowUpdate|' r'AlwaysOnBottom|AlwaysOnTop|Anchor|Application|' r'AutoActivate|AutoCenter|AutoCloseTables|AutoComplete|' r'AutoCompSource|AutoCompTable|AutoHideScrollBar|' r'AutoIncrement|AutoOpenTables|AutoRelease|AutoSize|' r'AutoVerbMenu|AutoYield|BackColor|ForeColor|BackStyle|' r'BaseClass|BatchUpdateCount|BindControls|BorderColor|' r'BorderStyle|BorderWidth|BoundColumn|BoundTo|Bound|' r'BreakOnError|BufferModeOverride|BufferMode|' r'BuildDateTime|ButtonCount|Buttons|Cancel|Caption|' r'Centered|Century|ChildAlias|ChildOrder|ChildTable|' r'ClassLibrary|Class|ClipControls|Closable|CLSID|CodePage|' r'ColorScheme|ColorSource|ColumnCount|ColumnLines|' r'ColumnOrder|Columns|ColumnWidths|CommandClauses|' r'Comment|CompareMemo|ConflictCheckCmd|ConflictCheckType|' r'ContinuousScroll|ControlBox|ControlCount|Controls|' r'ControlSource|ConversionFunc|Count|CurrentControl|' r'CurrentDataSession|CurrentPass|CurrentX|CurrentY|' r'CursorSchema|CursorSource|CursorStatus|Curvature|' r'Database|DataSessionID|DataSession|DataSourceType|' r'DataSource|DataType|DateFormat|DateMark|Debug|' r'DeclareXMLPrefix|DEClassLibrary|DEClass|DefaultFilePath|' r'Default|DefOLELCID|DeleteCmdDataSourceType|DeleteCmdDataSource|' r'DeleteCmd|DeleteMark|Description|Desktop|' r'Details|DisabledBackColor|DisabledForeColor|' r'DisabledItemBackColor|DisabledItemForeColor|' r'DisabledPicture|DisableEncode|DisplayCount|' r'DisplayValue|Dockable|Docked|DockPosition|' r'DocumentFile|DownPicture|DragIcon|DragMode|DrawMode|' r'DrawStyle|DrawWidth|DynamicAlignment|DynamicBackColor|' r'DynamicForeColor|DynamicCurrentControl|DynamicFontBold|' r'DynamicFontItalic|DynamicFontStrikethru|' r'DynamicFontUnderline|DynamicFontName|DynamicFontOutline|' r'DynamicFontShadow|DynamicFontSize|DynamicInputMask|' r'DynamicLineHeight|EditorOptions|Enabled|' r'EnableHyperlinks|Encrypted|ErrorNo|Exclude|Exclusive|' r'FetchAsNeeded|FetchMemoCmdList|FetchMemoDataSourceType|' r'FetchMemoDataSource|FetchMemo|FetchSize|' r'FileClassLibrary|FileClass|FillColor|FillStyle|Filter|' r'FirstElement|FirstNestedTable|Flags|FontBold|FontItalic|' r'FontStrikethru|FontUnderline|FontCharSet|FontCondense|' r'FontExtend|FontName|FontOutline|FontShadow|FontSize|' r'ForceCloseTag|Format|FormCount|FormattedOutput|Forms|' r'FractionDigits|FRXDataSession|FullName|GDIPlusGraphics|' r'GridLineColor|GridLines|GridLineWidth|HalfHeightCaption|' r'HeaderClassLibrary|HeaderClass|HeaderHeight|Height|' r'HelpContextID|HideSelection|HighlightBackColor|' r'HighlightForeColor|HighlightStyle|HighlightRowLineWidth|' r'HighlightRow|Highlight|HomeDir|Hours|HostName|' r'HScrollSmallChange|hWnd|Icon|IncrementalSearch|Increment|' r'InitialSelectedAlias|InputMask|InsertCmdDataSourceType|' r'InsertCmdDataSource|InsertCmdRefreshCmd|' r'InsertCmdRefreshFieldList|InsertCmdRefreshKeyFieldList|' r'InsertCmd|Instancing|IntegralHeight|' r'Interval|IMEMode|IsAttribute|IsBase64|IsBinary|IsNull|' r'IsDiffGram|IsLoaded|ItemBackColor,|ItemData|ItemIDData|' r'ItemTips|IXMLDOMElement|KeyboardHighValue|KeyboardLowValue|' r'Keyfield|KeyFieldList|KeyPreview|KeySort|LanguageOptions|' r'LeftColumn|Left|LineContents|LineNo|LineSlant|LinkMaster|' r'ListCount|ListenerType|ListIndex|ListItemID|ListItem|' r'List|LockColumnsLeft|LockColumns|LockScreen|MacDesktop|' r'MainFile|MapN19_4ToCurrency|MapBinary|MapVarchar|Margin|' r'MaxButton|MaxHeight|MaxLeft|MaxLength|MaxRecords|MaxTop|' r'MaxWidth|MDIForm|MemberClassLibrary|MemberClass|' r'MemoWindow|Message|MinButton|MinHeight|MinWidth|' r'MouseIcon|MousePointer|Movable|MoverBars|MultiSelect|' r'Name|NestedInto|NewIndex|NewItemID|NextSiblingTable|' r'NoCpTrans|NoDataOnLoad|NoData|NullDisplay|' r'NumberOfElements|Object|OLEClass|OLEDragMode|' r'OLEDragPicture|OLEDropEffects|OLEDropHasData|' r'OLEDropMode|OLEDropTextInsertion|OLELCID|' r'OLERequestPendingTimeout|OLEServerBusyRaiseError|' r'OLEServerBusyTimeout|OLETypeAllowed|OneToMany|' r'OpenViews|OpenWindow|Optimize|OrderDirection|Order|' r'OutputPageCount|OutputType|PageCount|PageHeight|' r'PageNo|PageOrder|Pages|PageTotal|PageWidth|' r'PanelLink|Panel|ParentAlias|ParentClass|ParentTable|' r'Parent|Partition|PasswordChar|PictureMargin|' r'PicturePosition|PictureSpacing|PictureSelectionDisplay|' r'PictureVal|Picture|Prepared|' r'PolyPoints|PreserveWhiteSpace|PreviewContainer|' r'PrintJobName|Procedure|PROCESSID|ProgID|ProjectHookClass|' r'ProjectHookLibrary|ProjectHook|QuietMode|' r'ReadCycle|ReadLock|ReadMouse|ReadObject|ReadOnly|' r'ReadSave|ReadTimeout|RecordMark|RecordSourceType|' r'RecordSource|RefreshAlias|' r'RefreshCmdDataSourceType|RefreshCmdDataSource|RefreshCmd|' r'RefreshIgnoreFieldList|RefreshTimeStamp|RelationalExpr|' r'RelativeColumn|RelativeRow|ReleaseType|Resizable|' r'RespectCursorCP|RespectNesting|RightToLeft|RotateFlip|' r'Rotation|RowColChange|RowHeight|RowSourceType|' r'RowSource|ScaleMode|SCCProvider|SCCStatus|ScrollBars|' r'Seconds|SelectCmd|SelectedID|' r'SelectedItemBackColor|SelectedItemForeColor|Selected|' r'SelectionNamespaces|SelectOnEntry|SelLength|SelStart|' r'SelText|SendGDIPlusImage|SendUpdates|ServerClassLibrary|' r'ServerClass|ServerHelpFile|ServerName|' r'ServerProject|ShowTips|ShowInTaskbar|ShowWindow|' r'Sizable|SizeBox|SOM|Sorted|Sparse|SpecialEffect|' r'SpinnerHighValue|SpinnerLowValue|SplitBar|StackLevel|' r'StartMode|StatusBarText|StatusBar|Stretch|StrictDateEntry|' r'Style|TabIndex|Tables|TabOrientation|Tabs|TabStop|' r'TabStretch|TabStyle|Tag|TerminateRead|Text|Themes|' r'ThreadID|TimestampFieldList|TitleBar|ToolTipText|' r'TopIndex|TopItemID|Top|TwoPassProcess|TypeLibCLSID|' r'TypeLibDesc|TypeLibName|Type|Unicode|UpdatableFieldList|' r'UpdateCmdDataSourceType|UpdateCmdDataSource|' r'UpdateCmdRefreshCmd|UpdateCmdRefreshFieldList|' r'UpdateCmdRefreshKeyFieldList|UpdateCmd|' r'UpdateGramSchemaLocation|UpdateGram|UpdateNameList|UpdateType|' r'UseCodePage|UseCursorSchema|UseDeDataSource|UseMemoSize|' r'UserValue|UseTransactions|UTF8Encoded|Value|VersionComments|' r'VersionCompany|VersionCopyright|VersionDescription|' r'VersionNumber|VersionProduct|VersionTrademarks|Version|' r'VFPXMLProgID|ViewPortHeight|ViewPortLeft|' r'ViewPortTop|ViewPortWidth|VScrollSmallChange|View|Visible|' r'VisualEffect|WhatsThisButton|WhatsThisHelpID|WhatsThisHelp|' r'WhereType|Width|WindowList|WindowState|WindowType|WordWrap|' r'WrapCharInCDATA|WrapInCDATA|WrapMemoInCDATA|XMLAdapter|' r'XMLConstraints|XMLNameIsXPath|XMLNamespace|XMLName|' r'XMLPrefix|XMLSchemaLocation|XMLTable|XMLType|' r'XSDfractionDigits|XSDmaxLength|XSDtotalDigits|' r'XSDtype|ZoomBox)', Name.Attribute),
(r'\.(ActivateCell|AddColumn|AddItem|AddListItem|AddObject|' r'AddProperty|AddTableSchema|AddToSCC|Add|' r'ApplyDiffgram|Attach|AutoFit|AutoOpen|Box|Build|' r'CancelReport|ChangesToCursor|CheckIn|CheckOut|Circle|' r'CleanUp|ClearData|ClearStatus|Clear|CloneObject|CloseTables|' r'Close|Cls|CursorAttach|CursorDetach|CursorFill|' r'CursorRefresh|DataToClip|DelayedMemoFetch|DeleteColumn|' r'Dock|DoMessage|DoScroll|DoStatus|DoVerb|Drag|Draw|Eval|' r'GetData|GetDockState|GetFormat|GetKey|GetLatestVersion|' r'GetPageHeight|GetPageWidth|Help|Hide|IncludePageInOutput|' r'IndexToItemID|ItemIDToIndex|Item|LoadXML|Line|Modify|' r'MoveItem|Move|Nest|OLEDrag|OnPreviewClose|OutputPage|' r'Point|Print|PSet|Quit|ReadExpression|ReadMethod|' r'RecordRefresh|Refresh|ReleaseXML|Release|RemoveFromSCC|' r'RemoveItem|RemoveListItem|RemoveObject|Remove|' r'Render|Requery|RequestData|ResetToDefault|Reset|Run|' r'SaveAsClass|SaveAs|SetAll|SetData|SetFocus|SetFormat|' r'SetMain|SetVar|SetViewPort|ShowWhatsThis|Show|' r'SupportsListenerType|TextHeight|TextWidth|ToCursor|' r'ToXML|UndoCheckOut|Unnest|UpdateStatus|WhatsThisMode|' r'WriteExpression|WriteMethod|ZOrder)', Name.Function),
(r'\.(Activate|AdjustObjectSize|AfterBand|AfterBuild|' r'AfterCloseTables|AfterCursorAttach|AfterCursorClose|' r'AfterCursorDetach|AfterCursorFill|AfterCursorRefresh|' r'AfterCursorUpdate|AfterDelete|AfterInsert|' r'AfterRecordRefresh|AfterUpdate|AfterDock|AfterReport|' r'AfterRowColChange|BeforeBand|BeforeCursorAttach|' r'BeforeCursorClose|BeforeCursorDetach|BeforeCursorFill|' r'BeforeCursorRefresh|BeforeCursorUpdate|BeforeDelete|' r'BeforeInsert|BeforeDock|BeforeOpenTables|' r'BeforeRecordRefresh|BeforeReport|BeforeRowColChange|' r'BeforeUpdate|Click|dbc_Activate|dbc_AfterAddTable|' r'dbc_AfterAppendProc|dbc_AfterCloseTable|dbc_AfterCopyProc|' r'dbc_AfterCreateConnection|dbc_AfterCreateOffline|' r'dbc_AfterCreateTable|dbc_AfterCreateView|dbc_AfterDBGetProp|' r'dbc_AfterDBSetProp|dbc_AfterDeleteConnection|' r'dbc_AfterDropOffline|dbc_AfterDropTable|' r'dbc_AfterModifyConnection|dbc_AfterModifyProc|' r'dbc_AfterModifyTable|dbc_AfterModifyView|dbc_AfterOpenTable|' r'dbc_AfterRemoveTable|dbc_AfterRenameConnection|' r'dbc_AfterRenameTable|dbc_AfterRenameView|' r'dbc_AfterValidateData|dbc_BeforeAddTable|' r'dbc_BeforeAppendProc|dbc_BeforeCloseTable|' r'dbc_BeforeCopyProc|dbc_BeforeCreateConnection|' r'dbc_BeforeCreateOffline|dbc_BeforeCreateTable|' r'dbc_BeforeCreateView|dbc_BeforeDBGetProp|' r'dbc_BeforeDBSetProp|dbc_BeforeDeleteConnection|' r'dbc_BeforeDropOffline|dbc_BeforeDropTable|' r'dbc_BeforeModifyConnection|dbc_BeforeModifyProc|' r'dbc_BeforeModifyTable|dbc_BeforeModifyView|' r'dbc_BeforeOpenTable|dbc_BeforeRemoveTable|' r'dbc_BeforeRenameConnection|dbc_BeforeRenameTable|' r'dbc_BeforeRenameView|dbc_BeforeValidateData|' r'dbc_CloseData|dbc_Deactivate|dbc_ModifyData|dbc_OpenData|' r'dbc_PackData|DblClick|Deactivate|Deleted|Destroy|DoCmd|' r'DownClick|DragDrop|DragOver|DropDown|ErrorMessage|Error|' r'EvaluateContents|GotFocus|Init|InteractiveChange|KeyPress|' r'LoadReport|Load|LostFocus|Message|MiddleClick|MouseDown|' r'MouseEnter|MouseLeave|MouseMove|MouseUp|MouseWheel|Moved|' r'OLECompleteDrag|OLEDragOver|OLEGiveFeedback|OLESetData|' r'OLEStartDrag|OnMoveItem|Paint|ProgrammaticChange|' r'QueryAddFile|QueryModifyFile|QueryNewFile|QueryRemoveFile|' r'QueryRunFile|QueryUnload|RangeHigh|RangeLow|ReadActivate|' r'ReadDeactivate|ReadShow|ReadValid|ReadWhen|Resize|' r'RightClick|SCCInit|SCCDestroy|Scrolled|Timer|UIEnable|' r'UnDock|UnloadReport|Unload|UpClick|Valid|When)', Name.Function),
(r'\s+', Text), # everything else is not colored (r'.', Text), ], 'newline': [ (r'\*.*?$', Comment.Single, '#pop'), (r'(ACCEPT|ACTIVATE\s*MENU|ACTIVATE\s*POPUP|ACTIVATE\s*SCREEN|' r'ACTIVATE\s*WINDOW|APPEND|APPEND\s*FROM|APPEND\s*FROM\s*ARRAY|' r'APPEND\s*GENERAL|APPEND\s*MEMO|ASSIST|AVERAGE|BLANK|BROWSE|' r'BUILD\s*APP|BUILD\s*EXE|BUILD\s*PROJECT|CALCULATE|CALL|' r'CANCEL|CHANGE|CLEAR|CLOSE|CLOSE\s*MEMO|COMPILE|CONTINUE|' r'COPY\s*FILE|COPY\s*INDEXES|COPY\s*MEMO|COPY\s*STRUCTURE|' r'COPY\s*STRUCTURE\s*EXTENDED|COPY\s*TAG|COPY\s*TO|' r'COPY\s*TO\s*ARRAY|COUNT|CREATE|CREATE\s*COLOR\s*SET|' r'CREATE\s*CURSOR|CREATE\s*FROM|CREATE\s*LABEL|CREATE\s*MENU|' r'CREATE\s*PROJECT|CREATE\s*QUERY|CREATE\s*REPORT|' r'CREATE\s*SCREEN|CREATE\s*TABLE|CREATE\s*VIEW|DDE|' r'DEACTIVATE\s*MENU|DEACTIVATE\s*POPUP|DEACTIVATE\s*WINDOW|' r'DECLARE|DEFINE\s*BAR|DEFINE\s*BOX|DEFINE\s*MENU|' r'DEFINE\s*PAD|DEFINE\s*POPUP|DEFINE\s*WINDOW|DELETE|' r'DELETE\s*FILE|DELETE\s*TAG|DIMENSION|DIRECTORY|DISPLAY|' r'DISPLAY\s*FILES|DISPLAY\s*MEMORY|DISPLAY\s*STATUS|' r'DISPLAY\s*STRUCTURE|DO|EDIT|EJECT|EJECT\s*PAGE|ERASE|' r'EXIT|EXPORT|EXTERNAL|FILER|FIND|FLUSH|FUNCTION|GATHER|' r'GETEXPR|GO|GOTO|HELP|HIDE\s*MENU|HIDE\s*POPUP|' r'HIDE\s*WINDOW|IMPORT|INDEX|INPUT|INSERT|JOIN|KEYBOARD|' r'LABEL|LIST|LOAD|LOCATE|LOOP|MENU|MENU\s*TO|MODIFY\s*COMMAND|' r'MODIFY\s*FILE|MODIFY\s*GENERAL|MODIFY\s*LABEL|MODIFY\s*MEMO|' r'MODIFY\s*MENU|MODIFY\s*PROJECT|MODIFY\s*QUERY|' r'MODIFY\s*REPORT|MODIFY\s*SCREEN|MODIFY\s*STRUCTURE|' r'MODIFY\s*WINDOW|MOVE\s*POPUP|MOVE\s*WINDOW|NOTE|' r'ON\s*APLABOUT|ON\s*BAR|ON\s*ERROR|ON\s*ESCAPE|' r'ON\s*EXIT\s*BAR|ON\s*EXIT\s*MENU|ON\s*EXIT\s*PAD|' r'ON\s*EXIT\s*POPUP|ON\s*KEY|ON\s*KEY\s*=|ON\s*KEY\s*LABEL|' r'ON\s*MACHELP|ON\s*PAD|ON\s*PAGE|ON\s*READERROR|' r'ON\s*SELECTION\s*BAR|ON\s*SELECTION\s*MENU|' r'ON\s*SELECTION\s*PAD|ON\s*SELECTION\s*POPUP|ON\s*SHUTDOWN|' r'PACK|PARAMETERS|PLAY\s*MACRO|POP\s*KEY|POP\s*MENU|' r'POP\s*POPUP|PRIVATE|PROCEDURE|PUBLIC|PUSH\s*KEY|' r'PUSH\s*MENU|PUSH\s*POPUP|QUIT|READ|READ\s*MENU|RECALL|' r'REINDEX|RELEASE|RELEASE\s*MODULE|RENAME|REPLACE|' r'REPLACE\s*FROM\s*ARRAY|REPORT|RESTORE\s*FROM|' r'RESTORE\s*MACROS|RESTORE\s*SCREEN|RESTORE\s*WINDOW|' r'RESUME|RETRY|RETURN|RUN|RUN\s*\/N"|RUNSCRIPT|' r'SAVE\s*MACROS|SAVE\s*SCREEN|SAVE\s*TO|SAVE\s*WINDOWS|' r'SCATTER|SCROLL|SEEK|SELECT|SET|SET\s*ALTERNATE|' r'SET\s*ANSI|SET\s*APLABOUT|SET\s*AUTOSAVE|SET\s*BELL|' r'SET\s*BLINK|SET\s*BLOCKSIZE|SET\s*BORDER|SET\s*BRSTATUS|' r'SET\s*CARRY|SET\s*CENTURY|SET\s*CLEAR|SET\s*CLOCK|' r'SET\s*COLLATE|SET\s*COLOR\s*OF|SET\s*COLOR\s*OF\s*SCHEME|' r'SET\s*COLOR\s*SET|SET\s*COLOR\s*TO|SET\s*COMPATIBLE|' r'SET\s*CONFIRM|SET\s*CONSOLE|SET\s*CURRENCY|SET\s*CURSOR|' r'SET\s*DATE|SET\s*DEBUG|SET\s*DECIMALS|SET\s*DEFAULT|' r'SET\s*DELETED|SET\s*DELIMITERS|SET\s*DEVELOPMENT|' r'SET\s*DEVICE|SET\s*DISPLAY|SET\s*DOHISTORY|SET\s*ECHO|' r'SET\s*ESCAPE|SET\s*EXACT|SET\s*EXCLUSIVE|SET\s*FIELDS|' r'SET\s*FILTER|SET\s*FIXED|SET\s*FORMAT|SET\s*FULLPATH|' r'SET\s*FUNCTION|SET\s*HEADINGS|SET\s*HELP|SET\s*HELPFILTER|' r'SET\s*HOURS|SET\s*INDEX|SET\s*INTENSITY|SET\s*KEY|' r'SET\s*KEYCOMP|SET\s*LIBRARY|SET\s*LOCK|SET\s*LOGERRORS|' r'SET\s*MACDESKTOP|SET\s*MACHELP|SET\s*MACKEY|SET\s*MARGIN|' r'SET\s*MARK\s*OF|SET\s*MARK\s*TO|SET\s*MEMOWIDTH|' r'SET\s*MESSAGE|SET\s*MOUSE|SET\s*MULTILOCKS|SET\s*NEAR|' r'SET\s*NOCPTRANS|SET\s*NOTIFY|SET\s*ODOMETER|SET\s*OPTIMIZE|' r'SET\s*ORDER|SET\s*PALETTE|SET\s*PATH|SET\s*PDSETUP|' r'SET\s*POINT|SET\s*PRINTER|SET\s*PROCEDURE|SET\s*READBORDER|' r'SET\s*REFRESH|SET\s*RELATION|SET\s*RELATION\s*OFF|' r'SET\s*REPROCESS|SET\s*RESOURCE|SET\s*SAFETY|SET\s*SCOREBOARD|' r'SET\s*SEPARATOR|SET\s*SHADOWS|SET\s*SKIP|SET\s*SKIP\s*OF|' r'SET\s*SPACE|SET\s*STATUS|SET\s*STATUS\s*BAR|SET\s*STEP|' r'SET\s*STICKY|SET\s*SYSMENU|SET\s*TALK|SET\s*TEXTMERGE|' r'SET\s*TEXTMERGE\s*DELIMITERS|SET\s*TOPIC|SET\s*TRBETWEEN|' r'SET\s*TYPEAHEAD|SET\s*UDFPARMS|SET\s*UNIQUE|SET\s*VIEW|' r'SET\s*VOLUME|SET\s*WINDOW\s*OF\s*MEMO|SET\s*XCMDFILE|' r'SHOW\s*GET|SHOW\s*GETS|SHOW\s*MENU|SHOW\s*OBJECT|' r'SHOW\s*POPUP|SHOW\s*WINDOW|SIZE\s*POPUP|SKIP|SORT|' r'STORE|SUM|SUSPEND|TOTAL|TYPE|UNLOCK|UPDATE|USE|WAIT|' r'ZAP|ZOOM\s*WINDOW|DO\s*CASE|CASE|OTHERWISE|ENDCASE|' r'DO\s*WHILE|ENDDO|FOR|ENDFOR|NEXT|IF|ELSE|ENDIF|PRINTJOB|' r'ENDPRINTJOB|SCAN|ENDSCAN|TEXT|ENDTEXT|=)', Keyword.Reserved, '#pop'), (r'#\s*(IF|ELIF|ELSE|ENDIF|DEFINE|IFDEF|IFNDEF|INCLUDE)', Comment.Preproc, '#pop'), (r'(m\.)?[a-z_]\w*', Name.Variable, '#pop'), (r'.', Text, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893""" pygments.lexers.freefem ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for FreeFem++ language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.token import Comment, Operator, Keyword, Name
from pygments.lexers.c_cpp import CppLexer
__all__ = ['FreeFemLexer']
class FreeFemLexer(CppLexer): """ For FreeFem++ source.
This is an extension of the CppLexer, as the FreeFem Language is a superset of C++. """
name = 'Freefem' url = 'https://freefem.org/' aliases = ['freefem'] filenames = ['*.edp'] mimetypes = ['text/x-freefem'] version_added = '2.4'
# Language operators operators = {'+', '-', '*', '.*', '/', './', '%', '^', '^-1', ':', '\''}
# types types = {'bool', 'border', 'complex', 'dmatrix', 'fespace', 'func', 'gslspline', 'ifstream', 'int', 'macro', 'matrix', 'mesh', 'mesh3', 'mpiComm', 'mpiGroup', 'mpiRequest', 'NewMacro', 'EndMacro', 'ofstream', 'Pmmap', 'problem', 'Psemaphore', 'real', 'solve', 'string', 'varf'}
# finite element spaces fespaces = {'BDM1', 'BDM1Ortho', 'Edge03d', 'Edge13d', 'Edge23d', 'FEQF', 'HCT', 'P0', 'P03d', 'P0Edge', 'P1', 'P13d', 'P1b', 'P1b3d', 'P1bl', 'P1bl3d', 'P1dc', 'P1Edge', 'P1nc', 'P2', 'P23d', 'P2b', 'P2BR', 'P2dc', 'P2Edge', 'P2h', 'P2Morley', 'P2pnc', 'P3', 'P3dc', 'P3Edge', 'P4', 'P4dc', 'P4Edge', 'P5Edge', 'RT0', 'RT03d', 'RT0Ortho', 'RT1', 'RT1Ortho', 'RT2', 'RT2Ortho'}
# preprocessor preprocessor = {'ENDIFMACRO', 'include', 'IFMACRO', 'load'}
# Language keywords keywords = { 'adj', 'append', 'area', 'ARGV', 'be', 'binary', 'BoundaryEdge', 'bordermeasure', 'CG', 'Cholesky', 'cin', 'cout', 'Crout', 'default', 'diag', 'edgeOrientation', 'endl', 'false', 'ffind', 'FILE', 'find', 'fixed', 'flush', 'GMRES', 'good', 'hTriangle', 'im', 'imax', 'imin', 'InternalEdge', 'l1', 'l2', 'label', 'lenEdge', 'length', 'LINE', 'linfty', 'LU', 'm', 'max', 'measure', 'min', 'mpiAnySource', 'mpiBAND', 'mpiBXOR', 'mpiCommWorld', 'mpiLAND', 'mpiLOR', 'mpiLXOR', 'mpiMAX', 'mpiMIN', 'mpiPROD', 'mpirank', 'mpisize', 'mpiSUM', 'mpiUndefined', 'n', 'N', 'nbe', 'ndof', 'ndofK', 'noshowbase', 'noshowpos', 'notaregion', 'nt', 'nTonEdge', 'nuEdge', 'nuTriangle', 'nv', 'P', 'pi', 'precision', 'qf1pE', 'qf1pElump', 'qf1pT', 'qf1pTlump', 'qfV1', 'qfV1lump', 'qf2pE', 'qf2pT', 'qf2pT4P1', 'qfV2', 'qf3pE', 'qf4pE', 'qf5pE', 'qf5pT', 'qfV5', 'qf7pT', 'qf9pT', 'qfnbpE', 'quantile', 're', 'region', 'rfind', 'scientific', 'searchMethod', 'setw', 'showbase', 'showpos', 'sparsesolver', 'sum', 'tellp', 'true', 'UMFPACK', 'unused', 'whoinElement', 'verbosity', 'version', 'volume', 'x', 'y', 'z' }
# Language shipped functions and class ( ) functions = { 'abs', 'acos', 'acosh', 'adaptmesh', 'adj', 'AffineCG', 'AffineGMRES', 'arg', 'asin', 'asinh', 'assert', 'atan', 'atan2', 'atanh', 'atof', 'atoi', 'BFGS', 'broadcast', 'buildlayers', 'buildmesh', 'ceil', 'chi', 'complexEigenValue', 'copysign', 'change', 'checkmovemesh', 'clock', 'cmaes', 'conj', 'convect', 'cos', 'cosh', 'cube', 'd', 'dd', 'dfft', 'diffnp', 'diffpos', 'dimKrylov', 'dist', 'dumptable', 'dx', 'dxx', 'dxy', 'dxz', 'dy', 'dyx', 'dyy', 'dyz', 'dz', 'dzx', 'dzy', 'dzz', 'EigenValue', 'emptymesh', 'erf', 'erfc', 'exec', 'exit', 'exp', 'fdim', 'floor', 'fmax', 'fmin', 'fmod', 'freeyams', 'getARGV', 'getline', 'gmshload', 'gmshload3', 'gslcdfugaussianP', 'gslcdfugaussianQ', 'gslcdfugaussianPinv', 'gslcdfugaussianQinv', 'gslcdfgaussianP', 'gslcdfgaussianQ', 'gslcdfgaussianPinv', 'gslcdfgaussianQinv', 'gslcdfgammaP', 'gslcdfgammaQ', 'gslcdfgammaPinv', 'gslcdfgammaQinv', 'gslcdfcauchyP', 'gslcdfcauchyQ', 'gslcdfcauchyPinv', 'gslcdfcauchyQinv', 'gslcdflaplaceP', 'gslcdflaplaceQ', 'gslcdflaplacePinv', 'gslcdflaplaceQinv', 'gslcdfrayleighP', 'gslcdfrayleighQ', 'gslcdfrayleighPinv', 'gslcdfrayleighQinv', 'gslcdfchisqP', 'gslcdfchisqQ', 'gslcdfchisqPinv', 'gslcdfchisqQinv', 'gslcdfexponentialP', 'gslcdfexponentialQ', 'gslcdfexponentialPinv', 'gslcdfexponentialQinv', 'gslcdfexppowP', 'gslcdfexppowQ', 'gslcdftdistP', 'gslcdftdistQ', 'gslcdftdistPinv', 'gslcdftdistQinv', 'gslcdffdistP', 'gslcdffdistQ', 'gslcdffdistPinv', 'gslcdffdistQinv', 'gslcdfbetaP', 'gslcdfbetaQ', 'gslcdfbetaPinv', 'gslcdfbetaQinv', 'gslcdfflatP', 'gslcdfflatQ', 'gslcdfflatPinv', 'gslcdfflatQinv', 'gslcdflognormalP', 'gslcdflognormalQ', 'gslcdflognormalPinv', 'gslcdflognormalQinv', 'gslcdfgumbel1P', 'gslcdfgumbel1Q', 'gslcdfgumbel1Pinv', 'gslcdfgumbel1Qinv', 'gslcdfgumbel2P', 'gslcdfgumbel2Q', 'gslcdfgumbel2Pinv', 'gslcdfgumbel2Qinv', 'gslcdfweibullP', 'gslcdfweibullQ', 'gslcdfweibullPinv', 'gslcdfweibullQinv', 'gslcdfparetoP', 'gslcdfparetoQ', 'gslcdfparetoPinv', 'gslcdfparetoQinv', 'gslcdflogisticP', 'gslcdflogisticQ', 'gslcdflogisticPinv', 'gslcdflogisticQinv', 'gslcdfbinomialP', 'gslcdfbinomialQ', 'gslcdfpoissonP', 'gslcdfpoissonQ', 'gslcdfgeometricP', 'gslcdfgeometricQ', 'gslcdfnegativebinomialP', 'gslcdfnegativebinomialQ', 'gslcdfpascalP', 'gslcdfpascalQ', 'gslinterpakima', 'gslinterpakimaperiodic', 'gslinterpcsplineperiodic', 'gslinterpcspline', 'gslinterpsteffen', 'gslinterplinear', 'gslinterppolynomial', 'gslranbernoullipdf', 'gslranbeta', 'gslranbetapdf', 'gslranbinomialpdf', 'gslranexponential', 'gslranexponentialpdf', 'gslranexppow', 'gslranexppowpdf', 'gslrancauchy', 'gslrancauchypdf', 'gslranchisq', 'gslranchisqpdf', 'gslranerlang', 'gslranerlangpdf', 'gslranfdist', 'gslranfdistpdf', 'gslranflat', 'gslranflatpdf', 'gslrangamma', 'gslrangammaint', 'gslrangammapdf', 'gslrangammamt', 'gslrangammaknuth', 'gslrangaussian', 'gslrangaussianratiomethod', 'gslrangaussianziggurat', 'gslrangaussianpdf', 'gslranugaussian', 'gslranugaussianratiomethod', 'gslranugaussianpdf', 'gslrangaussiantail', 'gslrangaussiantailpdf', 'gslranugaussiantail', 'gslranugaussiantailpdf', 'gslranlandau', 'gslranlandaupdf', 'gslrangeometricpdf', 'gslrangumbel1', 'gslrangumbel1pdf', 'gslrangumbel2', 'gslrangumbel2pdf', 'gslranlogistic', 'gslranlogisticpdf', 'gslranlognormal', 'gslranlognormalpdf', 'gslranlogarithmicpdf', 'gslrannegativebinomialpdf', 'gslranpascalpdf', 'gslranpareto', 'gslranparetopdf', 'gslranpoissonpdf', 'gslranrayleigh', 'gslranrayleighpdf', 'gslranrayleightail', 'gslranrayleightailpdf', 'gslrantdist', 'gslrantdistpdf', 'gslranlaplace', 'gslranlaplacepdf', 'gslranlevy', 'gslranweibull', 'gslranweibullpdf', 'gslsfairyAi', 'gslsfairyBi', 'gslsfairyAiscaled', 'gslsfairyBiscaled', 'gslsfairyAideriv', 'gslsfairyBideriv', 'gslsfairyAiderivscaled', 'gslsfairyBiderivscaled', 'gslsfairyzeroAi', 'gslsfairyzeroBi', 'gslsfairyzeroAideriv', 'gslsfairyzeroBideriv', 'gslsfbesselJ0', 'gslsfbesselJ1', 'gslsfbesselJn', 'gslsfbesselY0', 'gslsfbesselY1', 'gslsfbesselYn', 'gslsfbesselI0', 'gslsfbesselI1', 'gslsfbesselIn', 'gslsfbesselI0scaled', 'gslsfbesselI1scaled', 'gslsfbesselInscaled', 'gslsfbesselK0', 'gslsfbesselK1', 'gslsfbesselKn', 'gslsfbesselK0scaled', 'gslsfbesselK1scaled', 'gslsfbesselKnscaled', 'gslsfbesselj0', 'gslsfbesselj1', 'gslsfbesselj2', 'gslsfbesseljl', 'gslsfbessely0', 'gslsfbessely1', 'gslsfbessely2', 'gslsfbesselyl', 'gslsfbesseli0scaled', 'gslsfbesseli1scaled', 'gslsfbesseli2scaled', 'gslsfbesselilscaled', 'gslsfbesselk0scaled', 'gslsfbesselk1scaled', 'gslsfbesselk2scaled', 'gslsfbesselklscaled', 'gslsfbesselJnu', 'gslsfbesselYnu', 'gslsfbesselInuscaled', 'gslsfbesselInu', 'gslsfbesselKnuscaled', 'gslsfbesselKnu', 'gslsfbessellnKnu', 'gslsfbesselzeroJ0', 'gslsfbesselzeroJ1', 'gslsfbesselzeroJnu', 'gslsfclausen', 'gslsfhydrogenicR1', 'gslsfdawson', 'gslsfdebye1', 'gslsfdebye2', 'gslsfdebye3', 'gslsfdebye4', 'gslsfdebye5', 'gslsfdebye6', 'gslsfdilog', 'gslsfmultiply', 'gslsfellintKcomp', 'gslsfellintEcomp', 'gslsfellintPcomp', 'gslsfellintDcomp', 'gslsfellintF', 'gslsfellintE', 'gslsfellintRC', 'gslsferfc', 'gslsflogerfc', 'gslsferf', 'gslsferfZ', 'gslsferfQ', 'gslsfhazard', 'gslsfexp', 'gslsfexpmult', 'gslsfexpm1', 'gslsfexprel', 'gslsfexprel2', 'gslsfexpreln', 'gslsfexpintE1', 'gslsfexpintE2', 'gslsfexpintEn', 'gslsfexpintE1scaled', 'gslsfexpintE2scaled', 'gslsfexpintEnscaled', 'gslsfexpintEi', 'gslsfexpintEiscaled', 'gslsfShi', 'gslsfChi', 'gslsfexpint3', 'gslsfSi', 'gslsfCi', 'gslsfatanint', 'gslsffermidiracm1', 'gslsffermidirac0', 'gslsffermidirac1', 'gslsffermidirac2', 'gslsffermidiracint', 'gslsffermidiracmhalf', 'gslsffermidirachalf', 'gslsffermidirac3half', 'gslsffermidiracinc0', 'gslsflngamma', 'gslsfgamma', 'gslsfgammastar', 'gslsfgammainv', 'gslsftaylorcoeff', 'gslsffact', 'gslsfdoublefact', 'gslsflnfact', 'gslsflndoublefact', 'gslsflnchoose', 'gslsfchoose', 'gslsflnpoch', 'gslsfpoch', 'gslsfpochrel', 'gslsfgammaincQ', 'gslsfgammaincP', 'gslsfgammainc', 'gslsflnbeta', 'gslsfbeta', 'gslsfbetainc', 'gslsfgegenpoly1', 'gslsfgegenpoly2', 'gslsfgegenpoly3', 'gslsfgegenpolyn', 'gslsfhyperg0F1', 'gslsfhyperg1F1int', 'gslsfhyperg1F1', 'gslsfhypergUint', 'gslsfhypergU', 'gslsfhyperg2F0', 'gslsflaguerre1', 'gslsflaguerre2', 'gslsflaguerre3', 'gslsflaguerren', 'gslsflambertW0', 'gslsflambertWm1', 'gslsflegendrePl', 'gslsflegendreP1', 'gslsflegendreP2', 'gslsflegendreP3', 'gslsflegendreQ0', 'gslsflegendreQ1', 'gslsflegendreQl', 'gslsflegendrePlm', 'gslsflegendresphPlm', 'gslsflegendrearraysize', 'gslsfconicalPhalf', 'gslsfconicalPmhalf', 'gslsfconicalP0', 'gslsfconicalP1', 'gslsfconicalPsphreg', 'gslsfconicalPcylreg', 'gslsflegendreH3d0', 'gslsflegendreH3d1', 'gslsflegendreH3d', 'gslsflog', 'gslsflogabs', 'gslsflog1plusx', 'gslsflog1plusxmx', 'gslsfpowint', 'gslsfpsiint', 'gslsfpsi', 'gslsfpsi1piy', 'gslsfpsi1int', 'gslsfpsi1', 'gslsfpsin', 'gslsfsynchrotron1', 'gslsfsynchrotron2', 'gslsftransport2', 'gslsftransport3', 'gslsftransport4', 'gslsftransport5', 'gslsfsin', 'gslsfcos', 'gslsfhypot', 'gslsfsinc', 'gslsflnsinh', 'gslsflncosh', 'gslsfanglerestrictsymm', 'gslsfanglerestrictpos', 'gslsfzetaint', 'gslsfzeta', 'gslsfzetam1', 'gslsfzetam1int', 'gslsfhzeta', 'gslsfetaint', 'gslsfeta', 'imag', 'int1d', 'int2d', 'int3d', 'intalledges', 'intallfaces', 'interpolate', 'invdiff', 'invdiffnp', 'invdiffpos', 'Isend', 'isInf', 'isNaN', 'isoline', 'Irecv', 'j0', 'j1', 'jn', 'jump', 'lgamma', 'LinearCG', 'LinearGMRES', 'log', 'log10', 'lrint', 'lround', 'max', 'mean', 'medit', 'min', 'mmg3d', 'movemesh', 'movemesh23', 'mpiAlltoall', 'mpiAlltoallv', 'mpiAllgather', 'mpiAllgatherv', 'mpiAllReduce', 'mpiBarrier', 'mpiGather', 'mpiGatherv', 'mpiRank', 'mpiReduce', 'mpiScatter', 'mpiScatterv', 'mpiSize', 'mpiWait', 'mpiWaitAny', 'mpiWtick', 'mpiWtime', 'mshmet', 'NaN', 'NLCG', 'on', 'plot', 'polar', 'Post', 'pow', 'processor', 'processorblock', 'projection', 'randinit', 'randint31', 'randint32', 'random', 'randreal1', 'randreal2', 'randreal3', 'randres53', 'Read', 'readmesh', 'readmesh3', 'Recv', 'rint', 'round', 'savemesh', 'savesol', 'savevtk', 'seekg', 'Sent', 'set', 'sign', 'signbit', 'sin', 'sinh', 'sort', 'splitComm', 'splitmesh', 'sqrt', 'square', 'srandom', 'srandomdev', 'Stringification', 'swap', 'system', 'tan', 'tanh', 'tellg', 'tetg', 'tetgconvexhull', 'tetgreconstruction', 'tetgtransfo', 'tgamma', 'triangulate', 'trunc', 'Wait', 'Write', 'y0', 'y1', 'yn' }
# function parameters parameters = { 'A', 'A1', 'abserror', 'absolute', 'aniso', 'aspectratio', 'B', 'B1', 'bb', 'beginend', 'bin', 'boundary', 'bw', 'close', 'cmm', 'coef', 'composante', 'cutoff', 'datafilename', 'dataname', 'dim', 'distmax', 'displacement', 'doptions', 'dparams', 'eps', 'err', 'errg', 'facemerge', 'facetcl', 'factorize', 'file', 'fill', 'fixedborder', 'flabel', 'flags', 'floatmesh', 'floatsol', 'fregion', 'gradation', 'grey', 'hmax', 'hmin', 'holelist', 'hsv', 'init', 'inquire', 'inside', 'IsMetric', 'iso', 'ivalue', 'keepbackvertices', 'label', 'labeldown', 'labelmid', 'labelup', 'levelset', 'loptions', 'lparams', 'maxit', 'maxsubdiv', 'meditff', 'mem', 'memory', 'metric', 'mode', 'nbarrow', 'nbiso', 'nbiter', 'nbjacoby', 'nboffacetcl', 'nbofholes', 'nbofregions', 'nbregul', 'nbsmooth', 'nbvx', 'ncv', 'nev', 'nomeshgeneration', 'normalization', 'omega', 'op', 'optimize', 'option', 'options', 'order', 'orientation', 'periodic', 'power', 'precon', 'prev', 'ps', 'ptmerge', 'qfe', 'qforder', 'qft', 'qfV', 'ratio', 'rawvector', 'reffacelow', 'reffacemid', 'reffaceup', 'refnum', 'reftet', 'reftri', 'region', 'regionlist', 'renumv', 'rescaling', 'ridgeangle', 'save', 'sigma', 'sizeofvolume', 'smoothing', 'solver', 'sparams', 'split', 'splitin2', 'splitpbedge', 'stop', 'strategy', 'swap', 'switch', 'sym', 't', 'tgv', 'thetamax', 'tol', 'tolpivot', 'tolpivotsym', 'transfo', 'U2Vc', 'value', 'varrow', 'vector', 'veps', 'viso', 'wait', 'width', 'withsurfacemesh', 'WindowIndex', 'which', 'zbound' }
# deprecated deprecated = {'fixeborder'}
# do not highlight suppress_highlight = { 'alignof', 'asm', 'constexpr', 'decltype', 'div', 'double', 'grad', 'mutable', 'namespace', 'noexcept', 'restrict', 'static_assert', 'template', 'this', 'thread_local', 'typeid', 'typename', 'using' }
def get_tokens_unprocessed(self, text, stack=('root',)): for index, token, value in CppLexer.get_tokens_unprocessed(self, text, stack): if value in self.operators: yield index, Operator, value elif value in self.types: yield index, Keyword.Type, value elif value in self.fespaces: yield index, Name.Class, value elif value in self.preprocessor: yield index, Comment.Preproc, value elif value in self.keywords: yield index, Keyword.Reserved, value elif value in self.functions: yield index, Name.Function, value elif value in self.parameters: yield index, Keyword.Pseudo, value elif value in self.suppress_highlight: yield index, Name, value else: yield index, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110""" pygments.lexers.func ~~~~~~~~~~~~~~~~~~~~
Lexers for FunC.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Whitespace, Punctuation
__all__ = ['FuncLexer']
class FuncLexer(RegexLexer): """ For FunC source code. """
name = 'FunC' aliases = ['func', 'fc'] filenames = ['*.fc', '*.func'] url = 'https://docs.ton.org/develop/func/overview' version_added = ''
# 1. Does not start from " # 2. Can start from ` and end with `, containing any character # 3. Starts with underscore or { or } and have more than 1 character after it # 4. Starts with letter, contains letters, numbers and underscores identifier = r'(?!")(`([^`]+)`|((?=_)_|(?=\{)\{|(?=\})\}|(?![_`{}]))([^;,\[\]\(\)\s~.]+))'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace),
include('keywords'), include('strings'), include('directives'), include('numeric'), include('comments'), include('storage'), include('functions'), include('variables'),
(r'[.;(),\[\]~{}]', Punctuation) ], 'keywords': [ (words(( '<=>', '>=', '<=', '!=', '==', '^>>', '~>>', '>>', '<<', '/%', '^%', '~%', '^/', '~/', '+=', '-=', '*=', '/=', '~/=', '^/=', '%=', '^%=', '<<=', '>>=', '~>>=', '^>>=', '&=', '|=', '^=', '^', '=', '~', '/', '%', '-', '*', '+','>', '<', '&', '|', ':', '?'), prefix=r'(?<=\s)', suffix=r'(?=\s)'), Operator), (words(( 'if', 'ifnot', 'else', 'elseif', 'elseifnot', 'while', 'do', 'until', 'repeat', 'return', 'impure', 'method_id', 'forall', 'asm', 'inline', 'inline_ref'), prefix=r'\b', suffix=r'\b'), Keyword), (words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), ], 'directives': [ (r'#include|#pragma', Keyword, 'directive'), ], 'directive': [ include('strings'), (r'\s+', Whitespace), (r'version|not-version', Keyword), (r'(>=|<=|=|>|<|\^)?([0-9]+)(.[0-9]+)?(.[0-9]+)?', Number), # version (r';', Text, '#pop') ], 'strings': [ (r'\"([^\n\"]+)\"[Hhcusa]?', String), ], 'numeric': [ (r'\b(-?(?!_)([\d_]+|0x[\d_a-fA-F]+)|0b[1_0]+)(?<!_)(?=[\s\)\],;])', Number) ], 'comments': [ (r';;([^\n]*)', Comment.Singleline), (r'\{-', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^-}{]+', Comment.Multiline), (r'\{-', Comment.Multiline, '#push'), (r'-\}', Comment.Multiline, '#pop'), (r'[-}{]', Comment.Multiline), ], 'storage': [ (words(( 'var', 'int', 'slice', 'tuple', 'cell', 'builder', 'cont', '_'), prefix=r'\b', suffix=r'(?=[\s\(\),\[\]])'), Keyword.Type), (words(('global', 'const'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), ], 'variables': [ (identifier, Name.Variable), ], 'functions': [ # identifier followed by ( (identifier + r'(?=[\(])', Name.Function), ] }123456789101112131415161718192021""" pygments.lexers.functional ~~~~~~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
# ruff: noqa: F401from pygments.lexers.lisp import SchemeLexer, CommonLispLexer, RacketLexer, \ NewLispLexer, ShenLexerfrom pygments.lexers.haskell import HaskellLexer, LiterateHaskellLexer, \ KokaLexerfrom pygments.lexers.theorem import RocqLexerfrom pygments.lexers.erlang import ErlangLexer, ErlangShellLexer, \ ElixirConsoleLexer, ElixirLexerfrom pygments.lexers.ml import SMLLexer, OcamlLexer, OpaLexer
__all__ = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105""" pygments.lexers.futhark ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Futhark language
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespacefrom pygments import unistring as uni
__all__ = ['FutharkLexer']
class FutharkLexer(RegexLexer): """ A Futhark lexer """ name = 'Futhark' url = 'https://futhark-lang.org/' aliases = ['futhark'] filenames = ['*.fut'] mimetypes = ['text/x-futhark'] version_added = '2.8'
num_types = ('i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64', 'f32', 'f64')
other_types = ('bool', )
reserved = ('if', 'then', 'else', 'def', 'let', 'loop', 'in', 'with', 'type', 'type~', 'type^', 'val', 'entry', 'for', 'while', 'do', 'case', 'match', 'include', 'import', 'module', 'open', 'local', 'assert', '_')
ascii = ('NUL', 'SOH', '[SE]TX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT', 'FF', 'CR', 'S[OI]', 'DLE', 'DC[1-4]', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', '[FGRU]S', 'SP', 'DEL')
num_postfix = r'({})?'.format('|'.join(num_types))
identifier_re = '[a-zA-Z_][a-zA-Z_0-9\']*'
# opstart_re = '+\-\*/%=\!><\|&\^'
tokens = { 'root': [ (r'--(.*?)$', Comment.Single), (r'\s+', Whitespace), (r'\(\)', Punctuation), (r'\b({})(?!\')\b'.format('|'.join(reserved)), Keyword.Reserved), (r'\b({})(?!\')\b'.format('|'.join(num_types + other_types)), Keyword.Type),
# Identifiers (r'#\[([a-zA-Z_\(\) ]*)\]', Comment.Preproc), (rf'[#!]?({identifier_re}\.)*{identifier_re}', Name),
(r'\\', Operator), (r'[-+/%=!><|&*^][-+/%=!><|&*^.]*', Operator), (r'[][(),:;`{}?.\'~^]', Punctuation),
# Numbers (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*_*[pP][+-]?\d(_*\d)*' + num_postfix, Number.Float), (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*\.[\da-fA-F](_*[\da-fA-F])*' r'(_*[pP][+-]?\d(_*\d)*)?' + num_postfix, Number.Float), (r'\d(_*\d)*_*[eE][+-]?\d(_*\d)*' + num_postfix, Number.Float), (r'\d(_*\d)*\.\d(_*\d)*(_*[eE][+-]?\d(_*\d)*)?' + num_postfix, Number.Float), (r'0[bB]_*[01](_*[01])*' + num_postfix, Number.Bin), (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*' + num_postfix, Number.Hex), (r'\d(_*\d)*' + num_postfix, Number.Integer),
# Character/String Literals (r"'", String.Char, 'character'), (r'"', String, 'string'), # Special (r'\[[a-zA-Z_\d]*\]', Keyword.Type), (r'\(\)', Name.Builtin), ], 'character': [ # Allows multi-chars, incorrectly. (r"[^\\']'", String.Char, '#pop'), (r"\\", String.Escape, 'escape'), ("'", String.Char, '#pop'), ], 'string': [ (r'[^\\"]+', String), (r"\\", String.Escape, 'escape'), ('"', String, '#pop'), ],
'escape': [ (r'[abfnrtv"\'&\\]', String.Escape, '#pop'), (r'\^[][' + uni.Lu + r'@^_]', String.Escape, '#pop'), ('|'.join(ascii), String.Escape, '#pop'), (r'o[0-7]+', String.Escape, '#pop'), (r'x[\da-fA-F]+', String.Escape, '#pop'), (r'\d+', String.Escape, '#pop'), (r'(\s+)(\\)', bygroups(Whitespace, String.Escape), '#pop'), ], }1234567891011121314151617181920212223242526272829303132333435""" pygments.lexers.gcodelexer ~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for the G Code Language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Comment, Name, Text, Keyword, Number
__all__ = ['GcodeLexer']
class GcodeLexer(RegexLexer): """ For gcode source code. """ name = 'g-code' aliases = ['gcode'] filenames = ['*.gcode'] url = 'https://en.wikipedia.org/wiki/G-code' version_added = '2.9'
tokens = { 'root': [ (r';.*\n', Comment), (r'^[gmGM]\d{1,4}\s', Name.Builtin), # M or G commands (r'([^gGmM])([+-]?\d*[.]?\d+)', bygroups(Keyword, Number)), (r'\s', Text.Whitespace), (r'.*\n', Text), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189""" pygments.lexers.gdscript ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for GDScript.
Modified by Daniel J. Ramirez <djrmuv@gmail.com> based on the original python.py.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, default, words, \ combinedfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ["GDScriptLexer"]
class GDScriptLexer(RegexLexer): """ For GDScript source code. """
name = "GDScript" url = 'https://www.godotengine.org' aliases = ["gdscript", "gd"] filenames = ["*.gd"] mimetypes = ["text/x-gdscript", "application/x-gdscript"] version_added = ''
def innerstring_rules(ttype): return [ # the old style '%s' % (...) string formatting (r"%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?" "[hlL]?[E-GXc-giorsux%]", String.Interpol), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"%\n]+', ttype), (r'[\'"\\]', ttype), # unhandled string formatting sign (r"%", ttype), # newlines are an error (use "nl" state) ]
tokens = { "root": [ (r"\n", Whitespace), (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")', bygroups(Whitespace, String.Affix, String.Doc)), (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')", bygroups(Whitespace, String.Affix, String.Doc)), (r"[^\S\n]+", Whitespace), (r"#.*$", Comment.Single), (r"[]{}:(),;[]", Punctuation), (r"(\\)(\n)", bygroups(Text, Whitespace)), (r"\\", Text), (r"(in|and|or|not)\b", Operator.Word), (r"!=|==|<<|>>|&&|\+=|-=|\*=|/=|%=|&=|\|=|\|\||[-~+/*%=<>&^.!|$]", Operator), include("keywords"), (r"(func)(\s+)", bygroups(Keyword, Whitespace), "funcname"), (r"(class)(\s+)", bygroups(Keyword, Whitespace), "classname"), include("builtins"), ('([rR]|[uUbB][rR]|[rR][uUbB])(""")', bygroups(String.Affix, String.Double), "tdqs"), ("([rR]|[uUbB][rR]|[rR][uUbB])(''')", bygroups(String.Affix, String.Single), "tsqs"), ('([rR]|[uUbB][rR]|[rR][uUbB])(")', bygroups(String.Affix, String.Double), "dqs"), ("([rR]|[uUbB][rR]|[rR][uUbB])(')", bygroups(String.Affix, String.Single), "sqs"), ('([uUbB]?)(""")', bygroups(String.Affix, String.Double), combined("stringescape", "tdqs")), ("([uUbB]?)(''')", bygroups(String.Affix, String.Single), combined("stringescape", "tsqs")), ('([uUbB]?)(")', bygroups(String.Affix, String.Double), combined("stringescape", "dqs")), ("([uUbB]?)(')", bygroups(String.Affix, String.Single), combined("stringescape", "sqs")), include("name"), include("numbers"), ], "keywords": [ (words(("and", "in", "not", "or", "as", "breakpoint", "class", "class_name", "extends", "is", "func", "setget", "signal", "tool", "const", "enum", "export", "onready", "static", "var", "break", "continue", "if", "elif", "else", "for", "pass", "return", "match", "while", "remote", "master", "puppet", "remotesync", "mastersync", "puppetsync"), suffix=r"\b"), Keyword), ], "builtins": [ (words(("Color8", "ColorN", "abs", "acos", "asin", "assert", "atan", "atan2", "bytes2var", "ceil", "char", "clamp", "convert", "cos", "cosh", "db2linear", "decimals", "dectime", "deg2rad", "dict2inst", "ease", "exp", "floor", "fmod", "fposmod", "funcref", "hash", "inst2dict", "instance_from_id", "is_inf", "is_nan", "lerp", "linear2db", "load", "log", "max", "min", "nearest_po2", "pow", "preload", "print", "print_stack", "printerr", "printraw", "prints", "printt", "rad2deg", "rand_range", "rand_seed", "randf", "randi", "randomize", "range", "round", "seed", "sign", "sin", "sinh", "sqrt", "stepify", "str", "str2var", "tan", "tan", "tanh", "type_exist", "typeof", "var2bytes", "var2str", "weakref", "yield"), prefix=r"(?<!\.)", suffix=r"\b"), Name.Builtin), (r"((?<!\.)(self|false|true)|(PI|TAU|NAN|INF)" r")\b", Name.Builtin.Pseudo), (words(("bool", "int", "float", "String", "NodePath", "Vector2", "Rect2", "Transform2D", "Vector3", "Rect3", "Plane", "Quat", "Basis", "Transform", "Color", "RID", "Object", "NodePath", "Dictionary", "Array", "PackedByteArray", "PackedInt32Array", "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray", "PackedVector2Array", "PackedVector3Array", "PackedColorArray", "null", "void"), prefix=r"(?<!\.)", suffix=r"\b"), Name.Builtin.Type), ], "numbers": [ (r"(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?", Number.Float), (r"\d+[eE][+-]?[0-9]+j?", Number.Float), (r"0[xX][a-fA-F0-9]+", Number.Hex), (r"\d+j?", Number.Integer), ], "name": [(r"[a-zA-Z_]\w*", Name)], "funcname": [(r"[a-zA-Z_]\w*", Name.Function, "#pop"), default("#pop")], "classname": [(r"[a-zA-Z_]\w*", Name.Class, "#pop")], "stringescape": [ ( r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|' r"U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})", String.Escape, ) ], "strings-single": innerstring_rules(String.Single), "strings-double": innerstring_rules(String.Double), "dqs": [ (r'"', String.Double, "#pop"), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include("strings-double"), ], "sqs": [ (r"'", String.Single, "#pop"), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include("strings-single"), ], "tdqs": [ (r'"""', String.Double, "#pop"), include("strings-double"), (r"\n", Whitespace), ], "tsqs": [ (r"'''", String.Single, "#pop"), include("strings-single"), (r"\n", Whitespace), ], }
def analyse_text(text): score = 0.0
if re.search( r"func (_ready|_init|_input|_process|_unhandled_input)", text ): score += 0.8
if re.search( r"(extends |class_name |onready |preload|load|setget|func [^_])", text ): score += 0.4
if re.search(r"(var|const|enum|export|signal|tool)", text): score += 0.2
return min(score, 1.0)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374""" pygments.lexers.gleam ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Gleam programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['GleamLexer']
class GleamLexer(RegexLexer): """ Lexer for the Gleam programming language (version 1.0.0). """
name = 'Gleam' url = 'https://gleam.run/' filenames = ['*.gleam'] aliases = ['gleam'] mimetypes = ['text/x-gleam'] version_added = '2.19'
keywords = words(( 'as', 'assert', 'auto', 'case', 'const', 'delegate', 'derive', 'echo', 'else', 'fn', 'if', 'implement', 'import', 'let', 'macro', 'opaque', 'panic', 'pub', 'test', 'todo', 'type', 'use', ), suffix=r'\b')
tokens = { 'root': [ # Comments (r'(///.*?)(\n)', bygroups(String.Doc, Whitespace)), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# Keywords (keywords, Keyword), (r'([a-zA-Z_]+)(\.)', bygroups(Keyword, Punctuation)),
# Punctuation (r'[()\[\]{}:;,@]+', Punctuation), (r'(#|!=|!|==|\|>|\|\||\||\->|<\-|&&|<<|>>|\.\.|\.|=)', Punctuation),
# Operators (r'(<>|\+\.?|\-\.?|\*\.?|/\.?|%\.?|<=\.?|>=\.?|<\.?|>\.?|=)', Operator),
# Strings (r'"(\\"|[^"])*"', String),
# Identifiers (r'\b(let)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Variable)), (r'\b(fn)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Function)), (r'[a-zA-Z_/]\w*', Name),
# numbers (r'(\d+(_\d+)*\.(?!\.)(\d+(_\d+)*)?|\.\d+(_\d+)*)([eEf][+-]?[0-9]+)?', Number.Float), (r'\d+(_\d+)*[eEf][+-]?[0-9]+', Number.Float), (r'0[xX][a-fA-F0-9]+(_[a-fA-F0-9]+)*(\.([a-fA-F0-9]+(_[a-fA-F0-9]+)*)?)?p[+-]?\d+', Number.Float), (r'0[bB][01]+(_[01]+)*', Number.Bin), (r'0[oO][0-7]+(_[0-7]+)*', Number.Oct), (r'0[xX][a-fA-F0-9]+(_[a-fA-F0-9]+)*', Number.Hex), (r'\d+(_\d+)*', Number.Integer),
# Whitespace (r'\s+', Whitespace),
], }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697""" pygments.lexers.go ~~~~~~~~~~~~~~~~~~
Lexers for the Google Go language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['GoLexer']
class GoLexer(RegexLexer): """ For Go source. """ name = 'Go' url = 'https://go.dev/' filenames = ['*.go'] aliases = ['go', 'golang'] mimetypes = ['text/x-gosrc'] version_added = '1.2'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuations (r'//(.*?)$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'(import|package)\b', Keyword.Namespace), (r'(var|func|struct|map|chan|type|interface|const)\b', Keyword.Declaration), (words(( 'break', 'default', 'select', 'case', 'defer', 'go', 'else', 'goto', 'switch', 'fallthrough', 'if', 'range', 'continue', 'for', 'return'), suffix=r'\b'), Keyword), (r'(true|false|iota|nil)\b', Keyword.Constant), # It seems the builtin types aren't actually keywords, but # can be used as functions. So we need two declarations. (words(( 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64', 'complex64', 'complex128', 'byte', 'rune', 'string', 'bool', 'error', 'uintptr', 'any', 'comparable', 'print', 'println', 'panic', 'recover', 'close', 'complex', 'real', 'imag', 'len', 'cap', 'append', 'copy', 'delete', 'new', 'make', 'min', 'max', 'clear'), suffix=r'\b(\()'), bygroups(Name.Builtin, Punctuation)), (words(( 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64', 'complex64', 'complex128', 'byte', 'rune', 'string', 'bool', 'error', 'uintptr', 'any', 'comparable'), suffix=r'\b'), Keyword.Type), # imaginary_lit (r'\d+i', Number), (r'\d+\.\d*([Ee][-+]\d+)?i', Number), (r'\.\d+([Ee][-+]\d+)?i', Number), (r'\d+[Ee][-+]\d+i', Number), # float_lit (r'\d+(\.\d+[eE][+\-]?\d+|' r'\.\d*|[eE][+\-]?\d+)', Number.Float), (r'\.\d+([eE][+\-]?\d+)?', Number.Float), # int_lit # -- octal_lit (r'0[0-7]+', Number.Oct), # -- hex_lit (r'0[xX][0-9a-fA-F]+', Number.Hex), # -- decimal_lit (r'(0|[1-9][0-9]*)', Number.Integer), # char_lit (r"""'(\\['"\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|[^\\])'""", String.Char), # StringLiteral # -- raw_string_lit (r'`[^`]*`', String), # -- interpreted_string_lit (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # Tokens (r'(<<=|>>=|<<|>>|<=|>=|&\^=|&\^|\+=|-=|\*=|/=|%=|&=|\|=|&&|\|\|' r'|<-|\+\+|--|==|!=|:=|\.\.\.|[+\-*/%&]' r'|~|\|)', Operator), (r'[|^<>=!()\[\]{}.,;:]', Punctuation), # identifier (r'[^\W\d]\w*', Name.Other), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262""" pygments.lexers.grammar_notation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for grammar notations like BNF.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, this, using, wordsfrom pygments.token import Comment, Keyword, Literal, Name, Number, \ Operator, Punctuation, String, Text, Whitespace
__all__ = ['BnfLexer', 'AbnfLexer', 'JsgfLexer', 'PegLexer']
class BnfLexer(RegexLexer): """ This lexer is for grammar notations which are similar to original BNF.
In order to maximize a number of targets of this lexer, let's decide some designs:
* We don't distinguish `Terminal Symbol`.
* We do assume that `NonTerminal Symbol` are always enclosed with arrow brackets.
* We do assume that `NonTerminal Symbol` may include any printable characters except arrow brackets and ASCII 0x20. This assumption is for `RBNF <http://www.rfc-base.org/txt/rfc-5511.txt>`_.
* We do assume that target notation doesn't support comment.
* We don't distinguish any operators and punctuation except `::=`.
Though these decision making might cause too minimal highlighting and you might be disappointed, but it is reasonable for us. """
name = 'BNF' aliases = ['bnf'] filenames = ['*.bnf'] mimetypes = ['text/x-bnf'] url = 'https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form' version_added = '2.1'
tokens = { 'root': [ (r'(<)([ -;=?-~]+)(>)', bygroups(Punctuation, Name.Class, Punctuation)),
# an only operator (r'::=', Operator),
# fallback (r'[^<>:]+', Text), # for performance (r'.', Text), ], }
class AbnfLexer(RegexLexer): """ Lexer for IETF 7405 ABNF.
(Updates `5234 <http://www.ietf.org/rfc/rfc5234.txt>`_) grammars. """
name = 'ABNF' url = 'http://www.ietf.org/rfc/rfc7405.txt' aliases = ['abnf'] filenames = ['*.abnf'] mimetypes = ['text/x-abnf'] version_added = '2.1'
_core_rules = ( 'ALPHA', 'BIT', 'CHAR', 'CR', 'CRLF', 'CTL', 'DIGIT', 'DQUOTE', 'HEXDIG', 'HTAB', 'LF', 'LWSP', 'OCTET', 'SP', 'VCHAR', 'WSP')
tokens = { 'root': [ # comment (r';.*$', Comment.Single),
# quoted # double quote itself in this state, it is as '%x22'. (r'(%[si])?"[^"]*"', Literal),
# binary (but i have never seen...) (r'%b[01]+\-[01]+\b', Literal), # range (r'%b[01]+(\.[01]+)*\b', Literal), # concat
# decimal (r'%d[0-9]+\-[0-9]+\b', Literal), # range (r'%d[0-9]+(\.[0-9]+)*\b', Literal), # concat
# hexadecimal (r'%x[0-9a-fA-F]+\-[0-9a-fA-F]+\b', Literal), # range (r'%x[0-9a-fA-F]+(\.[0-9a-fA-F]+)*\b', Literal), # concat
# repetition (<a>*<b>element) including nRule (r'\b[0-9]+\*[0-9]+', Operator), (r'\b[0-9]+\*', Operator), (r'\b[0-9]+', Operator), (r'\*', Operator),
# Strictly speaking, these are not keyword but # are called `Core Rule'. (words(_core_rules, suffix=r'\b'), Keyword),
# nonterminals (ALPHA *(ALPHA / DIGIT / "-")) (r'[a-zA-Z][a-zA-Z0-9-]*\b', Name.Class),
# operators (r'(=/|=|/)', Operator),
# punctuation (r'[\[\]()]', Punctuation),
# fallback (r'\s+', Whitespace), (r'.', Text), ], }
class JsgfLexer(RegexLexer): """ For JSpeech Grammar Format grammars. """ name = 'JSGF' url = 'https://www.w3.org/TR/jsgf/' aliases = ['jsgf'] filenames = ['*.jsgf'] mimetypes = ['application/jsgf', 'application/x-jsgf', 'text/jsgf'] version_added = '2.2'
tokens = { 'root': [ include('comments'), include('non-comments'), ], 'comments': [ (r'/\*\*(?!/)', Comment.Multiline, 'documentation comment'), (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'//.*$', Comment.Single), ], 'non-comments': [ (r'\A#JSGF[^;]*', Comment.Preproc), (r'\s+', Whitespace), (r';', Punctuation), (r'[=|()\[\]*+]', Operator), (r'/[^/]+/', Number.Float), (r'"', String.Double, 'string'), (r'\{', String.Other, 'tag'), (words(('import', 'public'), suffix=r'\b'), Keyword.Reserved), (r'grammar\b', Keyword.Reserved, 'grammar name'), (r'(<)(NULL|VOID)(>)', bygroups(Punctuation, Name.Builtin, Punctuation)), (r'<', Punctuation, 'rulename'), (r'\w+|[^\s;=|()\[\]*+/"{<\w]+', Text), ], 'string': [ (r'"', String.Double, '#pop'), (r'\\.', String.Escape), (r'[^\\"]+', String.Double), ], 'tag': [ (r'\}', String.Other, '#pop'), (r'\\.', String.Escape), (r'[^\\}]+', String.Other), ], 'grammar name': [ (r';', Punctuation, '#pop'), (r'\s+', Whitespace), (r'\.', Punctuation), (r'[^;\s.]+', Name.Namespace), ], 'rulename': [ (r'>', Punctuation, '#pop'), (r'\*', Punctuation), (r'\s+', Whitespace), (r'([^.>]+)(\s*)(\.)', bygroups(Name.Namespace, Text, Punctuation)), (r'[^.>]+', Name.Constant), ], 'documentation comment': [ (r'\*/', Comment.Multiline, '#pop'), (r'^(\s*)(\*?)(\s*)(@(?:example|see))(\s+)' r'([\w\W]*?(?=(?:^\s*\*?\s*@|\*/)))', bygroups(Whitespace, Comment.Multiline, Whitespace, Comment.Special, Whitespace, using(this, state='example'))), (r'(^\s*\*?\s*)(@\S*)', bygroups(Comment.Multiline, Comment.Special)), (r'[^*\n@]+|\w|\W', Comment.Multiline), ], 'example': [ (r'(\n\s*)(\*)', bygroups(Whitespace, Comment.Multiline)), include('non-comments'), (r'.', Comment.Multiline), ], }
class PegLexer(RegexLexer): """ This lexer is for Parsing Expression Grammars (PEG).
Various implementations of PEG have made different decisions regarding the syntax, so let's try to be accommodating:
* `<-`, `←`, `:`, and `=` are all accepted as rule operators.
* Both `|` and `/` are choice operators.
* `^`, `↑`, and `~` are cut operators.
* A single `a-z` character immediately before a string, or multiple `a-z` characters following a string, are part of the string (e.g., `r"..."` or `"..."ilmsuxa`). """
name = 'PEG' url = 'https://bford.info/pub/lang/peg.pdf' aliases = ['peg'] filenames = ['*.peg'] mimetypes = ['text/x-peg'] version_added = '2.6'
tokens = { 'root': [ # Comments (r'#.*$', Comment.Single),
# All operators (r'<-|[←:=/|&!?*+^↑~]', Operator),
# Other punctuation (r'[()]', Punctuation),
# Keywords (r'\.', Keyword),
# Character classes (r'(\[)([^\]]*(?:\\.[^\]\\]*)*)(\])', bygroups(Punctuation, String, Punctuation)),
# Single and double quoted strings (with optional modifiers) (r'[a-z]?"[^"\\]*(?:\\.[^"\\]*)*"[a-z]*', String.Double), (r"[a-z]?'[^'\\]*(?:\\.[^'\\]*)*'[a-z]*", String.Single),
# Nonterminals are not whitespace, operators, or punctuation (r'[^\s<←:=/|&!?*+\^↑~()\[\]"\'#]+', Name.Class),
# Fallback (r'.', Text), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108""" pygments.lexers.graph ~~~~~~~~~~~~~~~~~~~~~
Lexers for graph query languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, using, this, wordsfrom pygments.token import Keyword, Punctuation, Comment, Operator, Name,\ String, Number, Whitespace
__all__ = ['CypherLexer']
class CypherLexer(RegexLexer): """ For Cypher Query Language
For the Cypher version in Neo4j 3.3 """ name = 'Cypher' url = 'https://neo4j.com/docs/developer-manual/3.3/cypher/' aliases = ['cypher'] filenames = ['*.cyp', '*.cypher'] version_added = '2.0'
flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ include('clauses'), include('keywords'), include('relations'), include('strings'), include('whitespace'), include('barewords'), include('comment'), ], 'keywords': [ (r'(create|order|match|limit|set|skip|start|return|with|where|' r'delete|foreach|not|by|true|false)\b', Keyword), ], 'clauses': [ # based on https://neo4j.com/docs/cypher-refcard/3.3/ (r'(create)(\s+)(index|unique)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(drop)(\s+)(contraint|index)(\s+)(on)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(ends)(\s+)(with)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(is)(\s+)(node)(\s+)(key)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(is)(\s+)(null|unique)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(load)(\s+)(csv)(\s+)(from)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(on)(\s+)(match|create)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(optional)(\s+)(match)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(order)(\s+)(by)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(starts)(\s+)(with)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(union)(\s+)(all)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(using)(\s+)(periodic)(\s+)(commit)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(using)(\s+)(index)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(using)(\s+)(range|text|point)(\s+)(index)\b', bygroups(Keyword, Whitespace, Name, Whitespace, Keyword)), (words(( 'all', 'any', 'as', 'asc', 'ascending', 'assert', 'call', 'case', 'create', 'delete', 'desc', 'descending', 'distinct', 'end', 'fieldterminator', 'foreach', 'in', 'limit', 'match', 'merge', 'none', 'not', 'null', 'remove', 'return', 'set', 'skip', 'single', 'start', 'then', 'union', 'unwind', 'yield', 'where', 'when', 'with', 'collect'), suffix=r'\b'), Keyword), ], 'relations': [ (r'(-\[)(.*?)(\]->)', bygroups(Operator, using(this), Operator)), (r'(<-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)), (r'(-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)), (r'-->|<--|\[|\]', Operator), (r'<|>|<>|=|<=|=>|\(|\)|\||:|,|;', Punctuation), (r'[.*{}]', Punctuation), ], 'strings': [ (r'([\'"])(?:\\[tbnrf\'"\\]|[^\\])*?\1', String), (r'`(?:``|[^`])+`', Name.Variable), ], 'whitespace': [ (r'\s+', Whitespace), ], 'barewords': [ (r'[a-z]\w*', Name), (r'\d+', Number), ], 'comment': [ (r'//.*$', Comment.Single), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794""" pygments.lexers.graphics ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for computer graphics and plotting related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, include, bygroups, using, \ this, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, \ Number, Punctuation, String, Whitespace
__all__ = ['GLShaderLexer', 'PostScriptLexer', 'AsymptoteLexer', 'GnuplotLexer', 'PovrayLexer', 'HLSLShaderLexer']
class GLShaderLexer(RegexLexer): """ GLSL (OpenGL Shader) lexer. """ name = 'GLSL' aliases = ['glsl'] filenames = ['*.vert', '*.frag', '*.geo'] mimetypes = ['text/x-glslsrc'] url = 'https://www.khronos.org/api/opengl' version_added = '1.1'
tokens = { 'root': [ (r'#(?:.*\\\n)*.*$', Comment.Preproc), (r'//.*$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?', Operator), (r'[?:]', Operator), # quick hack for ternary (r'\bdefined\b', Operator), (r'[;{}(),\[\]]', Punctuation), # FIXME when e is present, no decimal point needed (r'[+-]?\d*\.\d+([eE][-+]?\d+)?', Number.Float), (r'[+-]?\d+\.\d*([eE][-+]?\d+)?', Number.Float), (r'0[xX][0-9a-fA-F]*', Number.Hex), (r'0[0-7]*', Number.Oct), (r'[1-9][0-9]*', Number.Integer), (words(( # Storage qualifiers 'attribute', 'const', 'uniform', 'varying', 'buffer', 'shared', 'in', 'out', # Layout qualifiers 'layout', # Interpolation qualifiers 'flat', 'smooth', 'noperspective', # Auxiliary qualifiers 'centroid', 'sample', 'patch', # Parameter qualifiers. Some double as Storage qualifiers 'inout', # Precision qualifiers 'lowp', 'mediump', 'highp', 'precision', # Invariance qualifiers 'invariant', # Precise qualifiers 'precise', # Memory qualifiers 'coherent', 'volatile', 'restrict', 'readonly', 'writeonly', # Statements 'break', 'continue', 'do', 'for', 'while', 'switch', 'case', 'default', 'if', 'else', 'subroutine', 'discard', 'return', 'struct'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( # Boolean values 'true', 'false'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), (words(( # Miscellaneous types 'void', 'atomic_uint', # Floating-point scalars and vectors 'float', 'vec2', 'vec3', 'vec4', 'double', 'dvec2', 'dvec3', 'dvec4', # Integer scalars and vectors 'int', 'ivec2', 'ivec3', 'ivec4', 'uint', 'uvec2', 'uvec3', 'uvec4', # Boolean scalars and vectors 'bool', 'bvec2', 'bvec3', 'bvec4', # Matrices 'mat2', 'mat3', 'mat4', 'dmat2', 'dmat3', 'dmat4', 'mat2x2', 'mat2x3', 'mat2x4', 'dmat2x2', 'dmat2x3', 'dmat2x4', 'mat3x2', 'mat3x3', 'mat3x4', 'dmat3x2', 'dmat3x3', 'dmat3x4', 'mat4x2', 'mat4x3', 'mat4x4', 'dmat4x2', 'dmat4x3', 'dmat4x4', # Floating-point samplers 'sampler1D', 'sampler2D', 'sampler3D', 'samplerCube', 'sampler1DArray', 'sampler2DArray', 'samplerCubeArray', 'sampler2DRect', 'samplerBuffer', 'sampler2DMS', 'sampler2DMSArray', # Shadow samplers 'sampler1DShadow', 'sampler2DShadow', 'samplerCubeShadow', 'sampler1DArrayShadow', 'sampler2DArrayShadow', 'samplerCubeArrayShadow', 'sampler2DRectShadow', # Signed integer samplers 'isampler1D', 'isampler2D', 'isampler3D', 'isamplerCube', 'isampler1DArray', 'isampler2DArray', 'isamplerCubeArray', 'isampler2DRect', 'isamplerBuffer', 'isampler2DMS', 'isampler2DMSArray', # Unsigned integer samplers 'usampler1D', 'usampler2D', 'usampler3D', 'usamplerCube', 'usampler1DArray', 'usampler2DArray', 'usamplerCubeArray', 'usampler2DRect', 'usamplerBuffer', 'usampler2DMS', 'usampler2DMSArray', # Floating-point image types 'image1D', 'image2D', 'image3D', 'imageCube', 'image1DArray', 'image2DArray', 'imageCubeArray', 'image2DRect', 'imageBuffer', 'image2DMS', 'image2DMSArray', # Signed integer image types 'iimage1D', 'iimage2D', 'iimage3D', 'iimageCube', 'iimage1DArray', 'iimage2DArray', 'iimageCubeArray', 'iimage2DRect', 'iimageBuffer', 'iimage2DMS', 'iimage2DMSArray', # Unsigned integer image types 'uimage1D', 'uimage2D', 'uimage3D', 'uimageCube', 'uimage1DArray', 'uimage2DArray', 'uimageCubeArray', 'uimage2DRect', 'uimageBuffer', 'uimage2DMS', 'uimage2DMSArray'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(( # Reserved for future use. 'common', 'partition', 'active', 'asm', 'class', 'union', 'enum', 'typedef', 'template', 'this', 'resource', 'goto', 'inline', 'noinline', 'public', 'static', 'extern', 'external', 'interface', 'long', 'short', 'half', 'fixed', 'unsigned', 'superp', 'input', 'output', 'hvec2', 'hvec3', 'hvec4', 'fvec2', 'fvec3', 'fvec4', 'sampler3DRect', 'filter', 'sizeof', 'cast', 'namespace', 'using'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), # All names beginning with "gl_" are reserved. (r'gl_\w*', Name.Builtin), (r'[a-zA-Z_]\w*', Name), (r'\.', Punctuation), (r'\s+', Whitespace), ], }
class HLSLShaderLexer(RegexLexer): """ HLSL (Microsoft Direct3D Shader) lexer. """ name = 'HLSL' aliases = ['hlsl'] filenames = ['*.hlsl', '*.hlsli'] mimetypes = ['text/x-hlsl'] url = 'https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl' version_added = '2.3'
tokens = { 'root': [ (r'#(?:.*\\\n)*.*$', Comment.Preproc), (r'//.*$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?', Operator), (r'[?:]', Operator), # quick hack for ternary (r'\bdefined\b', Operator), (r'[;{}(),.\[\]]', Punctuation), # FIXME when e is present, no decimal point needed (r'[+-]?\d*\.\d+([eE][-+]?\d+)?f?', Number.Float), (r'[+-]?\d+\.\d*([eE][-+]?\d+)?f?', Number.Float), (r'0[xX][0-9a-fA-F]*', Number.Hex), (r'0[0-7]*', Number.Oct), (r'[1-9][0-9]*', Number.Integer), (r'"', String, 'string'), (words(( 'asm','asm_fragment','break','case','cbuffer','centroid','class', 'column_major','compile','compile_fragment','const','continue', 'default','discard','do','else','export','extern','for','fxgroup', 'globallycoherent','groupshared','if','in','inline','inout', 'interface','line','lineadj','linear','namespace','nointerpolation', 'noperspective','NULL','out','packoffset','pass','pixelfragment', 'point','precise','return','register','row_major','sample', 'sampler','shared','stateblock','stateblock_state','static', 'struct','switch','tbuffer','technique','technique10', 'technique11','texture','typedef','triangle','triangleadj', 'uniform','vertexfragment','volatile','while'), prefix=r'\b', suffix=r'\b'), Keyword), (words(('true','false'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), (words(( 'auto','catch','char','const_cast','delete','dynamic_cast','enum', 'explicit','friend','goto','long','mutable','new','operator', 'private','protected','public','reinterpret_cast','short','signed', 'sizeof','static_cast','template','this','throw','try','typename', 'union','unsigned','using','virtual'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), (words(( 'dword','matrix','snorm','string','unorm','unsigned','void','vector', 'BlendState','Buffer','ByteAddressBuffer','ComputeShader', 'DepthStencilState','DepthStencilView','DomainShader', 'GeometryShader','HullShader','InputPatch','LineStream', 'OutputPatch','PixelShader','PointStream','RasterizerState', 'RenderTargetView','RasterizerOrderedBuffer', 'RasterizerOrderedByteAddressBuffer', 'RasterizerOrderedStructuredBuffer','RasterizerOrderedTexture1D', 'RasterizerOrderedTexture1DArray','RasterizerOrderedTexture2D', 'RasterizerOrderedTexture2DArray','RasterizerOrderedTexture3D', 'RWBuffer','RWByteAddressBuffer','RWStructuredBuffer', 'RWTexture1D','RWTexture1DArray','RWTexture2D','RWTexture2DArray', 'RWTexture3D','SamplerState','SamplerComparisonState', 'StructuredBuffer','Texture1D','Texture1DArray','Texture2D', 'Texture2DArray','Texture2DMS','Texture2DMSArray','Texture3D', 'TextureCube','TextureCubeArray','TriangleStream','VertexShader'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(( 'bool','double','float','int','half','min16float','min10float', 'min16int','min12int','min16uint','uint'), prefix=r'\b', suffix=r'([1-4](x[1-4])?)?\b'), Keyword.Type), # vector and matrix types (words(( 'abort','abs','acos','all','AllMemoryBarrier', 'AllMemoryBarrierWithGroupSync','any','AppendStructuredBuffer', 'asdouble','asfloat','asin','asint','asuint','asuint','atan', 'atan2','ceil','CheckAccessFullyMapped','clamp','clip', 'CompileShader','ConsumeStructuredBuffer','cos','cosh','countbits', 'cross','D3DCOLORtoUBYTE4','ddx','ddx_coarse','ddx_fine','ddy', 'ddy_coarse','ddy_fine','degrees','determinant', 'DeviceMemoryBarrier','DeviceMemoryBarrierWithGroupSync','distance', 'dot','dst','errorf','EvaluateAttributeAtCentroid', 'EvaluateAttributeAtSample','EvaluateAttributeSnapped','exp', 'exp2','f16tof32','f32tof16','faceforward','firstbithigh', 'firstbitlow','floor','fma','fmod','frac','frexp','fwidth', 'GetRenderTargetSampleCount','GetRenderTargetSamplePosition', 'GlobalOrderedCountIncrement','GroupMemoryBarrier', 'GroupMemoryBarrierWithGroupSync','InterlockedAdd','InterlockedAnd', 'InterlockedCompareExchange','InterlockedCompareStore', 'InterlockedExchange','InterlockedMax','InterlockedMin', 'InterlockedOr','InterlockedXor','isfinite','isinf','isnan', 'ldexp','length','lerp','lit','log','log10','log2','mad','max', 'min','modf','msad4','mul','noise','normalize','pow','printf', 'Process2DQuadTessFactorsAvg','Process2DQuadTessFactorsMax', 'Process2DQuadTessFactorsMin','ProcessIsolineTessFactors', 'ProcessQuadTessFactorsAvg','ProcessQuadTessFactorsMax', 'ProcessQuadTessFactorsMin','ProcessTriTessFactorsAvg', 'ProcessTriTessFactorsMax','ProcessTriTessFactorsMin', 'QuadReadLaneAt','QuadSwapX','QuadSwapY','radians','rcp', 'reflect','refract','reversebits','round','rsqrt','saturate', 'sign','sin','sincos','sinh','smoothstep','sqrt','step','tan', 'tanh','tex1D','tex1D','tex1Dbias','tex1Dgrad','tex1Dlod', 'tex1Dproj','tex2D','tex2D','tex2Dbias','tex2Dgrad','tex2Dlod', 'tex2Dproj','tex3D','tex3D','tex3Dbias','tex3Dgrad','tex3Dlod', 'tex3Dproj','texCUBE','texCUBE','texCUBEbias','texCUBEgrad', 'texCUBElod','texCUBEproj','transpose','trunc','WaveAllBitAnd', 'WaveAllMax','WaveAllMin','WaveAllBitOr','WaveAllBitXor', 'WaveAllEqual','WaveAllProduct','WaveAllSum','WaveAllTrue', 'WaveAnyTrue','WaveBallot','WaveGetLaneCount','WaveGetLaneIndex', 'WaveGetOrderedIndex','WaveIsHelperLane','WaveOnce', 'WavePrefixProduct','WavePrefixSum','WaveReadFirstLane', 'WaveReadLaneAt'), prefix=r'\b', suffix=r'\b'), Name.Builtin), # built-in functions (words(( 'SV_ClipDistance','SV_ClipDistance0','SV_ClipDistance1', 'SV_Culldistance','SV_CullDistance0','SV_CullDistance1', 'SV_Coverage','SV_Depth','SV_DepthGreaterEqual', 'SV_DepthLessEqual','SV_DispatchThreadID','SV_DomainLocation', 'SV_GroupID','SV_GroupIndex','SV_GroupThreadID','SV_GSInstanceID', 'SV_InnerCoverage','SV_InsideTessFactor','SV_InstanceID', 'SV_IsFrontFace','SV_OutputControlPointID','SV_Position', 'SV_PrimitiveID','SV_RenderTargetArrayIndex','SV_SampleIndex', 'SV_StencilRef','SV_TessFactor','SV_VertexID', 'SV_ViewportArrayIndex'), prefix=r'\b', suffix=r'\b'), Name.Decorator), # system-value semantics (r'\bSV_Target[0-7]?\b', Name.Decorator), (words(( 'allow_uav_condition','branch','call','domain','earlydepthstencil', 'fastopt','flatten','forcecase','instance','loop','maxtessfactor', 'numthreads','outputcontrolpoints','outputtopology','partitioning', 'patchconstantfunc','unroll'), prefix=r'\b', suffix=r'\b'), Name.Decorator), # attributes (r'[a-zA-Z_]\w*', Name), (r'\\$', Comment.Preproc), # backslash at end of line -- usually macro continuation (r'\s+', Whitespace), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ], }
class PostScriptLexer(RegexLexer): """ Lexer for PostScript files. """ name = 'PostScript' url = 'https://en.wikipedia.org/wiki/PostScript' aliases = ['postscript', 'postscr'] filenames = ['*.ps', '*.eps'] mimetypes = ['application/postscript'] version_added = '1.4'
delimiter = r'()<>\[\]{}/%\s' delimiter_end = rf'(?=[{delimiter}])'
valid_name_chars = rf'[^{delimiter}]' valid_name = rf"{valid_name_chars}+{delimiter_end}"
tokens = { 'root': [ # All comment types (r'^%!.+$', Comment.Preproc), (r'%%.*$', Comment.Special), (r'(^%.*\n){2,}', Comment.Multiline), (r'%.*$', Comment.Single),
# String literals are awkward; enter separate state. (r'\(', String, 'stringliteral'),
(r'[{}<>\[\]]', Punctuation),
# Numbers (r'<[0-9A-Fa-f]+>' + delimiter_end, Number.Hex), # Slight abuse: use Oct to signify any explicit base system (r'[0-9]+\#(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)' r'((e|E)[0-9]+)?' + delimiter_end, Number.Oct), (r'(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)((e|E)[0-9]+)?' + delimiter_end, Number.Float), (r'(\-|\+)?[0-9]+' + delimiter_end, Number.Integer),
# References (rf'\/{valid_name}', Name.Variable),
# Names (valid_name, Name.Function), # Anything else is executed
# These keywords taken from # <http://www.math.ubc.ca/~cass/graphics/manual/pdf/a1.pdf> # Is there an authoritative list anywhere that doesn't involve # trawling documentation?
(r'(false|true)' + delimiter_end, Keyword.Constant),
# Conditionals / flow control (r'(eq|ne|g[et]|l[et]|and|or|not|if(?:else)?|for(?:all)?)' + delimiter_end, Keyword.Reserved),
(words(( 'abs', 'add', 'aload', 'arc', 'arcn', 'array', 'atan', 'begin', 'bind', 'ceiling', 'charpath', 'clip', 'closepath', 'concat', 'concatmatrix', 'copy', 'cos', 'currentlinewidth', 'currentmatrix', 'currentpoint', 'curveto', 'cvi', 'cvs', 'def', 'defaultmatrix', 'dict', 'dictstackoverflow', 'div', 'dtransform', 'dup', 'end', 'exch', 'exec', 'exit', 'exp', 'fill', 'findfont', 'floor', 'get', 'getinterval', 'grestore', 'gsave', 'gt', 'identmatrix', 'idiv', 'idtransform', 'index', 'invertmatrix', 'itransform', 'length', 'lineto', 'ln', 'load', 'log', 'loop', 'matrix', 'mod', 'moveto', 'mul', 'neg', 'newpath', 'pathforall', 'pathbbox', 'pop', 'print', 'pstack', 'put', 'quit', 'rand', 'rangecheck', 'rcurveto', 'repeat', 'restore', 'rlineto', 'rmoveto', 'roll', 'rotate', 'round', 'run', 'save', 'scale', 'scalefont', 'setdash', 'setfont', 'setgray', 'setlinecap', 'setlinejoin', 'setlinewidth', 'setmatrix', 'setrgbcolor', 'shfill', 'show', 'showpage', 'sin', 'sqrt', 'stack', 'stringwidth', 'stroke', 'strokepath', 'sub', 'syntaxerror', 'transform', 'translate', 'truncate', 'typecheck', 'undefined', 'undefinedfilename', 'undefinedresult'), suffix=delimiter_end), Name.Builtin),
(r'\s+', Whitespace), ],
'stringliteral': [ (r'[^()\\]+', String), (r'\\', String.Escape, 'escape'), (r'\(', String, '#push'), (r'\)', String, '#pop'), ],
'escape': [ (r'[0-8]{3}|n|r|t|b|f|\\|\(|\)', String.Escape, '#pop'), default('#pop'), ], }
class AsymptoteLexer(RegexLexer): """ For Asymptote source code. """ name = 'Asymptote' url = 'http://asymptote.sf.net/' aliases = ['asymptote', 'asy'] filenames = ['*.asy'] mimetypes = ['text/x-asymptote'] version_added = '1.2'
#: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/\*.*?\*/)+'
tokens = { 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//(\n|(.|\n)*?[^\\]\n)', Comment), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment), ], 'statements': [ # simple string (TeX friendly) (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # C style string (with character escapes) (r"'", String, 'string'), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'0x[0-9a-fA-F]+[Ll]?', Number.Hex), (r'0[0-7]+[Ll]?', Number.Oct), (r'\d+[Ll]?', Number.Integer), (r'[~!%^&*+=|?:<>/-]', Operator), (r'[()\[\],.]', Punctuation), (r'\b(case)(.+?)(:)', bygroups(Keyword, using(this), Text)), (r'(and|controls|tension|atleast|curl|if|else|while|for|do|' r'return|break|continue|struct|typedef|new|access|import|' r'unravel|from|include|quote|static|public|private|restricted|' r'this|explicit|true|false|null|cycle|newframe|operator)\b', Keyword), # Since an asy-type-name can be also an asy-function-name, # in the following we test if the string " [a-zA-Z]" follows # the Keyword.Type. # Of course it is not perfect ! (r'(Braid|FitResult|Label|Legend|TreeNode|abscissa|arc|arrowhead|' r'binarytree|binarytreeNode|block|bool|bool3|bounds|bqe|circle|' r'conic|coord|coordsys|cputime|ellipse|file|filltype|frame|grid3|' r'guide|horner|hsv|hyperbola|indexedTransform|int|inversion|key|' r'light|line|linefit|marginT|marker|mass|object|pair|parabola|path|' r'path3|pen|picture|point|position|projection|real|revolution|' r'scaleT|scientific|segment|side|slice|splitface|string|surface|' r'tensionSpecifier|ticklocate|ticksgridT|tickvalues|transform|' r'transformation|tree|triangle|trilinear|triple|vector|' r'vertex|void)(?=\s+[a-zA-Z])', Keyword.Type), # Now the asy-type-name which are not asy-function-name # except yours ! # Perhaps useless (r'(Braid|FitResult|TreeNode|abscissa|arrowhead|block|bool|bool3|' r'bounds|coord|frame|guide|horner|int|linefit|marginT|pair|pen|' r'picture|position|real|revolution|slice|splitface|ticksgridT|' r'tickvalues|tree|triple|vertex|void)\b', Keyword.Type), (r'[a-zA-Z_]\w*:(?!:)', Name.Label), (r'[a-zA-Z_]\w*', Name), ], 'root': [ include('whitespace'), # functions (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments r'([a-zA-Z_]\w*)' # method name r'(\s*\([^;]*?\))' # signature r'(' + _ws + r')(\{)', bygroups(using(this), Name.Function, using(this), using(this), Punctuation), 'function'), # function declarations (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments r'([a-zA-Z_]\w*)' # method name r'(\s*\([^;]*?\))' # signature r'(' + _ws + r')(;)', bygroups(using(this), Name.Function, using(this), using(this), Punctuation)), default('statement'), ], 'statement': [ include('whitespace'), include('statements'), ('[{}]', Punctuation), (';', Punctuation, '#pop'), ], 'function': [ include('whitespace'), include('statements'), (';', Punctuation), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], 'string': [ (r"'", String, '#pop'), (r'\\([\\abfnrtv"\'?]|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'\n', String), (r"[^\\'\n]+", String), # all other characters (r'\\\n', String), (r'\\n', String), # line continuation (r'\\', String), # stray backslash ], }
def get_tokens_unprocessed(self, text): from pygments.lexers._asy_builtins import ASYFUNCNAME, ASYVARNAME for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name and value in ASYFUNCNAME: token = Name.Function elif token is Name and value in ASYVARNAME: token = Name.Variable yield index, token, value
def _shortened(word): dpos = word.find('$') return '|'.join(word[:dpos] + word[dpos+1:i] + r'\b' for i in range(len(word), dpos, -1))
def _shortened_many(*words): return '|'.join(map(_shortened, words))
class GnuplotLexer(RegexLexer): """ For Gnuplot plotting scripts. """
name = 'Gnuplot' url = 'http://gnuplot.info/' aliases = ['gnuplot'] filenames = ['*.plot', '*.plt'] mimetypes = ['text/x-gnuplot'] version_added = '0.11'
tokens = { 'root': [ include('whitespace'), (_shortened('bi$nd'), Keyword, 'bind'), (_shortened_many('ex$it', 'q$uit'), Keyword, 'quit'), (_shortened('f$it'), Keyword, 'fit'), (r'(if)(\s*)(\()', bygroups(Keyword, Text, Punctuation), 'if'), (r'else\b', Keyword), (_shortened('pa$use'), Keyword, 'pause'), (_shortened_many('p$lot', 'rep$lot', 'sp$lot'), Keyword, 'plot'), (_shortened('sa$ve'), Keyword, 'save'), (_shortened('se$t'), Keyword, ('genericargs', 'optionarg')), (_shortened_many('sh$ow', 'uns$et'), Keyword, ('noargs', 'optionarg')), (_shortened_many('low$er', 'ra$ise', 'ca$ll', 'cd$', 'cl$ear', 'h$elp', '\\?$', 'hi$story', 'l$oad', 'pr$int', 'pwd$', 're$read', 'res$et', 'scr$eendump', 'she$ll', 'sy$stem', 'up$date'), Keyword, 'genericargs'), (_shortened_many('pwd$', 're$read', 'res$et', 'scr$eendump', 'she$ll', 'test$'), Keyword, 'noargs'), (r'([a-zA-Z_]\w*)(\s*)(=)', bygroups(Name.Variable, Whitespace, Operator), 'genericargs'), (r'([a-zA-Z_]\w*)(\s*)(\()(.*?)(\))(\s*)(=)', bygroups(Name.Function, Whitespace, Punctuation, Text, Punctuation, Whitespace, Operator), 'genericargs'), (r'@[a-zA-Z_]\w*', Name.Constant), # macros (r';', Keyword), ], 'comment': [ (r'[^\\\n]+', Comment), (r'\\\n', Comment), (r'\\', Comment), # don't add the newline to the Comment token default('#pop'), ], 'whitespace': [ ('#', Comment, 'comment'), (r'[ \t\v\f]+', Whitespace), ], 'noargs': [ include('whitespace'), # semicolon and newline end the argument list (r';', Punctuation, '#pop'), (r'\n', Whitespace, '#pop'), ], 'dqstring': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash (r'\n', Whitespace, '#pop'), # newline ends the string too ], 'sqstring': [ (r"''", String), # escaped single quote (r"'", String, '#pop'), (r"[^\\'\n]+", String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # normal backslash (r'\n', Whitespace, '#pop'), # newline ends the string too ], 'genericargs': [ include('noargs'), (r'"', String, 'dqstring'), (r"'", String, 'sqstring'), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float), (r'(\d+\.\d*|\.\d+)', Number.Float), (r'-?\d+', Number.Integer), ('[,.~!%^&*+=|?:<>/-]', Operator), (r'[{}()\[\]]', Punctuation), (r'(eq|ne)\b', Operator.Word), (r'([a-zA-Z_]\w*)(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[a-zA-Z_]\w*', Name), (r'@[a-zA-Z_]\w*', Name.Constant), # macros (r'(\\)(\n)', bygroups(Text, Whitespace)), ], 'optionarg': [ include('whitespace'), (_shortened_many( "a$ll", "an$gles", "ar$row", "au$toscale", "b$ars", "bor$der", "box$width", "cl$abel", "c$lip", "cn$trparam", "co$ntour", "da$ta", "data$file", "dg$rid3d", "du$mmy", "enc$oding", "dec$imalsign", "fit$", "font$path", "fo$rmat", "fu$nction", "fu$nctions", "g$rid", "hid$den3d", "his$torysize", "is$osamples", "k$ey", "keyt$itle", "la$bel", "li$nestyle", "ls$", "loa$dpath", "loc$ale", "log$scale", "mac$ros", "map$ping", "map$ping3d", "mar$gin", "lmar$gin", "rmar$gin", "tmar$gin", "bmar$gin", "mo$use", "multi$plot", "mxt$ics", "nomxt$ics", "mx2t$ics", "nomx2t$ics", "myt$ics", "nomyt$ics", "my2t$ics", "nomy2t$ics", "mzt$ics", "nomzt$ics", "mcbt$ics", "nomcbt$ics", "of$fsets", "or$igin", "o$utput", "pa$rametric", "pm$3d", "pal$ette", "colorb$ox", "p$lot", "poi$ntsize", "pol$ar", "pr$int", "obj$ect", "sa$mples", "si$ze", "st$yle", "su$rface", "table$", "t$erminal", "termo$ptions", "ti$cs", "ticsc$ale", "ticsl$evel", "timef$mt", "tim$estamp", "tit$le", "v$ariables", "ve$rsion", "vi$ew", "xyp$lane", "xda$ta", "x2da$ta", "yda$ta", "y2da$ta", "zda$ta", "cbda$ta", "xl$abel", "x2l$abel", "yl$abel", "y2l$abel", "zl$abel", "cbl$abel", "xti$cs", "noxti$cs", "x2ti$cs", "nox2ti$cs", "yti$cs", "noyti$cs", "y2ti$cs", "noy2ti$cs", "zti$cs", "nozti$cs", "cbti$cs", "nocbti$cs", "xdti$cs", "noxdti$cs", "x2dti$cs", "nox2dti$cs", "ydti$cs", "noydti$cs", "y2dti$cs", "noy2dti$cs", "zdti$cs", "nozdti$cs", "cbdti$cs", "nocbdti$cs", "xmti$cs", "noxmti$cs", "x2mti$cs", "nox2mti$cs", "ymti$cs", "noymti$cs", "y2mti$cs", "noy2mti$cs", "zmti$cs", "nozmti$cs", "cbmti$cs", "nocbmti$cs", "xr$ange", "x2r$ange", "yr$ange", "y2r$ange", "zr$ange", "cbr$ange", "rr$ange", "tr$ange", "ur$ange", "vr$ange", "xzeroa$xis", "x2zeroa$xis", "yzeroa$xis", "y2zeroa$xis", "zzeroa$xis", "zeroa$xis", "z$ero"), Name.Builtin, '#pop'), ], 'bind': [ ('!', Keyword, '#pop'), (_shortened('all$windows'), Name.Builtin), include('genericargs'), ], 'quit': [ (r'gnuplot\b', Keyword), include('noargs'), ], 'fit': [ (r'via\b', Name.Builtin), include('plot'), ], 'if': [ (r'\)', Punctuation, '#pop'), include('genericargs'), ], 'pause': [ (r'(mouse|any|button1|button2|button3)\b', Name.Builtin), (_shortened('key$press'), Name.Builtin), include('genericargs'), ], 'plot': [ (_shortened_many('ax$es', 'axi$s', 'bin$ary', 'ev$ery', 'i$ndex', 'mat$rix', 's$mooth', 'thru$', 't$itle', 'not$itle', 'u$sing', 'w$ith'), Name.Builtin), include('genericargs'), ], 'save': [ (_shortened_many('f$unctions', 's$et', 't$erminal', 'v$ariables'), Name.Builtin), include('genericargs'), ], }
class PovrayLexer(RegexLexer): """ For Persistence of Vision Raytracer files. """ name = 'POVRay' url = 'http://www.povray.org/' aliases = ['pov'] filenames = ['*.pov', '*.inc'] mimetypes = ['text/x-povray'] version_added = '0.11'
tokens = { 'root': [ (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'//.*$', Comment.Single), (r'(?s)"(?:\\.|[^"\\])+"', String.Double), (words(( 'break', 'case', 'debug', 'declare', 'default', 'define', 'else', 'elseif', 'end', 'error', 'fclose', 'fopen', 'for', 'if', 'ifdef', 'ifndef', 'include', 'local', 'macro', 'range', 'read', 'render', 'statistics', 'switch', 'undef', 'version', 'warning', 'while', 'write'), prefix=r'#', suffix=r'\b'), Comment.Preproc), (words(( 'aa_level', 'aa_threshold', 'abs', 'acos', 'acosh', 'adaptive', 'adc_bailout', 'agate', 'agate_turb', 'all', 'alpha', 'ambient', 'ambient_light', 'angle', 'aperture', 'arc_angle', 'area_light', 'asc', 'asin', 'asinh', 'assumed_gamma', 'atan', 'atan2', 'atanh', 'atmosphere', 'atmospheric_attenuation', 'attenuating', 'average', 'background', 'black_hole', 'blue', 'blur_samples', 'bounded_by', 'box_mapping', 'bozo', 'break', 'brick', 'brick_size', 'brightness', 'brilliance', 'bumps', 'bumpy1', 'bumpy2', 'bumpy3', 'bump_map', 'bump_size', 'case', 'caustics', 'ceil', 'checker', 'chr', 'clipped_by', 'clock', 'color', 'color_map', 'colour', 'colour_map', 'component', 'composite', 'concat', 'confidence', 'conic_sweep', 'constant', 'control0', 'control1', 'cos', 'cosh', 'count', 'crackle', 'crand', 'cube', 'cubic_spline', 'cylindrical_mapping', 'debug', 'declare', 'default', 'degrees', 'dents', 'diffuse', 'direction', 'distance', 'distance_maximum', 'div', 'dust', 'dust_type', 'eccentricity', 'else', 'emitting', 'end', 'error', 'error_bound', 'exp', 'exponent', 'fade_distance', 'fade_power', 'falloff', 'falloff_angle', 'false', 'file_exists', 'filter', 'finish', 'fisheye', 'flatness', 'flip', 'floor', 'focal_point', 'fog', 'fog_alt', 'fog_offset', 'fog_type', 'frequency', 'gif', 'global_settings', 'glowing', 'gradient', 'granite', 'gray_threshold', 'green', 'halo', 'hexagon', 'hf_gray_16', 'hierarchy', 'hollow', 'hypercomplex', 'if', 'ifdef', 'iff', 'image_map', 'incidence', 'include', 'int', 'interpolate', 'inverse', 'ior', 'irid', 'irid_wavelength', 'jitter', 'lambda', 'leopard', 'linear', 'linear_spline', 'linear_sweep', 'location', 'log', 'looks_like', 'look_at', 'low_error_factor', 'mandel', 'map_type', 'marble', 'material_map', 'matrix', 'max', 'max_intersections', 'max_iteration', 'max_trace_level', 'max_value', 'metallic', 'min', 'minimum_reuse', 'mod', 'mortar', 'nearest_count', 'no', 'normal', 'normal_map', 'no_shadow', 'number_of_waves', 'octaves', 'off', 'offset', 'omega', 'omnimax', 'on', 'once', 'onion', 'open', 'orthographic', 'panoramic', 'pattern1', 'pattern2', 'pattern3', 'perspective', 'pgm', 'phase', 'phong', 'phong_size', 'pi', 'pigment', 'pigment_map', 'planar_mapping', 'png', 'point_at', 'pot', 'pow', 'ppm', 'precision', 'pwr', 'quadratic_spline', 'quaternion', 'quick_color', 'quick_colour', 'quilted', 'radial', 'radians', 'radiosity', 'radius', 'rainbow', 'ramp_wave', 'rand', 'range', 'reciprocal', 'recursion_limit', 'red', 'reflection', 'refraction', 'render', 'repeat', 'rgb', 'rgbf', 'rgbft', 'rgbt', 'right', 'ripples', 'rotate', 'roughness', 'samples', 'scale', 'scallop_wave', 'scattering', 'seed', 'shadowless', 'sin', 'sine_wave', 'sinh', 'sky', 'sky_sphere', 'slice', 'slope_map', 'smooth', 'specular', 'spherical_mapping', 'spiral', 'spiral1', 'spiral2', 'spotlight', 'spotted', 'sqr', 'sqrt', 'statistics', 'str', 'strcmp', 'strength', 'strlen', 'strlwr', 'strupr', 'sturm', 'substr', 'switch', 'sys', 't', 'tan', 'tanh', 'test_camera_1', 'test_camera_2', 'test_camera_3', 'test_camera_4', 'texture', 'texture_map', 'tga', 'thickness', 'threshold', 'tightness', 'tile2', 'tiles', 'track', 'transform', 'translate', 'transmit', 'triangle_wave', 'true', 'ttf', 'turbulence', 'turb_depth', 'type', 'ultra_wide_angle', 'up', 'use_color', 'use_colour', 'use_index', 'u_steps', 'val', 'variance', 'vaxis_rotate', 'vcross', 'vdot', 'version', 'vlength', 'vnormalize', 'volume_object', 'volume_rendered', 'vol_with_light', 'vrotate', 'v_steps', 'warning', 'warp', 'water_level', 'waves', 'while', 'width', 'wood', 'wrinkles', 'yes'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'bicubic_patch', 'blob', 'box', 'camera', 'cone', 'cubic', 'cylinder', 'difference', 'disc', 'height_field', 'intersection', 'julia_fractal', 'lathe', 'light_source', 'merge', 'mesh', 'object', 'plane', 'poly', 'polygon', 'prism', 'quadric', 'quartic', 'smooth_triangle', 'sor', 'sphere', 'superellipsoid', 'text', 'torus', 'triangle', 'union'), suffix=r'\b'), Name.Builtin), (r'\b(x|y|z|u|v)\b', Name.Builtin.Pseudo), (r'[a-zA-Z_]\w*', Name), (r'[0-9]*\.[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), (r'[\[\](){}<>;,]', Punctuation), (r'[-+*/=.|&]|<=|>=|!=', Operator), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r'\s+', Whitespace), ] }
def analyse_text(text): """POVRAY is similar to JSON/C, but the combination of camera and light_source is probably not very likely elsewhere. HLSL or GLSL are similar (GLSL even has #version), but they miss #declare, and light_source/camera are not keywords anywhere else -- it's fair to assume though that any POVRAY scene must have a camera and lightsource.""" result = 0 if '#version' in text: result += 0.05 if '#declare' in text: result += 0.05 if 'camera' in text: result += 0.05 if 'light_source' in text: result += 0.1
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176""" pygments.lexers.graphql ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for GraphQL, an open-source data query and manipulation language for APIs.
More information: https://graphql.org/
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, include, bygroups, defaultfrom pygments.token import (Comment, Keyword, Name, Number, Punctuation, String, Whitespace)
__all__ = ["GraphQLLexer"]
OPERATION_TYPES = ("query", "mutation", "subscription")BUILTIN_TYPES = ("Int", "Float", "String", "Boolean", "ID")BOOLEAN_VALUES = ("true", "false", "null")KEYWORDS = ( "type", "schema", "extend", "enum", "scalar", "implements", "interface", "union", "input", "directive", "QUERY", "MUTATION", "SUBSCRIPTION", "FIELD", "FRAGMENT_DEFINITION", "FRAGMENT_SPREAD", "INLINE_FRAGMENT", "SCHEMA", "SCALAR", "OBJECT", "FIELD_DEFINITION", "ARGUMENT_DEFINITION", "INTERFACE", "UNION", "ENUM", "ENUM_VALUE", "INPUT_OBJECT", "INPUT_FIELD_DEFINITION",)
class GraphQLLexer(RegexLexer): """ Lexer for GraphQL syntax """ name = "GraphQL" aliases = ["graphql"] filenames = ["*.graphql"] url = "https://graphql.org" version_added = '2.16'
tokens = { "ignored_tokens": [ (r"\s+", Whitespace), # Whitespaces (r"#.*$", Comment), (",", Punctuation), # Insignificant commas ], "value": [ include("ignored_tokens"), (r"-?\d+(?![.eE])", Number.Integer, "#pop"), ( r"-?\d+(\.\d+)?([eE][+-]?\d+)?", Number.Float, "#pop", ), (r'"', String, ("#pop", "string")), (words(BOOLEAN_VALUES, suffix=r"\b"), Name.Builtin, "#pop"), (r"\$[a-zA-Z_]\w*", Name.Variable, "#pop"), (r"[a-zA-Z_]\w*", Name.Constant, "#pop"), (r"\[", Punctuation, ("#pop", "list_value")), (r"\{", Punctuation, ("#pop", "object_value")), ], "list_value": [ include("ignored_tokens"), ("]", Punctuation, "#pop"), default("value"), ], "object_value": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name), (r":", Punctuation, "value"), (r"\}", Punctuation, "#pop"), ], "string": [ (r'\\(["\\/bfnrt]|u[a-fA-F0-9]{4})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'"', String, "#pop"), ], "root": [ include("ignored_tokens"), (words(OPERATION_TYPES, suffix=r"\b"), Keyword, "operation"), (words(KEYWORDS, suffix=r"\b"), Keyword), (r"\{", Punctuation, "selection_set"), (r"fragment\b", Keyword, "fragment_definition"), ], "operation": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name.Function), (r"\(", Punctuation, "variable_definition"), (r"\{", Punctuation, ("#pop", "selection_set")), ], "variable_definition": [ include("ignored_tokens"), (r"\$[a-zA-Z_]\w*", Name.Variable), (r"[\]!]", Punctuation), (r":", Punctuation, "type"), (r"=", Punctuation, "value"), (r"\)", Punctuation, "#pop"), ], "type": [ include("ignored_tokens"), (r"\[", Punctuation), (words(BUILTIN_TYPES, suffix=r"\b"), Name.Builtin, "#pop"), (r"[a-zA-Z_]\w*", Name.Class, "#pop"), ], "selection_set": [ include("ignored_tokens"), (r"([a-zA-Z_]\w*)(\s*)(:)", bygroups(Name.Label, Whitespace, Punctuation)), (r"[a-zA-Z_]\w*", Name), # Field ( r"(\.\.\.)(\s+)(on)\b", bygroups(Punctuation, Whitespace, Keyword), "inline_fragment", ), (r"\.\.\.", Punctuation, "fragment_spread"), (r"\(", Punctuation, "arguments"), (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"\{", Punctuation, "selection_set"), (r"\}", Punctuation, "#pop"), ], "directive": [ include("ignored_tokens"), (r"\(", Punctuation, ("#pop", "arguments")), ], "arguments": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name), (r":", Punctuation, "value"), (r"\)", Punctuation, "#pop"), ], # Fragments "fragment_definition": [ include("ignored_tokens"), (r"[\]!]", Punctuation), # For NamedType (r"on\b", Keyword, "type"), (r"[a-zA-Z_]\w*", Name.Function), (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"\{", Punctuation, ("#pop", "selection_set")), ], "fragment_spread": [ include("ignored_tokens"), (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"[a-zA-Z_]\w*", Name, "#pop"), # Fragment name ], "inline_fragment": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name.Class), # Type condition (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"\{", Punctuation, ("#pop", "selection_set")), ], }.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/c_like.pyAdded+738
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/cddl.pyAdded+172
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/clean.pyAdded+180
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/codeql.pyAdded+80
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/comal.pyAdded+81
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/compiled.pyAdded+35
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/configs.pyAdded+1433
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/console.pyAdded+114
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/cplint.pyAdded+43
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/crystal.pyAdded+364
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/csound.pyAdded+466
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/css.pyAdded+632
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/d.pyAdded+259
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dalvik.pyAdded+126
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/data.pyAdded+763
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dax.pyAdded+135
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/devicetree.pyAdded+120
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/diff.pyAdded+169
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dns.pyAdded+109
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dotnet.pyAdded+873
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dsls.pyAdded+970
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/dylan.pyAdded+279
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ecl.pyAdded+144
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/eiffel.pyAdded+68
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/elm.pyAdded+123
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/elpi.pyAdded+201
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/email.pyAdded+132
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/erlang.pyAdded+526
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/esoteric.pyAdded+300
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ezhil.pyAdded+76
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/factor.pyAdded+363
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/fantom.pyAdded+251
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/felix.pyAdded+275
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/fift.pyAdded+68
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/floscript.pyAdded+81
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/forth.pyAdded+178
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/fortran.pyAdded+212
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/foxpro.pyAdded+427
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/freefem.pyAdded+893
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/func.pyAdded+110
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/functional.pyAdded+21
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/futhark.pyAdded+105
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/gcodelexer.pyAdded+35
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/gdscript.pyAdded+189
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/gleam.pyAdded+74
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/go.pyAdded+97
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/grammar_notation.pyAdded+262
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/graph.pyAdded+108
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/graphics.pyAdded+794
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/graphql.pyAdded+176