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/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/monte.pyAdded+203
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/mosel.pyAdded+447
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ncl.pyAdded+894
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/nimrod.pyAdded+199
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/nit.pyAdded+63
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/nix.pyAdded+144
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/numbair.pyAdded+63
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/oberon.pyAdded+120
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/objective.pyAdded+513
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ooc.pyAdded+84
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/openscad.pyAdded+96
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/other.pyAdded+41
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/parasail.pyAdded+78
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/parsers.pyAdded+798
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pascal.pyAdded+644
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pawn.pyAdded+202
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pddl.pyAdded+82
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/perl.pyAdded+733
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/phix.pyAdded+363
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/php.pyAdded+335
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pointless.pyAdded+70
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pony.pyAdded+93
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/praat.pyAdded+303
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/procfile.pyAdded+41
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/prolog.pyAdded+318
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/promql.pyAdded+176
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/prql.pyAdded+251
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ptx.pyAdded+119
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/python.pyAdded+1204
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/q.pyAdded+187
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/qlik.pyAdded+117
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/qvt.pyAdded+153
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/r.pyAdded+196
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rdf.pyAdded+468
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rebol.pyAdded+419
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rego.pyAdded+57
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rell.pyAdded+68
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/resource.pyAdded+83
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ride.pyAdded+138
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rita.pyAdded+42
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rnc.pyAdded+66
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/roboconf.pyAdded+81
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/robotframework.pyAdded+551
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ruby.pyAdded+518
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rust.pyAdded+222
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/sas.pyAdded+227
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/savi.pyAdded+171
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/scdoc.pyAdded+85
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/scripting.pyAdded+1638
- .cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/sgf.pyAdded+59
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203""" pygments.lexers.monte ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Monte programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.token import Comment, Error, Keyword, Name, Number, Operator, \ Punctuation, String, Whitespacefrom pygments.lexer import RegexLexer, include, words
__all__ = ['MonteLexer']
# `var` handled separately# `interface` handled separately_declarations = ['bind', 'def', 'fn', 'object']_methods = ['method', 'to']_keywords = [ 'as', 'break', 'catch', 'continue', 'else', 'escape', 'exit', 'exports', 'extends', 'finally', 'for', 'guards', 'if', 'implements', 'import', 'in', 'match', 'meta', 'pass', 'return', 'switch', 'try', 'via', 'when', 'while',]_operators = [ # Unary '~', '!', # Binary '+', '-', '*', '/', '%', '**', '&', '|', '^', '<<', '>>', # Binary augmented '+=', '-=', '*=', '/=', '%=', '**=', '&=', '|=', '^=', '<<=', '>>=', # Comparison '==', '!=', '<', '<=', '>', '>=', '<=>', # Patterns and assignment ':=', '?', '=~', '!~', '=>', # Calls and sends '.', '<-', '->',]_escape_pattern = ( r'(?:\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|' r'\\["\'\\bftnr])')# _char = _escape_chars + [('.', String.Char)]_identifier = r'[_a-zA-Z]\w*'
_constants = [ # Void constants 'null', # Bool constants 'false', 'true', # Double constants 'Infinity', 'NaN', # Special objects 'M', 'Ref', 'throw', 'traceln',]
_guards = [ 'Any', 'Binding', 'Bool', 'Bytes', 'Char', 'DeepFrozen', 'Double', 'Empty', 'Int', 'List', 'Map', 'Near', 'NullOk', 'Same', 'Selfless', 'Set', 'Str', 'SubrangeGuard', 'Transparent', 'Void',]
_safeScope = [ '_accumulateList', '_accumulateMap', '_auditedBy', '_bind', '_booleanFlow', '_comparer', '_equalizer', '_iterForever', '_loop', '_makeBytes', '_makeDouble', '_makeFinalSlot', '_makeInt', '_makeList', '_makeMap', '_makeMessageDesc', '_makeOrderedSpace', '_makeParamDesc', '_makeProtocolDesc', '_makeSourceSpan', '_makeString', '_makeVarSlot', '_makeVerbFacet', '_mapExtract', '_matchSame', '_quasiMatcher', '_slotToBinding', '_splitList', '_suchThat', '_switchFailed', '_validateFor', 'b__quasiParser', 'eval', 'import', 'm__quasiParser', 'makeBrandPair', 'makeLazySlot', 'safeScope', 'simple__quasiParser',]
class MonteLexer(RegexLexer): """ Lexer for the Monte programming language. """ name = 'Monte' url = 'https://monte.readthedocs.io/' aliases = ['monte'] filenames = ['*.mt'] version_added = '2.2'
tokens = { 'root': [ # Comments (r'#[^\n]*\n', Comment),
# Docstrings # Apologies for the non-greedy matcher here. (r'/\*\*.*?\*/', String.Doc),
# `var` declarations (r'\bvar\b', Keyword.Declaration, 'var'),
# `interface` declarations (r'\binterface\b', Keyword.Declaration, 'interface'),
# method declarations (words(_methods, prefix='\\b', suffix='\\b'), Keyword, 'method'),
# All other declarations (words(_declarations, prefix='\\b', suffix='\\b'), Keyword.Declaration),
# Keywords (words(_keywords, prefix='\\b', suffix='\\b'), Keyword),
# Literals ('[+-]?0x[_0-9a-fA-F]+', Number.Hex), (r'[+-]?[_0-9]+\.[_0-9]*([eE][+-]?[_0-9]+)?', Number.Float), ('[+-]?[_0-9]+', Number.Integer), ("'", String.Double, 'char'), ('"', String.Double, 'string'),
# Quasiliterals ('`', String.Backtick, 'ql'),
# Operators (words(_operators), Operator),
# Verb operators (_identifier + '=', Operator.Word),
# Safe scope constants (words(_constants, prefix='\\b', suffix='\\b'), Keyword.Pseudo),
# Safe scope guards (words(_guards, prefix='\\b', suffix='\\b'), Keyword.Type),
# All other safe scope names (words(_safeScope, prefix='\\b', suffix='\\b'), Name.Builtin),
# Identifiers (_identifier, Name),
# Punctuation (r'\(|\)|\{|\}|\[|\]|:|,', Punctuation),
# Whitespace (' +', Whitespace),
# Definite lexer errors ('=', Error), ], 'char': [ # It is definitely an error to have a char of width == 0. ("'", Error, 'root'), (_escape_pattern, String.Escape, 'charEnd'), ('.', String.Char, 'charEnd'), ], 'charEnd': [ ("'", String.Char, '#pop:2'), # It is definitely an error to have a char of width > 1. ('.', Error), ], # The state of things coming into an interface. 'interface': [ (' +', Whitespace), (_identifier, Name.Class, '#pop'), include('root'), ], # The state of things coming into a method. 'method': [ (' +', Whitespace), (_identifier, Name.Function, '#pop'), include('root'), ], 'string': [ ('"', String.Double, 'root'), (_escape_pattern, String.Escape), (r'\n', String.Double), ('.', String.Double), ], 'ql': [ ('`', String.Backtick, 'root'), (r'\$' + _escape_pattern, String.Escape), (r'\$\$', String.Escape), (r'@@', String.Escape), (r'\$\{', String.Interpol, 'qlNest'), (r'@\{', String.Interpol, 'qlNest'), (r'\$' + _identifier, Name), ('@' + _identifier, Name), ('.', String.Backtick), ], 'qlNest': [ (r'\}', String.Interpol, '#pop'), include('root'), ], # The state of things immediately following `var`. 'var': [ (' +', Whitespace), (_identifier, Name.Variable, '#pop'), include('root'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447""" pygments.lexers.mosel ~~~~~~~~~~~~~~~~~~~~~
Lexers for the mosel language. http://www.fico.com/en/products/fico-xpress-optimization
: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 Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['MoselLexer']
FUNCTIONS = ( # core functions '_', 'abs', 'arctan', 'asproc', 'assert', 'bitflip', 'bitneg', 'bitset', 'bitshift', 'bittest', 'bitval', 'ceil', 'cos', 'create', 'currentdate', 'currenttime', 'cutelt', 'cutfirst', 'cuthead', 'cutlast', 'cuttail', 'datablock', 'delcell', 'exists', 'exit', 'exp', 'exportprob', 'fclose', 'fflush', 'finalize', 'findfirst', 'findlast', 'floor', 'fopen', 'fselect', 'fskipline', 'fwrite', 'fwrite_', 'fwriteln', 'fwriteln_', 'getact', 'getcoeff', 'getcoeffs', 'getdual', 'getelt', 'getfid', 'getfirst', 'getfname', 'gethead', 'getlast', 'getobjval', 'getparam', 'getrcost', 'getreadcnt', 'getreverse', 'getsize', 'getslack', 'getsol', 'gettail', 'gettype', 'getvars', 'isdynamic', 'iseof', 'isfinite', 'ishidden', 'isinf', 'isnan', 'isodd', 'ln', 'localsetparam', 'log', 'makesos1', 'makesos2', 'maxlist', 'memoryuse', 'minlist', 'newmuid', 'publish', 'random', 'read', 'readln', 'reset', 'restoreparam', 'reverse', 'round', 'setcoeff', 'sethidden', 'setioerr', 'setmatherr', 'setname', 'setparam', 'setrandseed', 'setrange', 'settype', 'sin', 'splithead', 'splittail', 'sqrt', 'strfmt', 'substr', 'timestamp', 'unpublish', 'versionnum', 'versionstr', 'write', 'write_', 'writeln', 'writeln_',
# mosel exam mmxprs | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u 'addcut', 'addcuts', 'addmipsol', 'basisstability', 'calcsolinfo', 'clearmipdir', 'clearmodcut', 'command', 'copysoltoinit', 'crossoverlpsol', 'defdelayedrows', 'defsecurevecs', 'delcuts', 'dropcuts', 'estimatemarginals', 'fixglobal', 'flushmsgq', 'getbstat', 'getcnlist', 'getcplist', 'getdualray', 'getiis', 'getiissense', 'getiistype', 'getinfcause', 'getinfeas', 'getlb', 'getlct', 'getleft', 'getloadedlinctrs', 'getloadedmpvars', 'getname', 'getprimalray', 'getprobstat', 'getrange', 'getright', 'getsensrng', 'getsize', 'getsol', 'gettype', 'getub', 'getvars', 'gety', 'hasfeature', 'implies', 'indicator', 'initglobal', 'ishidden', 'isiisvalid', 'isintegral', 'loadbasis', 'loadcuts', 'loadlpsol', 'loadmipsol', 'loadprob', 'maximise', 'maximize', 'minimise', 'minimize', 'postsolve', 'readbasis', 'readdirs', 'readsol', 'refinemipsol', 'rejectintsol', 'repairinfeas', 'repairinfeas_deprec', 'resetbasis', 'resetiis', 'resetsol', 'savebasis', 'savemipsol', 'savesol', 'savestate', 'selectsol', 'setarchconsistency', 'setbstat', 'setcallback', 'setcbcutoff', 'setgndata', 'sethidden', 'setlb', 'setmipdir', 'setmodcut', 'setsol', 'setub', 'setucbdata', 'stopoptimise', 'stopoptimize', 'storecut', 'storecuts', 'unloadprob', 'uselastbarsol', 'writebasis', 'writedirs', 'writeprob', 'writesol', 'xor', 'xprs_addctr', 'xprs_addindic',
# mosel exam mmsystem | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u 'addmonths', 'copytext', 'cuttext', 'deltext', 'endswith', 'erase', 'expandpath', 'fcopy', 'fdelete', 'findfiles', 'findtext', 'fmove', 'formattext', 'getasnumber', 'getchar', 'getcwd', 'getdate', 'getday', 'getdaynum', 'getdays', 'getdirsep', 'getdsoparam', 'getendparse', 'getenv', 'getfsize', 'getfstat', 'getftime', 'gethour', 'getminute', 'getmonth', 'getmsec', 'getoserrmsg', 'getoserror', 'getpathsep', 'getqtype', 'getsecond', 'getsepchar', 'getsize', 'getstart', 'getsucc', 'getsysinfo', 'getsysstat', 'gettime', 'gettmpdir', 'gettrim', 'getweekday', 'getyear', 'inserttext', 'isvalid', 'jointext', 'makedir', 'makepath', 'newtar', 'newzip', 'nextfield', 'openpipe', 'parseextn', 'parseint', 'parsereal', 'parsetext', 'pastetext', 'pathmatch', 'pathsplit', 'qsort', 'quote', 'readtextline', 'regmatch', 'regreplace', 'removedir', 'removefiles', 'setchar', 'setdate', 'setday', 'setdsoparam', 'setendparse', 'setenv', 'sethour', 'setminute', 'setmonth', 'setmsec', 'setoserror', 'setqtype', 'setsecond', 'setsepchar', 'setstart', 'setsucc', 'settime', 'settrim', 'setyear', 'sleep', 'splittext', 'startswith', 'system', 'tarlist', 'textfmt', 'tolower', 'toupper', 'trim', 'untar', 'unzip', 'ziplist',
# mosel exam mmjobs | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u 'canceltimer', 'clearaliases', 'compile', 'connect', 'detach', 'disconnect', 'dropnextevent', 'findxsrvs', 'getaliases', 'getannidents', 'getannotations', 'getbanner', 'getclass', 'getdsoprop', 'getdsopropnum', 'getexitcode', 'getfromgid', 'getfromid', 'getfromuid', 'getgid', 'gethostalias', 'getid', 'getmodprop', 'getmodpropnum', 'getnextevent', 'getnode', 'getrmtid', 'getstatus', 'getsysinfo', 'gettimer', 'getuid', 'getvalue', 'isqueueempty', 'load', 'nullevent', 'peeknextevent', 'resetmodpar', 'run', 'send', 'setcontrol', 'setdefstream', 'setgid', 'sethostalias', 'setmodpar', 'settimer', 'setuid', 'setworkdir', 'stop', 'unload', 'wait', 'waitexpired', 'waitfor', 'waitforend',)
class MoselLexer(RegexLexer): """ For the Mosel optimization language. """ name = 'Mosel' aliases = ['mosel'] filenames = ['*.mos'] url = 'https://www.fico.com/fico-xpress-optimization/docs/latest/mosel/mosel_lang/dhtml/moselreflang.html' version_added = '2.6'
tokens = { 'root': [ (r'\n', Text), (r'\s+', Text.Whitespace), (r'!.*?\n', Comment.Single), (r'\(!(.|\n)*?!\)', Comment.Multiline), (words(( 'and', 'as', 'break', 'case', 'count', 'declarations', 'do', 'dynamic', 'elif', 'else', 'end-', 'end', 'evaluation', 'false', 'forall', 'forward', 'from', 'function', 'hashmap', 'if', 'imports', 'include', 'initialisations', 'initializations', 'inter', 'max', 'min', 'model', 'namespace', 'next', 'not', 'nsgroup', 'nssearch', 'of', 'options', 'or', 'package', 'parameters', 'procedure', 'public', 'prod', 'record', 'repeat', 'requirements', 'return', 'sum', 'then', 'to', 'true', 'union', 'until', 'uses', 'version', 'while', 'with'), prefix=r'\b', suffix=r'\b'), Keyword.Builtin), (words(( 'range', 'array', 'set', 'list', 'mpvar', 'mpproblem', 'linctr', 'nlctr', 'integer', 'string', 'real', 'boolean', 'text', 'time', 'date', 'datetime', 'returned', 'Model', 'Mosel', 'counter', 'xmldoc', 'is_sos1', 'is_sos2', 'is_integer', 'is_binary', 'is_continuous', 'is_free', 'is_semcont', 'is_semint', 'is_partint'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (r'(\+|\-|\*|/|=|<=|>=|\||\^|<|>|<>|\.\.|\.|:=|::|:|in|mod|div)', Operator), (r'[()\[\]{},;]+', Punctuation), (words(FUNCTIONS, prefix=r'\b', suffix=r'\b'), Name.Function), (r'(\d+\.(?!\.)\d*|\.(?!.)\d+)([eE][+-]?\d+)?', Number.Float), (r'\d+([eE][+-]?\d+)?', Number.Integer), (r'[+-]?Infinity', Number.Integer), (r'0[xX][0-9a-fA-F]+', Number), (r'"', String.Double, 'double_quote'), (r'\'', String.Single, 'single_quote'), (r'(\w+|(\.(?!\.)))', Text), ], 'single_quote': [ (r'\'', String.Single, '#pop'), (r'[^\']+', String.Single), ], 'double_quote': [ (r'(\\"|\\[0-7]{1,3}\D|\\[abfnrtv]|\\\\)', String.Escape), (r'\"', String.Double, '#pop'), (r'[^"\\]+', String.Double), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894""" pygments.lexers.ncl ~~~~~~~~~~~~~~~~~~~
Lexers for NCAR Command 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 Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['NCLLexer']
class NCLLexer(RegexLexer): """ Lexer for NCL code. """ name = 'NCL' aliases = ['ncl'] filenames = ['*.ncl'] mimetypes = ['text/ncl'] url = 'https://www.ncl.ucar.edu' version_added = '2.2'
flags = re.MULTILINE
tokens = { 'root': [ (r';.*\n', Comment), include('strings'), include('core'), (r'[a-zA-Z_]\w*', Name), include('nums'), (r'[\s]+', Text), ], 'core': [ # Statements (words(( 'begin', 'break', 'continue', 'create', 'defaultapp', 'do', 'else', 'end', 'external', 'exit', 'True', 'False', 'file', 'function', 'getvalues', 'graphic', 'group', 'if', 'list', 'load', 'local', 'new', '_Missing', 'Missing', 'noparent', 'procedure', 'quit', 'QUIT', 'Quit', 'record', 'return', 'setvalues', 'stop', 'then', 'while'), prefix=r'\b', suffix=r'\s*\b'), Keyword),
# Data Types (words(( 'ubyte', 'uint', 'uint64', 'ulong', 'string', 'byte', 'character', 'double', 'float', 'integer', 'int64', 'logical', 'long', 'short', 'ushort', 'enumeric', 'numeric', 'snumeric'), prefix=r'\b', suffix=r'\s*\b'), Keyword.Type),
# Operators (r'[\%^*+\-/<>]', Operator),
# punctuation: (r'[\[\]():@$!&|.,\\{}]', Punctuation), (r'[=:]', Punctuation),
# Intrinsics (words(( 'abs', 'acos', 'addfile', 'addfiles', 'all', 'angmom_atm', 'any', 'area_conserve_remap', 'area_hi2lores', 'area_poly_sphere', 'asciiread', 'asciiwrite', 'asin', 'atan', 'atan2', 'attsetvalues', 'avg', 'betainc', 'bin_avg', 'bin_sum', 'bw_bandpass_filter', 'cancor', 'cbinread', 'cbinwrite', 'cd_calendar', 'cd_inv_calendar', 'cdfbin_p', 'cdfbin_pr', 'cdfbin_s', 'cdfbin_xn', 'cdfchi_p', 'cdfchi_x', 'cdfgam_p', 'cdfgam_x', 'cdfnor_p', 'cdfnor_x', 'cdft_p', 'cdft_t', 'ceil', 'center_finite_diff', 'center_finite_diff_n', 'cfftb', 'cfftf', 'cfftf_frq_reorder', 'charactertodouble', 'charactertofloat', 'charactertointeger', 'charactertolong', 'charactertoshort', 'charactertostring', 'chartodouble', 'chartofloat', 'chartoint', 'chartointeger', 'chartolong', 'chartoshort', 'chartostring', 'chiinv', 'clear', 'color_index_to_rgba', 'conform', 'conform_dims', 'cos', 'cosh', 'count_unique_values', 'covcorm', 'covcorm_xy', 'craybinnumrec', 'craybinrecread', 'create_graphic', 'csa1', 'csa1d', 'csa1s', 'csa1x', 'csa1xd', 'csa1xs', 'csa2', 'csa2d', 'csa2l', 'csa2ld', 'csa2ls', 'csa2lx', 'csa2lxd', 'csa2lxs', 'csa2s', 'csa2x', 'csa2xd', 'csa2xs', 'csa3', 'csa3d', 'csa3l', 'csa3ld', 'csa3ls', 'csa3lx', 'csa3lxd', 'csa3lxs', 'csa3s', 'csa3x', 'csa3xd', 'csa3xs', 'csc2s', 'csgetp', 'css2c', 'cssetp', 'cssgrid', 'csstri', 'csvoro', 'cumsum', 'cz2ccm', 'datatondc', 'day_of_week', 'day_of_year', 'days_in_month', 'default_fillvalue', 'delete', 'depth_to_pres', 'destroy', 'determinant', 'dewtemp_trh', 'dgeevx_lapack', 'dim_acumrun_n', 'dim_avg', 'dim_avg_n', 'dim_avg_wgt', 'dim_avg_wgt_n', 'dim_cumsum', 'dim_cumsum_n', 'dim_gamfit_n', 'dim_gbits', 'dim_max', 'dim_max_n', 'dim_median', 'dim_median_n', 'dim_min', 'dim_min_n', 'dim_num', 'dim_num_n', 'dim_numrun_n', 'dim_pqsort', 'dim_pqsort_n', 'dim_product', 'dim_product_n', 'dim_rmsd', 'dim_rmsd_n', 'dim_rmvmean', 'dim_rmvmean_n', 'dim_rmvmed', 'dim_rmvmed_n', 'dim_spi_n', 'dim_standardize', 'dim_standardize_n', 'dim_stat4', 'dim_stat4_n', 'dim_stddev', 'dim_stddev_n', 'dim_sum', 'dim_sum_n', 'dim_sum_wgt', 'dim_sum_wgt_n', 'dim_variance', 'dim_variance_n', 'dimsizes', 'doubletobyte', 'doubletochar', 'doubletocharacter', 'doubletofloat', 'doubletoint', 'doubletointeger', 'doubletolong', 'doubletoshort', 'dpres_hybrid_ccm', 'dpres_plevel', 'draw', 'draw_color_palette', 'dsgetp', 'dsgrid2', 'dsgrid2d', 'dsgrid2s', 'dsgrid3', 'dsgrid3d', 'dsgrid3s', 'dspnt2', 'dspnt2d', 'dspnt2s', 'dspnt3', 'dspnt3d', 'dspnt3s', 'dssetp', 'dtrend', 'dtrend_msg', 'dtrend_msg_n', 'dtrend_n', 'dtrend_quadratic', 'dtrend_quadratic_msg_n', 'dv2uvf', 'dv2uvg', 'dz_height', 'echo_off', 'echo_on', 'eof2data', 'eof_varimax', 'eofcor', 'eofcor_pcmsg', 'eofcor_ts', 'eofcov', 'eofcov_pcmsg', 'eofcov_ts', 'eofunc', 'eofunc_ts', 'eofunc_varimax', 'equiv_sample_size', 'erf', 'erfc', 'esacr', 'esacv', 'esccr', 'esccv', 'escorc', 'escorc_n', 'escovc', 'exit', 'exp', 'exp_tapersh', 'exp_tapersh_wgts', 'exp_tapershC', 'ezfftb', 'ezfftb_n', 'ezfftf', 'ezfftf_n', 'f2fosh', 'f2foshv', 'f2fsh', 'f2fshv', 'f2gsh', 'f2gshv', 'fabs', 'fbindirread', 'fbindirwrite', 'fbinnumrec', 'fbinread', 'fbinrecread', 'fbinrecwrite', 'fbinwrite', 'fft2db', 'fft2df', 'fftshift', 'fileattdef', 'filechunkdimdef', 'filedimdef', 'fileexists', 'filegrpdef', 'filevarattdef', 'filevarchunkdef', 'filevarcompressleveldef', 'filevardef', 'filevardimsizes', 'filwgts_lancos', 'filwgts_lanczos', 'filwgts_normal', 'floattobyte', 'floattochar', 'floattocharacter', 'floattoint', 'floattointeger', 'floattolong', 'floattoshort', 'floor', 'fluxEddy', 'fo2fsh', 'fo2fshv', 'fourier_info', 'frame', 'fspan', 'ftcurv', 'ftcurvd', 'ftcurvi', 'ftcurvp', 'ftcurvpi', 'ftcurvps', 'ftcurvs', 'ftest', 'ftgetp', 'ftkurv', 'ftkurvd', 'ftkurvp', 'ftkurvpd', 'ftsetp', 'ftsurf', 'g2fsh', 'g2fshv', 'g2gsh', 'g2gshv', 'gamma', 'gammainc', 'gaus', 'gaus_lobat', 'gaus_lobat_wgt', 'gc_aangle', 'gc_clkwise', 'gc_dangle', 'gc_inout', 'gc_latlon', 'gc_onarc', 'gc_pnt2gc', 'gc_qarea', 'gc_tarea', 'generate_2d_array', 'get_color_index', 'get_color_rgba', 'get_cpu_time', 'get_isolines', 'get_ncl_version', 'get_script_name', 'get_script_prefix_name', 'get_sphere_radius', 'get_unique_values', 'getbitsone', 'getenv', 'getfiledimsizes', 'getfilegrpnames', 'getfilepath', 'getfilevaratts', 'getfilevarchunkdimsizes', 'getfilevardims', 'getfilevardimsizes', 'getfilevarnames', 'getfilevartypes', 'getvaratts', 'getvardims', 'gradsf', 'gradsg', 'greg2jul', 'grid2triple', 'hlsrgb', 'hsvrgb', 'hydro', 'hyi2hyo', 'idsfft', 'igradsf', 'igradsg', 'ilapsf', 'ilapsg', 'ilapvf', 'ilapvg', 'ind', 'ind_resolve', 'int2p', 'int2p_n', 'integertobyte', 'integertochar', 'integertocharacter', 'integertoshort', 'inttobyte', 'inttochar', 'inttoshort', 'inverse_matrix', 'isatt', 'isbigendian', 'isbyte', 'ischar', 'iscoord', 'isdefined', 'isdim', 'isdimnamed', 'isdouble', 'isenumeric', 'isfile', 'isfilepresent', 'isfilevar', 'isfilevaratt', 'isfilevarcoord', 'isfilevardim', 'isfloat', 'isfunc', 'isgraphic', 'isint', 'isint64', 'isinteger', 'isleapyear', 'islogical', 'islong', 'ismissing', 'isnan_ieee', 'isnumeric', 'ispan', 'isproc', 'isshort', 'issnumeric', 'isstring', 'isubyte', 'isuint', 'isuint64', 'isulong', 'isunlimited', 'isunsigned', 'isushort', 'isvar', 'jul2greg', 'kmeans_as136', 'kolsm2_n', 'kron_product', 'lapsf', 'lapsg', 'lapvf', 'lapvg', 'latlon2utm', 'lclvl', 'lderuvf', 'lderuvg', 'linint1', 'linint1_n', 'linint2', 'linint2_points', 'linmsg', 'linmsg_n', 'linrood_latwgt', 'linrood_wgt', 'list_files', 'list_filevars', 'list_hlus', 'list_procfuncs', 'list_vars', 'ListAppend', 'ListCount', 'ListGetType', 'ListIndex', 'ListIndexFromName', 'ListPop', 'ListPush', 'ListSetType', 'loadscript', 'local_max', 'local_min', 'log', 'log10', 'longtobyte', 'longtochar', 'longtocharacter', 'longtoint', 'longtointeger', 'longtoshort', 'lspoly', 'lspoly_n', 'mask', 'max', 'maxind', 'min', 'minind', 'mixed_layer_depth', 'mixhum_ptd', 'mixhum_ptrh', 'mjo_cross_coh2pha', 'mjo_cross_segment', 'moc_globe_atl', 'monthday', 'natgrid', 'natgridd', 'natgrids', 'ncargpath', 'ncargversion', 'ndctodata', 'ndtooned', 'new', 'NewList', 'ngezlogo', 'nggcog', 'nggetp', 'nglogo', 'ngsetp', 'NhlAddAnnotation', 'NhlAddData', 'NhlAddOverlay', 'NhlAddPrimitive', 'NhlAppGetDefaultParentId', 'NhlChangeWorkstation', 'NhlClassName', 'NhlClearWorkstation', 'NhlDataPolygon', 'NhlDataPolyline', 'NhlDataPolymarker', 'NhlDataToNDC', 'NhlDestroy', 'NhlDraw', 'NhlFrame', 'NhlFreeColor', 'NhlGetBB', 'NhlGetClassResources', 'NhlGetErrorObjectId', 'NhlGetNamedColorIndex', 'NhlGetParentId', 'NhlGetParentWorkstation', 'NhlGetWorkspaceObjectId', 'NhlIsAllocatedColor', 'NhlIsApp', 'NhlIsDataComm', 'NhlIsDataItem', 'NhlIsDataSpec', 'NhlIsTransform', 'NhlIsView', 'NhlIsWorkstation', 'NhlName', 'NhlNDCPolygon', 'NhlNDCPolyline', 'NhlNDCPolymarker', 'NhlNDCToData', 'NhlNewColor', 'NhlNewDashPattern', 'NhlNewMarker', 'NhlPalGetDefined', 'NhlRemoveAnnotation', 'NhlRemoveData', 'NhlRemoveOverlay', 'NhlRemovePrimitive', 'NhlSetColor', 'NhlSetDashPattern', 'NhlSetMarker', 'NhlUpdateData', 'NhlUpdateWorkstation', 'nice_mnmxintvl', 'nngetaspectd', 'nngetaspects', 'nngetp', 'nngetsloped', 'nngetslopes', 'nngetwts', 'nngetwtsd', 'nnpnt', 'nnpntd', 'nnpntend', 'nnpntendd', 'nnpntinit', 'nnpntinitd', 'nnpntinits', 'nnpnts', 'nnsetp', 'num', 'obj_anal_ic', 'omega_ccm', 'onedtond', 'overlay', 'paleo_outline', 'pdfxy_bin', 'poisson_grid_fill', 'pop_remap', 'potmp_insitu_ocn', 'prcwater_dp', 'pres2hybrid', 'pres_hybrid_ccm', 'pres_sigma', 'print', 'print_table', 'printFileVarSummary', 'printVarSummary', 'product', 'pslec', 'pslhor', 'pslhyp', 'qsort', 'rand', 'random_chi', 'random_gamma', 'random_normal', 'random_setallseed', 'random_uniform', 'rcm2points', 'rcm2rgrid', 'rdsstoi', 'read_colormap_file', 'reg_multlin', 'regcoef', 'regCoef_n', 'regline', 'relhum', 'replace_ieeenan', 'reshape', 'reshape_ind', 'rgba_to_color_index', 'rgbhls', 'rgbhsv', 'rgbyiq', 'rgrid2rcm', 'rhomb_trunc', 'rip_cape_2d', 'rip_cape_3d', 'round', 'rtest', 'runave', 'runave_n', 'set_default_fillvalue', 'set_sphere_radius', 'setfileoption', 'sfvp2uvf', 'sfvp2uvg', 'shaec', 'shagc', 'shgetnp', 'shgetp', 'shgrid', 'shorttobyte', 'shorttochar', 'shorttocharacter', 'show_ascii', 'shsec', 'shsetp', 'shsgc', 'shsgc_R42', 'sigma2hybrid', 'simpeq', 'simpne', 'sin', 'sindex_yrmo', 'sinh', 'sizeof', 'sleep', 'smth9', 'snindex_yrmo', 'solve_linsys', 'span_color_indexes', 'span_color_rgba', 'sparse_matrix_mult', 'spcorr', 'spcorr_n', 'specx_anal', 'specxy_anal', 'spei', 'sprintf', 'sprinti', 'sqrt', 'sqsort', 'srand', 'stat2', 'stat4', 'stat_medrng', 'stat_trim', 'status_exit', 'stdatmus_p2tdz', 'stdatmus_z2tdp', 'stddev', 'str_capital', 'str_concat', 'str_fields_count', 'str_get_cols', 'str_get_dq', 'str_get_field', 'str_get_nl', 'str_get_sq', 'str_get_tab', 'str_index_of_substr', 'str_insert', 'str_is_blank', 'str_join', 'str_left_strip', 'str_lower', 'str_match', 'str_match_ic', 'str_match_ic_regex', 'str_match_ind', 'str_match_ind_ic', 'str_match_ind_ic_regex', 'str_match_ind_regex', 'str_match_regex', 'str_right_strip', 'str_split', 'str_split_by_length', 'str_split_csv', 'str_squeeze', 'str_strip', 'str_sub_str', 'str_switch', 'str_upper', 'stringtochar', 'stringtocharacter', 'stringtodouble', 'stringtofloat', 'stringtoint', 'stringtointeger', 'stringtolong', 'stringtoshort', 'strlen', 'student_t', 'sum', 'svd_lapack', 'svdcov', 'svdcov_sv', 'svdstd', 'svdstd_sv', 'system', 'systemfunc', 'tan', 'tanh', 'taper', 'taper_n', 'tdclrs', 'tdctri', 'tdcudp', 'tdcurv', 'tddtri', 'tdez2d', 'tdez3d', 'tdgetp', 'tdgrds', 'tdgrid', 'tdgtrs', 'tdinit', 'tditri', 'tdlbla', 'tdlblp', 'tdlbls', 'tdline', 'tdlndp', 'tdlnpa', 'tdlpdp', 'tdmtri', 'tdotri', 'tdpara', 'tdplch', 'tdprpa', 'tdprpi', 'tdprpt', 'tdsetp', 'tdsort', 'tdstri', 'tdstrs', 'tdttri', 'thornthwaite', 'tobyte', 'tochar', 'todouble', 'tofloat', 'toint', 'toint64', 'tointeger', 'tolong', 'toshort', 'tosigned', 'tostring', 'tostring_with_format', 'totype', 'toubyte', 'touint', 'touint64', 'toulong', 'tounsigned', 'toushort', 'trend_manken', 'tri_trunc', 'triple2grid', 'triple2grid2d', 'trop_wmo', 'ttest', 'typeof', 'undef', 'unique_string', 'update', 'ushorttoint', 'ut_calendar', 'ut_inv_calendar', 'utm2latlon', 'uv2dv_cfd', 'uv2dvf', 'uv2dvg', 'uv2sfvpf', 'uv2sfvpg', 'uv2vr_cfd', 'uv2vrdvf', 'uv2vrdvg', 'uv2vrf', 'uv2vrg', 'v5d_close', 'v5d_create', 'v5d_setLowLev', 'v5d_setUnits', 'v5d_write', 'v5d_write_var', 'variance', 'vhaec', 'vhagc', 'vhsec', 'vhsgc', 'vibeta', 'vinth2p', 'vinth2p_ecmwf', 'vinth2p_ecmwf_nodes', 'vinth2p_nodes', 'vintp2p_ecmwf', 'vr2uvf', 'vr2uvg', 'vrdv2uvf', 'vrdv2uvg', 'wavelet', 'wavelet_default', 'weibull', 'wgt_area_smooth', 'wgt_areaave', 'wgt_areaave2', 'wgt_arearmse', 'wgt_arearmse2', 'wgt_areasum2', 'wgt_runave', 'wgt_runave_n', 'wgt_vert_avg_beta', 'wgt_volave', 'wgt_volave_ccm', 'wgt_volrmse', 'wgt_volrmse_ccm', 'where', 'wk_smooth121', 'wmbarb', 'wmbarbmap', 'wmdrft', 'wmgetp', 'wmlabs', 'wmsetp', 'wmstnm', 'wmvect', 'wmvectmap', 'wmvlbl', 'wrf_avo', 'wrf_cape_2d', 'wrf_cape_3d', 'wrf_dbz', 'wrf_eth', 'wrf_helicity', 'wrf_ij_to_ll', 'wrf_interp_1d', 'wrf_interp_2d_xy', 'wrf_interp_3d_z', 'wrf_latlon_to_ij', 'wrf_ll_to_ij', 'wrf_omega', 'wrf_pvo', 'wrf_rh', 'wrf_slp', 'wrf_smooth_2d', 'wrf_td', 'wrf_tk', 'wrf_updraft_helicity', 'wrf_uvmet', 'wrf_virtual_temp', 'wrf_wetbulb', 'wrf_wps_close_int', 'wrf_wps_open_int', 'wrf_wps_rddata_int', 'wrf_wps_rdhead_int', 'wrf_wps_read_int', 'wrf_wps_write_int', 'write_matrix', 'write_table', 'yiqrgb', 'z2geouv', 'zonal_mpsi', 'addfiles_GetVar', 'advect_variable', 'area_conserve_remap_Wrap', 'area_hi2lores_Wrap', 'array_append_record', 'assignFillValue', 'byte2flt', 'byte2flt_hdf', 'calcDayAnomTLL', 'calcMonAnomLLLT', 'calcMonAnomLLT', 'calcMonAnomTLL', 'calcMonAnomTLLL', 'calculate_monthly_values', 'cd_convert', 'changeCase', 'changeCaseChar', 'clmDayTLL', 'clmDayTLLL', 'clmMon2clmDay', 'clmMonLLLT', 'clmMonLLT', 'clmMonTLL', 'clmMonTLLL', 'closest_val', 'copy_VarAtts', 'copy_VarCoords', 'copy_VarCoords_1', 'copy_VarCoords_2', 'copy_VarMeta', 'copyatt', 'crossp3', 'cshstringtolist', 'cssgrid_Wrap', 'dble2flt', 'decimalPlaces', 'delete_VarAtts', 'dim_avg_n_Wrap', 'dim_avg_wgt_n_Wrap', 'dim_avg_wgt_Wrap', 'dim_avg_Wrap', 'dim_cumsum_n_Wrap', 'dim_cumsum_Wrap', 'dim_max_n_Wrap', 'dim_min_n_Wrap', 'dim_rmsd_n_Wrap', 'dim_rmsd_Wrap', 'dim_rmvmean_n_Wrap', 'dim_rmvmean_Wrap', 'dim_rmvmed_n_Wrap', 'dim_rmvmed_Wrap', 'dim_standardize_n_Wrap', 'dim_standardize_Wrap', 'dim_stddev_n_Wrap', 'dim_stddev_Wrap', 'dim_sum_n_Wrap', 'dim_sum_wgt_n_Wrap', 'dim_sum_wgt_Wrap', 'dim_sum_Wrap', 'dim_variance_n_Wrap', 'dim_variance_Wrap', 'dpres_plevel_Wrap', 'dtrend_leftdim', 'dv2uvF_Wrap', 'dv2uvG_Wrap', 'eof_north', 'eofcor_Wrap', 'eofcov_Wrap', 'eofunc_north', 'eofunc_ts_Wrap', 'eofunc_varimax_reorder', 'eofunc_varimax_Wrap', 'eofunc_Wrap', 'epsZero', 'f2fosh_Wrap', 'f2foshv_Wrap', 'f2fsh_Wrap', 'f2fshv_Wrap', 'f2gsh_Wrap', 'f2gshv_Wrap', 'fbindirSwap', 'fbinseqSwap1', 'fbinseqSwap2', 'flt2dble', 'flt2string', 'fo2fsh_Wrap', 'fo2fshv_Wrap', 'g2fsh_Wrap', 'g2fshv_Wrap', 'g2gsh_Wrap', 'g2gshv_Wrap', 'generate_resample_indices', 'generate_sample_indices', 'generate_unique_indices', 'genNormalDist', 'get1Dindex', 'get1Dindex_Collapse', 'get1Dindex_Exclude', 'get_file_suffix', 'GetFillColor', 'GetFillColorIndex', 'getFillValue', 'getind_latlon2d', 'getVarDimNames', 'getVarFillValue', 'grib_stime2itime', 'hyi2hyo_Wrap', 'ilapsF_Wrap', 'ilapsG_Wrap', 'ind_nearest_coord', 'indStrSubset', 'int2dble', 'int2flt', 'int2p_n_Wrap', 'int2p_Wrap', 'isMonotonic', 'isStrSubset', 'latGau', 'latGauWgt', 'latGlobeF', 'latGlobeFo', 'latRegWgt', 'linint1_n_Wrap', 'linint1_Wrap', 'linint2_points_Wrap', 'linint2_Wrap', 'local_max_1d', 'local_min_1d', 'lonFlip', 'lonGlobeF', 'lonGlobeFo', 'lonPivot', 'merge_levels_sfc', 'mod', 'month_to_annual', 'month_to_annual_weighted', 'month_to_season', 'month_to_season12', 'month_to_seasonN', 'monthly_total_to_daily_mean', 'nameDim', 'natgrid_Wrap', 'NewCosWeight', 'niceLatLon2D', 'NormCosWgtGlobe', 'numAsciiCol', 'numAsciiRow', 'numeric2int', 'obj_anal_ic_deprecated', 'obj_anal_ic_Wrap', 'omega_ccm_driver', 'omega_to_w', 'oneDtostring', 'pack_values', 'pattern_cor', 'pdfx', 'pdfxy', 'pdfxy_conform', 'pot_temp', 'pot_vort_hybrid', 'pot_vort_isobaric', 'pres2hybrid_Wrap', 'print_clock', 'printMinMax', 'quadroots', 'rcm2points_Wrap', 'rcm2rgrid_Wrap', 'readAsciiHead', 'readAsciiTable', 'reg_multlin_stats', 'region_ind', 'regline_stats', 'relhum_ttd', 'replaceSingleChar', 'RGBtoCmap', 'rgrid2rcm_Wrap', 'rho_mwjf', 'rm_single_dims', 'rmAnnCycle1D', 'rmInsufData', 'rmMonAnnCycLLLT', 'rmMonAnnCycLLT', 'rmMonAnnCycTLL', 'runave_n_Wrap', 'runave_Wrap', 'short2flt', 'short2flt_hdf', 'shsgc_R42_Wrap', 'sign_f90', 'sign_matlab', 'smth9_Wrap', 'smthClmDayTLL', 'smthClmDayTLLL', 'SqrtCosWeight', 'stat_dispersion', 'static_stability', 'stdMonLLLT', 'stdMonLLT', 'stdMonTLL', 'stdMonTLLL', 'symMinMaxPlt', 'table_attach_columns', 'table_attach_rows', 'time_to_newtime', 'transpose', 'triple2grid_Wrap', 'ut_convert', 'uv2dvF_Wrap', 'uv2dvG_Wrap', 'uv2vrF_Wrap', 'uv2vrG_Wrap', 'vr2uvF_Wrap', 'vr2uvG_Wrap', 'w_to_omega', 'wallClockElapseTime', 'wave_number_spc', 'wgt_areaave_Wrap', 'wgt_runave_leftdim', 'wgt_runave_n_Wrap', 'wgt_runave_Wrap', 'wgt_vertical_n', 'wind_component', 'wind_direction', 'yyyyddd_to_yyyymmdd', 'yyyymm_time', 'yyyymm_to_yyyyfrac', 'yyyymmdd_time', 'yyyymmdd_to_yyyyddd', 'yyyymmdd_to_yyyyfrac', 'yyyymmddhh_time', 'yyyymmddhh_to_yyyyfrac', 'zonal_mpsi_Wrap', 'zonalAve', 'calendar_decode2', 'cd_string', 'kf_filter', 'run_cor', 'time_axis_labels', 'ut_string', 'wrf_contour', 'wrf_map', 'wrf_map_overlay', 'wrf_map_overlays', 'wrf_map_resources', 'wrf_map_zoom', 'wrf_overlay', 'wrf_overlays', 'wrf_user_getvar', 'wrf_user_ij_to_ll', 'wrf_user_intrp2d', 'wrf_user_intrp3d', 'wrf_user_latlon_to_ij', 'wrf_user_list_times', 'wrf_user_ll_to_ij', 'wrf_user_unstagger', 'wrf_user_vert_interp', 'wrf_vector', 'gsn_add_annotation', 'gsn_add_polygon', 'gsn_add_polyline', 'gsn_add_polymarker', 'gsn_add_shapefile_polygons', 'gsn_add_shapefile_polylines', 'gsn_add_shapefile_polymarkers', 'gsn_add_text', 'gsn_attach_plots', 'gsn_blank_plot', 'gsn_contour', 'gsn_contour_map', 'gsn_contour_shade', 'gsn_coordinates', 'gsn_create_labelbar', 'gsn_create_legend', 'gsn_create_text', 'gsn_csm_attach_zonal_means', 'gsn_csm_blank_plot', 'gsn_csm_contour', 'gsn_csm_contour_map', 'gsn_csm_contour_map_ce', 'gsn_csm_contour_map_overlay', 'gsn_csm_contour_map_polar', 'gsn_csm_hov', 'gsn_csm_lat_time', 'gsn_csm_map', 'gsn_csm_map_ce', 'gsn_csm_map_polar', 'gsn_csm_pres_hgt', 'gsn_csm_pres_hgt_streamline', 'gsn_csm_pres_hgt_vector', 'gsn_csm_streamline', 'gsn_csm_streamline_contour_map', 'gsn_csm_streamline_contour_map_ce', 'gsn_csm_streamline_contour_map_polar', 'gsn_csm_streamline_map', 'gsn_csm_streamline_map_ce', 'gsn_csm_streamline_map_polar', 'gsn_csm_streamline_scalar', 'gsn_csm_streamline_scalar_map', 'gsn_csm_streamline_scalar_map_ce', 'gsn_csm_streamline_scalar_map_polar', 'gsn_csm_time_lat', 'gsn_csm_vector', 'gsn_csm_vector_map', 'gsn_csm_vector_map_ce', 'gsn_csm_vector_map_polar', 'gsn_csm_vector_scalar', 'gsn_csm_vector_scalar_map', 'gsn_csm_vector_scalar_map_ce', 'gsn_csm_vector_scalar_map_polar', 'gsn_csm_x2y', 'gsn_csm_x2y2', 'gsn_csm_xy', 'gsn_csm_xy2', 'gsn_csm_xy3', 'gsn_csm_y', 'gsn_define_colormap', 'gsn_draw_colormap', 'gsn_draw_named_colors', 'gsn_histogram', 'gsn_labelbar_ndc', 'gsn_legend_ndc', 'gsn_map', 'gsn_merge_colormaps', 'gsn_open_wks', 'gsn_panel', 'gsn_polygon', 'gsn_polygon_ndc', 'gsn_polyline', 'gsn_polyline_ndc', 'gsn_polymarker', 'gsn_polymarker_ndc', 'gsn_retrieve_colormap', 'gsn_reverse_colormap', 'gsn_streamline', 'gsn_streamline_map', 'gsn_streamline_scalar', 'gsn_streamline_scalar_map', 'gsn_table', 'gsn_text', 'gsn_text_ndc', 'gsn_vector', 'gsn_vector_map', 'gsn_vector_scalar', 'gsn_vector_scalar_map', 'gsn_xy', 'gsn_y', 'hsv2rgb', 'maximize_output', 'namedcolor2rgb', 'namedcolor2rgba', 'reset_device_coordinates', 'span_named_colors'), prefix=r'\b'), Name.Builtin),
# Resources (words(( 'amDataXF', 'amDataYF', 'amJust', 'amOn', 'amOrthogonalPosF', 'amParallelPosF', 'amResizeNotify', 'amSide', 'amTrackData', 'amViewId', 'amZone', 'appDefaultParent', 'appFileSuffix', 'appResources', 'appSysDir', 'appUsrDir', 'caCopyArrays', 'caXArray', 'caXCast', 'caXMaxV', 'caXMinV', 'caXMissingV', 'caYArray', 'caYCast', 'caYMaxV', 'caYMinV', 'caYMissingV', 'cnCellFillEdgeColor', 'cnCellFillMissingValEdgeColor', 'cnConpackParams', 'cnConstFEnableFill', 'cnConstFLabelAngleF', 'cnConstFLabelBackgroundColor', 'cnConstFLabelConstantSpacingF', 'cnConstFLabelFont', 'cnConstFLabelFontAspectF', 'cnConstFLabelFontColor', 'cnConstFLabelFontHeightF', 'cnConstFLabelFontQuality', 'cnConstFLabelFontThicknessF', 'cnConstFLabelFormat', 'cnConstFLabelFuncCode', 'cnConstFLabelJust', 'cnConstFLabelOn', 'cnConstFLabelOrthogonalPosF', 'cnConstFLabelParallelPosF', 'cnConstFLabelPerimColor', 'cnConstFLabelPerimOn', 'cnConstFLabelPerimSpaceF', 'cnConstFLabelPerimThicknessF', 'cnConstFLabelSide', 'cnConstFLabelString', 'cnConstFLabelTextDirection', 'cnConstFLabelZone', 'cnConstFUseInfoLabelRes', 'cnExplicitLabelBarLabelsOn', 'cnExplicitLegendLabelsOn', 'cnExplicitLineLabelsOn', 'cnFillBackgroundColor', 'cnFillColor', 'cnFillColors', 'cnFillDotSizeF', 'cnFillDrawOrder', 'cnFillMode', 'cnFillOn', 'cnFillOpacityF', 'cnFillPalette', 'cnFillPattern', 'cnFillPatterns', 'cnFillScaleF', 'cnFillScales', 'cnFixFillBleed', 'cnGridBoundFillColor', 'cnGridBoundFillPattern', 'cnGridBoundFillScaleF', 'cnGridBoundPerimColor', 'cnGridBoundPerimDashPattern', 'cnGridBoundPerimOn', 'cnGridBoundPerimThicknessF', 'cnHighLabelAngleF', 'cnHighLabelBackgroundColor', 'cnHighLabelConstantSpacingF', 'cnHighLabelCount', 'cnHighLabelFont', 'cnHighLabelFontAspectF', 'cnHighLabelFontColor', 'cnHighLabelFontHeightF', 'cnHighLabelFontQuality', 'cnHighLabelFontThicknessF', 'cnHighLabelFormat', 'cnHighLabelFuncCode', 'cnHighLabelPerimColor', 'cnHighLabelPerimOn', 'cnHighLabelPerimSpaceF', 'cnHighLabelPerimThicknessF', 'cnHighLabelString', 'cnHighLabelsOn', 'cnHighLowLabelOverlapMode', 'cnHighUseLineLabelRes', 'cnInfoLabelAngleF', 'cnInfoLabelBackgroundColor', 'cnInfoLabelConstantSpacingF', 'cnInfoLabelFont', 'cnInfoLabelFontAspectF', 'cnInfoLabelFontColor', 'cnInfoLabelFontHeightF', 'cnInfoLabelFontQuality', 'cnInfoLabelFontThicknessF', 'cnInfoLabelFormat', 'cnInfoLabelFuncCode', 'cnInfoLabelJust', 'cnInfoLabelOn', 'cnInfoLabelOrthogonalPosF', 'cnInfoLabelParallelPosF', 'cnInfoLabelPerimColor', 'cnInfoLabelPerimOn', 'cnInfoLabelPerimSpaceF', 'cnInfoLabelPerimThicknessF', 'cnInfoLabelSide', 'cnInfoLabelString', 'cnInfoLabelTextDirection', 'cnInfoLabelZone', 'cnLabelBarEndLabelsOn', 'cnLabelBarEndStyle', 'cnLabelDrawOrder', 'cnLabelMasking', 'cnLabelScaleFactorF', 'cnLabelScaleValueF', 'cnLabelScalingMode', 'cnLegendLevelFlags', 'cnLevelCount', 'cnLevelFlag', 'cnLevelFlags', 'cnLevelSelectionMode', 'cnLevelSpacingF', 'cnLevels', 'cnLineColor', 'cnLineColors', 'cnLineDashPattern', 'cnLineDashPatterns', 'cnLineDashSegLenF', 'cnLineDrawOrder', 'cnLineLabelAngleF', 'cnLineLabelBackgroundColor', 'cnLineLabelConstantSpacingF', 'cnLineLabelCount', 'cnLineLabelDensityF', 'cnLineLabelFont', 'cnLineLabelFontAspectF', 'cnLineLabelFontColor', 'cnLineLabelFontColors', 'cnLineLabelFontHeightF', 'cnLineLabelFontQuality', 'cnLineLabelFontThicknessF', 'cnLineLabelFormat', 'cnLineLabelFuncCode', 'cnLineLabelInterval', 'cnLineLabelPerimColor', 'cnLineLabelPerimOn', 'cnLineLabelPerimSpaceF', 'cnLineLabelPerimThicknessF', 'cnLineLabelPlacementMode', 'cnLineLabelStrings', 'cnLineLabelsOn', 'cnLinePalette', 'cnLineThicknessF', 'cnLineThicknesses', 'cnLinesOn', 'cnLowLabelAngleF', 'cnLowLabelBackgroundColor', 'cnLowLabelConstantSpacingF', 'cnLowLabelCount', 'cnLowLabelFont', 'cnLowLabelFontAspectF', 'cnLowLabelFontColor', 'cnLowLabelFontHeightF', 'cnLowLabelFontQuality', 'cnLowLabelFontThicknessF', 'cnLowLabelFormat', 'cnLowLabelFuncCode', 'cnLowLabelPerimColor', 'cnLowLabelPerimOn', 'cnLowLabelPerimSpaceF', 'cnLowLabelPerimThicknessF', 'cnLowLabelString', 'cnLowLabelsOn', 'cnLowUseHighLabelRes', 'cnMaxDataValueFormat', 'cnMaxLevelCount', 'cnMaxLevelValF', 'cnMaxPointDistanceF', 'cnMinLevelValF', 'cnMissingValFillColor', 'cnMissingValFillPattern', 'cnMissingValFillScaleF', 'cnMissingValPerimColor', 'cnMissingValPerimDashPattern', 'cnMissingValPerimGridBoundOn', 'cnMissingValPerimOn', 'cnMissingValPerimThicknessF', 'cnMonoFillColor', 'cnMonoFillPattern', 'cnMonoFillScale', 'cnMonoLevelFlag', 'cnMonoLineColor', 'cnMonoLineDashPattern', 'cnMonoLineLabelFontColor', 'cnMonoLineThickness', 'cnNoDataLabelOn', 'cnNoDataLabelString', 'cnOutOfRangeFillColor', 'cnOutOfRangeFillPattern', 'cnOutOfRangeFillScaleF', 'cnOutOfRangePerimColor', 'cnOutOfRangePerimDashPattern', 'cnOutOfRangePerimOn', 'cnOutOfRangePerimThicknessF', 'cnRasterCellSizeF', 'cnRasterMinCellSizeF', 'cnRasterModeOn', 'cnRasterSampleFactorF', 'cnRasterSmoothingOn', 'cnScalarFieldData', 'cnSmoothingDistanceF', 'cnSmoothingOn', 'cnSmoothingTensionF', 'cnSpanFillPalette', 'cnSpanLinePalette', 'ctCopyTables', 'ctXElementSize', 'ctXMaxV', 'ctXMinV', 'ctXMissingV', 'ctXTable', 'ctXTableLengths', 'ctXTableType', 'ctYElementSize', 'ctYMaxV', 'ctYMinV', 'ctYMissingV', 'ctYTable', 'ctYTableLengths', 'ctYTableType', 'dcDelayCompute', 'errBuffer', 'errFileName', 'errFilePtr', 'errLevel', 'errPrint', 'errUnitNumber', 'gsClipOn', 'gsColors', 'gsEdgeColor', 'gsEdgeDashPattern', 'gsEdgeDashSegLenF', 'gsEdgeThicknessF', 'gsEdgesOn', 'gsFillBackgroundColor', 'gsFillColor', 'gsFillDotSizeF', 'gsFillIndex', 'gsFillLineThicknessF', 'gsFillOpacityF', 'gsFillScaleF', 'gsFont', 'gsFontAspectF', 'gsFontColor', 'gsFontHeightF', 'gsFontOpacityF', 'gsFontQuality', 'gsFontThicknessF', 'gsLineColor', 'gsLineDashPattern', 'gsLineDashSegLenF', 'gsLineLabelConstantSpacingF', 'gsLineLabelFont', 'gsLineLabelFontAspectF', 'gsLineLabelFontColor', 'gsLineLabelFontHeightF', 'gsLineLabelFontQuality', 'gsLineLabelFontThicknessF', 'gsLineLabelFuncCode', 'gsLineLabelString', 'gsLineOpacityF', 'gsLineThicknessF', 'gsMarkerColor', 'gsMarkerIndex', 'gsMarkerOpacityF', 'gsMarkerSizeF', 'gsMarkerThicknessF', 'gsSegments', 'gsTextAngleF', 'gsTextConstantSpacingF', 'gsTextDirection', 'gsTextFuncCode', 'gsTextJustification', 'gsnAboveYRefLineBarColors', 'gsnAboveYRefLineBarFillScales', 'gsnAboveYRefLineBarPatterns', 'gsnAboveYRefLineColor', 'gsnAddCyclic', 'gsnAttachBorderOn', 'gsnAttachPlotsXAxis', 'gsnBelowYRefLineBarColors', 'gsnBelowYRefLineBarFillScales', 'gsnBelowYRefLineBarPatterns', 'gsnBelowYRefLineColor', 'gsnBoxMargin', 'gsnCenterString', 'gsnCenterStringFontColor', 'gsnCenterStringFontHeightF', 'gsnCenterStringFuncCode', 'gsnCenterStringOrthogonalPosF', 'gsnCenterStringParallelPosF', 'gsnContourLineThicknessesScale', 'gsnContourNegLineDashPattern', 'gsnContourPosLineDashPattern', 'gsnContourZeroLineThicknessF', 'gsnDebugWriteFileName', 'gsnDraw', 'gsnFrame', 'gsnHistogramBarWidthPercent', 'gsnHistogramBinIntervals', 'gsnHistogramBinMissing', 'gsnHistogramBinWidth', 'gsnHistogramClassIntervals', 'gsnHistogramCompare', 'gsnHistogramComputePercentages', 'gsnHistogramComputePercentagesNoMissing', 'gsnHistogramDiscreteBinValues', 'gsnHistogramDiscreteClassValues', 'gsnHistogramHorizontal', 'gsnHistogramMinMaxBinsOn', 'gsnHistogramNumberOfBins', 'gsnHistogramPercentSign', 'gsnHistogramSelectNiceIntervals', 'gsnLeftString', 'gsnLeftStringFontColor', 'gsnLeftStringFontHeightF', 'gsnLeftStringFuncCode', 'gsnLeftStringOrthogonalPosF', 'gsnLeftStringParallelPosF', 'gsnMajorLatSpacing', 'gsnMajorLonSpacing', 'gsnMaskLambertConformal', 'gsnMaskLambertConformalOutlineOn', 'gsnMaximize', 'gsnMinorLatSpacing', 'gsnMinorLonSpacing', 'gsnPanelBottom', 'gsnPanelCenter', 'gsnPanelDebug', 'gsnPanelFigureStrings', 'gsnPanelFigureStringsBackgroundFillColor', 'gsnPanelFigureStringsFontHeightF', 'gsnPanelFigureStringsJust', 'gsnPanelFigureStringsPerimOn', 'gsnPanelLabelBar', 'gsnPanelLeft', 'gsnPanelMainFont', 'gsnPanelMainFontColor', 'gsnPanelMainFontHeightF', 'gsnPanelMainString', 'gsnPanelRight', 'gsnPanelRowSpec', 'gsnPanelScalePlotIndex', 'gsnPanelTop', 'gsnPanelXF', 'gsnPanelXWhiteSpacePercent', 'gsnPanelYF', 'gsnPanelYWhiteSpacePercent', 'gsnPaperHeight', 'gsnPaperMargin', 'gsnPaperOrientation', 'gsnPaperWidth', 'gsnPolar', 'gsnPolarLabelDistance', 'gsnPolarLabelFont', 'gsnPolarLabelFontHeightF', 'gsnPolarLabelSpacing', 'gsnPolarTime', 'gsnPolarUT', 'gsnRightString', 'gsnRightStringFontColor', 'gsnRightStringFontHeightF', 'gsnRightStringFuncCode', 'gsnRightStringOrthogonalPosF', 'gsnRightStringParallelPosF', 'gsnScalarContour', 'gsnScale', 'gsnShape', 'gsnSpreadColorEnd', 'gsnSpreadColorStart', 'gsnSpreadColors', 'gsnStringFont', 'gsnStringFontColor', 'gsnStringFontHeightF', 'gsnStringFuncCode', 'gsnTickMarksOn', 'gsnXAxisIrregular2Linear', 'gsnXAxisIrregular2Log', 'gsnXRefLine', 'gsnXRefLineColor', 'gsnXRefLineDashPattern', 'gsnXRefLineThicknessF', 'gsnXYAboveFillColors', 'gsnXYBarChart', 'gsnXYBarChartBarWidth', 'gsnXYBarChartColors', 'gsnXYBarChartColors2', 'gsnXYBarChartFillDotSizeF', 'gsnXYBarChartFillLineThicknessF', 'gsnXYBarChartFillOpacityF', 'gsnXYBarChartFillScaleF', 'gsnXYBarChartOutlineOnly', 'gsnXYBarChartOutlineThicknessF', 'gsnXYBarChartPatterns', 'gsnXYBarChartPatterns2', 'gsnXYBelowFillColors', 'gsnXYFillColors', 'gsnXYFillOpacities', 'gsnXYLeftFillColors', 'gsnXYRightFillColors', 'gsnYAxisIrregular2Linear', 'gsnYAxisIrregular2Log', 'gsnYRefLine', 'gsnYRefLineColor', 'gsnYRefLineColors', 'gsnYRefLineDashPattern', 'gsnYRefLineDashPatterns', 'gsnYRefLineThicknessF', 'gsnYRefLineThicknesses', 'gsnZonalMean', 'gsnZonalMeanXMaxF', 'gsnZonalMeanXMinF', 'gsnZonalMeanYRefLine', 'lbAutoManage', 'lbBottomMarginF', 'lbBoxCount', 'lbBoxEndCapStyle', 'lbBoxFractions', 'lbBoxLineColor', 'lbBoxLineDashPattern', 'lbBoxLineDashSegLenF', 'lbBoxLineThicknessF', 'lbBoxLinesOn', 'lbBoxMajorExtentF', 'lbBoxMinorExtentF', 'lbBoxSeparatorLinesOn', 'lbBoxSizing', 'lbFillBackground', 'lbFillColor', 'lbFillColors', 'lbFillDotSizeF', 'lbFillLineThicknessF', 'lbFillPattern', 'lbFillPatterns', 'lbFillScaleF', 'lbFillScales', 'lbJustification', 'lbLabelAlignment', 'lbLabelAngleF', 'lbLabelAutoStride', 'lbLabelBarOn', 'lbLabelConstantSpacingF', 'lbLabelDirection', 'lbLabelFont', 'lbLabelFontAspectF', 'lbLabelFontColor', 'lbLabelFontHeightF', 'lbLabelFontQuality', 'lbLabelFontThicknessF', 'lbLabelFuncCode', 'lbLabelJust', 'lbLabelOffsetF', 'lbLabelPosition', 'lbLabelStride', 'lbLabelStrings', 'lbLabelsOn', 'lbLeftMarginF', 'lbMaxLabelLenF', 'lbMinLabelSpacingF', 'lbMonoFillColor', 'lbMonoFillPattern', 'lbMonoFillScale', 'lbOrientation', 'lbPerimColor', 'lbPerimDashPattern', 'lbPerimDashSegLenF', 'lbPerimFill', 'lbPerimFillColor', 'lbPerimOn', 'lbPerimThicknessF', 'lbRasterFillOn', 'lbRightMarginF', 'lbTitleAngleF', 'lbTitleConstantSpacingF', 'lbTitleDirection', 'lbTitleExtentF', 'lbTitleFont', 'lbTitleFontAspectF', 'lbTitleFontColor', 'lbTitleFontHeightF', 'lbTitleFontQuality', 'lbTitleFontThicknessF', 'lbTitleFuncCode', 'lbTitleJust', 'lbTitleOffsetF', 'lbTitleOn', 'lbTitlePosition', 'lbTitleString', 'lbTopMarginF', 'lgAutoManage', 'lgBottomMarginF', 'lgBoxBackground', 'lgBoxLineColor', 'lgBoxLineDashPattern', 'lgBoxLineDashSegLenF', 'lgBoxLineThicknessF', 'lgBoxLinesOn', 'lgBoxMajorExtentF', 'lgBoxMinorExtentF', 'lgDashIndex', 'lgDashIndexes', 'lgItemCount', 'lgItemOrder', 'lgItemPlacement', 'lgItemPositions', 'lgItemType', 'lgItemTypes', 'lgJustification', 'lgLabelAlignment', 'lgLabelAngleF', 'lgLabelAutoStride', 'lgLabelConstantSpacingF', 'lgLabelDirection', 'lgLabelFont', 'lgLabelFontAspectF', 'lgLabelFontColor', 'lgLabelFontHeightF', 'lgLabelFontQuality', 'lgLabelFontThicknessF', 'lgLabelFuncCode', 'lgLabelJust', 'lgLabelOffsetF', 'lgLabelPosition', 'lgLabelStride', 'lgLabelStrings', 'lgLabelsOn', 'lgLeftMarginF', 'lgLegendOn', 'lgLineColor', 'lgLineColors', 'lgLineDashSegLenF', 'lgLineDashSegLens', 'lgLineLabelConstantSpacingF', 'lgLineLabelFont', 'lgLineLabelFontAspectF', 'lgLineLabelFontColor', 'lgLineLabelFontColors', 'lgLineLabelFontHeightF', 'lgLineLabelFontHeights', 'lgLineLabelFontQuality', 'lgLineLabelFontThicknessF', 'lgLineLabelFuncCode', 'lgLineLabelStrings', 'lgLineLabelsOn', 'lgLineThicknessF', 'lgLineThicknesses', 'lgMarkerColor', 'lgMarkerColors', 'lgMarkerIndex', 'lgMarkerIndexes', 'lgMarkerSizeF', 'lgMarkerSizes', 'lgMarkerThicknessF', 'lgMarkerThicknesses', 'lgMonoDashIndex', 'lgMonoItemType', 'lgMonoLineColor', 'lgMonoLineDashSegLen', 'lgMonoLineLabelFontColor', 'lgMonoLineLabelFontHeight', 'lgMonoLineThickness', 'lgMonoMarkerColor', 'lgMonoMarkerIndex', 'lgMonoMarkerSize', 'lgMonoMarkerThickness', 'lgOrientation', 'lgPerimColor', 'lgPerimDashPattern', 'lgPerimDashSegLenF', 'lgPerimFill', 'lgPerimFillColor', 'lgPerimOn', 'lgPerimThicknessF', 'lgRightMarginF', 'lgTitleAngleF', 'lgTitleConstantSpacingF', 'lgTitleDirection', 'lgTitleExtentF', 'lgTitleFont', 'lgTitleFontAspectF', 'lgTitleFontColor', 'lgTitleFontHeightF', 'lgTitleFontQuality', 'lgTitleFontThicknessF', 'lgTitleFuncCode', 'lgTitleJust', 'lgTitleOffsetF', 'lgTitleOn', 'lgTitlePosition', 'lgTitleString', 'lgTopMarginF', 'mpAreaGroupCount', 'mpAreaMaskingOn', 'mpAreaNames', 'mpAreaTypes', 'mpBottomAngleF', 'mpBottomMapPosF', 'mpBottomNDCF', 'mpBottomNPCF', 'mpBottomPointLatF', 'mpBottomPointLonF', 'mpBottomWindowF', 'mpCenterLatF', 'mpCenterLonF', 'mpCenterRotF', 'mpCountyLineColor', 'mpCountyLineDashPattern', 'mpCountyLineDashSegLenF', 'mpCountyLineThicknessF', 'mpDataBaseVersion', 'mpDataResolution', 'mpDataSetName', 'mpDefaultFillColor', 'mpDefaultFillPattern', 'mpDefaultFillScaleF', 'mpDynamicAreaGroups', 'mpEllipticalBoundary', 'mpFillAreaSpecifiers', 'mpFillBoundarySets', 'mpFillColor', 'mpFillColors', 'mpFillColors-default', 'mpFillDotSizeF', 'mpFillDrawOrder', 'mpFillOn', 'mpFillPatternBackground', 'mpFillPattern', 'mpFillPatterns', 'mpFillPatterns-default', 'mpFillScaleF', 'mpFillScales', 'mpFillScales-default', 'mpFixedAreaGroups', 'mpGeophysicalLineColor', 'mpGeophysicalLineDashPattern', 'mpGeophysicalLineDashSegLenF', 'mpGeophysicalLineThicknessF', 'mpGreatCircleLinesOn', 'mpGridAndLimbDrawOrder', 'mpGridAndLimbOn', 'mpGridLatSpacingF', 'mpGridLineColor', 'mpGridLineDashPattern', 'mpGridLineDashSegLenF', 'mpGridLineThicknessF', 'mpGridLonSpacingF', 'mpGridMaskMode', 'mpGridMaxLatF', 'mpGridPolarLonSpacingF', 'mpGridSpacingF', 'mpInlandWaterFillColor', 'mpInlandWaterFillPattern', 'mpInlandWaterFillScaleF', 'mpLabelDrawOrder', 'mpLabelFontColor', 'mpLabelFontHeightF', 'mpLabelsOn', 'mpLambertMeridianF', 'mpLambertParallel1F', 'mpLambertParallel2F', 'mpLandFillColor', 'mpLandFillPattern', 'mpLandFillScaleF', 'mpLeftAngleF', 'mpLeftCornerLatF', 'mpLeftCornerLonF', 'mpLeftMapPosF', 'mpLeftNDCF', 'mpLeftNPCF', 'mpLeftPointLatF', 'mpLeftPointLonF', 'mpLeftWindowF', 'mpLimbLineColor', 'mpLimbLineDashPattern', 'mpLimbLineDashSegLenF', 'mpLimbLineThicknessF', 'mpLimitMode', 'mpMaskAreaSpecifiers', 'mpMaskOutlineSpecifiers', 'mpMaxLatF', 'mpMaxLonF', 'mpMinLatF', 'mpMinLonF', 'mpMonoFillColor', 'mpMonoFillPattern', 'mpMonoFillScale', 'mpNationalLineColor', 'mpNationalLineDashPattern', 'mpNationalLineThicknessF', 'mpOceanFillColor', 'mpOceanFillPattern', 'mpOceanFillScaleF', 'mpOutlineBoundarySets', 'mpOutlineDrawOrder', 'mpOutlineMaskingOn', 'mpOutlineOn', 'mpOutlineSpecifiers', 'mpPerimDrawOrder', 'mpPerimLineColor', 'mpPerimLineDashPattern', 'mpPerimLineDashSegLenF', 'mpPerimLineThicknessF', 'mpPerimOn', 'mpPolyMode', 'mpProjection', 'mpProvincialLineColor', 'mpProvincialLineDashPattern', 'mpProvincialLineDashSegLenF', 'mpProvincialLineThicknessF', 'mpRelativeCenterLat', 'mpRelativeCenterLon', 'mpRightAngleF', 'mpRightCornerLatF', 'mpRightCornerLonF', 'mpRightMapPosF', 'mpRightNDCF', 'mpRightNPCF', 'mpRightPointLatF', 'mpRightPointLonF', 'mpRightWindowF', 'mpSatelliteAngle1F', 'mpSatelliteAngle2F', 'mpSatelliteDistF', 'mpShapeMode', 'mpSpecifiedFillColors', 'mpSpecifiedFillDirectIndexing', 'mpSpecifiedFillPatterns', 'mpSpecifiedFillPriority', 'mpSpecifiedFillScales', 'mpTopAngleF', 'mpTopMapPosF', 'mpTopNDCF', 'mpTopNPCF', 'mpTopPointLatF', 'mpTopPointLonF', 'mpTopWindowF', 'mpUSStateLineColor', 'mpUSStateLineDashPattern', 'mpUSStateLineDashSegLenF', 'mpUSStateLineThicknessF', 'pmAnnoManagers', 'pmAnnoViews', 'pmLabelBarDisplayMode', 'pmLabelBarHeightF', 'pmLabelBarKeepAspect', 'pmLabelBarOrthogonalPosF', 'pmLabelBarParallelPosF', 'pmLabelBarSide', 'pmLabelBarWidthF', 'pmLabelBarZone', 'pmLegendDisplayMode', 'pmLegendHeightF', 'pmLegendKeepAspect', 'pmLegendOrthogonalPosF', 'pmLegendParallelPosF', 'pmLegendSide', 'pmLegendWidthF', 'pmLegendZone', 'pmOverlaySequenceIds', 'pmTickMarkDisplayMode', 'pmTickMarkZone', 'pmTitleDisplayMode', 'pmTitleZone', 'prGraphicStyle', 'prPolyType', 'prXArray', 'prYArray', 'sfCopyData', 'sfDataArray', 'sfDataMaxV', 'sfDataMinV', 'sfElementNodes', 'sfExchangeDimensions', 'sfFirstNodeIndex', 'sfMissingValueV', 'sfXArray', 'sfXCActualEndF', 'sfXCActualStartF', 'sfXCEndIndex', 'sfXCEndSubsetV', 'sfXCEndV', 'sfXCStartIndex', 'sfXCStartSubsetV', 'sfXCStartV', 'sfXCStride', 'sfXCellBounds', 'sfYArray', 'sfYCActualEndF', 'sfYCActualStartF', 'sfYCEndIndex', 'sfYCEndSubsetV', 'sfYCEndV', 'sfYCStartIndex', 'sfYCStartSubsetV', 'sfYCStartV', 'sfYCStride', 'sfYCellBounds', 'stArrowLengthF', 'stArrowStride', 'stCrossoverCheckCount', 'stExplicitLabelBarLabelsOn', 'stLabelBarEndLabelsOn', 'stLabelFormat', 'stLengthCheckCount', 'stLevelColors', 'stLevelCount', 'stLevelPalette', 'stLevelSelectionMode', 'stLevelSpacingF', 'stLevels', 'stLineColor', 'stLineOpacityF', 'stLineStartStride', 'stLineThicknessF', 'stMapDirection', 'stMaxLevelCount', 'stMaxLevelValF', 'stMinArrowSpacingF', 'stMinDistanceF', 'stMinLevelValF', 'stMinLineSpacingF', 'stMinStepFactorF', 'stMonoLineColor', 'stNoDataLabelOn', 'stNoDataLabelString', 'stScalarFieldData', 'stScalarMissingValColor', 'stSpanLevelPalette', 'stStepSizeF', 'stStreamlineDrawOrder', 'stUseScalarArray', 'stVectorFieldData', 'stZeroFLabelAngleF', 'stZeroFLabelBackgroundColor', 'stZeroFLabelConstantSpacingF', 'stZeroFLabelFont', 'stZeroFLabelFontAspectF', 'stZeroFLabelFontColor', 'stZeroFLabelFontHeightF', 'stZeroFLabelFontQuality', 'stZeroFLabelFontThicknessF', 'stZeroFLabelFuncCode', 'stZeroFLabelJust', 'stZeroFLabelOn', 'stZeroFLabelOrthogonalPosF', 'stZeroFLabelParallelPosF', 'stZeroFLabelPerimColor', 'stZeroFLabelPerimOn', 'stZeroFLabelPerimSpaceF', 'stZeroFLabelPerimThicknessF', 'stZeroFLabelSide', 'stZeroFLabelString', 'stZeroFLabelTextDirection', 'stZeroFLabelZone', 'tfDoNDCOverlay', 'tfPlotManagerOn', 'tfPolyDrawList', 'tfPolyDrawOrder', 'tiDeltaF', 'tiMainAngleF', 'tiMainConstantSpacingF', 'tiMainDirection', 'tiMainFont', 'tiMainFontAspectF', 'tiMainFontColor', 'tiMainFontHeightF', 'tiMainFontQuality', 'tiMainFontThicknessF', 'tiMainFuncCode', 'tiMainJust', 'tiMainOffsetXF', 'tiMainOffsetYF', 'tiMainOn', 'tiMainPosition', 'tiMainSide', 'tiMainString', 'tiUseMainAttributes', 'tiXAxisAngleF', 'tiXAxisConstantSpacingF', 'tiXAxisDirection', 'tiXAxisFont', 'tiXAxisFontAspectF', 'tiXAxisFontColor', 'tiXAxisFontHeightF', 'tiXAxisFontQuality', 'tiXAxisFontThicknessF', 'tiXAxisFuncCode', 'tiXAxisJust', 'tiXAxisOffsetXF', 'tiXAxisOffsetYF', 'tiXAxisOn', 'tiXAxisPosition', 'tiXAxisSide', 'tiXAxisString', 'tiYAxisAngleF', 'tiYAxisConstantSpacingF', 'tiYAxisDirection', 'tiYAxisFont', 'tiYAxisFontAspectF', 'tiYAxisFontColor', 'tiYAxisFontHeightF', 'tiYAxisFontQuality', 'tiYAxisFontThicknessF', 'tiYAxisFuncCode', 'tiYAxisJust', 'tiYAxisOffsetXF', 'tiYAxisOffsetYF', 'tiYAxisOn', 'tiYAxisPosition', 'tiYAxisSide', 'tiYAxisString', 'tmBorderLineColor', 'tmBorderThicknessF', 'tmEqualizeXYSizes', 'tmLabelAutoStride', 'tmSciNoteCutoff', 'tmXBAutoPrecision', 'tmXBBorderOn', 'tmXBDataLeftF', 'tmXBDataRightF', 'tmXBFormat', 'tmXBIrrTensionF', 'tmXBIrregularPoints', 'tmXBLabelAngleF', 'tmXBLabelConstantSpacingF', 'tmXBLabelDeltaF', 'tmXBLabelDirection', 'tmXBLabelFont', 'tmXBLabelFontAspectF', 'tmXBLabelFontColor', 'tmXBLabelFontHeightF', 'tmXBLabelFontQuality', 'tmXBLabelFontThicknessF', 'tmXBLabelFuncCode', 'tmXBLabelJust', 'tmXBLabelStride', 'tmXBLabels', 'tmXBLabelsOn', 'tmXBMajorLengthF', 'tmXBMajorLineColor', 'tmXBMajorOutwardLengthF', 'tmXBMajorThicknessF', 'tmXBMaxLabelLenF', 'tmXBMaxTicks', 'tmXBMinLabelSpacingF', 'tmXBMinorLengthF', 'tmXBMinorLineColor', 'tmXBMinorOn', 'tmXBMinorOutwardLengthF', 'tmXBMinorPerMajor', 'tmXBMinorThicknessF', 'tmXBMinorValues', 'tmXBMode', 'tmXBOn', 'tmXBPrecision', 'tmXBStyle', 'tmXBTickEndF', 'tmXBTickSpacingF', 'tmXBTickStartF', 'tmXBValues', 'tmXMajorGrid', 'tmXMajorGridLineColor', 'tmXMajorGridLineDashPattern', 'tmXMajorGridThicknessF', 'tmXMinorGrid', 'tmXMinorGridLineColor', 'tmXMinorGridLineDashPattern', 'tmXMinorGridThicknessF', 'tmXTAutoPrecision', 'tmXTBorderOn', 'tmXTDataLeftF', 'tmXTDataRightF', 'tmXTFormat', 'tmXTIrrTensionF', 'tmXTIrregularPoints', 'tmXTLabelAngleF', 'tmXTLabelConstantSpacingF', 'tmXTLabelDeltaF', 'tmXTLabelDirection', 'tmXTLabelFont', 'tmXTLabelFontAspectF', 'tmXTLabelFontColor', 'tmXTLabelFontHeightF', 'tmXTLabelFontQuality', 'tmXTLabelFontThicknessF', 'tmXTLabelFuncCode', 'tmXTLabelJust', 'tmXTLabelStride', 'tmXTLabels', 'tmXTLabelsOn', 'tmXTMajorLengthF', 'tmXTMajorLineColor', 'tmXTMajorOutwardLengthF', 'tmXTMajorThicknessF', 'tmXTMaxLabelLenF', 'tmXTMaxTicks', 'tmXTMinLabelSpacingF', 'tmXTMinorLengthF', 'tmXTMinorLineColor', 'tmXTMinorOn', 'tmXTMinorOutwardLengthF', 'tmXTMinorPerMajor', 'tmXTMinorThicknessF', 'tmXTMinorValues', 'tmXTMode', 'tmXTOn', 'tmXTPrecision', 'tmXTStyle', 'tmXTTickEndF', 'tmXTTickSpacingF', 'tmXTTickStartF', 'tmXTValues', 'tmXUseBottom', 'tmYLAutoPrecision', 'tmYLBorderOn', 'tmYLDataBottomF', 'tmYLDataTopF', 'tmYLFormat', 'tmYLIrrTensionF', 'tmYLIrregularPoints', 'tmYLLabelAngleF', 'tmYLLabelConstantSpacingF', 'tmYLLabelDeltaF', 'tmYLLabelDirection', 'tmYLLabelFont', 'tmYLLabelFontAspectF', 'tmYLLabelFontColor', 'tmYLLabelFontHeightF', 'tmYLLabelFontQuality', 'tmYLLabelFontThicknessF', 'tmYLLabelFuncCode', 'tmYLLabelJust', 'tmYLLabelStride', 'tmYLLabels', 'tmYLLabelsOn', 'tmYLMajorLengthF', 'tmYLMajorLineColor', 'tmYLMajorOutwardLengthF', 'tmYLMajorThicknessF', 'tmYLMaxLabelLenF', 'tmYLMaxTicks', 'tmYLMinLabelSpacingF', 'tmYLMinorLengthF', 'tmYLMinorLineColor', 'tmYLMinorOn', 'tmYLMinorOutwardLengthF', 'tmYLMinorPerMajor', 'tmYLMinorThicknessF', 'tmYLMinorValues', 'tmYLMode', 'tmYLOn', 'tmYLPrecision', 'tmYLStyle', 'tmYLTickEndF', 'tmYLTickSpacingF', 'tmYLTickStartF', 'tmYLValues', 'tmYMajorGrid', 'tmYMajorGridLineColor', 'tmYMajorGridLineDashPattern', 'tmYMajorGridThicknessF', 'tmYMinorGrid', 'tmYMinorGridLineColor', 'tmYMinorGridLineDashPattern', 'tmYMinorGridThicknessF', 'tmYRAutoPrecision', 'tmYRBorderOn', 'tmYRDataBottomF', 'tmYRDataTopF', 'tmYRFormat', 'tmYRIrrTensionF', 'tmYRIrregularPoints', 'tmYRLabelAngleF', 'tmYRLabelConstantSpacingF', 'tmYRLabelDeltaF', 'tmYRLabelDirection', 'tmYRLabelFont', 'tmYRLabelFontAspectF', 'tmYRLabelFontColor', 'tmYRLabelFontHeightF', 'tmYRLabelFontQuality', 'tmYRLabelFontThicknessF', 'tmYRLabelFuncCode', 'tmYRLabelJust', 'tmYRLabelStride', 'tmYRLabels', 'tmYRLabelsOn', 'tmYRMajorLengthF', 'tmYRMajorLineColor', 'tmYRMajorOutwardLengthF', 'tmYRMajorThicknessF', 'tmYRMaxLabelLenF', 'tmYRMaxTicks', 'tmYRMinLabelSpacingF', 'tmYRMinorLengthF', 'tmYRMinorLineColor', 'tmYRMinorOn', 'tmYRMinorOutwardLengthF', 'tmYRMinorPerMajor', 'tmYRMinorThicknessF', 'tmYRMinorValues', 'tmYRMode', 'tmYROn', 'tmYRPrecision', 'tmYRStyle', 'tmYRTickEndF', 'tmYRTickSpacingF', 'tmYRTickStartF', 'tmYRValues', 'tmYUseLeft', 'trGridType', 'trLineInterpolationOn', 'trXAxisType', 'trXCoordPoints', 'trXInterPoints', 'trXLog', 'trXMaxF', 'trXMinF', 'trXReverse', 'trXSamples', 'trXTensionF', 'trYAxisType', 'trYCoordPoints', 'trYInterPoints', 'trYLog', 'trYMaxF', 'trYMinF', 'trYReverse', 'trYSamples', 'trYTensionF', 'txAngleF', 'txBackgroundFillColor', 'txConstantSpacingF', 'txDirection', 'txFont', 'HLU-Fonts', 'txFontAspectF', 'txFontColor', 'txFontHeightF', 'txFontOpacityF', 'txFontQuality', 'txFontThicknessF', 'txFuncCode', 'txJust', 'txPerimColor', 'txPerimDashLengthF', 'txPerimDashPattern', 'txPerimOn', 'txPerimSpaceF', 'txPerimThicknessF', 'txPosXF', 'txPosYF', 'txString', 'vcExplicitLabelBarLabelsOn', 'vcFillArrowEdgeColor', 'vcFillArrowEdgeThicknessF', 'vcFillArrowFillColor', 'vcFillArrowHeadInteriorXF', 'vcFillArrowHeadMinFracXF', 'vcFillArrowHeadMinFracYF', 'vcFillArrowHeadXF', 'vcFillArrowHeadYF', 'vcFillArrowMinFracWidthF', 'vcFillArrowWidthF', 'vcFillArrowsOn', 'vcFillOverEdge', 'vcGlyphOpacityF', 'vcGlyphStyle', 'vcLabelBarEndLabelsOn', 'vcLabelFontColor', 'vcLabelFontHeightF', 'vcLabelsOn', 'vcLabelsUseVectorColor', 'vcLevelColors', 'vcLevelCount', 'vcLevelPalette', 'vcLevelSelectionMode', 'vcLevelSpacingF', 'vcLevels', 'vcLineArrowColor', 'vcLineArrowHeadMaxSizeF', 'vcLineArrowHeadMinSizeF', 'vcLineArrowThicknessF', 'vcMagnitudeFormat', 'vcMagnitudeScaleFactorF', 'vcMagnitudeScaleValueF', 'vcMagnitudeScalingMode', 'vcMapDirection', 'vcMaxLevelCount', 'vcMaxLevelValF', 'vcMaxMagnitudeF', 'vcMinAnnoAngleF', 'vcMinAnnoArrowAngleF', 'vcMinAnnoArrowEdgeColor', 'vcMinAnnoArrowFillColor', 'vcMinAnnoArrowLineColor', 'vcMinAnnoArrowMinOffsetF', 'vcMinAnnoArrowSpaceF', 'vcMinAnnoArrowUseVecColor', 'vcMinAnnoBackgroundColor', 'vcMinAnnoConstantSpacingF', 'vcMinAnnoExplicitMagnitudeF', 'vcMinAnnoFont', 'vcMinAnnoFontAspectF', 'vcMinAnnoFontColor', 'vcMinAnnoFontHeightF', 'vcMinAnnoFontQuality', 'vcMinAnnoFontThicknessF', 'vcMinAnnoFuncCode', 'vcMinAnnoJust', 'vcMinAnnoOn', 'vcMinAnnoOrientation', 'vcMinAnnoOrthogonalPosF', 'vcMinAnnoParallelPosF', 'vcMinAnnoPerimColor', 'vcMinAnnoPerimOn', 'vcMinAnnoPerimSpaceF', 'vcMinAnnoPerimThicknessF', 'vcMinAnnoSide', 'vcMinAnnoString1', 'vcMinAnnoString1On', 'vcMinAnnoString2', 'vcMinAnnoString2On', 'vcMinAnnoTextDirection', 'vcMinAnnoZone', 'vcMinDistanceF', 'vcMinFracLengthF', 'vcMinLevelValF', 'vcMinMagnitudeF', 'vcMonoFillArrowEdgeColor', 'vcMonoFillArrowFillColor', 'vcMonoLineArrowColor', 'vcMonoWindBarbColor', 'vcNoDataLabelOn', 'vcNoDataLabelString', 'vcPositionMode', 'vcRefAnnoAngleF', 'vcRefAnnoArrowAngleF', 'vcRefAnnoArrowEdgeColor', 'vcRefAnnoArrowFillColor', 'vcRefAnnoArrowLineColor', 'vcRefAnnoArrowMinOffsetF', 'vcRefAnnoArrowSpaceF', 'vcRefAnnoArrowUseVecColor', 'vcRefAnnoBackgroundColor', 'vcRefAnnoConstantSpacingF', 'vcRefAnnoExplicitMagnitudeF', 'vcRefAnnoFont', 'vcRefAnnoFontAspectF', 'vcRefAnnoFontColor', 'vcRefAnnoFontHeightF', 'vcRefAnnoFontQuality', 'vcRefAnnoFontThicknessF', 'vcRefAnnoFuncCode', 'vcRefAnnoJust', 'vcRefAnnoOn', 'vcRefAnnoOrientation', 'vcRefAnnoOrthogonalPosF', 'vcRefAnnoParallelPosF', 'vcRefAnnoPerimColor', 'vcRefAnnoPerimOn', 'vcRefAnnoPerimSpaceF', 'vcRefAnnoPerimThicknessF', 'vcRefAnnoSide', 'vcRefAnnoString1', 'vcRefAnnoString1On', 'vcRefAnnoString2', 'vcRefAnnoString2On', 'vcRefAnnoTextDirection', 'vcRefAnnoZone', 'vcRefLengthF', 'vcRefMagnitudeF', 'vcScalarFieldData', 'vcScalarMissingValColor', 'vcScalarValueFormat', 'vcScalarValueScaleFactorF', 'vcScalarValueScaleValueF', 'vcScalarValueScalingMode', 'vcSpanLevelPalette', 'vcUseRefAnnoRes', 'vcUseScalarArray', 'vcVectorDrawOrder', 'vcVectorFieldData', 'vcWindBarbCalmCircleSizeF', 'vcWindBarbColor', 'vcWindBarbLineThicknessF', 'vcWindBarbScaleFactorF', 'vcWindBarbTickAngleF', 'vcWindBarbTickLengthF', 'vcWindBarbTickSpacingF', 'vcZeroFLabelAngleF', 'vcZeroFLabelBackgroundColor', 'vcZeroFLabelConstantSpacingF', 'vcZeroFLabelFont', 'vcZeroFLabelFontAspectF', 'vcZeroFLabelFontColor', 'vcZeroFLabelFontHeightF', 'vcZeroFLabelFontQuality', 'vcZeroFLabelFontThicknessF', 'vcZeroFLabelFuncCode', 'vcZeroFLabelJust', 'vcZeroFLabelOn', 'vcZeroFLabelOrthogonalPosF', 'vcZeroFLabelParallelPosF', 'vcZeroFLabelPerimColor', 'vcZeroFLabelPerimOn', 'vcZeroFLabelPerimSpaceF', 'vcZeroFLabelPerimThicknessF', 'vcZeroFLabelSide', 'vcZeroFLabelString', 'vcZeroFLabelTextDirection', 'vcZeroFLabelZone', 'vfCopyData', 'vfDataArray', 'vfExchangeDimensions', 'vfExchangeUVData', 'vfMagMaxV', 'vfMagMinV', 'vfMissingUValueV', 'vfMissingVValueV', 'vfPolarData', 'vfSingleMissingValue', 'vfUDataArray', 'vfUMaxV', 'vfUMinV', 'vfVDataArray', 'vfVMaxV', 'vfVMinV', 'vfXArray', 'vfXCActualEndF', 'vfXCActualStartF', 'vfXCEndIndex', 'vfXCEndSubsetV', 'vfXCEndV', 'vfXCStartIndex', 'vfXCStartSubsetV', 'vfXCStartV', 'vfXCStride', 'vfYArray', 'vfYCActualEndF', 'vfYCActualStartF', 'vfYCEndIndex', 'vfYCEndSubsetV', 'vfYCEndV', 'vfYCStartIndex', 'vfYCStartSubsetV', 'vfYCStartV', 'vfYCStride', 'vpAnnoManagerId', 'vpClipOn', 'vpHeightF', 'vpKeepAspect', 'vpOn', 'vpUseSegments', 'vpWidthF', 'vpXF', 'vpYF', 'wkAntiAlias', 'wkBackgroundColor', 'wkBackgroundOpacityF', 'wkColorMapLen', 'wkColorMap', 'wkColorModel', 'wkDashTableLength', 'wkDefGraphicStyleId', 'wkDeviceLowerX', 'wkDeviceLowerY', 'wkDeviceUpperX', 'wkDeviceUpperY', 'wkFileName', 'wkFillTableLength', 'wkForegroundColor', 'wkFormat', 'wkFullBackground', 'wkGksWorkId', 'wkHeight', 'wkMarkerTableLength', 'wkMetaName', 'wkOrientation', 'wkPDFFileName', 'wkPDFFormat', 'wkPDFResolution', 'wkPSFileName', 'wkPSFormat', 'wkPSResolution', 'wkPaperHeightF', 'wkPaperSize', 'wkPaperWidthF', 'wkPause', 'wkTopLevelViews', 'wkViews', 'wkVisualType', 'wkWidth', 'wkWindowId', 'wkXColorMode', 'wsCurrentSize', 'wsMaximumSize', 'wsThresholdSize', 'xyComputeXMax', 'xyComputeXMin', 'xyComputeYMax', 'xyComputeYMin', 'xyCoordData', 'xyCoordDataSpec', 'xyCurveDrawOrder', 'xyDashPattern', 'xyDashPatterns', 'xyExplicitLabels', 'xyExplicitLegendLabels', 'xyLabelMode', 'xyLineColor', 'xyLineColors', 'xyLineDashSegLenF', 'xyLineLabelConstantSpacingF', 'xyLineLabelFont', 'xyLineLabelFontAspectF', 'xyLineLabelFontColor', 'xyLineLabelFontColors', 'xyLineLabelFontHeightF', 'xyLineLabelFontQuality', 'xyLineLabelFontThicknessF', 'xyLineLabelFuncCode', 'xyLineThicknessF', 'xyLineThicknesses', 'xyMarkLineMode', 'xyMarkLineModes', 'xyMarker', 'xyMarkerColor', 'xyMarkerColors', 'xyMarkerSizeF', 'xyMarkerSizes', 'xyMarkerThicknessF', 'xyMarkerThicknesses', 'xyMarkers', 'xyMonoDashPattern', 'xyMonoLineColor', 'xyMonoLineLabelFontColor', 'xyMonoLineThickness', 'xyMonoMarkLineMode', 'xyMonoMarker', 'xyMonoMarkerColor', 'xyMonoMarkerSize', 'xyMonoMarkerThickness', 'xyXIrrTensionF', 'xyXIrregularPoints', 'xyXStyle', 'xyYIrrTensionF', 'xyYIrregularPoints', 'xyYStyle'), prefix=r'\b'), Name.Builtin),
# Booleans (r'\.(True|False)\.', Name.Builtin), # Comparing Operators (r'\.(eq|ne|lt|le|gt|ge|not|and|or|xor)\.', Operator.Word), ],
'strings': [ (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double), ],
'nums': [ (r'\d+(?![.e])(_[a-z]\w+)?', Number.Integer), (r'[+-]?\d*\.\d+(e[-+]?\d+)?(_[a-z]\w+)?', Number.Float), (r'[+-]?\d+\.\d*(e[-+]?\d+)?(_[a-z]\w+)?', Number.Float), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199""" pygments.lexers.nimrod ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Nim language (formerly known as Nimrod).
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, default, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error
__all__ = ['NimrodLexer']
class NimrodLexer(RegexLexer): """ For Nim source code. """
name = 'Nimrod' url = 'http://nim-lang.org/' aliases = ['nimrod', 'nim'] filenames = ['*.nim', '*.nimrod'] mimetypes = ['text/x-nim'] version_added = '1.5'
flags = re.MULTILINE | re.IGNORECASE
def underscorize(words): newWords = [] new = [] for word in words: for ch in word: new.append(ch) new.append("_?") newWords.append(''.join(new)) new = [] return "|".join(newWords)
keywords = [ 'addr', 'and', 'as', 'asm', 'bind', 'block', 'break', 'case', 'cast', 'concept', 'const', 'continue', 'converter', 'defer', 'discard', 'distinct', 'div', 'do', 'elif', 'else', 'end', 'enum', 'except', 'export', 'finally', 'for', 'if', 'in', 'yield', 'interface', 'is', 'isnot', 'iterator', 'let', 'mixin', 'mod', 'not', 'notin', 'object', 'of', 'or', 'out', 'ptr', 'raise', 'ref', 'return', 'shl', 'shr', 'static', 'try', 'tuple', 'type', 'using', 'when', 'while', 'xor' ]
keywordsPseudo = [ 'nil', 'true', 'false' ]
opWords = [ 'and', 'or', 'not', 'xor', 'shl', 'shr', 'div', 'mod', 'in', 'notin', 'is', 'isnot' ]
types = [ 'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64', 'bool', 'char', 'range', 'array', 'seq', 'set', 'string' ]
tokens = { 'root': [ # Comments (r'##\[', String.Doc, 'doccomment'), (r'##.*$', String.Doc), (r'#\[', Comment.Multiline, 'comment'), (r'#.*$', Comment),
# Pragmas (r'\{\.', String.Other, 'pragma'),
# Operators (r'[*=><+\-/@$~&%!?|\\\[\]]', Operator), (r'\.\.|\.|,|\[\.|\.\]|\{\.|\.\}|\(\.|\.\)|\{|\}|\(|\)|:|\^|`|;', Punctuation),
# Case statement branch (r'(\n\s*)(of)(\s)', bygroups(Text.Whitespace, Keyword, Text.Whitespace), 'casebranch'),
# Strings (r'(?:[\w]+)"', String, 'rdqs'), (r'"""', String.Double, 'tdqs'), ('"', String, 'dqs'),
# Char ("'", String.Char, 'chars'),
# Keywords (rf'({underscorize(opWords)})\b', Operator.Word), (r'(proc|func|method|macro|template)(\s)(?![(\[\]])', bygroups(Keyword, Text.Whitespace), 'funcname'), (rf'({underscorize(keywords)})\b', Keyword), (r'({})\b'.format(underscorize(['from', 'import', 'include', 'export'])), Keyword.Namespace), (r'(v_?a_?r)\b', Keyword.Declaration), (rf'({underscorize(types)})\b', Name.Builtin), (rf'({underscorize(keywordsPseudo)})\b', Keyword.Pseudo),
# Identifiers (r'\b((?![_\d])\w)(((?!_)\w)|(_(?!_)\w))*', Name),
# Numbers (r'[0-9][0-9_]*(?=([e.]|\'f(32|64)))', Number.Float, ('float-suffix', 'float-number')), (r'0x[a-f0-9][a-f0-9_]*', Number.Hex, 'int-suffix'), (r'0b[01][01_]*', Number.Bin, 'int-suffix'), (r'0o[0-7][0-7_]*', Number.Oct, 'int-suffix'), (r'[0-9][0-9_]*', Number.Integer, 'int-suffix'),
# Whitespace (r'\s+', Text.Whitespace), (r'.+$', Error), ], 'chars': [ (r'\\([\\abcefnrtvl"\']|x[a-f0-9]{2}|[0-9]{1,3})', String.Escape), (r"'", String.Char, '#pop'), (r".", String.Char) ], 'strings': [ (r'(?<!\$)\$(\d+|#|\w+)+', String.Interpol), (r'[^\\\'"$\n]+', String), # quotes, dollars and backslashes must be parsed one at a time (r'[\'"\\]', String), # unhandled string formatting sign (r'\$', String) # newlines are an error (use "nl" state) ], 'doccomment': [ (r'[^\]#]+', String.Doc), (r'##\[', String.Doc, '#push'), (r'\]##', String.Doc, '#pop'), (r'[\]#]', String.Doc), ], 'comment': [ (r'[^\]#]+', Comment.Multiline), (r'#\[', Comment.Multiline, '#push'), (r'\]#', Comment.Multiline, '#pop'), (r'[\]#]', Comment.Multiline), ], 'dqs': [ (r'\\([\\abcefnrtvl"\']|\n|x[a-f0-9]{2}|[0-9]{1,3})', String.Escape), (r'"', String, '#pop'), include('strings') ], 'rdqs': [ (r'"(?!")', String, '#pop'), (r'""', String.Escape), include('strings') ], 'tdqs': [ (r'"""', String.Double, '#pop'), include('strings'), (r'\n', String.Double) ], 'funcname': [ (r'((?![\d_])\w)(((?!_)\w)|(_(?!_)\w))*', Name.Function, '#pop'), (r'`.+`', Name.Function, '#pop') ], 'nl': [ (r'\n', String) ], 'float-number': [ (r'\.(?!\.)[0-9_]*[f]*', Number.Float), (r'e[+-]?[0-9][0-9_]*', Number.Float), default('#pop') ], 'float-suffix': [ (r'\'f(32|64)', Number.Float), default('#pop') ], 'int-suffix': [ (r'\'i(32|64)', Number.Integer.Long), (r'\'i(8|16)', Number.Integer), default('#pop') ], 'casebranch': [ (r',', Punctuation), (r'[\n ]+', Text.Whitespace), (r':', Operator, '#pop'), (r'\w+|[^:]', Name.Label), ], 'pragma': [ (r'[:,]', Text), (r'[\n ]+', Text.Whitespace), (r'\.\}', String.Other, '#pop'), (r'\w+|\W+|[^.}]', String.Other), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263""" pygments.lexers.nit ~~~~~~~~~~~~~~~~~~~
Lexer for the Nit language.
: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 Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['NitLexer']
class NitLexer(RegexLexer): """ For nit source. """
name = 'Nit' url = 'http://nitlanguage.org' aliases = ['nit'] filenames = ['*.nit'] version_added = '2.0' tokens = { 'root': [ (r'#.*?$', Comment.Single), (words(( 'package', 'module', 'import', 'class', 'abstract', 'interface', 'universal', 'enum', 'end', 'fun', 'type', 'init', 'redef', 'isa', 'do', 'readable', 'writable', 'var', 'intern', 'extern', 'public', 'protected', 'private', 'intrude', 'if', 'then', 'else', 'while', 'loop', 'for', 'in', 'and', 'or', 'not', 'implies', 'return', 'continue', 'break', 'abort', 'assert', 'new', 'is', 'once', 'super', 'self', 'true', 'false', 'nullable', 'null', 'as', 'isset', 'label', '__debug__'), suffix=r'(?=[\r\n\t( ])'), Keyword), (r'[A-Z]\w*', Name.Class), (r'"""(([^\'\\]|\\.)|\\r|\\n)*((\{\{?)?(""?\{\{?)*""""*)', String), # Simple long string (r'\'\'\'(((\\.|[^\'\\])|\\r|\\n)|\'((\\.|[^\'\\])|\\r|\\n)|' r'\'\'((\\.|[^\'\\])|\\r|\\n))*\'\'\'', String), # Simple long string alt (r'"""(([^\'\\]|\\.)|\\r|\\n)*((""?)?(\{\{?""?)*\{\{\{\{*)', String), # Start long string (r'\}\}\}(((\\.|[^\'\\])|\\r|\\n))*(""?)?(\{\{?""?)*\{\{\{\{*', String), # Mid long string (r'\}\}\}(((\\.|[^\'\\])|\\r|\\n))*(\{\{?)?(""?\{\{?)*""""*', String), # End long string (r'"(\\.|([^"}{\\]))*"', String), # Simple String (r'"(\\.|([^"}{\\]))*\{', String), # Start string (r'\}(\\.|([^"}{\\]))*\{', String), # Mid String (r'\}(\\.|([^"}{\\]))*"', String), # End String (r'(\'[^\'\\]\')|(\'\\.\')', String.Char), (r'[0-9]+', Number.Integer), (r'[0-9]*.[0-9]+', Number.Float), (r'0(x|X)[0-9A-Fa-f]+', Number.Hex), (r'[a-z]\w*', Name), (r'_\w+', Name.Variable.Instance), (r'==|!=|<==>|>=|>>|>|<=|<<|<|\+|-|=|/|\*|%|\+=|-=|!|@', Operator), (r'\(|\)|\[|\]|,|\.\.\.|\.\.|\.|::|:', Punctuation), (r'`\{[^`]*`\}', Text), # Extern blocks won't be Lexed by Nit (r'[\r\n\t ]+', Text), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144""" pygments.lexers.nix ~~~~~~~~~~~~~~~~~~~
Lexers for the NixOS Nix language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, includefrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Literal
__all__ = ['NixLexer']
class NixLexer(RegexLexer): """ For the Nix language. """
name = 'Nix' url = 'http://nixos.org/nix/' aliases = ['nixos', 'nix'] filenames = ['*.nix'] mimetypes = ['text/x-nix'] version_added = '2.0'
keywords = ['rec', 'with', 'let', 'in', 'inherit', 'assert', 'if', 'else', 'then', '...'] builtins = ['import', 'abort', 'baseNameOf', 'dirOf', 'isNull', 'builtins', 'map', 'removeAttrs', 'throw', 'toString', 'derivation'] operators = ['++', '+', '?', '.', '!', '//', '==', '/', '!=', '&&', '||', '->', '=', '<', '>', '*', '-']
punctuations = ["(", ")", "[", "]", ";", "{", "}", ":", ",", "@"]
tokens = { 'root': [ # comments starting with # (r'#.*$', Comment.Single),
# multiline comments (r'/\*', Comment.Multiline, 'comment'),
# whitespace (r'\s+', Text),
# keywords ('({})'.format('|'.join(re.escape(entry) + '\\b' for entry in keywords)), Keyword),
# highlight the builtins ('({})'.format('|'.join(re.escape(entry) + '\\b' for entry in builtins)), Name.Builtin),
(r'\b(true|false|null)\b', Name.Constant),
# floats (r'-?(\d+\.\d*|\.\d+)([eE][-+]?\d+)?', Number.Float),
# integers (r'-?[0-9]+', Number.Integer),
# paths (r'[\w.+-]*(\/[\w.+-]+)+', Literal), (r'~(\/[\w.+-]+)+', Literal), (r'\<[\w.+-]+(\/[\w.+-]+)*\>', Literal),
# operators ('({})'.format('|'.join(re.escape(entry) for entry in operators)), Operator),
# word operators (r'\b(or|and)\b', Operator.Word),
(r'\{', Punctuation, 'block'),
# punctuations ('({})'.format('|'.join(re.escape(entry) for entry in punctuations)), Punctuation),
# strings (r'"', String.Double, 'doublequote'), (r"''", String.Multiline, 'multiline'),
# urls (r'[a-zA-Z][a-zA-Z0-9\+\-\.]*\:[\w%/?:@&=+$,\\.!~*\'-]+', Literal),
# names of variables (r'[\w-]+(?=\s*=)', String.Symbol), (r'[a-zA-Z_][\w\'-]*', Text),
(r"\$\{", String.Interpol, 'antiquote'), ], 'comment': [ (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'multiline': [ (r"''(\$|'|\\n|\\r|\\t|\\)", String.Escape), (r"''", String.Multiline, '#pop'), (r'\$\{', String.Interpol, 'antiquote'), (r"[^'\$]+", String.Multiline), (r"\$[^\{']", String.Multiline), (r"'[^']", String.Multiline), (r"\$(?=')", String.Multiline), ], 'doublequote': [ (r'\\(\\|"|\$|n)', String.Escape), (r'"', String.Double, '#pop'), (r'\$\{', String.Interpol, 'antiquote'), (r'[^"\\\$]+', String.Double), (r'\$[^\{"]', String.Double), (r'\$(?=")', String.Double), (r'\\', String.Double), ], 'antiquote': [ (r"\}", String.Interpol, '#pop'), # TODO: we should probably escape also here ''${ \${ (r"\$\{", String.Interpol, '#push'), include('root'), ], 'block': [ (r"\}", Punctuation, '#pop'), include('root'), ], }
def analyse_text(text): rv = 0.0 # TODO: let/in if re.search(r'import.+?<[^>]+>', text): rv += 0.4 if re.search(r'mkDerivation\s+(\(|\{|rec)', text): rv += 0.4 if re.search(r'=\s+mkIf\s+', text): rv += 0.4 if re.search(r'\{[a-zA-Z,\s]+\}:', text): rv += 0.1 return rv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263""" pygments.lexers.numbair ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for other Numba Intermediate Representation.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroups, wordsfrom pygments.token import Whitespace, Name, String, Punctuation, Keyword, \ Operator, Number
__all__ = ["NumbaIRLexer"]
class NumbaIRLexer(RegexLexer): """ Lexer for Numba IR """ name = 'Numba_IR' url = "https://numba.readthedocs.io/en/stable/developer/architecture.html#stage-2-generate-the-numba-ir" aliases = ['numba_ir', 'numbair'] filenames = ['*.numba_ir'] mimetypes = ['text/x-numba_ir', 'text/x-numbair'] version_added = '2.19'
identifier = r'\$[a-zA-Z0-9._]+' fun_or_var = r'([a-zA-Z_]+[a-zA-Z0-9]*)'
tokens = { 'root' : [ (r'(label)(\ [0-9]+)(:)$', bygroups(Keyword, Name.Label, Punctuation)),
(r'=', Operator), include('whitespace'), include('keyword'),
(identifier, Name.Variable), (fun_or_var + r'(\()', bygroups(Name.Function, Punctuation)), (fun_or_var + r'(\=)', bygroups(Name.Attribute, Punctuation)), (fun_or_var, Name.Constant), (r'[0-9]+', Number),
# <built-in function some> (r'<[^>\n]*>', String),
(r'[=<>{}\[\]()*.,!\':]|x\b', Punctuation) ],
'keyword':[ (words(( 'del', 'jump', 'call', 'branch', ), suffix=' '), Keyword), ],
'whitespace': [ (r'(\n|\s)+', Whitespace), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120""" pygments.lexers.oberon ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Oberon family 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, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['ComponentPascalLexer']
class ComponentPascalLexer(RegexLexer): """ For Component Pascal source code. """ name = 'Component Pascal' aliases = ['componentpascal', 'cp'] filenames = ['*.cp', '*.cps'] mimetypes = ['text/x-component-pascal'] url = 'https://blackboxframework.org' version_added = '2.1'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ include('whitespace'), include('comments'), include('punctuation'), include('numliterals'), include('strings'), include('operators'), include('builtins'), include('identifiers'), ], 'whitespace': [ (r'\n+', Text), # blank lines (r'\s+', Text), # whitespace ], 'comments': [ (r'\(\*([^$].*?)\*\)', Comment.Multiline), # TODO: nested comments (* (* ... *) ... (* ... *) *) not supported! ], 'punctuation': [ (r'[()\[\]{},.:;|]', Punctuation), ], 'numliterals': [ (r'[0-9A-F]+X\b', Number.Hex), # char code (r'[0-9A-F]+[HL]\b', Number.Hex), # hexadecimal number (r'[0-9]+\.[0-9]+E[+-][0-9]+', Number.Float), # real number (r'[0-9]+\.[0-9]+', Number.Float), # real number (r'[0-9]+', Number.Integer), # decimal whole number ], 'strings': [ (r"'[^\n']*'", String), # single quoted string (r'"[^\n"]*"', String), # double quoted string ], 'operators': [ # Arithmetic Operators (r'[+-]', Operator), (r'[*/]', Operator), # Relational Operators (r'[=#<>]', Operator), # Dereferencing Operator (r'\^', Operator), # Logical AND Operator (r'&', Operator), # Logical NOT Operator (r'~', Operator), # Assignment Symbol (r':=', Operator), # Range Constructor (r'\.\.', Operator), (r'\$', Operator), ], 'identifiers': [ (r'([a-zA-Z_$][\w$]*)', Name), ], 'builtins': [ (words(( 'ANYPTR', 'ANYREC', 'BOOLEAN', 'BYTE', 'CHAR', 'INTEGER', 'LONGINT', 'REAL', 'SET', 'SHORTCHAR', 'SHORTINT', 'SHORTREAL' ), suffix=r'\b'), Keyword.Type), (words(( 'ABS', 'ABSTRACT', 'ARRAY', 'ASH', 'ASSERT', 'BEGIN', 'BITS', 'BY', 'CAP', 'CASE', 'CHR', 'CLOSE', 'CONST', 'DEC', 'DIV', 'DO', 'ELSE', 'ELSIF', 'EMPTY', 'END', 'ENTIER', 'EXCL', 'EXIT', 'EXTENSIBLE', 'FOR', 'HALT', 'IF', 'IMPORT', 'IN', 'INC', 'INCL', 'IS', 'LEN', 'LIMITED', 'LONG', 'LOOP', 'MAX', 'MIN', 'MOD', 'MODULE', 'NEW', 'ODD', 'OF', 'OR', 'ORD', 'OUT', 'POINTER', 'PROCEDURE', 'RECORD', 'REPEAT', 'RETURN', 'SHORT', 'SHORTCHAR', 'SHORTINT', 'SIZE', 'THEN', 'TYPE', 'TO', 'UNTIL', 'VAR', 'WHILE', 'WITH' ), suffix=r'\b'), Keyword.Reserved), (r'(TRUE|FALSE|NIL|INF)\b', Keyword.Constant), ] }
def analyse_text(text): """The only other lexer using .cp is the C++ one, so we check if for a few common Pascal keywords here. Those are unfortunately quite common across various business languages as well.""" result = 0 if 'BEGIN' in text: result += 0.01 if 'END' in text: result += 0.01 if 'PROCEDURE' in text: result += 0.01 if 'MODULE' in text: result += 0.01
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513""" pygments.lexers.objective ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Objective-C family 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, words, \ inherit, defaultfrom pygments.token import Text, Keyword, Name, String, Operator, \ Number, Punctuation, Literal, Comment, Whitespace
from pygments.lexers.c_cpp import CLexer, CppLexer
__all__ = ['ObjectiveCLexer', 'ObjectiveCppLexer', 'LogosLexer', 'SwiftLexer']
def objective(baselexer): """ Generate a subclass of baselexer that accepts the Objective-C syntax extensions. """
# Have to be careful not to accidentally match JavaDoc/Doxygen syntax here, # since that's quite common in ordinary C/C++ files. It's OK to match # JavaDoc/Doxygen keywords that only apply to Objective-C, mind. # # The upshot of this is that we CANNOT match @class or @interface _oc_keywords = re.compile(r'@(?:end|implementation|protocol)')
# Matches [ <ws>? identifier <ws> ( identifier <ws>? ] | identifier? : ) # (note the identifier is *optional* when there is a ':'!) _oc_message = re.compile(r'\[\s*[a-zA-Z_]\w*\s+' r'(?:[a-zA-Z_]\w*\s*\]|' r'(?:[a-zA-Z_]\w*)?:)')
class GeneratedObjectiveCVariant(baselexer): """ Implements Objective-C syntax on top of an existing C family lexer. """
tokens = { 'statements': [ (r'@"', String, 'string'), (r'@(YES|NO)', Number), (r"@'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (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'@\(', Literal, 'literal_number'), (r'@\[', Literal, 'literal_array'), (r'@\{', Literal, 'literal_dictionary'), (words(( '@selector', '@private', '@protected', '@public', '@encode', '@synchronized', '@try', '@throw', '@catch', '@finally', '@end', '@property', '@synthesize', '__bridge', '__bridge_transfer', '__autoreleasing', '__block', '__weak', '__strong', 'weak', 'strong', 'copy', 'retain', 'assign', 'unsafe_unretained', 'atomic', 'nonatomic', 'readonly', 'readwrite', 'setter', 'getter', 'typeof', 'in', 'out', 'inout', 'release', 'class', '@dynamic', '@optional', '@required', '@autoreleasepool', '@import'), suffix=r'\b'), Keyword), (words(('id', 'instancetype', 'Class', 'IMP', 'SEL', 'BOOL', 'IBOutlet', 'IBAction', 'unichar'), suffix=r'\b'), Keyword.Type), (r'@(true|false|YES|NO)\n', Name.Builtin), (r'(YES|NO|nil|self|super)\b', Name.Builtin), # Carbon types (r'(Boolean|UInt8|SInt8|UInt16|SInt16|UInt32|SInt32)\b', Keyword.Type), # Carbon built-ins (r'(TRUE|FALSE)\b', Name.Builtin), (r'(@interface|@implementation)(\s+)', bygroups(Keyword, Text), ('#pop', 'oc_classname')), (r'(@class|@protocol)(\s+)', bygroups(Keyword, Text), ('#pop', 'oc_forward_classname')), # @ can also prefix other expressions like @{...} or @(...) (r'@', Punctuation), inherit, ], 'oc_classname': [ # interface definition that inherits (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?(\s*)(\{)', bygroups(Name.Class, Text, Name.Class, Text, Punctuation), ('#pop', 'oc_ivars')), (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?', bygroups(Name.Class, Text, Name.Class), '#pop'), # interface definition for a category (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))(\s*)(\{)', bygroups(Name.Class, Text, Name.Label, Text, Punctuation), ('#pop', 'oc_ivars')), (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))', bygroups(Name.Class, Text, Name.Label), '#pop'), # simple interface / implementation (r'([a-zA-Z$_][\w$]*)(\s*)(\{)', bygroups(Name.Class, Text, Punctuation), ('#pop', 'oc_ivars')), (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop') ], 'oc_forward_classname': [ (r'([a-zA-Z$_][\w$]*)(\s*,\s*)', bygroups(Name.Class, Text), 'oc_forward_classname'), (r'([a-zA-Z$_][\w$]*)(\s*;?)', bygroups(Name.Class, Text), '#pop') ], 'oc_ivars': [ include('whitespace'), include('statements'), (';', Punctuation), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], 'root': [ # methods (r'^([-+])(\s*)' # method marker r'(\(.*?\))?(\s*)' # return type r'([a-zA-Z$_][\w$]*:?)', # begin of method name bygroups(Punctuation, Text, using(this), Text, Name.Function), 'method'), inherit, ], 'method': [ include('whitespace'), # TODO unsure if ellipses are allowed elsewhere, see # discussion in Issue 789 (r',', Punctuation), (r'\.\.\.', Punctuation), (r'(\(.*?\))(\s*)([a-zA-Z$_][\w$]*)', bygroups(using(this), Text, Name.Variable)), (r'[a-zA-Z$_][\w$]*:', Name.Function), (';', Punctuation, '#pop'), (r'\{', Punctuation, 'function'), default('#pop'), ], 'literal_number': [ (r'\(', Punctuation, 'literal_number_inner'), (r'\)', Literal, '#pop'), include('statement'), ], 'literal_number_inner': [ (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), include('statement'), ], 'literal_array': [ (r'\[', Punctuation, 'literal_array_inner'), (r'\]', Literal, '#pop'), include('statement'), ], 'literal_array_inner': [ (r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), include('statement'), ], 'literal_dictionary': [ (r'\}', Literal, '#pop'), include('statement'), ], }
def analyse_text(text): if _oc_keywords.search(text): return 1.0 elif '@"' in text: # strings return 0.8 elif re.search('@[0-9]+', text): return 0.7 elif _oc_message.search(text): return 0.8 return 0
def get_tokens_unprocessed(self, text, stack=('root',)): from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \ COCOA_PROTOCOLS, COCOA_PRIMITIVES
for index, token, value in \ baselexer.get_tokens_unprocessed(self, text, stack): if token is Name or token is Name.Class: if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \ or value in COCOA_PRIMITIVES: token = Name.Builtin.Pseudo
yield index, token, value
return GeneratedObjectiveCVariant
class ObjectiveCLexer(objective(CLexer)): """ For Objective-C source code with preprocessor directives. """
name = 'Objective-C' url = 'https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html' aliases = ['objective-c', 'objectivec', 'obj-c', 'objc'] filenames = ['*.m', '*.h'] mimetypes = ['text/x-objective-c'] version_added = '' priority = 0.05 # Lower than C
class ObjectiveCppLexer(objective(CppLexer)): """ For Objective-C++ source code with preprocessor directives. """
name = 'Objective-C++' aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++'] filenames = ['*.mm', '*.hh'] mimetypes = ['text/x-objective-c++'] version_added = '' priority = 0.05 # Lower than C++
class LogosLexer(ObjectiveCppLexer): """ For Logos + Objective-C source code with preprocessor directives. """
name = 'Logos' aliases = ['logos'] filenames = ['*.x', '*.xi', '*.xm', '*.xmi'] mimetypes = ['text/x-logos'] version_added = '1.6' priority = 0.25
tokens = { 'statements': [ (r'(%orig|%log)\b', Keyword), (r'(%c)\b(\()(\s*)([a-zA-Z$_][\w$]*)(\s*)(\))', bygroups(Keyword, Punctuation, Text, Name.Class, Text, Punctuation)), (r'(%init)\b(\()', bygroups(Keyword, Punctuation), 'logos_init_directive'), (r'(%init)(?=\s*;)', bygroups(Keyword)), (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)', bygroups(Keyword, Text, Name.Class), '#pop'), (r'(%subclass)(\s+)', bygroups(Keyword, Text), ('#pop', 'logos_classname')), inherit, ], 'logos_init_directive': [ (r'\s+', Text), (',', Punctuation, ('logos_init_directive', '#pop')), (r'([a-zA-Z$_][\w$]*)(\s*)(=)(\s*)([^);]*)', bygroups(Name.Class, Text, Punctuation, Text, Text)), (r'([a-zA-Z$_][\w$]*)', Name.Class), (r'\)', Punctuation, '#pop'), ], 'logos_classname': [ (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?', bygroups(Name.Class, Text, Name.Class), '#pop'), (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop') ], 'root': [ (r'(%subclass)(\s+)', bygroups(Keyword, Text), 'logos_classname'), (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)', bygroups(Keyword, Text, Name.Class)), (r'(%config)(\s*\(\s*)(\w+)(\s*=)(.*?)(\)\s*)', bygroups(Keyword, Text, Name.Variable, Text, String, Text)), (r'(%ctor)(\s*)(\{)', bygroups(Keyword, Text, Punctuation), 'function'), (r'(%new)(\s*)(\()(.*?)(\))', bygroups(Keyword, Text, Keyword, String, Keyword)), (r'(\s*)(%end)(\s*)', bygroups(Text, Keyword, Text)), inherit, ], }
_logos_keywords = re.compile(r'%(?:hook|ctor|init|c\()')
def analyse_text(text): if LogosLexer._logos_keywords.search(text): return 1.0 return 0
class SwiftLexer(RegexLexer): """ For Swift source. """ name = 'Swift' url = 'https://www.swift.org/' filenames = ['*.swift'] aliases = ['swift'] mimetypes = ['text/x-swift'] version_added = '2.0'
tokens = { 'root': [ # Whitespace and Comments (r'\n', Text), (r'\s+', Whitespace), (r'//', Comment.Single, 'comment-single'), (r'/\*', Comment.Multiline, 'comment-multi'), (r'#(if|elseif|else|endif|available)\b', Comment.Preproc, 'preproc'),
# Keywords include('keywords'),
# Global Types (words(( 'Array', 'AutoreleasingUnsafeMutablePointer', 'BidirectionalReverseView', 'Bit', 'Bool', 'CFunctionPointer', 'COpaquePointer', 'CVaListPointer', 'Character', 'ClosedInterval', 'CollectionOfOne', 'ContiguousArray', 'Dictionary', 'DictionaryGenerator', 'DictionaryIndex', 'Double', 'EmptyCollection', 'EmptyGenerator', 'EnumerateGenerator', 'EnumerateSequence', 'FilterCollectionView', 'FilterCollectionViewIndex', 'FilterGenerator', 'FilterSequenceView', 'Float', 'Float80', 'FloatingPointClassification', 'GeneratorOf', 'GeneratorOfOne', 'GeneratorSequence', 'HalfOpenInterval', 'HeapBuffer', 'HeapBufferStorage', 'ImplicitlyUnwrappedOptional', 'IndexingGenerator', 'Int', 'Int16', 'Int32', 'Int64', 'Int8', 'LazyBidirectionalCollection', 'LazyForwardCollection', 'LazyRandomAccessCollection', 'LazySequence', 'MapCollectionView', 'MapSequenceGenerator', 'MapSequenceView', 'MirrorDisposition', 'ObjectIdentifier', 'OnHeap', 'Optional', 'PermutationGenerator', 'QuickLookObject', 'RandomAccessReverseView', 'Range', 'RangeGenerator', 'RawByte', 'Repeat', 'ReverseBidirectionalIndex', 'ReverseRandomAccessIndex', 'SequenceOf', 'SinkOf', 'Slice', 'StaticString', 'StrideThrough', 'StrideThroughGenerator', 'StrideTo', 'StrideToGenerator', 'String', 'UInt', 'UInt16', 'UInt32', 'UInt64', 'UInt8', 'UTF16', 'UTF32', 'UTF8', 'UnicodeDecodingResult', 'UnicodeScalar', 'Unmanaged', 'UnsafeBufferPointer', 'UnsafeBufferPointerGenerator', 'UnsafeMutableBufferPointer', 'UnsafeMutablePointer', 'UnsafePointer', 'Zip2', 'ZipGenerator2', # Protocols 'AbsoluteValuable', 'AnyObject', 'ArrayLiteralConvertible', 'BidirectionalIndexType', 'BitwiseOperationsType', 'BooleanLiteralConvertible', 'BooleanType', 'CVarArgType', 'CollectionType', 'Comparable', 'DebugPrintable', 'DictionaryLiteralConvertible', 'Equatable', 'ExtendedGraphemeClusterLiteralConvertible', 'ExtensibleCollectionType', 'FloatLiteralConvertible', 'FloatingPointType', 'ForwardIndexType', 'GeneratorType', 'Hashable', 'IntegerArithmeticType', 'IntegerLiteralConvertible', 'IntegerType', 'IntervalType', 'MirrorType', 'MutableCollectionType', 'MutableSliceable', 'NilLiteralConvertible', 'OutputStreamType', 'Printable', 'RandomAccessIndexType', 'RangeReplaceableCollectionType', 'RawOptionSetType', 'RawRepresentable', 'Reflectable', 'SequenceType', 'SignedIntegerType', 'SignedNumberType', 'SinkType', 'Sliceable', 'Streamable', 'Strideable', 'StringInterpolationConvertible', 'StringLiteralConvertible', 'UnicodeCodecType', 'UnicodeScalarLiteralConvertible', 'UnsignedIntegerType', '_ArrayBufferType', '_BidirectionalIndexType', '_CocoaStringType', '_CollectionType', '_Comparable', '_ExtensibleCollectionType', '_ForwardIndexType', '_Incrementable', '_IntegerArithmeticType', '_IntegerType', '_ObjectiveCBridgeable', '_RandomAccessIndexType', '_RawOptionSetType', '_SequenceType', '_Sequence_Type', '_SignedIntegerType', '_SignedNumberType', '_Sliceable', '_Strideable', '_SwiftNSArrayRequiredOverridesType', '_SwiftNSArrayType', '_SwiftNSCopyingType', '_SwiftNSDictionaryRequiredOverridesType', '_SwiftNSDictionaryType', '_SwiftNSEnumeratorType', '_SwiftNSFastEnumerationType', '_SwiftNSStringRequiredOverridesType', '_SwiftNSStringType', '_UnsignedIntegerType', # Variables 'C_ARGC', 'C_ARGV', 'Process', # Typealiases 'Any', 'AnyClass', 'BooleanLiteralType', 'CBool', 'CChar', 'CChar16', 'CChar32', 'CDouble', 'CFloat', 'CInt', 'CLong', 'CLongLong', 'CShort', 'CSignedChar', 'CUnsignedInt', 'CUnsignedLong', 'CUnsignedShort', 'CWideChar', 'ExtendedGraphemeClusterType', 'Float32', 'Float64', 'FloatLiteralType', 'IntMax', 'IntegerLiteralType', 'StringLiteralType', 'UIntMax', 'UWord', 'UnicodeScalarType', 'Void', 'Word', # Foundation/Cocoa 'NSErrorPointer', 'NSObjectProtocol', 'Selector'), suffix=r'\b'), Name.Builtin), # Functions (words(( 'abs', 'advance', 'alignof', 'alignofValue', 'assert', 'assertionFailure', 'contains', 'count', 'countElements', 'debugPrint', 'debugPrintln', 'distance', 'dropFirst', 'dropLast', 'dump', 'enumerate', 'equal', 'extend', 'fatalError', 'filter', 'find', 'first', 'getVaList', 'indices', 'insert', 'isEmpty', 'join', 'last', 'lazy', 'lexicographicalCompare', 'map', 'max', 'maxElement', 'min', 'minElement', 'numericCast', 'overlaps', 'partition', 'precondition', 'preconditionFailure', 'prefix', 'print', 'println', 'reduce', 'reflect', 'removeAll', 'removeAtIndex', 'removeLast', 'removeRange', 'reverse', 'sizeof', 'sizeofValue', 'sort', 'sorted', 'splice', 'split', 'startsWith', 'stride', 'strideof', 'strideofValue', 'suffix', 'swap', 'toDebugString', 'toString', 'transcode', 'underestimateCount', 'unsafeAddressOf', 'unsafeBitCast', 'unsafeDowncast', 'withExtendedLifetime', 'withUnsafeMutablePointer', 'withUnsafeMutablePointers', 'withUnsafePointer', 'withUnsafePointers', 'withVaList'), suffix=r'\b'), Name.Builtin.Pseudo),
# Implicit Block Variables (r'\$\d+', Name.Variable),
# Binary Literal (r'0b[01_]+', Number.Bin), # Octal Literal (r'0o[0-7_]+', Number.Oct), # Hexadecimal Literal (r'0x[0-9a-fA-F_]+', Number.Hex), # Decimal Literal (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|' r'\.[0-9_]*|[eE][+\-]?[0-9_]+)', Number.Float), (r'[0-9][0-9_]*', Number.Integer), # String Literal (r'"""', String, 'string-multi'), (r'"', String, 'string'),
# Operators and Punctuation (r'[(){}\[\].,:;=@#`?]|->|[<&?](?=\w)|(?<=\w)[>!?]', Punctuation), (r'[/=\-+!*%<>&|^?~]+', Operator),
# Identifier (r'[a-zA-Z_]\w*', Name) ], 'keywords': [ (words(( 'as', 'async', 'await', 'break', 'case', 'catch', 'continue', 'default', 'defer', 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'is', 'repeat', 'return', '#selector', 'switch', 'throw', 'try', 'where', 'while'), suffix=r'\b'), Keyword), (r'@availability\([^)]+\)', Keyword.Reserved), (words(( 'associativity', 'convenience', 'dynamic', 'didSet', 'final', 'get', 'indirect', 'infix', 'inout', 'lazy', 'left', 'mutating', 'none', 'nonmutating', 'optional', 'override', 'postfix', 'precedence', 'prefix', 'Protocol', 'required', 'rethrows', 'right', 'set', 'throws', 'Type', 'unowned', 'weak', 'willSet', '@availability', '@autoclosure', '@noreturn', '@NSApplicationMain', '@NSCopying', '@NSManaged', '@objc', '@UIApplicationMain', '@IBAction', '@IBDesignable', '@IBInspectable', '@IBOutlet'), suffix=r'\b'), Keyword.Reserved), (r'(as|dynamicType|false|is|nil|self|Self|super|true|__COLUMN__' r'|__FILE__|__FUNCTION__|__LINE__|_' r'|#(?:file|line|column|function))\b', Keyword.Constant), (r'import\b', Keyword.Declaration, 'module'), (r'(class|enum|extension|struct|protocol)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Class)), (r'(func)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Function)), (r'(var|let)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Variable)), (words(( 'actor', 'associatedtype', 'class', 'deinit', 'enum', 'extension', 'func', 'import', 'init', 'internal', 'let', 'operator', 'private', 'protocol', 'public', 'static', 'struct', 'subscript', 'typealias', 'var'), suffix=r'\b'), Keyword.Declaration) ], 'comment': [ (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):', Comment.Special) ],
# Nested 'comment-single': [ (r'\n', Whitespace, '#pop'), include('comment'), (r'[^\n]+', Comment.Single) ], 'comment-multi': [ include('comment'), (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]+', Comment.Multiline) ], 'module': [ (r'\n', Whitespace, '#pop'), (r'[a-zA-Z_]\w*', Name.Class), include('root') ], 'preproc': [ (r'\n', Whitespace, '#pop'), include('keywords'), (r'[A-Za-z]\w*', Comment.Preproc), include('root') ], 'string': [ (r'"', String, '#pop'), include("string-common"), ], 'string-multi': [ (r'"""', String, '#pop'), include("string-common"), ], 'string-common': [ (r'\\\(', String.Interpol, 'string-intp'), (r"""\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}""", String.Escape), (r'[^\\"]+', String), (r'\\', String) ], 'string-intp': [ (r'\(', String.Interpol, '#push'), (r'\)', String.Interpol, '#pop'), include('root') ] }
def get_tokens_unprocessed(self, text): from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \ COCOA_PROTOCOLS, COCOA_PRIMITIVES
for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name or token is Name.Class: if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \ or value in COCOA_PRIMITIVES: token = Name.Builtin.Pseudo
yield index, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384""" pygments.lexers.ooc ~~~~~~~~~~~~~~~~~~~
Lexers for the Ooc 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
__all__ = ['OocLexer']
class OocLexer(RegexLexer): """ For Ooc source code """ name = 'Ooc' url = 'https://ooc-lang.github.io/' aliases = ['ooc'] filenames = ['*.ooc'] mimetypes = ['text/x-ooc'] version_added = '1.2'
tokens = { 'root': [ (words(( 'class', 'interface', 'implement', 'abstract', 'extends', 'from', 'this', 'super', 'new', 'const', 'final', 'static', 'import', 'use', 'extern', 'inline', 'proto', 'break', 'continue', 'fallthrough', 'operator', 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'as', 'in', 'version', 'return', 'true', 'false', 'null'), prefix=r'\b', suffix=r'\b'), Keyword), (r'include\b', Keyword, 'include'), (r'(cover)([ \t]+)(from)([ \t]+)(\w+[*@]?)', bygroups(Keyword, Text, Keyword, Text, Name.Class)), (r'(func)((?:[ \t]|\\\n)+)(~[a-z_]\w*)', bygroups(Keyword, Text, Name.Function)), (r'\bfunc\b', Keyword), # Note: %= not listed on https://ooc-lang.github.io/docs/lang/operators/ (r'//.*', Comment), (r'(?s)/\*.*?\*/', Comment.Multiline), (r'(==?|\+=?|-[=>]?|\*=?|/=?|:=|!=?|%=?|\?|>{1,3}=?|<{1,3}=?|\.\.|' r'&&?|\|\|?|\^=?)', Operator), (r'(\.)([ \t]*)([a-z]\w*)', bygroups(Operator, Text, Name.Function)), (r'[A-Z][A-Z0-9_]+', Name.Constant), (r'[A-Z]\w*([@*]|\[[ \t]*\])?', Name.Class),
(r'([a-z]\w*(?:~[a-z]\w*)?)((?:[ \t]|\\\n)*)(?=\()', bygroups(Name.Function, Text)), (r'[a-z]\w*', Name.Variable),
# : introduces types (r'[:(){}\[\];,]', Punctuation),
(r'0x[0-9a-fA-F]+', Number.Hex), (r'0c[0-9]+', Number.Oct), (r'0b[01]+', Number.Bin), (r'[0-9_]\.[0-9_]*(?!\.)', Number.Float), (r'[0-9_]+', Number.Decimal),
(r'"(?:\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\"])*"', String.Double), (r"'(?:\\.|\\[0-9]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'@', Punctuation), # pointer dereference (r'\.', Punctuation), # imports or chain operator
(r'\\[ \t\n]', Text), (r'[ \t]+', Text), ], 'include': [ (r'[\w/]+', Name), (r',', Punctuation), (r'[ \t]', Text), (r'[;\n]', Text, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596""" pygments.lexers.openscad ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for the OpenSCAD languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, words, includefrom pygments.token import Text, Comment, Punctuation, Operator, Keyword, Name, Number, Whitespace, Literal, String
__all__ = ['OpenScadLexer']
class OpenScadLexer(RegexLexer): """For openSCAD code. """ name = "OpenSCAD" url = "https://openscad.org/" aliases = ["openscad"] filenames = ["*.scad"] mimetypes = ["application/x-openscad"] version_added = '2.16'
tokens = { "root": [ (r"[^\S\n]+", Whitespace), (r'//', Comment.Single, 'comment-single'), (r'/\*', Comment.Multiline, 'comment-multi'), (r"[{}\[\]\(\),;:]", Punctuation), (r"[*!#%\-+=?/]", Operator), (r"<=|<|==|!=|>=|>|&&|\|\|", Operator), (r"\$(f[asn]|t|vp[rtd]|children)", Operator), (r"(undef|PI)\b", Keyword.Constant), ( r"(use|include)((?:\s|\\\\s)+)", bygroups(Keyword.Namespace, Text), "includes", ), (r"(module)(\s*)([^\s\(]+)", bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r"(function)(\s*)([^\s\(]+)", bygroups(Keyword.Declaration, Whitespace, Name.Function)), (words(("true", "false"), prefix=r"\b", suffix=r"\b"), Literal), (words(( "function", "module", "include", "use", "for", "intersection_for", "if", "else", "return" ), prefix=r"\b", suffix=r"\b"), Keyword ), (words(( "circle", "square", "polygon", "text", "sphere", "cube", "cylinder", "polyhedron", "translate", "rotate", "scale", "resize", "mirror", "multmatrix", "color", "offset", "hull", "minkowski", "union", "difference", "intersection", "abs", "sign", "sin", "cos", "tan", "acos", "asin", "atan", "atan2", "floor", "round", "ceil", "ln", "log", "pow", "sqrt", "exp", "rands", "min", "max", "concat", "lookup", "str", "chr", "search", "version", "version_num", "norm", "cross", "parent_module", "echo", "import", "import_dxf", "dxf_linear_extrude", "linear_extrude", "rotate_extrude", "surface", "projection", "render", "dxf_cross", "dxf_dim", "let", "assign", "len" ), prefix=r"\b", suffix=r"\b"), Name.Builtin ), (r"\bchildren\b", Name.Builtin.Pseudo), (r'""".*?"""', String.Double), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"-?\d+(\.\d+)?(e[+-]?\d+)?", Number), (r"\w+", Name), ], "includes": [ ( r"(<)([^>]*)(>)", bygroups(Punctuation, Comment.PreprocFile, Punctuation), ), ], 'comment': [ (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):', Comment.Special) ], 'comment-single': [ (r'\n', Text, '#pop'), include('comment'), (r'[^\n]+', Comment.Single) ], 'comment-multi': [ include('comment'), (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], }1234567891011121314151617181920212223242526272829303132333435363738394041""" pygments.lexers.other ~~~~~~~~~~~~~~~~~~~~~
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.sql import SqlLexer, MySqlLexer, SqliteConsoleLexerfrom pygments.lexers.shell import BashLexer, BashSessionLexer, BatchLexer, \ TcshLexerfrom pygments.lexers.robotframework import RobotFrameworkLexerfrom pygments.lexers.testing import GherkinLexerfrom pygments.lexers.esoteric import BrainfuckLexer, BefungeLexer, RedcodeLexerfrom pygments.lexers.prolog import LogtalkLexerfrom pygments.lexers.snobol import SnobolLexerfrom pygments.lexers.rebol import RebolLexerfrom pygments.lexers.configs import KconfigLexer, Cfengine3Lexerfrom pygments.lexers.modeling import ModelicaLexerfrom pygments.lexers.scripting import AppleScriptLexer, MOOCodeLexer, \ HybrisLexerfrom pygments.lexers.graphics import PostScriptLexer, GnuplotLexer, \ AsymptoteLexer, PovrayLexerfrom pygments.lexers.business import ABAPLexer, OpenEdgeLexer, \ GoodDataCLLexer, MaqlLexerfrom pygments.lexers.automation import AutoItLexer, AutohotkeyLexerfrom pygments.lexers.dsls import ProtoBufLexer, BroLexer, PuppetLexer, \ MscgenLexer, VGLLexerfrom pygments.lexers.basic import CbmBasicV2Lexerfrom pygments.lexers.pawn import SourcePawnLexer, PawnLexerfrom pygments.lexers.ecl import ECLLexerfrom pygments.lexers.urbi import UrbiscriptLexerfrom pygments.lexers.smalltalk import SmalltalkLexer, NewspeakLexerfrom pygments.lexers.installers import NSISLexer, RPMSpecLexerfrom pygments.lexers.textedit import AwkLexerfrom pygments.lexers.smv import NuSMVLexer
__all__ = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778""" pygments.lexers.parasail ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for ParaSail.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, includefrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Literal
__all__ = ['ParaSailLexer']
class ParaSailLexer(RegexLexer): """ For ParaSail source code. """
name = 'ParaSail' url = 'http://www.parasail-lang.org' aliases = ['parasail'] filenames = ['*.psi', '*.psl'] mimetypes = ['text/x-parasail'] version_added = '2.1'
flags = re.MULTILINE
tokens = { 'root': [ (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'\b(and|or|xor)=', Operator.Word), (r'\b(and(\s+then)?|or(\s+else)?|xor|rem|mod|' r'(is|not)\s+null)\b', Operator.Word), # Keywords (r'\b(abs|abstract|all|block|class|concurrent|const|continue|' r'each|end|exit|extends|exports|forward|func|global|implements|' r'import|in|interface|is|lambda|locked|new|not|null|of|op|' r'optional|private|queued|ref|return|reverse|separate|some|' r'type|until|var|with|' # Control flow r'if|then|else|elsif|case|for|while|loop)\b', Keyword.Reserved), (r'(abstract\s+)?(interface|class|op|func|type)', Keyword.Declaration), # Literals (r'"[^"]*"', String), (r'\\[\'ntrf"0]', String.Escape), (r'#[a-zA-Z]\w*', Literal), # Enumeration include('numbers'), (r"'[^']'", String.Char), (r'[a-zA-Z]\w*', Name), # Operators and Punctuation (r'(<==|==>|<=>|\*\*=|<\|=|<<=|>>=|==|!=|=\?|<=|>=|' r'\*\*|<<|>>|=>|:=|\+=|-=|\*=|\|=|\||/=|\+|-|\*|/|' r'\.\.|<\.\.|\.\.<|<\.\.<)', Operator), (r'(<|>|\[|\]|\(|\)|\||:|;|,|.|\{|\}|->)', Punctuation), (r'\n+', Text), ], 'numbers': [ (r'\d[0-9_]*#[0-9a-fA-F][0-9a-fA-F_]*#', Number.Hex), # any base (r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex), # C-like hex (r'0[bB][01][01_]*', Number.Bin), # C-like bin (r'\d[0-9_]*\.\d[0-9_]*[eE][+-]\d[0-9_]*', # float exp Number.Float), (r'\d[0-9_]*\.\d[0-9_]*', Number.Float), # float (r'\d[0-9_]*', Number.Integer), # integer ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798""" pygments.lexers.parsers ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for parser generators.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, DelegatingLexer, \ include, bygroups, usingfrom pygments.token import Punctuation, Other, Text, Comment, Operator, \ Keyword, Name, String, Number, Whitespacefrom pygments.lexers.jvm import JavaLexerfrom pygments.lexers.c_cpp import CLexer, CppLexerfrom pygments.lexers.objective import ObjectiveCLexerfrom pygments.lexers.d import DLexerfrom pygments.lexers.dotnet import CSharpLexerfrom pygments.lexers.ruby import RubyLexerfrom pygments.lexers.python import PythonLexerfrom pygments.lexers.perl import PerlLexer
__all__ = ['RagelLexer', 'RagelEmbeddedLexer', 'RagelCLexer', 'RagelDLexer', 'RagelCppLexer', 'RagelObjectiveCLexer', 'RagelRubyLexer', 'RagelJavaLexer', 'AntlrLexer', 'AntlrPythonLexer', 'AntlrPerlLexer', 'AntlrRubyLexer', 'AntlrCppLexer', 'AntlrCSharpLexer', 'AntlrObjectiveCLexer', 'AntlrJavaLexer', 'AntlrActionScriptLexer', 'TreetopLexer', 'EbnfLexer']
class RagelLexer(RegexLexer): """A pure `Ragel <www.colm.net/open-source/ragel>`_ lexer.
Use this for fragments of Ragel. For ``.rl`` files, use :class:`RagelEmbeddedLexer` instead (or one of the language-specific subclasses). """
name = 'Ragel' url = 'http://www.colm.net/open-source/ragel/' aliases = ['ragel'] filenames = [] version_added = '1.1'
tokens = { 'whitespace': [ (r'\s+', Whitespace) ], 'comments': [ (r'\#.*$', Comment), ], 'keywords': [ (r'(access|action|alphtype)\b', Keyword), (r'(getkey|write|machine|include)\b', Keyword), (r'(any|ascii|extend|alpha|digit|alnum|lower|upper)\b', Keyword), (r'(xdigit|cntrl|graph|print|punct|space|zlen|empty)\b', Keyword) ], 'numbers': [ (r'0x[0-9A-Fa-f]+', Number.Hex), (r'[+-]?[0-9]+', Number.Integer), ], 'literals': [ (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'\[(\\\\|\\[^\\]|[^\\\]])*\]', String), # square bracket literals (r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/', String.Regex), # regular expressions ], 'identifiers': [ (r'[a-zA-Z_]\w*', Name.Variable), ], 'operators': [ (r',', Operator), # Join (r'\||&|--?', Operator), # Union, Intersection and Subtraction (r'\.|<:|:>>?', Operator), # Concatention (r':', Operator), # Label (r'->', Operator), # Epsilon Transition (r'(>|\$|%|<|@|<>)(/|eof\b)', Operator), # EOF Actions (r'(>|\$|%|<|@|<>)(!|err\b)', Operator), # Global Error Actions (r'(>|\$|%|<|@|<>)(\^|lerr\b)', Operator), # Local Error Actions (r'(>|\$|%|<|@|<>)(~|to\b)', Operator), # To-State Actions (r'(>|\$|%|<|@|<>)(\*|from\b)', Operator), # From-State Actions (r'>|@|\$|%', Operator), # Transition Actions and Priorities (r'\*|\?|\+|\{[0-9]*,[0-9]*\}', Operator), # Repetition (r'!|\^', Operator), # Negation (r'\(|\)', Operator), # Grouping ], 'root': [ include('literals'), include('whitespace'), include('comments'), include('keywords'), include('numbers'), include('identifiers'), include('operators'), (r'\{', Punctuation, 'host'), (r'=', Operator), (r';', Punctuation), ], 'host': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks r'[^{}\'"/#]+', # exclude unsafe characters r'[^\\]\\[{}]', # allow escaped { or }
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'//.*$\n?', # single line comment r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment r'\#.*$\n?', # ruby comment
# regular expression: There's no reason for it to start # with a * and this stops confusion with comments. r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
# / is safe now that we've handled regex and javadoc comments r'/', )) + r')+', Other),
(r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], }
class RagelEmbeddedLexer(RegexLexer): """ A lexer for Ragel embedded in a host language file.
This will only highlight Ragel statements. If you want host language highlighting then call the language-specific Ragel lexer. """
name = 'Embedded Ragel' aliases = ['ragel-em'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
tokens = { 'root': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks r'[^%\'"/#]+', # exclude unsafe characters r'%(?=[^%]|$)', # a single % sign is okay, just not 2 of them
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment r'//.*$\n?', # single line comment r'\#.*$\n?', # ruby/ragel comment r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/', # regular expression
# / is safe now that we've handled regex and javadoc comments r'/', )) + r')+', Other),
# Single Line FSM. # Please don't put a quoted newline in a single line FSM. # That's just mean. It will break this. (r'(%%)(?![{%])(.*)($|;)(\n?)', bygroups(Punctuation, using(RagelLexer), Punctuation, Text)),
# Multi Line FSM. (r'(%%%%|%%)\{', Punctuation, 'multi-line-fsm'), ], 'multi-line-fsm': [ (r'(' + r'|'.join(( # keep ragel code in largest possible chunks. r'(' + r'|'.join(( r'[^}\'"\[/#]', # exclude unsafe characters r'\}(?=[^%]|$)', # } is okay as long as it's not followed by % r'\}%(?=[^%]|$)', # ...well, one %'s okay, just not two... r'[^\\]\\[{}]', # ...and } is okay if it's escaped
# allow / if it's preceded with one of these symbols # (ragel EOF actions) r'(>|\$|%|<|@|<>)/',
# specifically allow regex followed immediately by * # so it doesn't get mistaken for a comment r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/\*',
# allow / as long as it's not followed by another / or by a * r'/(?=[^/*]|$)',
# We want to match as many of these as we can in one block. # Not sure if we need the + sign here, # does it help performance? )) + r')+',
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r"\[(\\\\|\\[^\\]|[^\]\\])*\]", # square bracket literal r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment r'//.*$\n?', # single line comment r'\#.*$\n?', # ruby/ragel comment )) + r')+', using(RagelLexer)),
(r'\}%%', Punctuation, '#pop'), ] }
def analyse_text(text): return '@LANG: indep' in text
class RagelRubyLexer(DelegatingLexer): """ A lexer for Ragel in a Ruby host file. """
name = 'Ragel in Ruby Host' aliases = ['ragel-ruby', 'ragel-rb'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(RubyLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: ruby' in text
class RagelCLexer(DelegatingLexer): """ A lexer for Ragel in a C host file. """
name = 'Ragel in C Host' aliases = ['ragel-c'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(CLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: c' in text
class RagelDLexer(DelegatingLexer): """ A lexer for Ragel in a D host file. """
name = 'Ragel in D Host' aliases = ['ragel-d'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(DLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: d' in text
class RagelCppLexer(DelegatingLexer): """ A lexer for Ragel in a C++ host file. """
name = 'Ragel in CPP Host' aliases = ['ragel-cpp'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(CppLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: c++' in text
class RagelObjectiveCLexer(DelegatingLexer): """ A lexer for Ragel in an Objective C host file. """
name = 'Ragel in Objective C Host' aliases = ['ragel-objc'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(ObjectiveCLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: objc' in text
class RagelJavaLexer(DelegatingLexer): """ A lexer for Ragel in a Java host file. """
name = 'Ragel in Java Host' aliases = ['ragel-java'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(JavaLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: java' in text
class AntlrLexer(RegexLexer): """ Generic ANTLR Lexer. Should not be called directly, instead use DelegatingLexer for your target language. """
name = 'ANTLR' aliases = ['antlr'] filenames = [] url = 'https://www.antlr.org' version_added = '1.1'
_id = r'[A-Za-z]\w*' _TOKEN_REF = r'[A-Z]\w*' _RULE_REF = r'[a-z]\w*' _STRING_LITERAL = r'\'(?:\\\\|\\\'|[^\']*)\'' _INT = r'[0-9]+'
tokens = { 'whitespace': [ (r'\s+', Whitespace), ], 'comments': [ (r'//.*$', Comment), (r'/\*(.|\n)*?\*/', Comment), ], 'root': [ include('whitespace'), include('comments'),
(r'(lexer|parser|tree)?(\s*)(grammar\b)(\s*)(' + _id + ')(;)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Class, Punctuation)), # optionsSpec (r'options\b', Keyword, 'options'), # tokensSpec (r'tokens\b', Keyword, 'tokens'), # attrScope (r'(scope)(\s*)(' + _id + r')(\s*)(\{)', bygroups(Keyword, Whitespace, Name.Variable, Whitespace, Punctuation), 'action'), # exception (r'(catch|finally)\b', Keyword, 'exception'), # action (r'(@' + _id + r')(\s*)(::)?(\s*)(' + _id + r')(\s*)(\{)', bygroups(Name.Label, Whitespace, Punctuation, Whitespace, Name.Label, Whitespace, Punctuation), 'action'), # rule (r'((?:protected|private|public|fragment)\b)?(\s*)(' + _id + ')(!)?', bygroups(Keyword, Whitespace, Name.Label, Punctuation), ('rule-alts', 'rule-prelims')), ], 'exception': [ (r'\n', Whitespace, '#pop'), (r'\s', Whitespace), include('comments'),
(r'\[', Punctuation, 'nested-arg-action'), (r'\{', Punctuation, 'action'), ], 'rule-prelims': [ include('whitespace'), include('comments'),
(r'returns\b', Keyword), (r'\[', Punctuation, 'nested-arg-action'), (r'\{', Punctuation, 'action'), # throwsSpec (r'(throws)(\s+)(' + _id + ')', bygroups(Keyword, Whitespace, Name.Label)), (r'(,)(\s*)(' + _id + ')', bygroups(Punctuation, Whitespace, Name.Label)), # Additional throws # optionsSpec (r'options\b', Keyword, 'options'), # ruleScopeSpec - scope followed by target language code or name of action # TODO finish implementing other possibilities for scope # L173 ANTLRv3.g from ANTLR book (r'(scope)(\s+)(\{)', bygroups(Keyword, Whitespace, Punctuation), 'action'), (r'(scope)(\s+)(' + _id + r')(\s*)(;)', bygroups(Keyword, Whitespace, Name.Label, Whitespace, Punctuation)), # ruleAction (r'(@' + _id + r')(\s*)(\{)', bygroups(Name.Label, Whitespace, Punctuation), 'action'), # finished prelims, go to rule alts! (r':', Punctuation, '#pop') ], 'rule-alts': [ include('whitespace'), include('comments'),
# These might need to go in a separate 'block' state triggered by ( (r'options\b', Keyword, 'options'), (r':', Punctuation),
# literals (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'<<([^>]|>[^>])>>', String), # identifiers # Tokens start with capital letter. (r'\$?[A-Z_]\w*', Name.Constant), # Rules start with small letter. (r'\$?[a-z_]\w*', Name.Variable), # operators (r'(\+|\||->|=>|=|\(|\)|\.\.|\.|\?|\*|\^|!|\#|~)', Operator), (r',', Punctuation), (r'\[', Punctuation, 'nested-arg-action'), (r'\{', Punctuation, 'action'), (r';', Punctuation, '#pop') ], 'tokens': [ include('whitespace'), include('comments'), (r'\{', Punctuation), (r'(' + _TOKEN_REF + r')(\s*)(=)?(\s*)(' + _STRING_LITERAL + r')?(\s*)(;)', bygroups(Name.Label, Whitespace, Punctuation, Whitespace, String, Whitespace, Punctuation)), (r'\}', Punctuation, '#pop'), ], 'options': [ include('whitespace'), include('comments'), (r'\{', Punctuation), (r'(' + _id + r')(\s*)(=)(\s*)(' + '|'.join((_id, _STRING_LITERAL, _INT, r'\*')) + r')(\s*)(;)', bygroups(Name.Variable, Whitespace, Punctuation, Whitespace, Text, Whitespace, Punctuation)), (r'\}', Punctuation, '#pop'), ], 'action': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks r'[^${}\'"/\\]+', # exclude unsafe characters
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'//.*$\n?', # single line comment r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment
# regular expression: There's no reason for it to start # with a * and this stops confusion with comments. r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
# backslashes are okay, as long as we are not backslashing a % r'\\(?!%)',
# Now that we've handled regex and javadoc comments # it's safe to let / through. r'/', )) + r')+', Other), (r'(\\)(%)', bygroups(Punctuation, Other)), (r'(\$[a-zA-Z]+)(\.?)(text|value)?', bygroups(Name.Variable, Punctuation, Name.Property)), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], 'nested-arg-action': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks. r'[^$\[\]\'"/]+', # exclude unsafe characters
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'//.*$\n?', # single line comment r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment
# regular expression: There's no reason for it to start # with a * and this stops confusion with comments. r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
# Now that we've handled regex and javadoc comments # it's safe to let / through. r'/', )) + r')+', Other),
(r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), (r'(\$[a-zA-Z]+)(\.?)(text|value)?', bygroups(Name.Variable, Punctuation, Name.Property)), (r'(\\\\|\\\]|\\\[|[^\[\]])+', Other), ] }
def analyse_text(text): return re.search(r'^\s*grammar\s+[a-zA-Z0-9]+\s*;', text, re.M)
# http://www.antlr.org/wiki/display/ANTLR3/Code+Generation+Targets
class AntlrCppLexer(DelegatingLexer): """ ANTLR with C++ Target """
name = 'ANTLR With CPP Target' aliases = ['antlr-cpp'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(CppLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*C\s*;', text, re.M)
class AntlrObjectiveCLexer(DelegatingLexer): """ ANTLR with Objective-C Target """
name = 'ANTLR With ObjectiveC Target' aliases = ['antlr-objc'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(ObjectiveCLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*ObjC\s*;', text)
class AntlrCSharpLexer(DelegatingLexer): """ ANTLR with C# Target """
name = 'ANTLR With C# Target' aliases = ['antlr-csharp', 'antlr-c#'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(CSharpLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*CSharp2\s*;', text, re.M)
class AntlrPythonLexer(DelegatingLexer): """ ANTLR with Python Target """
name = 'ANTLR With Python Target' aliases = ['antlr-python'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(PythonLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*Python\s*;', text, re.M)
class AntlrJavaLexer(DelegatingLexer): """ ANTLR with Java Target """
name = 'ANTLR With Java Target' aliases = ['antlr-java'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(JavaLexer, AntlrLexer, **options)
def analyse_text(text): # Antlr language is Java by default return AntlrLexer.analyse_text(text) and 0.9
class AntlrRubyLexer(DelegatingLexer): """ ANTLR with Ruby Target """
name = 'ANTLR With Ruby Target' aliases = ['antlr-ruby', 'antlr-rb'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(RubyLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*Ruby\s*;', text, re.M)
class AntlrPerlLexer(DelegatingLexer): """ ANTLR with Perl Target """
name = 'ANTLR With Perl Target' aliases = ['antlr-perl'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(PerlLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*Perl5\s*;', text, re.M)
class AntlrActionScriptLexer(DelegatingLexer): """ ANTLR with ActionScript Target """
name = 'ANTLR With ActionScript Target' aliases = ['antlr-actionscript', 'antlr-as'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): from pygments.lexers.actionscript import ActionScriptLexer super().__init__(ActionScriptLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*ActionScript\s*;', text, re.M)
class TreetopBaseLexer(RegexLexer): """ A base lexer for `Treetop <http://treetop.rubyforge.org/>`_ grammars. Not for direct use; use :class:`TreetopLexer` instead.
.. versionadded:: 1.6 """
tokens = { 'root': [ include('space'), (r'require[ \t]+[^\n\r]+[\n\r]', Other), (r'module\b', Keyword.Namespace, 'module'), (r'grammar\b', Keyword, 'grammar'), ], 'module': [ include('space'), include('end'), (r'module\b', Keyword, '#push'), (r'grammar\b', Keyword, 'grammar'), (r'[A-Z]\w*(?:::[A-Z]\w*)*', Name.Namespace), ], 'grammar': [ include('space'), include('end'), (r'rule\b', Keyword, 'rule'), (r'include\b', Keyword, 'include'), (r'[A-Z]\w*', Name), ], 'include': [ include('space'), (r'[A-Z]\w*(?:::[A-Z]\w*)*', Name.Class, '#pop'), ], 'rule': [ include('space'), include('end'), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'([A-Za-z_]\w*)(:)', bygroups(Name.Label, Punctuation)), (r'[A-Za-z_]\w*', Name), (r'[()]', Punctuation), (r'[?+*/&!~]', Operator), (r'\[(?:\\.|\[:\^?[a-z]+:\]|[^\\\]])+\]', String.Regex), (r'([0-9]*)(\.\.)([0-9]*)', bygroups(Number.Integer, Operator, Number.Integer)), (r'(<)([^>]+)(>)', bygroups(Punctuation, Name.Class, Punctuation)), (r'\{', Punctuation, 'inline_module'), (r'\.', String.Regex), ], 'inline_module': [ (r'\{', Other, 'ruby'), (r'\}', Punctuation, '#pop'), (r'[^{}]+', Other), ], 'ruby': [ (r'\{', Other, '#push'), (r'\}', Other, '#pop'), (r'[^{}]+', Other), ], 'space': [ (r'[ \t\n\r]+', Whitespace), (r'#[^\n]*', Comment.Single), ], 'end': [ (r'end\b', Keyword, '#pop'), ], }
class TreetopLexer(DelegatingLexer): """ A lexer for Treetop grammars. """
name = 'Treetop' aliases = ['treetop'] filenames = ['*.treetop', '*.tt'] url = 'https://cjheath.github.io/treetop' version_added = '1.6'
def __init__(self, **options): super().__init__(RubyLexer, TreetopBaseLexer, **options)
class EbnfLexer(RegexLexer): """ Lexer for `ISO/IEC 14977 EBNF <https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form>`_ grammars. """
name = 'EBNF' aliases = ['ebnf'] filenames = ['*.ebnf'] mimetypes = ['text/x-ebnf'] url = 'https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form' version_added = '2.0'
tokens = { 'root': [ include('whitespace'), include('comment_start'), include('identifier'), (r'=', Operator, 'production'), ], 'production': [ include('whitespace'), include('comment_start'), include('identifier'), (r'"[^"]*"', String.Double), (r"'[^']*'", String.Single), (r'(\?[^?]*\?)', Name.Entity), (r'[\[\]{}(),|]', Punctuation), (r'-', Operator), (r';', Punctuation, '#pop'), (r'\.', Punctuation, '#pop'), ], 'whitespace': [ (r'\s+', Text), ], 'comment_start': [ (r'\(\*', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^*)]', Comment.Multiline), include('comment_start'), (r'\*\)', Comment.Multiline, '#pop'), (r'[*)]', Comment.Multiline), ], 'identifier': [ (r'([a-zA-Z][\w \-]*)', Keyword), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644""" pygments.lexers.pascal ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Pascal family languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexerfrom pygments.util import get_bool_opt, get_list_optfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error, Whitespacefrom pygments.scanner import Scanner
# compatibility importfrom pygments.lexers.modula2 import Modula2Lexer # noqa: F401
__all__ = ['DelphiLexer', 'PortugolLexer']
class PortugolLexer(Lexer): """For Portugol, a Pascal dialect with keywords in Portuguese.""" name = 'Portugol' aliases = ['portugol'] filenames = ['*.alg', '*.portugol'] mimetypes = [] url = "https://www.apoioinformatica.inf.br/produtos/visualg/linguagem" version_added = ''
def __init__(self, **options): Lexer.__init__(self, **options) self.lexer = DelphiLexer(**options, portugol=True)
def get_tokens_unprocessed(self, text): return self.lexer.get_tokens_unprocessed(text)
class DelphiLexer(Lexer): """ For Delphi (Borland Object Pascal), Turbo Pascal and Free Pascal source code.
Additional options accepted:
`turbopascal` Highlight Turbo Pascal specific keywords (default: ``True``). `delphi` Highlight Borland Delphi specific keywords (default: ``True``). `freepascal` Highlight Free Pascal specific keywords (default: ``True``). `units` A list of units that should be considered builtin, supported are ``System``, ``SysUtils``, ``Classes`` and ``Math``. Default is to consider all of them builtin. """ name = 'Delphi' aliases = ['delphi', 'pas', 'pascal', 'objectpascal'] filenames = ['*.pas', '*.dpr'] mimetypes = ['text/x-pascal'] url = 'https://www.embarcadero.com/products/delphi' version_added = ''
TURBO_PASCAL_KEYWORDS = ( 'absolute', 'and', 'array', 'asm', 'begin', 'break', 'case', 'const', 'constructor', 'continue', 'destructor', 'div', 'do', 'downto', 'else', 'end', 'file', 'for', 'function', 'goto', 'if', 'implementation', 'in', 'inherited', 'inline', 'interface', 'label', 'mod', 'nil', 'not', 'object', 'of', 'on', 'operator', 'or', 'packed', 'procedure', 'program', 'record', 'reintroduce', 'repeat', 'self', 'set', 'shl', 'shr', 'string', 'then', 'to', 'type', 'unit', 'until', 'uses', 'var', 'while', 'with', 'xor' )
DELPHI_KEYWORDS = ( 'as', 'class', 'except', 'exports', 'finalization', 'finally', 'initialization', 'is', 'library', 'on', 'property', 'raise', 'threadvar', 'try' )
FREE_PASCAL_KEYWORDS = ( 'dispose', 'exit', 'false', 'new', 'true' )
BLOCK_KEYWORDS = { 'begin', 'class', 'const', 'constructor', 'destructor', 'end', 'finalization', 'function', 'implementation', 'initialization', 'label', 'library', 'operator', 'procedure', 'program', 'property', 'record', 'threadvar', 'type', 'unit', 'uses', 'var' }
FUNCTION_MODIFIERS = { 'alias', 'cdecl', 'export', 'inline', 'interrupt', 'nostackframe', 'pascal', 'register', 'safecall', 'softfloat', 'stdcall', 'varargs', 'name', 'dynamic', 'near', 'virtual', 'external', 'override', 'assembler' }
# XXX: those aren't global. but currently we know no way for defining # them just for the type context. DIRECTIVES = { 'absolute', 'abstract', 'assembler', 'cppdecl', 'default', 'far', 'far16', 'forward', 'index', 'oldfpccall', 'private', 'protected', 'published', 'public' }
BUILTIN_TYPES = { 'ansichar', 'ansistring', 'bool', 'boolean', 'byte', 'bytebool', 'cardinal', 'char', 'comp', 'currency', 'double', 'dword', 'extended', 'int64', 'integer', 'iunknown', 'longbool', 'longint', 'longword', 'pansichar', 'pansistring', 'pbool', 'pboolean', 'pbyte', 'pbytearray', 'pcardinal', 'pchar', 'pcomp', 'pcurrency', 'pdate', 'pdatetime', 'pdouble', 'pdword', 'pextended', 'phandle', 'pint64', 'pinteger', 'plongint', 'plongword', 'pointer', 'ppointer', 'pshortint', 'pshortstring', 'psingle', 'psmallint', 'pstring', 'pvariant', 'pwidechar', 'pwidestring', 'pword', 'pwordarray', 'pwordbool', 'real', 'real48', 'shortint', 'shortstring', 'single', 'smallint', 'string', 'tclass', 'tdate', 'tdatetime', 'textfile', 'thandle', 'tobject', 'ttime', 'variant', 'widechar', 'widestring', 'word', 'wordbool' }
BUILTIN_UNITS = { 'System': ( 'abs', 'acquireexceptionobject', 'addr', 'ansitoutf8', 'append', 'arctan', 'assert', 'assigned', 'assignfile', 'beginthread', 'blockread', 'blockwrite', 'break', 'chdir', 'chr', 'close', 'closefile', 'comptocurrency', 'comptodouble', 'concat', 'continue', 'copy', 'cos', 'dec', 'delete', 'dispose', 'doubletocomp', 'endthread', 'enummodules', 'enumresourcemodules', 'eof', 'eoln', 'erase', 'exceptaddr', 'exceptobject', 'exclude', 'exit', 'exp', 'filepos', 'filesize', 'fillchar', 'finalize', 'findclasshinstance', 'findhinstance', 'findresourcehinstance', 'flush', 'frac', 'freemem', 'get8087cw', 'getdir', 'getlasterror', 'getmem', 'getmemorymanager', 'getmodulefilename', 'getvariantmanager', 'halt', 'hi', 'high', 'inc', 'include', 'initialize', 'insert', 'int', 'ioresult', 'ismemorymanagerset', 'isvariantmanagerset', 'length', 'ln', 'lo', 'low', 'mkdir', 'move', 'new', 'odd', 'olestrtostring', 'olestrtostrvar', 'ord', 'paramcount', 'paramstr', 'pi', 'pos', 'pred', 'ptr', 'pucs4chars', 'random', 'randomize', 'read', 'readln', 'reallocmem', 'releaseexceptionobject', 'rename', 'reset', 'rewrite', 'rmdir', 'round', 'runerror', 'seek', 'seekeof', 'seekeoln', 'set8087cw', 'setlength', 'setlinebreakstyle', 'setmemorymanager', 'setstring', 'settextbuf', 'setvariantmanager', 'sin', 'sizeof', 'slice', 'sqr', 'sqrt', 'str', 'stringofchar', 'stringtoolestr', 'stringtowidechar', 'succ', 'swap', 'trunc', 'truncate', 'typeinfo', 'ucs4stringtowidestring', 'unicodetoutf8', 'uniquestring', 'upcase', 'utf8decode', 'utf8encode', 'utf8toansi', 'utf8tounicode', 'val', 'vararrayredim', 'varclear', 'widecharlentostring', 'widecharlentostrvar', 'widechartostring', 'widechartostrvar', 'widestringtoucs4string', 'write', 'writeln' ), 'SysUtils': ( 'abort', 'addexitproc', 'addterminateproc', 'adjustlinebreaks', 'allocmem', 'ansicomparefilename', 'ansicomparestr', 'ansicomparetext', 'ansidequotedstr', 'ansiextractquotedstr', 'ansilastchar', 'ansilowercase', 'ansilowercasefilename', 'ansipos', 'ansiquotedstr', 'ansisamestr', 'ansisametext', 'ansistrcomp', 'ansistricomp', 'ansistrlastchar', 'ansistrlcomp', 'ansistrlicomp', 'ansistrlower', 'ansistrpos', 'ansistrrscan', 'ansistrscan', 'ansistrupper', 'ansiuppercase', 'ansiuppercasefilename', 'appendstr', 'assignstr', 'beep', 'booltostr', 'bytetocharindex', 'bytetocharlen', 'bytetype', 'callterminateprocs', 'changefileext', 'charlength', 'chartobyteindex', 'chartobytelen', 'comparemem', 'comparestr', 'comparetext', 'createdir', 'createguid', 'currentyear', 'currtostr', 'currtostrf', 'date', 'datetimetofiledate', 'datetimetostr', 'datetimetostring', 'datetimetosystemtime', 'datetimetotimestamp', 'datetostr', 'dayofweek', 'decodedate', 'decodedatefully', 'decodetime', 'deletefile', 'directoryexists', 'diskfree', 'disksize', 'disposestr', 'encodedate', 'encodetime', 'exceptionerrormessage', 'excludetrailingbackslash', 'excludetrailingpathdelimiter', 'expandfilename', 'expandfilenamecase', 'expanduncfilename', 'extractfiledir', 'extractfiledrive', 'extractfileext', 'extractfilename', 'extractfilepath', 'extractrelativepath', 'extractshortpathname', 'fileage', 'fileclose', 'filecreate', 'filedatetodatetime', 'fileexists', 'filegetattr', 'filegetdate', 'fileisreadonly', 'fileopen', 'fileread', 'filesearch', 'fileseek', 'filesetattr', 'filesetdate', 'filesetreadonly', 'filewrite', 'finalizepackage', 'findclose', 'findcmdlineswitch', 'findfirst', 'findnext', 'floattocurr', 'floattodatetime', 'floattodecimal', 'floattostr', 'floattostrf', 'floattotext', 'floattotextfmt', 'fmtloadstr', 'fmtstr', 'forcedirectories', 'format', 'formatbuf', 'formatcurr', 'formatdatetime', 'formatfloat', 'freeandnil', 'getcurrentdir', 'getenvironmentvariable', 'getfileversion', 'getformatsettings', 'getlocaleformatsettings', 'getmodulename', 'getpackagedescription', 'getpackageinfo', 'gettime', 'guidtostring', 'incamonth', 'includetrailingbackslash', 'includetrailingpathdelimiter', 'incmonth', 'initializepackage', 'interlockeddecrement', 'interlockedexchange', 'interlockedexchangeadd', 'interlockedincrement', 'inttohex', 'inttostr', 'isdelimiter', 'isequalguid', 'isleapyear', 'ispathdelimiter', 'isvalidident', 'languages', 'lastdelimiter', 'loadpackage', 'loadstr', 'lowercase', 'msecstotimestamp', 'newstr', 'nextcharindex', 'now', 'outofmemoryerror', 'quotedstr', 'raiselastoserror', 'raiselastwin32error', 'removedir', 'renamefile', 'replacedate', 'replacetime', 'safeloadlibrary', 'samefilename', 'sametext', 'setcurrentdir', 'showexception', 'sleep', 'stralloc', 'strbufsize', 'strbytetype', 'strcat', 'strcharlength', 'strcomp', 'strcopy', 'strdispose', 'strecopy', 'strend', 'strfmt', 'stricomp', 'stringreplace', 'stringtoguid', 'strlcat', 'strlcomp', 'strlcopy', 'strlen', 'strlfmt', 'strlicomp', 'strlower', 'strmove', 'strnew', 'strnextchar', 'strpas', 'strpcopy', 'strplcopy', 'strpos', 'strrscan', 'strscan', 'strtobool', 'strtobooldef', 'strtocurr', 'strtocurrdef', 'strtodate', 'strtodatedef', 'strtodatetime', 'strtodatetimedef', 'strtofloat', 'strtofloatdef', 'strtoint', 'strtoint64', 'strtoint64def', 'strtointdef', 'strtotime', 'strtotimedef', 'strupper', 'supports', 'syserrormessage', 'systemtimetodatetime', 'texttofloat', 'time', 'timestamptodatetime', 'timestamptomsecs', 'timetostr', 'trim', 'trimleft', 'trimright', 'tryencodedate', 'tryencodetime', 'tryfloattocurr', 'tryfloattodatetime', 'trystrtobool', 'trystrtocurr', 'trystrtodate', 'trystrtodatetime', 'trystrtofloat', 'trystrtoint', 'trystrtoint64', 'trystrtotime', 'unloadpackage', 'uppercase', 'widecomparestr', 'widecomparetext', 'widefmtstr', 'wideformat', 'wideformatbuf', 'widelowercase', 'widesamestr', 'widesametext', 'wideuppercase', 'win32check', 'wraptext' ), 'Classes': ( 'activateclassgroup', 'allocatehwnd', 'bintohex', 'checksynchronize', 'collectionsequal', 'countgenerations', 'deallocatehwnd', 'equalrect', 'extractstrings', 'findclass', 'findglobalcomponent', 'getclass', 'groupdescendantswith', 'hextobin', 'identtoint', 'initinheritedcomponent', 'inttoident', 'invalidpoint', 'isuniqueglobalcomponentname', 'linestart', 'objectbinarytotext', 'objectresourcetotext', 'objecttexttobinary', 'objecttexttoresource', 'pointsequal', 'readcomponentres', 'readcomponentresex', 'readcomponentresfile', 'rect', 'registerclass', 'registerclassalias', 'registerclasses', 'registercomponents', 'registerintegerconsts', 'registernoicon', 'registernonactivex', 'smallpoint', 'startclassgroup', 'teststreamformat', 'unregisterclass', 'unregisterclasses', 'unregisterintegerconsts', 'unregistermoduleclasses', 'writecomponentresfile' ), 'Math': ( 'arccos', 'arccosh', 'arccot', 'arccoth', 'arccsc', 'arccsch', 'arcsec', 'arcsech', 'arcsin', 'arcsinh', 'arctan2', 'arctanh', 'ceil', 'comparevalue', 'cosecant', 'cosh', 'cot', 'cotan', 'coth', 'csc', 'csch', 'cycletodeg', 'cycletograd', 'cycletorad', 'degtocycle', 'degtograd', 'degtorad', 'divmod', 'doubledecliningbalance', 'ensurerange', 'floor', 'frexp', 'futurevalue', 'getexceptionmask', 'getprecisionmode', 'getroundmode', 'gradtocycle', 'gradtodeg', 'gradtorad', 'hypot', 'inrange', 'interestpayment', 'interestrate', 'internalrateofreturn', 'intpower', 'isinfinite', 'isnan', 'iszero', 'ldexp', 'lnxp1', 'log10', 'log2', 'logn', 'max', 'maxintvalue', 'maxvalue', 'mean', 'meanandstddev', 'min', 'minintvalue', 'minvalue', 'momentskewkurtosis', 'netpresentvalue', 'norm', 'numberofperiods', 'payment', 'periodpayment', 'poly', 'popnstddev', 'popnvariance', 'power', 'presentvalue', 'radtocycle', 'radtodeg', 'radtograd', 'randg', 'randomrange', 'roundto', 'samevalue', 'sec', 'secant', 'sech', 'setexceptionmask', 'setprecisionmode', 'setroundmode', 'sign', 'simpleroundto', 'sincos', 'sinh', 'slndepreciation', 'stddev', 'sum', 'sumint', 'sumofsquares', 'sumsandsquares', 'syddepreciation', 'tan', 'tanh', 'totalvariance', 'variance' ) }
ASM_REGISTERS = { 'ah', 'al', 'ax', 'bh', 'bl', 'bp', 'bx', 'ch', 'cl', 'cr0', 'cr1', 'cr2', 'cr3', 'cr4', 'cs', 'cx', 'dh', 'di', 'dl', 'dr0', 'dr1', 'dr2', 'dr3', 'dr4', 'dr5', 'dr6', 'dr7', 'ds', 'dx', 'eax', 'ebp', 'ebx', 'ecx', 'edi', 'edx', 'es', 'esi', 'esp', 'fs', 'gs', 'mm0', 'mm1', 'mm2', 'mm3', 'mm4', 'mm5', 'mm6', 'mm7', 'si', 'sp', 'ss', 'st0', 'st1', 'st2', 'st3', 'st4', 'st5', 'st6', 'st7', 'xmm0', 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5', 'xmm6', 'xmm7' }
ASM_INSTRUCTIONS = { 'aaa', 'aad', 'aam', 'aas', 'adc', 'add', 'and', 'arpl', 'bound', 'bsf', 'bsr', 'bswap', 'bt', 'btc', 'btr', 'bts', 'call', 'cbw', 'cdq', 'clc', 'cld', 'cli', 'clts', 'cmc', 'cmova', 'cmovae', 'cmovb', 'cmovbe', 'cmovc', 'cmovcxz', 'cmove', 'cmovg', 'cmovge', 'cmovl', 'cmovle', 'cmovna', 'cmovnae', 'cmovnb', 'cmovnbe', 'cmovnc', 'cmovne', 'cmovng', 'cmovnge', 'cmovnl', 'cmovnle', 'cmovno', 'cmovnp', 'cmovns', 'cmovnz', 'cmovo', 'cmovp', 'cmovpe', 'cmovpo', 'cmovs', 'cmovz', 'cmp', 'cmpsb', 'cmpsd', 'cmpsw', 'cmpxchg', 'cmpxchg486', 'cmpxchg8b', 'cpuid', 'cwd', 'cwde', 'daa', 'das', 'dec', 'div', 'emms', 'enter', 'hlt', 'ibts', 'icebp', 'idiv', 'imul', 'in', 'inc', 'insb', 'insd', 'insw', 'int', 'int01', 'int03', 'int1', 'int3', 'into', 'invd', 'invlpg', 'iret', 'iretd', 'iretw', 'ja', 'jae', 'jb', 'jbe', 'jc', 'jcxz', 'jcxz', 'je', 'jecxz', 'jg', 'jge', 'jl', 'jle', 'jmp', 'jna', 'jnae', 'jnb', 'jnbe', 'jnc', 'jne', 'jng', 'jnge', 'jnl', 'jnle', 'jno', 'jnp', 'jns', 'jnz', 'jo', 'jp', 'jpe', 'jpo', 'js', 'jz', 'lahf', 'lar', 'lcall', 'lds', 'lea', 'leave', 'les', 'lfs', 'lgdt', 'lgs', 'lidt', 'ljmp', 'lldt', 'lmsw', 'loadall', 'loadall286', 'lock', 'lodsb', 'lodsd', 'lodsw', 'loop', 'loope', 'loopne', 'loopnz', 'loopz', 'lsl', 'lss', 'ltr', 'mov', 'movd', 'movq', 'movsb', 'movsd', 'movsw', 'movsx', 'movzx', 'mul', 'neg', 'nop', 'not', 'or', 'out', 'outsb', 'outsd', 'outsw', 'pop', 'popa', 'popad', 'popaw', 'popf', 'popfd', 'popfw', 'push', 'pusha', 'pushad', 'pushaw', 'pushf', 'pushfd', 'pushfw', 'rcl', 'rcr', 'rdmsr', 'rdpmc', 'rdshr', 'rdtsc', 'rep', 'repe', 'repne', 'repnz', 'repz', 'ret', 'retf', 'retn', 'rol', 'ror', 'rsdc', 'rsldt', 'rsm', 'sahf', 'sal', 'salc', 'sar', 'sbb', 'scasb', 'scasd', 'scasw', 'seta', 'setae', 'setb', 'setbe', 'setc', 'setcxz', 'sete', 'setg', 'setge', 'setl', 'setle', 'setna', 'setnae', 'setnb', 'setnbe', 'setnc', 'setne', 'setng', 'setnge', 'setnl', 'setnle', 'setno', 'setnp', 'setns', 'setnz', 'seto', 'setp', 'setpe', 'setpo', 'sets', 'setz', 'sgdt', 'shl', 'shld', 'shr', 'shrd', 'sidt', 'sldt', 'smi', 'smint', 'smintold', 'smsw', 'stc', 'std', 'sti', 'stosb', 'stosd', 'stosw', 'str', 'sub', 'svdc', 'svldt', 'svts', 'syscall', 'sysenter', 'sysexit', 'sysret', 'test', 'ud1', 'ud2', 'umov', 'verr', 'verw', 'wait', 'wbinvd', 'wrmsr', 'wrshr', 'xadd', 'xbts', 'xchg', 'xlat', 'xlatb', 'xor' }
PORTUGOL_KEYWORDS = ( 'aleatorio', 'algoritmo', 'arquivo', 'ate', 'caso', 'cronometro', 'debug', 'e', 'eco', 'enquanto', 'entao', 'escolha', 'escreva', 'escreval', 'faca', 'falso', 'fimalgoritmo', 'fimenquanto', 'fimescolha', 'fimfuncao', 'fimpara', 'fimprocedimento', 'fimrepita', 'fimse', 'funcao', 'inicio', 'int', 'interrompa', 'leia', 'limpatela', 'mod', 'nao', 'ou', 'outrocaso', 'para', 'passo', 'pausa', 'procedimento', 'repita', 'retorne', 'se', 'senao', 'timer', 'var', 'vetor', 'verdadeiro', 'xou', 'div', 'mod', 'abs', 'arccos', 'arcsen', 'arctan', 'cos', 'cotan', 'Exp', 'grauprad', 'int', 'log', 'logn', 'pi', 'quad', 'radpgrau', 'raizq', 'rand', 'randi', 'sen', 'Tan', 'asc', 'carac', 'caracpnum', 'compr', 'copia', 'maiusc', 'minusc', 'numpcarac', 'pos', )
PORTUGOL_BUILTIN_TYPES = { 'inteiro', 'real', 'caractere', 'logico' }
def __init__(self, **options): Lexer.__init__(self, **options) self.keywords = set() self.builtins = set() if get_bool_opt(options, 'portugol', False): self.keywords.update(self.PORTUGOL_KEYWORDS) self.builtins.update(self.PORTUGOL_BUILTIN_TYPES) self.is_portugol = True else: self.is_portugol = False
if get_bool_opt(options, 'turbopascal', True): self.keywords.update(self.TURBO_PASCAL_KEYWORDS) if get_bool_opt(options, 'delphi', True): self.keywords.update(self.DELPHI_KEYWORDS) if get_bool_opt(options, 'freepascal', True): self.keywords.update(self.FREE_PASCAL_KEYWORDS) for unit in get_list_opt(options, 'units', list(self.BUILTIN_UNITS)): self.builtins.update(self.BUILTIN_UNITS[unit])
def get_tokens_unprocessed(self, text): scanner = Scanner(text, re.DOTALL | re.MULTILINE | re.IGNORECASE) stack = ['initial'] in_function_block = False in_property_block = False was_dot = False next_token_is_function = False next_token_is_property = False collect_labels = False block_labels = set() brace_balance = [0, 0]
while not scanner.eos: token = Error
if stack[-1] == 'initial': if scanner.scan(r'\s+'): token = Whitespace elif not self.is_portugol and scanner.scan(r'\{.*?\}|\(\*.*?\*\)'): if scanner.match.startswith('$'): token = Comment.Preproc else: token = Comment.Multiline elif scanner.scan(r'//.*?$'): token = Comment.Single elif self.is_portugol and scanner.scan(r'(<\-)|(>=)|(<=)|%|<|>|-|\+|\*|\=|(<>)|\/|\.|:|,'): token = Operator elif not self.is_portugol and scanner.scan(r'[-+*\/=<>:;,.@\^]'): token = Operator # stop label highlighting on next ";" if collect_labels and scanner.match == ';': collect_labels = False elif scanner.scan(r'[\(\)\[\]]+'): token = Punctuation # abort function naming ``foo = Function(...)`` next_token_is_function = False # if we are in a function block we count the open # braces because ootherwise it's impossible to # determine the end of the modifier context if in_function_block or in_property_block: if scanner.match == '(': brace_balance[0] += 1 elif scanner.match == ')': brace_balance[0] -= 1 elif scanner.match == '[': brace_balance[1] += 1 elif scanner.match == ']': brace_balance[1] -= 1 elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'): lowercase_name = scanner.match.lower() if lowercase_name == 'result': token = Name.Builtin.Pseudo elif lowercase_name in self.keywords: token = Keyword # if we are in a special block and a # block ending keyword occurs (and the parenthesis # is balanced) we end the current block context if self.is_portugol: if lowercase_name in ('funcao', 'procedimento'): in_function_block = True next_token_is_function = True else: if (in_function_block or in_property_block) and \ lowercase_name in self.BLOCK_KEYWORDS and \ brace_balance[0] <= 0 and \ brace_balance[1] <= 0: in_function_block = False in_property_block = False brace_balance = [0, 0] block_labels = set() if lowercase_name in ('label', 'goto'): collect_labels = True elif lowercase_name == 'asm': stack.append('asm') elif lowercase_name == 'property': in_property_block = True next_token_is_property = True elif lowercase_name in ('procedure', 'operator', 'function', 'constructor', 'destructor'): in_function_block = True next_token_is_function = True # we are in a function block and the current name # is in the set of registered modifiers. highlight # it as pseudo keyword elif not self.is_portugol and in_function_block and \ lowercase_name in self.FUNCTION_MODIFIERS: token = Keyword.Pseudo # if we are in a property highlight some more # modifiers elif not self.is_portugol and in_property_block and \ lowercase_name in ('read', 'write'): token = Keyword.Pseudo next_token_is_function = True # if the last iteration set next_token_is_function # to true we now want this name highlighted as # function. so do that and reset the state elif next_token_is_function: # Look if the next token is a dot. If yes it's # not a function, but a class name and the # part after the dot a function name if not self.is_portugol and scanner.test(r'\s*\.\s*'): token = Name.Class # it's not a dot, our job is done else: token = Name.Function next_token_is_function = False
if self.is_portugol: block_labels.add(scanner.match.lower())
# same for properties elif not self.is_portugol and next_token_is_property: token = Name.Property next_token_is_property = False # Highlight this token as label and add it # to the list of known labels elif not self.is_portugol and collect_labels: token = Name.Label block_labels.add(scanner.match.lower()) # name is in list of known labels elif lowercase_name in block_labels: token = Name.Label elif self.is_portugol and lowercase_name in self.PORTUGOL_BUILTIN_TYPES: token = Keyword.Type elif not self.is_portugol and lowercase_name in self.BUILTIN_TYPES: token = Keyword.Type elif not self.is_portugol and lowercase_name in self.DIRECTIVES: token = Keyword.Pseudo # builtins are just builtins if the token # before isn't a dot elif not self.is_portugol and not was_dot and lowercase_name in self.builtins: token = Name.Builtin else: token = Name elif self.is_portugol and scanner.scan(r"\""): token = String stack.append('string') elif not self.is_portugol and scanner.scan(r"'"): token = String stack.append('string') elif not self.is_portugol and scanner.scan(r'\#(\d+|\$[0-9A-Fa-f]+)'): token = String.Char elif not self.is_portugol and scanner.scan(r'\$[0-9A-Fa-f]+'): token = Number.Hex elif scanner.scan(r'\d+(?![eE]|\.[^.])'): token = Number.Integer elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'): token = Number.Float else: # if the stack depth is deeper than once, pop if len(stack) > 1: stack.pop() scanner.get_char()
elif stack[-1] == 'string': if self.is_portugol: if scanner.scan(r"''"): token = String.Escape elif scanner.scan(r"\""): token = String stack.pop() elif scanner.scan(r"[^\"]*"): token = String else: scanner.get_char() stack.pop() else: if scanner.scan(r"''"): token = String.Escape elif scanner.scan(r"'"): token = String stack.pop() elif scanner.scan(r"[^']*"): token = String else: scanner.get_char() stack.pop() elif not self.is_portugol and stack[-1] == 'asm': if scanner.scan(r'\s+'): token = Whitespace elif scanner.scan(r'end'): token = Keyword stack.pop() elif scanner.scan(r'\{.*?\}|\(\*.*?\*\)'): if scanner.match.startswith('$'): token = Comment.Preproc else: token = Comment.Multiline elif scanner.scan(r'//.*?$'): token = Comment.Single elif scanner.scan(r"'"): token = String stack.append('string') elif scanner.scan(r'@@[A-Za-z_][A-Za-z_0-9]*'): token = Name.Label elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'): lowercase_name = scanner.match.lower() if lowercase_name in self.ASM_INSTRUCTIONS: token = Keyword elif lowercase_name in self.ASM_REGISTERS: token = Name.Builtin else: token = Name elif scanner.scan(r'[-+*\/=<>:;,.@\^]+'): token = Operator elif scanner.scan(r'[\(\)\[\]]+'): token = Punctuation elif scanner.scan(r'\$[0-9A-Fa-f]+'): token = Number.Hex elif scanner.scan(r'\d+(?![eE]|\.[^.])'): token = Number.Integer elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'): token = Number.Float else: scanner.get_char() stack.pop()
# save the dot!!!11 if not self.is_portugol and scanner.match.strip(): was_dot = scanner.match == '.'
yield scanner.start_pos, token, scanner.match or ''123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202""" pygments.lexers.pawn ~~~~~~~~~~~~~~~~~~~~
Lexers for the Pawn languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexerfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuationfrom pygments.util import get_bool_opt
__all__ = ['SourcePawnLexer', 'PawnLexer']
class SourcePawnLexer(RegexLexer): """ For SourcePawn source code with preprocessor directives. """ name = 'SourcePawn' aliases = ['sp'] filenames = ['*.sp'] mimetypes = ['text/x-sourcepawn'] url = 'https://github.com/alliedmodders/sourcepawn' version_added = '1.6'
#: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/\*.*?\*/)+' #: only one /* */ style comment _ws1 = r'\s*(?:/[*].*?[*]/\s*)*'
tokens = { 'root': [ # preprocessor directives: without whitespace (r'^#if\s+0', Comment.Preproc, 'if0'), ('^#', Comment.Preproc, 'macro'), # or with whitespace ('^' + _ws1 + r'#if\s+0', Comment.Preproc, 'if0'), ('^' + _ws1 + '#', Comment.Preproc, 'macro'), (r'\n', Text), (r'\s+', Text), (r'\\\n', Text), # line continuation (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline), (r'[{}]', Punctuation), (r'L?"', String, 'string'), (r"L?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', 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'[()\[\],.;]', Punctuation), (r'(case|const|continue|native|' r'default|else|enum|for|if|new|operator|' r'public|return|sizeof|static|decl|struct|switch)\b', Keyword), (r'(bool|Float)\b', Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'[a-zA-Z_]\w*', Name), ], '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 ], 'macro': [ (r'[^/\n]+', Comment.Preproc), (r'/\*(.|\n)*?\*/', Comment.Multiline), (r'//.*?\n', Comment.Single, '#pop'), (r'/', Comment.Preproc), (r'(?<=\\)\n', Comment.Preproc), (r'\n', Comment.Preproc, '#pop'), ], 'if0': [ (r'^\s*#if.*?(?<!\\)\n', Comment.Preproc, '#push'), (r'^\s*#endif.*?(?<!\\)\n', Comment.Preproc, '#pop'), (r'.*?\n', Comment), ] }
SM_TYPES = {'Action', 'bool', 'Float', 'Plugin', 'String', 'any', 'AdminFlag', 'OverrideType', 'OverrideRule', 'ImmunityType', 'GroupId', 'AdminId', 'AdmAccessMode', 'AdminCachePart', 'CookieAccess', 'CookieMenu', 'CookieMenuAction', 'NetFlow', 'ConVarBounds', 'QueryCookie', 'ReplySource', 'ConVarQueryResult', 'ConVarQueryFinished', 'Function', 'Action', 'Identity', 'PluginStatus', 'PluginInfo', 'DBResult', 'DBBindType', 'DBPriority', 'PropType', 'PropFieldType', 'MoveType', 'RenderMode', 'RenderFx', 'EventHookMode', 'EventHook', 'FileType', 'FileTimeMode', 'PathType', 'ParamType', 'ExecType', 'DialogType', 'Handle', 'KvDataTypes', 'NominateResult', 'MapChange', 'MenuStyle', 'MenuAction', 'MenuSource', 'RegexError', 'SDKCallType', 'SDKLibrary', 'SDKFuncConfSource', 'SDKType', 'SDKPassMethod', 'RayType', 'TraceEntityFilter', 'ListenOverride', 'SortOrder', 'SortType', 'SortFunc2D', 'APLRes', 'FeatureType', 'FeatureStatus', 'SMCResult', 'SMCError', 'TFClassType', 'TFTeam', 'TFCond', 'TFResourceType', 'Timer', 'TopMenuAction', 'TopMenuObjectType', 'TopMenuPosition', 'TopMenuObject', 'UserMsg'}
def __init__(self, **options): self.smhighlighting = get_bool_opt(options, 'sourcemod', True)
self._functions = set() if self.smhighlighting: from pygments.lexers._sourcemod_builtins import FUNCTIONS self._functions.update(FUNCTIONS) RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name: if self.smhighlighting: if value in self.SM_TYPES: token = Keyword.Type elif value in self._functions: token = Name.Builtin yield index, token, value
class PawnLexer(RegexLexer): """ For Pawn source code. """
name = 'Pawn' aliases = ['pawn'] filenames = ['*.p', '*.pwn', '*.inc'] mimetypes = ['text/x-pawn'] url = 'https://www.compuphase.com/pawn/pawn.htm' version_added = '2.0'
#: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/[*][\w\W]*?[*]/)+' #: only one /* */ style comment _ws1 = r'\s*(?:/[*].*?[*]/\s*)*'
tokens = { 'root': [ # preprocessor directives: without whitespace (r'^#if\s+0', Comment.Preproc, 'if0'), ('^#', Comment.Preproc, 'macro'), # or with whitespace ('^' + _ws1 + r'#if\s+0', Comment.Preproc, 'if0'), ('^' + _ws1 + '#', Comment.Preproc, 'macro'), (r'\n', Text), (r'\s+', Text), (r'\\\n', Text), # line continuation (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?\*[\w\W]*?\*(\\\n)?/', Comment.Multiline), (r'[{}]', Punctuation), (r'L?"', String, 'string'), (r"L?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', 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'[()\[\],.;]', Punctuation), (r'(switch|case|default|const|new|static|char|continue|break|' r'if|else|for|while|do|operator|enum|' r'public|return|sizeof|tagof|state|goto)\b', Keyword), (r'(bool|Float)\b', Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'[a-zA-Z_]\w*', Name), ], '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 ], 'macro': [ (r'[^/\n]+', Comment.Preproc), (r'/\*(.|\n)*?\*/', Comment.Multiline), (r'//.*?\n', Comment.Single, '#pop'), (r'/', Comment.Preproc), (r'(?<=\\)\n', Comment.Preproc), (r'\n', Comment.Preproc, '#pop'), ], 'if0': [ (r'^\s*#if.*?(?<!\\)\n', Comment.Preproc, '#push'), (r'^\s*#endif.*?(?<!\\)\n', Comment.Preproc, '#pop'), (r'.*?\n', Comment), ] }
def analyse_text(text): """This is basically C. There is a keyword which doesn't exist in C though and is nearly unique to this language.""" if 'tagof' in text: return 0.0112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182""" pygments.lexers.pddl ~~~~~~~~~~~~~~~~~~~~
Lexer for the Planning Domain Definition Language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, includefrom pygments.token import Punctuation, Keyword, Whitespace, Name, Comment, \ Operator, Number
__all__ = ['PddlLexer']
class PddlLexer(RegexLexer): """ A PDDL lexer.
It should support up to PDDL 3.1. """
name = 'PDDL' aliases = ['pddl'] filenames = ['*.pddl'] # there doesn't really seem to be a PDDL homepage. url = 'https://en.wikipedia.org/wiki/Planning_Domain_Definition_Language' version_added = '2.19'
tokens = { 'root': [ (r'\s+', Whitespace), (r';.*$', Comment.Singleline), include('keywords'), include('builtins'), (r'[()]', Punctuation), (r'[=/*+><-]', Operator), (r'[a-zA-Z][a-zA-Z0-9_-]*', Name), (r'\?[a-zA-Z][a-zA-Z0-9_-]*', Name.Variable), (r'[0-9]+\.[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), ], 'keywords': [ (words(( ':requirements', ':types', ':constants', ':predicates', ':functions', ':action', ':agent', ':parameters', ':precondition', ':effect', ':durative-action', ':duration', ':condition', ':derived', ':domain', ':objects', ':init', ':goal', ':metric', ':length', ':serial', ':parallel', # the following are requirements ':strips', ':typing', ':negative-preconditions', ':disjunctive-preconditions', ':equality', ':existential-preconditions', ':universal-preconditions', ':conditional-effects', ':fluents', ':numeric-fluents', ':object-fluents', ':adl', ':durative-actions', ':continuous-effects', ':derived-predicates', ':time-intial-literals', ':preferences', ':constraints', ':action-costs', ':multi-agent', ':unfactored-privacy', ':factored-privacy', ':non-deterministic' ), suffix=r'\b'), Keyword) ], 'builtins': [ (words(( 'define', 'domain', 'object', 'either', 'and', 'forall', 'preference', 'imply', 'or', 'exists', 'not', 'when', 'assign', 'scale-up', 'scale-down', 'increase', 'decrease', 'at', 'over', 'start', 'end', 'all', 'problem', 'always', 'sometime', 'within', 'at-most-once', 'sometime-after', 'sometime-before', 'always-within', 'hold-during', 'hold-after', 'minimize', 'maximize', 'total-time', 'is-violated'), suffix=r'\b'), Name.Builtin) ] }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733""" pygments.lexers.perl ~~~~~~~~~~~~~~~~~~~~
Lexers for Perl, Raku and 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, ExtendedRegexLexer, include, bygroups, \ using, this, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespacefrom pygments.util import shebang_matches
__all__ = ['PerlLexer', 'Perl6Lexer']
class PerlLexer(RegexLexer): """ For Perl source code. """
name = 'Perl' url = 'https://www.perl.org' aliases = ['perl', 'pl'] filenames = ['*.pl', '*.pm', '*.t', '*.perl'] mimetypes = ['text/x-perl', 'application/x-perl'] version_added = ''
flags = re.DOTALL | re.MULTILINE # TODO: give this to a perl guy who knows how to parse perl... tokens = { 'balanced-regex': [ (r'/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*', String.Regex, '#pop'), (r'!(\\\\|\\[^\\]|[^\\!])*![egimosx]*', String.Regex, '#pop'), (r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'), (r'\{(\\\\|\\[^\\]|[^\\}])*\}[egimosx]*', String.Regex, '#pop'), (r'<(\\\\|\\[^\\]|[^\\>])*>[egimosx]*', String.Regex, '#pop'), (r'\[(\\\\|\\[^\\]|[^\\\]])*\][egimosx]*', String.Regex, '#pop'), (r'\((\\\\|\\[^\\]|[^\\)])*\)[egimosx]*', String.Regex, '#pop'), (r'@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*', String.Regex, '#pop'), (r'%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*', String.Regex, '#pop'), (r'\$(\\\\|\\[^\\]|[^\\$])*\$[egimosx]*', String.Regex, '#pop'), ], 'root': [ (r'\A\#!.+?$', Comment.Hashbang), (r'\#.*?$', Comment.Single), (r'^=[a-zA-Z0-9]+\s+.*?\n=cut', Comment.Multiline), (words(( 'case', 'continue', 'do', 'else', 'elsif', 'for', 'foreach', 'if', 'last', 'my', 'next', 'our', 'redo', 'reset', 'then', 'unless', 'until', 'while', 'print', 'new', 'BEGIN', 'CHECK', 'INIT', 'END', 'return'), suffix=r'\b'), Keyword), (r'(format)(\s+)(\w+)(\s*)(=)(\s*\n)', bygroups(Keyword, Whitespace, Name, Whitespace, Punctuation, Whitespace), 'format'), (r'(eq|lt|gt|le|ge|ne|not|and|or|cmp)\b', Operator.Word), # common delimiters (r's/(\\\\|\\[^\\]|[^\\/])*/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*', String.Regex), (r's!(\\\\|\\!|[^!])*!(\\\\|\\!|[^!])*![egimosx]*', String.Regex), (r's\\(\\\\|[^\\])*\\(\\\\|[^\\])*\\[egimosx]*', String.Regex), (r's@(\\\\|\\[^\\]|[^\\@])*@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*', String.Regex), (r's%(\\\\|\\[^\\]|[^\\%])*%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*', String.Regex), # balanced delimiters (r's\{(\\\\|\\[^\\]|[^\\}])*\}\s*', String.Regex, 'balanced-regex'), (r's<(\\\\|\\[^\\]|[^\\>])*>\s*', String.Regex, 'balanced-regex'), (r's\[(\\\\|\\[^\\]|[^\\\]])*\]\s*', String.Regex, 'balanced-regex'), (r's\((\\\\|\\[^\\]|[^\\)])*\)\s*', String.Regex, 'balanced-regex'),
(r'm?/(\\\\|\\[^\\]|[^\\/\n])*/[gcimosx]*', String.Regex), (r'm(?=[/!\\{<\[(@%$])', String.Regex, 'balanced-regex'), (r'((?<==~)|(?<=\())\s*/(\\\\|\\[^\\]|[^\\/])*/[gcimosx]*', String.Regex), (r'\s+', Whitespace), (words(( 'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller', 'chdir', 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'close', 'closedir', 'connect', 'continue', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined', 'delete', 'die', 'dump', 'each', 'endgrent', 'endhostent', 'endnetent', 'endprotoent', 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists', 'exit', 'exp', 'fcntl', 'fileno', 'flock', 'fork', 'format', 'formline', 'getc', 'getgrent', 'getgrgid', 'getgrnam', 'gethostbyaddr', 'gethostbyname', 'gethostent', 'getlogin', 'getnetbyaddr', 'getnetbyname', 'getnetent', 'getpeername', 'getpgrp', 'getppid', 'getpriority', 'getprotobyname', 'getprotobynumber', 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid', 'getservbyname', 'getservbyport', 'getservent', 'getsockname', 'getsockopt', 'glob', 'gmtime', 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl', 'join', 'keys', 'kill', 'last', 'lc', 'lcfirst', 'length', 'link', 'listen', 'local', 'localtime', 'log', 'lstat', 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'my', 'next', 'oct', 'open', 'opendir', 'ord', 'our', 'pack', 'pipe', 'pop', 'pos', 'printf', 'prototype', 'push', 'quotemeta', 'rand', 'read', 'readdir', 'readline', 'readlink', 'readpipe', 'recv', 'redo', 'ref', 'rename', 'reverse', 'rewinddir', 'rindex', 'rmdir', 'scalar', 'seek', 'seekdir', 'select', 'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent', 'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent', 'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown', 'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf', 'sqrt', 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysopen', 'sysread', 'sysseek', 'system', 'syswrite', 'tell', 'telldir', 'tie', 'tied', 'time', 'times', 'tr', 'truncate', 'uc', 'ucfirst', 'umask', 'undef', 'unlink', 'unpack', 'unshift', 'untie', 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray', 'warn', 'write'), suffix=r'\b'), Name.Builtin), (r'((__(DATA|DIE|WARN)__)|(STD(IN|OUT|ERR)))\b', Name.Builtin.Pseudo), (r'(<<)([\'"]?)([a-zA-Z_]\w*)(\2;?\n.*?\n)(\3)(\n)', bygroups(String, String, String.Delimiter, String, String.Delimiter, Whitespace)), (r'__END__', Comment.Preproc, 'end-part'), (r'\$\^[ADEFHILMOPSTWX]', Name.Variable.Global), (r"\$[\\\"\[\]'&`+*.,;=%~?@$!<>(^|/-](?!\w)", Name.Variable.Global), (r'[$@%#]+', Name.Variable, 'varname'), (r'0_?[0-7]+(_[0-7]+)*', Number.Oct), (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex), (r'0b[01]+(_[01]+)*', Number.Bin), (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?', Number.Float), (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float), (r'\d+(_\d+)*', Number.Integer), (r"'(\\\\|\\[^\\]|[^'\\])*'", String), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r'`(\\\\|\\[^\\]|[^`\\])*`', String.Backtick), (r'<([^\s>]+)>', String.Regex), (r'(q|qq|qw|qr|qx)\{', String.Other, 'cb-string'), (r'(q|qq|qw|qr|qx)\(', String.Other, 'rb-string'), (r'(q|qq|qw|qr|qx)\[', String.Other, 'sb-string'), (r'(q|qq|qw|qr|qx)\<', String.Other, 'lt-string'), (r'(q|qq|qw|qr|qx)([\W_])(.|\n)*?\2', String.Other), (r'(package)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(use|require|no)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(sub)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (words(( 'no', 'package', 'require', 'use'), suffix=r'\b'), Keyword), (r'(\[\]|\*\*|::|<<|>>|>=|<=>|<=|={3}|!=|=~|' r'!~|&&?|\|\||\.{1,3})', Operator), (r'[-+/*%=<>&^|!\\~]=?', Operator), (r'[()\[\]:;,<>/?{}]', Punctuation), # yes, there's no shortage # of punctuation in Perl! (r'(?=\w)', Name, 'name'), ], 'format': [ (r'\.\n', String.Interpol, '#pop'), (r'[^\n]*\n', String.Interpol), ], 'varname': [ (r'\s+', Whitespace), (r'\{', Punctuation, '#pop'), # hash syntax? (r'\)|,', Punctuation, '#pop'), # argument specifier (r'\w+::', Name.Namespace), (r'[\w:]+', Name.Variable, '#pop'), ], 'name': [ (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*(::)?(?=\s*->)', Name.Namespace, '#pop'), (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*::', Name.Namespace, '#pop'), (r'[\w:]+', Name, '#pop'), (r'[A-Z_]+(?=\W)', Name.Constant, '#pop'), (r'(?=\W)', Text, '#pop'), ], 'funcname': [ (r'[a-zA-Z_]\w*[!?]?', Name.Function), (r'\s+', Whitespace), # argument declaration (r'(\([$@%]*\))(\s*)', bygroups(Punctuation, Whitespace)), (r';', Punctuation, '#pop'), (r'.*?\{', Punctuation, '#pop'), ], 'cb-string': [ (r'\\[{}\\]', String.Other), (r'\\', String.Other), (r'\{', String.Other, 'cb-string'), (r'\}', String.Other, '#pop'), (r'[^{}\\]+', String.Other) ], 'rb-string': [ (r'\\[()\\]', String.Other), (r'\\', String.Other), (r'\(', String.Other, 'rb-string'), (r'\)', String.Other, '#pop'), (r'[^()]+', String.Other) ], 'sb-string': [ (r'\\[\[\]\\]', String.Other), (r'\\', String.Other), (r'\[', String.Other, 'sb-string'), (r'\]', String.Other, '#pop'), (r'[^\[\]]+', String.Other) ], 'lt-string': [ (r'\\[<>\\]', String.Other), (r'\\', String.Other), (r'\<', String.Other, 'lt-string'), (r'\>', String.Other, '#pop'), (r'[^<>]+', String.Other) ], 'end-part': [ (r'.+', Comment.Preproc, '#pop') ] }
def analyse_text(text): if shebang_matches(text, r'perl'): return True
result = 0
if re.search(r'(?:my|our)\s+[$@%(]', text): result += 0.9
if ':=' in text: # := is not valid Perl, but it appears in unicon, so we should # become less confident if we think we found Perl with := result /= 2
return result
class Perl6Lexer(ExtendedRegexLexer): """ For Raku (a.k.a. Perl 6) source code. """
name = 'Perl6' url = 'https://www.raku.org' aliases = ['perl6', 'pl6', 'raku'] filenames = ['*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6', '*.6pm', '*.p6m', '*.pm6', '*.t', '*.raku', '*.rakumod', '*.rakutest', '*.rakudoc'] mimetypes = ['text/x-perl6', 'application/x-perl6'] version_added = '2.0' flags = re.MULTILINE | re.DOTALL
PERL6_IDENTIFIER_RANGE = r"['\w:-]"
PERL6_KEYWORDS = ( #Phasers 'BEGIN','CATCH','CHECK','CLOSE','CONTROL','DOC','END','ENTER','FIRST', 'INIT','KEEP','LAST','LEAVE','NEXT','POST','PRE','QUIT','UNDO', #Keywords 'anon','augment','but','class','constant','default','does','else', 'elsif','enum','for','gather','given','grammar','has','if','import', 'is','let','loop','made','make','method','module','multi','my','need', 'orwith','our','proceed','proto','repeat','require','return', 'return-rw','returns','role','rule','state','sub','submethod','subset', 'succeed','supersede','token','try','unit','unless','until','use', 'when','while','with','without', #Traits 'export','native','repr','required','rw','symbol', )
PERL6_BUILTINS = ( 'ACCEPTS','abs','abs2rel','absolute','accept','accessed','acos', 'acosec','acosech','acosh','acotan','acotanh','acquire','act','action', 'actions','add','add_attribute','add_enum_value','add_fallback', 'add_method','add_parent','add_private_method','add_role','add_trustee', 'adverb','after','all','allocate','allof','allowed','alternative-names', 'annotations','antipair','antipairs','any','anyof','app_lifetime', 'append','arch','archname','args','arity','Array','asec','asech','asin', 'asinh','ASSIGN-KEY','ASSIGN-POS','assuming','ast','at','atan','atan2', 'atanh','AT-KEY','atomic-assign','atomic-dec-fetch','atomic-fetch', 'atomic-fetch-add','atomic-fetch-dec','atomic-fetch-inc', 'atomic-fetch-sub','atomic-inc-fetch','AT-POS','attributes','auth', 'await','backtrace','Bag','BagHash','bail-out','base','basename', 'base-repeating','batch','BIND-KEY','BIND-POS','bind-stderr', 'bind-stdin','bind-stdout','bind-udp','bits','bless','block','Bool', 'bool-only','bounds','break','Bridge','broken','BUILD','build-date', 'bytes','cache','callframe','calling-package','CALL-ME','callsame', 'callwith','can','cancel','candidates','cando','can-ok','canonpath', 'caps','caption','Capture','cas','catdir','categorize','categorize-list', 'catfile','catpath','cause','ceiling','cglobal','changed','Channel', 'chars','chdir','child','child-name','child-typename','chmod','chomp', 'chop','chr','chrs','chunks','cis','classify','classify-list','cleanup', 'clone','close','closed','close-stdin','cmp-ok','code','codes','collate', 'column','comb','combinations','command','comment','compiler','Complex', 'compose','compose_type','composer','condition','config', 'configure_destroy','configure_type_checking','conj','connect', 'constraints','construct','contains','contents','copy','cos','cosec', 'cosech','cosh','cotan','cotanh','count','count-only','cpu-cores', 'cpu-usage','CREATE','create_type','cross','cue','curdir','curupdir','d', 'Date','DateTime','day','daycount','day-of-month','day-of-week', 'day-of-year','days-in-month','declaration','decode','decoder','deepmap', 'default','defined','DEFINITE','delayed','DELETE-KEY','DELETE-POS', 'denominator','desc','DESTROY','destroyers','devnull','diag', 'did-you-mean','die','dies-ok','dir','dirname','dir-sep','DISTROnames', 'do','does','does-ok','done','done-testing','duckmap','dynamic','e', 'eager','earlier','elems','emit','enclosing','encode','encoder', 'encoding','end','ends-with','enum_from_value','enum_value_list', 'enum_values','enums','eof','EVAL','eval-dies-ok','EVALFILE', 'eval-lives-ok','exception','excludes-max','excludes-min','EXISTS-KEY', 'EXISTS-POS','exit','exitcode','exp','expected','explicitly-manage', 'expmod','extension','f','fail','fails-like','fc','feature','file', 'filename','find_method','find_method_qualified','finish','first','flat', 'flatmap','flip','floor','flunk','flush','fmt','format','formatter', 'freeze','from','from-list','from-loop','from-posix','full', 'full-barrier','get','get_value','getc','gist','got','grab','grabpairs', 'grep','handle','handled','handles','hardware','has_accessor','Hash', 'head','headers','hh-mm-ss','hidden','hides','hour','how','hyper','id', 'illegal','im','in','indent','index','indices','indir','infinite', 'infix','infix:<+>','infix:<->','install_method_cache','Instant', 'instead','Int','int-bounds','interval','in-timezone','invalid-str', 'invert','invocant','IO','IO::Notification.watch-path','is_trusted', 'is_type','isa','is-absolute','isa-ok','is-approx','is-deeply', 'is-hidden','is-initial-thread','is-int','is-lazy','is-leap-year', 'isNaN','isnt','is-prime','is-relative','is-routine','is-setting', 'is-win','item','iterator','join','keep','kept','KERNELnames','key', 'keyof','keys','kill','kv','kxxv','l','lang','last','lastcall','later', 'lazy','lc','leading','level','like','line','lines','link','List', 'listen','live','lives-ok','local','lock','log','log10','lookup','lsb', 'made','MAIN','make','Map','match','max','maxpairs','merge','message', 'method','method_table','methods','migrate','min','minmax','minpairs', 'minute','misplaced','Mix','MixHash','mkdir','mode','modified','month', 'move','mro','msb','multi','multiness','my','name','named','named_names', 'narrow','nativecast','native-descriptor','nativesizeof','new','new_type', 'new-from-daycount','new-from-pairs','next','nextcallee','next-handle', 'nextsame','nextwith','NFC','NFD','NFKC','NFKD','nl-in','nl-out', 'nodemap','nok','none','norm','not','note','now','nude','Num', 'numerator','Numeric','of','offset','offset-in-hours','offset-in-minutes', 'ok','old','on-close','one','on-switch','open','opened','operation', 'optional','ord','ords','orig','os-error','osname','out-buffer','pack', 'package','package-kind','package-name','packages','pair','pairs', 'pairup','parameter','params','parent','parent-name','parents','parse', 'parse-base','parsefile','parse-names','parts','pass','path','path-sep', 'payload','peer-host','peer-port','periods','perl','permutations','phaser', 'pick','pickpairs','pid','placeholder','plan','plus','polar','poll', 'polymod','pop','pos','positional','posix','postfix','postmatch', 'precomp-ext','precomp-target','pred','prefix','prematch','prepend', 'print','printf','print-nl','print-to','private','private_method_table', 'proc','produce','Promise','prompt','protect','pull-one','push', 'push-all','push-at-least','push-exactly','push-until-lazy','put', 'qualifier-type','quit','r','race','radix','rand','range','Rat','raw', 're','read','readchars','readonly','ready','Real','reallocate','reals', 'reason','rebless','receive','recv','redispatcher','redo','reduce', 'rel2abs','relative','release','rename','repeated','replacement', 'report','reserved','resolve','restore','result','resume','rethrow', 'reverse','right','rindex','rmdir','role','roles_to_compose','rolish', 'roll','rootdir','roots','rotate','rotor','round','roundrobin', 'routine-type','run','rwx','s','samecase','samemark','samewith','say', 'schedule-on','scheduler','scope','sec','sech','second','seek','self', 'send','Set','set_hidden','set_name','set_package','set_rw','set_value', 'SetHash','set-instruments','setup_finalization','shape','share','shell', 'shift','sibling','sigil','sign','signal','signals','signature','sin', 'sinh','sink','sink-all','skip','skip-at-least','skip-at-least-pull-one', 'skip-one','skip-rest','sleep','sleep-timer','sleep-until','Slip','slurp', 'slurp-rest','slurpy','snap','snapper','so','socket-host','socket-port', 'sort','source','source-package','spawn','SPEC','splice','split', 'splitdir','splitpath','sprintf','spurt','sqrt','squish','srand','stable', 'start','started','starts-with','status','stderr','stdout','Str', 'sub_signature','subbuf','subbuf-rw','subname','subparse','subst', 'subst-mutate','substr','substr-eq','substr-rw','subtest','succ','sum', 'Supply','symlink','t','tail','take','take-rw','tan','tanh','tap', 'target','target-name','tc','tclc','tell','then','throttle','throw', 'throws-like','timezone','tmpdir','to','today','todo','toggle','to-posix', 'total','trailing','trans','tree','trim','trim-leading','trim-trailing', 'truncate','truncated-to','trusts','try_acquire','trying','twigil','type', 'type_captures','typename','uc','udp','uncaught_handler','unimatch', 'uniname','uninames','uniparse','uniprop','uniprops','unique','unival', 'univals','unlike','unlink','unlock','unpack','unpolar','unshift', 'unwrap','updir','USAGE','use-ok','utc','val','value','values','VAR', 'variable','verbose-config','version','VMnames','volume','vow','w','wait', 'warn','watch','watch-path','week','weekday-of-month','week-number', 'week-year','WHAT','when','WHERE','WHEREFORE','WHICH','WHO', 'whole-second','WHY','wordcase','words','workaround','wrap','write', 'write-to','x','yada','year','yield','yyyy-mm-dd','z','zip','zip-latest',
)
PERL6_BUILTIN_CLASSES = ( #Booleans 'False','True', #Classes 'Any','Array','Associative','AST','atomicint','Attribute','Backtrace', 'Backtrace::Frame','Bag','Baggy','BagHash','Blob','Block','Bool','Buf', 'Callable','CallFrame','Cancellation','Capture','CArray','Channel','Code', 'compiler','Complex','ComplexStr','Cool','CurrentThreadScheduler', 'Cursor','Date','Dateish','DateTime','Distro','Duration','Encoding', 'Exception','Failure','FatRat','Grammar','Hash','HyperWhatever','Instant', 'Int','int16','int32','int64','int8','IntStr','IO','IO::ArgFiles', 'IO::CatHandle','IO::Handle','IO::Notification','IO::Path', 'IO::Path::Cygwin','IO::Path::QNX','IO::Path::Unix','IO::Path::Win32', 'IO::Pipe','IO::Socket','IO::Socket::Async','IO::Socket::INET','IO::Spec', 'IO::Spec::Cygwin','IO::Spec::QNX','IO::Spec::Unix','IO::Spec::Win32', 'IO::Special','Iterable','Iterator','Junction','Kernel','Label','List', 'Lock','Lock::Async','long','longlong','Macro','Map','Match', 'Metamodel::AttributeContainer','Metamodel::C3MRO','Metamodel::ClassHOW', 'Metamodel::EnumHOW','Metamodel::Finalization','Metamodel::MethodContainer', 'Metamodel::MROBasedMethodDispatch','Metamodel::MultipleInheritance', 'Metamodel::Naming','Metamodel::Primitives','Metamodel::PrivateMethodContainer', 'Metamodel::RoleContainer','Metamodel::Trusting','Method','Mix','MixHash', 'Mixy','Mu','NFC','NFD','NFKC','NFKD','Nil','Num','num32','num64', 'Numeric','NumStr','ObjAt','Order','Pair','Parameter','Perl','Pod::Block', 'Pod::Block::Code','Pod::Block::Comment','Pod::Block::Declarator', 'Pod::Block::Named','Pod::Block::Para','Pod::Block::Table','Pod::Heading', 'Pod::Item','Pointer','Positional','PositionalBindFailover','Proc', 'Proc::Async','Promise','Proxy','PseudoStash','QuantHash','Range','Rat', 'Rational','RatStr','Real','Regex','Routine','Scalar','Scheduler', 'Semaphore','Seq','Set','SetHash','Setty','Signature','size_t','Slip', 'Stash','Str','StrDistance','Stringy','Sub','Submethod','Supplier', 'Supplier::Preserving','Supply','Systemic','Tap','Telemetry', 'Telemetry::Instrument::Thread','Telemetry::Instrument::Usage', 'Telemetry::Period','Telemetry::Sampler','Thread','ThreadPoolScheduler', 'UInt','uint16','uint32','uint64','uint8','Uni','utf8','Variable', 'Version','VM','Whatever','WhateverCode','WrapHandle' )
PERL6_OPERATORS = ( 'X', 'Z', 'after', 'also', 'and', 'andthen', 'before', 'cmp', 'div', 'eq', 'eqv', 'extra', 'ff', 'fff', 'ge', 'gt', 'le', 'leg', 'lt', 'm', 'mm', 'mod', 'ne', 'or', 'orelse', 'rx', 's', 'tr', 'x', 'xor', 'xx', '++', '--', '**', '!', '+', '-', '~', '?', '|', '||', '+^', '~^', '?^', '^', '*', '/', '%', '%%', '+&', '+<', '+>', '~&', '~<', '~>', '?&', 'gcd', 'lcm', '+', '-', '+|', '+^', '~|', '~^', '?|', '?^', '~', '&', '^', 'but', 'does', '<=>', '..', '..^', '^..', '^..^', '!=', '==', '<', '<=', '>', '>=', '~~', '===', '!eqv', '&&', '||', '^^', '//', 'min', 'max', '??', '!!', 'ff', 'fff', 'so', 'not', '<==', '==>', '<<==', '==>>','unicmp', )
# Perl 6 has a *lot* of possible bracketing characters # this list was lifted from STD.pm6 (https://github.com/perl6/std) PERL6_BRACKETS = { '\u0028': '\u0029', '\u003c': '\u003e', '\u005b': '\u005d', '\u007b': '\u007d', '\u00ab': '\u00bb', '\u0f3a': '\u0f3b', '\u0f3c': '\u0f3d', '\u169b': '\u169c', '\u2018': '\u2019', '\u201a': '\u2019', '\u201b': '\u2019', '\u201c': '\u201d', '\u201e': '\u201d', '\u201f': '\u201d', '\u2039': '\u203a', '\u2045': '\u2046', '\u207d': '\u207e', '\u208d': '\u208e', '\u2208': '\u220b', '\u2209': '\u220c', '\u220a': '\u220d', '\u2215': '\u29f5', '\u223c': '\u223d', '\u2243': '\u22cd', '\u2252': '\u2253', '\u2254': '\u2255', '\u2264': '\u2265', '\u2266': '\u2267', '\u2268': '\u2269', '\u226a': '\u226b', '\u226e': '\u226f', '\u2270': '\u2271', '\u2272': '\u2273', '\u2274': '\u2275', '\u2276': '\u2277', '\u2278': '\u2279', '\u227a': '\u227b', '\u227c': '\u227d', '\u227e': '\u227f', '\u2280': '\u2281', '\u2282': '\u2283', '\u2284': '\u2285', '\u2286': '\u2287', '\u2288': '\u2289', '\u228a': '\u228b', '\u228f': '\u2290', '\u2291': '\u2292', '\u2298': '\u29b8', '\u22a2': '\u22a3', '\u22a6': '\u2ade', '\u22a8': '\u2ae4', '\u22a9': '\u2ae3', '\u22ab': '\u2ae5', '\u22b0': '\u22b1', '\u22b2': '\u22b3', '\u22b4': '\u22b5', '\u22b6': '\u22b7', '\u22c9': '\u22ca', '\u22cb': '\u22cc', '\u22d0': '\u22d1', '\u22d6': '\u22d7', '\u22d8': '\u22d9', '\u22da': '\u22db', '\u22dc': '\u22dd', '\u22de': '\u22df', '\u22e0': '\u22e1', '\u22e2': '\u22e3', '\u22e4': '\u22e5', '\u22e6': '\u22e7', '\u22e8': '\u22e9', '\u22ea': '\u22eb', '\u22ec': '\u22ed', '\u22f0': '\u22f1', '\u22f2': '\u22fa', '\u22f3': '\u22fb', '\u22f4': '\u22fc', '\u22f6': '\u22fd', '\u22f7': '\u22fe', '\u2308': '\u2309', '\u230a': '\u230b', '\u2329': '\u232a', '\u23b4': '\u23b5', '\u2768': '\u2769', '\u276a': '\u276b', '\u276c': '\u276d', '\u276e': '\u276f', '\u2770': '\u2771', '\u2772': '\u2773', '\u2774': '\u2775', '\u27c3': '\u27c4', '\u27c5': '\u27c6', '\u27d5': '\u27d6', '\u27dd': '\u27de', '\u27e2': '\u27e3', '\u27e4': '\u27e5', '\u27e6': '\u27e7', '\u27e8': '\u27e9', '\u27ea': '\u27eb', '\u2983': '\u2984', '\u2985': '\u2986', '\u2987': '\u2988', '\u2989': '\u298a', '\u298b': '\u298c', '\u298d': '\u298e', '\u298f': '\u2990', '\u2991': '\u2992', '\u2993': '\u2994', '\u2995': '\u2996', '\u2997': '\u2998', '\u29c0': '\u29c1', '\u29c4': '\u29c5', '\u29cf': '\u29d0', '\u29d1': '\u29d2', '\u29d4': '\u29d5', '\u29d8': '\u29d9', '\u29da': '\u29db', '\u29f8': '\u29f9', '\u29fc': '\u29fd', '\u2a2b': '\u2a2c', '\u2a2d': '\u2a2e', '\u2a34': '\u2a35', '\u2a3c': '\u2a3d', '\u2a64': '\u2a65', '\u2a79': '\u2a7a', '\u2a7d': '\u2a7e', '\u2a7f': '\u2a80', '\u2a81': '\u2a82', '\u2a83': '\u2a84', '\u2a8b': '\u2a8c', '\u2a91': '\u2a92', '\u2a93': '\u2a94', '\u2a95': '\u2a96', '\u2a97': '\u2a98', '\u2a99': '\u2a9a', '\u2a9b': '\u2a9c', '\u2aa1': '\u2aa2', '\u2aa6': '\u2aa7', '\u2aa8': '\u2aa9', '\u2aaa': '\u2aab', '\u2aac': '\u2aad', '\u2aaf': '\u2ab0', '\u2ab3': '\u2ab4', '\u2abb': '\u2abc', '\u2abd': '\u2abe', '\u2abf': '\u2ac0', '\u2ac1': '\u2ac2', '\u2ac3': '\u2ac4', '\u2ac5': '\u2ac6', '\u2acd': '\u2ace', '\u2acf': '\u2ad0', '\u2ad1': '\u2ad2', '\u2ad3': '\u2ad4', '\u2ad5': '\u2ad6', '\u2aec': '\u2aed', '\u2af7': '\u2af8', '\u2af9': '\u2afa', '\u2e02': '\u2e03', '\u2e04': '\u2e05', '\u2e09': '\u2e0a', '\u2e0c': '\u2e0d', '\u2e1c': '\u2e1d', '\u2e20': '\u2e21', '\u3008': '\u3009', '\u300a': '\u300b', '\u300c': '\u300d', '\u300e': '\u300f', '\u3010': '\u3011', '\u3014': '\u3015', '\u3016': '\u3017', '\u3018': '\u3019', '\u301a': '\u301b', '\u301d': '\u301e', '\ufd3e': '\ufd3f', '\ufe17': '\ufe18', '\ufe35': '\ufe36', '\ufe37': '\ufe38', '\ufe39': '\ufe3a', '\ufe3b': '\ufe3c', '\ufe3d': '\ufe3e', '\ufe3f': '\ufe40', '\ufe41': '\ufe42', '\ufe43': '\ufe44', '\ufe47': '\ufe48', '\ufe59': '\ufe5a', '\ufe5b': '\ufe5c', '\ufe5d': '\ufe5e', '\uff08': '\uff09', '\uff1c': '\uff1e', '\uff3b': '\uff3d', '\uff5b': '\uff5d', '\uff5f': '\uff60', '\uff62': '\uff63', }
def _build_word_match(words, boundary_regex_fragment=None, prefix='', suffix=''): if boundary_regex_fragment is None: return r'\b(' + prefix + r'|'.join(re.escape(x) for x in words) + \ suffix + r')\b' else: return r'(?<!' + boundary_regex_fragment + r')' + prefix + r'(' + \ r'|'.join(re.escape(x) for x in words) + r')' + suffix + r'(?!' + \ boundary_regex_fragment + r')'
def brackets_callback(token_class): def callback(lexer, match, context): groups = match.groupdict() opening_chars = groups['delimiter'] n_chars = len(opening_chars) adverbs = groups.get('adverbs')
closer = Perl6Lexer.PERL6_BRACKETS.get(opening_chars[0]) text = context.text
if closer is None: # it's not a mirrored character, which means we # just need to look for the next occurrence
end_pos = text.find(opening_chars, match.start('delimiter') + n_chars) else: # we need to look for the corresponding closing character, # keep nesting in mind closing_chars = closer * n_chars nesting_level = 1
search_pos = match.start('delimiter')
while nesting_level > 0: next_open_pos = text.find(opening_chars, search_pos + n_chars) next_close_pos = text.find(closing_chars, search_pos + n_chars)
if next_close_pos == -1: next_close_pos = len(text) nesting_level = 0 elif next_open_pos != -1 and next_open_pos < next_close_pos: nesting_level += 1 search_pos = next_open_pos else: # next_close_pos < next_open_pos nesting_level -= 1 search_pos = next_close_pos
end_pos = next_close_pos
if end_pos < 0: # if we didn't find a closer, just highlight the # rest of the text in this class end_pos = len(text)
if adverbs is not None and re.search(r':to\b', adverbs): heredoc_terminator = text[match.start('delimiter') + n_chars:end_pos] end_heredoc = re.search(r'^\s*' + re.escape(heredoc_terminator) + r'\s*$', text[end_pos:], re.MULTILINE)
if end_heredoc: end_pos += end_heredoc.end() else: end_pos = len(text)
yield match.start(), token_class, text[match.start():end_pos + n_chars] context.pos = end_pos + n_chars
return callback
def opening_brace_callback(lexer, match, context): stack = context.stack
yield match.start(), Text, context.text[match.start():match.end()] context.pos = match.end()
# if we encounter an opening brace and we're one level # below a token state, it means we need to increment # the nesting level for braces so we know later when # we should return to the token rules. if len(stack) > 2 and stack[-2] == 'token': context.perl6_token_nesting_level += 1
def closing_brace_callback(lexer, match, context): stack = context.stack
yield match.start(), Text, context.text[match.start():match.end()] context.pos = match.end()
# if we encounter a free closing brace and we're one level # below a token state, it means we need to check the nesting # level to see if we need to return to the token state. if len(stack) > 2 and stack[-2] == 'token': context.perl6_token_nesting_level -= 1 if context.perl6_token_nesting_level == 0: stack.pop()
def embedded_perl6_callback(lexer, match, context): context.perl6_token_nesting_level = 1 yield match.start(), Text, context.text[match.start():match.end()] context.pos = match.end() context.stack.append('root')
# If you're modifying these rules, be careful if you need to process '{' or '}' # characters. We have special logic for processing these characters (due to the fact # that you can nest Perl 6 code in regex blocks), so if you need to process one of # them, make sure you also process the corresponding one! tokens = { 'common': [ (r'#[`|=](?P<delimiter>(?P<first_char>[' + ''.join(PERL6_BRACKETS) + r'])(?P=first_char)*)', brackets_callback(Comment.Multiline)), (r'#[^\n]*$', Comment.Single), (r'^(\s*)=begin\s+(\w+)\b.*?^\1=end\s+\2', Comment.Multiline), (r'^(\s*)=for.*?\n\s*?\n', Comment.Multiline), (r'^=.*?\n\s*?\n', Comment.Multiline), (r'(regex|token|rule)(\s*' + PERL6_IDENTIFIER_RANGE + '+:sym)', bygroups(Keyword, Name), 'token-sym-brackets'), (r'(regex|token|rule)(?!' + PERL6_IDENTIFIER_RANGE + r')(\s*' + PERL6_IDENTIFIER_RANGE + '+)?', bygroups(Keyword, Name), 'pre-token'), # deal with a special case in the Perl 6 grammar (role q { ... }) (r'(role)(\s+)(q)(\s*)', bygroups(Keyword, Whitespace, Name, Whitespace)), (_build_word_match(PERL6_KEYWORDS, PERL6_IDENTIFIER_RANGE), Keyword), (_build_word_match(PERL6_BUILTIN_CLASSES, PERL6_IDENTIFIER_RANGE, suffix='(?::[UD])?'), Name.Builtin), (_build_word_match(PERL6_BUILTINS, PERL6_IDENTIFIER_RANGE), Name.Builtin), # copied from PerlLexer (r'[$@%&][.^:?=!~]?' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable), (r'\$[!/](?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable.Global), (r'::\?\w+', Name.Variable.Global), (r'[$@%&]\*' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable.Global), (r'\$(?:<.*?>)+', Name.Variable), (r'(?:q|qq|Q)[a-zA-Z]?\s*(?P<adverbs>:[\w\s:]+)?\s*(?P<delimiter>(?P<first_char>[^0-9a-zA-Z:\s])' r'(?P=first_char)*)', brackets_callback(String)), # copied from PerlLexer (r'0_?[0-7]+(_[0-7]+)*', Number.Oct), (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex), (r'0b[01]+(_[01]+)*', Number.Bin), (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?', Number.Float), (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float), (r'\d+(_\d+)*', Number.Integer), (r'(?<=~~)\s*/(?:\\\\|\\/|.)*?/', String.Regex), (r'(?<=[=(,])\s*/(?:\\\\|\\/|.)*?/', String.Regex), (r'm\w+(?=\()', Name), (r'(?:m|ms|rx)\s*(?P<adverbs>:[\w\s:]+)?\s*(?P<delimiter>(?P<first_char>[^\w:\s])' r'(?P=first_char)*)', brackets_callback(String.Regex)), (r'(?:s|ss|tr)\s*(?::[\w\s:]+)?\s*/(?:\\\\|\\/|.)*?/(?:\\\\|\\/|.)*?/', String.Regex), (r'<[^\s=].*?\S>', String), (_build_word_match(PERL6_OPERATORS), Operator), (r'\w' + PERL6_IDENTIFIER_RANGE + '*', Name), (r"'(\\\\|\\[^\\]|[^'\\])*'", String), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), ], 'root': [ include('common'), (r'\{', opening_brace_callback), (r'\}', closing_brace_callback), (r'.+?', Text), ], 'pre-token': [ include('common'), (r'\{', Text, ('#pop', 'token')), (r'.+?', Text), ], 'token-sym-brackets': [ (r'(?P<delimiter>(?P<first_char>[' + ''.join(PERL6_BRACKETS) + '])(?P=first_char)*)', brackets_callback(Name), ('#pop', 'pre-token')), default(('#pop', 'pre-token')), ], 'token': [ (r'\}', Text, '#pop'), (r'(?<=:)(?:my|our|state|constant|temp|let).*?;', using(this)), # make sure that quotes in character classes aren't treated as strings (r'<(?:[-!?+.]\s*)?\[.*?\]>', String.Regex), # make sure that '#' characters in quotes aren't treated as comments (r"(?<!\\)'(\\\\|\\[^\\]|[^'\\])*'", String.Regex), (r'(?<!\\)"(\\\\|\\[^\\]|[^"\\])*"', String.Regex), (r'#.*?$', Comment.Single), (r'\{', embedded_perl6_callback), ('.+?', String.Regex), ], }
def analyse_text(text): def strip_pod(lines): in_pod = False stripped_lines = []
for line in lines: if re.match(r'^=(?:end|cut)', line): in_pod = False elif re.match(r'^=\w+', line): in_pod = True elif not in_pod: stripped_lines.append(line)
return stripped_lines
# XXX handle block comments lines = text.splitlines() lines = strip_pod(lines) text = '\n'.join(lines)
if shebang_matches(text, r'perl6|rakudo|niecza|pugs'): return True
saw_perl_decl = False rating = False
# check for my/our/has declarations if re.search(r"(?:my|our|has)\s+(?:" + Perl6Lexer.PERL6_IDENTIFIER_RANGE + r"+\s+)?[$@%&(]", text): rating = 0.8 saw_perl_decl = True
for line in lines: line = re.sub('#.*', '', line) if re.match(r'^\s*$', line): continue
# match v6; use v6; use v6.0; use v6.0.0; if re.match(r'^\s*(?:use\s+)?v6(?:\.\d(?:\.\d)?)?;', line): return True # match class, module, role, enum, grammar declarations class_decl = re.match(r'^\s*(?:(?P<scope>my|our)\s+)?(?:module|class|role|enum|grammar)', line) if class_decl: if saw_perl_decl or class_decl.group('scope') is not None: return True rating = 0.05 continue break
if ':=' in text: # Same logic as above for PerlLexer rating /= 2
return rating
def __init__(self, **options): super().__init__(**options) self.encoding = options.get('encoding', 'utf-8')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363""" pygments.lexers.phix ~~~~~~~~~~~~~~~~~~~~
Lexers for Phix.
: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 Text, Comment, Operator, Keyword, Name, String, \ Whitespace
__all__ = ['PhixLexer']
class PhixLexer(RegexLexer): """ Pygments Lexer for Phix files (.exw). See http://phix.x10.mx """
name = 'Phix' url = 'http://phix.x10.mx' aliases = ['phix'] filenames = ['*.exw'] mimetypes = ['text/x-phix'] version_added = '2.14'
flags = re.MULTILINE # nb: **NOT** re.DOTALL! (totally spanners comment handling)
preproc = ( 'ifdef', 'elsifdef', 'elsedef' ) # Note these lists are auto-generated by pwa/p2js.exw, when pwa\src\p2js_keywords.e (etc) # change, though of course subsequent copy/commit/pull requests are all manual steps. types = ( 'string', 'nullable_string', 'atom_string', 'atom', 'bool', 'boolean', 'cdCanvan', 'cdCanvas', 'complex', 'CURLcode', 'dictionary', 'int', 'integer', 'Ihandle', 'Ihandles', 'Ihandln', 'mpfr', 'mpq', 'mpz', 'mpz_or_string', 'number', 'rid_string', 'seq', 'sequence', 'timedate', 'object' ) keywords = ( 'abstract', 'class', 'continue', 'export', 'extends', 'nullable', 'private', 'public', 'static', 'struct', 'trace', 'and', 'break', 'by', 'case', 'catch', 'const', 'constant', 'debug', 'default', 'do', 'else', 'elsif', 'end', 'enum', 'exit', 'fallthru', 'fallthrough', 'for', 'forward', 'function', 'global', 'if', 'in', 'include', 'js', 'javascript', 'javascript_semantics', 'let', 'not', 'or', 'procedure', 'profile', 'profile_time', 'return', 'safe_mode', 'switch', 'then', 'to', 'try', 'type', 'type_check', 'until', 'warning', 'while', 'with', 'without', 'xor' ) routines = ( 'abort', 'abs', 'adjust_timedate', 'and_bits', 'and_bitsu', 'apply', 'append', 'arccos', 'arcsin', 'arctan', 'assert', 'atan2', 'atom_to_float32', 'atom_to_float64', 'bankers_rounding', 'beep', 'begins', 'binary_search', 'bits_to_int', 'bk_color', 'bytes_to_int', 'call_func', 'call_proc', 'cdCanvasActivate', 'cdCanvasArc', 'cdCanvasBegin', 'cdCanvasBox', 'cdCanvasChord', 'cdCanvasCircle', 'cdCanvasClear', 'cdCanvasEnd', 'cdCanvasFlush', 'cdCanvasFont', 'cdCanvasGetImageRGB', 'cdCanvasGetSize', 'cdCanvasGetTextAlignment', 'cdCanvasGetTextSize', 'cdCanvasLine', 'cdCanvasMark', 'cdCanvasMarkSize', 'cdCanvasMultiLineVectorText', 'cdCanvasPixel', 'cdCanvasRect', 'cdCanvasRoundedBox', 'cdCanvasRoundedRect', 'cdCanvasSector', 'cdCanvasSetAttribute', 'cdCanvasSetBackground', 'cdCanvasSetFillMode', 'cdCanvasSetForeground', 'cdCanvasSetInteriorStyle', 'cdCanvasSetLineStyle', 'cdCanvasSetLineWidth', 'cdCanvasSetTextAlignment', 'cdCanvasText', 'cdCanvasSetTextOrientation', 'cdCanvasGetTextOrientation', 'cdCanvasVectorText', 'cdCanvasVectorTextDirection', 'cdCanvasVectorTextSize', 'cdCanvasVertex', 'cdCreateCanvas', 'cdDecodeAlpha', 'cdDecodeColor', 'cdDecodeColorAlpha', 'cdEncodeAlpha', 'cdEncodeColor', 'cdEncodeColorAlpha', 'cdKillCanvas', 'cdVersion', 'cdVersionDate', 'ceil', 'change_timezone', 'choose', 'clear_screen', 'columnize', 'command_line', 'compare', 'complex_abs', 'complex_add', 'complex_arg', 'complex_conjugate', 'complex_cos', 'complex_cosh', 'complex_div', 'complex_exp', 'complex_imag', 'complex_inv', 'complex_log', 'complex_mul', 'complex_neg', 'complex_new', 'complex_norm', 'complex_power', 'complex_rho', 'complex_real', 'complex_round', 'complex_sin', 'complex_sinh', 'complex_sprint', 'complex_sqrt', 'complex_sub', 'complex_theta', 'concat', 'cos', 'crash', 'custom_sort', 'date', 'day_of_week', 'day_of_year', 'days_in_month', 'decode_base64', 'decode_flags', 'deep_copy', 'deld', 'deserialize', 'destroy_dict', 'destroy_queue', 'destroy_stack', 'dict_name', 'dict_size', 'elapsed', 'elapsed_short', 'encode_base64', 'equal', 'even', 'exp', 'extract', 'factorial', 'factors', 'file_size_k', 'find', 'find_all', 'find_any', 'find_replace', 'filter', 'flatten', 'float32_to_atom', 'float64_to_atom', 'floor', 'format_timedate', 'free_console', 'from_polar', 'gcd', 'get_file_base', 'get_file_extension', 'get_file_name', 'get_file_name_and_path', 'get_file_path', 'get_file_path_and_name', 'get_maxprime', 'get_prime', 'get_primes', 'get_primes_le', 'get_proper_dir', 'get_proper_path', 'get_rand', 'get_routine_info', 'get_test_abort', 'get_test_logfile', 'get_test_pause', 'get_test_verbosity', 'get_tzid', 'getd', 'getdd', 'getd_all_keys', 'getd_by_index', 'getd_index', 'getd_partial_key', 'glAttachShader', 'glBindBuffer', 'glBindTexture', 'glBufferData', 'glCanvasSpecialText', 'glClear', 'glClearColor', 'glColor', 'glCompileShader', 'glCreateBuffer', 'glCreateProgram', 'glCreateShader', 'glCreateTexture', 'glDeleteProgram', 'glDeleteShader', 'glDrawArrays', 'glEnable', 'glEnableVertexAttribArray', 'glFloat32Array', 'glInt32Array', 'glFlush', 'glGetAttribLocation', 'glGetError', 'glGetProgramInfoLog', 'glGetProgramParameter', 'glGetShaderInfoLog', 'glGetShaderParameter', 'glGetUniformLocation', 'glLinkProgram', 'glLoadIdentity', 'glMatrixMode', 'glOrtho', 'glRotatef', 'glShadeModel', 'glShaderSource', 'glSimpleA7texcoords', 'glTexImage2Dc', 'glTexParameteri', 'glTranslate', 'glUniform1f', 'glUniform1i', 'glUniformMatrix4fv', 'glUseProgram', 'glVertex', 'glVertexAttribPointer', 'glViewport', 'head', 'hsv_to_rgb', 'iff', 'iif', 'include_file', 'incl0de_file', 'insert', 'instance', 'int_to_bits', 'int_to_bytes', 'is_dict', 'is_integer', 's_leap_year', 'is_prime', 'is_prime2', 'islower', 'isupper', 'Icallback', 'iup_isdouble', 'iup_isprint', 'iup_XkeyBase', 'IupAppend', 'IupAlarm', 'IupBackgroundBox', 'IupButton', 'IupCalendar', 'IupCanvas', 'IupClipboard', 'IupClose', 'IupCloseOnEscape', 'IupControlsOpen', 'IupDatePick', 'IupDestroy', 'IupDialog', 'IupDrawArc', 'IupDrawBegin', 'IupDrawEnd', 'IupDrawGetSize', 'IupDrawGetTextSize', 'IupDrawLine', 'IupDrawRectangle', 'IupDrawText', 'IupExpander', 'IupFill', 'IupFlatLabel', 'IupFlatList', 'IupFlatTree', 'IupFlush', 'IupFrame', 'IupGetAttribute', 'IupGetAttributeId', 'IupGetAttributePtr', 'IupGetBrother', 'IupGetChild', 'IupGetChildCount', 'IupGetClassName', 'IupGetDialog', 'IupGetDialogChild', 'IupGetDouble', 'IupGetFocus', 'IupGetGlobal', 'IupGetGlobalInt', 'IupGetGlobalIntInt', 'IupGetInt', 'IupGetInt2', 'IupGetIntId', 'IupGetIntInt', 'IupGetParent', 'IupGLCanvas', 'IupGLCanvasOpen', 'IupGLMakeCurrent', 'IupGraph', 'IupHbox', 'IupHide', 'IupImage', 'IupImageRGBA', 'IupItem', 'iupKeyCodeToName', 'IupLabel', 'IupLink', 'IupList', 'IupMap', 'IupMenu', 'IupMenuItem', 'IupMessage', 'IupMessageDlg', 'IupMultiBox', 'IupMultiLine', 'IupNextField', 'IupNormaliser', 'IupOpen', 'IupPlayInput', 'IupPopup', 'IupPreviousField', 'IupProgressBar', 'IupRadio', 'IupRecordInput', 'IupRedraw', 'IupRefresh', 'IupRefreshChildren', 'IupSeparator', 'IupSetAttribute', 'IupSetAttributes', 'IupSetAttributeHandle', 'IupSetAttributeId', 'IupSetAttributePtr', 'IupSetCallback', 'IupSetCallbacks', 'IupSetDouble', 'IupSetFocus', 'IupSetGlobal', 'IupSetGlobalInt', 'IupSetGlobalFunction', 'IupSetHandle', 'IupSetInt', 'IupSetStrAttribute', 'IupSetStrGlobal', 'IupShow', 'IupShowXY', 'IupSplit', 'IupStoreAttribute', 'IupSubmenu', 'IupTable', 'IupTableClearSelected', 'IupTableClick_cb', 'IupTableGetSelected', 'IupTableResize_cb', 'IupTableSetData', 'IupTabs', 'IupText', 'IupTimer', 'IupToggle', 'IupTreeAddNodes', 'IupTreeView', 'IupUpdate', 'IupValuator', 'IupVbox', 'join', 'join_by', 'join_path', 'k_perm', 'largest', 'lcm', 'length', 'log', 'log10', 'log2', 'lower', 'm4_crossProduct', 'm4_inverse', 'm4_lookAt', 'm4_multiply', 'm4_normalize', 'm4_perspective', 'm4_subtractVectors', 'm4_xRotate', 'm4_yRotate', 'machine_bits', 'machine_word', 'match', 'match_all', 'match_replace', 'max', 'maxsq', 'min', 'minsq', 'mod', 'mpfr_add', 'mpfr_ceil', 'mpfr_cmp', 'mpfr_cmp_si', 'mpfr_const_pi', 'mpfr_div', 'mpfr_div_si', 'mpfr_div_z', 'mpfr_floor', 'mpfr_free', 'mpfr_get_d', 'mpfr_get_default_precision', 'mpfr_get_default_rounding_mode', 'mpfr_get_fixed', 'mpfr_get_precision', 'mpfr_get_si', 'mpfr_init', 'mpfr_inits', 'mpfr_init_set', 'mpfr_init_set_q', 'mpfr_init_set_z', 'mpfr_mul', 'mpfr_mul_si', 'mpfr_pow_si', 'mpfr_set', 'mpfr_set_d', 'mpfr_set_default_precision', 'mpfr_set_default_rounding_mode', 'mpfr_set_precision', 'mpfr_set_q', 'mpfr_set_si', 'mpfr_set_str', 'mpfr_set_z', 'mpfr_si_div', 'mpfr_si_sub', 'mpfr_sqrt', 'mpfr_sub', 'mpfr_sub_si', 'mpq_abs', 'mpq_add', 'mpq_add_si', 'mpq_canonicalize', 'mpq_cmp', 'mpq_cmp_si', 'mpq_div', 'mpq_div_2exp', 'mpq_free', 'mpq_get_den', 'mpq_get_num', 'mpq_get_str', 'mpq_init', 'mpq_init_set', 'mpq_init_set_si', 'mpq_init_set_str', 'mpq_init_set_z', 'mpq_inits', 'mpq_inv', 'mpq_mul', 'mpq_neg', 'mpq_set', 'mpq_set_si', 'mpq_set_str', 'mpq_set_z', 'mpq_sub', 'mpz_abs', 'mpz_add', 'mpz_addmul', 'mpz_addmul_ui', 'mpz_addmul_si', 'mpz_add_si', 'mpz_add_ui', 'mpz_and', 'mpz_bin_uiui', 'mpz_cdiv_q', 'mpz_cmp', 'mpz_cmp_si', 'mpz_divexact', 'mpz_divexact_ui', 'mpz_divisible_p', 'mpz_divisible_ui_p', 'mpz_even', 'mpz_fac_ui', 'mpz_factorstring', 'mpz_fdiv_q', 'mpz_fdiv_q_2exp', 'mpz_fdiv_q_ui', 'mpz_fdiv_qr', 'mpz_fdiv_r', 'mpz_fdiv_ui', 'mpz_fib_ui', 'mpz_fib2_ui', 'mpz_fits_atom', 'mpz_fits_integer', 'mpz_free', 'mpz_gcd', 'mpz_gcd_ui', 'mpz_get_atom', 'mpz_get_integer', 'mpz_get_short_str', 'mpz_get_str', 'mpz_init', 'mpz_init_set', 'mpz_inits', 'mpz_invert', 'mpz_lcm', 'mpz_lcm_ui', 'mpz_max', 'mpz_min', 'mpz_mod', 'mpz_mod_ui', 'mpz_mul', 'mpz_mul_2exp', 'mpz_mul_d', 'mpz_mul_si', 'mpz_neg', 'mpz_nthroot', 'mpz_odd', 'mpz_pollard_rho', 'mpz_pow_ui', 'mpz_powm', 'mpz_powm_ui', 'mpz_prime', 'mpz_prime_factors', 'mpz_prime_mr', 'mpz_rand', 'mpz_rand_ui', 'mpz_re_compose', 'mpz_remove', 'mpz_scan0', 'mpz_scan1', 'mpz_set', 'mpz_set_d', 'mpz_set_si', 'mpz_set_str', 'mpz_set_v', 'mpz_sign', 'mpz_sizeinbase', 'mpz_sqrt', 'mpz_sub', 'mpz_sub_si', 'mpz_sub_ui', 'mpz_si_sub', 'mpz_tdiv_q_2exp', 'mpz_tdiv_r_2exp', 'mpz_tstbit', 'mpz_ui_pow_ui', 'mpz_xor', 'named_dict', 'new_dict', 'new_queue', 'new_stack', 'not_bits', 'not_bitsu', 'odd', 'or_all', 'or_allu', 'or_bits', 'or_bitsu', 'ord', 'ordinal', 'ordinant', 'override_timezone', 'pad', 'pad_head', 'pad_tail', 'parse_date_string', 'papply', 'peep', 'peepn', 'peep_dict', 'permute', 'permutes', 'platform', 'pop', 'popn', 'pop_dict', 'power', 'pp', 'ppEx', 'ppExf', 'ppf', 'ppOpt', 'pq_add', 'pq_destroy', 'pq_empty', 'pq_new', 'pq_peek', 'pq_pop', 'pq_pop_data', 'pq_size', 'prepend', 'prime_factors', 'printf', 'product', 'proper', 'push', 'pushn', 'putd', 'puts', 'queue_empty', 'queue_size', 'rand', 'rand_range', 'reinstate', 'remainder', 'remove', 'remove_all', 'repeat', 'repeatch', 'replace', 'requires', 'reverse', 'rfind', 'rgb', 'rmatch', 'rmdr', 'rnd', 'round', 'routine_id', 'scanf', 'serialize', 'series', 'set_rand', 'set_test_abort', 'set_test_logfile', 'set_test_module', 'set_test_pause', 'set_test_verbosity', 'set_timedate_formats', 'set_timezone', 'setd', 'setd_default', 'shorten', 'sha256', 'shift_bits', 'shuffle', 'sign', 'sin', 'smallest', 'sort', 'sort_columns', 'speak', 'splice', 'split', 'split_any', 'split_by', 'sprint', 'sprintf', 'sq_abs', 'sq_add', 'sq_and', 'sq_and_bits', 'sq_arccos', 'sq_arcsin', 'sq_arctan', 'sq_atom', 'sq_ceil', 'sq_cmp', 'sq_cos', 'sq_div', 'sq_even', 'sq_eq', 'sq_floor', 'sq_floor_div', 'sq_ge', 'sq_gt', 'sq_int', 'sq_le', 'sq_log', 'sq_log10', 'sq_log2', 'sq_lt', 'sq_max', 'sq_min', 'sq_mod', 'sq_mul', 'sq_ne', 'sq_not', 'sq_not_bits', 'sq_odd', 'sq_or', 'sq_or_bits', 'sq_power', 'sq_rand', 'sq_remainder', 'sq_rmdr', 'sq_rnd', 'sq_round', 'sq_seq', 'sq_sign', 'sq_sin', 'sq_sqrt', 'sq_str', 'sq_sub', 'sq_tan', 'sq_trunc', 'sq_uminus', 'sq_xor', 'sq_xor_bits', 'sqrt', 'square_free', 'stack_empty', 'stack_size', 'substitute', 'substitute_all', 'sum', 'tail', 'tan', 'test_equal', 'test_fail', 'test_false', 'test_not_equal', 'test_pass', 'test_summary', 'test_true', 'text_color', 'throw', 'time', 'timedate_diff', 'timedelta', 'to_integer', 'to_number', 'to_rgb', 'to_string', 'traverse_dict', 'traverse_dict_partial_key', 'trim', 'trim_head', 'trim_tail', 'trunc', 'tagset', 'tagstart', 'typeof', 'unique', 'unix_dict', 'upper', 'utf8_to_utf32', 'utf32_to_utf8', 'version', 'vlookup', 'vslice', 'wglGetProcAddress', 'wildcard_file', 'wildcard_match', 'with_rho', 'with_theta', 'xml_new_doc', 'xml_new_element', 'xml_set_attribute', 'xml_sprint', 'xor_bits', 'xor_bitsu', 'accept', 'allocate', 'allocate_string', 'allow_break', 'ARM', 'atom_to_float80', 'c_func', 'c_proc', 'call_back', 'chdir', 'check_break', 'clearDib', 'close', 'closesocket', 'console', 'copy_file', 'create', 'create_directory', 'create_thread', 'curl_easy_cleanup', 'curl_easy_get_file', 'curl_easy_init', 'curl_easy_perform', 'curl_easy_perform_ex', 'curl_easy_setopt', 'curl_easy_strerror', 'curl_global_cleanup', 'curl_global_init', 'curl_slist_append', 'curl_slist_free_all', 'current_dir', 'cursor', 'define_c_func', 'define_c_proc', 'delete', 'delete_cs', 'delete_file', 'dir', 'DLL', 'drawDib', 'drawShadedPolygonToDib', 'ELF32', 'ELF64', 'enter_cs', 'eval', 'exit_thread', 'free', 'file_exists', 'final', 'float80_to_atom', 'format', 'get_bytes', 'get_file_date', 'get_file_size', 'get_file_type', 'get_interpreter', 'get_key', 'get_socket_error', 'get_text', 'get_thread_exitcode', 'get_thread_id', 'getc', 'getenv', 'gets', 'getsockaddr', 'glBegin', 'glCallList', 'glFrustum', 'glGenLists', 'glGetString', 'glLight', 'glMaterial', 'glNewList', 'glNormal', 'glPopMatrix', 'glPushMatrix', 'glRotate', 'glEnd', 'glEndList', 'glTexImage2D', 'goto', 'GUI', 'icons', 'ilASM', 'include_files', 'include_paths', 'init_cs', 'ip_to_string', 'IupConfig', 'IupConfigDialogClosed', 'IupConfigDialogShow', 'IupConfigGetVariableInt', 'IupConfigLoad', 'IupConfigSave', 'IupConfigSetVariableInt', 'IupExitLoop', 'IupFileDlg', 'IupFileList', 'IupGLSwapBuffers', 'IupHelp', 'IupLoopStep', 'IupMainLoop', 'IupNormalizer', 'IupPlot', 'IupPlotAdd', 'IupPlotBegin', 'IupPlotEnd', 'IupPlotInsert', 'IupSaveImage', 'IupTreeGetUserId', 'IupUser', 'IupVersion', 'IupVersionDate', 'IupVersionNumber', 'IupVersionShow', 'killDib', 'leave_cs', 'listen', 'manifest', 'mem_copy', 'mem_set', 'mpfr_gamma', 'mpfr_printf', 'mpfr_sprintf', 'mpz_export', 'mpz_import', 'namespace', 'new', 'newDib', 'open', 'open_dll', 'PE32', 'PE64', 'peek', 'peek_string', 'peek1s', 'peek1u', 'peek2s', 'peek2u', 'peek4s', 'peek4u', 'peek8s', 'peek8u', 'peekNS', 'peekns', 'peeknu', 'poke', 'poke2', 'poke4', 'poke8', 'pokeN', 'poke_string', 'poke_wstring', 'position', 'progress', 'prompt_number', 'prompt_string', 'read_file', 'read_lines', 'recv', 'resume_thread', 'seek', 'select', 'send', 'setHandler', 'shutdown', 'sleep', 'SO', 'sockaddr_in', 'socket', 'split_path', 'suspend_thread', 'system', 'system_exec', 'system_open', 'system_wait', 'task_clock_start', 'task_clock_stop', 'task_create', 'task_delay', 'task_list', 'task_schedule', 'task_self', 'task_status', 'task_suspend', 'task_yield', 'thread_safe_string', 'try_cs', 'utf8_to_utf16', 'utf16_to_utf8', 'utf16_to_utf32', 'utf32_to_utf16', 'video_config', 'WSACleanup', 'wait_thread', 'walk_dir', 'where', 'write_lines', 'wait_key' ) constants = ( 'ANY_QUEUE', 'ASCENDING', 'BLACK', 'BLOCK_CURSOR', 'BLUE', 'BRIGHT_CYAN', 'BRIGHT_BLUE', 'BRIGHT_GREEN', 'BRIGHT_MAGENTA', 'BRIGHT_RED', 'BRIGHT_WHITE', 'BROWN', 'C_DWORD', 'C_INT', 'C_POINTER', 'C_USHORT', 'C_WORD', 'CD_AMBER', 'CD_BLACK', 'CD_BLUE', 'CD_BOLD', 'CD_BOLD_ITALIC', 'CD_BOX', 'CD_CENTER', 'CD_CIRCLE', 'CD_CLOSED_LINES', 'CD_CONTINUOUS', 'CD_CUSTOM', 'CD_CYAN', 'CD_DARK_BLUE', 'CD_DARK_CYAN', 'CD_DARK_GRAY', 'CD_DARK_GREY', 'CD_DARK_GREEN', 'CD_DARK_MAGENTA', 'CD_DARK_RED', 'CD_DARK_YELLOW', 'CD_DASH_DOT', 'CD_DASH_DOT_DOT', 'CD_DASHED', 'CD_DBUFFER', 'CD_DEG2RAD', 'CD_DIAMOND', 'CD_DOTTED', 'CD_EAST', 'CD_EVENODD', 'CD_FILL', 'CD_GL', 'CD_GRAY', 'CD_GREY', 'CD_GREEN', 'CD_HATCH', 'CD_HOLLOW', 'CD_HOLLOW_BOX', 'CD_HOLLOW_CIRCLE', 'CD_HOLLOW_DIAMOND', 'CD_INDIGO', 'CD_ITALIC', 'CD_IUP', 'CD_IUPDBUFFER', 'CD_LIGHT_BLUE', 'CD_LIGHT_GRAY', 'CD_LIGHT_GREY', 'CD_LIGHT_GREEN', 'CD_LIGHT_PARCHMENT', 'CD_MAGENTA', 'CD_NAVY', 'CD_NORTH', 'CD_NORTH_EAST', 'CD_NORTH_WEST', 'CD_OLIVE', 'CD_OPEN_LINES', 'CD_ORANGE', 'CD_PARCHMENT', 'CD_PATTERN', 'CD_PRINTER', 'CD_PURPLE', 'CD_PLAIN', 'CD_PLUS', 'CD_QUERY', 'CD_RAD2DEG', 'CD_RED', 'CD_SILVER', 'CD_SOLID', 'CD_SOUTH_EAST', 'CD_SOUTH_WEST', 'CD_STAR', 'CD_STIPPLE', 'CD_STRIKEOUT', 'CD_UNDERLINE', 'CD_WEST', 'CD_WHITE', 'CD_WINDING', 'CD_VIOLET', 'CD_X', 'CD_YELLOW', 'CURLE_OK', 'CURLOPT_MAIL_FROM', 'CURLOPT_MAIL_RCPT', 'CURLOPT_PASSWORD', 'CURLOPT_READDATA', 'CURLOPT_READFUNCTION', 'CURLOPT_SSL_VERIFYPEER', 'CURLOPT_SSL_VERIFYHOST', 'CURLOPT_UPLOAD', 'CURLOPT_URL', 'CURLOPT_USE_SSL', 'CURLOPT_USERNAME', 'CURLOPT_VERBOSE', 'CURLOPT_WRITEFUNCTION', 'CURLUSESSL_ALL', 'CYAN', 'D_NAME', 'D_ATTRIBUTES', 'D_SIZE', 'D_YEAR', 'D_MONTH', 'D_DAY', 'D_HOUR', 'D_MINUTE', 'D_SECOND', 'D_CREATION', 'D_LASTACCESS', 'D_MODIFICATION', 'DT_YEAR', 'DT_MONTH', 'DT_DAY', 'DT_HOUR', 'DT_MINUTE', 'DT_SECOND', 'DT_DOW', 'DT_MSEC', 'DT_DOY', 'DT_GMT', 'EULER', 'E_CODE', 'E_ADDR', 'E_LINE', 'E_RTN', 'E_NAME', 'E_FILE', 'E_PATH', 'E_USER', 'false', 'False', 'FALSE', 'FIFO_QUEUE', 'FILETYPE_DIRECTORY', 'FILETYPE_FILE', 'GET_EOF', 'GET_FAIL', 'GET_IGNORE', 'GET_SUCCESS', 'GL_AMBIENT_AND_DIFFUSE', 'GL_ARRAY_BUFFER', 'GL_CLAMP', 'GL_CLAMP_TO_BORDER', 'GL_CLAMP_TO_EDGE', 'GL_COLOR_BUFFER_BIT', 'GL_COMPILE', 'GL_COMPILE_STATUS', 'GL_CULL_FACE', 'GL_DEPTH_BUFFER_BIT', 'GL_DEPTH_TEST', 'GL_EXTENSIONS', 'GL_FLAT', 'GL_FLOAT', 'GL_FRAGMENT_SHADER', 'GL_FRONT', 'GL_LIGHT0', 'GL_LIGHTING', 'GL_LINEAR', 'GL_LINK_STATUS', 'GL_MODELVIEW', 'GL_NEAREST', 'GL_NO_ERROR', 'GL_NORMALIZE', 'GL_POSITION', 'GL_PROJECTION', 'GL_QUAD_STRIP', 'GL_QUADS', 'GL_RENDERER', 'GL_REPEAT', 'GL_RGB', 'GL_RGBA', 'GL_SMOOTH', 'GL_STATIC_DRAW', 'GL_TEXTURE_2D', 'GL_TEXTURE_MAG_FILTER', 'GL_TEXTURE_MIN_FILTER', 'GL_TEXTURE_WRAP_S', 'GL_TEXTURE_WRAP_T', 'GL_TRIANGLES', 'GL_UNSIGNED_BYTE', 'GL_VENDOR', 'GL_VERSION', 'GL_VERTEX_SHADER', 'GRAY', 'GREEN', 'GT_LF_STRIPPED', 'GT_WHOLE_FILE', 'INVLN10', 'IUP_CLOSE', 'IUP_CONTINUE', 'IUP_DEFAULT', 'IUP_BLACK', 'IUP_BLUE', 'IUP_BUTTON1', 'IUP_BUTTON3', 'IUP_CENTER', 'IUP_CYAN', 'IUP_DARK_BLUE', 'IUP_DARK_CYAN', 'IUP_DARK_GRAY', 'IUP_DARK_GREY', 'IUP_DARK_GREEN', 'IUP_DARK_MAGENTA', 'IUP_DARK_RED', 'IUP_GRAY', 'IUP_GREY', 'IUP_GREEN', 'IUP_IGNORE', 'IUP_INDIGO', 'IUP_MAGENTA', 'IUP_MASK_INT', 'IUP_MASK_UINT', 'IUP_MOUSEPOS', 'IUP_NAVY', 'IUP_OLIVE', 'IUP_RECTEXT', 'IUP_RED', 'IUP_LIGHT_BLUE', 'IUP_LIGHT_GRAY', 'IUP_LIGHT_GREY', 'IUP_LIGHT_GREEN', 'IUP_ORANGE', 'IUP_PARCHMENT', 'IUP_PURPLE', 'IUP_SILVER', 'IUP_TEAL', 'IUP_VIOLET', 'IUP_WHITE', 'IUP_YELLOW', 'K_BS', 'K_cA', 'K_cC', 'K_cD', 'K_cF5', 'K_cK', 'K_cM', 'K_cN', 'K_cO', 'K_cP', 'K_cR', 'K_cS', 'K_cT', 'K_cW', 'K_CR', 'K_DEL', 'K_DOWN', 'K_END', 'K_ESC', 'K_F1', 'K_F2', 'K_F3', 'K_F4', 'K_F5', 'K_F6', 'K_F7', 'K_F8', 'K_F9', 'K_F10', 'K_F11', 'K_F12', 'K_HOME', 'K_INS', 'K_LEFT', 'K_MIDDLE', 'K_PGDN', 'K_PGUP', 'K_RIGHT', 'K_SP', 'K_TAB', 'K_UP', 'K_h', 'K_i', 'K_j', 'K_p', 'K_r', 'K_s', 'JS', 'LIFO_QUEUE', 'LINUX', 'MAX_HEAP', 'MAGENTA', 'MIN_HEAP', 'Nan', 'NO_CURSOR', 'null', 'NULL', 'PI', 'pp_Ascii', 'pp_Brkt', 'pp_Date', 'pp_File', 'pp_FltFmt', 'pp_Indent', 'pp_IntCh', 'pp_IntFmt', 'pp_Maxlen', 'pp_Nest', 'pp_Pause', 'pp_Q22', 'pp_StrFmt', 'RED', 'SEEK_OK', 'SLASH', 'TEST_ABORT', 'TEST_CRASH', 'TEST_PAUSE', 'TEST_PAUSE_FAIL', 'TEST_QUIET', 'TEST_SHOW_ALL', 'TEST_SHOW_FAILED', 'TEST_SUMMARY', 'true', 'True', 'TRUE', 'VC_SCRNLINES', 'WHITE', 'WINDOWS', 'YELLOW' )
tokens = { 'root': [ (r"\s+", Whitespace), (r'/\*|--/\*|#\[', Comment.Multiline, 'comment'), (r'(?://|--|#!).*$', Comment.Single),#Alt:# (r'//.*$|--.*$|#!.*$', Comment.Single), (r'"([^"\\]|\\.)*"', String.Other), (r'\'[^\']*\'', String.Other), (r'`[^`]*`', String.Other),
(words(types, prefix=r'\b', suffix=r'\b'), Name.Function), (words(routines, prefix=r'\b', suffix=r'\b'), Name.Function), (words(preproc, prefix=r'\b', suffix=r'\b'), Keyword.Declaration), (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword.Declaration), (words(constants, prefix=r'\b', suffix=r'\b'), Name.Constant), # Aside: Phix only supports/uses the ascii/non-unicode tilde (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|\.(){},?:\[\]$\\;#]', Operator), (r'[\w-]+', Text) ], 'comment': [ (r'[^*/#]+', Comment.Multiline), (r'/\*|#\[', Comment.Multiline, '#push'), (r'\*/|#\]', Comment.Multiline, '#pop'), (r'[*/#]', Comment.Multiline) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335""" pygments.lexers.php ~~~~~~~~~~~~~~~~~~~
Lexers for PHP and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, default, \ using, this, words, do_insertions, line_refrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Other, Genericfrom pygments.util import get_bool_opt, get_list_opt, shebang_matches
__all__ = ['ZephirLexer', 'PsyshConsoleLexer', 'PhpLexer']
class ZephirLexer(RegexLexer): """ For Zephir language source code.
Zephir is a compiled high level language aimed to the creation of C-extensions for PHP. """
name = 'Zephir' url = 'http://zephir-lang.com/' aliases = ['zephir'] filenames = ['*.zep'] version_added = '2.0'
zephir_keywords = ['fetch', 'echo', 'isset', 'empty'] zephir_type = ['bit', 'bits', 'string']
flags = re.DOTALL | re.MULTILINE
tokens = { 'commentsandwhitespace': [ (r'\s+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gim]+\b|\B)', String.Regex, '#pop'), (r'/', Operator, '#pop'), default('#pop') ], 'badregex': [ (r'\n', Text, '#pop') ], 'root': [ (r'^(?=\s|/)', Text, 'slashstartsregex'), include('commentsandwhitespace'), (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|' r'(<<|>>>?|==?|!=?|->|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (r'(for|in|while|do|break|return|continue|switch|case|default|if|else|loop|' r'require|inline|throw|try|catch|finally|new|delete|typeof|instanceof|void|' r'namespace|use|extends|this|fetch|isset|unset|echo|fetch|likely|unlikely|' r'empty)\b', Keyword, 'slashstartsregex'), (r'(var|let|with|function)\b', Keyword.Declaration, 'slashstartsregex'), (r'(abstract|boolean|bool|char|class|const|double|enum|export|extends|final|' r'native|goto|implements|import|int|string|interface|long|ulong|char|uchar|' r'float|unsigned|private|protected|public|short|static|self|throws|reverse|' r'transient|volatile|readonly)\b', Keyword.Reserved), (r'(true|false|null|undefined)\b', Keyword.Constant), (r'(Array|Boolean|Date|_REQUEST|_COOKIE|_SESSION|' r'_GET|_POST|_SERVER|this|stdClass|range|count|iterator|' r'window)\b', Name.Builtin), (r'[$a-zA-Z_][\w\\]*', Name.Other), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ] }
class PsyshConsoleLexer(Lexer): """ For PsySH console output, such as:
.. sourcecode:: psysh
>>> $greeting = function($name): string { ... return "Hello, {$name}"; ... }; => Closure($name): string {#2371 …3} >>> $greeting('World') => "Hello, World" """ name = 'PsySH console session for PHP' url = 'https://psysh.org/' aliases = ['psysh'] version_added = '2.7'
def __init__(self, **options): options['startinline'] = True Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): phplexer = PhpLexer(**self.options) curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() if line.startswith('>>> ') or line.startswith('... '): insertions.append((len(curcode), [(0, Generic.Prompt, line[:4])])) curcode += line[4:] elif line.rstrip() == '...': insertions.append((len(curcode), [(0, Generic.Prompt, '...')])) curcode += line[3:] else: if curcode: yield from do_insertions( insertions, phplexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, phplexer.get_tokens_unprocessed(curcode))
class PhpLexer(RegexLexer): """ For PHP source code. For PHP embedded in HTML, use the `HtmlPhpLexer`.
Additional options accepted:
`startinline` If given and ``True`` the lexer starts highlighting with php code (i.e.: no starting ``<?php`` required). The default is ``False``. `funcnamehighlighting` If given and ``True``, highlight builtin function names (default: ``True``). `disabledmodules` If given, must be a list of module names whose function names should not be highlighted. By default all modules are highlighted except the special ``'unknown'`` module that includes functions that are known to php but are undocumented.
To get a list of allowed modules have a look into the `_php_builtins` module:
.. sourcecode:: pycon
>>> from pygments.lexers._php_builtins import MODULES >>> MODULES.keys() ['PHP Options/Info', 'Zip', 'dba', ...]
In fact the names of those modules match the module names from the php documentation. """
name = 'PHP' url = 'https://www.php.net/' aliases = ['php', 'php3', 'php4', 'php5'] filenames = ['*.php', '*.php[345]', '*.inc'] mimetypes = ['text/x-php'] version_added = ''
# Note that a backslash is included, PHP uses a backslash as a namespace # separator. _ident_inner = r'(?:[\\_a-z]|[^\x00-\x7f])(?:[\\\w]|[^\x00-\x7f])*' # But not inside strings. _ident_nons = r'(?:[_a-z]|[^\x00-\x7f])(?:\w|[^\x00-\x7f])*'
flags = re.IGNORECASE | re.DOTALL | re.MULTILINE tokens = { 'root': [ (r'<\?(php)?', Comment.Preproc, 'php'), (r'[^<]+', Other), (r'<', Other) ], 'php': [ (r'\?>', Comment.Preproc, '#pop'), (r'(<<<)([\'"]?)(' + _ident_nons + r')(\2\n.*?\n\s*)(\3)(;?)(\n)', bygroups(String, String, String.Delimiter, String, String.Delimiter, Punctuation, Text)), (r'\s+', Text), (r'#\[', Punctuation, 'attribute'), (r'#.*?\n', Comment.Single), (r'//.*?\n', Comment.Single), # put the empty comment here, it is otherwise seen as # the start of a docstring (r'/\*\*/', Comment.Multiline), (r'/\*\*.*?\*/', String.Doc), (r'/\*.*?\*/', Comment.Multiline), (r'(->|::)(\s*)(' + _ident_nons + ')', bygroups(Operator, Text, Name.Attribute)), (r'[~!%^&*+=|:.<>/@-]+', Operator), (r'\?', Operator), # don't add to the charclass above! (r'[\[\]{}();,]+', Punctuation), (r'(new)(\s+)(class)\b', bygroups(Keyword, Text, Keyword)), (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'), (r'(function)(\s*)(?=\()', bygroups(Keyword, Text)), (r'(function)(\s+)(&?)(\s*)', bygroups(Keyword, Text, Operator, Text), 'functionname'), (r'(const)(\s+)(' + _ident_inner + ')', bygroups(Keyword, Text, Name.Constant)), # source: https://www.php.net/manual/en/reserved.keywords.php (r'(and|E_PARSE|old_function|E_ERROR|or|as|E_WARNING|parent|' r'eval|PHP_OS|break|exit|case|extends|PHP_VERSION|cfunction|' r'FALSE|print|for|require|continue|foreach|require_once|' r'declare|return|default|static|do|switch|die|stdClass|' r'echo|else|TRUE|elseif|var|empty|if|xor|enddeclare|include|' r'virtual|endfor|include_once|while|endforeach|global|' r'endif|list|endswitch|new|endwhile|not|' r'array|E_ALL|NULL|final|php_user_filter|interface|' r'implements|public|private|protected|abstract|clone|try|' r'catch|throw|this|use|namespace|trait|yield( from)?|' r'finally|match|readonly)\b', Keyword), (r'(true|false|null)\b', Keyword.Constant), include('magicconstants'), (r'\$\{', Name.Variable, 'variablevariable'), (r'\$+' + _ident_inner, Name.Variable), (_ident_inner, Name.Other), (r'(\d+\.\d*|\d*\.\d+)(e[+-]?[0-9]+)?', Number.Float), (r'\d+e[+-]?[0-9]+', Number.Float), (r'0[0-7]+', Number.Oct), (r'0x[a-f0-9]+', Number.Hex), (r'\d+', Number.Integer), (r'0b[01]+', Number.Bin), (r"'([^'\\]*(?:\\.[^'\\]*)*)'", String.Single), (r'`([^`\\]*(?:\\.[^`\\]*)*)`', String.Backtick), (r'"', String.Double, 'string'), ], 'variablevariable': [ (r'\}', Name.Variable, '#pop'), include('php') ], 'magicfuncs': [ # source: http://php.net/manual/en/language.oop5.magic.php (words(( '__construct', '__destruct', '__call', '__callStatic', '__get', '__set', '__isset', '__unset', '__sleep', '__wakeup', '__toString', '__invoke', '__set_state', '__clone', '__debugInfo',), suffix=r'\b'), Name.Function.Magic), ], 'magicconstants': [ # source: https://www.php.net/manual/en/language.constants.magic.php (words(( '__LINE__', '__FILE__', '__DIR__', '__FUNCTION__', '__CLASS__', '__TRAIT__', '__METHOD__', '__NAMESPACE__', '__PROPERTY__',), suffix=r'\b'), Name.Constant), ], 'classname': [ (_ident_inner, Name.Class, '#pop') ], 'functionname': [ include('magicfuncs'), (_ident_inner, Name.Function, '#pop'), default('#pop') ], 'string': [ (r'"', String.Double, '#pop'), (r'[^{$"\\]+', String.Double), (r'\\([nrt"$\\]|[0-7]{1,3}|x[0-9a-f]{1,2})', String.Escape), (r'\$' + _ident_nons + r'(\[\S+?\]|->' + _ident_nons + ')?', String.Interpol), (r'(\{\$\{)(.*?)(\}\})', bygroups(String.Interpol, using(this, _startinline=True), String.Interpol)), (r'(\{)(\$.*?)(\})', bygroups(String.Interpol, using(this, _startinline=True), String.Interpol)), (r'(\$\{)(\S+)(\})', bygroups(String.Interpol, Name.Variable, String.Interpol)), (r'[${\\]', String.Double) ], 'attribute': [ (r'\]', Punctuation, '#pop'), (r'\(', Punctuation, 'attributeparams'), (_ident_inner, Name.Decorator), include('php') ], 'attributeparams': [ (r'\)', Punctuation, '#pop'), include('php') ], }
def __init__(self, **options): self.funcnamehighlighting = get_bool_opt( options, 'funcnamehighlighting', True) self.disabledmodules = get_list_opt( options, 'disabledmodules', ['unknown']) self.startinline = get_bool_opt(options, 'startinline', False)
# private option argument for the lexer itself if '_startinline' in options: self.startinline = options.pop('_startinline')
# collect activated functions in a set self._functions = set() if self.funcnamehighlighting: from pygments.lexers._php_builtins import MODULES for key, value in MODULES.items(): if key not in self.disabledmodules: self._functions.update(value) RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): stack = ['root'] if self.startinline: stack.append('php') for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text, stack): if token is Name.Other: if value in self._functions: yield index, Name.Builtin, value continue yield index, token, value
def analyse_text(text): if shebang_matches(text, r'php'): return True rv = 0.0 if re.search(r'<\?(?!xml)', text): rv += 0.3 return rv12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970""" pygments.lexers.pointless ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Pointless.
: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, Error, Keyword, Name, Number, Operator, \ Punctuation, String, Text
__all__ = ['PointlessLexer']
class PointlessLexer(RegexLexer): """ For Pointless source code. """
name = 'Pointless' url = 'https://ptls.dev' aliases = ['pointless'] filenames = ['*.ptls'] version_added = '2.7'
ops = words([ "+", "-", "*", "/", "**", "%", "+=", "-=", "*=", "/=", "**=", "%=", "|>", "=", "==", "!=", "<", ">", "<=", ">=", "=>", "$", "++", ])
keywords = words([ "if", "then", "else", "where", "with", "cond", "case", "and", "or", "not", "in", "as", "for", "requires", "throw", "try", "catch", "when", "yield", "upval", ], suffix=r'\b')
tokens = { 'root': [ (r'[ \n\r]+', Text), (r'--.*$', Comment.Single), (r'"""', String, 'multiString'), (r'"', String, 'string'), (r'[\[\](){}:;,.]', Punctuation), (ops, Operator), (keywords, Keyword), (r'\d+|\d*\.\d+', Number), (r'(true|false)\b', Name.Builtin), (r'[A-Z][a-zA-Z0-9]*\b', String.Symbol), (r'output\b', Name.Variable.Magic), (r'(export|import)\b', Keyword.Namespace), (r'[a-z][a-zA-Z0-9]*\b', Name.Variable) ], 'multiString': [ (r'\\.', String.Escape), (r'"""', String, '#pop'), (r'"', String), (r'[^\\"]+', String), ], 'string': [ (r'\\.', String.Escape), (r'"', String, '#pop'), (r'\n', Error), (r'[^\\"]+', String), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293""" pygments.lexers.pony ~~~~~~~~~~~~~~~~~~~~
Lexers for Pony and related languages.
: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
__all__ = ['PonyLexer']
class PonyLexer(RegexLexer): """ For Pony source code. """
name = 'Pony' aliases = ['pony'] filenames = ['*.pony'] url = 'https://www.ponylang.io' version_added = '2.4'
_caps = r'(iso|trn|ref|val|box|tag)'
tokens = { 'root': [ (r'\n', Text), (r'[^\S\n]+', Text), (r'//.*\n', Comment.Single), (r'/\*', Comment.Multiline, 'nested_comment'), (r'"""(?:.|\n)*?"""', String.Doc), (r'"', String, 'string'), (r'\'.*\'', String.Char), (r'=>|[]{}:().~;,|&!^?[]', Punctuation), (words(( 'addressof', 'and', 'as', 'consume', 'digestof', 'is', 'isnt', 'not', 'or'), suffix=r'\b'), Operator.Word), (r'!=|==|<<|>>|[-+/*%=<>]', Operator), (words(( 'box', 'break', 'compile_error', 'compile_intrinsic', 'continue', 'do', 'else', 'elseif', 'embed', 'end', 'error', 'for', 'if', 'ifdef', 'in', 'iso', 'lambda', 'let', 'match', 'object', 'recover', 'ref', 'repeat', 'return', 'tag', 'then', 'this', 'trn', 'try', 'until', 'use', 'var', 'val', 'where', 'while', 'with', '#any', '#read', '#send', '#share'), suffix=r'\b'), Keyword), (r'(actor|class|struct|primitive|interface|trait|type)((?:\s)+)', bygroups(Keyword, Text), 'typename'), (r'(new|fun|be)((?:\s)+)', bygroups(Keyword, Text), 'methodname'), (words(( 'I8', 'U8', 'I16', 'U16', 'I32', 'U32', 'I64', 'U64', 'I128', 'U128', 'ILong', 'ULong', 'ISize', 'USize', 'F32', 'F64', 'Bool', 'Pointer', 'None', 'Any', 'Array', 'String', 'Iterator'), suffix=r'\b'), Name.Builtin.Type), (r'_?[A-Z]\w*', Name.Type), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (r'(true|false)\b', Name.Builtin), (r'_\d*', Name), (r'_?[a-z][\w\']*', Name) ], 'typename': [ (_caps + r'?((?:\s)*)(_?[A-Z]\w*)', bygroups(Keyword, Text, Name.Class), '#pop') ], 'methodname': [ (_caps + r'?((?:\s)*)(_?[a-z]\w*)', bygroups(Keyword, Text, Name.Function), '#pop') ], 'nested_comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'string': [ (r'"', String, '#pop'), (r'\\"', String), (r'[^\\"]+', String) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303""" pygments.lexers.praat ~~~~~~~~~~~~~~~~~~~~~
Lexer for Praat
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, bygroups, includefrom pygments.token import Name, Text, Comment, Keyword, String, Punctuation, \ Number, Operator, Whitespace
__all__ = ['PraatLexer']
class PraatLexer(RegexLexer): """ For Praat scripts. """
name = 'Praat' url = 'http://www.praat.org' aliases = ['praat'] filenames = ['*.praat', '*.proc', '*.psc'] version_added = '2.1'
keywords = ( 'if', 'then', 'else', 'elsif', 'elif', 'endif', 'fi', 'for', 'from', 'to', 'endfor', 'endproc', 'while', 'endwhile', 'repeat', 'until', 'select', 'plus', 'minus', 'demo', 'assert', 'stopwatch', 'nocheck', 'nowarn', 'noprogress', 'editor', 'endeditor', 'clearinfo', )
functions_string = ( 'backslashTrigraphsToUnicode', 'chooseDirectory', 'chooseReadFile', 'chooseWriteFile', 'date', 'demoKey', 'do', 'environment', 'extractLine', 'extractWord', 'fixed', 'info', 'left', 'mid', 'percent', 'readFile', 'replace', 'replace_regex', 'right', 'selected', 'string', 'unicodeToBackslashTrigraphs', )
functions_numeric = ( 'abs', 'appendFile', 'appendFileLine', 'appendInfo', 'appendInfoLine', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'barkToHertz', 'beginPause', 'beginSendPraat', 'besselI', 'besselK', 'beta', 'beta2', 'binomialP', 'binomialQ', 'boolean', 'ceiling', 'chiSquareP', 'chiSquareQ', 'choice', 'comment', 'cos', 'cosh', 'createDirectory', 'deleteFile', 'demoClicked', 'demoClickedIn', 'demoCommandKeyPressed', 'demoExtraControlKeyPressed', 'demoInput', 'demoKeyPressed', 'demoOptionKeyPressed', 'demoShiftKeyPressed', 'demoShow', 'demoWaitForInput', 'demoWindowTitle', 'demoX', 'demoY', 'differenceLimensToPhon', 'do', 'editor', 'endPause', 'endSendPraat', 'endsWith', 'erb', 'erbToHertz', 'erf', 'erfc', 'exitScript', 'exp', 'extractNumber', 'fileReadable', 'fisherP', 'fisherQ', 'floor', 'gaussP', 'gaussQ', 'hertzToBark', 'hertzToErb', 'hertzToMel', 'hertzToSemitones', 'imax', 'imin', 'incompleteBeta', 'incompleteGammaP', 'index', 'index_regex', 'integer', 'invBinomialP', 'invBinomialQ', 'invChiSquareQ', 'invFisherQ', 'invGaussQ', 'invSigmoid', 'invStudentQ', 'length', 'ln', 'lnBeta', 'lnGamma', 'log10', 'log2', 'max', 'melToHertz', 'min', 'minusObject', 'natural', 'number', 'numberOfColumns', 'numberOfRows', 'numberOfSelected', 'objectsAreIdentical', 'option', 'optionMenu', 'pauseScript', 'phonToDifferenceLimens', 'plusObject', 'positive', 'randomBinomial', 'randomGauss', 'randomInteger', 'randomPoisson', 'randomUniform', 'real', 'readFile', 'removeObject', 'rindex', 'rindex_regex', 'round', 'runScript', 'runSystem', 'runSystem_nocheck', 'selectObject', 'selected', 'semitonesToHertz', 'sentence', 'sentencetext', 'sigmoid', 'sin', 'sinc', 'sincpi', 'sinh', 'soundPressureToPhon', 'sqrt', 'startsWith', 'studentP', 'studentQ', 'tan', 'tanh', 'text', 'variableExists', 'word', 'writeFile', 'writeFileLine', 'writeInfo', 'writeInfoLine', )
functions_array = ( 'linear', 'randomGauss', 'randomInteger', 'randomUniform', 'zero', )
objects = ( 'Activation', 'AffineTransform', 'AmplitudeTier', 'Art', 'Artword', 'Autosegment', 'BarkFilter', 'BarkSpectrogram', 'CCA', 'Categories', 'Cepstrogram', 'Cepstrum', 'Cepstrumc', 'ChebyshevSeries', 'ClassificationTable', 'Cochleagram', 'Collection', 'ComplexSpectrogram', 'Configuration', 'Confusion', 'ContingencyTable', 'Corpus', 'Correlation', 'Covariance', 'CrossCorrelationTable', 'CrossCorrelationTables', 'DTW', 'DataModeler', 'Diagonalizer', 'Discriminant', 'Dissimilarity', 'Distance', 'Distributions', 'DurationTier', 'EEG', 'ERP', 'ERPTier', 'EditCostsTable', 'EditDistanceTable', 'Eigen', 'Excitation', 'Excitations', 'ExperimentMFC', 'FFNet', 'FeatureWeights', 'FileInMemory', 'FilesInMemory', 'Formant', 'FormantFilter', 'FormantGrid', 'FormantModeler', 'FormantPoint', 'FormantTier', 'GaussianMixture', 'HMM', 'HMM_Observation', 'HMM_ObservationSequence', 'HMM_State', 'HMM_StateSequence', 'Harmonicity', 'ISpline', 'Index', 'Intensity', 'IntensityTier', 'IntervalTier', 'KNN', 'KlattGrid', 'KlattTable', 'LFCC', 'LPC', 'Label', 'LegendreSeries', 'LinearRegression', 'LogisticRegression', 'LongSound', 'Ltas', 'MFCC', 'MSpline', 'ManPages', 'Manipulation', 'Matrix', 'MelFilter', 'MelSpectrogram', 'MixingMatrix', 'Movie', 'Network', 'Object', 'OTGrammar', 'OTHistory', 'OTMulti', 'PCA', 'PairDistribution', 'ParamCurve', 'Pattern', 'Permutation', 'Photo', 'Pitch', 'PitchModeler', 'PitchTier', 'PointProcess', 'Polygon', 'Polynomial', 'PowerCepstrogram', 'PowerCepstrum', 'Procrustes', 'RealPoint', 'RealTier', 'ResultsMFC', 'Roots', 'SPINET', 'SSCP', 'SVD', 'Salience', 'ScalarProduct', 'Similarity', 'SimpleString', 'SortedSetOfString', 'Sound', 'Speaker', 'Spectrogram', 'Spectrum', 'SpectrumTier', 'SpeechSynthesizer', 'SpellingChecker', 'Strings', 'StringsIndex', 'Table', 'TableOfReal', 'TextGrid', 'TextInterval', 'TextPoint', 'TextTier', 'Tier', 'Transition', 'VocalTract', 'VocalTractTier', 'Weight', 'WordList', )
variables_numeric = ( 'macintosh', 'windows', 'unix', 'praatVersion', 'pi', 'e', 'undefined', )
variables_string = ( 'praatVersion', 'tab', 'shellDirectory', 'homeDirectory', 'preferencesDirectory', 'newline', 'temporaryDirectory', 'defaultDirectory', )
object_attributes = ( 'ncol', 'nrow', 'xmin', 'ymin', 'xmax', 'ymax', 'nx', 'ny', 'dx', 'dy', )
tokens = { 'root': [ (r'(\s+)(#.*?$)', bygroups(Whitespace, Comment.Single)), (r'^#.*?$', Comment.Single), (r';[^\n]*', Comment.Single), (r'\s+', Whitespace),
(r'\bprocedure\b', Keyword, 'procedure_definition'), (r'\bcall\b', Keyword, 'procedure_call'), (r'@', Name.Function, 'procedure_call'),
include('function_call'),
(words(keywords, suffix=r'\b'), Keyword),
(r'(\bform\b)(\s+)([^\n]+)', bygroups(Keyword, Whitespace, String), 'old_form'),
(r'(print(?:line|tab)?|echo|exit|asserterror|pause|send(?:praat|socket)|' r'include|execute|system(?:_nocheck)?)(\s+)', bygroups(Keyword, Whitespace), 'string_unquoted'),
(r'(goto|label)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Label)),
include('variable_name'), include('number'),
(r'"', String, 'string'),
(words((objects), suffix=r'(?=\s+\S+\n)'), Name.Class, 'string_unquoted'),
(r'\b[A-Z]', Keyword, 'command'), (r'(\.{3}|[)(,])', Punctuation), ], 'command': [ (r'( ?[\w()-]+ ?)', Keyword),
include('string_interpolated'),
(r'\.{3}', Keyword, ('#pop', 'old_arguments')), (r':', Keyword, ('#pop', 'comma_list')), (r'\s', Whitespace, '#pop'), ], 'procedure_call': [ (r'\s+', Whitespace), (r'([\w.]+)(?:(:)|(?:(\s*)(\()))', bygroups(Name.Function, Punctuation, Text.Whitespace, Punctuation), '#pop'), (r'([\w.]+)', Name.Function, ('#pop', 'old_arguments')), ], 'procedure_definition': [ (r'\s', Whitespace), (r'([\w.]+)(\s*?[(:])', bygroups(Name.Function, Whitespace), '#pop'), (r'([\w.]+)([^\n]*)', bygroups(Name.Function, Text), '#pop'), ], 'function_call': [ (words(functions_string, suffix=r'\$(?=\s*[:(])'), Name.Function, 'function'), (words(functions_array, suffix=r'#(?=\s*[:(])'), Name.Function, 'function'), (words(functions_numeric, suffix=r'(?=\s*[:(])'), Name.Function, 'function'), ], 'function': [ (r'\s+', Whitespace), (r':', Punctuation, ('#pop', 'comma_list')), (r'\s*\(', Punctuation, ('#pop', 'comma_list')), ], 'comma_list': [ (r'(\s*\n\s*)(\.{3})', bygroups(Whitespace, Punctuation)),
(r'(\s*)(?:([)\]])|(\n))', bygroups( Whitespace, Punctuation, Whitespace), '#pop'),
(r'\s+', Whitespace), (r'"', String, 'string'), (r'\b(if|then|else|fi|endif)\b', Keyword),
include('function_call'), include('variable_name'), include('operator'), include('number'),
(r'[()]', Text), (r',', Punctuation), ], 'old_arguments': [ (r'\n', Whitespace, '#pop'),
include('variable_name'), include('operator'), include('number'),
(r'"', String, 'string'), (r'[^\n]', Text), ], 'number': [ (r'\n', Whitespace, '#pop'), (r'\b\d+(\.\d*)?([eE][-+]?\d+)?%?', Number), ], 'object_reference': [ include('string_interpolated'), (r'([a-z][a-zA-Z0-9_]*|\d+)', Name.Builtin),
(words(object_attributes, prefix=r'\.'), Name.Builtin, '#pop'),
(r'\$', Name.Builtin), (r'\[', Text, '#pop'), ], 'variable_name': [ include('operator'), include('number'),
(words(variables_string, suffix=r'\$'), Name.Variable.Global), (words(variables_numeric, suffix=r'(?=[^a-zA-Z0-9_."\'$#\[:(]|\s|^|$)'), Name.Variable.Global),
(words(objects, prefix=r'\b', suffix=r"(_)"), bygroups(Name.Builtin, Name.Builtin), 'object_reference'),
(r'\.?_?[a-z][\w.]*(\$|#)?', Text), (r'[\[\]]', Punctuation, 'comma_list'),
include('string_interpolated'), ], 'operator': [ (r'([+\/*<>=!-]=?|[&*|][&*|]?|\^|<>)', Operator), (r'(?<![\w.])(and|or|not|div|mod)(?![\w.])', Operator.Word), ], 'string_interpolated': [ (r'\'[_a-z][^\[\]\'":]*(\[([\d,]+|"[\w,]+")\])?(:[0-9]+)?\'', String.Interpol), ], 'string_unquoted': [ (r'(\n\s*)(\.{3})', bygroups(Whitespace, Punctuation)),
(r'\n', Whitespace, '#pop'), (r'\s', Whitespace),
include('string_interpolated'),
(r"'", String), (r"[^'\n]+", String), ], 'string': [ (r'(\n\s*)(\.{3})', bygroups(Whitespace, Punctuation)),
(r'"', String, '#pop'),
include('string_interpolated'),
(r"'", String), (r'[^\'"\n]+', String), ], 'old_form': [ (r'(\s+)(#.*?$)', bygroups(Whitespace, Comment.Single)), (r'\s+', Whitespace),
(r'(optionmenu|choice)([ \t]+)(\S+)(:)([ \t]+)', bygroups(Keyword, Whitespace, Text, Punctuation, Whitespace), 'number'),
(r'(option|button)([ \t]+)', bygroups(Keyword, Whitespace), 'string_unquoted'),
(r'(sentence|text)([ \t]+)(\S+)', bygroups(Keyword, Whitespace, String), 'string_unquoted'),
(r'(word)([ \t]+)(\S+)([ \t]*)(\S+)?(?:([ \t]+)(.*))?', bygroups(Keyword, Whitespace, Text, Whitespace, Text, Whitespace, Text)),
(r'(boolean)(\s+\S+\s*)(0|1|"?(?:yes|no)"?)', bygroups(Keyword, Whitespace, Name.Variable)),
# Ideally processing of the number would happen in the 'number' # but that doesn't seem to work (r'(real|natural|positive|integer)([ \t]+\S+[ \t]*)([+-]?)(\d+(?:\.\d*)?' r'(?:[eE][-+]?\d+)?%?)', bygroups(Keyword, Whitespace, Operator, Number)),
(r'(comment)(\s+)', bygroups(Keyword, Whitespace), 'string_unquoted'),
(r'\bendform\b', Keyword, '#pop'), ] }1234567891011121314151617181920212223242526272829303132333435363738394041""" pygments.lexers.procfile ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Procfile file format.
: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 Name, Number, String, Text, Punctuation
__all__ = ["ProcfileLexer"]
class ProcfileLexer(RegexLexer): """ Lexer for Procfile file format.
The format is used to run processes on Heroku or is used by Foreman or Honcho tools. """ name = 'Procfile' url = 'https://devcenter.heroku.com/articles/procfile#procfile-format' aliases = ['procfile'] filenames = ['Procfile'] version_added = '2.10'
tokens = { 'root': [ (r'^([a-z]+)(:)', bygroups(Name.Label, Punctuation)), (r'\s+', Text.Whitespace), (r'"[^"]*"', String), (r"'[^']*'", String), (r'[0-9]+', Number.Integer), (r'\$[a-zA-Z_][\w]*', Name.Variable), (r'(\w+)(=)(\w+)', bygroups(Name.Variable, Punctuation, String)), (r'([\w\-\./]+)', Text), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318""" pygments.lexers.prolog ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Prolog and Prolog-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, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['PrologLexer', 'LogtalkLexer']
class PrologLexer(RegexLexer): """ Lexer for Prolog files. """ name = 'Prolog' aliases = ['prolog'] filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl'] mimetypes = ['text/x-prolog'] url = 'https://en.wikipedia.org/wiki/Prolog' version_added = ''
tokens = { 'root': [ (r'/\*', Comment.Multiline, 'nested-comment'), (r'%.*', Comment.Single), # character literal (r'0\'.', String.Char), (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), # literal with prepended base (r'\d\d?\'[a-zA-Z0-9]+', Number.Integer), (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), (r'\d+', Number.Integer), (r'[\[\](){}|.,;!]', Punctuation), (r':-|-->', Punctuation), (r'"(?:\\x[0-9a-fA-F]+\\|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|' r'\\[0-7]+\\|\\["\\abcefnrstv]|[^\\"])*"', String.Double), (r"'(?:''|[^'])*'", String.Atom), # quoted atom # Needs to not be followed by an atom. # (r'=(?=\s|[a-zA-Z\[])', Operator), (r'is\b', Operator), (r'(<|>|=<|>=|==|=:=|=|/|//|\*|\+|-)(?=\s|[a-zA-Z0-9\[])', Operator), (r'(mod|div|not)\b', Operator), (r'_', Keyword), # The don't-care variable (r'([a-z]+)(:)', bygroups(Name.Namespace, Punctuation)), (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' r'(\s*)(:-|-->)', bygroups(Name.Function, Text, Operator)), # function defn (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' r'(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*', String.Atom), # atom, characters # This one includes ! (r'[#&*+\-./:<=>?@\\^~\u00a1-\u00bf\u2010-\u303f]+', String.Atom), # atom, graphics (r'[A-Z_]\w*', Name.Variable), (r'\s+|[\u2000-\u200f\ufff0-\ufffe\uffef]', Text), ], 'nested-comment': [ (r'\*/', Comment.Multiline, '#pop'), (r'/\*', Comment.Multiline, '#push'), (r'[^*/]+', Comment.Multiline), (r'[*/]', Comment.Multiline), ], }
def analyse_text(text): """Competes with IDL and Visual Prolog on *.pro""" if ':-' in text: # Visual Prolog also uses :- return 0.5 else: return 0
class LogtalkLexer(RegexLexer): """ For Logtalk source code. """
name = 'Logtalk' url = 'http://logtalk.org/' aliases = ['logtalk'] filenames = ['*.lgt', '*.logtalk'] mimetypes = ['text/x-logtalk'] version_added = '0.10'
tokens = { 'root': [ # Directives (r'^\s*:-\s', Punctuation, 'directive'), # Comments (r'%.*?\n', Comment), (r'/\*(.|\n)*?\*/', Comment), # Whitespace (r'\n', Text), (r'\s+', Text), # Numbers (r"0'[\\]?.", Number), (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number), # Variables (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable), # Event handlers (r'(after|before)(?=[(])', Keyword), # Message forwarding handler (r'forward(?=[(])', Keyword), # Execution-context methods (r'(context|parameter|this|se(lf|nder))(?=[(])', Keyword), # Reflection (r'(current_predicate|predicate_property)(?=[(])', Keyword), # DCGs and term expansion (r'(expand_(goal|term)|(goal|term)_expansion|phrase)(?=[(])', Keyword), # Entity (r'(abolish|c(reate|urrent))_(object|protocol|category)(?=[(])', Keyword), (r'(object|protocol|category)_property(?=[(])', Keyword), # Entity relations (r'co(mplements_object|nforms_to_protocol)(?=[(])', Keyword), (r'extends_(object|protocol|category)(?=[(])', Keyword), (r'imp(lements_protocol|orts_category)(?=[(])', Keyword), (r'(instantiat|specializ)es_class(?=[(])', Keyword), # Events (r'(current_event|(abolish|define)_events)(?=[(])', Keyword), # Flags (r'(create|current|set)_logtalk_flag(?=[(])', Keyword), # Compiling, loading, and library paths (r'logtalk_(compile|l(ibrary_path|oad|oad_context)|make(_target_action)?)(?=[(])', Keyword), (r'\blogtalk_make\b', Keyword), # Database (r'(clause|retract(all)?)(?=[(])', Keyword), (r'a(bolish|ssert(a|z))(?=[(])', Keyword), # Control constructs (r'(ca(ll|tch)|throw)(?=[(])', Keyword), (r'(fa(il|lse)|true|(instantiation|system)_error)\b', Keyword), (r'(uninstantiation|type|domain|existence|permission|representation|evaluation|resource|syntax)_error(?=[(])', Keyword), # All solutions (r'((bag|set)of|f(ind|or)all)(?=[(])', Keyword), # Multi-threading predicates (r'threaded(_(ca(ll|ncel)|once|ignore|exit|peek|wait|notify))?(?=[(])', Keyword), # Engine predicates (r'threaded_engine(_(create|destroy|self|next|next_reified|yield|post|fetch))?(?=[(])', Keyword), # Term unification (r'(subsumes_term|unify_with_occurs_check)(?=[(])', Keyword), # Term creation and decomposition (r'(functor|arg|copy_term|numbervars|term_variables)(?=[(])', Keyword), # Evaluable functors (r'(div|rem|m(ax|in|od)|abs|sign)(?=[(])', Keyword), (r'float(_(integer|fractional)_part)?(?=[(])', Keyword), (r'(floor|t(an|runcate)|round|ceiling)(?=[(])', Keyword), # Other arithmetic functors (r'(cos|a(cos|sin|tan|tan2)|exp|log|s(in|qrt)|xor)(?=[(])', Keyword), # Term testing (r'(var|atom(ic)?|integer|float|c(allable|ompound)|n(onvar|umber)|ground|acyclic_term)(?=[(])', Keyword), # Term comparison (r'compare(?=[(])', Keyword), # Stream selection and control (r'(curren|se)t_(in|out)put(?=[(])', Keyword), (r'(open|close)(?=[(])', Keyword), (r'flush_output(?=[(])', Keyword), (r'(at_end_of_stream|flush_output)\b', Keyword), (r'(stream_property|at_end_of_stream|set_stream_position)(?=[(])', Keyword), # Character and byte input/output (r'(nl|(get|peek|put)_(byte|c(har|ode)))(?=[(])', Keyword), (r'\bnl\b', Keyword), # Term input/output (r'read(_term)?(?=[(])', Keyword), (r'write(q|_(canonical|term))?(?=[(])', Keyword), (r'(current_)?op(?=[(])', Keyword), (r'(current_)?char_conversion(?=[(])', Keyword), # Atomic term processing (r'atom_(length|c(hars|o(ncat|des)))(?=[(])', Keyword), (r'(char_code|sub_atom)(?=[(])', Keyword), (r'number_c(har|ode)s(?=[(])', Keyword), # Implementation defined hooks functions (r'(se|curren)t_prolog_flag(?=[(])', Keyword), (r'\bhalt\b', Keyword), (r'halt(?=[(])', Keyword), # Message sending operators (r'(::|:|\^\^)', Operator), # External call (r'[{}]', Keyword), # Logic and control (r'(ignore|once)(?=[(])', Keyword), (r'\brepeat\b', Keyword), # Sorting (r'(key)?sort(?=[(])', Keyword), # Bitwise functors (r'(>>|<<|/\\|\\\\|\\)', Operator), # Predicate aliases (r'\bas\b', Operator), # Arithmetic evaluation (r'\bis\b', Keyword), # Arithmetic comparison (r'(=:=|=\\=|<|=<|>=|>)', Operator), # Term creation and decomposition (r'=\.\.', Operator), # Term unification (r'(=|\\=)', Operator), # Term comparison (r'(==|\\==|@=<|@<|@>=|@>)', Operator), # Evaluable functors (r'(//|[-+*/])', Operator), (r'\b(e|pi|div|mod|rem)\b', Operator), # Other arithmetic functors (r'\b\*\*\b', Operator), # DCG rules (r'-->', Operator), # Control constructs (r'([!;]|->)', Operator), # Logic and control (r'\\+', Operator), # Mode operators (r'[?@]', Operator), # Existential quantifier (r'\^', Operator), # Punctuation (r'[()\[\],.|]', Text), # Atoms (r"[a-z][a-zA-Z0-9_]*", Text), (r"'", String, 'quoted_atom'), # Double-quoted terms (r'"', String, 'double_quoted_term'), ],
'quoted_atom': [ (r"''", String), (r"'", String, '#pop'), (r'\\([\\abfnrtv"\']|(x[a-fA-F0-9]+|[0-7]+)\\)', String.Escape), (r"[^\\'\n]+", String), (r'\\', String), ],
'double_quoted_term': [ (r'""', String), (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|(x[a-fA-F0-9]+|[0-7]+)\\)', String.Escape), (r'[^\\"\n]+', String), (r'\\', String), ],
'directive': [ # Conditional compilation directives (r'(el)?if(?=[(])', Keyword, 'root'), (r'(e(lse|ndif))(?=[.])', Keyword, 'root'), # Entity directives (r'(category|object|protocol)(?=[(])', Keyword, 'entityrelations'), (r'(end_(category|object|protocol))(?=[.])', Keyword, 'root'), # Predicate scope directives (r'(public|protected|private)(?=[(])', Keyword, 'root'), # Other directives (r'e(n(coding|sure_loaded)|xport)(?=[(])', Keyword, 'root'), (r'in(clude|itialization|fo)(?=[(])', Keyword, 'root'), (r'(built_in|dynamic|synchronized|threaded)(?=[.])', Keyword, 'root'), (r'(alias|d(ynamic|iscontiguous)|m(eta_(non_terminal|predicate)|ode|ultifile)|s(et_(logtalk|prolog)_flag|ynchronized))(?=[(])', Keyword, 'root'), (r'op(?=[(])', Keyword, 'root'), (r'(c(alls|oinductive)|module|reexport|use(s|_module))(?=[(])', Keyword, 'root'), (r'[a-z][a-zA-Z0-9_]*(?=[(])', Text, 'root'), (r'[a-z][a-zA-Z0-9_]*(?=[.])', Text, 'root'), ],
'entityrelations': [ (r'(complements|extends|i(nstantiates|mp(lements|orts))|specializes)(?=[(])', Keyword), # Numbers (r"0'[\\]?.", Number), (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number), # Variables (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable), # Atoms (r"[a-z][a-zA-Z0-9_]*", Text), (r"'", String, 'quoted_atom'), # Double-quoted terms (r'"', String, 'double_quoted_term'), # End of entity-opening directive (r'([)]\.)', Text, 'root'), # Scope operator (r'(::)', Operator), # Punctuation (r'[()\[\],.|]', Text), # Comments (r'%.*?\n', Comment), (r'/\*(.|\n)*?\*/', Comment), # Whitespace (r'\n', Text), (r'\s+', Text), ] }
def analyse_text(text): if ':- object(' in text: return 1.0 elif ':- protocol(' in text: return 1.0 elif ':- category(' in text: return 1.0 elif re.search(r'^:-\s[a-z]', text, re.M): return 0.9 else: return 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176""" pygments.lexers.promql ~~~~~~~~~~~~~~~~~~~~~~
Lexer for Prometheus Query 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 Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Whitespace
__all__ = ["PromQLLexer"]
class PromQLLexer(RegexLexer): """ For PromQL queries.
For details about the grammar see: https://github.com/prometheus/prometheus/tree/master/promql/parser
.. versionadded: 2.7 """
name = "PromQL" url = 'https://prometheus.io/docs/prometheus/latest/querying/basics/' aliases = ["promql"] filenames = ["*.promql"] version_added = ''
base_keywords = ( words( ( "bool", "by", "group_left", "group_right", "ignoring", "offset", "on", "without", ), suffix=r"\b", ), Keyword, )
aggregator_keywords = ( words( ( "sum", "min", "max", "avg", "group", "stddev", "stdvar", "count", "count_values", "bottomk", "topk", "quantile", ), suffix=r"\b", ), Keyword, )
function_keywords = ( words( ( "abs", "absent", "absent_over_time", "avg_over_time", "ceil", "changes", "clamp_max", "clamp_min", "count_over_time", "day_of_month", "day_of_week", "days_in_month", "delta", "deriv", "exp", "floor", "histogram_quantile", "holt_winters", "hour", "idelta", "increase", "irate", "label_join", "label_replace", "ln", "log10", "log2", "max_over_time", "min_over_time", "minute", "month", "predict_linear", "quantile_over_time", "rate", "resets", "round", "scalar", "sort", "sort_desc", "sqrt", "stddev_over_time", "stdvar_over_time", "sum_over_time", "time", "timestamp", "vector", "year", ), suffix=r"\b", ), Keyword.Reserved, )
tokens = { "root": [ (r"\n", Whitespace), (r"\s+", Whitespace), (r",", Punctuation), # Keywords base_keywords, aggregator_keywords, function_keywords, # Offsets (r"[1-9][0-9]*[smhdwy]", String), # Numbers (r"-?[0-9]+\.[0-9]+", Number.Float), (r"-?[0-9]+", Number.Integer), # Comments (r"#.*?$", Comment.Single), # Operators (r"(\+|\-|\*|\/|\%|\^)", Operator), (r"==|!=|>=|<=|<|>", Operator), (r"and|or|unless", Operator.Word), # Metrics (r"[_a-zA-Z][a-zA-Z0-9_]+", Name.Variable), # Params (r'(["\'])(.*?)(["\'])', bygroups(Punctuation, String, Punctuation)), # Other states (r"\(", Operator, "function"), (r"\)", Operator), (r"\{", Punctuation, "labels"), (r"\[", Punctuation, "range"), ], "labels": [ (r"\}", Punctuation, "#pop"), (r"\n", Whitespace), (r"\s+", Whitespace), (r",", Punctuation), (r'([_a-zA-Z][a-zA-Z0-9_]*?)(\s*?)(=~|!=|=|!~)(\s*?)("|\')(.*?)("|\')', bygroups(Name.Label, Whitespace, Operator, Whitespace, Punctuation, String, Punctuation)), ], "range": [ (r"\]", Punctuation, "#pop"), (r"[1-9][0-9]*[smhdwy]", String), ], "function": [ (r"\)", Operator, "#pop"), (r"\(", Operator, "#push"), default("#pop"), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251""" pygments.lexers.prql ~~~~~~~~~~~~~~~~~~~~
Lexer for the PRQL query language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, combined, words, include, bygroupsfrom pygments.token import Comment, Literal, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace
__all__ = ['PrqlLexer']
class PrqlLexer(RegexLexer): """ For PRQL source code.
grammar: https://github.com/PRQL/prql/tree/main/grammars """
name = 'PRQL' url = 'https://prql-lang.org/' aliases = ['prql'] filenames = ['*.prql'] mimetypes = ['application/prql', 'application/x-prql'] version_added = '2.17'
builtinTypes = words(( "bool", "int", "int8", "int16", "int32", "int64", "int128", "float", "text", "set"), suffix=r'\b')
def innerstring_rules(ttype): return [ # the new style '{}'.format(...) string formatting (r'\{' r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?' # field name r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?' r'\}', String.Interpol),
(r'[^\\\'"%{\n]+', ttype), (r'[\'"\\]', ttype), (r'%|(\{{1,2})', ttype) ]
def fstring_rules(ttype): return [ (r'\}', String.Interpol), (r'\{', String.Interpol, 'expr-inside-fstring'), (r'[^\\\'"{}\n]+', ttype), (r'[\'"\\]', ttype), ]
tokens = { 'root': [
# Comments (r'#!.*', String.Doc), (r'#.*', Comment.Single),
# Whitespace (r'\s+', Whitespace),
# Modules (r'^(\s*)(module)(\s*)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'imports'),
(builtinTypes, Keyword.Type),
# Main (r'^prql ', Keyword.Reserved),
('let', Keyword.Declaration),
include('keywords'), include('expr'),
# Transforms (r'^[A-Za-z_][a-zA-Z0-9_]*', Keyword), ], 'expr': [ # non-raw f-strings ('(f)(""")', bygroups(String.Affix, String.Double), combined('fstringescape', 'tdqf')), ("(f)(''')", bygroups(String.Affix, String.Single), combined('fstringescape', 'tsqf')), ('(f)(")', bygroups(String.Affix, String.Double), combined('fstringescape', 'dqf')), ("(f)(')", bygroups(String.Affix, String.Single), combined('fstringescape', 'sqf')),
# non-raw s-strings ('(s)(""")', bygroups(String.Affix, String.Double), combined('stringescape', 'tdqf')), ("(s)(''')", bygroups(String.Affix, String.Single), combined('stringescape', 'tsqf')), ('(s)(")', bygroups(String.Affix, String.Double), combined('stringescape', 'dqf')), ("(s)(')", bygroups(String.Affix, String.Single), combined('stringescape', 'sqf')),
# raw strings ('(?i)(r)(""")', bygroups(String.Affix, String.Double), 'tdqs'), ("(?i)(r)(''')", bygroups(String.Affix, String.Single), 'tsqs'), ('(?i)(r)(")', bygroups(String.Affix, String.Double), 'dqs'), ("(?i)(r)(')", bygroups(String.Affix, String.Single), 'sqs'),
# non-raw strings ('"""', String.Double, combined('stringescape', 'tdqs')), ("'''", String.Single, combined('stringescape', 'tsqs')), ('"', String.Double, combined('stringescape', 'dqs')), ("'", String.Single, combined('stringescape', 'sqs')),
# Time and dates (r'@\d{4}-\d{2}-\d{2}T\d{2}(:\d{2})?(:\d{2})?(\.\d{1,6})?(Z|[+-]\d{1,2}(:\d{1,2})?)?', Literal.Date), (r'@\d{4}-\d{2}-\d{2}', Literal.Date), (r'@\d{2}(:\d{2})?(:\d{2})?(\.\d{1,6})?(Z|[+-]\d{1,2}(:\d{1,2})?)?', Literal.Date),
(r'[^\S\n]+', Text), include('numbers'), (r'->|=>|==|!=|>=|<=|~=|&&|\|\||\?\?|\/\/', Operator), (r'[-~+/*%=<>&^|.@]', Operator), (r'[]{}:(),;[]', Punctuation), include('functions'),
# Variable Names (r'[A-Za-z_][a-zA-Z0-9_]*', Name.Variable), ], 'numbers': [ (r'(\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|(?:\d(?:_?\d)*)?\.\d(?:_?\d)*)' r'([eE][+-]?\d(?:_?\d)*)?', Number.Float), (r'\d(?:_?\d)*[eE][+-]?\d(?:_?\d)*j?', Number.Float), (r'0[oO](?:_?[0-7])+', Number.Oct), (r'0[bB](?:_?[01])+', Number.Bin), (r'0[xX](?:_?[a-fA-F0-9])+', Number.Hex), (r'\d(?:_?\d)*', Number.Integer), ], 'fstringescape': [ include('stringescape'), ], 'bytesescape': [ (r'\\([\\bfnrt"\']|\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], 'stringescape': [ (r'\\(N\{.*?\}|u\{[a-fA-F0-9]{1,6}\})', String.Escape), include('bytesescape') ], 'fstrings-single': fstring_rules(String.Single), 'fstrings-double': fstring_rules(String.Double), 'strings-single': innerstring_rules(String.Single), 'strings-double': innerstring_rules(String.Double), 'dqf': [ (r'"', String.Double, '#pop'), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include('fstrings-double') ], 'sqf': [ (r"'", String.Single, '#pop'), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include('fstrings-single') ], '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') ], 'tdqf': [ (r'"""', String.Double, '#pop'), include('fstrings-double'), (r'\n', String.Double) ], 'tsqf': [ (r"'''", String.Single, '#pop'), include('fstrings-single'), (r'\n', String.Single) ], 'tdqs': [ (r'"""', String.Double, '#pop'), include('strings-double'), (r'\n', String.Double) ], 'tsqs': [ (r"'''", String.Single, '#pop'), include('strings-single'), (r'\n', String.Single) ],
'expr-inside-fstring': [ (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), # without format specifier (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) r'\}', String.Interpol, '#pop'), # with format specifier # we'll catch the remaining '}' in the outer scope (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) r':', String.Interpol, '#pop'), (r'\s+', Whitespace), # allow new lines include('expr'), ], 'expr-inside-fstring-inner': [ (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), (r'[])}]', Punctuation, '#pop'), (r'\s+', Whitespace), # allow new lines include('expr'), ], 'keywords': [ (words(( 'into', 'case', 'type', 'module', 'internal', ), suffix=r'\b'), Keyword), (words(('true', 'false', 'null'), suffix=r'\b'), Keyword.Constant), ], 'functions': [ (words(( "min", "max", "sum", "average", "stddev", "every", "any", "concat_array", "count", "lag", "lead", "first", "last", "rank", "rank_dense", "row_number", "round", "as", "in", "tuple_every", "tuple_map", "tuple_zip", "_eq", "_is_null", "from_text", "lower", "upper", "read_parquet", "read_csv"), suffix=r'\b'), Name.Function), ],
'comment': [ (r'-(?!\})', Comment.Multiline), (r'\{-', Comment.Multiline, 'comment'), (r'[^-}]', Comment.Multiline), (r'-\}', Comment.Multiline, '#pop'), ],
'imports': [ (r'\w+(\.\w+)*', Name.Class, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119""" pygments.lexers.ptx ~~~~~~~~~~~~~~~~~~~
Lexer for other PTX language.
: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 Comment, Keyword, Name, String, Number, \ Punctuation, Whitespace, Operator
__all__ = ["PtxLexer"]
class PtxLexer(RegexLexer): """ For NVIDIA `PTX <https://docs.nvidia.com/cuda/parallel-thread-execution/>`_ source. """ name = 'PTX' url = "https://docs.nvidia.com/cuda/parallel-thread-execution/" filenames = ['*.ptx'] aliases = ['ptx'] mimetypes = ['text/x-ptx'] version_added = '2.16'
#: optional Comment or Whitespace string = r'"[^"]*?"' followsym = r'[a-zA-Z0-9_$]' identifier = r'([-a-zA-Z$._][\w\-$.]*|' + string + ')' block_label = r'(' + identifier + r'|(\d+))'
tokens = { 'root': [ include('whitespace'),
(block_label + r'\s*:', Name.Label),
include('keyword'),
(r'%' + identifier, Name.Variable), (r'%\d+', Name.Variable.Anonymous), (r'c?' + string, String), (identifier, Name.Variable), (r';', Punctuation), (r'[*+-/]', Operator),
(r'0[xX][a-fA-F0-9]+', Number), (r'-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?', Number),
(r'[=<>{}\[\]()*.,!]|x\b', Punctuation)
], 'whitespace': [ (r'(\n|\s+)+', Whitespace), (r'//.*?\n', Comment) ],
'keyword': [ # Instruction keywords (words(( 'abs', 'discard', 'min', 'shf', 'vadd', 'activemask', 'div', 'mma', 'shfl', 'vadd2', 'add', 'dp2a', 'mov', 'shl', 'vadd4', 'addc', 'dp4a', 'movmatrix', 'shr', 'vavrg2', 'alloca', 'elect', 'mul', 'sin', 'vavrg4', 'and', 'ex2', 'mul24', 'slct', 'vmad', 'applypriority', 'exit', 'multimem', 'sqrt', 'vmax', 'atom', 'fence', 'nanosleep', 'st', 'vmax2', 'bar', 'fma', 'neg', 'stackrestore', 'vmax4', 'barrier', 'fns', 'not', 'stacksave', 'vmin', 'bfe', 'getctarank', 'or', 'stmatrix', 'vmin2', 'bfi', 'griddepcontrol', 'pmevent', 'sub', 'vmin4', 'bfind', 'isspacep', 'popc', 'subc', 'vote', 'bmsk', 'istypep', 'prefetch', 'suld', 'vset', 'bra', 'ld', 'prefetchu', 'suq', 'vset2', 'brev', 'ldmatrix', 'prmt', 'sured', 'vset4', 'brkpt', 'ldu', 'rcp', 'sust', 'vshl', 'brx', 'lg2', 'red', 'szext', 'vshr', 'call', 'lop3', 'redux', 'tanh', 'vsub', 'clz', 'mad', 'rem', 'testp', 'vsub2', 'cnot', 'mad24', 'ret', 'tex', 'vsub4', 'copysign', 'madc', 'rsqrt', 'tld4', 'wgmma', 'cos', 'mapa', 'sad', 'trap', 'wmma', 'cp', 'match', 'selp', 'txq', 'xor', 'createpolicy', 'max', 'set', 'vabsdiff', 'cvt', 'mbarrier', 'setmaxnreg', 'vabsdiff2', 'cvta', 'membar', 'setp', 'vabsdiff4')), Keyword), # State Spaces and Suffixes (words(( 'reg', '.sreg', '.const', '.global', '.local', '.param', '.shared', '.tex', '.wide', '.loc' )), Keyword.Pseudo), # PTX Directives (words(( '.address_size', '.explicitcluster', '.maxnreg', '.section', '.alias', '.extern', '.maxntid', '.shared', '.align', '.file', '.minnctapersm', '.sreg', '.branchtargets', '.func', '.noreturn', '.target', '.callprototype', '.global', '.param', '.tex', '.calltargets', '.loc', '.pragma', '.version', '.common', '.local', '.reg', '.visible', '.const', '.maxclusterrank', '.reqnctapercluster', '.weak', '.entry', '.maxnctapersm', '.reqntid')), Keyword.Reserved), # Fundamental Types (words(( '.s8', '.s16', '.s32', '.s64', '.u8', '.u16', '.u32', '.u64', '.f16', '.f16x2', '.f32', '.f64', '.b8', '.b16', '.b32', '.b64', '.pred' )), Keyword.Type) ],
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204""" pygments.lexers.python ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Python and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import keyword
from pygments.lexer import DelegatingLexer, RegexLexer, include, \ bygroups, using, default, words, combined, thisfrom pygments.util import get_bool_opt, shebang_matchesfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Other, Error, Whitespacefrom pygments import unistring as uni
__all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer', 'Python2Lexer', 'Python2TracebackLexer', 'CythonLexer', 'DgLexer', 'NumPyLexer']
class PythonLexer(RegexLexer): """ For Python source code (version 3.x).
.. versionchanged:: 2.5 This is now the default ``PythonLexer``. It is still available as the alias ``Python3Lexer``. """
name = 'Python' url = 'https://www.python.org' aliases = ['python', 'py', 'sage', 'python3', 'py3', 'bazel', 'starlark', 'pyi'] filenames = [ '*.py', '*.pyw', # Type stubs '*.pyi', # Jython '*.jy', # Sage '*.sage', # SCons '*.sc', 'SConstruct', 'SConscript', # Skylark/Starlark (used by Bazel, Buck, and Pants) '*.bzl', 'BUCK', 'BUILD', 'BUILD.bazel', 'WORKSPACE', # Twisted Application infrastructure '*.tac', # Execubot level format '*.pye', ] mimetypes = ['text/x-python', 'application/x-python', 'text/x-python3', 'application/x-python3'] version_added = '0.10'
uni_name = f"[{uni.xid_start}][{uni.xid_continue}]*"
def innerstring_rules(ttype): return [ # the old style '%s' % (...) string formatting (still valid in Py3) (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' '[hlL]?[E-GXc-giorsaux%]', String.Interpol), # the new style '{}'.format(...) string formatting (r'\{' r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?' # field name r'(\![sra])?' # conversion r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?' r'\}', String.Interpol),
# backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"%{\n]+', ttype), (r'[\'"\\]', ttype), # unhandled string formatting sign (r'%|(\{{1,2})', ttype) # newlines are an error (use "nl" state) ]
def fstring_rules(ttype): return [ # Assuming that a '}' is the closing brace after format specifier. # Sadly, this means that we won't detect syntax error. But it's # more important to parse correct syntax correctly, than to # highlight invalid syntax. (r'\}', String.Interpol), (r'\{', String.Interpol, 'expr-inside-fstring'), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"{}\n]+', ttype), (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'\A#!.+$', Comment.Hashbang), (r'#.*$', Comment.Single), (r'\\\n', Text), (r'\\', Text), include('keywords'), include('soft-keywords'), (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'classname'), (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), 'fromimport'), (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), 'import'), include('expr'), ], 'expr': [ # raw f-strings and t-strings ('(?i)(r[ft]|[ft]r)(""")', bygroups(String.Affix, String.Double), combined('rfstringescape', 'tdqf')), ("(?i)(r[ft]|[ft]r)(''')", bygroups(String.Affix, String.Single), combined('rfstringescape', 'tsqf')), ('(?i)(r[ft]|[ft]r)(")', bygroups(String.Affix, String.Double), combined('rfstringescape', 'dqf')), ("(?i)(r[ft]|[ft]r)(')", bygroups(String.Affix, String.Single), combined('rfstringescape', 'sqf')), # non-raw f-strings and t-strings ('([fFtT])(""")', bygroups(String.Affix, String.Double), combined('fstringescape', 'tdqf')), ("([fFtT])(''')", bygroups(String.Affix, String.Single), combined('fstringescape', 'tsqf')), ('([fFtT])(")', bygroups(String.Affix, String.Double), combined('fstringescape', 'dqf')), ("([fFtT])(')", bygroups(String.Affix, String.Single), combined('fstringescape', 'sqf')), # raw bytes and strings ('(?i)(rb|br|r)(""")', bygroups(String.Affix, String.Double), 'tdqs'), ("(?i)(rb|br|r)(''')", bygroups(String.Affix, String.Single), 'tsqs'), ('(?i)(rb|br|r)(")', bygroups(String.Affix, String.Double), 'dqs'), ("(?i)(rb|br|r)(')", bygroups(String.Affix, String.Single), 'sqs'), # non-raw strings ('([uU]?)(""")', bygroups(String.Affix, String.Double), combined('stringescape', 'tdqs')), ("([uU]?)(''')", bygroups(String.Affix, String.Single), combined('stringescape', 'tsqs')), ('([uU]?)(")', bygroups(String.Affix, String.Double), combined('stringescape', 'dqs')), ("([uU]?)(')", bygroups(String.Affix, String.Single), combined('stringescape', 'sqs')), # non-raw bytes ('([bB])(""")', bygroups(String.Affix, String.Double), combined('bytesescape', 'tdqs')), ("([bB])(''')", bygroups(String.Affix, String.Single), combined('bytesescape', 'tsqs')), ('([bB])(")', bygroups(String.Affix, String.Double), combined('bytesescape', 'dqs')), ("([bB])(')", bygroups(String.Affix, String.Single), combined('bytesescape', 'sqs')),
(r'[^\S\n]+', Text), include('numbers'), (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator), (r'[]{}:(),;[]', Punctuation), (r'(in|is|and|or|not)\b', Operator.Word), include('expr-keywords'), include('builtins'), include('magicfuncs'), include('magicvars'), include('name'), ], 'expr-inside-fstring': [ (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), # without format specifier (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) r'(\![sraf])?' # conversion r'\}', String.Interpol, '#pop'), # with format specifier # we'll catch the remaining '}' in the outer scope (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) r'(\![sraf])?' # conversion r':', String.Interpol, '#pop'), (r'\s+', Whitespace), # allow new lines include('expr'), ], 'expr-inside-fstring-inner': [ (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), (r'[])}]', Punctuation, '#pop'), (r'\s+', Whitespace), # allow new lines include('expr'), ], 'expr-keywords': [ # Based on https://docs.python.org/3/reference/expressions.html (words(( 'async for', 'await', 'else', 'for', 'if', 'lambda', 'yield', 'yield from'), suffix=r'\b'), Keyword), (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), ], 'keywords': [ (words(( 'assert', 'async', 'await', 'break', 'continue', 'del', 'elif', 'else', 'except', 'finally', 'for', 'global', 'if', 'lambda', 'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield', 'yield from', 'as', 'with'), suffix=r'\b'), Keyword), (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), ], 'soft-keywords': [ # `match`, `case` and `_` soft keywords (r'(^[ \t]*)' # at beginning of line + possible indentation r'(match|case)\b' # a possible keyword r'(?![ \t]*(?:' # not followed by... r'[:,;=^&|@~)\]}]|(?:' + # characters and keywords that mean this isn't # pattern matching (but None/True/False is ok) r'|'.join(k for k in keyword.kwlist if k[0].islower()) + r')\b))', bygroups(Text, Keyword), 'soft-keywords-inner'), ], 'soft-keywords-inner': [ # optional `_` keyword (r'(\s+)([^\n_]*)(_\b)', bygroups(Whitespace, using(this), Keyword)), default('#pop') ], 'builtins': [ (words(( '__import__', 'abs', 'aiter', 'all', 'any', 'bin', 'bool', 'bytearray', 'breakpoint', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), (r'(?<!\.)(self|Ellipsis|NotImplemented|cls)\b', Name.Builtin.Pseudo), (words(( 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError', 'Warning', 'WindowsError', 'ZeroDivisionError', # new builtin exceptions from PEP 3151 'BlockingIOError', 'ChildProcessError', 'ConnectionError', 'BrokenPipeError', 'ConnectionAbortedError', 'ConnectionRefusedError', 'ConnectionResetError', 'FileExistsError', 'FileNotFoundError', 'InterruptedError', 'IsADirectoryError', 'NotADirectoryError', 'PermissionError', 'ProcessLookupError', 'TimeoutError', # others new in Python 3 'StopAsyncIteration', 'ModuleNotFoundError', 'RecursionError', 'EncodingWarning'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Exception), ], 'magicfuncs': [ (words(( '__abs__', '__add__', '__aenter__', '__aexit__', '__aiter__', '__and__', '__anext__', '__await__', '__bool__', '__bytes__', '__call__', '__complex__', '__contains__', '__del__', '__delattr__', '__delete__', '__delitem__', '__dir__', '__divmod__', '__enter__', '__eq__', '__exit__', '__float__', '__floordiv__', '__format__', '__ge__', '__get__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__instancecheck__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__length_hint__', '__lshift__', '__lt__', '__matmul__', '__missing__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__next__', '__or__', '__pos__', '__pow__', '__prepare__', '__radd__', '__rand__', '__rdivmod__', '__repr__', '__reversed__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__', '__str__', '__sub__', '__subclasscheck__', '__truediv__', '__xor__'), suffix=r'\b'), Name.Function.Magic), ], 'magicvars': [ (words(( '__annotations__', '__bases__', '__class__', '__closure__', '__code__', '__defaults__', '__dict__', '__doc__', '__file__', '__func__', '__globals__', '__kwdefaults__', '__module__', '__mro__', '__name__', '__objclass__', '__qualname__', '__self__', '__slots__', '__weakref__'), suffix=r'\b'), Name.Variable.Magic), ], 'numbers': [ (r'(\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|(?:\d(?:_?\d)*)?\.\d(?:_?\d)*)' r'([eE][+-]?\d(?:_?\d)*)?', Number.Float), (r'\d(?:_?\d)*[eE][+-]?\d(?:_?\d)*j?', Number.Float), (r'0[oO](?:_?[0-7])+', Number.Oct), (r'0[bB](?:_?[01])+', Number.Bin), (r'0[xX](?:_?[a-fA-F0-9])+', Number.Hex), (r'\d(?:_?\d)*', Number.Integer), ], 'name': [ (r'@' + uni_name, Name.Decorator), (r'@', Operator), # new matrix multiplication operator (uni_name, Name), ], 'funcname': [ include('magicfuncs'), (uni_name, Name.Function, '#pop'), default('#pop'), ], 'classname': [ (uni_name, Name.Class, '#pop'), ], 'import': [ (r'(\s+)(as)(\s+)', bygroups(Whitespace, Keyword, Whitespace)), (r'\.', Name.Namespace), (uni_name, Name.Namespace), (r'(\s*)(,)(\s*)', bygroups(Whitespace, Operator, Whitespace)), default('#pop') # all else: go back ], 'fromimport': [ (r'(\s+)(import)\b', bygroups(Whitespace, Keyword.Namespace), '#pop'), (r'\.', Name.Namespace), # if None occurs here, it's "raise x from None", since None can # never be a module name (r'None\b', Keyword.Constant, '#pop'), (uni_name, Name.Namespace), default('#pop'), ], 'rfstringescape': [ (r'\{\{', String.Escape), (r'\}\}', String.Escape), ], 'fstringescape': [ include('rfstringescape'), include('stringescape'), ], 'bytesescape': [ (r'\\([\\abfnrtv"\']|\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], 'stringescape': [ (r'\\(N\{.*?\}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})', String.Escape), include('bytesescape') ], 'fstrings-single': fstring_rules(String.Single), 'fstrings-double': fstring_rules(String.Double), 'strings-single': innerstring_rules(String.Single), 'strings-double': innerstring_rules(String.Double), 'dqf': [ (r'"', String.Double, '#pop'), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include('fstrings-double') ], 'sqf': [ (r"'", String.Single, '#pop'), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include('fstrings-single') ], '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') ], 'tdqf': [ (r'"""', String.Double, '#pop'), include('fstrings-double'), (r'\n', String.Double) ], 'tsqf': [ (r"'''", String.Single, '#pop'), include('fstrings-single'), (r'\n', String.Single) ], 'tdqs': [ (r'"""', String.Double, '#pop'), include('strings-double'), (r'\n', String.Double) ], 'tsqs': [ (r"'''", String.Single, '#pop'), include('strings-single'), (r'\n', String.Single) ], }
def analyse_text(text): return shebang_matches(text, r'pythonw?(3(\.\d)?)?') or \ 'import ' in text[:1000]
Python3Lexer = PythonLexer
class Python2Lexer(RegexLexer): """ For Python 2.x source code.
.. versionchanged:: 2.5 This class has been renamed from ``PythonLexer``. ``PythonLexer`` now refers to the Python 3 variant. File name patterns like ``*.py`` have been moved to Python 3 as well. """
name = 'Python 2.x' url = 'https://www.python.org' aliases = ['python2', 'py2'] filenames = [] # now taken over by PythonLexer (3.x) mimetypes = ['text/x-python2', 'application/x-python2'] 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]+', Text), (r'\A#!.+$', Comment.Hashbang), (r'#.*$', Comment.Single), (r'[]{}:(),;[]', Punctuation), (r'\\\n', Text), (r'\\', Text), (r'(in|is|and|or|not)\b', Operator.Word), (r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator), include('keywords'), (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'classname'), (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), 'fromimport'), (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), 'import'), include('builtins'), include('magicfuncs'), include('magicvars'), include('backtick'), ('([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(( 'assert', 'break', 'continue', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield', 'yield from', 'as', 'with'), suffix=r'\b'), Keyword), ], 'builtins': [ (words(( '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), (r'(?<!\.)(self|None|Ellipsis|NotImplemented|False|True|cls' r')\b', Name.Builtin.Pseudo), (words(( 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError', 'Warning', 'WindowsError', 'ZeroDivisionError'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Exception), ], 'magicfuncs': [ (words(( '__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__', '__complex__', '__contains__', '__del__', '__delattr__', '__delete__', '__delitem__', '__delslice__', '__div__', '__divmod__', '__enter__', '__eq__', '__exit__', '__float__', '__floordiv__', '__ge__', '__get__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__', '__ilshift__', '__imod__', '__imul__', '__index__', '__init__', '__instancecheck__', '__int__', '__invert__', '__iop__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__', '__missing__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__oct__', '__op__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rcmp__', '__rdiv__', '__rdivmod__', '__repr__', '__reversed__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__rop__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__', '__setslice__', '__str__', '__sub__', '__subclasscheck__', '__truediv__', '__unicode__', '__xor__'), suffix=r'\b'), Name.Function.Magic), ], 'magicvars': [ (words(( '__bases__', '__class__', '__closure__', '__code__', '__defaults__', '__dict__', '__doc__', '__file__', '__func__', '__globals__', '__metaclass__', '__module__', '__mro__', '__name__', '__self__', '__slots__', '__weakref__'), suffix=r'\b'), Name.Variable.Magic), ], '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) ], 'backtick': [ ('`.*?`', String.Backtick), ], 'name': [ (r'@[\w.]+', Name.Decorator), (r'[a-zA-Z_]\w*', Name), ], 'funcname': [ include('magicfuncs'), (r'[a-zA-Z_]\w*', Name.Function, '#pop'), default('#pop'), ], 'classname': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'import': [ (r'(?:[ \t]|\\\n)+', Text), (r'as\b', Keyword.Namespace), (r',', Operator), (r'[a-zA-Z_][\w.]*', Name.Namespace), default('#pop') # all else: go back ], 'fromimport': [ (r'(?:[ \t]|\\\n)+', Text), (r'import\b', Keyword.Namespace, '#pop'), # if None occurs here, it's "raise x from None", since None can # never be a module name (r'None\b', Name.Builtin.Pseudo, '#pop'), # sadly, in "raise x from y" y will be highlighted as namespace too (r'[a-zA-Z_.][\w.]*', Name.Namespace), # anything else here also means "raise x from y" and is therefore # not an error default('#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', String.Double) ], 'tsqs': [ (r"'''", String.Single, '#pop'), include('strings-single'), (r'\n', String.Single) ], }
def analyse_text(text): return shebang_matches(text, r'pythonw?2(\.\d)?')
class _PythonConsoleLexerBase(RegexLexer): name = 'Python console session' aliases = ['pycon', 'python-console'] mimetypes = ['text/x-python-doctest']
"""Auxiliary lexer for `PythonConsoleLexer`.
Code tokens are output as ``Token.Other.Code``, traceback tokens as ``Token.Other.Traceback``. """ tokens = { 'root': [ (r'(>>> )(.*\n)', bygroups(Generic.Prompt, Other.Code), 'continuations'), # This happens, e.g., when tracebacks are embedded in documentation; # trailing whitespaces are often stripped in such contexts. (r'(>>>)(\n)', bygroups(Generic.Prompt, Whitespace)), (r'(\^C)?Traceback \(most recent call last\):\n', Other.Traceback, 'traceback'), # SyntaxError starts with this (r' File "[^"]+", line \d+', Other.Traceback, 'traceback'), (r'.*\n', Generic.Output), ], 'continuations': [ (r'(\.\.\. )(.*\n)', bygroups(Generic.Prompt, Other.Code)), # See above. (r'(\.\.\.)(\n)', bygroups(Generic.Prompt, Whitespace)), default('#pop'), ], 'traceback': [ # As soon as we see a traceback, consume everything until the next # >>> prompt. (r'(?=>>>( |$))', Text, '#pop'), (r'(KeyboardInterrupt)(\n)', bygroups(Name.Class, Whitespace)), (r'.*\n', Other.Traceback), ], }
class PythonConsoleLexer(DelegatingLexer): """ For Python console output or doctests, such as:
.. sourcecode:: pycon
>>> a = 'foo' >>> print(a) foo >>> 1 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
Additional options:
`python3` Use Python 3 lexer for code. Default is ``True``.
.. versionadded:: 1.0 .. versionchanged:: 2.5 Now defaults to ``True``. """
name = 'Python console session' aliases = ['pycon', 'python-console'] mimetypes = ['text/x-python-doctest'] url = 'https://python.org' version_added = ''
def __init__(self, **options): python3 = get_bool_opt(options, 'python3', True) if python3: pylexer = PythonLexer tblexer = PythonTracebackLexer else: pylexer = Python2Lexer tblexer = Python2TracebackLexer # We have two auxiliary lexers. Use DelegatingLexer twice with # different tokens. TODO: DelegatingLexer should support this # directly, by accepting a tuplet of auxiliary lexers and a tuple of # distinguishing tokens. Then we wouldn't need this intermediary # class. class _ReplaceInnerCode(DelegatingLexer): def __init__(self, **options): super().__init__(pylexer, _PythonConsoleLexerBase, Other.Code, **options) super().__init__(tblexer, _ReplaceInnerCode, Other.Traceback, **options)
class PythonTracebackLexer(RegexLexer): """ For Python 3.x tracebacks, with support for chained exceptions.
.. versionchanged:: 2.5 This is now the default ``PythonTracebackLexer``. It is still available as the alias ``Python3TracebackLexer``. """
name = 'Python Traceback' aliases = ['pytb', 'py3tb'] filenames = ['*.pytb', '*.py3tb'] mimetypes = ['text/x-python-traceback', 'text/x-python3-traceback'] url = 'https://python.org' version_added = '1.0'
tokens = { 'root': [ (r'\n', Whitespace), (r'^(\^C)?Traceback \(most recent call last\):\n', Generic.Traceback, 'intb'), (r'^During handling of the above exception, another ' r'exception occurred:\n\n', Generic.Traceback), (r'^The above exception was the direct cause of the ' r'following exception:\n\n', Generic.Traceback), (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'), (r'^.*\n', Other), ], 'intb': [ (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)', bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)), (r'^( File )("[^"]+")(, line )(\d+)(\n)', bygroups(Text, Name.Builtin, Text, Number, Whitespace)), (r'^( )(.+)(\n)', bygroups(Whitespace, using(PythonLexer), Whitespace), 'markers'), (r'^([ \t]*)(\.\.\.)(\n)', bygroups(Whitespace, Comment, Whitespace)), # for doctests... (r'^([^:]+)(: )(.+)(\n)', bygroups(Generic.Error, Text, Name, Whitespace), '#pop'), (r'^([a-zA-Z_][\w.]*)(:?\n)', bygroups(Generic.Error, Whitespace), '#pop'), default('#pop'), ], 'markers': [ # Either `PEP 657 <https://www.python.org/dev/peps/pep-0657/>` # error locations in Python 3.11+, or single-caret markers # for syntax errors before that. (r'^( {4,})([~^]+)(\n)', bygroups(Whitespace, Punctuation.Marker, Whitespace), '#pop'), default('#pop'), ], }
Python3TracebackLexer = PythonTracebackLexer
class Python2TracebackLexer(RegexLexer): """ For Python tracebacks.
.. versionchanged:: 2.5 This class has been renamed from ``PythonTracebackLexer``. ``PythonTracebackLexer`` now refers to the Python 3 variant. """
name = 'Python 2.x Traceback' aliases = ['py2tb'] filenames = ['*.py2tb'] mimetypes = ['text/x-python2-traceback'] url = 'https://python.org' version_added = '0.7'
tokens = { 'root': [ # Cover both (most recent call last) and (innermost last) # The optional ^C allows us to catch keyboard interrupt signals. (r'^(\^C)?(Traceback.*\n)', bygroups(Text, Generic.Traceback), 'intb'), # SyntaxError starts with this. (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'), (r'^.*\n', Other), ], 'intb': [ (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)', bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)), (r'^( File )("[^"]+")(, line )(\d+)(\n)', bygroups(Text, Name.Builtin, Text, Number, Whitespace)), (r'^( )(.+)(\n)', bygroups(Text, using(Python2Lexer), Whitespace), 'marker'), (r'^([ \t]*)(\.\.\.)(\n)', bygroups(Text, Comment, Whitespace)), # for doctests... (r'^([^:]+)(: )(.+)(\n)', bygroups(Generic.Error, Text, Name, Whitespace), '#pop'), (r'^([a-zA-Z_]\w*)(:?\n)', bygroups(Generic.Error, Whitespace), '#pop') ], 'marker': [ # For syntax errors. (r'( {4,})(\^)', bygroups(Text, Punctuation.Marker), '#pop'), default('#pop'), ], }
class CythonLexer(RegexLexer): """ For Pyrex and Cython source code. """
name = 'Cython' url = 'https://cython.org' aliases = ['cython', 'pyx', 'pyrex'] filenames = ['*.pyx', '*.pxd', '*.pxi'] mimetypes = ['text/x-cython', 'application/x-cython'] version_added = '1.1'
tokens = { 'root': [ (r'\n', Whitespace), (r'^(\s*)("""(?:.|\n)*?""")', bygroups(Whitespace, String.Doc)), (r"^(\s*)('''(?:.|\n)*?''')", bygroups(Whitespace, String.Doc)), (r'[^\S\n]+', Text), (r'#.*$', Comment), (r'[]{}:(),;[]', Punctuation), (r'\\\n', Whitespace), (r'\\', Text), (r'(in|is|and|or|not)\b', Operator.Word), (r'(<)([a-zA-Z0-9.?]+)(>)', bygroups(Punctuation, Keyword.Type, Punctuation)), (r'!=|==|<<|>>|[-~+/*%=<>&^|.?]', Operator), (r'(from)(\d+)(<=)(\s+)(<)(\d+)(:)', bygroups(Keyword, Number.Integer, Operator, Whitespace, Operator, Name, Punctuation)), include('keywords'), (r'(def|property)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(cp?def)(\s+)', bygroups(Keyword, Whitespace), 'cdef'), # (should actually start a block with only cdefs) (r'(cdef)(:)', bygroups(Keyword, Punctuation)), (r'(class|cppclass|struct)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(from)(\s+)', bygroups(Keyword, Whitespace), 'fromimport'), (r'(c?import)(\s+)', bygroups(Keyword, Whitespace), 'import'), include('builtins'), include('backtick'), ('(?:[rR]|[uU][rR]|[rR][uU])"""', String, 'tdqs'), ("(?:[rR]|[uU][rR]|[rR][uU])'''", String, 'tsqs'), ('(?:[rR]|[uU][rR]|[rR][uU])"', String, 'dqs'), ("(?:[rR]|[uU][rR]|[rR][uU])'", String, 'sqs'), ('[uU]?"""', String, combined('stringescape', 'tdqs')), ("[uU]?'''", String, combined('stringescape', 'tsqs')), ('[uU]?"', String, combined('stringescape', 'dqs')), ("[uU]?'", String, combined('stringescape', 'sqs')), include('name'), include('numbers'), ], 'keywords': [ (words(( 'assert', 'async', 'await', 'break', 'by', 'continue', 'ctypedef', 'del', 'elif', 'else', 'except', 'except?', 'exec', 'finally', 'for', 'fused', 'gil', 'global', 'if', 'include', 'lambda', 'namespace', 'new', 'noexcept','nogil', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield', 'as', 'with'), suffix=r'\b'), Keyword), (words(('True', 'False', 'None', 'NULL'), suffix=r'\b'), Keyword.Constant), (r'(DEF|IF|ELIF|ELSE)\b', Comment.Preproc), ], 'builtins': [ (words(( '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bint', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'char', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', 'double', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'Py_ssize_t', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'size_t', 'slice', 'sorted', 'staticmethod', 'ssize_t', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'unsigned', 'vars', 'xrange', 'zip'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), (r'(?<!\.)(self|cls|Ellipsis|NotImplemented)\b', Name.Builtin.Pseudo), (words(( 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Exception), ], 'numbers': [ (r'(\d+\.?\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), (r'0\d+', Number.Oct), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+', Number.Integer) ], 'backtick': [ ('`.*?`', String.Backtick), ], 'name': [ (r'@\w+', Name.Decorator), (r'[a-zA-Z_]\w*', Name), ], 'funcname': [ (r'[a-zA-Z_]\w*', Name.Function, '#pop') ], 'cdef': [ (r"(public|readonly|extern|api|inline|packed)\b", Keyword.Reserved), (r"(struct|enum|union|class|cppclass)\b(\s+)([a-zA-Z_]\w*)", bygroups(Keyword, Whitespace, Name.Class), "#pop",), (r"([a-zA-Z_]\w*)(\s*)(?=\()", bygroups(Name.Function, Whitespace), "#pop"), (r"([a-zA-Z_]\w*)(\s*)(?=[:,=#\n]|$)", bygroups(Name.Variable, Whitespace), "#pop"), (r"([a-zA-Z_]\w*)(\s*)(,)", bygroups(Name.Variable, Whitespace, Punctuation)), (r'from\b', Keyword, '#pop'), (r'as\b', Keyword), (r':', Punctuation, '#pop'), (r'(?=["\'])', Text, '#pop'), (r'[a-zA-Z_]\w*', Keyword.Type), (r'.', Text), ], 'classname': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'import': [ (r'(\s+)(as)(\s+)', bygroups(Whitespace, Keyword, Whitespace)), (r'[a-zA-Z_][\w.]*', Name.Namespace), (r'(\s*)(,)(\s*)', bygroups(Whitespace, Operator, Whitespace)), default('#pop') # all else: go back ], 'fromimport': [ (r'(\s+)(c?import)\b', bygroups(Whitespace, Keyword), '#pop'), (r'[a-zA-Z_.][\w.]*', Name.Namespace), # ``cdef foo from "header"``, or ``for foo from 0 < i < 10`` default('#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': [ (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'), (r'\\\\|\\"|\\\n', String.Escape), # included here again for raw strings include('strings') ], 'sqs': [ (r"'", String, '#pop'), (r"\\\\|\\'|\\\n", String.Escape), # included here again for raw strings include('strings') ], 'tdqs': [ (r'"""', String, '#pop'), include('strings'), include('nl') ], 'tsqs': [ (r"'''", String, '#pop'), include('strings'), include('nl') ], }
class DgLexer(RegexLexer): """ Lexer for dg, a functional and object-oriented programming language running on the CPython 3 VM. """ name = 'dg' aliases = ['dg'] filenames = ['*.dg'] mimetypes = ['text/x-dg'] url = 'http://pyos.github.io/dg' version_added = '1.6'
tokens = { 'root': [ (r'\s+', Text), (r'#.*?$', Comment.Single),
(r'(?i)0b[01]+', Number.Bin), (r'(?i)0o[0-7]+', Number.Oct), (r'(?i)0x[0-9a-f]+', Number.Hex), (r'(?i)[+-]?[0-9]+\.[0-9]+(e[+-]?[0-9]+)?j?', Number.Float), (r'(?i)[+-]?[0-9]+e[+-]?\d+j?', Number.Float), (r'(?i)[+-]?[0-9]+j?', Number.Integer),
(r"(?i)(br|r?b?)'''", String, combined('stringescape', 'tsqs', 'string')), (r'(?i)(br|r?b?)"""', String, combined('stringescape', 'tdqs', 'string')), (r"(?i)(br|r?b?)'", String, combined('stringescape', 'sqs', 'string')), (r'(?i)(br|r?b?)"', String, combined('stringescape', 'dqs', 'string')),
(r"`\w+'*`", Operator), (r'\b(and|in|is|or|where)\b', Operator.Word), (r'[!$%&*+\-./:<-@\\^|~;,]+', Operator),
(words(( 'bool', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'dict\'', 'float', 'frozenset', 'int', 'list', 'list\'', 'memoryview', 'object', 'property', 'range', 'set', 'set\'', 'slice', 'staticmethod', 'str', 'super', 'tuple', 'tuple\'', 'type'), prefix=r'(?<!\.)', suffix=r'(?![\'\w])'), Name.Builtin), (words(( '__import__', 'abs', 'all', 'any', 'bin', 'bind', 'chr', 'cmp', 'compile', 'complex', 'delattr', 'dir', 'divmod', 'drop', 'dropwhile', 'enumerate', 'eval', 'exhaust', 'filter', 'flip', 'foldl1?', 'format', 'fst', 'getattr', 'globals', 'hasattr', 'hash', 'head', 'hex', 'id', 'init', 'input', 'isinstance', 'issubclass', 'iter', 'iterate', 'last', 'len', 'locals', 'map', 'max', 'min', 'next', 'oct', 'open', 'ord', 'pow', 'print', 'repr', 'reversed', 'round', 'setattr', 'scanl1?', 'snd', 'sorted', 'sum', 'tail', 'take', 'takewhile', 'vars', 'zip'), prefix=r'(?<!\.)', suffix=r'(?![\'\w])'), Name.Builtin), (r"(?<!\.)(self|Ellipsis|NotImplemented|None|True|False)(?!['\w])", Name.Builtin.Pseudo),
(r"(?<!\.)[A-Z]\w*(Error|Exception|Warning)'*(?!['\w])", Name.Exception), (r"(?<!\.)(Exception|GeneratorExit|KeyboardInterrupt|StopIteration|" r"SystemExit)(?!['\w])", Name.Exception),
(r"(?<![\w.])(except|finally|for|if|import|not|otherwise|raise|" r"subclass|while|with|yield)(?!['\w])", Keyword.Reserved),
(r"[A-Z_]+'*(?!['\w])", Name), (r"[A-Z]\w+'*(?!['\w])", Keyword.Type), (r"\w+'*", Name),
(r'[()]', Punctuation), (r'.', Error), ], '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) ], 'string': [ (r'%(\(\w+\))?[-#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), (r'\n', String) ], 'dqs': [ (r'"', String, '#pop') ], 'sqs': [ (r"'", String, '#pop') ], 'tdqs': [ (r'"""', String, '#pop') ], 'tsqs': [ (r"'''", String, '#pop') ], }
class NumPyLexer(PythonLexer): """ A Python lexer recognizing Numerical Python builtins. """
name = 'NumPy' url = 'https://numpy.org/' aliases = ['numpy'] version_added = '0.10'
# override the mimetypes to not inherit them from python mimetypes = [] filenames = []
EXTRA_KEYWORDS = { 'abs', 'absolute', 'accumulate', 'add', 'alen', 'all', 'allclose', 'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str', 'arrayrange', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'astype', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'beta', 'binary_repr', 'bincount', 'binomial', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'bmat', 'broadcast', 'byte_bounds', 'bytes', 'byteswap', 'c_', 'can_cast', 'ceil', 'choose', 'clip', 'column_stack', 'common_type', 'compare_chararrays', 'compress', 'concatenate', 'conj', 'conjugate', 'convolve', 'copy', 'corrcoef', 'correlate', 'cos', 'cosh', 'cov', 'cross', 'cumprod', 'cumproduct', 'cumsum', 'delete', 'deprecate', 'diag', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'dot', 'dsplit', 'dstack', 'dtype', 'dump', 'dumps', 'ediff1d', 'empty', 'empty_like', 'equal', 'exp', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fftfreq', 'fftshift', 'fill', 'finfo', 'fix', 'flat', 'flatnonzero', 'flatten', 'fliplr', 'flipud', 'floor', 'floor_divide', 'fmod', 'frexp', 'fromarrays', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromstring', 'generic', 'get_array_wrap', 'get_include', 'get_numarray_include', 'get_numpy_include', 'get_printoptions', 'getbuffer', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'getfield', 'gradient', 'greater', 'greater_equal', 'gumbel', 'hamming', 'hanning', 'histogram', 'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'ifft', 'imag', 'index_exp', 'indices', 'inf', 'info', 'inner', 'insert', 'int_asbuffer', 'interp', 'intersect1d', 'intersect1d_nu', 'inv', 'invert', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isinf', 'isnan', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'item', 'itemset', 'iterable', 'ix_', 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'linspace', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'lstsq', 'mat', 'matrix', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'meshgrid', 'mgrid', 'min', 'minimum', 'mintypecode', 'mod', 'modf', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum', 'ndenumerate', 'ndim', 'ndindex', 'negative', 'newaxis', 'newbuffer', 'newbyteorder', 'nonzero', 'not_equal', 'obj2sctype', 'ogrid', 'ones', 'ones_like', 'outer', 'permutation', 'piecewise', 'pinv', 'pkgload', 'place', 'poisson', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'prod', 'product', 'ptp', 'put', 'putmask', 'r_', 'randint', 'random_integers', 'random_sample', 'ranf', 'rank', 'ravel', 'real', 'real_if_close', 'recarray', 'reciprocal', 'reduce', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'restoredot', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'sample', 'savetxt', 'sctype2char', 'searchsorted', 'seed', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setfield', 'setflags', 'setmember1d', 'setxor1d', 'shape', 'show_config', 'shuffle', 'sign', 'signbit', 'sin', 'sinc', 'sinh', 'size', 'slice', 'solve', 'sometrue', 'sort', 'sort_complex', 'source', 'split', 'sqrt', 'square', 'squeeze', 'standard_normal', 'std', 'subtract', 'sum', 'svd', 'swapaxes', 'take', 'tan', 'tanh', 'tensordot', 'test', 'tile', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'trapz', 'tri', 'tril', 'trim_zeros', 'triu', 'true_divide', 'typeDict', 'typename', 'uniform', 'union1d', 'unique', 'unique1d', 'unravel_index', 'unwrap', 'vander', 'var', 'vdot', 'vectorize', 'view', 'vonmises', 'vsplit', 'vstack', 'weibull', 'where', 'who', 'zeros', 'zeros_like' }
def get_tokens_unprocessed(self, text): for index, token, value in \ PythonLexer.get_tokens_unprocessed(self, text): if token is Name and value in self.EXTRA_KEYWORDS: yield index, Keyword.Pseudo, value else: yield index, token, value
def analyse_text(text): ltext = text[:1000] return (shebang_matches(text, r'pythonw?(3(\.\d)?)?') or 'import ' in ltext) \ and ('import numpy' in ltext or 'from numpy import' in ltext)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187""" pygments.lexers.q ~~~~~~~~~~~~~~~~~
Lexer for the Q 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, bygroups, inheritfrom pygments.token import Comment, Name, Number, Operator, Punctuation, \ String, Whitespace, Literal, Generic
__all__ = ["KLexer", "QLexer"]
class KLexer(RegexLexer): """ For K source code. """
name = "K" aliases = ["k"] filenames = ["*.k"] url = "https://code.kx.com" version_added = '2.12'
tokens = { "whitespace": [ # hashbang script (r"^#!.*", Comment.Hashbang), # Comments (r"^/\s*\n", Comment.Multiline, "comments"), (r"(?<!\S)/.*", Comment.Single), # Whitespace (r"\s+", Whitespace), # Strings (r"\"", String.Double, "strings"), ], "root": [ include("whitespace"), include("keywords"), include("declarations"), ], "keywords": [ (words(("abs", "acos", "asin", "atan", "avg", "bin", "binr", "by", "cor", "cos", "cov", "dev", "delete", "div", "do", "enlist", "exec", "exit", "exp", "from", "getenv", "hopen", "if", "in", "insert", "last", "like", "log", "max", "min", "prd", "select", "setenv", "sin", "sqrt", "ss", "sum", "tan", "update", "var", "wavg", "while", "within", "wsum", "xexp"), suffix=r"\b"), Operator.Word), ], "declarations": [ # Timing (r"^\\ts?", Comment.Preproc), (r"^(\\\w\s+[^/\n]*?)(/.*)", bygroups(Comment.Preproc, Comment.Single)), # Generic System Commands (r"^\\\w.*", Comment.Preproc), # Prompt (r"^[a-zA-Z]\)", Generic.Prompt), # Function Names (r"([.]?[a-zA-Z][\w.]*)(\s*)([-.~=!@#$%^&*_+|,<>?/\\:']?:)(\s*)(\{)", bygroups(Name.Function, Whitespace, Operator, Whitespace, Punctuation), "functions"), # Variable Names (r"([.]?[a-zA-Z][\w.]*)(\s*)([-.~=!@#$%^&*_+|,<>?/\\:']?:)", bygroups(Name.Variable, Whitespace, Operator)), # Functions (r"\{", Punctuation, "functions"), # Parentheses (r"\(", Punctuation, "parentheses"), # Brackets (r"\[", Punctuation, "brackets"), # Errors (r"'`([a-zA-Z][\w.]*)?", Name.Exception), # File Symbols (r"`:([a-zA-Z/][\w./]*)?", String.Symbol), # Symbols (r"`([a-zA-Z][\w.]*)?", String.Symbol), # Numbers include("numbers"), # Variable Names (r"[a-zA-Z][\w.]*", Name), # Operators (r"[-=+*#$%@!~^&:.,<>'\\|/?_]", Operator), # Punctuation (r";", Punctuation), ], "functions": [ include("root"), (r"\}", Punctuation, "#pop"), ], "parentheses": [ include("root"), (r"\)", Punctuation, "#pop"), ], "brackets": [ include("root"), (r"\]", Punctuation, "#pop"), ], "numbers": [ # Binary Values (r"[01]+b", Number.Bin), # Nulls/Infinities (r"0[nNwW][cefghijmndzuvtp]?", Number), # Timestamps ((r"(?:[0-9]{4}[.][0-9]{2}[.][0-9]{2}|[0-9]+)" "D(?:[0-9](?:[0-9](?::[0-9]{2}" "(?::[0-9]{2}(?:[.][0-9]*)?)?)?)?)?"), Literal.Date), # Datetimes ((r"[0-9]{4}[.][0-9]{2}" "(?:m|[.][0-9]{2}(?:T(?:[0-9]{2}:[0-9]{2}" "(?::[0-9]{2}(?:[.][0-9]*)?)?)?)?)"), Literal.Date), # Times (r"[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:[.][0-9]{1,3})?)?", Literal.Date), # GUIDs (r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", Number.Hex), # Byte Vectors (r"0x[0-9a-fA-F]+", Number.Hex), # Floats (r"([0-9]*[.]?[0-9]+|[0-9]+[.]?[0-9]*)[eE][+-]?[0-9]+[ef]?", Number.Float), (r"([0-9]*[.][0-9]+|[0-9]+[.][0-9]*)[ef]?", Number.Float), (r"[0-9]+[ef]", Number.Float), # Characters (r"[0-9]+c", Number), # Integers (r"[0-9]+[ihtuv]", Number.Integer), # Long Integers (r"[0-9]+[jnp]?", Number.Integer.Long), ], "comments": [ (r"[^\\]+", Comment.Multiline), (r"^\\", Comment.Multiline, "#pop"), (r"\\", Comment.Multiline), ], "strings": [ (r'[^"\\]+', String.Double), (r"\\.", String.Escape), (r'"', String.Double, "#pop"), ], }
class QLexer(KLexer): """ For `Q <https://code.kx.com/>`_ source code. """
name = "Q" aliases = ["q"] filenames = ["*.q"] version_added = '2.12'
tokens = { "root": [ (words(("aj", "aj0", "ajf", "ajf0", "all", "and", "any", "asc", "asof", "attr", "avgs", "ceiling", "cols", "count", "cross", "csv", "cut", "deltas", "desc", "differ", "distinct", "dsave", "each", "ej", "ema", "eval", "except", "fby", "fills", "first", "fkeys", "flip", "floor", "get", "group", "gtime", "hclose", "hcount", "hdel", "hsym", "iasc", "idesc", "ij", "ijf", "inter", "inv", "key", "keys", "lj", "ljf", "load", "lower", "lsq", "ltime", "ltrim", "mavg", "maxs", "mcount", "md5", "mdev", "med", "meta", "mins", "mmax", "mmin", "mmu", "mod", "msum", "neg", "next", "not", "null", "or", "over", "parse", "peach", "pj", "prds", "prior", "prev", "rand", "rank", "ratios", "raze", "read0", "read1", "reciprocal", "reval", "reverse", "rload", "rotate", "rsave", "rtrim", "save", "scan", "scov", "sdev", "set", "show", "signum", "ssr", "string", "sublist", "sums", "sv", "svar", "system", "tables", "til", "trim", "txf", "type", "uj", "ujf", "ungroup", "union", "upper", "upsert", "value", "view", "views", "vs", "where", "wj", "wj1", "ww", "xasc", "xbar", "xcol", "xcols", "xdesc", "xgroup", "xkey", "xlog", "xprev", "xrank"), suffix=r"\b"), Name.Builtin, ), inherit, ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117""" pygments.lexers.qlik ~~~~~~~~~~~~~~~~~~~~
Lexer for the qlik scripting 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, Keyword, Name, Number, Operator, \ Punctuation, String, Textfrom pygments.lexers._qlik_builtins import OPERATORS_LIST, STATEMENT_LIST, \ SCRIPT_FUNCTIONS, CONSTANT_LIST
__all__ = ["QlikLexer"]
class QlikLexer(RegexLexer): """ Lexer for qlik code, including .qvs files """
name = "Qlik" aliases = ["qlik", "qlikview", "qliksense", "qlikscript"] filenames = ["*.qvs", "*.qvw"] url = "https://qlik.com" version_added = '2.12'
flags = re.IGNORECASE
tokens = { # Handle multi-line comments "comment": [ (r"\*/", Comment.Multiline, "#pop"), (r"[^*]+", Comment.Multiline), ], # Handle numbers "numerics": [ (r"\b\d+\.\d+(e\d+)?[fd]?\b", Number.Float), (r"\b\d+\b", Number.Integer), ], # Handle variable names in things "interp": [ ( r"(\$\()(\w+)(\))", bygroups(String.Interpol, Name.Variable, String.Interpol), ), ], # Handle strings "string": [ (r"'", String, "#pop"), include("interp"), (r"[^'$]+", String), (r"\$", String), ], # "assignment": [ (r";", Punctuation, "#pop"), include("root"), ], "field_name_quote": [ (r'"', String.Symbol, "#pop"), include("interp"), (r"[^\"$]+", String.Symbol), (r"\$", String.Symbol), ], "field_name_bracket": [ (r"\]", String.Symbol, "#pop"), include("interp"), (r"[^\]$]+", String.Symbol), (r"\$", String.Symbol), ], "function": [(r"\)", Punctuation, "#pop"), include("root")], "root": [ # Whitespace and comments (r"\s+", Text.Whitespace), (r"/\*", Comment.Multiline, "comment"), (r"//.*\n", Comment.Single), # variable assignment (r"(let|set)(\s+)", bygroups(Keyword.Declaration, Text.Whitespace), "assignment"), # Word operators (words(OPERATORS_LIST["words"], prefix=r"\b", suffix=r"\b"), Operator.Word), # Statements (words(STATEMENT_LIST, suffix=r"\b"), Keyword), # Table names (r"[a-z]\w*:", Keyword.Declaration), # Constants (words(CONSTANT_LIST, suffix=r"\b"), Keyword.Constant), # Functions (words(SCRIPT_FUNCTIONS, suffix=r"(?=\s*\()"), Name.Builtin, "function"), # interpolation - e.g. $(variableName) include("interp"), # Quotes denote a field/file name (r'"', String.Symbol, "field_name_quote"), # Square brackets denote a field/file name (r"\[", String.Symbol, "field_name_bracket"), # Strings (r"'", String, "string"), # Numbers include("numerics"), # Operator symbols (words(OPERATORS_LIST["symbols"]), Operator), # Strings denoted by single quotes (r"'.+?'", String), # Words as text (r"\b\w+\b", Text), # Basic punctuation (r"[,;.()\\/]", Punctuation), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153""" pygments.lexers.qvt ~~~~~~~~~~~~~~~~~~~
Lexer for QVT Operational language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, combined, default, \ wordsfrom pygments.token import Text, Comment, Operator, Keyword, Punctuation, \ Name, String, Number
__all__ = ['QVToLexer']
class QVToLexer(RegexLexer): """ For the QVT Operational Mapping language.
Reference for implementing this: «Meta Object Facility (MOF) 2.0 Query/View/Transformation Specification», Version 1.1 - January 2011 (https://www.omg.org/spec/QVT/1.1/), see §8.4, «Concrete Syntax» in particular.
Notable tokens assignments:
- Name.Class is assigned to the identifier following any of the following keywords: metamodel, class, exception, primitive, enum, transformation or library
- Name.Function is assigned to the names of mappings and queries
- Name.Builtin.Pseudo is assigned to the pre-defined variables 'this', 'self' and 'result'. """ # With obvious borrowings & inspiration from the Java, Python and C lexers
name = 'QVTO' aliases = ['qvto', 'qvt'] filenames = ['*.qvto'] url = 'https://www.omg.org/spec/QVT/1.1' version_added = ''
tokens = { 'root': [ (r'\n', Text), (r'[^\S\n]+', Text), (r'(--|//)(\s*)(directive:)?(.*)$', bygroups(Comment, Comment, Comment.Preproc, Comment)), # Uncomment the following if you want to distinguish between # '/*' and '/**', à la javadoc # (r'/[*]{2}(.|\n)*?[*]/', Comment.Multiline), (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'\\\n', Text), (r'(and|not|or|xor|##?)\b', Operator.Word), (r'(:{1,2}=|[-+]=)\b', Operator.Word), (r'(@|<<|>>)\b', Keyword), # stereotypes (r'!=|<>|==|=|!->|->|>=|<=|[.]{3}|[+/*%=<>&|.~]', Operator), (r'[]{}:(),;[]', Punctuation), (r'(true|false|unlimited|null)\b', Keyword.Constant), (r'(this|self|result)\b', Name.Builtin.Pseudo), (r'(var)\b', Keyword.Declaration), (r'(from|import)\b', Keyword.Namespace, 'fromimport'), (r'(metamodel|class|exception|primitive|enum|transformation|' r'library)(\s+)(\w+)', bygroups(Keyword.Word, Text, Name.Class)), (r'(exception)(\s+)(\w+)', bygroups(Keyword.Word, Text, Name.Exception)), (r'(main)\b', Name.Function), (r'(mapping|helper|query)(\s+)', bygroups(Keyword.Declaration, Text), 'operation'), (r'(assert)(\s+)\b', bygroups(Keyword, Text), 'assert'), (r'(Bag|Collection|Dict|OrderedSet|Sequence|Set|Tuple|List)\b', Keyword.Type), include('keywords'), ('"', String, combined('stringescape', 'dqs')), ("'", String, combined('stringescape', 'sqs')), include('name'), include('numbers'), # (r'([a-zA-Z_]\w*)(::)([a-zA-Z_]\w*)', # bygroups(Text, Text, Text)), ],
'fromimport': [ (r'(?:[ \t]|\\\n)+', Text), (r'[a-zA-Z_][\w.]*', Name.Namespace), default('#pop'), ],
'operation': [ (r'::', Text), (r'(.*::)([a-zA-Z_]\w*)([ \t]*)(\()', bygroups(Text, Name.Function, Text, Punctuation), '#pop') ],
'assert': [ (r'(warning|error|fatal)\b', Keyword, '#pop'), default('#pop'), # all else: go back ],
'keywords': [ (words(( 'abstract', 'access', 'any', 'assert', 'blackbox', 'break', 'case', 'collect', 'collectNested', 'collectOne', 'collectselect', 'collectselectOne', 'composes', 'compute', 'configuration', 'constructor', 'continue', 'datatype', 'default', 'derived', 'disjuncts', 'do', 'elif', 'else', 'end', 'endif', 'except', 'exists', 'extends', 'forAll', 'forEach', 'forOne', 'from', 'if', 'implies', 'in', 'inherits', 'init', 'inout', 'intermediate', 'invresolve', 'invresolveIn', 'invresolveone', 'invresolveoneIn', 'isUnique', 'iterate', 'late', 'let', 'literal', 'log', 'map', 'merges', 'modeltype', 'new', 'object', 'one', 'ordered', 'out', 'package', 'population', 'property', 'raise', 'readonly', 'references', 'refines', 'reject', 'resolve', 'resolveIn', 'resolveone', 'resolveoneIn', 'return', 'select', 'selectOne', 'sortedBy', 'static', 'switch', 'tag', 'then', 'try', 'typedef', 'unlimited', 'uses', 'when', 'where', 'while', 'with', 'xcollect', 'xmap', 'xselect'), suffix=r'\b'), Keyword), ],
# There is no need to distinguish between String.Single and # String.Double: 'strings' is factorised for 'dqs' and 'sqs' 'strings': [ (r'[^\\\'"\n]+', String), # quotes, percents and backslashes must be parsed one at a time (r'[\'"\\]', String), ], 'stringescape': [ (r'\\([\\btnfr"\']|u[0-3][0-7]{2}|u[0-7]{1,2})', String.Escape) ], 'dqs': [ # double-quoted string (r'"', String, '#pop'), (r'\\\\|\\"', String.Escape), include('strings') ], 'sqs': [ # single-quoted string (r"'", String, '#pop'), (r"\\\\|\\'", String.Escape), include('strings') ], 'name': [ (r'[a-zA-Z_]\w*', Name), ], # numbers: excerpt taken from the python lexer 'numbers': [ (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), (r'\d+[eE][+-]?[0-9]+', Number.Float), (r'\d+', Number.Integer) ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196""" pygments.lexers.r ~~~~~~~~~~~~~~~~~
Lexers for the R/S languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, include, do_insertionsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace
__all__ = ['RConsoleLexer', 'SLexer', 'RdLexer']
line_re = re.compile('.*?\n')
class RConsoleLexer(Lexer): """ For R console transcripts or R CMD BATCH output files. """
name = 'RConsole' aliases = ['rconsole', 'rout'] filenames = ['*.Rout'] url = 'https://www.r-project.org' version_added = '' _example = "rconsole/r-console-transcript.Rout"
def get_tokens_unprocessed(self, text): slexer = SLexer(**self.options)
current_code_block = '' insertions = []
for match in line_re.finditer(text): line = match.group() if line.startswith('>') or line.startswith('+'): # Colorize the prompt as such, # then put rest of line into current_code_block insertions.append((len(current_code_block), [(0, Generic.Prompt, line[:2])])) current_code_block += line[2:] else: # We have reached a non-prompt line! # If we have stored prompt lines, need to process them first. if current_code_block: # Weave together the prompts and highlight code. yield from do_insertions( insertions, slexer.get_tokens_unprocessed(current_code_block)) # Reset vars for next code block. current_code_block = '' insertions = [] # Now process the actual line itself, this is output from R. yield match.start(), Generic.Output, line
# If we happen to end on a code block with nothing after it, need to # process the last code block. This is neither elegant nor DRY so # should be changed. if current_code_block: yield from do_insertions( insertions, slexer.get_tokens_unprocessed(current_code_block))
class SLexer(RegexLexer): """ For S, S-plus, and R source code. """
name = 'S' aliases = ['splus', 's', 'r'] filenames = ['*.S', '*.R', '.Rhistory', '.Rprofile', '.Renviron'] mimetypes = ['text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r', 'text/x-R', 'text/x-r-history', 'text/x-r-profile'] url = 'https://www.r-project.org' version_added = '0.10'
valid_name = r'`[^`\\]*(?:\\.[^`\\]*)*`|(?:[a-zA-Z]|\.[A-Za-z_.])[\w.]*|\.' tokens = { 'comments': [ (r'#.*$', Comment.Single), ], 'valid_name': [ (valid_name, Name), ], 'function_name': [ (rf'({valid_name})\s*(?=\()', Name.Function), ], 'punctuation': [ (r'\[{1,2}|\]{1,2}|\(|\)|;|,', Punctuation), ], 'keywords': [ (r'(if|else|for|while|repeat|in|next|break|return|switch|function)' r'(?![\w.])', Keyword.Reserved), ], 'operators': [ (r'<<?-|->>?|-|==|<=|>=|\|>|<|>|&&?|!=|\|\|?|\?', Operator), (r'\*|\+|\^|/|!|%[^%]*%|=|~|\$|@|:{1,3}', Operator), ], 'builtin_symbols': [ (r'(NULL|NA(_(integer|real|complex|character)_)?|' r'letters|LETTERS|Inf|TRUE|FALSE|NaN|pi|\.\.(\.|[0-9]+))' r'(?![\w.])', Keyword.Constant), (r'(T|F)\b', Name.Builtin.Pseudo), ], 'numbers': [ # hex number (r'0[xX][a-fA-F0-9]+([pP][0-9]+)?[Li]?', Number.Hex), # decimal number (r'[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)([eE][+-]?[0-9]+)?[Li]?', Number), ], 'statements': [ include('comments'), # whitespaces (r'\s+', Whitespace), (r'\'', String, 'string_squote'), (r'\"', String, 'string_dquote'), include('builtin_symbols'), include('keywords'), include('function_name'), include('valid_name'), include('numbers'), include('punctuation'), include('operators'), ], 'root': [ # calls: include('statements'), # blocks: (r'\{|\}', Punctuation), # (r'\{', Punctuation, 'block'), (r'.', Text), ], # 'block': [ # include('statements'), # ('\{', Punctuation, '#push'), # ('\}', Punctuation, '#pop') # ], 'string_squote': [ (r'([^\'\\]|\\.)*\'', String, '#pop'), ], 'string_dquote': [ (r'([^"\\]|\\.)*"', String, '#pop'), ], }
def analyse_text(text): if re.search(r'[a-z0-9_\])\s]<-(?!-)', text): return 0.11
class RdLexer(RegexLexer): """ Pygments Lexer for R documentation (Rd) files
This is a very minimal implementation, highlighting little more than the macros. A description of Rd syntax is found in `Writing R Extensions <http://cran.r-project.org/doc/manuals/R-exts.html>`_ and `Parsing Rd files <http://developer.r-project.org/parseRd.pdf>`_. """ name = 'Rd' aliases = ['rd'] filenames = ['*.Rd'] mimetypes = ['text/x-r-doc'] url = 'http://cran.r-project.org/doc/manuals/R-exts.html' version_added = '1.6'
# To account for verbatim / LaTeX-like / and R-like areas # would require parsing. tokens = { 'root': [ # catch escaped brackets and percent sign (r'\\[\\{}%]', String.Escape), # comments (r'%.*$', Comment), # special macros with no arguments (r'\\(?:cr|l?dots|R|tab)\b', Keyword.Constant), # macros (r'\\[a-zA-Z]+\b', Keyword), # special preprocessor macros (r'^\s*#(?:ifn?def|endif).*\b', Comment.Preproc), # non-escaped brackets (r'[{}]', Name.Builtin), # everything else (r'[^\\%\n{}]+', Text), (r'.', Text), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468""" pygments.lexers.rdf ~~~~~~~~~~~~~~~~~~~
Lexers for semantic web and RDF query languages and markup.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroups, defaultfrom pygments.token import Keyword, Punctuation, String, Number, Operator, \ Generic, Whitespace, Name, Literal, Comment, Text
__all__ = ['SparqlLexer', 'TurtleLexer', 'ShExCLexer']
class SparqlLexer(RegexLexer): """ Lexer for SPARQL query language. """ name = 'SPARQL' aliases = ['sparql'] filenames = ['*.rq', '*.sparql'] mimetypes = ['application/sparql-query'] url = 'https://www.w3.org/TR/sparql11-query' version_added = '2.0'
# character group definitions ::
PN_CHARS_BASE_GRP = ('a-zA-Z' '\u00c0-\u00d6' '\u00d8-\u00f6' '\u00f8-\u02ff' '\u0370-\u037d' '\u037f-\u1fff' '\u200c-\u200d' '\u2070-\u218f' '\u2c00-\u2fef' '\u3001-\ud7ff' '\uf900-\ufdcf' '\ufdf0-\ufffd')
PN_CHARS_U_GRP = (PN_CHARS_BASE_GRP + '_')
PN_CHARS_GRP = (PN_CHARS_U_GRP + r'\-' + r'0-9' + '\u00b7' + '\u0300-\u036f' + '\u203f-\u2040')
HEX_GRP = '0-9A-Fa-f'
PN_LOCAL_ESC_CHARS_GRP = r' _~.\-!$&"()*+,;=/?#@%'
# terminal productions ::
PN_CHARS_BASE = '[' + PN_CHARS_BASE_GRP + ']'
PN_CHARS_U = '[' + PN_CHARS_U_GRP + ']'
PN_CHARS = '[' + PN_CHARS_GRP + ']'
HEX = '[' + HEX_GRP + ']'
PN_LOCAL_ESC_CHARS = '[' + PN_LOCAL_ESC_CHARS_GRP + ']'
IRIREF = r'<(?:[^<>"{}|^`\\\x00-\x20])*>'
BLANK_NODE_LABEL = '_:[0-9' + PN_CHARS_U_GRP + '](?:[' + PN_CHARS_GRP + \ '.]*' + PN_CHARS + ')?'
PN_PREFIX = PN_CHARS_BASE + '(?:[' + PN_CHARS_GRP + '.]*' + PN_CHARS + ')?'
VARNAME = '[0-9' + PN_CHARS_U_GRP + '][' + PN_CHARS_U_GRP + \ '0-9\u00b7\u0300-\u036f\u203f-\u2040]*'
PERCENT = '%' + HEX + HEX
PN_LOCAL_ESC = r'\\' + PN_LOCAL_ESC_CHARS
PLX = '(?:' + PERCENT + ')|(?:' + PN_LOCAL_ESC + ')'
PN_LOCAL = ('(?:[' + PN_CHARS_U_GRP + ':0-9' + ']|' + PLX + ')' + '(?:(?:[' + PN_CHARS_GRP + '.:]|' + PLX + ')*(?:[' + PN_CHARS_GRP + ':]|' + PLX + '))?')
EXPONENT = r'[eE][+-]?\d+'
# Lexer token definitions ::
tokens = { 'root': [ (r'\s+', Text), # keywords :: (r'(?i)(select|construct|describe|ask|where|filter|group\s+by|minus|' r'distinct|reduced|from\s+named|from|order\s+by|desc|asc|limit|' r'offset|values|bindings|load|into|clear|drop|create|add|move|copy|' r'insert\s+data|delete\s+data|delete\s+where|with|delete|insert|' r'using\s+named|using|graph|default|named|all|optional|service|' r'silent|bind|undef|union|not\s+in|in|as|having|to|prefix|base)\b', Keyword), (r'(a)\b', Keyword), # IRIs :: ('(' + IRIREF + ')', Name.Label), # blank nodes :: ('(' + BLANK_NODE_LABEL + ')', Name.Label), # # variables :: ('[?$]' + VARNAME, Name.Variable), # prefixed names :: (r'(' + PN_PREFIX + r')?(\:)(' + PN_LOCAL + r')?', bygroups(Name.Namespace, Punctuation, Name.Tag)), # function names :: (r'(?i)(str|lang|langmatches|datatype|bound|iri|uri|bnode|rand|abs|' r'ceil|floor|round|concat|strlen|ucase|lcase|encode_for_uri|' r'contains|strstarts|strends|strbefore|strafter|year|month|day|' r'hours|minutes|seconds|timezone|tz|now|uuid|struuid|md5|sha1|sha256|sha384|' r'sha512|coalesce|if|strlang|strdt|sameterm|isiri|isuri|isblank|' r'isliteral|isnumeric|regex|substr|replace|exists|not\s+exists|' r'count|sum|min|max|avg|sample|group_concat|separator)\b', Name.Function), # boolean literals :: (r'(true|false)', Keyword.Constant), # double literals :: (r'[+\-]?(\d+\.\d*' + EXPONENT + r'|\.?\d+' + EXPONENT + ')', Number.Float), # decimal literals :: (r'[+\-]?(\d+\.\d*|\.\d+)', Number.Float), # integer literals :: (r'[+\-]?\d+', Number.Integer), # operators :: (r'(\|\||&&|=|\*|\-|\+|/|!=|<=|>=|!|<|>)', Operator), # punctuation characters :: (r'[(){}.;,:^\[\]]', Punctuation), # line comments :: (r'#[^\n]*', Comment), # strings :: (r'"""', String, 'triple-double-quoted-string'), (r'"', String, 'single-double-quoted-string'), (r"'''", String, 'triple-single-quoted-string'), (r"'", String, 'single-single-quoted-string'), ], 'triple-double-quoted-string': [ (r'"""', String, 'end-of-string'), (r'[^\\]+', String), (r'\\', String, 'string-escape'), ], 'single-double-quoted-string': [ (r'"', String, 'end-of-string'), (r'[^"\\\n]+', String), (r'\\', String, 'string-escape'), ], 'triple-single-quoted-string': [ (r"'''", String, 'end-of-string'), (r'[^\\]+', String), (r'\\', String.Escape, 'string-escape'), ], 'single-single-quoted-string': [ (r"'", String, 'end-of-string'), (r"[^'\\\n]+", String), (r'\\', String, 'string-escape'), ], 'string-escape': [ (r'u' + HEX + '{4}', String.Escape, '#pop'), (r'U' + HEX + '{8}', String.Escape, '#pop'), (r'.', String.Escape, '#pop'), ], 'end-of-string': [ (r'(@)([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)', bygroups(Operator, Name.Function), '#pop:2'), (r'\^\^', Operator, '#pop:2'), default('#pop:2'), ], }
class TurtleLexer(RegexLexer): """ Lexer for Turtle data language. """ name = 'Turtle' aliases = ['turtle'] filenames = ['*.ttl'] mimetypes = ['text/turtle', 'application/x-turtle'] url = 'https://www.w3.org/TR/turtle' version_added = '2.1'
# character group definitions :: PN_CHARS_BASE_GRP = ('a-zA-Z' '\u00c0-\u00d6' '\u00d8-\u00f6' '\u00f8-\u02ff' '\u0370-\u037d' '\u037f-\u1fff' '\u200c-\u200d' '\u2070-\u218f' '\u2c00-\u2fef' '\u3001-\ud7ff' '\uf900-\ufdcf' '\ufdf0-\ufffd')
PN_CHARS_U_GRP = (PN_CHARS_BASE_GRP + '_')
PN_CHARS_GRP = (PN_CHARS_U_GRP + r'\-' + r'0-9' + '\u00b7' + '\u0300-\u036f' + '\u203f-\u2040')
PN_CHARS = '[' + PN_CHARS_GRP + ']'
PN_CHARS_BASE = '[' + PN_CHARS_BASE_GRP + ']'
PN_PREFIX = PN_CHARS_BASE + '(?:[' + PN_CHARS_GRP + '.]*' + PN_CHARS + ')?'
HEX_GRP = '0-9A-Fa-f'
HEX = '[' + HEX_GRP + ']'
PERCENT = '%' + HEX + HEX
PN_LOCAL_ESC_CHARS_GRP = r' _~.\-!$&"()*+,;=/?#@%'
PN_LOCAL_ESC_CHARS = '[' + PN_LOCAL_ESC_CHARS_GRP + ']'
PN_LOCAL_ESC = r'\\' + PN_LOCAL_ESC_CHARS
PLX = '(?:' + PERCENT + ')|(?:' + PN_LOCAL_ESC + ')'
PN_LOCAL = ('(?:[' + PN_CHARS_U_GRP + ':0-9' + ']|' + PLX + ')' + '(?:(?:[' + PN_CHARS_GRP + '.:]|' + PLX + ')*(?:[' + PN_CHARS_GRP + ':]|' + PLX + '))?')
patterns = { 'PNAME_NS': r'((?:[a-zA-Z][\w-]*)?\:)', # Simplified character range 'IRIREF': r'(<[^<>"{}|^`\\\x00-\x20]*>)' }
tokens = { 'root': [ (r'\s+', Text),
# Base / prefix (r'(@base|BASE)(\s+){IRIREF}(\s*)(\.?)'.format(**patterns), bygroups(Keyword, Whitespace, Name.Variable, Whitespace, Punctuation)), (r'(@prefix|PREFIX)(\s+){PNAME_NS}(\s+){IRIREF}(\s*)(\.?)'.format(**patterns), bygroups(Keyword, Whitespace, Name.Namespace, Whitespace, Name.Variable, Whitespace, Punctuation)),
# The shorthand predicate 'a' (r'(?<=\s)a(?=\s)', Keyword.Type),
# IRIREF (r'{IRIREF}'.format(**patterns), Name.Variable),
# PrefixedName (r'(' + PN_PREFIX + r')?(\:)(' + PN_LOCAL + r')?', bygroups(Name.Namespace, Punctuation, Name.Tag)),
# BlankNodeLabel (r'(_)(:)([' + PN_CHARS_U_GRP + r'0-9]([' + PN_CHARS_GRP + r'.]*' + PN_CHARS + ')?)', bygroups(Name.Namespace, Punctuation, Name.Tag)),
# Comment (r'#([^\n]+|$)', Comment),
(r'\b(true|false)\b', Literal), (r'[+\-]?\d*\.\d+', Number.Float), (r'[+\-]?\d*(:?\.\d+)?E[+\-]?\d+', Number.Float), (r'[+\-]?\d+', Number.Integer), (r'[\[\](){}.;,:^]', Punctuation),
(r'"""', String, 'triple-double-quoted-string'), (r'"', String, 'single-double-quoted-string'), (r"'''", String, 'triple-single-quoted-string'), (r"'", String, 'single-single-quoted-string'), ], 'triple-double-quoted-string': [ (r'"""', String, 'end-of-string'), (r'[^\\]+(?=""")', String), (r'\\', String, 'string-escape'), ], 'single-double-quoted-string': [ (r'"', String, 'end-of-string'), (r'[^"\\\n]+', String), (r'\\', String, 'string-escape'), ], 'triple-single-quoted-string': [ (r"'''", String, 'end-of-string'), (r"[^\\]+(?=''')", String), (r'\\', String, 'string-escape'), ], 'single-single-quoted-string': [ (r"'", String, 'end-of-string'), (r"[^'\\\n]+", String), (r'\\', String, 'string-escape'), ], 'string-escape': [ (r'.', String, '#pop'), ], 'end-of-string': [ (r'(@)([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)', bygroups(Operator, Generic.Emph), '#pop:2'),
(r'(\^\^){IRIREF}'.format(**patterns), bygroups(Operator, Generic.Emph), '#pop:2'),
default('#pop:2'),
], }
# Turtle and Tera Term macro files share the same file extension # but each has a recognizable and distinct syntax. def analyse_text(text): for t in ('@base ', 'BASE ', '@prefix ', 'PREFIX '): if re.search(rf'^\s*{t}', text): return 0.80
class ShExCLexer(RegexLexer): """ Lexer for ShExC shape expressions language syntax. """ name = 'ShExC' aliases = ['shexc', 'shex'] filenames = ['*.shex'] mimetypes = ['text/shex'] url = 'https://shex.io/shex-semantics/#shexc' version_added = ''
# character group definitions ::
PN_CHARS_BASE_GRP = ('a-zA-Z' '\u00c0-\u00d6' '\u00d8-\u00f6' '\u00f8-\u02ff' '\u0370-\u037d' '\u037f-\u1fff' '\u200c-\u200d' '\u2070-\u218f' '\u2c00-\u2fef' '\u3001-\ud7ff' '\uf900-\ufdcf' '\ufdf0-\ufffd')
PN_CHARS_U_GRP = (PN_CHARS_BASE_GRP + '_')
PN_CHARS_GRP = (PN_CHARS_U_GRP + r'\-' + r'0-9' + '\u00b7' + '\u0300-\u036f' + '\u203f-\u2040')
HEX_GRP = '0-9A-Fa-f'
PN_LOCAL_ESC_CHARS_GRP = r"_~.\-!$&'()*+,;=/?#@%"
# terminal productions ::
PN_CHARS_BASE = '[' + PN_CHARS_BASE_GRP + ']'
PN_CHARS_U = '[' + PN_CHARS_U_GRP + ']'
PN_CHARS = '[' + PN_CHARS_GRP + ']'
HEX = '[' + HEX_GRP + ']'
PN_LOCAL_ESC_CHARS = '[' + PN_LOCAL_ESC_CHARS_GRP + ']'
UCHAR_NO_BACKSLASH = '(?:u' + HEX + '{4}|U' + HEX + '{8})'
UCHAR = r'\\' + UCHAR_NO_BACKSLASH
IRIREF = r'<(?:[^\x00-\x20<>"{}|^`\\]|' + UCHAR + ')*>'
BLANK_NODE_LABEL = '_:[0-9' + PN_CHARS_U_GRP + '](?:[' + PN_CHARS_GRP + \ '.]*' + PN_CHARS + ')?'
PN_PREFIX = PN_CHARS_BASE + '(?:[' + PN_CHARS_GRP + '.]*' + PN_CHARS + ')?'
PERCENT = '%' + HEX + HEX
PN_LOCAL_ESC = r'\\' + PN_LOCAL_ESC_CHARS
PLX = '(?:' + PERCENT + ')|(?:' + PN_LOCAL_ESC + ')'
PN_LOCAL = ('(?:[' + PN_CHARS_U_GRP + ':0-9' + ']|' + PLX + ')' + '(?:(?:[' + PN_CHARS_GRP + '.:]|' + PLX + ')*(?:[' + PN_CHARS_GRP + ':]|' + PLX + '))?')
EXPONENT = r'[eE][+-]?\d+'
# Lexer token definitions ::
tokens = { 'root': [ (r'\s+', Text), # keywords :: (r'(?i)(base|prefix|start|external|' r'literal|iri|bnode|nonliteral|length|minlength|maxlength|' r'mininclusive|minexclusive|maxinclusive|maxexclusive|' r'totaldigits|fractiondigits|' r'closed|extra)\b', Keyword), (r'(a)\b', Keyword), # IRIs :: ('(' + IRIREF + ')', Name.Label), # blank nodes :: ('(' + BLANK_NODE_LABEL + ')', Name.Label), # prefixed names :: (r'(' + PN_PREFIX + r')?(\:)(' + PN_LOCAL + ')?', bygroups(Name.Namespace, Punctuation, Name.Tag)), # boolean literals :: (r'(true|false)', Keyword.Constant), # double literals :: (r'[+\-]?(\d+\.\d*' + EXPONENT + r'|\.?\d+' + EXPONENT + ')', Number.Float), # decimal literals :: (r'[+\-]?(\d+\.\d*|\.\d+)', Number.Float), # integer literals :: (r'[+\-]?\d+', Number.Integer), # operators :: (r'[@|$&=*+?^\-~]', Operator), # operator keywords :: (r'(?i)(and|or|not)\b', Operator.Word), # punctuation characters :: (r'[(){}.;,:^\[\]]', Punctuation), # line comments :: (r'#[^\n]*', Comment), # strings :: (r'"""', String, 'triple-double-quoted-string'), (r'"', String, 'single-double-quoted-string'), (r"'''", String, 'triple-single-quoted-string'), (r"'", String, 'single-single-quoted-string'), ], 'triple-double-quoted-string': [ (r'"""', String, 'end-of-string'), (r'[^\\]+', String), (r'\\', String, 'string-escape'), ], 'single-double-quoted-string': [ (r'"', String, 'end-of-string'), (r'[^"\\\n]+', String), (r'\\', String, 'string-escape'), ], 'triple-single-quoted-string': [ (r"'''", String, 'end-of-string'), (r'[^\\]+', String), (r'\\', String.Escape, 'string-escape'), ], 'single-single-quoted-string': [ (r"'", String, 'end-of-string'), (r"[^'\\\n]+", String), (r'\\', String, 'string-escape'), ], 'string-escape': [ (UCHAR_NO_BACKSLASH, String.Escape, '#pop'), (r'.', String.Escape, '#pop'), ], 'end-of-string': [ (r'(@)([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)', bygroups(Operator, Name.Function), '#pop:2'), (r'\^\^', Operator, '#pop:2'), default('#pop:2'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419""" pygments.lexers.rebol ~~~~~~~~~~~~~~~~~~~~~
Lexers for the REBOL and 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, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Generic, Whitespace
__all__ = ['RebolLexer', 'RedLexer']
class RebolLexer(RegexLexer): """ A REBOL lexer. """ name = 'REBOL' aliases = ['rebol'] filenames = ['*.r', '*.r3', '*.reb'] mimetypes = ['text/x-rebol'] url = 'http://www.rebol.com' version_added = '1.1'
flags = re.IGNORECASE | re.MULTILINE
escape_re = r'(?:\^\([0-9a-f]{1,4}\)*)'
def word_callback(lexer, match): word = match.group()
if re.match(".*:$", word): yield match.start(), Generic.Subheading, word elif re.match( r'(native|alias|all|any|as-string|as-binary|bind|bound\?|case|' r'catch|checksum|comment|debase|dehex|exclude|difference|disarm|' r'either|else|enbase|foreach|remove-each|form|free|get|get-env|if|' r'in|intersect|loop|minimum-of|maximum-of|mold|new-line|' r'new-line\?|not|now|prin|print|reduce|compose|construct|repeat|' r'reverse|save|script\?|set|shift|switch|throw|to-hex|trace|try|' r'type\?|union|unique|unless|unprotect|unset|until|use|value\?|' r'while|compress|decompress|secure|open|close|read|read-io|' r'write-io|write|update|query|wait|input\?|exp|log-10|log-2|' r'log-e|square-root|cosine|sine|tangent|arccosine|arcsine|' r'arctangent|protect|lowercase|uppercase|entab|detab|connected\?|' r'browse|launch|stats|get-modes|set-modes|to-local-file|' r'to-rebol-file|encloak|decloak|create-link|do-browser|bind\?|' r'hide|draw|show|size-text|textinfo|offset-to-caret|' r'caret-to-offset|local-request-file|rgb-to-hsv|hsv-to-rgb|' r'crypt-strength\?|dh-make-key|dh-generate-key|dh-compute-key|' r'dsa-make-key|dsa-generate-key|dsa-make-signature|' r'dsa-verify-signature|rsa-make-key|rsa-generate-key|' r'rsa-encrypt)$', word): yield match.start(), Name.Builtin, word elif re.match( r'(add|subtract|multiply|divide|remainder|power|and~|or~|xor~|' r'minimum|maximum|negate|complement|absolute|random|head|tail|' r'next|back|skip|at|pick|first|second|third|fourth|fifth|sixth|' r'seventh|eighth|ninth|tenth|last|path|find|select|make|to|copy\*|' r'insert|remove|change|poke|clear|trim|sort|min|max|abs|cp|' r'copy)$', word): yield match.start(), Name.Function, word elif re.match( r'(error|source|input|license|help|install|echo|Usage|with|func|' r'throw-on-error|function|does|has|context|probe|\?\?|as-pair|' r'mod|modulo|round|repend|about|set-net|append|join|rejoin|reform|' r'remold|charset|array|replace|move|extract|forskip|forall|alter|' r'first+|also|take|for|forever|dispatch|attempt|what-dir|' r'change-dir|clean-path|list-dir|dirize|rename|split-path|delete|' r'make-dir|delete-dir|in-dir|confirm|dump-obj|upgrade|what|' r'build-tag|process-source|build-markup|decode-cgi|read-cgi|' r'write-user|save-user|set-user-name|protect-system|parse-xml|' r'cvs-date|cvs-version|do-boot|get-net-info|desktop|layout|' r'scroll-para|get-face|alert|set-face|uninstall|unfocus|' r'request-dir|center-face|do-events|net-error|decode-url|' r'parse-header|parse-header-date|parse-email-addrs|import-email|' r'send|build-attach-body|resend|show-popup|hide-popup|open-events|' r'find-key-face|do-face|viewtop|confine|find-window|' r'insert-event-func|remove-event-func|inform|dump-pane|dump-face|' r'flag-face|deflag-face|clear-fields|read-net|vbug|path-thru|' r'read-thru|load-thru|do-thru|launch-thru|load-image|' r'request-download|do-face-alt|set-font|set-para|get-style|' r'set-style|make-face|stylize|choose|hilight-text|hilight-all|' r'unlight-text|focus|scroll-drag|clear-face|reset-face|scroll-face|' r'resize-face|load-stock|load-stock-block|notify|request|flash|' r'request-color|request-pass|request-text|request-list|' r'request-date|request-file|dbug|editor|link-relative-path|' r'emailer|parse-error)$', word): yield match.start(), Keyword.Namespace, word elif re.match( r'(halt|quit|do|load|q|recycle|call|run|ask|parse|view|unview|' r'return|exit|break)$', word): yield match.start(), Name.Exception, word elif re.match('REBOL$', word): yield match.start(), Generic.Heading, word elif re.match("to-.*", word): yield match.start(), Keyword, word elif re.match(r'(\+|-|\*|/|//|\*\*|and|or|xor|=\?|=|==|<>|<|>|<=|>=)$', word): yield match.start(), Operator, word elif re.match(r".*\?$", word): yield match.start(), Keyword, word elif re.match(r".*\!$", word): yield match.start(), Keyword.Type, word elif re.match("'.*", word): yield match.start(), Name.Variable.Instance, word # lit-word elif re.match("#.*", word): yield match.start(), Name.Label, word # issue elif re.match("%.*", word): yield match.start(), Name.Decorator, word # file else: yield match.start(), Name.Variable, word
tokens = { 'root': [ (r'\s+', Text), (r'#"', String.Char, 'char'), (r'#\{[0-9a-f]*\}', Number.Hex), (r'2#\{', Number.Hex, 'bin2'), (r'64#\{[0-9a-z+/=\s]*\}', Number.Hex), (r'"', String, 'string'), (r'\{', String, 'string2'), (r';#+.*\n', Comment.Special), (r';\*+.*\n', Comment.Preproc), (r';.*\n', Comment), (r'%"', Name.Decorator, 'stringFile'), (r'%[^(^{")\s\[\]]+', Name.Decorator), (r'[+-]?([a-z]{1,3})?\$\d+(\.\d+)?', Number.Float), # money (r'[+-]?\d+\:\d+(\:\d+)?(\.\d+)?', String.Other), # time (r'\d+[\-/][0-9a-z]+[\-/]\d+(\/\d+\:\d+((\:\d+)?' r'([.\d+]?([+-]?\d+:\d+)?)?)?)?', String.Other), # date (r'\d+(\.\d+)+\.\d+', Keyword.Constant), # tuple (r'\d+X\d+', Keyword.Constant), # pair (r'[+-]?\d+(\'\d+)?([.,]\d*)?E[+-]?\d+', Number.Float), (r'[+-]?\d+(\'\d+)?[.,]\d*', Number.Float), (r'[+-]?\d+(\'\d+)?', Number), (r'[\[\]()]', Generic.Strong), (r'[a-z]+[^(^{"\s:)]*://[^(^{"\s)]*', Name.Decorator), # url (r'mailto:[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator), # url (r'[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator), # email (r'comment\s"', Comment, 'commentString1'), (r'comment\s\{', Comment, 'commentString2'), (r'comment\s\[', Comment, 'commentBlock'), (r'comment\s[^(\s{"\[]+', Comment), (r'/[^(^{")\s/[\]]*', Name.Attribute), (r'([^(^{")\s/[\]]+)(?=[:({"\s/\[\]])', word_callback), (r'<[\w:.-]*>', Name.Tag), (r'<[^(<>\s")]+', Name.Tag, 'tag'), (r'([^(^{")\s]+)', Text), ], 'string': [ (r'[^(^")]+', String), (escape_re, String.Escape), (r'[(|)]+', String), (r'\^.', String.Escape), (r'"', String, '#pop'), ], 'string2': [ (r'[^(^{})]+', String), (escape_re, String.Escape), (r'[(|)]+', String), (r'\^.', String.Escape), (r'\{', String, '#push'), (r'\}', String, '#pop'), ], 'stringFile': [ (r'[^(^")]+', Name.Decorator), (escape_re, Name.Decorator), (r'\^.', Name.Decorator), (r'"', Name.Decorator, '#pop'), ], 'char': [ (escape_re + '"', String.Char, '#pop'), (r'\^."', String.Char, '#pop'), (r'."', String.Char, '#pop'), ], 'tag': [ (escape_re, Name.Tag), (r'"', Name.Tag, 'tagString'), (r'[^(<>\r\n")]+', Name.Tag), (r'>', Name.Tag, '#pop'), ], 'tagString': [ (r'[^(^")]+', Name.Tag), (escape_re, Name.Tag), (r'[(|)]+', Name.Tag), (r'\^.', Name.Tag), (r'"', Name.Tag, '#pop'), ], 'tuple': [ (r'(\d+\.)+', Keyword.Constant), (r'\d+', Keyword.Constant, '#pop'), ], 'bin2': [ (r'\s+', Number.Hex), (r'([01]\s*){8}', Number.Hex), (r'\}', Number.Hex, '#pop'), ], 'commentString1': [ (r'[^(^")]+', Comment), (escape_re, Comment), (r'[(|)]+', Comment), (r'\^.', Comment), (r'"', Comment, '#pop'), ], 'commentString2': [ (r'[^(^{})]+', Comment), (escape_re, Comment), (r'[(|)]+', Comment), (r'\^.', Comment), (r'\{', Comment, '#push'), (r'\}', Comment, '#pop'), ], 'commentBlock': [ (r'\[', Comment, '#push'), (r'\]', Comment, '#pop'), (r'"', Comment, "commentString1"), (r'\{', Comment, "commentString2"), (r'[^(\[\]"{)]+', Comment), ], }
def analyse_text(text): """ Check if code contains REBOL header and so it probably not R code """ if re.match(r'^\s*REBOL\s*\[', text, re.IGNORECASE): # The code starts with REBOL header return 1.0 elif re.search(r'\s*REBOL\s*\[', text, re.IGNORECASE): # The code contains REBOL header but also some text before it return 0.5
class RedLexer(RegexLexer): """ A Red-language lexer. """ name = 'Red' aliases = ['red', 'red/system'] filenames = ['*.red', '*.reds'] mimetypes = ['text/x-red', 'text/x-red-system'] url = 'https://www.red-lang.org' version_added = '2.0'
flags = re.IGNORECASE | re.MULTILINE
escape_re = r'(?:\^\([0-9a-f]{1,4}\)*)'
def word_callback(lexer, match): word = match.group()
if re.match(".*:$", word): yield match.start(), Generic.Subheading, word elif re.match(r'(if|unless|either|any|all|while|until|loop|repeat|' r'foreach|forall|func|function|does|has|switch|' r'case|reduce|compose|get|set|print|prin|equal\?|' r'not-equal\?|strict-equal\?|lesser\?|greater\?|lesser-or-equal\?|' r'greater-or-equal\?|same\?|not|type\?|stats|' r'bind|union|replace|charset|routine)$', word): yield match.start(), Name.Builtin, word elif re.match(r'(make|random|reflect|to|form|mold|absolute|add|divide|multiply|negate|' r'power|remainder|round|subtract|even\?|odd\?|and~|complement|or~|xor~|' r'append|at|back|change|clear|copy|find|head|head\?|index\?|insert|' r'length\?|next|pick|poke|remove|reverse|select|sort|skip|swap|tail|tail\?|' r'take|trim|create|close|delete|modify|open|open\?|query|read|rename|' r'update|write)$', word): yield match.start(), Name.Function, word elif re.match(r'(yes|on|no|off|true|false|tab|cr|lf|newline|escape|slash|sp|space|null|' r'none|crlf|dot|null-byte)$', word): yield match.start(), Name.Builtin.Pseudo, word elif re.match(r'(#system-global|#include|#enum|#define|#either|#if|#import|#export|' r'#switch|#default|#get-definition)$', word): yield match.start(), Keyword.Namespace, word elif re.match(r'(system|halt|quit|quit-return|do|load|q|recycle|call|run|ask|parse|' r'raise-error|return|exit|break|alias|push|pop|probe|\?\?|spec-of|body-of|' r'quote|forever)$', word): yield match.start(), Name.Exception, word elif re.match(r'(action\?|block\?|char\?|datatype\?|file\?|function\?|get-path\?|zero\?|' r'get-word\?|integer\?|issue\?|lit-path\?|lit-word\?|logic\?|native\?|' r'op\?|paren\?|path\?|refinement\?|set-path\?|set-word\?|string\?|unset\?|' r'any-struct\?|none\?|word\?|any-series\?)$', word): yield match.start(), Keyword, word elif re.match(r'(JNICALL|stdcall|cdecl|infix)$', word): yield match.start(), Keyword.Namespace, word elif re.match("to-.*", word): yield match.start(), Keyword, word elif re.match(r'(\+|-\*\*|-|\*\*|//|/|\*|and|or|xor|=\?|===|==|=|<>|<=|>=|' r'<<<|>>>|<<|>>|<|>%)$', word): yield match.start(), Operator, word elif re.match(r".*\!$", word): yield match.start(), Keyword.Type, word elif re.match("'.*", word): yield match.start(), Name.Variable.Instance, word # lit-word elif re.match("#.*", word): yield match.start(), Name.Label, word # issue elif re.match("%.*", word): yield match.start(), Name.Decorator, word # file elif re.match(":.*", word): yield match.start(), Generic.Subheading, word # get-word else: yield match.start(), Name.Variable, word
tokens = { 'root': [ (r'\s+', Text), (r'#"', String.Char, 'char'), (r'#\{[0-9a-f\s]*\}', Number.Hex), (r'2#\{', Number.Hex, 'bin2'), (r'64#\{[0-9a-z+/=\s]*\}', Number.Hex), (r'([0-9a-f]+)(h)((\s)|(?=[\[\]{}"()]))', bygroups(Number.Hex, Name.Variable, Whitespace)), (r'"', String, 'string'), (r'\{', String, 'string2'), (r';#+.*\n', Comment.Special), (r';\*+.*\n', Comment.Preproc), (r';.*\n', Comment), (r'%"', Name.Decorator, 'stringFile'), (r'%[^(^{")\s\[\]]+', Name.Decorator), (r'[+-]?([a-z]{1,3})?\$\d+(\.\d+)?', Number.Float), # money (r'[+-]?\d+\:\d+(\:\d+)?(\.\d+)?', String.Other), # time (r'\d+[\-/][0-9a-z]+[\-/]\d+(/\d+:\d+((:\d+)?' r'([\.\d+]?([+-]?\d+:\d+)?)?)?)?', String.Other), # date (r'\d+(\.\d+)+\.\d+', Keyword.Constant), # tuple (r'\d+X\d+', Keyword.Constant), # pair (r'[+-]?\d+(\'\d+)?([.,]\d*)?E[+-]?\d+', Number.Float), (r'[+-]?\d+(\'\d+)?[.,]\d*', Number.Float), (r'[+-]?\d+(\'\d+)?', Number), (r'[\[\]()]', Generic.Strong), (r'[a-z]+[^(^{"\s:)]*://[^(^{"\s)]*', Name.Decorator), # url (r'mailto:[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator), # url (r'[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator), # email (r'comment\s"', Comment, 'commentString1'), (r'comment\s\{', Comment, 'commentString2'), (r'comment\s\[', Comment, 'commentBlock'), (r'comment\s[^(\s{"\[]+', Comment), (r'/[^(^{^")\s/[\]]*', Name.Attribute), (r'([^(^{^")\s/[\]]+)(?=[:({"\s/\[\]])', word_callback), (r'<[\w:.-]*>', Name.Tag), (r'<[^(<>\s")]+', Name.Tag, 'tag'), (r'([^(^{")\s]+)', Text), ], 'string': [ (r'[^(^")]+', String), (escape_re, String.Escape), (r'[(|)]+', String), (r'\^.', String.Escape), (r'"', String, '#pop'), ], 'string2': [ (r'[^(^{})]+', String), (escape_re, String.Escape), (r'[(|)]+', String), (r'\^.', String.Escape), (r'\{', String, '#push'), (r'\}', String, '#pop'), ], 'stringFile': [ (r'[^(^")]+', Name.Decorator), (escape_re, Name.Decorator), (r'\^.', Name.Decorator), (r'"', Name.Decorator, '#pop'), ], 'char': [ (escape_re + '"', String.Char, '#pop'), (r'\^."', String.Char, '#pop'), (r'."', String.Char, '#pop'), ], 'tag': [ (escape_re, Name.Tag), (r'"', Name.Tag, 'tagString'), (r'[^(<>\r\n")]+', Name.Tag), (r'>', Name.Tag, '#pop'), ], 'tagString': [ (r'[^(^")]+', Name.Tag), (escape_re, Name.Tag), (r'[(|)]+', Name.Tag), (r'\^.', Name.Tag), (r'"', Name.Tag, '#pop'), ], 'tuple': [ (r'(\d+\.)+', Keyword.Constant), (r'\d+', Keyword.Constant, '#pop'), ], 'bin2': [ (r'\s+', Number.Hex), (r'([01]\s*){8}', Number.Hex), (r'\}', Number.Hex, '#pop'), ], 'commentString1': [ (r'[^(^")]+', Comment), (escape_re, Comment), (r'[(|)]+', Comment), (r'\^.', Comment), (r'"', Comment, '#pop'), ], 'commentString2': [ (r'[^(^{})]+', Comment), (escape_re, Comment), (r'[(|)]+', Comment), (r'\^.', Comment), (r'\{', Comment, '#push'), (r'\}', Comment, '#pop'), ], 'commentBlock': [ (r'\[', Comment, '#push'), (r'\]', Comment, '#pop'), (r'"', Comment, "commentString1"), (r'\{', Comment, "commentString2"), (r'[^(\[\]"{)]+', Comment), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657""" pygments.lexers.rego ~~~~~~~~~~~~~~~~~~~~
Lexers for the Rego policy languages.
: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, Operator, Keyword, Name, String, Number, Punctuation, Whitespace
class RegoLexer(RegexLexer): """ For Rego source. """ name = 'Rego' url = 'https://www.openpolicyagent.org/docs/latest/policy-language/' filenames = ['*.rego'] aliases = ['rego'] mimetypes = ['text/x-rego'] version_added = '2.19'
reserved_words = ( 'as', 'contains', 'data', 'default', 'else', 'every', 'false', 'if', 'in', 'import', 'package', 'not', 'null', 'some', 'true', 'with' )
builtins = ( # https://www.openpolicyagent.org/docs/latest/philosophy/#the-opa-document-model 'data', # Global variable for accessing base and virtual documents 'input', # Represents synchronously pushed base documents )
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'#.*?$', Comment.Single), (words(reserved_words, suffix=r'\b'), Keyword), (words(builtins, suffix=r'\b'), Name.Builtin), (r'[a-zA-Z_][a-zA-Z0-9_]*', Name), (r'"(\\\\|\\"|[^"])*"', String.Double), (r'`[^`]*`', String.Backtick), (r'-?\d+(\.\d+)?', Number), (r'(==|!=|<=|>=|:=)', Operator), # Compound operators (r'[=<>+\-*/%&|]', Operator), # Single-character operators (r'[\[\]{}(),.:;]', Punctuation), ] }
__all__ = ['RegoLexer']
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768""" pygments.lexers.rell ~~~~~~~~~~~~~~~~~~~~
Lexers for the Rell 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 Comment, Keyword, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['RellLexer']
class RellLexer(RegexLexer): """ A Lexer for Rell. """ name = 'Rell' url = 'https://docs.chromia.com/rell/rell-intro' aliases = ['rell'] filenames = ['*.rell'] mimetypes = ['text/x-rell'] version_added = '2.20'
ident = r'[a-zA-Z_][a-zA-Z0-9_]*'
tokens = { 'root': [ (words(( 'big_integer', 'boolean', 'byte_array', 'decimal', 'gtv', 'integer', 'json', 'list', 'map', 'mutable', 'set', 'text', 'virtual'), suffix=r'\b'), Keyword.Type), (r'(false|true|null)\b', Keyword.Constant), (r'(entity|enum|namespace|object|struct)\b', Keyword.Declaration), (r'(function|operation|query)\b', Keyword.Declaration, 'function'), (words(( 'abstract', 'and', 'break', 'continue', 'create', 'delete', 'else', 'for', 'if', 'import', 'in', 'index', 'key', 'limit', 'module', 'not', 'offset', 'or', 'override', 'return', 'update', 'val', 'var', 'when', 'while'), suffix=r'\b'), Keyword.Reserved), (r'//.*?$', Comment.Single), (r'/\*(.|\n|\r)*?\*/', Comment.Multiline), (r'"(\\\\|\\"|[^"])*"', String.Double), (r'\'(\\\\|\\\'|[^\\\'])*\'', String.Single), (r'-?[0-9]*\.[0-9]+([eE][+-][0-9]+)?', Number.Float), (r'-?[0-9]+([eE][+-][0-9]+|[lL])?', Number.Integer), (r'x(\'[a-fA-F0-9]*\'|"[a-fA-F0-9]*")', String.Binary), (r'(\.)([ \n\t\r]*)(' + ident + ')', bygroups(Punctuation, Whitespace, Name.Attribute)), (r'[{}():;,]+', Punctuation), (r'[ \n\t\r]+', Whitespace), (r'@[a-zA-Z_][a-zA-Z0-9_]*', Name.Decorator), (r'[~^*!%&\[\]<>|+=/?\-@\$]', Punctuation.Marker), (ident, Name), (r'(\.)+', Punctuation), ], 'function': [ (r'[ \n\t\r]+', Whitespace), (ident, Name.Function, '#pop'), default('#pop'), ], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283""" pygments.lexers.resource ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for resource definition files.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroups, wordsfrom pygments.token import Comment, String, Number, Operator, Text, \ Keyword, Name
__all__ = ['ResourceLexer']
class ResourceLexer(RegexLexer): """Lexer for ICU Resource bundles. """ name = 'ResourceBundle' aliases = ['resourcebundle', 'resource'] filenames = [] url = 'https://unicode-org.github.io/icu/userguide/locale/resources.html' version_added = '2.0'
_types = (':table', ':array', ':string', ':bin', ':import', ':intvector', ':int', ':alias')
flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'//.*?$', Comment), (r'"', String, 'string'), (r'-?\d+', Number.Integer), (r'[,{}]', Operator), (r'([^\s{{:]+)(\s*)({}?)'.format('|'.join(_types)), bygroups(Name, Text, Keyword)), (r'\s+', Text), (words(_types), Keyword), ], 'string': [ (r'(\\x[0-9a-f]{2}|\\u[0-9a-f]{4}|\\U00[0-9a-f]{6}|' r'\\[0-7]{1,3}|\\c.|\\[abtnvfre\'"?\\]|\\\{|[^"{\\])+', String), (r'\{', String.Escape, 'msgname'), (r'"', String, '#pop') ], 'msgname': [ (r'([^{},]+)(\s*)', bygroups(Name, String.Escape), ('#pop', 'message')) ], 'message': [ (r'\{', String.Escape, 'msgname'), (r'\}', String.Escape, '#pop'), (r'(,)(\s*)([a-z]+)(\s*\})', bygroups(Operator, String.Escape, Keyword, String.Escape), '#pop'), (r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)(offset)(\s*)(:)(\s*)(-?\d+)(\s*)', bygroups(Operator, String.Escape, Keyword, String.Escape, Operator, String.Escape, Operator.Word, String.Escape, Operator, String.Escape, Number.Integer, String.Escape), 'choice'), (r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)', bygroups(Operator, String.Escape, Keyword, String.Escape, Operator, String.Escape), 'choice'), (r'\s+', String.Escape) ], 'choice': [ (r'(=|<|>|<=|>=|!=)(-?\d+)(\s*\{)', bygroups(Operator, Number.Integer, String.Escape), 'message'), (r'([a-z]+)(\s*\{)', bygroups(Keyword.Type, String.Escape), 'str'), (r'\}', String.Escape, ('#pop', '#pop')), (r'\s+', String.Escape) ], 'str': [ (r'\}', String.Escape, '#pop'), (r'\{', String.Escape, 'msgname'), (r'[^{}]+', String) ] }
def analyse_text(text): if text.startswith('root:table'): return 1.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138""" pygments.lexers.ride ~~~~~~~~~~~~~~~~~~~~
Lexer for the Ride programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, includefrom pygments.token import Comment, Keyword, Name, Number, Punctuation, \ String, Text
__all__ = ['RideLexer']
class RideLexer(RegexLexer): """ For Ride source code. """
name = 'Ride' aliases = ['ride'] filenames = ['*.ride'] mimetypes = ['text/x-ride'] url = 'https://docs.waves.tech/en/ride' version_added = '2.6'
validName = r'[a-zA-Z_][a-zA-Z0-9_\']*'
builtinOps = ( '||', '|', '>=', '>', '==', '!', '=', '<=', '<', '::', ':+', ':', '!=', '/', '.', '=>', '-', '+', '*', '&&', '%', '++', )
globalVariablesName = ( 'NOALG', 'MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'SHA3224', 'SHA3256', 'SHA3384', 'SHA3512', 'nil', 'this', 'unit', 'height', 'lastBlock', 'Buy', 'Sell', 'CEILING', 'FLOOR', 'DOWN', 'HALFDOWN', 'HALFEVEN', 'HALFUP', 'UP', )
typesName = ( 'Unit', 'Int', 'Boolean', 'ByteVector', 'String', 'Address', 'Alias', 'Transfer', 'AssetPair', 'DataEntry', 'Order', 'Transaction', 'GenesisTransaction', 'PaymentTransaction', 'ReissueTransaction', 'BurnTransaction', 'MassTransferTransaction', 'ExchangeTransaction', 'TransferTransaction', 'SetAssetScriptTransaction', 'InvokeScriptTransaction', 'IssueTransaction', 'LeaseTransaction', 'LeaseCancelTransaction', 'CreateAliasTransaction', 'SetScriptTransaction', 'SponsorFeeTransaction', 'DataTransaction', 'WriteSet', 'AttachedPayment', 'ScriptTransfer', 'TransferSet', 'ScriptResult', 'Invocation', 'Asset', 'BlockInfo', 'Issue', 'Reissue', 'Burn', 'NoAlg', 'Md5', 'Sha1', 'Sha224', 'Sha256', 'Sha384', 'Sha512', 'Sha3224', 'Sha3256', 'Sha3384', 'Sha3512', 'BinaryEntry', 'BooleanEntry', 'IntegerEntry', 'StringEntry', 'List', 'Ceiling', 'Down', 'Floor', 'HalfDown', 'HalfEven', 'HalfUp', 'Up', )
functionsName = ( 'fraction', 'size', 'toBytes', 'take', 'drop', 'takeRight', 'dropRight', 'toString', 'isDefined', 'extract', 'throw', 'getElement', 'value', 'cons', 'toUtf8String', 'toInt', 'indexOf', 'lastIndexOf', 'split', 'parseInt', 'parseIntValue', 'keccak256', 'blake2b256', 'sha256', 'sigVerify', 'toBase58String', 'fromBase58String', 'toBase64String', 'fromBase64String', 'transactionById', 'transactionHeightById', 'getInteger', 'getBoolean', 'getBinary', 'getString', 'addressFromPublicKey', 'addressFromString', 'addressFromRecipient', 'assetBalance', 'wavesBalance', 'getIntegerValue', 'getBooleanValue', 'getBinaryValue', 'getStringValue', 'addressFromStringValue', 'assetInfo', 'rsaVerify', 'checkMerkleProof', 'median', 'valueOrElse', 'valueOrErrorMessage', 'contains', 'log', 'pow', 'toBase16String', 'fromBase16String', 'blockInfoByHeight', 'transferTransactionById', )
reservedWords = words(( 'match', 'case', 'else', 'func', 'if', 'let', 'then', '@Callable', '@Verifier', ), suffix=r'\b')
tokens = { 'root': [ # Comments (r'#.*', Comment.Single), # Whitespace (r'\s+', Text), # Strings (r'"', String, 'doublequote'), (r'utf8\'', String, 'utf8quote'), (r'base(58|64|16)\'', String, 'singlequote'), # Keywords (reservedWords, Keyword.Reserved), (r'\{-#.*?#-\}', Keyword.Reserved), (r'FOLD<\d+>', Keyword.Reserved), # Types (words(typesName), Keyword.Type), # Main # (specialName, Keyword.Reserved), # Prefix Operators (words(builtinOps, prefix=r'\(', suffix=r'\)'), Name.Function), # Infix Operators (words(builtinOps), Name.Function), (words(globalVariablesName), Name.Function), (words(functionsName), Name.Function), # Numbers include('numbers'), # Variable Names (validName, Name.Variable), # Parens (r'[,()\[\]{}]', Punctuation), ],
'doublequote': [ (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\[nrfvb\\"]', String.Escape), (r'[^"]', String), (r'"', String, '#pop'), ],
'utf8quote': [ (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\[nrfvb\\\']', String.Escape), (r'[^\']', String), (r'\'', String, '#pop'), ],
'singlequote': [ (r'[^\']', String), (r'\'', String, '#pop'), ],
'numbers': [ (r'_?\d+', Number.Integer), ], }123456789101112131415161718192021222324252627282930313233343536373839404142""" pygments.lexers.rita ~~~~~~~~~~~~~~~~~~~~
Lexers for RITA language
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexerfrom pygments.token import Comment, Operator, Keyword, Name, Literal, \ Punctuation, Whitespace
__all__ = ['RitaLexer']
class RitaLexer(RegexLexer): """ Lexer for RITA. """ name = 'Rita' url = 'https://github.com/zaibacu/rita-dsl' filenames = ['*.rita'] aliases = ['rita'] mimetypes = ['text/rita'] version_added = '2.11'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'#(.*?)\n', Comment.Single), (r'@(.*?)\n', Operator), # Yes, whole line as an operator (r'"(\w|\d|\s|(\\")|[\'_\-./,\?\!])+?"', Literal), (r'\'(\w|\d|\s|(\\\')|["_\-./,\?\!])+?\'', Literal), (r'([A-Z_]+)', Keyword), (r'([a-z0-9_]+)', Name), (r'((->)|[!?+*|=])', Operator), (r'[\(\),\{\}]', Punctuation) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566""" pygments.lexers.rnc ~~~~~~~~~~~~~~~~~~~
Lexer for Relax-NG Compact syntax
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexerfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Punctuation
__all__ = ['RNCCompactLexer']
class RNCCompactLexer(RegexLexer): """ For RelaxNG-compact syntax. """
name = 'Relax-NG Compact' url = 'http://relaxng.org' aliases = ['rng-compact', 'rnc'] filenames = ['*.rnc'] version_added = '2.2'
tokens = { 'root': [ (r'namespace\b', Keyword.Namespace), (r'(?:default|datatypes)\b', Keyword.Declaration), (r'##.*$', Comment.Preproc), (r'#.*$', Comment.Single), (r'"[^"]*"', String.Double), # TODO single quoted strings and escape sequences outside of # double-quoted strings (r'(?:element|attribute|mixed)\b', Keyword.Declaration, 'variable'), (r'(text\b|xsd:[^ ]+)', Keyword.Type, 'maybe_xsdattributes'), (r'[,?&*=|~]|>>', Operator), (r'[(){}]', Punctuation), (r'.', Text), ],
# a variable has been declared using `element` or `attribute` 'variable': [ (r'[^{]+', Name.Variable), (r'\{', Punctuation, '#pop'), ],
# after an xsd:<datatype> declaration there may be attributes 'maybe_xsdattributes': [ (r'\{', Punctuation, 'xsdattributes'), (r'\}', Punctuation, '#pop'), (r'.', Text), ],
# attributes take the form { key1 = value1 key2 = value2 ... } 'xsdattributes': [ (r'[^ =}]', Name.Attribute), (r'=', Operator), (r'"[^"]*"', String.Double), (r'\}', Punctuation, '#pop'), (r'.', Text), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081""" pygments.lexers.roboconf ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Roboconf DSL.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, refrom pygments.token import Text, Operator, Keyword, Name, Comment
__all__ = ['RoboconfGraphLexer', 'RoboconfInstancesLexer']
class RoboconfGraphLexer(RegexLexer): """ Lexer for Roboconf graph files. """ name = 'Roboconf Graph' aliases = ['roboconf-graph'] filenames = ['*.graph'] url = 'https://roboconf.github.io/en/user-guide/graph-definition.html' version_added = '2.1'
flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [ # Skip white spaces (r'\s+', Text),
# There is one operator (r'=', Operator),
# Keywords (words(('facet', 'import'), suffix=r'\s*\b', prefix=r'\b'), Keyword), (words(( 'installer', 'extends', 'exports', 'imports', 'facets', 'children'), suffix=r'\s*:?', prefix=r'\b'), Name),
# Comments (r'#.*\n', Comment),
# Default (r'[^#]', Text), (r'.*\n', Text) ] }
class RoboconfInstancesLexer(RegexLexer): """ Lexer for Roboconf instances files. """ name = 'Roboconf Instances' aliases = ['roboconf-instances'] filenames = ['*.instances'] url = 'https://roboconf.github.io' version_added = '2.1'
flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [
# Skip white spaces (r'\s+', Text),
# Keywords (words(('instance of', 'import'), suffix=r'\s*\b', prefix=r'\b'), Keyword), (words(('name', 'count'), suffix=r's*:?', prefix=r'\b'), Name), (r'\s*[\w.-]+\s*:', Name),
# Comments (r'#.*\n', Comment),
# Default (r'[^#]', Text), (r'.*\n', Text) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551""" pygments.lexers.robotframework ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Robot Framework.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
# Copyright 2012 Nokia Siemens Networks Oyj## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import re
from pygments.lexer import Lexerfrom pygments.token import Token
__all__ = ['RobotFrameworkLexer']
HEADING = Token.Generic.HeadingSETTING = Token.Keyword.NamespaceIMPORT = Token.Name.NamespaceTC_KW_NAME = Token.Generic.SubheadingKEYWORD = Token.Name.FunctionARGUMENT = Token.StringVARIABLE = Token.Name.VariableCOMMENT = Token.CommentSEPARATOR = Token.PunctuationSYNTAX = Token.PunctuationGHERKIN = Token.Generic.EmphERROR = Token.Error
def normalize(string, remove=''): string = string.lower() for char in remove + ' ': if char in string: string = string.replace(char, '') return string
class RobotFrameworkLexer(Lexer): """ For Robot Framework test data.
Supports both space and pipe separated plain text formats. """ name = 'RobotFramework' url = 'http://robotframework.org' aliases = ['robotframework'] filenames = ['*.robot', '*.resource'] mimetypes = ['text/x-robotframework'] version_added = '1.6'
def __init__(self, **options): options['tabsize'] = 2 options['encoding'] = 'UTF-8' Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): row_tokenizer = RowTokenizer() var_tokenizer = VariableTokenizer() index = 0 for row in text.splitlines(): for value, token in row_tokenizer.tokenize(row): for value, token in var_tokenizer.tokenize(value, token): if value: yield index, token, str(value) index += len(value)
class VariableTokenizer:
def tokenize(self, string, token): var = VariableSplitter(string, identifiers='$@%&') if var.start < 0 or token in (COMMENT, ERROR): yield string, token return for value, token in self._tokenize(var, string, token): if value: yield value, token
def _tokenize(self, var, string, orig_token): before = string[:var.start] yield before, orig_token yield var.identifier + '{', SYNTAX yield from self.tokenize(var.base, VARIABLE) yield '}', SYNTAX if var.index is not None: yield '[', SYNTAX yield from self.tokenize(var.index, VARIABLE) yield ']', SYNTAX yield from self.tokenize(string[var.end:], orig_token)
class RowTokenizer:
def __init__(self): self._table = UnknownTable() self._splitter = RowSplitter() testcases = TestCaseTable() settings = SettingTable(testcases.set_default_template) variables = VariableTable() keywords = KeywordTable() self._tables = {'settings': settings, 'setting': settings, 'metadata': settings, 'variables': variables, 'variable': variables, 'testcases': testcases, 'testcase': testcases, 'tasks': testcases, 'task': testcases, 'keywords': keywords, 'keyword': keywords, 'userkeywords': keywords, 'userkeyword': keywords}
def tokenize(self, row): commented = False heading = False for index, value in enumerate(self._splitter.split(row)): # First value, and every second after that, is a separator. index, separator = divmod(index-1, 2) if value.startswith('#'): commented = True elif index == 0 and value.startswith('*'): self._table = self._start_table(value) heading = True yield from self._tokenize(value, index, commented, separator, heading) self._table.end_row()
def _start_table(self, header): name = normalize(header, remove='*') return self._tables.get(name, UnknownTable())
def _tokenize(self, value, index, commented, separator, heading): if commented: yield value, COMMENT elif separator: yield value, SEPARATOR elif heading: yield value, HEADING else: yield from self._table.tokenize(value, index)
class RowSplitter: _space_splitter = re.compile('( {2,})') _pipe_splitter = re.compile(r'((?:^| +)\|(?: +|$))')
def split(self, row): splitter = (row.startswith('| ') and self._split_from_pipes or self._split_from_spaces) yield from splitter(row) yield '\n'
def _split_from_spaces(self, row): yield '' # Start with (pseudo)separator similarly as with pipes yield from self._space_splitter.split(row)
def _split_from_pipes(self, row): _, separator, rest = self._pipe_splitter.split(row, 1) yield separator while self._pipe_splitter.search(rest): cell, separator, rest = self._pipe_splitter.split(rest, 1) yield cell yield separator yield rest
class Tokenizer: _tokens = None
def __init__(self): self._index = 0
def tokenize(self, value): values_and_tokens = self._tokenize(value, self._index) self._index += 1 if isinstance(values_and_tokens, type(Token)): values_and_tokens = [(value, values_and_tokens)] return values_and_tokens
def _tokenize(self, value, index): index = min(index, len(self._tokens) - 1) return self._tokens[index]
def _is_assign(self, value): if value.endswith('='): value = value[:-1].strip() var = VariableSplitter(value, identifiers='$@&') return var.start == 0 and var.end == len(value)
class Comment(Tokenizer): _tokens = (COMMENT,)
class Setting(Tokenizer): _tokens = (SETTING, ARGUMENT) _keyword_settings = ('suitesetup', 'suiteprecondition', 'suiteteardown', 'suitepostcondition', 'testsetup', 'tasksetup', 'testprecondition', 'testteardown','taskteardown', 'testpostcondition', 'testtemplate', 'tasktemplate') _import_settings = ('library', 'resource', 'variables') _other_settings = ('documentation', 'metadata', 'forcetags', 'defaulttags', 'testtimeout','tasktimeout') _custom_tokenizer = None
def __init__(self, template_setter=None): Tokenizer.__init__(self) self._template_setter = template_setter
def _tokenize(self, value, index): if index == 1 and self._template_setter: self._template_setter(value) if index == 0: normalized = normalize(value) if normalized in self._keyword_settings: self._custom_tokenizer = KeywordCall(support_assign=False) elif normalized in self._import_settings: self._custom_tokenizer = ImportSetting() elif normalized not in self._other_settings: return ERROR elif self._custom_tokenizer: return self._custom_tokenizer.tokenize(value) return Tokenizer._tokenize(self, value, index)
class ImportSetting(Tokenizer): _tokens = (IMPORT, ARGUMENT)
class TestCaseSetting(Setting): _keyword_settings = ('setup', 'precondition', 'teardown', 'postcondition', 'template') _import_settings = () _other_settings = ('documentation', 'tags', 'timeout')
def _tokenize(self, value, index): if index == 0: type = Setting._tokenize(self, value[1:-1], index) return [('[', SYNTAX), (value[1:-1], type), (']', SYNTAX)] return Setting._tokenize(self, value, index)
class KeywordSetting(TestCaseSetting): _keyword_settings = ('teardown',) _other_settings = ('documentation', 'arguments', 'return', 'timeout', 'tags')
class Variable(Tokenizer): _tokens = (SYNTAX, ARGUMENT)
def _tokenize(self, value, index): if index == 0 and not self._is_assign(value): return ERROR return Tokenizer._tokenize(self, value, index)
class KeywordCall(Tokenizer): _tokens = (KEYWORD, ARGUMENT)
def __init__(self, support_assign=True): Tokenizer.__init__(self) self._keyword_found = not support_assign self._assigns = 0
def _tokenize(self, value, index): if not self._keyword_found and self._is_assign(value): self._assigns += 1 return SYNTAX # VariableTokenizer tokenizes this later. if self._keyword_found: return Tokenizer._tokenize(self, value, index - self._assigns) self._keyword_found = True return GherkinTokenizer().tokenize(value, KEYWORD)
class GherkinTokenizer: _gherkin_prefix = re.compile('^(Given|When|Then|And|But) ', re.IGNORECASE)
def tokenize(self, value, token): match = self._gherkin_prefix.match(value) if not match: return [(value, token)] end = match.end() return [(value[:end], GHERKIN), (value[end:], token)]
class TemplatedKeywordCall(Tokenizer): _tokens = (ARGUMENT,)
class ForLoop(Tokenizer):
def __init__(self): Tokenizer.__init__(self) self._in_arguments = False
def _tokenize(self, value, index): token = self._in_arguments and ARGUMENT or SYNTAX if value.upper() in ('IN', 'IN RANGE'): self._in_arguments = True return token
class _Table: _tokenizer_class = None
def __init__(self, prev_tokenizer=None): self._tokenizer = self._tokenizer_class() self._prev_tokenizer = prev_tokenizer self._prev_values_on_row = []
def tokenize(self, value, index): if self._continues(value, index): self._tokenizer = self._prev_tokenizer yield value, SYNTAX else: yield from self._tokenize(value, index) self._prev_values_on_row.append(value)
def _continues(self, value, index): return value == '...' and all(self._is_empty(t) for t in self._prev_values_on_row)
def _is_empty(self, value): return value in ('', '\\')
def _tokenize(self, value, index): return self._tokenizer.tokenize(value)
def end_row(self): self.__init__(prev_tokenizer=self._tokenizer)
class UnknownTable(_Table): _tokenizer_class = Comment
def _continues(self, value, index): return False
class VariableTable(_Table): _tokenizer_class = Variable
class SettingTable(_Table): _tokenizer_class = Setting
def __init__(self, template_setter, prev_tokenizer=None): _Table.__init__(self, prev_tokenizer) self._template_setter = template_setter
def _tokenize(self, value, index): if index == 0 and normalize(value) == 'testtemplate': self._tokenizer = Setting(self._template_setter) return _Table._tokenize(self, value, index)
def end_row(self): self.__init__(self._template_setter, prev_tokenizer=self._tokenizer)
class TestCaseTable(_Table): _setting_class = TestCaseSetting _test_template = None _default_template = None
@property def _tokenizer_class(self): if self._test_template or (self._default_template and self._test_template is not False): return TemplatedKeywordCall return KeywordCall
def _continues(self, value, index): return index > 0 and _Table._continues(self, value, index)
def _tokenize(self, value, index): if index == 0: if value: self._test_template = None return GherkinTokenizer().tokenize(value, TC_KW_NAME) if index == 1 and self._is_setting(value): if self._is_template(value): self._test_template = False self._tokenizer = self._setting_class(self.set_test_template) else: self._tokenizer = self._setting_class() if index == 1 and self._is_for_loop(value): self._tokenizer = ForLoop() if index == 1 and self._is_empty(value): return [(value, SYNTAX)] return _Table._tokenize(self, value, index)
def _is_setting(self, value): return value.startswith('[') and value.endswith(']')
def _is_template(self, value): return normalize(value) == '[template]'
def _is_for_loop(self, value): return value.startswith(':') and normalize(value, remove=':') == 'for'
def set_test_template(self, template): self._test_template = self._is_template_set(template)
def set_default_template(self, template): self._default_template = self._is_template_set(template)
def _is_template_set(self, template): return normalize(template) not in ('', '\\', 'none', '${empty}')
class KeywordTable(TestCaseTable): _tokenizer_class = KeywordCall _setting_class = KeywordSetting
def _is_template(self, value): return False
# Following code copied directly from Robot Framework 2.7.5.
class VariableSplitter:
def __init__(self, string, identifiers): self.identifier = None self.base = None self.index = None self.start = -1 self.end = -1 self._identifiers = identifiers self._may_have_internal_variables = False try: self._split(string) except ValueError: pass else: self._finalize()
def get_replaced_base(self, variables): if self._may_have_internal_variables: return variables.replace_string(self.base) return self.base
def _finalize(self): self.identifier = self._variable_chars[0] self.base = ''.join(self._variable_chars[2:-1]) self.end = self.start + len(self._variable_chars) if self._has_list_or_dict_variable_index(): self.index = ''.join(self._list_and_dict_variable_index_chars[1:-1]) self.end += len(self._list_and_dict_variable_index_chars)
def _has_list_or_dict_variable_index(self): return self._list_and_dict_variable_index_chars\ and self._list_and_dict_variable_index_chars[-1] == ']'
def _split(self, string): start_index, max_index = self._find_variable(string) self.start = start_index self._open_curly = 1 self._state = self._variable_state self._variable_chars = [string[start_index], '{'] self._list_and_dict_variable_index_chars = [] self._string = string start_index += 2 for index, char in enumerate(string[start_index:]): index += start_index # Giving start to enumerate only in Py 2.6+ try: self._state(char, index) except StopIteration: return if index == max_index and not self._scanning_list_variable_index(): return
def _scanning_list_variable_index(self): return self._state in [self._waiting_list_variable_index_state, self._list_variable_index_state]
def _find_variable(self, string): max_end_index = string.rfind('}') if max_end_index == -1: raise ValueError('No variable end found') if self._is_escaped(string, max_end_index): return self._find_variable(string[:max_end_index]) start_index = self._find_start_index(string, 1, max_end_index) if start_index == -1: raise ValueError('No variable start found') return start_index, max_end_index
def _find_start_index(self, string, start, end): index = string.find('{', start, end) - 1 if index < 0: return -1 if self._start_index_is_ok(string, index): return index return self._find_start_index(string, index+2, end)
def _start_index_is_ok(self, string, index): return string[index] in self._identifiers\ and not self._is_escaped(string, index)
def _is_escaped(self, string, index): escaped = False while index > 0 and string[index-1] == '\\': index -= 1 escaped = not escaped return escaped
def _variable_state(self, char, index): self._variable_chars.append(char) if char == '}' and not self._is_escaped(self._string, index): self._open_curly -= 1 if self._open_curly == 0: if not self._is_list_or_dict_variable(): raise StopIteration self._state = self._waiting_list_variable_index_state elif char in self._identifiers: self._state = self._internal_variable_start_state
def _is_list_or_dict_variable(self): return self._variable_chars[0] in ('@','&')
def _internal_variable_start_state(self, char, index): self._state = self._variable_state if char == '{': self._variable_chars.append(char) self._open_curly += 1 self._may_have_internal_variables = True else: self._variable_state(char, index)
def _waiting_list_variable_index_state(self, char, index): if char != '[': raise StopIteration self._list_and_dict_variable_index_chars.append(char) self._state = self._list_variable_index_state
def _list_variable_index_state(self, char, index): self._list_and_dict_variable_index_chars.append(char) if char == ']': raise StopIteration123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518""" pygments.lexers.ruby ~~~~~~~~~~~~~~~~~~~~
Lexers for Ruby and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, ExtendedRegexLexer, include, \ bygroups, default, LexerContext, do_insertions, words, line_refrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error, Generic, Whitespacefrom pygments.util import shebang_matches
__all__ = ['RubyLexer', 'RubyConsoleLexer', 'FancyLexer']
RUBY_OPERATORS = ( '*', '**', '-', '+', '-@', '+@', '/', '%', '&', '|', '^', '`', '~', '[]', '[]=', '<<', '>>', '<', '<>', '<=>', '>', '>=', '==', '===')
class RubyLexer(ExtendedRegexLexer): """ For Ruby source code. """
name = 'Ruby' url = 'http://www.ruby-lang.org' aliases = ['ruby', 'rb', 'duby'] filenames = ['*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec', '*.rbx', '*.duby', 'Gemfile', 'Vagrantfile'] mimetypes = ['text/x-ruby', 'application/x-ruby'] version_added = ''
flags = re.DOTALL | re.MULTILINE
def heredoc_callback(self, match, ctx): # okay, this is the hardest part of parsing Ruby... # 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) in ('<<-', '<<~'), 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_rubystrings_rules(): def intp_regex_callback(self, match, ctx): yield match.start(1), String.Regex, match.group(1) # begin nctx = LexerContext(match.group(3), 0, ['interpolated-regex']) for i, t, v in self.get_tokens_unprocessed(context=nctx): yield match.start(3)+i, t, v yield match.start(4), String.Regex, match.group(4) # end[mixounse]* ctx.pos = match.end()
def intp_string_callback(self, match, ctx): yield match.start(1), String.Other, match.group(1) nctx = LexerContext(match.group(3), 0, ['interpolated-string']) for i, t, v in self.get_tokens_unprocessed(context=nctx): yield match.start(3)+i, t, v yield match.start(4), String.Other, match.group(4) # end ctx.pos = match.end()
states = {} states['strings'] = [ # easy ones (r'\:@{0,2}[a-zA-Z_]\w*[!?]?', String.Symbol), (words(RUBY_OPERATORS, prefix=r'\:@{0,2}'), String.Symbol), (r":'(\\\\|\\[^\\]|[^'\\])*'", String.Symbol), (r':"', String.Symbol, 'simple-sym'), (r'([a-zA-Z_]\w*)(:)(?!:)', bygroups(String.Symbol, Punctuation)), # Since Ruby 1.9 (r'"', String.Double, 'simple-string-double'), (r"'", String.Single, 'simple-string-single'), (r'(?<!\.)`', String.Backtick, 'simple-backtick'), ]
# quoted string and symbol for name, ttype, end in ('string-double', String.Double, '"'), \ ('string-single', String.Single, "'"),\ ('sym', String.Symbol, '"'), \ ('backtick', String.Backtick, '`'): states['simple-'+name] = [ include('string-intp-escaped'), (rf'[^\\{end}#]+', ttype), (r'[\\#]', ttype), (end, ttype, '#pop'), ]
# braced quoted strings for lbrace, rbrace, bracecc, name in \ ('\\{', '\\}', '{}', 'cb'), \ ('\\[', '\\]', '\\[\\]', 'sb'), \ ('\\(', '\\)', '()', 'pa'), \ ('<', '>', '<>', 'ab'): states[name+'-intp-string'] = [ (r'\\[\\' + bracecc + ']', String.Other), (lbrace, String.Other, '#push'), (rbrace, String.Other, '#pop'), include('string-intp-escaped'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] states['strings'].append((r'%[QWx]?' + lbrace, String.Other, name+'-intp-string')) states[name+'-string'] = [ (r'\\[\\' + bracecc + ']', String.Other), (lbrace, String.Other, '#push'), (rbrace, String.Other, '#pop'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] states['strings'].append((r'%[qsw]' + lbrace, String.Other, name+'-string')) states[name+'-regex'] = [ (r'\\[\\' + bracecc + ']', String.Regex), (lbrace, String.Regex, '#push'), (rbrace + '[mixounse]*', String.Regex, '#pop'), include('string-intp'), (r'[\\#' + bracecc + ']', String.Regex), (r'[^\\#' + bracecc + ']+', String.Regex), ] states['strings'].append((r'%r' + lbrace, String.Regex, name+'-regex'))
# these must come after %<brace>! states['strings'] += [ # %r regex (r'(%r([\W_]))((?:\\\2|(?!\2).)*)(\2[mixounse]*)', intp_regex_callback), # regular fancy strings with qsw (r'%[qsw]([\W_])((?:\\\1|(?!\1).)*)\1', String.Other), (r'(%[QWx]([\W_]))((?:\\\2|(?!\2).)*)(\2)', intp_string_callback), # special forms of fancy strings after operators or # in method calls with braces (r'(?<=[-+/*%=<>&!^|~,(])(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)', bygroups(Whitespace, String.Other, None)), # and because of fixed width lookbehinds the whole thing a # second time for line startings... (r'^(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)', bygroups(Whitespace, String.Other, None)), # all regular fancy strings without qsw (r'(%([^a-zA-Z0-9\s]))((?:\\\2|(?!\2).)*)(\2)', intp_string_callback), ]
return states
tokens = { 'root': [ (r'\A#!.+?$', Comment.Hashbang), (r'#.*?$', Comment.Single), (r'=begin\s.*?\n=end.*?$', Comment.Multiline), # keywords (words(( 'BEGIN', 'END', 'alias', 'begin', 'break', 'case', 'defined?', 'do', 'else', 'elsif', 'end', 'ensure', 'for', 'if', 'in', 'next', 'redo', 'rescue', 'raise', 'retry', 'return', 'super', 'then', 'undef', 'unless', 'until', 'when', 'while', 'yield'), suffix=r'\b'), Keyword), # start of function, class and module names (r'(module)(\s+)([a-zA-Z_]\w*' r'(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(def)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'def(?=[*%&^`~+-/\[<>=])', Keyword, 'funcname'), (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'), # special methods (words(( 'initialize', 'new', 'loop', 'include', 'extend', 'raise', 'attr_reader', 'attr_writer', 'attr_accessor', 'attr', 'catch', 'throw', 'private', 'module_function', 'public', 'protected', 'true', 'false', 'nil'), suffix=r'\b'), Keyword.Pseudo), (r'(not|and|or)\b', Operator.Word), (words(( 'autoload', 'block_given', 'const_defined', 'eql', 'equal', 'frozen', 'include', 'instance_of', 'is_a', 'iterator', 'kind_of', 'method_defined', 'nil', 'private_method_defined', 'protected_method_defined', 'public_method_defined', 'respond_to', 'tainted'), suffix=r'\?'), Name.Builtin), (r'(chomp|chop|exit|gsub|sub)!', Name.Builtin), (words(( 'Array', 'Float', 'Integer', 'String', '__id__', '__send__', 'abort', 'ancestors', 'at_exit', 'autoload', 'binding', 'callcc', 'caller', 'catch', 'chomp', 'chop', 'class_eval', 'class_variables', 'clone', 'const_defined?', 'const_get', 'const_missing', 'const_set', 'constants', 'display', 'dup', 'eval', 'exec', 'exit', 'extend', 'fail', 'fork', 'format', 'freeze', 'getc', 'gets', 'global_variables', 'gsub', 'hash', 'id', 'included_modules', 'inspect', 'instance_eval', 'instance_method', 'instance_methods', 'instance_variable_get', 'instance_variable_set', 'instance_variables', 'lambda', 'load', 'local_variables', 'loop', 'method', 'method_missing', 'methods', 'module_eval', 'name', 'object_id', 'open', 'p', 'print', 'printf', 'private_class_method', 'private_instance_methods', 'private_methods', 'proc', 'protected_instance_methods', 'protected_methods', 'public_class_method', 'public_instance_methods', 'public_methods', 'putc', 'puts', 'raise', 'rand', 'readline', 'readlines', 'require', 'scan', 'select', 'self', 'send', 'set_trace_func', 'singleton_methods', 'sleep', 'split', 'sprintf', 'srand', 'sub', 'syscall', 'system', 'taint', 'test', 'throw', 'to_a', 'to_s', 'trace_var', 'trap', 'untaint', 'untrace_var', 'warn'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), (r'__(FILE|LINE)__\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(Text, 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'(0_?[0-7]+(?:_[0-7]+)*)(\s*)([/?])?', bygroups(Number.Oct, Whitespace, Operator)), (r'(0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*)(\s*)([/?])?', bygroups(Number.Hex, Whitespace, Operator)), (r'(0b[01]+(?:_[01]+)*)(\s*)([/?])?', bygroups(Number.Bin, Whitespace, Operator)), (r'([\d]+(?:_\d+)*)(\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'), # chars (r'\?(\\[MC]-)*' # modifiers r'(\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})|\S)' r'(?!\w)', String.Char), (r'[A-Z]\w+', Name.Constant), # this is needed because ruby attributes can look # like keywords (class) or like this: ` ?!? (words(RUBY_OPERATORS, prefix=r'(\.|::)'), bygroups(Operator, Name.Operator)), (r'(\.|::)([a-zA-Z_]\w*[!?]?|[*%&^`~+\-/\[<>=])', bygroups(Operator, Name)), (r'[a-zA-Z_]\w*[!?]?', Name), (r'(\[|\]|\*\*|<<?|>>?|>=|<=|<=>|=~|={3}|' r'!~|&&?|\|\||\.{1,3})', Operator), (r'[-+/*%=<>&!^|~]=?', Operator), (r'[(){};,/?:\\]', Punctuation), (r'\s+', Whitespace) ], 'funcname': [ (r'\(', Punctuation, 'defexpr'), (r'(?:([a-zA-Z_]\w*)(\.))?' # optional scope name, like "self." r'(' r'[a-zA-Z\u0080-\uffff][a-zA-Z0-9_\u0080-\uffff]*[!?=]?' # method name r'|!=|!~|=~|\*\*?|[-+!~]@?|[/%&|^]|<=>|<[<=]?|>[>=]?|===?' # or operator override r'|\[\]=?' # or element reference/assignment override r'|`' # or the undocumented backtick override r')', bygroups(Name.Class, Operator, Name.Function), '#pop'), default('#pop') ], 'classname': [ (r'\(', Punctuation, 'defexpr'), (r'<<', Operator, '#pop'), (r'[A-Z_]\w*', Name.Class, '#pop'), default('#pop') ], 'defexpr': [ (r'(\))(\.|::)?', bygroups(Punctuation, Operator), '#pop'), (r'\(', Operator, '#push'), include('root') ], 'in-intp': [ (r'\{', String.Interpol, '#push'), (r'\}', String.Interpol, '#pop'), include('root'), ], 'string-intp': [ (r'#\{', String.Interpol, 'in-intp'), (r'#@@?[a-zA-Z_]\w*', String.Interpol), (r'#\$[a-zA-Z_]\w*', String.Interpol) ], 'string-intp-escaped': [ include('string-intp'), (r'\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})', String.Escape) ], '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'/[mixounse]*', String.Regex, '#pop'), ], 'end-part': [ (r'.+', Comment.Preproc, '#pop') ] } tokens.update(gen_rubystrings_rules())
def analyse_text(text): return shebang_matches(text, r'ruby(1\.\d)?')
class RubyConsoleLexer(Lexer): """ For Ruby interactive console (**irb**) output. """ name = 'Ruby irb session' aliases = ['rbcon', 'irb'] mimetypes = ['text/x-ruby-shellsession'] url = 'https://www.ruby-lang.org' version_added = '' _example = 'rbcon/console'
_prompt_re = re.compile(r'irb\([a-zA-Z_]\w*\):\d{3}:\d+[>*"\'] ' r'|>> |\?> ')
def get_tokens_unprocessed(self, text): rblexer = RubyLexer(**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, rblexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] yield match.start(), Generic.Output, line if curcode: yield from do_insertions( insertions, rblexer.get_tokens_unprocessed(curcode))
class FancyLexer(RegexLexer): """ Pygments Lexer For Fancy.
Fancy is a self-hosted, pure object-oriented, dynamic, class-based, concurrent general-purpose programming language running on Rubinius, the Ruby VM. """ name = 'Fancy' url = 'https://github.com/bakkdoor/fancy' filenames = ['*.fy', '*.fancypack'] aliases = ['fancy', 'fy'] mimetypes = ['text/x-fancysrc'] version_added = '1.5'
tokens = { # copied from PerlLexer: 'balanced-regex': [ (r'/(\\\\|\\[^\\]|[^/\\])*/[egimosx]*', String.Regex, '#pop'), (r'!(\\\\|\\[^\\]|[^!\\])*![egimosx]*', String.Regex, '#pop'), (r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'), (r'\{(\\\\|\\[^\\]|[^}\\])*\}[egimosx]*', String.Regex, '#pop'), (r'<(\\\\|\\[^\\]|[^>\\])*>[egimosx]*', String.Regex, '#pop'), (r'\[(\\\\|\\[^\\]|[^\]\\])*\][egimosx]*', String.Regex, '#pop'), (r'\((\\\\|\\[^\\]|[^)\\])*\)[egimosx]*', String.Regex, '#pop'), (r'@(\\\\|\\[^\\]|[^@\\])*@[egimosx]*', String.Regex, '#pop'), (r'%(\\\\|\\[^\\]|[^%\\])*%[egimosx]*', String.Regex, '#pop'), (r'\$(\\\\|\\[^\\]|[^$\\])*\$[egimosx]*', String.Regex, '#pop'), ], 'root': [ (r'\s+', Whitespace),
# balanced delimiters (copied from PerlLexer): (r's\{(\\\\|\\[^\\]|[^}\\])*\}\s*', String.Regex, 'balanced-regex'), (r's<(\\\\|\\[^\\]|[^>\\])*>\s*', String.Regex, 'balanced-regex'), (r's\[(\\\\|\\[^\\]|[^\]\\])*\]\s*', String.Regex, 'balanced-regex'), (r's\((\\\\|\\[^\\]|[^)\\])*\)\s*', String.Regex, 'balanced-regex'), (r'm?/(\\\\|\\[^\\]|[^///\n])*/[gcimosx]*', String.Regex), (r'm(?=[/!\\{<\[(@%$])', String.Regex, 'balanced-regex'),
# Comments (r'#(.*?)\n', Comment.Single), # Symbols (r'\'([^\'\s\[\](){}]+|\[\])', String.Symbol), # Multi-line DoubleQuotedString (r'"""(\\\\|\\[^\\]|[^\\])*?"""', String), # DoubleQuotedString (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # keywords (r'(def|class|try|catch|finally|retry|return|return_local|match|' r'case|->|=>)\b', Keyword), # constants (r'(self|super|nil|false|true)\b', Name.Constant), (r'[(){};,/?|:\\]', Punctuation), # names (words(( 'Object', 'Array', 'Hash', 'Directory', 'File', 'Class', 'String', 'Number', 'Enumerable', 'FancyEnumerable', 'Block', 'TrueClass', 'NilClass', 'FalseClass', 'Tuple', 'Symbol', 'Stack', 'Set', 'FancySpec', 'Method', 'Package', 'Range'), suffix=r'\b'), Name.Builtin), # functions (r'[a-zA-Z](\w|[-+?!=*/^><%])*:', Name.Function), # operators, must be below functions (r'[-+*/~,<>=&!?%^\[\].$]+', Operator), (r'[A-Z]\w*', Name.Constant), (r'@[a-zA-Z_]\w*', Name.Variable.Instance), (r'@@[a-zA-Z_]\w*', Name.Variable.Class), ('@@?', Operator), (r'[a-zA-Z_]\w*', Name), # numbers - / checks are necessary to avoid mismarking regexes, # see comment in RubyLexer (r'(0[oO]?[0-7]+(?:_[0-7]+)*)(\s*)([/?])?', bygroups(Number.Oct, Whitespace, Operator)), (r'(0[xX][0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*)(\s*)([/?])?', bygroups(Number.Hex, Whitespace, Operator)), (r'(0[bB][01]+(?:_[01]+)*)(\s*)([/?])?', bygroups(Number.Bin, Whitespace, Operator)), (r'([\d]+(?:_\d+)*)(\s*)([/?])?', bygroups(Number.Integer, Whitespace, Operator)), (r'\d+([eE][+-]?[0-9]+)|\d+\.\d+([eE][+-]?[0-9]+)?', Number.Float), (r'\d+', Number.Integer) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222""" pygments.lexers.rust ~~~~~~~~~~~~~~~~~~~~
Lexers for the Rust language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroups, words, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['RustLexer']
class RustLexer(RegexLexer): """ Lexer for the Rust programming language (version 1.47). """ name = 'Rust' url = 'https://www.rust-lang.org/' filenames = ['*.rs', '*.rs.in'] aliases = ['rust', 'rs'] mimetypes = ['text/rust', 'text/x-rust'] version_added = '1.6'
keyword_types = (words(( 'u8', 'u16', 'u32', 'u64', 'u128', 'i8', 'i16', 'i32', 'i64', 'i128', 'usize', 'isize', 'f32', 'f64', 'char', 'str', 'bool', ), suffix=r'\b'), Keyword.Type)
builtin_funcs_types = (words(( 'Copy', 'Send', 'Sized', 'Sync', 'Unpin', 'Drop', 'Fn', 'FnMut', 'FnOnce', 'drop', 'Box', 'ToOwned', 'Clone', 'PartialEq', 'PartialOrd', 'Eq', 'Ord', 'AsRef', 'AsMut', 'Into', 'From', 'Default', 'Iterator', 'Extend', 'IntoIterator', 'DoubleEndedIterator', 'ExactSizeIterator', 'Option', 'Some', 'None', 'Result', 'Ok', 'Err', 'String', 'ToString', 'Vec', ), suffix=r'\b'), Name.Builtin)
builtin_macros = (words(( 'asm', 'assert', 'assert_eq', 'assert_ne', 'cfg', 'column', 'compile_error', 'concat', 'concat_idents', 'dbg', 'debug_assert', 'debug_assert_eq', 'debug_assert_ne', 'env', 'eprint', 'eprintln', 'file', 'format', 'format_args', 'format_args_nl', 'global_asm', 'include', 'include_bytes', 'include_str', 'is_aarch64_feature_detected', 'is_arm_feature_detected', 'is_mips64_feature_detected', 'is_mips_feature_detected', 'is_powerpc64_feature_detected', 'is_powerpc_feature_detected', 'is_x86_feature_detected', 'line', 'llvm_asm', 'log_syntax', 'macro_rules', 'matches', 'module_path', 'option_env', 'panic', 'print', 'println', 'stringify', 'thread_local', 'todo', 'trace_macros', 'unimplemented', 'unreachable', 'vec', 'write', 'writeln', ), suffix=r'!'), Name.Function.Magic)
tokens = { 'root': [ # rust allows a file to start with a shebang, but if the first line # starts with #![ then it's not a shebang but a crate attribute. (r'#![^[\r\n].*$', Comment.Preproc), default('base'), ], 'base': [ # Whitespace and Comments (r'\n', Whitespace), (r'\s+', Whitespace), (r'//!.*?\n', String.Doc), (r'///(\n|[^/].*?\n)', String.Doc), (r'//(.*?)\n', Comment.Single), (r'/\*\*(\n|[^/*])', String.Doc, 'doccomment'), (r'/\*!', String.Doc, 'doccomment'), (r'/\*', Comment.Multiline, 'comment'),
# Macro parameters (r"""\$([a-zA-Z_]\w*|\(,?|\),?|,?)""", Comment.Preproc), # Keywords (words(('as', 'async', 'await', 'box', 'const', 'crate', 'dyn', 'else', 'extern', 'for', 'if', 'impl', 'in', 'loop', 'match', 'move', 'mut', 'pub', 'ref', 'return', 'static', 'super', 'trait', 'unsafe', 'use', 'where', 'while'), suffix=r'\b'), Keyword), (words(('abstract', 'become', 'do', 'final', 'macro', 'override', 'priv', 'typeof', 'try', 'unsized', 'virtual', 'yield'), suffix=r'\b'), Keyword.Reserved), (r'(true|false)\b', Keyword.Constant), (r'self\b', Name.Builtin.Pseudo), (r'mod\b', Keyword, 'modname'), (r'let\b', Keyword.Declaration), (r'fn\b', Keyword, 'funcname'), (r'(struct|enum|type|union)\b', Keyword, 'typename'), (r'(default)(\s+)(type|fn)\b', bygroups(Keyword, Whitespace, Keyword)), keyword_types, (r'[sS]elf\b', Name.Builtin.Pseudo), # Prelude (taken from Rust's src/libstd/prelude.rs) builtin_funcs_types, builtin_macros, # Path separators, so types don't catch them. (r'::\b', Punctuation), # Types in positions. (r'(?::|->)', Punctuation, 'typename'), # Labels (r'(break|continue)(\b\s*)(\'[A-Za-z_]\w*)?', bygroups(Keyword, Text.Whitespace, Name.Label)),
# Character literals (r"""'(\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0""" r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""", String.Char), (r"""b'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\0""" r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""", String.Char),
# Binary literals (r'0b[01_]+', Number.Bin, 'number_lit'), # Octal literals (r'0o[0-7_]+', Number.Oct, 'number_lit'), # Hexadecimal literals (r'0[xX][0-9a-fA-F_]+', Number.Hex, 'number_lit'), # Decimal literals (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|' r'\.[0-9_]*(?!\.)|[eE][+\-]?[0-9_]+)', Number.Float, 'number_lit'), (r'[0-9][0-9_]*', Number.Integer, 'number_lit'),
# String literals (r'b"', String, 'bytestring'), (r'"', String, 'string'), (r'(?s)b?r(#*)".*?"\1', String),
# Lifetime names (r"'", Operator, 'lifetime'),
# Operators and Punctuation (r'\.\.=?', Operator), (r'[{}()\[\],.;]', Punctuation), (r'[+\-*/%&|<>^!~@=:?]', Operator),
# Identifiers (r'[a-zA-Z_]\w*', Name), # Raw identifiers (r'r#[a-zA-Z_]\w*', Name),
# Attributes (r'#!?\[', Comment.Preproc, 'attribute['),
# Misc # Lone hashes: not used in Rust syntax, but allowed in macro # arguments, most famously for quote::quote!() (r'#', Punctuation), ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'doccomment': [ (r'[^*/]+', String.Doc), (r'/\*', String.Doc, '#push'), (r'\*/', String.Doc, '#pop'), (r'[*/]', String.Doc), ], 'modname': [ (r'\s+', Whitespace), (r'[a-zA-Z_]\w*', Name.Namespace, '#pop'), default('#pop'), ], 'funcname': [ (r'\s+', Whitespace), (r'[a-zA-Z_]\w*', Name.Function, '#pop'), default('#pop'), ], 'typename': [ (r'\s+', Whitespace), (r'&', Keyword.Pseudo), (r"'", Operator, 'lifetime'), builtin_funcs_types, keyword_types, (r'[a-zA-Z_]\w*', Name.Class, '#pop'), default('#pop'), ], 'lifetime': [ (r"(static|_)", Name.Builtin), (r"[a-zA-Z_]+\w*", Name.Attribute), default('#pop'), ], 'number_lit': [ (r'[ui](8|16|32|64|size)', Keyword, '#pop'), (r'f(32|64)', Keyword, '#pop'), default('#pop'), ], 'string': [ (r'"', String, '#pop'), (r"""\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0""" r"""|\\u\{[0-9a-fA-F]{1,6}\}""", String.Escape), (r'[^\\"]+', String), (r'\\', String), ], 'bytestring': [ (r"""\\x[89a-fA-F][0-9a-fA-F]""", String.Escape), include('string'), ], 'attribute_common': [ (r'"', String, 'string'), (r'\[', Comment.Preproc, 'attribute['), ], 'attribute[': [ include('attribute_common'), (r'\]', Comment.Preproc, '#pop'), (r'[^"\]\[]+', Comment.Preproc), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227""" pygments.lexers.sas ~~~~~~~~~~~~~~~~~~~
Lexer for SAS.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import refrom pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Comment, Keyword, Name, Number, String, Text, \ Other, Generic
__all__ = ['SASLexer']
class SASLexer(RegexLexer): """ For SAS files. """ # Syntax from syntax/sas.vim by James Kidd <james.kidd@covance.com>
name = 'SAS' aliases = ['sas'] filenames = ['*.SAS', '*.sas'] mimetypes = ['text/x-sas', 'text/sas', 'application/x-sas'] url = 'https://en.wikipedia.org/wiki/SAS_(software)' version_added = '2.2' flags = re.IGNORECASE | re.MULTILINE
builtins_macros = ( "bquote", "nrbquote", "cmpres", "qcmpres", "compstor", "datatyp", "display", "do", "else", "end", "eval", "global", "goto", "if", "index", "input", "keydef", "label", "left", "length", "let", "local", "lowcase", "macro", "mend", "nrquote", "nrstr", "put", "qleft", "qlowcase", "qscan", "qsubstr", "qsysfunc", "qtrim", "quote", "qupcase", "scan", "str", "substr", "superq", "syscall", "sysevalf", "sysexec", "sysfunc", "sysget", "syslput", "sysprod", "sysrc", "sysrput", "then", "to", "trim", "unquote", "until", "upcase", "verify", "while", "window" )
builtins_conditionals = ( "do", "if", "then", "else", "end", "until", "while" )
builtins_statements = ( "abort", "array", "attrib", "by", "call", "cards", "cards4", "catname", "continue", "datalines", "datalines4", "delete", "delim", "delimiter", "display", "dm", "drop", "endsas", "error", "file", "filename", "footnote", "format", "goto", "in", "infile", "informat", "input", "keep", "label", "leave", "length", "libname", "link", "list", "lostcard", "merge", "missing", "modify", "options", "output", "out", "page", "put", "redirect", "remove", "rename", "replace", "retain", "return", "select", "set", "skip", "startsas", "stop", "title", "update", "waitsas", "where", "window", "x", "systask" )
builtins_sql = ( "add", "and", "alter", "as", "cascade", "check", "create", "delete", "describe", "distinct", "drop", "foreign", "from", "group", "having", "index", "insert", "into", "in", "key", "like", "message", "modify", "msgtype", "not", "null", "on", "or", "order", "primary", "references", "reset", "restrict", "select", "set", "table", "unique", "update", "validate", "view", "where" )
builtins_functions = ( "abs", "addr", "airy", "arcos", "arsin", "atan", "attrc", "attrn", "band", "betainv", "blshift", "bnot", "bor", "brshift", "bxor", "byte", "cdf", "ceil", "cexist", "cinv", "close", "cnonct", "collate", "compbl", "compound", "compress", "cos", "cosh", "css", "curobs", "cv", "daccdb", "daccdbsl", "daccsl", "daccsyd", "dacctab", "dairy", "date", "datejul", "datepart", "datetime", "day", "dclose", "depdb", "depdbsl", "depsl", "depsyd", "deptab", "dequote", "dhms", "dif", "digamma", "dim", "dinfo", "dnum", "dopen", "doptname", "doptnum", "dread", "dropnote", "dsname", "erf", "erfc", "exist", "exp", "fappend", "fclose", "fcol", "fdelete", "fetch", "fetchobs", "fexist", "fget", "fileexist", "filename", "fileref", "finfo", "finv", "fipname", "fipnamel", "fipstate", "floor", "fnonct", "fnote", "fopen", "foptname", "foptnum", "fpoint", "fpos", "fput", "fread", "frewind", "frlen", "fsep", "fuzz", "fwrite", "gaminv", "gamma", "getoption", "getvarc", "getvarn", "hbound", "hms", "hosthelp", "hour", "ibessel", "index", "indexc", "indexw", "input", "inputc", "inputn", "int", "intck", "intnx", "intrr", "irr", "jbessel", "juldate", "kurtosis", "lag", "lbound", "left", "length", "lgamma", "libname", "libref", "log", "log10", "log2", "logpdf", "logpmf", "logsdf", "lowcase", "max", "mdy", "mean", "min", "minute", "mod", "month", "mopen", "mort", "n", "netpv", "nmiss", "normal", "note", "npv", "open", "ordinal", "pathname", "pdf", "peek", "peekc", "pmf", "point", "poisson", "poke", "probbeta", "probbnml", "probchi", "probf", "probgam", "probhypr", "probit", "probnegb", "probnorm", "probt", "put", "putc", "putn", "qtr", "quote", "ranbin", "rancau", "ranexp", "rangam", "range", "rank", "rannor", "ranpoi", "rantbl", "rantri", "ranuni", "repeat", "resolve", "reverse", "rewind", "right", "round", "saving", "scan", "sdf", "second", "sign", "sin", "sinh", "skewness", "soundex", "spedis", "sqrt", "std", "stderr", "stfips", "stname", "stnamel", "substr", "sum", "symget", "sysget", "sysmsg", "sysprod", "sysrc", "system", "tan", "tanh", "time", "timepart", "tinv", "tnonct", "today", "translate", "tranwrd", "trigamma", "trim", "trimn", "trunc", "uniform", "upcase", "uss", "var", "varfmt", "varinfmt", "varlabel", "varlen", "varname", "varnum", "varray", "varrayx", "vartype", "verify", "vformat", "vformatd", "vformatdx", "vformatn", "vformatnx", "vformatw", "vformatwx", "vformatx", "vinarray", "vinarrayx", "vinformat", "vinformatd", "vinformatdx", "vinformatn", "vinformatnx", "vinformatw", "vinformatwx", "vinformatx", "vlabel", "vlabelx", "vlength", "vlengthx", "vname", "vnamex", "vtype", "vtypex", "weekday", "year", "yyq", "zipfips", "zipname", "zipnamel", "zipstate" )
tokens = { 'root': [ include('comments'), include('proc-data'), include('cards-datalines'), include('logs'), include('general'), (r'.', Text), ], # SAS is multi-line regardless, but * is ended by ; 'comments': [ (r'^\s*\*.*?;', Comment), (r'/\*.*?\*/', Comment), (r'^\s*\*(.|\n)*?;', Comment.Multiline), (r'/[*](.|\n)*?[*]/', Comment.Multiline), ], # Special highlight for proc, data, quit, run 'proc-data': [ (r'(^|;)\s*(proc \w+|data|run|quit)[\s;]', Keyword.Reserved), ], # Special highlight cards and datalines 'cards-datalines': [ (r'^\s*(datalines|cards)\s*;\s*$', Keyword, 'data'), ], 'data': [ (r'(.|\n)*^\s*;\s*$', Other, '#pop'), ], # Special highlight for put NOTE|ERROR|WARNING (order matters) 'logs': [ (r'\n?^\s*%?put ', Keyword, 'log-messages'), ], 'log-messages': [ (r'NOTE(:|-).*', Generic, '#pop'), (r'WARNING(:|-).*', Generic.Emph, '#pop'), (r'ERROR(:|-).*', Generic.Error, '#pop'), include('general'), ], 'general': [ include('keywords'), include('vars-strings'), include('special'), include('numbers'), ], # Keywords, statements, functions, macros 'keywords': [ (words(builtins_statements, prefix = r'\b', suffix = r'\b'), Keyword), (words(builtins_sql, prefix = r'\b', suffix = r'\b'), Keyword), (words(builtins_conditionals, prefix = r'\b', suffix = r'\b'), Keyword), (words(builtins_macros, prefix = r'%', suffix = r'\b'), Name.Builtin), (words(builtins_functions, prefix = r'\b', suffix = r'\('), Name.Builtin), ], # Strings and user-defined variables and macros (order matters) 'vars-strings': [ (r'&[a-z_]\w{0,31}\.?', Name.Variable), (r'%[a-z_]\w{0,31}', Name.Function), (r'\'', String, 'string_squote'), (r'"', String, 'string_dquote'), ], 'string_squote': [ ('\'', String, '#pop'), (r'\\\\|\\"|\\\n', String.Escape), # AFAIK, macro variables are not evaluated in single quotes # (r'&', Name.Variable, 'validvar'), (r'[^$\'\\]+', String), (r'[$\'\\]', String), ], 'string_dquote': [ (r'"', String, '#pop'), (r'\\\\|\\"|\\\n', String.Escape), (r'&', Name.Variable, 'validvar'), (r'[^$&"\\]+', String), (r'[$"\\]', String), ], 'validvar': [ (r'[a-z_]\w{0,31}\.?', Name.Variable, '#pop'), ], # SAS numbers and special variables 'numbers': [ (r'\b[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)(E[+-]?[0-9]+)?i?\b', Number), ], 'special': [ (r'(null|missing|_all_|_automatic_|_character_|_n_|' r'_infile_|_name_|_null_|_numeric_|_user_|_webout_)', Keyword.Constant), ], # 'operators': [ # (r'(-|=|<=|>=|<|>|<>|&|!=|' # r'\||\*|\+|\^|/|!|~|~=)', Operator) # ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171""" pygments.lexers.savi ~~~~~~~~~~~~~~~~~~~~
Lexer for Savi.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, includefrom pygments.token import Whitespace, Keyword, Name, String, Number, \ Operator, Punctuation, Comment, Generic, Error
__all__ = ['SaviLexer']
# The canonical version of this file can be found in the following repository,# where it is kept in sync with any language changes, as well as the other# pygments-like lexers that are maintained for use with other tools:# - https://github.com/savi-lang/savi/blob/main/tooling/pygments/lexers/savi.py## If you're changing this file in the pygments repository, please ensure that# any changes you make are also propagated to the official Savi repository,# in order to avoid accidental clobbering of your changes later when an update# from the Savi repository flows forward into the pygments repository.## If you're changing this file in the Savi repository, please ensure that# any changes you make are also reflected in the other pygments-like lexers# (rouge, vscode, etc) so that all of the lexers can be kept cleanly in sync.
class SaviLexer(RegexLexer): """ For Savi source code.
.. versionadded: 2.10 """
name = 'Savi' url = 'https://github.com/savi-lang/savi' aliases = ['savi'] filenames = ['*.savi'] version_added = ''
tokens = { "root": [ # Line Comment (r'//.*?$', Comment.Single),
# Doc Comment (r'::.*?$', Comment.Single),
# Capability Operator (r'(\')(\w+)(?=[^\'])', bygroups(Operator, Name)),
# Double-Quote String (r'\w?"', String.Double, "string.double"),
# Single-Char String (r"'", String.Char, "string.char"),
# Type Name (r'(_?[A-Z]\w*)', Name.Class),
# Nested Type Name (r'(\.)(\s*)(_?[A-Z]\w*)', bygroups(Punctuation, Whitespace, Name.Class)),
# Declare (r'^([ \t]*)(:\w+)', bygroups(Whitespace, Name.Tag), "decl"),
# Error-Raising Calls/Names (r'((\w+|\+|\-|\*)\!)', Generic.Deleted),
# Numeric Values (r'\b\d([\d_]*(\.[\d_]+)?)\b', Number),
# Hex Numeric Values (r'\b0x([0-9a-fA-F_]+)\b', Number.Hex),
# Binary Numeric Values (r'\b0b([01_]+)\b', Number.Bin),
# Function Call (with braces) (r'\w+(?=\()', Name.Function),
# Function Call (with receiver) (r'(\.)(\s*)(\w+)', bygroups(Punctuation, Whitespace, Name.Function)),
# Function Call (with self receiver) (r'(@)(\w+)', bygroups(Punctuation, Name.Function)),
# Parenthesis (r'\(', Punctuation, "root"), (r'\)', Punctuation, "#pop"),
# Brace (r'\{', Punctuation, "root"), (r'\}', Punctuation, "#pop"),
# Bracket (r'\[', Punctuation, "root"), (r'(\])(\!)', bygroups(Punctuation, Generic.Deleted), "#pop"), (r'\]', Punctuation, "#pop"),
# Punctuation (r'[,;:\.@]', Punctuation),
# Piping Operators (r'(\|\>)', Operator),
# Branching Operators (r'(\&\&|\|\||\?\?|\&\?|\|\?|\.\?)', Operator),
# Comparison Operators (r'(\<\=\>|\=\~|\=\=|\<\=|\>\=|\<|\>)', Operator),
# Arithmetic Operators (r'(\+|\-|\/|\*|\%)', Operator),
# Assignment Operators (r'(\=)', Operator),
# Other Operators (r'(\!|\<\<|\<|\&|\|)', Operator),
# Identifiers (r'\b\w+\b', Name),
# Whitespace (r'[ \t\r]+\n*|\n+', Whitespace), ],
# Declare (nested rules) "decl": [ (r'\b[a-z_]\w*\b(?!\!)', Keyword.Declaration), (r':', Punctuation, "#pop"), (r'\n', Whitespace, "#pop"), include("root"), ],
# Double-Quote String (nested rules) "string.double": [ (r'\\\(', String.Interpol, "string.interpolation"), (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\x[0-9a-fA-F]{2}', String.Escape), (r'\\[bfnrt\\\']', String.Escape), (r'\\"', String.Escape), (r'"', String.Double, "#pop"), (r'[^\\"]+', String.Double), (r'.', Error), ],
# Single-Char String (nested rules) "string.char": [ (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\x[0-9a-fA-F]{2}', String.Escape), (r'\\[bfnrt\\\']', String.Escape), (r"\\'", String.Escape), (r"'", String.Char, "#pop"), (r"[^\\']+", String.Char), (r'.', Error), ],
# Interpolation inside String (nested rules) "string.interpolation": [ (r"\)", String.Interpol, "#pop"), include("root"), ] }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485""" pygments.lexers.scdoc ~~~~~~~~~~~~~~~~~~~~~
Lexer for scdoc, a simple man page generator.
: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, thisfrom pygments.token import Text, Comment, Keyword, String, Generic
__all__ = ['ScdocLexer']
class ScdocLexer(RegexLexer): """ `scdoc` is a simple man page generator for POSIX systems written in C99. """ name = 'scdoc' url = 'https://git.sr.ht/~sircmpwn/scdoc' aliases = ['scdoc', 'scd'] filenames = ['*.scd', '*.scdoc'] version_added = '2.5' flags = re.MULTILINE
tokens = { 'root': [ # comment (r'^(;.+\n)', bygroups(Comment)),
# heading with pound prefix (r'^(#)([^#].+\n)', bygroups(Generic.Heading, Text)), (r'^(#{2})(.+\n)', bygroups(Generic.Subheading, Text)), # bulleted lists (r'^(\s*)([*-])(\s)(.+\n)', bygroups(Text, Keyword, Text, using(this, state='inline'))), # numbered lists (r'^(\s*)(\.+\.)( .+\n)', bygroups(Text, Keyword, using(this, state='inline'))), # quote (r'^(\s*>\s)(.+\n)', bygroups(Keyword, Generic.Emph)), # text block (r'^(```\n)([\w\W]*?)(^```$)', bygroups(String, Text, String)),
include('inline'), ], 'inline': [ # escape (r'\\.', Text), # underlines (r'(\s)(_[^_]+_)(\W|\n)', bygroups(Text, Generic.Emph, Text)), # bold (r'(\s)(\*[^*]+\*)(\W|\n)', bygroups(Text, Generic.Strong, Text)), # inline code (r'`[^`]+`', String.Backtick),
# general text, must come last! (r'[^\\\s]+', Text), (r'.', Text), ], }
def analyse_text(text): """We checks for bold and underline text with * and _. Also every scdoc file must start with a strictly defined first line.""" result = 0
if '*' in text: result += 0.01
if '_' in text: result += 0.01
# name(section) ["left_footer" ["center_header"]] first_line = text.partition('\n')[0] scdoc_preamble_pattern = r'^.*\([1-7]\)( "[^"]+"){0,2}$'
if re.search(scdoc_preamble_pattern, first_line): result += 0.5
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638""" pygments.lexers.scripting ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for scripting and embedded 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, default, combined, \ wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error, Whitespace, Otherfrom pygments.util import get_bool_opt, get_list_opt
__all__ = ['LuaLexer', 'LuauLexer', 'MoonScriptLexer', 'ChaiscriptLexer', 'LSLLexer', 'AppleScriptLexer', 'RexxLexer', 'MOOCodeLexer', 'HybrisLexer', 'EasytrieveLexer', 'JclLexer', 'MiniScriptLexer']
def all_lua_builtins(): from pygments.lexers._lua_builtins import MODULES return [w for values in MODULES.values() for w in values]
class LuaLexer(RegexLexer): """ For Lua source code.
Additional options accepted:
`func_name_highlighting` If given and ``True``, highlight builtin function names (default: ``True``). `disabled_modules` If given, must be a list of module names whose function names should not be highlighted. By default all modules are highlighted.
To get a list of allowed modules have a look into the `_lua_builtins` module:
.. sourcecode:: pycon
>>> from pygments.lexers._lua_builtins import MODULES >>> MODULES.keys() ['string', 'coroutine', 'modules', 'io', 'basic', ...] """
name = 'Lua' url = 'https://www.lua.org/' aliases = ['lua'] filenames = ['*.lua', '*.wlua'] mimetypes = ['text/x-lua', 'application/x-lua'] version_added = ''
_comment_multiline = r'(?:--\[(?P<level>=*)\[[\w\W]*?\](?P=level)\])' _comment_single = r'(?:--.*$)' _space = r'(?:\s+(?!\s))' _s = rf'(?:{_comment_multiline}|{_comment_single}|{_space})' # A lookahead-safe version of _s that avoids catastrophic backtracking. # The _comment_multiline pattern contains [\w\W]*? which, when used # inside a lookahead with a * quantifier, causes exponential blowup. # This version skips only whitespace; comments between an identifier # and a following [.:] or ( are rare enough to sacrifice. _s_la = r'\s' _name = r'(?:[^\W\d]\w*)'
tokens = { 'root': [ # Lua allows a file to start with a shebang. (r'#!.*', Comment.Preproc), default('base'), ], 'ws': [ (_comment_multiline, Comment.Multiline), (_comment_single, Comment.Single), (_space, Whitespace), ], 'base': [ include('ws'),
(r'(?i)0x[\da-f]*(\.[\da-f]*)?(p[+-]?\d+)?', Number.Hex), (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float), (r'(?i)\d+e[+-]?\d+', Number.Float), (r'\d+', Number.Integer),
# multiline strings (r'(?s)\[(=*)\[.*?\]\1\]', String),
(r'::', Punctuation, 'label'), (r'\.{3}', Punctuation), (r'[=<>|~&+\-*/%#^]+|\.\.', Operator), (r'[\[\]{}().,:;]+', Punctuation), (r'(and|or|not)\b', Operator.Word),
(words([ 'break', 'do', 'else', 'elseif', 'end', 'for', 'if', 'in', 'repeat', 'return', 'then', 'until', 'while' ], suffix=r'\b'), Keyword.Reserved), (r'goto\b', Keyword.Reserved, 'goto'), (r'(local)\b', Keyword.Declaration), (r'(true|false|nil)\b', Keyword.Constant),
(r'(function)\b', Keyword.Reserved, 'funcname'),
(words(all_lua_builtins(), suffix=r"\b"), Name.Builtin), (fr'[A-Za-z_]\w*(?={_s_la}*[.:])', Name.Variable, 'varname'), (fr'[A-Za-z_]\w*(?={_s_la}*\()', Name.Function), (r'[A-Za-z_]\w*', Name.Variable),
("'", String.Single, combined('stringescape', 'sqs')), ('"', String.Double, combined('stringescape', 'dqs')) ],
'varname': [ include('ws'), (r'\.\.', Operator, '#pop'), (r'[.:]', Punctuation), (rf'{_name}(?={_s_la}*[.:])', Name.Property), (rf'{_name}(?={_s_la}*\()', Name.Function, '#pop'), (_name, Name.Property, '#pop'), ],
'funcname': [ include('ws'), (r'[.:]', Punctuation), (rf'{_name}(?={_s_la}*[.:])', Name.Class), (_name, Name.Function, '#pop'), # inline function (r'\(', Punctuation, '#pop'), ],
'goto': [ include('ws'), (_name, Name.Label, '#pop'), ],
'label': [ include('ws'), (r'::', Punctuation, '#pop'), (_name, Name.Label), ],
'stringescape': [ (r'\\([abfnrtv\\"\']|[\r\n]{1,2}|z\s*|x[0-9a-fA-F]{2}|\d{1,3}|' r'u\{[0-9a-fA-F]+\})', String.Escape), ],
'sqs': [ (r"'", String.Single, '#pop'), (r"[^\\']+", String.Single), ],
'dqs': [ (r'"', String.Double, '#pop'), (r'[^\\"]+', String.Double), ] }
def __init__(self, **options): self.func_name_highlighting = get_bool_opt( options, 'func_name_highlighting', True) self.disabled_modules = get_list_opt(options, 'disabled_modules', [])
self._functions = set() if self.func_name_highlighting: from pygments.lexers._lua_builtins import MODULES for mod, func in MODULES.items(): if mod not in self.disabled_modules: self._functions.update(func) RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name.Builtin and value not in self._functions: if '.' in value: a, b = value.split('.') yield index, Name, a yield index + len(a), Punctuation, '.' yield index + len(a) + 1, Name, b else: yield index, Name, value continue yield index, token, value
def _luau_make_expression(should_pop, _s, _s_la): temp_list = [ (r'0[xX][\da-fA-F_]*', Number.Hex, '#pop'), (r'0[bB][\d_]*', Number.Bin, '#pop'), (r'\.?\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?[\d_]+)?', Number.Float, '#pop'),
(words(( 'true', 'false', 'nil' ), suffix=r'\b'), Keyword.Constant, '#pop'),
(r'\[(=*)\[[.\n]*?\]\1\]', String, '#pop'),
(r'(\.)([a-zA-Z_]\w*)(?=%s*[({"\'])', bygroups(Punctuation, Name.Function), '#pop'), (r'(\.)([a-zA-Z_]\w*)', bygroups(Punctuation, Name.Variable), '#pop'),
(rf'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*(?={_s_la}*[({{"\'])', Name.Other, '#pop'), (r'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*', Name, '#pop'), ] if should_pop: return temp_list return [entry[:2] for entry in temp_list]
def _luau_make_expression_special(should_pop): temp_list = [ (r'\{', Punctuation, ('#pop', 'closing_brace_base', 'expression')), (r'\(', Punctuation, ('#pop', 'closing_parenthesis_base', 'expression')),
(r'::?', Punctuation, ('#pop', 'type_end', 'type_start')),
(r"'", String.Single, ('#pop', 'string_single')), (r'"', String.Double, ('#pop', 'string_double')), (r'`', String.Backtick, ('#pop', 'string_interpolated')), ] if should_pop: return temp_list return [(entry[0], entry[1], entry[2][1:]) for entry in temp_list]
class LuauLexer(RegexLexer): """ For Luau source code.
Additional options accepted:
`include_luau_builtins` If given and ``True``, automatically highlight Luau builtins (default: ``True``). `include_roblox_builtins` If given and ``True``, automatically highlight Roblox-specific builtins (default: ``False``). `additional_builtins` If given, must be a list of additional builtins to highlight. `disabled_builtins` If given, must be a list of builtins that will not be highlighted. """
name = 'Luau' url = 'https://luau-lang.org/' aliases = ['luau'] filenames = ['*.luau'] version_added = '2.18'
_comment_multiline = r'(?:--\[(?P<level>=*)\[[\w\W]*?\](?P=level)\])' _comment_single = r'(?:--.*$)' _s = r'(?:{}|{}|{})'.format(_comment_multiline, _comment_single, r'\s+') # Lookahead-safe version — avoids catastrophic backtracking from # [\w\W]*? inside _comment_multiline when combined with * quantifier. _s_la = r'\s'
tokens = { 'root': [ (r'#!.*', Comment.Hashbang, 'base'), default('base'), ],
'ws': [ (_comment_multiline, Comment.Multiline), (_comment_single, Comment.Single), (r'\s+', Whitespace), ],
'base': [ include('ws'),
*_luau_make_expression_special(False), (r'\.\.\.', Punctuation),
(rf'type\b(?={_s}+[a-zA-Z_])', Keyword.Reserved, 'type_declaration'), (rf'export\b(?={_s}+[a-zA-Z_])', Keyword.Reserved),
(r'(?:\.\.|//|[+\-*\/%^<>=])=?', Operator, 'expression'), (r'~=', Operator, 'expression'),
(words(( 'and', 'or', 'not' ), suffix=r'\b'), Operator.Word, 'expression'),
(words(( 'elseif', 'for', 'if', 'in', 'repeat', 'return', 'until', 'while'), suffix=r'\b'), Keyword.Reserved, 'expression'), (r'local\b', Keyword.Declaration, 'expression'),
(r'function\b', Keyword.Reserved, ('expression', 'func_name')),
(r'[\])};]+', Punctuation),
include('expression_static'), *_luau_make_expression(False, _s, _s_la),
(r'[\[.,]', Punctuation, 'expression'), ], 'expression_static': [ (words(( 'break', 'continue', 'do', 'else', 'elseif', 'end', 'for', 'if', 'in', 'repeat', 'return', 'then', 'until', 'while'), suffix=r'\b'), Keyword.Reserved), ], 'expression': [ include('ws'),
(r'if\b', Keyword.Reserved, ('ternary', 'expression')),
(r'local\b', Keyword.Declaration), *_luau_make_expression_special(True), (r'\.\.\.', Punctuation, '#pop'),
(r'function\b', Keyword.Reserved, 'func_name'),
include('expression_static'), *_luau_make_expression(True, _s, _s_la),
default('#pop'), ], 'ternary': [ include('ws'),
(r'else\b', Keyword.Reserved, '#pop'), (words(( 'then', 'elseif', ), suffix=r'\b'), Operator.Reserved, 'expression'),
default('#pop'), ],
'closing_brace_pop': [ (r'\}', Punctuation, '#pop'), ], 'closing_parenthesis_pop': [ (r'\)', Punctuation, '#pop'), ], 'closing_gt_pop': [ (r'>', Punctuation, '#pop'), ],
'closing_parenthesis_base': [ include('closing_parenthesis_pop'), include('base'), ], 'closing_parenthesis_type': [ include('closing_parenthesis_pop'), include('type'), ], 'closing_brace_base': [ include('closing_brace_pop'), include('base'), ], 'closing_brace_type': [ include('closing_brace_pop'), include('type'), ], 'closing_gt_type': [ include('closing_gt_pop'), include('type'), ],
'string_escape': [ (r'\\z\s*', String.Escape), (r'\\(?:[abfnrtvz\\"\'`\{\n])|[\r\n]{1,2}|x[\da-fA-F]{2}|\d{1,3}|' r'u\{\}[\da-fA-F]*\}', String.Escape), ], 'string_single': [ include('string_escape'),
(r"'", String.Single, "#pop"), (r"[^\\']+", String.Single), ], 'string_double': [ include('string_escape'),
(r'"', String.Double, "#pop"), (r'[^\\"]+', String.Double), ], 'string_interpolated': [ include('string_escape'),
(r'\{', Punctuation, ('closing_brace_base', 'expression')),
(r'`', String.Backtick, "#pop"), (r'[^\\`\{]+', String.Backtick), ],
'func_name': [ include('ws'),
(r'[.:]', Punctuation), (rf'[a-zA-Z_]\w*(?={_s_la}*[.:])', Name.Class), (r'[a-zA-Z_]\w*', Name.Function),
(r'<', Punctuation, 'closing_gt_type'),
(r'\(', Punctuation, '#pop'), ],
'type': [ include('ws'),
(r'\(', Punctuation, 'closing_parenthesis_type'), (r'\{', Punctuation, 'closing_brace_type'), (r'<', Punctuation, 'closing_gt_type'),
(r"'", String.Single, 'string_single'), (r'"', String.Double, 'string_double'),
(r'[|&\.,\[\]:=]+', Punctuation), (r'->', Punctuation),
(r'typeof\(', Name.Builtin, ('closing_parenthesis_base', 'expression')), (r'[a-zA-Z_]\w*', Name.Class), ], 'type_start': [ include('ws'),
(r'\(', Punctuation, ('#pop', 'closing_parenthesis_type')), (r'\{', Punctuation, ('#pop', 'closing_brace_type')), (r'<', Punctuation, ('#pop', 'closing_gt_type')),
(r"'", String.Single, ('#pop', 'string_single')), (r'"', String.Double, ('#pop', 'string_double')),
(r'typeof\(', Name.Builtin, ('#pop', 'closing_parenthesis_base', 'expression')), (r'[a-zA-Z_]\w*', Name.Class, '#pop'), ], 'type_end': [ include('ws'),
(r'[|&\.]', Punctuation, 'type_start'), (r'->', Punctuation, 'type_start'),
(r'<', Punctuation, 'closing_gt_type'),
default('#pop'), ], 'type_declaration': [ include('ws'),
(r'[a-zA-Z_]\w*', Name.Class), (r'<', Punctuation, 'closing_gt_type'),
(r'=', Punctuation, ('#pop', 'type_end', 'type_start')), ], }
def __init__(self, **options): self.include_luau_builtins = get_bool_opt( options, 'include_luau_builtins', True) self.include_roblox_builtins = get_bool_opt( options, 'include_roblox_builtins', False) self.additional_builtins = get_list_opt(options, 'additional_builtins', []) self.disabled_builtins = get_list_opt(options, 'disabled_builtins', [])
self._builtins = set(self.additional_builtins) if self.include_luau_builtins: from pygments.lexers._luau_builtins import LUAU_BUILTINS self._builtins.update(LUAU_BUILTINS) if self.include_roblox_builtins: from pygments.lexers._luau_builtins import ROBLOX_BUILTINS self._builtins.update(ROBLOX_BUILTINS) if self.additional_builtins: self._builtins.update(self.additional_builtins) self._builtins.difference_update(self.disabled_builtins)
RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name or token is Name.Other: split_value = value.split('.') complete_value = [] new_index = index for position in range(len(split_value), 0, -1): potential_string = '.'.join(split_value[:position]) if potential_string in self._builtins: yield index, Name.Builtin, potential_string new_index += len(potential_string)
if complete_value: yield new_index, Punctuation, '.' new_index += 1 break complete_value.insert(0, split_value[position - 1])
for position, substring in enumerate(complete_value): if position + 1 == len(complete_value): if token is Name: yield new_index, Name.Variable, substring continue yield new_index, Name.Function, substring continue yield new_index, Name.Variable, substring new_index += len(substring) yield new_index, Punctuation, '.' new_index += 1
continue yield index, token, value
class MoonScriptLexer(LuaLexer): """ For MoonScript source code. """
name = 'MoonScript' url = 'http://moonscript.org' aliases = ['moonscript', 'moon'] filenames = ['*.moon'] mimetypes = ['text/x-moonscript', 'application/x-moonscript'] version_added = '1.5'
tokens = { 'root': [ (r'#!(.*?)$', Comment.Preproc), default('base'), ], 'base': [ ('--.*$', Comment.Single), (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float), (r'(?i)\d+e[+-]?\d+', Number.Float), (r'(?i)0x[0-9a-f]*', Number.Hex), (r'\d+', Number.Integer), (r'\n', Whitespace), (r'[^\S\n]+', Text), (r'(?s)\[(=*)\[.*?\]\1\]', String), (r'(->|=>)', Name.Function), (r':[a-zA-Z_]\w*', Name.Variable), (r'(==|!=|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#!.\\:])', Operator), (r'[;,]', Punctuation), (r'[\[\]{}()]', Keyword.Type), (r'[a-zA-Z_]\w*:', Name.Variable), (words(( 'class', 'extends', 'if', 'then', 'super', 'do', 'with', 'import', 'export', 'while', 'elseif', 'return', 'for', 'in', 'from', 'when', 'using', 'else', 'and', 'or', 'not', 'switch', 'break'), suffix=r'\b'), Keyword), (r'(true|false|nil)\b', Keyword.Constant), (r'(and|or|not)\b', Operator.Word), (r'(self)\b', Name.Builtin.Pseudo), (r'@@?([a-zA-Z_]\w*)?', Name.Variable.Class), (r'[A-Z]\w*', Name.Class), # proper name (words(all_lua_builtins(), suffix=r"\b"), Name.Builtin), (r'[A-Za-z_]\w*', Name), ("'", String.Single, combined('stringescape', 'sqs')), ('"', String.Double, combined('stringescape', 'dqs')) ], 'stringescape': [ (r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape) ], 'strings': [ (r'[^#\\\'"]+', String), # note that strings are multi-line. # hashmarks, quotes and backslashes must be parsed one at a time ], 'interpoling_string': [ (r'\}', String.Interpol, "#pop"), include('base') ], 'dqs': [ (r'"', String.Double, '#pop'), (r'\\.|\'', String), # double-quoted string don't need ' escapes (r'#\{', String.Interpol, "interpoling_string"), (r'#', String), include('strings') ], 'sqs': [ (r"'", String.Single, '#pop'), (r'#|\\.|"', String), # single quoted strings don't need " escapses include('strings') ] }
def get_tokens_unprocessed(self, text): # set . as Operator instead of Punctuation for index, token, value in LuaLexer.get_tokens_unprocessed(self, text): if token == Punctuation and value == ".": token = Operator yield index, token, value
class ChaiscriptLexer(RegexLexer): """ For ChaiScript source code. """
name = 'ChaiScript' url = 'http://chaiscript.com/' aliases = ['chaiscript', 'chai'] filenames = ['*.chai'] mimetypes = ['text/x-chaiscript', 'application/x-chaiscript'] version_added = '2.0'
flags = re.DOTALL | re.MULTILINE
tokens = { 'commentsandwhitespace': [ (r'\s+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'^\#.*?\n', Comment.Single) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gim]+\b|\B)', String.Regex, '#pop'), (r'(?=/)', Text, ('#pop', 'badregex')), default('#pop') ], 'badregex': [ (r'\n', Text, '#pop') ], 'root': [ include('commentsandwhitespace'), (r'\n', Text), (r'[^\S\n]+', Text), (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|\.\.' r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (r'[=+\-*/]', Operator), (r'(for|in|while|do|break|return|continue|if|else|' r'throw|try|catch' r')\b', Keyword, 'slashstartsregex'), (r'(var)\b', Keyword.Declaration, 'slashstartsregex'), (r'(attr|def|fun)\b', Keyword.Reserved), (r'(true|false)\b', Keyword.Constant), (r'(eval|throw)\b', Name.Builtin), (r'`\S+`', Name.Builtin), (r'[$a-zA-Z_]\w*', Name.Other), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer), (r'"', String.Double, 'dqstring'), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ], 'dqstring': [ (r'\$\{[^"}]+?\}', String.Interpol), (r'\$', String.Double), (r'\\\\', String.Double), (r'\\"', String.Double), (r'[^\\"$]+', String.Double), (r'"', String.Double, '#pop'), ], }
class LSLLexer(RegexLexer): """ For Second Life's Linden Scripting Language source code. """
name = 'LSL' aliases = ['lsl'] filenames = ['*.lsl'] mimetypes = ['text/x-lsl'] url = 'https://wiki.secondlife.com/wiki/Linden_Scripting_Language' version_added = '2.0'
flags = re.MULTILINE
lsl_keywords = r'\b(?:do|else|for|if|jump|return|while)\b' lsl_types = r'\b(?:float|integer|key|list|quaternion|rotation|string|vector)\b' lsl_states = r'\b(?:(?:state)\s+\w+|default)\b' lsl_events = r'\b(?:state_(?:entry|exit)|touch(?:_(?:start|end))?|(?:land_)?collision(?:_(?:start|end))?|timer|listen|(?:no_)?sensor|control|(?:not_)?at_(?:rot_)?target|money|email|run_time_permissions|changed|attach|dataserver|moving_(?:start|end)|link_message|(?:on|object)_rez|remote_data|http_re(?:sponse|quest)|path_update|transaction_result)\b' lsl_functions_builtin = r'\b(?:ll(?:ReturnObjectsBy(?:ID|Owner)|Json(?:2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(?:Mag|Norm|Dist)|Rot(?:Between|2(?:Euler|Fwd|Left|Up))|(?:Euler|Axes)2Rot|Whisper|(?:Region|Owner)?Say|Shout|Listen(?:Control|Remove)?|Sensor(?:Repeat|Remove)?|Detected(?:Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|(?:[GS]et)(?:AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(?:Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(?:Scale|Offset|Rotate)Texture|(?:Rot)?Target(?:Remove)?|(?:Stop)?MoveToTarget|Apply(?:Rotational)?Impulse|Set(?:KeyframedMotion|ContentType|RegionPos|(?:Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(?:Queueing|Radius)|Vehicle(?:Type|(?:Float|Vector|Rotation)Param)|(?:Touch|Sit)?Text|Camera(?:Eye|At)Offset|PrimitiveParams|ClickAction|Link(?:Alpha|Color|PrimitiveParams(?:Fast)?|Texture(?:Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get(?:(?:Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(?:PrimitiveParams|Number(?:OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(?:Details|PermMask|PrimCount)|Parcel(?:MaxPrims|Details|Prim(?:Count|Owners))|Attached|(?:SPMax|Free|Used)Memory|Region(?:Name|TimeDilation|FPS|Corner|AgentCount)|Root(?:Position|Rotation)|UnixTime|(?:Parcel|Region)Flags|(?:Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(?:Prims|NotecardLines|Sides)|Animation(?:List)?|(?:Camera|Local)(?:Pos|Rot)|Vel|Accel|Omega|Time(?:stamp|OfDay)|(?:Object|CenterOf)?Mass|MassMKS|Energy|Owner|(?:Owner)?Key|SunDirection|Texture(?:Offset|Scale|Rot)|Inventory(?:Number|Name|Key|Type|Creator|PermMask)|Permissions(?:Key)?|StartParameter|List(?:Length|EntryType)|Date|Agent(?:Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(?:Name|State))|(?:Get|Reset|GetAndReset)Time|PlaySound(?:Slave)?|LoopSound(?:Master|Slave)?|(?:Trigger|Stop|Preload)Sound|(?:(?:Get|Delete)Sub|Insert)String|To(?:Upper|Lower)|Give(?:InventoryList|Money)|RezObject|(?:Stop)?LookAt|Sleep|CollisionFilter|(?:Take|Release)Controls|DetachFromAvatar|AttachToAvatar(?:Temp)?|InstantMessage|(?:GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(?:Length|Trim)|(?:Start|Stop)Animation|TargetOmega|RequestPermissions|(?:Create|Break)Link|BreakAllLinks|(?:Give|Remove)Inventory|Water|PassTouches|Request(?:Agent|Inventory)Data|TeleportAgent(?:Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(?:Axis|Angle)|A(?:cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(?:CSV|Integer|Json|Float|String|Key|Vector|Rot|List(?:Strided)?)|DeleteSubList|List(?:Statistics|Sort|Randomize|(?:Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(?:CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(?:Slope|Normal|Contour)|GroundRepel|(?:Set|Remove)VehicleFlags|(?:AvatarOn)?(?:Link)?SitTarget|Script(?:Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(?:Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(?:Integer|String)ToBase64|XorBase64|Log(?:10)?|Base64To(?:String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(?:Load|Release|(?:E|Une)scape)URL|ParcelMedia(?:CommandList|Query)|ModPow|MapDestination|(?:RemoveFrom|AddTo|Reset)Land(?:Pass|Ban)List|(?:Set|Clear)CameraParams|HTTP(?:Request|Response)|TextBox|DetectedTouch(?:UV|Face|Pos|(?:N|Bin)ormal|ST)|(?:MD5|SHA1|DumpList2)String|Request(?:Secure)?URL|Clear(?:Prim|Link)Media|(?:Link)?ParticleSystem|(?:Get|Request)(?:Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(?:Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\b' lsl_constants_float = r'\b(?:DEG_TO_RAD|PI(?:_BY_TWO)?|RAD_TO_DEG|SQRT2|TWO_PI)\b' lsl_constants_integer = r'\b(?:JSON_APPEND|STATUS_(?:PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(?:_OBJECT)?|(?:DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(?:FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(?:_(?:BY_(?:LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(?:PARCEL(?:_OWNER)?|REGION)))?|CAMERA_(?:PITCH|DISTANCE|BEHINDNESS_(?:ANGLE|LAG)|(?:FOCUS|POSITION)(?:_(?:THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(?:ROOT|SET|ALL_(?:OTHERS|CHILDREN)|THIS)|ACTIVE|PASSIVE|SCRIPTED|CONTROL_(?:FWD|BACK|(?:ROT_)?(?:LEFT|RIGHT)|UP|DOWN|(?:ML_)?LBUTTON)|PERMISSION_(?:RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(?:CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(?:TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(?:INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(?:_START)?|TELEPORT|MEDIA)|OBJECT_(?:(?:PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_ON_REZ|NAME|DESC|POS|PRIM_EQUIVALENCE|RETURN_(?:PARCEL(?:_OWNER)?|REGION)|ROO?T|VELOCITY|OWNER|GROUP|CREATOR|ATTACHED_POINT|RENDER_WEIGHT|PATHFINDING_TYPE|(?:RUNNING|TOTAL)_SCRIPT_COUNT|SCRIPT_(?:MEMORY|TIME))|TYPE_(?:INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(?:DEBUG|PUBLIC)_CHANNEL|ATTACH_(?:AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](?:SHOULDER|HAND|FOOT|EAR|EYE|[UL](?:ARM|LEG)|HIP)|(?:LEFT|RIGHT)_PEC|HUD_(?:CENTER_[12]|TOP_(?:RIGHT|CENTER|LEFT)|BOTTOM(?:_(?:RIGHT|LEFT))?))|LAND_(?:LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(?:ONLINE|NAME|BORN|SIM_(?:POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(?:ON_FILE|USED)|REMOTE_DATA_(?:CHANNEL|REQUEST|REPLY)|PSYS_(?:PART_(?:BF_(?:ZERO|ONE(?:_MINUS_(?:DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(?:START|END)_(?:COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(?:RIBBON|WIND|INTERP_(?:COLOR|SCALE)|BOUNCE|FOLLOW_(?:SRC|VELOCITY)|TARGET_(?:POS|LINEAR)|EMISSIVE)_MASK)|SRC_(?:MAX_AGE|PATTERN|ANGLE_(?:BEGIN|END)|BURST_(?:RATE|PART_COUNT|RADIUS|SPEED_(?:MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(?:DROP|EXPLODE|ANGLE(?:_CONE(?:_EMPTY)?)?)))|VEHICLE_(?:REFERENCE_FRAME|TYPE_(?:NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(?:LINEAR|ANGULAR)_(?:FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(?:HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(?:LINEAR|ANGULAR)_(?:DEFLECTION_(?:EFFICIENCY|TIMESCALE)|MOTOR_(?:DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(?:EFFICIENCY|TIMESCALE)|BANKING_(?:EFFICIENCY|MIX|TIMESCALE)|FLAG_(?:NO_DEFLECTION_UP|LIMIT_(?:ROLL_ONLY|MOTOR_UP)|HOVER_(?:(?:WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(?:STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(?:TYPE(?:_(?:BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(?:DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(?:_(?:STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(?:NONE|LOW|MEDIUM|HIGH)|BUMP_(?:NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(?:DEFAULT|PLANAR)|SCULPT_(?:TYPE_(?:SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(?:MIRROR|INVERT))|PHYSICS(?:_(?:SHAPE_(?:CONVEX|NONE|PRIM|TYPE)))?|(?:POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(?:ALT_IMAGE_ENABLE|CONTROLS|(?:CURRENT|HOME)_URL|AUTO_(?:LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(?:WIDTH|HEIGHT)_PIXELS|WHITELIST(?:_ENABLE)?|PERMS_(?:INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(?:STANDARD|MINI)|PERM_(?:NONE|OWNER|GROUP|ANYONE)|MAX_(?:URL_LENGTH|WHITELIST_(?:SIZE|COUNT)|(?:WIDTH|HEIGHT)_PIXELS)))|MASK_(?:BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(?:TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(?:MEDIA_COMMAND_(?:STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(?:ALLOW_(?:FLY|(?:GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(?:GROUP_)?OBJECTS)|USE_(?:ACCESS_(?:GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(?:GROUP|ALL)_OBJECT_ENTRY)|COUNT_(?:TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(?:NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(?:MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(?:_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(?:HIDE|DEFAULT)|REGION_FLAG_(?:ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(?:COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(?:METHOD|MIMETYPE|BODY_(?:MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|STRING_(?:TRIM(?:_(?:HEAD|TAIL))?)|CLICK_ACTION_(?:NONE|TOUCH|SIT|BUY|PAY|OPEN(?:_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(?:NONE|SCRIPT_MEMORY)|RC_(?:DATA_FLAGS|DETECT_PHANTOM|GET_(?:LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(?:TYPES|AGENTS|(?:NON)?PHYSICAL|LAND))|RCERR_(?:CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(?:ALLOWED_(?:AGENT|GROUP)_(?:ADD|REMOVE)|BANNED_AGENT_(?:ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(?:COMMAND|CMD_(?:PLAY|STOP|PAUSE|SET_MODE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(?:GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(?:CMD_(?:(?:SMOOTH_)?STOP|JUMP)|DESIRED_(?:TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(?:_(?:[A-D]|NONE))?|MAX_(?:DECEL|TURN_RADIUS|(?:ACCEL|SPEED)))|PURSUIT_(?:OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(?:CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(?:EVADE_(?:HIDDEN|SPOTTED)|FAILURE_(?:DYNAMIC_PATHFINDING_DISABLED|INVALID_(?:GOAL|START)|NO_(?:NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(?:PARCEL_)?UNREACHABLE)|(?:GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(?:_(?:FAST|NONE|SLOW))?|CONTENT_TYPE_(?:ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(?:RADIUS|STATIC)|(?:PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(?:AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\b' lsl_constants_integer_boolean = r'\b(?:FALSE|TRUE)\b' lsl_constants_rotation = r'\b(?:ZERO_ROTATION)\b' lsl_constants_string = r'\b(?:EOF|JSON_(?:ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(?:BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(?:GRANTED|DENIED))\b' lsl_constants_vector = r'\b(?:TOUCH_INVALID_(?:TEXCOORD|VECTOR)|ZERO_VECTOR)\b' lsl_invalid_broken = r'\b(?:LAND_(?:LARGE|MEDIUM|SMALL)_BRUSH)\b' lsl_invalid_deprecated = r'\b(?:ATTACH_[LR]PEC|DATA_RATING|OBJECT_ATTACHMENT_(?:GEOMETRY_BYTES|SURFACE_AREA)|PRIM_(?:CAST_SHADOWS|MATERIAL_LIGHT|TYPE_LEGACY)|PSYS_SRC_(?:INNER|OUTER)ANGLE|VEHICLE_FLAG_NO_FLY_UP|ll(?:Cloud|Make(?:Explosion|Fountain|Smoke|Fire)|RemoteDataSetRegion|Sound(?:Preload)?|XorBase64Strings(?:Correct)?))\b' lsl_invalid_illegal = r'\b(?:event)\b' lsl_invalid_unimplemented = r'\b(?:CHARACTER_(?:MAX_ANGULAR_(?:ACCEL|SPEED)|TURN_SPEED_MULTIPLIER)|PERMISSION_(?:CHANGE_(?:JOINTS|PERMISSIONS)|RELEASE_OWNERSHIP|REMAP_CONTROLS)|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|ll(?:CollisionSprite|(?:Stop)?PointAt|(?:(?:Refresh|Set)Prim)URL|(?:Take|Release)Camera|RemoteLoadScript))\b' lsl_reserved_godmode = r'\b(?:ll(?:GodLikeRezObject|Set(?:Inventory|Object)PermMask))\b' lsl_reserved_log = r'\b(?:print)\b' lsl_operators = r'\+\+|\-\-|<<|>>|&&?|\|\|?|\^|~|[!%<>=*+\-/]=?'
tokens = { 'root': [ (r'//.*?\n', Comment.Single), (r'/\*', Comment.Multiline, 'comment'), (r'"', String.Double, 'string'), (lsl_keywords, Keyword), (lsl_types, Keyword.Type), (lsl_states, Name.Class), (lsl_events, Name.Builtin), (lsl_functions_builtin, Name.Function), (lsl_constants_float, Keyword.Constant), (lsl_constants_integer, Keyword.Constant), (lsl_constants_integer_boolean, Keyword.Constant), (lsl_constants_rotation, Keyword.Constant), (lsl_constants_string, Keyword.Constant), (lsl_constants_vector, Keyword.Constant), (lsl_invalid_broken, Error), (lsl_invalid_deprecated, Error), (lsl_invalid_illegal, Error), (lsl_invalid_unimplemented, Error), (lsl_reserved_godmode, Keyword.Reserved), (lsl_reserved_log, Keyword.Reserved), (r'\b([a-zA-Z_]\w*)\b', Name.Variable), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d*', Number.Float), (r'(\d+\.\d*|\.\d+)', Number.Float), (r'0[xX][0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (lsl_operators, Operator), (r':=?', Error), (r'[,;{}()\[\]]', Punctuation), (r'\n+', Whitespace), (r'\s+', Whitespace) ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'string': [ (r'\\([nt"\\])', String.Escape), (r'"', String.Double, '#pop'), (r'\\.', Error), (r'[^"\\]+', String.Double), ] }
class AppleScriptLexer(RegexLexer): """ For AppleScript source code, including `AppleScript Studio <http://developer.apple.com/documentation/AppleScript/ Reference/StudioReference>`_. Contributed by Andreas Amann <aamann@mac.com>. """
name = 'AppleScript' url = 'https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html' aliases = ['applescript'] filenames = ['*.applescript'] version_added = '1.0'
flags = re.MULTILINE | re.DOTALL
Identifiers = r'[a-zA-Z]\w*'
# XXX: use words() for all of these Literals = ('AppleScript', 'current application', 'false', 'linefeed', 'missing value', 'pi', 'quote', 'result', 'return', 'space', 'tab', 'text item delimiters', 'true', 'version') Classes = ('alias ', 'application ', 'boolean ', 'class ', 'constant ', 'date ', 'file ', 'integer ', 'list ', 'number ', 'POSIX file ', 'real ', 'record ', 'reference ', 'RGB color ', 'script ', 'text ', 'unit types', '(?:Unicode )?text', 'string') BuiltIn = ('attachment', 'attribute run', 'character', 'day', 'month', 'paragraph', 'word', 'year') HandlerParams = ('about', 'above', 'against', 'apart from', 'around', 'aside from', 'at', 'below', 'beneath', 'beside', 'between', 'for', 'given', 'instead of', 'on', 'onto', 'out of', 'over', 'since') Commands = ('ASCII (character|number)', 'activate', 'beep', 'choose URL', 'choose application', 'choose color', 'choose file( name)?', 'choose folder', 'choose from list', 'choose remote application', 'clipboard info', 'close( access)?', 'copy', 'count', 'current date', 'delay', 'delete', 'display (alert|dialog)', 'do shell script', 'duplicate', 'exists', 'get eof', 'get volume settings', 'info for', 'launch', 'list (disks|folder)', 'load script', 'log', 'make', 'mount volume', 'new', 'offset', 'open( (for access|location))?', 'path to', 'print', 'quit', 'random number', 'read', 'round', 'run( script)?', 'say', 'scripting components', 'set (eof|the clipboard to|volume)', 'store script', 'summarize', 'system attribute', 'system info', 'the clipboard', 'time to GMT', 'write', 'quoted form') References = ('(in )?back of', '(in )?front of', '[0-9]+(st|nd|rd|th)', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'after', 'back', 'before', 'behind', 'every', 'front', 'index', 'last', 'middle', 'some', 'that', 'through', 'thru', 'where', 'whose') Operators = ("and", "or", "is equal", "equals", "(is )?equal to", "is not", "isn't", "isn't equal( to)?", "is not equal( to)?", "doesn't equal", "does not equal", "(is )?greater than", "comes after", "is not less than or equal( to)?", "isn't less than or equal( to)?", "(is )?less than", "comes before", "is not greater than or equal( to)?", "isn't greater than or equal( to)?", "(is )?greater than or equal( to)?", "is not less than", "isn't less than", "does not come before", "doesn't come before", "(is )?less than or equal( to)?", "is not greater than", "isn't greater than", "does not come after", "doesn't come after", "starts? with", "begins? with", "ends? with", "contains?", "does not contain", "doesn't contain", "is in", "is contained by", "is not in", "is not contained by", "isn't contained by", "div", "mod", "not", "(a )?(ref( to)?|reference to)", "is", "does") Control = ('considering', 'else', 'error', 'exit', 'from', 'if', 'ignoring', 'in', 'repeat', 'tell', 'then', 'times', 'to', 'try', 'until', 'using terms from', 'while', 'whith', 'with timeout( of)?', 'with transaction', 'by', 'continue', 'end', 'its?', 'me', 'my', 'return', 'of', 'as') Declarations = ('global', 'local', 'prop(erty)?', 'set', 'get') Reserved = ('but', 'put', 'returning', 'the') StudioClasses = ('action cell', 'alert reply', 'application', 'box', 'browser( cell)?', 'bundle', 'button( cell)?', 'cell', 'clip view', 'color well', 'color-panel', 'combo box( item)?', 'control', 'data( (cell|column|item|row|source))?', 'default entry', 'dialog reply', 'document', 'drag info', 'drawer', 'event', 'font(-panel)?', 'formatter', 'image( (cell|view))?', 'matrix', 'menu( item)?', 'item', 'movie( view)?', 'open-panel', 'outline view', 'panel', 'pasteboard', 'plugin', 'popup button', 'progress indicator', 'responder', 'save-panel', 'scroll view', 'secure text field( cell)?', 'slider', 'sound', 'split view', 'stepper', 'tab view( item)?', 'table( (column|header cell|header view|view))', 'text( (field( cell)?|view))?', 'toolbar( item)?', 'user-defaults', 'view', 'window') StudioEvents = ('accept outline drop', 'accept table drop', 'action', 'activated', 'alert ended', 'awake from nib', 'became key', 'became main', 'begin editing', 'bounds changed', 'cell value', 'cell value changed', 'change cell value', 'change item value', 'changed', 'child of item', 'choose menu item', 'clicked', 'clicked toolbar item', 'closed', 'column clicked', 'column moved', 'column resized', 'conclude drop', 'data representation', 'deminiaturized', 'dialog ended', 'document nib name', 'double clicked', 'drag( (entered|exited|updated))?', 'drop', 'end editing', 'exposed', 'idle', 'item expandable', 'item value', 'item value changed', 'items changed', 'keyboard down', 'keyboard up', 'launched', 'load data representation', 'miniaturized', 'mouse down', 'mouse dragged', 'mouse entered', 'mouse exited', 'mouse moved', 'mouse up', 'moved', 'number of browser rows', 'number of items', 'number of rows', 'open untitled', 'opened', 'panel ended', 'parameters updated', 'plugin loaded', 'prepare drop', 'prepare outline drag', 'prepare outline drop', 'prepare table drag', 'prepare table drop', 'read from file', 'resigned active', 'resigned key', 'resigned main', 'resized( sub views)?', 'right mouse down', 'right mouse dragged', 'right mouse up', 'rows changed', 'scroll wheel', 'selected tab view item', 'selection changed', 'selection changing', 'should begin editing', 'should close', 'should collapse item', 'should end editing', 'should expand item', 'should open( untitled)?', 'should quit( after last window closed)?', 'should select column', 'should select item', 'should select row', 'should select tab view item', 'should selection change', 'should zoom', 'shown', 'update menu item', 'update parameters', 'update toolbar item', 'was hidden', 'was miniaturized', 'will become active', 'will close', 'will dismiss', 'will display browser cell', 'will display cell', 'will display item cell', 'will display outline cell', 'will finish launching', 'will hide', 'will miniaturize', 'will move', 'will open', 'will pop up', 'will quit', 'will resign active', 'will resize( sub views)?', 'will select tab view item', 'will show', 'will zoom', 'write to file', 'zoomed') StudioCommands = ('animate', 'append', 'call method', 'center', 'close drawer', 'close panel', 'display', 'display alert', 'display dialog', 'display panel', 'go', 'hide', 'highlight', 'increment', 'item for', 'load image', 'load movie', 'load nib', 'load panel', 'load sound', 'localized string', 'lock focus', 'log', 'open drawer', 'path for', 'pause', 'perform action', 'play', 'register', 'resume', 'scroll', 'select( all)?', 'show', 'size to fit', 'start', 'step back', 'step forward', 'stop', 'synchronize', 'unlock focus', 'update') StudioProperties = ('accepts arrow key', 'action method', 'active', 'alignment', 'allowed identifiers', 'allows branch selection', 'allows column reordering', 'allows column resizing', 'allows column selection', 'allows customization', 'allows editing text attributes', 'allows empty selection', 'allows mixed state', 'allows multiple selection', 'allows reordering', 'allows undo', 'alpha( value)?', 'alternate image', 'alternate increment value', 'alternate title', 'animation delay', 'associated file name', 'associated object', 'auto completes', 'auto display', 'auto enables items', 'auto repeat', 'auto resizes( outline column)?', 'auto save expanded items', 'auto save name', 'auto save table columns', 'auto saves configuration', 'auto scroll', 'auto sizes all columns to fit', 'auto sizes cells', 'background color', 'bezel state', 'bezel style', 'bezeled', 'border rect', 'border type', 'bordered', 'bounds( rotation)?', 'box type', 'button returned', 'button type', 'can choose directories', 'can choose files', 'can draw', 'can hide', 'cell( (background color|size|type))?', 'characters', 'class', 'click count', 'clicked( data)? column', 'clicked data item', 'clicked( data)? row', 'closeable', 'collating', 'color( (mode|panel))', 'command key down', 'configuration', 'content(s| (size|view( margins)?))?', 'context', 'continuous', 'control key down', 'control size', 'control tint', 'control view', 'controller visible', 'coordinate system', 'copies( on scroll)?', 'corner view', 'current cell', 'current column', 'current( field)? editor', 'current( menu)? item', 'current row', 'current tab view item', 'data source', 'default identifiers', 'delta (x|y|z)', 'destination window', 'directory', 'display mode', 'displayed cell', 'document( (edited|rect|view))?', 'double value', 'dragged column', 'dragged distance', 'dragged items', 'draws( cell)? background', 'draws grid', 'dynamically scrolls', 'echos bullets', 'edge', 'editable', 'edited( data)? column', 'edited data item', 'edited( data)? row', 'enabled', 'enclosing scroll view', 'ending page', 'error handling', 'event number', 'event type', 'excluded from windows menu', 'executable path', 'expanded', 'fax number', 'field editor', 'file kind', 'file name', 'file type', 'first responder', 'first visible column', 'flipped', 'floating', 'font( panel)?', 'formatter', 'frameworks path', 'frontmost', 'gave up', 'grid color', 'has data items', 'has horizontal ruler', 'has horizontal scroller', 'has parent data item', 'has resize indicator', 'has shadow', 'has sub menu', 'has vertical ruler', 'has vertical scroller', 'header cell', 'header view', 'hidden', 'hides when deactivated', 'highlights by', 'horizontal line scroll', 'horizontal page scroll', 'horizontal ruler view', 'horizontally resizable', 'icon image', 'id', 'identifier', 'ignores multiple clicks', 'image( (alignment|dims when disabled|frame style|scaling))?', 'imports graphics', 'increment value', 'indentation per level', 'indeterminate', 'index', 'integer value', 'intercell spacing', 'item height', 'key( (code|equivalent( modifier)?|window))?', 'knob thickness', 'label', 'last( visible)? column', 'leading offset', 'leaf', 'level', 'line scroll', 'loaded', 'localized sort', 'location', 'loop mode', 'main( (bunde|menu|window))?', 'marker follows cell', 'matrix mode', 'maximum( content)? size', 'maximum visible columns', 'menu( form representation)?', 'miniaturizable', 'miniaturized', 'minimized image', 'minimized title', 'minimum column width', 'minimum( content)? size', 'modal', 'modified', 'mouse down state', 'movie( (controller|file|rect))?', 'muted', 'name', 'needs display', 'next state', 'next text', 'number of tick marks', 'only tick mark values', 'opaque', 'open panel', 'option key down', 'outline table column', 'page scroll', 'pages across', 'pages down', 'palette label', 'pane splitter', 'parent data item', 'parent window', 'pasteboard', 'path( (names|separator))?', 'playing', 'plays every frame', 'plays selection only', 'position', 'preferred edge', 'preferred type', 'pressure', 'previous text', 'prompt', 'properties', 'prototype cell', 'pulls down', 'rate', 'released when closed', 'repeated', 'requested print time', 'required file type', 'resizable', 'resized column', 'resource path', 'returns records', 'reuses columns', 'rich text', 'roll over', 'row height', 'rulers visible', 'save panel', 'scripts path', 'scrollable', 'selectable( identifiers)?', 'selected cell', 'selected( data)? columns?', 'selected data items?', 'selected( data)? rows?', 'selected item identifier', 'selection by rect', 'send action on arrow key', 'sends action when done editing', 'separates columns', 'separator item', 'sequence number', 'services menu', 'shared frameworks path', 'shared support path', 'sheet', 'shift key down', 'shows alpha', 'shows state by', 'size( mode)?', 'smart insert delete enabled', 'sort case sensitivity', 'sort column', 'sort order', 'sort type', 'sorted( data rows)?', 'sound', 'source( mask)?', 'spell checking enabled', 'starting page', 'state', 'string value', 'sub menu', 'super menu', 'super view', 'tab key traverses cells', 'tab state', 'tab type', 'tab view', 'table view', 'tag', 'target( printer)?', 'text color', 'text container insert', 'text container origin', 'text returned', 'tick mark position', 'time stamp', 'title(d| (cell|font|height|position|rect))?', 'tool tip', 'toolbar', 'trailing offset', 'transparent', 'treat packages as directories', 'truncated labels', 'types', 'unmodified characters', 'update views', 'use sort indicator', 'user defaults', 'uses data source', 'uses ruler', 'uses threaded animation', 'uses title from previous column', 'value wraps', 'version', 'vertical( (line scroll|page scroll|ruler view))?', 'vertically resizable', 'view', 'visible( document rect)?', 'volume', 'width', 'window', 'windows menu', 'wraps', 'zoomable', 'zoomed')
tokens = { 'root': [ (r'\s+', Text), (r'¬\n', String.Escape), (r"'s\s+", Text), # This is a possessive, consider moving (r'(--|#).*?$', Comment), (r'\(\*', Comment.Multiline, 'comment'), (r'[(){}!,.:]', Punctuation), (r'(«)([^»]+)(»)', bygroups(Text, Name.Builtin, Text)), (r'\b((?:considering|ignoring)\s*)' r'(application responses|case|diacriticals|hyphens|' r'numeric strings|punctuation|white space)', bygroups(Keyword, Name.Builtin)), (r'(-|\*|\+|&|≠|>=?|<=?|=|≥|≤|/|÷|\^)', Operator), (r"\b({})\b".format('|'.join(Operators)), Operator.Word), (r'^(\s*(?:on|end)\s+)' r'({})'.format('|'.join(StudioEvents[::-1])), bygroups(Keyword, Name.Function)), (r'^(\s*)(in|on|script|to)(\s+)', bygroups(Text, Keyword, Text)), (r'\b(as )({})\b'.format('|'.join(Classes)), bygroups(Keyword, Name.Class)), (r'\b({})\b'.format('|'.join(Literals)), Name.Constant), (r'\b({})\b'.format('|'.join(Commands)), Name.Builtin), (r'\b({})\b'.format('|'.join(Control)), Keyword), (r'\b({})\b'.format('|'.join(Declarations)), Keyword), (r'\b({})\b'.format('|'.join(Reserved)), Name.Builtin), (r'\b({})s?\b'.format('|'.join(BuiltIn)), Name.Builtin), (r'\b({})\b'.format('|'.join(HandlerParams)), Name.Builtin), (r'\b({})\b'.format('|'.join(StudioProperties)), Name.Attribute), (r'\b({})s?\b'.format('|'.join(StudioClasses)), Name.Builtin), (r'\b({})\b'.format('|'.join(StudioCommands)), Name.Builtin), (r'\b({})\b'.format('|'.join(References)), Name.Builtin), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (rf'\b({Identifiers})\b', Name.Variable), (r'[-+]?(\d+\.\d*|\d*\.\d+)(E[-+][0-9]+)?', Number.Float), (r'[-+]?\d+', Number.Integer), ], 'comment': [ (r'\(\*', Comment.Multiline, '#push'), (r'\*\)', Comment.Multiline, '#pop'), ('[^*(]+', Comment.Multiline), ('[*(]', Comment.Multiline), ], }
class RexxLexer(RegexLexer): """ Rexx is a scripting language available for a wide range of different platforms with its roots found on mainframe systems. It is popular for I/O- and data based tasks and can act as glue language to bind different applications together. """ name = 'Rexx' url = 'http://www.rexxinfo.org/' aliases = ['rexx', 'arexx'] filenames = ['*.rexx', '*.rex', '*.rx', '*.arexx'] mimetypes = ['text/x-rexx'] version_added = '2.0' flags = re.IGNORECASE
tokens = { 'root': [ (r'\s+', Whitespace), (r'/\*', Comment.Multiline, 'comment'), (r'"', String, 'string_double'), (r"'", String, 'string_single'), (r'[0-9]+(\.[0-9]+)?(e[+-]?[0-9])?', Number), (r'([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b', bygroups(Name.Function, Whitespace, Operator, Whitespace, Keyword.Declaration)), (r'([a-z_]\w*)(\s*)(:)', bygroups(Name.Label, Whitespace, Operator)), include('function'), include('keyword'), include('operator'), (r'[a-z_]\w*', Text), ], 'function': [ (words(( 'abbrev', 'abs', 'address', 'arg', 'b2x', 'bitand', 'bitor', 'bitxor', 'c2d', 'c2x', 'center', 'charin', 'charout', 'chars', 'compare', 'condition', 'copies', 'd2c', 'd2x', 'datatype', 'date', 'delstr', 'delword', 'digits', 'errortext', 'form', 'format', 'fuzz', 'insert', 'lastpos', 'left', 'length', 'linein', 'lineout', 'lines', 'max', 'min', 'overlay', 'pos', 'queued', 'random', 'reverse', 'right', 'sign', 'sourceline', 'space', 'stream', 'strip', 'substr', 'subword', 'symbol', 'time', 'trace', 'translate', 'trunc', 'value', 'verify', 'word', 'wordindex', 'wordlength', 'wordpos', 'words', 'x2b', 'x2c', 'x2d', 'xrange'), suffix=r'(\s*)(\()'), bygroups(Name.Builtin, Whitespace, Operator)), ], 'keyword': [ (r'(address|arg|by|call|do|drop|else|end|exit|for|forever|if|' r'interpret|iterate|leave|nop|numeric|off|on|options|parse|' r'pull|push|queue|return|say|select|signal|to|then|trace|until|' r'while)\b', Keyword.Reserved), ], 'operator': [ (r'(-|//|/|\(|\)|\*\*|\*|\\<<|\\<|\\==|\\=|\\>>|\\>|\\|\|\||\||' r'&&|&|%|\+|<<=|<<|<=|<>|<|==|=|><|>=|>>=|>>|>|¬<<|¬<|¬==|¬=|' r'¬>>|¬>|¬|\.|,)', Operator), ], 'string_double': [ (r'[^"\n]+', String), (r'""', String), (r'"', String, '#pop'), (r'\n', Text, '#pop'), # Stray linefeed also terminates strings. ], 'string_single': [ (r'[^\'\n]+', String), (r'\'\'', String), (r'\'', String, '#pop'), (r'\n', Text, '#pop'), # Stray linefeed also terminates strings. ], 'comment': [ (r'[^*]+', Comment.Multiline), (r'\*/', Comment.Multiline, '#pop'), (r'\*', Comment.Multiline), ] }
def _c(s): return re.compile(s, re.MULTILINE) _ADDRESS_COMMAND_PATTERN = _c(r'^\s*address\s+command\b') _ADDRESS_PATTERN = _c(r'^\s*address\s+') _DO_WHILE_PATTERN = _c(r'^\s*do\s+while\b') _IF_THEN_DO_PATTERN = _c(r'^\s*if\b.+\bthen\s+do\s*$') _PROCEDURE_PATTERN = _c(r'^\s*([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b') _ELSE_DO_PATTERN = _c(r'\belse\s+do\s*$') _PARSE_ARG_PATTERN = _c(r'^\s*parse\s+(upper\s+)?(arg|value)\b') PATTERNS_AND_WEIGHTS = ( (_ADDRESS_COMMAND_PATTERN, 0.2), (_ADDRESS_PATTERN, 0.05), (_DO_WHILE_PATTERN, 0.1), (_ELSE_DO_PATTERN, 0.1), (_IF_THEN_DO_PATTERN, 0.1), (_PROCEDURE_PATTERN, 0.5), (_PARSE_ARG_PATTERN, 0.2), )
def analyse_text(text): """ Check for initial comment and patterns that distinguish Rexx from other C-like languages. """ if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE): # Header matches MVS Rexx requirements, this is certainly a Rexx # script. return 1.0 elif text.startswith('/*'): # Header matches general Rexx requirements; the source code might # still be any language using C comments such as C++, C# or Java. lowerText = text.lower() result = sum(weight for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS if pattern.search(lowerText)) + 0.01 return min(result, 1.0)
class MOOCodeLexer(RegexLexer): """ For MOOCode (the MOO scripting language). """ name = 'MOOCode' url = 'http://www.moo.mud.org/' filenames = ['*.moo'] aliases = ['moocode', 'moo'] mimetypes = ['text/x-moocode'] version_added = '0.9'
tokens = { 'root': [ # Numbers (r'(0|[1-9][0-9_]*)', Number.Integer), # Strings (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # exceptions (r'(E_PERM|E_DIV)', Name.Exception), # db-refs (r'((#[-0-9]+)|(\$\w+))', Name.Entity), # Keywords (r'\b(if|else|elseif|endif|for|endfor|fork|endfork|while' r'|endwhile|break|continue|return|try' r'|except|endtry|finally|in)\b', Keyword), # builtins (r'(random|length)', Name.Builtin), # special variables (r'(player|caller|this|args)', Name.Variable.Instance), # skip whitespace (r'\s+', Text), (r'\n', Text), # other operators (r'([!;=,{}&|:.\[\]@()<>?]+)', Operator), # function call (r'(\w+)(\()', bygroups(Name.Function, Operator)), # variables (r'(\w+)', Text), ] }
class HybrisLexer(RegexLexer): """ For Hybris source code. """
name = 'Hybris' aliases = ['hybris'] filenames = ['*.hyb'] mimetypes = ['text/x-hybris', 'application/x-hybris'] url = 'https://github.com/evilsocket/hybris' version_added = '1.4'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ # method names (r'^(\s*(?:function|method|operator\s+)+?)' r'([a-zA-Z_]\w*)' r'(\s*)(\()', bygroups(Keyword, Name.Function, Text, Operator)), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][\w.]*', Name.Decorator), (r'(break|case|catch|next|default|do|else|finally|for|foreach|of|' r'unless|if|new|return|switch|me|throw|try|while)\b', Keyword), (r'(extends|private|protected|public|static|throws|function|method|' r'operator)\b', Keyword.Declaration), (r'(true|false|null|__FILE__|__LINE__|__VERSION__|__LIB_PATH__|' r'__INC_PATH__)\b', Keyword.Constant), (r'(class|struct)(\s+)', bygroups(Keyword.Declaration, Text), 'class'), (r'(import|include)(\s+)', bygroups(Keyword.Namespace, Text), 'import'), (words(( 'gc_collect', 'gc_mm_items', 'gc_mm_usage', 'gc_collect_threshold', 'urlencode', 'urldecode', 'base64encode', 'base64decode', 'sha1', 'crc32', 'sha2', 'md5', 'md5_file', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'exp', 'fabs', 'floor', 'fmod', 'log', 'log10', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'isint', 'isfloat', 'ischar', 'isstring', 'isarray', 'ismap', 'isalias', 'typeof', 'sizeof', 'toint', 'tostring', 'fromxml', 'toxml', 'binary', 'pack', 'load', 'eval', 'var_names', 'var_values', 'user_functions', 'dyn_functions', 'methods', 'call', 'call_method', 'mknod', 'mkfifo', 'mount', 'umount2', 'umount', 'ticks', 'usleep', 'sleep', 'time', 'strtime', 'strdate', 'dllopen', 'dlllink', 'dllcall', 'dllcall_argv', 'dllclose', 'env', 'exec', 'fork', 'getpid', 'wait', 'popen', 'pclose', 'exit', 'kill', 'pthread_create', 'pthread_create_argv', 'pthread_exit', 'pthread_join', 'pthread_kill', 'smtp_send', 'http_get', 'http_post', 'http_download', 'socket', 'bind', 'listen', 'accept', 'getsockname', 'getpeername', 'settimeout', 'connect', 'server', 'recv', 'send', 'close', 'print', 'println', 'printf', 'input', 'readline', 'serial_open', 'serial_fcntl', 'serial_get_attr', 'serial_get_ispeed', 'serial_get_ospeed', 'serial_set_attr', 'serial_set_ispeed', 'serial_set_ospeed', 'serial_write', 'serial_read', 'serial_close', 'xml_load', 'xml_parse', 'fopen', 'fseek', 'ftell', 'fsize', 'fread', 'fwrite', 'fgets', 'fclose', 'file', 'readdir', 'pcre_replace', 'size', 'pop', 'unmap', 'has', 'keys', 'values', 'length', 'find', 'substr', 'replace', 'split', 'trim', 'remove', 'contains', 'join'), suffix=r'\b'), Name.Builtin), (words(( 'MethodReference', 'Runner', 'Dll', 'Thread', 'Pipe', 'Process', 'Runnable', 'CGI', 'ClientSocket', 'Socket', 'ServerSocket', 'File', 'Console', 'Directory', 'Exception'), suffix=r'\b'), Keyword.Type), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char), (r'(\.)([a-zA-Z_]\w*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_]\w*:', Name.Label), (r'[a-zA-Z_$]\w*', Name), (r'[~^*!%&\[\](){}<>|+=:;,./?\-@]+', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-f]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Text), ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'import': [ (r'[\w.]+\*?', Name.Namespace, '#pop') ], }
def analyse_text(text): """public method and private method don't seem to be quite common elsewhere.""" result = 0 if re.search(r'\b(?:public|private)\s+method\b', text): result += 0.01 return result
class EasytrieveLexer(RegexLexer): """ Easytrieve Plus is a programming language for extracting, filtering and converting sequential data. Furthermore it can layout data for reports. It is mainly used on mainframe platforms and can access several of the mainframe's native file formats. It is somewhat comparable to awk. """ name = 'Easytrieve' aliases = ['easytrieve'] filenames = ['*.ezt', '*.mac'] mimetypes = ['text/x-easytrieve'] url = 'https://www.broadcom.com/products/mainframe/application-development/easytrieve-report-generator' version_added = '2.1' flags = 0
# Note: We cannot use r'\b' at the start and end of keywords because # Easytrieve Plus delimiter characters are: # # * space ( ) # * apostrophe (') # * period (.) # * comma (,) # * parenthesis ( and ) # * colon (:) # # Additionally words end once a '*' appears, indicatins a comment. _DELIMITERS = r' \'.,():\n' _DELIMITERS_OR_COMENT = _DELIMITERS + '*' _DELIMITER_PATTERN = '[' + _DELIMITERS + ']' _DELIMITER_PATTERN_CAPTURE = '(' + _DELIMITER_PATTERN + ')' _NON_DELIMITER_OR_COMMENT_PATTERN = '[^' + _DELIMITERS_OR_COMENT + ']' _OPERATORS_PATTERN = '[.+\\-/=\\[\\](){}<>;,&%¬]' _KEYWORDS = [ 'AFTER-BREAK', 'AFTER-LINE', 'AFTER-SCREEN', 'AIM', 'AND', 'ATTR', 'BEFORE', 'BEFORE-BREAK', 'BEFORE-LINE', 'BEFORE-SCREEN', 'BUSHU', 'BY', 'CALL', 'CASE', 'CHECKPOINT', 'CHKP', 'CHKP-STATUS', 'CLEAR', 'CLOSE', 'COL', 'COLOR', 'COMMIT', 'CONTROL', 'COPY', 'CURSOR', 'D', 'DECLARE', 'DEFAULT', 'DEFINE', 'DELETE', 'DENWA', 'DISPLAY', 'DLI', 'DO', 'DUPLICATE', 'E', 'ELSE', 'ELSE-IF', 'END', 'END-CASE', 'END-DO', 'END-IF', 'END-PROC', 'ENDPAGE', 'ENDTABLE', 'ENTER', 'EOF', 'EQ', 'ERROR', 'EXIT', 'EXTERNAL', 'EZLIB', 'F1', 'F10', 'F11', 'F12', 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F2', 'F20', 'F21', 'F22', 'F23', 'F24', 'F25', 'F26', 'F27', 'F28', 'F29', 'F3', 'F30', 'F31', 'F32', 'F33', 'F34', 'F35', 'F36', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'FETCH', 'FILE-STATUS', 'FILL', 'FINAL', 'FIRST', 'FIRST-DUP', 'FOR', 'GE', 'GET', 'GO', 'GOTO', 'GQ', 'GR', 'GT', 'HEADING', 'HEX', 'HIGH-VALUES', 'IDD', 'IDMS', 'IF', 'IN', 'INSERT', 'JUSTIFY', 'KANJI-DATE', 'KANJI-DATE-LONG', 'KANJI-TIME', 'KEY', 'KEY-PRESSED', 'KOKUGO', 'KUN', 'LAST-DUP', 'LE', 'LEVEL', 'LIKE', 'LINE', 'LINE-COUNT', 'LINE-NUMBER', 'LINK', 'LIST', 'LOW-VALUES', 'LQ', 'LS', 'LT', 'MACRO', 'MASK', 'MATCHED', 'MEND', 'MESSAGE', 'MOVE', 'MSTART', 'NE', 'NEWPAGE', 'NOMASK', 'NOPRINT', 'NOT', 'NOTE', 'NOVERIFY', 'NQ', 'NULL', 'OF', 'OR', 'OTHERWISE', 'PA1', 'PA2', 'PA3', 'PAGE-COUNT', 'PAGE-NUMBER', 'PARM-REGISTER', 'PATH-ID', 'PATTERN', 'PERFORM', 'POINT', 'POS', 'PRIMARY', 'PRINT', 'PROCEDURE', 'PROGRAM', 'PUT', 'READ', 'RECORD', 'RECORD-COUNT', 'RECORD-LENGTH', 'REFRESH', 'RELEASE', 'RENUM', 'REPEAT', 'REPORT', 'REPORT-INPUT', 'RESHOW', 'RESTART', 'RETRIEVE', 'RETURN-CODE', 'ROLLBACK', 'ROW', 'S', 'SCREEN', 'SEARCH', 'SECONDARY', 'SELECT', 'SEQUENCE', 'SIZE', 'SKIP', 'SOKAKU', 'SORT', 'SQL', 'STOP', 'SUM', 'SYSDATE', 'SYSDATE-LONG', 'SYSIN', 'SYSIPT', 'SYSLST', 'SYSPRINT', 'SYSSNAP', 'SYSTIME', 'TALLY', 'TERM-COLUMNS', 'TERM-NAME', 'TERM-ROWS', 'TERMINATION', 'TITLE', 'TO', 'TRANSFER', 'TRC', 'UNIQUE', 'UNTIL', 'UPDATE', 'UPPERCASE', 'USER', 'USERID', 'VALUE', 'VERIFY', 'W', 'WHEN', 'WHILE', 'WORK', 'WRITE', 'X', 'XDM', 'XRST' ]
tokens = { 'root': [ (r'\*.*\n', Comment.Single), (r'\n+', Whitespace), # Macro argument (r'&' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+\.', Name.Variable, 'after_macro_argument'), # Macro call (r'%' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Variable), (r'(FILE|MACRO|REPORT)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'after_declaration'), (r'(JOB|PARM)' + r'(' + _DELIMITER_PATTERN + r')', bygroups(Keyword.Declaration, Operator)), (words(_KEYWORDS, suffix=_DELIMITER_PATTERN_CAPTURE), bygroups(Keyword.Reserved, Operator)), (_OPERATORS_PATTERN, Operator), # Procedure declaration (r'(' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+)(\s*)(\.?)(\s*)(PROC)(\s*\n)', bygroups(Name.Function, Whitespace, Operator, Whitespace, Keyword.Declaration, Whitespace)), (r'[0-9]+\.[0-9]*', Number.Float), (r'[0-9]+', Number.Integer), (r"'(''|[^'])*'", String), (r'\s+', Whitespace), # Everything else just belongs to a name (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name), ], 'after_declaration': [ (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Function), default('#pop'), ], 'after_macro_argument': [ (r'\*.*\n', Comment.Single, '#pop'), (r'\s+', Whitespace, '#pop'), (_OPERATORS_PATTERN, Operator, '#pop'), (r"'(''|[^'])*'", String, '#pop'), # Everything else just belongs to a name (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name), ], } _COMMENT_LINE_REGEX = re.compile(r'^\s*\*') _MACRO_HEADER_REGEX = re.compile(r'^\s*MACRO')
def analyse_text(text): """ Perform a structural analysis for basic Easytrieve constructs. """ result = 0.0 lines = text.split('\n') hasEndProc = False hasHeaderComment = False hasFile = False hasJob = False hasProc = False hasParm = False hasReport = False
def isCommentLine(line): return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None
def isEmptyLine(line): return not bool(line.strip())
# Remove possible empty lines and header comments. while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])): if not isEmptyLine(lines[0]): hasHeaderComment = True del lines[0]
if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]): # Looks like an Easytrieve macro. result = 0.4 if hasHeaderComment: result += 0.4 else: # Scan the source for lines starting with indicators. for line in lines: words = line.split() if (len(words) >= 2): firstWord = words[0] if not hasReport: if not hasJob: if not hasFile: if not hasParm: if firstWord == 'PARM': hasParm = True if firstWord == 'FILE': hasFile = True if firstWord == 'JOB': hasJob = True elif firstWord == 'PROC': hasProc = True elif firstWord == 'END-PROC': hasEndProc = True elif firstWord == 'REPORT': hasReport = True
# Weight the findings. if hasJob and (hasProc == hasEndProc): if hasHeaderComment: result += 0.1 if hasParm: if hasProc: # Found PARM, JOB and PROC/END-PROC: # pretty sure this is Easytrieve. result += 0.8 else: # Found PARAM and JOB: probably this is Easytrieve result += 0.5 else: # Found JOB and possibly other keywords: might be Easytrieve result += 0.11 if hasParm: # Note: PARAM is not a proper English word, so this is # regarded a much better indicator for Easytrieve than # the other words. result += 0.2 if hasFile: result += 0.01 if hasReport: result += 0.01 assert 0.0 <= result <= 1.0 return result
class JclLexer(RegexLexer): """ Job Control Language (JCL) is a scripting language used on mainframe platforms to instruct the system on how to run a batch job or start a subsystem. It is somewhat comparable to MS DOS batch and Unix shell scripts. """ name = 'JCL' aliases = ['jcl'] filenames = ['*.jcl'] mimetypes = ['text/x-jcl'] url = 'https://en.wikipedia.org/wiki/Job_Control_Language' version_added = '2.1'
flags = re.IGNORECASE
tokens = { 'root': [ (r'//\*.*\n', Comment.Single), (r'//', Keyword.Pseudo, 'statement'), (r'/\*', Keyword.Pseudo, 'jes2_statement'), # TODO: JES3 statement (r'.*\n', Other) # Input text or inline code in any language. ], 'statement': [ (r'\s*\n', Whitespace, '#pop'), (r'([a-z]\w*)(\s+)(exec|job)(\s*)', bygroups(Name.Label, Whitespace, Keyword.Reserved, Whitespace), 'option'), (r'[a-z]\w*', Name.Variable, 'statement_command'), (r'\s+', Whitespace, 'statement_command'), ], 'statement_command': [ (r'\s+(command|cntl|dd|endctl|endif|else|include|jcllib|' r'output|pend|proc|set|then|xmit)\s+', Keyword.Reserved, 'option'), include('option') ], 'jes2_statement': [ (r'\s*\n', Whitespace, '#pop'), (r'\$', Keyword, 'option'), (r'\b(jobparam|message|netacct|notify|output|priority|route|' r'setup|signoff|xeq|xmit)\b', Keyword, 'option'), ], 'option': [ # (r'\n', Text, 'root'), (r'\*', Name.Builtin), (r'[\[\](){}<>;,]', Punctuation), (r'[-+*/=&%]', Operator), (r'[a-z_]\w*', Name), (r'\d+\.\d*', Number.Float), (r'\.\d+', Number.Float), (r'\d+', Number.Integer), (r"'", String, 'option_string'), (r'[ \t]+', Whitespace, 'option_comment'), (r'\.', Punctuation), ], 'option_string': [ (r"(\n)(//)", bygroups(Text, Keyword.Pseudo)), (r"''", String), (r"[^']", String), (r"'", String, '#pop'), ], 'option_comment': [ # (r'\n', Text, 'root'), (r'.+', Comment.Single), ] }
_JOB_HEADER_PATTERN = re.compile(r'^//[a-z#$@][a-z0-9#$@]{0,7}\s+job(\s+.*)?$', re.IGNORECASE)
def analyse_text(text): """ Recognize JCL job by header. """ result = 0.0 lines = text.split('\n') if len(lines) > 0: if JclLexer._JOB_HEADER_PATTERN.match(lines[0]): result = 1.0 assert 0.0 <= result <= 1.0 return result
class MiniScriptLexer(RegexLexer): """ For MiniScript source code. """
name = 'MiniScript' url = 'https://miniscript.org' aliases = ['miniscript', 'ms'] filenames = ['*.ms'] mimetypes = ['text/x-minicript', 'application/x-miniscript'] version_added = '2.6'
tokens = { 'root': [ (r'#!(.*?)$', Comment.Preproc), default('base'), ], 'base': [ ('//.*$', Comment.Single), (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number), (r'(?i)\d+e[+-]?\d+', Number), (r'\d+', Number), (r'\n', Text), (r'[^\S\n]+', Text), (r'"', String, 'string_double'), (r'(==|!=|<=|>=|[=+\-*/%^<>.:])', Operator), (r'[;,\[\]{}()]', Punctuation), (words(( 'break', 'continue', 'else', 'end', 'for', 'function', 'if', 'in', 'isa', 'then', 'repeat', 'return', 'while'), suffix=r'\b'), Keyword), (words(( 'abs', 'acos', 'asin', 'atan', 'ceil', 'char', 'cos', 'floor', 'log', 'round', 'rnd', 'pi', 'sign', 'sin', 'sqrt', 'str', 'tan', 'hasIndex', 'indexOf', 'len', 'val', 'code', 'remove', 'lower', 'upper', 'replace', 'split', 'indexes', 'values', 'join', 'sum', 'sort', 'shuffle', 'push', 'pop', 'pull', 'range', 'print', 'input', 'time', 'wait', 'locals', 'globals', 'outer', 'yield'), suffix=r'\b'), Name.Builtin), (r'(true|false|null)\b', Keyword.Constant), (r'(and|or|not|new)\b', Operator.Word), (r'(self|super|__isa)\b', Name.Builtin.Pseudo), (r'[a-zA-Z_]\w*', Name.Variable) ], 'string_double': [ (r'[^"\n]+', String), (r'""', String), (r'"', String, '#pop'), (r'\n', Text, '#pop'), # Stray linefeed also terminates strings. ] }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859""" pygments.lexers.sgf ~~~~~~~~~~~~~~~~~~~
Lexer for Smart Game Format (sgf) file format.
: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 Name, Literal, String, Punctuation, Whitespace
__all__ = ["SmartGameFormatLexer"]
class SmartGameFormatLexer(RegexLexer): """ Lexer for Smart Game Format (sgf) file format.
The format is used to store game records of board games for two players (mainly Go game). """ name = 'SmartGameFormat' url = 'https://www.red-bean.com/sgf/' aliases = ['sgf'] filenames = ['*.sgf'] version_added = '2.4'
tokens = { 'root': [ (r'[():;]+', Punctuation), # tokens: (r'(A[BW]|AE|AN|AP|AR|AS|[BW]L|BM|[BW]R|[BW]S|[BW]T|CA|CH|CP|CR|' r'DD|DM|DO|DT|EL|EV|EX|FF|FG|G[BW]|GC|GM|GN|HA|HO|ID|IP|IT|IY|KM|' r'KO|LB|LN|LT|L|MA|MN|M|N|OB|OM|ON|OP|OT|OV|P[BW]|PC|PL|PM|RE|RG|' r'RO|RU|SO|SC|SE|SI|SL|SO|SQ|ST|SU|SZ|T[BW]|TC|TE|TM|TR|UC|US|VW|' r'V|[BW]|C)', Name.Builtin), # number: (r'(\[)([0-9.]+)(\])', bygroups(Punctuation, Literal.Number, Punctuation)), # date: (r'(\[)([0-9]{4}-[0-9]{2}-[0-9]{2})(\])', bygroups(Punctuation, Literal.Date, Punctuation)), # point: (r'(\[)([a-z]{2})(\])', bygroups(Punctuation, String, Punctuation)), # double points: (r'(\[)([a-z]{2})(:)([a-z]{2})(\])', bygroups(Punctuation, String, Punctuation, String, Punctuation)),
(r'(\[)([\w\s#()+,\-.:?]+)(\])', bygroups(Punctuation, String, Punctuation)), (r'(\[)(\s.*)(\])', bygroups(Punctuation, Whitespace, Punctuation)), (r'\s+', Whitespace) ], }.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/monte.pyAdded+203
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/mosel.pyAdded+447
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ncl.pyAdded+894
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/nimrod.pyAdded+199
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/nit.pyAdded+63
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/nix.pyAdded+144
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/numbair.pyAdded+63
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/oberon.pyAdded+120
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/objective.pyAdded+513
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ooc.pyAdded+84
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/openscad.pyAdded+96
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/other.pyAdded+41
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/parasail.pyAdded+78
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/parsers.pyAdded+798
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pascal.pyAdded+644
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pawn.pyAdded+202
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pddl.pyAdded+82
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/perl.pyAdded+733
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/phix.pyAdded+363
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/php.pyAdded+335
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pointless.pyAdded+70
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/pony.pyAdded+93
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/praat.pyAdded+303
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/procfile.pyAdded+41
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/prolog.pyAdded+318
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/promql.pyAdded+176
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/prql.pyAdded+251
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ptx.pyAdded+119
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/python.pyAdded+1204
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/q.pyAdded+187
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/qlik.pyAdded+117
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/qvt.pyAdded+153
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/r.pyAdded+196
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rdf.pyAdded+468
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rebol.pyAdded+419
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rego.pyAdded+57
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rell.pyAdded+68
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/resource.pyAdded+83
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ride.pyAdded+138
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rita.pyAdded+42
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rnc.pyAdded+66
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/roboconf.pyAdded+81
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/robotframework.pyAdded+551
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/ruby.pyAdded+518
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/rust.pyAdded+222
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/sas.pyAdded+227
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/savi.pyAdded+171
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/scdoc.pyAdded+85
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/scripting.pyAdded+1638
.cache/uv/archive-v0/tBxQFW0T5WHZlgaRRErLR/pygments/lexers/sgf.pyAdded+59