Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/q.pyAdded+187
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/qvt.pyAdded+153
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rdf.pyAdded+468
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rebol.pyAdded+419
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rego.pyAdded+57
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rell.pyAdded+68
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/resource.pyAdded+83
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ride.pyAdded+138
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rita.pyAdded+42
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rnc.pyAdded+66
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/roboconf.pyAdded+81
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/robotframework.pyAdded+551
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ruby.pyAdded+518
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rust.pyAdded+222
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sas.pyAdded+227
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/savi.pyAdded+171
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/scdoc.pyAdded+85
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/scripting.pyAdded+1638
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sgf.pyAdded+59
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/shell.pyAdded+902
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sieve.pyAdded+78
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/slash.pyAdded+183
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/smalltalk.pyAdded+194
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/smithy.pyAdded+77
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/smv.pyAdded+78
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/snobol.pyAdded+82
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/solidity.pyAdded+87
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/soong.pyAdded+78
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sophia.pyAdded+102
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/special.pyAdded+122
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/spice.pyAdded+70
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sql.pyAdded+1111
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/srcinfo.pyAdded+62
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/stata.pyAdded+170
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/supercollider.pyAdded+94
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tablegen.pyAdded+177
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tact.pyAdded+303
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tal.pyAdded+77
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tcl.pyAdded+148
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/teal.pyAdded+88
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/templates.pyAdded+2355
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/teraterm.pyAdded+335
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/testing.pyAdded+209
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/text.pyAdded+27
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/textedit.pyAdded+205
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/textfmts.pyAdded+436
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/theorem.pyAdded+410
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/thingsdb.pyAdded+143
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tlb.pyAdded+59
- .cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tls.pyAdded+54
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, ], }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) ], }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) ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902""" pygments.lexers.shell ~~~~~~~~~~~~~~~~~~~~~
Lexers for various shells.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, \ include, default, this, using, words, line_refrom pygments.token import Punctuation, Whitespace, \ Text, Comment, Operator, Keyword, Name, String, Number, Genericfrom pygments.util import shebang_matches
__all__ = ['BashLexer', 'BashSessionLexer', 'TcshLexer', 'BatchLexer', 'SlurmBashLexer', 'MSDOSSessionLexer', 'PowerShellLexer', 'PowerShellSessionLexer', 'TcshSessionLexer', 'FishShellLexer', 'ExeclineLexer']
class BashLexer(RegexLexer): """ Lexer for (ba|k|z|)sh shell scripts. """
name = 'Bash' aliases = ['bash', 'sh', 'ksh', 'zsh', 'shell', 'openrc'] filenames = ['*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass', '*.exheres-0', '*.exlib', '*.zsh', '.bashrc', 'bashrc', '.bash_*', 'bash_*', 'zshrc', '.zshrc', '.kshrc', 'kshrc', 'PKGBUILD'] mimetypes = ['application/x-sh', 'application/x-shellscript', 'text/x-shellscript'] url = 'https://en.wikipedia.org/wiki/Unix_shell' version_added = '0.6'
tokens = { 'root': [ include('basic'), (r'`', String.Backtick, 'backticks'), include('data'), include('interp'), ], 'interp': [ (r'\$\(\(', Keyword, 'math'), (r'\$\(', Keyword, 'paren'), (r'\$\{#?', String.Interpol, 'curly'), (r'\$[a-zA-Z_]\w*', Name.Variable), # user variable (r'\$(?:\d+|[#$?!_*@-])', Name.Variable), # builtin (r'\$', Text), ], 'basic': [ (r'\b(if|fi|else|while|in|do|done|for|then|return|function|case|' r'select|break|continue|until|esac|elif)(\s*)\b', bygroups(Keyword, Whitespace)), (r'\b(alias|bg|bind|builtin|caller|cd|command|compgen|' r'complete|declare|dirs|disown|echo|enable|eval|exec|exit|' r'export|false|fc|fg|getopts|hash|help|history|jobs|kill|let|' r'local|logout|popd|printf|pushd|pwd|read|readonly|set|shift|' r'shopt|source|suspend|test|time|times|trap|true|type|typeset|' r'ulimit|umask|unalias|unset|wait)(?=[\s)`])', Name.Builtin), (r'\A#!.+\n', Comment.Hashbang), (r'#.*\n', Comment.Single), (r'\\[\w\W]', String.Escape), (r'(\b\w+)(\s*)(\+?=)', bygroups(Name.Variable, Whitespace, Operator)), (r'[\[\]{}()=]', Operator), (r'<<<', Operator), # here-string (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String), (r'&&|\|\|', Operator), ], 'data': [ (r'(?s)\$?"(\\.|[^"\\$])*"', String.Double), (r'"', String.Double, 'string'), (r"(?s)\$'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single), (r"(?s)'.*?'", String.Single), (r';', Punctuation), (r'&', Punctuation), (r'\|', Punctuation), (r'\s+', Whitespace), (r'\d+\b', Number), (r'[^=\s\[\]{}()$"\'`\\<&|;]+', Text), (r'<', Text), ], 'string': [ (r'"', String.Double, '#pop'), (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\$])+', String.Double), include('interp'), ], 'curly': [ (r'\}', String.Interpol, '#pop'), (r':-', Keyword), (r'\w+', Name.Variable), (r'[^}:"\'`$\\]+', Punctuation), (r':', Punctuation), include('root'), ], 'paren': [ (r'\)', Keyword, '#pop'), include('root'), ], 'math': [ (r'\)\)', Keyword, '#pop'), (r'\*\*|\|\||<<|>>|[-+*/%^|&<>]', Operator), (r'\d+#[\da-zA-Z]+', Number), (r'\d+#(?! )', Number), (r'0[xX][\da-fA-F]+', Number), (r'\d+', Number), (r'[a-zA-Z_]\w*', Name.Variable), # user variable include('root'), ], 'backticks': [ (r'`', String.Backtick, '#pop'), include('root'), ], }
def analyse_text(text): if shebang_matches(text, r'(ba|z|)sh'): return 1 if text.startswith('$ '): return 0.2
class SlurmBashLexer(BashLexer): """ Lexer for (ba|k|z|)sh Slurm scripts. """
name = 'Slurm' aliases = ['slurm', 'sbatch'] filenames = ['*.sl'] mimetypes = [] version_added = '2.4' EXTRA_KEYWORDS = {'srun'}
def get_tokens_unprocessed(self, text): for index, token, value in BashLexer.get_tokens_unprocessed(self, text): if token is Text and value in self.EXTRA_KEYWORDS: yield index, Name.Builtin, value elif token is Comment.Single and 'SBATCH' in value: yield index, Keyword.Pseudo, value else: yield index, token, value
class ShellSessionBaseLexer(Lexer): """ Base lexer for shell sessions.
.. versionadded:: 2.1 """
_bare_continuation = False _venv = re.compile(r'^(\([^)]*\))(\s*)')
def get_tokens_unprocessed(self, text): innerlexer = self._innerLexerCls(**self.options)
pos = 0 curcode = '' insertions = [] backslash_continuation = False
for match in line_re.finditer(text): line = match.group()
venv_match = self._venv.match(line) if venv_match: venv = venv_match.group(1) venv_whitespace = venv_match.group(2) insertions.append((len(curcode), [(0, Generic.Prompt.VirtualEnv, venv)])) if venv_whitespace: insertions.append((len(curcode), [(0, Text, venv_whitespace)])) line = line[venv_match.end():]
m = self._ps1rgx.match(line) if m: # To support output lexers (say diff output), the output # needs to be broken by prompts whenever the output lexer # changes. if not insertions: pos = match.start()
insertions.append((len(curcode), [(0, Generic.Prompt, m.group(1))])) curcode += m.group(2) backslash_continuation = curcode.endswith('\\\n') elif backslash_continuation: if line.startswith(self._ps2): insertions.append((len(curcode), [(0, Generic.Prompt, line[:len(self._ps2)])])) curcode += line[len(self._ps2):] else: curcode += line backslash_continuation = curcode.endswith('\\\n') elif self._bare_continuation and line.startswith(self._ps2): insertions.append((len(curcode), [(0, Generic.Prompt, line[:len(self._ps2)])])) curcode += line[len(self._ps2):] else: if insertions: toks = innerlexer.get_tokens_unprocessed(curcode) for i, t, v in do_insertions(insertions, toks): yield pos+i, t, v yield match.start(), Generic.Output, line insertions = [] curcode = '' if insertions: for i, t, v in do_insertions(insertions, innerlexer.get_tokens_unprocessed(curcode)): yield pos+i, t, v
class BashSessionLexer(ShellSessionBaseLexer): """ Lexer for Bash shell sessions, i.e. command lines, including a prompt, interspersed with output. """
name = 'Bash Session' aliases = ['console', 'shell-session'] filenames = ['*.sh-session', '*.shell-session'] mimetypes = ['application/x-shell-session', 'application/x-sh-session'] url = 'https://en.wikipedia.org/wiki/Unix_shell' version_added = '1.1' _example = "console/example.sh-session"
_innerLexerCls = BashLexer _ps1rgx = re.compile( r'^((?:(?:\[.*?\])|(?:\(\S+\))?(?:| |sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)' \ r'?|\[\S+[@:][^\n]+\].+))\s*[$#%]\s*)(.*\n?)') _ps2 = '> '
class BatchLexer(RegexLexer): """ Lexer for the DOS/Windows Batch file format. """ name = 'Batchfile' aliases = ['batch', 'bat', 'dosbatch', 'winbatch'] filenames = ['*.bat', '*.cmd'] mimetypes = ['application/x-dos-batch'] url = 'https://en.wikipedia.org/wiki/Batch_file' version_added = '0.7'
flags = re.MULTILINE | re.IGNORECASE
_nl = r'\n\x1a' _punct = r'&<>|' _ws = r'\t\v\f\r ,;=\xa0' _nlws = r'\s\x1a\xa0,;=' _space = rf'(?:(?:(?:\^[{_nl}])?[{_ws}])+)' _keyword_terminator = (rf'(?=(?:\^[{_nl}]?)?[{_ws}+./:[\\\]]|[{_nl}{_punct}(])') _token_terminator = rf'(?=\^?[{_ws}]|[{_punct}{_nl}])' _start_label = rf'((?:(?<=^[^:])|^[^:]?)[{_ws}]*)(:)' _label = rf'(?:(?:[^{_nlws}{_punct}+:^]|\^[{_nl}]?[\w\W])*)' _label_compound = rf'(?:(?:[^{_nlws}{_punct}+:^)]|\^[{_nl}]?[^)])*)' _number = rf'(?:-?(?:0[0-7]+|0x[\da-f]+|\d+){_token_terminator})' _opword = r'(?:equ|geq|gtr|leq|lss|neq)' _string = rf'(?:"[^{_nl}"]*(?:"|(?=[{_nl}])))' _variable = (r'(?:(?:%(?:\*|(?:~[a-z]*(?:\$[^:]+:)?)?\d|' rf'[^%:{_nl}]+(?::(?:~(?:-?\d+)?(?:,(?:-?\d+)?)?|(?:[^%{_nl}^]|' rf'\^[^%{_nl}])[^={_nl}]*=(?:[^%{_nl}^]|\^[^%{_nl}])*)?)?%))|' rf'(?:\^?![^!:{_nl}]+(?::(?:~(?:-?\d+)?(?:,(?:-?\d+)?)?|(?:' rf'[^!{_nl}^]|\^[^!{_nl}])[^={_nl}]*=(?:[^!{_nl}^]|\^[^!{_nl}])*)?)?\^?!))') _core_token = rf'(?:(?:(?:\^[{_nl}]?)?[^"{_nlws}{_punct}])+)' _core_token_compound = rf'(?:(?:(?:\^[{_nl}]?)?[^"{_nlws}{_punct})])+)' _token = rf'(?:[{_punct}]+|{_core_token})' _token_compound = rf'(?:[{_punct}]+|{_core_token_compound})' _stoken = (rf'(?:[{_punct}]+|(?:{_string}|{_variable}|{_core_token})+)')
def _make_begin_state(compound, _core_token=_core_token, _core_token_compound=_core_token_compound, _keyword_terminator=_keyword_terminator, _nl=_nl, _punct=_punct, _string=_string, _space=_space, _start_label=_start_label, _stoken=_stoken, _token_terminator=_token_terminator, _variable=_variable, _ws=_ws): rest = '(?:{}|{}|[^"%{}{}{}])*'.format(_string, _variable, _nl, _punct, ')' if compound else '') rest_of_line = rf'(?:(?:[^{_nl}^]|\^[{_nl}]?[\w\W])*)' rest_of_line_compound = rf'(?:(?:[^{_nl}^)]|\^[{_nl}]?[^)])*)' set_space = rf'((?:(?:\^[{_nl}]?)?[^\S\n])*)' suffix = '' if compound: _keyword_terminator = rf'(?:(?=\))|{_keyword_terminator})' _token_terminator = rf'(?:(?=\))|{_token_terminator})' suffix = '/compound' return [ ((r'\)', Punctuation, '#pop') if compound else (rf'\)((?=\()|{_token_terminator}){rest_of_line}', Comment.Single)), (rf'(?={_start_label})', Text, f'follow{suffix}'), (_space, using(this, state='text')), include(f'redirect{suffix}'), (rf'[{_nl}]+', Text), (r'\(', Punctuation, 'root/compound'), (r'@+', Punctuation), (rf'((?:for|if|rem)(?:(?=(?:\^[{_nl}]?)?/)|(?:(?!\^)|' rf'(?<=m))(?:(?=\()|{_token_terminator})))({_space}?{_core_token_compound if compound else _core_token}?(?:\^[{_nl}]?)?/(?:\^[{_nl}]?)?\?)', bygroups(Keyword, using(this, state='text')), f'follow{suffix}'), (rf'(goto{_keyword_terminator})({rest}(?:\^[{_nl}]?)?/(?:\^[{_nl}]?)?\?{rest})', bygroups(Keyword, using(this, state='text')), f'follow{suffix}'), (words(('assoc', 'break', 'cd', 'chdir', 'cls', 'color', 'copy', 'date', 'del', 'dir', 'dpath', 'echo', 'endlocal', 'erase', 'exit', 'ftype', 'keys', 'md', 'mkdir', 'mklink', 'move', 'path', 'pause', 'popd', 'prompt', 'pushd', 'rd', 'ren', 'rename', 'rmdir', 'setlocal', 'shift', 'start', 'time', 'title', 'type', 'ver', 'verify', 'vol'), suffix=_keyword_terminator), Keyword, f'follow{suffix}'), (rf'(call)({_space}?)(:)', bygroups(Keyword, using(this, state='text'), Punctuation), f'call{suffix}'), (rf'call{_keyword_terminator}', Keyword), (rf'(for{_token_terminator}(?!\^))({_space})(/f{_token_terminator})', bygroups(Keyword, using(this, state='text'), Keyword), ('for/f', 'for')), (rf'(for{_token_terminator}(?!\^))({_space})(/l{_token_terminator})', bygroups(Keyword, using(this, state='text'), Keyword), ('for/l', 'for')), (rf'for{_token_terminator}(?!\^)', Keyword, ('for2', 'for')), (rf'(goto{_keyword_terminator})({_space}?)(:?)', bygroups(Keyword, using(this, state='text'), Punctuation), f'label{suffix}'), (rf'(if(?:(?=\()|{_token_terminator})(?!\^))({_space}?)((?:/i{_token_terminator})?)({_space}?)((?:not{_token_terminator})?)({_space}?)', bygroups(Keyword, using(this, state='text'), Keyword, using(this, state='text'), Keyword, using(this, state='text')), ('(?', 'if')), (rf'rem(((?=\()|{_token_terminator}){_space}?{_stoken}?.*|{_keyword_terminator}{rest_of_line_compound if compound else rest_of_line})', Comment.Single, f'follow{suffix}'), (rf'(set{_keyword_terminator}){set_space}(/a)', bygroups(Keyword, using(this, state='text'), Keyword), f'arithmetic{suffix}'), (r'(set{}){}((?:/p)?){}((?:(?:(?:\^[{}]?)?[^"{}{}^={}]|' r'\^[{}]?[^"=])+)?)((?:(?:\^[{}]?)?=)?)'.format(_keyword_terminator, set_space, set_space, _nl, _nl, _punct, ')' if compound else '', _nl, _nl), bygroups(Keyword, using(this, state='text'), Keyword, using(this, state='text'), using(this, state='variable'), Punctuation), f'follow{suffix}'), default(f'follow{suffix}') ]
def _make_follow_state(compound, _label=_label, _label_compound=_label_compound, _nl=_nl, _space=_space, _start_label=_start_label, _token=_token, _token_compound=_token_compound, _ws=_ws): suffix = '/compound' if compound else '' state = [] if compound: state.append((r'(?=\))', Text, '#pop')) state += [ (rf'{_start_label}([{_ws}]*)({_label_compound if compound else _label})(.*)', bygroups(Text, Punctuation, Text, Name.Label, Comment.Single)), include(f'redirect{suffix}'), (rf'(?=[{_nl}])', Text, '#pop'), (r'\|\|?|&&?', Punctuation, '#pop'), include('text') ] return state
def _make_arithmetic_state(compound, _nl=_nl, _punct=_punct, _string=_string, _variable=_variable, _ws=_ws, _nlws=_nlws): op = r'=+\-*/!~' state = [] if compound: state.append((r'(?=\))', Text, '#pop')) state += [ (r'0[0-7]+', Number.Oct), (r'0x[\da-f]+', Number.Hex), (r'\d+', Number.Integer), (r'[(),]+', Punctuation), (rf'([{op}]|%|\^\^)+', Operator), (r'({}|{}|(\^[{}]?)?[^(){}%\^"{}{}]|\^[{}]?{})+'.format(_string, _variable, _nl, op, _nlws, _punct, _nlws, r'[^)]' if compound else r'[\w\W]'), using(this, state='variable')), (r'(?=[\x00|&])', Text, '#pop'), include('follow') ] return state
def _make_call_state(compound, _label=_label, _label_compound=_label_compound): state = [] if compound: state.append((r'(?=\))', Text, '#pop')) state.append((r'(:?)(%s)' % (_label_compound if compound else _label), bygroups(Punctuation, Name.Label), '#pop')) return state
def _make_label_state(compound, _label=_label, _label_compound=_label_compound, _nl=_nl, _punct=_punct, _string=_string, _variable=_variable): state = [] if compound: state.append((r'(?=\))', Text, '#pop')) state.append((r'({}?)((?:{}|{}|\^[{}]?{}|[^"%^{}{}{}])*)'.format(_label_compound if compound else _label, _string, _variable, _nl, r'[^)]' if compound else r'[\w\W]', _nl, _punct, r')' if compound else ''), bygroups(Name.Label, Comment.Single), '#pop')) return state
def _make_redirect_state(compound, _core_token_compound=_core_token_compound, _nl=_nl, _punct=_punct, _stoken=_stoken, _string=_string, _space=_space, _variable=_variable, _nlws=_nlws): stoken_compound = (rf'(?:[{_punct}]+|(?:{_string}|{_variable}|{_core_token_compound})+)') return [ (rf'((?:(?<=[{_nlws}])\d)?)(>>?&|<&)([{_nlws}]*)(\d)', bygroups(Number.Integer, Punctuation, Text, Number.Integer)), (rf'((?:(?<=[{_nlws}])(?<!\^[{_nl}])\d)?)(>>?|<)({_space}?{stoken_compound if compound else _stoken})', bygroups(Number.Integer, Punctuation, using(this, state='text'))) ]
tokens = { 'root': _make_begin_state(False), 'follow': _make_follow_state(False), 'arithmetic': _make_arithmetic_state(False), 'call': _make_call_state(False), 'label': _make_label_state(False), 'redirect': _make_redirect_state(False), 'root/compound': _make_begin_state(True), 'follow/compound': _make_follow_state(True), 'arithmetic/compound': _make_arithmetic_state(True), 'call/compound': _make_call_state(True), 'label/compound': _make_label_state(True), 'redirect/compound': _make_redirect_state(True), 'variable-or-escape': [ (_variable, Name.Variable), (rf'%%|\^[{_nl}]?(\^!|[\w\W])', String.Escape) ], 'string': [ (r'"', String.Double, '#pop'), (_variable, Name.Variable), (r'\^!|%%', String.Escape), (rf'[^"%^{_nl}]+|[%^]', String.Double), default('#pop') ], 'sqstring': [ include('variable-or-escape'), (r'[^%]+|%', String.Single) ], 'bqstring': [ include('variable-or-escape'), (r'[^%]+|%', String.Backtick) ], 'text': [ (r'"', String.Double, 'string'), include('variable-or-escape'), (rf'[^"%^{_nlws}{_punct}\d)]+|.', Text) ], 'variable': [ (r'"', String.Double, 'string'), include('variable-or-escape'), (rf'[^"%^{_nl}]+|.', Name.Variable) ], 'for': [ (rf'({_space})(in)({_space})(\()', bygroups(using(this, state='text'), Keyword, using(this, state='text'), Punctuation), '#pop'), include('follow') ], 'for2': [ (r'\)', Punctuation), (rf'({_space})(do{_token_terminator})', bygroups(using(this, state='text'), Keyword), '#pop'), (rf'[{_nl}]+', Text), include('follow') ], 'for/f': [ (rf'(")((?:{_variable}|[^"])*?")([{_nlws}]*)(\))', bygroups(String.Double, using(this, state='string'), Text, Punctuation)), (r'"', String.Double, ('#pop', 'for2', 'string')), (rf"('(?:%%|{_variable}|[\w\W])*?')([{_nlws}]*)(\))", bygroups(using(this, state='sqstring'), Text, Punctuation)), (rf'(`(?:%%|{_variable}|[\w\W])*?`)([{_nlws}]*)(\))', bygroups(using(this, state='bqstring'), Text, Punctuation)), include('for2') ], 'for/l': [ (r'-?\d+', Number.Integer), include('for2') ], 'if': [ (rf'((?:cmdextversion|errorlevel){_token_terminator})({_space})(\d+)', bygroups(Keyword, using(this, state='text'), Number.Integer), '#pop'), (rf'(defined{_token_terminator})({_space})({_stoken})', bygroups(Keyword, using(this, state='text'), using(this, state='variable')), '#pop'), (rf'(exist{_token_terminator})({_space}{_stoken})', bygroups(Keyword, using(this, state='text')), '#pop'), (rf'({_number}{_space})({_opword})({_space}{_number})', bygroups(using(this, state='arithmetic'), Operator.Word, using(this, state='arithmetic')), '#pop'), (_stoken, using(this, state='text'), ('#pop', 'if2')), ], 'if2': [ (rf'({_space}?)(==)({_space}?{_stoken})', bygroups(using(this, state='text'), Operator, using(this, state='text')), '#pop'), (rf'({_space})({_opword})({_space}{_stoken})', bygroups(using(this, state='text'), Operator.Word, using(this, state='text')), '#pop') ], '(?': [ (_space, using(this, state='text')), (r'\(', Punctuation, ('#pop', 'else?', 'root/compound')), default('#pop') ], 'else?': [ (_space, using(this, state='text')), (rf'else{_token_terminator}', Keyword, '#pop'), default('#pop') ] }
class MSDOSSessionLexer(ShellSessionBaseLexer): """ Lexer for MS DOS shell sessions, i.e. command lines, including a prompt, interspersed with output. """
name = 'MSDOS Session' aliases = ['doscon'] filenames = [] mimetypes = [] url = 'https://en.wikipedia.org/wiki/MS-DOS' version_added = '2.1' _example = "doscon/session"
_innerLexerCls = BatchLexer _ps1rgx = re.compile(r'^([^>]*>)(.*\n?)') _ps2 = 'More? '
class TcshLexer(RegexLexer): """ Lexer for tcsh scripts. """
name = 'Tcsh' aliases = ['tcsh', 'csh'] filenames = ['*.tcsh', '*.csh'] mimetypes = ['application/x-csh'] url = 'https://www.tcsh.org' version_added = '0.10'
tokens = { 'root': [ include('basic'), (r'\$\(', Keyword, 'paren'), (r'\$\{#?', Keyword, 'curly'), (r'`', String.Backtick, 'backticks'), include('data'), ], 'basic': [ (r'\b(if|endif|else|while|then|foreach|case|default|' r'break|continue|goto|breaksw|end|switch|endsw)\s*\b', Keyword), (r'\b(alias|alloc|bg|bindkey|builtins|bye|caller|cd|chdir|' r'complete|dirs|echo|echotc|eval|exec|exit|fg|filetest|getxvers|' r'glob|getspath|hashstat|history|hup|inlib|jobs|kill|' r'limit|log|login|logout|ls-F|migrate|newgrp|nice|nohup|notify|' r'onintr|popd|printenv|pushd|rehash|repeat|rootnode|popd|pushd|' r'set|shift|sched|setenv|setpath|settc|setty|setxvers|shift|' r'source|stop|suspend|source|suspend|telltc|time|' r'umask|unalias|uncomplete|unhash|universe|unlimit|unset|unsetenv|' r'ver|wait|warp|watchlog|where|which)\s*\b', Name.Builtin), (r'#.*', Comment), (r'\\[\w\W]', String.Escape), (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)), (r'[\[\]{}()=]+', Operator), (r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String), (r';', Punctuation), ], 'data': [ (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double), (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single), (r'\s+', Text), (r'[^=\s\[\]{}()$"\'`\\;#]+', Text), (r'\d+(?= |\Z)', Number), (r'\$#?(\w+|.)', Name.Variable), ], 'curly': [ (r'\}', Keyword, '#pop'), (r':-', Keyword), (r'\w+', Name.Variable), (r'[^}:"\'`$]+', Punctuation), (r':', Punctuation), include('root'), ], 'paren': [ (r'\)', Keyword, '#pop'), include('root'), ], 'backticks': [ (r'`', String.Backtick, '#pop'), include('root'), ], }
class TcshSessionLexer(ShellSessionBaseLexer): """ Lexer for Tcsh sessions, i.e. command lines, including a prompt, interspersed with output. """
name = 'Tcsh Session' aliases = ['tcshcon'] filenames = [] mimetypes = [] url = 'https://www.tcsh.org' version_added = '2.1' _example = "tcshcon/session"
_innerLexerCls = TcshLexer _ps1rgx = re.compile(r'^([^>]+>)(.*\n?)') _ps2 = '? '
class PowerShellLexer(RegexLexer): """ For Windows PowerShell code. """ name = 'PowerShell' aliases = ['powershell', 'pwsh', 'posh', 'ps1', 'psm1'] filenames = ['*.ps1', '*.psm1'] mimetypes = ['text/x-powershell'] url = 'https://learn.microsoft.com/en-us/powershell' version_added = '1.5'
flags = re.DOTALL | re.IGNORECASE | re.MULTILINE
keywords = ( 'while validateset validaterange validatepattern validatelength ' 'validatecount until trap switch return ref process param parameter in ' 'if global: local: function foreach for finally filter end elseif else ' 'dynamicparam do default continue cmdletbinding break begin alias \\? ' '% #script #private #local #global mandatory parametersetname position ' 'valuefrompipeline valuefrompipelinebypropertyname ' 'valuefromremainingarguments helpmessage try catch throw').split()
operators = ( 'and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle ' 'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains ' 'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt ' 'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like ' 'lt match ne not notcontains notlike notmatch or regex replace ' 'wildcard').split()
verbs = ( 'write where watch wait use update unregister unpublish unprotect ' 'unlock uninstall undo unblock trace test tee take sync switch ' 'suspend submit stop step start split sort skip show set send select ' 'search scroll save revoke resume restore restart resolve resize ' 'reset request repair rename remove register redo receive read push ' 'publish protect pop ping out optimize open new move mount merge ' 'measure lock limit join invoke install initialize import hide group ' 'grant get format foreach find export expand exit enter enable edit ' 'dismount disconnect disable deny debug cxnew copy convertto ' 'convertfrom convert connect confirm compress complete compare close ' 'clear checkpoint block backup assert approve aggregate add').split()
aliases_ = ( 'ac asnp cat cd cfs chdir clc clear clhy cli clp cls clv cnsn ' 'compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo epal ' 'epcsv epsn erase etsn exsn fc fhx fl foreach ft fw gal gbp gc gci gcm ' 'gcs gdr ghy gi gjb gl gm gmo gp gps gpv group gsn gsnp gsv gu gv gwmi ' 'h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ' 'ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv ' 'oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo ' 'rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc select ' 'set shcm si sl sleep sls sort sp spjb spps spsv start sujb sv swmi tee ' 'trcm type wget where wjb write').split()
commenthelp = ( 'component description example externalhelp forwardhelpcategory ' 'forwardhelptargetname functionality inputs link ' 'notes outputs parameter remotehelprunspace role synopsis').split()
tokens = { 'root': [ # we need to count pairs of parentheses for correct highlight # of '$(...)' blocks in strings (r'\(', Punctuation, 'child'), (r'\s+', Text), (r'^(\s*#[#\s]*)(\.(?:{}))([^\n]*$)'.format('|'.join(commenthelp)), bygroups(Comment, String.Doc, Comment)), (r'#[^\n]*?$', Comment), (r'(<|<)#', Comment.Multiline, 'multline'), (r'@"\n', String.Heredoc, 'heredoc-double'), (r"@'\n.*?\n'@", String.Heredoc), # escaped syntax (r'`[\'"$@-]', Punctuation), (r'"', String.Double, 'string'), (r"'([^']|'')*'", String.Single), (r'(\$|@@|@)((global|script|private|env):)?\w+', Name.Variable), (r'({})\b'.format('|'.join(keywords)), Keyword), (r'-({})\b'.format('|'.join(operators)), Operator), (r'({})-[a-z_]\w*\b'.format('|'.join(verbs)), Name.Builtin), (r'({})\s'.format('|'.join(aliases_)), Name.Builtin), (r'\[[a-z_\[][\w. `,\[\]]*\]', Name.Constant), # .net [type]s (r'-[a-z_]\w*', Name), (r'\w+', Name), (r'[.,;:@{}\[\]$()=+*/\\&%!~?^`|<>-]', Punctuation), ], 'child': [ (r'\)', Punctuation, '#pop'), include('root'), ], 'multline': [ (r'[^#&.]+', Comment.Multiline), (r'#(>|>)', Comment.Multiline, '#pop'), (r'\.({})'.format('|'.join(commenthelp)), String.Doc), (r'[#&.]', Comment.Multiline), ], 'string': [ (r"`[0abfnrtv'\"$`]", String.Escape), (r'[^$`"]+', String.Double), (r'\$\(', Punctuation, 'child'), (r'""', String.Double), (r'[`$]', String.Double), (r'"', String.Double, '#pop'), ], 'heredoc-double': [ (r'\n"@', String.Heredoc, '#pop'), (r'\$\(', Punctuation, 'child'), (r'[^@\n]+"]', String.Heredoc), (r".", String.Heredoc), ] }
class PowerShellSessionLexer(ShellSessionBaseLexer): """ Lexer for PowerShell sessions, i.e. command lines, including a prompt, interspersed with output. """
name = 'PowerShell Session' aliases = ['pwsh-session', 'ps1con'] filenames = [] mimetypes = [] url = 'https://learn.microsoft.com/en-us/powershell' version_added = '2.1' _example = "pwsh-session/session"
_innerLexerCls = PowerShellLexer _bare_continuation = True _ps1rgx = re.compile(r'^((?:\[[^]]+\]: )?PS[^>]*> ?)(.*\n?)') _ps2 = '> '
class FishShellLexer(RegexLexer): """ Lexer for Fish shell scripts. """
name = 'Fish' aliases = ['fish', 'fishshell'] filenames = ['*.fish', '*.load'] mimetypes = ['application/x-fish'] url = 'https://fishshell.com' version_added = '2.1'
tokens = { 'root': [ include('basic'), include('data'), include('interp'), ], 'interp': [ (r'\$\(\(', Keyword, 'math'), (r'\(', Keyword, 'paren'), (r'\$#?(\w+|.)', Name.Variable), ], 'basic': [ (r'\b(begin|end|if|else|while|break|for|in|return|function|block|' r'case|continue|switch|not|and|or|set|echo|exit|pwd|true|false|' r'cd|count|test)(\s*)\b', bygroups(Keyword, Text)), (r'\b(alias|bg|bind|breakpoint|builtin|command|commandline|' r'complete|contains|dirh|dirs|emit|eval|exec|fg|fish|fish_config|' r'fish_indent|fish_pager|fish_prompt|fish_right_prompt|' r'fish_update_completions|fishd|funced|funcsave|functions|help|' r'history|isatty|jobs|math|mimedb|nextd|open|popd|prevd|psub|' r'pushd|random|read|set_color|source|status|trap|type|ulimit|' r'umask|vared|fc|getopts|hash|kill|printf|time|wait)\s*\b(?!\.)', Name.Builtin), (r'#.*\n', Comment), (r'\\[\w\W]', String.Escape), (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Whitespace, Operator)), (r'[\[\]()=]', Operator), (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String), ], 'data': [ (r'(?s)\$?"(\\\\|\\[0-7]+|\\.|[^"\\$])*"', String.Double), (r'"', String.Double, 'string'), (r"(?s)\$'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single), (r"(?s)'.*?'", String.Single), (r';', Punctuation), (r'&|\||\^|<|>', Operator), (r'\s+', Text), (r'\d+(?= |\Z)', Number), (r'[^=\s\[\]{}()$"\'`\\<&|;]+', Text), ], 'string': [ (r'"', String.Double, '#pop'), (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\$])+', String.Double), include('interp'), ], 'paren': [ (r'\)', Keyword, '#pop'), include('root'), ], 'math': [ (r'\)\)', Keyword, '#pop'), (r'[-+*/%^|&]|\*\*|\|\|', Operator), (r'\d+#\d+', Number), (r'\d+#(?! )', Number), (r'\d+', Number), include('root'), ], }
class ExeclineLexer(RegexLexer): """ Lexer for Laurent Bercot's execline language. """
name = 'execline' aliases = ['execline'] filenames = ['*.exec'] url = 'https://skarnet.org/software/execline' version_added = '2.7'
tokens = { 'root': [ include('basic'), include('data'), include('interp') ], 'interp': [ (r'\$\{', String.Interpol, 'curly'), (r'\$[\w@#]+', Name.Variable), # user variable (r'\$', Text), ], 'basic': [ (r'\b(background|backtick|cd|define|dollarat|elgetopt|' r'elgetpositionals|elglob|emptyenv|envfile|exec|execlineb|' r'exit|export|fdblock|fdclose|fdmove|fdreserve|fdswap|' r'forbacktickx|foreground|forstdin|forx|getcwd|getpid|heredoc|' r'homeof|if|ifelse|ifte|ifthenelse|importas|loopwhilex|' r'multidefine|multisubstitute|pipeline|piperw|posix-cd|' r'redirfd|runblock|shift|trap|tryexec|umask|unexport|wait|' r'withstdinas)\b', Name.Builtin), (r'\A#!.+\n', Comment.Hashbang), (r'#.*\n', Comment.Single), (r'[{}]', Operator) ], 'data': [ (r'(?s)"(\\.|[^"\\$])*"', String.Double), (r'"', String.Double, 'string'), (r'\s+', Text), (r'[^\s{}$"\\]+', Text) ], 'string': [ (r'"', String.Double, '#pop'), (r'(?s)(\\\\|\\.|[^"\\$])+', String.Double), include('interp'), ], 'curly': [ (r'\}', String.Interpol, '#pop'), (r'[\w#@]+', Name.Variable), include('root') ]
}
def analyse_text(text): if shebang_matches(text, r'execlineb'): return 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778""" pygments.lexers.sieve ~~~~~~~~~~~~~~~~~~~~~
Lexer for Sieve file format.
https://tools.ietf.org/html/rfc5228 https://tools.ietf.org/html/rfc5173 https://tools.ietf.org/html/rfc5229 https://tools.ietf.org/html/rfc5230 https://tools.ietf.org/html/rfc5232 https://tools.ietf.org/html/rfc5235 https://tools.ietf.org/html/rfc5429 https://tools.ietf.org/html/rfc8580
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Comment, Name, Literal, String, Text, Punctuation, \ Keyword
__all__ = ["SieveLexer"]
class SieveLexer(RegexLexer): """ Lexer for sieve format. """ name = 'Sieve' filenames = ['*.siv', '*.sieve'] aliases = ['sieve'] url = 'https://en.wikipedia.org/wiki/Sieve_(mail_filtering_language)' version_added = '2.6'
tokens = { 'root': [ (r'\s+', Text), (r'[();,{}\[\]]', Punctuation), # import: (r'(?i)require', Keyword.Namespace), # tags: (r'(?i)(:)(addresses|all|contains|content|create|copy|comparator|' r'count|days|detail|domain|fcc|flags|from|handle|importance|is|' r'localpart|length|lowerfirst|lower|matches|message|mime|options|' r'over|percent|quotewildcard|raw|regex|specialuse|subject|text|' r'under|upperfirst|upper|value)', bygroups(Name.Tag, Name.Tag)), # tokens: (r'(?i)(address|addflag|allof|anyof|body|discard|elsif|else|envelope|' r'ereject|exists|false|fileinto|if|hasflag|header|keep|' r'notify_method_capability|notify|not|redirect|reject|removeflag|' r'setflag|size|spamtest|stop|string|true|vacation|virustest)', Name.Builtin), (r'(?i)set', Keyword.Declaration), # number: (r'([0-9.]+)([kmgKMG])?', bygroups(Literal.Number, Literal.Number)), # comment: (r'#.*$', Comment.Single), (r'/\*.*\*/', Comment.Multiline), # string: (r'"[^"]*?"', String), # text block: (r'text:', Name.Tag, 'text'), ], 'text': [ (r'[^.].*?\n', String), (r'^\.', Punctuation, "#pop"), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183""" pygments.lexers.slash ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Slash programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import ExtendedRegexLexer, bygroups, DelegatingLexerfrom pygments.token import Name, Number, String, Comment, Punctuation, \ Other, Keyword, Operator, Whitespace
__all__ = ['SlashLexer']
class SlashLanguageLexer(ExtendedRegexLexer): _nkw = r'(?=[^a-zA-Z_0-9])'
def move_state(new_state): return ("#pop", new_state)
def right_angle_bracket(lexer, match, ctx): if len(ctx.stack) > 1 and ctx.stack[-2] == "string": ctx.stack.pop() yield match.start(), String.Interpol, '}' ctx.pos = match.end() pass
tokens = { "root": [ (r"<%=", Comment.Preproc, move_state("slash")), (r"<%!!", Comment.Preproc, move_state("slash")), (r"<%#.*?%>", Comment.Multiline), (r"<%", Comment.Preproc, move_state("slash")), (r".|\n", Other), ], "string": [ (r"\\", String.Escape, move_state("string_e")), (r"\"", String, move_state("slash")), (r"#\{", String.Interpol, "slash"), (r'.|\n', String), ], "string_e": [ (r'n', String.Escape, move_state("string")), (r't', String.Escape, move_state("string")), (r'r', String.Escape, move_state("string")), (r'e', String.Escape, move_state("string")), (r'x[a-fA-F0-9]{2}', String.Escape, move_state("string")), (r'.', String.Escape, move_state("string")), ], "regexp": [ (r'}[a-z]*', String.Regex, move_state("slash")), (r'\\(.|\n)', String.Regex), (r'{', String.Regex, "regexp_r"), (r'.|\n', String.Regex), ], "regexp_r": [ (r'}[a-z]*', String.Regex, "#pop"), (r'\\(.|\n)', String.Regex), (r'{', String.Regex, "regexp_r"), ], "slash": [ (r"%>", Comment.Preproc, move_state("root")), (r"\"", String, move_state("string")), (r"'[a-zA-Z0-9_]+", String), (r'%r{', String.Regex, move_state("regexp")), (r'/\*.*?\*/', Comment.Multiline), (r"(#|//).*?\n", Comment.Single), (r'-?[0-9]+e[+-]?[0-9]+', Number.Float), (r'-?[0-9]+\.[0-9]+(e[+-]?[0-9]+)?', Number.Float), (r'-?[0-9]+', Number.Integer), (r'nil'+_nkw, Name.Builtin), (r'true'+_nkw, Name.Builtin), (r'false'+_nkw, Name.Builtin), (r'self'+_nkw, Name.Builtin), (r'(class)(\s+)([A-Z][a-zA-Z0-9_\']*)', bygroups(Keyword, Whitespace, Name.Class)), (r'class'+_nkw, Keyword), (r'extends'+_nkw, Keyword), (r'(def)(\s+)(self)(\s*)(\.)(\s*)([a-z_][a-zA-Z0-9_\']*=?|<<|>>|==|<=>|<=|<|>=|>|\+|-(self)?|~(self)?|\*|/|%|^|&&|&|\||\[\]=?)', bygroups(Keyword, Whitespace, Name.Builtin, Whitespace, Punctuation, Whitespace, Name.Function)), (r'(def)(\s+)([a-z_][a-zA-Z0-9_\']*=?|<<|>>|==|<=>|<=|<|>=|>|\+|-(self)?|~(self)?|\*|/|%|^|&&|&|\||\[\]=?)', bygroups(Keyword, Whitespace, Name.Function)), (r'def'+_nkw, Keyword), (r'if'+_nkw, Keyword), (r'elsif'+_nkw, Keyword), (r'else'+_nkw, Keyword), (r'unless'+_nkw, Keyword), (r'for'+_nkw, Keyword), (r'in'+_nkw, Keyword), (r'while'+_nkw, Keyword), (r'until'+_nkw, Keyword), (r'and'+_nkw, Keyword), (r'or'+_nkw, Keyword), (r'not'+_nkw, Keyword), (r'lambda'+_nkw, Keyword), (r'try'+_nkw, Keyword), (r'catch'+_nkw, Keyword), (r'return'+_nkw, Keyword), (r'next'+_nkw, Keyword), (r'last'+_nkw, Keyword), (r'throw'+_nkw, Keyword), (r'use'+_nkw, Keyword), (r'switch'+_nkw, Keyword), (r'\\', Keyword), (r'λ', Keyword), (r'__FILE__'+_nkw, Name.Builtin.Pseudo), (r'__LINE__'+_nkw, Name.Builtin.Pseudo), (r'[A-Z][a-zA-Z0-9_\']*'+_nkw, Name.Constant), (r'[a-z_][a-zA-Z0-9_\']*'+_nkw, Name), (r'@[a-z_][a-zA-Z0-9_\']*'+_nkw, Name.Variable.Instance), (r'@@[a-z_][a-zA-Z0-9_\']*'+_nkw, Name.Variable.Class), (r'\(', Punctuation), (r'\)', Punctuation), (r'\[', Punctuation), (r'\]', Punctuation), (r'\{', Punctuation), (r'\}', right_angle_bracket), (r';', Punctuation), (r',', Punctuation), (r'<<=', Operator), (r'>>=', Operator), (r'<<', Operator), (r'>>', Operator), (r'==', Operator), (r'!=', Operator), (r'=>', Operator), (r'=', Operator), (r'<=>', Operator), (r'<=', Operator), (r'>=', Operator), (r'<', Operator), (r'>', Operator), (r'\+\+', Operator), (r'\+=', Operator), (r'-=', Operator), (r'\*\*=', Operator), (r'\*=', Operator), (r'\*\*', Operator), (r'\*', Operator), (r'/=', Operator), (r'\+', Operator), (r'-', Operator), (r'/', Operator), (r'%=', Operator), (r'%', Operator), (r'^=', Operator), (r'&&=', Operator), (r'&=', Operator), (r'&&', Operator), (r'&', Operator), (r'\|\|=', Operator), (r'\|=', Operator), (r'\|\|', Operator), (r'\|', Operator), (r'!', Operator), (r'\.\.\.', Operator), (r'\.\.', Operator), (r'\.', Operator), (r'::', Operator), (r':', Operator), (r'(\s|\n)+', Whitespace), (r'[a-z_][a-zA-Z0-9_\']*', Name.Variable), ], }
class SlashLexer(DelegatingLexer): """ Lexer for the Slash programming language. """
name = 'Slash' aliases = ['slash'] filenames = ['*.sla'] url = 'https://github.com/arturadib/Slash-A' version_added = '2.4'
def __init__(self, **options): from pygments.lexers.web import HtmlLexer super().__init__(HtmlLexer, SlashLanguageLexer, **options)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194""" pygments.lexers.smalltalk ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Smalltalk and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroups, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['SmalltalkLexer', 'NewspeakLexer']
class SmalltalkLexer(RegexLexer): """ For Smalltalk syntax. Contributed by Stefan Matthias Aust. Rewritten by Nils Winter. """ name = 'Smalltalk' url = 'http://www.smalltalk.org/' filenames = ['*.st'] aliases = ['smalltalk', 'squeak', 'st'] mimetypes = ['text/x-smalltalk'] version_added = '0.10'
tokens = { 'root': [ (r'(<)(\w+:)(.*?)(>)', bygroups(Text, Keyword, Text, Text)), include('squeak fileout'), include('whitespaces'), include('method definition'), (r'(\|)([\w\s]*)(\|)', bygroups(Operator, Name.Variable, Operator)), include('objects'), (r'\^|\:=|\_', Operator), # temporaries (r'[\]({}.;!]', Text), ], 'method definition': [ # Not perfect can't allow whitespaces at the beginning and the # without breaking everything (r'([a-zA-Z]+\w*:)(\s*)(\w+)', bygroups(Name.Function, Text, Name.Variable)), (r'^(\b[a-zA-Z]+\w*\b)(\s*)$', bygroups(Name.Function, Text)), (r'^([-+*/\\~<>=|&!?,@%]+)(\s*)(\w+)(\s*)$', bygroups(Name.Function, Text, Name.Variable, Text)), ], 'blockvariables': [ include('whitespaces'), (r'(:)(\s*)(\w+)', bygroups(Operator, Text, Name.Variable)), (r'\|', Operator, '#pop'), default('#pop'), # else pop ], 'literals': [ (r"'(''|[^'])*'", String, 'afterobject'), (r'\$.', String.Char, 'afterobject'), (r'#\(', String.Symbol, 'parenth'), (r'\)', Text, 'afterobject'), (r'(\d+r)?-?\d+(\.\d+)?(e-?\d+)?', Number, 'afterobject'), ], '_parenth_helper': [ include('whitespaces'), (r'(\d+r)?-?\d+(\.\d+)?(e-?\d+)?', Number), (r'[-+*/\\~<>=|&#!?,@%\w:]+', String.Symbol), # literals (r"'(''|[^'])*'", String), (r'\$.', String.Char), (r'#*\(', String.Symbol, 'inner_parenth'), ], 'parenth': [ # This state is a bit tricky since # we can't just pop this state (r'\)', String.Symbol, ('root', 'afterobject')), include('_parenth_helper'), ], 'inner_parenth': [ (r'\)', String.Symbol, '#pop'), include('_parenth_helper'), ], 'whitespaces': [ # skip whitespace and comments (r'\s+', Text), (r'"(""|[^"])*"', Comment), ], 'objects': [ (r'\[', Text, 'blockvariables'), (r'\]', Text, 'afterobject'), (r'\b(self|super|true|false|nil|thisContext)\b', Name.Builtin.Pseudo, 'afterobject'), (r'\b[A-Z]\w*(?!:)\b', Name.Class, 'afterobject'), (r'\b[a-z]\w*(?!:)\b', Name.Variable, 'afterobject'), (r'#("(""|[^"])*"|[-+*/\\~<>=|&!?,@%]+|[\w:]+)', String.Symbol, 'afterobject'), include('literals'), ], 'afterobject': [ (r'! !$', Keyword, '#pop'), # squeak chunk delimiter include('whitespaces'), (r'\b(ifTrue:|ifFalse:|whileTrue:|whileFalse:|timesRepeat:)', Name.Builtin, '#pop'), (r'\b(new\b(?!:))', Name.Builtin), (r'\:=|\_', Operator, '#pop'), (r'\b[a-zA-Z]+\w*:', Name.Function, '#pop'), (r'\b[a-zA-Z]+\w*', Name.Function), (r'\w+:?|[-+*/\\~<>=|&!?,@%]+', Name.Function, '#pop'), (r'\.', Punctuation, '#pop'), (r';', Punctuation), (r'[\])}]', Text), (r'[\[({]', Text, '#pop'), ], 'squeak fileout': [ # Squeak fileout format (optional) (r'^"(""|[^"])*"!', Keyword), (r"^'(''|[^'])*'!", Keyword), (r'^(!)(\w+)( commentStamp: )(.*?)( prior: .*?!\n)(.*?)(!)', bygroups(Keyword, Name.Class, Keyword, String, Keyword, Text, Keyword)), (r"^(!)(\w+(?: class)?)( methodsFor: )('(?:''|[^'])*')(.*?!)", bygroups(Keyword, Name.Class, Keyword, String, Keyword)), (r'^(\w+)( subclass: )(#\w+)' r'(\s+instanceVariableNames: )(.*?)' r'(\s+classVariableNames: )(.*?)' r'(\s+poolDictionaries: )(.*?)' r'(\s+category: )(.*?)(!)', bygroups(Name.Class, Keyword, String.Symbol, Keyword, String, Keyword, String, Keyword, String, Keyword, String, Keyword)), (r'^(\w+(?: class)?)(\s+instanceVariableNames: )(.*?)(!)', bygroups(Name.Class, Keyword, String, Keyword)), (r'(!\n)(\].*)(! !)$', bygroups(Keyword, Text, Keyword)), (r'! !$', Keyword), ], }
class NewspeakLexer(RegexLexer): """ For Newspeak syntax. """ name = 'Newspeak' url = 'http://newspeaklanguage.org/' filenames = ['*.ns2'] aliases = ['newspeak', ] mimetypes = ['text/x-newspeak'] version_added = '1.1'
tokens = { 'root': [ (r'\b(Newsqueak2)\b', Keyword.Declaration), (r"'[^']*'", String), (r'\b(class)(\s+)(\w+)(\s*)', bygroups(Keyword.Declaration, Text, Name.Class, Text)), (r'\b(mixin|self|super|private|public|protected|nil|true|false)\b', Keyword), (r'(\w+\:)(\s*)([a-zA-Z_]\w+)', bygroups(Name.Function, Text, Name.Variable)), (r'(\w+)(\s*)(=)', bygroups(Name.Attribute, Text, Operator)), (r'<\w+>', Comment.Special), include('expressionstat'), include('whitespace') ],
'expressionstat': [ (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'\d+', Number.Integer), (r':\w+', Name.Variable), (r'(\w+)(::)', bygroups(Name.Variable, Operator)), (r'\w+:', Name.Function), (r'\w+', Name.Variable), (r'\(|\)', Punctuation), (r'\[|\]', Punctuation), (r'\{|\}', Punctuation),
(r'(\^|\+|\/|~|\*|<|>|=|@|%|\||&|\?|!|,|-|:)', Operator), (r'\.|;', Punctuation), include('whitespace'), include('literals'), ], 'literals': [ (r'\$.', String), (r"'[^']*'", String), (r"#'[^']*'", String.Symbol), (r"#\w+:?", String.Symbol), (r"#(\+|\/|~|\*|<|>|=|@|%|\||&|\?|!|,|-)+", String.Symbol) ], 'whitespace': [ (r'\s+', Text), (r'"[^"]*"', Comment) ], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677""" pygments.lexers.smithy ~~~~~~~~~~~~~~~~~~~~~~
Lexers for the Smithy IDL.
: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, Keyword, Name, String, \ Number, Whitespace, Punctuation
__all__ = ['SmithyLexer']
class SmithyLexer(RegexLexer): """ For Smithy IDL """ name = 'Smithy' url = 'https://awslabs.github.io/smithy/' filenames = ['*.smithy'] aliases = ['smithy'] version_added = '2.10'
unquoted = r'[A-Za-z0-9_\.#$-]+' identifier = r"[A-Za-z0-9_\.#$-]+"
simple_shapes = ( 'use', 'byte', 'short', 'integer', 'long', 'float', 'document', 'double', 'bigInteger', 'bigDecimal', 'boolean', 'blob', 'string', 'timestamp', )
aggregate_shapes = ( 'apply', 'list', 'map', 'set', 'structure', 'union', 'resource', 'operation', 'service', 'trait' )
tokens = { 'root': [ (r'///.*$', Comment.Multiline), (r'//.*$', Comment), (r'@[0-9a-zA-Z\.#-]*', Name.Decorator), (r'(=)', Name.Decorator), (r'^(\$version)(:)(.+)', bygroups(Keyword.Declaration, Name.Decorator, Name.Class)), (r'^(namespace)(\s+' + identifier + r')\b', bygroups(Keyword.Declaration, Name.Class)), (words(simple_shapes, prefix=r'^', suffix=r'(\s+' + identifier + r')\b'), bygroups(Keyword.Declaration, Name.Class)), (words(aggregate_shapes, prefix=r'^', suffix=r'(\s+' + identifier + r')'), bygroups(Keyword.Declaration, Name.Class)), (r'^(metadata)(\s+)((?:\S+)|(?:\"[^"]+\"))(\s*)(=)', bygroups(Keyword.Declaration, Whitespace, Name.Class, Whitespace, Name.Decorator)), (r"(true|false|null)", Keyword.Constant), (r"(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)", Number), (identifier + ":", Name.Label), (identifier, Name.Variable.Class), (r'\[', Text, "#push"), (r'\]', Text, "#pop"), (r'\(', Text, "#push"), (r'\)', Text, "#pop"), (r'\{', Text, "#push"), (r'\}', Text, "#pop"), (r'"{3}(\\\\|\n|\\")*"{3}', String.Doc), (r'"(\\\\|\n|\\"|[^"])*"', String.Double), (r"'(\\\\|\n|\\'|[^'])*'", String.Single), (r'[:,]+', Punctuation), (r'\s+', Whitespace), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778""" pygments.lexers.smv ~~~~~~~~~~~~~~~~~~~
Lexers for the SMV 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, Keyword, Name, Number, Operator, \ Punctuation, Text
__all__ = ['NuSMVLexer']
class NuSMVLexer(RegexLexer): """ Lexer for the NuSMV language. """
name = 'NuSMV' aliases = ['nusmv'] filenames = ['*.smv'] mimetypes = [] url = 'https://nusmv.fbk.eu' version_added = '2.2'
tokens = { 'root': [ # Comments (r'(?s)\/\-\-.*?\-\-/', Comment), (r'--.*\n', Comment),
# Reserved (words(('MODULE', 'DEFINE', 'MDEFINE', 'CONSTANTS', 'VAR', 'IVAR', 'FROZENVAR', 'INIT', 'TRANS', 'INVAR', 'SPEC', 'CTLSPEC', 'LTLSPEC', 'PSLSPEC', 'COMPUTE', 'NAME', 'INVARSPEC', 'FAIRNESS', 'JUSTICE', 'COMPASSION', 'ISA', 'ASSIGN', 'CONSTRAINT', 'SIMPWFF', 'CTLWFF', 'LTLWFF', 'PSLWFF', 'COMPWFF', 'IN', 'MIN', 'MAX', 'MIRROR', 'PRED', 'PREDICATES'), suffix=r'(?![\w$#-])'), Keyword.Declaration), (r'process(?![\w$#-])', Keyword), (words(('array', 'of', 'boolean', 'integer', 'real', 'word'), suffix=r'(?![\w$#-])'), Keyword.Type), (words(('case', 'esac'), suffix=r'(?![\w$#-])'), Keyword), (words(('word1', 'bool', 'signed', 'unsigned', 'extend', 'resize', 'sizeof', 'uwconst', 'swconst', 'init', 'self', 'count', 'abs', 'max', 'min'), suffix=r'(?![\w$#-])'), Name.Builtin), (words(('EX', 'AX', 'EF', 'AF', 'EG', 'AG', 'E', 'F', 'O', 'G', 'H', 'X', 'Y', 'Z', 'A', 'U', 'S', 'V', 'T', 'BU', 'EBF', 'ABF', 'EBG', 'ABG', 'next', 'mod', 'union', 'in', 'xor', 'xnor'), suffix=r'(?![\w$#-])'), Operator.Word), (words(('TRUE', 'FALSE'), suffix=r'(?![\w$#-])'), Keyword.Constant),
# Names (r'[a-zA-Z_][\w$#-]*', Name.Variable),
# Operators (r':=', Operator), (r'[-&|+*/<>!=]', Operator),
# Literals (r'\-?\d+\b', Number.Integer), (r'0[su][bB]\d*_[01_]+', Number.Bin), (r'0[su][oO]\d*_[0-7_]+', Number.Oct), (r'0[su][dD]\d*_[\d_]+', Number.Decimal), (r'0[su][hH]\d*_[\da-fA-F_]+', Number.Hex),
# Whitespace, punctuation and the rest (r'\s+', Text.Whitespace), (r'[()\[\]{};?:.,]', Punctuation), ], }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182""" pygments.lexers.snobol ~~~~~~~~~~~~~~~~~~~~~~
Lexers for the SNOBOL language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['SnobolLexer']
class SnobolLexer(RegexLexer): """ Lexer for the SNOBOL4 programming language.
Recognizes the common ASCII equivalents of the original SNOBOL4 operators. Does not require spaces around binary operators. """
name = "Snobol" aliases = ["snobol"] filenames = ['*.snobol'] mimetypes = ['text/x-snobol'] url = 'https://www.regressive.org/snobol4' version_added = '1.5'
tokens = { # root state, start of line # comments, continuation lines, and directives start in column 1 # as do labels 'root': [ (r'\*.*\n', Comment), (r'[+.] ', Punctuation, 'statement'), (r'-.*\n', Comment), (r'END\s*\n', Name.Label, 'heredoc'), (r'[A-Za-z$][\w$]*', Name.Label, 'statement'), (r'\s+', Text, 'statement'), ], # statement state, line after continuation or label 'statement': [ (r'\s*\n', Text, '#pop'), (r'\s+', Text), (r'(?<=[^\w.])(LT|LE|EQ|NE|GE|GT|INTEGER|IDENT|DIFFER|LGT|SIZE|' r'REPLACE|TRIM|DUPL|REMDR|DATE|TIME|EVAL|APPLY|OPSYN|LOAD|UNLOAD|' r'LEN|SPAN|BREAK|ANY|NOTANY|TAB|RTAB|REM|POS|RPOS|FAIL|FENCE|' r'ABORT|ARB|ARBNO|BAL|SUCCEED|INPUT|OUTPUT|TERMINAL)(?=[^\w.])', Name.Builtin), (r'[A-Za-z][\w.]*', Name), # ASCII equivalents of original operators # | for the EBCDIC equivalent, ! likewise # \ for EBCDIC negation (r'\*\*|[?$.!%*/#+\-@|&\\=]', Operator), (r'"[^"]*"', String), (r"'[^']*'", String), # Accept SPITBOL syntax for real numbers # as well as Macro SNOBOL4 (r'[0-9]+(?=[^.EeDd])', Number.Integer), (r'[0-9]+(\.[0-9]*)?([EDed][-+]?[0-9]+)?', Number.Float), # Goto (r':', Punctuation, 'goto'), (r'[()<>,;]', Punctuation), ], # Goto block 'goto': [ (r'\s*\n', Text, "#pop:2"), (r'\s+', Text), (r'F|S', Keyword), (r'(\()([A-Za-z][\w.]*)(\))', bygroups(Punctuation, Name.Label, Punctuation)) ], # everything after the END statement is basically one # big heredoc. 'heredoc': [ (r'.*\n', String.Heredoc) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687""" pygments.lexers.solidity ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Solidity.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['SolidityLexer']
class SolidityLexer(RegexLexer): """ For Solidity source code. """
name = 'Solidity' aliases = ['solidity'] filenames = ['*.sol'] mimetypes = [] url = 'https://soliditylang.org' version_added = '2.5'
datatype = ( r'\b(address|bool|(?:(?:bytes|hash|int|string|uint)(?:8|16|24|32|40|48|56|64' r'|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208' r'|216|224|232|240|248|256)?))\b' )
tokens = { 'root': [ include('whitespace'), include('comments'), (r'\bpragma\s+solidity\b', Keyword, 'pragma'), (r'\b(contract)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword, Whitespace, Name.Entity)), (datatype + r'(\s+)((?:external|public|internal|private)\s+)?' + r'([a-zA-Z_]\w*)', bygroups(Keyword.Type, Whitespace, Keyword, Name.Variable)), (r'\b(enum|event|function|struct)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Type, Whitespace, Name.Variable)), (r'\b(msg|block|tx)\.([A-Za-z_][a-zA-Z0-9_]*)\b', Keyword), (words(( 'block', 'break', 'constant', 'constructor', 'continue', 'contract', 'do', 'else', 'external', 'false', 'for', 'function', 'if', 'import', 'inherited', 'internal', 'is', 'library', 'mapping', 'memory', 'modifier', 'msg', 'new', 'payable', 'private', 'public', 'require', 'return', 'returns', 'struct', 'suicide', 'throw', 'this', 'true', 'tx', 'var', 'while'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(('keccak256',), prefix=r'\b', suffix=r'\b'), Name.Builtin), (datatype, Keyword.Type), include('constants'), (r'[a-zA-Z_]\w*', Text), (r'[~!%^&*+=|?:<>/-]', Operator), (r'[.;{}(),\[\]]', Punctuation) ], 'comments': [ (r'//(\n|[\w\W]*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*][\w\W]*?[*](\\\n)?/', Comment.Multiline), (r'/(\\\n)?[*][\w\W]*', Comment.Multiline) ], 'constants': [ (r'("(\\"|.)*?")', String.Double), (r"('(\\'|.)*?')", String.Single), (r'\b0[xX][0-9a-fA-F]+\b', Number.Hex), (r'\b\d+\b', Number.Decimal), ], 'pragma': [ include('whitespace'), include('comments'), (r'(\^|>=|<)(\s*)(\d+\.\d+\.\d+)', bygroups(Operator, Whitespace, Keyword)), (r';', Punctuation, '#pop') ], 'whitespace': [ (r'\s+', Whitespace), (r'\n', Whitespace) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778""" pygments.lexers.soong ~~~~~~~~~~~~~~~~~~~~~
Lexers for Soong (Android.bp Blueprint) files.
: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 Comment, Name, Number, Operator, Punctuation, \ String, Whitespace
__all__ = ['SoongLexer']
class SoongLexer(RegexLexer): name = 'Soong' version_added = '2.18' url = 'https://source.android.com/docs/setup/reference/androidbp' aliases = ['androidbp', 'bp', 'soong'] filenames = ['Android.bp']
tokens = { 'root': [ # A variable assignment (r'(\w*)(\s*)(\+?=)(\s*)', bygroups(Name.Variable, Whitespace, Operator, Whitespace), 'assign-rhs'),
# A top-level module (r'(\w*)(\s*)(\{)', bygroups(Name.Function, Whitespace, Punctuation), 'in-rule'),
# Everything else include('comments'), (r'\s+', Whitespace), # newlines okay ], 'assign-rhs': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'in-list': [ include('expr'), include('comments'), (r'\s+', Whitespace), # newlines okay in a list (r',', Punctuation), (r'\]', Punctuation, '#pop'), ], 'in-map': [ # A map key (r'(\w+)(:)(\s*)', bygroups(Name, Punctuation, Whitespace)),
include('expr'), include('comments'), (r'\s+', Whitespace), # newlines okay in a map (r',', Punctuation), (r'\}', Punctuation, '#pop'), ], 'in-rule': [ # Just re-use map syntax include('in-map'), ], 'comments': [ (r'//.*', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), ], 'expr': [ (r'(true|false)\b', Name.Builtin), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (r'".*?"', String), (r'\{', Punctuation, 'in-map'), (r'\[', Punctuation, 'in-list'), (r'\w+', Name), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102""" pygments.lexers.sophia ~~~~~~~~~~~~~~~~~~~~~~
Lexer for Sophia.
Derived from pygments/lexers/reason.py.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, default, wordsfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text
__all__ = ['SophiaLexer']
class SophiaLexer(RegexLexer): """ A Sophia lexer. """
name = 'Sophia' aliases = ['sophia'] filenames = ['*.aes'] mimetypes = [] url = 'https://docs.aeternity.com/aesophia' version_added = '2.11'
keywords = ( 'contract', 'include', 'let', 'switch', 'type', 'record', 'datatype', 'if', 'elif', 'else', 'function', 'stateful', 'payable', 'public', 'entrypoint', 'private', 'indexed', 'namespace', 'interface', 'main', 'using', 'as', 'for', 'hiding', )
builtins = ('state', 'put', 'abort', 'require')
word_operators = ('mod', 'band', 'bor', 'bxor', 'bnot')
primitive_types = ('int', 'address', 'bool', 'bits', 'bytes', 'string', 'list', 'option', 'char', 'unit', 'map', 'event', 'hash', 'signature', 'oracle', 'oracle_query')
tokens = { 'escape-sequence': [ (r'\\[\\"\'ntbr]', String.Escape), (r'\\[0-9]{3}', String.Escape), (r'\\x[0-9a-fA-F]{2}', String.Escape), ], 'root': [ (r'\s+', Text.Whitespace), (r'(true|false)\b', Keyword.Constant), (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Class, 'dotted'), (r'\b([A-Z][\w\']*)', Name.Function), (r'//.*?\n', Comment.Single), (r'\/\*(?!/)', Comment.Multiline, 'comment'),
(r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex), (r'#[\da-fA-F][\da-fA-F_]*', Name.Label), (r'\d[\d_]*', Number.Integer),
(words(keywords, suffix=r'\b'), Keyword), (words(builtins, suffix=r'\b'), Name.Builtin), (words(word_operators, prefix=r'\b', suffix=r'\b'), Operator.Word), (words(primitive_types, prefix=r'\b', suffix=r'\b'), Keyword.Type),
(r'[=!<>+\\*/:&|?~@^-]', Operator.Word), (r'[.;:{}(),\[\]]', Punctuation),
(r"(ak_|ok_|oq_|ct_)[\w']*", Name.Label), (r"[^\W\d][\w']*", Name),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'", String.Char), (r"'.'", String.Char), (r"'[a-z][\w]*", Name.Variable),
(r'"', String.Double, 'string') ], 'comment': [ (r'[^/*]+', Comment.Multiline), (r'\/\*', Comment.Multiline, '#push'), (r'\*\/', Comment.Multiline, '#pop'), (r'\*', Comment.Multiline), ], 'string': [ (r'[^\\"]+', String.Double), include('escape-sequence'), (r'\\\n', String.Double), (r'"', String.Double, '#pop'), ], 'dotted': [ (r'\s+', Text), (r'\.', Punctuation), (r'[A-Z][\w\']*(?=\s*\.)', Name.Function), (r'[A-Z][\w\']*', Name.Function, '#pop'), (r'[a-z_][\w\']*', Name, '#pop'), default('#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122""" pygments.lexers.special ~~~~~~~~~~~~~~~~~~~~~~~
Special lexers.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import ast
from pygments.lexer import Lexer, line_refrom pygments.token import Token, Error, Text, Genericfrom pygments.util import get_choice_opt
__all__ = ['TextLexer', 'OutputLexer', 'RawTokenLexer']
class TextLexer(Lexer): """ "Null" lexer, doesn't highlight anything. """ name = 'Text only' aliases = ['text'] filenames = ['*.txt'] mimetypes = ['text/plain'] url = "" version_added = ''
priority = 0.01
def get_tokens_unprocessed(self, text): yield 0, Text, text
def analyse_text(text): return TextLexer.priority
class OutputLexer(Lexer): """ Simple lexer that highlights everything as ``Token.Generic.Output``. """ name = 'Text output' aliases = ['output'] url = "" version_added = '2.10' _example = "output/output"
def get_tokens_unprocessed(self, text): yield 0, Generic.Output, text
_ttype_cache = {}
class RawTokenLexer(Lexer): """ Recreate a token stream formatted with the `RawTokenFormatter`.
Additional options accepted:
`compress` If set to ``"gz"`` or ``"bz2"``, decompress the token stream with the given compression algorithm before lexing (default: ``""``). """ name = 'Raw token data' aliases = [] filenames = [] mimetypes = ['application/x-pygments-tokens'] url = 'https://pygments.org/docs/formatters/#RawTokenFormatter' version_added = ''
def __init__(self, **options): self.compress = get_choice_opt(options, 'compress', ['', 'none', 'gz', 'bz2'], '') Lexer.__init__(self, **options)
def get_tokens(self, text): if self.compress: if isinstance(text, str): text = text.encode('latin1') try: if self.compress == 'gz': import gzip text = gzip.decompress(text) elif self.compress == 'bz2': import bz2 text = bz2.decompress(text) except OSError: yield Error, text.decode('latin1') if isinstance(text, bytes): text = text.decode('latin1')
# do not call Lexer.get_tokens() because stripping is not optional. text = text.strip('\n') + '\n' for i, t, v in self.get_tokens_unprocessed(text): yield t, v
def get_tokens_unprocessed(self, text): length = 0 for match in line_re.finditer(text): try: ttypestr, val = match.group().rstrip().split('\t', 1) ttype = _ttype_cache.get(ttypestr) if not ttype: ttype = Token ttypes = ttypestr.split('.')[1:] for ttype_ in ttypes: if not ttype_ or not ttype_[0].isupper(): raise ValueError('malformed token name') ttype = getattr(ttype, ttype_) _ttype_cache[ttypestr] = ttype val = ast.literal_eval(val) if not isinstance(val, str): raise ValueError('expected str') except (SyntaxError, ValueError): val = match.group() ttype = Error yield length, ttype, val length += len(val)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970""" pygments.lexers.spice ~~~~~~~~~~~~~~~~~~~~~
Lexers for the Spice programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['SpiceLexer']
class SpiceLexer(RegexLexer): """ For Spice source. """ name = 'Spice' url = 'https://www.spicelang.com' filenames = ['*.spice'] aliases = ['spice', 'spicelang'] mimetypes = ['text/x-spice'] version_added = '2.11'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'\\\n', Text), # comments (r'//(.*?)\n', Comment.Single), (r'/(\\\n)?[*]{2}(.|\n)*?[*](\\\n)?/', String.Doc), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), # keywords (r'(import|as)\b', Keyword.Namespace), (r'(f|p|type|struct|interface|enum|alias|operator)\b', Keyword.Declaration), (words(('if', 'else', 'switch', 'case', 'default', 'for', 'foreach', 'do', 'while', 'break', 'continue', 'fallthrough', 'return', 'assert', 'unsafe', 'ext', 'cast'), suffix=r'\b'), Keyword), (words(('const', 'signed', 'unsigned', 'inline', 'public', 'heap', 'compose'), suffix=r'\b'), Keyword.Pseudo), (words(('new', 'yield', 'stash', 'pick', 'sync', 'class'), suffix=r'\b'), Keyword.Reserved), (r'(true|false|nil)\b', Keyword.Constant), (words(('double', 'int', 'short', 'long', 'byte', 'char', 'string', 'bool', 'dyn'), suffix=r'\b'), Keyword.Type), (words(('printf', 'sizeof', 'alignof', 'len', 'panic'), suffix=r'\b(\()'), bygroups(Name.Builtin, Punctuation)), # numeric literals (r'[-]?[0-9]*[.][0-9]+([eE][+-]?[0-9]+)?', Number.Double), (r'0[bB][01]+[slu]?', Number.Bin), (r'0[oO][0-7]+[slu]?', Number.Oct), (r'0[xXhH][0-9a-fA-F]+[slu]?', Number.Hex), (r'(0[dD])?[0-9]+[slu]?', Number.Integer), # string literal (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # char literal (r'\'(\\\\|\\[^\\]|[^\'\\])\'', String.Char), # tokens (r'<<=|>>=|<<|>>|<=|>=|\+=|-=|\*=|/=|\%=|\|=|&=|\^=|&&|\|\||&|\||' r'\+\+|--|\%|\^|\~|==|!=|->|::|[.]{3}|#!|#|[+\-*/&]', Operator), (r'[|<>=!()\[\]{}.,;:\?]', Punctuation), # identifiers (r'[^\W\d]\w*', Name.Other), ] }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111""" pygments.lexers.sql ~~~~~~~~~~~~~~~~~~~
Lexers for various SQL dialects and related interactive sessions.
Postgres specific lexers:
`PostgresLexer` A SQL lexer for the PostgreSQL dialect. Differences w.r.t. the SQL lexer are:
- keywords and data types list parsed from the PG docs (run the `_postgres_builtins` module to update them); - Content of $-strings parsed using a specific lexer, e.g. the content of a PL/Python function is parsed using the Python lexer; - parse PG specific constructs: E-strings, $-strings, U&-strings, different operators and punctuation.
`PlPgsqlLexer` A lexer for the PL/pgSQL language. Adds a few specific construct on top of the PG SQL lexer (such as <<label>>).
`PostgresConsoleLexer` A lexer to highlight an interactive psql session:
- identifies the prompt and does its best to detect the end of command in multiline statement where not all the lines are prefixed by a prompt, telling them apart from the output; - highlights errors in the output and notification levels; - handles psql backslash commands.
`PostgresExplainLexer` A lexer to highlight Postgres execution plan.
The ``tests/examplefiles`` contains a few test files with data to be parsed by these lexers.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import collectionsimport re
from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, wordsfrom pygments.lexers import _googlesql_builtinsfrom pygments.lexers import _mysql_builtinsfrom pygments.lexers import _postgres_builtinsfrom pygments.lexers import _sql_builtinsfrom pygments.lexers import _tsql_builtinsfrom pygments.lexers import get_lexer_by_name, ClassNotFoundfrom pygments.token import Punctuation, Whitespace, Text, Comment, Operator, \ Keyword, Name, String, Number, Generic, Literal
__all__ = ['GoogleSqlLexer', 'PostgresLexer', 'PlPgsqlLexer', 'PostgresConsoleLexer', 'PostgresExplainLexer', 'SqlLexer', 'TransactSqlLexer', 'MySqlLexer', 'SqliteConsoleLexer', 'RqlLexer']
line_re = re.compile('.*?\n')sqlite_prompt_re = re.compile(r'^(?:sqlite| ...)>(?= )')
language_re = re.compile(r"\s+LANGUAGE\s+'?(\w+)'?", re.IGNORECASE)
do_re = re.compile(r'\bDO\b', re.IGNORECASE)
# Regular expressions for analyse_text()name_between_bracket_re = re.compile(r'\[[a-zA-Z_]\w*\]')name_between_backtick_re = re.compile(r'`[a-zA-Z_]\w*`')tsql_go_re = re.compile(r'\bgo\b', re.IGNORECASE)tsql_declare_re = re.compile(r'\bdeclare\s+@', re.IGNORECASE)tsql_variable_re = re.compile(r'@[a-zA-Z_]\w*\b')
# Identifiers for analyse_text()googlesql_identifiers = ( _googlesql_builtins.functionnames + _googlesql_builtins.keywords + _googlesql_builtins.types)
def language_callback(lexer, match): """Parse the content of a $-string using a lexer
The lexer is chosen looking for a nearby LANGUAGE or assumed as plpgsql if inside a DO statement and no LANGUAGE has been found. """ lx = None m = language_re.match(lexer.text[match.end():match.end()+100]) if m is not None: lx = lexer._get_lexer(m.group(1)) else: m = list(language_re.finditer( lexer.text[max(0, match.start()-100):match.start()])) if m: lx = lexer._get_lexer(m[-1].group(1)) else: m = list(do_re.finditer( lexer.text[max(0, match.start()-25):match.start()])) if m: lx = lexer._get_lexer('plpgsql')
# 1 = $, 2 = delimiter, 3 = $ yield (match.start(1), String, match.group(1)) yield (match.start(2), String.Delimiter, match.group(2)) yield (match.start(3), String, match.group(3)) # 4 = string contents if lx: yield from lx.get_tokens_unprocessed(match.group(4)) else: yield (match.start(4), String, match.group(4)) # 5 = $, 6 = delimiter, 7 = $ yield (match.start(5), String, match.group(5)) yield (match.start(6), String.Delimiter, match.group(6)) yield (match.start(7), String, match.group(7))
class PostgresBase: """Base class for Postgres-related lexers.
This is implemented as a mixin to avoid the Lexer metaclass kicking in. this way the different lexer don't have a common Lexer ancestor. If they had, _tokens could be created on this ancestor and not updated for the other classes, resulting e.g. in PL/pgSQL parsed as SQL. This shortcoming seem to suggest that regexp lexers are not really subclassable. """ def get_tokens_unprocessed(self, text, *args): # Have a copy of the entire text to be used by `language_callback`. self.text = text yield from super().get_tokens_unprocessed(text, *args)
def _get_lexer(self, lang): if lang.lower() == 'sql': return get_lexer_by_name('postgresql', **self.options)
tries = [lang] if lang.startswith('pl'): tries.append(lang[2:]) if lang.endswith('u'): tries.append(lang[:-1]) if lang.startswith('pl') and lang.endswith('u'): tries.append(lang[2:-1])
for lx in tries: try: return get_lexer_by_name(lx, **self.options) except ClassNotFound: pass else: # TODO: better logging # print >>sys.stderr, "language not found:", lang return None
class PostgresLexer(PostgresBase, RegexLexer): """ Lexer for the PostgreSQL dialect of SQL. """
name = 'PostgreSQL SQL dialect' aliases = ['postgresql', 'postgres'] mimetypes = ['text/x-postgresql'] url = 'https://www.postgresql.org' version_added = '1.5'
flags = re.IGNORECASE tokens = { 'root': [ (r'\s+', Whitespace), (r'--.*\n?', Comment.Single), (r'/\*', Comment.Multiline, 'multiline-comments'), (r'(' + '|'.join(s.replace(" ", r"\s+") for s in _postgres_builtins.DATATYPES + _postgres_builtins.PSEUDO_TYPES) + r')\b', Name.Builtin), (words(_postgres_builtins.KEYWORDS, suffix=r'\b'), Keyword), (r'[+*/<>=~!@#%^&|`?-]+', Operator), (r'::', Operator), # cast (r'\$\d+', Name.Variable), (r'([0-9]*\.[0-9]*|[0-9]+)(e[+-]?[0-9]+)?', Number.Float), (r'[0-9]+', Number.Integer), (r"((?:E|U&)?)(')", bygroups(String.Affix, String.Single), 'string'), # quoted identifier (r'((?:U&)?)(")', bygroups(String.Affix, String.Name), 'quoted-ident'), (r'(?s)(\$)([^$]*)(\$)(.*?)(\$)(\2)(\$)', language_callback), (r'[a-z_]\w*', Name),
# psql variable in SQL (r""":(['"]?)[a-z]\w*\b\1""", Name.Variable),
(r'[;:()\[\]{},.]', Punctuation), ], 'multiline-comments': [ (r'/\*', Comment.Multiline, 'multiline-comments'), (r'\*/', Comment.Multiline, '#pop'), (r'[^/*]+', Comment.Multiline), (r'[/*]', Comment.Multiline) ], 'string': [ (r"[^']+", String.Single), (r"''", String.Single), (r"'", String.Single, '#pop'), ], 'quoted-ident': [ (r'[^"]+', String.Name), (r'""', String.Name), (r'"', String.Name, '#pop'), ], }
class PlPgsqlLexer(PostgresBase, RegexLexer): """ Handle the extra syntax in Pl/pgSQL language. """ name = 'PL/pgSQL' aliases = ['plpgsql'] mimetypes = ['text/x-plpgsql'] url = 'https://www.postgresql.org/docs/current/plpgsql.html' version_added = '1.5'
flags = re.IGNORECASE # FIXME: use inheritance tokens = {name: state[:] for (name, state) in PostgresLexer.tokens.items()}
# extend the keywords list for i, pattern in enumerate(tokens['root']): if pattern[1] == Keyword: tokens['root'][i] = ( words(_postgres_builtins.KEYWORDS + _postgres_builtins.PLPGSQL_KEYWORDS, suffix=r'\b'), Keyword) del i break else: assert 0, "SQL keywords not found"
# Add specific PL/pgSQL rules (before the SQL ones) tokens['root'][:0] = [ (r'\%[a-z]\w*\b', Name.Builtin), # actually, a datatype (r':=', Operator), (r'\<\<[a-z]\w*\>\>', Name.Label), (r'\#[a-z]\w*\b', Keyword.Pseudo), # #variable_conflict ]
class PsqlRegexLexer(PostgresBase, RegexLexer): """ Extend the PostgresLexer adding support specific for psql commands.
This is not a complete psql lexer yet as it lacks prompt support and output rendering. """
name = 'PostgreSQL console - regexp based lexer' aliases = [] # not public
flags = re.IGNORECASE tokens = {name: state[:] for (name, state) in PostgresLexer.tokens.items()}
tokens['root'].append( (r'\\[^\s]+', Keyword.Pseudo, 'psql-command')) tokens['psql-command'] = [ (r'\n', Text, 'root'), (r'\s+', Whitespace), (r'\\[^\s]+', Keyword.Pseudo), (r""":(['"]?)[a-z]\w*\b\1""", Name.Variable), (r"'(''|[^'])*'", String.Single), (r"`([^`])*`", String.Backtick), (r"[^\s]+", String.Symbol), ]
re_prompt = re.compile(r'^(\S.*?)??[=\-\(\$\'\"][#>]')re_psql_command = re.compile(r'\s*\\')re_end_command = re.compile(r';\s*(--.*?)?$')re_psql_command = re.compile(r'(\s*)(\\.+?)(\s+)$')re_error = re.compile(r'(ERROR|FATAL):')re_message = re.compile( r'((?:DEBUG|INFO|NOTICE|WARNING|ERROR|' r'FATAL|HINT|DETAIL|CONTEXT|LINE [0-9]+):)(.*?\n)')
class lookahead: """Wrap an iterator and allow pushing back an item.""" def __init__(self, x): self.iter = iter(x) self._nextitem = None
def __iter__(self): return self
def send(self, i): self._nextitem = i return i
def __next__(self): if self._nextitem is not None: ni = self._nextitem self._nextitem = None return ni return next(self.iter) next = __next__
class PostgresConsoleLexer(Lexer): """ Lexer for psql sessions. """
name = 'PostgreSQL console (psql)' aliases = ['psql', 'postgresql-console', 'postgres-console'] mimetypes = ['text/x-postgresql-psql'] url = 'https://www.postgresql.org' version_added = '1.5' _example = "psql/psql_session.txt"
def get_tokens_unprocessed(self, data): sql = PsqlRegexLexer(**self.options)
lines = lookahead(line_re.findall(data))
# prompt-output cycle while 1:
# consume the lines of the command: start with an optional prompt # and continue until the end of command is detected curcode = '' insertions = [] for line in lines: # Identify a shell prompt in case of psql commandline example if line.startswith('$') and not curcode: lexer = get_lexer_by_name('console', **self.options) yield from lexer.get_tokens_unprocessed(line) break
# Identify a psql prompt mprompt = re_prompt.match(line) if mprompt is not None: insertions.append((len(curcode), [(0, Generic.Prompt, mprompt.group())])) curcode += line[len(mprompt.group()):] else: curcode += line
# Check if this is the end of the command # TODO: better handle multiline comments at the end with # a lexer with an external state? if re_psql_command.match(curcode) \ or re_end_command.search(curcode): break
# Emit the combined stream of command and prompt(s) yield from do_insertions(insertions, sql.get_tokens_unprocessed(curcode))
# Emit the output lines out_token = Generic.Output for line in lines: mprompt = re_prompt.match(line) if mprompt is not None: # push the line back to have it processed by the prompt lines.send(line) break
mmsg = re_message.match(line) if mmsg is not None: if mmsg.group(1).startswith("ERROR") \ or mmsg.group(1).startswith("FATAL"): out_token = Generic.Error yield (mmsg.start(1), Generic.Strong, mmsg.group(1)) yield (mmsg.start(2), out_token, mmsg.group(2)) else: yield (0, out_token, line) else: return
class PostgresExplainLexer(RegexLexer): """ Handle PostgreSQL EXPLAIN output """
name = 'PostgreSQL EXPLAIN dialect' aliases = ['postgres-explain'] filenames = ['*.explain'] mimetypes = ['text/x-postgresql-explain'] url = 'https://www.postgresql.org/docs/current/using-explain.html' version_added = '2.15'
tokens = { 'root': [ (r'(:|\(|\)|ms|kB|->|\.\.|\,|\/|=|%)', Punctuation), (r'(\s+)', Whitespace),
# This match estimated cost and effectively measured counters with ANALYZE # Then, we move to instrumentation state (r'(cost)(=?)', bygroups(Name.Class, Punctuation), 'instrumentation'), (r'(actual)( )(=?)', bygroups(Name.Class, Whitespace, Punctuation), 'instrumentation'),
# Misc keywords (words(('actual', 'Memory Usage', 'Disk Usage', 'Memory', 'Buckets', 'Batches', 'originally', 'row', 'rows', 'Hits', 'Misses', 'Evictions', 'Overflows', 'Planned Partitions', 'Estimates', 'capacity', 'distinct keys', 'lookups', 'hit percent', 'Index Searches', 'Storage', 'Disk Maximum Storage'), suffix=r'\b'), Comment.Single),
(r'(hit|read|dirtied|written|write|time|calls)(=)', bygroups(Comment.Single, Operator)), (r'(shared|temp|local)', Keyword.Pseudo),
# We move to sort state in order to emphasize specific keywords (especially disk access) (r'(Sort Method)(: )', bygroups(Comment.Preproc, Punctuation), 'sort'),
# These keywords can be followed by an object, like a table (r'(Sort Key|Group Key|Presorted Key|Hash Key)(:)( )', bygroups(Comment.Preproc, Punctuation, Whitespace), 'object_name'), (r'(Cache Key|Cache Mode)(:)( )', bygroups(Comment, Punctuation, Whitespace), 'object_name'),
# These keywords can be followed by a predicate (words(('Join Filter', 'Subplans Removed', 'Filter', 'Merge Cond', 'Hash Cond', 'Index Cond', 'Recheck Cond', 'Heap Blocks', 'TID Cond', 'Run Condition', 'Order By', 'Function Call', 'Table Function Call', 'Inner Unique', 'Params Evaluated', 'Single Copy', 'Sampling', 'One-Time Filter', 'Output', 'Relations', 'Remote SQL', 'Disabled'), suffix=r'\b'), Comment.Preproc, 'predicate'),
# Special keyword to handle ON CONFLICT (r'Conflict ', Comment.Preproc, 'conflict'),
# Special keyword for InitPlan or SubPlan (r'(InitPlan|SubPlan)( )(\d+)( )', bygroups(Keyword, Whitespace, Number.Integer, Whitespace), 'init_plan'),
(words(('Sort Method', 'Join Filter', 'Planning time', 'Planning Time', 'Execution time', 'Execution Time', 'Workers Planned', 'Workers Launched', 'Buffers', 'Planning', 'Worker', 'Query Identifier', 'Time', 'Full-sort Groups', 'Pre-sorted Groups'), suffix=r'\b'), Comment.Preproc),
# Emphasize these keywords
(words(('Rows Removed by Join Filter', 'Rows Removed by Filter', 'Rows Removed by Index Recheck', 'Heap Fetches', 'never executed'), suffix=r'\b'), Name.Exception), (r'(I/O Timings)(:)( )', bygroups(Name.Exception, Punctuation, Whitespace)),
(words(_postgres_builtins.EXPLAIN_KEYWORDS, suffix=r'\b'), Keyword),
# join keywords (r'((Right|Left|Full|Semi|Anti) Join)', Keyword.Type), (r'(Parallel |Async |Finalize |Partial )', Comment.Preproc), (r'Backward', Comment.Preproc), (r'(Intersect|Except|Hash)', Comment.Preproc),
(r'(CTE)( )(\w*)?', bygroups(Comment, Whitespace, Name.Variable)),
# Treat "on" and "using" as a punctuation (r'(on|using)', Punctuation, 'object_name'),
# strings (r"'(''|[^'])*'", String.Single), # numbers (r'-?\d+\.\d+', Number.Float), (r'(-?\d+)', Number.Integer),
# boolean (r'(true|false)', Name.Constant), # explain header (r'\s*QUERY PLAN\s*\n\s*-+', Comment.Single), # Settings (r'(Settings)(:)( )', bygroups(Comment.Preproc, Punctuation, Whitespace), 'setting'),
# Handle JIT counters (r'(JIT|Functions|Options|Timing)(:)', bygroups(Comment.Preproc, Punctuation)), (r'(Inlining|Optimization|Expressions|Deforming|Generation|Emission|Total)', Keyword.Pseudo),
# Handle Triggers counters (r'(Trigger)( )(\S*)(:)( )', bygroups(Comment.Preproc, Whitespace, Name.Variable, Punctuation, Whitespace)),
], 'expression': [ # matches any kind of parenthesized expression # the first opening paren is matched by the 'caller' (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), (r'(never executed)', Name.Exception), (r'[^)(]+', Comment), ], 'object_name': [
# This is a cost or analyze measure (r'(\(cost)(=?)', bygroups(Name.Class, Punctuation), 'instrumentation'), (r'(\(actual)( )(=?)', bygroups(Name.Class, Whitespace, Punctuation), 'instrumentation'),
# if object_name is parenthesized, mark opening paren as # punctuation, call 'expression', and exit state (r'\(', Punctuation, 'expression'), (r'(on)', Punctuation), # matches possibly schema-qualified table and column names (r'\w+(\.\w+)*( USING \S+| \w+ USING \S+)', Name.Variable), (r'\"?\w+\"?(?:\.\"?\w+\"?)?', Name.Variable), (r'\'\S*\'', Name.Variable),
# if we encounter a comma, another object is listed (r',\n', Punctuation, 'object_name'), (r',', Punctuation, 'object_name'),
# special case: "*SELECT*" (r'"\*SELECT\*( \d+)?"(.\w+)?', Name.Variable), (r'"\*VALUES\*(_\d+)?"(.\w+)?', Name.Variable), (r'"ANY_subquery"', Name.Variable),
# Variable $1 ... (r'\$\d+', Name.Variable), # cast (r'::\w+', Name.Variable), (r' +', Whitespace), (r'"', Punctuation), (r'\[\.\.\.\]', Punctuation), (r'\)', Punctuation, '#pop'), ], 'predicate': [ # if predicate is parenthesized, mark paren as punctuation (r'(\()([^\n]*)(\))', bygroups(Punctuation, Name.Variable, Punctuation), '#pop'), # otherwise color until newline (r'[^\n]*', Name.Variable, '#pop'), ], 'instrumentation': [ (r'=|\.\.', Punctuation), (r' +', Whitespace), (r'(rows|width|time|loops)', Name.Class), (r'\d+\.\d+', Number.Float), (r'(\d+)', Number.Integer), (r'\)', Punctuation, '#pop'), ], 'conflict': [ (r'(Resolution: )(\w+)', bygroups(Comment.Preproc, Name.Variable)), (r'(Arbiter \w+:)', Comment.Preproc, 'object_name'), (r'(Filter: )', Comment.Preproc, 'predicate'), ], 'setting': [ (r'([a-z_]*?)(\s*)(=)(\s*)(\'.*?\')', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), (r'\, ', Punctuation), ], 'init_plan': [ (r'\(', Punctuation), (r'returns \$\d+(,\$\d+)?', Name.Variable), (r'\)', Punctuation, '#pop'), ], 'sort': [ (r':|kB', Punctuation), (r'(quicksort|top-N|heapsort|Average|Memory|Peak)', Comment.Prepoc), (r'(external|merge|Disk|sort)', Name.Exception), (r'(\d+)', Number.Integer), (r' +', Whitespace), ], }
class SqlLexer(RegexLexer): """ Lexer for Structured Query Language. Currently, this lexer does not recognize any special syntax except ANSI SQL. """
name = 'SQL' aliases = ['sql'] filenames = ['*.sql'] mimetypes = ['text/x-sql'] url = 'https://en.wikipedia.org/wiki/SQL' version_added = ''
flags = re.IGNORECASE tokens = { 'root': [ (r'\s+', Whitespace), (r'--.*\n?', Comment.Single), (r'/\*', Comment.Multiline, 'multiline-comments'), (words(_sql_builtins.KEYWORDS, suffix=r'\b'), Keyword), (words(_sql_builtins.DATATYPES, suffix=r'\b'), Name.Builtin), (r'[+*/<>=~!@#%^&|`?-]', Operator), (r'[0-9]+', Number.Integer), # TODO: Backslash escapes? (r"'(''|[^'])*'", String.Single), (r'"(""|[^"])*"', String.Symbol), # not a real string literal in ANSI SQL (r'[a-z_][\w$]*', Name), # allow $s in strings for Oracle (r'[;:()\[\],.]', Punctuation) ], 'multiline-comments': [ (r'/\*', Comment.Multiline, 'multiline-comments'), (r'\*/', Comment.Multiline, '#pop'), (r'[^/*]+', Comment.Multiline), (r'[/*]', Comment.Multiline) ] }
def analyse_text(self, text): return
class TransactSqlLexer(RegexLexer): """ Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to SQL.
The list of keywords includes ODBC and keywords reserved for future use. """
name = 'Transact-SQL' aliases = ['tsql', 't-sql'] filenames = ['*.sql'] mimetypes = ['text/x-tsql'] url = 'https://www.tsql.info' version_added = ''
flags = re.IGNORECASE
tokens = { 'root': [ (r'\s+', Whitespace), (r'--.*[$|\n]?', Comment.Single), (r'/\*', Comment.Multiline, 'multiline-comments'), (words(_tsql_builtins.OPERATORS), Operator), (words(_tsql_builtins.OPERATOR_WORDS, suffix=r'\b'), Operator.Word), (words(_tsql_builtins.TYPES, suffix=r'\b'), Name.Class), (words(_tsql_builtins.FUNCTIONS, suffix=r'\b'), Name.Function), (r'(goto)(\s+)(\w+\b)', bygroups(Keyword, Whitespace, Name.Label)), (words(_tsql_builtins.KEYWORDS, suffix=r'\b'), Keyword), (r'(\[)([^]]+)(\])', bygroups(Operator, Name, Operator)), (r'0x[0-9a-f]+', Number.Hex), # Float variant 1, for example: 1., 1.e2, 1.2e3 (r'[0-9]+\.[0-9]*(e[+-]?[0-9]+)?', Number.Float), # Float variant 2, for example: .1, .1e2 (r'\.[0-9]+(e[+-]?[0-9]+)?', Number.Float), # Float variant 3, for example: 123e45 (r'[0-9]+e[+-]?[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), (r"'(''|[^'])*'", String.Single), (r'"(""|[^"])*"', String.Symbol), (r'[;(),.]', Punctuation), # Below we use \w even for the first "real" character because # tokens starting with a digit have already been recognized # as Number above. (r'@@\w+', Name.Builtin), (r'@\w+', Name.Variable), (r'(\w+)(:)', bygroups(Name.Label, Punctuation)), (r'#?#?\w+', Name), # names for temp tables and anything else (r'\?', Name.Variable.Magic), # parameter for prepared statements ], 'multiline-comments': [ (r'/\*', Comment.Multiline, 'multiline-comments'), (r'\*/', Comment.Multiline, '#pop'), (r'[^/*]+', Comment.Multiline), (r'[/*]', Comment.Multiline) ] }
def analyse_text(text): rating = 0 if tsql_declare_re.search(text): # Found T-SQL variable declaration. rating = 1.0 else: name_between_backtick_count = len( name_between_backtick_re.findall(text)) name_between_bracket_count = len( name_between_bracket_re.findall(text)) # We need to check if there are any names using # backticks or brackets, as otherwise both are 0 # and 0 >= 2 * 0, so we would always assume it's true dialect_name_count = name_between_backtick_count + name_between_bracket_count if dialect_name_count >= 1 and \ name_between_bracket_count >= 2 * name_between_backtick_count: # Found at least twice as many [name] as `name`. rating += 0.5 elif name_between_bracket_count > name_between_backtick_count: rating += 0.2 elif name_between_bracket_count > 0: rating += 0.1 if tsql_variable_re.search(text) is not None: rating += 0.1 if tsql_go_re.search(text) is not None: rating += 0.1 return rating
class MySqlLexer(RegexLexer): """The Oracle MySQL lexer.
This lexer does not attempt to maintain strict compatibility with MariaDB syntax or keywords. Although MySQL and MariaDB's common code history suggests there may be significant overlap between the two, compatibility between the two is not a target for this lexer. """
name = 'MySQL' aliases = ['mysql'] mimetypes = ['text/x-mysql'] url = 'https://www.mysql.com' version_added = ''
flags = re.IGNORECASE tokens = { 'root': [ (r'\s+', Whitespace),
# Comments (r'(?:#|--\s+).*', Comment.Single), (r'/\*\+', Comment.Special, 'optimizer-hints'), (r'/\*', Comment.Multiline, 'multiline-comment'),
# Hexadecimal literals (r"x'([0-9a-f]{2})+'", Number.Hex), # MySQL requires paired hex characters in this form. (r'0x[0-9a-f]+', Number.Hex),
# Binary literals (r"b'[01]+'", Number.Bin), (r'0b[01]+', Number.Bin),
# Numeric literals (r'[0-9]+\.[0-9]*(e[+-]?[0-9]+)?', Number.Float), # Mandatory integer, optional fraction and exponent (r'[0-9]*\.[0-9]+(e[+-]?[0-9]+)?', Number.Float), # Mandatory fraction, optional integer and exponent (r'[0-9]+e[+-]?[0-9]+', Number.Float), # Exponents with integer significands are still floats (r'[0-9]+(?=[^0-9a-z$_\u0080-\uffff])', Number.Integer), # Integers that are not in a schema object name
# Date literals (r"\{\s*d\s*(?P<quote>['\"])\s*\d{2}(\d{2})?.?\d{2}.?\d{2}\s*(?P=quote)\s*\}", Literal.Date),
# Time literals (r"\{\s*t\s*(?P<quote>['\"])\s*(?:\d+\s+)?\d{1,2}.?\d{1,2}.?\d{1,2}(\.\d*)?\s*(?P=quote)\s*\}", Literal.Date),
# Timestamp literals ( r"\{\s*ts\s*(?P<quote>['\"])\s*" r"\d{2}(?:\d{2})?.?\d{2}.?\d{2}" # Date part r"\s+" # Whitespace between date and time r"\d{1,2}.?\d{1,2}.?\d{1,2}(\.\d*)?" # Time part r"\s*(?P=quote)\s*\}", Literal.Date ),
# String literals (r"'", String.Single, 'single-quoted-string'), (r'"', String.Double, 'double-quoted-string'),
# Variables (r'@@(?:global\.|persist\.|persist_only\.|session\.)?[a-z_]+', Name.Variable), (r'@[a-z0-9_$.]+', Name.Variable), (r"@'", Name.Variable, 'single-quoted-variable'), (r'@"', Name.Variable, 'double-quoted-variable'), (r"@`", Name.Variable, 'backtick-quoted-variable'), (r'\?', Name.Variable), # For demonstrating prepared statements
# Operators (r'[!%&*+/:<=>^|~-]+', Operator),
# Exceptions; these words tokenize differently in different contexts. (r'\b(set)(?!\s*\()', Keyword), (r'\b(character)(\s+)(set)\b', bygroups(Keyword, Whitespace, Keyword)), # In all other known cases, "SET" is tokenized by MYSQL_DATATYPES.
(words(_mysql_builtins.MYSQL_CONSTANTS, prefix=r'\b', suffix=r'\b'), Name.Constant), (words(_mysql_builtins.MYSQL_DATATYPES, prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(_mysql_builtins.MYSQL_KEYWORDS, prefix=r'\b', suffix=r'\b'), Keyword), (words(_mysql_builtins.MYSQL_FUNCTIONS, prefix=r'\b', suffix=r'\b(\s*)(\()'), bygroups(Name.Function, Whitespace, Punctuation)),
# Schema object names # # Note: Although the first regex supports unquoted all-numeric # identifiers, this will not be a problem in practice because # numeric literals have already been handled above. # ('[0-9a-z$_\u0080-\uffff]+', Name), (r'`', Name.Quoted, 'schema-object-name'),
# Punctuation (r'[(),.;]', Punctuation), ],
# Multiline comment substates # ---------------------------
'optimizer-hints': [ (r'[^*a-z]+', Comment.Special), (r'\*/', Comment.Special, '#pop'), (words(_mysql_builtins.MYSQL_OPTIMIZER_HINTS, suffix=r'\b'), Comment.Preproc), ('[a-z]+', Comment.Special), (r'\*', Comment.Special), ],
'multiline-comment': [ (r'[^*]+', Comment.Multiline), (r'\*/', Comment.Multiline, '#pop'), (r'\*', Comment.Multiline), ],
# String substates # ----------------
'single-quoted-string': [ (r"[^'\\]+", String.Single), (r"''", String.Escape), (r"""\\[0'"bnrtZ\\%_]""", String.Escape), (r"'", String.Single, '#pop'), ],
'double-quoted-string': [ (r'[^"\\]+', String.Double), (r'""', String.Escape), (r"""\\[0'"bnrtZ\\%_]""", String.Escape), (r'"', String.Double, '#pop'), ],
# Variable substates # ------------------
'single-quoted-variable': [ (r"[^']+", Name.Variable), (r"''", Name.Variable), (r"'", Name.Variable, '#pop'), ],
'double-quoted-variable': [ (r'[^"]+', Name.Variable), (r'""', Name.Variable), (r'"', Name.Variable, '#pop'), ],
'backtick-quoted-variable': [ (r'[^`]+', Name.Variable), (r'``', Name.Variable), (r'`', Name.Variable, '#pop'), ],
# Schema object name substates # ---------------------------- # # "Name.Quoted" and "Name.Quoted.Escape" are non-standard but # formatters will style them as "Name" by default but add # additional styles based on the token name. This gives users # flexibility to add custom styles as desired. # 'schema-object-name': [ (r'[^`]+', Name.Quoted), (r'``', Name.Quoted.Escape), (r'`', Name.Quoted, '#pop'), ], }
def analyse_text(text): rating = 0 name_between_backtick_count = len( name_between_backtick_re.findall(text)) name_between_bracket_count = len( name_between_bracket_re.findall(text)) # Same logic as above in the TSQL analysis dialect_name_count = name_between_backtick_count + name_between_bracket_count if dialect_name_count >= 1 and \ name_between_backtick_count >= 2 * name_between_bracket_count: # Found at least twice as many `name` as [name]. rating += 0.5 elif name_between_backtick_count > name_between_bracket_count: rating += 0.2 elif name_between_backtick_count > 0: rating += 0.1 return rating
class GoogleSqlLexer(RegexLexer): """ GoogleSQL is Google's standard SQL dialect, formerly known as ZetaSQL.
The list of keywords includes reserved words for future use. """
name = 'GoogleSQL' aliases = ['googlesql', 'zetasql'] filenames = ['*.googlesql', '*.googlesql.sql'] mimetypes = ['text/x-google-sql', 'text/x-google-sql-aux'] url = 'https://cloud.google.com/bigquery/googlesql' version_added = '2.19'
flags = re.IGNORECASE tokens = { 'root': [ (r'\s+', Whitespace),
# Comments (r'(?:#|--\s+).*', Comment.Single), (r'/\*', Comment.Multiline, 'multiline-comment'),
# Hexadecimal literals (r"x'([0-9a-f]{2})+'", Number.Hex), (r'0x[0-9a-f]+', Number.Hex),
# Binary literals (r"b'[01]+'", Number.Bin), (r'0b[01]+', Number.Bin),
# Numeric literals (r'[0-9]+\.[0-9]*(e[+-]?[0-9]+)?', Number.Float), # Mandatory integer, optional fraction and exponent (r'[0-9]*\.[0-9]+(e[+-]?[0-9]+)?', Number.Float), # Mandatory fraction, optional integer and exponent (r'[0-9]+e[+-]?[0-9]+', Number.Float), # Exponents with integer significands are still floats (r'[0-9]+(?=[^0-9a-z$_\u0080-\uffff])', Number.Integer), # Integers that are not in a schema object name
# Date literals (r"\{\s*d\s*(?P<quote>['\"])\s*\d{2}(\d{2})?.?\d{2}.?\d{2}\s*(?P=quote)\s*\}", Literal.Date),
# Time literals (r"\{\s*t\s*(?P<quote>['\"])\s*(?:\d+\s+)?\d{1,2}.?\d{1,2}.?\d{1,2}(\.\d*)?\s*(?P=quote)\s*\}", Literal.Date),
# Timestamp literals ( r"\{\s*ts\s*(?P<quote>['\"])\s*" r"\d{2}(?:\d{2})?.?\d{2}.?\d{2}" # Date part r"\s+" # Whitespace between date and time r"\d{1,2}.?\d{1,2}.?\d{1,2}(\.\d*)?" # Time part r"\s*(?P=quote)\s*\}", Literal.Date ),
# String literals (r"'", String.Single, 'single-quoted-string'), (r'"', String.Double, 'double-quoted-string'),
# Variables (r'@@(?:global\.|persist\.|persist_only\.|session\.)?[a-z_]+', Name.Variable), (r'@[a-z0-9_$.]+', Name.Variable), (r"@'", Name.Variable, 'single-quoted-variable'), (r'@"', Name.Variable, 'double-quoted-variable'), (r"@`", Name.Variable, 'backtick-quoted-variable'), (r'\?', Name.Variable), # For demonstrating prepared statements
# Exceptions; these words tokenize differently in different contexts. (r'\b(set)(?!\s*\()', Keyword), (r'\b(character)(\s+)(set)\b', bygroups(Keyword, Whitespace, Keyword)),
# Constants, types, keywords, functions, operators (words(_googlesql_builtins.constants, prefix=r'\b', suffix=r'\b'), Name.Constant), (words(_googlesql_builtins.types, prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(_googlesql_builtins.keywords, prefix=r'\b', suffix=r'\b'), Keyword), (words(_googlesql_builtins.functionnames, prefix=r'\b', suffix=r'\b(\s*)(\()'), bygroups(Name.Function, Whitespace, Punctuation)), (words(_googlesql_builtins.operators, prefix=r'\b', suffix=r'\b'), Operator),
# Schema object names # # Note: Although the first regex supports unquoted all-numeric # identifiers, this will not be a problem in practice because # numeric literals have already been handled above. # ('[0-9a-z$_\u0080-\uffff]+', Name), (r'`', Name.Quoted, 'schema-object-name'),
# Punctuation (r'[(),.;]', Punctuation), ],
# Multiline comment substates # ---------------------------
'multiline-comment': [ (r'[^*]+', Comment.Multiline), (r'\*/', Comment.Multiline, '#pop'), (r'\*', Comment.Multiline), ],
# String substates # ----------------
'single-quoted-string': [ (r"[^'\\]+", String.Single), (r"''", String.Escape), (r"""\\[0'"bnrtZ\\%_]""", String.Escape), (r"'", String.Single, '#pop'), ],
'double-quoted-string': [ (r'[^"\\]+', String.Double), (r'""', String.Escape), (r"""\\[0'"bnrtZ\\%_]""", String.Escape), (r'"', String.Double, '#pop'), ],
# Variable substates # ------------------
'single-quoted-variable': [ (r"[^']+", Name.Variable), (r"''", Name.Variable), (r"'", Name.Variable, '#pop'), ],
'double-quoted-variable': [ (r'[^"]+', Name.Variable), (r'""', Name.Variable), (r'"', Name.Variable, '#pop'), ],
'backtick-quoted-variable': [ (r'[^`]+', Name.Variable), (r'``', Name.Variable), (r'`', Name.Variable, '#pop'), ],
# Schema object name substates # ---------------------------- # # "Name.Quoted" and "Name.Quoted.Escape" are non-standard but # formatters will style them as "Name" by default but add # additional styles based on the token name. This gives users # flexibility to add custom styles as desired. # 'schema-object-name': [ (r'[^`]+', Name.Quoted), (r'``', Name.Quoted.Escape), (r'`', Name.Quoted, '#pop'), ], }
def analyse_text(text): tokens = collections.Counter(text.split()) return 0.001 * sum(count for t, count in tokens.items() if t in googlesql_identifiers)
class SqliteConsoleLexer(Lexer): """ Lexer for example sessions using sqlite3. """
name = 'sqlite3con' aliases = ['sqlite3'] filenames = ['*.sqlite3-console'] mimetypes = ['text/x-sqlite3-console'] url = 'https://www.sqlite.org' version_added = '0.11' _example = "sqlite3/sqlite3.sqlite3-console"
def get_tokens_unprocessed(self, data): sql = SqlLexer(**self.options)
curcode = '' insertions = [] for match in line_re.finditer(data): line = match.group() prompt_match = sqlite_prompt_re.match(line) if prompt_match is not None: insertions.append((len(curcode), [(0, Generic.Prompt, line[:7])])) insertions.append((len(curcode), [(7, Whitespace, ' ')])) curcode += line[8:] else: if curcode: yield from do_insertions(insertions, sql.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] if line.startswith('SQL error: '): yield (match.start(), Generic.Traceback, line) else: yield (match.start(), Generic.Output, line) if curcode: yield from do_insertions(insertions, sql.get_tokens_unprocessed(curcode))
class RqlLexer(RegexLexer): """ Lexer for Relation Query Language. """ name = 'RQL' url = 'http://www.logilab.org/project/rql' aliases = ['rql'] filenames = ['*.rql'] mimetypes = ['text/x-rql'] version_added = '2.0'
flags = re.IGNORECASE tokens = { 'root': [ (r'\s+', Whitespace), (r'(DELETE|SET|INSERT|UNION|DISTINCT|WITH|WHERE|BEING|OR' r'|AND|NOT|GROUPBY|HAVING|ORDERBY|ASC|DESC|LIMIT|OFFSET' r'|TODAY|NOW|TRUE|FALSE|NULL|EXISTS)\b', Keyword), (r'[+*/<>=%-]', Operator), (r'(Any|is|instance_of|CWEType|CWRelation)\b', Name.Builtin), (r'[0-9]+', Number.Integer), (r'[A-Z_]\w*\??', Name), (r"'(''|[^'])*'", String.Single), (r'"(""|[^"])*"', String.Single), (r'[;:()\[\],.]', Punctuation) ], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162""" pygments.lexers.srcinfo ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for .SRCINFO files used by Arch Linux Packages.
The description of the format can be found in the wiki: https://wiki.archlinux.org/title/.SRCINFO
: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, Keyword, Name, Operator, Whitespace
__all__ = ['SrcinfoLexer']
keywords = ( 'pkgbase', 'pkgname', 'pkgver', 'pkgrel', 'epoch', 'pkgdesc', 'url', 'install', 'changelog', 'arch', 'groups', 'license', 'noextract', 'options', 'backup', 'validpgpkeys',)
architecture_dependent_keywords = ( 'source', 'depends', 'checkdepends', 'makedepends', 'optdepends', 'provides', 'conflicts', 'replaces', 'md5sums', 'sha1sums', 'sha224sums', 'sha256sums', 'sha384sums', 'sha512sums',)
class SrcinfoLexer(RegexLexer): """Lexer for .SRCINFO files used by Arch Linux Packages. """
name = 'Srcinfo' aliases = ['srcinfo'] filenames = ['.SRCINFO'] url = 'https://wiki.archlinux.org/title/.SRCINFO' version_added = '2.11'
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*', Comment.Single), (words(keywords), Keyword, 'assignment'), (words(architecture_dependent_keywords, suffix=r'_\w+'), Keyword, 'assignment'), (r'\w+', Name.Variable, 'assignment'), ], 'assignment': [ (r' +', Whitespace), (r'=', Operator, 'value'), ], 'value': [ (r' +', Whitespace), (r'.*', Text, '#pop:2'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170""" pygments.lexers.stata ~~~~~~~~~~~~~~~~~~~~~
Lexer for Stata
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import refrom pygments.lexer import RegexLexer, default, include, wordsfrom pygments.token import Comment, Keyword, Name, Number, \ String, Text, Operator
from pygments.lexers._stata_builtins import builtins_base, builtins_functions
__all__ = ['StataLexer']
class StataLexer(RegexLexer): """ For Stata do files. """ # Syntax based on # - http://fmwww.bc.edu/RePEc/bocode/s/synlightlist.ado # - https://github.com/isagalaev/highlight.js/blob/master/src/languages/stata.js # - https://github.com/jpitblado/vim-stata/blob/master/syntax/stata.vim
name = 'Stata' url = 'http://www.stata.com/' version_added = '2.2' aliases = ['stata', 'do'] filenames = ['*.do', '*.ado'] mimetypes = ['text/x-stata', 'text/stata', 'application/x-stata'] flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ include('comments'), include('strings'), include('macros'), include('numbers'), include('keywords'), include('operators'), include('format'), (r'.', Text), ], # Comments are a complicated beast in Stata because they can be # nested and there are a few corner cases with that. See: # - github.com/kylebarron/language-stata/issues/90 # - statalist.org/forums/forum/general-stata-discussion/general/1448244 'comments': [ (r'(^//|(?<=\s)//)(?!/)', Comment.Single, 'comments-double-slash'), (r'^\s*\*', Comment.Single, 'comments-star'), (r'/\*', Comment.Multiline, 'comments-block'), (r'(^///|(?<=\s)///)', Comment.Special, 'comments-triple-slash') ], 'comments-block': [ (r'/\*', Comment.Multiline, '#push'), # this ends and restarts a comment block. but need to catch this so # that it doesn\'t start _another_ level of comment blocks (r'\*/\*', Comment.Multiline), (r'(\*/\s+\*(?!/)[^\n]*)|(\*/)', Comment.Multiline, '#pop'), # Match anything else as a character inside the comment (r'.', Comment.Multiline), ], 'comments-star': [ (r'///.*?\n', Comment.Single, ('#pop', 'comments-triple-slash')), (r'(^//|(?<=\s)//)(?!/)', Comment.Single, ('#pop', 'comments-double-slash')), (r'/\*', Comment.Multiline, 'comments-block'), (r'.(?=\n)', Comment.Single, '#pop'), (r'.', Comment.Single), ], 'comments-triple-slash': [ (r'\n', Comment.Special, '#pop'), # A // breaks out of a comment for the rest of the line (r'//.*?(?=\n)', Comment.Single, '#pop'), (r'.', Comment.Special), ], 'comments-double-slash': [ (r'\n', Text, '#pop'), (r'.', Comment.Single), ], # `"compound string"' and regular "string"; note the former are # nested. 'strings': [ (r'`"', String, 'string-compound'), (r'(?<!`)"', String, 'string-regular'), ], 'string-compound': [ (r'`"', String, '#push'), (r'"\'', String, '#pop'), (r'\\\\|\\"|\\\$|\\`|\\\n', String.Escape), include('macros'), (r'.', String) ], 'string-regular': [ (r'(")(?!\')|(?=\n)', String, '#pop'), (r'\\\\|\\"|\\\$|\\`|\\\n', String.Escape), include('macros'), (r'.', String) ], # A local is usually # `\w{0,31}' # `:extended macro' # `=expression' # `[rsen](results)' # `(++--)scalar(++--)' # # However, there are all sorts of weird rules wrt edge # cases. Instead of writing 27 exceptions, anything inside # `' is a local. # # A global is more restricted, so we do follow rules. Note only # locals explicitly enclosed ${} can be nested. 'macros': [ (r'\$(\{|(?=[$`]))', Name.Variable.Global, 'macro-global-nested'), (r'\$', Name.Variable.Global, 'macro-global-name'), (r'`', Name.Variable, 'macro-local'), ], 'macro-local': [ (r'`', Name.Variable, '#push'), (r"'", Name.Variable, '#pop'), (r'\$(\{|(?=[$`]))', Name.Variable.Global, 'macro-global-nested'), (r'\$', Name.Variable.Global, 'macro-global-name'), (r'.', Name.Variable), # fallback ], 'macro-global-nested': [ (r'\$(\{|(?=[$`]))', Name.Variable.Global, '#push'), (r'\}', Name.Variable.Global, '#pop'), (r'\$', Name.Variable.Global, 'macro-global-name'), (r'`', Name.Variable, 'macro-local'), (r'\w', Name.Variable.Global), # fallback default('#pop'), ], 'macro-global-name': [ (r'\$(\{|(?=[$`]))', Name.Variable.Global, 'macro-global-nested', '#pop'), (r'\$', Name.Variable.Global, 'macro-global-name', '#pop'), (r'`', Name.Variable, 'macro-local', '#pop'), (r'\w{1,32}', Name.Variable.Global, '#pop'), ], # Built in functions and statements 'keywords': [ (words(builtins_functions, prefix = r'\b', suffix = r'(?=\()'), Name.Function), (words(builtins_base, prefix = r'(^\s*|\s)', suffix = r'\b'), Keyword), ], # http://www.stata.com/help.cgi?operators 'operators': [ (r'-|==|<=|>=|<|>|&|!=', Operator), (r'\*|\+|\^|/|!|~|==|~=', Operator) ], # Stata numbers 'numbers': [ # decimal number (r'\b[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)([eE][+-]?[0-9]+)?[i]?\b', Number), ], # Stata formats 'format': [ (r'%-?\d{1,2}(\.\d{1,2})?[gfe]c?', Name.Other), (r'%(21x|16H|16L|8H|8L)', Name.Other), (r'%-?(tc|tC|td|tw|tm|tq|th|ty|tg)\S{0,32}', Name.Other), (r'%[-~]?\d{1,4}s', Name.Other), ] }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394""" pygments.lexers.supercollider ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for SuperCollider
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, words, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['SuperColliderLexer']
class SuperColliderLexer(RegexLexer): """ For SuperCollider source code. """
name = 'SuperCollider' url = 'http://supercollider.github.io/' aliases = ['supercollider', 'sc'] filenames = ['*.sc', '*.scd'] mimetypes = ['application/supercollider', 'text/supercollider'] version_added = '2.1'
flags = re.DOTALL | re.MULTILINE tokens = { 'commentsandwhitespace': [ (r'\s+', Text), (r'<!--', Comment), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline) ], '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': [ (r'^(?=\s|/|<!--)', Text, 'slashstartsregex'), include('commentsandwhitespace'), (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|' r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (words(( 'for', 'in', 'while', 'do', 'break', 'return', 'continue', 'switch', 'case', 'default', 'if', 'else', 'throw', 'try', 'catch', 'finally', 'new', 'delete', 'typeof', 'instanceof', 'void'), suffix=r'\b'), Keyword, 'slashstartsregex'), (words(('var', 'let', 'with', 'function', 'arg'), suffix=r'\b'), Keyword.Declaration, 'slashstartsregex'), (words(( '(abstract', 'boolean', 'byte', 'char', 'class', 'const', 'debugger', 'double', 'enum', 'export', 'extends', 'final', 'float', 'goto', 'implements', 'import', 'int', 'interface', 'long', 'native', 'package', 'private', 'protected', 'public', 'short', 'static', 'super', 'synchronized', 'throws', 'transient', 'volatile'), suffix=r'\b'), Keyword.Reserved), (words(('true', 'false', 'nil', 'inf'), suffix=r'\b'), Keyword.Constant), (words(( 'Array', 'Boolean', 'Date', 'Error', 'Function', 'Number', 'Object', 'Packages', 'RegExp', 'String', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'super', 'thisFunctionDef', 'thisFunction', 'thisMethod', 'thisProcess', 'thisThread', 'this'), suffix=r'\b'), Name.Builtin), (r'[$a-zA-Z_]\w*', Name.Other), (r'\\?[$a-zA-Z_]\w*', String.Symbol), (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), ] }
def analyse_text(text): """We're searching for a common function and a unique keyword here.""" if 'SinOsc' in text or 'thisFunctionDef' in text: return 0.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177""" pygments.lexers.tablegen ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for LLVM's TableGen DSL.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, usingfrom pygments.lexers.c_cpp import CppLexerfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace, Error
__all__ = ['TableGenLexer']
KEYWORDS = ( 'assert', 'class', 'code', 'def', 'dump', 'else', 'foreach', 'defm', 'defset', 'defvar', 'field', 'if', 'in', 'include', 'let', 'multiclass', 'then',)
KEYWORDS_CONST = ( 'false', 'true',)KEYWORDS_TYPE = ( 'bit', 'bits', 'dag', 'int', 'list', 'string',)
BANG_OPERATORS = ( 'add', 'and', 'cast', 'con', 'cond', 'dag', 'div', 'empty', 'eq', 'exists', 'filter', 'find', 'foldl', 'foreach', 'ge', 'getdagarg', 'getdagname', 'getdagop', 'gt', 'head', 'if', 'interleave', 'isa', 'le', 'listconcat', 'listremove', 'listsplat', 'logtwo', 'lt', 'mul', 'ne', 'not', 'or', 'range', 'repr', 'setdagarg', 'setdagname', 'setdagop', 'shl', 'size', 'sra', 'srl', 'strconcat', 'sub', 'subst', 'substr', 'tail', 'tolower', 'toupper', 'xor',)
class TableGenLexer(RegexLexer): """ Lexer for TableGen """
name = 'TableGen' url = 'https://llvm.org/docs/TableGen/ProgRef.html' aliases = ['tablegen', 'td'] filenames = ['*.td']
version_added = '2.19'
tokens = { 'root': [ (r'\s+', Whitespace),
(r'/\*', Comment.Multiline, 'comment'), (r'//.*?$', Comment.Single), (r'#(define|ifdef|ifndef|else|endif)', Comment.Preproc),
# Binary/hex numbers. Note that these take priority over names, # which may begin with numbers. (r'0b[10]+', Number.Bin), (r'0x[0-9a-fA-F]+', Number.Hex),
# Keywords (words(KEYWORDS, suffix=r'\b'), Keyword), (words(KEYWORDS_CONST, suffix=r'\b'), Keyword.Constant), (words(KEYWORDS_TYPE, suffix=r'\b'), Keyword.Type),
# Bang operators (words(BANG_OPERATORS, prefix=r'\!', suffix=r'\b'), Operator), # Unknown bang operators are an error (r'![a-zA-Z]+', Error),
# Names and identifiers (r'[0-9]*[a-zA-Z_][a-zA-Z_0-9]*', Name), (r'\$[a-zA-Z_][a-zA-Z_0-9]*', Name.Variable),
# Place numbers after keywords. Names/identifiers may begin with # numbers, and we want to parse 1X as one name token as opposed to # a number and a name. (r'[-\+]?[0-9]+', Number.Integer),
# String literals (r'"', String, 'dqs'), (r'\[\{', Punctuation, 'codeblock'),
# Misc. punctuation (r'[-+\[\]{}()<>\.,;:=?#]+', Punctuation), ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'strings': [ (r'\\[\\\'"tn]', String.Escape), (r'[^\\"]+', String), ], # Double-quoted string, a la C 'dqs': [ (r'"', String, '#pop'), include('strings'), ], # NOTE: Must escape (pop Cpplexer) codeblock to avoid infinite loop. # Assume that the code inside a code block is C++. This isn't always # true in TableGen, but is the far most common scenario. 'codeblock': [ (r'\}\]', Text, '#pop'), (r'([^}]+|\}[^]])*', using(CppLexer), "#pop"), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303""" pygments.lexers.tact ~~~~~~~~~~~~~~~~~~~~
Lexers for Tact.
: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 Comment, Operator, Keyword, Name, String, \ Number, Whitespace, Punctuation
__all__ = ['TactLexer']
class TactLexer(RegexLexer): """For Tact source code."""
name = 'Tact' aliases = ['tact'] filenames = ['*.tact'] url = "https://tact-lang.org" version_added = '2.18'
tokens = { 'root': [ (r'\s+', Whitespace), (r'[.;(),\[\]{}]', Punctuation), (r'\?|!!', Operator), include('comments'), include('import-in'), include('struct-in'), include('contract-or-trait-in'), include('annotation-in'), include('fun-declaration-in'), include('const-declaration-in'), include('statements'), ], 'import-in': [ (r'((?<=\.\.\.)|(?<![.$]))\b(import)\b(\s*)', bygroups(Punctuation, Keyword, Whitespace), 'import'), ], 'import': [ (r';', Punctuation, '#pop'), include('comments'), include('string-in'), (r'\s+', Whitespace), ], 'struct-in': [ (r'((?<=\.\.\.)|(?<![.$]))\b(struct|message)\b', bygroups(Punctuation, Keyword), 'struct'), ], 'struct': [ include('comments'), include('struct-header'), include('struct-body-in'), (r'\s+', Whitespace), ], 'struct-header': [ include('comments'), (r'\b\w+', Name.Class), (r'(\()((?:\b0[xX])[0-9a-fA-F][0-9a-fA-F_]*\b)(\))', bygroups(Punctuation, Number.Hex, Punctuation)), (r'(\()((?:\b[0-9]+\b))(\))', bygroups(Punctuation, Number.Integer, Punctuation)), ], 'struct-body-in': [ (r'\{', Punctuation, 'struct-body'), ], 'struct-body': [ (r'\}', Punctuation, '#pop:2'), include('comments'), include('field-declaration-in'), ], 'contract-or-trait-in': [ (r'((?<=\.\.\.)|(?<![.$]))\b(contract|trait)\b', Keyword, 'contract-or-trait'), ], 'contract-or-trait': [ include('comments'), (r'with', Keyword), (r'\b\w+', Name.Class), include('contract-or-trait-body-in'), (r'\s+', Whitespace), (r',', Punctuation), ], 'contract-or-trait-body-in': [ (r'\{', Punctuation, 'contract-or-trait-body'), ], 'contract-or-trait-body': [ (r'\}', Punctuation, '#pop:2'), include('comments'), include('init-declaration-in'), include('receive-declaration-in'), include('bounce-declaration-in'), include('fun-declaration-in'), include('const-declaration-in'), include('field-declaration-in'), (r'\s+', Whitespace), ], 'field-declaration-in': [ (r'\b\w+', Name.Property, 'field-declaration'), ], 'field-declaration': [ (r';', Punctuation, '#pop'), include('comments'), include('type-annotation-in'), include('variable-init-in'), ], 'const-declaration-in': [ (r'(?=\b(?:(?:get|native|extends|mutates|virtual|override|inline|abstract)\s*)*const\b)', Keyword, 'const-declaration'), ], 'const-declaration': [ (r'(;)', Punctuation, '#pop'), (r'const', Keyword), (words(('get', 'native', 'extends', 'mutates', 'virtual', 'override', 'inline', 'abstract'), suffix=r'\b'), Keyword), (r'\b\w+\b', Name.Constant), include('comments'), include('type-annotation-in'), include('variable-init-in'), (r'\s+', Whitespace), ], 'init-declaration-in': [ (r'(init)', Keyword, 'init-declaration') ], 'init-declaration': [ (r'(?<=\})', Punctuation, '#pop'), include('comments'), include('fun-arguments-in'), include('block-declaration-in'), (r'\s+', Whitespace), ], 'receive-declaration-in': [ (r'(receive|exernal)', Keyword, 'receive-declaration') ], 'receive-declaration': [ (r'(?<=\})', Punctuation, '#pop'), include('comments'), include('fun-arguments-in'), include('block-declaration-in'), ], 'bounce-declaration-in': [ (r'(bounced)', Keyword, 'bounce-declaration') ], 'bounce-declaration': [ (r'(?<=\})', Punctuation, '#pop'), include('comments'), include('fun-arguments-in'), include('block-declaration-in'), ], 'fun-declaration-in': [ (r'(?=\b(?:(?:get|native|extends|mutates|virtual|override|inline|abstract)\s*)*fun\b)', Keyword, 'fun-declaration') ], 'fun-declaration': [ (r'(?<=\}|\;)', Punctuation, '#pop'), (r'fun', Keyword), (r'\b(get|native|extends|mutates|virtual|override|inline|abstract)\b', Keyword), (r'\b[\w]+', Name.Function), include('fun-declaration-body'), (r'[,;]', Punctuation), ], 'fun-declaration-body': [ include('comments'), include('fun-arguments-in'), include('type-annotation-in'), include('block-declaration-in'), (r'\s+', Whitespace), ], 'fun-arguments-in': [ (r'\(', Punctuation, 'fun-arguments'), ], 'fun-arguments': [ (r'\)', Punctuation, '#pop'), include('comments'), include('string-in'), include('type-annotation-in'), (r'(self)|(\b[\w]+\b)', bygroups(Name.Variable.Instance, Name.Variable)), (r',', Punctuation), (r'\s+', Whitespace), ], 'block-declaration-in': [ (r'\{', Punctuation, 'block-declaration') ], 'block-declaration': [ (r'\}', Punctuation, '#pop'), include('statements'), ], 'statements': [ include('comments'), include('block-declaration-in'), include('expressions'), ], 'annotation-in': [ (r'(@)(\w+)(\()', bygroups(Keyword.Pseudo, Keyword, Punctuation), 'annotation') ], 'annotation': [ (r'\)', Punctuation, '#pop'), include('annotation-argument'), (r'\s+', Whitespace), ], 'annotation-argument': [ (r'\w+', Name.Function.Magic), ], 'expressions': [ include('comments'), include('type-annotation-in'), include('keywords'), include('numeric'), include('string-in'), include('variable'), include('function-call'), include('struct-init-in'), ], 'struct-init-in': [ (r'(\b\w+)(\s*)(\{)', bygroups(Name.Class, Whitespace, Punctuation), 'struct-init') ], 'struct-init': [ (r'(\})', Punctuation, '#pop'), include('comments'), include('struct-property-in'), (r'\s+', Whitespace), (r',', Punctuation), ], 'struct-property-in': [ (r'(\b[\w]+)(\s*)(:)', bygroups(Name.Property, Whitespace, Punctuation), 'struct-property') ], 'struct-property': [ (r'(?=\}|\,)', Punctuation, '#pop'), include('comments'), include('expressions'), (r'\s+', Whitespace), ], 'variable-init-in': [ (r'(=)', Operator, 'variable-init') ], 'variable-init': [ (r'(?=\}|\{|\,|\;)',Punctuation, '#pop'), include('comments'), include('expressions'), (r'\s+', Whitespace), ], 'type-annotation-in': [ (r'(:)(\s+)', bygroups(Punctuation, Whitespace), 'type-annotation') ], 'type-annotation': [ (r'(?=\{|\;|\=|\,|\))', Punctuation, '#pop'), include('comments'), include('type-as-in'), include('type-generic-in'), (r'\?', Operator), (r'\b\w+', Keyword.Type), (r'\s+', Whitespace), ], 'type-generic-in': [ (r'<', Punctuation, 'type-generic'), ], 'type-generic': [ (r'>', Punctuation, '#pop'), include('comments'), include('type-as-in'), (r'\b\w+', Keyword.Type), (r'\s+', Whitespace), (r',', Punctuation), ], 'type-as-in': [ (r'\b(as)(\s+)', bygroups(Keyword, Whitespace), 'type-as'), ], 'type-as': [ (r'(?=\{|\;|\=|\,|\)|\>)', Punctuation, '#pop'), include('comments'), (r'\b\w+', Keyword.Type), (r'\s+', Whitespace), ], 'keywords': [ (words(('if', 'else', 'while', 'do', 'until', 'repeat', 'return', 'extends', 'mutates', 'virtual', 'override', 'inline', 'native', 'let', 'const', 'fun', 'self', 'is', 'initOf', 'map', 'bounced', 'get', 'as'), prefix=r'\b', suffix=r'\b'), Keyword), (r'(<=>|>=|<=|!=|==|\^>>|~>>|>>|<<|\/%|\^%|~%|\^\/|~\/|\+=|-=|\*=|\/=|~\/=|\^\/=|%=|\^%=|<<=|>>=|~>>=|\^>>=|&=|\|=|\^=|\^|=|~|\/|%|-|\*|\+|>|<|&|\||:|\?)', Operator), (words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), ], 'string-in': [ (r'"', String, 'string'), ], 'string': [ (r'"', String, '#pop'), (r'\\.', String.Escape), (r'[^\\"]+', String.Double), ], 'numeric': [ (r'(?:\b0[xX])[0-9a-fA-F][0-9a-fA-F_]*\b', Number.Hex), (r'(?:\b[0-9]+\b)', Number.Integer), ], 'comments': [ (r'//.*', Comment.Single), (r'/\*', Comment.Multiline, 'comments-multiline'), ], 'comments-multiline': [ (r'\*/', Comment.Multiline, '#pop'), (r'[^*]+', Comment.Multiline), (r'[*]', Comment.Multiline), ], 'variable': [ (r'\b\w+\b(?!\s*\()(?!\s*\{)', Name.Variable) ], 'function-call': [ (r'\b\w+\b(?=\s*\()(?!\s*\{)', Name.Function) ], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677""" pygments.lexers.tal ~~~~~~~~~~~~~~~~~~~
Lexer for Uxntal
.. versionadded:: 2.12
: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, Keyword, Name, String, Number, \ Punctuation, Whitespace, Literal
__all__ = ['TalLexer']
class TalLexer(RegexLexer): """ For Uxntal source code. """
name = 'Tal' aliases = ['tal', 'uxntal'] filenames = ['*.tal'] mimetypes = ['text/x-uxntal'] url = 'https://wiki.xxiivv.com/site/uxntal.html' version_added = '2.12'
instructions = [ 'BRK', 'LIT', 'INC', 'POP', 'DUP', 'NIP', 'SWP', 'OVR', 'ROT', 'EQU', 'NEQ', 'GTH', 'LTH', 'JMP', 'JCN', 'JSR', 'STH', 'LDZ', 'STZ', 'LDR', 'STR', 'LDA', 'STA', 'DEI', 'DEO', 'ADD', 'SUB', 'MUL', 'DIV', 'AND', 'ORA', 'EOR', 'SFT' ]
tokens = { # the comment delimiters must not be adjacent to non-space characters. # this means ( foo ) is a valid comment but (foo) is not. this also # applies to nested comments. 'comment': [ (r'(?<!\S)\((?!\S)', Comment.Multiline, '#push'), # nested comments (r'(?<!\S)\)(?!\S)', Comment.Multiline, '#pop'), # nested comments (r'[^()]+', Comment.Multiline), # comments (r'[()]+', Comment.Multiline), # comments ], 'root': [ (r'\s+', Whitespace), # spaces (r'(?<!\S)\((?!\S)', Comment.Multiline, 'comment'), # comments (words(instructions, prefix=r'(?<!\S)', suffix=r'2?k?r?(?!\S)'), Keyword.Reserved), # instructions (r'[][{}](?!\S)', Punctuation), # delimiters (r'#([0-9a-f]{2}){1,2}(?!\S)', Number.Hex), # integer (r'"\S+', String), # raw string (r'([0-9a-f]{2}){1,2}(?!\S)', Literal), # raw integer (r'[|$][0-9a-f]{1,4}(?!\S)', Keyword.Declaration), # abs/rel pad (r'%\S+', Name.Decorator), # macro (r'@\S+', Name.Function), # label (r'&\S+', Name.Label), # sublabel (r'/\S+', Name.Tag), # spacer (r'\.\S+', Name.Variable.Magic), # literal zero page addr (r',\S+', Name.Variable.Instance), # literal rel addr (r';\S+', Name.Variable.Global), # literal abs addr (r'-\S+', Literal), # raw zero page addr (r'_\S+', Literal), # raw relative addr (r'=\S+', Literal), # raw absolute addr (r'!\S+', Name.Function), # immediate jump (r'\?\S+', Name.Function), # conditional immediate jump (r'~\S+', Keyword.Namespace), # include (r'\S+', Name.Function), # macro invocation, immediate subroutine ] }
def analyse_text(text): return '|0100' in text[:500]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148""" pygments.lexers.tcl ~~~~~~~~~~~~~~~~~~~
Lexers for Tcl and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Whitespacefrom pygments.util import shebang_matches
__all__ = ['TclLexer']
class TclLexer(RegexLexer): """ For Tcl source code. """
keyword_cmds_re = words(( 'after', 'apply', 'array', 'break', 'catch', 'continue', 'elseif', 'else', 'error', 'eval', 'expr', 'for', 'foreach', 'global', 'if', 'namespace', 'proc', 'rename', 'return', 'set', 'switch', 'then', 'trace', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while'), prefix=r'\b', suffix=r'\b')
builtin_cmds_re = words(( 'append', 'bgerror', 'binary', 'cd', 'chan', 'clock', 'close', 'concat', 'dde', 'dict', 'encoding', 'eof', 'exec', 'exit', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent', 'flush', 'format', 'gets', 'glob', 'history', 'http', 'incr', 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'loadTk', 'lrange', 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat', 'open', 'package', 'pid', 'pkg::create', 'pkg_mkIndex', 'platform', 'platform::shell', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'scan', 'seek', 'socket', 'source', 'split', 'string', 'subst', 'tell', 'time', 'tm', 'unknown', 'unload'), prefix=r'\b', suffix=r'\b')
name = 'Tcl' url = 'https://www.tcl.tk/about/language.html' aliases = ['tcl'] filenames = ['*.tcl', '*.rvt'] mimetypes = ['text/x-tcl', 'text/x-script.tcl', 'application/x-tcl'] version_added = '0.10'
def _gen_command_rules(keyword_cmds_re, builtin_cmds_re, context=""): return [ (keyword_cmds_re, Keyword, 'params' + context), (builtin_cmds_re, Name.Builtin, 'params' + context), (r'([\w.-]+)', Name.Variable, 'params' + context), (r'#', Comment, 'comment'), ]
tokens = { 'root': [ include('command'), include('basic'), include('data'), (r'\}', Keyword), # HACK: somehow we miscounted our braces ], 'command': _gen_command_rules(keyword_cmds_re, builtin_cmds_re), 'command-in-brace': _gen_command_rules(keyword_cmds_re, builtin_cmds_re, "-in-brace"), 'command-in-bracket': _gen_command_rules(keyword_cmds_re, builtin_cmds_re, "-in-bracket"), 'command-in-paren': _gen_command_rules(keyword_cmds_re, builtin_cmds_re, "-in-paren"), 'basic': [ (r'\(', Keyword, 'paren'), (r'\[', Keyword, 'bracket'), (r'\{', Keyword, 'brace'), (r'"', String.Double, 'string'), (r'(eq|ne|in|ni)\b', Operator.Word), (r'!=|==|<<|>>|<=|>=|&&|\|\||\*\*|[-+~!*/%<>&^|?:]', Operator), ], 'data': [ (r'\s+', Whitespace), (r'0x[a-fA-F0-9]+', Number.Hex), (r'0[0-7]+', Number.Oct), (r'\d+\.\d+', Number.Float), (r'\d+', Number.Integer), (r'\$[\w.:-]+', Name.Variable), (r'\$\{[\w.:-]+\}', Name.Variable), (r'[\w.,@:-]+', Text), ], 'params': [ (r';', Keyword, '#pop'), (r'\n', Text, '#pop'), (r'(else|elseif|then)\b', Keyword), include('basic'), include('data'), ], 'params-in-brace': [ (r'\}', Keyword, ('#pop', '#pop')), include('params') ], 'params-in-paren': [ (r'\)', Keyword, ('#pop', '#pop')), include('params') ], 'params-in-bracket': [ (r'\]', Keyword, ('#pop', '#pop')), include('params') ], 'string': [ (r'\[', String.Double, 'string-square'), (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\])', String.Double), (r'"', String.Double, '#pop') ], 'string-square': [ (r'\[', String.Double, 'string-square'), (r'(?s)(\\\\|\\[0-7]+|\\.|\\\n|[^\]\\])', String.Double), (r'\]', String.Double, '#pop') ], 'brace': [ (r'\}', Keyword, '#pop'), include('command-in-brace'), include('basic'), include('data'), ], 'paren': [ (r'\)', Keyword, '#pop'), include('command-in-paren'), include('basic'), include('data'), ], 'bracket': [ (r'\]', Keyword, '#pop'), include('command-in-bracket'), include('basic'), include('data'), ], 'comment': [ (r'.*[^\\]\n', Comment, '#pop'), (r'.*\\\n', Comment), ], }
def analyse_text(text): return shebang_matches(text, r'(tcl)')12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788""" pygments.lexers.teal ~~~~~~~~~~~~~~~~~~~~
Lexer for TEAL.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, wordsfrom pygments.token import Comment, Name, Number, String, Text, Keyword, \ Whitespace
__all__ = ['TealLexer']
class TealLexer(RegexLexer): """ For the Transaction Execution Approval Language (TEAL)
For more information about the grammar, see: https://github.com/algorand/go-algorand/blob/master/data/transactions/logic/assembler.go """ name = 'teal' url = 'https://developer.algorand.org/docs/reference/teal/specification/' aliases = ['teal'] filenames = ['*.teal'] version_added = '2.9'
keywords = words({ 'Sender', 'Fee', 'FirstValid', 'FirstValidTime', 'LastValid', 'Note', 'Lease', 'Receiver', 'Amount', 'CloseRemainderTo', 'VotePK', 'SelectionPK', 'VoteFirst', 'VoteLast', 'VoteKeyDilution', 'Type', 'TypeEnum', 'XferAsset', 'AssetAmount', 'AssetSender', 'AssetReceiver', 'AssetCloseTo', 'GroupIndex', 'TxID', 'ApplicationID', 'OnCompletion', 'ApplicationArgs', 'NumAppArgs', 'Accounts', 'NumAccounts', 'ApprovalProgram', 'ClearStateProgram', 'RekeyTo', 'ConfigAsset', 'ConfigAssetTotal', 'ConfigAssetDecimals', 'ConfigAssetDefaultFrozen', 'ConfigAssetUnitName', 'ConfigAssetName', 'ConfigAssetURL', 'ConfigAssetMetadataHash', 'ConfigAssetManager', 'ConfigAssetReserve', 'ConfigAssetFreeze', 'ConfigAssetClawback', 'FreezeAsset', 'FreezeAssetAccount', 'FreezeAssetFrozen', 'NoOp', 'OptIn', 'CloseOut', 'ClearState', 'UpdateApplication', 'DeleteApplication', 'MinTxnFee', 'MinBalance', 'MaxTxnLife', 'ZeroAddress', 'GroupSize', 'LogicSigVersion', 'Round', 'LatestTimestamp', 'CurrentApplicationID', 'AssetBalance', 'AssetFrozen', 'AssetTotal', 'AssetDecimals', 'AssetDefaultFrozen', 'AssetUnitName', 'AssetName', 'AssetURL', 'AssetMetadataHash', 'AssetManager', 'AssetReserve', 'AssetFreeze', 'AssetClawback', }, suffix=r'\b')
identifier = r'[^ \t\n]+(?=\/\/)|[^ \t\n]+' newline = r'\r?\n' tokens = { 'root': [ include('whitespace'), # pragmas match specifically on the space character (r'^#pragma .*' + newline, Comment.Directive), # labels must be followed by a space, # but anything after that is ignored ('(' + identifier + ':' + ')' + '([ \t].*)', bygroups(Name.Label, Comment.Single)), (identifier, Name.Function, 'function-args'), ], 'function-args': [ include('whitespace'), (r'"', String, 'string'), (r'(b(?:ase)?(?:32|64) ?)(\(?[a-zA-Z0-9+/=]+\)?)', bygroups(String.Affix, String.Other)), (r'[A-Z2-7]{58}', Number), # address (r'0x[\da-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (keywords, Keyword), (identifier, Name.Attributes), # branch targets (newline, Text, '#pop'), ], 'string': [ (r'\\(?:["nrt\\]|x\d\d)', String.Escape), (r'[^\\\"\n]+', String), (r'"', String, '#pop'), ], 'whitespace': [ (r'[ \t]+', Whitespace), (r'//[^\n]+', Comment.Single), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355""" pygments.lexers.templates ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for various template engines' markup.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexers.html import HtmlLexer, XmlLexerfrom pygments.lexers.javascript import JavascriptLexer, LassoLexerfrom pygments.lexers.css import CssLexerfrom pygments.lexers.php import PhpLexerfrom pygments.lexers.python import PythonLexerfrom pygments.lexers.perl import PerlLexerfrom pygments.lexers.jvm import JavaLexer, TeaLangLexerfrom pygments.lexers.data import YamlLexerfrom pygments.lexers.sql import SqlLexerfrom pygments.lexer import Lexer, DelegatingLexer, RegexLexer, bygroups, \ include, using, this, default, combinedfrom pygments.token import Error, Punctuation, Whitespace, \ Text, Comment, Operator, Keyword, Name, String, Number, Other, Tokenfrom pygments.util import html_doctype_matches, looks_like_xml
__all__ = ['HtmlPhpLexer', 'XmlPhpLexer', 'CssPhpLexer', 'JavascriptPhpLexer', 'ErbLexer', 'RhtmlLexer', 'XmlErbLexer', 'CssErbLexer', 'JavascriptErbLexer', 'SmartyLexer', 'HtmlSmartyLexer', 'XmlSmartyLexer', 'CssSmartyLexer', 'JavascriptSmartyLexer', 'DjangoLexer', 'HtmlDjangoLexer', 'CssDjangoLexer', 'XmlDjangoLexer', 'JavascriptDjangoLexer', 'GenshiLexer', 'HtmlGenshiLexer', 'GenshiTextLexer', 'CssGenshiLexer', 'JavascriptGenshiLexer', 'MyghtyLexer', 'MyghtyHtmlLexer', 'MyghtyXmlLexer', 'MyghtyCssLexer', 'MyghtyJavascriptLexer', 'MasonLexer', 'MakoLexer', 'MakoHtmlLexer', 'MakoXmlLexer', 'MakoJavascriptLexer', 'MakoCssLexer', 'JspLexer', 'CheetahLexer', 'CheetahHtmlLexer', 'CheetahXmlLexer', 'CheetahJavascriptLexer', 'EvoqueLexer', 'EvoqueHtmlLexer', 'EvoqueXmlLexer', 'ColdfusionLexer', 'ColdfusionHtmlLexer', 'ColdfusionCFCLexer', 'VelocityLexer', 'VelocityHtmlLexer', 'VelocityXmlLexer', 'SspLexer', 'TeaTemplateLexer', 'LassoHtmlLexer', 'LassoXmlLexer', 'LassoCssLexer', 'LassoJavascriptLexer', 'HandlebarsLexer', 'HandlebarsHtmlLexer', 'YamlJinjaLexer', 'LiquidLexer', 'TwigLexer', 'TwigHtmlLexer', 'Angular2Lexer', 'Angular2HtmlLexer', 'SqlJinjaLexer']
class ErbLexer(Lexer): """ Generic ERB (Ruby Templating) lexer.
Just highlights ruby code between the preprocessor directives, other data is left untouched by the lexer.
All options are also forwarded to the `RubyLexer`. """
name = 'ERB' url = 'https://github.com/ruby/erb' aliases = ['erb'] mimetypes = ['application/x-ruby-templating'] version_added = ''
_block_re = re.compile(r'(<%%|%%>|<%=|<%#|<%-|<%|-%>|%>|^%[^%].*?$)', re.M)
def __init__(self, **options): from pygments.lexers.ruby import RubyLexer self.ruby_lexer = RubyLexer(**options) Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): """ Since ERB doesn't allow "<%" and other tags inside of ruby blocks we have to use a split approach here that fails for that too. """ tokens = self._block_re.split(text) tokens.reverse() state = idx = 0 try: while True: # text if state == 0: val = tokens.pop() yield idx, Other, val idx += len(val) state = 1 # block starts elif state == 1: tag = tokens.pop() # literals if tag in ('<%%', '%%>'): yield idx, Other, tag idx += 3 state = 0 # comment elif tag == '<%#': yield idx, Comment.Preproc, tag val = tokens.pop() yield idx + 3, Comment, val idx += 3 + len(val) state = 2 # blocks or output elif tag in ('<%', '<%=', '<%-'): yield idx, Comment.Preproc, tag idx += len(tag) data = tokens.pop() r_idx = 0 for r_idx, r_token, r_value in \ self.ruby_lexer.get_tokens_unprocessed(data): yield r_idx + idx, r_token, r_value idx += len(data) state = 2 elif tag in ('%>', '-%>'): yield idx, Error, tag idx += len(tag) state = 0 # % raw ruby statements else: yield idx, Comment.Preproc, tag[0] r_idx = 0 for r_idx, r_token, r_value in \ self.ruby_lexer.get_tokens_unprocessed(tag[1:]): yield idx + 1 + r_idx, r_token, r_value idx += len(tag) state = 0 # block ends elif state == 2: tag = tokens.pop() if tag not in ('%>', '-%>'): yield idx, Other, tag else: yield idx, Comment.Preproc, tag idx += len(tag) state = 0 except IndexError: return
def analyse_text(text): if '<%' in text and '%>' in text: return 0.4
class SmartyLexer(RegexLexer): """ Generic Smarty template lexer.
Just highlights smarty code between the preprocessor directives, other data is left untouched by the lexer. """
name = 'Smarty' url = 'https://www.smarty.net/' aliases = ['smarty'] filenames = ['*.tpl'] mimetypes = ['application/x-smarty'] version_added = ''
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ (r'[^{]+', Other), (r'(\{)(\*.*?\*)(\})', bygroups(Comment.Preproc, Comment, Comment.Preproc)), (r'(\{php\})(.*?)(\{/php\})', bygroups(Comment.Preproc, using(PhpLexer, startinline=True), Comment.Preproc)), (r'(\{)(/?[a-zA-Z_]\w*)(\s*)', bygroups(Comment.Preproc, Name.Function, Text), 'smarty'), (r'\{', Comment.Preproc, 'smarty') ], 'smarty': [ (r'\s+', Text), (r'\{', Comment.Preproc, '#push'), (r'\}', Comment.Preproc, '#pop'), (r'#[a-zA-Z_]\w*#', Name.Variable), (r'\$[a-zA-Z_]\w*(\.\w+)*', Name.Variable), (r'[~!%^&*()+=|\[\]:;,.<>/?@-]', Operator), (r'(true|false|null)\b', Keyword.Constant), (r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_]\w*', Name.Attribute) ] }
def analyse_text(text): rv = 0.0 if re.search(r'\{if\s+.*?\}.*?\{/if\}', text): rv += 0.15 if re.search(r'\{include\s+file=.*?\}', text): rv += 0.15 if re.search(r'\{foreach\s+.*?\}.*?\{/foreach\}', text): rv += 0.15 if re.search(r'\{\$.*?\}', text): rv += 0.01 return rv
class VelocityLexer(RegexLexer): """ Generic Velocity template lexer.
Just highlights velocity directives and variable references, other data is left untouched by the lexer. """
name = 'Velocity' url = 'https://velocity.apache.org/' aliases = ['velocity'] filenames = ['*.vm', '*.fhtml'] version_added = ''
flags = re.MULTILINE | re.DOTALL
identifier = r'[a-zA-Z_]\w*'
tokens = { 'root': [ (r'[^{#$]+', Other), (r'(#)(\*.*?\*)(#)', bygroups(Comment.Preproc, Comment, Comment.Preproc)), (r'(##)(.*?$)', bygroups(Comment.Preproc, Comment)), (r'(#\{?)(' + identifier + r')(\}?)(\s?\()', bygroups(Comment.Preproc, Name.Function, Comment.Preproc, Punctuation), 'directiveparams'), (r'(#\{?)(' + identifier + r')(\}|\b)', bygroups(Comment.Preproc, Name.Function, Comment.Preproc)), (r'\$!?\{?', Punctuation, 'variable') ], 'variable': [ (identifier, Name.Variable), (r'\(', Punctuation, 'funcparams'), (r'(\.)(' + identifier + r')', bygroups(Punctuation, Name.Variable), '#push'), (r'\}', Punctuation, '#pop'), default('#pop') ], 'directiveparams': [ (r'(&&|\|\||==?|!=?|[-<>+*%&|^/])|\b(eq|ne|gt|lt|ge|le|not|in)\b', Operator), (r'\[', Operator, 'rangeoperator'), (r'\b' + identifier + r'\b', Name.Function), include('funcparams') ], 'rangeoperator': [ (r'\.\.', Operator), include('funcparams'), (r'\]', Operator, '#pop') ], 'funcparams': [ (r'\$!?\{?', Punctuation, 'variable'), (r'\s+', Text), (r'[,:]', Punctuation), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r"\b[0-9]+\b", Number), (r'(true|false|null)\b', Keyword.Constant), (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), (r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), ] }
def analyse_text(text): rv = 0.0 if re.search(r'#\{?macro\}?\(.*?\).*?#\{?end\}?', text, re.DOTALL): rv += 0.25 if re.search(r'#\{?if\}?\(.+?\).*?#\{?end\}?', text, re.DOTALL): rv += 0.15 if re.search(r'#\{?foreach\}?\(.+?\).*?#\{?end\}?', text, re.DOTALL): rv += 0.15 if re.search(r'\$!?\{?[a-zA-Z_]\w*(\([^)]*\))?' r'(\.\w+(\([^)]*\))?)*\}?', text): rv += 0.01 return rv
class VelocityHtmlLexer(DelegatingLexer): """ Subclass of the `VelocityLexer` that highlights unlexed data with the `HtmlLexer`.
"""
name = 'HTML+Velocity' aliases = ['html+velocity'] version_added = '' alias_filenames = ['*.html', '*.fhtml'] mimetypes = ['text/html+velocity'] url = 'https://velocity.apache.org/'
def __init__(self, **options): super().__init__(HtmlLexer, VelocityLexer, **options)
class VelocityXmlLexer(DelegatingLexer): """ Subclass of the `VelocityLexer` that highlights unlexed data with the `XmlLexer`.
"""
name = 'XML+Velocity' aliases = ['xml+velocity'] version_added = '' alias_filenames = ['*.xml', '*.vm'] mimetypes = ['application/xml+velocity'] url = 'https://velocity.apache.org/'
def __init__(self, **options): super().__init__(XmlLexer, VelocityLexer, **options)
def analyse_text(text): rv = VelocityLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv
class DjangoLexer(RegexLexer): """ Generic `Django <https://www.djangoproject.com/documentation/templates/>`_ and `Jinja <https://jinja.palletsprojects.com>`_ template lexer.
It just highlights django/jinja code between the preprocessor directives, other data is left untouched by the lexer. """
name = 'Django/Jinja' aliases = ['django', 'jinja'] mimetypes = ['application/x-django-templating', 'application/x-jinja'] url = 'https://www.djangoproject.com/documentation/templates' version_added = ''
flags = re.M | re.S
tokens = { 'root': [ (r'[^{]+', Other), (r'\{\{', Comment.Preproc, 'var'), # jinja/django comments (r'\{#.*?#\}', Comment), # django comments (r'(\{%)(-?\s*)(comment)(\s*-?)(%\})(.*?)' r'(\{%)(-?\s*)(endcomment)(\s*-?)(%\})', bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc, Comment, Comment.Preproc, Text, Keyword, Text, Comment.Preproc)), # raw jinja blocks (r'(\{%)(-?\s*)(raw)(\s*-?)(%\})(.*?)' r'(\{%)(-?\s*)(endraw)(\s*-?)(%\})', bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc, Text, Comment.Preproc, Text, Keyword, Text, Comment.Preproc)), # filter blocks (r'(\{%)(-?\s*)(filter)(\s+)([a-zA-Z_]\w*)', bygroups(Comment.Preproc, Text, Keyword, Text, Name.Function), 'block'), (r'(\{%)(-?\s*)([a-zA-Z_]\w*)', bygroups(Comment.Preproc, Text, Keyword), 'block'), (r'\{', Other) ], 'varnames': [ (r'(\|)(\s*)([a-zA-Z_]\w*)', bygroups(Operator, Text, Name.Function)), (r'(is)(\s+)(not)?(\s+)?([a-zA-Z_]\w*)', bygroups(Keyword, Text, Keyword, Text, Name.Function)), (r'(_|true|false|none|True|False|None)\b', Keyword.Pseudo), (r'(in|as|reversed|recursive|not|and|or|is|if|else|import|' r'with(?:(?:out)?\s*context)?|scoped|ignore\s+missing)\b', Keyword), (r'(loop|block|super|forloop)\b', Name.Builtin), (r'[a-zA-Z_][\w-]*', Name.Variable), (r'\.\w+', Name.Variable), (r':?"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r":?'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'([{}()\[\]+\-*/%,:~]|[><=]=?|!=)', Operator), (r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number), ], 'var': [ (r'\s+', Text), (r'(-?)(\}\})', bygroups(Text, Comment.Preproc), '#pop'), include('varnames') ], 'block': [ (r'\s+', Text), (r'(-?)(%\})', bygroups(Text, Comment.Preproc), '#pop'), include('varnames'), (r'.', Punctuation) ] }
def analyse_text(text): rv = 0.0 if re.search(r'\{%\s*(block|extends)', text) is not None: rv += 0.4 if re.search(r'\{%\s*if\s*.*?%\}', text) is not None: rv += 0.1 if re.search(r'\{\{.*?\}\}', text) is not None: rv += 0.1 return rv
class MyghtyLexer(RegexLexer): """ Generic myghty templates lexer. Code that isn't Myghty markup is yielded as `Token.Other`. """
name = 'Myghty' url = 'http://www.myghty.org/' aliases = ['myghty'] filenames = ['*.myt', 'autodelegate'] mimetypes = ['application/x-myghty'] version_added = '0.6'
tokens = { 'root': [ (r'\s+', Text), (r'(?s)(<%(?:def|method))(\s*)(.*?)(>)(.*?)(</%\2\s*>)', bygroups(Name.Tag, Text, Name.Function, Name.Tag, using(this), Name.Tag)), (r'(?s)(<%\w+)(.*?)(>)(.*?)(</%\2\s*>)', bygroups(Name.Tag, Name.Function, Name.Tag, using(PythonLexer), Name.Tag)), (r'(<&[^|])(.*?)(,.*?)?(&>)', bygroups(Name.Tag, Name.Function, using(PythonLexer), Name.Tag)), (r'(?s)(<&\|)(.*?)(,.*?)?(&>)', bygroups(Name.Tag, Name.Function, using(PythonLexer), Name.Tag)), (r'</&>', Name.Tag), (r'(?s)(<%!?)(.*?)(%>)', bygroups(Name.Tag, using(PythonLexer), Name.Tag)), (r'(?<=^)#[^\n]*(\n|\Z)', Comment), (r'(?<=^)(%)([^\n]*)(\n|\Z)', bygroups(Name.Tag, using(PythonLexer), Other)), (r"""(?sx) (.+?) # anything, followed by: (?: (?<=\n)(?=[%#]) | # an eval or comment line (?=</?[%&]) | # a substitution or block or # call start or end # - don't consume (\\\n) | # an escaped newline \Z # end of string )""", bygroups(Other, Operator)), ] }
class MyghtyHtmlLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexed data with the `HtmlLexer`. """
name = 'HTML+Myghty' aliases = ['html+myghty'] mimetypes = ['text/html+myghty'] url = 'http://www.myghty.org/' version_added = '0.6'
def __init__(self, **options): super().__init__(HtmlLexer, MyghtyLexer, **options)
class MyghtyXmlLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexed data with the `XmlLexer`. """
name = 'XML+Myghty' aliases = ['xml+myghty'] mimetypes = ['application/xml+myghty'] url = 'http://www.myghty.org/' version_added = '0.6'
def __init__(self, **options): super().__init__(XmlLexer, MyghtyLexer, **options)
class MyghtyJavascriptLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexed data with the `JavascriptLexer`. """
name = 'JavaScript+Myghty' aliases = ['javascript+myghty', 'js+myghty'] mimetypes = ['application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy'] url = 'http://www.myghty.org/' version_added = '0.6'
def __init__(self, **options): super().__init__(JavascriptLexer, MyghtyLexer, **options)
class MyghtyCssLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexed data with the `CssLexer`. """
name = 'CSS+Myghty' aliases = ['css+myghty'] mimetypes = ['text/css+myghty'] url = 'http://www.myghty.org/' version_added = '0.6'
def __init__(self, **options): super().__init__(CssLexer, MyghtyLexer, **options)
class MasonLexer(RegexLexer): """ Generic mason templates lexer. Stolen from Myghty lexer. Code that isn't Mason markup is HTML. """ name = 'Mason' url = 'http://www.masonhq.com/' aliases = ['mason'] filenames = ['*.m', '*.mhtml', '*.mc', '*.mi', 'autohandler', 'dhandler'] mimetypes = ['application/x-mason'] version_added = '1.4'
tokens = { 'root': [ (r'\s+', Whitespace), (r'(?s)(<%doc>)(.*?)(</%doc>)', bygroups(Name.Tag, Comment.Multiline, Name.Tag)), (r'(?s)(<%(?:def|method))(\s*)(.*?)(>)(.*?)(</%\2\s*>)', bygroups(Name.Tag, Whitespace, Name.Function, Name.Tag, using(this), Name.Tag)), (r'(?s)(<%(\w+)(.*?)(>))(.*?)(</%\2\s*>)', bygroups(Name.Tag, None, None, None, using(PerlLexer), Name.Tag)), (r'(?s)(<&[^|])(.*?)(,.*?)?(&>)', bygroups(Name.Tag, Name.Function, using(PerlLexer), Name.Tag)), (r'(?s)(<&\|)(.*?)(,.*?)?(&>)', bygroups(Name.Tag, Name.Function, using(PerlLexer), Name.Tag)), (r'</&>', Name.Tag), (r'(?s)(<%!?)(.*?)(%>)', bygroups(Name.Tag, using(PerlLexer), Name.Tag)), (r'(?<=^)#[^\n]*(\n|\Z)', Comment), (r'(?<=^)(%)([^\n]*)(\n|\Z)', bygroups(Name.Tag, using(PerlLexer), Other)), (r"""(?sx) (.+?) # anything, followed by: (?: (?<=\n)(?=[%#]) | # an eval or comment line (?=</?[%&]) | # a substitution or block or # call start or end # - don't consume (\\\n) | # an escaped newline \Z # end of string )""", bygroups(using(HtmlLexer), Operator)), ] }
def analyse_text(text): result = 0.0 if re.search(r'</%(class|doc|init)>', text) is not None: result = 1.0 elif re.search(r'<&.+&>', text, re.DOTALL) is not None: result = 0.11 return result
class MakoLexer(RegexLexer): """ Generic mako templates lexer. Code that isn't Mako markup is yielded as `Token.Other`. """
name = 'Mako' url = 'http://www.makotemplates.org/' aliases = ['mako'] filenames = ['*.mao'] mimetypes = ['application/x-mako'] version_added = '0.7'
tokens = { 'root': [ (r'(\s*)(%)(\s*end(?:\w+))(\n|\Z)', bygroups(Text.Whitespace, Comment.Preproc, Keyword, Other)), (r'(\s*)(%)([^\n]*)(\n|\Z)', bygroups(Text.Whitespace, Comment.Preproc, using(PythonLexer), Other)), (r'(\s*)(##[^\n]*)(\n|\Z)', bygroups(Text.Whitespace, Comment.Single, Text.Whitespace)), (r'(?s)<%doc>.*?</%doc>', Comment.Multiline), (r'(<%)([\w.:]+)', bygroups(Comment.Preproc, Name.Builtin), 'tag'), (r'(</%)([\w.:]+)(>)', bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc)), (r'<%(?=([\w.:]+))', Comment.Preproc, 'ondeftags'), (r'(?s)(<%(?:!?))(.*?)(%>)', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'(\$\{)(.*?)(\})', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'''(?sx) (.+?) # anything, followed by: (?: (?<=\n)(?=%|\#\#) | # an eval or comment line (?=\#\*) | # multiline comment (?=</?%) | # a python block # call start or end (?=\$\{) | # a substitution (?<=\n)(?=\s*%) | # - don't consume (\\\n) | # an escaped newline \Z # end of string ) ''', bygroups(Other, Operator)), (r'\s+', Text), ], 'ondeftags': [ (r'<%', Comment.Preproc), (r'(?<=<%)(include|inherit|namespace|page)', Name.Builtin), include('tag'), ], 'tag': [ (r'((?:\w+)\s*=)(\s*)(".*?")', bygroups(Name.Attribute, Text, String)), (r'/?\s*>', Comment.Preproc, '#pop'), (r'\s+', Text), ], 'attr': [ ('".*?"', String, '#pop'), ("'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop'), ], }
class MakoHtmlLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexed data with the `HtmlLexer`. """
name = 'HTML+Mako' aliases = ['html+mako'] mimetypes = ['text/html+mako'] url = 'http://www.makotemplates.org/' version_added = '0.7'
def __init__(self, **options): super().__init__(HtmlLexer, MakoLexer, **options)
class MakoXmlLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexed data with the `XmlLexer`. """
name = 'XML+Mako' aliases = ['xml+mako'] mimetypes = ['application/xml+mako'] url = 'http://www.makotemplates.org/' version_added = '0.7'
def __init__(self, **options): super().__init__(XmlLexer, MakoLexer, **options)
class MakoJavascriptLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexed data with the `JavascriptLexer`. """
name = 'JavaScript+Mako' aliases = ['javascript+mako', 'js+mako'] mimetypes = ['application/x-javascript+mako', 'text/x-javascript+mako', 'text/javascript+mako'] url = 'http://www.makotemplates.org/' version_added = '0.7'
def __init__(self, **options): super().__init__(JavascriptLexer, MakoLexer, **options)
class MakoCssLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexed data with the `CssLexer`. """
name = 'CSS+Mako' aliases = ['css+mako'] mimetypes = ['text/css+mako'] url = 'http://www.makotemplates.org/' version_added = '0.7'
def __init__(self, **options): super().__init__(CssLexer, MakoLexer, **options)
# Genshi and Cheetah lexers courtesy of Matt Good.
class CheetahPythonLexer(Lexer): """ Lexer for handling Cheetah's special $ tokens in Python syntax. """
def get_tokens_unprocessed(self, text): pylexer = PythonLexer(**self.options) for pos, type_, value in pylexer.get_tokens_unprocessed(text): if type_ == Token.Error and value == '$': type_ = Comment.Preproc yield pos, type_, value
class CheetahLexer(RegexLexer): """ Generic cheetah templates lexer. Code that isn't Cheetah markup is yielded as `Token.Other`. This also works for `spitfire templates`_ which use the same syntax.
.. _spitfire templates: http://code.google.com/p/spitfire/ """
name = 'Cheetah' url = 'http://www.cheetahtemplate.org/' aliases = ['cheetah', 'spitfire'] filenames = ['*.tmpl', '*.spt'] mimetypes = ['application/x-cheetah', 'application/x-spitfire'] version_added = ''
tokens = { 'root': [ (r'(##[^\n]*)$', (bygroups(Comment))), (r'#[*](.|\n)*?[*]#', Comment), (r'#end[^#\n]*(?:#|$)', Comment.Preproc), (r'#slurp$', Comment.Preproc), (r'(#[a-zA-Z]+)([^#\n]*)(#|$)', (bygroups(Comment.Preproc, using(CheetahPythonLexer), Comment.Preproc))), # TODO support other Python syntax like $foo['bar'] (r'(\$)([a-zA-Z_][\w.]*\w)', bygroups(Comment.Preproc, using(CheetahPythonLexer))), (r'(?s)(\$\{!?)(.*?)(\})', bygroups(Comment.Preproc, using(CheetahPythonLexer), Comment.Preproc)), (r'''(?sx) (.+?) # anything, followed by: (?: (?=\#[#a-zA-Z]*) | # an eval comment (?=\$[a-zA-Z_{]) | # a substitution \Z # end of string ) ''', Other), (r'\s+', Text), ], }
class CheetahHtmlLexer(DelegatingLexer): """ Subclass of the `CheetahLexer` that highlights unlexed data with the `HtmlLexer`. """
name = 'HTML+Cheetah' aliases = ['html+cheetah', 'html+spitfire', 'htmlcheetah'] mimetypes = ['text/html+cheetah', 'text/html+spitfire'] url = 'http://www.cheetahtemplate.org/' version_added = ''
def __init__(self, **options): super().__init__(HtmlLexer, CheetahLexer, **options)
class CheetahXmlLexer(DelegatingLexer): """ Subclass of the `CheetahLexer` that highlights unlexed data with the `XmlLexer`. """
name = 'XML+Cheetah' aliases = ['xml+cheetah', 'xml+spitfire'] mimetypes = ['application/xml+cheetah', 'application/xml+spitfire'] url = 'http://www.cheetahtemplate.org/' version_added = ''
def __init__(self, **options): super().__init__(XmlLexer, CheetahLexer, **options)
class CheetahJavascriptLexer(DelegatingLexer): """ Subclass of the `CheetahLexer` that highlights unlexed data with the `JavascriptLexer`. """
name = 'JavaScript+Cheetah' aliases = ['javascript+cheetah', 'js+cheetah', 'javascript+spitfire', 'js+spitfire'] mimetypes = ['application/x-javascript+cheetah', 'text/x-javascript+cheetah', 'text/javascript+cheetah', 'application/x-javascript+spitfire', 'text/x-javascript+spitfire', 'text/javascript+spitfire'] url = 'http://www.cheetahtemplate.org/' version_added = ''
def __init__(self, **options): super().__init__(JavascriptLexer, CheetahLexer, **options)
class GenshiTextLexer(RegexLexer): """ A lexer that highlights genshi text templates. """
name = 'Genshi Text' url = 'https://genshi.edgewall.org/' aliases = ['genshitext'] mimetypes = ['application/x-genshi-text', 'text/x-genshi'] version_added = ''
tokens = { 'root': [ (r'[^#$\s]+', Other), (r'^(\s*)(##.*)$', bygroups(Text, Comment)), (r'^(\s*)(#)', bygroups(Text, Comment.Preproc), 'directive'), include('variable'), (r'[#$\s]', Other), ], 'directive': [ (r'\n', Text, '#pop'), (r'(?:def|for|if)\s+.*', using(PythonLexer), '#pop'), (r'(choose|when|with)([^\S\n]+)(.*)', bygroups(Keyword, Text, using(PythonLexer)), '#pop'), (r'(choose|otherwise)\b', Keyword, '#pop'), (r'(end\w*)([^\S\n]*)(.*)', bygroups(Keyword, Text, Comment), '#pop'), ], 'variable': [ (r'(?<!\$)(\$\{)(.+?)(\})', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'(?<!\$)(\$)([a-zA-Z_][\w.]*)', Name.Variable), ] }
class GenshiMarkupLexer(RegexLexer): """ Base lexer for Genshi markup, used by `HtmlGenshiLexer` and `GenshiLexer`. """
flags = re.DOTALL
tokens = { 'root': [ (r'[^<$]+', Other), (r'(<\?python)(.*?)(\?>)', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), # yield style and script blocks as Other (r'<\s*(script|style)\s*.*?>.*?<\s*/\1\s*>', Other), (r'<\s*py:[a-zA-Z0-9]+', Name.Tag, 'pytag'), (r'<\s*[a-zA-Z0-9:.]+', Name.Tag, 'tag'), include('variable'), (r'[<$]', Other), ], 'pytag': [ (r'\s+', Text), (r'[\w:-]+\s*=', Name.Attribute, 'pyattr'), (r'/?\s*>', Name.Tag, '#pop'), ], 'pyattr': [ ('(")(.*?)(")', bygroups(String, using(PythonLexer), String), '#pop'), ("(')(.*?)(')", bygroups(String, using(PythonLexer), String), '#pop'), (r'[^\s>]+', String, '#pop'), ], 'tag': [ (r'\s+', Text), (r'py:[\w-]+\s*=', Name.Attribute, 'pyattr'), (r'[\w:-]+\s*=', Name.Attribute, 'attr'), (r'/?\s*>', Name.Tag, '#pop'), ], 'attr': [ ('"', String, 'attr-dstring'), ("'", String, 'attr-sstring'), (r'[^\s>]*', String, '#pop') ], 'attr-dstring': [ ('"', String, '#pop'), include('strings'), ("'", String) ], 'attr-sstring': [ ("'", String, '#pop'), include('strings'), ("'", String) ], 'strings': [ ('[^"\'$]+', String), include('variable') ], 'variable': [ (r'(?<!\$)(\$\{)(.+?)(\})', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'(?<!\$)(\$)([a-zA-Z_][\w\.]*)', Name.Variable), ] }
class HtmlGenshiLexer(DelegatingLexer): """ A lexer that highlights `genshi <https://genshi.edgewall.org/>`_ and `kid <http://kid-templating.org/>`_ kid HTML templates. """
name = 'HTML+Genshi' aliases = ['html+genshi', 'html+kid'] version_added = '' alias_filenames = ['*.html', '*.htm', '*.xhtml'] mimetypes = ['text/html+genshi'] url = 'https://genshi.edgewall.org/'
def __init__(self, **options): super().__init__(HtmlLexer, GenshiMarkupLexer, **options)
def analyse_text(text): rv = 0.0 if re.search(r'\$\{.*?\}', text) is not None: rv += 0.2 if re.search(r'py:(.*?)=["\']', text) is not None: rv += 0.2 return rv + HtmlLexer.analyse_text(text) - 0.01
class GenshiLexer(DelegatingLexer): """ A lexer that highlights `genshi <https://genshi.edgewall.org/>`_ and `kid <http://kid-templating.org/>`_ kid XML templates. """
name = 'Genshi' aliases = ['genshi', 'kid', 'xml+genshi', 'xml+kid'] filenames = ['*.kid'] version_added = '' alias_filenames = ['*.xml'] mimetypes = ['application/x-genshi', 'application/x-kid'] url = 'https://genshi.edgewall.org/'
def __init__(self, **options): super().__init__(XmlLexer, GenshiMarkupLexer, **options)
def analyse_text(text): rv = 0.0 if re.search(r'\$\{.*?\}', text) is not None: rv += 0.2 if re.search(r'py:(.*?)=["\']', text) is not None: rv += 0.2 return rv + XmlLexer.analyse_text(text) - 0.01
class JavascriptGenshiLexer(DelegatingLexer): """ A lexer that highlights javascript code in genshi text templates. """
name = 'JavaScript+Genshi Text' aliases = ['js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'] version_added = '' alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi'] url = 'https://genshi.edgewall.org'
def __init__(self, **options): super().__init__(JavascriptLexer, GenshiTextLexer, **options)
def analyse_text(text): return GenshiLexer.analyse_text(text) - 0.05
class CssGenshiLexer(DelegatingLexer): """ A lexer that highlights CSS definitions in genshi text templates. """
name = 'CSS+Genshi Text' aliases = ['css+genshitext', 'css+genshi'] version_added = '' alias_filenames = ['*.css'] mimetypes = ['text/css+genshi'] url = 'https://genshi.edgewall.org'
def __init__(self, **options): super().__init__(CssLexer, GenshiTextLexer, **options)
def analyse_text(text): return GenshiLexer.analyse_text(text) - 0.05
class RhtmlLexer(DelegatingLexer): """ Subclass of the ERB lexer that highlights the unlexed data with the html lexer.
Nested Javascript and CSS is highlighted too. """
name = 'RHTML' aliases = ['rhtml', 'html+erb', 'html+ruby'] filenames = ['*.rhtml'] version_added = '' alias_filenames = ['*.html', '*.htm', '*.xhtml'] mimetypes = ['text/html+ruby'] url = 'https://github.com/ruby/erb'
def __init__(self, **options): super().__init__(HtmlLexer, ErbLexer, **options)
def analyse_text(text): rv = ErbLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): # one more than the XmlErbLexer returns rv += 0.5 return rv
class XmlErbLexer(DelegatingLexer): """ Subclass of `ErbLexer` which highlights data outside preprocessor directives with the `XmlLexer`. """
name = 'XML+Ruby' aliases = ['xml+ruby', 'xml+erb'] version_added = '' alias_filenames = ['*.xml'] mimetypes = ['application/xml+ruby'] url = 'https://github.com/ruby/erb'
def __init__(self, **options): super().__init__(XmlLexer, ErbLexer, **options)
def analyse_text(text): rv = ErbLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv
class CssErbLexer(DelegatingLexer): """ Subclass of `ErbLexer` which highlights unlexed data with the `CssLexer`. """
name = 'CSS+Ruby' aliases = ['css+ruby', 'css+erb'] version_added = '' alias_filenames = ['*.css'] mimetypes = ['text/css+ruby'] url = 'https://github.com/ruby/erb'
def __init__(self, **options): super().__init__(CssLexer, ErbLexer, **options)
def analyse_text(text): return ErbLexer.analyse_text(text) - 0.05
class JavascriptErbLexer(DelegatingLexer): """ Subclass of `ErbLexer` which highlights unlexed data with the `JavascriptLexer`. """
name = 'JavaScript+Ruby' aliases = ['javascript+ruby', 'js+ruby', 'javascript+erb', 'js+erb'] version_added = '' alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby'] url = 'https://github.com/ruby/erb'
def __init__(self, **options): super().__init__(JavascriptLexer, ErbLexer, **options)
def analyse_text(text): return ErbLexer.analyse_text(text) - 0.05
class HtmlPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` that highlights unhandled data with the `HtmlLexer`.
Nested Javascript and CSS is highlighted too. """
name = 'HTML+PHP' aliases = ['html+php'] filenames = ['*.phtml'] version_added = '' alias_filenames = ['*.php', '*.html', '*.htm', '*.xhtml', '*.php[345]'] mimetypes = ['application/x-php', 'application/x-httpd-php', 'application/x-httpd-php3', 'application/x-httpd-php4', 'application/x-httpd-php5'] url = 'https://www.php.net'
def __init__(self, **options): super().__init__(HtmlLexer, PhpLexer, **options)
def analyse_text(text): rv = PhpLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): rv += 0.5 return rv
class XmlPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` that highlights unhandled data with the `XmlLexer`. """
name = 'XML+PHP' aliases = ['xml+php'] version_added = '' alias_filenames = ['*.xml', '*.php', '*.php[345]'] mimetypes = ['application/xml+php'] url = 'https://www.php.net'
def __init__(self, **options): super().__init__(XmlLexer, PhpLexer, **options)
def analyse_text(text): rv = PhpLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv
class CssPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` which highlights unmatched data with the `CssLexer`. """
name = 'CSS+PHP' aliases = ['css+php'] version_added = '' alias_filenames = ['*.css'] mimetypes = ['text/css+php'] url = 'https://www.php.net'
def __init__(self, **options): super().__init__(CssLexer, PhpLexer, **options)
def analyse_text(text): return PhpLexer.analyse_text(text) - 0.05
class JavascriptPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` which highlights unmatched data with the `JavascriptLexer`. """
name = 'JavaScript+PHP' aliases = ['javascript+php', 'js+php'] version_added = '' alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+php', 'text/x-javascript+php', 'text/javascript+php'] url = 'https://www.php.net'
def __init__(self, **options): super().__init__(JavascriptLexer, PhpLexer, **options)
def analyse_text(text): return PhpLexer.analyse_text(text)
class HtmlSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `HtmlLexer`.
Nested Javascript and CSS is highlighted too. """
name = 'HTML+Smarty' aliases = ['html+smarty'] version_added = '' alias_filenames = ['*.html', '*.htm', '*.xhtml', '*.tpl'] mimetypes = ['text/html+smarty'] url = 'https://www.smarty.net/'
def __init__(self, **options): super().__init__(HtmlLexer, SmartyLexer, **options)
def analyse_text(text): rv = SmartyLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): rv += 0.5 return rv
class XmlSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `XmlLexer`. """
name = 'XML+Smarty' aliases = ['xml+smarty'] version_added = '' alias_filenames = ['*.xml', '*.tpl'] mimetypes = ['application/xml+smarty'] url = 'https://www.smarty.net/'
def __init__(self, **options): super().__init__(XmlLexer, SmartyLexer, **options)
def analyse_text(text): rv = SmartyLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv
class CssSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `CssLexer`. """
name = 'CSS+Smarty' aliases = ['css+smarty'] version_added = '' alias_filenames = ['*.css', '*.tpl'] mimetypes = ['text/css+smarty'] url = 'https://www.smarty.net/'
def __init__(self, **options): super().__init__(CssLexer, SmartyLexer, **options)
def analyse_text(text): return SmartyLexer.analyse_text(text) - 0.05
class JavascriptSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `JavascriptLexer`. """
name = 'JavaScript+Smarty' aliases = ['javascript+smarty', 'js+smarty'] version_added = '' alias_filenames = ['*.js', '*.tpl'] mimetypes = ['application/x-javascript+smarty', 'text/x-javascript+smarty', 'text/javascript+smarty'] url = 'https://www.smarty.net/'
def __init__(self, **options): super().__init__(JavascriptLexer, SmartyLexer, **options)
def analyse_text(text): return SmartyLexer.analyse_text(text) - 0.05
class HtmlDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `HtmlLexer`.
Nested Javascript and CSS is highlighted too. """
name = 'HTML+Django/Jinja' aliases = ['html+django', 'html+jinja', 'htmldjango'] filenames = ['*.html.j2', '*.htm.j2', '*.xhtml.j2', '*.html.jinja2', '*.htm.jinja2', '*.xhtml.jinja2'] version_added = '' alias_filenames = ['*.html', '*.htm', '*.xhtml'] mimetypes = ['text/html+django', 'text/html+jinja'] url = 'https://www.djangoproject.com/documentation/templates'
def __init__(self, **options): super().__init__(HtmlLexer, DjangoLexer, **options)
def analyse_text(text): rv = DjangoLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): rv += 0.5 return rv
class XmlDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `XmlLexer`. """
name = 'XML+Django/Jinja' aliases = ['xml+django', 'xml+jinja'] filenames = ['*.xml.j2', '*.xml.jinja2'] version_added = '' alias_filenames = ['*.xml'] mimetypes = ['application/xml+django', 'application/xml+jinja'] url = 'https://www.djangoproject.com/documentation/templates'
def __init__(self, **options): super().__init__(XmlLexer, DjangoLexer, **options)
def analyse_text(text): rv = DjangoLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv
class CssDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `CssLexer`. """
name = 'CSS+Django/Jinja' aliases = ['css+django', 'css+jinja'] filenames = ['*.css.j2', '*.css.jinja2'] version_added = '' alias_filenames = ['*.css'] mimetypes = ['text/css+django', 'text/css+jinja'] url = 'https://www.djangoproject.com/documentation/templates'
def __init__(self, **options): super().__init__(CssLexer, DjangoLexer, **options)
def analyse_text(text): return DjangoLexer.analyse_text(text) - 0.05
class JavascriptDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `JavascriptLexer`. """
name = 'JavaScript+Django/Jinja' aliases = ['javascript+django', 'js+django', 'javascript+jinja', 'js+jinja'] filenames = ['*.js.j2', '*.js.jinja2'] version_added = '' alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja'] url = 'https://www.djangoproject.com/documentation/templates'
def __init__(self, **options): super().__init__(JavascriptLexer, DjangoLexer, **options)
def analyse_text(text): return DjangoLexer.analyse_text(text) - 0.05
class JspRootLexer(RegexLexer): """ Base for the `JspLexer`. Yields `Token.Other` for area outside of JSP tags.
.. versionadded:: 0.7 """
tokens = { 'root': [ (r'<%\S?', Keyword, 'sec'), # FIXME: I want to make these keywords but still parse attributes. (r'</?jsp:(forward|getProperty|include|plugin|setProperty|useBean).*?>', Keyword), (r'[^<]+', Other), (r'<', Other), ], 'sec': [ (r'%>', Keyword, '#pop'), # note: '\w\W' != '.' without DOTALL. (r'[\w\W]+?(?=%>|\Z)', using(JavaLexer)), ], }
class JspLexer(DelegatingLexer): """ Lexer for Java Server Pages. """ name = 'Java Server Page' aliases = ['jsp'] filenames = ['*.jsp'] mimetypes = ['application/x-jsp'] url = 'https://projects.eclipse.org/projects/ee4j.jsp' version_added = '0.7'
def __init__(self, **options): super().__init__(XmlLexer, JspRootLexer, **options)
def analyse_text(text): rv = JavaLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 if '<%' in text and '%>' in text: rv += 0.1 return rv
class EvoqueLexer(RegexLexer): """ For files using the Evoque templating system. """ name = 'Evoque' aliases = ['evoque'] filenames = ['*.evoque'] mimetypes = ['application/x-evoque'] url = 'https://gizmojo.org/templating' version_added = '1.1'
flags = re.DOTALL
tokens = { 'root': [ (r'[^#$]+', Other), (r'#\[', Comment.Multiline, 'comment'), (r'\$\$', Other), # svn keywords (r'\$\w+:[^$\n]*\$', Comment.Multiline), # directives: begin, end (r'(\$)(begin|end)(\{(%)?)(.*?)((?(4)%)\})', bygroups(Punctuation, Name.Builtin, Punctuation, None, String, Punctuation)), # directives: evoque, overlay # see doc for handling first name arg: /directives/evoque/ # + minor inconsistency: the "name" in e.g. $overlay{name=site_base} # should be using(PythonLexer), not passed out as String (r'(\$)(evoque|overlay)(\{(%)?)(\s*[#\w\-"\'.]+)?' r'(.*?)((?(4)%)\})', bygroups(Punctuation, Name.Builtin, Punctuation, None, String, using(PythonLexer), Punctuation)), # directives: if, for, prefer, test (r'(\$)(\w+)(\{(%)?)(.*?)((?(4)%)\})', bygroups(Punctuation, Name.Builtin, Punctuation, None, using(PythonLexer), Punctuation)), # directive clauses (no {} expression) (r'(\$)(else|rof|fi)', bygroups(Punctuation, Name.Builtin)), # expressions (r'(\$\{(%)?)(.*?)((!)(.*?))?((?(2)%)\})', bygroups(Punctuation, None, using(PythonLexer), Name.Builtin, None, None, Punctuation)), (r'#', Other), ], 'comment': [ (r'[^\]#]', Comment.Multiline), (r'#\[', Comment.Multiline, '#push'), (r'\]#', Comment.Multiline, '#pop'), (r'[\]#]', Comment.Multiline) ], }
def analyse_text(text): """Evoque templates use $evoque, which is unique.""" if '$evoque' in text: return 1
class EvoqueHtmlLexer(DelegatingLexer): """ Subclass of the `EvoqueLexer` that highlights unlexed data with the `HtmlLexer`. """ name = 'HTML+Evoque' aliases = ['html+evoque'] alias_filenames = ['*.html'] mimetypes = ['text/html+evoque'] url = 'https://gizmojo.org/templating' version_added = '1.1'
def __init__(self, **options): super().__init__(HtmlLexer, EvoqueLexer, **options)
def analyse_text(text): return EvoqueLexer.analyse_text(text)
class EvoqueXmlLexer(DelegatingLexer): """ Subclass of the `EvoqueLexer` that highlights unlexed data with the `XmlLexer`. """ name = 'XML+Evoque' aliases = ['xml+evoque'] alias_filenames = ['*.xml'] mimetypes = ['application/xml+evoque'] url = 'https://gizmojo.org/templating' version_added = '1.1'
def __init__(self, **options): super().__init__(XmlLexer, EvoqueLexer, **options)
def analyse_text(text): return EvoqueLexer.analyse_text(text)
class ColdfusionLexer(RegexLexer): """ Coldfusion statements """ name = 'cfstatement' aliases = ['cfs'] filenames = [] mimetypes = [] url = 'https://www.adobe.com/products/coldfusion-family.html' version_added = ''
flags = re.IGNORECASE
tokens = { 'root': [ (r'//.*?\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), (r'\+\+|--', Operator), (r'[-+*/^&=!]', Operator), (r'<=|>=|<|>|==', Operator), (r'mod\b', Operator), (r'(eq|lt|gt|lte|gte|not|is|and|or)\b', Operator), (r'\|\||&&', Operator), (r'\?', Operator), (r'"', String.Double, 'string'), # There is a special rule for allowing html in single quoted # strings, evidently. (r"'.*?'", String.Single), (r'\d+', Number), (r'(if|else|len|var|xml|default|break|switch|component|property|function|do|' r'try|catch|in|continue|for|return|while|required|any|array|binary|boolean|' r'component|date|guid|numeric|query|string|struct|uuid|case)\b', Keyword), (r'(true|false|null)\b', Keyword.Constant), (r'(application|session|client|cookie|super|this|variables|arguments)\b', Name.Constant), (r'([a-z_$][\w.]*)(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[a-z_$][\w.]*', Name.Variable), (r'[()\[\]{};:,.\\]', Punctuation), (r'\s+', Text), ], 'string': [ (r'""', String.Double), (r'#.+?#', String.Interp), (r'[^"#]+', String.Double), (r'#', String.Double), (r'"', String.Double, '#pop'), ], }
class ColdfusionMarkupLexer(RegexLexer): """ Coldfusion markup only """ name = 'Coldfusion' aliases = ['cf'] filenames = [] mimetypes = [] url = 'https://www.adobe.com/products/coldfusion-family.html'
tokens = { 'root': [ (r'[^<]+', Other), include('tags'), (r'<[^<>]*', Other), ], 'tags': [ (r'<!---', Comment.Multiline, 'cfcomment'), (r'(?s)<!--.*?-->', Comment), (r'<cfoutput.*?>', Name.Builtin, 'cfoutput'), (r'(?s)(<cfscript.*?>)(.+?)(</cfscript.*?>)', bygroups(Name.Builtin, using(ColdfusionLexer), Name.Builtin)), # negative lookbehind is for strings with embedded > (r'(?s)(</?cf(?:component|include|if|else|elseif|loop|return|' r'dbinfo|dump|abort|location|invoke|throw|file|savecontent|' r'mailpart|mail|header|content|zip|image|lock|argument|try|' r'catch|break|directory|http|set|function|param)\b)(.*?)((?<!\\)>)', bygroups(Name.Builtin, using(ColdfusionLexer), Name.Builtin)), ], 'cfoutput': [ (r'[^#<]+', Other), (r'(#)(.*?)(#)', bygroups(Punctuation, using(ColdfusionLexer), Punctuation)), # (r'<cfoutput.*?>', Name.Builtin, '#push'), (r'</cfoutput.*?>', Name.Builtin, '#pop'), include('tags'), (r'(?s)<[^<>]*', Other), (r'#', Other), ], 'cfcomment': [ (r'<!---', Comment.Multiline, '#push'), (r'--->', Comment.Multiline, '#pop'), (r'([^<-]|<(?!!---)|-(?!-->))+', Comment.Multiline), ], }
class ColdfusionHtmlLexer(DelegatingLexer): """ Coldfusion markup in html """ name = 'Coldfusion HTML' aliases = ['cfm'] filenames = ['*.cfm', '*.cfml'] mimetypes = ['application/x-coldfusion'] url = 'https://www.adobe.com/products/coldfusion-family.html' version_added = ''
def __init__(self, **options): super().__init__(HtmlLexer, ColdfusionMarkupLexer, **options)
class ColdfusionCFCLexer(DelegatingLexer): """ Coldfusion markup/script components """ name = 'Coldfusion CFC' aliases = ['cfc'] filenames = ['*.cfc'] mimetypes = [] url = 'https://www.adobe.com/products/coldfusion-family.html' version_added = '2.0'
def __init__(self, **options): super().__init__(ColdfusionHtmlLexer, ColdfusionLexer, **options)
class SspLexer(DelegatingLexer): """ Lexer for Scalate Server Pages. """ name = 'Scalate Server Page' aliases = ['ssp'] filenames = ['*.ssp'] mimetypes = ['application/x-ssp'] url = 'https://scalate.github.io/scalate/' version_added = '1.4'
def __init__(self, **options): super().__init__(XmlLexer, JspRootLexer, **options)
def analyse_text(text): rv = 0.0 if re.search(r'val \w+\s*:', text): rv += 0.6 if looks_like_xml(text): rv += 0.2 if '<%' in text and '%>' in text: rv += 0.1 return rv
class TeaTemplateRootLexer(RegexLexer): """ Base for the `TeaTemplateLexer`. Yields `Token.Other` for area outside of code blocks.
.. versionadded:: 1.5 """
tokens = { 'root': [ (r'<%\S?', Keyword, 'sec'), (r'[^<]+', Other), (r'<', Other), ], 'sec': [ (r'%>', Keyword, '#pop'), # note: '\w\W' != '.' without DOTALL. (r'[\w\W]+?(?=%>|\Z)', using(TeaLangLexer)), ], }
class TeaTemplateLexer(DelegatingLexer): """ Lexer for Tea Templates. """ name = 'Tea' aliases = ['tea'] filenames = ['*.tea'] mimetypes = ['text/x-tea'] url = 'https://github.com/teatrove/teatrove' version_added = '1.5'
def __init__(self, **options): super().__init__(XmlLexer, TeaTemplateRootLexer, **options)
def analyse_text(text): rv = TeaLangLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 if '<%' in text and '%>' in text: rv += 0.1 return rv
class LassoHtmlLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `HtmlLexer`.
Nested JavaScript and CSS is also highlighted. """
name = 'HTML+Lasso' aliases = ['html+lasso'] version_added = '1.6' alias_filenames = ['*.html', '*.htm', '*.xhtml', '*.lasso', '*.lasso[89]', '*.incl', '*.inc', '*.las'] mimetypes = ['text/html+lasso', 'application/x-httpd-lasso', 'application/x-httpd-lasso[89]'] url = 'https://www.lassosoft.com'
def __init__(self, **options): super().__init__(HtmlLexer, LassoLexer, **options)
def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): # same as HTML lexer rv += 0.5 return rv
class LassoXmlLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `XmlLexer`. """
name = 'XML+Lasso' aliases = ['xml+lasso'] version_added = '1.6' alias_filenames = ['*.xml', '*.lasso', '*.lasso[89]', '*.incl', '*.inc', '*.las'] mimetypes = ['application/xml+lasso'] url = 'https://www.lassosoft.com'
def __init__(self, **options): super().__init__(XmlLexer, LassoLexer, **options)
def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv
class LassoCssLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `CssLexer`. """
name = 'CSS+Lasso' aliases = ['css+lasso'] version_added = '1.6' alias_filenames = ['*.css'] mimetypes = ['text/css+lasso'] url = 'https://www.lassosoft.com'
def __init__(self, **options): options['requiredelimiters'] = True super().__init__(CssLexer, LassoLexer, **options)
def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.05 if re.search(r'\w+:[^;]+;', text): rv += 0.1 if 'padding:' in text: rv += 0.1 return rv
class LassoJavascriptLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `JavascriptLexer`. """
name = 'JavaScript+Lasso' aliases = ['javascript+lasso', 'js+lasso'] version_added = '1.6' alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+lasso', 'text/x-javascript+lasso', 'text/javascript+lasso'] url = 'https://www.lassosoft.com'
def __init__(self, **options): options['requiredelimiters'] = True super().__init__(JavascriptLexer, LassoLexer, **options)
def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.05 return rv
class HandlebarsLexer(RegexLexer): """ Generic handlebars template lexer.
Highlights only the Handlebars template tags (stuff between `{{` and `}}`). Everything else is left for a delegating lexer. """
name = "Handlebars" url = 'https://handlebarsjs.com/' aliases = ['handlebars'] version_added = '2.0'
tokens = { 'root': [ (r'[^{]+', Other),
# Comment start {{! }} or {{!-- (r'\{\{!.*\}\}', Comment),
# HTML Escaping open {{{expression (r'(\{\{\{)(\s*)', bygroups(Comment.Special, Text), 'tag'),
# {{blockOpen {{#blockOpen {{/blockClose with optional tilde ~ (r'(\{\{)([#~/]+)([^\s}]*)', bygroups(Comment.Preproc, Number.Attribute, Number.Attribute), 'tag'), (r'(\{\{)(\s*)', bygroups(Comment.Preproc, Text), 'tag'), ],
'tag': [ (r'\s+', Text), # HTML Escaping close }}} (r'\}\}\}', Comment.Special, '#pop'), # blockClose}}, includes optional tilde ~ (r'(~?)(\}\})', bygroups(Number, Comment.Preproc), '#pop'),
# {{opt=something}} (r'([^\s}]+)(=)', bygroups(Name.Attribute, Operator)),
# Partials {{> ...}} (r'(>)(\s*)(@partial-block)', bygroups(Keyword, Text, Keyword)), (r'(#?>)(\s*)([\w-]+)', bygroups(Keyword, Text, Name.Variable)), (r'(>)(\s*)(\()', bygroups(Keyword, Text, Punctuation), 'dynamic-partial'),
include('generic'), ], 'dynamic-partial': [ (r'\s+', Text), (r'\)', Punctuation, '#pop'),
(r'(lookup)(\s+)(\.|this)(\s+)', bygroups(Keyword, Text, Name.Variable, Text)), (r'(lookup)(\s+)(\S+)', bygroups(Keyword, Text, using(this, state='variable'))), (r'[\w-]+', Name.Function),
include('generic'), ], 'variable': [ (r'[()/@a-zA-Z][\w-]*', Name.Variable), (r'\.[\w-]+', Name.Variable), (r'(this\/|\.\/|(\.\.\/)+)[\w-]+', Name.Variable), ], 'generic': [ include('variable'),
# borrowed from DjangoLexer (r':?"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r":?'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number), ] }
class HandlebarsHtmlLexer(DelegatingLexer): """ Subclass of the `HandlebarsLexer` that highlights unlexed data with the `HtmlLexer`. """
name = "HTML+Handlebars" aliases = ["html+handlebars"] filenames = ['*.handlebars', '*.hbs'] mimetypes = ['text/html+handlebars', 'text/x-handlebars-template'] url = 'https://handlebarsjs.com/' version_added = '2.0'
def __init__(self, **options): super().__init__(HtmlLexer, HandlebarsLexer, **options)
class YamlJinjaLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `YamlLexer`.
Commonly used in Saltstack salt states. """
name = 'YAML+Jinja' aliases = ['yaml+jinja', 'salt', 'sls'] filenames = ['*.sls', '*.yaml.j2', '*.yml.j2', '*.yaml.jinja2', '*.yml.jinja2'] mimetypes = ['text/x-yaml+jinja', 'text/x-sls'] url = 'https://jinja.palletsprojects.com' version_added = '2.0'
def __init__(self, **options): super().__init__(YamlLexer, DjangoLexer, **options)
class LiquidLexer(RegexLexer): """ Lexer for Liquid templates. """ name = 'liquid' url = 'https://www.rubydoc.info/github/Shopify/liquid' aliases = ['liquid'] filenames = ['*.liquid'] version_added = '2.0'
tokens = { 'root': [ (r'[^{]+', Text), # tags and block tags (r'(\{%)(\s*)', bygroups(Punctuation, Whitespace), 'tag-or-block'), # output tags (r'(\{\{)(\s*)([^\s}]+)', bygroups(Punctuation, Whitespace, using(this, state = 'generic')), 'output'), (r'\{', Text) ],
'tag-or-block': [ # builtin logic blocks (r'(if|unless|elsif|case)(?=\s+)', Keyword.Reserved, 'condition'), (r'(when)(\s+)', bygroups(Keyword.Reserved, Whitespace), combined('end-of-block', 'whitespace', 'generic')), (r'(else)(\s*)(%\})', bygroups(Keyword.Reserved, Whitespace, Punctuation), '#pop'),
# other builtin blocks (r'(capture)(\s+)([^\s%]+)(\s*)(%\})', bygroups(Name.Tag, Whitespace, using(this, state = 'variable'), Whitespace, Punctuation), '#pop'), (r'(comment)(\s*)(%\})', bygroups(Name.Tag, Whitespace, Punctuation), 'comment'), (r'(raw)(\s*)(%\})', bygroups(Name.Tag, Whitespace, Punctuation), 'raw'),
# end of block (r'(end(case|unless|if))(\s*)(%\})', bygroups(Keyword.Reserved, None, Whitespace, Punctuation), '#pop'), (r'(end([^\s%]+))(\s*)(%\})', bygroups(Name.Tag, None, Whitespace, Punctuation), '#pop'),
# builtin tags (assign and include are handled together with usual tags) (r'(cycle)(\s+)(?:([^\s:]*)(:))?(\s*)', bygroups(Name.Tag, Whitespace, using(this, state='generic'), Punctuation, Whitespace), 'variable-tag-markup'),
# other tags or blocks (r'([^\s%]+)(\s*)', bygroups(Name.Tag, Whitespace), 'tag-markup') ],
'output': [ include('whitespace'), (r'\}\}', Punctuation, '#pop'), # end of output
(r'\|', Punctuation, 'filters') ],
'filters': [ include('whitespace'), (r'\}\}', Punctuation, ('#pop', '#pop')), # end of filters and output
(r'([^\s|:]+)(:?)(\s*)', bygroups(Name.Function, Punctuation, Whitespace), 'filter-markup') ],
'filter-markup': [ (r'\|', Punctuation, '#pop'), include('end-of-tag'), include('default-param-markup') ],
'condition': [ include('end-of-block'), include('whitespace'),
(r'([^\s=!><]+)(\s*)([=!><]=?)(\s*)(\S+)(\s*)(%\})', bygroups(using(this, state = 'generic'), Whitespace, Operator, Whitespace, using(this, state = 'generic'), Whitespace, Punctuation)), (r'\b!', Operator), (r'\bnot\b', Operator.Word), (r'([\w.\'"]+)(\s+)(contains)(\s+)([\w.\'"]+)', bygroups(using(this, state = 'generic'), Whitespace, Operator.Word, Whitespace, using(this, state = 'generic'))),
include('generic'), include('whitespace') ],
'generic-value': [ include('generic'), include('end-at-whitespace') ],
'operator': [ (r'(\s*)((=|!|>|<)=?)(\s*)', bygroups(Whitespace, Operator, None, Whitespace), '#pop'), (r'(\s*)(\bcontains\b)(\s*)', bygroups(Whitespace, Operator.Word, Whitespace), '#pop'), ],
'end-of-tag': [ (r'\}\}', Punctuation, '#pop') ],
'end-of-block': [ (r'%\}', Punctuation, ('#pop', '#pop')) ],
'end-at-whitespace': [ (r'\s+', Whitespace, '#pop') ],
# states for unknown markup 'param-markup': [ include('whitespace'), # params with colons or equals (r'([^\s=:]+)(\s*)(=|:)', bygroups(Name.Attribute, Whitespace, Operator)), # explicit variables (r'(\{\{)(\s*)([^\s}])(\s*)(\}\})', bygroups(Punctuation, Whitespace, using(this, state = 'variable'), Whitespace, Punctuation)),
include('string'), include('number'), include('keyword'), (r',', Punctuation) ],
'default-param-markup': [ include('param-markup'), (r'.', Text) # fallback for switches / variables / un-quoted strings / ... ],
'variable-param-markup': [ include('param-markup'), include('variable'), (r'.', Text) # fallback ],
'tag-markup': [ (r'%\}', Punctuation, ('#pop', '#pop')), # end of tag include('default-param-markup') ],
'variable-tag-markup': [ (r'%\}', Punctuation, ('#pop', '#pop')), # end of tag include('variable-param-markup') ],
# states for different values types 'keyword': [ (r'\b(false|true)\b', Keyword.Constant) ],
'variable': [ (r'[a-zA-Z_]\w*', Name.Variable), (r'(?<=\w)\.(?=\w)', Punctuation) ],
'string': [ (r"'[^']*'", String.Single), (r'"[^"]*"', String.Double) ],
'number': [ (r'\d+\.\d+', Number.Float), (r'\d+', Number.Integer) ],
'generic': [ # decides for variable, string, keyword or number include('keyword'), include('string'), include('number'), include('variable') ],
'whitespace': [ (r'[ \t]+', Whitespace) ],
# states for builtin blocks 'comment': [ (r'(\{%)(\s*)(endcomment)(\s*)(%\})', bygroups(Punctuation, Whitespace, Name.Tag, Whitespace, Punctuation), ('#pop', '#pop')), (r'.', Comment) ],
'raw': [ (r'[^{]+', Text), (r'(\{%)(\s*)(endraw)(\s*)(%\})', bygroups(Punctuation, Whitespace, Name.Tag, Whitespace, Punctuation), '#pop'), (r'\{', Text) ], }
class TwigLexer(RegexLexer): """ Twig template lexer.
It just highlights Twig code between the preprocessor directives, other data is left untouched by the lexer. """
name = 'Twig' aliases = ['twig'] mimetypes = ['application/x-twig'] url = 'https://twig.symfony.com' version_added = '2.0'
flags = re.M | re.S
# Note that a backslash is included in the following two patterns # PHP uses a backslash as a namespace separator _ident_char = r'[\\\w-]|[^\x00-\x7f]' _ident_begin = r'(?:[\\_a-z]|[^\x00-\x7f])' _ident_end = r'(?:' + _ident_char + ')*' _ident_inner = _ident_begin + _ident_end
tokens = { 'root': [ (r'[^{]+', Other), (r'\{\{', Comment.Preproc, 'var'), # twig comments (r'\{\#.*?\#\}', Comment), # raw twig blocks (r'(\{%)(-?\s*)(raw)(\s*-?)(%\})(.*?)' r'(\{%)(-?\s*)(endraw)(\s*-?)(%\})', bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc, Other, Comment.Preproc, Text, Keyword, Text, Comment.Preproc)), (r'(\{%)(-?\s*)(verbatim)(\s*-?)(%\})(.*?)' r'(\{%)(-?\s*)(endverbatim)(\s*-?)(%\})', bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc, Other, Comment.Preproc, Text, Keyword, Text, Comment.Preproc)), # filter blocks (rf'(\{{%)(-?\s*)(filter)(\s+)({_ident_inner})', bygroups(Comment.Preproc, Text, Keyword, Text, Name.Function), 'tag'), (r'(\{%)(-?\s*)([a-zA-Z_]\w*)', bygroups(Comment.Preproc, Text, Keyword), 'tag'), (r'\{', Other), ], 'varnames': [ (rf'(\|)(\s*)({_ident_inner})', bygroups(Operator, Text, Name.Function)), (rf'(is)(\s+)(not)?(\s*)({_ident_inner})', bygroups(Keyword, Text, Keyword, Text, Name.Function)), (r'(?i)(true|false|none|null)\b', Keyword.Pseudo), (r'(in|not|and|b-and|or|b-or|b-xor|is' r'if|elseif|else|import' r'constant|defined|divisibleby|empty|even|iterable|odd|sameas' r'matches|starts\s+with|ends\s+with)\b', Keyword), (r'(loop|block|parent)\b', Name.Builtin), (_ident_inner, Name.Variable), (r'\.' + _ident_inner, Name.Variable), (r'\.[0-9]+', Number), (r':?"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r":?'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'([{}()\[\]+\-*/,:~%]|\.\.|\?|:|\*\*|\/\/|!=|[><=]=?)', Operator), (r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number), ], 'var': [ (r'\s+', Text), (r'(-?)(\}\})', bygroups(Text, Comment.Preproc), '#pop'), include('varnames') ], 'tag': [ (r'\s+', Text), (r'(-?)(%\})', bygroups(Text, Comment.Preproc), '#pop'), include('varnames'), (r'.', Punctuation), ], }
class TwigHtmlLexer(DelegatingLexer): """ Subclass of the `TwigLexer` that highlights unlexed data with the `HtmlLexer`. """
name = "HTML+Twig" aliases = ["html+twig"] filenames = ['*.twig'] mimetypes = ['text/html+twig'] url = 'https://twig.symfony.com' version_added = '2.0'
def __init__(self, **options): super().__init__(HtmlLexer, TwigLexer, **options)
class Angular2Lexer(RegexLexer): """ Generic angular2 template lexer.
Highlights only the Angular template tags (stuff between `{{` and `}}` and special attributes: '(event)=', '[property]=', '[(twoWayBinding)]='). Everything else is left for a delegating lexer. """
name = "Angular2" url = 'https://angular.io/guide/template-syntax' aliases = ['ng2'] version_added = '2.1'
tokens = { 'root': [ (r'[^{([*#]+', Other),
# {{meal.name}} (r'(\{\{)(\s*)', bygroups(Comment.Preproc, Text), 'ngExpression'),
# (click)="deleteOrder()"; [value]="test"; [(twoWayTest)]="foo.bar" (r'([([]+)([\w:.-]+)([\])]+)(\s*)(=)(\s*)', bygroups(Punctuation, Name.Attribute, Punctuation, Text, Operator, Text), 'attr'), (r'([([]+)([\w:.-]+)([\])]+)(\s*)', bygroups(Punctuation, Name.Attribute, Punctuation, Text)),
# *ngIf="..."; #f="ngForm" (r'([*#])([\w:.-]+)(\s*)(=)(\s*)', bygroups(Punctuation, Name.Attribute, Text, Operator, Text), 'attr'), (r'([*#])([\w:.-]+)(\s*)', bygroups(Punctuation, Name.Attribute, Text)), ],
'ngExpression': [ (r'\s+(\|\s+)?', Text), (r'\}\}', Comment.Preproc, '#pop'),
# Literals (r':?(true|false)', String.Boolean), (r':?"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r":?'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number),
# Variabletext (r'[a-zA-Z][\w-]*(\(.*\))?', Name.Variable), (r'\.[\w-]+(\(.*\))?', Name.Variable),
# inline If (r'(\?)(\s*)([^}\s]+)(\s*)(:)(\s*)([^}\s]+)(\s*)', bygroups(Operator, Text, String, Text, Operator, Text, String, Text)), ], 'attr': [ ('".*?"', String, '#pop'), ("'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop'), ], }
class Angular2HtmlLexer(DelegatingLexer): """ Subclass of the `Angular2Lexer` that highlights unlexed data with the `HtmlLexer`. """
name = "HTML + Angular2" aliases = ["html+ng2"] filenames = ['*.ng2'] url = 'https://angular.io/guide/template-syntax' version_added = '2.0'
def __init__(self, **options): super().__init__(HtmlLexer, Angular2Lexer, **options)
class SqlJinjaLexer(DelegatingLexer): """ Templated SQL lexer. """
name = 'SQL+Jinja' aliases = ['sql+jinja'] filenames = ['*.sql', '*.sql.j2', '*.sql.jinja2'] url = 'https://jinja.palletsprojects.com' version_added = '2.13'
def __init__(self, **options): super().__init__(SqlLexer, DjangoLexer, **options)
def analyse_text(text): rv = 0.0 # dbt's ref function if re.search(r'\{\{\s*ref\(.*\)\s*\}\}', text): rv += 0.4 # dbt's source function if re.search(r'\{\{\s*source\(.*\)\s*\}\}', text): rv += 0.25 # Jinja macro if re.search(r'\{%-?\s*macro \w+\(.*\)\s*-?%\}', text): rv += 0.15 return rv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335""" pygments.lexers.teraterm ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Tera Term macro files.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Text, Comment, Operator, Name, String, \ Number, Keyword, Error
__all__ = ['TeraTermLexer']
class TeraTermLexer(RegexLexer): """ For Tera Term macro source code. """ name = 'Tera Term macro' url = 'https://ttssh2.osdn.jp/' aliases = ['teratermmacro', 'teraterm', 'ttl'] filenames = ['*.ttl'] mimetypes = ['text/x-teratermmacro'] version_added = '2.4'
tokens = { 'root': [ include('comments'), include('labels'), include('commands'), include('builtin-variables'), include('user-variables'), include('operators'), include('numeric-literals'), include('string-literals'), include('all-whitespace'), (r'\S', Text), ], 'comments': [ (r';[^\r\n]*', Comment.Single), (r'/\*', Comment.Multiline, 'in-comment'), ], 'in-comment': [ (r'\*/', Comment.Multiline, '#pop'), (r'[^*/]+', Comment.Multiline), (r'[*/]', Comment.Multiline) ], 'labels': [ (r'(?i)^(\s*)(:[a-z0-9_]+)', bygroups(Text.Whitespace, Name.Label)), ], 'commands': [ ( r'(?i)\b(' r'basename|' r'beep|' r'bplusrecv|' r'bplussend|' r'break|' r'bringupbox|' # 'call' is handled separately. r'callmenu|' r'changedir|' r'checksum16|' r'checksum16file|' r'checksum32|' r'checksum32file|' r'checksum8|' r'checksum8file|' r'clearscreen|' r'clipb2var|' r'closesbox|' r'closett|' r'code2str|' r'connect|' r'continue|' r'crc16|' r'crc16file|' r'crc32|' r'crc32file|' r'cygconnect|' r'delpassword|' r'delpassword2|' r'dirname|' r'dirnamebox|' r'disconnect|' r'dispstr|' r'do|' r'else|' r'elseif|' r'enablekeyb|' r'end|' r'endif|' r'enduntil|' r'endwhile|' r'exec|' r'execcmnd|' r'exit|' r'expandenv|' r'fileclose|' r'fileconcat|' r'filecopy|' r'filecreate|' r'filedelete|' r'filelock|' r'filemarkptr|' r'filenamebox|' r'fileopen|' r'fileread|' r'filereadln|' r'filerename|' r'filesearch|' r'fileseek|' r'fileseekback|' r'filestat|' r'filestrseek|' r'filestrseek2|' r'filetruncate|' r'fileunlock|' r'filewrite|' r'filewriteln|' r'findclose|' r'findfirst|' r'findnext|' r'flushrecv|' r'foldercreate|' r'folderdelete|' r'foldersearch|' r'for|' r'getdate|' r'getdir|' r'getenv|' r'getfileattr|' r'gethostname|' r'getipv4addr|' r'getipv6addr|' r'getmodemstatus|' r'getpassword|' r'getpassword2|' r'getspecialfolder|' r'gettime|' r'gettitle|' r'getttdir|' r'getttpos|' r'getver|' # 'goto' is handled separately. r'if|' r'ifdefined|' r'include|' r'inputbox|' r'int2str|' r'intdim|' r'ispassword|' r'ispassword2|' r'kmtfinish|' r'kmtget|' r'kmtrecv|' r'kmtsend|' r'listbox|' r'loadkeymap|' r'logautoclosemode|' r'logclose|' r'loginfo|' r'logopen|' r'logpause|' r'logrotate|' r'logstart|' r'logwrite|' r'loop|' r'makepath|' r'messagebox|' r'mpause|' r'next|' r'passwordbox|' r'pause|' r'quickvanrecv|' r'quickvansend|' r'random|' r'recvfile' r'recvln|' r'regexoption|' r'restoresetup|' r'return|' r'rotateleft|' r'rotateright|' r'scprecv|' r'scpsend|' r'send|' r'sendbinary|' r'sendbreak|' r'sendbroadcast|' r'sendfile|' r'sendkcode|' r'sendln|' r'sendlnbroadcast|' r'sendlnmulticast|' r'sendmulticast|' r'sendtext|' r'setbaud|' r'setdate|' r'setdebug|' r'setdir|' r'setdlgpos|' r'setdtr|' r'setecho|' r'setenv|' r'setexitcode|' r'setfileattr|' r'setflowctrl|' r'setmulticastname|' r'setpassword|' r'setpassword2|' r'setrts|' r'setserialdelaychar' r'setserialdelayline' r'setspeed|' r'setsync|' r'settime|' r'settitle|' r'show|' r'showtt|' r'sprintf|' r'sprintf2|' r'statusbox|' r'str2code|' r'str2int|' r'strcompare|' r'strconcat|' r'strcopy|' r'strdim|' r'strinsert|' r'strjoin|' r'strlen|' r'strmatch|' r'strremove|' r'strreplace|' r'strscan|' r'strspecial|' r'strsplit|' r'strtrim|' r'testlink|' r'then|' r'tolower|' r'toupper|' r'unlink|' r'until|' r'uptime|' r'var2clipb|' r'wait|' r'wait4all|' r'waitevent|' r'waitln|' r'waitn|' r'waitrecv|' r'waitregex|' r'while|' r'xmodemrecv|' r'xmodemsend|' r'yesnobox|' r'ymodemrecv|' r'ymodemsend|' r'zmodemrecv|' r'zmodemsend' r')\b', Keyword, ), (r'(?i)(call|goto)([ \t]+)([a-z0-9_]+)', bygroups(Keyword, Text.Whitespace, Name.Label)), ], 'builtin-variables': [ ( r'(?i)(' r'groupmatchstr1|' r'groupmatchstr2|' r'groupmatchstr3|' r'groupmatchstr4|' r'groupmatchstr5|' r'groupmatchstr6|' r'groupmatchstr7|' r'groupmatchstr8|' r'groupmatchstr9|' r'inputstr|' r'matchstr|' r'mtimeout|' r'param1|' r'param2|' r'param3|' r'param4|' r'param5|' r'param6|' r'param7|' r'param8|' r'param9|' r'paramcnt|' r'params|' r'result|' r'timeout' r')\b', Name.Builtin ), ], 'user-variables': [ (r'(?i)[a-z_][a-z0-9_]*', Name.Variable), ], 'numeric-literals': [ (r'(-?)([0-9]+)', bygroups(Operator, Number.Integer)), (r'(?i)\$[0-9a-f]+', Number.Hex), ], 'string-literals': [ (r'(?i)#(?:[0-9]+|\$[0-9a-f]+)', String.Char), (r"'[^'\n]*'", String.Single), (r'"[^"\n]*"', String.Double), # Opening quotes without a closing quote on the same line are errors. (r"('[^']*)(\n)", bygroups(Error, Text.Whitespace)), (r'("[^"]*)(\n)', bygroups(Error, Text.Whitespace)), ], 'operators': [ (r'and|not|or|xor', Operator.Word), (r'[!%&*+<=>^~\|\/-]+', Operator), (r'[()]', String.Symbol), ], 'all-whitespace': [ (r'\s+', Text.Whitespace), ], }
# Turtle and Tera Term macro files share the same file extension # but each has a recognizable and distinct syntax. def analyse_text(text): if re.search(TeraTermLexer.tokens['commands'][0][0], text): return 0.01123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209""" pygments.lexers.testing ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for testing languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Comment, Keyword, Name, String, Number, Generic, Text
__all__ = ['GherkinLexer', 'TAPLexer']
class GherkinLexer(RegexLexer): """ For Gherkin syntax. """ name = 'Gherkin' aliases = ['gherkin', 'cucumber'] filenames = ['*.feature'] mimetypes = ['text/x-gherkin'] url = 'https://cucumber.io/docs/gherkin' version_added = '1.2'
feature_keywords = '^(기능|機能|功能|フィーチャ|خاصية|תכונה|Функціонал|Функционалност|Функционал|Фича|Особина|Могућност|Özellik|Właściwość|Tính năng|Trajto|Savybė|Požiadavka|Požadavek|Osobina|Ominaisuus|Omadus|OH HAI|Mogućnost|Mogucnost|Jellemző|Fīča|Funzionalità|Funktionalität|Funkcionalnost|Funkcionalitāte|Funcționalitate|Functionaliteit|Functionalitate|Funcionalitat|Funcionalidade|Fonctionnalité|Fitur|Feature|Egenskap|Egenskab|Crikey|Característica|Arwedd)(:)(.*)$' feature_element_keywords = '^(\\s*)(시나리오 개요|시나리오|배경|背景|場景大綱|場景|场景大纲|场景|劇本大綱|劇本|剧本大纲|剧本|テンプレ|シナリオテンプレート|シナリオテンプレ|シナリオアウトライン|シナリオ|سيناريو مخطط|سيناريو|الخلفية|תרחיש|תבנית תרחיש|רקע|Тарих|Сценарій|Сценарио|Сценарий структураси|Сценарий|Структура сценарію|Структура сценарија|Структура сценария|Скица|Рамка на сценарий|Пример|Предыстория|Предистория|Позадина|Передумова|Основа|Концепт|Контекст|Założenia|Wharrimean is|Tình huống|The thing of it is|Tausta|Taust|Tapausaihio|Tapaus|Szenariogrundriss|Szenario|Szablon scenariusza|Stsenaarium|Struktura scenarija|Skica|Skenario konsep|Skenario|Situācija|Senaryo taslağı|Senaryo|Scénář|Scénario|Schema dello scenario|Scenārijs pēc parauga|Scenārijs|Scenár|Scenaro|Scenariusz|Scenariul de şablon|Scenariul de sablon|Scenariu|Scenario Outline|Scenario Amlinellol|Scenario|Scenarijus|Scenarijaus šablonas|Scenarij|Scenarie|Rerefons|Raamstsenaarium|Primer|Pozadí|Pozadina|Pozadie|Plan du scénario|Plan du Scénario|Osnova scénáře|Osnova|Náčrt Scénáře|Náčrt Scenáru|Mate|MISHUN SRSLY|MISHUN|Kịch bản|Konturo de la scenaro|Kontext|Konteksts|Kontekstas|Kontekst|Koncept|Khung tình huống|Khung kịch bản|Háttér|Grundlage|Geçmiş|Forgatókönyv vázlat|Forgatókönyv|Fono|Esquema do Cenário|Esquema do Cenario|Esquema del escenario|Esquema de l\'escenari|Escenario|Escenari|Dis is what went down|Dasar|Contexto|Contexte|Contesto|Condiţii|Conditii|Cenário|Cenario|Cefndir|Bối cảnh|Blokes|Bakgrunn|Bakgrund|Baggrund|Background|B4|Antecedents|Antecedentes|All y\'all|Achtergrond|Abstrakt Scenario|Abstract Scenario)(:)(.*)$' examples_keywords = '^(\\s*)(예|例子|例|サンプル|امثلة|דוגמאות|Сценарији|Примери|Приклади|Мисоллар|Значения|Örnekler|Voorbeelden|Variantai|Tapaukset|Scenarios|Scenariji|Scenarijai|Příklady|Példák|Príklady|Przykłady|Primjeri|Primeri|Piemēri|Pavyzdžiai|Paraugs|Juhtumid|Exemplos|Exemples|Exemplele|Exempel|Examples|Esempi|Enghreifftiau|Ekzemploj|Eksempler|Ejemplos|EXAMPLZ|Dữ liệu|Contoh|Cobber|Beispiele)(:)(.*)$' step_keywords = '^(\\s*)(하지만|조건|먼저|만일|만약|단|그리고|그러면|那麼|那么|而且|當|当|前提|假設|假设|假如|假定|但是|但し|並且|并且|同時|同时|もし|ならば|ただし|しかし|かつ|و |متى |لكن |عندما |ثم |بفرض |اذاً |כאשר |וגם |בהינתן |אזי |אז |אבל |Якщо |Унда |То |Припустимо, що |Припустимо |Онда |Но |Нехай |Лекин |Когато |Када |Кад |К тому же |И |Задато |Задати |Задате |Если |Допустим |Дадено |Ва |Бирок |Аммо |Али |Але |Агар |А |І |Și |És |Zatati |Zakładając |Zadato |Zadate |Zadano |Zadani |Zadan |Youse know when youse got |Youse know like when |Yna |Ya know how |Ya gotta |Y |Wun |Wtedy |When y\'all |When |Wenn |WEN |Và |Ve |Und |Un |Thì |Then y\'all |Then |Tapi |Tak |Tada |Tad |Så |Stel |Soit |Siis |Si |Sed |Se |Quando |Quand |Quan |Pryd |Pokud |Pokiaľ |Però |Pero |Pak |Oraz |Onda |Ond |Oletetaan |Og |Och |O zaman |Når |När |Niin |Nhưng |N |Mutta |Men |Mas |Maka |Majd |Mais |Maar |Ma |Lorsque |Lorsqu\'|Kun |Kuid |Kui |Khi |Keď |Ketika |Když |Kaj |Kai |Kada |Kad |Jeżeli |Ja |Ir |I CAN HAZ |I |Ha |Givun |Givet |Given y\'all |Given |Gitt |Gegeven |Gegeben sei |Fakat |Eğer ki |Etant donné |Et |Então |Entonces |Entao |En |Eeldades |E |Duota |Dun |Donitaĵo |Donat |Donada |Do |Diyelim ki |Dengan |Den youse gotta |De |Dato |Dar |Dann |Dan |Dado |Dacă |Daca |DEN |Când |Cuando |Cho |Cept |Cand |Cal |But y\'all |But |Buh |Biết |Bet |BUT |Atès |Atunci |Atesa |Anrhegedig a |Angenommen |And y\'all |And |An |Ama |Als |Alors |Allora |Ali |Aleshores |Ale |Akkor |Aber |AN |A také |A |\\* )'
tokens = { 'comments': [ (r'^\s*#.*$', Comment), ], 'feature_elements': [ (step_keywords, Keyword, "step_content_stack"), include('comments'), (r"(\s|.)", Name.Function), ], 'feature_elements_on_stack': [ (step_keywords, Keyword, "#pop:2"), include('comments'), (r"(\s|.)", Name.Function), ], 'examples_table': [ (r"\s+\|", Keyword, 'examples_table_header'), include('comments'), (r"(\s|.)", Name.Function), ], 'examples_table_header': [ (r"\s+\|\s*$", Keyword, "#pop:2"), include('comments'), (r"\\\|", Name.Variable), (r"\s*\|", Keyword), (r"[^|]", Name.Variable), ], 'scenario_sections_on_stack': [ (feature_element_keywords, bygroups(Name.Function, Keyword, Keyword, Name.Function), "feature_elements_on_stack"), ], 'narrative': [ include('scenario_sections_on_stack'), include('comments'), (r"(\s|.)", Name.Function), ], 'table_vars': [ (r'(<[^>]+>)', Name.Variable), ], 'numbers': [ (r'(\d+\.?\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', String), ], 'string': [ include('table_vars'), (r'(\s|.)', String), ], 'py_string': [ (r'"""', Keyword, "#pop"), include('string'), ], 'step_content_root': [ (r"$", Keyword, "#pop"), include('step_content'), ], 'step_content_stack': [ (r"$", Keyword, "#pop:2"), include('step_content'), ], 'step_content': [ (r'"', Name.Function, "double_string"), include('table_vars'), include('numbers'), include('comments'), (r'(\s|.)', Name.Function), ], 'table_content': [ (r"\s+\|\s*$", Keyword, "#pop"), include('comments'), (r"\\\|", String), (r"\s*\|", Keyword), include('string'), ], 'double_string': [ (r'"', Name.Function, "#pop"), include('string'), ], 'root': [ (r'\n', Name.Function), include('comments'), (r'"""', Keyword, "py_string"), (r'\s+\|', Keyword, 'table_content'), (r'"', Name.Function, "double_string"), include('table_vars'), include('numbers'), (r'(\s*)(@[^@\r\n\t ]+)', bygroups(Name.Function, Name.Tag)), (step_keywords, bygroups(Name.Function, Keyword), 'step_content_root'), (feature_keywords, bygroups(Keyword, Keyword, Name.Function), 'narrative'), (feature_element_keywords, bygroups(Name.Function, Keyword, Keyword, Name.Function), 'feature_elements'), (examples_keywords, bygroups(Name.Function, Keyword, Keyword, Name.Function), 'examples_table'), (r'(\s|.)', Name.Function), ] }
def analyse_text(self, text): return
class TAPLexer(RegexLexer): """ For Test Anything Protocol (TAP) output. """ name = 'TAP' url = 'https://testanything.org/' aliases = ['tap'] filenames = ['*.tap'] version_added = '2.1'
tokens = { 'root': [ # A TAP version may be specified. (r'^TAP version \d+\n', Name.Namespace),
# Specify a plan with a plan line. (r'^1\.\.\d+', Keyword.Declaration, 'plan'),
# A test failure (r'^(not ok)([^\S\n]*)(\d*)', bygroups(Generic.Error, Text, Number.Integer), 'test'),
# A test success (r'^(ok)([^\S\n]*)(\d*)', bygroups(Keyword.Reserved, Text, Number.Integer), 'test'),
# Diagnostics start with a hash. (r'^#.*\n', Comment),
# TAP's version of an abort statement. (r'^Bail out!.*\n', Generic.Error),
# TAP ignores any unrecognized lines. (r'^.*\n', Text), ], 'plan': [ # Consume whitespace (but not newline). (r'[^\S\n]+', Text),
# A plan may have a directive with it. (r'#', Comment, 'directive'),
# Or it could just end. (r'\n', Comment, '#pop'),
# Anything else is wrong. (r'.*\n', Generic.Error, '#pop'), ], 'test': [ # Consume whitespace (but not newline). (r'[^\S\n]+', Text),
# A test may have a directive with it. (r'#', Comment, 'directive'),
(r'\S+', Text),
(r'\n', Text, '#pop'), ], 'directive': [ # Consume whitespace (but not newline). (r'[^\S\n]+', Comment),
# Extract todo items. (r'(?i)\bTODO\b', Comment.Preproc),
# Extract skip items. (r'(?i)\bSKIP\S*', Comment.Preproc),
(r'\S+', Comment),
(r'\n', Comment, '#pop:2'), ], }123456789101112131415161718192021222324252627""" pygments.lexers.text ~~~~~~~~~~~~~~~~~~~~
Lexers for non-source code file types.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
# ruff: noqa: F401from pygments.lexers.configs import ApacheConfLexer, NginxConfLexer, \ SquidConfLexer, LighttpdConfLexer, IniLexer, RegeditLexer, PropertiesLexer, \ UnixConfigLexerfrom pygments.lexers.console import PyPyLogLexerfrom pygments.lexers.textedit import VimLexerfrom pygments.lexers.markup import BBCodeLexer, MoinWikiLexer, RstLexer, \ TexLexer, GroffLexerfrom pygments.lexers.installers import DebianControlLexer, DebianSourcesLexer, SourcesListLexerfrom pygments.lexers.make import MakefileLexer, BaseMakefileLexer, CMakeLexerfrom pygments.lexers.haxe import HxmlLexerfrom pygments.lexers.sgf import SmartGameFormatLexerfrom pygments.lexers.diff import DiffLexer, DarcsPatchLexerfrom pygments.lexers.data import YamlLexerfrom pygments.lexers.textfmts import IrcLogsLexer, GettextLexer, HttpLexer
__all__ = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205""" pygments.lexers.textedit ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for languages related to text processing.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import refrom bisect import bisect
from pygments.lexer import RegexLexer, bygroups, default, include, this, usingfrom pygments.lexers.python import PythonLexerfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace
__all__ = ['AwkLexer', 'SedLexer', 'VimLexer']
class AwkLexer(RegexLexer): """ For Awk scripts. """
name = 'Awk' aliases = ['awk', 'gawk', 'mawk', 'nawk'] filenames = ['*.awk'] mimetypes = ['application/x-awk'] url = 'https://en.wikipedia.org/wiki/AWK' version_added = '1.5'
tokens = { 'commentsandwhitespace': [ (r'\s+', Text), (r'#.*$', Comment.Single) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'\B', String.Regex, '#pop'), (r'(?=/)', Text, ('#pop', 'badregex')), default('#pop') ], 'badregex': [ (r'\n', Text, '#pop') ], 'root': [ (r'^(?=\s|/)', Text, 'slashstartsregex'), include('commentsandwhitespace'), (r'\+\+|--|\|\||&&|in\b|\$|!?~|\?|:|' r'(\*\*|[-<>+*%\^/!=|])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (r'(break|continue|do|while|exit|for|if|else|' r'return)\b', Keyword, 'slashstartsregex'), (r'function\b', Keyword.Declaration, 'slashstartsregex'), (r'(atan2|cos|exp|int|log|rand|sin|sqrt|srand|gensub|gsub|index|' r'length|match|split|sprintf|sub|substr|tolower|toupper|close|' r'fflush|getline|next|nextfile|print|printf|strftime|systime|' r'delete|system)\b', Keyword.Reserved), (r'(ARGC|ARGIND|ARGV|BEGIN|CONVFMT|ENVIRON|END|ERRNO|FIELDWIDTHS|' r'FILENAME|FNR|FS|IGNORECASE|NF|NR|OFMT|OFS|ORFS|RLENGTH|RS|' r'RSTART|RT|SUBSEP)\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 SedLexer(RegexLexer): """ Lexer for Sed script files. """ name = 'Sed' aliases = ['sed', 'gsed', 'ssed'] filenames = ['*.sed', '*.[gs]sed'] mimetypes = ['text/x-sed'] url = 'https://en.wikipedia.org/wiki/Sed' version_added = '' flags = re.MULTILINE
# Match the contents within delimiters such as /<contents>/ _inside_delims = r'((?:(?:\\[^\n]|[^\\])*?\\\n)*?(?:\\.|[^\\])*?)'
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*$', Comment.Single), (r'[0-9]+', Number.Integer), (r'\$', Operator), (r'[{};,!]', Punctuation), (r'[dDFgGhHlnNpPqQxz=]', Keyword), (r'([berRtTvwW:])([^;\n]*)', bygroups(Keyword, String.Single)), (r'([aci])((?:.*?\\\n)*(?:.*?[^\\]$))', bygroups(Keyword, String.Double)), (r'([qQ])([0-9]*)', bygroups(Keyword, Number.Integer)), (r'(/)' + _inside_delims + r'(/)', bygroups(Punctuation, String.Regex, Punctuation)), (r'(\\(.))' + _inside_delims + r'(\2)', bygroups(Punctuation, None, String.Regex, Punctuation)), (r'(y)(.)' + _inside_delims + r'(\2)' + _inside_delims + r'(\2)', bygroups(Keyword, Punctuation, String.Single, Punctuation, String.Single, Punctuation)), (r'(s)(.)' + _inside_delims + r'(\2)' + _inside_delims + r'(\2)((?:[gpeIiMm]|[0-9])*)', bygroups(Keyword, Punctuation, String.Regex, Punctuation, String.Single, Punctuation, Keyword)) ] }
class VimLexer(RegexLexer): """ Lexer for VimL script files. """ name = 'VimL' aliases = ['vim'] filenames = ['*.vim', '.vimrc', '.exrc', '.gvimrc', '_vimrc', '_exrc', '_gvimrc', 'vimrc', 'gvimrc'] mimetypes = ['text/x-vim'] url = 'https://www.vim.org' version_added = '0.8'
flags = re.MULTILINE
_python = r'py(?:t(?:h(?:o(?:n)?)?)?)?'
tokens = { 'root': [ (r'^([ \t:]*)(' + _python + r')([ \t]*)(<<)([ \t]*)(.*)((?:\n|.)*)(\6)', bygroups(using(this), Keyword, Text, Operator, Text, Text, using(PythonLexer), Text)), (r'^([ \t:]*)(' + _python + r')([ \t])(.*)', bygroups(using(this), Keyword, Text, using(PythonLexer))),
(r'^\s*".*', Comment),
(r'[ \t]+', Text), # TODO: regexes can have other delims (r'/[^/\\\n]*(?:\\[\s\S][^/\\\n]*)*/', String.Regex), (r'"[^"\\\n]*(?:\\[\s\S][^"\\\n]*)*"', String.Double), (r"'[^\n']*(?:''[^\n']*)*'", String.Single),
# Who decided that doublequote was a good comment character?? (r'(?<=\s)"[^\-:.%#=*].*', Comment), (r'-?\d+', Number), (r'#[0-9a-f]{6}', Number.Hex), (r'^:', Punctuation), (r'[()<>+=!|,~-]', Punctuation), # Inexact list. Looks decent. (r'\b(let|if|else|endif|elseif|fun|function|endfunction)\b', Keyword), (r'\b(NONE|bold|italic|underline|dark|light)\b', Name.Builtin), (r'\b\w+\b', Name.Other), # These are postprocessed below (r'.', Text), ], }
def __init__(self, **options): from pygments.lexers._vim_builtins import auto, command, option self._cmd = command self._opt = option self._aut = auto
RegexLexer.__init__(self, **options)
def is_in(self, w, mapping): r""" It's kind of difficult to decide if something might be a keyword in VimL because it allows you to abbreviate them. In fact, 'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are valid ways to call it so rather than making really awful regexps like::
\bab(?:b(?:r(?:e(?:v(?:i(?:a(?:t(?:e)?)?)?)?)?)?)?)?\b
we match `\b\w+\b` and then call is_in() on those tokens. See `scripts/get_vimkw.py` for how the lists are extracted. """ p = bisect(mapping, (w,)) if p > 0: if mapping[p-1][0] == w[:len(mapping[p-1][0])] and \ mapping[p-1][1][:len(w)] == w: return True if p < len(mapping): return mapping[p][0] == w[:len(mapping[p][0])] and \ mapping[p][1][:len(w)] == w return False
def get_tokens_unprocessed(self, text): # TODO: builtins are only subsequent tokens on lines # and 'keywords' only happen at the beginning except # for :au ones for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name.Other: if self.is_in(value, self._cmd): yield index, Keyword, value elif self.is_in(value, self._opt) or \ self.is_in(value, self._aut): yield index, Name.Builtin, value else: yield index, Text, value else: yield index, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436""" pygments.lexers.textfmts ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for various text formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexers import guess_lexer, get_lexer_by_namefrom pygments.lexer import RegexLexer, bygroups, default, includefrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Generic, Literal, Punctuationfrom pygments.util import ClassNotFound
__all__ = ['IrcLogsLexer', 'TodotxtLexer', 'HttpLexer', 'GettextLexer', 'NotmuchLexer', 'KernelLogLexer']
class IrcLogsLexer(RegexLexer): """ Lexer for IRC logs in *irssi*, *xchat* or *weechat* style. """
name = 'IRC logs' aliases = ['irc'] filenames = ['*.weechatlog'] mimetypes = ['text/x-irclog'] url = 'https://en.wikipedia.org/wiki/Internet_Relay_Chat' version_added = ''
flags = re.VERBOSE | re.MULTILINE timestamp = r""" ( # irssi / xchat and others (?: \[|\()? # Opening bracket or paren for the timestamp (?: # Timestamp (?: (?:\d{1,4} [-/])* # Date as - or /-separated groups of digits (?:\d{1,4}) [T ])? # Date/time separator: T or space (?: \d?\d [:.])* # Time as :/.-separated groups of 1 or 2 digits (?: \d?\d) ) (?: \]|\))?\s+ # Closing bracket or paren for the timestamp | # weechat \d{4}\s\w{3}\s\d{2}\s # Date \d{2}:\d{2}:\d{2}\s+ # Time + Whitespace | # xchat \w{3}\s\d{2}\s # Date \d{2}:\d{2}:\d{2}\s+ # Time + Whitespace )? """ tokens = { 'root': [ # log start/end (r'^\*\*\*\*(.*)\*\*\*\*$', Comment), # hack ("^" + timestamp + r'(\s*<[^>]*>\s*)$', bygroups(Comment.Preproc, Name.Tag)), # normal msgs ("^" + timestamp + r""" (\s*<.*?>\s*) # Nick """, bygroups(Comment.Preproc, Name.Tag), 'msg'), # /me msgs ("^" + timestamp + r""" (\s*[*]\s+) # Star (\S+\s+.*?\n) # Nick + rest of message """, bygroups(Comment.Preproc, Keyword, Generic.Inserted)), # join/part msgs ("^" + timestamp + r""" (\s*(?:\*{3}|<?-[!@=P]?->?)\s*) # Star(s) or symbols (\S+\s+) # Nick + Space (.*?\n) # Rest of message """, bygroups(Comment.Preproc, Keyword, String, Comment)), (r"^.*?\n", Text), ], 'msg': [ (r"\S+:(?!//)", Name.Attribute), # Prefix (r".*\n", Text, '#pop'), ], }
class GettextLexer(RegexLexer): """ Lexer for Gettext catalog files. """ name = 'Gettext Catalog' aliases = ['pot', 'po'] filenames = ['*.pot', '*.po'] mimetypes = ['application/x-gettext', 'text/x-gettext', 'text/gettext'] url = 'https://www.gnu.org/software/gettext' version_added = '0.9'
tokens = { 'root': [ (r'^#,\s.*?$', Keyword.Type), (r'^#:\s.*?$', Keyword.Declaration), # (r'^#$', Comment), (r'^(#|#\.\s|#\|\s|#~\s|#\s).*$', Comment.Single), (r'^(")([A-Za-z-]+:)(.*")$', bygroups(String, Name.Property, String)), (r'^".*"$', String), (r'^(msgid|msgid_plural|msgstr|msgctxt)(\s+)(".*")$', bygroups(Name.Variable, Text, String)), (r'^(msgstr\[)(\d)(\])(\s+)(".*")$', bygroups(Name.Variable, Number.Integer, Name.Variable, Text, String)), ] }
class HttpLexer(RegexLexer): """ Lexer for HTTP sessions. """
name = 'HTTP' aliases = ['http'] url = 'https://httpwg.org/specs' version_added = '1.5'
flags = re.DOTALL
def get_tokens_unprocessed(self, text, stack=('root',)): """Reset the content-type state.""" self.content_type = None return RegexLexer.get_tokens_unprocessed(self, text, stack)
def header_callback(self, match): if match.group(1).lower() == 'content-type': content_type = match.group(5).strip() if ';' in content_type: content_type = content_type[:content_type.find(';')].strip() self.content_type = content_type yield match.start(1), Name.Attribute, match.group(1) yield match.start(2), Text, match.group(2) yield match.start(3), Operator, match.group(3) yield match.start(4), Text, match.group(4) yield match.start(5), Literal, match.group(5) yield match.start(6), Text, match.group(6)
def continuous_header_callback(self, match): yield match.start(1), Text, match.group(1) yield match.start(2), Literal, match.group(2) yield match.start(3), Text, match.group(3)
def content_callback(self, match): content_type = getattr(self, 'content_type', None) content = match.group() offset = match.start() if content_type: from pygments.lexers import get_lexer_for_mimetype possible_lexer_mimetypes = [content_type] if '+' in content_type: # application/calendar+xml can be treated as application/xml # if there's not a better match. general_type = re.sub(r'^(.*)/.*\+(.*)$', r'\1/\2', content_type) possible_lexer_mimetypes.append(general_type)
for i in possible_lexer_mimetypes: try: lexer = get_lexer_for_mimetype(i) except ClassNotFound: pass else: for idx, token, value in lexer.get_tokens_unprocessed(content): yield offset + idx, token, value return yield offset, Text, content
tokens = { 'root': [ (r'([a-zA-Z][-_a-zA-Z]+)( +)([^ ]+)( +)' r'(HTTP)(/)(1\.[01]|2(?:\.0)?|3)(\r?\n|\Z)', bygroups(Name.Function, Text, Name.Namespace, Text, Keyword.Reserved, Operator, Number, Text), 'headers'), (r'(HTTP)(/)(1\.[01]|2(?:\.0)?|3)( +)(\d{3})(?:( +)([^\r\n]*))?(\r?\n|\Z)', bygroups(Keyword.Reserved, Operator, Number, Text, Number, Text, Name.Exception, Text), 'headers'), ], 'headers': [ (r'([^\s:]+)( *)(:)( *)([^\r\n]*)(\r?\n|\Z)', header_callback), (r'([\t ]+)([^\r\n]+)(\r?\n|\Z)', continuous_header_callback), (r'\r?\n', Text, 'content') ], 'content': [ (r'.+', content_callback) ] }
def analyse_text(text): return any ( re.search(pattern, text) is not None for pattern in ( r'^([a-zA-Z][-_a-zA-Z]+)( +)([^ ]+)( +)(HTTP)(/)(1\.[01]|2(?:\.0)?|3)(\r?\n|\Z)', r'^(HTTP)(/)(1\.[01]|2(?:\.0)?|3)( +)(\d{3})(?:( +)([^\r\n]*))?(\r?\n|\Z)', ) )
class TodotxtLexer(RegexLexer): """ Lexer for Todo.txt todo list format. """
name = 'Todotxt' url = 'http://todotxt.com/' aliases = ['todotxt'] version_added = '2.0' # *.todotxt is not a standard extension for Todo.txt files; including it # makes testing easier, and also makes autodetecting file type easier. filenames = ['todo.txt', '*.todotxt'] mimetypes = ['text/x-todo']
# Aliases mapping standard token types of Todo.txt format concepts CompleteTaskText = Operator # Chosen to de-emphasize complete tasks IncompleteTaskText = Text # Incomplete tasks should look like plain text
# Priority should have most emphasis to indicate importance of tasks Priority = Generic.Heading # Dates should have next most emphasis because time is important Date = Generic.Subheading
# Project and context should have equal weight, and be in different colors Project = Generic.Error Context = String
# If tag functionality is added, it should have the same weight as Project # and Context, and a different color. Generic.Traceback would work well.
# Regex patterns for building up rules; dates, priorities, projects, and # contexts are all atomic # TODO: Make date regex more ISO 8601 compliant date_regex = r'\d{4,}-\d{2}-\d{2}' priority_regex = r'\([A-Z]\)' project_regex = r'\+\S+' context_regex = r'@\S+'
# Compound regex expressions complete_one_date_regex = r'(x )(' + date_regex + r')' complete_two_date_regex = (complete_one_date_regex + r'( )(' + date_regex + r')') priority_date_regex = r'(' + priority_regex + r')( )(' + date_regex + r')'
tokens = { # Should parse starting at beginning of line; each line is a task 'root': [ # Complete task entry points: two total: # 1. Complete task with two dates (complete_two_date_regex, bygroups(CompleteTaskText, Date, CompleteTaskText, Date), 'complete'), # 2. Complete task with one date (complete_one_date_regex, bygroups(CompleteTaskText, Date), 'complete'),
# Incomplete task entry points: six total: # 1. Priority plus date (priority_date_regex, bygroups(Priority, IncompleteTaskText, Date), 'incomplete'), # 2. Priority only (priority_regex, Priority, 'incomplete'), # 3. Leading date (date_regex, Date, 'incomplete'), # 4. Leading context (context_regex, Context, 'incomplete'), # 5. Leading project (project_regex, Project, 'incomplete'), # 6. Non-whitespace catch-all (r'\S+', IncompleteTaskText, 'incomplete'), ],
# Parse a complete task 'complete': [ # Newline indicates end of task, should return to root (r'\s*\n', CompleteTaskText, '#pop'), # Tokenize contexts and projects (context_regex, Context), (project_regex, Project), # Tokenize non-whitespace text (r'\S+', CompleteTaskText), # Tokenize whitespace not containing a newline (r'\s+', CompleteTaskText), ],
# Parse an incomplete task 'incomplete': [ # Newline indicates end of task, should return to root (r'\s*\n', IncompleteTaskText, '#pop'), # Tokenize contexts and projects (context_regex, Context), (project_regex, Project), # Tokenize non-whitespace text (r'\S+', IncompleteTaskText), # Tokenize whitespace not containing a newline (r'\s+', IncompleteTaskText), ], }
class NotmuchLexer(RegexLexer): """ For Notmuch email text format.
Additional options accepted:
`body_lexer` If given, highlight the contents of the message body with the specified lexer, else guess it according to the body content (default: ``None``). """
name = 'Notmuch' url = 'https://notmuchmail.org/' aliases = ['notmuch'] version_added = '2.5'
def _highlight_code(self, match): code = match.group(1)
try: if self.body_lexer: lexer = get_lexer_by_name(self.body_lexer) else: lexer = guess_lexer(code.strip()) except ClassNotFound: lexer = get_lexer_by_name('text')
yield from lexer.get_tokens_unprocessed(code)
tokens = { 'root': [ (r'\fmessage\{\s*', Keyword, ('message', 'message-attr')), ], 'message-attr': [ (r'(\s*id:\s*)(\S+)', bygroups(Name.Attribute, String)), (r'(\s*(?:depth|match|excluded):\s*)(\d+)', bygroups(Name.Attribute, Number.Integer)), (r'(\s*filename:\s*)(.+\n)', bygroups(Name.Attribute, String)), default('#pop'), ], 'message': [ (r'\fmessage\}\n', Keyword, '#pop'), (r'\fheader\{\n', Keyword, 'header'), (r'\fbody\{\n', Keyword, 'body'), ], 'header': [ (r'\fheader\}\n', Keyword, '#pop'), (r'((?:Subject|From|To|Cc|Date):\s*)(.*\n)', bygroups(Name.Attribute, String)), (r'(.*)(\s*\(.*\))(\s*\(.*\)\n)', bygroups(Generic.Strong, Literal, Name.Tag)), ], 'body': [ (r'\fpart\{\n', Keyword, 'part'), (r'\f(part|attachment)\{\s*', Keyword, ('part', 'part-attr')), (r'\fbody\}\n', Keyword, '#pop'), ], 'part-attr': [ (r'(ID:\s*)(\d+)', bygroups(Name.Attribute, Number.Integer)), (r'(,\s*)((?:Filename|Content-id):\s*)([^,]+)', bygroups(Punctuation, Name.Attribute, String)), (r'(,\s*)(Content-type:\s*)(.+\n)', bygroups(Punctuation, Name.Attribute, String)), default('#pop'), ], 'part': [ (r'\f(?:part|attachment)\}\n', Keyword, '#pop'), (r'\f(?:part|attachment)\{\s*', Keyword, ('#push', 'part-attr')), (r'^Non-text part: .*\n', Comment), (r'(?s)(.*?(?=\f(?:part|attachment)\}\n))', _highlight_code), ], }
def analyse_text(text): return 1.0 if text.startswith('\fmessage{') else 0.0
def __init__(self, **options): self.body_lexer = options.get('body_lexer', None) RegexLexer.__init__(self, **options)
class KernelLogLexer(RegexLexer): """ For Linux Kernel log ("dmesg") output. """ name = 'Kernel log' aliases = ['kmsg', 'dmesg'] filenames = ['*.kmsg', '*.dmesg'] url = 'https://fr.wikipedia.org/wiki/Dmesg' version_added = '2.6'
tokens = { 'root': [ (r'^[^:]+:debug : (?=\[)', Text, 'debug'), (r'^[^:]+:info : (?=\[)', Text, 'info'), (r'^[^:]+:warn : (?=\[)', Text, 'warn'), (r'^[^:]+:notice: (?=\[)', Text, 'warn'), (r'^[^:]+:err : (?=\[)', Text, 'error'), (r'^[^:]+:crit : (?=\[)', Text, 'error'), (r'^(?=\[)', Text, 'unknown'), ], 'unknown': [ (r'^(?=.+(warning|notice|audit|deprecated))', Text, 'warn'), (r'^(?=.+(error|critical|fail|Bug))', Text, 'error'), default('info'), ], 'base': [ (r'\[[0-9. ]+\] ', Number), (r'(?<=\] ).+?:', Keyword), (r'\n', Text, '#pop'), ], 'debug': [ include('base'), (r'.+\n', Comment, '#pop') ], 'info': [ include('base'), (r'.+\n', Text, '#pop') ], 'warn': [ include('base'), (r'.+\n', Generic.Strong, '#pop') ], 'error': [ include('base'), (r'.+\n', Generic.Error, '#pop') ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410""" pygments.lexers.theorem ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for theorem-proving languages.
See also :mod:`pygments.lexers.lean`
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace# compatibility importfrom pygments.lexers.lean import LeanLexer # noqa: F401
__all__ = ['RocqLexer', 'IsabelleLexer']
class RocqLexer(RegexLexer): """ For the Rocq Prover. """
name = 'Rocq Prover' url = 'https://rocq-prover.org/' aliases = ['coq', 'rocq', 'rocq-prover'] filenames = ['*.v'] mimetypes = ['text/x-coq', 'text/x-rocq'] version_added = '1.5'
flags = 0 # no re.MULTILINE
keywords1 = ( # Vernacular commands 'Section', 'Module', 'End', 'Require', 'Import', 'Export', 'Include', 'Variable', 'Variables', 'Parameter', 'Parameters', 'Axiom', 'Axioms', 'Hypothesis', 'Hypotheses', 'Notation', 'Local', 'Tactic', 'Reserved', 'Scope', 'Open', 'Close', 'Bind', 'Declare', 'Delimit', 'Definition', 'Example', 'Let', 'Ltac', 'Ltac2', 'Fixpoint', 'CoFixpoint', 'Morphism', 'Relation', 'Implicit', 'Arguments', 'Types', 'Contextual', 'Strict', 'Prenex', 'Implicits', 'Inductive', 'CoInductive', 'Record', 'Structure', 'Variant', 'Canonical', 'Coercion', 'Theorem', 'Lemma', 'Fact', 'Remark', 'Corollary', 'Proposition', 'Property', 'Goal', 'Proof', 'Restart', 'Save', 'Qed', 'Defined', 'Abort', 'Admitted', 'Hint', 'Resolve', 'Rewrite', 'View', 'Search', 'Compute', 'Eval', 'Show', 'Print', 'Printing', 'All', 'Graph', 'Projections', 'inside', 'outside', 'Check', 'Global', 'Instance', 'Class', 'Existing', 'Universe', 'Polymorphic', 'Monomorphic', 'Context', 'Scheme', 'From', 'Undo', 'Fail', 'Function', 'Program', 'Elpi', 'Extract', 'Opaque', 'Transparent', 'Unshelve', 'Next Obligation', ) keywords2 = ( # Gallina 'forall', 'exists', 'exists2', 'fun', 'fix', 'cofix', 'struct', 'match', 'end', 'in', 'return', 'let', 'if', 'is', 'then', 'else', 'for', 'of', 'nosimpl', 'with', 'as', ) keywords3 = ( # Sorts 'Type', 'Prop', 'SProp', 'Set', ) keywords4 = ( # Tactics 'pose', 'set', 'move', 'case', 'elim', 'apply', 'clear', 'hnf', 'intro', 'intros', 'generalize', 'rename', 'pattern', 'after', 'destruct', 'induction', 'using', 'refine', 'inversion', 'injection', 'rewrite', 'congr', 'unlock', 'compute', 'ring', 'field', 'replace', 'fold', 'unfold', 'change', 'cutrewrite', 'simpl', 'have', 'suff', 'wlog', 'suffices', 'without', 'loss', 'nat_norm', 'assert', 'cut', 'trivial', 'revert', 'bool_congr', 'nat_congr', 'symmetry', 'transitivity', 'auto', 'split', 'left', 'right', 'autorewrite', 'tauto', 'setoid_rewrite', 'intuition', 'eauto', 'eapply', 'econstructor', 'etransitivity', 'constructor', 'erewrite', 'red', 'cbv', 'lazy', 'vm_compute', 'native_compute', 'subst', ) keywords5 = ( # Terminators 'by', 'now', 'done', 'exact', 'reflexivity', 'tauto', 'romega', 'omega', 'lia', 'nia', 'lra', 'nra', 'psatz', 'assumption', 'solve', 'contradiction', 'discriminate', 'congruence', 'admit' ) keywords6 = ( # Control 'do', 'last', 'first', 'try', 'idtac', 'repeat', ) # 'as', 'assert', 'begin', 'class', 'constraint', 'do', 'done', # 'downto', 'else', 'end', 'exception', 'external', 'false', # 'for', 'fun', 'function', 'functor', 'if', 'in', 'include', # 'inherit', 'initializer', 'lazy', 'let', 'match', 'method', # 'module', 'mutable', 'new', 'object', 'of', 'open', 'private', # 'raise', 'rec', 'sig', 'struct', 'then', 'to', 'true', 'try', # 'type', 'val', 'virtual', 'when', 'while', 'with' keyopts = ( '!=', '#', '&', '&&', r'\(', r'\)', r'\*', r'\+', ',', '-', r'-\.', '->', r'\.', r'\.\.', ':', '::', ':=', ':>', ';', ';;', '<', '<-', '<->', '=', '>', '>]', r'>\}', r'\?', r'\?\?', r'\[', r'\[<', r'\[>', r'\[\|', ']', '_', '`', r'\{', r'\{<', r'lp:\{\{', r'\|', r'\|]', r'\}', '~', '=>', r'/\\', r'\\/', r'\{\|', r'\|\}', # 'Π', 'Σ', # Not defined in the standard library 'λ', '¬', '∧', '∨', '∀', '∃', '→', '↔', '≠', '≤', '≥', ) operators = r'[!$%&*+\./:<=>?@^|~-]' prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]'
tokens = { 'root': [ (r'\s+', Text), (r'false|true|\(\)|\[\]', Name.Builtin.Pseudo), (r'\(\*', Comment, 'comment'), (r'\b(?:[^\W\d][\w\']*\.)+[^\W\d][\w\']*\b', Name), (r'\bEquations\b\??', Keyword.Namespace), (r'\b(Elpi)(\s+)(Program|Query|Accumulate|Command|Typecheck|Db|Export|Tactic)?\b', bygroups(Keyword.Namespace,Text,Keyword.Namespace)), # Very weak heuristic to distinguish the Set vernacular from the Set sort (r'\bUnset\b|\bSet(?=[ \t]+[A-Z][a-z][^\n]*?\.)', Keyword.Namespace, 'set-options'), (r'\b(?:String|Number)\s+Notation', Keyword.Namespace, 'sn-notation'), (words(keywords1, prefix=r'\b', suffix=r'\b'), Keyword.Namespace), (words(keywords2, prefix=r'\b', suffix=r'\b'), Keyword), (words(keywords3, prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(keywords4, prefix=r'\b', suffix=r'\b'), Keyword), (words(keywords5, prefix=r'\b', suffix=r'\b'), Keyword.Pseudo), (words(keywords6, prefix=r'\b', suffix=r'\b'), Keyword.Reserved), # (r'\b([A-Z][\w\']*)(\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][\w\']*)', Name), (r'({})'.format('|'.join(keyopts[::-1])), Operator), (rf'({infix_syms}|{prefix_syms})?{operators}', Operator),
(r"[^\W\d][\w']*", Name),
(r'\d[\d_]*', Number.Integer), (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex), (r'0[oO][0-7][0-7_]*', Number.Oct), (r'0[bB][01][01_]*', Number.Bin), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'", String.Char),
(r"'.'", String.Char), (r"'", Keyword), # a stray quote is another syntax element
(r'"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name), (r'\S', Name.Builtin.Pseudo), ], 'set-options': [ (r'\s+', Text), (r'[A-Z]\w*', Keyword.Namespace), (r'"', String.Double, 'string'), (r'\d+', Number.Integer), (r'\.', Punctuation, '#pop'), ], 'sn-notation': [ (r'\s+', Text), # Extra keywords to highlight only in this scope (r'\b(?:via|mapping|abstract|warning|after)\b', Keyword), (r'=>|[()\[\]:,]', Operator), (r'\b[^\W\d][\w\']*(?:\.[^\W\d][\w\']*)*\b', Name), (r'\d[\d_]*', Number.Integer), (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex), (r'\(\*', Comment, 'comment'), (r'\.', Punctuation, '#pop'), ], 'comment': [ # Consume comments like ***** as one token (r'([^(*)]+|\*+(?!\)))+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), (r'[(*)]', Comment), ], 'string': [ (r'[^"]+', String.Double), (r'""', String.Double), (r'"', String.Double, '#pop'), ], 'dotted': [ (r'\s+', Text), (r'\.', Punctuation), (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace), (r'[A-Z][\w\']*', Name.Class, '#pop'), (r'[a-z][a-z0-9_\']*', Name, '#pop'), default('#pop') ], }
def analyse_text(text): if 'Qed' in text and 'Proof' in text: return 1
class IsabelleLexer(RegexLexer): """ For the Isabelle proof assistant. """
name = 'Isabelle' url = 'https://isabelle.in.tum.de/' aliases = ['isabelle'] filenames = ['*.thy'] mimetypes = ['text/x-isabelle'] version_added = '2.0'
keyword_minor = ( 'and', 'assumes', 'attach', 'avoids', 'binder', 'checking', 'class_instance', 'class_relation', 'code_module', 'congs', 'constant', 'constrains', 'datatypes', 'defines', 'file', 'fixes', 'for', 'functions', 'hints', 'identifier', 'if', 'imports', 'in', 'includes', 'infix', 'infixl', 'infixr', 'is', 'keywords', 'lazy', 'module_name', 'monos', 'morphisms', 'no_discs_sels', 'notes', 'obtains', 'open', 'output', 'overloaded', 'parametric', 'permissive', 'pervasive', 'rep_compat', 'shows', 'structure', 'type_class', 'type_constructor', 'unchecked', 'unsafe', 'where', )
keyword_diag = ( 'ML_command', 'ML_val', 'class_deps', 'code_deps', 'code_thms', 'display_drafts', 'find_consts', 'find_theorems', 'find_unused_assms', 'full_prf', 'help', 'locale_deps', 'nitpick', 'pr', 'prf', 'print_abbrevs', 'print_antiquotations', 'print_attributes', 'print_binds', 'print_bnfs', 'print_bundles', 'print_case_translations', 'print_cases', 'print_claset', 'print_classes', 'print_codeproc', 'print_codesetup', 'print_coercions', 'print_commands', 'print_context', 'print_defn_rules', 'print_dependencies', 'print_facts', 'print_induct_rules', 'print_inductives', 'print_interps', 'print_locale', 'print_locales', 'print_methods', 'print_options', 'print_orders', 'print_quot_maps', 'print_quotconsts', 'print_quotients', 'print_quotientsQ3', 'print_quotmapsQ3', 'print_rules', 'print_simpset', 'print_state', 'print_statement', 'print_syntax', 'print_theorems', 'print_theory', 'print_trans_rules', 'prop', 'pwd', 'quickcheck', 'refute', 'sledgehammer', 'smt_status', 'solve_direct', 'spark_status', 'term', 'thm', 'thm_deps', 'thy_deps', 'try', 'try0', 'typ', 'unused_thms', 'value', 'values', 'welcome', 'print_ML_antiquotations', 'print_term_bindings', 'values_prolog', )
keyword_thy = ('theory', 'begin', 'end')
keyword_section = ('header', 'chapter')
keyword_subsection = ( 'section', 'subsection', 'subsubsection', 'sect', 'subsect', 'subsubsect', )
keyword_theory_decl = ( 'ML', 'ML_file', 'abbreviation', 'adhoc_overloading', 'arities', 'atom_decl', 'attribute_setup', 'axiomatization', 'bundle', 'case_of_simps', 'class', 'classes', 'classrel', 'codatatype', 'code_abort', 'code_class', 'code_const', 'code_datatype', 'code_identifier', 'code_include', 'code_instance', 'code_modulename', 'code_monad', 'code_printing', 'code_reflect', 'code_reserved', 'code_type', 'coinductive', 'coinductive_set', 'consts', 'context', 'datatype', 'datatype_new', 'datatype_new_compat', 'declaration', 'declare', 'default_sort', 'defer_recdef', 'definition', 'defs', 'domain', 'domain_isomorphism', 'domaindef', 'equivariance', 'export_code', 'extract', 'extract_type', 'fixrec', 'fun', 'fun_cases', 'hide_class', 'hide_const', 'hide_fact', 'hide_type', 'import_const_map', 'import_file', 'import_tptp', 'import_type_map', 'inductive', 'inductive_set', 'instantiation', 'judgment', 'lemmas', 'lifting_forget', 'lifting_update', 'local_setup', 'locale', 'method_setup', 'nitpick_params', 'no_adhoc_overloading', 'no_notation', 'no_syntax', 'no_translations', 'no_type_notation', 'nominal_datatype', 'nonterminal', 'notation', 'notepad', 'oracle', 'overloading', 'parse_ast_translation', 'parse_translation', 'partial_function', 'primcorec', 'primrec', 'primrec_new', 'print_ast_translation', 'print_translation', 'quickcheck_generator', 'quickcheck_params', 'realizability', 'realizers', 'recdef', 'record', 'refute_params', 'setup', 'setup_lifting', 'simproc_setup', 'simps_of_case', 'sledgehammer_params', 'spark_end', 'spark_open', 'spark_open_siv', 'spark_open_vcg', 'spark_proof_functions', 'spark_types', 'statespace', 'syntax', 'syntax_declaration', 'text', 'text_raw', 'theorems', 'translations', 'type_notation', 'type_synonym', 'typed_print_translation', 'typedecl', 'hoarestate', 'install_C_file', 'install_C_types', 'wpc_setup', 'c_defs', 'c_types', 'memsafe', 'SML_export', 'SML_file', 'SML_import', 'approximate', 'bnf_axiomatization', 'cartouche', 'datatype_compat', 'free_constructors', 'functor', 'nominal_function', 'nominal_termination', 'permanent_interpretation', 'binds', 'defining', 'smt2_status', 'term_cartouche', 'boogie_file', 'text_cartouche', )
keyword_theory_script = ('inductive_cases', 'inductive_simps')
keyword_theory_goal = ( 'ax_specification', 'bnf', 'code_pred', 'corollary', 'cpodef', 'crunch', 'crunch_ignore', 'enriched_type', 'function', 'instance', 'interpretation', 'lemma', 'lift_definition', 'nominal_inductive', 'nominal_inductive2', 'nominal_primrec', 'pcpodef', 'primcorecursive', 'quotient_definition', 'quotient_type', 'recdef_tc', 'rep_datatype', 'schematic_corollary', 'schematic_lemma', 'schematic_theorem', 'spark_vc', 'specification', 'subclass', 'sublocale', 'termination', 'theorem', 'typedef', 'wrap_free_constructors', )
keyword_qed = ('by', 'done', 'qed') keyword_abandon_proof = ('sorry', 'oops')
keyword_proof_goal = ('have', 'hence', 'interpret')
keyword_proof_block = ('next', 'proof')
keyword_proof_chain = ( 'finally', 'from', 'then', 'ultimately', 'with', )
keyword_proof_decl = ( 'ML_prf', 'also', 'include', 'including', 'let', 'moreover', 'note', 'txt', 'txt_raw', 'unfolding', 'using', 'write', )
keyword_proof_asm = ('assume', 'case', 'def', 'fix', 'presume')
keyword_proof_asm_goal = ('guess', 'obtain', 'show', 'thus')
keyword_proof_script = ( 'apply', 'apply_end', 'apply_trace', 'back', 'defer', 'prefer', )
operators = ( '::', ':', '(', ')', '[', ']', '_', '=', ',', '|', '+', '-', '!', '?', )
proof_operators = ('{', '}', '.', '..')
tokens = { 'root': [ (r'\s+', Whitespace), (r'\(\*', Comment, 'comment'), (r'\\<open>', String.Symbol, 'cartouche'), (r'\{\*|‹', String, 'cartouche'),
(words(operators), Operator), (words(proof_operators), Operator.Word),
(words(keyword_minor, prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
(words(keyword_diag, prefix=r'\b', suffix=r'\b'), Keyword.Type),
(words(keyword_thy, prefix=r'\b', suffix=r'\b'), Keyword), (words(keyword_theory_decl, prefix=r'\b', suffix=r'\b'), Keyword),
(words(keyword_section, prefix=r'\b', suffix=r'\b'), Generic.Heading), (words(keyword_subsection, prefix=r'\b', suffix=r'\b'), Generic.Subheading),
(words(keyword_theory_goal, prefix=r'\b', suffix=r'\b'), Keyword.Namespace), (words(keyword_theory_script, prefix=r'\b', suffix=r'\b'), Keyword.Namespace),
(words(keyword_abandon_proof, prefix=r'\b', suffix=r'\b'), Generic.Error),
(words(keyword_qed, prefix=r'\b', suffix=r'\b'), Keyword), (words(keyword_proof_goal, prefix=r'\b', suffix=r'\b'), Keyword), (words(keyword_proof_block, prefix=r'\b', suffix=r'\b'), Keyword), (words(keyword_proof_decl, prefix=r'\b', suffix=r'\b'), Keyword),
(words(keyword_proof_chain, prefix=r'\b', suffix=r'\b'), Keyword), (words(keyword_proof_asm, prefix=r'\b', suffix=r'\b'), Keyword), (words(keyword_proof_asm_goal, prefix=r'\b', suffix=r'\b'), Keyword),
(words(keyword_proof_script, prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
(r'\\<(\w|\^)*>', Text.Symbol),
(r"'[^\W\d][.\w']*", Name.Type),
(r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex), (r'0[oO][0-7][0-7_]*', Number.Oct), (r'0[bB][01][01_]*', Number.Bin),
(r'"', String, 'string'), (r'`', String.Other, 'fact'), (r'[^\s:|\[\]\-()=,+!?{}._][^\s:|\[\]\-()=,+!?{}]*', Name), ], 'comment': [ (r'[^(*)]+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), (r'[(*)]', Comment), ], 'cartouche': [ (r'[^{*}\\‹›]+', String), (r'\\<open>', String.Symbol, '#push'), (r'\{\*|‹', String, '#push'), (r'\\<close>', String.Symbol, '#pop'), (r'\*\}|›', String, '#pop'), (r'\\<(\w|\^)*>', String.Symbol), (r'[{*}\\]', String), ], 'string': [ (r'[^"\\]+', String), (r'\\<(\w|\^)*>', String.Symbol), (r'\\"', String), (r'\\', String), (r'"', String, '#pop'), ], 'fact': [ (r'[^`\\]+', String.Other), (r'\\<(\w|\^)*>', String.Symbol), (r'\\`', String.Other), (r'\\', String.Other), (r'`', String.Other, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143""" pygments.lexers.thingsdb ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for the ThingsDB language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Comment, Keyword, Name, Number, String, Text, \ Operator, Punctuation, Whitespace
__all__ = ['ThingsDBLexer']
class ThingsDBLexer(RegexLexer): """ Lexer for the ThingsDB programming language. """ name = 'ThingsDB' aliases = ['ti', 'thingsdb'] filenames = ['*.ti'] url = 'https://www.thingsdb.net' version_added = '2.9'
tokens = { 'root': [ include('expression'), ], 'expression': [ include('comments'), include('whitespace'),
# numbers (r'[-+]?0b[01]+', Number.Bin), (r'[-+]?0o[0-8]+', Number.Oct), (r'([-+]?0x[0-9a-fA-F]+)', Number.Hex), (r'[-+]?[0-9]+', Number.Integer), (r'[-+]?((inf|nan)([^0-9A-Za-z_]|$)|[0-9]*\.[0-9]+(e[+-][0-9]+)?)', Number.Float),
# strings (r'(?:"(?:[^"]*)")+', String.Double), (r"(?:'(?:[^']*)')+", String.Single), (r"(?:`(?:[^`]*)`)+", String.Backtick),
# literals (r'(true|false|nil)\b', Keyword.Constant),
# name constants (r'(FULL|USER|GRANT|CHANGE|JOIN|RUN|QUERY|' r'DEBUG|INFO|WARNING|ERROR|CRITICAL|' r'NO_IDS|INT_MIN|INT_MAX|MATH_E|MATH_PI)\b', Name.Constant),
# regular expressions (r'(/[^/\\]*(?:\\.[^/\\]*)*/i?)', String.Regex),
# name, assignments and functions include('names'),
(r'[(){}\[\],;]', Punctuation), (r'[+\-*/%&|<>^!~@=:?]', Operator), ], 'names': [ (r'(\.)' r'(first|last|then|else|load|at|again_in|again_at|err|cancel|' r'closure|set_closure|args|set_args|owner|set_owner|equals|copy|' r'dup|assign|week|weekday|yday|zone|len|call|doc|emit|extract|' r'choice|code|format|msg|each|every|extend|extend_unique|filter|' r'find|flat|find_index|has|index_of|count|sum|is_unique|unique|' r'join|map|map_id|map_wrap|map_type|vmap|move|pop|push|fill|' r'remove|replace|restrict|restriction|shift|sort|splice|to|add|' r'one|clear|contains|ends_with|name|lower|replace|reverse|' r'starts_with|split|test|trim|trim_left|trim_right|upper|del|ren|' r'to_type|to_thing|get|id|keys|reduce|set|some|value|values|wrap|' r'unshift|unwrap|search|set_name|bit_count)' r'(\()', bygroups(Name.Function, Name.Function, Punctuation), 'arguments'), (r'(alt_raise|assert|base64_encode|base64_decode|bool|bytes|' r'closure|datetime|deep|future|is_future|del_enum|del_type|room|' r'is_room|task|tasks|is_task|is_email|is_url|is_tel|is_time_zone|' r'timeit|enum|enum_info|enum_map|enums_info|err|regex|is_regex|' r'change_id|float|has_enum|has_type|int|is_array|is_ascii|' r'is_float|is_bool|is_bytes|is_closure|is_datetime|is_enum|' r'is_err|is_mpdata|is_inf|is_int|is_list|is_nan|is_nil|is_raw|' r'is_set|is_str|is_thing|is_timeval|is_tuple|is_utf8|json_dump|' r'json_load|list|log|import|export|root|mod_enum|mod_type|new|' r'new_type|now|raise|rand|range|randint|randstr|refs|rename_enum|' r'set|set_enum|set_type|str|thing|timeval|try|type|type_assert|' r'type_all|type_count|type_info|types_info|nse|wse|backup_info|' r'backups_info|backups_ok|counters|del_backup|has_backup|' r'new_backup|node_info|nodes_info|reset_counters|restart_module|' r'set_log_level|shutdown|has_module|del_module|module_info|' r'modules_info|new_module|deploy_module|rename_module|' r'refresh_module|set_module_conf|set_module_scope|' r'collections_info|del_collection|del_expired|del_node|del_token|' r'del_user|grant|has_collection|has_node|has_token|has_user|' r'new_collection|new_node|new_token|new_user|rename_collection|' r'rename_user|restore|revoke|set_password|set_time_zone|' r'set_default_deep|time_zones_info|user_info|users_info|' r'del_procedure|has_procedure|new_procedure|mod_procedure|' r'procedure_doc|procedure_info|procedures_info|rename_procedure|' r'run|assert_err|auth_err|bad_data_err|cancelled_err|' r'rename_type|forbidden_err|lookup_err|max_quota_err|node_err|' r'num_arguments_err|operation_err|overflow_err|syntax_err|' r'collection_info|type_err|value_err|zero_div_err|whitelist_add|' r'whitelist_del|round|abs|ceil|cos|exp|floor|log10|log2|' r'loge|pow|sin|sqrt|tan|is_module|commit|history|set_history|' r'del_history|ano)' r'(\()', bygroups(Name.Function, Punctuation), 'arguments'), (r'(\.[A-Za-z_][0-9A-Za-z_]*)' r'(\s*)(=)', bygroups(Name.Attribute, Text, Operator)), (r'\.[A-Za-z_][0-9A-Za-z_]*', Name.Attribute), (r'([A-Za-z_][0-9A-Za-z_]*)(\s*)(=)', bygroups(Name.Variable, Text, Operator)), (r'[A-Za-z_][0-9A-Za-z_]*', Name.Variable), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), ], 'comments': [ (r'//(.*?)\n', Comment.Single), (r'/\*', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'arguments': [ include('expression'), (',', Punctuation), (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), ], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859""" pygments.lexers.tlb ~~~~~~~~~~~~~~~~~~~
Lexers for TL-b.
: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 Operator, Name, \ Number, Whitespace, Punctuation, Comment
__all__ = ['TlbLexer']
class TlbLexer(RegexLexer): """ For TL-b source code. """
name = 'Tl-b' aliases = ['tlb'] filenames = ['*.tlb'] url = 'https://docs.ton.org/#/overviews/TL-B' version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace),
include('comments'),
(r'[0-9]+', Number), (words(( '+', '-', '*', '=', '?', '~', '.', '^', '==', '<', '>', '<=', '>=', '!=' )), Operator), (words(('##', '#<', '#<=')), Name.Tag), (r'#[0-9a-f]*_?', Name.Tag), (r'\$[01]*_?', Name.Tag),
(r'[a-zA-Z_][0-9a-zA-Z_]*', Name),
(r'[;():\[\]{}]', Punctuation) ],
'comments': [ (r'//.*', Comment.Singleline), (r'/\*', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354""" pygments.lexers.tls ~~~~~~~~~~~~~~~~~~~
Lexers for the TLS presentation language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""import re
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['TlsLexer']
class TlsLexer(RegexLexer): """ The TLS presentation language, described in RFC 8446. """ name = 'TLS Presentation Language' url = 'https://www.rfc-editor.org/rfc/rfc8446#section-3' filenames = [] aliases = ['tls'] mimetypes = [] version_added = '2.16'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ (r'\s+', Whitespace), # comments (r'/[*].*?[*]/', Comment.Multiline), # Keywords (words(('struct', 'enum', 'select', 'case'), suffix=r'\b'), Keyword), (words(('uint8', 'uint16', 'uint24', 'uint32', 'uint64', 'opaque'), suffix=r'\b'), Keyword.Type), # numeric literals (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer), # string literal (r'"(\\.|[^"\\])*"', String), # tokens (r'[.]{2}', Operator), (r'[+\-*/&^]', Operator), (r'[|<>=!()\[\]{}.,;:\?]', Punctuation), # identifiers (r'[^\W\d]\w*', Name.Other), ] }.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/q.pyAdded+187
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/qvt.pyAdded+153
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rdf.pyAdded+468
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rebol.pyAdded+419
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rego.pyAdded+57
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rell.pyAdded+68
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/resource.pyAdded+83
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ride.pyAdded+138
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rita.pyAdded+42
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rnc.pyAdded+66
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/roboconf.pyAdded+81
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/robotframework.pyAdded+551
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/ruby.pyAdded+518
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/rust.pyAdded+222
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sas.pyAdded+227
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/savi.pyAdded+171
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/scdoc.pyAdded+85
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/scripting.pyAdded+1638
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sgf.pyAdded+59
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/shell.pyAdded+902
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sieve.pyAdded+78
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/slash.pyAdded+183
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/smalltalk.pyAdded+194
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/smithy.pyAdded+77
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/smv.pyAdded+78
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/snobol.pyAdded+82
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/solidity.pyAdded+87
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/soong.pyAdded+78
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sophia.pyAdded+102
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/special.pyAdded+122
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/spice.pyAdded+70
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/sql.pyAdded+1111
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/srcinfo.pyAdded+62
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/stata.pyAdded+170
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/supercollider.pyAdded+94
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tablegen.pyAdded+177
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tact.pyAdded+303
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tal.pyAdded+77
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tcl.pyAdded+148
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/teal.pyAdded+88
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/templates.pyAdded+2355
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/teraterm.pyAdded+335
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/testing.pyAdded+209
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/text.pyAdded+27
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/textedit.pyAdded+205
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/textfmts.pyAdded+436
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/theorem.pyAdded+410
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/thingsdb.pyAdded+143
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tlb.pyAdded+59
.cache/uv/archive-v0/6WaZhd1wSprhjD1HCu34f/pygments/lexers/tls.pyAdded+54