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/8HXDPXsFSToj27nOg3aiO/pygments/console.pyAdded+70
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/javascript.pyAdded+1591
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/jsonnet.pyAdded+169
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/jsx.pyAdded+100
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/julia.pyAdded+294
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/jvm.pyAdded+1807
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/kuin.pyAdded+332
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/kusto.pyAdded+93
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/ldap.pyAdded+155
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/lean.pyAdded+241
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/lilypond.pyAdded+225
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/lisp.pyAdded
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/macaulay2.pyAdded+1847
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/make.pyAdded+212
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/maple.pyAdded+291
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/markup.pyAdded+1659
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/math.pyAdded+21
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/matlab.pyAdded
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/maxima.pyAdded+84
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/meson.pyAdded+139
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mime.pyAdded+210
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/minecraft.pyAdded+392
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mips.pyAdded+130
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/ml.pyAdded+958
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/modeling.pyAdded+368
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/modula2.pyAdded+1579
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mojo.pyAdded+707
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/monte.pyAdded+203
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mosel.pyAdded+447
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/ncl.pyAdded+894
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/nimrod.pyAdded+199
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/nit.pyAdded+63
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/nix.pyAdded+144
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/numbair.pyAdded+63
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/objective.pyAdded+513
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/openscad.pyAdded+96
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/other.pyAdded+41
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/parasail.pyAdded+78
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/parsers.pyAdded+798
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pascal.pyAdded+644
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pddl.pyAdded+82
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/perl.pyAdded+733
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/phix.pyAdded+363
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/php.pyAdded+335
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pointless.pyAdded+70
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pony.pyAdded+93
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/praat.pyAdded+303
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/procfile.pyAdded+41
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/prolog.pyAdded+318
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/promql.pyAdded+176
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970""" pygments.console ~~~~~~~~~~~~~~~~
Format colored console output.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
esc = "\x1b["
codes = {}codes[""] = ""codes["reset"] = esc + "39;49;00m"
codes["bold"] = esc + "01m"codes["faint"] = esc + "02m"codes["standout"] = esc + "03m"codes["underline"] = esc + "04m"codes["blink"] = esc + "05m"codes["overline"] = esc + "06m"
dark_colors = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "gray"]light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue", "brightmagenta", "brightcyan", "white"]
x = 30for dark, light in zip(dark_colors, light_colors): codes[dark] = esc + "%im" % x codes[light] = esc + "%im" % (60 + x) x += 1
del dark, light, x
codes["white"] = codes["bold"]
def reset_color(): return codes["reset"]
def colorize(color_key, text): return codes[color_key] + text + codes["reset"]
def ansiformat(attr, text): """ Format ``text`` with a color and/or some attributes::
color normal color *color* bold color _color_ underlined color +color+ blinking color """ result = [] if attr[:1] == attr[-1:] == '+': result.append(codes['blink']) attr = attr[1:-1] if attr[:1] == attr[-1:] == '*': result.append(codes['bold']) attr = attr[1:-1] if attr[:1] == attr[-1:] == '_': result.append(codes['underline']) attr = attr[1:-1] result.append(codes[attr]) result.append(text) result.append(codes['reset']) return ''.join(result)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591""" pygments.lexers.javascript ~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for JavaScript 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 bygroups, combined, default, do_insertions, include, \ inherit, Lexer, RegexLexer, this, using, words, line_refrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Other, Generic, Whitespacefrom pygments.util import get_bool_optimport pygments.unistring as uni
__all__ = ['JavascriptLexer', 'KalLexer', 'LiveScriptLexer', 'DartLexer', 'TypeScriptLexer', 'LassoLexer', 'ObjectiveJLexer', 'CoffeeScriptLexer', 'MaskLexer', 'EarlGreyLexer', 'JuttleLexer', 'NodeConsoleLexer']
JS_IDENT_START = ('(?:[$_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + ']|\\\\u[a-fA-F0-9]{4})')JS_IDENT_PART = ('(?:[$' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Mn', 'Mc', 'Nd', 'Pc') + '\u200c\u200d]|\\\\u[a-fA-F0-9]{4})')JS_IDENT = JS_IDENT_START + '(?:' + JS_IDENT_PART + ')*'
class JavascriptLexer(RegexLexer): """ For JavaScript source code. """
name = 'JavaScript' url = 'https://www.ecma-international.org/publications-and-standards/standards/ecma-262/' aliases = ['javascript', 'js'] filenames = ['*.js', '*.jsm', '*.mjs', '*.cjs'] mimetypes = ['application/javascript', 'application/x-javascript', 'text/x-javascript', 'text/javascript'] version_added = ''
flags = re.DOTALL | re.MULTILINE
tokens = { 'commentsandwhitespace': [ (r'\s+', Whitespace), (r'<!--', Comment), (r'//.*?$', Comment.Single), (r'/\*.*?\*/', Comment.Multiline) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gimuysd]+\b|\B)', String.Regex, '#pop'), (r'(?=/)', Text, ('#pop', 'badregex')), default('#pop') ], 'badregex': [ (r'\n', Whitespace, '#pop') ], 'root': [ (r'\A#! ?/.*?$', Comment.Hashbang), # recognized by node.js (r'^(?=\s|/|<!--)', Text, 'slashstartsregex'), include('commentsandwhitespace'),
# Numeric literals (r'0[bB][01]+n?', Number.Bin), (r'0[oO]?[0-7]+n?', Number.Oct), # Browsers support "0o7" and "07" (< ES5) notations (r'0[xX][0-9a-fA-F]+n?', Number.Hex), (r'[0-9]+n', Number.Integer), # Javascript BigInt requires an "n" postfix # Javascript doesn't have actual integer literals, so every other # numeric literal is handled by the regex below (including "normal") # integers (r'(\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)([eE][-+]?[0-9]+)?', Number.Float),
(r'\.\.\.|=>', Punctuation), (r'\+\+|--|~|\?\?=?|\?|:|\\(?=\n)|' r'(<<|>>>?|==?|!=?|(?:\*\*|\|\||&&|[-<>+*%&|^/]))=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation),
(r'(typeof|instanceof|in|void|delete|new)\b', Operator.Word, 'slashstartsregex'),
# Match stuff like: constructor (r'\b(constructor|from|as)\b', Keyword.Reserved),
(r'(for|in|while|do|break|return|continue|switch|case|default|if|else|' r'throw|try|catch|finally|yield|await|async|this|of|static|export|' r'import|debugger|extends|super)\b', Keyword, 'slashstartsregex'), (r'(var|let|const|with|function|class)\b', Keyword.Declaration, 'slashstartsregex'),
(r'(abstract|boolean|byte|char|double|enum|final|float|goto|' r'implements|int|interface|long|native|package|private|protected|' r'public|short|synchronized|throws|transient|volatile)\b', Keyword.Reserved), (r'(true|false|null|NaN|Infinity|undefined)\b', Keyword.Constant),
(r'(Array|Boolean|Date|BigInt|Function|Math|ArrayBuffer|' r'Number|Object|RegExp|String|Promise|Proxy|decodeURI|' r'decodeURIComponent|encodeURI|encodeURIComponent|' r'eval|isFinite|isNaN|parseFloat|parseInt|DataView|' r'document|window|globalThis|global|Symbol|Intl|' r'WeakSet|WeakMap|Set|Map|Reflect|JSON|Atomics|' r'Int(?:8|16|32)Array|BigInt64Array|Float32Array|Float64Array|' r'Uint8ClampedArray|Uint(?:8|16|32)Array|BigUint64Array)\b', Name.Builtin),
(r'((?:Eval|Internal|Range|Reference|Syntax|Type|URI)?Error)\b', Name.Exception),
# Match stuff like: super(argument, list) (r'(super)(\s*)(\([\w,?.$\s]+\s*\))', bygroups(Keyword, Whitespace), 'slashstartsregex'), # Match stuff like: function() {...} (r'([a-zA-Z_?.$][\w?.$]*)(?=\(\) \{)', Name.Other, 'slashstartsregex'),
(JS_IDENT, Name.Other), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'`', String.Backtick, 'interp'), # private identifier (r'#[a-zA-Z_]\w*', Name), ], 'interp': [ (r'`', String.Backtick, '#pop'), (r'\\.', String.Backtick), (r'\$\{', String.Interpol, 'interp-inside'), (r'\$', String.Backtick), (r'[^`\\$]+', String.Backtick), ], 'interp-inside': [ # TODO: should this include single-line comments and allow nesting strings? (r'\}', String.Interpol, '#pop'), include('root'), ], }
class TypeScriptLexer(JavascriptLexer): """ For TypeScript source code. """
name = 'TypeScript' url = 'https://www.typescriptlang.org/' aliases = ['typescript', 'ts'] filenames = ['*.ts'] mimetypes = ['application/x-typescript', 'text/x-typescript'] version_added = '1.6'
# Higher priority than the TypoScriptLexer, as TypeScript is far more # common these days priority = 0.5
tokens = { 'root': [ (r'(abstract|implements|private|protected|public|readonly)\b', Keyword, 'slashstartsregex'), (r'(enum|interface|override)\b', Keyword.Declaration, 'slashstartsregex'), (r'\b(declare|type)\b', Keyword.Reserved), # Match variable type keywords (r'\b(string|boolean|number)\b', Keyword.Type), # Match stuff like: module name {...} (r'\b(module)(\s*)([\w?.$]+)(\s*)', bygroups(Keyword.Reserved, Whitespace, Name.Other, Whitespace), 'slashstartsregex'), # Match stuff like: (function: return type) (r'([\w?.$]+)(\s*)(:)(\s*)([\w?.$]+)', bygroups(Name.Other, Whitespace, Operator, Whitespace, Keyword.Type)), # Match stuff like: Decorators (r'@' + JS_IDENT, Keyword.Declaration), inherit, # private identifier (r'#[a-zA-Z_]\w*', Name), ], }
class KalLexer(RegexLexer): """ For Kal source code. """
name = 'Kal' url = 'http://rzimmerman.github.io/kal' aliases = ['kal'] filenames = ['*.kal'] mimetypes = ['text/kal', 'application/kal'] version_added = '2.0'
flags = re.DOTALL tokens = { 'commentsandwhitespace': [ (r'\s+', Whitespace), (r'###[^#].*?###', Comment.Multiline), (r'(#(?!##[^#]).*?)(\n)', bygroups(Comment.Single, Whitespace)), ], 'functiondef': [ (r'([$a-zA-Z_][\w$]*)(\s*)', bygroups(Name.Function, Whitespace), '#pop'), include('commentsandwhitespace'), ], 'classdef': [ (r'\b(inherits)(\s+)(from)\b', bygroups(Keyword, Whitespace, Keyword)), (r'([$a-zA-Z_][\w$]*)(?=\s*\n)', Name.Class, '#pop'), (r'[$a-zA-Z_][\w$]*\b', Name.Class), include('commentsandwhitespace'), ], 'listcomprehension': [ (r'\]', Punctuation, '#pop'), (r'\b(property|value)\b', Keyword), include('root'), ], 'waitfor': [ (r'\n', Whitespace, '#pop'), (r'\bfrom\b', Keyword), include('root'), ], 'root': [ include('commentsandwhitespace'), (r'/(?! )(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gimuysd]+\b|\B)', String.Regex), (r'\?|:|_(?=\n)|==?|!=|-(?!>)|[<>+*/-]=?', Operator), (r'\b(and|or|isnt|is|not|but|bitwise|mod|\^|xor|exists|' r'doesnt\s+exist)\b', Operator.Word), (r'(\([^()]+\))?(\s*)(>)', bygroups(Name.Function, Whitespace, Punctuation)), (r'[{(]', Punctuation), (r'\[', Punctuation, 'listcomprehension'), (r'[})\].,]', Punctuation), (r'\b(function|method|task)\b', Keyword.Declaration, 'functiondef'), (r'\bclass\b', Keyword.Declaration, 'classdef'), (r'\b(safe(?=\s))?(\s*)(wait(?=\s))(\s+)(for)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword), 'waitfor'), (r'\b(me|this)(\.[$a-zA-Z_][\w.$]*)?\b', Name.Variable.Instance), (r'(?<![.$])(run)(\s+)(in)(\s+)(parallel)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(?<![.$])(for)(\s+)(parallel|series)?\b', bygroups(Keyword, Whitespace, Keyword)), (r'(?<![.$])(except)(\s+)(when)?\b', bygroups(Keyword, Whitespace, Keyword)), (r'(?<![.$])(fail)(\s+)(with)?\b', bygroups(Keyword, Whitespace, Keyword)), (r'(?<![.$])(inherits)(\s+)(from)?\b', bygroups(Keyword, Whitespace, Keyword)), (r'(?<![.$])(for)(\s+)(parallel|series)?\b', bygroups(Keyword, Whitespace, Keyword)), (words(( 'in', 'of', 'while', 'until', 'break', 'return', 'continue', 'when', 'if', 'unless', 'else', 'otherwise', 'throw', 'raise', 'try', 'catch', 'finally', 'new', 'delete', 'typeof', 'instanceof', 'super'), prefix=r'(?<![.$])', suffix=r'\b'), Keyword), (words(( 'true', 'false', 'yes', 'no', 'on', 'off', 'null', 'nothing', 'none', 'NaN', 'Infinity', 'undefined'), prefix=r'(?<![.$])', suffix=r'\b'), Keyword.Constant), (words(( 'Array', 'Boolean', 'Date', 'Error', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'String', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'eval', 'isFinite', 'isNaN', 'isSafeInteger', 'parseFloat', 'parseInt', 'document', 'window', 'globalThis', 'Symbol', 'print'), suffix=r'\b'), Name.Builtin), (r'([$a-zA-Z_][\w.$]*)(\s*)(:|[+\-*/]?\=)?\b', bygroups(Name.Variable, Whitespace, Operator)), (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), ('"""', String, 'tdqs'), ("'''", String, 'tsqs'), ('"', String, 'dqs'), ("'", String, 'sqs'), ], 'strings': [ (r'[^#\\\'"]+', String), # note that all kal strings are multi-line. # hashmarks, quotes and backslashes must be parsed one at a time ], 'interpoling_string': [ (r'\}', String.Interpol, "#pop"), include('root') ], 'dqs': [ (r'"', String, '#pop'), (r'\\.|\'', String), # double-quoted string don't need ' escapes (r'#\{', String.Interpol, "interpoling_string"), include('strings') ], 'sqs': [ (r"'", String, '#pop'), (r'#|\\.|"', String), # single quoted strings don't need " escapses include('strings') ], 'tdqs': [ (r'"""', String, '#pop'), (r'\\.|\'|"', String), # no need to escape quotes in triple-string (r'#\{', String.Interpol, "interpoling_string"), include('strings'), ], 'tsqs': [ (r"'''", String, '#pop'), (r'#|\\.|\'|"', String), # no need to escape quotes in triple-strings include('strings') ], }
class LiveScriptLexer(RegexLexer): """ For LiveScript source code. """
name = 'LiveScript' url = 'https://livescript.net/' aliases = ['livescript', 'live-script'] filenames = ['*.ls'] mimetypes = ['text/livescript'] version_added = '1.6'
flags = re.DOTALL tokens = { 'commentsandwhitespace': [ (r'\s+', Whitespace), (r'/\*.*?\*/', Comment.Multiline), (r'(#.*?)(\n)', bygroups(Comment.Single, Whitespace)), ], 'multilineregex': [ include('commentsandwhitespace'), (r'//([gimuysd]+\b|\B)', String.Regex, '#pop'), (r'/', String.Regex), (r'[^/#]+', String.Regex) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'//', String.Regex, ('#pop', 'multilineregex')), (r'/(?! )(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gimuysd]+\b|\B)', String.Regex, '#pop'), (r'/', Operator, '#pop'), default('#pop'), ], 'root': [ (r'\A(?=\s|/)', Text, 'slashstartsregex'), include('commentsandwhitespace'), (r'(?:\([^()]+\))?[ ]*[~-]{1,2}>|' r'(?:\(?[^()\n]+\)?)?[ ]*<[~-]{1,2}', Name.Function), (r'\+\+|&&|(?<![.$])\b(?:and|x?or|is|isnt|not)\b|\?|:|=|' r'\|\||\\(?=\n)|(<<|>>>?|==?|!=?|' r'~(?!\~?>)|-(?!\-?>)|<(?!\[)|(?<!\])>|' r'[+*`%&|^/])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (r'(?<![.$])(for|own|in|of|while|until|loop|break|' r'return|continue|switch|when|then|if|unless|else|' r'throw|try|catch|finally|new|delete|typeof|instanceof|super|' r'extends|this|class|by|const|var|to|til)\b', Keyword, 'slashstartsregex'), (r'(?<![.$])(true|false|yes|no|on|off|' r'null|NaN|Infinity|undefined|void)\b', Keyword.Constant), (r'(Array|Boolean|Date|Error|Function|Math|' r'Number|Object|RegExp|String|decodeURI|' r'decodeURIComponent|encodeURI|encodeURIComponent|' r'eval|isFinite|isNaN|parseFloat|parseInt|document|window|' r'globalThis|Symbol|Symbol|BigInt)\b', Name.Builtin), (r'([$a-zA-Z_][\w.\-:$]*)(\s*)([:=])(\s+)', bygroups(Name.Variable, Whitespace, Operator, Whitespace), 'slashstartsregex'), (r'(@[$a-zA-Z_][\w.\-:$]*)(\s*)([:=])(\s+)', bygroups(Name.Variable.Instance, Whitespace, Operator, Whitespace), 'slashstartsregex'), (r'@', Name.Other, 'slashstartsregex'), (r'@?[$a-zA-Z_][\w-]*', Name.Other, 'slashstartsregex'), (r'[0-9]+\.[0-9]+([eE][0-9]+)?[fd]?(?:[a-zA-Z_]+)?', Number.Float), (r'[0-9]+(~[0-9a-z]+)?(?:[a-zA-Z_]+)?', Number.Integer), ('"""', String, 'tdqs'), ("'''", String, 'tsqs'), ('"', String, 'dqs'), ("'", String, 'sqs'), (r'\\\S+', String), (r'<\[.*?\]>', String), ], 'strings': [ (r'[^#\\\'"]+', String), # note that all coffee script strings are multi-line. # hashmarks, quotes and backslashes must be parsed one at a time ], 'interpoling_string': [ (r'\}', String.Interpol, "#pop"), include('root') ], 'dqs': [ (r'"', String, '#pop'), (r'\\.|\'', String), # double-quoted string don't need ' escapes (r'#\{', String.Interpol, "interpoling_string"), (r'#', String), include('strings') ], 'sqs': [ (r"'", String, '#pop'), (r'#|\\.|"', String), # single quoted strings don't need " escapses include('strings') ], 'tdqs': [ (r'"""', String, '#pop'), (r'\\.|\'|"', String), # no need to escape quotes in triple-string (r'#\{', String.Interpol, "interpoling_string"), (r'#', String), include('strings'), ], 'tsqs': [ (r"'''", String, '#pop'), (r'#|\\.|\'|"', String), # no need to escape quotes in triple-strings include('strings') ], }
class DartLexer(RegexLexer): """ For Dart source code. """
name = 'Dart' url = 'http://dart.dev/' aliases = ['dart'] filenames = ['*.dart'] mimetypes = ['text/x-dart'] version_added = '1.5'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ include('string_literal'), (r'#!(.*?)$', Comment.Preproc), (r'\b(import|export)\b', Keyword, 'import_decl'), (r'\b(library|source|part of|part)\b', Keyword), (r'[^\S\n]+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline), (r'\b(class|extension|mixin)\b(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'\b(as|assert|break|case|catch|const|continue|default|do|else|finally|' r'for|if|in|is|new|rethrow|return|super|switch|this|throw|try|while)\b', Keyword), (r'\b(abstract|async|await|const|covariant|extends|external|factory|final|' r'get|implements|late|native|on|operator|required|set|static|sync|typedef|' r'var|with|yield)\b', Keyword.Declaration), (r'\b(bool|double|dynamic|int|num|Function|Never|Null|Object|String|void)\b', Keyword.Type), (r'\b(false|null|true)\b', Keyword.Constant), (r'[~!%^&*+=|?:<>/-]|as\b', Operator), (r'@[a-zA-Z_$]\w*', Name.Decorator), (r'[a-zA-Z_$]\w*:', Name.Label), (r'[a-zA-Z_$]\w*', Name), (r'[(){}\[\],.;]', Punctuation), (r'0[xX][0-9a-fA-F]+', Number.Hex), # DIGIT+ (‘.’ DIGIT*)? EXPONENT? (r'\d+(\.\d*)?([eE][+-]?\d+)?', Number), (r'\.\d+([eE][+-]?\d+)?', Number), # ‘.’ DIGIT+ EXPONENT? (r'\n', Whitespace) # pseudo-keyword negate intentionally left out ], 'class': [ (r'[a-zA-Z_$]\w*', Name.Class, '#pop') ], 'import_decl': [ include('string_literal'), (r'\s+', Whitespace), (r'\b(as|deferred|show|hide)\b', Keyword), (r'[a-zA-Z_$]\w*', Name), (r'\,', Punctuation), (r'\;', Punctuation, '#pop') ], 'string_literal': [ # Raw strings. (r'r"""([\w\W]*?)"""', String.Double), (r"r'''([\w\W]*?)'''", String.Single), (r'r"(.*?)"', String.Double), (r"r'(.*?)'", String.Single), # Normal Strings. (r'"""', String.Double, 'string_double_multiline'), (r"'''", String.Single, 'string_single_multiline'), (r'"', String.Double, 'string_double'), (r"'", String.Single, 'string_single') ], 'string_common': [ (r"\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|u\{[0-9A-Fa-f]*\}|[a-z'\"$\\])", String.Escape), (r'(\$)([a-zA-Z_]\w*)', bygroups(String.Interpol, Name)), (r'(\$\{)(.*?)(\})', bygroups(String.Interpol, using(this), String.Interpol)) ], 'string_double': [ (r'"', String.Double, '#pop'), (r'[^"$\\\n]+', String.Double), include('string_common'), (r'\$+', String.Double) ], 'string_double_multiline': [ (r'"""', String.Double, '#pop'), (r'[^"$\\]+', String.Double), include('string_common'), (r'(\$|\")+', String.Double) ], 'string_single': [ (r"'", String.Single, '#pop'), (r"[^'$\\\n]+", String.Single), include('string_common'), (r'\$+', String.Single) ], 'string_single_multiline': [ (r"'''", String.Single, '#pop'), (r'[^\'$\\]+', String.Single), include('string_common'), (r'(\$|\')+', String.Single) ] }
class LassoLexer(RegexLexer): """ For Lasso source code, covering both Lasso 9 syntax and LassoScript for Lasso 8.6 and earlier. For Lasso embedded in HTML, use the `LassoHtmlLexer`.
Additional options accepted:
`builtinshighlighting` If given and ``True``, highlight builtin types, traits, methods, and members (default: ``True``). `requiredelimiters` If given and ``True``, only highlight code between delimiters as Lasso (default: ``False``). """
name = 'Lasso' aliases = ['lasso', 'lassoscript'] filenames = ['*.lasso', '*.lasso[89]'] version_added = '1.6' alias_filenames = ['*.incl', '*.inc', '*.las'] mimetypes = ['text/x-lasso'] url = 'https://www.lassosoft.com'
flags = re.IGNORECASE | re.DOTALL | re.MULTILINE
tokens = { 'root': [ (r'^#![ \S]+lasso9\b', Comment.Preproc, 'lasso'), (r'(?=\[|<)', Other, 'delimiters'), (r'\s+', Whitespace), default(('delimiters', 'lassofile')), ], 'delimiters': [ (r'\[no_square_brackets\]', Comment.Preproc, 'nosquarebrackets'), (r'\[noprocess\]', Comment.Preproc, 'noprocess'), (r'\[', Comment.Preproc, 'squarebrackets'), (r'<\?(lasso(script)?|=)', Comment.Preproc, 'anglebrackets'), (r'<(!--.*?-->)?', Other), (r'[^[<]+', Other), ], 'nosquarebrackets': [ (r'\[noprocess\]', Comment.Preproc, 'noprocess'), (r'\[', Other), (r'<\?(lasso(script)?|=)', Comment.Preproc, 'anglebrackets'), (r'<(!--.*?-->)?', Other), (r'[^[<]+', Other), ], 'noprocess': [ (r'\[/noprocess\]', Comment.Preproc, '#pop'), (r'\[', Other), (r'[^[]', Other), ], 'squarebrackets': [ (r'\]', Comment.Preproc, '#pop'), include('lasso'), ], 'anglebrackets': [ (r'\?>', Comment.Preproc, '#pop'), include('lasso'), ], 'lassofile': [ (r'\]|\?>', Comment.Preproc, '#pop'), include('lasso'), ], 'whitespacecomments': [ (r'\s+', Whitespace), (r'(//.*?)(\s*)$', bygroups(Comment.Single, Whitespace)), (r'/\*\*!.*?\*/', String.Doc), (r'/\*.*?\*/', Comment.Multiline), ], 'lasso': [ # whitespace/comments include('whitespacecomments'),
# literals (r'\d*\.\d+(e[+-]?\d+)?', Number.Float), (r'0x[\da-f]+', Number.Hex), (r'\d+', Number.Integer), (r'(infinity|NaN)\b', Number), (r"'", String.Single, 'singlestring'), (r'"', String.Double, 'doublestring'), (r'`[^`]*`', String.Backtick),
# names (r'\$[a-z_][\w.]*', Name.Variable), (r'#([a-z_][\w.]*|\d+\b)', Name.Variable.Instance), (r"(\.)(\s*)('[a-z_][\w.]*')", bygroups(Name.Builtin.Pseudo, Whitespace, Name.Variable.Class)), (r"(self)(\s*)(->)(\s*)('[a-z_][\w.]*')", bygroups(Name.Builtin.Pseudo, Whitespace, Operator, Whitespace, Name.Variable.Class)), (r'(\.\.?)(\s*)([a-z_][\w.]*(=(?!=))?)', bygroups(Name.Builtin.Pseudo, Whitespace, Name.Other.Member)), (r'(->\\?|&)(\s*)([a-z_][\w.]*(=(?!=))?)', bygroups(Operator, Whitespace, Name.Other.Member)), (r'(?<!->)(self|inherited|currentcapture|givenblock)\b', Name.Builtin.Pseudo), (r'-(?!infinity)[a-z_][\w.]*', Name.Attribute), (r'(::)(\s*)([a-z_][\w.]*)', bygroups(Punctuation, Whitespace, Name.Label)), (r'(error_(code|msg)_\w+|Error_AddError|Error_ColumnRestriction|' r'Error_DatabaseConnectionUnavailable|Error_DatabaseTimeout|' r'Error_DeleteError|Error_FieldRestriction|Error_FileNotFound|' r'Error_InvalidDatabase|Error_InvalidPassword|' r'Error_InvalidUsername|Error_ModuleNotFound|' r'Error_NoError|Error_NoPermission|Error_OutOfMemory|' r'Error_ReqColumnMissing|Error_ReqFieldMissing|' r'Error_RequiredColumnMissing|Error_RequiredFieldMissing|' r'Error_UpdateError)\b', Name.Exception),
# definitions (r'(define)(\s+)([a-z_][\w.]*)(\s*)(=>)(\s*)(type|trait|thread)\b', bygroups(Keyword.Declaration, Whitespace, Name.Class, Whitespace, Operator, Whitespace, Keyword)), (r'(define)(\s+)([a-z_][\w.]*)(\s*)(->)(\s*)([a-z_][\w.]*=?|[-+*/%])', bygroups(Keyword.Declaration, Whitespace, Name.Class, Whitespace, Operator, Whitespace, Name.Function), 'signature'), (r'(define)(\s+)([a-z_][\w.]*)', bygroups(Keyword.Declaration, Whitespace, Name.Function), 'signature'), (r'(public|protected|private|provide)(\s+)(([a-z_][\w.]*=?|[-+*/%])' r'(?=\s*\())', bygroups(Keyword, Whitespace, Name.Function), 'signature'), (r'(public|protected|private|provide)(\s+)([a-z_][\w.]*)', bygroups(Keyword, Whitespace, Name.Function)),
# keywords (r'(true|false|none|minimal|full|all|void)\b', Keyword.Constant), (r'(local|var|variable|global|data(?=\s))\b', Keyword.Declaration), (r'(array|date|decimal|duration|integer|map|pair|string|tag|xml|' r'null|boolean|bytes|keyword|list|locale|queue|set|stack|' r'staticarray)\b', Keyword.Type), (r'([a-z_][\w.]*)(\s+)(in)\b', bygroups(Name, Whitespace, Keyword)), (r'(let|into)(\s+)([a-z_][\w.]*)', bygroups(Keyword, Whitespace, Name)), (r'require\b', Keyword, 'requiresection'), (r'(/?)(Namespace_Using)\b', bygroups(Punctuation, Keyword.Namespace)), (r'(/?)(Cache|Database_Names|Database_SchemaNames|' r'Database_TableNames|Define_Tag|Define_Type|Email_Batch|' r'Encode_Set|HTML_Comment|Handle|Handle_Error|Header|If|Inline|' r'Iterate|LJAX_Target|Link|Link_CurrentAction|Link_CurrentGroup|' r'Link_CurrentRecord|Link_Detail|Link_FirstGroup|Link_FirstRecord|' r'Link_LastGroup|Link_LastRecord|Link_NextGroup|Link_NextRecord|' r'Link_PrevGroup|Link_PrevRecord|Log|Loop|Output_None|Portal|' r'Private|Protect|Records|Referer|Referrer|Repeating|ResultSet|' r'Rows|Search_Args|Search_Arguments|Select|Sort_Args|' r'Sort_Arguments|Thread_Atomic|Value_List|While|Abort|Case|Else|' r'Fail_If|Fail_IfNot|Fail|If_Empty|If_False|If_Null|If_True|' r'Loop_Abort|Loop_Continue|Loop_Count|Params|Params_Up|Return|' r'Return_Value|Run_Children|SOAP_DefineTag|SOAP_LastRequest|' r'SOAP_LastResponse|Tag_Name|ascending|average|by|define|' r'descending|do|equals|frozen|group|handle_failure|import|in|into|' r'join|let|match|max|min|on|order|parent|protected|provide|public|' r'require|returnhome|skip|split_thread|sum|take|thread|to|trait|' r'type|where|with|yield|yieldhome)\b', bygroups(Punctuation, Keyword)),
# other (r',', Punctuation, 'commamember'), (r'(and|or|not)\b', Operator.Word), (r'([a-z_][\w.]*)(\s*)(::)(\s*)([a-z_][\w.]*)?(\s*=(?!=))', bygroups(Name, Whitespace, Punctuation, Whitespace, Name.Label, Operator)), (r'(/?)([\w.]+)', bygroups(Punctuation, Name.Other)), (r'(=)(n?bw|n?ew|n?cn|lte?|gte?|n?eq|n?rx|ft)\b', bygroups(Operator, Operator.Word)), (r':=|[-+*/%=<>&|!?\\]+', Operator), (r'[{}():;,@^]', Punctuation), ], 'singlestring': [ (r"'", String.Single, '#pop'), (r"[^'\\]+", String.Single), include('escape'), (r"\\", String.Single), ], 'doublestring': [ (r'"', String.Double, '#pop'), (r'[^"\\]+', String.Double), include('escape'), (r'\\', String.Double), ], 'escape': [ (r'\\(U[\da-f]{8}|u[\da-f]{4}|x[\da-f]{1,2}|[0-7]{1,3}|:[^:\n\r]+:|' r'[abefnrtv?"\'\\]|$)', String.Escape), ], 'signature': [ (r'=>', Operator, '#pop'), (r'\)', Punctuation, '#pop'), (r'[(,]', Punctuation, 'parameter'), include('lasso'), ], 'parameter': [ (r'\)', Punctuation, '#pop'), (r'-?[a-z_][\w.]*', Name.Attribute, '#pop'), (r'\.\.\.', Name.Builtin.Pseudo), include('lasso'), ], 'requiresection': [ (r'(([a-z_][\w.]*=?|[-+*/%])(?=\s*\())', Name, 'requiresignature'), (r'(([a-z_][\w.]*=?|[-+*/%])(?=(\s*::\s*[\w.]+)?\s*,))', Name), (r'[a-z_][\w.]*=?|[-+*/%]', Name, '#pop'), (r'(::)(\s*)([a-z_][\w.]*)', bygroups(Punctuation, Whitespace, Name.Label)), (r',', Punctuation), include('whitespacecomments'), ], 'requiresignature': [ (r'(\)(?=(\s*::\s*[\w.]+)?\s*,))', Punctuation, '#pop'), (r'\)', Punctuation, '#pop:2'), (r'-?[a-z_][\w.]*', Name.Attribute), (r'(::)(\s*)([a-z_][\w.]*)', bygroups(Punctuation, Whitespace, Name.Label)), (r'\.\.\.', Name.Builtin.Pseudo), (r'[(,]', Punctuation), include('whitespacecomments'), ], 'commamember': [ (r'(([a-z_][\w.]*=?|[-+*/%])' r'(?=\s*(\(([^()]*\([^()]*\))*[^)]*\)\s*)?(::[\w.\s]+)?=>))', Name.Function, 'signature'), include('whitespacecomments'), default('#pop'), ], }
def __init__(self, **options): self.builtinshighlighting = get_bool_opt( options, 'builtinshighlighting', True) self.requiredelimiters = get_bool_opt( options, 'requiredelimiters', False)
self._builtins = set() self._members = set() if self.builtinshighlighting: from pygments.lexers._lasso_builtins import BUILTINS, MEMBERS for key, value in BUILTINS.items(): self._builtins.update(value) for key, value in MEMBERS.items(): self._members.update(value) RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): stack = ['root'] if self.requiredelimiters: stack.append('delimiters') for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text, stack): if (token is Name.Other and value.lower() in self._builtins or token is Name.Other.Member and value.lower().rstrip('=') in self._members): yield index, Name.Builtin, value continue yield index, token, value
def analyse_text(text): rv = 0.0 if 'bin/lasso9' in text: rv += 0.8 if re.search(r'<\?lasso', text, re.I): rv += 0.4 if re.search(r'local\(', text, re.I): rv += 0.4 return rv
class ObjectiveJLexer(RegexLexer): """ For Objective-J source code with preprocessor directives. """
name = 'Objective-J' aliases = ['objective-j', 'objectivej', 'obj-j', 'objj'] filenames = ['*.j'] mimetypes = ['text/x-objective-j'] url = 'https://www.cappuccino.dev/learn/objective-j.html' version_added = '1.3'
#: optional Comment or Whitespace _ws = r'(?:\s|//[^\n]*\n|/[*](?:[^*]|[*][^/])*[*]/)*'
flags = re.DOTALL | re.MULTILINE
tokens = { 'root': [ include('whitespace'),
# function definition (r'^(' + _ws + r'[+-]' + _ws + r')([(a-zA-Z_].*?[^(])(' + _ws + r'\{)', bygroups(using(this), using(this, state='function_signature'), using(this))),
# class definition (r'(@interface|@implementation)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(@class|@protocol)(\s*)', bygroups(Keyword, Whitespace), 'forward_classname'), (r'(\s*)(@end)(\s*)', bygroups(Whitespace, Keyword, Whitespace)),
include('statements'), ('[{()}]', Punctuation), (';', Punctuation), ], 'whitespace': [ (r'(@import)(\s+)("(?:\\\\|\\"|[^"])*")', bygroups(Comment.Preproc, Whitespace, String.Double)), (r'(@import)(\s+)(<(?:\\\\|\\>|[^>])*>)', bygroups(Comment.Preproc, Whitespace, String.Double)), (r'(#(?:include|import))(\s+)("(?:\\\\|\\"|[^"])*")', bygroups(Comment.Preproc, Whitespace, String.Double)), (r'(#(?:include|import))(\s+)(<(?:\\\\|\\>|[^>])*>)', bygroups(Comment.Preproc, Whitespace, String.Double)),
(r'#if\s+0', Comment.Preproc, 'if0'), (r'#', Comment.Preproc, 'macro'),
(r'\s+', Whitespace), (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation (r'//(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'<!--', Comment), ], 'slashstartsregex': [ include('whitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gim]+\b|\B)', String.Regex, '#pop'), (r'(?=/)', Text, ('#pop', 'badregex')), default('#pop'), ], 'badregex': [ (r'\n', Whitespace, '#pop'), ], 'statements': [ (r'(L|@)?"', String, 'string'), (r"(L|@)?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'0x[0-9a-fA-F]+[Ll]?', Number.Hex), (r'0[0-7]+[Ll]?', Number.Oct), (r'\d+[Ll]?', Number.Integer),
(r'^(?=\s|/|<!--)', Text, 'slashstartsregex'),
(r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|' r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation),
(r'(for|in|while|do|break|return|continue|switch|case|default|if|' r'else|throw|try|catch|finally|new|delete|typeof|instanceof|void|' r'prototype|__proto__)\b', Keyword, 'slashstartsregex'),
(r'(var|with|function)\b', Keyword.Declaration, 'slashstartsregex'),
(r'(@selector|@private|@protected|@public|@encode|' r'@synchronized|@try|@throw|@catch|@finally|@end|@property|' r'@synthesize|@dynamic|@for|@accessors|new)\b', Keyword),
(r'(int|long|float|short|double|char|unsigned|signed|void|' r'id|BOOL|bool|boolean|IBOutlet|IBAction|SEL|@outlet|@action)\b', Keyword.Type),
(r'(self|super)\b', Name.Builtin),
(r'(TRUE|YES|FALSE|NO|Nil|nil|NULL)\b', Keyword.Constant), (r'(true|false|null|NaN|Infinity|undefined)\b', Keyword.Constant), (r'(ABS|ASIN|ACOS|ATAN|ATAN2|SIN|COS|TAN|EXP|POW|CEIL|FLOOR|ROUND|' r'MIN|MAX|RAND|SQRT|E|LN2|LN10|LOG2E|LOG10E|PI|PI2|PI_2|SQRT1_2|' r'SQRT2)\b', Keyword.Constant),
(r'(Array|Boolean|Date|Error|Function|Math|' r'Number|Object|RegExp|String|decodeURI|' r'decodeURIComponent|encodeURI|encodeURIComponent|' r'Error|eval|isFinite|isNaN|parseFloat|parseInt|document|this|' r'window|globalThis|Symbol)\b', Name.Builtin),
(r'([$a-zA-Z_]\w*)(' + _ws + r')(?=\()', bygroups(Name.Function, using(this))),
(r'[$a-zA-Z_]\w*', Name), ], 'classname': [ # interface definition that inherits (r'([a-zA-Z_]\w*)(' + _ws + r':' + _ws + r')([a-zA-Z_]\w*)?', bygroups(Name.Class, using(this), Name.Class), '#pop'), # interface definition for a category (r'([a-zA-Z_]\w*)(' + _ws + r'\()([a-zA-Z_]\w*)(\))', bygroups(Name.Class, using(this), Name.Label, Text), '#pop'), # simple interface / implementation (r'([a-zA-Z_]\w*)', Name.Class, '#pop'), ], 'forward_classname': [ (r'([a-zA-Z_]\w*)(\s*)(,)(\s*)', bygroups(Name.Class, Whitespace, Text, Whitespace), '#push'), (r'([a-zA-Z_]\w*)(\s*)(;?)', bygroups(Name.Class, Whitespace, Text), '#pop'), ], 'function_signature': [ include('whitespace'),
# start of a selector w/ parameters (r'(\(' + _ws + r')' # open paren r'([a-zA-Z_]\w+)' # return type r'(' + _ws + r'\)' + _ws + r')' # close paren r'([$a-zA-Z_]\w+' + _ws + r':)', # function name bygroups(using(this), Keyword.Type, using(this), Name.Function), 'function_parameters'),
# no-param function (r'(\(' + _ws + r')' # open paren r'([a-zA-Z_]\w+)' # return type r'(' + _ws + r'\)' + _ws + r')' # close paren r'([$a-zA-Z_]\w+)', # function name bygroups(using(this), Keyword.Type, using(this), Name.Function), "#pop"),
# no return type given, start of a selector w/ parameters (r'([$a-zA-Z_]\w+' + _ws + r':)', # function name bygroups(Name.Function), 'function_parameters'),
# no return type given, no-param function (r'([$a-zA-Z_]\w+)', # function name bygroups(Name.Function), "#pop"),
default('#pop'), ], 'function_parameters': [ include('whitespace'),
# parameters (r'(\(' + _ws + ')' # open paren r'([^)]+)' # type r'(' + _ws + r'\)' + _ws + r')' # close paren r'([$a-zA-Z_]\w+)', # param name bygroups(using(this), Keyword.Type, using(this), Text)),
# one piece of a selector name (r'([$a-zA-Z_]\w+' + _ws + r':)', # function name Name.Function),
# smallest possible selector piece (r'(:)', Name.Function),
# var args (r'(,' + _ws + r'\.\.\.)', using(this)),
# param name (r'([$a-zA-Z_]\w+)', Text), ], 'expression': [ (r'([$a-zA-Z_]\w*)(\()', bygroups(Name.Function, Punctuation)), (r'(\))', Punctuation, "#pop"), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation (r'\\', String), # stray backslash ], 'macro': [ (r'[^/\n]+', Comment.Preproc), (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace), '#pop'), (r'/', Comment.Preproc), (r'(?<=\\)\n', Whitespace), (r'\n', Whitespace, '#pop'), ], 'if0': [ (r'^\s*#if.*?(?<!\\)\n', Comment.Preproc, '#push'), (r'^\s*#endif.*?(?<!\\)\n', Comment.Preproc, '#pop'), (r'(.*?)(\n)', bygroups(Comment, Whitespace)), ] }
def analyse_text(text): if re.search(r'^\s*@import\s+[<"]', text, re.MULTILINE): # special directive found in most Objective-J files return True return False
class CoffeeScriptLexer(RegexLexer): """ For CoffeeScript source code. """
name = 'CoffeeScript' url = 'http://coffeescript.org' aliases = ['coffeescript', 'coffee-script', 'coffee'] filenames = ['*.coffee'] mimetypes = ['text/coffeescript'] version_added = '1.3'
_operator_re = ( r'\+\+|~|&&|\band\b|\bor\b|\bis\b|\bisnt\b|\bnot\b|\?|:|' r'\|\||\\(?=\n)|' r'(<<|>>>?|==?(?!>)|!=?|=(?!>)|-(?!>)|[<>+*`%&|\^/])=?')
flags = re.DOTALL tokens = { 'commentsandwhitespace': [ (r'\s+', Whitespace), (r'###[^#].*?###', Comment.Multiline), (r'(#(?!##[^#]).*?)(\n)', bygroups(Comment.Single, Whitespace)), ], 'multilineregex': [ (r'[^/#]+', String.Regex), (r'///([gimuysd]+\b|\B)', String.Regex, '#pop'), (r'#\{', String.Interpol, 'interpoling_string'), (r'[/#]', String.Regex), ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'///', String.Regex, ('#pop', 'multilineregex')), (r'/(?! )(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gimuysd]+\b|\B)', String.Regex, '#pop'), # This isn't really guarding against mishighlighting well-formed # code, just the ability to infinite-loop between root and # slashstartsregex. (r'/', Operator, '#pop'), default('#pop'), ], 'root': [ include('commentsandwhitespace'), (r'\A(?=\s|/)', Text, 'slashstartsregex'), (_operator_re, Operator, 'slashstartsregex'), (r'(?:\([^()]*\))?\s*[=-]>', Name.Function, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (r'(?<![.$])(for|own|in|of|while|until|' r'loop|break|return|continue|' r'switch|when|then|if|unless|else|' r'throw|try|catch|finally|new|delete|typeof|instanceof|super|' r'extends|this|class|by)\b', Keyword, 'slashstartsregex'), (r'(?<![.$])(true|false|yes|no|on|off|null|' r'NaN|Infinity|undefined)\b', Keyword.Constant), (r'(Array|Boolean|Date|Error|Function|Math|' r'Number|Object|RegExp|String|decodeURI|' r'decodeURIComponent|encodeURI|encodeURIComponent|' r'eval|isFinite|isNaN|parseFloat|parseInt|document|window|globalThis|Symbol)\b', Name.Builtin), (r'([$a-zA-Z_][\w.:$]*)(\s*)([:=])(\s+)', bygroups(Name.Variable, Whitespace, Operator, Whitespace), 'slashstartsregex'), (r'(@[$a-zA-Z_][\w.:$]*)(\s*)([:=])(\s+)', bygroups(Name.Variable.Instance, Whitespace, Operator, Whitespace), 'slashstartsregex'), (r'@', Name.Other, 'slashstartsregex'), (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), ('"""', String, 'tdqs'), ("'''", String, 'tsqs'), ('"', String, 'dqs'), ("'", String, 'sqs'), ], 'strings': [ (r'[^#\\\'"]+', String), # note that all coffee script strings are multi-line. # hashmarks, quotes and backslashes must be parsed one at a time ], 'interpoling_string': [ (r'\}', String.Interpol, "#pop"), include('root') ], 'dqs': [ (r'"', String, '#pop'), (r'\\.|\'', String), # double-quoted string don't need ' escapes (r'#\{', String.Interpol, "interpoling_string"), (r'#', String), include('strings') ], 'sqs': [ (r"'", String, '#pop'), (r'#|\\.|"', String), # single quoted strings don't need " escapses include('strings') ], 'tdqs': [ (r'"""', String, '#pop'), (r'\\.|\'|"', String), # no need to escape quotes in triple-string (r'#\{', String.Interpol, "interpoling_string"), (r'#', String), include('strings'), ], 'tsqs': [ (r"'''", String, '#pop'), (r'#|\\.|\'|"', String), # no need to escape quotes in triple-strings include('strings') ], }
class MaskLexer(RegexLexer): """ For Mask markup. """ name = 'Mask' url = 'https://github.com/atmajs/MaskJS' aliases = ['mask'] filenames = ['*.mask'] mimetypes = ['text/x-mask'] version_added = '2.0'
flags = re.MULTILINE | re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'\s+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline), (r'[{};>]', Punctuation), (r"'''", String, 'string-trpl-single'), (r'"""', String, 'string-trpl-double'), (r"'", String, 'string-single'), (r'"', String, 'string-double'), (r'([\w-]+)', Name.Tag, 'node'), (r'([^.#;{>\s]+)', Name.Class, 'node'), (r'(#[\w-]+)', Name.Function, 'node'), (r'(\.[\w-]+)', Name.Variable.Class, 'node') ], 'string-base': [ (r'\\.', String.Escape), (r'~\[', String.Interpol, 'interpolation'), (r'.', String.Single), ], 'string-single': [ (r"'", String.Single, '#pop'), include('string-base') ], 'string-double': [ (r'"', String.Single, '#pop'), include('string-base') ], 'string-trpl-single': [ (r"'''", String.Single, '#pop'), include('string-base') ], 'string-trpl-double': [ (r'"""', String.Single, '#pop'), include('string-base') ], 'interpolation': [ (r'\]', String.Interpol, '#pop'), (r'(\s*)(:)', bygroups(Whitespace, String.Interpol), 'expression'), (r'(\s*)(\w+)(:)', bygroups(Whitespace, Name.Other, Punctuation)), (r'[^\]]+', String.Interpol) ], 'expression': [ (r'[^\]]+', using(JavascriptLexer), '#pop') ], 'node': [ (r'\s+', Whitespace), (r'\.', Name.Variable.Class, 'node-class'), (r'\#', Name.Function, 'node-id'), (r'(style)([ \t]*)(=)', bygroups(Name.Attribute, Whitespace, Operator), 'node-attr-style-value'), (r'([\w:-]+)([ \t]*)(=)', bygroups(Name.Attribute, Whitespace, Operator), 'node-attr-value'), (r'[\w:-]+', Name.Attribute), (r'[>{;]', Punctuation, '#pop') ], 'node-class': [ (r'[\w-]+', Name.Variable.Class), (r'~\[', String.Interpol, 'interpolation'), default('#pop') ], 'node-id': [ (r'[\w-]+', Name.Function), (r'~\[', String.Interpol, 'interpolation'), default('#pop') ], 'node-attr-value': [ (r'\s+', Whitespace), (r'\w+', Name.Variable, '#pop'), (r"'", String, 'string-single-pop2'), (r'"', String, 'string-double-pop2'), default('#pop') ], 'node-attr-style-value': [ (r'\s+', Whitespace), (r"'", String.Single, 'css-single-end'), (r'"', String.Single, 'css-double-end'), include('node-attr-value') ], 'css-base': [ (r'\s+', Whitespace), (r";", Punctuation), (r"[\w\-]+\s*:", Name.Builtin) ], 'css-single-end': [ include('css-base'), (r"'", String.Single, '#pop:2'), (r"[^;']+", Name.Entity) ], 'css-double-end': [ include('css-base'), (r'"', String.Single, '#pop:2'), (r'[^;"]+', Name.Entity) ], 'string-single-pop2': [ (r"'", String.Single, '#pop:2'), include('string-base') ], 'string-double-pop2': [ (r'"', String.Single, '#pop:2'), include('string-base') ], }
class EarlGreyLexer(RegexLexer): """ For Earl-Grey source code.
.. versionadded: 2.1 """
name = 'Earl Grey' aliases = ['earl-grey', 'earlgrey', 'eg'] filenames = ['*.eg'] mimetypes = ['text/x-earl-grey'] url = 'https://github.com/breuleux/earl-grey' version_added = ''
tokens = { 'root': [ (r'\n', Whitespace), include('control'), (r'[^\S\n]+', Text), (r'(;;.*)(\n)', bygroups(Comment, Whitespace)), (r'[\[\]{}:(),;]', Punctuation), (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), (r'\\', Text), include('errors'), (words(( 'with', 'where', 'when', 'and', 'not', 'or', 'in', 'as', 'of', 'is'), prefix=r'(?<=\s|\[)', suffix=r'(?![\w$\-])'), Operator.Word), (r'[*@]?->', Name.Function), (r'[+\-*/~^<>%&|?!@#.]*=', Operator.Word), (r'\.{2,3}', Operator.Word), # Range Operator (r'([+*/~^<>&|?!]+)|([#\-](?=\s))|@@+(?=\s)|=+', Operator), (r'(?<![\w$\-])(var|let)(?:[^\w$])', Keyword.Declaration), include('keywords'), include('builtins'), include('assignment'), (r'''(?x) (?:()([a-zA-Z$_](?:[\w$\-]*[\w$])?)| (?<=[\s{\[(])(\.)([a-zA-Z$_](?:[\w$\-]*[\w$])?)) (?=.*%)''', bygroups(Punctuation, Name.Tag, Punctuation, Name.Class.Start), 'dbs'), (r'[rR]?`', String.Backtick, 'bt'), (r'[rR]?```', String.Backtick, 'tbt'), (r'(?<=[\s\[{(,;])\.([a-zA-Z$_](?:[\w$\-]*[\w$])?)' r'(?=[\s\]}),;])', String.Symbol), include('nested'), (r'(?:[rR]|[rR]\.[gmi]{1,3})?"', String, combined('stringescape', 'dqs')), (r'(?:[rR]|[rR]\.[gmi]{1,3})?\'', String, combined('stringescape', 'sqs')), (r'"""', String, combined('stringescape', 'tdqs')), include('tuple'), include('import_paths'), include('name'), include('numbers'), ], 'dbs': [ (r'(\.)([a-zA-Z$_](?:[\w$\-]*[\w$])?)(?=[.\[\s])', bygroups(Punctuation, Name.Class.DBS)), (r'(\[)([\^#][a-zA-Z$_](?:[\w$\-]*[\w$])?)(\])', bygroups(Punctuation, Name.Entity.DBS, Punctuation)), (r'\s+', Whitespace), (r'%', Operator.DBS, '#pop'), ], 'import_paths': [ (r'(?<=[\s:;,])(\.{1,3}(?:[\w\-]*/)*)(\w(?:[\w\-]*\w)*)(?=[\s;,])', bygroups(Text.Whitespace, Text)), ], 'assignment': [ (r'(\.)?([a-zA-Z$_](?:[\w$\-]*[\w$])?)' r'(?=\s+[+\-*/~^<>%&|?!@#.]*\=\s)', bygroups(Punctuation, Name.Variable)) ], 'errors': [ (words(('Error', 'TypeError', 'ReferenceError'), prefix=r'(?<![\w\-$.])', suffix=r'(?![\w\-$.])'), Name.Exception), (r'''(?x) (?<![\w$]) E\.[\w$](?:[\w$\-]*[\w$])? (?:\.[\w$](?:[\w$\-]*[\w$])?)* (?=[({\[?!\s])''', Name.Exception), ], 'control': [ (r'''(?x) ([a-zA-Z$_](?:[\w$-]*[\w$])?) (?!\n)\s+ (?!and|as|each\*|each|in|is|mod|of|or|when|where|with) (?=(?:[+\-*/~^<>%&|?!@#.])?[a-zA-Z$_](?:[\w$-]*[\w$])?)''', Keyword.Control), (r'([a-zA-Z$_](?:[\w$-]*[\w$])?)(?!\n)(\s+)(?=[\'"\d{\[(])', bygroups(Keyword.Control, Whitespace)), (r'''(?x) (?: (?<=[%=])| (?<=[=\-]>)| (?<=with|each|with)| (?<=each\*|where) )(\s+) ([a-zA-Z$_](?:[\w$-]*[\w$])?)(:)''', bygroups(Whitespace, Keyword.Control, Punctuation)), (r'''(?x) (?<![+\-*/~^<>%&|?!@#.])(\s+) ([a-zA-Z$_](?:[\w$-]*[\w$])?)(:)''', bygroups(Whitespace, Keyword.Control, Punctuation)), ], 'nested': [ (r'''(?x) (?<=[\w$\]})])(\.) ([a-zA-Z$_](?:[\w$-]*[\w$])?) (?=\s+with(?:\s|\n))''', bygroups(Punctuation, Name.Function)), (r'''(?x) (?<!\s)(\.) ([a-zA-Z$_](?:[\w$-]*[\w$])?) (?=[}\]).,;:\s])''', bygroups(Punctuation, Name.Field)), (r'''(?x) (?<=[\w$\]})])(\.) ([a-zA-Z$_](?:[\w$-]*[\w$])?) (?=[\[{(:])''', bygroups(Punctuation, Name.Function)), ], 'keywords': [ (words(( 'each', 'each*', 'mod', 'await', 'break', 'chain', 'continue', 'elif', 'expr-value', 'if', 'match', 'return', 'yield', 'pass', 'else', 'require', 'var', 'let', 'async', 'method', 'gen'), prefix=r'(?<![\w\-$.])', suffix=r'(?![\w\-$.])'), Keyword.Pseudo), (words(('this', 'self', '@'), prefix=r'(?<![\w\-$.])', suffix=r'(?![\w\-$])'), Keyword.Constant), (words(( 'Function', 'Object', 'Array', 'String', 'Number', 'Boolean', 'ErrorFactory', 'ENode', 'Promise'), prefix=r'(?<![\w\-$.])', suffix=r'(?![\w\-$])'), Keyword.Type), ], 'builtins': [ (words(( 'send', 'object', 'keys', 'items', 'enumerate', 'zip', 'product', 'neighbours', 'predicate', 'equal', 'nequal', 'contains', 'repr', 'clone', 'range', 'getChecker', 'get-checker', 'getProperty', 'get-property', 'getProjector', 'get-projector', 'consume', 'take', 'promisify', 'spawn', 'constructor'), prefix=r'(?<![\w\-#.])', suffix=r'(?![\w\-.])'), Name.Builtin), (words(( 'true', 'false', 'null', 'undefined'), prefix=r'(?<![\w\-$.])', suffix=r'(?![\w\-$.])'), Name.Constant), ], 'name': [ (r'@([a-zA-Z$_](?:[\w$-]*[\w$])?)', Name.Variable.Instance), (r'([a-zA-Z$_](?:[\w$-]*[\w$])?)(\+\+|\-\-)?', bygroups(Name.Symbol, Operator.Word)) ], 'tuple': [ (r'#[a-zA-Z_][\w\-]*(?=[\s{(,;])', Name.Namespace) ], 'interpoling_string': [ (r'\}', String.Interpol, '#pop'), include('root') ], 'stringescape': [ (r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|' r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], 'strings': [ (r'[^\\\'"]', String), (r'[\'"\\]', String), (r'\n', String) # All strings are multiline in EG ], 'dqs': [ (r'"', String, '#pop'), (r'\\\\|\\"|\\\n', String.Escape), include('strings') ], 'sqs': [ (r"'", String, '#pop'), (r"\\\\|\\'|\\\n", String.Escape), (r'\{', String.Interpol, 'interpoling_string'), include('strings') ], 'tdqs': [ (r'"""', String, '#pop'), include('strings'), ], 'bt': [ (r'`', String.Backtick, '#pop'), (r'(?<!`)\n', String.Backtick), (r'\^=?', String.Escape), (r'.+', String.Backtick), ], 'tbt': [ (r'```', String.Backtick, '#pop'), (r'\n', String.Backtick), (r'\^=?', String.Escape), (r'[^`]+', String.Backtick), ], 'numbers': [ (r'\d+\.(?!\.)\d*([eE][+-]?[0-9]+)?', Number.Float), (r'\d+[eE][+-]?[0-9]+', Number.Float), (r'8r[0-7]+', Number.Oct), (r'2r[01]+', Number.Bin), (r'16r[a-fA-F0-9]+', Number.Hex), (r'([3-79]|[12][0-9]|3[0-6])r[a-zA-Z\d]+(\.[a-zA-Z\d]+)?', Number.Radix), (r'\d+', Number.Integer) ], }
class JuttleLexer(RegexLexer): """ For Juttle source code. """
name = 'Juttle' url = 'http://juttle.github.io/' aliases = ['juttle'] filenames = ['*.juttle'] mimetypes = ['application/juttle', 'application/x-juttle', 'text/x-juttle', 'text/juttle'] version_added = '2.2'
flags = re.DOTALL | re.MULTILINE
tokens = { 'commentsandwhitespace': [ (r'\s+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gimuysd]+\b|\B)', String.Regex, '#pop'), (r'(?=/)', Text, ('#pop', 'badregex')), default('#pop') ], 'badregex': [ (r'\n', Text, '#pop') ], 'root': [ (r'^(?=\s|/)', Text, 'slashstartsregex'), include('commentsandwhitespace'), (r':\d{2}:\d{2}:\d{2}(\.\d*)?:', String.Moment), (r':(now|beginning|end|forever|yesterday|today|tomorrow|' r'(\d+(\.\d*)?|\.\d+)(ms|[smhdwMy])?):', String.Moment), (r':\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d*)?)?' r'(Z|[+-]\d{2}:\d{2}|[+-]\d{4})?:', String.Moment), (r':((\d+(\.\d*)?|\.\d+)[ ]+)?(millisecond|second|minute|hour|' r'day|week|month|year)[s]?' r'(([ ]+and[ ]+(\d+[ ]+)?(millisecond|second|minute|hour|' r'day|week|month|year)[s]?)' r'|[ ]+(ago|from[ ]+now))*:', String.Moment), (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|' r'(==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (r'(import|return|continue|if|else)\b', Keyword, 'slashstartsregex'), (r'(var|const|function|reducer|sub|input)\b', Keyword.Declaration, 'slashstartsregex'), (r'(batch|emit|filter|head|join|keep|pace|pass|put|read|reduce|remove|' r'sequence|skip|sort|split|tail|unbatch|uniq|view|write)\b', Keyword.Reserved), (r'(true|false|null|Infinity)\b', Keyword.Constant), (r'(Array|Date|Juttle|Math|Number|Object|RegExp|String)\b', Name.Builtin), (JS_IDENT, Name.Other), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'[0-9]+', Number.Integer), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ]
}
class NodeConsoleLexer(Lexer): """ For parsing within an interactive Node.js REPL, such as:
.. sourcecode:: nodejsrepl
> let a = 3 undefined > a 3 > let b = '4' undefined > b '4' > b == a false
.. versionadded: 2.10 """ name = 'Node.js REPL console session' aliases = ['nodejsrepl', ] mimetypes = ['text/x-nodejsrepl', ] url = 'https://nodejs.org' version_added = ''
def get_tokens_unprocessed(self, text): jslexer = JavascriptLexer(**self.options)
curcode = '' insertions = []
for match in line_re.finditer(text): line = match.group() if line.startswith('> '): insertions.append((len(curcode), [(0, Generic.Prompt, line[:1]), (1, Whitespace, line[1:2])]))
curcode += line[2:] elif line.startswith('...'): # node does a nested ... thing depending on depth code = line.lstrip('.') lead = len(line) - len(code)
insertions.append((len(curcode), [(0, Generic.Prompt, line[:lead])]))
curcode += code else: if curcode: yield from do_insertions(insertions, jslexer.get_tokens_unprocessed(curcode))
curcode = '' insertions = []
yield from do_insertions([], jslexer.get_tokens_unprocessed(line))
if curcode: yield from do_insertions(insertions, jslexer.get_tokens_unprocessed(curcode))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169""" pygments.lexers.jsonnet ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Jsonnet data templating language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import include, RegexLexer, wordsfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace
__all__ = ['JsonnetLexer']
jsonnet_token = r'[^\W\d]\w*'jsonnet_function_token = jsonnet_token + r'(?=\()'
def string_rules(quote_mark): return [ (rf"[^{quote_mark}\\]", String), (r"\\.", String.Escape), (quote_mark, String, '#pop'), ]
def quoted_field_name(quote_mark): return [ (rf'([^{quote_mark}\\]|\\.)*{quote_mark}', Name.Variable, 'field_separator') ]
class JsonnetLexer(RegexLexer): """Lexer for Jsonnet source code."""
name = 'Jsonnet' aliases = ['jsonnet'] filenames = ['*.jsonnet', '*.libsonnet'] url = "https://jsonnet.org" version_added = '' tokens = { # Not used by itself '_comments': [ (r'(//|#).*\n', Comment.Single), (r'/\*\*([^/]|/(?!\*))*\*/', String.Doc), (r'/\*([^/]|/(?!\*))*\*/', Comment), ], 'root': [ include('_comments'), (r"@'.*'", String), (r'@".*"', String), (r"'", String, 'singlestring'), (r'"', String, 'doublestring'), (r'\|\|\|(.|\n)*\|\|\|', String), # Jsonnet has no integers, only an IEEE754 64-bit float (r'[+-]?[0-9]+(.[0-9])?', Number.Float), # Omit : despite spec because it appears to be used as a field # separator (r'[!$~+\-&|^=<>*/%]', Operator), (r'\{', Punctuation, 'object'), (r'\[', Punctuation, 'array'), (r'local\b', Keyword, ('local_name')), (r'assert\b', Keyword, 'assert'), (words([ 'assert', 'else', 'error', 'false', 'for', 'if', 'import', 'importstr', 'in', 'null', 'tailstrict', 'then', 'self', 'super', 'true', ], suffix=r'\b'), Keyword), (r'\s+', Whitespace), (r'function(?=\()', Keyword, 'function_params'), (r'std\.' + jsonnet_function_token, Name.Builtin, 'function_args'), (jsonnet_function_token, Name.Function, 'function_args'), (jsonnet_token, Name.Variable), (r'[\.()]', Punctuation), ], 'singlestring': string_rules("'"), 'doublestring': string_rules('"'), 'array': [ (r',', Punctuation), (r'\]', Punctuation, '#pop'), include('root'), ], 'local_name': [ (jsonnet_function_token, Name.Function, 'function_params'), (jsonnet_token, Name.Variable), (r'\s+', Whitespace), ('(?==)', Whitespace, ('#pop', 'local_value')), ], 'local_value': [ (r'=', Operator), (r';', Punctuation, '#pop'), include('root'), ], 'assert': [ (r':', Punctuation), (r';', Punctuation, '#pop'), include('root'), ], 'function_params': [ (jsonnet_token, Name.Variable), (r'\(', Punctuation), (r'\)', Punctuation, '#pop'), (r',', Punctuation), (r'\s+', Whitespace), (r'=', Operator, 'function_param_default'), ], 'function_args': [ (r'\(', Punctuation), (r'\)', Punctuation, '#pop'), (r',', Punctuation), (r'\s+', Whitespace), include('root'), ], 'object': [ (r'\s+', Whitespace), (r'local\b', Keyword, 'object_local_name'), (r'assert\b', Keyword, 'object_assert'), (r'\[', Operator, 'field_name_expr'), (fr'(?={jsonnet_token})', Text, 'field_name'), (r'\}', Punctuation, '#pop'), (r'"', Name.Variable, 'double_field_name'), (r"'", Name.Variable, 'single_field_name'), include('_comments'), ], 'field_name': [ (jsonnet_function_token, Name.Function, ('field_separator', 'function_params') ), (jsonnet_token, Name.Variable, 'field_separator'), ], 'double_field_name': quoted_field_name('"'), 'single_field_name': quoted_field_name("'"), 'field_name_expr': [ (r'\]', Operator, 'field_separator'), include('root'), ], 'function_param_default': [ (r'(?=[,\)])', Whitespace, '#pop'), include('root'), ], 'field_separator': [ (r'\s+', Whitespace), (r'\+?::?:?', Punctuation, ('#pop', '#pop', 'field_value')), include('_comments'), ], 'field_value': [ (r',', Punctuation, '#pop'), (r'\}', Punctuation, '#pop:2'), include('root'), ], 'object_assert': [ (r':', Punctuation), (r',', Punctuation, '#pop'), include('root'), ], 'object_local_name': [ (jsonnet_token, Name.Variable, ('#pop', 'object_local_value')), (r'\s+', Whitespace), ], 'object_local_value': [ (r'=', Operator), (r',', Punctuation, '#pop'), (r'\}', Punctuation, '#pop:2'), include('root'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100""" pygments.lexers.jsx ~~~~~~~~~~~~~~~~~~~
Lexers for JSX (React) and TSX (TypeScript flavor).
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import bygroups, default, include, inheritfrom pygments.lexers.javascript import JavascriptLexer, TypeScriptLexerfrom pygments.token import Name, Operator, Punctuation, String, Text, \ Whitespace
__all__ = ['JsxLexer', 'TsxLexer']
_JSX_RULES = { "jsx": [ (r"</?>", Punctuation), # JSXFragment <>|</> (r"(<)(\w+)(\.?)", bygroups(Punctuation, Name.Tag, Punctuation), "tag"), ( r"(</)(\w+)(>)", bygroups(Punctuation, Name.Tag, Punctuation), ), ( r"(</)(\w+)", bygroups(Punctuation, Name.Tag), "fragment", ), # Same for React.Context ], "tag": [ (r"\s+", Whitespace), (r"([\w-]+)(\s*)(=)(\s*)", bygroups(Name.Attribute, Whitespace, Operator, Whitespace), "attr"), (r"[{}]+", Punctuation), (r"[\w\.]+", Name.Attribute), (r"(/?)(\s*)(>)", bygroups(Punctuation, Text, Punctuation), "#pop"), ], "fragment": [ (r"(.)(\w+)", bygroups(Punctuation, Name.Attribute)), (r"(>)", bygroups(Punctuation), "#pop"), ], "attr": [ (r"\{", Punctuation, "expression"), (r'".*?"', String, "#pop"), (r"'.*?'", String, "#pop"), default("#pop"), ], "expression": [ (r"\{", Punctuation, "#push"), (r"\}", Punctuation, "#pop"), include("root"), ],}
class JsxLexer(JavascriptLexer): """For JavaScript Syntax Extension (JSX). """
name = "JSX" aliases = ["jsx", "react"] filenames = ["*.jsx", "*.react"] mimetypes = ["text/jsx", "text/typescript-jsx"] url = "https://facebook.github.io/jsx/" version_added = '2.17'
flags = re.MULTILINE | re.DOTALL
# Use same tokens as `JavascriptLexer`, but with tags and attributes support tokens = { "root": [ include("jsx"), inherit, ], **_JSX_RULES}
class TsxLexer(TypeScriptLexer): """For TypeScript with embedded JSX """
name = "TSX" aliases = ["tsx"] filenames = ["*.tsx"] mimetypes = ["text/typescript-tsx"] url = "https://www.typescriptlang.org/docs/handbook/jsx.html" version_added = '2.19'
flags = re.MULTILINE | re.DOTALL
# Use same tokens as `TypescriptLexer`, but with tags and attributes support tokens = { "root": [ include("jsx"), inherit, ], **_JSX_RULES}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294""" pygments.lexers.julia ~~~~~~~~~~~~~~~~~~~~~
Lexers for the Julia language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import Lexer, RegexLexer, bygroups, do_insertions, \ words, includefrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespacefrom pygments.util import shebang_matchesfrom pygments.lexers._julia_builtins import OPERATORS_LIST, DOTTED_OPERATORS_LIST, \ KEYWORD_LIST, BUILTIN_LIST, LITERAL_LIST
__all__ = ['JuliaLexer', 'JuliaConsoleLexer']
# see https://docs.julialang.org/en/v1/manual/variables/#Allowed-Variable-Namesallowed_variable = \ '(?:[a-zA-Z_\u00A1-\U0010ffff][a-zA-Z_0-9!\u00A1-\U0010ffff]*)'# see https://github.com/JuliaLang/julia/blob/master/src/flisp/julia_opsuffs.hoperator_suffixes = r'[²³¹ʰʲʳʷʸˡˢˣᴬᴮᴰᴱᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᴿᵀᵁᵂᵃᵇᵈᵉᵍᵏᵐᵒᵖᵗᵘᵛᵝᵞᵟᵠᵡᵢᵣᵤᵥᵦᵧᵨᵩᵪᶜᶠᶥᶦᶫᶰᶸᶻᶿ′″‴‵‶‷⁗⁰ⁱ⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ⁿ₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎ₐₑₒₓₕₖₗₘₙₚₛₜⱼⱽ]*'
class JuliaLexer(RegexLexer): """ For Julia source code. """
name = 'Julia' url = 'https://julialang.org/' aliases = ['julia', 'jl'] filenames = ['*.jl'] mimetypes = ['text/x-julia', 'application/x-julia'] version_added = '1.6'
tokens = { 'root': [ (r'\n', Whitespace), (r'[^\S\n]+', Whitespace), (r'#=', Comment.Multiline, "blockcomment"), (r'#.*$', Comment), (r'[\[\](),;]', Punctuation),
# symbols # intercept range expressions first (r'(' + allowed_variable + r')(\s*)(:)(' + allowed_variable + ')', bygroups(Name, Whitespace, Operator, Name)), # then match :name which does not follow closing brackets, digits, or the # ::, <:, and :> operators (r'(?<![\]):<>\d.])(:' + allowed_variable + ')', String.Symbol),
# type assertions - excludes expressions like ::typeof(sin) and ::avec[1] (r'(?<=::)(\s*)(' + allowed_variable + r')\b(?![(\[])', bygroups(Whitespace, Keyword.Type)), # type comparisons # - MyType <: A or MyType >: A ('(' + allowed_variable + r')(\s*)([<>]:)(\s*)(' + allowed_variable + r')\b(?![(\[])', bygroups(Keyword.Type, Whitespace, Operator, Whitespace, Keyword.Type)), # - <: B or >: B (r'([<>]:)(\s*)(' + allowed_variable + r')\b(?![(\[])', bygroups(Operator, Whitespace, Keyword.Type)), # - A <: or A >: (r'\b(' + allowed_variable + r')(\s*)([<>]:)', bygroups(Keyword.Type, Whitespace, Operator)),
# operators # Suffixes aren't actually allowed on all operators, but we'll ignore that # since those cases are invalid Julia code. (words([*OPERATORS_LIST, *DOTTED_OPERATORS_LIST], suffix=operator_suffixes), Operator), (words(['.' + o for o in DOTTED_OPERATORS_LIST], suffix=operator_suffixes), Operator), (words(['...', '..']), Operator),
# NOTE # Patterns below work only for definition sites and thus hardly reliable. # # functions # (r'(function)(\s+)(' + allowed_variable + ')', # bygroups(Keyword, Text, Name.Function)),
# chars (r"'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,3}|\\u[a-fA-F0-9]{1,4}|" r"\\U[a-fA-F0-9]{1,6}|[^\\\'\n])'", String.Char),
# try to match trailing transpose (r'(?<=[.\w)\]])(\'' + operator_suffixes + ')+', Operator),
# raw strings (r'(raw)(""")', bygroups(String.Affix, String), 'tqrawstring'), (r'(raw)(")', bygroups(String.Affix, String), 'rawstring'), # regular expressions (r'(r)(""")', bygroups(String.Affix, String.Regex), 'tqregex'), (r'(r)(")', bygroups(String.Affix, String.Regex), 'regex'), # other strings (r'(' + allowed_variable + ')?(""")', bygroups(String.Affix, String), 'tqstring'), (r'(' + allowed_variable + ')?(")', bygroups(String.Affix, String), 'string'),
# backticks (r'(' + allowed_variable + ')?(```)', bygroups(String.Affix, String.Backtick), 'tqcommand'), (r'(' + allowed_variable + ')?(`)', bygroups(String.Affix, String.Backtick), 'command'),
# type names # - names that begin a curly expression ('(' + allowed_variable + r')(\{)', bygroups(Keyword.Type, Punctuation), 'curly'), # - names as part of bare 'where' (r'(where)(\s+)(' + allowed_variable + ')', bygroups(Keyword, Whitespace, Keyword.Type)), # - curly expressions in general (r'(\{)', Punctuation, 'curly'), # - names as part of type declaration (r'(abstract|primitive)([ \t]+)(type\b)([\s()]+)(' + allowed_variable + r')', bygroups(Keyword, Whitespace, Keyword, Text, Keyword.Type)), (r'(mutable(?=[ \t]))?([ \t]+)?(struct\b)([\s()]+)(' + allowed_variable + r')', bygroups(Keyword, Whitespace, Keyword, Text, Keyword.Type)),
# macros (r'@' + allowed_variable, Name.Decorator), (words([*OPERATORS_LIST, '..', '.', *DOTTED_OPERATORS_LIST], prefix='@', suffix=operator_suffixes), Name.Decorator),
# keywords (words(KEYWORD_LIST, suffix=r'\b'), Keyword), # builtin types (words(BUILTIN_LIST, suffix=r'\b'), Keyword.Type), # builtin literals (words(LITERAL_LIST, suffix=r'\b'), Name.Builtin),
# names (allowed_variable, Name),
# numbers (r'(\d+((_\d+)+)?\.(?!\.)(\d+((_\d+)+)?)?|\.\d+((_\d+)+)?)([eEf][+-]?[0-9]+)?', Number.Float), (r'\d+((_\d+)+)?[eEf][+-]?[0-9]+', Number.Float), (r'0x[a-fA-F0-9]+((_[a-fA-F0-9]+)+)?(\.([a-fA-F0-9]+((_[a-fA-F0-9]+)+)?)?)?p[+-]?\d+', Number.Float), (r'0b[01]+((_[01]+)+)?', Number.Bin), (r'0o[0-7]+((_[0-7]+)+)?', Number.Oct), (r'0x[a-fA-F0-9]+((_[a-fA-F0-9]+)+)?', Number.Hex), (r'\d+((_\d+)+)?', Number.Integer),
# single dot operator matched last to permit e.g. ".1" as a float (words(['.']), Operator), ],
"blockcomment": [ (r'[^=#]', Comment.Multiline), (r'#=', Comment.Multiline, '#push'), (r'=#', Comment.Multiline, '#pop'), (r'[=#]', Comment.Multiline), ],
'curly': [ (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), (allowed_variable, Keyword.Type), include('root'), ],
'tqrawstring': [ (r'"""', String, '#pop'), (r'([^"]|"[^"][^"])+', String), ], 'rawstring': [ (r'"', String, '#pop'), (r'\\"', String.Escape), (r'([^"\\]|\\[^"])+', String), ],
# Interpolation is defined as "$" followed by the shortest full # expression, which is something we can't parse. Include the most # common cases here: $word, and $(paren'd expr). 'interp': [ (r'\$' + allowed_variable, String.Interpol), (r'(\$)(\()', bygroups(String.Interpol, Punctuation), 'in-intp'), ], 'in-intp': [ (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), include('root'), ],
'string': [ (r'(")(' + allowed_variable + r'|\d+)?', bygroups(String, String.Affix), '#pop'), # FIXME: This escape pattern is not perfect. (r'\\([\\"\'$nrbtfav]|(x|u|U)[a-fA-F0-9]+|\d+)', String.Escape), include('interp'), # @printf and @sprintf formats (r'%[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?[hlL]?[E-GXc-giorsux%]', String.Interpol), (r'[^"$%\\]+', String), (r'.', String), ], 'tqstring': [ (r'(""")(' + allowed_variable + r'|\d+)?', bygroups(String, String.Affix), '#pop'), (r'\\([\\"\'$nrbtfav]|(x|u|U)[a-fA-F0-9]+|\d+)', String.Escape), include('interp'), (r'[^"$%\\]+', String), (r'.', String), ],
'regex': [ (r'(")([imsxa]*)?', bygroups(String.Regex, String.Affix), '#pop'), (r'\\"', String.Regex), (r'[^\\"]+', String.Regex), ],
'tqregex': [ (r'(""")([imsxa]*)?', bygroups(String.Regex, String.Affix), '#pop'), (r'[^"]+', String.Regex), ],
'command': [ (r'(`)(' + allowed_variable + r'|\d+)?', bygroups(String.Backtick, String.Affix), '#pop'), (r'\\[`$]', String.Escape), include('interp'), (r'[^\\`$]+', String.Backtick), (r'.', String.Backtick), ], 'tqcommand': [ (r'(```)(' + allowed_variable + r'|\d+)?', bygroups(String.Backtick, String.Affix), '#pop'), (r'\\\$', String.Escape), include('interp'), (r'[^\\`$]+', String.Backtick), (r'.', String.Backtick), ], }
def analyse_text(text): return shebang_matches(text, r'julia')
class JuliaConsoleLexer(Lexer): """ For Julia console sessions. Modeled after MatlabSessionLexer. """ name = 'Julia console' aliases = ['jlcon', 'julia-repl'] url = 'https://julialang.org/' version_added = '1.6' _example = "jlcon/console"
def get_tokens_unprocessed(self, text): jllexer = JuliaLexer(**self.options) start = 0 curcode = '' insertions = [] output = False error = False
for line in text.splitlines(keepends=True): if line.startswith('julia>'): insertions.append((len(curcode), [(0, Generic.Prompt, line[:6])])) curcode += line[6:] output = False error = False elif line.startswith('help?>') or line.startswith('shell>'): yield start, Generic.Prompt, line[:6] yield start + 6, Text, line[6:] output = False error = False elif line.startswith(' ') and not output: insertions.append((len(curcode), [(0, Whitespace, line[:6])])) curcode += line[6:] else: if curcode: yield from do_insertions( insertions, jllexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] if line.startswith('ERROR: ') or error: yield start, Generic.Error, line error = True else: yield start, Generic.Output, line output = True start += len(line)
if curcode: yield from do_insertions( insertions, jllexer.get_tokens_unprocessed(curcode))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807""" pygments.lexers.jvm ~~~~~~~~~~~~~~~~~~~
Pygments lexers for JVM languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, using, \ this, combined, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespacefrom pygments.util import shebang_matchesfrom pygments import unistring as uni
__all__ = ['JavaLexer', 'ScalaLexer', 'GosuLexer', 'GosuTemplateLexer', 'GroovyLexer', 'IokeLexer', 'ClojureLexer', 'ClojureScriptLexer', 'KotlinLexer', 'XtendLexer', 'AspectJLexer', 'CeylonLexer', 'PigLexer', 'GoloLexer', 'JasminLexer', 'SarlLexer']
class JavaLexer(RegexLexer): """ For Java source code. """
name = 'Java' url = 'https://www.oracle.com/technetwork/java/' aliases = ['java'] filenames = ['*.java'] mimetypes = ['text/x-java'] version_added = ''
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ (r'(^\s*)((?:(?:public|private|protected|static|strictfp)(?:\s+))*)(record)\b', bygroups(Whitespace, using(this), Keyword.Declaration), 'class'), (r'[^\S\n]+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline), # keywords: go before method names to avoid lexing "throw new XYZ" # as a method signature (r'(assert|break|case|catch|continue|default|do|else|finally|for|' r'if|goto|instanceof|new|return|switch|this|throw|try|while)\b', Keyword), # method names (r'((?:(?:[^\W\d]|\$)[\w.\[\]$<>?]*\s+)+?)' # return arguments r'((?:[^\W\d]|\$)[\w$]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Punctuation)), (r'@[^\W\d][\w.]*', Name.Decorator), (r'(abstract|const|enum|exports|extends|final|implements|native|non-sealed|' r'open|opens|permits|private|protected|provides|public|requires|sealed|static|strictfp|' r'super|synchronized|throws|to|transient|transitive|uses|volatile|with|yield)\b', Keyword.Declaration), (r'(boolean|byte|char|double|float|int|long|short|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'import'), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface)\b', Keyword.Declaration, 'class'), (r'(module)\b', Keyword.Declaration, 'module'), (r'(var)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'var'), (r'(import(?:\s+(?:static|module))?)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'import'), (r'"""\n', String, 'multiline_string'), (r'"', String, 'string'), (r"'\\.'|'[^\\]'|'\\u[0-9a-fA-F]{4}'", String.Char), (r'(\.)((?:[^\W\d]|\$)[\w$]*)', bygroups(Punctuation, Name.Attribute)), (r'^(\s*)(default)(:)', bygroups(Whitespace, Keyword, Punctuation)), (r'^(\s*)((?:[^\W\d]|\$)[\w$]*)(:)', bygroups(Whitespace, Name.Label, Punctuation)), (r'([^\W\d]|\$)[\w$]*', Name), (r'([0-9][0-9_]*\.([0-9][0-9_]*)?|' r'\.[0-9][0-9_]*)' r'([eE][+\-]?[0-9][0-9_]*)?[fFdD]?|' r'[0-9][eE][+\-]?[0-9][0-9_]*[fFdD]?|' r'[0-9]([eE][+\-]?[0-9][0-9_]*)?[fFdD]|' r'0[xX]([0-9a-fA-F][0-9a-fA-F_]*\.?|' r'([0-9a-fA-F][0-9a-fA-F_]*)?\.[0-9a-fA-F][0-9a-fA-F_]*)' r'[pP][+\-]?[0-9][0-9_]*[fFdD]?', Number.Float), (r'0[xX][0-9a-fA-F][0-9a-fA-F_]*[lL]?', Number.Hex), (r'0[bB][01][01_]*[lL]?', Number.Bin), (r'0[0-7_]+[lL]?', Number.Oct), (r'0|[1-9][0-9_]*[lL]?', Number.Integer), (r'[~^*!%&\[\]<>|+=/?-]', Operator), (r'[{}();:.,]', Punctuation), (r'\n', Whitespace) ], 'class': [ (r'\s+', Text), (r'([^\W\d]|\$)[\w$]*', Name.Class, '#pop') ], 'module': [ (r'\s+', Text), (r'([^\W\d]|\$)[\w$]*', Name.Class, '#pop') ], 'var': [ (r'([^\W\d]|\$)[\w$]*', Name, '#pop') ], 'import': [ (r'[\w.]+\*?', Name.Namespace, '#pop') ], 'multiline_string': [ (r'"""', String, '#pop'), (r'"', String), include('string') ], 'string': [ (r'[^\\"]+', String), (r'\\\\', String), # Escaped backslash (r'\\"', String), # Escaped quote (r'\\', String), # Bare backslash (r'"', String, '#pop'), # Closing quote ], }
class AspectJLexer(JavaLexer): """ For AspectJ source code. """
name = 'AspectJ' url = 'http://www.eclipse.org/aspectj/' aliases = ['aspectj'] filenames = ['*.aj'] mimetypes = ['text/x-aspectj'] version_added = '1.6'
aj_keywords = { 'aspect', 'pointcut', 'privileged', 'call', 'execution', 'initialization', 'preinitialization', 'handler', 'get', 'set', 'staticinitialization', 'target', 'args', 'within', 'withincode', 'cflow', 'cflowbelow', 'annotation', 'before', 'after', 'around', 'proceed', 'throwing', 'returning', 'adviceexecution', 'declare', 'parents', 'warning', 'error', 'soft', 'precedence', 'thisJoinPoint', 'thisJoinPointStaticPart', 'thisEnclosingJoinPointStaticPart', 'issingleton', 'perthis', 'pertarget', 'percflow', 'percflowbelow', 'pertypewithin', 'lock', 'unlock', 'thisAspectInstance' } aj_inter_type = {'parents:', 'warning:', 'error:', 'soft:', 'precedence:'} aj_inter_type_annotation = {'@type', '@method', '@constructor', '@field'}
def get_tokens_unprocessed(self, text): for index, token, value in JavaLexer.get_tokens_unprocessed(self, text): if token is Name and value in self.aj_keywords: yield index, Keyword, value elif token is Name.Label and value in self.aj_inter_type: yield index, Keyword, value[:-1] yield index, Operator, value[-1] elif token is Name.Decorator and value in self.aj_inter_type_annotation: yield index, Keyword, value else: yield index, token, value
class ScalaLexer(RegexLexer): """ For Scala source code. """
name = 'Scala' url = 'http://www.scala-lang.org' aliases = ['scala'] filenames = ['*.scala'] mimetypes = ['text/x-scala'] version_added = ''
flags = re.MULTILINE | re.DOTALL
opchar = '[!#%&*\\-\\/:?@^' + uni.combine('Sm', 'So') + ']' letter = '[_\\$' + uni.combine('Ll', 'Lu', 'Lo', 'Nl', 'Lt') + ']' upperLetter = '[' + uni.combine('Lu', 'Lt') + ']' letterOrDigit = f'(?:{letter}|[0-9])' letterOrDigitNoDollarSign = '(?:{}|[0-9])'.format(letter.replace('\\$', '')) alphaId = f'{letter}+' simpleInterpolatedVariable = f'{letter}{letterOrDigitNoDollarSign}*' idrest = f'{letter}{letterOrDigit}*(?:(?<=_){opchar}+)?' idUpper = f'{upperLetter}{letterOrDigit}*(?:(?<=_){opchar}+)?' plainid = f'(?:{idrest}|{opchar}+)' backQuotedId = r'`[^`]+`' anyId = rf'(?:{plainid}|{backQuotedId})' notStartOfComment = r'(?!//|/\*)' endOfLineMaybeWithComment = r'(?=\s*(//|$))'
keywords = ( 'new', 'return', 'throw', 'classOf', 'isInstanceOf', 'asInstanceOf', 'else', 'if', 'then', 'do', 'while', 'for', 'yield', 'match', 'case', 'catch', 'finally', 'try' )
operators = ( '<%', '=:=', '<:<', '<%<', '>:', '<:', '=', '==', '!=', '<=', '>=', '<>', '<', '>', '<-', '←', '->', '→', '=>', '⇒', '?', '@', '|', '-', '+', '*', '%', '~', '\\' )
storage_modifiers = ( 'private', 'protected', 'synchronized', '@volatile', 'abstract', 'final', 'lazy', 'sealed', 'implicit', 'override', '@transient', '@native' )
tokens = { 'root': [ include('whitespace'), include('comments'), include('script-header'), include('imports'), include('exports'), include('storage-modifiers'), include('annotations'), include('using'), include('declarations'), include('inheritance'), include('extension'), include('end'), include('constants'), include('strings'), include('symbols'), include('singleton-type'), include('inline'), include('quoted'), include('keywords'), include('operators'), include('punctuation'), include('names'), ],
# Includes: 'whitespace': [ (r'\s+', Whitespace), ], 'comments': [ (r'//.*?\n', Comment.Single), (r'/\*', Comment.Multiline, 'comment'), ], 'script-header': [ (r'^#!([^\n]*)$', Comment.Hashbang), ], 'imports': [ (r'\b(import)(\s+)', bygroups(Keyword, Whitespace), 'import-path'), ], 'exports': [ (r'\b(export)(\s+)(given)(\s+)', bygroups(Keyword, Whitespace, Keyword, Whitespace), 'export-path'), (r'\b(export)(\s+)', bygroups(Keyword, Whitespace), 'export-path'), ], 'storage-modifiers': [ (words(storage_modifiers, prefix=r'\b', suffix=r'\b'), Keyword), # Only highlight soft modifiers if they are eventually followed by # the correct keyword. Note that soft modifiers can be followed by a # sequence of regular modifiers; [a-z\s]* skips those, and we just # check that the soft modifier is applied to a supported statement. (r'\b(transparent|opaque|infix|open|inline)\b(?=[a-z\s]*\b' r'(def|val|var|given|type|class|trait|object|enum)\b)', Keyword), ], 'annotations': [ (rf'@{idrest}', Name.Decorator), ], 'using': [ # using is a soft keyword, can only be used in the first position of # a parameter or argument list. (r'(\()(\s*)(using)(\s)', bygroups(Punctuation, Whitespace, Keyword, Whitespace)), ], 'declarations': [ (rf'\b(def)\b(\s*){notStartOfComment}({anyId})?', bygroups(Keyword, Whitespace, Name.Function)), (rf'\b(trait)\b(\s*){notStartOfComment}({anyId})?', bygroups(Keyword, Whitespace, Name.Class)), (rf'\b(?:(case)(\s+))?(class|object|enum)\b(\s*){notStartOfComment}({anyId})?', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Class)), (rf'(?<!\.)\b(type)\b(\s*){notStartOfComment}({anyId})?', bygroups(Keyword, Whitespace, Name.Class)), (r'\b(val|var)\b', Keyword.Declaration), (rf'\b(package)(\s+)(object)\b(\s*){notStartOfComment}({anyId})?', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Namespace)), (r'\b(package)(\s+)', bygroups(Keyword, Whitespace), 'package'), (rf'\b(given)\b(\s*)({idUpper})', bygroups(Keyword, Whitespace, Name.Class)), (rf'\b(given)\b(\s*)({anyId})?', bygroups(Keyword, Whitespace, Name)), ], 'inheritance': [ (r'\b(extends|with|derives)\b(\s*)' rf'({idUpper}|{backQuotedId}|(?=\([^\)]+=>)|(?={plainid})|(?="))?', bygroups(Keyword, Whitespace, Name.Class)), ], 'extension': [ (r'\b(extension)(\s+)(?=[\[\(])', bygroups(Keyword, Whitespace)), ], 'end': [ # end is a soft keyword, should only be highlighted in certain cases (r'\b(end)(\s+)(if|while|for|match|new|extension|val|var)\b', bygroups(Keyword, Whitespace, Keyword)), (rf'\b(end)(\s+)({idUpper}){endOfLineMaybeWithComment}', bygroups(Keyword, Whitespace, Name.Class)), (rf'\b(end)(\s+)({backQuotedId}|{plainid})?{endOfLineMaybeWithComment}', bygroups(Keyword, Whitespace, Name.Namespace)), ], 'punctuation': [ (r'[{}()\[\];,.]', Punctuation), (r'(?<!:):(?!:)', Punctuation), ], 'keywords': [ (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword), ], 'operators': [ (rf'({opchar}{{2,}})(\s+)', bygroups(Operator, Whitespace)), (r'/(?![/*])', Operator), (words(operators), Operator), (rf'(?<!{opchar})(!|&&|\|\|)(?!{opchar})', Operator), ], 'constants': [ (r'\b(this|super)\b', Name.Builtin.Pseudo), (r'(true|false|null)\b', Keyword.Constant), (r'0[xX][0-9a-fA-F_]*', Number.Hex), (r'([0-9][0-9_]*\.[0-9][0-9_]*|\.[0-9][0-9_]*)' r'([eE][+-]?[0-9][0-9_]*)?[fFdD]?', Number.Float), (r'[0-9]+([eE][+-]?[0-9]+)?[fFdD]', Number.Float), (r'[0-9]+([eE][+-]?[0-9]+)[fFdD]?', Number.Float), (r'[0-9]+[lL]', Number.Integer.Long), (r'[0-9]+', Number.Integer), (r'""".*?"""(?!")', String), (r'"(\\\\|\\"|[^"])*"', String), (r"(')(\\.)(')", bygroups(String.Char, String.Escape, String.Char)), (r"'[^\\]'|'\\u[0-9a-fA-F]{4}'", String.Char), ], "strings": [ (r'[fs]"""', String, 'interpolated-string-triple'), (r'[fs]"', String, 'interpolated-string'), (r'raw"(\\\\|\\"|[^"])*"', String), ], 'symbols': [ (rf"('{plainid})(?!')", String.Symbol), ], 'singleton-type': [ (r'(\.)(type)\b', bygroups(Punctuation, Keyword)), ], 'inline': [ # inline is a soft modifier, only highlighted if followed by if, # match or parameters. (rf'\b(inline)(?=\s+({plainid}|{backQuotedId})\s*:)', Keyword), (r'\b(inline)\b(?=(?:.(?!\b(?:val|def|given)\b))*\b(if|match)\b)', Keyword), ], 'quoted': [ # '{...} or ${...} (r"['$]\{(?!')", Punctuation), # '[...] (r"'\[(?!')", Punctuation), ], 'names': [ (idUpper, Name.Class), (anyId, Name), ],
# States 'comment': [ (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'import-path': [ (r'(?<=[\n;:])', Text, '#pop'), include('comments'), (r'\b(given)\b', Keyword), include('qualified-name'), (r'\{', Punctuation, 'import-path-curly-brace'), ], 'import-path-curly-brace': [ include('whitespace'), include('comments'), (r'\b(given)\b', Keyword), (r'=>', Operator), (r'\}', Punctuation, '#pop'), (r',', Punctuation), (r'[\[\]]', Punctuation), include('qualified-name'), ], 'export-path': [ (r'(?<=[\n;:])', Text, '#pop'), include('comments'), include('qualified-name'), (r'\{', Punctuation, 'export-path-curly-brace'), ], 'export-path-curly-brace': [ include('whitespace'), include('comments'), (r'=>', Operator), (r'\}', Punctuation, '#pop'), (r',', Punctuation), include('qualified-name'), ], 'package': [ (r'(?<=[\n;])', Text, '#pop'), (r':', Punctuation, '#pop'), include('comments'), include('qualified-name'), ], 'interpolated-string-triple': [ (r'"""(?!")', String, '#pop'), (r'"', String), include('interpolated-string-common'), ], 'interpolated-string': [ (r'"', String, '#pop'), include('interpolated-string-common'), ], 'interpolated-string-brace': [ (r'\}', String.Interpol, '#pop'), (r'\{', Punctuation, 'interpolated-string-nested-brace'), include('root'), ], 'interpolated-string-nested-brace': [ (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), include('root'), ],
# Helpers 'qualified-name': [ (idUpper, Name.Class), (rf'({anyId})(\.)', bygroups(Name.Namespace, Punctuation)), (r'\.', Punctuation), (anyId, Name), (r'[^\S\n]+', Whitespace), ], 'interpolated-string-common': [ (r'[^"$\\]+', String), (r'\$\$', String.Escape), (rf'(\$)({simpleInterpolatedVariable})', bygroups(String.Interpol, Name)), (r'\$\{', String.Interpol, 'interpolated-string-brace'), (r'\\.', String), ], }
class GosuLexer(RegexLexer): """ For Gosu source code. """
name = 'Gosu' aliases = ['gosu'] filenames = ['*.gs', '*.gsx', '*.gsp', '*.vark'] mimetypes = ['text/x-gosu'] url = 'https://gosu-lang.github.io' version_added = '1.5'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][\w.\[\]]*\s+)+?)' # modifiers etc. r'([a-zA-Z_]\w*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), (r'[^\S\n]+', Whitespace), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][\w.]*', Name.Decorator), (r'(in|as|typeof|statictypeof|typeis|typeas|if|else|foreach|for|' r'index|while|do|continue|break|return|try|catch|finally|this|' r'throw|new|switch|case|default|eval|super|outer|classpath|' r'using)\b', Keyword), (r'(var|delegate|construct|function|private|internal|protected|' r'public|abstract|override|final|static|extends|transient|' r'implements|represents|readonly)\b', Keyword.Declaration), (r'(property)(\s+)(get|set)?', bygroups(Keyword.Declaration, Whitespace, Keyword.Declaration)), (r'(boolean|byte|char|double|float|int|long|short|void|block)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace)), (r'(true|false|null|NaN|Infinity)\b', Keyword.Constant), (r'(class|interface|enhancement|enum)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Class)), (r'(uses)(\s+)([\w.]+\*?)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r'"', String, 'string'), (r'(\??[.#])([a-zA-Z_]\w*)', bygroups(Operator, Name.Attribute)), (r'(:)([a-zA-Z_]\w*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_$]\w*', Name), (r'and|or|not|[\\~^*!%&\[\](){}<>|+=:;,./?-]', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'[0-9]+', Number.Integer), (r'\n', Whitespace) ], 'templateText': [ (r'(\\<)|(\\\$)', String), (r'(<%@\s+)(extends|params)', bygroups(Operator, Name.Decorator), 'stringTemplate'), (r'<%!--.*?--%>', Comment.Multiline), (r'(<%)|(<%=)', Operator, 'stringTemplate'), (r'\$\{', Operator, 'stringTemplateShorthand'), (r'.', String) ], 'string': [ (r'"', String, '#pop'), include('templateText') ], 'stringTemplate': [ (r'"', String, 'string'), (r'%>', Operator, '#pop'), include('root') ], 'stringTemplateShorthand': [ (r'"', String, 'string'), (r'\{', Operator, 'stringTemplateShorthand'), (r'\}', Operator, '#pop'), include('root') ], }
class GosuTemplateLexer(Lexer): """ For Gosu templates. """
name = 'Gosu Template' aliases = ['gst'] filenames = ['*.gst'] mimetypes = ['text/x-gosu-template'] url = 'https://gosu-lang.github.io' version_added = '1.5'
def get_tokens_unprocessed(self, text): lexer = GosuLexer() stack = ['templateText'] yield from lexer.get_tokens_unprocessed(text, stack)
class GroovyLexer(RegexLexer): """ For Groovy source code. """
name = 'Groovy' url = 'https://groovy-lang.org/' aliases = ['groovy'] filenames = ['*.groovy','*.gradle'] mimetypes = ['text/x-groovy'] version_added = '1.5'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ # Groovy allows a file to start with a shebang (r'#!(.*?)$', Comment.Preproc, 'base'), default('base'), ], 'base': [ (r'[^\S\n]+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline), # keywords: go before method names to avoid lexing "throw new XYZ" # as a method signature (r'(assert|break|case|catch|continue|default|do|else|finally|for|' r'if|goto|instanceof|new|return|switch|this|throw|try|while|in|as)\b', Keyword), # method names (r'^(\s*(?:[a-zA-Z_][\w.\[\]]*\s+)+?)' # return arguments r'(' r'[a-zA-Z_]\w*' # method name r'|"(?:\\\\|\\[^\\]|[^"\\])*"' # or double-quoted method name r"|'(?:\\\\|\\[^\\]|[^'\\])*'" # or single-quoted method name r')' r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), (r'@[a-zA-Z_][\w.]*', Name.Decorator), (r'(abstract|const|enum|extends|final|implements|native|private|' r'protected|public|static|strictfp|super|synchronized|throws|' r'transient|volatile)\b', Keyword.Declaration), (r'(def|boolean|byte|char|double|float|int|long|short|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace)), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'import'), (r'""".*?"""', String.Double), (r"'''.*?'''", String.Single), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'\$/((?!/\$).)*/\$', String), (r'/(\\\\|\\[^\\]|[^/\\])*/', String), (r"'\\.'|'[^\\]'|'\\u[0-9a-fA-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-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Whitespace) ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'import': [ (r'[\w.]+\*?', Name.Namespace, '#pop') ], }
def analyse_text(text): return shebang_matches(text, r'groovy')
class IokeLexer(RegexLexer): """ For Ioke (a strongly typed, dynamic, prototype based programming language) source. """ name = 'Ioke' url = 'https://ioke.org/' filenames = ['*.ik'] aliases = ['ioke', 'ik'] mimetypes = ['text/x-iokesrc'] version_added = '1.4' tokens = { 'interpolatableText': [ (r'(\\b|\\e|\\t|\\n|\\f|\\r|\\"|\\\\|\\#|\\\Z|\\u[0-9a-fA-F]{1,4}' r'|\\[0-3]?[0-7]?[0-7])', String.Escape), (r'#\{', Punctuation, 'textInterpolationRoot') ],
'text': [ (r'(?<!\\)"', String, '#pop'), include('interpolatableText'), (r'[^"]', String) ],
'documentation': [ (r'(?<!\\)"', String.Doc, '#pop'), include('interpolatableText'), (r'[^"]', String.Doc) ],
'textInterpolationRoot': [ (r'\}', Punctuation, '#pop'), include('root') ],
'slashRegexp': [ (r'(?<!\\)/[im-psux]*', String.Regex, '#pop'), include('interpolatableText'), (r'\\/', String.Regex), (r'[^/]', String.Regex) ],
'squareRegexp': [ (r'(?<!\\)][im-psux]*', String.Regex, '#pop'), include('interpolatableText'), (r'\\]', String.Regex), (r'[^\]]', String.Regex) ],
'squareText': [ (r'(?<!\\)]', String, '#pop'), include('interpolatableText'), (r'[^\]]', String) ],
'root': [ (r'\n', Whitespace), (r'\s+', Whitespace),
# Comments (r';(.*?)\n', Comment), (r'\A#!(.*?)\n', Comment),
# Regexps (r'#/', String.Regex, 'slashRegexp'), (r'#r\[', String.Regex, 'squareRegexp'),
# Symbols (r':[\w!:?]+', String.Symbol), (r'[\w!:?]+:(?![\w!?])', String.Other), (r':"(\\\\|\\[^\\]|[^"\\])*"', String.Symbol),
# Documentation (r'((?<=fn\()|(?<=fnx\()|(?<=method\()|(?<=macro\()|(?<=lecro\()' r'|(?<=syntax\()|(?<=dmacro\()|(?<=dlecro\()|(?<=dlecrox\()' r'|(?<=dsyntax\())(\s*)"', String.Doc, 'documentation'),
# Text (r'"', String, 'text'), (r'#\[', String, 'squareText'),
# Mimic (r'\w[\w!:?]+(?=\s*=.*mimic\s)', Name.Entity),
# Assignment (r'[a-zA-Z_][\w!:?]*(?=[\s]*[+*/-]?=[^=].*($|\.))', Name.Variable),
# keywords (r'(break|cond|continue|do|ensure|for|for:dict|for:set|if|let|' r'loop|p:for|p:for:dict|p:for:set|return|unless|until|while|' r'with)(?![\w!:?])', Keyword.Reserved),
# Origin (r'(eval|mimic|print|println)(?![\w!:?])', Keyword),
# Base (r'(cell\?|cellNames|cellOwner\?|cellOwner|cells|cell|' r'documentation|hash|identity|mimic|removeCell\!|undefineCell\!)' r'(?![\w!:?])', Keyword),
# Ground (r'(stackTraceAsText)(?![\w!:?])', Keyword),
# DefaultBehaviour Literals (r'(dict|list|message|set)(?![\w!:?])', Keyword.Reserved),
# DefaultBehaviour Case (r'(case|case:and|case:else|case:nand|case:nor|case:not|case:or|' r'case:otherwise|case:xor)(?![\w!:?])', Keyword.Reserved),
# DefaultBehaviour Reflection (r'(asText|become\!|derive|freeze\!|frozen\?|in\?|is\?|kind\?|' r'mimic\!|mimics|mimics\?|prependMimic\!|removeAllMimics\!|' r'removeMimic\!|same\?|send|thaw\!|uniqueHexId)' r'(?![\w!:?])', Keyword),
# DefaultBehaviour Aspects (r'(after|around|before)(?![\w!:?])', Keyword.Reserved),
# DefaultBehaviour (r'(kind|cellDescriptionDict|cellSummary|genSym|inspect|notice)' r'(?![\w!:?])', Keyword), (r'(use|destructuring)', Keyword.Reserved),
# DefaultBehavior BaseBehavior (r'(cell\?|cellOwner\?|cellOwner|cellNames|cells|cell|' r'documentation|identity|removeCell!|undefineCell)' r'(?![\w!:?])', Keyword),
# DefaultBehavior Internal (r'(internal:compositeRegexp|internal:concatenateText|' r'internal:createDecimal|internal:createNumber|' r'internal:createRegexp|internal:createText)' r'(?![\w!:?])', Keyword.Reserved),
# DefaultBehaviour Conditions (r'(availableRestarts|bind|error\!|findRestart|handle|' r'invokeRestart|rescue|restart|signal\!|warn\!)' r'(?![\w!:?])', Keyword.Reserved),
# constants (r'(nil|false|true)(?![\w!:?])', Name.Constant),
# names (r'(Arity|Base|Call|Condition|DateTime|Aspects|Pointcut|' r'Assignment|BaseBehavior|Boolean|Case|AndCombiner|Else|' r'NAndCombiner|NOrCombiner|NotCombiner|OrCombiner|XOrCombiner|' r'Conditions|Definitions|FlowControl|Internal|Literals|' r'Reflection|DefaultMacro|DefaultMethod|DefaultSyntax|Dict|' r'FileSystem|Ground|Handler|Hook|IO|IokeGround|Struct|' r'LexicalBlock|LexicalMacro|List|Message|Method|Mixins|' r'NativeMethod|Number|Origin|Pair|Range|Reflector|Regexp Match|' r'Regexp|Rescue|Restart|Runtime|Sequence|Set|Symbol|' r'System|Text|Tuple)(?![\w!:?])', Name.Builtin),
# functions ('(generateMatchMethod|aliasMethod|\u03bb|\u028E|fnx|fn|method|' 'dmacro|dlecro|syntax|macro|dlecrox|lecrox|lecro|syntax)' '(?![\\w!:?])', Name.Function),
# Numbers (r'-?0[xX][0-9a-fA-F]+', Number.Hex), (r'-?(\d+\.?\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), (r'-?\d+', Number.Integer),
(r'#\(', Punctuation),
# Operators (r'(&&>>|\|\|>>|\*\*>>|:::|::|\.\.\.|===|\*\*>|\*\*=|&&>|&&=|' r'\|\|>|\|\|=|\->>|\+>>|!>>|<>>>|<>>|&>>|%>>|#>>|@>>|/>>|\*>>|' r'\?>>|\|>>|\^>>|~>>|\$>>|=>>|<<=|>>=|<=>|<\->|=~|!~|=>|\+\+|' r'\-\-|<=|>=|==|!=|&&|\.\.|\+=|\-=|\*=|\/=|%=|&=|\^=|\|=|<\-|' r'\+>|!>|<>|&>|%>|#>|\@>|\/>|\*>|\?>|\|>|\^>|~>|\$>|<\->|\->|' r'<<|>>|\*\*|\?\||\?&|\|\||>|<|\*|\/|%|\+|\-|&|\^|\||=|\$|!|~|' r'\?|#|\u2260|\u2218|\u2208|\u2209)', Operator), (r'(and|nand|or|xor|nor|return|import)(?![\w!?])', Operator),
# Punctuation (r'(\`\`|\`|\'\'|\'|\.|\,|@@|@|\[|\]|\(|\)|\{|\})', Punctuation),
# kinds (r'[A-Z][\w!:?]*', Name.Class),
# default cellnames (r'[a-z_][\w!:?]*', Name) ] }
class ClojureLexer(RegexLexer): """ Lexer for Clojure source code. """ name = 'Clojure' url = 'http://clojure.org/' aliases = ['clojure', 'clj'] filenames = ['*.clj', '*.cljc'] mimetypes = ['text/x-clojure', 'application/x-clojure'] version_added = '0.11'
special_forms = ( '.', 'def', 'do', 'fn', 'if', 'let', 'new', 'quote', 'var', 'loop' )
# It's safe to consider 'ns' a declaration thing because it defines a new # namespace. declarations = ( 'def-', 'defn', 'defn-', 'defmacro', 'defmulti', 'defmethod', 'defstruct', 'defonce', 'declare', 'definline', 'definterface', 'defprotocol', 'defrecord', 'deftype', 'defproject', 'ns' )
builtins = ( '*', '+', '-', '->', '/', '<', '<=', '=', '==', '>', '>=', '..', 'accessor', 'agent', 'agent-errors', 'aget', 'alength', 'all-ns', 'alter', 'and', 'append-child', 'apply', 'array-map', 'aset', 'aset-boolean', 'aset-byte', 'aset-char', 'aset-double', 'aset-float', 'aset-int', 'aset-long', 'aset-short', 'assert', 'assoc', 'await', 'await-for', 'bean', 'binding', 'bit-and', 'bit-not', 'bit-or', 'bit-shift-left', 'bit-shift-right', 'bit-xor', 'boolean', 'branch?', 'butlast', 'byte', 'cast', 'char', 'children', 'class', 'clear-agent-errors', 'comment', 'commute', 'comp', 'comparator', 'complement', 'concat', 'conj', 'cons', 'constantly', 'cond', 'if-not', 'construct-proxy', 'contains?', 'count', 'create-ns', 'create-struct', 'cycle', 'dec', 'deref', 'difference', 'disj', 'dissoc', 'distinct', 'doall', 'doc', 'dorun', 'doseq', 'dosync', 'dotimes', 'doto', 'double', 'down', 'drop', 'drop-while', 'edit', 'end?', 'ensure', 'eval', 'every?', 'false?', 'ffirst', 'file-seq', 'filter', 'find', 'find-doc', 'find-ns', 'find-var', 'first', 'float', 'flush', 'for', 'fnseq', 'frest', 'gensym', 'get-proxy-class', 'get', 'hash-map', 'hash-set', 'identical?', 'identity', 'if-let', 'import', 'in-ns', 'inc', 'index', 'insert-child', 'insert-left', 'insert-right', 'inspect-table', 'inspect-tree', 'instance?', 'int', 'interleave', 'intersection', 'into', 'into-array', 'iterate', 'join', 'key', 'keys', 'keyword', 'keyword?', 'last', 'lazy-cat', 'lazy-cons', 'left', 'lefts', 'line-seq', 'list*', 'list', 'load', 'load-file', 'locking', 'long', 'loop', 'macroexpand', 'macroexpand-1', 'make-array', 'make-node', 'map', 'map-invert', 'map?', 'mapcat', 'max', 'max-key', 'memfn', 'merge', 'merge-with', 'meta', 'min', 'min-key', 'name', 'namespace', 'neg?', 'new', 'newline', 'next', 'nil?', 'node', 'not', 'not-any?', 'not-every?', 'not=', 'ns-imports', 'ns-interns', 'ns-map', 'ns-name', 'ns-publics', 'ns-refers', 'ns-resolve', 'ns-unmap', 'nth', 'nthrest', 'or', 'parse', 'partial', 'path', 'peek', 'pop', 'pos?', 'pr', 'pr-str', 'print', 'print-str', 'println', 'println-str', 'prn', 'prn-str', 'project', 'proxy', 'proxy-mappings', 'quot', 'rand', 'rand-int', 'range', 're-find', 're-groups', 're-matcher', 're-matches', 're-pattern', 're-seq', 'read', 'read-line', 'reduce', 'ref', 'ref-set', 'refer', 'rem', 'remove', 'remove-method', 'remove-ns', 'rename', 'rename-keys', 'repeat', 'replace', 'replicate', 'resolve', 'rest', 'resultset-seq', 'reverse', 'rfirst', 'right', 'rights', 'root', 'rrest', 'rseq', 'second', 'select', 'select-keys', 'send', 'send-off', 'seq', 'seq-zip', 'seq?', 'set', 'short', 'slurp', 'some', 'sort', 'sort-by', 'sorted-map', 'sorted-map-by', 'sorted-set', 'special-symbol?', 'split-at', 'split-with', 'str', 'string?', 'struct', 'struct-map', 'subs', 'subvec', 'symbol', 'symbol?', 'sync', 'take', 'take-nth', 'take-while', 'test', 'time', 'to-array', 'to-array-2d', 'tree-seq', 'true?', 'union', 'up', 'update-proxy', 'val', 'vals', 'var-get', 'var-set', 'var?', 'vector', 'vector-zip', 'vector?', 'when', 'when-first', 'when-let', 'when-not', 'with-local-vars', 'with-meta', 'with-open', 'with-out-str', 'xml-seq', 'xml-zip', 'zero?', 'zipmap', 'zipper')
# valid names for identifiers # well, names can only not consist fully of numbers # but this should be good enough for now
# TODO / should divide keywords/symbols into namespace/rest # but that's hard, so just pretend / is part of the name valid_name = r'(?!#)[\w!$%*+<=>?/.#|-]+'
tokens = { 'root': [ # the comments - always starting with semicolon # and going to the end of the line (r';.*$', Comment.Single),
# whitespaces - usually not relevant (r',+', Text), (r'\s+', Whitespace),
# numbers (r'-?\d+\.\d+', Number.Float), (r'-?\d+/\d+', Number), (r'-?\d+', Number.Integer), (r'0x-?[abcdef\d]+', Number.Hex),
# strings, symbols and characters (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r"'" + valid_name, String.Symbol), (r"\\(.|[a-z]+)", String.Char),
# keywords (r'::?#?' + valid_name, String.Symbol),
# special operators (r'~@|[`\'#^~&@]', Operator),
# highlight the special forms (words(special_forms, suffix=' '), Keyword),
# Technically, only the special forms are 'keywords'. The problem # is that only treating them as keywords means that things like # 'defn' and 'ns' need to be highlighted as builtins. This is ugly # and weird for most styles. So, as a compromise we're going to # highlight them as Keyword.Declarations. (words(declarations, suffix=' '), Keyword.Declaration),
# highlight the builtins (words(builtins, suffix=' '), Name.Builtin),
# the remaining functions (r'(?<=\()' + valid_name, Name.Function),
# find the remaining variables (valid_name, Name.Variable),
# Clojure accepts vector notation (r'(\[|\])', Punctuation),
# Clojure accepts map notation (r'(\{|\})', Punctuation),
# the famous parentheses! (r'(\(|\))', Punctuation), ], }
class ClojureScriptLexer(ClojureLexer): """ Lexer for ClojureScript source code. """ name = 'ClojureScript' url = 'http://clojure.org/clojurescript' aliases = ['clojurescript', 'cljs'] filenames = ['*.cljs'] mimetypes = ['text/x-clojurescript', 'application/x-clojurescript'] version_added = '2.0'
class TeaLangLexer(RegexLexer): """ For Tea source code. Only used within a TeaTemplateLexer.
.. versionadded:: 1.5 """
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][\w\.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_]\w*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), (r'[^\S\n]+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][\w\.]*', Name.Decorator), (r'(and|break|else|foreach|if|in|not|or|reverse)\b', Keyword), (r'(as|call|define)\b', Keyword.Declaration), (r'(true|false|null)\b', Keyword.Constant), (r'(template)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'template'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'import'), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'(\.)([a-zA-Z_]\w*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_]\w*:', Name.Label), (r'[a-zA-Z_\$]\w*', Name), (r'(isa|[.]{3}|[.]{2}|[=#!<>+-/%&;,.\*\\\(\)\[\]\{\}])', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Whitespace) ], 'template': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'import': [ (r'[\w.]+\*?', Name.Namespace, '#pop') ], }
class CeylonLexer(RegexLexer): """ For Ceylon source code. """
name = 'Ceylon' url = 'http://ceylon-lang.org/' aliases = ['ceylon'] filenames = ['*.ceylon'] mimetypes = ['text/x-ceylon'] version_added = '1.6'
flags = re.MULTILINE | re.DOTALL
#: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+'
tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][\w.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_]\w*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), (r'[^\S\n]+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*', Comment.Multiline, 'comment'), (r'(shared|abstract|formal|default|actual|variable|deprecated|small|' r'late|literal|doc|by|see|throws|optional|license|tagged|final|native|' r'annotation|sealed)\b', Name.Decorator), (r'(break|case|catch|continue|else|finally|for|in|' r'if|return|switch|this|throw|try|while|is|exists|dynamic|' r'nonempty|then|outer|assert|let)\b', Keyword), (r'(abstracts|extends|satisfies|' r'super|given|of|out|assign)\b', Keyword.Declaration), (r'(function|value|void|new)\b', Keyword.Type), (r'(assembly|module|package)(\s+)', bygroups(Keyword.Namespace, Whitespace)), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface|object|alias)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'import'), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r"'\\.'|'[^\\]'|'\\\{#[0-9a-fA-F]{4}\}'", String.Char), (r'(\.)([a-z_]\w*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_]\w*:', Name.Label), (r'[a-zA-Z_]\w*', Name), (r'[~^*!%&\[\](){}<>|+=:;,./?-]', Operator), (r'\d{1,3}(_\d{3})+\.\d{1,3}(_\d{3})+[kMGTPmunpf]?', Number.Float), (r'\d{1,3}(_\d{3})+\.[0-9]+([eE][+-]?[0-9]+)?[kMGTPmunpf]?', Number.Float), (r'[0-9][0-9]*\.\d{1,3}(_\d{3})+[kMGTPmunpf]?', Number.Float), (r'[0-9][0-9]*\.[0-9]+([eE][+-]?[0-9]+)?[kMGTPmunpf]?', Number.Float), (r'#([0-9a-fA-F]{4})(_[0-9a-fA-F]{4})+', Number.Hex), (r'#[0-9a-fA-F]+', Number.Hex), (r'\$([01]{4})(_[01]{4})+', Number.Bin), (r'\$[01]+', Number.Bin), (r'\d{1,3}(_\d{3})+[kMGTP]?', Number.Integer), (r'[0-9]+[kMGTP]?', Number.Integer), (r'\n', Whitespace) ], 'class': [ (r'[A-Za-z_]\w*', Name.Class, '#pop') ], 'import': [ (r'[a-z][\w.]*', Name.Namespace, '#pop') ], 'comment': [ (r'[^*/]', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], }
class KotlinLexer(RegexLexer): """ For Kotlin source code. """
name = 'Kotlin' url = 'http://kotlinlang.org/' aliases = ['kotlin'] filenames = ['*.kt', '*.kts'] mimetypes = ['text/x-kotlin'] version_added = '1.5'
flags = re.MULTILINE | re.DOTALL
kt_name = ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*')
kt_space_name = ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc', 'Zs') + r'\'~!%^&*()+=|\[\]:;,.<>/\?-]*')
kt_id = '(' + kt_name + '|`' + kt_space_name + '`)'
modifiers = (r'actual|abstract|annotation|companion|const|crossinline|' r'data|enum|expect|external|final|infix|inline|inner|' r'internal|lateinit|noinline|open|operator|override|private|' r'protected|public|sealed|suspend|tailrec|value')
tokens = { 'root': [ # Whitespaces (r'[^\S\n]+', Whitespace), (r'\s+', Whitespace), (r'\\$', String.Escape), # line continuation (r'\n', Whitespace), # Comments (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'^(#!/.+?)(\n)', bygroups(Comment.Single, Whitespace)), # shebang for kotlin scripts (r'/[*].*?[*]/', Comment.Multiline), # Keywords (r'as\?', Keyword), (r'(as|break|by|catch|constructor|continue|do|dynamic|else|finally|' r'get|for|if|init|[!]*in|[!]*is|out|reified|return|set|super|this|' r'throw|try|typealias|typeof|vararg|when|where|while)\b', Keyword), (r'it\b', Name.Builtin), # Built-in types (words(('Boolean?', 'Byte?', 'Char?', 'Double?', 'Float?', 'Int?', 'Long?', 'Short?', 'String?', 'Any?', 'Unit?')), Keyword.Type), (words(('Boolean', 'Byte', 'Char', 'Double', 'Float', 'Int', 'Long', 'Short', 'String', 'Any', 'Unit'), suffix=r'\b'), Keyword.Type), # Constants (r'(true|false|null)\b', Keyword.Constant), # Imports (r'(package|import)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Namespace)), # Dot access (r'(\?\.)((?:[^\W\d]|\$)[\w$]*)', bygroups(Operator, Name.Attribute)), (r'(\.)((?:[^\W\d]|\$)[\w$]*)', bygroups(Punctuation, Name.Attribute)), # Annotations (r'@[^\W\d][\w.]*', Name.Decorator), # Labels (r'[^\W\d][\w.]+@', Name.Decorator), # Object expression (r'(object)(\s+)(:)(\s+)', bygroups(Keyword, Whitespace, Punctuation, Whitespace), 'class'), # Types (r'((?:(?:' + modifiers + r'|fun)\s+)*)(class|interface|object)(\s+)', bygroups(using(this, state='modifiers'), Keyword.Declaration, Whitespace), 'class'), # Variables (r'(var|val)(\s+)(\()', bygroups(Keyword.Declaration, Whitespace, Punctuation), 'destructuring_assignment'), (r'((?:(?:' + modifiers + r')\s+)*)(var|val)(\s+)', bygroups(using(this, state='modifiers'), Keyword.Declaration, Whitespace), 'variable'), # Functions (r'((?:(?:' + modifiers + r')\s+)*)(fun)(\s+)', bygroups(using(this, state='modifiers'), Keyword.Declaration, Whitespace), 'function'), # Operators (r'::|!!|\?[:.]', Operator), (r'[~^*!%&\[\]<>|+=/?-]', Operator), # Punctuation (r'[{}();:.,]', Punctuation), # Strings (r'"""', String, 'multiline_string'), (r'"', String, 'string'), (r"'\\.'|'[^\\]'", String.Char), # Numbers (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFL]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number), # Identifiers (r'' + kt_id + r'((\?[^.])?)', Name) # additionally handle nullable types ], 'class': [ (kt_id, Name.Class, '#pop') ], 'variable': [ (kt_id, Name.Variable, '#pop') ], 'destructuring_assignment': [ (r',', Punctuation), (r'\s+', Whitespace), (kt_id, Name.Variable), (r'(:)(\s+)(' + kt_id + ')', bygroups(Punctuation, Whitespace, Name)), (r'<', Operator, 'generic'), (r'\)', Punctuation, '#pop') ], 'function': [ (r'<', Operator, 'generic'), (r'' + kt_id + r'(\.)' + kt_id, bygroups(Name, Punctuation, Name.Function), '#pop'), (kt_id, Name.Function, '#pop') ], 'generic': [ (r'(>)(\s*)', bygroups(Operator, Whitespace), '#pop'), (r':', Punctuation), (r'(reified|out|in)\b', Keyword), (r',', Punctuation), (r'\s+', Whitespace), (kt_id, Name) ], 'modifiers': [ (r'\w+', Keyword.Declaration), (r'\s+', Whitespace), default('#pop') ], 'string': [ (r'"', String, '#pop'), include('string_common') ], 'multiline_string': [ (r'"""', String, '#pop'), (r'"', String), include('string_common') ], 'string_common': [ (r'\\\\', String), # escaped backslash (r'\\"', String), # escaped quote (r'\\', String), # bare backslash (r'\$\{', String.Interpol, 'interpolation'), (r'(\$)(\w+)', bygroups(String.Interpol, Name)), (r'[^\\"$]+', String) ], 'interpolation': [ (r'"', String), (r'\$\{', String.Interpol, 'interpolation'), (r'\{', Punctuation, 'scope'), (r'\}', String.Interpol, '#pop'), include('root') ], 'scope': [ (r'\{', Punctuation, 'scope'), (r'\}', Punctuation, '#pop'), include('root') ] }
class XtendLexer(RegexLexer): """ For Xtend source code. """
name = 'Xtend' url = 'https://www.eclipse.org/xtend/' aliases = ['xtend'] filenames = ['*.xtend'] mimetypes = ['text/x-xtend'] version_added = '1.6'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][\w.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_$][\w$]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), (r'[^\S\n]+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][\w.]*', Name.Decorator), (r'(assert|break|case|catch|continue|default|do|else|finally|for|' r'if|goto|instanceof|new|return|switch|this|throw|try|while|IF|' r'ELSE|ELSEIF|ENDIF|FOR|ENDFOR|SEPARATOR|BEFORE|AFTER)\b', Keyword), (r'(def|abstract|const|enum|extends|final|implements|native|private|' r'protected|public|static|strictfp|super|synchronized|throws|' r'transient|volatile|val|var)\b', Keyword.Declaration), (r'(boolean|byte|char|double|float|int|long|short|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace)), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'import'), (r"(''')", String, 'template'), (r'(\u00BB)', String, 'template'), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (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-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Whitespace) ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'import': [ (r'[\w.]+\*?', Name.Namespace, '#pop') ], 'template': [ (r"'''", String, '#pop'), (r'\u00AB', String, '#pop'), (r'.', String) ], }
class PigLexer(RegexLexer): """ For Pig Latin source code. """
name = 'Pig' url = 'https://pig.apache.org/' aliases = ['pig'] filenames = ['*.pig'] mimetypes = ['text/x-pig'] version_added = '2.0'
flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ (r'\s+', Whitespace), (r'--.*', Comment), (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'\\$', String.Escape), (r'\\', Text), (r'\'(?:\\[ntbrf\\\']|\\u[0-9a-f]{4}|[^\'\\\n\r])*\'', String), include('keywords'), include('types'), include('builtins'), include('punct'), include('operators'), (r'[0-9]*\.[0-9]+(e[0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-f]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Whitespace), (r'([a-z_]\w*)(\s*)(\()', bygroups(Name.Function, Whitespace, Punctuation)), (r'[()#:]', Text), (r'[^(:#\'")\s]+', Text), (r'\S+\s+', Text) # TODO: make tests pass without \s+ ], 'keywords': [ (r'(assert|and|any|all|arrange|as|asc|bag|by|cache|CASE|cat|cd|cp|' r'%declare|%default|define|dense|desc|describe|distinct|du|dump|' r'eval|exex|explain|filter|flatten|foreach|full|generate|group|' r'help|if|illustrate|import|inner|input|into|is|join|kill|left|' r'limit|load|ls|map|matches|mkdir|mv|not|null|onschema|or|order|' r'outer|output|parallel|pig|pwd|quit|register|returns|right|rm|' r'rmf|rollup|run|sample|set|ship|split|stderr|stdin|stdout|store|' r'stream|through|union|using|void)\b', Keyword) ], 'builtins': [ (r'(AVG|BinStorage|cogroup|CONCAT|copyFromLocal|copyToLocal|COUNT|' r'cross|DIFF|MAX|MIN|PigDump|PigStorage|SIZE|SUM|TextLoader|' r'TOKENIZE)\b', Name.Builtin) ], 'types': [ (r'(bytearray|BIGINTEGER|BIGDECIMAL|chararray|datetime|double|float|' r'int|long|tuple)\b', Keyword.Type) ], 'punct': [ (r'[;(){}\[\]]', Punctuation), ], 'operators': [ (r'[#=,./%+\-?]', Operator), (r'(eq|gt|lt|gte|lte|neq|matches)\b', Operator), (r'(==|<=|<|>=|>|!=)', Operator), ], }
class GoloLexer(RegexLexer): """ For Golo source code. """
name = 'Golo' url = 'http://golo-lang.org/' filenames = ['*.golo'] aliases = ['golo'] version_added = '2.0'
tokens = { 'root': [ (r'[^\S\n]+', Whitespace),
(r'#.*$', Comment),
(r'(\^|\.\.\.|:|\?:|->|==|!=|=|\+|\*|%|/|<=|<|>=|>|=|\.)', Operator), (r'(?<=[^-])(-)(?=[^-])', Operator),
(r'(?<=[^`])(is|isnt|and|or|not|oftype|in|orIfNull)\b', Operator.Word), (r'[]{}|(),[]', Punctuation),
(r'(module|import)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'modname'), (r'\b([a-zA-Z_][\w$.]*)(::)', bygroups(Name.Namespace, Punctuation)), (r'\b([a-zA-Z_][\w$]*(?:\.[a-zA-Z_][\w$]*)+)\b', Name.Namespace),
(r'(let|var)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'varname'), (r'(struct)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'structname'), (r'(function)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'funcname'),
(r'(null|true|false)\b', Keyword.Constant), (r'(augment|pimp' r'|if|else|case|match|return' r'|case|when|then|otherwise' r'|while|for|foreach' r'|try|catch|finally|throw' r'|local' r'|continue|break)\b', Keyword),
(r'(map|array|list|set|vector|tuple)(\[)', bygroups(Name.Builtin, Punctuation)), (r'(print|println|readln|raise|fun' r'|asInterfaceInstance)\b', Name.Builtin), (r'(`?[a-zA-Z_][\w$]*)(\()', bygroups(Name.Function, Punctuation)),
(r'-?[\d_]*\.[\d_]*([eE][+-]?\d[\d_]*)?F?', Number.Float), (r'0[0-7]+j?', Number.Oct), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'-?\d[\d_]*L', Number.Integer.Long), (r'-?\d[\d_]*', Number.Integer),
(r'`?[a-zA-Z_][\w$]*', Name), (r'@[a-zA-Z_][\w$.]*', Name.Decorator),
(r'"""', String, combined('stringescape', 'triplestring')), (r'"', String, combined('stringescape', 'doublestring')), (r"'", String, combined('stringescape', 'singlestring')), (r'----((.|\n)*?)----', String.Doc)
],
'funcname': [ (r'`?[a-zA-Z_][\w$]*', Name.Function, '#pop'), ], 'modname': [ (r'[a-zA-Z_][\w$.]*\*?', Name.Namespace, '#pop') ], 'structname': [ (r'`?[\w.]+\*?', Name.Class, '#pop') ], 'varname': [ (r'`?[a-zA-Z_][\w$]*', Name.Variable, '#pop'), ], 'string': [ (r'[^\\\'"\n]+', String), (r'[\'"\\]', String) ], 'stringescape': [ (r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|' r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], 'triplestring': [ (r'"""', String, '#pop'), include('string'), (r'\n', String), ], 'doublestring': [ (r'"', String.Double, '#pop'), include('string'), ], 'singlestring': [ (r"'", String, '#pop'), include('string'), ], 'operators': [ (r'[#=,./%+\-?]', Operator), (r'(eq|gt|lt|gte|lte|neq|matches)\b', Operator), (r'(==|<=|<|>=|>|!=)', Operator), ], }
class JasminLexer(RegexLexer): """ For Jasmin assembly code. """
name = 'Jasmin' url = 'http://jasmin.sourceforge.net/' aliases = ['jasmin', 'jasminxt'] filenames = ['*.j'] version_added = '2.0'
_whitespace = r' \n\t\r' _ws = rf'(?:[{_whitespace}]+)' _separator = rf'{_whitespace}:=' _break = rf'(?=[{_separator}]|$)' _name = rf'[^{_separator}]+' _unqualified_name = rf'(?:[^{_separator}.;\[/]+)'
tokens = { 'default': [ (r'\n', Whitespace, '#pop'), (r"'", String.Single, ('#pop', 'quote')), (r'"', String.Double, 'string'), (r'=', Punctuation), (r':', Punctuation, 'label'), (_ws, Whitespace), (r';.*', Comment.Single), (rf'(\$[-+])?0x-?[\da-fA-F]+{_break}', Number.Hex), (rf'(\$[-+]|\+)?-?\d+{_break}', Number.Integer), (r'-?(\d+\.\d*|\.\d+)([eE][-+]?\d+)?[fFdD]?' rf'[\x00-\x08\x0b\x0c\x0e-\x1f]*{_break}', Number.Float), (rf'\${_name}', Name.Variable),
# Directives (rf'\.annotation{_break}', Keyword.Reserved, 'annotation'), (r'(\.attribute|\.bytecode|\.debug|\.deprecated|\.enclosing|' r'\.interface|\.line|\.signature|\.source|\.stack|\.var|abstract|' r'annotation|bridge|class|default|enum|field|final|fpstrict|' r'interface|native|private|protected|public|signature|static|' rf'synchronized|synthetic|transient|varargs|volatile){_break}', Keyword.Reserved), (rf'\.catch{_break}', Keyword.Reserved, 'caught-exception'), (r'(\.class|\.implements|\.inner|\.super|inner|invisible|' rf'invisibleparam|outer|visible|visibleparam){_break}', Keyword.Reserved, 'class/convert-dots'), (rf'\.field{_break}', Keyword.Reserved, ('descriptor/convert-dots', 'field')), (rf'(\.end|\.limit|use){_break}', Keyword.Reserved, 'no-verification'), (rf'\.method{_break}', Keyword.Reserved, 'method'), (rf'\.set{_break}', Keyword.Reserved, 'var'), (rf'\.throws{_break}', Keyword.Reserved, 'exception'), (rf'(from|offset|to|using){_break}', Keyword.Reserved, 'label'), (rf'is{_break}', Keyword.Reserved, ('descriptor/convert-dots', 'var')), (rf'(locals|stack){_break}', Keyword.Reserved, 'verification'), (rf'method{_break}', Keyword.Reserved, 'enclosing-method'),
# Instructions (words(( 'aaload', 'aastore', 'aconst_null', 'aload', 'aload_0', 'aload_1', 'aload_2', 'aload_3', 'aload_w', 'areturn', 'arraylength', 'astore', 'astore_0', 'astore_1', 'astore_2', 'astore_3', 'astore_w', 'athrow', 'baload', 'bastore', 'bipush', 'breakpoint', 'caload', 'castore', 'd2f', 'd2i', 'd2l', 'dadd', 'daload', 'dastore', 'dcmpg', 'dcmpl', 'dconst_0', 'dconst_1', 'ddiv', 'dload', 'dload_0', 'dload_1', 'dload_2', 'dload_3', 'dload_w', 'dmul', 'dneg', 'drem', 'dreturn', 'dstore', 'dstore_0', 'dstore_1', 'dstore_2', 'dstore_3', 'dstore_w', 'dsub', 'dup', 'dup2', 'dup2_x1', 'dup2_x2', 'dup_x1', 'dup_x2', 'f2d', 'f2i', 'f2l', 'fadd', 'faload', 'fastore', 'fcmpg', 'fcmpl', 'fconst_0', 'fconst_1', 'fconst_2', 'fdiv', 'fload', 'fload_0', 'fload_1', 'fload_2', 'fload_3', 'fload_w', 'fmul', 'fneg', 'frem', 'freturn', 'fstore', 'fstore_0', 'fstore_1', 'fstore_2', 'fstore_3', 'fstore_w', 'fsub', 'i2b', 'i2c', 'i2d', 'i2f', 'i2l', 'i2s', 'iadd', 'iaload', 'iand', 'iastore', 'iconst_0', 'iconst_1', 'iconst_2', 'iconst_3', 'iconst_4', 'iconst_5', 'iconst_m1', 'idiv', 'iinc', 'iinc_w', 'iload', 'iload_0', 'iload_1', 'iload_2', 'iload_3', 'iload_w', 'imul', 'ineg', 'int2byte', 'int2char', 'int2short', 'ior', 'irem', 'ireturn', 'ishl', 'ishr', 'istore', 'istore_0', 'istore_1', 'istore_2', 'istore_3', 'istore_w', 'isub', 'iushr', 'ixor', 'l2d', 'l2f', 'l2i', 'ladd', 'laload', 'land', 'lastore', 'lcmp', 'lconst_0', 'lconst_1', 'ldc2_w', 'ldiv', 'lload', 'lload_0', 'lload_1', 'lload_2', 'lload_3', 'lload_w', 'lmul', 'lneg', 'lookupswitch', 'lor', 'lrem', 'lreturn', 'lshl', 'lshr', 'lstore', 'lstore_0', 'lstore_1', 'lstore_2', 'lstore_3', 'lstore_w', 'lsub', 'lushr', 'lxor', 'monitorenter', 'monitorexit', 'nop', 'pop', 'pop2', 'ret', 'ret_w', 'return', 'saload', 'sastore', 'sipush', 'swap'), suffix=_break), Keyword.Reserved), (rf'(anewarray|checkcast|instanceof|ldc|ldc_w|new){_break}', Keyword.Reserved, 'class/no-dots'), (r'invoke(dynamic|interface|nonvirtual|special|' rf'static|virtual){_break}', Keyword.Reserved, 'invocation'), (rf'(getfield|putfield){_break}', Keyword.Reserved, ('descriptor/no-dots', 'field')), (rf'(getstatic|putstatic){_break}', Keyword.Reserved, ('descriptor/no-dots', 'static')), (words(( 'goto', 'goto_w', 'if_acmpeq', 'if_acmpne', 'if_icmpeq', 'if_icmpge', 'if_icmpgt', 'if_icmple', 'if_icmplt', 'if_icmpne', 'ifeq', 'ifge', 'ifgt', 'ifle', 'iflt', 'ifne', 'ifnonnull', 'ifnull', 'jsr', 'jsr_w'), suffix=_break), Keyword.Reserved, 'label'), (rf'(multianewarray|newarray){_break}', Keyword.Reserved, 'descriptor/convert-dots'), (rf'tableswitch{_break}', Keyword.Reserved, 'table') ], 'quote': [ (r"'", String.Single, '#pop'), (r'\\u[\da-fA-F]{4}', String.Escape), (r"[^'\\]+", String.Single) ], 'string': [ (r'"', String.Double, '#pop'), (r'\\([nrtfb"\'\\]|u[\da-fA-F]{4}|[0-3]?[0-7]{1,2})', String.Escape), (r'[^"\\]+', String.Double) ], 'root': [ (r'\n+', Whitespace), (r"'", String.Single, 'quote'), include('default'), (rf'({_name})([ \t\r]*)(:)', bygroups(Name.Label, Whitespace, Punctuation)), (_name, String.Other) ], 'annotation': [ (r'\n', Whitespace, ('#pop', 'annotation-body')), (rf'default{_break}', Keyword.Reserved, ('#pop', 'annotation-default')), include('default') ], 'annotation-body': [ (r'\n+', Whitespace), (rf'\.end{_break}', Keyword.Reserved, '#pop'), include('default'), (_name, String.Other, ('annotation-items', 'descriptor/no-dots')) ], 'annotation-default': [ (r'\n+', Whitespace), (rf'\.end{_break}', Keyword.Reserved, '#pop'), include('default'), default(('annotation-items', 'descriptor/no-dots')) ], 'annotation-items': [ (r"'", String.Single, 'quote'), include('default'), (_name, String.Other) ], 'caught-exception': [ (rf'all{_break}', Keyword, '#pop'), include('exception') ], 'class/convert-dots': [ include('default'), (rf'(L)((?:{_unqualified_name}[/.])*)({_name})(;)', bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation), '#pop'), (rf'((?:{_unqualified_name}[/.])*)({_name})', bygroups(Name.Namespace, Name.Class), '#pop') ], 'class/no-dots': [ include('default'), (r'\[+', Punctuation, ('#pop', 'descriptor/no-dots')), (rf'(L)((?:{_unqualified_name}/)*)({_name})(;)', bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation), '#pop'), (rf'((?:{_unqualified_name}/)*)({_name})', bygroups(Name.Namespace, Name.Class), '#pop') ], 'descriptor/convert-dots': [ include('default'), (r'\[+', Punctuation), (rf'(L)((?:{_unqualified_name}[/.])*)({_name}?)(;)', bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation), '#pop'), (rf'[^{_separator}\[)L]+', Keyword.Type, '#pop'), default('#pop') ], 'descriptor/no-dots': [ include('default'), (r'\[+', Punctuation), (rf'(L)((?:{_unqualified_name}/)*)({_name})(;)', bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation), '#pop'), (rf'[^{_separator}\[)L]+', Keyword.Type, '#pop'), default('#pop') ], 'descriptors/convert-dots': [ (r'\)', Punctuation, '#pop'), default('descriptor/convert-dots') ], 'enclosing-method': [ (_ws, Whitespace), (rf'(?=[^{_separator}]*\()', Text, ('#pop', 'invocation')), default(('#pop', 'class/convert-dots')) ], 'exception': [ include('default'), (rf'((?:{_unqualified_name}[/.])*)({_name})', bygroups(Name.Namespace, Name.Exception), '#pop') ], 'field': [ (rf'static{_break}', Keyword.Reserved, ('#pop', 'static')), include('default'), (rf'((?:{_unqualified_name}[/.](?=[^{_separator}]*[/.]))*)({_unqualified_name}[/.])?({_name})', bygroups(Name.Namespace, Name.Class, Name.Variable.Instance), '#pop') ], 'invocation': [ include('default'), (rf'((?:{_unqualified_name}[/.](?=[^{_separator}(]*[/.]))*)({_unqualified_name}[/.])?({_name})(\()', bygroups(Name.Namespace, Name.Class, Name.Function, Punctuation), ('#pop', 'descriptor/convert-dots', 'descriptors/convert-dots', 'descriptor/convert-dots')) ], 'label': [ include('default'), (_name, Name.Label, '#pop') ], 'method': [ include('default'), (rf'({_name})(\()', bygroups(Name.Function, Punctuation), ('#pop', 'descriptor/convert-dots', 'descriptors/convert-dots', 'descriptor/convert-dots')) ], 'no-verification': [ (rf'(locals|method|stack){_break}', Keyword.Reserved, '#pop'), include('default') ], 'static': [ include('default'), (rf'((?:{_unqualified_name}[/.](?=[^{_separator}]*[/.]))*)({_unqualified_name}[/.])?({_name})', bygroups(Name.Namespace, Name.Class, Name.Variable.Class), '#pop') ], 'table': [ (r'\n+', Whitespace), (rf'default{_break}', Keyword.Reserved, '#pop'), include('default'), (_name, Name.Label) ], 'var': [ include('default'), (_name, Name.Variable, '#pop') ], 'verification': [ include('default'), (rf'(Double|Float|Integer|Long|Null|Top|UninitializedThis){_break}', Keyword, '#pop'), (rf'Object{_break}', Keyword, ('#pop', 'class/no-dots')), (rf'Uninitialized{_break}', Keyword, ('#pop', 'label')) ] }
def analyse_text(text): score = 0 if re.search(r'^\s*\.class\s', text, re.MULTILINE): score += 0.5 if re.search(r'^\s*[a-z]+_[a-z]+\b', text, re.MULTILINE): score += 0.3 if re.search(r'^\s*\.(attribute|bytecode|debug|deprecated|enclosing|' r'inner|interface|limit|set|signature|stack)\b', text, re.MULTILINE): score += 0.6 return min(score, 1.0)
class SarlLexer(RegexLexer): """ For SARL source code. """
name = 'SARL' url = 'http://www.sarl.io' aliases = ['sarl'] filenames = ['*.sarl'] mimetypes = ['text/x-sarl'] version_added = '2.4'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][\w.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_$][\w$]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), (r'[^\S\n]+', Whitespace), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][\w.]*', Name.Decorator), (r'(as|break|case|catch|default|do|else|extends|extension|finally|' r'fires|for|if|implements|instanceof|new|on|requires|return|super|' r'switch|throw|throws|try|typeof|uses|while|with)\b', Keyword), (r'(abstract|def|dispatch|final|native|override|private|protected|' r'public|static|strictfp|synchronized|transient|val|var|volatile)\b', Keyword.Declaration), (r'(boolean|byte|char|double|float|int|long|short|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace)), (r'(false|it|null|occurrence|this|true|void)\b', Keyword.Constant), (r'(agent|annotation|artifact|behavior|capacity|class|enum|event|' r'interface|skill|space)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'import'), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (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-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Whitespace) ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'import': [ (r'[\w.]+\*?', Name.Namespace, '#pop') ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332""" pygments.lexers.kuin ~~~~~~~~~~~~~~~~~~~~
Lexers for the Kuin language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, using, this, bygroups, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['KuinLexer']
class KuinLexer(RegexLexer): """ For Kuin source code. """ name = 'Kuin' url = 'https://github.com/kuina/Kuin' aliases = ['kuin'] filenames = ['*.kn'] version_added = '2.9'
tokens = { 'root': [ include('statement'), ], 'statement': [ # Whitespace / Comment include('whitespace'),
# Block-statement (r'(\+?)([ \t]*)(\*?)([ \t]*)(\bfunc)([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*)', bygroups(Keyword,Whitespace, Keyword, Whitespace, Keyword, using(this), Name.Function), 'func_'), (r'\b(class)([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*)', bygroups(Keyword, using(this), Name.Class), 'class_'), (r'\b(enum)([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*)', bygroups(Keyword, using(this), Name.Constant), 'enum_'), (r'\b(block)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'block_'), (r'\b(ifdef)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'ifdef_'), (r'\b(if)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'if_'), (r'\b(switch)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'switch_'), (r'\b(while)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'while_'), (r'\b(for)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'for_'), (r'\b(foreach)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'foreach_'), (r'\b(try)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', bygroups(Keyword, using(this), Name.Other), 'try_'),
# Line-statement (r'\b(do)\b', Keyword, 'do'), (r'(\+?[ \t]*\bvar)\b', Keyword, 'var'), (r'\b(const)\b', Keyword, 'const'), (r'\b(ret)\b', Keyword, 'ret'), (r'\b(throw)\b', Keyword, 'throw'), (r'\b(alias)\b', Keyword, 'alias'), (r'\b(assert)\b', Keyword, 'assert'), (r'\|', Text, 'continued_line'), (r'[ \t]*\n', Whitespace), ],
# Whitespace / Comment 'whitespace': [ (r'^([ \t]*)(;.*)', bygroups(Comment.Single, Whitespace)), (r'[ \t]+(?![; \t])', Whitespace), (r'\{', Comment.Multiline, 'multiline_comment'), ], 'multiline_comment': [ (r'\{', Comment.Multiline, 'multiline_comment'), (r'(?:\s*;.*|[^{}\n]+)', Comment.Multiline), (r'\n', Comment.Multiline), (r'\}', Comment.Multiline, '#pop'), ],
# Block-statement 'func_': [ include('expr'), (r'\n', Whitespace, 'func'), ], 'func': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(func)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), include('statement'), ], 'class_': [ include('expr'), (r'\n', Whitespace, 'class'), ], 'class': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(class)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), include('statement'), ], 'enum_': [ include('expr'), (r'\n', Whitespace, 'enum'), ], 'enum': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(enum)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), include('expr'), (r'\n', Whitespace), ], 'block_': [ include('expr'), (r'\n', Whitespace, 'block'), ], 'block': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(block)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), include('statement'), include('break'), include('skip'), ], 'ifdef_': [ include('expr'), (r'\n', Whitespace, 'ifdef'), ], 'ifdef': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(ifdef)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), (words(('rls', 'dbg'), prefix=r'\b', suffix=r'\b'), Keyword.Constant, 'ifdef_sp'), include('statement'), include('break'), include('skip'), ], 'ifdef_sp': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'if_': [ include('expr'), (r'\n', Whitespace, 'if'), ], 'if': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(if)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), (words(('elif', 'else'), prefix=r'\b', suffix=r'\b'), Keyword, 'if_sp'), include('statement'), include('break'), include('skip'), ], 'if_sp': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'switch_': [ include('expr'), (r'\n', Whitespace, 'switch'), ], 'switch': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(switch)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), (words(('case', 'default', 'to'), prefix=r'\b', suffix=r'\b'), Keyword, 'switch_sp'), include('statement'), include('break'), include('skip'), ], 'switch_sp': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'while_': [ include('expr'), (r'\n', Whitespace, 'while'), ], 'while': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(while)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), include('statement'), include('break'), include('skip'), ], 'for_': [ include('expr'), (r'\n', Whitespace, 'for'), ], 'for': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(for)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), include('statement'), include('break'), include('skip'), ], 'foreach_': [ include('expr'), (r'\n', Whitespace, 'foreach'), ], 'foreach': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(foreach)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), include('statement'), include('break'), include('skip'), ], 'try_': [ include('expr'), (r'\n', Whitespace, 'try'), ], 'try': [ (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(try)\b', bygroups(Keyword, using(this), Keyword), '#pop:2'), (words(('catch', 'finally', 'to'), prefix=r'\b', suffix=r'\b'), Keyword, 'try_sp'), include('statement'), include('break'), include('skip'), ], 'try_sp': [ include('expr'), (r'\n', Whitespace, '#pop'), ],
# Line-statement 'break': [ (r'\b(break)\b([ \t]+)([a-zA-Z_][0-9a-zA-Z_]*)', bygroups(Keyword, using(this), Name.Other)), ], 'skip': [ (r'\b(skip)\b([ \t]+)([a-zA-Z_][0-9a-zA-Z_]*)', bygroups(Keyword, using(this), Name.Other)), ], 'alias': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'assert': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'const': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'do': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'ret': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'throw': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'var': [ include('expr'), (r'\n', Whitespace, '#pop'), ], 'continued_line': [ include('expr'), (r'\n', Whitespace, '#pop'), ],
'expr': [ # Whitespace / Comment include('whitespace'),
# Punctuation (r'\(', Punctuation,), (r'\)', Punctuation,), (r'\[', Punctuation,), (r'\]', Punctuation,), (r',', Punctuation),
# Keyword (words(( 'true', 'false', 'null', 'inf' ), prefix=r'\b', suffix=r'\b'), Keyword.Constant), (words(( 'me' ), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'bit16', 'bit32', 'bit64', 'bit8', 'bool', 'char', 'class', 'dict', 'enum', 'float', 'func', 'int', 'list', 'queue', 'stack' ), prefix=r'\b', suffix=r'\b'), Keyword.Type),
# Number (r'\b[0-9]\.[0-9]+(?!\.)(:?e[\+-][0-9]+)?\b', Number.Float), (r'\b2#[01]+(?:b(?:8|16|32|64))?\b', Number.Bin), (r'\b8#[0-7]+(?:b(?:8|16|32|64))?\b', Number.Oct), (r'\b16#[0-9A-F]+(?:b(?:8|16|32|64))?\b', Number.Hex), (r'\b[0-9]+(?:b(?:8|16|32|64))?\b', Number.Decimal),
# String / Char (r'"', String.Double, 'string'), (r"'(?:\\.|.)+?'", String.Char),
# Operator (r'(?:\.|\$(?:>|<)?)', Operator), (r'(?:\^)', Operator), (r'(?:\+|-|!|##?)', Operator), (r'(?:\*|/|%)', Operator), (r'(?:~)', Operator), (r'(?:(?:=|<>)(?:&|\$)?|<=?|>=?)', Operator), (r'(?:&)', Operator), (r'(?:\|)', Operator), (r'(?:\?)', Operator), (r'(?::(?::|\+|-|\*|/|%|\^|~)?)', Operator),
# Identifier (r"\b([a-zA-Z_][0-9a-zA-Z_]*)(?=@)\b", Name), (r"(@)?\b([a-zA-Z_][0-9a-zA-Z_]*)\b", bygroups(Name.Other, Name.Variable)), ],
# String 'string': [ (r'(?:\\[^{\n]|[^"\\])+', String.Double), (r'\\\{', String.Double, 'toStrInString'), (r'"', String.Double, '#pop'), ], 'toStrInString': [ include('expr'), (r'\}', String.Double, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293""" pygments.lexers.kusto ~~~~~~~~~~~~~~~~~~~~~
Lexers for Kusto Query Language (KQL).
: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, Punctuation, String, Whitespace)
__all__ = ["KustoLexer"]
# Although these all seem to be keywords# https://github.com/microsoft/Kusto-Query-Language/blob/master/src/Kusto.Language/Syntax/SyntaxFacts.cs# it appears that only the ones with tags here# https://github.com/microsoft/Kusto-Query-Language/blob/master/src/Kusto.Language/Parser/QueryGrammar.cs# are highlighted in the Azure portal log query editor.KUSTO_KEYWORDS = [ 'and', 'as', 'between', 'by', 'consume', 'contains', 'containscs', 'count', 'distinct', 'evaluate', 'extend', 'facet', 'filter', 'find', 'fork', 'getschema', 'has', 'invoke', 'join', 'limit', 'lookup', 'make-series', 'matches regex', 'mv-apply', 'mv-expand', 'notcontains', 'notcontainscs', '!contains', '!has', '!startswith', 'on', 'or', 'order', 'parse', 'parse-where', 'parse-kv', 'partition', 'print', 'project', 'project-away', 'project-keep', 'project-rename', 'project-reorder', 'range', 'reduce', 'regex', 'render', 'sample', 'sample-distinct', 'scan', 'search', 'serialize', 'sort', 'startswith', 'summarize', 'take', 'top', 'top-hitters', 'top-nested', 'typeof', 'union', 'where', 'bool', 'date', 'datetime', 'int', 'long', 'real', 'string', 'time']
# From# https://github.com/microsoft/Kusto-Query-Language/blob/master/src/Kusto.Language/Syntax/SyntaxFacts.csKUSTO_PUNCTUATION = [ "(", ")", "[", "]", "{", "}", "|", "<|", "+", "-", "*", "/", "%", ".." "!", "<", "<=", ">", ">=", "=", "==", "!=", "<>", ":", ";", ",", "=~", "!~", "?", "=>",]
class KustoLexer(RegexLexer): """For Kusto Query Language source code. """
name = "Kusto" aliases = ["kql", "kusto"] filenames = ["*.kql", "*.kusto", ".csl"] url = "https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query" version_added = '2.17'
tokens = { "root": [ (r"\s+", Whitespace), (words(KUSTO_KEYWORDS, suffix=r"\b"), Keyword), (r"//.*", Comment), (words(KUSTO_PUNCTUATION), Punctuation), (r"[^\W\d]\w*", Name), # Numbers can take the form 1, .1, 1., 1.1, 1.1111, etc. (r"\d+[.]\d*|[.]\d+", Number.Float), (r"\d+", Number.Integer), (r"'", String, "single_string"), (r'"', String, "double_string"), (r"@'", String, "single_verbatim"), (r'@"', String, "double_verbatim"), (r"```", String, "multi_string"), ], "single_string": [ (r"'", String, "#pop"), (r"\\.", String.Escape), (r"[^'\\]+", String), ], "double_string": [ (r'"', String, "#pop"), (r"\\.", String.Escape), (r'[^"\\]+', String), ], "single_verbatim": [ (r"'", String, "#pop"), (r"[^']+", String), ], "double_verbatim": [ (r'"', String, "#pop"), (r'[^"]+', String), ], "multi_string": [ (r"[^`]+", String), (r"```", String, "#pop"), (r"`", String), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155""" pygments.lexers.ldap ~~~~~~~~~~~~~~~~~~~~
Pygments lexers for LDAP.
: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 Operator, Comment, Keyword, Literal, Name, String, \ Number, Punctuation, Whitespace, Escape
__all__ = ['LdifLexer', 'LdaprcLexer']
class LdifLexer(RegexLexer):
""" Lexer for LDIF """
name = 'LDIF' aliases = ['ldif'] filenames = ['*.ldif'] mimetypes = ["text/x-ldif"] url = "https://datatracker.ietf.org/doc/html/rfc2849" version_added = '2.17'
tokens = { 'root': [ (r'\s*\n', Whitespace), (r'(-)(\n)', bygroups(Punctuation, Whitespace)), (r'(#.*)(\n)', bygroups(Comment.Single, Whitespace)), (r'(version)(:)([ \t]*)(.*)([ \t]*\n)', bygroups(Keyword, Punctuation, Whitespace, Number.Integer, Whitespace)), (r'(control)(:)([ \t]*)([\.0-9]+)([ \t]+)((?:true|false)?)([ \t]*)', bygroups(Keyword, Punctuation, Whitespace, Name.Other, Whitespace, Keyword, Whitespace), "after-control"), (r'(deleteoldrdn)(:)([ \n]*)([0-1]+)([ \t]*\n)', bygroups(Keyword, Punctuation, Whitespace, Number, Whitespace)), (r'(add|delete|replace)(::?)(\s*)(.*)([ \t]*\n)', bygroups( Keyword, Punctuation, Whitespace, Name.Attribute, Whitespace)), (r'(changetype)(:)([ \t]*)([a-z]*)([ \t]*\n)', bygroups(Keyword, Punctuation, Whitespace, Keyword, Whitespace)), (r'(dn|newrdn)(::)', bygroups(Keyword, Punctuation), "base64-dn"), (r'(dn|newrdn)(:)', bygroups(Keyword, Punctuation), "dn"), (r'(objectclass)(:)([ \t]*)([^ \t\n]*)([ \t]*\n)', bygroups( Keyword, Punctuation, Whitespace, Name.Class, Whitespace)), (r'([a-zA-Z]*|[0-9][0-9\.]*[0-9])(;)', bygroups(Name.Attribute, Punctuation), "property"), (r'([a-zA-Z]*|[0-9][0-9\.]*[0-9])(:<)', bygroups(Name.Attribute, Punctuation), "url"), (r'([a-zA-Z]*|[0-9][0-9\.]*[0-9])(::?)', bygroups(Name.Attribute, Punctuation), "value"), ], "after-control": [ (r":<", Punctuation, ("#pop", "url")), (r"::?", Punctuation, ("#pop", "value")), default("#pop"), ], 'property': [ (r'([-a-zA-Z0-9]*)(;)', bygroups(Name.Property, Punctuation)), (r'([-a-zA-Z0-9]*)(:<)', bygroups(Name.Property, Punctuation), ("#pop", "url")), (r'([-a-zA-Z0-9]*)(::?)', bygroups(Name.Property, Punctuation), ("#pop", "value")), ], 'value': [ (r'(\s*)([^\n]+\S)(\n )', bygroups(Whitespace, String, Whitespace)), (r'(\s*)([^\n]+\S)(\n)', bygroups(Whitespace, String, Whitespace), "#pop"), ], 'url': [ (r'([ \t]*)(\S*)([ \t]*\n )', bygroups(Whitespace, Comment.PreprocFile, Whitespace)), (r'([ \t]*)(\S*)([ \t]*\n)', bygroups(Whitespace, Comment.PreprocFile, Whitespace), "#pop"), ], "dn": [ (r'([ \t]*)([-a-zA-Z0-9\.]+)(=)', bygroups(Whitespace, Name.Attribute, Operator), ("#pop", "dn-value")), ], "dn-value": [ (r'\\[^\n]', Escape), (r',', Punctuation, ("#pop", "dn")), (r'\+', Operator, ("#pop", "dn")), (r'[^,\+\n]+', String), (r'\n ', Whitespace), (r'\n', Whitespace, "#pop"), ], "base64-dn": [ (r'([ \t]*)([^ \t\n][^ \t\n]*[^\n])([ \t]*\n )', bygroups(Whitespace, Name, Whitespace)), (r'([ \t]*)([^ \t\n][^ \t\n]*[^\n])([ \t]*\n)', bygroups(Whitespace, Name, Whitespace), "#pop"), ] }
class LdaprcLexer(RegexLexer): """ Lexer for OpenLDAP configuration files. """
name = 'LDAP configuration file' aliases = ['ldapconf', 'ldaprc'] filenames = ['.ldaprc', 'ldaprc', 'ldap.conf'] mimetypes = ["text/x-ldapconf"] url = 'https://www.openldap.org/software//man.cgi?query=ldap.conf&sektion=5&apropos=0&manpath=OpenLDAP+2.4-Release' version_added = '2.17'
_sasl_keywords = r'SASL_(?:MECH|REALM|AUTHCID|AUTHZID|CBINDING)' _tls_keywords = r'TLS_(?:CACERT|CACERTDIR|CERT|ECNAME|KEY|CIPHER_SUITE|PROTOCOL_MIN|RANDFILE|CRLFILE)' _literal_keywords = rf'(?:URI|SOCKET_BIND_ADDRESSES|{_sasl_keywords}|{_tls_keywords})' _boolean_keywords = r'GSSAPI_(?:ALLOW_REMOTE_PRINCIPAL|ENCRYPT|SIGN)|REFERRALS|SASL_NOCANON' _integer_keywords = r'KEEPALIVE_(?:IDLE|PROBES|INTERVAL)|NETWORK_TIMEOUT|PORT|SIZELIMIT|TIMELIMIT|TIMEOUT' _secprops = r'none|noanonymous|noplain|noactive|nodict|forwardsec|passcred|(?:minssf|maxssf|maxbufsize)=\d+'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'#.*', Comment.Single), (r'\s+', Whitespace), (rf'({_boolean_keywords})(\s+)(on|true|yes|off|false|no)$', bygroups(Keyword, Whitespace, Keyword.Constant)), (rf'({_integer_keywords})(\s+)(\d+)', bygroups(Keyword, Whitespace, Number.Integer)), (r'(VERSION)(\s+)(2|3)', bygroups(Keyword, Whitespace, Number.Integer)), # Constants (r'(DEREF)(\s+)(never|searching|finding|always)', bygroups(Keyword, Whitespace, Keyword.Constant)), (rf'(SASL_SECPROPS)(\s+)((?:{_secprops})(?:,{_secprops})*)', bygroups(Keyword, Whitespace, Keyword.Constant)), (r'(SASL_CBINDING)(\s+)(none|tls-unique|tls-endpoint)', bygroups(Keyword, Whitespace, Keyword.Constant)), (r'(TLS_REQ(?:CERT|SAN))(\s+)(allow|demand|hard|never|try)', bygroups(Keyword, Whitespace, Keyword.Constant)), (r'(TLS_CRLCHECK)(\s+)(none|peer|all)', bygroups(Keyword, Whitespace, Keyword.Constant)), # Literals (r'(BASE|BINDDN)(\s+)(\S+)$', bygroups(Keyword, Whitespace, Literal)), # Accepts hostname with or without port. (r'(HOST)(\s+)([a-z0-9]+)((?::(\d+))?)', bygroups(Keyword, Whitespace, Literal, Number.Integer)), (rf'({_literal_keywords})(\s+)(\S+)$', bygroups(Keyword, Whitespace, Literal)), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241""" pygments.lexers.lean ~~~~~~~~~~~~~~~~~~~~
Lexers for the Lean theorem prover.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, words, includefrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Generic, Whitespace
__all__ = ['Lean3Lexer', 'Lean4Lexer']
class Lean3Lexer(RegexLexer): """ For the Lean 3 theorem prover. """ name = 'Lean' url = 'https://leanprover-community.github.io/lean3' aliases = ['lean', 'lean3'] filenames = ['*.lean'] mimetypes = ['text/x-lean', 'text/x-lean3'] version_added = '2.0'
# from https://github.com/leanprover/vscode-lean/blob/1589ca3a65e394b3789409707febbd2d166c9344/syntaxes/lean.json#L186C20-L186C217 _name_segment = ( "(?![λΠΣ])[_a-zA-Zα-ωΑ-Ωϊ-ϻἀ-῾℀-⅏𝒜-𝖟]" "(?:(?![λΠΣ])[_a-zA-Zα-ωΑ-Ωϊ-ϻἀ-῾℀-⅏𝒜-𝖟0-9'ⁿ-₉ₐ-ₜᵢ-ᵪ])*") _name = _name_segment + r"(\." + _name_segment + r")*"
tokens = { 'expression': [ (r'\s+', Whitespace), (r'/--', String.Doc, 'docstring'), (r'/-', Comment, 'comment'), (r'--.*?$', Comment.Single), (words(( 'forall', 'fun', 'Pi', 'from', 'have', 'show', 'assume', 'suffices', 'let', 'if', 'else', 'then', 'in', 'with', 'calc', 'match', 'do' ), prefix=r'\b', suffix=r'\b'), Keyword), (words(('sorry', 'admit'), prefix=r'\b', suffix=r'\b'), Generic.Error), (words(('Sort', 'Prop', 'Type'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(( '(', ')', ':', '{', '}', '[', ']', '⟨', '⟩', '‹', '›', '⦃', '⦄', ':=', ',', )), Operator), (_name, Name), (r'``?' + _name, String.Symbol), (r'0x[A-Za-z0-9]+', Number.Integer), (r'0b[01]+', Number.Integer), (r'\d+', Number.Integer), (r'"', String.Double, 'string'), (r"'(?:(\\[\\\"'nt])|(\\x[0-9a-fA-F]{2})|(\\u[0-9a-fA-F]{4})|.)'", String.Char), (r'[~?][a-z][\w\']*:', Name.Variable), (r'\S', Name.Builtin.Pseudo), ], 'root': [ (words(( 'import', 'renaming', 'hiding', 'namespace', 'local', 'private', 'protected', 'section', 'include', 'omit', 'section', 'protected', 'export', 'open', 'attribute', ), prefix=r'\b', suffix=r'\b'), Keyword.Namespace), (words(( 'lemma', 'theorem', 'def', 'definition', 'example', 'axiom', 'axioms', 'constant', 'constants', 'universe', 'universes', 'inductive', 'coinductive', 'structure', 'extends', 'class', 'instance', 'abbreviation',
'noncomputable theory',
'noncomputable', 'mutual', 'meta',
'attribute',
'parameter', 'parameters', 'variable', 'variables',
'reserve', 'precedence', 'postfix', 'prefix', 'notation', 'infix', 'infixl', 'infixr',
'begin', 'by', 'end',
'set_option', 'run_cmd', ), prefix=r'\b', suffix=r'\b'), Keyword.Declaration), (r'@\[', Keyword.Declaration, 'attribute'), (words(( '#eval', '#check', '#reduce', '#exit', '#print', '#help', ), suffix=r'\b'), Keyword), include('expression') ], 'attribute': [ (r'\]', Keyword.Declaration, '#pop'), include('expression'), ], 'comment': [ (r'[^/-]+', Comment.Multiline), (r'/-', Comment.Multiline, '#push'), (r'-/', Comment.Multiline, '#pop'), (r'[/-]', Comment.Multiline) ], 'docstring': [ (r'[^/-]+', String.Doc), (r'-/', String.Doc, '#pop'), (r'[/-]', String.Doc) ], 'string': [ (r'[^\\"]+', String.Double), (r"(?:(\\[\\\"'nt])|(\\x[0-9a-fA-F]{2})|(\\u[0-9a-fA-F]{4}))", String.Escape), ('"', String.Double, '#pop'), ], }
def analyse_text(text): if re.search(r'^import [a-z]', text, re.MULTILINE): return 0.1
LeanLexer = Lean3Lexer
class Lean4Lexer(RegexLexer): """ For the Lean 4 theorem prover. """
name = 'Lean4' url = 'https://github.com/leanprover/lean4' aliases = ['lean4'] filenames = ['*.lean'] mimetypes = ['text/x-lean4'] version_added = '2.18'
# same as Lean3Lexer, with `!` and `?` allowed _name_segment = ( "(?![λΠΣ])[_a-zA-Zα-ωΑ-Ωϊ-ϻἀ-῾℀-⅏𝒜-𝖟]" "(?:(?![λΠΣ])[_a-zA-Zα-ωΑ-Ωϊ-ϻἀ-῾℀-⅏𝒜-𝖟0-9'ⁿ-₉ₐ-ₜᵢ-ᵪ!?])*") _name = _name_segment + r"(\." + _name_segment + r")*"
keywords1 = ( 'import', 'unif_hint', 'renaming', 'inline', 'hiding', 'lemma', 'variable', 'theorem', 'axiom', 'inductive', 'structure', 'universe', 'alias', '#help', 'precedence', 'postfix', 'prefix', 'infix', 'infixl', 'infixr', 'notation', '#eval', '#check', '#reduce', '#exit', 'end', 'private', 'using', 'namespace', 'instance', 'section', 'protected', 'export', 'set_option', 'extends', 'open', 'example', '#print', 'opaque', 'def', 'macro', 'elab', 'syntax', 'macro_rules', '#reduce', 'where', 'abbrev', 'noncomputable', 'class', 'attribute', '#synth', 'mutual', 'scoped', 'local', )
keywords2 = ( 'forall', 'fun', 'obtain', 'from', 'have', 'show', 'assume', 'let', 'if', 'else', 'then', 'by', 'in', 'with', 'calc', 'match', 'nomatch', 'do', 'at', )
keywords3 = ( # Sorts 'Type', 'Prop', 'Sort', )
operators = ( '!=', '#', '&', '&&', '*', '+', '-', '/', '@', '!', '-.', '->', '.', '..', '...', '::', ':>', ';', ';;', '<', '<-', '=', '==', '>', '_', '|', '||', '~', '=>', '<=', '>=', '/\\', '\\/', '∀', 'Π', 'λ', '↔', '∧', '∨', '≠', '≤', '≥', '¬', '⁻¹', '⬝', '▸', '→', '∃', '≈', '×', '⌞', '⌟', '≡', '⟨', '⟩', "↦", )
punctuation = ('(', ')', ':', '{', '}', '[', ']', '⦃', '⦄', ':=', ',', ']\'', ']?', ']!')
tokens = { 'expression': [ (r'\s+', Whitespace), (r'/--', String.Doc, 'docstring'), (r'/-', Comment, 'comment'), (r'--.*$', Comment.Single), (words(keywords3, prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(('sorry', 'admit'), prefix=r'\b', suffix=r'\b'), Generic.Error), (words(operators), Name.Builtin.Pseudo), (words(punctuation), Operator), (_name_segment, Name), (r'``?' + _name, String.Symbol), (r'(?<=\.)\d+', Number), (r'(\d+\.\d*)([eE][+-]?[0-9]+)?', Number.Float), (r'\d+', Number.Integer), (r'"', String.Double, 'string'), (r'[~?][a-z][\w\']*:', Name.Variable), (r'\S', Name.Builtin.Pseudo), ], 'root': [ (words(keywords1, prefix=r'\b', suffix=r'\b'), Keyword.Namespace), (words(keywords2, prefix=r'\b', suffix=r'\b'), Keyword), (r'@\[', Keyword.Declaration, 'attribute'), include('expression') ], 'attribute': [ (r'\]', Keyword.Declaration, '#pop'), include('expression'), ], 'comment': [ # Multiline Comments (r'[^/-]+', Comment.Multiline), (r'/-', Comment.Multiline, '#push'), (r'-/', Comment.Multiline, '#pop'), (r'[/-]', Comment.Multiline) ], 'docstring': [ (r'[^/-]+', String.Doc), (r'-/', String.Doc, '#pop'), (r'[/-]', String.Doc) ], 'string': [ (r'[^\\"]+', String.Double), (r'\\[n"\\\n]', String.Escape), ('"', String.Double, '#pop'), ], }
def analyse_text(text): if re.search(r'^import [A-Z]', text, re.MULTILINE): return 0.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225""" pygments.lexers.lilypond ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for LilyPond.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import bygroups, default, inherit, wordsfrom pygments.lexers.lisp import SchemeLexerfrom pygments.lexers._lilypond_builtins import ( keywords, pitch_language_names, clefs, scales, repeat_types, units, chord_modifiers, pitches, music_functions, dynamics, articulations, music_commands, markup_commands, grobs, translators, contexts, context_properties, grob_properties, scheme_functions, paper_variables, header_variables)from pygments.token import Token
__all__ = ["LilyPondLexer"]
# In LilyPond, (unquoted) name tokens only contain letters, hyphens,# and underscores, where hyphens and underscores must not start or end# a name token.## Note that many of the entities listed as LilyPond built-in keywords# (in file `_lilypond_builtins.py`) are only valid if surrounded by# double quotes, for example, 'hufnagel-fa1'. This means that# `NAME_END_RE` doesn't apply to such entities in valid LilyPond code.NAME_END_RE = r"(?=\d|[^\w\-]|[\-_][\W\d])"
def builtin_words(names, backslash, suffix=NAME_END_RE): prefix = r"[\-_^]?" if backslash == "mandatory": prefix += r"\\" elif backslash == "optional": prefix += r"\\?" else: assert backslash == "disallowed" return words(names, prefix, suffix)
class LilyPondLexer(SchemeLexer): """ Lexer for input to LilyPond, a text-based music typesetter.
.. important::
This lexer is meant to be used in conjunction with the ``lilypond`` style. """ name = 'LilyPond' url = 'https://lilypond.org' aliases = ['lilypond'] filenames = ['*.ly'] mimetypes = [] version_added = '2.11'
flags = re.DOTALL | re.MULTILINE
# Because parsing LilyPond input is very tricky (and in fact # impossible without executing LilyPond when there is Scheme # code in the file), this lexer does not try to recognize # lexical modes. Instead, it catches the most frequent pieces # of syntax, and, above all, knows about many kinds of builtins.
# In order to parse embedded Scheme, this lexer subclasses the SchemeLexer. # It redefines the 'root' state entirely, and adds a rule for #{ #} # to the 'value' state. The latter is used to parse a Scheme expression # after #.
def get_tokens_unprocessed(self, text): """Highlight Scheme variables as LilyPond builtins when applicable.""" for index, token, value in super().get_tokens_unprocessed(text): if token is Token.Name.Function or token is Token.Name.Variable: if value in scheme_functions: token = Token.Name.Builtin.SchemeFunction elif token is Token.Name.Builtin: token = Token.Name.Builtin.SchemeBuiltin yield index, token, value
tokens = { "root": [ # Whitespace. (r"\s+", Token.Text.Whitespace),
# Multi-line comments. These are non-nestable. (r"%\{.*?%\}", Token.Comment.Multiline),
# Simple comments. (r"%.*?$", Token.Comment.Single),
# End of embedded LilyPond in Scheme. (r"#\}", Token.Punctuation, "#pop"),
# Embedded Scheme, starting with # ("delayed"), # or $ (immediate). #@ and and $@ are the lesser known # "list splicing operators". (r"[#$]@?", Token.Punctuation, "value"),
# Any kind of punctuation: # - sequential music: { }, # - parallel music: << >>, # - voice separator: << \\ >>, # - chord: < >, # - bar check: |, # - dot in nested properties: \revert NoteHead.color, # - equals sign in assignments and lists for various commands: # \override Stem.color = red, # - comma as alternative syntax for lists: \time 3,3,2 4/4, # - colon in tremolos: c:32, # - double hyphen and underscore in lyrics: li -- ly -- pond __ # (which must be preceded by ASCII whitespace) (r"""(?x) \\\\ | (?<= \s ) (?: -- | __ ) | [{}<>=.,:|] """, Token.Punctuation),
# Pitches, with optional octavation marks, octave check, # and forced or cautionary accidental. (words(pitches, suffix=r"=?[',]*!?\??" + NAME_END_RE), Token.Pitch),
# Strings, optionally with direction specifier. (r'[\-_^]?"', Token.String, "string"),
# Numbers. (r"-?\d+\.\d+", Token.Number.Float), # 5. and .5 are not allowed (r"-?\d+/\d+", Token.Number.Fraction), # Integers, or durations with optional augmentation dots. # We have no way to distinguish these, so we highlight # them all as numbers. # # Normally, there is a space before the integer (being an # argument to a music function), which we check here. The # case without a space is handled below (as a fingering # number). (r"""(?x) (?<= \s ) -\d+ | (?: (?: \d+ | \\breve | \\longa | \\maxima ) \.* ) """, Token.Number), # Separates duration and duration multiplier highlighted as fraction. (r"\*", Token.Number),
# Ties, slurs, manual beams. (r"[~()[\]]", Token.Name.Builtin.Articulation),
# Predefined articulation shortcuts. A direction specifier is # required here. (r"[\-_^][>^_!.\-+]", Token.Name.Builtin.Articulation),
# Fingering numbers, string numbers. (r"[\-_^]?\\?\d+", Token.Name.Builtin.Articulation),
# Builtins. (builtin_words(keywords, "mandatory"), Token.Keyword), (builtin_words(pitch_language_names, "disallowed"), Token.Name.PitchLanguage), (builtin_words(clefs, "disallowed"), Token.Name.Builtin.Clef), (builtin_words(scales, "mandatory"), Token.Name.Builtin.Scale), (builtin_words(repeat_types, "disallowed"), Token.Name.Builtin.RepeatType), (builtin_words(units, "mandatory"), Token.Number), (builtin_words(chord_modifiers, "disallowed"), Token.ChordModifier), (builtin_words(music_functions, "mandatory"), Token.Name.Builtin.MusicFunction), (builtin_words(dynamics, "mandatory"), Token.Name.Builtin.Dynamic), # Those like slurs that don't take a backslash are covered above. (builtin_words(articulations, "mandatory"), Token.Name.Builtin.Articulation), (builtin_words(music_commands, "mandatory"), Token.Name.Builtin.MusicCommand), (builtin_words(markup_commands, "mandatory"), Token.Name.Builtin.MarkupCommand), (builtin_words(grobs, "disallowed"), Token.Name.Builtin.Grob), (builtin_words(translators, "disallowed"), Token.Name.Builtin.Translator), # Optional backslash because of \layout { \context { \Score ... } }. (builtin_words(contexts, "optional"), Token.Name.Builtin.Context), (builtin_words(context_properties, "disallowed"), Token.Name.Builtin.ContextProperty), (builtin_words(grob_properties, "disallowed"), Token.Name.Builtin.GrobProperty, "maybe-subproperties"), # Optional backslashes here because output definitions are wrappers # around modules. Concretely, you can do, e.g., # \paper { oddHeaderMarkup = \evenHeaderMarkup } (builtin_words(paper_variables, "optional"), Token.Name.Builtin.PaperVariable), (builtin_words(header_variables, "optional"), Token.Name.Builtin.HeaderVariable),
# Other backslashed-escaped names (like dereferencing a # music variable), possibly with a direction specifier. (r"[\-_^]?\\.+?" + NAME_END_RE, Token.Name.BackslashReference),
# Definition of a variable. Support assignments to alist keys # (myAlist.my-key.my-nested-key = \markup \spam \eggs). (r"""(?x) (?: [^\W\d] | - )+ (?= (?: [^\W\d] | [\-.] )* \s* = ) """, Token.Name.Lvalue),
# Virtually everything can appear in markup mode, so we highlight # as text. Try to get a complete word, or we might wrongly lex # a suffix that happens to be a builtin as a builtin (e.g., "myStaff"). (r"([^\W\d]|-)+?" + NAME_END_RE, Token.Text), (r".", Token.Text), ], "string": [ (r'"', Token.String, "#pop"), (r'\\.', Token.String.Escape), (r'[^\\"]+', Token.String), ], "value": [ # Scan a LilyPond value, then pop back since we had a # complete expression. (r"#\{", Token.Punctuation, ("#pop", "root")), inherit, ], # Grob subproperties are undeclared and it would be tedious # to maintain them by hand. Instead, this state allows recognizing # everything that looks like a-known-property.foo.bar-baz as # one single property name. "maybe-subproperties": [ (r"\s+", Token.Text.Whitespace), (r"(\.)((?:[^\W\d]|-)+?)" + NAME_END_RE, bygroups(Token.Punctuation, Token.Name.Builtin.GrobProperty)), default("#pop"), ] }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847""" pygments.lexers.macaulay2 ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Macaulay2.
: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, Text
__all__ = ['Macaulay2Lexer']
# Auto-generated for Macaulay2-1.25.11. Do not modify this file manually.
M2KEYWORDS = ( "SPACE", "TEST", "and", "break", "breakpoint", "catch", "continue", "do", "elapsedTime", "elapsedTiming", "else", "for", "from", "global", "if", "in", "list", "local", "new", "not", "of", "or", "profile", "return", "shield", "step", "symbol", "then", "threadLocal", "threadVariable", "throw", "time", "timing", "to", "try", "when", "while", "xor" )
M2DATATYPES = ( "ANCHOR", "Adjacent", "AffineVariety", "Analyzer", "AngleBarList", "Array", "AssociativeExpression", "AtomicInt", "BLOCKQUOTE", "BODY", "BOLD", "BR", "BUTTON", "Bag", "BasicList", "BettiTally", "BinaryOperation", "Boolean", "CC", "CDATA", "CODE", "COMMENT", "CacheTable", "ChainComplex", "ChainComplexMap", "CoherentSheaf", "Command", "CompiledFunction", "CompiledFunctionBody", "CompiledFunctionClosure", "ComplexField", "Constant", "DD", "DIV", "DL", "DT", "Database", "Descent", "Describe", "Dictionary", "DirectSum", "Divide", "DocumentTag", "EM", "Eliminate", "EngineRing", "Equation", "ExampleItem", "Expression", "File", "FilePosition", "FractionField", "Function", "FunctionApplication", "FunctionBody", "FunctionClosure", "GaloisField", "GeneralOrderedMonoid", "GlobalDictionary", "GradedModule", "GradedModuleMap", "GroebnerBasis", "GroebnerBasisOptions", "HEAD", "HEADER1", "HEADER2", "HEADER3", "HEADER4", "HEADER5", "HEADER6", "HR", "HREF", "HTML", "HashTable", "HeaderType", "Holder", "Hybrid", "Hypertext", "HypertextContainer", "HypertextParagraph", "HypertextVoid", "IFRAME", "IMG", "INDENT", "INPUT", "ITALIC", "Ideal", "ImmutableType", "IndeterminateNumber", "IndexedVariable", "IndexedVariableTable", "InexactField", "InexactFieldFamily", "InexactNumber", "InfiniteNumber", "IntermediateMarkUpType", "Iterator", "KBD", "Keyword", "LABEL", "LATER", "LI", "LINK", "LITERAL", "List", "LocalDictionary", "LowerBound", "MENU", "META", "Manipulator", "MapExpression", "MarkUpType", "Matrix", "MatrixExpression", "MethodFunction", "MethodFunctionBinary", "MethodFunctionSingle", "MethodFunctionWithOptions", "Minus", "Module", "Monoid", "MonoidElement", "MonomialIdeal", "MultigradedBettiTally", "MutableHashTable", "MutableList", "MutableMatrix", "Net", "NetFile", "Nothing", "Number", "NumberedVerticalList", "OL", "OneExpression", "Option", "OptionTable", "OrderedMonoid", "PARA", "PRE", "Package", "Parenthesize", "Parser", "Partition", "PolynomialRing", "Power", "Product", "ProductOrder", "Program", "ProgramRun", "ProjectiveHilbertPolynomial", "ProjectiveVariety", "Pseudocode", "PseudocodeClosure", "QQ", "QuotientRing", "RR", "RRi", "RealField", "Resolution", "Ring", "RingElement", "RingFamily", "RingMap", "RowExpression", "SAMP", "SCRIPT", "SMALL", "SPAN", "STRONG", "STYLE", "SUB", "SUBSECTION", "SUP", "ScriptedFunctor", "SelfInitializingType", "Sequence", "Set", "SheafExpression", "SheafMap", "SheafOfRings", "SparseMonomialVectorExpression", "SparseVectorExpression", "String", "Subscript", "Sum", "SumOfTwists", "Superscript", "Symbol", "SymbolBody", "TABLE", "TD", "TEX", "TH", "TITLE", "TO", "TO2", "TOH", "TR", "TT", "Table", "Tally", "Task", "TensorProduct", "TestInput", "Thing", "Time", "Type", "UL", "URL", "VAR", "Variety", "Vector", "VectorExpression", "VerticalList", "VirtualTally", "VisibleList", "WrapperType", "ZZ", "ZeroExpression" )
M2FUNCTIONS = ( "BesselJ", "BesselY", "Beta", "Digamma", "EXAMPLE", "End", "Fano", "GCstats", "GF", "Gamma", "Grassmannian", "Hom", "LLL", "LUdecomposition", "M2CODE", "NNParser", "Proj", "QQParser", "QRDecomposition", "SVD", "SYNOPSIS", "Schubert", "Spec", "ZZParser", "about", "abs", "accumulate", "acos", "acosh", "acot", "acoth", "addCancelTask", "addDependencyTask", "addEndFunction", "addHook", "addStartTask", "adjoint", "agm", "alarm", "all", "ambient", "analyticSpread", "ancestor", "ancestors", "andP", "ann", "annihilator", "antipode", "any", "append", "applicationDirectory", "apply", "applyKeys", "applyPairs", "applyTable", "applyValues", "apropos", "arXiv", "ascii", "asin", "asinh", "ass", "assert", "associatedGradedRing", "associatedPrimes", "atEndOfFile", "atan", "atan2", "atanh", "autoload", "baseFilename", "baseName", "baseRing", "basis", "beginDocumentation", "benchmark", "betti", "between", "binomial", "borel", "cacheValue", "cancelTask", "canonicalBundle", "capture", "ceiling", "centerString", "chainComplex", "changeBase", "changeDirectory", "char", "charAnalyzer", "characters", "check", "checkDegrees", "chi", "class", "clean", "clearEcho", "code", "codim", "coefficient", "coefficientRing", "coefficients", "cohomology", "coimage", "coker", "cokernel", "collectGarbage", "columnAdd", "columnMult", "columnPermute", "columnRankProfile", "columnSwap", "columnate", "combine", "commandInterpreter", "commonRing", "commonest", "comodule", "compareExchange", "complement", "complete", "components", "compose", "compositions", "compress", "concatenate", "conductor", "cone", "conjugate", "connectionCount", "constParser", "content", "contract", "conwayPolynomial", "copy", "copyDirectory", "copyFile", "cos", "cosh", "cot", "cotangentSheaf", "coth", "cover", "coverMap", "cpuTime", "createTask", "csc", "csch", "currentColumnNumber", "currentDirectory", "currentPosition", "currentRowNumber", "currentTime", "deadParser", "debug", "debugError", "decompose", "deepSplice", "default", "degree", "degreeGroup", "degreeLength", "degrees", "degreesMonoid", "degreesRing", "delete", "demark", "denominator", "depth", "describe", "det", "determinant", "diagonalMatrix", "diameter", "dictionary", "diff", "difference", "dim", "directProduct", "directSum", "disassemble", "discriminant", "dismiss", "distinguished", "divideByVariable", "doc", "document", "drop", "dual", "eagonNorthcott", "echoOff", "echoOn", "eigenvalues", "eigenvectors", "eint", "elements", "eliminate", "endPackage", "entries", "erase", "erf", "erfc", "error", "euler", "eulers", "even", "examples", "exchange", "exec", "exp", "expectedReesIdeal", "expm1", "exponents", "export", "exportFrom", "exportMutable", "expression", "extend", "exteriorPower", "factor", "fileExecutable", "fileExists", "fileLength", "fileMode", "fileReadable", "fileTime", "fileWritable", "fillMatrix", "findFiles", "findHeft", "findProgram", "findSynonyms", "first", "firstkey", "fittingIdeal", "flagLookup", "flatten", "flattenRing", "flip", "floor", "fold", "forceGB", "fork", "format", "formation", "frac", "fraction", "frames", "fromDividedPowers", "fromDual", "functionBody", "futureParser", "gb", "gbRemove", "gbSnapshot", "gcd", "gcdCoefficients", "gcdLLL", "genera", "generateAssertions", "generator", "generators", "genericMatrix", "genericSkewMatrix", "genericSymmetricMatrix", "gens", "genus", "get", "getChangeMatrix", "getGlobalSymbol", "getIOThreadMode", "getNetFile", "getNonUnit", "getPrimeWithRootOfUnity", "getSymbol", "getWWW", "getc", "getenv", "globalAssign", "globalAssignFunction", "globalAssignment", "globalReleaseFunction", "gradedModule", "gradedModuleMap", "gramm", "graphIdeal", "graphRing", "groebnerBasis", "groupID", "hash", "hashTable", "headlines", "heft", "height", "hermite", "hilbertFunction", "hilbertPolynomial", "hilbertSeries", "hold", "homogenize", "homology", "homomorphism", "hooks", "horizontalJoin", "html", "httpHeaders", "hypertext", "icFracP", "icFractions", "icMap", "icPIdeal", "ideal", "idealSheaf", "idealizer", "identity", "image", "imaginaryPart", "importFrom", "independentSets", "index", "indices", "inducedMap", "inducesWellDefinedMap", "info", "input", "insert", "installAssignmentMethod", "installHilbertFunction", "installMethod", "installMinprimes", "installPackage", "installedPackages", "instance", "instances", "integralClosure", "integrate", "intersect", "intersectInP", "intersection", "interval", "inverse", "inverseErf", "inversePermutation", "inverseRegularizedBeta", "inverseRegularizedGamma", "inverseSystem", "irreducibleCharacteristicSeries", "irreducibleDecomposition", "isANumber", "isAffineRing", "isBorel", "isCanceled", "isCommutative", "isConstant", "isDirectSum", "isDirectory", "isEmpty", "isExact", "isField", "isFinite", "isFinitePrimeField", "isFreeModule", "isGlobalSymbol", "isHomogeneous", "isIdeal", "isInfinite", "isInjective", "isInputFile", "isIsomorphic", "isIsomorphism", "isLLL", "isLinearType", "isListener", "isLocallyFree", "isMember", "isModule", "isMonomialIdeal", "isMutable", "isNormal", "isOpen", "isOutputFile", "isPolynomialRing", "isPrimary", "isPrime", "isPrimitive", "isProjective", "isPseudoprime", "isQuotientModule", "isQuotientOf", "isQuotientRing", "isReady", "isReal", "isReduction", "isRegularFile", "isRing", "isSkewCommutative", "isSmooth", "isSorted", "isSquareFree", "isStandardGradedPolynomialRing", "isSubmodule", "isSubquotient", "isSubset", "isSupportedInZeroLocus", "isSurjective", "isTable", "isUnit", "isVeryAmple", "isWellDefined", "isWeylAlgebra", "isc", "isomorphism", "iterator", "jacobian", "jacobianDual", "join", "ker", "kernel", "kernelLLL", "kernelOfLocalization", "keys", "kill", "koszul", "last", "lcm", "leadCoefficient", "leadComponent", "leadMonomial", "leadTerm", "left", "length", "letterParser", "lift", "liftable", "limitFiles", "limitProcesses", "lines", "linkFile", "listForm", "listSymbols", "lngamma", "load", "loadPackage", "localDictionaries", "localize", "locate", "log", "log1p", "lookup", "lookupCount", "makeDirectory", "makeDocumentTag", "makePackageIndex", "makeS2", "map", "markedGB", "match", "mathML", "matrix", "max", "maxPosition", "member", "memoize", "memoizeClear", "memoizeValues", "merge", "mergePairs", "method", "methodOptions", "methods", "midpoint", "min", "minPosition", "minPres", "mingens", "mingle", "minimalBetti", "minimalPresentation", "minimalPrimes", "minimalReduction", "minimize", "minimizeFilename", "minors", "minprimes", "minus", "mkdir", "mod", "module", "modulo", "monoid", "monomialCurveIdeal", "monomialIdeal", "monomialSubideal", "monomials", "moveFile", "multidegree", "multidoc", "multigraded", "multiplicity", "mutable", "mutableIdentity", "mutableMatrix", "nanosleep", "needs", "needsPackage", "net", "netList", "newClass", "newCoordinateSystem", "newNetFile", "newPackage", "newRing", "next", "nextPrime", "nextkey", "nonspaceAnalyzer", "norm", "normalCone", "notImplemented", "nullParser", "nullSpace", "nullhomotopy", "numColumns", "numRows", "number", "numcols", "numerator", "numeric", "numericInterval", "numgens", "numrows", "odd", "oeis", "ofClass", "on", "openDatabase", "openDatabaseOut", "openFiles", "openIn", "openInOut", "openListener", "openOut", "openOutAppend", "optP", "optionalSignParser", "options", "orP", "override", "pack", "package", "packageTemplate", "pad", "pager", "pairs", "parallelApply", "parent", "part", "partition", "partitions", "parts", "pdim", "peek", "permanents", "permutations", "pfaffian", "pfaffians", "pivots", "plus", "poincare", "poincareN", "polarize", "poly", "position", "positions", "power", "powermod", "precision", "preimage", "prepend", "presentation", "pretty", "primaryComponent", "primaryDecomposition", "print", "printString", "printerr", "processID", "product", "projectiveHilbertPolynomial", "promote", "protect", "prune", "pseudoRemainder", "pseudocode", "pullback", "pushForward", "pushout", "quotient", "quotientRemainder", "radical", "radicalContainment", "random", "randomKRationalPoint", "randomMutableMatrix", "randomSubset", "rank", "rays", "read", "readDirectory", "readPackage", "readlink", "realPart", "realpath", "recursionDepth", "reduceHilbert", "reducedRowEchelonForm", "reductionNumber", "reesAlgebra", "reesAlgebraIdeal", "reesIdeal", "regSeqInIdeal", "regex", "regexQuote", "registerFinalizer", "regularity", "regularizedBeta", "regularizedGamma", "relations", "relativizeFilename", "remainder", "remove", "removeDirectory", "removeFile", "removeLowestDimension", "reorganize", "replace", "res", "reshape", "resolution", "resultant", "reverse", "right", "ring", "ringFromFractions", "roots", "rotate", "round", "rowAdd", "rowMult", "rowPermute", "rowRankProfile", "rowSwap", "rsort", "run", "runHooks", "runLengthEncode", "runProgram", "same", "saturate", "scan", "scanKeys", "scanLines", "scanPairs", "scanValues", "schedule", "schreyerOrder", "searchPath", "sec", "sech", "seeParsing", "select", "selectInSubring", "selectKeys", "selectPairs", "selectValues", "selectVariables", "separate", "separateRegexp", "sequence", "serialNumber", "set", "setEcho", "setGroupID", "setIOExclusive", "setIOSynchronized", "setIOUnSynchronized", "setRandomSeed", "setup", "setupEmacs", "setupLift", "setupPromote", "sheaf", "sheafHom", "sheafMap", "show", "showHtml", "showTex", "sign", "simpleDocFrob", "sin", "singularLocus", "sinh", "size", "size2", "sleep", "smithNormalForm", "solve", "someTerms", "sort", "sortColumns", "source", "span", "specialFiber", "specialFiberIdeal", "splice", "splitWWW", "sqrt", "stack", "stacksProject", "stacktrace", "standardForm", "standardPairs", "stashValue", "status", "store", "style", "sub", "sublists", "submatrix", "submatrixByDegrees", "subquotient", "subsets", "substitute", "substring", "subtable", "sum", "super", "support", "switch", "sylvesterMatrix", "symbolBody", "symlinkDirectory", "symlinkFile", "symmetricAlgebra", "symmetricAlgebraIdeal", "symmetricKernel", "symmetricPower", "synonym", "syz", "syzygyScheme", "table", "take", "tally", "tan", "tangentCone", "tangentSheaf", "tanh", "target", "taskResult", "temporaryFileName", "tensor", "tensorAssociativity", "terminalParser", "terms", "testHunekeQuestion", "tests", "tex", "texMath", "times", "toAbsolutePath", "toCC", "toDividedPowers", "toDual", "toExternalString", "toField", "toList", "toLower", "toRR", "toRRi", "toSequence", "toString", "toUpper", "top", "topCoefficients", "topComponents", "trace", "transpose", "trim", "truncate", "truncateOutput", "tutorial", "ultimate", "unbag", "uncurry", "undocumented", "uniform", "uninstallAllPackages", "uninstallPackage", "union", "unique", "uniquePermutations", "unsequence", "unstack", "urlEncode", "use", "userSymbols", "utf8", "utf8check", "utf8substring", "validate", "value", "values", "variety", "vars", "vector", "versalEmbedding", "wait", "wedgeProduct", "weightRange", "whichGm", "width", "wikipedia", "wrap", "youngest", "zero", "zeta" )
M2CONSTANTS = ( "A1BrouwerDegrees", "AbstractSimplicialComplexes", "AbstractToricVarieties", "Acknowledgement", "AdditionalPaths", "AdjointIdeal", "AdjunctionForSurfaces", "AfterEval", "AfterNoPrint", "AfterPrint", "AInfinity", "AlgebraicSplines", "Algorithm", "Alignment", "AllCodimensions", "AllMarkovBases", "allowableThreads", "AnalyzeSheafOnP1", "applicationDirectorySuffix", "argument", "Ascending", "AssociativeAlgebras", "Authors", "AuxiliaryFiles", "backtrace", "Bareiss", "Base", "BaseFunction", "baseRings", "BaseRow", "BasisElementLimit", "Bayer", "BeforePrint", "BeginningMacaulay2", "Benchmark", "BernsteinSato", "Bertini", "BettiCharacters", "BGG", "BIBasis", "Binary", "Binomial", "BinomialEdgeIdeals", "Binomials", "BKZ", "blockMatrixForm", "Body", "BoijSoederberg", "Book3264Examples", "BooleanGB", "Boxes", "Brackets", "Browse", "Bruns", "cache", "CacheExampleOutput", "CallLimit", "CannedExample", "CatalanConstant", "Caveat", "CellularResolutions", "Center", "Certification", "ChainComplexExtras", "ChainComplexOperations", "ChangeMatrix", "CharacteristicClasses", "CheckDocumentation", "Chordal", "Citation", "cite", "Classic", "clearAll", "clearOutput", "close", "closeIn", "closeOut", "ClosestFit", "Code", "CodimensionLimit", "CodingTheory", "CoefficientRing", "Cofactor", "CohenEngine", "CohenTopLevel", "CohomCalg", "CoincidentRootLoci", "commandLine", "compactMatrixForm", "Complement", "CompleteIntersection", "CompleteIntersectionResolutions", "Complexes", "ConductorElement", "Configuration", "ConformalBlocks", "ConnectionMatrices", "Consequences", "Constants", "Contributors", "ConvexInterface", "ConwayPolynomials", "copyright", "Core", "CorrespondenceScrolls", "CotangentSchubert", "cotangentSurjection", "coverageSummary", "CpMackeyFunctors", "Cremona", "currentFileDirectory", "currentFileName", "currentLayout", "currentPackage", "Cyclotomic", "Date", "dd", "DebuggingMode", "debuggingMode", "debugLevel", "DecomposableSparseSystems", "Decompose", "Default", "defaultPrecision", "Degree", "DegreeGroup", "DegreeLift", "DegreeLimit", "DegreeMap", "DegreeOrder", "DegreeRank", "Degrees", "Dense", "Density", "Depth", "Descending", "Description", "DeterminantalRepresentations", "DGAlgebras", "dictionaryPath", "DiffAlg", "Dispatch", "DivideConquer", "DividedPowers", "Dmodules", "docExample", "docTemplate", "Down", "Dynamic", "EagonResolution", "EdgeIdeals", "edit", "EigenSolver", "EisenbudHunekeVasconcelos", "Elimination", "EliminationMatrices", "EllipticCurves", "EllipticIntegrals", "Email", "embeddedToAbstract", "end", "endl", "Engine", "engineDebugLevel", "EngineTests", "EnumerationCurves", "environment", "EquivariantGB", "errorDepth", "EulerConstant", "eulerSequence", "Example", "ExampleFiles", "ExampleSystems", "Exclude", "exit", "Ext", "ExteriorExtensions", "ExteriorIdeals", "ExteriorModules", "ExtLongExactSequence", "false", "FastMinors", "FastNonminimal", "FGLM", "fileDictionaries", "fileExitHooks", "FileName", "FindOne", "FiniteFittingIdeals", "First", "FirstPackage", "FlatMonoid", "Flexible", "flush", "FollowLinks", "ForeignFunctions", "FormalGroupLaws", "Format", "FourierMotzkin", "FourTiTwo", "fpLLL", "FrobeniusThresholds", "FunctionFieldDesingularization", "GameTheory", "GBDegrees", "gbTrace", "GenerateAssertions", "Generic", "GenericInitialIdeal", "GeometricDecomposability", "gfanInterface", "Givens", "GKMVarieties", "GLex", "Global", "GlobalAssignHook", "globalAssignmentHooks", "GlobalHookStore", "GlobalReleaseHook", "GlobalSectionLimit", "Gorenstein", "GradedLieAlgebras", "GraphicalModels", "GraphicalModelsMLE", "Graphics", "Graphs", "GRevLex", "GroebnerStrata", "GroebnerWalk", "GroupLex", "GroupRevLex", "GTZ", "Hadamard", "handleInterrupts", "HardDegreeLimit", "Heading", "Headline", "Heft", "Height", "help", "Hermite", "Hermitian", "HH", "hh", "HigherCIOperators", "HighestWeights", "Hilbert", "HodgeIntegrals", "HolonomicSystems", "homeDirectory", "HomePage", "Homogeneous", "Homogeneous2", "HomologicalAlgebraPackage", "HomotopyLieAlgebra", "HorizontalSpace", "HyperplaneArrangements", "id", "idealSheafSequence", "IgnoreExampleErrors", "ii", "IncidenceCorrespondenceCohomology", "incomparable", "Increment", "indeterminate", "Index", "indexComponents", "infinity", "InfoDirSection", "infoHelp", "Inhomogeneous", "Inputs", "InstallPrefix", "IntegerProgramming", "IntegralClosure", "interpreterDepth", "Intersection", "InvariantRing", "InverseMethod", "Inverses", "InverseSystems", "Invertible", "InvolutiveBases", "Isomorphism", "Item", "Iterate", "Jacobian", "Jets", "Join", "JSON", "JSONRPC", "K3Carpets", "K3Surfaces", "Keep", "KeepFiles", "KeepZeroes", "Key", "Keywords", "Kronecker", "KustinMiller", "lastMatch", "LatticePolytopes", "Layout", "Left", "LengthLimit", "Lex", "LexIdeals", "LieAlgebraRepresentations", "Limit", "Linear", "LinearAlgebra", "LinearTruncations", "lineNumber", "listLocalSymbols", "listUserSymbols", "LLLBases", "loadDepth", "LoadDocumentation", "loadedFiles", "loadedPackages", "Local", "LocalRings", "LongPolynomial", "M0nbar", "Macaulay2Doc", "Maintainer", "MakeDocumentation", "MakeHTML", "MakeInfo", "MakePDF", "MapleInterface", "Markov", "MatchingFields", "MatrixFactorizations", "MatrixSchubert", "Matroids", "maxAllowableThreads", "maxExponent", "MaximalRank", "MaxReductionCount", "MCMApproximations", "MergeTeX", "minExponent", "MinimalGenerators", "MinimalMatrix", "minimalPresentationMap", "minimalPresentationMapInv", "MinimalPrimes", "Minimize", "MinimumVersion", "Miura", "MixedMultiplicity", "ModuleDeformations", "MonodromySolver", "Monomial", "MonomialAlgebras", "MonomialIntegerPrograms", "MonomialOrbits", "MonomialOrder", "Monomials", "MonomialSize", "Msolve", "MultigradedBGG", "MultigradedImplicitization", "MultiGradedRationalMap", "MultiplicitySequence", "MultiplierIdeals", "MultiplierIdealsDim2", "MultiprojectiveVarieties", "NAGtypes", "Name", "Nauty", "NautyGraphs", "NCAlgebra", "NCLex", "NewFromMethod", "newline", "NewMethod", "NewOfFromMethod", "NewOfMethod", "nil", "Node", "NoetherianOperators", "NoetherNormalization", "NonminimalComplexes", "NonPrincipalTestIdeals", "NoPrint", "Normaliz", "NormalToricVarieties", "NotANumber", "notify", "NTL", "null", "nullaryMethods", "NumericalAlgebraicGeometry", "NumericalCertification", "NumericalImplicitization", "NumericalLinearAlgebra", "NumericalSchubertCalculus", "NumericalSemigroups", "NumericSolutions", "numTBBThreads", "OIGroebnerBases", "OldChainComplexes", "OldPolyhedra", "OldToricVectorBundles", "OnlineLookup", "OO", "oo", "ooo", "oooo", "OpenMath", "operatorAttributes", "OptionalComponentsPresent", "Options", "Order", "order", "Oscillators", "OutputDictionary", "Outputs", "PackageCitations", "PackageDictionary", "PackageExports", "PackageImports", "PackageTemplate", "PairLimit", "PairsRemaining", "ParallelF4", "ParallelizeByDegree", "Parametrization", "Parsing", "path", "PathSignatures", "PencilsOfQuadrics", "Permanents", "Permutations", "PHCpack", "PhylogeneticTrees", "pi", "PieriMaps", "PlaneCurveLinearSeries", "PlaneCurveSingularities", "Points", "Polyhedra", "Polymake", "PolyominoIdeals", "Posets", "Position", "PositivityToricBundles", "POSIX", "Postfix", "Pre", "Precision", "Prefix", "prefixDirectory", "prefixPath", "PrimaryDecomposition", "PrimaryTag", "PrimitiveElement", "Print", "printingAccuracy", "printingLeadLimit", "printingPrecision", "printingSeparator", "printingTimeLimit", "printingTrailLimit", "printWidth", "Probability", "profileSummary", "programPaths", "Projective", "Prune", "PruneComplex", "pruningMap", "PseudomonomialPrimaryDecomposition", "Pullback", "pullbackMaps", "PushForward", "pushoutMaps", "Python", "QthPower", "QuadraticIdealExamplesByRoos", "Quasidegrees", "QuaternaryQuartics", "QuillenSuslin", "quit", "Quotient", "Radical", "RadicalCodim1", "RaiseError", "RandomCanonicalCurves", "RandomComplexes", "RandomCurves", "RandomCurvesOverVerySmallFiniteFields", "RandomGenus14Curves", "RandomIdeals", "RandomMonomialIdeals", "RandomObjects", "RandomPlaneCurves", "RandomPoints", "RandomSpaceCurves", "Range", "RationalMaps", "RationalPoints", "RationalPoints2", "ReactionNetworks", "RealFP", "RealQP", "RealQP1", "RealRoots", "RealRR", "RealXD", "recursionLimit", "Reduce", "ReesAlgebra", "References", "ReflexivePolytopesDB", "Regularity", "RelativeCanonicalResolution", "Reload", "RemakeAllDocumentation", "RerunExamples", "ResidualIntersections", "ResLengthThree", "ResolutionsOfStanleyReisnerRings", "restart", "Result", "Resultants", "returnCode", "Reverse", "RevLex", "RHom", "Right", "RInterface", "rootPath", "rootURI", "RunDirectory", "RunExamples", "RunExternalM2", "SagbiGbDetection", "Saturation", "SaturationMap", "Schubert2", "SchurComplexes", "SchurFunctors", "SchurRings", "SchurVeronese", "SCMAlgebras", "scriptCommandLine", "SCSCP", "SectionRing", "SeeAlso", "SegreClasses", "SemidefiniteProgramming", "Seminormalization", "SeparateExec", "Serialization", "sheafExt", "ShimoyamaYokoyama", "showClassStructure", "showStructure", "showUserStructure", "SimpleDoc", "SimplicialComplexes", "SimplicialDecomposability", "SimplicialPosets", "SimplifyFractions", "SizeLimit", "SkewCommutative", "SlackIdeals", "SLnEquivariantMatrices", "SLPexpressions", "Sort", "SortStrategy", "SourceCode", "SourceRing", "SpaceCurves", "SparseResultants", "SpechtModule", "SpecialFanoFourfolds", "SpectralSequences", "SRdeformations", "Standard", "StartWithOneMinor", "StatePolytope", "StatGraphs", "stderr", "stdio", "StopBeforeComputation", "stopIfError", "StopIteration", "StopWithMinimalGenerators", "Strategy", "Strict", "StronglyStableIdeals", "Style", "SubalgebraBases", "Subnodes", "SubringLimit", "subscript", "Sugarless", "SumsOfSquares", "SuperLinearAlgebra", "superscript", "SVDComplexes", "SwitchingFields", "SymbolicPowers", "SymmetricPolynomials", "Synopsis", "Syzygies", "SyzygyLimit", "SyzygyMatrix", "SyzygyRows", "Tableaux", "TangentCone", "TateOnProducts", "TensorComplexes", "TerraciniLoci", "Test", "testExample", "TestIdeals", "TeXmacs", "Text", "ThinSincereQuivers", "ThreadedGB", "Threads", "Threshold", "Topcom", "topLevelMode", "Tor", "TorAlgebra", "Toric", "ToricHigherDirectImages", "ToricInvariants", "ToricTopology", "ToricVectorBundles", "Torsion", "TorsionFree", "TotalPairs", "Tree", "TriangularSets", "Triangulations", "Tries", "Trim", "Triplets", "Tropical", "TropicalToric", "true", "Truncate", "Truncations", "TSpreadIdeals", "TypicalValue", "typicalValues", "Undo", "Unique", "Units", "Unmixed", "Up", "UpdateOnly", "UpperTriangular", "Usage", "UseCachedExampleOutput", "UseHilbertFunction", "UserMode", "UseSyzygies", "Valuations", "Variable", "VariableBaseName", "Variables", "Varieties", "Vasconcelos", "VectorFields", "VectorGraphics", "Verbose", "Verbosity", "Verify", "VersalDeformations", "Version", "version", "VerticalSpace", "viewHelp", "VirtualResolutions", "Visualize", "VNumber", "WebApp", "Weights", "WeilDivisors", "WeylAlgebra", "WeylAlgebras", "WeylGroups", "WhitneyStratifications", "Wrap", "XML", "yonedaSheafExtension" )
class Macaulay2Lexer(RegexLexer): """Lexer for Macaulay2, a software system for research in algebraic geometry."""
name = 'Macaulay2' url = 'https://macaulay2.com/' aliases = ['macaulay2'] filenames = ['*.m2'] version_added = '2.12'
tokens = { 'root': [ (r'--.*$', Comment.Single), (r'-\*', Comment.Multiline, 'block comment'), (r'"', String, 'quote string'), (r'///', String, 'slash string'), (words(M2KEYWORDS, prefix=r'\b', suffix=r'\b'), Keyword), (words(M2DATATYPES, prefix=r'\b', suffix=r'\b'), Name.Builtin), (words(M2FUNCTIONS, prefix=r'\b', suffix=r'\b'), Name.Function), (words(M2CONSTANTS, prefix=r'\b', suffix=r'\b'), Name.Constant), (r'\s+', Text.Whitespace), (r'.', Text) ], 'block comment' : [ (r'[^*-]+', Comment.Multiline), (r'\*-', Comment.Multiline, '#pop'), (r'[*-]', Comment.Multiline) ], 'quote string' : [ (r'[^\\"]+', String), (r'"', String, '#pop'), (r'\\"?', String), ], 'slash string' : [ (r'[^/]+', String), (r'(//)+(?!/)', String), (r'/(//)+(?!/)', String, '#pop'), (r'/', String) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212""" pygments.lexers.make ~~~~~~~~~~~~~~~~~~~~
Lexers for Makefiles and similar.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, \ do_insertions, usingfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Punctuation, Whitespacefrom pygments.lexers.shell import BashLexer
__all__ = ['MakefileLexer', 'BaseMakefileLexer', 'CMakeLexer']
class MakefileLexer(Lexer): """ Lexer for BSD and GNU make extensions (lenient enough to handle both in the same file even).
*Rewritten in Pygments 0.10.* """
name = 'Makefile' aliases = ['make', 'makefile', 'mf', 'bsdmake'] filenames = ['*.mak', '*.mk', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'] mimetypes = ['text/x-makefile'] url = 'https://en.wikipedia.org/wiki/Make_(software)' version_added = ''
r_special = re.compile( r'^(?:' # BSD Make r'\.\s*(include|undef|error|warning|if|else|elif|endif|for|endfor)|' # GNU Make r'\s*(ifeq|ifneq|ifdef|ifndef|else|endif|-?include|define|endef|:|vpath)|' # GNU Automake r'\s*(if|else|endif))(?=\s)') r_comment = re.compile(r'^\s*@?#')
def get_tokens_unprocessed(self, text): ins = [] lines = text.splitlines(keepends=True) done = '' lex = BaseMakefileLexer(**self.options) backslashflag = False for line in lines: if self.r_special.match(line) or backslashflag: ins.append((len(done), [(0, Comment.Preproc, line)])) backslashflag = line.strip().endswith('\\') elif self.r_comment.match(line): ins.append((len(done), [(0, Comment, line)])) else: done += line yield from do_insertions(ins, lex.get_tokens_unprocessed(done))
def analyse_text(text): # Many makefiles have $(BIG_CAPS) style variables if re.search(r'\$\([A-Z_]+\)', text): return 0.1
class BaseMakefileLexer(RegexLexer): """ Lexer for simple Makefiles (no preprocessing). """
name = 'Base Makefile' aliases = ['basemake'] filenames = [] mimetypes = [] url = 'https://en.wikipedia.org/wiki/Make_(software)' version_added = '0.10'
tokens = { 'root': [ # recipes (need to allow spaces because of expandtabs) (r'^(?:[\t ]+.*\n|\n)+', using(BashLexer)), # special variables (r'\$[<@$+%?|*]', Keyword), (r'\s+', Whitespace), (r'#.*?\n', Comment), (r'((?:un)?export)(\s+)(?=[\w${}\t -]+\n)', bygroups(Keyword, Whitespace), 'export'), (r'(?:un)?export\s+', Keyword), # assignment (r'([\w${}().-]+)(\s*)([!?:+]?=)([ \t]*)((?:.*\\\n)+|.*\n)', bygroups( Name.Variable, Whitespace, Operator, Whitespace, using(BashLexer))), # strings (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), # targets (r'([^\n:]+)(:+)([ \t]*)', bygroups( Name.Function, Operator, Whitespace), 'block-header'), # expansions (r'\$\(', Keyword, 'expansion'), ], 'expansion': [ (r'[^\w$().-]+', Text), (r'[\w.-]+', Name.Variable), (r'\$', Keyword), (r'\(', Keyword, '#push'), (r'\)', Keyword, '#pop'), ], 'export': [ (r'[\w${}-]+', Name.Variable), (r'\n', Text, '#pop'), (r'\s+', Whitespace), ], 'block-header': [ (r'[,|]', Punctuation), (r'#.*?\n', Comment, '#pop'), (r'\\\n', Text), # line continuation (r'\$\(', Keyword, 'expansion'), (r'[a-zA-Z_]+', Name), (r'\n', Whitespace, '#pop'), (r'.', Text), ], }
class CMakeLexer(RegexLexer): """ Lexer for CMake files. """ name = 'CMake' url = 'https://cmake.org/documentation/' aliases = ['cmake'] filenames = ['*.cmake', 'CMakeLists.txt'] mimetypes = ['text/x-cmake'] version_added = '1.2'
tokens = { 'root': [ # (r'(ADD_CUSTOM_COMMAND|ADD_CUSTOM_TARGET|ADD_DEFINITIONS|' # r'ADD_DEPENDENCIES|ADD_EXECUTABLE|ADD_LIBRARY|ADD_SUBDIRECTORY|' # r'ADD_TEST|AUX_SOURCE_DIRECTORY|BUILD_COMMAND|BUILD_NAME|' # r'CMAKE_MINIMUM_REQUIRED|CONFIGURE_FILE|CREATE_TEST_SOURCELIST|' # r'ELSE|ELSEIF|ENABLE_LANGUAGE|ENABLE_TESTING|ENDFOREACH|' # r'ENDFUNCTION|ENDIF|ENDMACRO|ENDWHILE|EXEC_PROGRAM|' # r'EXECUTE_PROCESS|EXPORT_LIBRARY_DEPENDENCIES|FILE|FIND_FILE|' # r'FIND_LIBRARY|FIND_PACKAGE|FIND_PATH|FIND_PROGRAM|FLTK_WRAP_UI|' # r'FOREACH|FUNCTION|GET_CMAKE_PROPERTY|GET_DIRECTORY_PROPERTY|' # r'GET_FILENAME_COMPONENT|GET_SOURCE_FILE_PROPERTY|' # r'GET_TARGET_PROPERTY|GET_TEST_PROPERTY|IF|INCLUDE|' # r'INCLUDE_DIRECTORIES|INCLUDE_EXTERNAL_MSPROJECT|' # r'INCLUDE_REGULAR_EXPRESSION|INSTALL|INSTALL_FILES|' # r'INSTALL_PROGRAMS|INSTALL_TARGETS|LINK_DIRECTORIES|' # r'LINK_LIBRARIES|LIST|LOAD_CACHE|LOAD_COMMAND|MACRO|' # r'MAKE_DIRECTORY|MARK_AS_ADVANCED|MATH|MESSAGE|OPTION|' # r'OUTPUT_REQUIRED_FILES|PROJECT|QT_WRAP_CPP|QT_WRAP_UI|REMOVE|' # r'REMOVE_DEFINITIONS|SEPARATE_ARGUMENTS|SET|' # r'SET_DIRECTORY_PROPERTIES|SET_SOURCE_FILES_PROPERTIES|' # r'SET_TARGET_PROPERTIES|SET_TESTS_PROPERTIES|SITE_NAME|' # r'SOURCE_GROUP|STRING|SUBDIR_DEPENDS|SUBDIRS|' # r'TARGET_LINK_LIBRARIES|TRY_COMPILE|TRY_RUN|UNSET|' # r'USE_MANGLED_MESA|UTILITY_SOURCE|VARIABLE_REQUIRES|' # r'VTK_MAKE_INSTANTIATOR|VTK_WRAP_JAVA|VTK_WRAP_PYTHON|' # r'VTK_WRAP_TCL|WHILE|WRITE_FILE|' # r'COUNTARGS)\b', Name.Builtin, 'args'), (r'\b(\w+)([ \t]*)(\()', bygroups(Name.Builtin, Whitespace, Punctuation), 'args'), include('keywords'), include('ws') ], 'args': [ (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), (r'(\$\{)(.+?)(\})', bygroups(Operator, Name.Variable, Operator)), (r'(\$ENV\{)(.+?)(\})', bygroups(Operator, Name.Variable, Operator)), (r'(\$<)(.+?)(>)', bygroups(Operator, Name.Variable, Operator)), (r'(?s)".*?"', String.Double), (r'\\\S+', String), (r'\[(?P<level>=*)\[[\w\W]*?\](?P=level)\]', String.Multiline), (r'[^)$"# \t\n]+', String), (r'\n', Whitespace), # explicitly legal include('keywords'), include('ws') ], 'string': [
], 'keywords': [ (r'\b(WIN32|UNIX|APPLE|CYGWIN|BORLAND|MINGW|MSVC|MSVC_IDE|MSVC60|' r'MSVC70|MSVC71|MSVC80|MSVC90)\b', Keyword), ], 'ws': [ (r'[ \t]+', Whitespace), (r'#\[(?P<level>=*)\[[\w\W]*?\](?P=level)\]', Comment), (r'#.*\n', Comment), ] }
def analyse_text(text): exp = ( r'^[ \t]*CMAKE_MINIMUM_REQUIRED[ \t]*' r'\([ \t]*VERSION[ \t]*\d+(\.\d+)*[ \t]*' r'([ \t]FATAL_ERROR)?[ \t]*\)[ \t]*' r'(#[^\n]*)?$' ) if re.search(exp, text, flags=re.MULTILINE | re.IGNORECASE): return 0.8 return 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291""" pygments.lexers.maple ~~~~~~~~~~~~~~~~~~~~~
Lexers for Maple.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import words, bygroups, ExtendedRegexLexerfrom pygments.token import Comment, Name, String, Whitespace, Operator, Punctuation, Number, Keyword
__all__ = ['MapleLexer']
class MapleLexer(ExtendedRegexLexer): """ Lexer for Maple. """
name = 'Maple' aliases = ['maple'] filenames = ['*.mpl', '*.mi', '*.mm'] mimetypes = ['text/x-maple'] url = 'https://www.maplesoft.com/products/Maple/' version_added = '2.19'
keywords = ('and', 'assuming', 'break', 'by', 'catch', 'description', 'do', 'done', 'elif', 'else', 'end', 'error', 'export', 'fi', 'finally', 'for', 'from', 'global', 'if', 'implies', 'in', 'intersect', 'local', 'minus', 'mod', 'module', 'next', 'not', 'od', 'option', 'options', 'or', 'proc', 'quit', 'read', 'return', 'save', 'stop', 'subset', 'then', 'to', 'try', 'union', 'use', 'uses', 'while', 'xor')
builtins = ('abs', 'add', 'addressof', 'anames', 'and', 'andmap', 'andseq', 'appendto', 'Array', 'array', 'ArrayOptions', 'assemble', 'ASSERT', 'assign', 'assigned', 'attributes', 'cat', 'ceil', 'coeff', 'coeffs', 'conjugate', 'convert', 'CopySign', 'DEBUG', 'debugopts', 'Default0', 'DefaultOverflow', 'DefaultUnderflow', 'degree', 'denom', 'diff', 'disassemble', 'divide', 'done', 'entries', 'EqualEntries', 'eval', 'evalb', 'evalf', 'evalhf', 'evalindets', 'evaln', 'expand', 'exports', 'factorial', 'floor', 'frac', 'frem', 'FromInert', 'frontend', 'gc', 'genpoly', 'has', 'hastype', 'hfarray', 'icontent', 'igcd', 'ilcm', 'ilog10', 'Im', 'implies', 'indets', 'indices', 'intersect', 'iolib', 'iquo', 'irem', 'iroot', 'iroot', 'isqrt', 'kernelopts', 'lcoeff', 'ldegree', 'length', 'lexorder', 'lhs', 'lowerbound', 'lprint', 'macro', 'map', 'max', 'maxnorm', 'member', 'membertype', 'min', 'minus', 'mod', 'modp', 'modp1', 'modp2', 'mods', 'mul', 'NextAfter', 'nops', 'normal', 'not', 'numboccur', 'numelems', 'numer', 'NumericClass', 'NumericEvent', 'NumericEventHandler', 'NumericStatus', 'op', 'or', 'order', 'OrderedNE', 'ormap', 'orseq', 'parse', 'piecewise', 'pointto', 'print', 'quit', 'Re', 'readlib', 'Record', 'remove', 'rhs', 'round', 'rtable', 'rtable_elems', 'rtable_eval', 'rtable_indfns', 'rtable_num_elems', 'rtable_options', 'rtable_redim', 'rtable_scanblock', 'rtable_set_indfn', 'rtable_split_unit', 'savelib', 'Scale10', 'Scale2', 'SDMPolynom', 'searchtext', 'SearchText', 'select', 'selectremove', 'seq', 'series', 'setattribute', 'SFloatExponent', 'SFloatMantissa', 'sign', 'sort', 'ssystem', 'stop', 'String', 'subs', 'subset', 'subsindets', 'subsop', 'substring', 'system', 'table', 'taylor', 'tcoeff', 'time', 'timelimit', 'ToInert', 'traperror', 'trunc', 'type', 'typematch', 'unames', 'unassign', 'union', 'Unordered', 'upperbound', 'userinfo', 'writeto', 'xor', 'xormap', 'xorseq')
def delayed_callback(self, match, ctx): yield match.start(1), Punctuation, match.group(1) # quote
ctx.pos = match.start(2) orig_end = ctx.end ctx.end = match.end(2)
yield from self.get_tokens_unprocessed(context=ctx) yield match.end(2), Punctuation, match.group(1) # quote
ctx.pos = match.end() ctx.end = orig_end
tokens = { 'root': [ (r'#.*\n', Comment.Single), (r'\(\*', Comment.Multiline, 'comment'), (r'"(\\.|.|\s)*?"', String), (r"('+)((.|\n)*?)\1", delayed_callback), (r'`(\\`|.)*?`', Name), (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword), (words(builtins, prefix=r'\b', suffix=r'\b'), Name.Builtin), (r'[a-zA-Z_][a-zA-Z0-9_]*', Name), (r'(:=|\*\*|@@|<=|>=|<>|->|::|\.\.|&\+|[\+\-\*\.\^\$/@&,:=<>%~])', Operator), (r'[;^!@$\(\)\[\]{}|_\\#?]+', Punctuation), (r'(\d+)(\.\.)', bygroups(Number.Integer, Punctuation)), (r'(\d*\.\d+|\d+\.\d*)([eE][+-]?\d+)?', Number.Float), (r'\d+', Number.Integer), (r'\s+', Whitespace), ], 'comment': [ (r'.*\(\*', Comment.Multiline, '#push'), (r'.*\*\)', Comment.Multiline, '#pop'), (r'.*\n', Comment.Multiline), ] }
def analyse_text(text): if ':=' in text: return 0.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659""" pygments.lexers.markup ~~~~~~~~~~~~~~~~~~~~~~
Lexers for non-HTML markup languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexers.html import XmlLexerfrom pygments.lexers.javascript import JavascriptLexerfrom pygments.lexers.css import CssLexerfrom pygments.lexers.lilypond import LilyPondLexerfrom pygments.lexers.data import JsonLexer
from pygments.lexer import RegexLexer, DelegatingLexer, include, bygroups, \ using, this, do_insertions, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Other, Whitespace, Literalfrom pygments.util import get_bool_opt, ClassNotFound
__all__ = ['BBCodeLexer', 'MoinWikiLexer', 'RstLexer', 'TexLexer', 'GroffLexer', 'MozPreprocHashLexer', 'MozPreprocPercentLexer', 'MozPreprocXulLexer', 'MozPreprocJavascriptLexer', 'MozPreprocCssLexer', 'MarkdownLexer', 'OrgLexer', 'TiddlyWiki5Lexer', 'WikitextLexer']
class BBCodeLexer(RegexLexer): """ A lexer that highlights BBCode(-like) syntax. """
name = 'BBCode' aliases = ['bbcode'] mimetypes = ['text/x-bbcode'] url = 'https://www.bbcode.org/' version_added = '0.6'
tokens = { 'root': [ (r'[^[]+', Text), # tag/end tag begin (r'\[/?\w+', Keyword, 'tag'), # stray bracket (r'\[', Text), ], 'tag': [ (r'\s+', Text), # attribute with value (r'(\w+)(=)("?[^\s"\]]+"?)', bygroups(Name.Attribute, Operator, String)), # tag argument (a la [color=green]) (r'(=)("?[^\s"\]]+"?)', bygroups(Operator, String)), # tag end (r'\]', Keyword, '#pop'), ], }
class MoinWikiLexer(RegexLexer): """ For MoinMoin (and Trac) Wiki markup. """
name = 'MoinMoin/Trac Wiki markup' aliases = ['trac-wiki', 'moin'] filenames = [] mimetypes = ['text/x-trac-wiki'] url = 'https://moinmo.in' version_added = '0.7'
flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ (r'^#.*$', Comment), (r'(!)(\S+)', bygroups(Keyword, Text)), # Ignore-next # Titles (r'^(=+)([^=]+)(=+)(\s*#.+)?$', bygroups(Generic.Heading, using(this), Generic.Heading, String)), # Literal code blocks, with optional shebang (r'(\{\{\{)(\n#!.+)?', bygroups(Name.Builtin, Name.Namespace), 'codeblock'), (r'(\'\'\'?|\|\||`|__|~~|\^|,,|::)', Comment), # Formatting # Lists (r'^( +)([.*-])( )', bygroups(Text, Name.Builtin, Text)), (r'^( +)([a-z]{1,5}\.)( )', bygroups(Text, Name.Builtin, Text)), # Other Formatting (r'\[\[\w+.*?\]\]', Keyword), # Macro (r'(\[[^\s\]]+)(\s+[^\]]+?)?(\])', bygroups(Keyword, String, Keyword)), # Link (r'^----+$', Keyword), # Horizontal rules (r'[^\n\'\[{!_~^,|]+', Text), (r'\n', Text), (r'.', Text), ], 'codeblock': [ (r'\}\}\}', Name.Builtin, '#pop'), # these blocks are allowed to be nested in Trac, but not MoinMoin (r'\{\{\{', Text, '#push'), (r'[^{}]+', Comment.Preproc), # slurp boring text (r'.', Comment.Preproc), # allow loose { or } ], }
class RstLexer(RegexLexer): """ For reStructuredText markup.
Additional options accepted:
`handlecodeblocks` Highlight the contents of ``.. sourcecode:: language``, ``.. code:: language`` and ``.. code-block:: language`` directives with a lexer for the given language (default: ``True``).
.. versionadded:: 0.8 """ name = 'reStructuredText' url = 'https://docutils.sourceforge.io/rst.html' aliases = ['restructuredtext', 'rst', 'rest'] filenames = ['*.rst', '*.rest'] mimetypes = ["text/x-rst", "text/prs.fallenstein.rst"] version_added = '0.7' flags = re.MULTILINE
def _handle_sourcecode(self, match): from pygments.lexers import get_lexer_by_name
# section header yield match.start(1), Punctuation, match.group(1) yield match.start(2), Text, match.group(2) yield match.start(3), Operator.Word, match.group(3) yield match.start(4), Punctuation, match.group(4) yield match.start(5), Text, match.group(5) yield match.start(6), Keyword, match.group(6) yield match.start(7), Text, match.group(7)
# lookup lexer if wanted and existing lexer = None if self.handlecodeblocks: try: lexer = get_lexer_by_name(match.group(6).strip()) except ClassNotFound: pass indention = match.group(8) indention_size = len(indention) code = (indention + match.group(9) + match.group(10) + match.group(11))
# no lexer for this language. handle it like it was a code block if lexer is None: yield match.start(8), String, code return
# highlight the lines with the lexer. ins = [] codelines = code.splitlines(True) code = '' for line in codelines: if len(line) > indention_size: ins.append((len(code), [(0, Text, line[:indention_size])])) code += line[indention_size:] else: code += line yield from do_insertions(ins, lexer.get_tokens_unprocessed(code))
# from docutils.parsers.rst.states closers = '\'")]}>\u2019\u201d\xbb!?' unicode_delimiters = '\u2010\u2011\u2012\u2013\u2014\u00a0' end_string_suffix = (rf'((?=$)|(?=[-/:.,; \n\x00{re.escape(unicode_delimiters)}{re.escape(closers)}]))')
tokens = { 'root': [ # Heading with overline (r'^(=+|-+|`+|:+|\.+|\'+|"+|~+|\^+|_+|\*+|\++|#+)([ \t]*\n)' r'(.+)(\n)(\1)(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text, Generic.Heading, Text)), # Plain heading (r'^(\S.*)(\n)(={3,}|-{3,}|`{3,}|:{3,}|\.{3,}|\'{3,}|"{3,}|' r'~{3,}|\^{3,}|_{3,}|\*{3,}|\+{3,}|#{3,})(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text)), # Bulleted lists (r'^(\s*)([-*+])( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), # Numbered lists (r'^(\s*)([0-9#ivxlcmIVXLCM]+\.)( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), (r'^(\s*)(\(?[0-9#ivxlcmIVXLCM]+\))( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), # Numbered, but keep words at BOL from becoming lists (r'^(\s*)([A-Z]+\.)( .+\n(?:\1 .+\n)+)', bygroups(Text, Number, using(this, state='inline'))), (r'^(\s*)(\(?[A-Za-z]+\))( .+\n(?:\1 .+\n)+)', bygroups(Text, Number, using(this, state='inline'))), # Line blocks (r'^(\s*)(\|)( .+\n(?:\| .+\n)*)', bygroups(Text, Operator, using(this, state='inline'))), # Sourcecode directives (r'^( *\.\.)(\s*)((?:source)?code(?:-block)?)(::)([ \t]*)([^\n]+)' r'(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\8.*)?\n)+)', _handle_sourcecode), # A directive (r'^( *\.\.)(\s*)([\w:-]+?)(::)(?:([ \t]*)(.*))', bygroups(Punctuation, Text, Operator.Word, Punctuation, Text, using(this, state='inline'))), # A reference target (r'^( *\.\.)(\s*)(_(?:[^:\\]|\\.)+:)(.*?)$', bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))), # A footnote/citation target (r'^( *\.\.)(\s*)(\[.+\])(.*?)$', bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))), # A substitution def (r'^( *\.\.)(\s*)(\|.+\|)(\s*)([\w:-]+?)(::)(?:([ \t]*)(.*))', bygroups(Punctuation, Text, Name.Tag, Text, Operator.Word, Punctuation, Text, using(this, state='inline'))), # Comments (r'^ *\.\..*(\n( +.*\n|\n)+)?', Comment), # Field list marker (r'^( *)(:(?:\\\\|\\:|[^:\n])+:(?=\s))([ \t]*)', bygroups(Text, Name.Class, Text)), # Definition list (r'^(\S.*(?<!::)\n)((?:(?: +.*)\n)+)', bygroups(using(this, state='inline'), using(this, state='inline'))), # Code blocks (r'(::)(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\3.*)?\n)+)', bygroups(String.Escape, Text, String, String, Text, String)), include('inline'), ], 'inline': [ (r'\\.', Text), # escape (r'``', String, 'literal'), # code (r'(`.+?)(<.+?>)(`__?)', # reference with inline target bygroups(String, String.Interpol, String)), (r'`.+?`__?', String), # reference (r'(`.+?`)(:[a-zA-Z0-9:-]+?:)?', bygroups(Name.Variable, Name.Attribute)), # role (r'(:[a-zA-Z0-9:-]+?:)(`.+?`)', bygroups(Name.Attribute, Name.Variable)), # role (content first) (r'\*\*.+?\*\*', Generic.Strong), # Strong emphasis (r'\*.+?\*', Generic.Emph), # Emphasis (r'\[.*?\]_', String), # Footnote or citation (r'<.+?>', Name.Tag), # Hyperlink (r'[^\\\n\[*`:]+', Text), (r'.', Text), ], 'literal': [ (r'[^`]+', String), (r'``' + end_string_suffix, String, '#pop'), (r'`', String), ] }
def __init__(self, **options): self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True) RegexLexer.__init__(self, **options)
def analyse_text(text): if text[:2] == '..' and text[2:3] != '.': return 0.3 p1 = text.find("\n") p2 = text.find("\n", p1 + 1) if (p2 > -1 and # has two lines p1 * 2 + 1 == p2 and # they are the same length text[p1+1] in '-=' and # the next line both starts and ends with text[p1+1] == text[p2-1]): # ...a sufficiently high header return 0.5
class TexLexer(RegexLexer): """ Lexer for the TeX and LaTeX typesetting languages. """
name = 'TeX' aliases = ['tex', 'latex'] filenames = ['*.tex', '*.aux', '*.toc'] mimetypes = ['text/x-tex', 'text/x-latex'] url = 'https://tug.org' version_added = ''
tokens = { 'general': [ (r'%.*?\n', Comment), (r'[{}]', Name.Builtin), (r'[&_^]', Name.Builtin), ], 'root': [ (r'\\\[', String.Backtick, 'displaymath'), (r'\\\(', String, 'inlinemath'), (r'\$\$', String.Backtick, 'displaymath'), (r'\$', String, 'inlinemath'), (r'\\([a-zA-Z@_:]+|\S?)', Keyword, 'command'), (r'\\$', Keyword), include('general'), (r'[^\\$%&_^{}]+', Text), ], 'math': [ (r'\\([a-zA-Z]+|\S?)', Name.Variable), include('general'), (r'[0-9]+', Number), (r'[-=!+*/()\[\]]', Operator), (r'[^=!+*/()\[\]\\$%&_^{}0-9-]+', Name.Builtin), ], 'inlinemath': [ (r'\\\)', String, '#pop'), (r'\$', String, '#pop'), include('math'), ], 'displaymath': [ (r'\\\]', String, '#pop'), (r'\$\$', String, '#pop'), (r'\$', Name.Builtin), include('math'), ], 'command': [ (r'\[.*?\]', Name.Attribute), (r'\*', Keyword), default('#pop'), ], }
def analyse_text(text): for start in ("\\documentclass", "\\input", "\\documentstyle", "\\relax"): if text[:len(start)] == start: return True
class GroffLexer(RegexLexer): """ Lexer for the (g)roff typesetting language, supporting groff extensions. Mainly useful for highlighting manpage sources. """
name = 'Groff' aliases = ['groff', 'nroff', 'man'] filenames = ['*.[1-9]', '*.man', '*.1p', '*.3pm'] mimetypes = ['application/x-troff', 'text/troff'] url = 'https://www.gnu.org/software/groff' version_added = '0.6'
tokens = { 'root': [ (r'(\.)(\w+)', bygroups(Text, Keyword), 'request'), (r'\.', Punctuation, 'request'), # Regular characters, slurp till we find a backslash or newline (r'[^\\\n]+', Text, 'textline'), default('textline'), ], 'textline': [ include('escapes'), (r'[^\\\n]+', Text), (r'\n', Text, '#pop'), ], 'escapes': [ # groff has many ways to write escapes. (r'\\"[^\n]*', Comment), (r'\\[fn]\w', String.Escape), (r'\\\(.{2}', String.Escape), (r'\\.\[.*\]', String.Escape), (r'\\.', String.Escape), (r'\\\n', Text, 'request'), ], 'request': [ (r'\n', Text, '#pop'), include('escapes'), (r'"[^\n"]+"', String.Double), (r'\d+', Number), (r'\S+', String), (r'\s+', Text), ], }
def analyse_text(text): if text[:1] != '.': return False if text[:3] == '.\\"': return True if text[:4] == '.TH ': return True if text[1:3].isalnum() and text[3].isspace(): return 0.9
class MozPreprocHashLexer(RegexLexer): """ Lexer for Mozilla Preprocessor files (with '#' as the marker).
Other data is left untouched. """ name = 'mozhashpreproc' aliases = [name] filenames = [] mimetypes = [] url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html' version_added = '2.0'
tokens = { 'root': [ (r'^#', Comment.Preproc, ('expr', 'exprstart')), (r'.+', Other), ], 'exprstart': [ (r'(literal)(.*)', bygroups(Comment.Preproc, Text), '#pop:2'), (words(( 'define', 'undef', 'if', 'ifdef', 'ifndef', 'else', 'elif', 'elifdef', 'elifndef', 'endif', 'expand', 'filter', 'unfilter', 'include', 'includesubst', 'error')), Comment.Preproc, '#pop'), ], 'expr': [ (words(('!', '!=', '==', '&&', '||')), Operator), (r'(defined)(\()', bygroups(Keyword, Punctuation)), (r'\)', Punctuation), (r'[0-9]+', Number.Decimal), (r'__\w+?__', Name.Variable), (r'@\w+?@', Name.Class), (r'\w+', Name), (r'\n', Text, '#pop'), (r'\s+', Text), (r'\S', Punctuation), ], }
class MozPreprocPercentLexer(MozPreprocHashLexer): """ Lexer for Mozilla Preprocessor files (with '%' as the marker).
Other data is left untouched. """ name = 'mozpercentpreproc' aliases = [name] filenames = [] mimetypes = [] url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html' version_added = '2.0'
tokens = { 'root': [ (r'^%', Comment.Preproc, ('expr', 'exprstart')), (r'.+', Other), ], }
class MozPreprocXulLexer(DelegatingLexer): """ Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the `XmlLexer`. """ name = "XUL+mozpreproc" aliases = ['xul+mozpreproc'] filenames = ['*.xul.in'] mimetypes = [] url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html' version_added = '2.0'
def __init__(self, **options): super().__init__(XmlLexer, MozPreprocHashLexer, **options)
class MozPreprocJavascriptLexer(DelegatingLexer): """ Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the `JavascriptLexer`. """ name = "Javascript+mozpreproc" aliases = ['javascript+mozpreproc'] filenames = ['*.js.in'] mimetypes = [] url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html' version_added = '2.0'
def __init__(self, **options): super().__init__(JavascriptLexer, MozPreprocHashLexer, **options)
class MozPreprocCssLexer(DelegatingLexer): """ Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the `CssLexer`. """ name = "CSS+mozpreproc" aliases = ['css+mozpreproc'] filenames = ['*.css.in'] mimetypes = [] url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html' version_added = '2.0'
def __init__(self, **options): super().__init__(CssLexer, MozPreprocPercentLexer, **options)
class MarkdownLexer(RegexLexer): """ For Markdown markup. """ name = 'Markdown' url = 'https://daringfireball.net/projects/markdown/' aliases = ['markdown', 'md'] filenames = ['*.md', '*.markdown'] mimetypes = ["text/x-markdown"] version_added = '2.2' flags = re.MULTILINE
def _handle_codeblock(self, match): from pygments.lexers import get_lexer_by_name
yield match.start('initial'), String.Backtick, match.group('initial') yield match.start('lang'), String.Backtick, match.group('lang') if match.group('afterlang') is not None: yield match.start('whitespace'), Whitespace, match.group('whitespace') yield match.start('extra'), Text, match.group('extra') yield match.start('newline'), Whitespace, match.group('newline')
# lookup lexer if wanted and existing lexer = None if self.handlecodeblocks: try: lexer = get_lexer_by_name(match.group('lang').strip()) except ClassNotFound: pass code = match.group('code') # no lexer for this language. handle it like it was a code block if lexer is None: yield match.start('code'), String, code else: # FIXME: aren't the offsets wrong? yield from do_insertions([], lexer.get_tokens_unprocessed(code))
yield match.start('terminator'), String.Backtick, match.group('terminator')
tokens = { 'root': [ # heading with '#' prefix (atx-style) (r'(^#[^#].+)(\n)', bygroups(Generic.Heading, Text)), # subheading with '#' prefix (atx-style) (r'(^#{2,6}[^#].+)(\n)', bygroups(Generic.Subheading, Text)), # heading with '=' underlines (Setext-style) (r'^(.+)(\n)(=+)(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text)), # subheading with '-' underlines (Setext-style) (r'^(.+)(\n)(-+)(\n)', bygroups(Generic.Subheading, Text, Generic.Subheading, Text)), # task list (r'^(\s*)([*-] )(\[[ xX]\])( .+\n)', bygroups(Whitespace, Keyword, Keyword, using(this, state='inline'))), # bulleted list (r'^(\s*)([*-])(\s)(.+\n)', bygroups(Whitespace, Keyword, Whitespace, using(this, state='inline'))), # numbered list (r'^(\s*)([0-9]+\.)( .+\n)', bygroups(Whitespace, Keyword, using(this, state='inline'))), # quote (r'^(\s*>\s)(.+\n)', bygroups(Keyword, Generic.Emph)), # code block fenced by 3 backticks (r'^(\s*```\n[\w\W]*?^\s*```$\n)', String.Backtick), # code block with language # Some tools include extra stuff after the language name, just # highlight that as text. For example: https://docs.enola.dev/use/execmd (r'''(?x) ^(?P<initial>\s*```) (?P<lang>[\w\-]+) (?P<afterlang> (?P<whitespace>[^\S\n]+) (?P<extra>.*))? (?P<newline>\n) (?P<code>(.|\n)*?) (?P<terminator>^\s*```$\n) ''', _handle_codeblock),
include('inline'), ], 'inline': [ # escape (r'\\.', Text), # inline code (r'([^`]?)(`[^`\n]+`)', bygroups(Text, String.Backtick)), # warning: the following rules eat outer tags. # eg. **foo _bar_ baz** => foo and baz are not recognized as bold # bold fenced by '**' (r'([^\*]?)(\*\*[^* \n][^*\n]*\*\*)', bygroups(Text, Generic.Strong)), # bold fenced by '__' (r'([^_]?)(__[^_ \n][^_\n]*__)', bygroups(Text, Generic.Strong)), # italics fenced by '*' (r'([^\*]?)(\*[^* \n][^*\n]*\*)', bygroups(Text, Generic.Emph)), # italics fenced by '_' (r'([^_]?)(_[^_ \n][^_\n]*_)', bygroups(Text, Generic.Emph)), # strikethrough (r'([^~]?)(~~[^~ \n][^~\n]*~~)', bygroups(Text, Generic.Deleted)), # mentions and topics (twitter and github stuff) (r'[@#][\w/:]+', Name.Entity), # (image?) links eg:  (r'(!?\[)([^]]+)(\])(\()([^)]+)(\))', bygroups(Text, Name.Tag, Text, Text, Name.Attribute, Text)), # reference-style links, e.g.: # [an example][id] # [id]: http://example.com/ (r'(\[)([^]]+)(\])(\[)([^]]*)(\])', bygroups(Text, Name.Tag, Text, Text, Name.Label, Text)), (r'^(\s*\[)([^]]*)(\]:\s*)(.+)', bygroups(Text, Name.Label, Text, Name.Attribute)),
# general text, must come last! (r'[^\\\s]+', Text), (r'.', Text), ], }
def __init__(self, **options): self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True) RegexLexer.__init__(self, **options)
class OrgLexer(RegexLexer): """ For Org Mode markup. """ name = 'Org Mode' url = 'https://orgmode.org' aliases = ['org', 'orgmode', 'org-mode'] filenames = ['*.org'] mimetypes = ["text/org"] version_added = '2.18'
def _inline(start, end): return rf'(?<!\w){start}(.|\n(?!\n))+?{end}(?!\w)'
tokens = { 'root': [ (r'^# .*', Comment.Single),
# Headings (r'^(\* )(COMMENT)( .*)', bygroups(Generic.Heading, Comment.Preproc, Generic.Heading)), (r'^(\*\*+ )(COMMENT)( .*)', bygroups(Generic.Subheading, Comment.Preproc, Generic.Subheading)), (r'^(\* )(DONE)( .*)', bygroups(Generic.Heading, Generic.Deleted, Generic.Heading)), (r'^(\*\*+ )(DONE)( .*)', bygroups(Generic.Subheading, Generic.Deleted, Generic.Subheading)), (r'^(\* )(TODO)( .*)', bygroups(Generic.Heading, Generic.Error, Generic.Heading)), (r'^(\*\*+ )(TODO)( .*)', bygroups(Generic.Subheading, Generic.Error, Generic.Subheading)),
(r'^(\* .+?)( :[a-zA-Z0-9_@:]+:)?$', bygroups(Generic.Heading, Generic.Emph)), (r'^(\*\*+ .+?)( :[a-zA-Z0-9_@:]+:)?$', bygroups(Generic.Subheading, Generic.Emph)),
# Unordered lists items, including TODO items and description items (r'^(?:( *)([+-] )|( +)(\* ))(\[[ X-]\])?(.+ ::)?', bygroups(Whitespace, Keyword, Whitespace, Keyword, Generic.Prompt, Name.Label)),
# Ordered list items (r'^( *)([0-9]+[.)])( \[@[0-9]+\])?', bygroups(Whitespace, Keyword, Generic.Emph)),
# Dynamic blocks (r'(?i)^( *#\+begin: *)((?:.|\n)*?)(^ *#\+end: *$)', bygroups(Operator.Word, using(this), Operator.Word)),
# Comment blocks (r'(?i)^( *#\+begin_comment *\n)((?:.|\n)*?)(^ *#\+end_comment *$)', bygroups(Operator.Word, Comment.Multiline, Operator.Word)),
# Source code blocks # TODO: language-dependent syntax highlighting (see Markdown lexer) (r'(?i)^( *#\+begin_src .*)((?:.|\n)*?)(^ *#\+end_src *$)', bygroups(Operator.Word, Text, Operator.Word)),
# Other blocks (r'(?i)^( *#\+begin_\w+)( *\n)((?:.|\n)*?)(^ *#\+end_\w+)( *$)', bygroups(Operator.Word, Whitespace, Text, Operator.Word, Whitespace)),
# Keywords (r'^(#\+\w+:)(.*)$', bygroups(Name.Namespace, Text)),
# Properties and drawers (r'(?i)^( *:\w+: *\n)((?:.|\n)*?)(^ *:end: *$)', bygroups(Name.Decorator, Comment.Special, Name.Decorator)),
# Line break operator (r'\\\\$', Operator),
(r'^\s*CLOSED:\s+', Generic.Deleted, 'dateline'), (r'^\s*(?:DEADLINE:|SCHEDULED:)\s+', Generic.Error, 'dateline'),
# Bold (_inline(r'\*', r'\*+'), Generic.Strong), # Italic (_inline(r'/', r'/'), Generic.Emph), # Verbatim (_inline(r'=', r'='), String), # TODO token # Code (_inline(r'~', r'~'), String), # Strikethrough (_inline(r'\+', r'\+'), Generic.Deleted), # Underline (_inline(r'_', r'_+'), Generic.EmphStrong),
# Dates (r'<.+?>', Literal.Date), # Macros (r'\{\{\{.+?\}\}\}', Comment.Preproc), # Footnotes (r'(?<!\[)\[fn:.+?\]', Name.Tag), # Links (r'(?s)(\[\[)(.*?)(\]\[)(.*?)(\]\])', bygroups(Punctuation, Name.Attribute, Punctuation, Name.Tag, Punctuation)), (r'(?s)(\[\[)(.+?)(\]\])', bygroups(Punctuation, Name.Attribute, Punctuation)), (r'(<<)(.+?)(>>)', bygroups(Punctuation, Name.Attribute, Punctuation)),
# Tables (r'^( *)(\|[ -].*?[ -]\|)$', bygroups(Whitespace, String)),
# Any other text (r'[^#*+\-0-9:\\/=~_<{\[|\n]+', Text), (r'[#*+\-0-9:\\/=~_<{\[|\n]', Text), ], 'dateline': [ (r'\s*CLOSED:\s+', Generic.Deleted), (r'\s*(?:DEADLINE:|SCHEDULED:)\s+', Generic.Error), (r'\[.+?\]', Literal.Date), (r'<[^>]+?>', Literal.Date), (r'(\s*)$', Text, '#pop'), (r'.', Text), ], }
class TiddlyWiki5Lexer(RegexLexer): """ For TiddlyWiki5 markup. """ name = 'tiddler' url = 'https://tiddlywiki.com/#TiddlerFiles' aliases = ['tid'] filenames = ['*.tid'] mimetypes = ["text/vnd.tiddlywiki"] version_added = '2.7' flags = re.MULTILINE
def _handle_codeblock(self, match): """ match args: 1:backticks, 2:lang_name, 3:newline, 4:code, 5:backticks """ from pygments.lexers import get_lexer_by_name
# section header yield match.start(1), String, match.group(1) yield match.start(2), String, match.group(2) yield match.start(3), Text, match.group(3)
# lookup lexer if wanted and existing lexer = None if self.handlecodeblocks: try: lexer = get_lexer_by_name(match.group(2).strip()) except ClassNotFound: pass code = match.group(4)
# no lexer for this language. handle it like it was a code block if lexer is None: yield match.start(4), String, code return
yield from do_insertions([], lexer.get_tokens_unprocessed(code))
yield match.start(5), String, match.group(5)
def _handle_cssblock(self, match): """ match args: 1:style tag 2:newline, 3:code, 4:closing style tag """ from pygments.lexers import get_lexer_by_name
# section header yield match.start(1), String, match.group(1) yield match.start(2), String, match.group(2)
lexer = None if self.handlecodeblocks: try: lexer = get_lexer_by_name('css') except ClassNotFound: pass code = match.group(3)
# no lexer for this language. handle it like it was a code block if lexer is None: yield match.start(3), String, code return
yield from do_insertions([], lexer.get_tokens_unprocessed(code))
yield match.start(4), String, match.group(4)
tokens = { 'root': [ # title in metadata section (r'^(title)(:\s)(.+\n)', bygroups(Keyword, Text, Generic.Heading)), # headings (r'^(!)([^!].+\n)', bygroups(Generic.Heading, Text)), (r'^(!{2,6})(.+\n)', bygroups(Generic.Subheading, Text)), # bulleted or numbered lists or single-line block quotes # (can be mixed) (r'^(\s*)([*#>]+)(\s*)(.+\n)', bygroups(Text, Keyword, Text, using(this, state='inline'))), # multi-line block quotes (r'^(<<<.*\n)([\w\W]*?)(^<<<.*$)', bygroups(String, Text, String)), # table header (r'^(\|.*?\|h)$', bygroups(Generic.Strong)), # table footer or caption (r'^(\|.*?\|[cf])$', bygroups(Generic.Emph)), # table class (r'^(\|.*?\|k)$', bygroups(Name.Tag)), # definitions (r'^(;.*)$', bygroups(Generic.Strong)), # text block (r'^(```\n)([\w\W]*?)(^```$)', bygroups(String, Text, String)), # code block with language (r'^(```)(\w+)(\n)([\w\W]*?)(^```$)', _handle_codeblock), # CSS style block (r'^(<style>)(\n)([\w\W]*?)(^</style>$)', _handle_cssblock),
include('keywords'), include('inline'), ], 'keywords': [ (words(( '\\define', '\\end', 'caption', 'created', 'modified', 'tags', 'title', 'type'), prefix=r'^', suffix=r'\b'), Keyword), ], 'inline': [ # escape (r'\\.', Text), # created or modified date (r'\d{17}', Number.Integer), # italics (r'(\s)(//[^/]+//)((?=\W|\n))', bygroups(Text, Generic.Emph, Text)), # superscript (r'(\s)(\^\^[^\^]+\^\^)', bygroups(Text, Generic.Emph)), # subscript (r'(\s)(,,[^,]+,,)', bygroups(Text, Generic.Emph)), # underscore (r'(\s)(__[^_]+__)', bygroups(Text, Generic.Strong)), # bold (r"(\s)(''[^']+'')((?=\W|\n))", bygroups(Text, Generic.Strong, Text)), # strikethrough (r'(\s)(~~[^~]+~~)((?=\W|\n))', bygroups(Text, Generic.Deleted, Text)), # TiddlyWiki variables (r'<<[^>]+>>', Name.Tag), (r'\$\$[^$]+\$\$', Name.Tag), (r'\$\([^)]+\)\$', Name.Tag), # TiddlyWiki style or class (r'^@@.*$', Name.Tag), # HTML tags (r'</?[^>]+>', Name.Tag), # inline code (r'`[^`]+`', String.Backtick), # HTML escaped symbols (r'&\S*?;', String.Regex), # Wiki links (r'(\[{2})([^]\|]+)(\]{2})', bygroups(Text, Name.Tag, Text)), # External links (r'(\[{2})([^]\|]+)(\|)([^]\|]+)(\]{2})', bygroups(Text, Name.Tag, Text, Name.Attribute, Text)), # Transclusion (r'(\{{2})([^}]+)(\}{2})', bygroups(Text, Name.Tag, Text)), # URLs (r'(\b.?.?tps?://[^\s"]+)', bygroups(Name.Attribute)),
# general text, must come last! (r'[\w]+', Text), (r'.', Text) ], }
def __init__(self, **options): self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True) RegexLexer.__init__(self, **options)
class WikitextLexer(RegexLexer): """ For MediaWiki Wikitext.
Parsing Wikitext is tricky, and results vary between different MediaWiki installations, so we only highlight common syntaxes (built-in or from popular extensions), and also assume templates produce no unbalanced syntaxes. """ name = 'Wikitext' url = 'https://www.mediawiki.org/wiki/Wikitext' aliases = ['wikitext', 'mediawiki'] filenames = [] mimetypes = ['text/x-wiki'] version_added = '2.15' flags = re.MULTILINE
def nowiki_tag_rules(tag_name): return [ (rf'(?i)(</)({tag_name})(\s*)(>)', bygroups(Punctuation, Name.Tag, Whitespace, Punctuation), '#pop'), include('entity'), include('text'), ]
def plaintext_tag_rules(tag_name): return [ (rf'(?si)(.*?)(</)({tag_name})(\s*)(>)', bygroups(Text, Punctuation, Name.Tag, Whitespace, Punctuation), '#pop'), ]
def delegate_tag_rules(tag_name, lexer, **lexer_kwargs): return [ (rf'(?i)(</)({tag_name})(\s*)(>)', bygroups(Punctuation, Name.Tag, Whitespace, Punctuation), '#pop'), (rf'(?si).+?(?=</{tag_name}\s*>)', using(lexer, **lexer_kwargs)), ]
def text_rules(token): return [ (r'\w+', token), (r'[^\S\n]+', token), (r'(?s).', token), ]
def handle_syntaxhighlight(self, match, ctx): from pygments.lexers import get_lexer_by_name
attr_content = match.group() start = 0 index = 0 while True: index = attr_content.find('>', start) # Exclude comment end (-->) if attr_content[index-2:index] != '--': break start = index + 1
if index == -1: # No tag end yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr']) return attr = attr_content[:index] yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr']) yield match.start(3) + index, Punctuation, '>'
lexer = None content = attr_content[index+1:] lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr)
if len(lang_match) >= 1: # Pick the last match in case of multiple matches lang = lang_match[-1][1] try: lexer = get_lexer_by_name(lang) except ClassNotFound: pass
if lexer is None: yield match.start() + index + 1, Text, content else: yield from lexer.get_tokens_unprocessed(content)
def handle_score(self, match, ctx): attr_content = match.group() start = 0 index = 0 while True: index = attr_content.find('>', start) # Exclude comment end (-->) if attr_content[index-2:index] != '--': break start = index + 1
if index == -1: # No tag end yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr']) return attr = attr_content[:index] content = attr_content[index+1:] yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr']) yield match.start(3) + index, Punctuation, '>'
lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr) # Pick the last match in case of multiple matches lang = lang_match[-1][1] if len(lang_match) >= 1 else 'lilypond'
if lang == 'lilypond': # Case sensitive yield from LilyPondLexer().get_tokens_unprocessed(content) else: # ABC # FIXME: Use ABC lexer in the future yield match.start() + index + 1, Text, content
# a-z removed to prevent linter from complaining, REMEMBER to use (?i) title_char = r' %!"$&\'()*,\-./0-9:;=?@A-Z\\\^_`~+\u0080-\uFFFF' nbsp_char = r'(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000])' link_address = r'(?:[0-9.]+|\[[0-9a-f:.]+\]|[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD])' link_char_class = r'[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD]' double_slashes_i = { '__FORCETOC__', '__NOCONTENTCONVERT__', '__NOCC__', '__NOEDITSECTION__', '__NOGALLERY__', '__NOTITLECONVERT__', '__NOTC__', '__NOTOC__', '__TOC__', } double_slashes = { '__EXPECTUNUSEDCATEGORY__', '__HIDDENCAT__', '__INDEX__', '__NEWSECTIONLINK__', '__NOINDEX__', '__NONEWSECTIONLINK__', '__STATICREDIRECT__', '__NOGLOBAL__', '__DISAMBIG__', '__EXPECTED_UNCONNECTED_PAGE__', } protocols = { 'bitcoin:', 'ftp://', 'ftps://', 'geo:', 'git://', 'gopher://', 'http://', 'https://', 'irc://', 'ircs://', 'magnet:', 'mailto:', 'mms://', 'news:', 'nntp://', 'redis://', 'sftp://', 'sip:', 'sips:', 'sms:', 'ssh://', 'svn://', 'tel:', 'telnet://', 'urn:', 'worldwind://', 'xmpp:', '//', } non_relative_protocols = protocols - {'//'} html_tags = { 'abbr', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'data', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'link', 'mark', 'meta', 'ol', 'p', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'td', 'th', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr', } parser_tags = { 'graph', 'charinsert', 'rss', 'chem', 'categorytree', 'nowiki', 'inputbox', 'math', 'hiero', 'score', 'pre', 'ref', 'translate', 'imagemap', 'templatestyles', 'languages', 'noinclude', 'mapframe', 'section', 'poem', 'syntaxhighlight', 'includeonly', 'tvar', 'onlyinclude', 'templatedata', 'langconvert', 'timeline', 'dynamicpagelist', 'gallery', 'maplink', 'ce', 'references', } variant_langs = { # ZhConverter.php 'zh', 'zh-hans', 'zh-hant', 'zh-cn', 'zh-hk', 'zh-mo', 'zh-my', 'zh-sg', 'zh-tw', # WuuConverter.php 'wuu', 'wuu-hans', 'wuu-hant', # UzConverter.php 'uz', 'uz-latn', 'uz-cyrl', # TlyConverter.php 'tly', 'tly-cyrl', # TgConverter.php 'tg', 'tg-latn', # SrConverter.php 'sr', 'sr-ec', 'sr-el', # ShiConverter.php 'shi', 'shi-tfng', 'shi-latn', # ShConverter.php 'sh-latn', 'sh-cyrl', # KuConverter.php 'ku', 'ku-arab', 'ku-latn', # IuConverter.php 'iu', 'ike-cans', 'ike-latn', # GanConverter.php 'gan', 'gan-hans', 'gan-hant', # EnConverter.php 'en', 'en-x-piglatin', # CrhConverter.php 'crh', 'crh-cyrl', 'crh-latn', # BanConverter.php 'ban', 'ban-bali', 'ban-x-dharma', 'ban-x-palmleaf', 'ban-x-pku', } magic_vars_i = { 'ARTICLEPATH', 'INT', 'PAGEID', 'SCRIPTPATH', 'SERVER', 'SERVERNAME', 'STYLEPATH', } magic_vars = { '!', '=', 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'CONTENTLANGUAGE', 'CONTENTLANG', 'CURRENTDAY', 'CURRENTDAY2', 'CURRENTDAYNAME', 'CURRENTDOW', 'CURRENTHOUR', 'CURRENTMONTH', 'CURRENTMONTH2', 'CURRENTMONTH1', 'CURRENTMONTHABBREV', 'CURRENTMONTHNAME', 'CURRENTMONTHNAMEGEN', 'CURRENTTIME', 'CURRENTTIMESTAMP', 'CURRENTVERSION', 'CURRENTWEEK', 'CURRENTYEAR', 'DIRECTIONMARK', 'DIRMARK', 'FULLPAGENAME', 'FULLPAGENAMEE', 'LOCALDAY', 'LOCALDAY2', 'LOCALDAYNAME', 'LOCALDOW', 'LOCALHOUR', 'LOCALMONTH', 'LOCALMONTH2', 'LOCALMONTH1', 'LOCALMONTHABBREV', 'LOCALMONTHNAME', 'LOCALMONTHNAMEGEN', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCALWEEK', 'LOCALYEAR', 'NAMESPACE', 'NAMESPACEE', 'NAMESPACENUMBER', 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS', 'NUMBEROFARTICLES', 'NUMBEROFEDITS', 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS', 'PAGELANGUAGE', 'PAGENAME', 'PAGENAMEE', 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH', 'REVISIONMONTH1', 'REVISIONSIZE', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME', 'ROOTPAGENAMEE', 'SITENAME', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE', 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE', 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE', } parser_functions_i = { 'ANCHORENCODE', 'BIDI', 'CANONICALURL', 'CANONICALURLE', 'FILEPATH', 'FORMATNUM', 'FULLURL', 'FULLURLE', 'GENDER', 'GRAMMAR', 'INT', r'\#LANGUAGE', 'LC', 'LCFIRST', 'LOCALURL', 'LOCALURLE', 'NS', 'NSE', 'PADLEFT', 'PADRIGHT', 'PAGEID', 'PLURAL', 'UC', 'UCFIRST', 'URLENCODE', } parser_functions = { 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'DEFAULTSORT', 'DEFAULTSORTKEY', 'DEFAULTCATEGORYSORT', 'FULLPAGENAME', 'FULLPAGENAMEE', 'NAMESPACE', 'NAMESPACEE', 'NAMESPACENUMBER', 'NUMBERINGROUP', 'NUMINGROUP', 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS', 'NUMBEROFARTICLES', 'NUMBEROFEDITS', 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS', 'PAGENAME', 'PAGENAMEE', 'PAGESINCATEGORY', 'PAGESINCAT', 'PAGESIZE', 'PROTECTIONEXPIRY', 'PROTECTIONLEVEL', 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH', 'REVISIONMONTH1', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME', 'ROOTPAGENAMEE', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE', 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE', 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE', 'INT', 'DISPLAYTITLE', 'PAGESINNAMESPACE', 'PAGESINNS', }
tokens = { 'root': [ # Redirects (r"""(?xi) (\A\s*?)(\#REDIRECT:?) # may contain a colon (\s+)(\[\[) (?=[^\]\n]* \]\]$) """, bygroups(Whitespace, Keyword, Whitespace, Punctuation), 'redirect-inner'), # Subheadings (r'^(={2,6})(.+?)(\1)(\s*$\n)', bygroups(Generic.Subheading, Generic.Subheading, Generic.Subheading, Whitespace)), # Headings (r'^(=.+?=)(\s*$\n)', bygroups(Generic.Heading, Whitespace)), # Double-slashed magic words (words(double_slashes_i, prefix=r'(?i)'), Name.Function.Magic), (words(double_slashes), Name.Function.Magic), # Raw URLs (r'(?i)\b(?:{}){}{}*'.format('|'.join(protocols), link_address, link_char_class), Name.Label), # Magic links (rf'\b(?:RFC|PMID){nbsp_char}+[0-9]+\b', Name.Function.Magic), (r"""(?x) \bISBN {nbsp_char} (?: 97[89] {nbsp_dash}? )? (?: [0-9] {nbsp_dash}? ){{9}} # escape format() [0-9Xx]\b """.format(nbsp_char=nbsp_char, nbsp_dash=f'(?:-|{nbsp_char})'), Name.Function.Magic), include('list'), include('inline'), include('text'), ], 'redirect-inner': [ (r'(\]\])(\s*?\n)', bygroups(Punctuation, Whitespace), '#pop'), (r'(\#)([^#]*?)', bygroups(Punctuation, Name.Label)), (rf'(?i)[{title_char}]+', Name.Tag), ], 'list': [ # Description lists (r'^;', Keyword, 'dt'), # Ordered lists, unordered lists and indents (r'^[#:*]+', Keyword), # Horizontal rules (r'^-{4,}', Keyword), ], 'inline': [ # Signatures (r'~{3,5}', Keyword), # Entities include('entity'), # Bold & italic (r"('')(''')(?!')", bygroups(Generic.Emph, Generic.EmphStrong), 'inline-italic-bold'), (r"'''(?!')", Generic.Strong, 'inline-bold'), (r"''(?!')", Generic.Emph, 'inline-italic'), # Comments & parameters & templates include('replaceable'), # Media links ( r"""(?xi) (\[\[) (File|Image) (:) ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | <!--[\s\S]*?--> )*) (?: (\#) ([{}]*?) )? """.format(title_char, f'{title_char}#'), bygroups(Punctuation, Name.Namespace, Punctuation, using(this, state=['wikilink-name']), Punctuation, Name.Label), 'medialink-inner' ), # Wikilinks ( r"""(?xi) (\[\[)(?!{}) # Should not contain URLs (?: ([{}]*) (:))? ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | <!--[\s\S]*?--> )*?) (?: (\#) ([{}]*?) )? (\]\]) """.format('|'.join(protocols), title_char.replace('/', ''), title_char, f'{title_char}#'), bygroups(Punctuation, Name.Namespace, Punctuation, using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation) ), ( r"""(?xi) (\[\[)(?!{}) (?: ([{}]*) (:))? ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | <!--[\s\S]*?--> )*?) (?: (\#) ([{}]*?) )? (\|) """.format('|'.join(protocols), title_char.replace('/', ''), title_char, f'{title_char}#'), bygroups(Punctuation, Name.Namespace, Punctuation, using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation), 'wikilink-inner' ), # External links ( r"""(?xi) (\[) ((?:{}) {} {}*) (\s*) """.format('|'.join(protocols), link_address, link_char_class), bygroups(Punctuation, Name.Label, Whitespace), 'extlink-inner' ), # Tables (r'^(:*)(\s*?)(\{\|)([^\n]*)$', bygroups(Keyword, Whitespace, Punctuation, using(this, state=['root', 'attr'])), 'table'), # HTML tags (r'(?i)(<)({})\b'.format('|'.join(html_tags)), bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'), (r'(?i)(</)({})\b(\s*)(>)'.format('|'.join(html_tags)), bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)), # <nowiki> (r'(?i)(<)(nowiki)\b', bygroups(Punctuation, Name.Tag), ('tag-nowiki', 'tag-inner')), # <pre> (r'(?i)(<)(pre)\b', bygroups(Punctuation, Name.Tag), ('tag-pre', 'tag-inner')), # <categorytree> (r'(?i)(<)(categorytree)\b', bygroups( Punctuation, Name.Tag), ('tag-categorytree', 'tag-inner')), # <hiero> (r'(?i)(<)(hiero)\b', bygroups(Punctuation, Name.Tag), ('tag-hiero', 'tag-inner')), # <math> (r'(?i)(<)(math)\b', bygroups(Punctuation, Name.Tag), ('tag-math', 'tag-inner')), # <chem> (r'(?i)(<)(chem)\b', bygroups(Punctuation, Name.Tag), ('tag-chem', 'tag-inner')), # <ce> (r'(?i)(<)(ce)\b', bygroups(Punctuation, Name.Tag), ('tag-ce', 'tag-inner')), # <charinsert> (r'(?i)(<)(charinsert)\b', bygroups( Punctuation, Name.Tag), ('tag-charinsert', 'tag-inner')), # <templatedata> (r'(?i)(<)(templatedata)\b', bygroups( Punctuation, Name.Tag), ('tag-templatedata', 'tag-inner')), # <gallery> (r'(?i)(<)(gallery)\b', bygroups( Punctuation, Name.Tag), ('tag-gallery', 'tag-inner')), # <graph> (r'(?i)(<)(gallery)\b', bygroups( Punctuation, Name.Tag), ('tag-graph', 'tag-inner')), # <dynamicpagelist> (r'(?i)(<)(dynamicpagelist)\b', bygroups( Punctuation, Name.Tag), ('tag-dynamicpagelist', 'tag-inner')), # <inputbox> (r'(?i)(<)(inputbox)\b', bygroups( Punctuation, Name.Tag), ('tag-inputbox', 'tag-inner')), # <rss> (r'(?i)(<)(rss)\b', bygroups( Punctuation, Name.Tag), ('tag-rss', 'tag-inner')), # <imagemap> (r'(?i)(<)(imagemap)\b', bygroups( Punctuation, Name.Tag), ('tag-imagemap', 'tag-inner')), # <syntaxhighlight> (r'(?i)(</)(syntaxhighlight)\b(\s*)(>)', bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)), (r'(?si)(<)(syntaxhighlight)\b([^>]*?(?<!/)>.*?)(?=</\2\s*>)', bygroups(Punctuation, Name.Tag, handle_syntaxhighlight)), # <syntaxhighlight>: Fallback case for self-closing tags (r'(?i)(<)(syntaxhighlight)\b(\s*?)((?:[^>]|-->)*?)(/\s*?(?<!--)>)', bygroups( Punctuation, Name.Tag, Whitespace, using(this, state=['root', 'attr']), Punctuation)), # <source> (r'(?i)(</)(source)\b(\s*)(>)', bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)), (r'(?si)(<)(source)\b([^>]*?(?<!/)>.*?)(?=</\2\s*>)', bygroups(Punctuation, Name.Tag, handle_syntaxhighlight)), # <source>: Fallback case for self-closing tags (r'(?i)(<)(source)\b(\s*?)((?:[^>]|-->)*?)(/\s*?(?<!--)>)', bygroups( Punctuation, Name.Tag, Whitespace, using(this, state=['root', 'attr']), Punctuation)), # <score> (r'(?i)(</)(score)\b(\s*)(>)', bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)), (r'(?si)(<)(score)\b([^>]*?(?<!/)>.*?)(?=</\2\s*>)', bygroups(Punctuation, Name.Tag, handle_score)), # <score>: Fallback case for self-closing tags (r'(?i)(<)(score)\b(\s*?)((?:[^>]|-->)*?)(/\s*?(?<!--)>)', bygroups( Punctuation, Name.Tag, Whitespace, using(this, state=['root', 'attr']), Punctuation)), # Other parser tags (r'(?i)(<)({})\b'.format('|'.join(parser_tags)), bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'), (r'(?i)(</)({})\b(\s*)(>)'.format('|'.join(parser_tags)), bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)), # LanguageConverter markups ( r"""(?xi) (-\{{) # Use {{ to escape format() ([^|]) (\|) (?: (?: ([^;]*?) (=>))? (\s* (?:{variants}) \s*) (:) )? """.format(variants='|'.join(variant_langs)), bygroups(Punctuation, Keyword, Punctuation, using(this, state=['root', 'lc-raw']), Operator, Name.Label, Punctuation), 'lc-inner' ), # LanguageConverter markups: composite conversion grammar ( r"""(?xi) (-\{) ([a-z\s;-]*?) (\|) """, bygroups(Punctuation, using(this, state=['root', 'lc-flag']), Punctuation), 'lc-raw' ), # LanguageConverter markups: fallbacks ( r"""(?xi) (-\{{) (?!\{{) # Use {{ to escape format() (?: (\s* (?:{variants}) \s*) (:))? """.format(variants='|'.join(variant_langs)), bygroups(Punctuation, Name.Label, Punctuation), 'lc-inner' ), ], 'wikilink-name': [ include('replaceable'), (r'[^{<]+', Name.Tag), (r'(?s).', Name.Tag), ], 'wikilink-inner': [ # Quit in case of another wikilink (r'(?=\[\[)', Punctuation, '#pop'), (r'\]\]', Punctuation, '#pop'), include('inline'), include('text'), ], 'medialink-inner': [ (r'\]\]', Punctuation, '#pop'), (r'(\|)([^\n=|]*)(=)', bygroups(Punctuation, Name.Attribute, Operator)), (r'\|', Punctuation), include('inline'), include('text'), ], 'quote-common': [ # Quit in case of link/template endings (r'(?=\]\]|\{\{|\}\})', Punctuation, '#pop'), (r'\n', Text, '#pop'), ], 'inline-italic': [ include('quote-common'), (r"('')(''')(?!')", bygroups(Generic.Emph, Generic.Strong), ('#pop', 'inline-bold')), (r"'''(?!')", Generic.EmphStrong, ('#pop', 'inline-italic-bold')), (r"''(?!')", Generic.Emph, '#pop'), include('inline'), include('text-italic'), ], 'inline-bold': [ include('quote-common'), (r"(''')('')(?!')", bygroups( Generic.Strong, Generic.Emph), ('#pop', 'inline-italic')), (r"'''(?!')", Generic.Strong, '#pop'), (r"''(?!')", Generic.EmphStrong, ('#pop', 'inline-bold-italic')), include('inline'), include('text-bold'), ], 'inline-bold-italic': [ include('quote-common'), (r"('')(''')(?!')", bygroups(Generic.EmphStrong, Generic.Strong), '#pop'), (r"'''(?!')", Generic.EmphStrong, ('#pop', 'inline-italic')), (r"''(?!')", Generic.EmphStrong, ('#pop', 'inline-bold')), include('inline'), include('text-bold-italic'), ], 'inline-italic-bold': [ include('quote-common'), (r"(''')('')(?!')", bygroups( Generic.EmphStrong, Generic.Emph), '#pop'), (r"'''(?!')", Generic.EmphStrong, ('#pop', 'inline-italic')), (r"''(?!')", Generic.EmphStrong, ('#pop', 'inline-bold')), include('inline'), include('text-bold-italic'), ], 'lc-flag': [ (r'\s+', Whitespace), (r';', Punctuation), *text_rules(Keyword), ], 'lc-inner': [ ( r"""(?xi) (;) (?: ([^;]*?) (=>))? (\s* (?:{variants}) \s*) (:) """.format(variants='|'.join(variant_langs)), bygroups(Punctuation, using(this, state=['root', 'lc-raw']), Operator, Name.Label, Punctuation) ), (r';?\s*?\}-', Punctuation, '#pop'), include('inline'), include('text'), ], 'lc-raw': [ (r'\}-', Punctuation, '#pop'), include('inline'), include('text'), ], 'replaceable': [ # Comments (r'<!--[\s\S]*?(?:-->|\Z)', Comment.Multiline), # Parameters ( r"""(?x) (\{{3}) ([^|]*?) (?=\}{3}|\|) """, bygroups(Punctuation, Name.Variable), 'parameter-inner', ), # Magic variables (r'(?i)(\{{\{{)(\s*)({})(\s*)(\}}\}})'.format('|'.join(magic_vars_i)), bygroups(Punctuation, Whitespace, Name.Function, Whitespace, Punctuation)), (r'(\{{\{{)(\s*)({})(\s*)(\}}\}})'.format('|'.join(magic_vars)), bygroups(Punctuation, Whitespace, Name.Function, Whitespace, Punctuation)), # Parser functions & templates (r'\{\{', Punctuation, 'template-begin-space'), # <tvar> legacy syntax (r'(?i)(<)(tvar)\b(\|)([^>]*?)(>)', bygroups(Punctuation, Name.Tag, Punctuation, String, Punctuation)), (r'</>', Punctuation, '#pop'), # <tvar> (r'(?i)(<)(tvar)\b', bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'), (r'(?i)(</)(tvar)\b(\s*)(>)', bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)), ], 'parameter-inner': [ (r'\}{3}', Punctuation, '#pop'), (r'\|', Punctuation), include('inline'), include('text'), ], 'template-begin-space': [ # Templates allow line breaks at the beginning, and due to how MediaWiki handles # comments, an extra state is required to handle things like {{\n<!---->\n name}} (r'<!--[\s\S]*?(?:-->|\Z)', Comment.Multiline), (r'\s+', Whitespace), # Parser functions ( r'(?i)(\#[{}]*?|{})(:)'.format(title_char, '|'.join(parser_functions_i)), bygroups(Name.Function, Punctuation), ('#pop', 'template-inner') ), ( r'({})(:)'.format('|'.join(parser_functions)), bygroups(Name.Function, Punctuation), ('#pop', 'template-inner') ), # Templates ( rf'(?i)([{title_char}]*?)(:)', bygroups(Name.Namespace, Punctuation), ('#pop', 'template-name') ), default(('#pop', 'template-name'),), ], 'template-name': [ (r'(\s*?)(\|)', bygroups(Text, Punctuation), ('#pop', 'template-inner')), (r'\}\}', Punctuation, '#pop'), (r'\n', Text, '#pop'), include('replaceable'), *text_rules(Name.Tag), ], 'template-inner': [ (r'\}\}', Punctuation, '#pop'), (r'\|', Punctuation), ( r"""(?x) (?<=\|) ( (?: (?! \{\{ | \}\} )[^=\|<])*? ) # Exclude templates and tags (=) """, bygroups(Name.Label, Operator) ), include('inline'), include('text'), ], 'table': [ # Use [ \t\n\r\0\x0B] instead of \s to follow PHP trim() behavior # Endings (r'^([ \t\n\r\0\x0B]*?)(\|\})', bygroups(Whitespace, Punctuation), '#pop'), # Table rows (r'^([ \t\n\r\0\x0B]*?)(\|-+)(.*)$', bygroups(Whitespace, Punctuation, using(this, state=['root', 'attr']))), # Captions ( r"""(?x) ^([ \t\n\r\0\x0B]*?)(\|\+) # Exclude links, template and tags (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|) )? (.*?)$ """, bygroups(Whitespace, Punctuation, using(this, state=[ 'root', 'attr']), Punctuation, Generic.Heading), ), # Table data ( r"""(?x) ( ^(?:[ \t\n\r\0\x0B]*?)\| | \|\| ) (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|)(?!\|) )? """, bygroups(Punctuation, using(this, state=[ 'root', 'attr']), Punctuation), ), # Table headers ( r"""(?x) ( ^(?:[ \t\n\r\0\x0B]*?)! ) (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|)(?!\|) )? """, bygroups(Punctuation, using(this, state=[ 'root', 'attr']), Punctuation), 'table-header', ), include('list'), include('inline'), include('text'), ], 'table-header': [ # Requires another state for || handling inside headers (r'\n', Text, '#pop'), ( r"""(?x) (!!|\|\|) (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? ) (\|)(?!\|) )? """, bygroups(Punctuation, using(this, state=[ 'root', 'attr']), Punctuation) ), *text_rules(Generic.Subheading), ], 'entity': [ (r'&\S*?;', Name.Entity), ], 'dt': [ (r'\n', Text, '#pop'), include('inline'), (r':', Keyword, '#pop'), include('text'), ], 'extlink-inner': [ (r'\]', Punctuation, '#pop'), include('inline'), include('text'), ], 'nowiki-ish': [ include('entity'), include('text'), ], 'attr': [ include('replaceable'), (r'\s+', Whitespace), (r'(=)(\s*)(")', bygroups(Operator, Whitespace, String.Double), 'attr-val-2'), (r"(=)(\s*)(')", bygroups(Operator, Whitespace, String.Single), 'attr-val-1'), (r'(=)(\s*)', bygroups(Operator, Whitespace), 'attr-val-0'), (r'[\w:-]+', Name.Attribute),
], 'attr-val-0': [ (r'\s', Whitespace, '#pop'), include('replaceable'), *text_rules(String), ], 'attr-val-1': [ (r"'", String.Single, '#pop'), include('replaceable'), *text_rules(String.Single), ], 'attr-val-2': [ (r'"', String.Double, '#pop'), include('replaceable'), *text_rules(String.Double), ], 'tag-inner-ordinary': [ (r'/?\s*>', Punctuation, '#pop'), include('tag-attr'), ], 'tag-inner': [ # Return to root state for self-closing tags (r'/\s*>', Punctuation, '#pop:2'), (r'\s*>', Punctuation, '#pop'), include('tag-attr'), ], # There states below are just like their non-tag variants, the key difference is # they forcibly quit when encountering tag closing markup 'tag-attr': [ include('replaceable'), (r'\s+', Whitespace), (r'(=)(\s*)(")', bygroups(Operator, Whitespace, String.Double), 'tag-attr-val-2'), (r"(=)(\s*)(')", bygroups(Operator, Whitespace, String.Single), 'tag-attr-val-1'), (r'(=)(\s*)', bygroups(Operator, Whitespace), 'tag-attr-val-0'), (r'[\w:-]+', Name.Attribute),
], 'tag-attr-val-0': [ (r'\s', Whitespace, '#pop'), (r'/?>', Punctuation, '#pop:2'), include('replaceable'), *text_rules(String), ], 'tag-attr-val-1': [ (r"'", String.Single, '#pop'), (r'/?>', Punctuation, '#pop:2'), include('replaceable'), *text_rules(String.Single), ], 'tag-attr-val-2': [ (r'"', String.Double, '#pop'), (r'/?>', Punctuation, '#pop:2'), include('replaceable'), *text_rules(String.Double), ], 'tag-nowiki': nowiki_tag_rules('nowiki'), 'tag-pre': nowiki_tag_rules('pre'), 'tag-categorytree': plaintext_tag_rules('categorytree'), 'tag-dynamicpagelist': plaintext_tag_rules('dynamicpagelist'), 'tag-hiero': plaintext_tag_rules('hiero'), 'tag-inputbox': plaintext_tag_rules('inputbox'), 'tag-imagemap': plaintext_tag_rules('imagemap'), 'tag-charinsert': plaintext_tag_rules('charinsert'), 'tag-timeline': plaintext_tag_rules('timeline'), 'tag-gallery': plaintext_tag_rules('gallery'), 'tag-graph': plaintext_tag_rules('graph'), 'tag-rss': plaintext_tag_rules('rss'), 'tag-math': delegate_tag_rules('math', TexLexer, state='math'), 'tag-chem': delegate_tag_rules('chem', TexLexer, state='math'), 'tag-ce': delegate_tag_rules('ce', TexLexer, state='math'), 'tag-templatedata': delegate_tag_rules('templatedata', JsonLexer), 'text-italic': text_rules(Generic.Emph), 'text-bold': text_rules(Generic.Strong), 'text-bold-italic': text_rules(Generic.EmphStrong), 'text': text_rules(Text), }123456789101112131415161718192021""" pygments.lexers.math ~~~~~~~~~~~~~~~~~~~~
Just export lexers that were contained in this module.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
# ruff: noqa: F401from pygments.lexers.python import NumPyLexerfrom pygments.lexers.matlab import MatlabLexer, MatlabSessionLexer, \ OctaveLexer, ScilabLexerfrom pygments.lexers.julia import JuliaLexer, JuliaConsoleLexerfrom pygments.lexers.r import RConsoleLexer, SLexer, RdLexerfrom pygments.lexers.modeling import BugsLexer, JagsLexer, StanLexerfrom pygments.lexers.idl import IDLLexerfrom pygments.lexers.algebra import MuPADLexer
__all__ = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384""" pygments.lexers.maxima ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the computer algebra system Maxima.
Derived from pygments/lexers/algebra.py.
: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 Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['MaximaLexer']
class MaximaLexer(RegexLexer): """ A Maxima lexer. Derived from pygments.lexers.MuPADLexer. """ name = 'Maxima' url = 'http://maxima.sourceforge.net' aliases = ['maxima', 'macsyma'] filenames = ['*.mac', '*.max'] version_added = '2.11'
keywords = ('if', 'then', 'else', 'elseif', 'do', 'while', 'repeat', 'until', 'for', 'from', 'to', 'downto', 'step', 'thru')
constants = ('%pi', '%e', '%phi', '%gamma', '%i', 'und', 'ind', 'infinity', 'inf', 'minf', 'true', 'false', 'unknown', 'done')
operators = (r'.', r':', r'=', r'#', r'+', r'-', r'*', r'/', r'^', r'@', r'>', r'<', r'|', r'!', r"'")
operator_words = ('and', 'or', 'not')
tokens = { 'root': [ (r'/\*', Comment.Multiline, 'comment'), (r'"(?:[^"\\]|\\.)*"', String), (r'\(|\)|\[|\]|\{|\}', Punctuation), (r'[,;$]', Punctuation), (words (constants), Name.Constant), (words (keywords), Keyword), (words (operators), Operator), (words (operator_words), Operator.Word), (r'''(?x) ((?:[a-zA-Z_#][\w#]*|`[^`]*`) (?:::[a-zA-Z_#][\w#]*|`[^`]*`)*)(\s*)([(])''', bygroups(Name.Function, Text.Whitespace, Punctuation)), (r'''(?x) (?:[a-zA-Z_#%][\w#%]*|`[^`]*`) (?:::[a-zA-Z_#%][\w#%]*|`[^`]*`)*''', Name.Variable), (r'[-+]?(\d*\.\d+([bdefls][-+]?\d+)?|\d+(\.\d*)?[bdefls][-+]?\d+)', Number.Float), (r'[-+]?\d+', Number.Integer), (r'\s+', Text.Whitespace), (r'.', Text) ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ] }
def analyse_text (text): strength = 0.0 # Input expression terminator. if re.search (r'\$\s*$', text, re.MULTILINE): strength += 0.05 # Function definition operator. if ':=' in text: strength += 0.02 return strength123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139""" pygments.lexers.meson ~~~~~~~~~~~~~~~~~~~~~
Pygments lexer for the Meson build system
: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, Name, Number, Punctuation, Operator, \ Keyword, String, Whitespace
__all__ = ['MesonLexer']
class MesonLexer(RegexLexer): """Meson language lexer.
The grammar definition use to transcribe the syntax was retrieved from https://mesonbuild.com/Syntax.html#grammar for version 0.58. Some of those definitions are improperly transcribed, so the Meson++ implementation was also checked: https://github.com/dcbaker/meson-plus-plus. """
# TODO String interpolation @VARNAME@ inner matches # TODO keyword_arg: value inner matches
name = 'Meson' url = 'https://mesonbuild.com/' aliases = ['meson', 'meson.build'] filenames = ['meson.build', 'meson.options', 'meson_options.txt'] mimetypes = ['text/x-meson'] version_added = '2.10'
tokens = { 'root': [ (r'#.*?$', Comment), (r"'''.*'''", String.Single), (r'[1-9][0-9]*', Number.Integer), (r'0o[0-7]+', Number.Oct), (r'0x[a-fA-F0-9]+', Number.Hex), include('string'), include('keywords'), include('expr'), (r'[a-zA-Z_][a-zA-Z_0-9]*', Name), (r'\s+', Whitespace), ], 'string': [ (r"[']{3}([']{0,2}([^\\']|\\(.|\n)))*[']{3}", String), (r"'.*?(?<!\\)(\\\\)*?'", String), ], 'keywords': [ (words(( 'if', 'elif', 'else', 'endif', 'foreach', 'endforeach', 'break', 'continue', ), suffix=r'\b'), Keyword), ], 'expr': [ (r'(in|and|or|not)\b', Operator.Word), (r'([\*/%\+-]=?|==|!=|=)', Operator), (r'[\[\]{}:().,?]', Punctuation), (words(('true', 'false'), suffix=r'\b'), Keyword.Constant), include('builtins'), (words(( 'meson', 'build_machine', 'host_machine', 'target_machine', ), suffix=r'\b'), Name.Variable.Magic), ], 'builtins': [ # This list was extracted from the v0.58 reference manual (words(( 'add_global_arguments', 'add_global_link_arguments', 'add_languages', 'add_project_arguments', 'add_project_link_arguments', 'add_test_setup', 'assert', 'benchmark', 'both_libraries', 'build_target', 'configuration_data', 'configure_file', 'custom_target', 'declare_dependency', 'dependency', 'disabler', 'environment', 'error', 'executable', 'files', 'find_library', 'find_program', 'generator', 'get_option', 'get_variable', 'include_directories', 'install_data', 'install_headers', 'install_man', 'install_subdir', 'is_disabler', 'is_variable', 'jar', 'join_paths', 'library', 'message', 'project', 'range', 'run_command', 'set_variable', 'shared_library', 'shared_module', 'static_library', 'subdir', 'subdir_done', 'subproject', 'summary', 'test', 'vcs_tag', 'warning', ), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), (r'(?<!\.)import\b', Name.Namespace), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210""" pygments.lexers.mime ~~~~~~~~~~~~~~~~~~~~
Lexer for Multipurpose Internet Mail Extensions (MIME) data.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, includefrom pygments.lexers import get_lexer_for_mimetypefrom pygments.token import Text, Name, String, Operator, Comment, Otherfrom pygments.util import get_int_opt, ClassNotFound
__all__ = ["MIMELexer"]
class MIMELexer(RegexLexer): """ Lexer for Multipurpose Internet Mail Extensions (MIME) data. This lexer is designed to process nested multipart data.
It assumes that the given data contains both header and body (and is split at an empty line). If no valid header is found, then the entire data will be treated as body.
Additional options accepted:
`MIME-max-level` Max recursion level for nested MIME structure. Any negative number would treated as unlimited. (default: -1)
`Content-Type` Treat the data as a specific content type. Useful when header is missing, or this lexer would try to parse from header. (default: `text/plain`)
`Multipart-Boundary` Set the default multipart boundary delimiter. This option is only used when `Content-Type` is `multipart` and header is missing. This lexer would try to parse from header by default. (default: None)
`Content-Transfer-Encoding` Treat the data as a specific encoding. Or this lexer would try to parse from header by default. (default: None) """
name = "MIME" aliases = ["mime"] mimetypes = ["multipart/mixed", "multipart/related", "multipart/alternative"] url = 'https://en.wikipedia.org/wiki/MIME' version_added = '2.5'
def __init__(self, **options): super().__init__(**options) self.boundary = options.get("Multipart-Boundary") self.content_transfer_encoding = options.get("Content_Transfer_Encoding") self.content_type = options.get("Content_Type", "text/plain") self.max_nested_level = get_int_opt(options, "MIME-max-level", -1)
def get_header_tokens(self, match): field = match.group(1)
if field.lower() in self.attention_headers: yield match.start(1), Name.Tag, field + ":" yield match.start(2), Text.Whitespace, match.group(2)
pos = match.end(2) body = match.group(3) for i, t, v in self.get_tokens_unprocessed(body, ("root", field.lower())): yield pos + i, t, v
else: yield match.start(), Comment, match.group()
def get_body_tokens(self, match): pos_body_start = match.start() entire_body = match.group()
# skip first newline if entire_body[0] == '\n': yield pos_body_start, Text.Whitespace, '\n' pos_body_start = pos_body_start + 1 entire_body = entire_body[1:]
# if it is not a multipart if not self.content_type.startswith("multipart") or not self.boundary: for i, t, v in self.get_bodypart_tokens(entire_body): yield pos_body_start + i, t, v return
# find boundary bdry_pattern = rf"^--{re.escape(self.boundary)}(--)?\n" bdry_matcher = re.compile(bdry_pattern, re.MULTILINE)
# some data has prefix text before first boundary m = bdry_matcher.search(entire_body) if m: pos_part_start = pos_body_start + m.end() pos_iter_start = lpos_end = m.end() yield pos_body_start, Text, entire_body[:m.start()] yield pos_body_start + lpos_end, String.Delimiter, m.group() else: pos_part_start = pos_body_start pos_iter_start = 0
# process tokens of each body part for m in bdry_matcher.finditer(entire_body, pos_iter_start): # bodypart lpos_start = pos_part_start - pos_body_start lpos_end = m.start() part = entire_body[lpos_start:lpos_end] for i, t, v in self.get_bodypart_tokens(part): yield pos_part_start + i, t, v
# boundary yield pos_body_start + lpos_end, String.Delimiter, m.group() pos_part_start = pos_body_start + m.end()
# some data has suffix text after last boundary lpos_start = pos_part_start - pos_body_start if lpos_start != len(entire_body): yield pos_part_start, Text, entire_body[lpos_start:]
def get_bodypart_tokens(self, text): # return if: # * no content # * no content type specific # * content encoding is not readable # * max recurrsion exceed if not text.strip() or not self.content_type: return [(0, Other, text)]
cte = self.content_transfer_encoding if cte and cte not in {"8bit", "7bit", "quoted-printable"}: return [(0, Other, text)]
if self.max_nested_level == 0: return [(0, Other, text)]
# get lexer try: lexer = get_lexer_for_mimetype(self.content_type) except ClassNotFound: return [(0, Other, text)]
if isinstance(lexer, type(self)): lexer.max_nested_level = self.max_nested_level - 1
return lexer.get_tokens_unprocessed(text)
def store_content_type(self, match): self.content_type = match.group(1)
prefix_len = match.start(1) - match.start(0) yield match.start(0), Text.Whitespace, match.group(0)[:prefix_len] yield match.start(1), Name.Label, match.group(2) yield match.end(2), String.Delimiter, '/' yield match.start(3), Name.Label, match.group(3)
def get_content_type_subtokens(self, match): yield match.start(1), Text, match.group(1) yield match.start(2), Text.Whitespace, match.group(2) yield match.start(3), Name.Attribute, match.group(3) yield match.start(4), Operator, match.group(4) yield match.start(5), String, match.group(5)
if match.group(3).lower() == "boundary": boundary = match.group(5).strip() if boundary[0] == '"' and boundary[-1] == '"': boundary = boundary[1:-1] self.boundary = boundary
def store_content_transfer_encoding(self, match): self.content_transfer_encoding = match.group(0).lower() yield match.start(0), Name.Constant, match.group(0)
attention_headers = {"content-type", "content-transfer-encoding"}
tokens = { "root": [ (r"^([\w-]+):( *)([\s\S]*?\n)(?![ \t])", get_header_tokens), (r"^$[\s\S]+", get_body_tokens), ], "header": [ # folding (r"\n[ \t]", Text.Whitespace), (r"\n(?![ \t])", Text.Whitespace, "#pop"), ], "content-type": [ include("header"), ( r"^\s*((multipart|application|audio|font|image|model|text|video" r"|message)/([\w-]+))", store_content_type, ), (r'(;)((?:[ \t]|\n[ \t])*)([\w:-]+)(=)([\s\S]*?)(?=;|\n(?![ \t]))', get_content_type_subtokens), (r';[ \t]*\n(?![ \t])', Text, '#pop'), ], "content-transfer-encoding": [ include("header"), (r"([\w-]+)", store_content_transfer_encoding), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392""" pygments.lexers.minecraft ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Minecraft related languages.
SNBT. A data communication format used in Minecraft. wiki: https://minecraft.wiki/w/NBT_format
MCFunction. The Function file for Minecraft Data packs and Add-ons. official: https://learn.microsoft.com/en-us/minecraft/creator/documents/functionsintroduction wiki: https://minecraft.wiki/w/Function
MCSchema. A kind of data Schema for Minecraft Add-on Development. official: https://learn.microsoft.com/en-us/minecraft/creator/reference/content/schemasreference/ community example: https://www.mcbe-dev.net/addons/data-driven/manifest.html
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, default, include, bygroupsfrom pygments.token import Comment, Keyword, Literal, Name, Number, Operator, \ Punctuation, String, Text, Whitespace
__all__ = ['SNBTLexer', 'MCFunctionLexer', 'MCSchemaLexer']
class SNBTLexer(RegexLexer): """Lexer for stringified NBT, a data format used in Minecraft """
name = "SNBT" url = "https://minecraft.wiki/w/NBT_format" aliases = ["snbt"] filenames = ["*.snbt"] mimetypes = ["text/snbt"] version_added = '2.12'
tokens = { "root": [ # We only look for the open bracket here since square bracket # is only valid in NBT pathing (which is a mcfunction idea). (r"\{", Punctuation, "compound"), (r"[^\{]+", Text), ],
"whitespace": [ (r"\s+", Whitespace), ],
"operators": [ (r"[,:;]", Punctuation), ],
"literals": [ (r"(true|false)", Keyword.Constant), (r"-?\d+[eE]-?\d+", Number.Float), (r"-?\d*\.\d+[fFdD]?", Number.Float), (r"-?\d+[bBsSlLfFdD]?", Number.Integer),
# Separate states for both types of strings so they don't entangle (r'"', String.Double, "literals.string_double"), (r"'", String.Single, "literals.string_single"), ], "literals.string_double": [ (r"\\.", String.Escape), (r'[^\\"\n]+', String.Double), (r'"', String.Double, "#pop"), ], "literals.string_single": [ (r"\\.", String.Escape), (r"[^\\'\n]+", String.Single), (r"'", String.Single, "#pop"), ],
"compound": [ # this handles the unquoted snbt keys # note: stringified keys still work (r"[A-Z_a-z]+", Name.Attribute), include("operators"), include("whitespace"), include("literals"), (r"\{", Punctuation, "#push"), (r"\[", Punctuation, "list"), (r"\}", Punctuation, "#pop"), ],
"list": [ (r"[A-Z_a-z]+", Name.Attribute), include("literals"), include("operators"), include("whitespace"), (r"\[", Punctuation, "#push"), (r"\{", Punctuation, "compound"), (r"\]", Punctuation, "#pop"), ], }
class MCFunctionLexer(RegexLexer): """Lexer for the mcfunction scripting language used in Minecraft.
Modelled somewhat after the `GitHub mcfunction grammar <https://github.com/Arcensoth/language-mcfunction>`_. """
name = "MCFunction" url = "https://minecraft.wiki/w/Commands" aliases = ["mcfunction", "mcf"] filenames = ["*.mcfunction"] mimetypes = ["text/mcfunction"] version_added = '2.12'
# Used to denotate the start of a block comment, borrowed from Github's mcfunction _block_comment_prefix = "[>!]"
tokens = { "root": [ include("names"), include("comments"), include("literals"), include("whitespace"), include("property"), include("operators"), include("selectors"), ],
"names": [ # The start of a command (either beginning of line OR after the run keyword) # We don't encode a list of keywords since mods, plugins, or even pre-processors # may add new commands, so we have a 'close-enough' regex which catches them. (r"^(\s*)([a-z_]+)", bygroups(Whitespace, Name.Builtin)), (r"(?<=run)\s+[a-z_]+", Name.Builtin),
# UUID (r"\b[0-9a-fA-F]+(?:-[0-9a-fA-F]+){4}\b", Name.Variable), include("resource-name"), # normal command names and scoreboards # there's no way to know the differences unfortuntely (r"[A-Za-z_][\w.#%$]+", Keyword.Constant), (r"[#%$][\w.#%$]+", Name.Variable.Magic), ],
"resource-name": [ # resource names have to be lowercase (r"#?[a-z_][a-z_.-]*:[a-z0-9_./-]+", Name.Function), # similar to above except optional `:`` # a `/` must be present "somewhere" (r"#?[a-z0-9_\.\-]+\/[a-z0-9_\.\-\/]+", Name.Function), ],
"whitespace": [ (r"\s+", Whitespace), ],
"comments": [ (rf"^\s*(#{_block_comment_prefix})", Comment.Multiline, ("comments.block", "comments.block.emphasized")), (r"#.*$", Comment.Single), ], "comments.block": [ (rf"^\s*#{_block_comment_prefix}", Comment.Multiline, "comments.block.emphasized"), (r"^\s*#", Comment.Multiline, "comments.block.normal"), default("#pop"), ], "comments.block.normal": [ include("comments.block.special"), (r"\S+", Comment.Multiline), (r"\n", Text, "#pop"), include("whitespace"), ], "comments.block.emphasized": [ include("comments.block.special"), (r"\S+", String.Doc), (r"\n", Text, "#pop"), include("whitespace"), ], "comments.block.special": [ # Params (r"@\S+", Name.Decorator),
include("resource-name"),
# Scoreboard player names (r"[#%$][\w.#%$]+", Name.Variable.Magic), ],
"operators": [ (r"[\-~%^?!+*<>\\/|&=.]", Operator), ],
"literals": [ (r"\.\.", Literal), (r"(true|false)", Keyword.Pseudo),
# these are like unquoted strings and appear in many places (r"[A-Za-z_]+", Name.Variable.Class),
(r"[0-7]b", Number.Byte), (r"[+-]?\d*\.?\d+([eE]?[+-]?\d+)?[df]?\b", Number.Float), (r"[+-]?\d+\b", Number.Integer), (r'"', String.Double, "literals.string-double"), (r"'", String.Single, "literals.string-single"), ], "literals.string-double": [ (r"\\.", String.Escape), (r'[^\\"\n]+', String.Double), (r'"', String.Double, "#pop"), ], "literals.string-single": [ (r"\\.", String.Escape), (r"[^\\'\n]+", String.Single), (r"'", String.Single, "#pop"), ],
"selectors": [ (r"@[a-z]", Name.Variable), ],
## Generic Property Container # There are several, differing instances where the language accepts # specific contained keys or contained key, value pairings. # # Property Maps: # - Starts with either `[` or `{` # - Key separated by `:` or `=` # - Deliminated by `,` # # Property Lists: # - Starts with `[` # - Deliminated by `,` # # For simplicity, these patterns match a generic, nestable structure # which follow a key, value pattern. For normal lists, there's only keys. # This allow some "illegal" structures, but we'll accept those for # sake of simplicity # # Examples: # - `[facing=up, powered=true]` (blockstate) # - `[name="hello world", nbt={key: 1b}]` (selector + nbt) # - `[{"text": "value"}, "literal"]` (json) ## "property": [ # This state gets included in root and also several substates # We do this to shortcut the starting of new properties # within other properties. Lists can have sublists and compounds # and values can start a new property (see the `difficult_1.txt` # snippet). (r"\{", Punctuation, ("property.curly", "property.key")), (r"\[", Punctuation, ("property.square", "property.key")), ], "property.curly": [ include("whitespace"), include("property"), (r"\}", Punctuation, "#pop"), ], "property.square": [ include("whitespace"), include("property"), (r"\]", Punctuation, "#pop"),
# lists can have sequences of items (r",", Punctuation), ], "property.key": [ include("whitespace"),
# resource names (for advancements) # can omit `:` to default `minecraft:` # must check if there is a future equals sign if `:` is in the name (r"#?[a-z_][a-z_\.\-]*\:[a-z0-9_\.\-/]+(?=\s*\=)", Name.Attribute, "property.delimiter"), (r"#?[a-z_][a-z0-9_\.\-/]+", Name.Attribute, "property.delimiter"),
# unquoted NBT key (r"[A-Za-z_\-\+]+", Name.Attribute, "property.delimiter"),
# quoted JSON or NBT key (r'"', Name.Attribute, "property.delimiter", "literals.string-double"), (r"'", Name.Attribute, "property.delimiter", "literals.string-single"),
# index for a list (r"-?\d+", Number.Integer, "property.delimiter"),
default("#pop"), ], "property.key.string-double": [ (r"\\.", String.Escape), (r'[^\\"\n]+', Name.Attribute), (r'"', Name.Attribute, "#pop"), ], "property.key.string-single": [ (r"\\.", String.Escape), (r"[^\\'\n]+", Name.Attribute), (r"'", Name.Attribute, "#pop"), ], "property.delimiter": [ include("whitespace"),
(r"[:=]!?", Punctuation, "property.value"), (r",", Punctuation),
default("#pop"), ], "property.value": [ include("whitespace"),
# unquoted resource names are valid literals here (r"#?[a-z_][a-z_\.\-]*\:[a-z0-9_\.\-/]+", Name.Tag), (r"#?[a-z_][a-z0-9_\.\-/]+", Name.Tag),
include("literals"), include("property"),
default("#pop"), ], }
class MCSchemaLexer(RegexLexer): """Lexer for Minecraft Add-ons data Schemas, an interface structure standard used in Minecraft """
name = 'MCSchema' url = 'https://learn.microsoft.com/en-us/minecraft/creator/reference/content/schemasreference/' aliases = ['mcschema'] filenames = ['*.mcschema'] mimetypes = ['text/mcschema'] version_added = '2.14'
tokens = { 'commentsandwhitespace': [ (r'\s+', Whitespace), (r'//.*?$', Comment.Single), (r'/\*.*?\*/', Comment.Multiline) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gimuysd]+\b|\B)', String.Regex, '#pop'), (r'(?=/)', Text, ('#pop', 'badregex')), default('#pop') ], 'badregex': [ (r'\n', Whitespace, '#pop') ], 'singlestring': [ (r'\\.', String.Escape), (r"'", String.Single, '#pop'), (r"[^\\']+", String.Single), ], 'doublestring': [ (r'\\.', String.Escape), (r'"', String.Double, '#pop'), (r'[^\\"]+', String.Double), ], 'root': [ (r'^(?=\s|/|<!--)', Text, 'slashstartsregex'), include('commentsandwhitespace'),
# keywords for optional word and field types (r'(?<=: )opt', Operator.Word), (r'(?<=\s)[\w-]*(?=(\s+"|\n))', Keyword.Declaration),
# numeric literals (r'0[bB][01]+', Number.Bin), (r'0[oO]?[0-7]+', Number.Oct), (r'0[xX][0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (r'(\.\d+|\d+\.\d*|\d+)([eE][-+]?\d+)?', Number.Float),
# possible punctuations (r'\.\.\.|=>', Punctuation), (r'\+\+|--|~|\?\?=?|\?|:|\\(?=\n)|' r'(<<|>>>?|==?|!=?|(?:\*\*|\|\||&&|[-<>+*%&|^/]))=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation),
# strings (r"'", String.Single, 'singlestring'), (r'"', String.Double, 'doublestring'),
# title line (r'[\w-]*?(?=:\{?\n)', String.Symbol), # title line with a version code, formatted # `major.minor.patch-prerelease+buildmeta` (r'([\w-]*?)(:)(\d+)(?:(\.)(\d+)(?:(\.)(\d+)(?:(\-)((?:[^\W_]|-)*(?:\.(?:[^\W_]|-)*)*))?(?:(\+)((?:[^\W_]|-)+(?:\.(?:[^\W_]|-)+)*))?)?)?(?=:\{?\n)', bygroups(String.Symbol, Operator, Number.Integer, Operator, Number.Integer, Operator, Number.Integer, Operator, String, Operator, String)),
(r'.*\n', Text), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130""" pygments.lexers.mips ~~~~~~~~~~~~~~~~~~~~
Lexers for MIPS assembly.
: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 Whitespace, Comment, String, Keyword, Name, Text
__all__ = ["MIPSLexer"]
class MIPSLexer(RegexLexer): """ A MIPS Assembly Lexer.
Based on the Emacs major mode by hlissner: https://github.com/hlissner/emacs-mips-mode """
name = 'MIPS' aliases = ['mips'] version_added = '' # TODO: add '*.s' and '*.asm', which will require designing an analyse_text # method for this lexer and refactoring those from Gas and Nasm in order to # have relatively reliable detection filenames = ['*.mips', '*.MIPS'] url = 'https://mips.com'
keywords = [ # Arithmetic insturctions "add", "sub", "subu", "addi", "subi", "addu", "addiu", # Multiplication/division "mul", "mult", "multu", "mulu", "madd", "maddu", "msub", "msubu", "div", "divu", # Bitwise operations "and", "or", "nor", "xor", "andi", "ori", "xori", "clo", "clz", # Shifts "sll", "srl", "sllv", "srlv", "sra", "srav", # Comparisons "slt", "sltu", "slti", "sltiu", # Move data "mfhi", "mthi", "mflo", "mtlo", "movn", "movz", "movf", "movt", # Jump "j", "jal", "jalr", "jr", # branch "bc1f", "bc1t", "beq", "bgez", "bgezal", "bgtz", "blez", "bltzal", "bltz", "bne", # Load "lui", "lb", "lbu", "lh", "lhu", "lw", "lwcl", "lwl", "lwr", # Store "sb", "sh", "sw", "swl", "swr", # coproc: swc1 sdc1 # Concurrent load/store "ll", "sc", # Trap handling "teq", "teqi", "tne", "tneqi", "tge", "tgeu", "tgei", "tgeiu", "tlt", "tltu", "tlti", "tltiu", # Exception / Interrupt "eret", "break", "bop", "syscall", # --- Floats ----------------------------------------------------- # Arithmetic "add.s", "add.d", "sub.s", "sub.d", "mul.s", "mul.d", "div.s", "div.d", "neg.d", "neg.s", # Comparison "c.e.d", "c.e.s", "c.le.d", "c.le.s", "c.lt.s", "c.lt.d", # "c.gt.s", "c.gt.d", "madd.s", "madd.d", "msub.s", "msub.d", # Move Floats "mov.d", "move.s", "movf.d", "movf.s", "movt.d", "movt.s", "movn.d", "movn.s", "movnzd", "movz.s", "movz.d", # Conversion "cvt.d.s", "cvt.d.w", "cvt.s.d", "cvt.s.w", "cvt.w.d", "cvt.w.s", "trunc.w.d", "trunc.w.s", # Math "abs.s", "abs.d", "sqrt.s", "sqrt.d", "ceil.w.d", "ceil.w.s", "floor.w.d", "floor.w.s", "round.w.d", "round.w.s", ]
pseudoinstructions = [ # Arithmetic & logical "rem", "remu", "mulo", "mulou", "abs", "neg", "negu", "not", "rol", "ror", # branches "b", "beqz", "bge", "bgeu", "bgt", "bgtu", "ble", "bleu", "blt", "bltu", "bnez", # loads "la", "li", "ld", "ulh", "ulhu", "ulw", # Store "sd", "ush", "usw", # move "move", # coproc: "mfc1.d", # comparisons "sgt", "sgtu", "sge", "sgeu", "sle", "sleu", "sne", "seq", # --- Floats ----------------------------------------------------- # load-store "l.d", "l.s", "s.d", "s.s", ]
directives = [ ".align", ".ascii", ".asciiz", ".byte", ".data", ".double", ".extern", ".float", ".globl", ".half", ".kdata", ".ktext", ".space", ".text", ".word", ]
deprecated = [ "beql", "bnel", "bgtzl", "bgezl", "bltzl", "blezl", "bltzall", "bgezall", ]
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*', Comment), (r'"', String, 'string'), (r'-?[0-9]+?', Keyword.Constant), (r'\w*:', Name.Function), (words(deprecated, suffix=r'\b'), Keyword.Pseudo), # need warning face (words(pseudoinstructions, suffix=r'\b'), Name.Variable), (words(keywords, suffix=r'\b'), Keyword), (r'[slm][ftwd]c[0-9]([.]d)?', Keyword), (r'\$(f?[0-2][0-9]|f?3[01]|[ft]?[0-9]|[vk][01]|a[0-3]|s[0-7]|[gsf]p|ra|at|zero)', Keyword.Type), (words(directives, suffix=r'\b'), Name.Entity), # Preprocessor? (r':|,|;|\{|\}|=>|@|\$|=', Name.Builtin), (r'\w+', Text), (r'.', Text), ], 'string': [ (r'\\.', String.Escape), (r'"', String, '#pop'), (r'[^\\"]+', String), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958""" pygments.lexers.ml ~~~~~~~~~~~~~~~~~~
Lexers for ML family languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error
__all__ = ['SMLLexer', 'OcamlLexer', 'OpaLexer', 'ReasonLexer', 'FStarLexer']
class SMLLexer(RegexLexer): """ For the Standard ML language. """
name = 'Standard ML' aliases = ['sml'] filenames = ['*.sml', '*.sig', '*.fun'] mimetypes = ['text/x-standardml', 'application/x-standardml'] url = 'https://en.wikipedia.org/wiki/Standard_ML' version_added = '1.5'
alphanumid_reserved = { # Core 'abstype', 'and', 'andalso', 'as', 'case', 'datatype', 'do', 'else', 'end', 'exception', 'fn', 'fun', 'handle', 'if', 'in', 'infix', 'infixr', 'let', 'local', 'nonfix', 'of', 'op', 'open', 'orelse', 'raise', 'rec', 'then', 'type', 'val', 'with', 'withtype', 'while', # Modules 'eqtype', 'functor', 'include', 'sharing', 'sig', 'signature', 'struct', 'structure', 'where', }
symbolicid_reserved = { # Core ':', r'\|', '=', '=>', '->', '#', # Modules ':>', }
nonid_reserved = {'(', ')', '[', ']', '{', '}', ',', ';', '...', '_'}
alphanumid_re = r"[a-zA-Z][\w']*" symbolicid_re = r"[!%&$#+\-/:<=>?@\\~`^|*]+"
# A character constant is a sequence of the form #s, where s is a string # constant denoting a string of size one character. This setup just parses # the entire string as either a String.Double or a String.Char (depending # on the argument), even if the String.Char is an erroneous # multiple-character string. def stringy(whatkind): return [ (r'[^"\\]', whatkind), (r'\\[\\"abtnvfr]', String.Escape), # Control-character notation is used for codes < 32, # where \^@ == \000 (r'\\\^[\x40-\x5e]', String.Escape), # Docs say 'decimal digits' (r'\\[0-9]{3}', String.Escape), (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\\s+\\', String.Interpol), (r'"', whatkind, '#pop'), ]
# Callbacks for distinguishing tokens and reserved words def long_id_callback(self, match): if match.group(1) in self.alphanumid_reserved: token = Error else: token = Name.Namespace yield match.start(1), token, match.group(1) yield match.start(2), Punctuation, match.group(2)
def end_id_callback(self, match): if match.group(1) in self.alphanumid_reserved: token = Error elif match.group(1) in self.symbolicid_reserved: token = Error else: token = Name yield match.start(1), token, match.group(1)
def id_callback(self, match): str = match.group(1) if str in self.alphanumid_reserved: token = Keyword.Reserved elif str in self.symbolicid_reserved: token = Punctuation else: token = Name yield match.start(1), token, str
tokens = { # Whitespace and comments are (almost) everywhere 'whitespace': [ (r'\s+', Text), (r'\(\*', Comment.Multiline, 'comment'), ],
'delimiters': [ # This lexer treats these delimiters specially: # Delimiters define scopes, and the scope is how the meaning of # the `|' is resolved - is it a case/handle expression, or function # definition by cases? (This is not how the Definition works, but # it's how MLton behaves, see http://mlton.org/SMLNJDeviations) (r'\(|\[|\{', Punctuation, 'main'), (r'\)|\]|\}', Punctuation, '#pop'), (r'\b(let|if|local)\b(?!\')', Keyword.Reserved, ('main', 'main')), (r'\b(struct|sig|while)\b(?!\')', Keyword.Reserved, 'main'), (r'\b(do|else|end|in|then)\b(?!\')', Keyword.Reserved, '#pop'), ],
'core': [ # Punctuation that doesn't overlap symbolic identifiers (r'({})'.format('|'.join(re.escape(z) for z in nonid_reserved)), Punctuation),
# Special constants: strings, floats, numbers in decimal and hex (r'#"', String.Char, 'char'), (r'"', String.Double, 'string'), (r'~?0x[0-9a-fA-F]+', Number.Hex), (r'0wx[0-9a-fA-F]+', Number.Hex), (r'0w\d+', Number.Integer), (r'~?\d+\.\d+[eE]~?\d+', Number.Float), (r'~?\d+\.\d+', Number.Float), (r'~?\d+[eE]~?\d+', Number.Float), (r'~?\d+', Number.Integer),
# Labels (r'#\s*[1-9][0-9]*', Name.Label), (rf'#\s*({alphanumid_re})', Name.Label), (rf'#\s+({symbolicid_re})', Name.Label), # Some reserved words trigger a special, local lexer state change (r'\b(datatype|abstype)\b(?!\')', Keyword.Reserved, 'dname'), (r'\b(exception)\b(?!\')', Keyword.Reserved, 'ename'), (r'\b(functor|include|open|signature|structure)\b(?!\')', Keyword.Reserved, 'sname'), (r'\b(type|eqtype)\b(?!\')', Keyword.Reserved, 'tname'),
# Regular identifiers, long and otherwise (r'\'[\w\']*', Name.Decorator), (rf'({alphanumid_re})(\.)', long_id_callback, "dotted"), (rf'({alphanumid_re})', id_callback), (rf'({symbolicid_re})', id_callback), ], 'dotted': [ (rf'({alphanumid_re})(\.)', long_id_callback), (rf'({alphanumid_re})', end_id_callback, "#pop"), (rf'({symbolicid_re})', end_id_callback, "#pop"), (r'\s+', Error), (r'\S+', Error), ],
# Main parser (prevents errors in files that have scoping errors) 'root': [ default('main') ],
# In this scope, I expect '|' to not be followed by a function name, # and I expect 'and' to be followed by a binding site 'main': [ include('whitespace'),
# Special behavior of val/and/fun (r'\b(val|and)\b(?!\')', Keyword.Reserved, 'vname'), (r'\b(fun)\b(?!\')', Keyword.Reserved, ('#pop', 'main-fun', 'fname')),
include('delimiters'), include('core'), (r'\S+', Error), ],
# In this scope, I expect '|' and 'and' to be followed by a function 'main-fun': [ include('whitespace'),
(r'\s', Text), (r'\(\*', Comment.Multiline, 'comment'),
# Special behavior of val/and/fun (r'\b(fun|and)\b(?!\')', Keyword.Reserved, 'fname'), (r'\b(val)\b(?!\')', Keyword.Reserved, ('#pop', 'main', 'vname')),
# Special behavior of '|' and '|'-manipulating keywords (r'\|', Punctuation, 'fname'), (r'\b(case|handle)\b(?!\')', Keyword.Reserved, ('#pop', 'main')),
include('delimiters'), include('core'), (r'\S+', Error), ],
# Character and string parsers 'char': stringy(String.Char), 'string': stringy(String.Double),
'breakout': [ (r'(?=\b({})\b(?!\'))'.format('|'.join(alphanumid_reserved)), Text, '#pop'), ],
# Dealing with what comes after module system keywords 'sname': [ include('whitespace'), include('breakout'),
(rf'({alphanumid_re})', Name.Namespace), default('#pop'), ],
# Dealing with what comes after the 'fun' (or 'and' or '|') keyword 'fname': [ include('whitespace'), (r'\'[\w\']*', Name.Decorator), (r'\(', Punctuation, 'tyvarseq'),
(rf'({alphanumid_re})', Name.Function, '#pop'), (rf'({symbolicid_re})', Name.Function, '#pop'),
# Ignore interesting function declarations like "fun (x + y) = ..." default('#pop'), ],
# Dealing with what comes after the 'val' (or 'and') keyword 'vname': [ include('whitespace'), (r'\'[\w\']*', Name.Decorator), (r'\(', Punctuation, 'tyvarseq'),
(rf'({alphanumid_re})(\s*)(=(?!{symbolicid_re}))', bygroups(Name.Variable, Text, Punctuation), '#pop'), (rf'({symbolicid_re})(\s*)(=(?!{symbolicid_re}))', bygroups(Name.Variable, Text, Punctuation), '#pop'), (rf'({alphanumid_re})', Name.Variable, '#pop'), (rf'({symbolicid_re})', Name.Variable, '#pop'),
# Ignore interesting patterns like 'val (x, y)' default('#pop'), ],
# Dealing with what comes after the 'type' (or 'and') keyword 'tname': [ include('whitespace'), include('breakout'),
(r'\'[\w\']*', Name.Decorator), (r'\(', Punctuation, 'tyvarseq'), (rf'=(?!{symbolicid_re})', Punctuation, ('#pop', 'typbind')),
(rf'({alphanumid_re})', Keyword.Type), (rf'({symbolicid_re})', Keyword.Type), (r'\S+', Error, '#pop'), ],
# A type binding includes most identifiers 'typbind': [ include('whitespace'),
(r'\b(and)\b(?!\')', Keyword.Reserved, ('#pop', 'tname')),
include('breakout'), include('core'), (r'\S+', Error, '#pop'), ],
# Dealing with what comes after the 'datatype' (or 'and') keyword 'dname': [ include('whitespace'), include('breakout'),
(r'\'[\w\']*', Name.Decorator), (r'\(', Punctuation, 'tyvarseq'), (r'(=)(\s*)(datatype)', bygroups(Punctuation, Text, Keyword.Reserved), '#pop'), (rf'=(?!{symbolicid_re})', Punctuation, ('#pop', 'datbind', 'datcon')),
(rf'({alphanumid_re})', Keyword.Type), (rf'({symbolicid_re})', Keyword.Type), (r'\S+', Error, '#pop'), ],
# common case - A | B | C of int 'datbind': [ include('whitespace'),
(r'\b(and)\b(?!\')', Keyword.Reserved, ('#pop', 'dname')), (r'\b(withtype)\b(?!\')', Keyword.Reserved, ('#pop', 'tname')), (r'\b(of)\b(?!\')', Keyword.Reserved),
(rf'(\|)(\s*)({alphanumid_re})', bygroups(Punctuation, Text, Name.Class)), (rf'(\|)(\s+)({symbolicid_re})', bygroups(Punctuation, Text, Name.Class)),
include('breakout'), include('core'), (r'\S+', Error), ],
# Dealing with what comes after an exception 'ename': [ include('whitespace'),
(rf'(and\b)(\s+)({alphanumid_re})', bygroups(Keyword.Reserved, Text, Name.Class)), (rf'(and\b)(\s*)({symbolicid_re})', bygroups(Keyword.Reserved, Text, Name.Class)), (r'\b(of)\b(?!\')', Keyword.Reserved), (rf'({alphanumid_re})|({symbolicid_re})', Name.Class),
default('#pop'), ],
'datcon': [ include('whitespace'), (rf'({alphanumid_re})', Name.Class, '#pop'), (rf'({symbolicid_re})', Name.Class, '#pop'), (r'\S+', Error, '#pop'), ],
# Series of type variables 'tyvarseq': [ (r'\s', Text), (r'\(\*', Comment.Multiline, 'comment'),
(r'\'[\w\']*', Name.Decorator), (alphanumid_re, Name), (r',', Punctuation), (r'\)', Punctuation, '#pop'), (symbolicid_re, Name), ],
'comment': [ (r'[^(*)]', Comment.Multiline), (r'\(\*', Comment.Multiline, '#push'), (r'\*\)', Comment.Multiline, '#pop'), (r'[(*)]', Comment.Multiline), ], }
class OcamlLexer(RegexLexer): """ For the OCaml language. """
name = 'OCaml' url = 'https://ocaml.org/' aliases = ['ocaml'] filenames = ['*.ml', '*.mli', '*.mll', '*.mly'] mimetypes = ['text/x-ocaml'] version_added = '0.7'
keywords = ( 'and', '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'\|', r'\|]', r'\}', '~' )
operators = r'[!$%&*+\./:<=>?@^|~-]' word_operators = ('asr', 'land', 'lor', 'lsl', 'lxor', 'mod', 'or') prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]' primitives = ('unit', 'int', 'float', 'bool', 'string', 'char', 'list', 'array')
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), (r'false|true|\(\)|\[\]', Name.Builtin.Pseudo), (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][\w\']*)', Name.Class), (r'\(\*(?![)])', Comment, 'comment'), (r'\b({})\b'.format('|'.join(keywords)), Keyword), (r'({})'.format('|'.join(keyopts[::-1])), Operator), (rf'({infix_syms}|{prefix_syms})?{operators}', Operator), (r'\b({})\b'.format('|'.join(word_operators)), Operator.Word), (r'\b({})\b'.format('|'.join(primitives)), Keyword.Type),
(r"[^\W\d][\w']*", Name),
(r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float), (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_]*', Number.Integer),
(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.Variable), ], 'comment': [ (r'[^(*)]+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), (r'[(*)]', Comment), ], '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.Namespace), (r'[A-Z][\w\']*', Name.Class, '#pop'), (r'[a-z_][\w\']*', Name, '#pop'), default('#pop'), ], }
class OpaLexer(RegexLexer): """ Lexer for the Opa language. """
name = 'Opa' aliases = ['opa'] filenames = ['*.opa'] mimetypes = ['text/x-opa'] url = 'http://opalang.org' version_added = '1.5'
# most of these aren't strictly keywords # but if you color only real keywords, you might just # as well not color anything keywords = ( 'and', 'as', 'begin', 'case', 'client', 'css', 'database', 'db', 'do', 'else', 'end', 'external', 'forall', 'function', 'if', 'import', 'match', 'module', 'or', 'package', 'parser', 'rec', 'server', 'then', 'type', 'val', 'with', 'xml_parser', )
# matches both stuff and `stuff` ident_re = r'(([a-zA-Z_]\w*)|(`[^`]*`))'
op_re = r'[.=\-<>,@~%/+?*&^!]' punc_re = r'[()\[\],;|]' # '{' and '}' are treated elsewhere # because they are also used for inserts
tokens = { # copied from the caml lexer, should be adapted 'escape-sequence': [ (r'\\[\\"\'ntr}]', String.Escape), (r'\\[0-9]{3}', String.Escape), (r'\\x[0-9a-fA-F]{2}', String.Escape), ],
# factorizing these rules, because they are inserted many times 'comments': [ (r'/\*', Comment, 'nested-comment'), (r'//.*?$', Comment), ], 'comments-and-spaces': [ include('comments'), (r'\s+', Text), ],
'root': [ include('comments-and-spaces'), # keywords (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword), # directives # we could parse the actual set of directives instead of anything # starting with @, but this is troublesome # because it needs to be adjusted all the time # and assuming we parse only sources that compile, it is useless (r'@' + ident_re + r'\b', Name.Builtin.Pseudo),
# number literals (r'-?.[\d]+([eE][+\-]?\d+)', Number.Float), (r'-?\d+.\d*([eE][+\-]?\d+)', Number.Float), (r'-?\d+[eE][+\-]?\d+', Number.Float), (r'0[xX][\da-fA-F]+', Number.Hex), (r'0[oO][0-7]+', Number.Oct), (r'0[bB][01]+', Number.Bin), (r'\d+', Number.Integer), # color literals (r'#[\da-fA-F]{3,6}', Number.Integer),
# string literals (r'"', String.Double, 'string'), # char literal, should be checked because this is the regexp from # the caml lexer (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2})|.)'", String.Char),
# this is meant to deal with embedded exprs in strings # every time we find a '}' we pop a state so that if we were # inside a string, we are back in the string state # as a consequence, we must also push a state every time we find a # '{' or else we will have errors when parsing {} for instance (r'\{', Operator, '#push'), (r'\}', Operator, '#pop'),
# html literals # this is a much more strict that the actual parser, # since a<b would not be parsed as html # but then again, the parser is way too lax, and we can't hope # to have something as tolerant (r'<(?=[a-zA-Z>])', String.Single, 'html-open-tag'),
# db path # matching the '[_]' in '/a[_]' because it is a part # of the syntax of the db path definition # unfortunately, i don't know how to match the ']' in # /a[1], so this is somewhat inconsistent (r'[@?!]?(/\w+)+(\[_\])?', Name.Variable), # putting the same color on <- as on db path, since # it can be used only to mean Db.write (r'<-(?!'+op_re+r')', Name.Variable),
# 'modules' # although modules are not distinguished by their names as in caml # the standard library seems to follow the convention that modules # only area capitalized (r'\b([A-Z]\w*)(?=\.)', Name.Namespace),
# operators # = has a special role because this is the only # way to syntactic distinguish binding constructions # unfortunately, this colors the equal in {x=2} too (r'=(?!'+op_re+r')', Keyword), (rf'({op_re})+', Operator), (rf'({punc_re})+', Operator),
# coercions (r':', Operator, 'type'), # type variables # we need this rule because we don't parse specially type # definitions so in "type t('a) = ...", "'a" is parsed by 'root' ("'"+ident_re, Keyword.Type),
# id literal, #something, or #{expr} (r'#'+ident_re, String.Single), (r'#(?=\{)', String.Single),
# identifiers # this avoids to color '2' in 'a2' as an integer (ident_re, Text),
# default, not sure if that is needed or not # (r'.', Text), ],
# it is quite painful to have to parse types to know where they end # this is the general rule for a type # a type is either: # * -> ty # * type-with-slash # * type-with-slash -> ty # * type-with-slash (, type-with-slash)+ -> ty # # the code is pretty funky in here, but this code would roughly # translate in caml to: # let rec type stream = # match stream with # | [< "->"; stream >] -> type stream # | [< ""; stream >] -> # type_with_slash stream # type_lhs_1 stream; # and type_1 stream = ... 'type': [ include('comments-and-spaces'), (r'->', Keyword.Type), default(('#pop', 'type-lhs-1', 'type-with-slash')), ],
# parses all the atomic or closed constructions in the syntax of type # expressions: record types, tuple types, type constructors, basic type # and type variables 'type-1': [ include('comments-and-spaces'), (r'\(', Keyword.Type, ('#pop', 'type-tuple')), (r'~?\{', Keyword.Type, ('#pop', 'type-record')), (ident_re+r'\(', Keyword.Type, ('#pop', 'type-tuple')), (ident_re, Keyword.Type, '#pop'), ("'"+ident_re, Keyword.Type), # this case is not in the syntax but sometimes # we think we are parsing types when in fact we are parsing # some css, so we just pop the states until we get back into # the root state default('#pop'), ],
# type-with-slash is either: # * type-1 # * type-1 (/ type-1)+ 'type-with-slash': [ include('comments-and-spaces'), default(('#pop', 'slash-type-1', 'type-1')), ], 'slash-type-1': [ include('comments-and-spaces'), ('/', Keyword.Type, ('#pop', 'type-1')), # same remark as above default('#pop'), ],
# we go in this state after having parsed a type-with-slash # while trying to parse a type # and at this point we must determine if we are parsing an arrow # type (in which case we must continue parsing) or not (in which # case we stop) 'type-lhs-1': [ include('comments-and-spaces'), (r'->', Keyword.Type, ('#pop', 'type')), (r'(?=,)', Keyword.Type, ('#pop', 'type-arrow')), default('#pop'), ], 'type-arrow': [ include('comments-and-spaces'), # the look ahead here allows to parse f(x : int, y : float -> truc) # correctly (r',(?=[^:]*?->)', Keyword.Type, 'type-with-slash'), (r'->', Keyword.Type, ('#pop', 'type')), # same remark as above default('#pop'), ],
# no need to do precise parsing for tuples and records # because they are closed constructions, so we can simply # find the closing delimiter # note that this function would be not work if the source # contained identifiers like `{)` (although it could be patched # to support it) 'type-tuple': [ include('comments-and-spaces'), (r'[^()/*]+', Keyword.Type), (r'[/*]', Keyword.Type), (r'\(', Keyword.Type, '#push'), (r'\)', Keyword.Type, '#pop'), ], 'type-record': [ include('comments-and-spaces'), (r'[^{}/*]+', Keyword.Type), (r'[/*]', Keyword.Type), (r'\{', Keyword.Type, '#push'), (r'\}', Keyword.Type, '#pop'), ],
# 'type-tuple': [ # include('comments-and-spaces'), # (r'\)', Keyword.Type, '#pop'), # default(('#pop', 'type-tuple-1', 'type-1')), # ], # 'type-tuple-1': [ # include('comments-and-spaces'), # (r',?\s*\)', Keyword.Type, '#pop'), # ,) is a valid end of tuple, in (1,) # (r',', Keyword.Type, 'type-1'), # ], # 'type-record':[ # include('comments-and-spaces'), # (r'\}', Keyword.Type, '#pop'), # (r'~?(?:\w+|`[^`]*`)', Keyword.Type, 'type-record-field-expr'), # ], # 'type-record-field-expr': [ # # ],
'nested-comment': [ (r'[^/*]+', Comment), (r'/\*', Comment, '#push'), (r'\*/', Comment, '#pop'), (r'[/*]', Comment), ],
# the copy pasting between string and single-string # is kinda sad. Is there a way to avoid that?? 'string': [ (r'[^\\"{]+', String.Double), (r'"', String.Double, '#pop'), (r'\{', Operator, 'root'), include('escape-sequence'), ], 'single-string': [ (r'[^\\\'{]+', String.Double), (r'\'', String.Double, '#pop'), (r'\{', Operator, 'root'), include('escape-sequence'), ],
# all the html stuff # can't really reuse some existing html parser # because we must be able to parse embedded expressions
# we are in this state after someone parsed the '<' that # started the html literal 'html-open-tag': [ (r'[\w\-:]+', String.Single, ('#pop', 'html-attr')), (r'>', String.Single, ('#pop', 'html-content')), ],
# we are in this state after someone parsed the '</' that # started the end of the closing tag 'html-end-tag': [ # this is a star, because </> is allowed (r'[\w\-:]*>', String.Single, '#pop'), ],
# we are in this state after having parsed '<ident(:ident)?' # we thus parse a possibly empty list of attributes 'html-attr': [ (r'\s+', Text), (r'[\w\-:]+=', String.Single, 'html-attr-value'), (r'/>', String.Single, '#pop'), (r'>', String.Single, ('#pop', 'html-content')), ],
'html-attr-value': [ (r"'", String.Single, ('#pop', 'single-string')), (r'"', String.Single, ('#pop', 'string')), (r'#'+ident_re, String.Single, '#pop'), (r'#(?=\{)', String.Single, ('#pop', 'root')), (r'[^"\'{`=<>]+', String.Single, '#pop'), (r'\{', Operator, ('#pop', 'root')), # this is a tail call! ],
# we should probably deal with '\' escapes here 'html-content': [ (r'<!--', Comment, 'html-comment'), (r'</', String.Single, ('#pop', 'html-end-tag')), (r'<', String.Single, 'html-open-tag'), (r'\{', Operator, 'root'), (r'[^<{]+', String.Single), ],
'html-comment': [ (r'-->', Comment, '#pop'), (r'[^\-]+|-', Comment), ], }
class ReasonLexer(RegexLexer): """ For the ReasonML language. """
name = 'ReasonML' url = 'https://reasonml.github.io/' aliases = ['reasonml', 'reason'] filenames = ['*.re', '*.rei'] mimetypes = ['text/x-reasonml'] version_added = '2.6'
keywords = ( 'as', 'assert', 'begin', 'class', 'constraint', 'do', 'done', 'downto', 'else', 'end', 'exception', 'external', 'false', 'for', 'fun', 'esfun', 'function', 'functor', 'if', 'in', 'include', 'inherit', 'initializer', 'lazy', 'let', 'switch', 'module', 'pub', 'mutable', 'new', 'nonrec', 'object', 'of', 'open', 'pri', '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'\{<', r'\|', r'\|\|', r'\|]', r'\}', '~' )
operators = r'[!$%&*+\./:<=>?@^|~-]' word_operators = ('and', 'asr', 'land', 'lor', 'lsl', 'lsr', 'lxor', 'mod', 'or') prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]' primitives = ('unit', 'int', 'float', 'bool', 'string', 'char', 'list', 'array')
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), (r'false|true|\(\)|\[\]', Name.Builtin.Pseudo), (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][\w\']*)', Name.Class), (r'//.*?\n', Comment.Single), (r'\/\*(?!/)', Comment.Multiline, 'comment'), (r'\b({})\b'.format('|'.join(keywords)), Keyword), (r'({})'.format('|'.join(keyopts[::-1])), Operator.Word), (rf'({infix_syms}|{prefix_syms})?{operators}', Operator), (r'\b({})\b'.format('|'.join(word_operators)), Operator.Word), (r'\b({})\b'.format('|'.join(primitives)), Keyword.Type),
(r"[^\W\d][\w']*", Name),
(r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float), (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_]*', Number.Integer),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'", String.Char), (r"'.'", String.Char), (r"'", Keyword),
(r'"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name.Variable), ], '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.Namespace), (r'[A-Z][\w\']*', Name.Class, '#pop'), (r'[a-z_][\w\']*', Name, '#pop'), default('#pop'), ], }
class FStarLexer(RegexLexer): """ For the F* language. """
name = 'FStar' url = 'https://www.fstar-lang.org/' aliases = ['fstar'] filenames = ['*.fst', '*.fsti'] mimetypes = ['text/x-fstar'] version_added = '2.7'
keywords = ( 'abstract', 'attributes', 'noeq', 'unopteq', 'and' 'begin', 'by', 'default', 'effect', 'else', 'end', 'ensures', 'exception', 'exists', 'false', 'forall', 'fun', 'function', 'if', 'in', 'include', 'inline', 'inline_for_extraction', 'irreducible', 'logic', 'match', 'module', 'mutable', 'new', 'new_effect', 'noextract', 'of', 'open', 'opaque', 'private', 'range_of', 'reifiable', 'reify', 'reflectable', 'requires', 'set_range_of', 'sub_effect', 'synth', 'then', 'total', 'true', 'try', 'type', 'unfold', 'unfoldable', 'val', 'when', 'with', 'not' ) decl_keywords = ('let', 'rec') assume_keywords = ('assume', 'admit', 'assert', 'calc') keyopts = ( r'~', r'-', r'/\\', r'\\/', r'<:', r'<@', r'\(\|', r'\|\)', r'#', r'u#', r'&', r'\(', r'\)', r'\(\)', r',', r'~>', r'->', r'<-', r'<--', r'<==>', r'==>', r'\.', r'\?', r'\?\.', r'\.\[', r'\.\(', r'\.\(\|', r'\.\[\|', r'\{:pattern', r':', r'::', r':=', r';', r';;', r'=', r'%\[', r'!\{', r'\[', r'\[@', r'\[\|', r'\|>', r'\]', r'\|\]', r'\{', r'\|', r'\}', r'\$' )
operators = r'[!$%&*+\./:<=>?@^|~-]' prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]' primitives = ('unit', 'int', 'float', 'bool', 'string', 'char', 'list', 'array')
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), (r'false|true|False|True|\(\)|\[\]', Name.Builtin.Pseudo), (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][\w\']*)', Name.Class), (r'\(\*(?![)])', Comment, 'comment'), (r'\/\/.+$', Comment), (r'\b({})\b'.format('|'.join(keywords)), Keyword), (r'\b({})\b'.format('|'.join(assume_keywords)), Name.Exception), (r'\b({})\b'.format('|'.join(decl_keywords)), Keyword.Declaration), (r'({})'.format('|'.join(keyopts[::-1])), Operator), (rf'({infix_syms}|{prefix_syms})?{operators}', Operator), (r'\b({})\b'.format('|'.join(primitives)), Keyword.Type),
(r"[^\W\d][\w']*", Name),
(r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float), (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_]*', Number.Integer),
(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"\`([\w\'.]+)\`", Operator.Word), # for infix applications (r"\`", Keyword), # for quoting (r'"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name.Variable), ], 'comment': [ (r'[^(*)]+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), (r'[(*)]', Comment), ], '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.Namespace), (r'[A-Z][\w\']*', Name.Class, '#pop'), (r'[a-z_][\w\']*', Name, '#pop'), default('#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368""" pygments.lexers.modeling ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for modeling languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, using, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
from pygments.lexers.html import HtmlLexerfrom pygments.lexers import _stan_builtins
__all__ = ['ModelicaLexer', 'BugsLexer', 'JagsLexer', 'StanLexer']
class ModelicaLexer(RegexLexer): """ For Modelica source code. """ name = 'Modelica' url = 'http://www.modelica.org/' aliases = ['modelica'] filenames = ['*.mo'] mimetypes = ['text/x-modelica'] version_added = '1.1'
flags = re.DOTALL | re.MULTILINE
_name = r"(?:'(?:[^\\']|\\.)+'|[a-zA-Z_]\w*)"
tokens = { 'whitespace': [ (r'[\s\ufeff]+', Text), (r'//[^\n]*\n?', Comment.Single), (r'/\*.*?\*/', Comment.Multiline) ], 'root': [ include('whitespace'), (r'"', String.Double, 'string'), (r'[()\[\]{},;]+', Punctuation), (r'\.?[*^/+-]|\.|<>|[<>:=]=?', Operator), (r'\d+(\.?\d*[eE][-+]?\d+|\.\d*)', Number.Float), (r'\d+', Number.Integer), (r'(abs|acos|actualStream|array|asin|assert|AssertionLevel|atan|' r'atan2|backSample|Boolean|cardinality|cat|ceil|change|Clock|' r'Connections|cos|cosh|cross|delay|diagonal|div|edge|exp|' r'ExternalObject|fill|floor|getInstanceName|hold|homotopy|' r'identity|inStream|integer|Integer|interval|inverse|isPresent|' r'linspace|log|log10|matrix|max|min|mod|ndims|noClock|noEvent|' r'ones|outerProduct|pre|previous|product|Real|reinit|rem|rooted|' r'sample|scalar|semiLinear|shiftSample|sign|sin|sinh|size|skew|' r'smooth|spatialDistribution|sqrt|StateSelect|String|subSample|' r'sum|superSample|symmetric|tan|tanh|terminal|terminate|time|' r'transpose|vector|zeros)\b', Name.Builtin), (r'(algorithm|annotation|break|connect|constant|constrainedby|der|' r'discrete|each|else|elseif|elsewhen|encapsulated|enumeration|' r'equation|exit|expandable|extends|external|firstTick|final|flow|for|if|' r'import|impure|in|initial|inner|input|interval|loop|nondiscrete|outer|' r'output|parameter|partial|protected|public|pure|redeclare|' r'replaceable|return|stream|then|when|while)\b', Keyword.Reserved), (r'(and|not|or)\b', Operator.Word), (r'(block|class|connector|end|function|model|operator|package|' r'record|type)\b', Keyword.Reserved, 'class'), (r'(false|true)\b', Keyword.Constant), (r'within\b', Keyword.Reserved, 'package-prefix'), (_name, Name) ], 'class': [ include('whitespace'), (r'(function|record)\b', Keyword.Reserved), (r'(if|for|when|while)\b', Keyword.Reserved, '#pop'), (_name, Name.Class, '#pop'), default('#pop') ], 'package-prefix': [ include('whitespace'), (_name, Name.Namespace, '#pop'), default('#pop') ], 'string': [ (r'"', String.Double, '#pop'), (r'\\[\'"?\\abfnrtv]', String.Escape), (r'(?i)<\s*html\s*>([^\\"]|\\.)+?(<\s*/\s*html\s*>|(?="))', using(HtmlLexer)), (r'<|\\?[^"\\<]+', String.Double) ] }
class BugsLexer(RegexLexer): """ Pygments Lexer for OpenBugs and WinBugs models. """
name = 'BUGS' aliases = ['bugs', 'winbugs', 'openbugs'] filenames = ['*.bug'] url = 'https://www.mrc-bsu.cam.ac.uk/software/bugs/openbugs' version_added = '1.6'
_FUNCTIONS = ( # Scalar functions 'abs', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh', 'cloglog', 'cos', 'cosh', 'cumulative', 'cut', 'density', 'deviance', 'equals', 'expr', 'gammap', 'ilogit', 'icloglog', 'integral', 'log', 'logfact', 'loggam', 'logit', 'max', 'min', 'phi', 'post.p.value', 'pow', 'prior.p.value', 'probit', 'replicate.post', 'replicate.prior', 'round', 'sin', 'sinh', 'solution', 'sqrt', 'step', 'tan', 'tanh', 'trunc', # Vector functions 'inprod', 'interp.lin', 'inverse', 'logdet', 'mean', 'eigen.vals', 'ode', 'prod', 'p.valueM', 'rank', 'ranked', 'replicate.postM', 'sd', 'sort', 'sum', # Special 'D', 'I', 'F', 'T', 'C') """ OpenBUGS built-in functions
From http://www.openbugs.info/Manuals/ModelSpecification.html#ContentsAII
This also includes
- T, C, I : Truncation and censoring. ``T`` and ``C`` are in OpenBUGS. ``I`` in WinBUGS. - D : ODE - F : Functional http://www.openbugs.info/Examples/Functionals.html
"""
_DISTRIBUTIONS = ('dbern', 'dbin', 'dcat', 'dnegbin', 'dpois', 'dhyper', 'dbeta', 'dchisqr', 'ddexp', 'dexp', 'dflat', 'dgamma', 'dgev', 'df', 'dggamma', 'dgpar', 'dloglik', 'dlnorm', 'dlogis', 'dnorm', 'dpar', 'dt', 'dunif', 'dweib', 'dmulti', 'ddirch', 'dmnorm', 'dmt', 'dwish') """ OpenBUGS built-in distributions
Functions from http://www.openbugs.info/Manuals/ModelSpecification.html#ContentsAI """
tokens = { 'whitespace': [ (r"\s+", Text), ], 'comments': [ # Comments (r'#.*$', Comment.Single), ], 'root': [ # Comments include('comments'), include('whitespace'), # Block start (r'(model)(\s+)(\{)', bygroups(Keyword.Namespace, Text, Punctuation)), # Reserved Words (r'(for|in)(?![\w.])', Keyword.Reserved), # Built-in Functions (r'({})(?=\s*\()'.format(r'|'.join(_FUNCTIONS + _DISTRIBUTIONS)), Name.Builtin), # Regular variable names (r'[A-Za-z][\w.]*', Name), # Number Literals (r'[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?', Number), # Punctuation (r'\[|\]|\(|\)|:|,|;', Punctuation), # Assignment operators # SLexer makes these tokens Operators. (r'<-|~', Operator), # Infix and prefix operators (r'\+|-|\*|/', Operator), # Block (r'[{}]', Punctuation), ] }
def analyse_text(text): if re.search(r"^\s*model\s*{", text, re.M): return 0.7 else: return 0.0
class JagsLexer(RegexLexer): """ Pygments Lexer for JAGS. """
name = 'JAGS' aliases = ['jags'] filenames = ['*.jag', '*.bug'] url = 'https://mcmc-jags.sourceforge.io' version_added = '1.6'
# JAGS _FUNCTIONS = ( 'abs', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh', 'cos', 'cosh', 'cloglog', 'equals', 'exp', 'icloglog', 'ifelse', 'ilogit', 'log', 'logfact', 'loggam', 'logit', 'phi', 'pow', 'probit', 'round', 'sin', 'sinh', 'sqrt', 'step', 'tan', 'tanh', 'trunc', 'inprod', 'interp.lin', 'logdet', 'max', 'mean', 'min', 'prod', 'sum', 'sd', 'inverse', 'rank', 'sort', 't', 'acos', 'acosh', 'asin', 'asinh', 'atan', # Truncation/Censoring (should I include) 'T', 'I') # Distributions with density, probability and quartile functions _DISTRIBUTIONS = tuple(f'[dpq]{x}' for x in ('bern', 'beta', 'dchiqsqr', 'ddexp', 'dexp', 'df', 'gamma', 'gen.gamma', 'logis', 'lnorm', 'negbin', 'nchisqr', 'norm', 'par', 'pois', 'weib')) # Other distributions without density and probability _OTHER_DISTRIBUTIONS = ( 'dt', 'dunif', 'dbetabin', 'dbern', 'dbin', 'dcat', 'dhyper', 'ddirch', 'dmnorm', 'dwish', 'dmt', 'dmulti', 'dbinom', 'dchisq', 'dnbinom', 'dweibull', 'ddirich')
tokens = { 'whitespace': [ (r"\s+", Text), ], 'names': [ # Regular variable names (r'[a-zA-Z][\w.]*\b', Name), ], 'comments': [ # do not use stateful comments (r'(?s)/\*.*?\*/', Comment.Multiline), # Comments (r'#.*$', Comment.Single), ], 'root': [ # Comments include('comments'), include('whitespace'), # Block start (r'(model|data)(\s+)(\{)', bygroups(Keyword.Namespace, Text, Punctuation)), (r'var(?![\w.])', Keyword.Declaration), # Reserved Words (r'(for|in)(?![\w.])', Keyword.Reserved), # Builtins # Need to use lookahead because . is a valid char (r'({})(?=\s*\()'.format(r'|'.join(_FUNCTIONS + _DISTRIBUTIONS + _OTHER_DISTRIBUTIONS)), Name.Builtin), # Names include('names'), # Number Literals (r'[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?', Number), (r'\[|\]|\(|\)|:|,|;', Punctuation), # Assignment operators (r'<-|~', Operator), # # JAGS includes many more than OpenBUGS (r'\+|-|\*|\/|\|\|[&]{2}|[<>=]=?|\^|%.*?%', Operator), (r'[{}]', Punctuation), ] }
def analyse_text(text): if re.search(r'^\s*model\s*\{', text, re.M): if re.search(r'^\s*data\s*\{', text, re.M): return 0.9 elif re.search(r'^\s*var', text, re.M): return 0.9 else: return 0.3 else: return 0
class StanLexer(RegexLexer): """Pygments Lexer for Stan models.
The Stan modeling language is specified in the *Stan Modeling Language User's Guide and Reference Manual, v2.17.0*, `pdf <https://github.com/stan-dev/stan/releases/download/v2.17.0/stan-reference-2.17.0.pdf>`__. """
name = 'Stan' aliases = ['stan'] filenames = ['*.stan'] url = 'https://mc-stan.org' version_added = '1.6'
tokens = { 'whitespace': [ (r"\s+", Text), ], 'comments': [ (r'(?s)/\*.*?\*/', Comment.Multiline), # Comments (r'(//|#).*$', Comment.Single), ], 'root': [ (r'"[^"]*"', String), # Comments include('comments'), # block start include('whitespace'), # Block start (r'({})(\s*)(\{{)'.format(r'|'.join(('functions', 'data', r'transformed\s+?data', 'parameters', r'transformed\s+parameters', 'model', r'generated\s+quantities'))), bygroups(Keyword.Namespace, Text, Punctuation)), # target keyword (r'target\s*\+=', Keyword), # jacobian += statement (r'jacobian\s*\+=', Keyword), # Reserved Words (r'({})\b'.format(r'|'.join(_stan_builtins.KEYWORDS)), Keyword), # Truncation (r'T(?=\s*\[)', Keyword), # Data types (r'({})\b'.format(r'|'.join(_stan_builtins.TYPES)), Keyword.Type), # < should be punctuation, but elsewhere I can't tell if it is in # a range constraint (r'(<)(\s*)(upper|lower|offset|multiplier)(\s*)(=)', bygroups(Operator, Whitespace, Keyword, Whitespace, Punctuation)), (r'(,)(\s*)(upper)(\s*)(=)', bygroups(Punctuation, Whitespace, Keyword, Whitespace, Punctuation)), # Punctuation (r"[;,\[\]()]", Punctuation), # Builtin (r'({})(?=\s*\()'.format('|'.join(_stan_builtins.FUNCTIONS)), Name.Builtin), (r'(~)(\s*)({})(?=\s*\()'.format('|'.join(_stan_builtins.DISTRIBUTIONS)), bygroups(Operator, Whitespace, Name.Builtin)), # Special names ending in __, like lp__ (r'[A-Za-z]\w*__\b', Name.Builtin.Pseudo), (r'({})\b'.format(r'|'.join(_stan_builtins.RESERVED)), Keyword.Reserved), # user-defined functions (r'[A-Za-z]\w*(?=\s*\()]', Name.Function), # Imaginary Literals (r'[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?i', Number.Float), (r'\.[0-9]+([eE][+-]?[0-9]+)?i', Number.Float), (r'[0-9]+i', Number.Float), # Real Literals (r'[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?', Number.Float), (r'\.[0-9]+([eE][+-]?[0-9]+)?', Number.Float), # Integer Literals (r'[0-9]+', Number.Integer), # Regular variable names (r'[A-Za-z]\w*\b', Name), # Assignment operators (r'<-|(?:\+|-|\.?/|\.?\*|=)?=|~', Operator), # Infix, prefix and postfix operators (and = ) (r"\+|-|\.?\*|\.?/|\\|'|\.?\^|!=?|<=?|>=?|\|\||&&|%|\?|:|%/%|!", Operator), # Block delimiters (r'[{}]', Punctuation), # Distribution | (r'\|', Punctuation) ] }
def analyse_text(text): if re.search(r'^\s*parameters\s*\{', text, re.M): return 1.0 else: return 0.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579""" pygments.lexers.modula2 ~~~~~~~~~~~~~~~~~~~~~~~
Multi-Dialect Lexer for Modula-2.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, includefrom pygments.util import get_bool_opt, get_list_optfrom pygments.token import Text, Comment, Operator, Keyword, Name, \ String, Number, Punctuation, Error
__all__ = ['Modula2Lexer']
# Multi-Dialect Modula-2 Lexerclass Modula2Lexer(RegexLexer): """ For Modula-2 source code.
The Modula-2 lexer supports several dialects. By default, it operates in fallback mode, recognising the *combined* literals, punctuation symbols and operators of all supported dialects, and the *combined* reserved words and builtins of PIM Modula-2, ISO Modula-2 and Modula-2 R10, while not differentiating between library defined identifiers.
To select a specific dialect, a dialect option may be passed or a dialect tag may be embedded into a source file.
Dialect Options:
`m2pim` Select PIM Modula-2 dialect. `m2iso` Select ISO Modula-2 dialect. `m2r10` Select Modula-2 R10 dialect. `objm2` Select Objective Modula-2 dialect.
The PIM and ISO dialect options may be qualified with a language extension.
Language Extensions:
`+aglet` Select Aglet Modula-2 extensions, available with m2iso. `+gm2` Select GNU Modula-2 extensions, available with m2pim. `+p1` Select p1 Modula-2 extensions, available with m2iso. `+xds` Select XDS Modula-2 extensions, available with m2iso.
Passing a Dialect Option via Unix Commandline Interface
Dialect options may be passed to the lexer using the `dialect` key. Only one such option should be passed. If multiple dialect options are passed, the first valid option is used, any subsequent options are ignored.
Examples:
`$ pygmentize -O full,dialect=m2iso -f html -o /path/to/output /path/to/input` Use ISO dialect to render input to HTML output `$ pygmentize -O full,dialect=m2iso+p1 -f rtf -o /path/to/output /path/to/input` Use ISO dialect with p1 extensions to render input to RTF output
Embedding a Dialect Option within a source file
A dialect option may be embedded in a source file in form of a dialect tag, a specially formatted comment that specifies a dialect option.
Dialect Tag EBNF::
dialectTag : OpeningCommentDelim Prefix dialectOption ClosingCommentDelim ;
dialectOption : 'm2pim' | 'm2iso' | 'm2r10' | 'objm2' | 'm2iso+aglet' | 'm2pim+gm2' | 'm2iso+p1' | 'm2iso+xds' ;
Prefix : '!' ;
OpeningCommentDelim : '(*' ;
ClosingCommentDelim : '*)' ;
No whitespace is permitted between the tokens of a dialect tag.
In the event that a source file contains multiple dialect tags, the first tag that contains a valid dialect option will be used and any subsequent dialect tags will be ignored. Ideally, a dialect tag should be placed at the beginning of a source file.
An embedded dialect tag overrides a dialect option set via command line.
Examples:
``(*!m2r10*) DEFINITION MODULE Foobar; ...`` Use Modula2 R10 dialect to render this source file. ``(*!m2pim+gm2*) DEFINITION MODULE Bazbam; ...`` Use PIM dialect with GNU extensions to render this source file.
Algol Publication Mode:
In Algol publication mode, source text is rendered for publication of algorithms in scientific papers and academic texts, following the format of the Revised Algol-60 Language Report. It is activated by passing one of two corresponding styles as an option:
`algol` render reserved words lowercase underline boldface and builtins lowercase boldface italic `algol_nu` render reserved words lowercase boldface (no underlining) and builtins lowercase boldface italic
The lexer automatically performs the required lowercase conversion when this mode is activated.
Example:
``$ pygmentize -O full,style=algol -f latex -o /path/to/output /path/to/input`` Render input file in Algol publication mode to LaTeX output.
Rendering Mode of First Class ADT Identifiers:
The rendering of standard library first class ADT identifiers is controlled by option flag "treat_stdlib_adts_as_builtins".
When this option is turned on, standard library ADT identifiers are rendered as builtins. When it is turned off, they are rendered as ordinary library identifiers.
`treat_stdlib_adts_as_builtins` (default: On)
The option is useful for dialects that support ADTs as first class objects and provide ADTs in the standard library that would otherwise be built-in.
At present, only Modula-2 R10 supports library ADTs as first class objects and therefore, no ADT identifiers are defined for any other dialects.
Example:
``$ pygmentize -O full,dialect=m2r10,treat_stdlib_adts_as_builtins=Off ...`` Render standard library ADTs as ordinary library types.
.. versionchanged:: 2.1 Added multi-dialect support. """ name = 'Modula-2' url = 'http://www.modula2.org/' aliases = ['modula2', 'm2'] filenames = ['*.def', '*.mod'] mimetypes = ['text/x-modula2'] version_added = '1.3'
flags = re.MULTILINE | re.DOTALL
tokens = { 'whitespace': [ (r'\n+', Text), # blank lines (r'\s+', Text), # whitespace ], 'dialecttags': [ # PIM Dialect Tag (r'\(\*!m2pim\*\)', Comment.Special), # ISO Dialect Tag (r'\(\*!m2iso\*\)', Comment.Special), # M2R10 Dialect Tag (r'\(\*!m2r10\*\)', Comment.Special), # ObjM2 Dialect Tag (r'\(\*!objm2\*\)', Comment.Special), # Aglet Extensions Dialect Tag (r'\(\*!m2iso\+aglet\*\)', Comment.Special), # GNU Extensions Dialect Tag (r'\(\*!m2pim\+gm2\*\)', Comment.Special), # p1 Extensions Dialect Tag (r'\(\*!m2iso\+p1\*\)', Comment.Special), # XDS Extensions Dialect Tag (r'\(\*!m2iso\+xds\*\)', Comment.Special), ], 'identifiers': [ (r'([a-zA-Z_$][\w$]*)', Name), ], 'prefixed_number_literals': [ # # Base-2, whole number (r'0b[01]+(\'[01]+)*', Number.Bin), # # Base-16, whole number (r'0[ux][0-9A-F]+(\'[0-9A-F]+)*', Number.Hex), ], 'plain_number_literals': [ # # Base-10, real number with exponent (r'[0-9]+(\'[0-9]+)*' # integral part r'\.[0-9]+(\'[0-9]+)*' # fractional part r'[eE][+-]?[0-9]+(\'[0-9]+)*', # exponent Number.Float), # # Base-10, real number without exponent (r'[0-9]+(\'[0-9]+)*' # integral part r'\.[0-9]+(\'[0-9]+)*', # fractional part Number.Float), # # Base-10, whole number (r'[0-9]+(\'[0-9]+)*', Number.Integer), ], 'suffixed_number_literals': [ # # Base-8, whole number (r'[0-7]+B', Number.Oct), # # Base-8, character code (r'[0-7]+C', Number.Oct), # # Base-16, number (r'[0-9A-F]+H', Number.Hex), ], 'string_literals': [ (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ], 'digraph_operators': [ # Dot Product Operator (r'\*\.', Operator), # Array Concatenation Operator (r'\+>', Operator), # M2R10 + ObjM2 # Inequality Operator (r'<>', Operator), # ISO + PIM # Less-Or-Equal, Subset (r'<=', Operator), # Greater-Or-Equal, Superset (r'>=', Operator), # Identity Operator (r'==', Operator), # M2R10 + ObjM2 # Type Conversion Operator (r'::', Operator), # M2R10 + ObjM2 # Assignment Symbol (r':=', Operator), # Postfix Increment Mutator (r'\+\+', Operator), # M2R10 + ObjM2 # Postfix Decrement Mutator (r'--', Operator), # M2R10 + ObjM2 ], 'unigraph_operators': [ # Arithmetic Operators (r'[+-]', Operator), (r'[*/]', Operator), # ISO 80000-2 compliant Set Difference Operator (r'\\', Operator), # M2R10 + ObjM2 # Relational Operators (r'[=#<>]', Operator), # Dereferencing Operator (r'\^', Operator), # Dereferencing Operator Synonym (r'@', Operator), # ISO # Logical AND Operator Synonym (r'&', Operator), # PIM + ISO # Logical NOT Operator Synonym (r'~', Operator), # PIM + ISO # Smalltalk Message Prefix (r'`', Operator), # ObjM2 ], 'digraph_punctuation': [ # Range Constructor (r'\.\.', Punctuation), # Opening Chevron Bracket (r'<<', Punctuation), # M2R10 + ISO # Closing Chevron Bracket (r'>>', Punctuation), # M2R10 + ISO # Blueprint Punctuation (r'->', Punctuation), # M2R10 + ISO # Distinguish |# and # in M2 R10 (r'\|#', Punctuation), # Distinguish ## and # in M2 R10 (r'##', Punctuation), # Distinguish |* and * in M2 R10 (r'\|\*', Punctuation), ], 'unigraph_punctuation': [ # Common Punctuation (r'[()\[\]{},.:;|]', Punctuation), # Case Label Separator Synonym (r'!', Punctuation), # ISO # Blueprint Punctuation (r'\?', Punctuation), # M2R10 + ObjM2 ], 'comments': [ # Single Line Comment (r'^//.*?\n', Comment.Single), # M2R10 + ObjM2 # Block Comment (r'\(\*([^$].*?)\*\)', Comment.Multiline), # Template Block Comment (r'/\*(.*?)\*/', Comment.Multiline), # M2R10 + ObjM2 ], 'pragmas': [ # ISO Style Pragmas (r'<\*.*?\*>', Comment.Preproc), # ISO, M2R10 + ObjM2 # Pascal Style Pragmas (r'\(\*\$.*?\*\)', Comment.Preproc), # PIM ], 'root': [ include('whitespace'), include('dialecttags'), include('pragmas'), include('comments'), include('identifiers'), include('suffixed_number_literals'), # PIM + ISO include('prefixed_number_literals'), # M2R10 + ObjM2 include('plain_number_literals'), include('string_literals'), include('digraph_punctuation'), include('digraph_operators'), include('unigraph_punctuation'), include('unigraph_operators'), ] }
# C o m m o n D a t a s e t s
# Common Reserved Words Dataset common_reserved_words = ( # 37 common reserved words 'AND', 'ARRAY', 'BEGIN', 'BY', 'CASE', 'CONST', 'DEFINITION', 'DIV', 'DO', 'ELSE', 'ELSIF', 'END', 'EXIT', 'FOR', 'FROM', 'IF', 'IMPLEMENTATION', 'IMPORT', 'IN', 'LOOP', 'MOD', 'MODULE', 'NOT', 'OF', 'OR', 'POINTER', 'PROCEDURE', 'RECORD', 'REPEAT', 'RETURN', 'SET', 'THEN', 'TO', 'TYPE', 'UNTIL', 'VAR', 'WHILE', )
# Common Builtins Dataset common_builtins = ( # 16 common builtins 'ABS', 'BOOLEAN', 'CARDINAL', 'CHAR', 'CHR', 'FALSE', 'INTEGER', 'LONGINT', 'LONGREAL', 'MAX', 'MIN', 'NIL', 'ODD', 'ORD', 'REAL', 'TRUE', )
# Common Pseudo-Module Builtins Dataset common_pseudo_builtins = ( # 4 common pseudo builtins 'ADDRESS', 'BYTE', 'WORD', 'ADR' )
# P I M M o d u l a - 2 D a t a s e t s
# Lexemes to Mark as Error Tokens for PIM Modula-2 pim_lexemes_to_reject = ( '!', '`', '@', '$', '%', '?', '\\', '==', '++', '--', '::', '*.', '+>', '->', '<<', '>>', '|#', '##', )
# PIM Modula-2 Additional Reserved Words Dataset pim_additional_reserved_words = ( # 3 additional reserved words 'EXPORT', 'QUALIFIED', 'WITH', )
# PIM Modula-2 Additional Builtins Dataset pim_additional_builtins = ( # 16 additional builtins 'BITSET', 'CAP', 'DEC', 'DISPOSE', 'EXCL', 'FLOAT', 'HALT', 'HIGH', 'INC', 'INCL', 'NEW', 'NIL', 'PROC', 'SIZE', 'TRUNC', 'VAL', )
# PIM Modula-2 Additional Pseudo-Module Builtins Dataset pim_additional_pseudo_builtins = ( # 5 additional pseudo builtins 'SYSTEM', 'PROCESS', 'TSIZE', 'NEWPROCESS', 'TRANSFER', )
# I S O M o d u l a - 2 D a t a s e t s
# Lexemes to Mark as Error Tokens for ISO Modula-2 iso_lexemes_to_reject = ( '`', '$', '%', '?', '\\', '==', '++', '--', '::', '*.', '+>', '->', '<<', '>>', '|#', '##', )
# ISO Modula-2 Additional Reserved Words Dataset iso_additional_reserved_words = ( # 9 additional reserved words (ISO 10514-1) 'EXCEPT', 'EXPORT', 'FINALLY', 'FORWARD', 'PACKEDSET', 'QUALIFIED', 'REM', 'RETRY', 'WITH', # 10 additional reserved words (ISO 10514-2 & ISO 10514-3) 'ABSTRACT', 'AS', 'CLASS', 'GUARD', 'INHERIT', 'OVERRIDE', 'READONLY', 'REVEAL', 'TRACED', 'UNSAFEGUARDED', )
# ISO Modula-2 Additional Builtins Dataset iso_additional_builtins = ( # 26 additional builtins (ISO 10514-1) 'BITSET', 'CAP', 'CMPLX', 'COMPLEX', 'DEC', 'DISPOSE', 'EXCL', 'FLOAT', 'HALT', 'HIGH', 'IM', 'INC', 'INCL', 'INT', 'INTERRUPTIBLE', 'LENGTH', 'LFLOAT', 'LONGCOMPLEX', 'NEW', 'PROC', 'PROTECTION', 'RE', 'SIZE', 'TRUNC', 'UNINTERRUBTIBLE', 'VAL', # 5 additional builtins (ISO 10514-2 & ISO 10514-3) 'CREATE', 'DESTROY', 'EMPTY', 'ISMEMBER', 'SELF', )
# ISO Modula-2 Additional Pseudo-Module Builtins Dataset iso_additional_pseudo_builtins = ( # 14 additional builtins (SYSTEM) 'SYSTEM', 'BITSPERLOC', 'LOCSPERBYTE', 'LOCSPERWORD', 'LOC', 'ADDADR', 'SUBADR', 'DIFADR', 'MAKEADR', 'ADR', 'ROTATE', 'SHIFT', 'CAST', 'TSIZE', # 13 additional builtins (COROUTINES) 'COROUTINES', 'ATTACH', 'COROUTINE', 'CURRENT', 'DETACH', 'HANDLER', 'INTERRUPTSOURCE', 'IOTRANSFER', 'IsATTACHED', 'LISTEN', 'NEWCOROUTINE', 'PROT', 'TRANSFER', # 9 additional builtins (EXCEPTIONS) 'EXCEPTIONS', 'AllocateSource', 'CurrentNumber', 'ExceptionNumber', 'ExceptionSource', 'GetMessage', 'IsCurrentSource', 'IsExceptionalExecution', 'RAISE', # 3 additional builtins (TERMINATION) 'TERMINATION', 'IsTerminating', 'HasHalted', # 4 additional builtins (M2EXCEPTION) 'M2EXCEPTION', 'M2Exceptions', 'M2Exception', 'IsM2Exception', 'indexException', 'rangeException', 'caseSelectException', 'invalidLocation', 'functionException', 'wholeValueException', 'wholeDivException', 'realValueException', 'realDivException', 'complexValueException', 'complexDivException', 'protException', 'sysException', 'coException', 'exException', )
# M o d u l a - 2 R 1 0 D a t a s e t s
# Lexemes to Mark as Error Tokens for Modula-2 R10 m2r10_lexemes_to_reject = ( '!', '`', '@', '$', '%', '&', '<>', )
# Modula-2 R10 reserved words in addition to the common set m2r10_additional_reserved_words = ( # 12 additional reserved words 'ALIAS', 'ARGLIST', 'BLUEPRINT', 'COPY', 'GENLIB', 'INDETERMINATE', 'NEW', 'NONE', 'OPAQUE', 'REFERENTIAL', 'RELEASE', 'RETAIN', # 2 additional reserved words with symbolic assembly option 'ASM', 'REG', )
# Modula-2 R10 builtins in addition to the common set m2r10_additional_builtins = ( # 26 additional builtins 'CARDINAL', 'COUNT', 'EMPTY', 'EXISTS', 'INSERT', 'LENGTH', 'LONGCARD', 'OCTET', 'PTR', 'PRED', 'READ', 'READNEW', 'REMOVE', 'RETRIEVE', 'SORT', 'STORE', 'SUBSET', 'SUCC', 'TLIMIT', 'TMAX', 'TMIN', 'TRUE', 'TSIZE', 'UNICHAR', 'WRITE', 'WRITEF', )
# Modula-2 R10 Additional Pseudo-Module Builtins Dataset m2r10_additional_pseudo_builtins = ( # 13 additional builtins (TPROPERTIES) 'TPROPERTIES', 'PROPERTY', 'LITERAL', 'TPROPERTY', 'TLITERAL', 'TBUILTIN', 'TDYN', 'TREFC', 'TNIL', 'TBASE', 'TPRECISION', 'TMAXEXP', 'TMINEXP', # 4 additional builtins (CONVERSION) 'CONVERSION', 'TSXFSIZE', 'SXF', 'VAL', # 35 additional builtins (UNSAFE) 'UNSAFE', 'CAST', 'INTRINSIC', 'AVAIL', 'ADD', 'SUB', 'ADDC', 'SUBC', 'FETCHADD', 'FETCHSUB', 'SHL', 'SHR', 'ASHR', 'ROTL', 'ROTR', 'ROTLC', 'ROTRC', 'BWNOT', 'BWAND', 'BWOR', 'BWXOR', 'BWNAND', 'BWNOR', 'SETBIT', 'TESTBIT', 'LSBIT', 'MSBIT', 'CSBITS', 'BAIL', 'HALT', 'TODO', 'FFI', 'ADDR', 'VARGLIST', 'VARGC', # 11 additional builtins (ATOMIC) 'ATOMIC', 'INTRINSIC', 'AVAIL', 'SWAP', 'CAS', 'INC', 'DEC', 'BWAND', 'BWNAND', 'BWOR', 'BWXOR', # 7 additional builtins (COMPILER) 'COMPILER', 'DEBUG', 'MODNAME', 'PROCNAME', 'LINENUM', 'DEFAULT', 'HASH', # 5 additional builtins (ASSEMBLER) 'ASSEMBLER', 'REGISTER', 'SETREG', 'GETREG', 'CODE', )
# O b j e c t i v e M o d u l a - 2 D a t a s e t s
# Lexemes to Mark as Error Tokens for Objective Modula-2 objm2_lexemes_to_reject = ( '!', '$', '%', '&', '<>', )
# Objective Modula-2 Extensions # reserved words in addition to Modula-2 R10 objm2_additional_reserved_words = ( # 16 additional reserved words 'BYCOPY', 'BYREF', 'CLASS', 'CONTINUE', 'CRITICAL', 'INOUT', 'METHOD', 'ON', 'OPTIONAL', 'OUT', 'PRIVATE', 'PROTECTED', 'PROTOCOL', 'PUBLIC', 'SUPER', 'TRY', )
# Objective Modula-2 Extensions # builtins in addition to Modula-2 R10 objm2_additional_builtins = ( # 3 additional builtins 'OBJECT', 'NO', 'YES', )
# Objective Modula-2 Extensions # pseudo-module builtins in addition to Modula-2 R10 objm2_additional_pseudo_builtins = ( # None )
# A g l e t M o d u l a - 2 D a t a s e t s
# Aglet Extensions # reserved words in addition to ISO Modula-2 aglet_additional_reserved_words = ( # None )
# Aglet Extensions # builtins in addition to ISO Modula-2 aglet_additional_builtins = ( # 9 additional builtins 'BITSET8', 'BITSET16', 'BITSET32', 'CARDINAL8', 'CARDINAL16', 'CARDINAL32', 'INTEGER8', 'INTEGER16', 'INTEGER32', )
# Aglet Modula-2 Extensions # pseudo-module builtins in addition to ISO Modula-2 aglet_additional_pseudo_builtins = ( # None )
# G N U M o d u l a - 2 D a t a s e t s
# GNU Extensions # reserved words in addition to PIM Modula-2 gm2_additional_reserved_words = ( # 10 additional reserved words 'ASM', '__ATTRIBUTE__', '__BUILTIN__', '__COLUMN__', '__DATE__', '__FILE__', '__FUNCTION__', '__LINE__', '__MODULE__', 'VOLATILE', )
# GNU Extensions # builtins in addition to PIM Modula-2 gm2_additional_builtins = ( # 21 additional builtins 'BITSET8', 'BITSET16', 'BITSET32', 'CARDINAL8', 'CARDINAL16', 'CARDINAL32', 'CARDINAL64', 'COMPLEX32', 'COMPLEX64', 'COMPLEX96', 'COMPLEX128', 'INTEGER8', 'INTEGER16', 'INTEGER32', 'INTEGER64', 'REAL8', 'REAL16', 'REAL32', 'REAL96', 'REAL128', 'THROW', )
# GNU Extensions # pseudo-module builtins in addition to PIM Modula-2 gm2_additional_pseudo_builtins = ( # None )
# p 1 M o d u l a - 2 D a t a s e t s
# p1 Extensions # reserved words in addition to ISO Modula-2 p1_additional_reserved_words = ( # None )
# p1 Extensions # builtins in addition to ISO Modula-2 p1_additional_builtins = ( # None )
# p1 Modula-2 Extensions # pseudo-module builtins in addition to ISO Modula-2 p1_additional_pseudo_builtins = ( # 1 additional builtin 'BCD', )
# X D S M o d u l a - 2 D a t a s e t s
# XDS Extensions # reserved words in addition to ISO Modula-2 xds_additional_reserved_words = ( # 1 additional reserved word 'SEQ', )
# XDS Extensions # builtins in addition to ISO Modula-2 xds_additional_builtins = ( # 9 additional builtins 'ASH', 'ASSERT', 'DIFFADR_TYPE', 'ENTIER', 'INDEX', 'LEN', 'LONGCARD', 'SHORTCARD', 'SHORTINT', )
# XDS Modula-2 Extensions # pseudo-module builtins in addition to ISO Modula-2 xds_additional_pseudo_builtins = ( # 22 additional builtins (SYSTEM) 'PROCESS', 'NEWPROCESS', 'BOOL8', 'BOOL16', 'BOOL32', 'CARD8', 'CARD16', 'CARD32', 'INT8', 'INT16', 'INT32', 'REF', 'MOVE', 'FILL', 'GET', 'PUT', 'CC', 'int', 'unsigned', 'size_t', 'void' # 3 additional builtins (COMPILER) 'COMPILER', 'OPTION', 'EQUATION' )
# P I M S t a n d a r d L i b r a r y D a t a s e t s
# PIM Modula-2 Standard Library Modules Dataset pim_stdlib_module_identifiers = ( 'Terminal', 'FileSystem', 'InOut', 'RealInOut', 'MathLib0', 'Storage', )
# PIM Modula-2 Standard Library Types Dataset pim_stdlib_type_identifiers = ( 'Flag', 'FlagSet', 'Response', 'Command', 'Lock', 'Permission', 'MediumType', 'File', 'FileProc', 'DirectoryProc', 'FileCommand', 'DirectoryCommand', )
# PIM Modula-2 Standard Library Procedures Dataset pim_stdlib_proc_identifiers = ( 'Read', 'BusyRead', 'ReadAgain', 'Write', 'WriteString', 'WriteLn', 'Create', 'Lookup', 'Close', 'Delete', 'Rename', 'SetRead', 'SetWrite', 'SetModify', 'SetOpen', 'Doio', 'SetPos', 'GetPos', 'Length', 'Reset', 'Again', 'ReadWord', 'WriteWord', 'ReadChar', 'WriteChar', 'CreateMedium', 'DeleteMedium', 'AssignName', 'DeassignName', 'ReadMedium', 'LookupMedium', 'OpenInput', 'OpenOutput', 'CloseInput', 'CloseOutput', 'ReadString', 'ReadInt', 'ReadCard', 'ReadWrd', 'WriteInt', 'WriteCard', 'WriteOct', 'WriteHex', 'WriteWrd', 'ReadReal', 'WriteReal', 'WriteFixPt', 'WriteRealOct', 'sqrt', 'exp', 'ln', 'sin', 'cos', 'arctan', 'entier', 'ALLOCATE', 'DEALLOCATE', )
# PIM Modula-2 Standard Library Variables Dataset pim_stdlib_var_identifiers = ( 'Done', 'termCH', 'in', 'out' )
# PIM Modula-2 Standard Library Constants Dataset pim_stdlib_const_identifiers = ( 'EOL', )
# I S O S t a n d a r d L i b r a r y D a t a s e t s
# ISO Modula-2 Standard Library Modules Dataset iso_stdlib_module_identifiers = ( # TO DO )
# ISO Modula-2 Standard Library Types Dataset iso_stdlib_type_identifiers = ( # TO DO )
# ISO Modula-2 Standard Library Procedures Dataset iso_stdlib_proc_identifiers = ( # TO DO )
# ISO Modula-2 Standard Library Variables Dataset iso_stdlib_var_identifiers = ( # TO DO )
# ISO Modula-2 Standard Library Constants Dataset iso_stdlib_const_identifiers = ( # TO DO )
# M 2 R 1 0 S t a n d a r d L i b r a r y D a t a s e t s
# Modula-2 R10 Standard Library ADTs Dataset m2r10_stdlib_adt_identifiers = ( 'BCD', 'LONGBCD', 'BITSET', 'SHORTBITSET', 'LONGBITSET', 'LONGLONGBITSET', 'COMPLEX', 'LONGCOMPLEX', 'SHORTCARD', 'LONGLONGCARD', 'SHORTINT', 'LONGLONGINT', 'POSINT', 'SHORTPOSINT', 'LONGPOSINT', 'LONGLONGPOSINT', 'BITSET8', 'BITSET16', 'BITSET32', 'BITSET64', 'BITSET128', 'BS8', 'BS16', 'BS32', 'BS64', 'BS128', 'CARDINAL8', 'CARDINAL16', 'CARDINAL32', 'CARDINAL64', 'CARDINAL128', 'CARD8', 'CARD16', 'CARD32', 'CARD64', 'CARD128', 'INTEGER8', 'INTEGER16', 'INTEGER32', 'INTEGER64', 'INTEGER128', 'INT8', 'INT16', 'INT32', 'INT64', 'INT128', 'STRING', 'UNISTRING', )
# Modula-2 R10 Standard Library Blueprints Dataset m2r10_stdlib_blueprint_identifiers = ( 'ProtoRoot', 'ProtoComputational', 'ProtoNumeric', 'ProtoScalar', 'ProtoNonScalar', 'ProtoCardinal', 'ProtoInteger', 'ProtoReal', 'ProtoComplex', 'ProtoVector', 'ProtoTuple', 'ProtoCompArray', 'ProtoCollection', 'ProtoStaticArray', 'ProtoStaticSet', 'ProtoStaticString', 'ProtoArray', 'ProtoString', 'ProtoSet', 'ProtoMultiSet', 'ProtoDictionary', 'ProtoMultiDict', 'ProtoExtension', 'ProtoIO', 'ProtoCardMath', 'ProtoIntMath', 'ProtoRealMath', )
# Modula-2 R10 Standard Library Modules Dataset m2r10_stdlib_module_identifiers = ( 'ASCII', 'BooleanIO', 'CharIO', 'UnicharIO', 'OctetIO', 'CardinalIO', 'LongCardIO', 'IntegerIO', 'LongIntIO', 'RealIO', 'LongRealIO', 'BCDIO', 'LongBCDIO', 'CardMath', 'LongCardMath', 'IntMath', 'LongIntMath', 'RealMath', 'LongRealMath', 'BCDMath', 'LongBCDMath', 'FileIO', 'FileSystem', 'Storage', 'IOSupport', )
# Modula-2 R10 Standard Library Types Dataset m2r10_stdlib_type_identifiers = ( 'File', 'Status', # TO BE COMPLETED )
# Modula-2 R10 Standard Library Procedures Dataset m2r10_stdlib_proc_identifiers = ( 'ALLOCATE', 'DEALLOCATE', 'SIZE', # TO BE COMPLETED )
# Modula-2 R10 Standard Library Variables Dataset m2r10_stdlib_var_identifiers = ( 'stdIn', 'stdOut', 'stdErr', )
# Modula-2 R10 Standard Library Constants Dataset m2r10_stdlib_const_identifiers = ( 'pi', 'tau', )
# D i a l e c t s
# Dialect modes dialects = ( 'unknown', 'm2pim', 'm2iso', 'm2r10', 'objm2', 'm2iso+aglet', 'm2pim+gm2', 'm2iso+p1', 'm2iso+xds', )
# D a t a b a s e s
# Lexemes to Mark as Errors Database lexemes_to_reject_db = { # Lexemes to reject for unknown dialect 'unknown': ( # LEAVE THIS EMPTY ), # Lexemes to reject for PIM Modula-2 'm2pim': ( pim_lexemes_to_reject, ), # Lexemes to reject for ISO Modula-2 'm2iso': ( iso_lexemes_to_reject, ), # Lexemes to reject for Modula-2 R10 'm2r10': ( m2r10_lexemes_to_reject, ), # Lexemes to reject for Objective Modula-2 'objm2': ( objm2_lexemes_to_reject, ), # Lexemes to reject for Aglet Modula-2 'm2iso+aglet': ( iso_lexemes_to_reject, ), # Lexemes to reject for GNU Modula-2 'm2pim+gm2': ( pim_lexemes_to_reject, ), # Lexemes to reject for p1 Modula-2 'm2iso+p1': ( iso_lexemes_to_reject, ), # Lexemes to reject for XDS Modula-2 'm2iso+xds': ( iso_lexemes_to_reject, ), }
# Reserved Words Database reserved_words_db = { # Reserved words for unknown dialect 'unknown': ( common_reserved_words, pim_additional_reserved_words, iso_additional_reserved_words, m2r10_additional_reserved_words, ),
# Reserved words for PIM Modula-2 'm2pim': ( common_reserved_words, pim_additional_reserved_words, ),
# Reserved words for Modula-2 R10 'm2iso': ( common_reserved_words, iso_additional_reserved_words, ),
# Reserved words for ISO Modula-2 'm2r10': ( common_reserved_words, m2r10_additional_reserved_words, ),
# Reserved words for Objective Modula-2 'objm2': ( common_reserved_words, m2r10_additional_reserved_words, objm2_additional_reserved_words, ),
# Reserved words for Aglet Modula-2 Extensions 'm2iso+aglet': ( common_reserved_words, iso_additional_reserved_words, aglet_additional_reserved_words, ),
# Reserved words for GNU Modula-2 Extensions 'm2pim+gm2': ( common_reserved_words, pim_additional_reserved_words, gm2_additional_reserved_words, ),
# Reserved words for p1 Modula-2 Extensions 'm2iso+p1': ( common_reserved_words, iso_additional_reserved_words, p1_additional_reserved_words, ),
# Reserved words for XDS Modula-2 Extensions 'm2iso+xds': ( common_reserved_words, iso_additional_reserved_words, xds_additional_reserved_words, ), }
# Builtins Database builtins_db = { # Builtins for unknown dialect 'unknown': ( common_builtins, pim_additional_builtins, iso_additional_builtins, m2r10_additional_builtins, ),
# Builtins for PIM Modula-2 'm2pim': ( common_builtins, pim_additional_builtins, ),
# Builtins for ISO Modula-2 'm2iso': ( common_builtins, iso_additional_builtins, ),
# Builtins for ISO Modula-2 'm2r10': ( common_builtins, m2r10_additional_builtins, ),
# Builtins for Objective Modula-2 'objm2': ( common_builtins, m2r10_additional_builtins, objm2_additional_builtins, ),
# Builtins for Aglet Modula-2 Extensions 'm2iso+aglet': ( common_builtins, iso_additional_builtins, aglet_additional_builtins, ),
# Builtins for GNU Modula-2 Extensions 'm2pim+gm2': ( common_builtins, pim_additional_builtins, gm2_additional_builtins, ),
# Builtins for p1 Modula-2 Extensions 'm2iso+p1': ( common_builtins, iso_additional_builtins, p1_additional_builtins, ),
# Builtins for XDS Modula-2 Extensions 'm2iso+xds': ( common_builtins, iso_additional_builtins, xds_additional_builtins, ), }
# Pseudo-Module Builtins Database pseudo_builtins_db = { # Builtins for unknown dialect 'unknown': ( common_pseudo_builtins, pim_additional_pseudo_builtins, iso_additional_pseudo_builtins, m2r10_additional_pseudo_builtins, ),
# Builtins for PIM Modula-2 'm2pim': ( common_pseudo_builtins, pim_additional_pseudo_builtins, ),
# Builtins for ISO Modula-2 'm2iso': ( common_pseudo_builtins, iso_additional_pseudo_builtins, ),
# Builtins for ISO Modula-2 'm2r10': ( common_pseudo_builtins, m2r10_additional_pseudo_builtins, ),
# Builtins for Objective Modula-2 'objm2': ( common_pseudo_builtins, m2r10_additional_pseudo_builtins, objm2_additional_pseudo_builtins, ),
# Builtins for Aglet Modula-2 Extensions 'm2iso+aglet': ( common_pseudo_builtins, iso_additional_pseudo_builtins, aglet_additional_pseudo_builtins, ),
# Builtins for GNU Modula-2 Extensions 'm2pim+gm2': ( common_pseudo_builtins, pim_additional_pseudo_builtins, gm2_additional_pseudo_builtins, ),
# Builtins for p1 Modula-2 Extensions 'm2iso+p1': ( common_pseudo_builtins, iso_additional_pseudo_builtins, p1_additional_pseudo_builtins, ),
# Builtins for XDS Modula-2 Extensions 'm2iso+xds': ( common_pseudo_builtins, iso_additional_pseudo_builtins, xds_additional_pseudo_builtins, ), }
# Standard Library ADTs Database stdlib_adts_db = { # Empty entry for unknown dialect 'unknown': ( # LEAVE THIS EMPTY ), # Standard Library ADTs for PIM Modula-2 'm2pim': ( # No first class library types ),
# Standard Library ADTs for ISO Modula-2 'm2iso': ( # No first class library types ),
# Standard Library ADTs for Modula-2 R10 'm2r10': ( m2r10_stdlib_adt_identifiers, ),
# Standard Library ADTs for Objective Modula-2 'objm2': ( m2r10_stdlib_adt_identifiers, ),
# Standard Library ADTs for Aglet Modula-2 'm2iso+aglet': ( # No first class library types ),
# Standard Library ADTs for GNU Modula-2 'm2pim+gm2': ( # No first class library types ),
# Standard Library ADTs for p1 Modula-2 'm2iso+p1': ( # No first class library types ),
# Standard Library ADTs for XDS Modula-2 'm2iso+xds': ( # No first class library types ), }
# Standard Library Modules Database stdlib_modules_db = { # Empty entry for unknown dialect 'unknown': ( # LEAVE THIS EMPTY ), # Standard Library Modules for PIM Modula-2 'm2pim': ( pim_stdlib_module_identifiers, ),
# Standard Library Modules for ISO Modula-2 'm2iso': ( iso_stdlib_module_identifiers, ),
# Standard Library Modules for Modula-2 R10 'm2r10': ( m2r10_stdlib_blueprint_identifiers, m2r10_stdlib_module_identifiers, m2r10_stdlib_adt_identifiers, ),
# Standard Library Modules for Objective Modula-2 'objm2': ( m2r10_stdlib_blueprint_identifiers, m2r10_stdlib_module_identifiers, ),
# Standard Library Modules for Aglet Modula-2 'm2iso+aglet': ( iso_stdlib_module_identifiers, ),
# Standard Library Modules for GNU Modula-2 'm2pim+gm2': ( pim_stdlib_module_identifiers, ),
# Standard Library Modules for p1 Modula-2 'm2iso+p1': ( iso_stdlib_module_identifiers, ),
# Standard Library Modules for XDS Modula-2 'm2iso+xds': ( iso_stdlib_module_identifiers, ), }
# Standard Library Types Database stdlib_types_db = { # Empty entry for unknown dialect 'unknown': ( # LEAVE THIS EMPTY ), # Standard Library Types for PIM Modula-2 'm2pim': ( pim_stdlib_type_identifiers, ),
# Standard Library Types for ISO Modula-2 'm2iso': ( iso_stdlib_type_identifiers, ),
# Standard Library Types for Modula-2 R10 'm2r10': ( m2r10_stdlib_type_identifiers, ),
# Standard Library Types for Objective Modula-2 'objm2': ( m2r10_stdlib_type_identifiers, ),
# Standard Library Types for Aglet Modula-2 'm2iso+aglet': ( iso_stdlib_type_identifiers, ),
# Standard Library Types for GNU Modula-2 'm2pim+gm2': ( pim_stdlib_type_identifiers, ),
# Standard Library Types for p1 Modula-2 'm2iso+p1': ( iso_stdlib_type_identifiers, ),
# Standard Library Types for XDS Modula-2 'm2iso+xds': ( iso_stdlib_type_identifiers, ), }
# Standard Library Procedures Database stdlib_procedures_db = { # Empty entry for unknown dialect 'unknown': ( # LEAVE THIS EMPTY ), # Standard Library Procedures for PIM Modula-2 'm2pim': ( pim_stdlib_proc_identifiers, ),
# Standard Library Procedures for ISO Modula-2 'm2iso': ( iso_stdlib_proc_identifiers, ),
# Standard Library Procedures for Modula-2 R10 'm2r10': ( m2r10_stdlib_proc_identifiers, ),
# Standard Library Procedures for Objective Modula-2 'objm2': ( m2r10_stdlib_proc_identifiers, ),
# Standard Library Procedures for Aglet Modula-2 'm2iso+aglet': ( iso_stdlib_proc_identifiers, ),
# Standard Library Procedures for GNU Modula-2 'm2pim+gm2': ( pim_stdlib_proc_identifiers, ),
# Standard Library Procedures for p1 Modula-2 'm2iso+p1': ( iso_stdlib_proc_identifiers, ),
# Standard Library Procedures for XDS Modula-2 'm2iso+xds': ( iso_stdlib_proc_identifiers, ), }
# Standard Library Variables Database stdlib_variables_db = { # Empty entry for unknown dialect 'unknown': ( # LEAVE THIS EMPTY ), # Standard Library Variables for PIM Modula-2 'm2pim': ( pim_stdlib_var_identifiers, ),
# Standard Library Variables for ISO Modula-2 'm2iso': ( iso_stdlib_var_identifiers, ),
# Standard Library Variables for Modula-2 R10 'm2r10': ( m2r10_stdlib_var_identifiers, ),
# Standard Library Variables for Objective Modula-2 'objm2': ( m2r10_stdlib_var_identifiers, ),
# Standard Library Variables for Aglet Modula-2 'm2iso+aglet': ( iso_stdlib_var_identifiers, ),
# Standard Library Variables for GNU Modula-2 'm2pim+gm2': ( pim_stdlib_var_identifiers, ),
# Standard Library Variables for p1 Modula-2 'm2iso+p1': ( iso_stdlib_var_identifiers, ),
# Standard Library Variables for XDS Modula-2 'm2iso+xds': ( iso_stdlib_var_identifiers, ), }
# Standard Library Constants Database stdlib_constants_db = { # Empty entry for unknown dialect 'unknown': ( # LEAVE THIS EMPTY ), # Standard Library Constants for PIM Modula-2 'm2pim': ( pim_stdlib_const_identifiers, ),
# Standard Library Constants for ISO Modula-2 'm2iso': ( iso_stdlib_const_identifiers, ),
# Standard Library Constants for Modula-2 R10 'm2r10': ( m2r10_stdlib_const_identifiers, ),
# Standard Library Constants for Objective Modula-2 'objm2': ( m2r10_stdlib_const_identifiers, ),
# Standard Library Constants for Aglet Modula-2 'm2iso+aglet': ( iso_stdlib_const_identifiers, ),
# Standard Library Constants for GNU Modula-2 'm2pim+gm2': ( pim_stdlib_const_identifiers, ),
# Standard Library Constants for p1 Modula-2 'm2iso+p1': ( iso_stdlib_const_identifiers, ),
# Standard Library Constants for XDS Modula-2 'm2iso+xds': ( iso_stdlib_const_identifiers, ), }
# M e t h o d s
# initialise a lexer instance def __init__(self, **options): # # check dialect options # dialects = get_list_opt(options, 'dialect', []) # for dialect_option in dialects: if dialect_option in self.dialects[1:-1]: # valid dialect option found self.set_dialect(dialect_option) break # # Fallback Mode (DEFAULT) else: # no valid dialect option self.set_dialect('unknown') # self.dialect_set_by_tag = False # # check style options # styles = get_list_opt(options, 'style', []) # # use lowercase mode for Algol style if 'algol' in styles or 'algol_nu' in styles: self.algol_publication_mode = True else: self.algol_publication_mode = False # # Check option flags # self.treat_stdlib_adts_as_builtins = get_bool_opt( options, 'treat_stdlib_adts_as_builtins', True) # # call superclass initialiser RegexLexer.__init__(self, **options)
# Set lexer to a specified dialect def set_dialect(self, dialect_id): # # if __debug__: # print 'entered set_dialect with arg: ', dialect_id # # check dialect name against known dialects if dialect_id not in self.dialects: dialect = 'unknown' # default else: dialect = dialect_id # # compose lexemes to reject set lexemes_to_reject_set = set() # add each list of reject lexemes for this dialect for list in self.lexemes_to_reject_db[dialect]: lexemes_to_reject_set.update(set(list)) # # compose reserved words set reswords_set = set() # add each list of reserved words for this dialect for list in self.reserved_words_db[dialect]: reswords_set.update(set(list)) # # compose builtins set builtins_set = set() # add each list of builtins for this dialect excluding reserved words for list in self.builtins_db[dialect]: builtins_set.update(set(list).difference(reswords_set)) # # compose pseudo-builtins set pseudo_builtins_set = set() # add each list of builtins for this dialect excluding reserved words for list in self.pseudo_builtins_db[dialect]: pseudo_builtins_set.update(set(list).difference(reswords_set)) # # compose ADTs set adts_set = set() # add each list of ADTs for this dialect excluding reserved words for list in self.stdlib_adts_db[dialect]: adts_set.update(set(list).difference(reswords_set)) # # compose modules set modules_set = set() # add each list of builtins for this dialect excluding builtins for list in self.stdlib_modules_db[dialect]: modules_set.update(set(list).difference(builtins_set)) # # compose types set types_set = set() # add each list of types for this dialect excluding builtins for list in self.stdlib_types_db[dialect]: types_set.update(set(list).difference(builtins_set)) # # compose procedures set procedures_set = set() # add each list of procedures for this dialect excluding builtins for list in self.stdlib_procedures_db[dialect]: procedures_set.update(set(list).difference(builtins_set)) # # compose variables set variables_set = set() # add each list of variables for this dialect excluding builtins for list in self.stdlib_variables_db[dialect]: variables_set.update(set(list).difference(builtins_set)) # # compose constants set constants_set = set() # add each list of constants for this dialect excluding builtins for list in self.stdlib_constants_db[dialect]: constants_set.update(set(list).difference(builtins_set)) # # update lexer state self.dialect = dialect self.lexemes_to_reject = lexemes_to_reject_set self.reserved_words = reswords_set self.builtins = builtins_set self.pseudo_builtins = pseudo_builtins_set self.adts = adts_set self.modules = modules_set self.types = types_set self.procedures = procedures_set self.variables = variables_set self.constants = constants_set # # if __debug__: # print 'exiting set_dialect' # print ' self.dialect: ', self.dialect # print ' self.lexemes_to_reject: ', self.lexemes_to_reject # print ' self.reserved_words: ', self.reserved_words # print ' self.builtins: ', self.builtins # print ' self.pseudo_builtins: ', self.pseudo_builtins # print ' self.adts: ', self.adts # print ' self.modules: ', self.modules # print ' self.types: ', self.types # print ' self.procedures: ', self.procedures # print ' self.variables: ', self.variables # print ' self.types: ', self.types # print ' self.constants: ', self.constants
# Extracts a dialect name from a dialect tag comment string and checks # the extracted name against known dialects. If a match is found, the # matching name is returned, otherwise dialect id 'unknown' is returned def get_dialect_from_dialect_tag(self, dialect_tag): # # if __debug__: # print 'entered get_dialect_from_dialect_tag with arg: ', dialect_tag # # constants left_tag_delim = '(*!' right_tag_delim = '*)' left_tag_delim_len = len(left_tag_delim) right_tag_delim_len = len(right_tag_delim) indicator_start = left_tag_delim_len indicator_end = -(right_tag_delim_len) # # check comment string for dialect indicator if len(dialect_tag) > (left_tag_delim_len + right_tag_delim_len) \ and dialect_tag.startswith(left_tag_delim) \ and dialect_tag.endswith(right_tag_delim): # # if __debug__: # print 'dialect tag found' # # extract dialect indicator indicator = dialect_tag[indicator_start:indicator_end] # # if __debug__: # print 'extracted: ', indicator # # check against known dialects for index in range(1, len(self.dialects)): # # if __debug__: # print 'dialects[', index, ']: ', self.dialects[index] # if indicator == self.dialects[index]: # # if __debug__: # print 'matching dialect found' # # indicator matches known dialect return indicator else: # indicator does not match any dialect return 'unknown' # default else: # invalid indicator string return 'unknown' # default
# intercept the token stream, modify token attributes and return them def get_tokens_unprocessed(self, text): for index, token, value in RegexLexer.get_tokens_unprocessed(self, text): # # check for dialect tag if dialect has not been set by tag if not self.dialect_set_by_tag and token == Comment.Special: indicated_dialect = self.get_dialect_from_dialect_tag(value) if indicated_dialect != 'unknown': # token is a dialect indicator # reset reserved words and builtins self.set_dialect(indicated_dialect) self.dialect_set_by_tag = True # # check for reserved words, predefined and stdlib identifiers if token is Name: if value in self.reserved_words: token = Keyword.Reserved if self.algol_publication_mode: value = value.lower() # elif value in self.builtins: token = Name.Builtin if self.algol_publication_mode: value = value.lower() # elif value in self.pseudo_builtins: token = Name.Builtin.Pseudo if self.algol_publication_mode: value = value.lower() # elif value in self.adts: if not self.treat_stdlib_adts_as_builtins: token = Name.Namespace else: token = Name.Builtin.Pseudo if self.algol_publication_mode: value = value.lower() # elif value in self.modules: token = Name.Namespace # elif value in self.types: token = Name.Class # elif value in self.procedures: token = Name.Function # elif value in self.variables: token = Name.Variable # elif value in self.constants: token = Name.Constant # elif token in Number: # # mark prefix number literals as error for PIM and ISO dialects if self.dialect not in ('unknown', 'm2r10', 'objm2'): if "'" in value or value[0:2] in ('0b', '0x', '0u'): token = Error # elif self.dialect in ('m2r10', 'objm2'): # mark base-8 number literals as errors for M2 R10 and ObjM2 if token is Number.Oct: token = Error # mark suffix base-16 literals as errors for M2 R10 and ObjM2 elif token is Number.Hex and 'H' in value: token = Error # mark real numbers with E as errors for M2 R10 and ObjM2 elif token is Number.Float and 'E' in value: token = Error # elif token in Comment: # # mark single line comment as error for PIM and ISO dialects if token is Comment.Single: if self.dialect not in ('unknown', 'm2r10', 'objm2'): token = Error # if token is Comment.Preproc: # mark ISO pragma as error for PIM dialects if value.startswith('<*') and \ self.dialect.startswith('m2pim'): token = Error # mark PIM pragma as comment for other dialects elif value.startswith('(*$') and \ self.dialect != 'unknown' and \ not self.dialect.startswith('m2pim'): token = Comment.Multiline # else: # token is neither Name nor Comment # # mark lexemes matching the dialect's error token set as errors if value in self.lexemes_to_reject: token = Error # # substitute lexemes when in Algol mode if self.algol_publication_mode: if value == '#': value = '≠' elif value == '<=': value = '≤' elif value == '>=': value = '≥' elif value == '==': value = '≡' elif value == '*.': value = '•'
# return result yield index, token, value
def analyse_text(text): """It's Pascal-like, but does not use FUNCTION -- uses PROCEDURE instead."""
# Check if this looks like Pascal, if not, bail out early if not ('(*' in text and '*)' in text and ':=' in text): return
result = 0 # Procedure is in Modula2 if re.search(r'\bPROCEDURE\b', text): result += 0.6
# FUNCTION is only valid in Pascal, but not in Modula2 if re.search(r'\bFUNCTION\b', text): result = 0.0
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707""" pygments.lexers.mojo ~~~~~~~~~~~~~~~~~~~~
Lexers for Mojo and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import keyword
from pygments import unistring as unifrom pygments.lexer import ( RegexLexer, bygroups, combined, default, include, this, using, words,)from pygments.token import ( Comment, # Error, Keyword, Name, Number, Operator, Punctuation, String, Text, Whitespace,)from pygments.util import shebang_matches
__all__ = ["MojoLexer"]
class MojoLexer(RegexLexer): """ For Mojo source code (version 24.2.1). """
name = "Mojo" url = "https://docs.modular.com/mojo/" aliases = ["mojo", "🔥"] filenames = [ "*.mojo", "*.🔥", ] mimetypes = [ "text/x-mojo", "application/x-mojo", ] version_added = "2.18"
uni_name = f"[{uni.xid_start}][{uni.xid_continue}]*"
def innerstring_rules(ttype): return [ # the old style '%s' % (...) string formatting (still valid in Py3) ( r"%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?" "[hlL]?[E-GXc-giorsaux%]", String.Interpol, ), # the new style '{}'.format(...) string formatting ( r"\{" r"((\w+)((\.\w+)|(\[[^\]]+\]))*)?" # field name r"(\![sra])?" # conversion r"(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?" r"\}", String.Interpol, ), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"%{\n]+', ttype), (r'[\'"\\]', ttype), # unhandled string formatting sign (r"%|(\{{1,2})", ttype), # newlines are an error (use "nl" state) ]
def fstring_rules(ttype): return [ # Assuming that a '}' is the closing brace after format specifier. # Sadly, this means that we won't detect syntax error. But it's # more important to parse correct syntax correctly, than to # highlight invalid syntax. (r"\}", String.Interpol), (r"\{", String.Interpol, "expr-inside-fstring"), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"{}\n]+', ttype), (r'[\'"\\]', ttype), # newlines are an error (use "nl" state) ]
tokens = { "root": [ (r"\s+", Whitespace), ( r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")', bygroups(Whitespace, String.Affix, String.Doc), ), ( r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')", bygroups(Whitespace, String.Affix, String.Doc), ), (r"\A#!.+$", Comment.Hashbang), (r"#.*$", Comment.Single), (r"\\\n", Whitespace), (r"\\", Whitespace), include("keywords"), include("soft-keywords"), # In the original PR, all the below here used ((?:\s|\\\s)+) to # designate whitespace, but I can't find any example of this being # needed in the example file, so we're replacing it with `\s+`. ( r"(alias)(\s+)", bygroups(Keyword, Whitespace), "varname", # TODO varname the right fit? ), (r"(var)(\s+)", bygroups(Keyword, Whitespace), "varname"), (r"(def)(\s+)", bygroups(Keyword, Whitespace), "funcname"), (r"(fn)(\s+)", bygroups(Keyword, Whitespace), "funcname"), ( r"(class)(\s+)", bygroups(Keyword, Whitespace), "classname", ), # not implemented yet (r"(struct)(\s+)", bygroups(Keyword, Whitespace), "structname"), (r"(trait)(\s+)", bygroups(Keyword, Whitespace), "structname"), (r"(from)(\s+)", bygroups(Keyword.Namespace, Whitespace), "fromimport"), (r"(import)(\s+)", bygroups(Keyword.Namespace, Whitespace), "import"), include("expr"), ], "expr": [ # raw f-strings ( '(?i)(rf|fr)(""")', bygroups(String.Affix, String.Double), combined("rfstringescape", "tdqf"), ), ( "(?i)(rf|fr)(''')", bygroups(String.Affix, String.Single), combined("rfstringescape", "tsqf"), ), ( '(?i)(rf|fr)(")', bygroups(String.Affix, String.Double), combined("rfstringescape", "dqf"), ), ( "(?i)(rf|fr)(')", bygroups(String.Affix, String.Single), combined("rfstringescape", "sqf"), ), # non-raw f-strings ( '([fF])(""")', bygroups(String.Affix, String.Double), combined("fstringescape", "tdqf"), ), ( "([fF])(''')", bygroups(String.Affix, String.Single), combined("fstringescape", "tsqf"), ), ( '([fF])(")', bygroups(String.Affix, String.Double), combined("fstringescape", "dqf"), ), ( "([fF])(')", bygroups(String.Affix, String.Single), combined("fstringescape", "sqf"), ), # raw bytes and strings ('(?i)(rb|br|r)(""")', bygroups(String.Affix, String.Double), "tdqs"), ("(?i)(rb|br|r)(''')", bygroups(String.Affix, String.Single), "tsqs"), ('(?i)(rb|br|r)(")', bygroups(String.Affix, String.Double), "dqs"), ("(?i)(rb|br|r)(')", bygroups(String.Affix, String.Single), "sqs"), # non-raw strings ( '([uU]?)(""")', bygroups(String.Affix, String.Double), combined("stringescape", "tdqs"), ), ( "([uU]?)(''')", bygroups(String.Affix, String.Single), combined("stringescape", "tsqs"), ), ( '([uU]?)(")', bygroups(String.Affix, String.Double), combined("stringescape", "dqs"), ), ( "([uU]?)(')", bygroups(String.Affix, String.Single), combined("stringescape", "sqs"), ), # non-raw bytes ( '([bB])(""")', bygroups(String.Affix, String.Double), combined("bytesescape", "tdqs"), ), ( "([bB])(''')", bygroups(String.Affix, String.Single), combined("bytesescape", "tsqs"), ), ( '([bB])(")', bygroups(String.Affix, String.Double), combined("bytesescape", "dqs"), ), ( "([bB])(')", bygroups(String.Affix, String.Single), combined("bytesescape", "sqs"), ), (r"[^\S\n]+", Text), include("numbers"), (r"!=|==|<<|>>|:=|[-~+/*%=<>&^|.]", Operator), (r"([]{}:\(\),;[])+", Punctuation), (r"(in|is|and|or|not)\b", Operator.Word), include("expr-keywords"), include("builtins"), include("magicfuncs"), include("magicvars"), include("name"), ], "expr-inside-fstring": [ (r"[{([]", Punctuation, "expr-inside-fstring-inner"), # without format specifier ( r"(=\s*)?" # debug (https://bugs.python.org/issue36817) r"(\![sraf])?" # conversion r"\}", String.Interpol, "#pop", ), # with format specifier # we'll catch the remaining '}' in the outer scope ( r"(=\s*)?" # debug (https://bugs.python.org/issue36817) r"(\![sraf])?" # conversion r":", String.Interpol, "#pop", ), (r"\s+", Whitespace), # allow new lines include("expr"), ], "expr-inside-fstring-inner": [ (r"[{([]", Punctuation, "expr-inside-fstring-inner"), (r"[])}]", Punctuation, "#pop"), (r"\s+", Whitespace), # allow new lines include("expr"), ], "expr-keywords": [ # Based on https://docs.python.org/3/reference/expressions.html ( words( ( "async for", # TODO https://docs.modular.com/mojo/roadmap#no-async-for-or-async-with "async with", # TODO https://docs.modular.com/mojo/roadmap#no-async-for-or-async-with "await", "else", "for", "if", "lambda", "yield", "yield from", ), suffix=r"\b", ), Keyword, ), (words(("True", "False", "None"), suffix=r"\b"), Keyword.Constant), ], "keywords": [ ( words( ( "assert", "async", "await", "borrowed", "break", "continue", "del", "elif", "else", "except", "finally", "for", "global", "if", "lambda", "pass", "raise", "nonlocal", "return", "try", "while", "yield", "yield from", "as", "with", ), suffix=r"\b", ), Keyword, ), (words(("True", "False", "None"), suffix=r"\b"), Keyword.Constant), ], "soft-keywords": [ # `match`, `case` and `_` soft keywords ( r"(^[ \t]*)" # at beginning of line + possible indentation r"(match|case)\b" # a possible keyword r"(?![ \t]*(?:" # not followed by... r"[:,;=^&|@~)\]}]|(?:" + # characters and keywords that mean this isn't # pattern matching (but None/True/False is ok) r"|".join(k for k in keyword.kwlist if k[0].islower()) + r")\b))", bygroups(Whitespace, Keyword), "soft-keywords-inner", ), ], "soft-keywords-inner": [ # optional `_` keyword (r"(\s+)([^\n_]*)(_\b)", bygroups(Whitespace, using(this), Keyword)), default("#pop"), ], "builtins": [ ( words( ( "__import__", "abs", "aiter", "all", "any", "bin", "bool", "bytearray", "breakpoint", "bytes", "callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr", "hash", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow", "print", "property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", # Mojo builtin types: https://docs.modular.com/mojo/stdlib/builtin/ "AnyType", "Coroutine", "DType", "Error", "Int", "List", "ListLiteral", "Scalar", "Int8", "UInt8", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "BFloat16", "Float16", "Float32", "Float64", "SIMD", "String", "Tensor", "Tuple", "Movable", "Copyable", "CollectionElement", ), prefix=r"(?<!\.)", suffix=r"\b", ), Name.Builtin, ), (r"(?<!\.)(self|Ellipsis|NotImplemented|cls)\b", Name.Builtin.Pseudo), ( words( ("Error",), prefix=r"(?<!\.)", suffix=r"\b", ), Name.Exception, ), ], "magicfuncs": [ ( words( ( "__abs__", "__add__", "__aenter__", "__aexit__", "__aiter__", "__and__", "__anext__", "__await__", "__bool__", "__bytes__", "__call__", "__complex__", "__contains__", "__del__", "__delattr__", "__delete__", "__delitem__", "__dir__", "__divmod__", "__enter__", "__eq__", "__exit__", "__float__", "__floordiv__", "__format__", "__ge__", "__get__", "__getattr__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__iand__", "__ifloordiv__", "__ilshift__", "__imatmul__", "__imod__", "__imul__", "__index__", "__init__", "__instancecheck__", "__int__", "__invert__", "__ior__", "__ipow__", "__irshift__", "__isub__", "__iter__", "__itruediv__", "__ixor__", "__le__", "__len__", "__length_hint__", "__lshift__", "__lt__", "__matmul__", "__missing__", "__mod__", "__mul__", "__ne__", "__neg__", "__new__", "__next__", "__or__", "__pos__", "__pow__", "__prepare__", "__radd__", "__rand__", "__rdivmod__", "__repr__", "__reversed__", "__rfloordiv__", "__rlshift__", "__rmatmul__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__set__", "__setattr__", "__setitem__", "__str__", "__sub__", "__subclasscheck__", "__truediv__", "__xor__", ), suffix=r"\b", ), Name.Function.Magic, ), ], "magicvars": [ ( words( ( "__annotations__", "__bases__", "__class__", "__closure__", "__code__", "__defaults__", "__dict__", "__doc__", "__file__", "__func__", "__globals__", "__kwdefaults__", "__module__", "__mro__", "__name__", "__objclass__", "__qualname__", "__self__", "__slots__", "__weakref__", ), suffix=r"\b", ), Name.Variable.Magic, ), ], "numbers": [ ( r"(\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|(?:\d(?:_?\d)*)?\.\d(?:_?\d)*)" r"([eE][+-]?\d(?:_?\d)*)?", Number.Float, ), (r"\d(?:_?\d)*[eE][+-]?\d(?:_?\d)*j?", Number.Float), (r"0[oO](?:_?[0-7])+", Number.Oct), (r"0[bB](?:_?[01])+", Number.Bin), (r"0[xX](?:_?[a-fA-F0-9])+", Number.Hex), (r"\d(?:_?\d)*", Number.Integer), ], "name": [ (r"@" + uni_name, Name.Decorator), (r"@", Operator), # new matrix multiplication operator (uni_name, Name), ], "varname": [ (uni_name, Name.Variable, "#pop"), ], "funcname": [ include("magicfuncs"), (uni_name, Name.Function, "#pop"), default("#pop"), ], "classname": [ (uni_name, Name.Class, "#pop"), ], "structname": [ (uni_name, Name.Struct, "#pop"), ], "import": [ (r"(\s+)(as)(\s+)", bygroups(Whitespace, Keyword, Whitespace)), (r"\.", Name.Namespace), (uni_name, Name.Namespace), (r"(\s*)(,)(\s*)", bygroups(Whitespace, Operator, Whitespace)), default("#pop"), # all else: go back ], "fromimport": [ (r"(\s+)(import)\b", bygroups(Whitespace, Keyword.Namespace), "#pop"), (r"\.", Name.Namespace), # if None occurs here, it's "raise x from None", since None can # never be a module name (r"None\b", Keyword.Constant, "#pop"), (uni_name, Name.Namespace), default("#pop"), ], "rfstringescape": [ (r"\{\{", String.Escape), (r"\}\}", String.Escape), ], "fstringescape": [ include("rfstringescape"), include("stringescape"), ], "bytesescape": [ (r'\\([\\abfnrtv"\']|\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], "stringescape": [ (r"\\(N\{.*?\}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})", String.Escape), include("bytesescape"), ], "fstrings-single": fstring_rules(String.Single), "fstrings-double": fstring_rules(String.Double), "strings-single": innerstring_rules(String.Single), "strings-double": innerstring_rules(String.Double), "dqf": [ (r'"', String.Double, "#pop"), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include("fstrings-double"), ], "sqf": [ (r"'", String.Single, "#pop"), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include("fstrings-single"), ], "dqs": [ (r'"', String.Double, "#pop"), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include("strings-double"), ], "sqs": [ (r"'", String.Single, "#pop"), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include("strings-single"), ], "tdqf": [ (r'"""', String.Double, "#pop"), include("fstrings-double"), (r"\n", String.Double), ], "tsqf": [ (r"'''", String.Single, "#pop"), include("fstrings-single"), (r"\n", String.Single), ], "tdqs": [ (r'"""', String.Double, "#pop"), include("strings-double"), (r"\n", String.Double), ], "tsqs": [ (r"'''", String.Single, "#pop"), include("strings-single"), (r"\n", String.Single), ], }
def analyse_text(text): # TODO supported? if shebang_matches(text, r"mojo?"): return 1.0 if "import " in text[:1000]: return 0.9 return 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203""" pygments.lexers.monte ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Monte programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.token import Comment, Error, Keyword, Name, Number, Operator, \ Punctuation, String, Whitespacefrom pygments.lexer import RegexLexer, include, words
__all__ = ['MonteLexer']
# `var` handled separately# `interface` handled separately_declarations = ['bind', 'def', 'fn', 'object']_methods = ['method', 'to']_keywords = [ 'as', 'break', 'catch', 'continue', 'else', 'escape', 'exit', 'exports', 'extends', 'finally', 'for', 'guards', 'if', 'implements', 'import', 'in', 'match', 'meta', 'pass', 'return', 'switch', 'try', 'via', 'when', 'while',]_operators = [ # Unary '~', '!', # Binary '+', '-', '*', '/', '%', '**', '&', '|', '^', '<<', '>>', # Binary augmented '+=', '-=', '*=', '/=', '%=', '**=', '&=', '|=', '^=', '<<=', '>>=', # Comparison '==', '!=', '<', '<=', '>', '>=', '<=>', # Patterns and assignment ':=', '?', '=~', '!~', '=>', # Calls and sends '.', '<-', '->',]_escape_pattern = ( r'(?:\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|' r'\\["\'\\bftnr])')# _char = _escape_chars + [('.', String.Char)]_identifier = r'[_a-zA-Z]\w*'
_constants = [ # Void constants 'null', # Bool constants 'false', 'true', # Double constants 'Infinity', 'NaN', # Special objects 'M', 'Ref', 'throw', 'traceln',]
_guards = [ 'Any', 'Binding', 'Bool', 'Bytes', 'Char', 'DeepFrozen', 'Double', 'Empty', 'Int', 'List', 'Map', 'Near', 'NullOk', 'Same', 'Selfless', 'Set', 'Str', 'SubrangeGuard', 'Transparent', 'Void',]
_safeScope = [ '_accumulateList', '_accumulateMap', '_auditedBy', '_bind', '_booleanFlow', '_comparer', '_equalizer', '_iterForever', '_loop', '_makeBytes', '_makeDouble', '_makeFinalSlot', '_makeInt', '_makeList', '_makeMap', '_makeMessageDesc', '_makeOrderedSpace', '_makeParamDesc', '_makeProtocolDesc', '_makeSourceSpan', '_makeString', '_makeVarSlot', '_makeVerbFacet', '_mapExtract', '_matchSame', '_quasiMatcher', '_slotToBinding', '_splitList', '_suchThat', '_switchFailed', '_validateFor', 'b__quasiParser', 'eval', 'import', 'm__quasiParser', 'makeBrandPair', 'makeLazySlot', 'safeScope', 'simple__quasiParser',]
class MonteLexer(RegexLexer): """ Lexer for the Monte programming language. """ name = 'Monte' url = 'https://monte.readthedocs.io/' aliases = ['monte'] filenames = ['*.mt'] version_added = '2.2'
tokens = { 'root': [ # Comments (r'#[^\n]*\n', Comment),
# Docstrings # Apologies for the non-greedy matcher here. (r'/\*\*.*?\*/', String.Doc),
# `var` declarations (r'\bvar\b', Keyword.Declaration, 'var'),
# `interface` declarations (r'\binterface\b', Keyword.Declaration, 'interface'),
# method declarations (words(_methods, prefix='\\b', suffix='\\b'), Keyword, 'method'),
# All other declarations (words(_declarations, prefix='\\b', suffix='\\b'), Keyword.Declaration),
# Keywords (words(_keywords, prefix='\\b', suffix='\\b'), Keyword),
# Literals ('[+-]?0x[_0-9a-fA-F]+', Number.Hex), (r'[+-]?[_0-9]+\.[_0-9]*([eE][+-]?[_0-9]+)?', Number.Float), ('[+-]?[_0-9]+', Number.Integer), ("'", String.Double, 'char'), ('"', String.Double, 'string'),
# Quasiliterals ('`', String.Backtick, 'ql'),
# Operators (words(_operators), Operator),
# Verb operators (_identifier + '=', Operator.Word),
# Safe scope constants (words(_constants, prefix='\\b', suffix='\\b'), Keyword.Pseudo),
# Safe scope guards (words(_guards, prefix='\\b', suffix='\\b'), Keyword.Type),
# All other safe scope names (words(_safeScope, prefix='\\b', suffix='\\b'), Name.Builtin),
# Identifiers (_identifier, Name),
# Punctuation (r'\(|\)|\{|\}|\[|\]|:|,', Punctuation),
# Whitespace (' +', Whitespace),
# Definite lexer errors ('=', Error), ], 'char': [ # It is definitely an error to have a char of width == 0. ("'", Error, 'root'), (_escape_pattern, String.Escape, 'charEnd'), ('.', String.Char, 'charEnd'), ], 'charEnd': [ ("'", String.Char, '#pop:2'), # It is definitely an error to have a char of width > 1. ('.', Error), ], # The state of things coming into an interface. 'interface': [ (' +', Whitespace), (_identifier, Name.Class, '#pop'), include('root'), ], # The state of things coming into a method. 'method': [ (' +', Whitespace), (_identifier, Name.Function, '#pop'), include('root'), ], 'string': [ ('"', String.Double, 'root'), (_escape_pattern, String.Escape), (r'\n', String.Double), ('.', String.Double), ], 'ql': [ ('`', String.Backtick, 'root'), (r'\$' + _escape_pattern, String.Escape), (r'\$\$', String.Escape), (r'@@', String.Escape), (r'\$\{', String.Interpol, 'qlNest'), (r'@\{', String.Interpol, 'qlNest'), (r'\$' + _identifier, Name), ('@' + _identifier, Name), ('.', String.Backtick), ], 'qlNest': [ (r'\}', String.Interpol, '#pop'), include('root'), ], # The state of things immediately following `var`. 'var': [ (' +', Whitespace), (_identifier, Name.Variable, '#pop'), include('root'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447""" pygments.lexers.mosel ~~~~~~~~~~~~~~~~~~~~~
Lexers for the mosel language. http://www.fico.com/en/products/fico-xpress-optimization
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['MoselLexer']
FUNCTIONS = ( # core functions '_', 'abs', 'arctan', 'asproc', 'assert', 'bitflip', 'bitneg', 'bitset', 'bitshift', 'bittest', 'bitval', 'ceil', 'cos', 'create', 'currentdate', 'currenttime', 'cutelt', 'cutfirst', 'cuthead', 'cutlast', 'cuttail', 'datablock', 'delcell', 'exists', 'exit', 'exp', 'exportprob', 'fclose', 'fflush', 'finalize', 'findfirst', 'findlast', 'floor', 'fopen', 'fselect', 'fskipline', 'fwrite', 'fwrite_', 'fwriteln', 'fwriteln_', 'getact', 'getcoeff', 'getcoeffs', 'getdual', 'getelt', 'getfid', 'getfirst', 'getfname', 'gethead', 'getlast', 'getobjval', 'getparam', 'getrcost', 'getreadcnt', 'getreverse', 'getsize', 'getslack', 'getsol', 'gettail', 'gettype', 'getvars', 'isdynamic', 'iseof', 'isfinite', 'ishidden', 'isinf', 'isnan', 'isodd', 'ln', 'localsetparam', 'log', 'makesos1', 'makesos2', 'maxlist', 'memoryuse', 'minlist', 'newmuid', 'publish', 'random', 'read', 'readln', 'reset', 'restoreparam', 'reverse', 'round', 'setcoeff', 'sethidden', 'setioerr', 'setmatherr', 'setname', 'setparam', 'setrandseed', 'setrange', 'settype', 'sin', 'splithead', 'splittail', 'sqrt', 'strfmt', 'substr', 'timestamp', 'unpublish', 'versionnum', 'versionstr', 'write', 'write_', 'writeln', 'writeln_',
# mosel exam mmxprs | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u 'addcut', 'addcuts', 'addmipsol', 'basisstability', 'calcsolinfo', 'clearmipdir', 'clearmodcut', 'command', 'copysoltoinit', 'crossoverlpsol', 'defdelayedrows', 'defsecurevecs', 'delcuts', 'dropcuts', 'estimatemarginals', 'fixglobal', 'flushmsgq', 'getbstat', 'getcnlist', 'getcplist', 'getdualray', 'getiis', 'getiissense', 'getiistype', 'getinfcause', 'getinfeas', 'getlb', 'getlct', 'getleft', 'getloadedlinctrs', 'getloadedmpvars', 'getname', 'getprimalray', 'getprobstat', 'getrange', 'getright', 'getsensrng', 'getsize', 'getsol', 'gettype', 'getub', 'getvars', 'gety', 'hasfeature', 'implies', 'indicator', 'initglobal', 'ishidden', 'isiisvalid', 'isintegral', 'loadbasis', 'loadcuts', 'loadlpsol', 'loadmipsol', 'loadprob', 'maximise', 'maximize', 'minimise', 'minimize', 'postsolve', 'readbasis', 'readdirs', 'readsol', 'refinemipsol', 'rejectintsol', 'repairinfeas', 'repairinfeas_deprec', 'resetbasis', 'resetiis', 'resetsol', 'savebasis', 'savemipsol', 'savesol', 'savestate', 'selectsol', 'setarchconsistency', 'setbstat', 'setcallback', 'setcbcutoff', 'setgndata', 'sethidden', 'setlb', 'setmipdir', 'setmodcut', 'setsol', 'setub', 'setucbdata', 'stopoptimise', 'stopoptimize', 'storecut', 'storecuts', 'unloadprob', 'uselastbarsol', 'writebasis', 'writedirs', 'writeprob', 'writesol', 'xor', 'xprs_addctr', 'xprs_addindic',
# mosel exam mmsystem | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u 'addmonths', 'copytext', 'cuttext', 'deltext', 'endswith', 'erase', 'expandpath', 'fcopy', 'fdelete', 'findfiles', 'findtext', 'fmove', 'formattext', 'getasnumber', 'getchar', 'getcwd', 'getdate', 'getday', 'getdaynum', 'getdays', 'getdirsep', 'getdsoparam', 'getendparse', 'getenv', 'getfsize', 'getfstat', 'getftime', 'gethour', 'getminute', 'getmonth', 'getmsec', 'getoserrmsg', 'getoserror', 'getpathsep', 'getqtype', 'getsecond', 'getsepchar', 'getsize', 'getstart', 'getsucc', 'getsysinfo', 'getsysstat', 'gettime', 'gettmpdir', 'gettrim', 'getweekday', 'getyear', 'inserttext', 'isvalid', 'jointext', 'makedir', 'makepath', 'newtar', 'newzip', 'nextfield', 'openpipe', 'parseextn', 'parseint', 'parsereal', 'parsetext', 'pastetext', 'pathmatch', 'pathsplit', 'qsort', 'quote', 'readtextline', 'regmatch', 'regreplace', 'removedir', 'removefiles', 'setchar', 'setdate', 'setday', 'setdsoparam', 'setendparse', 'setenv', 'sethour', 'setminute', 'setmonth', 'setmsec', 'setoserror', 'setqtype', 'setsecond', 'setsepchar', 'setstart', 'setsucc', 'settime', 'settrim', 'setyear', 'sleep', 'splittext', 'startswith', 'system', 'tarlist', 'textfmt', 'tolower', 'toupper', 'trim', 'untar', 'unzip', 'ziplist',
# mosel exam mmjobs | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u 'canceltimer', 'clearaliases', 'compile', 'connect', 'detach', 'disconnect', 'dropnextevent', 'findxsrvs', 'getaliases', 'getannidents', 'getannotations', 'getbanner', 'getclass', 'getdsoprop', 'getdsopropnum', 'getexitcode', 'getfromgid', 'getfromid', 'getfromuid', 'getgid', 'gethostalias', 'getid', 'getmodprop', 'getmodpropnum', 'getnextevent', 'getnode', 'getrmtid', 'getstatus', 'getsysinfo', 'gettimer', 'getuid', 'getvalue', 'isqueueempty', 'load', 'nullevent', 'peeknextevent', 'resetmodpar', 'run', 'send', 'setcontrol', 'setdefstream', 'setgid', 'sethostalias', 'setmodpar', 'settimer', 'setuid', 'setworkdir', 'stop', 'unload', 'wait', 'waitexpired', 'waitfor', 'waitforend',)
class MoselLexer(RegexLexer): """ For the Mosel optimization language. """ name = 'Mosel' aliases = ['mosel'] filenames = ['*.mos'] url = 'https://www.fico.com/fico-xpress-optimization/docs/latest/mosel/mosel_lang/dhtml/moselreflang.html' version_added = '2.6'
tokens = { 'root': [ (r'\n', Text), (r'\s+', Text.Whitespace), (r'!.*?\n', Comment.Single), (r'\(!(.|\n)*?!\)', Comment.Multiline), (words(( 'and', 'as', 'break', 'case', 'count', 'declarations', 'do', 'dynamic', 'elif', 'else', 'end-', 'end', 'evaluation', 'false', 'forall', 'forward', 'from', 'function', 'hashmap', 'if', 'imports', 'include', 'initialisations', 'initializations', 'inter', 'max', 'min', 'model', 'namespace', 'next', 'not', 'nsgroup', 'nssearch', 'of', 'options', 'or', 'package', 'parameters', 'procedure', 'public', 'prod', 'record', 'repeat', 'requirements', 'return', 'sum', 'then', 'to', 'true', 'union', 'until', 'uses', 'version', 'while', 'with'), prefix=r'\b', suffix=r'\b'), Keyword.Builtin), (words(( 'range', 'array', 'set', 'list', 'mpvar', 'mpproblem', 'linctr', 'nlctr', 'integer', 'string', 'real', 'boolean', 'text', 'time', 'date', 'datetime', 'returned', 'Model', 'Mosel', 'counter', 'xmldoc', 'is_sos1', 'is_sos2', 'is_integer', 'is_binary', 'is_continuous', 'is_free', 'is_semcont', 'is_semint', 'is_partint'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (r'(\+|\-|\*|/|=|<=|>=|\||\^|<|>|<>|\.\.|\.|:=|::|:|in|mod|div)', Operator), (r'[()\[\]{},;]+', Punctuation), (words(FUNCTIONS, prefix=r'\b', suffix=r'\b'), Name.Function), (r'(\d+\.(?!\.)\d*|\.(?!.)\d+)([eE][+-]?\d+)?', Number.Float), (r'\d+([eE][+-]?\d+)?', Number.Integer), (r'[+-]?Infinity', Number.Integer), (r'0[xX][0-9a-fA-F]+', Number), (r'"', String.Double, 'double_quote'), (r'\'', String.Single, 'single_quote'), (r'(\w+|(\.(?!\.)))', Text), ], 'single_quote': [ (r'\'', String.Single, '#pop'), (r'[^\']+', String.Single), ], 'double_quote': [ (r'(\\"|\\[0-7]{1,3}\D|\\[abfnrtv]|\\\\)', String.Escape), (r'\"', String.Double, '#pop'), (r'[^"\\]+', String.Double), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894""" pygments.lexers.ncl ~~~~~~~~~~~~~~~~~~~
Lexers for NCAR Command Language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['NCLLexer']
class NCLLexer(RegexLexer): """ Lexer for NCL code. """ name = 'NCL' aliases = ['ncl'] filenames = ['*.ncl'] mimetypes = ['text/ncl'] url = 'https://www.ncl.ucar.edu' version_added = '2.2'
flags = re.MULTILINE
tokens = { 'root': [ (r';.*\n', Comment), include('strings'), include('core'), (r'[a-zA-Z_]\w*', Name), include('nums'), (r'[\s]+', Text), ], 'core': [ # Statements (words(( 'begin', 'break', 'continue', 'create', 'defaultapp', 'do', 'else', 'end', 'external', 'exit', 'True', 'False', 'file', 'function', 'getvalues', 'graphic', 'group', 'if', 'list', 'load', 'local', 'new', '_Missing', 'Missing', 'noparent', 'procedure', 'quit', 'QUIT', 'Quit', 'record', 'return', 'setvalues', 'stop', 'then', 'while'), prefix=r'\b', suffix=r'\s*\b'), Keyword),
# Data Types (words(( 'ubyte', 'uint', 'uint64', 'ulong', 'string', 'byte', 'character', 'double', 'float', 'integer', 'int64', 'logical', 'long', 'short', 'ushort', 'enumeric', 'numeric', 'snumeric'), prefix=r'\b', suffix=r'\s*\b'), Keyword.Type),
# Operators (r'[\%^*+\-/<>]', Operator),
# punctuation: (r'[\[\]():@$!&|.,\\{}]', Punctuation), (r'[=:]', Punctuation),
# Intrinsics (words(( 'abs', 'acos', 'addfile', 'addfiles', 'all', 'angmom_atm', 'any', 'area_conserve_remap', 'area_hi2lores', 'area_poly_sphere', 'asciiread', 'asciiwrite', 'asin', 'atan', 'atan2', 'attsetvalues', 'avg', 'betainc', 'bin_avg', 'bin_sum', 'bw_bandpass_filter', 'cancor', 'cbinread', 'cbinwrite', 'cd_calendar', 'cd_inv_calendar', 'cdfbin_p', 'cdfbin_pr', 'cdfbin_s', 'cdfbin_xn', 'cdfchi_p', 'cdfchi_x', 'cdfgam_p', 'cdfgam_x', 'cdfnor_p', 'cdfnor_x', 'cdft_p', 'cdft_t', 'ceil', 'center_finite_diff', 'center_finite_diff_n', 'cfftb', 'cfftf', 'cfftf_frq_reorder', 'charactertodouble', 'charactertofloat', 'charactertointeger', 'charactertolong', 'charactertoshort', 'charactertostring', 'chartodouble', 'chartofloat', 'chartoint', 'chartointeger', 'chartolong', 'chartoshort', 'chartostring', 'chiinv', 'clear', 'color_index_to_rgba', 'conform', 'conform_dims', 'cos', 'cosh', 'count_unique_values', 'covcorm', 'covcorm_xy', 'craybinnumrec', 'craybinrecread', 'create_graphic', 'csa1', 'csa1d', 'csa1s', 'csa1x', 'csa1xd', 'csa1xs', 'csa2', 'csa2d', 'csa2l', 'csa2ld', 'csa2ls', 'csa2lx', 'csa2lxd', 'csa2lxs', 'csa2s', 'csa2x', 'csa2xd', 'csa2xs', 'csa3', 'csa3d', 'csa3l', 'csa3ld', 'csa3ls', 'csa3lx', 'csa3lxd', 'csa3lxs', 'csa3s', 'csa3x', 'csa3xd', 'csa3xs', 'csc2s', 'csgetp', 'css2c', 'cssetp', 'cssgrid', 'csstri', 'csvoro', 'cumsum', 'cz2ccm', 'datatondc', 'day_of_week', 'day_of_year', 'days_in_month', 'default_fillvalue', 'delete', 'depth_to_pres', 'destroy', 'determinant', 'dewtemp_trh', 'dgeevx_lapack', 'dim_acumrun_n', 'dim_avg', 'dim_avg_n', 'dim_avg_wgt', 'dim_avg_wgt_n', 'dim_cumsum', 'dim_cumsum_n', 'dim_gamfit_n', 'dim_gbits', 'dim_max', 'dim_max_n', 'dim_median', 'dim_median_n', 'dim_min', 'dim_min_n', 'dim_num', 'dim_num_n', 'dim_numrun_n', 'dim_pqsort', 'dim_pqsort_n', 'dim_product', 'dim_product_n', 'dim_rmsd', 'dim_rmsd_n', 'dim_rmvmean', 'dim_rmvmean_n', 'dim_rmvmed', 'dim_rmvmed_n', 'dim_spi_n', 'dim_standardize', 'dim_standardize_n', 'dim_stat4', 'dim_stat4_n', 'dim_stddev', 'dim_stddev_n', 'dim_sum', 'dim_sum_n', 'dim_sum_wgt', 'dim_sum_wgt_n', 'dim_variance', 'dim_variance_n', 'dimsizes', 'doubletobyte', 'doubletochar', 'doubletocharacter', 'doubletofloat', 'doubletoint', 'doubletointeger', 'doubletolong', 'doubletoshort', 'dpres_hybrid_ccm', 'dpres_plevel', 'draw', 'draw_color_palette', 'dsgetp', 'dsgrid2', 'dsgrid2d', 'dsgrid2s', 'dsgrid3', 'dsgrid3d', 'dsgrid3s', 'dspnt2', 'dspnt2d', 'dspnt2s', 'dspnt3', 'dspnt3d', 'dspnt3s', 'dssetp', 'dtrend', 'dtrend_msg', 'dtrend_msg_n', 'dtrend_n', 'dtrend_quadratic', 'dtrend_quadratic_msg_n', 'dv2uvf', 'dv2uvg', 'dz_height', 'echo_off', 'echo_on', 'eof2data', 'eof_varimax', 'eofcor', 'eofcor_pcmsg', 'eofcor_ts', 'eofcov', 'eofcov_pcmsg', 'eofcov_ts', 'eofunc', 'eofunc_ts', 'eofunc_varimax', 'equiv_sample_size', 'erf', 'erfc', 'esacr', 'esacv', 'esccr', 'esccv', 'escorc', 'escorc_n', 'escovc', 'exit', 'exp', 'exp_tapersh', 'exp_tapersh_wgts', 'exp_tapershC', 'ezfftb', 'ezfftb_n', 'ezfftf', 'ezfftf_n', 'f2fosh', 'f2foshv', 'f2fsh', 'f2fshv', 'f2gsh', 'f2gshv', 'fabs', 'fbindirread', 'fbindirwrite', 'fbinnumrec', 'fbinread', 'fbinrecread', 'fbinrecwrite', 'fbinwrite', 'fft2db', 'fft2df', 'fftshift', 'fileattdef', 'filechunkdimdef', 'filedimdef', 'fileexists', 'filegrpdef', 'filevarattdef', 'filevarchunkdef', 'filevarcompressleveldef', 'filevardef', 'filevardimsizes', 'filwgts_lancos', 'filwgts_lanczos', 'filwgts_normal', 'floattobyte', 'floattochar', 'floattocharacter', 'floattoint', 'floattointeger', 'floattolong', 'floattoshort', 'floor', 'fluxEddy', 'fo2fsh', 'fo2fshv', 'fourier_info', 'frame', 'fspan', 'ftcurv', 'ftcurvd', 'ftcurvi', 'ftcurvp', 'ftcurvpi', 'ftcurvps', 'ftcurvs', 'ftest', 'ftgetp', 'ftkurv', 'ftkurvd', 'ftkurvp', 'ftkurvpd', 'ftsetp', 'ftsurf', 'g2fsh', 'g2fshv', 'g2gsh', 'g2gshv', 'gamma', 'gammainc', 'gaus', 'gaus_lobat', 'gaus_lobat_wgt', 'gc_aangle', 'gc_clkwise', 'gc_dangle', 'gc_inout', 'gc_latlon', 'gc_onarc', 'gc_pnt2gc', 'gc_qarea', 'gc_tarea', 'generate_2d_array', 'get_color_index', 'get_color_rgba', 'get_cpu_time', 'get_isolines', 'get_ncl_version', 'get_script_name', 'get_script_prefix_name', 'get_sphere_radius', 'get_unique_values', 'getbitsone', 'getenv', 'getfiledimsizes', 'getfilegrpnames', 'getfilepath', 'getfilevaratts', 'getfilevarchunkdimsizes', 'getfilevardims', 'getfilevardimsizes', 'getfilevarnames', 'getfilevartypes', 'getvaratts', 'getvardims', 'gradsf', 'gradsg', 'greg2jul', 'grid2triple', 'hlsrgb', 'hsvrgb', 'hydro', 'hyi2hyo', 'idsfft', 'igradsf', 'igradsg', 'ilapsf', 'ilapsg', 'ilapvf', 'ilapvg', 'ind', 'ind_resolve', 'int2p', 'int2p_n', 'integertobyte', 'integertochar', 'integertocharacter', 'integertoshort', 'inttobyte', 'inttochar', 'inttoshort', 'inverse_matrix', 'isatt', 'isbigendian', 'isbyte', 'ischar', 'iscoord', 'isdefined', 'isdim', 'isdimnamed', 'isdouble', 'isenumeric', 'isfile', 'isfilepresent', 'isfilevar', 'isfilevaratt', 'isfilevarcoord', 'isfilevardim', 'isfloat', 'isfunc', 'isgraphic', 'isint', 'isint64', 'isinteger', 'isleapyear', 'islogical', 'islong', 'ismissing', 'isnan_ieee', 'isnumeric', 'ispan', 'isproc', 'isshort', 'issnumeric', 'isstring', 'isubyte', 'isuint', 'isuint64', 'isulong', 'isunlimited', 'isunsigned', 'isushort', 'isvar', 'jul2greg', 'kmeans_as136', 'kolsm2_n', 'kron_product', 'lapsf', 'lapsg', 'lapvf', 'lapvg', 'latlon2utm', 'lclvl', 'lderuvf', 'lderuvg', 'linint1', 'linint1_n', 'linint2', 'linint2_points', 'linmsg', 'linmsg_n', 'linrood_latwgt', 'linrood_wgt', 'list_files', 'list_filevars', 'list_hlus', 'list_procfuncs', 'list_vars', 'ListAppend', 'ListCount', 'ListGetType', 'ListIndex', 'ListIndexFromName', 'ListPop', 'ListPush', 'ListSetType', 'loadscript', 'local_max', 'local_min', 'log', 'log10', 'longtobyte', 'longtochar', 'longtocharacter', 'longtoint', 'longtointeger', 'longtoshort', 'lspoly', 'lspoly_n', 'mask', 'max', 'maxind', 'min', 'minind', 'mixed_layer_depth', 'mixhum_ptd', 'mixhum_ptrh', 'mjo_cross_coh2pha', 'mjo_cross_segment', 'moc_globe_atl', 'monthday', 'natgrid', 'natgridd', 'natgrids', 'ncargpath', 'ncargversion', 'ndctodata', 'ndtooned', 'new', 'NewList', 'ngezlogo', 'nggcog', 'nggetp', 'nglogo', 'ngsetp', 'NhlAddAnnotation', 'NhlAddData', 'NhlAddOverlay', 'NhlAddPrimitive', 'NhlAppGetDefaultParentId', 'NhlChangeWorkstation', 'NhlClassName', 'NhlClearWorkstation', 'NhlDataPolygon', 'NhlDataPolyline', 'NhlDataPolymarker', 'NhlDataToNDC', 'NhlDestroy', 'NhlDraw', 'NhlFrame', 'NhlFreeColor', 'NhlGetBB', 'NhlGetClassResources', 'NhlGetErrorObjectId', 'NhlGetNamedColorIndex', 'NhlGetParentId', 'NhlGetParentWorkstation', 'NhlGetWorkspaceObjectId', 'NhlIsAllocatedColor', 'NhlIsApp', 'NhlIsDataComm', 'NhlIsDataItem', 'NhlIsDataSpec', 'NhlIsTransform', 'NhlIsView', 'NhlIsWorkstation', 'NhlName', 'NhlNDCPolygon', 'NhlNDCPolyline', 'NhlNDCPolymarker', 'NhlNDCToData', 'NhlNewColor', 'NhlNewDashPattern', 'NhlNewMarker', 'NhlPalGetDefined', 'NhlRemoveAnnotation', 'NhlRemoveData', 'NhlRemoveOverlay', 'NhlRemovePrimitive', 'NhlSetColor', 'NhlSetDashPattern', 'NhlSetMarker', 'NhlUpdateData', 'NhlUpdateWorkstation', 'nice_mnmxintvl', 'nngetaspectd', 'nngetaspects', 'nngetp', 'nngetsloped', 'nngetslopes', 'nngetwts', 'nngetwtsd', 'nnpnt', 'nnpntd', 'nnpntend', 'nnpntendd', 'nnpntinit', 'nnpntinitd', 'nnpntinits', 'nnpnts', 'nnsetp', 'num', 'obj_anal_ic', 'omega_ccm', 'onedtond', 'overlay', 'paleo_outline', 'pdfxy_bin', 'poisson_grid_fill', 'pop_remap', 'potmp_insitu_ocn', 'prcwater_dp', 'pres2hybrid', 'pres_hybrid_ccm', 'pres_sigma', 'print', 'print_table', 'printFileVarSummary', 'printVarSummary', 'product', 'pslec', 'pslhor', 'pslhyp', 'qsort', 'rand', 'random_chi', 'random_gamma', 'random_normal', 'random_setallseed', 'random_uniform', 'rcm2points', 'rcm2rgrid', 'rdsstoi', 'read_colormap_file', 'reg_multlin', 'regcoef', 'regCoef_n', 'regline', 'relhum', 'replace_ieeenan', 'reshape', 'reshape_ind', 'rgba_to_color_index', 'rgbhls', 'rgbhsv', 'rgbyiq', 'rgrid2rcm', 'rhomb_trunc', 'rip_cape_2d', 'rip_cape_3d', 'round', 'rtest', 'runave', 'runave_n', 'set_default_fillvalue', 'set_sphere_radius', 'setfileoption', 'sfvp2uvf', 'sfvp2uvg', 'shaec', 'shagc', 'shgetnp', 'shgetp', 'shgrid', 'shorttobyte', 'shorttochar', 'shorttocharacter', 'show_ascii', 'shsec', 'shsetp', 'shsgc', 'shsgc_R42', 'sigma2hybrid', 'simpeq', 'simpne', 'sin', 'sindex_yrmo', 'sinh', 'sizeof', 'sleep', 'smth9', 'snindex_yrmo', 'solve_linsys', 'span_color_indexes', 'span_color_rgba', 'sparse_matrix_mult', 'spcorr', 'spcorr_n', 'specx_anal', 'specxy_anal', 'spei', 'sprintf', 'sprinti', 'sqrt', 'sqsort', 'srand', 'stat2', 'stat4', 'stat_medrng', 'stat_trim', 'status_exit', 'stdatmus_p2tdz', 'stdatmus_z2tdp', 'stddev', 'str_capital', 'str_concat', 'str_fields_count', 'str_get_cols', 'str_get_dq', 'str_get_field', 'str_get_nl', 'str_get_sq', 'str_get_tab', 'str_index_of_substr', 'str_insert', 'str_is_blank', 'str_join', 'str_left_strip', 'str_lower', 'str_match', 'str_match_ic', 'str_match_ic_regex', 'str_match_ind', 'str_match_ind_ic', 'str_match_ind_ic_regex', 'str_match_ind_regex', 'str_match_regex', 'str_right_strip', 'str_split', 'str_split_by_length', 'str_split_csv', 'str_squeeze', 'str_strip', 'str_sub_str', 'str_switch', 'str_upper', 'stringtochar', 'stringtocharacter', 'stringtodouble', 'stringtofloat', 'stringtoint', 'stringtointeger', 'stringtolong', 'stringtoshort', 'strlen', 'student_t', 'sum', 'svd_lapack', 'svdcov', 'svdcov_sv', 'svdstd', 'svdstd_sv', 'system', 'systemfunc', 'tan', 'tanh', 'taper', 'taper_n', 'tdclrs', 'tdctri', 'tdcudp', 'tdcurv', 'tddtri', 'tdez2d', 'tdez3d', 'tdgetp', 'tdgrds', 'tdgrid', 'tdgtrs', 'tdinit', 'tditri', 'tdlbla', 'tdlblp', 'tdlbls', 'tdline', 'tdlndp', 'tdlnpa', 'tdlpdp', 'tdmtri', 'tdotri', 'tdpara', 'tdplch', 'tdprpa', 'tdprpi', 'tdprpt', 'tdsetp', 'tdsort', 'tdstri', 'tdstrs', 'tdttri', 'thornthwaite', 'tobyte', 'tochar', 'todouble', 'tofloat', 'toint', 'toint64', 'tointeger', 'tolong', 'toshort', 'tosigned', 'tostring', 'tostring_with_format', 'totype', 'toubyte', 'touint', 'touint64', 'toulong', 'tounsigned', 'toushort', 'trend_manken', 'tri_trunc', 'triple2grid', 'triple2grid2d', 'trop_wmo', 'ttest', 'typeof', 'undef', 'unique_string', 'update', 'ushorttoint', 'ut_calendar', 'ut_inv_calendar', 'utm2latlon', 'uv2dv_cfd', 'uv2dvf', 'uv2dvg', 'uv2sfvpf', 'uv2sfvpg', 'uv2vr_cfd', 'uv2vrdvf', 'uv2vrdvg', 'uv2vrf', 'uv2vrg', 'v5d_close', 'v5d_create', 'v5d_setLowLev', 'v5d_setUnits', 'v5d_write', 'v5d_write_var', 'variance', 'vhaec', 'vhagc', 'vhsec', 'vhsgc', 'vibeta', 'vinth2p', 'vinth2p_ecmwf', 'vinth2p_ecmwf_nodes', 'vinth2p_nodes', 'vintp2p_ecmwf', 'vr2uvf', 'vr2uvg', 'vrdv2uvf', 'vrdv2uvg', 'wavelet', 'wavelet_default', 'weibull', 'wgt_area_smooth', 'wgt_areaave', 'wgt_areaave2', 'wgt_arearmse', 'wgt_arearmse2', 'wgt_areasum2', 'wgt_runave', 'wgt_runave_n', 'wgt_vert_avg_beta', 'wgt_volave', 'wgt_volave_ccm', 'wgt_volrmse', 'wgt_volrmse_ccm', 'where', 'wk_smooth121', 'wmbarb', 'wmbarbmap', 'wmdrft', 'wmgetp', 'wmlabs', 'wmsetp', 'wmstnm', 'wmvect', 'wmvectmap', 'wmvlbl', 'wrf_avo', 'wrf_cape_2d', 'wrf_cape_3d', 'wrf_dbz', 'wrf_eth', 'wrf_helicity', 'wrf_ij_to_ll', 'wrf_interp_1d', 'wrf_interp_2d_xy', 'wrf_interp_3d_z', 'wrf_latlon_to_ij', 'wrf_ll_to_ij', 'wrf_omega', 'wrf_pvo', 'wrf_rh', 'wrf_slp', 'wrf_smooth_2d', 'wrf_td', 'wrf_tk', 'wrf_updraft_helicity', 'wrf_uvmet', 'wrf_virtual_temp', 'wrf_wetbulb', 'wrf_wps_close_int', 'wrf_wps_open_int', 'wrf_wps_rddata_int', 'wrf_wps_rdhead_int', 'wrf_wps_read_int', 'wrf_wps_write_int', 'write_matrix', 'write_table', 'yiqrgb', 'z2geouv', 'zonal_mpsi', 'addfiles_GetVar', 'advect_variable', 'area_conserve_remap_Wrap', 'area_hi2lores_Wrap', 'array_append_record', 'assignFillValue', 'byte2flt', 'byte2flt_hdf', 'calcDayAnomTLL', 'calcMonAnomLLLT', 'calcMonAnomLLT', 'calcMonAnomTLL', 'calcMonAnomTLLL', 'calculate_monthly_values', 'cd_convert', 'changeCase', 'changeCaseChar', 'clmDayTLL', 'clmDayTLLL', 'clmMon2clmDay', 'clmMonLLLT', 'clmMonLLT', 'clmMonTLL', 'clmMonTLLL', 'closest_val', 'copy_VarAtts', 'copy_VarCoords', 'copy_VarCoords_1', 'copy_VarCoords_2', 'copy_VarMeta', 'copyatt', 'crossp3', 'cshstringtolist', 'cssgrid_Wrap', 'dble2flt', 'decimalPlaces', 'delete_VarAtts', 'dim_avg_n_Wrap', 'dim_avg_wgt_n_Wrap', 'dim_avg_wgt_Wrap', 'dim_avg_Wrap', 'dim_cumsum_n_Wrap', 'dim_cumsum_Wrap', 'dim_max_n_Wrap', 'dim_min_n_Wrap', 'dim_rmsd_n_Wrap', 'dim_rmsd_Wrap', 'dim_rmvmean_n_Wrap', 'dim_rmvmean_Wrap', 'dim_rmvmed_n_Wrap', 'dim_rmvmed_Wrap', 'dim_standardize_n_Wrap', 'dim_standardize_Wrap', 'dim_stddev_n_Wrap', 'dim_stddev_Wrap', 'dim_sum_n_Wrap', 'dim_sum_wgt_n_Wrap', 'dim_sum_wgt_Wrap', 'dim_sum_Wrap', 'dim_variance_n_Wrap', 'dim_variance_Wrap', 'dpres_plevel_Wrap', 'dtrend_leftdim', 'dv2uvF_Wrap', 'dv2uvG_Wrap', 'eof_north', 'eofcor_Wrap', 'eofcov_Wrap', 'eofunc_north', 'eofunc_ts_Wrap', 'eofunc_varimax_reorder', 'eofunc_varimax_Wrap', 'eofunc_Wrap', 'epsZero', 'f2fosh_Wrap', 'f2foshv_Wrap', 'f2fsh_Wrap', 'f2fshv_Wrap', 'f2gsh_Wrap', 'f2gshv_Wrap', 'fbindirSwap', 'fbinseqSwap1', 'fbinseqSwap2', 'flt2dble', 'flt2string', 'fo2fsh_Wrap', 'fo2fshv_Wrap', 'g2fsh_Wrap', 'g2fshv_Wrap', 'g2gsh_Wrap', 'g2gshv_Wrap', 'generate_resample_indices', 'generate_sample_indices', 'generate_unique_indices', 'genNormalDist', 'get1Dindex', 'get1Dindex_Collapse', 'get1Dindex_Exclude', 'get_file_suffix', 'GetFillColor', 'GetFillColorIndex', 'getFillValue', 'getind_latlon2d', 'getVarDimNames', 'getVarFillValue', 'grib_stime2itime', 'hyi2hyo_Wrap', 'ilapsF_Wrap', 'ilapsG_Wrap', 'ind_nearest_coord', 'indStrSubset', 'int2dble', 'int2flt', 'int2p_n_Wrap', 'int2p_Wrap', 'isMonotonic', 'isStrSubset', 'latGau', 'latGauWgt', 'latGlobeF', 'latGlobeFo', 'latRegWgt', 'linint1_n_Wrap', 'linint1_Wrap', 'linint2_points_Wrap', 'linint2_Wrap', 'local_max_1d', 'local_min_1d', 'lonFlip', 'lonGlobeF', 'lonGlobeFo', 'lonPivot', 'merge_levels_sfc', 'mod', 'month_to_annual', 'month_to_annual_weighted', 'month_to_season', 'month_to_season12', 'month_to_seasonN', 'monthly_total_to_daily_mean', 'nameDim', 'natgrid_Wrap', 'NewCosWeight', 'niceLatLon2D', 'NormCosWgtGlobe', 'numAsciiCol', 'numAsciiRow', 'numeric2int', 'obj_anal_ic_deprecated', 'obj_anal_ic_Wrap', 'omega_ccm_driver', 'omega_to_w', 'oneDtostring', 'pack_values', 'pattern_cor', 'pdfx', 'pdfxy', 'pdfxy_conform', 'pot_temp', 'pot_vort_hybrid', 'pot_vort_isobaric', 'pres2hybrid_Wrap', 'print_clock', 'printMinMax', 'quadroots', 'rcm2points_Wrap', 'rcm2rgrid_Wrap', 'readAsciiHead', 'readAsciiTable', 'reg_multlin_stats', 'region_ind', 'regline_stats', 'relhum_ttd', 'replaceSingleChar', 'RGBtoCmap', 'rgrid2rcm_Wrap', 'rho_mwjf', 'rm_single_dims', 'rmAnnCycle1D', 'rmInsufData', 'rmMonAnnCycLLLT', 'rmMonAnnCycLLT', 'rmMonAnnCycTLL', 'runave_n_Wrap', 'runave_Wrap', 'short2flt', 'short2flt_hdf', 'shsgc_R42_Wrap', 'sign_f90', 'sign_matlab', 'smth9_Wrap', 'smthClmDayTLL', 'smthClmDayTLLL', 'SqrtCosWeight', 'stat_dispersion', 'static_stability', 'stdMonLLLT', 'stdMonLLT', 'stdMonTLL', 'stdMonTLLL', 'symMinMaxPlt', 'table_attach_columns', 'table_attach_rows', 'time_to_newtime', 'transpose', 'triple2grid_Wrap', 'ut_convert', 'uv2dvF_Wrap', 'uv2dvG_Wrap', 'uv2vrF_Wrap', 'uv2vrG_Wrap', 'vr2uvF_Wrap', 'vr2uvG_Wrap', 'w_to_omega', 'wallClockElapseTime', 'wave_number_spc', 'wgt_areaave_Wrap', 'wgt_runave_leftdim', 'wgt_runave_n_Wrap', 'wgt_runave_Wrap', 'wgt_vertical_n', 'wind_component', 'wind_direction', 'yyyyddd_to_yyyymmdd', 'yyyymm_time', 'yyyymm_to_yyyyfrac', 'yyyymmdd_time', 'yyyymmdd_to_yyyyddd', 'yyyymmdd_to_yyyyfrac', 'yyyymmddhh_time', 'yyyymmddhh_to_yyyyfrac', 'zonal_mpsi_Wrap', 'zonalAve', 'calendar_decode2', 'cd_string', 'kf_filter', 'run_cor', 'time_axis_labels', 'ut_string', 'wrf_contour', 'wrf_map', 'wrf_map_overlay', 'wrf_map_overlays', 'wrf_map_resources', 'wrf_map_zoom', 'wrf_overlay', 'wrf_overlays', 'wrf_user_getvar', 'wrf_user_ij_to_ll', 'wrf_user_intrp2d', 'wrf_user_intrp3d', 'wrf_user_latlon_to_ij', 'wrf_user_list_times', 'wrf_user_ll_to_ij', 'wrf_user_unstagger', 'wrf_user_vert_interp', 'wrf_vector', 'gsn_add_annotation', 'gsn_add_polygon', 'gsn_add_polyline', 'gsn_add_polymarker', 'gsn_add_shapefile_polygons', 'gsn_add_shapefile_polylines', 'gsn_add_shapefile_polymarkers', 'gsn_add_text', 'gsn_attach_plots', 'gsn_blank_plot', 'gsn_contour', 'gsn_contour_map', 'gsn_contour_shade', 'gsn_coordinates', 'gsn_create_labelbar', 'gsn_create_legend', 'gsn_create_text', 'gsn_csm_attach_zonal_means', 'gsn_csm_blank_plot', 'gsn_csm_contour', 'gsn_csm_contour_map', 'gsn_csm_contour_map_ce', 'gsn_csm_contour_map_overlay', 'gsn_csm_contour_map_polar', 'gsn_csm_hov', 'gsn_csm_lat_time', 'gsn_csm_map', 'gsn_csm_map_ce', 'gsn_csm_map_polar', 'gsn_csm_pres_hgt', 'gsn_csm_pres_hgt_streamline', 'gsn_csm_pres_hgt_vector', 'gsn_csm_streamline', 'gsn_csm_streamline_contour_map', 'gsn_csm_streamline_contour_map_ce', 'gsn_csm_streamline_contour_map_polar', 'gsn_csm_streamline_map', 'gsn_csm_streamline_map_ce', 'gsn_csm_streamline_map_polar', 'gsn_csm_streamline_scalar', 'gsn_csm_streamline_scalar_map', 'gsn_csm_streamline_scalar_map_ce', 'gsn_csm_streamline_scalar_map_polar', 'gsn_csm_time_lat', 'gsn_csm_vector', 'gsn_csm_vector_map', 'gsn_csm_vector_map_ce', 'gsn_csm_vector_map_polar', 'gsn_csm_vector_scalar', 'gsn_csm_vector_scalar_map', 'gsn_csm_vector_scalar_map_ce', 'gsn_csm_vector_scalar_map_polar', 'gsn_csm_x2y', 'gsn_csm_x2y2', 'gsn_csm_xy', 'gsn_csm_xy2', 'gsn_csm_xy3', 'gsn_csm_y', 'gsn_define_colormap', 'gsn_draw_colormap', 'gsn_draw_named_colors', 'gsn_histogram', 'gsn_labelbar_ndc', 'gsn_legend_ndc', 'gsn_map', 'gsn_merge_colormaps', 'gsn_open_wks', 'gsn_panel', 'gsn_polygon', 'gsn_polygon_ndc', 'gsn_polyline', 'gsn_polyline_ndc', 'gsn_polymarker', 'gsn_polymarker_ndc', 'gsn_retrieve_colormap', 'gsn_reverse_colormap', 'gsn_streamline', 'gsn_streamline_map', 'gsn_streamline_scalar', 'gsn_streamline_scalar_map', 'gsn_table', 'gsn_text', 'gsn_text_ndc', 'gsn_vector', 'gsn_vector_map', 'gsn_vector_scalar', 'gsn_vector_scalar_map', 'gsn_xy', 'gsn_y', 'hsv2rgb', 'maximize_output', 'namedcolor2rgb', 'namedcolor2rgba', 'reset_device_coordinates', 'span_named_colors'), prefix=r'\b'), Name.Builtin),
# Resources (words(( 'amDataXF', 'amDataYF', 'amJust', 'amOn', 'amOrthogonalPosF', 'amParallelPosF', 'amResizeNotify', 'amSide', 'amTrackData', 'amViewId', 'amZone', 'appDefaultParent', 'appFileSuffix', 'appResources', 'appSysDir', 'appUsrDir', 'caCopyArrays', 'caXArray', 'caXCast', 'caXMaxV', 'caXMinV', 'caXMissingV', 'caYArray', 'caYCast', 'caYMaxV', 'caYMinV', 'caYMissingV', 'cnCellFillEdgeColor', 'cnCellFillMissingValEdgeColor', 'cnConpackParams', 'cnConstFEnableFill', 'cnConstFLabelAngleF', 'cnConstFLabelBackgroundColor', 'cnConstFLabelConstantSpacingF', 'cnConstFLabelFont', 'cnConstFLabelFontAspectF', 'cnConstFLabelFontColor', 'cnConstFLabelFontHeightF', 'cnConstFLabelFontQuality', 'cnConstFLabelFontThicknessF', 'cnConstFLabelFormat', 'cnConstFLabelFuncCode', 'cnConstFLabelJust', 'cnConstFLabelOn', 'cnConstFLabelOrthogonalPosF', 'cnConstFLabelParallelPosF', 'cnConstFLabelPerimColor', 'cnConstFLabelPerimOn', 'cnConstFLabelPerimSpaceF', 'cnConstFLabelPerimThicknessF', 'cnConstFLabelSide', 'cnConstFLabelString', 'cnConstFLabelTextDirection', 'cnConstFLabelZone', 'cnConstFUseInfoLabelRes', 'cnExplicitLabelBarLabelsOn', 'cnExplicitLegendLabelsOn', 'cnExplicitLineLabelsOn', 'cnFillBackgroundColor', 'cnFillColor', 'cnFillColors', 'cnFillDotSizeF', 'cnFillDrawOrder', 'cnFillMode', 'cnFillOn', 'cnFillOpacityF', 'cnFillPalette', 'cnFillPattern', 'cnFillPatterns', 'cnFillScaleF', 'cnFillScales', 'cnFixFillBleed', 'cnGridBoundFillColor', 'cnGridBoundFillPattern', 'cnGridBoundFillScaleF', 'cnGridBoundPerimColor', 'cnGridBoundPerimDashPattern', 'cnGridBoundPerimOn', 'cnGridBoundPerimThicknessF', 'cnHighLabelAngleF', 'cnHighLabelBackgroundColor', 'cnHighLabelConstantSpacingF', 'cnHighLabelCount', 'cnHighLabelFont', 'cnHighLabelFontAspectF', 'cnHighLabelFontColor', 'cnHighLabelFontHeightF', 'cnHighLabelFontQuality', 'cnHighLabelFontThicknessF', 'cnHighLabelFormat', 'cnHighLabelFuncCode', 'cnHighLabelPerimColor', 'cnHighLabelPerimOn', 'cnHighLabelPerimSpaceF', 'cnHighLabelPerimThicknessF', 'cnHighLabelString', 'cnHighLabelsOn', 'cnHighLowLabelOverlapMode', 'cnHighUseLineLabelRes', 'cnInfoLabelAngleF', 'cnInfoLabelBackgroundColor', 'cnInfoLabelConstantSpacingF', 'cnInfoLabelFont', 'cnInfoLabelFontAspectF', 'cnInfoLabelFontColor', 'cnInfoLabelFontHeightF', 'cnInfoLabelFontQuality', 'cnInfoLabelFontThicknessF', 'cnInfoLabelFormat', 'cnInfoLabelFuncCode', 'cnInfoLabelJust', 'cnInfoLabelOn', 'cnInfoLabelOrthogonalPosF', 'cnInfoLabelParallelPosF', 'cnInfoLabelPerimColor', 'cnInfoLabelPerimOn', 'cnInfoLabelPerimSpaceF', 'cnInfoLabelPerimThicknessF', 'cnInfoLabelSide', 'cnInfoLabelString', 'cnInfoLabelTextDirection', 'cnInfoLabelZone', 'cnLabelBarEndLabelsOn', 'cnLabelBarEndStyle', 'cnLabelDrawOrder', 'cnLabelMasking', 'cnLabelScaleFactorF', 'cnLabelScaleValueF', 'cnLabelScalingMode', 'cnLegendLevelFlags', 'cnLevelCount', 'cnLevelFlag', 'cnLevelFlags', 'cnLevelSelectionMode', 'cnLevelSpacingF', 'cnLevels', 'cnLineColor', 'cnLineColors', 'cnLineDashPattern', 'cnLineDashPatterns', 'cnLineDashSegLenF', 'cnLineDrawOrder', 'cnLineLabelAngleF', 'cnLineLabelBackgroundColor', 'cnLineLabelConstantSpacingF', 'cnLineLabelCount', 'cnLineLabelDensityF', 'cnLineLabelFont', 'cnLineLabelFontAspectF', 'cnLineLabelFontColor', 'cnLineLabelFontColors', 'cnLineLabelFontHeightF', 'cnLineLabelFontQuality', 'cnLineLabelFontThicknessF', 'cnLineLabelFormat', 'cnLineLabelFuncCode', 'cnLineLabelInterval', 'cnLineLabelPerimColor', 'cnLineLabelPerimOn', 'cnLineLabelPerimSpaceF', 'cnLineLabelPerimThicknessF', 'cnLineLabelPlacementMode', 'cnLineLabelStrings', 'cnLineLabelsOn', 'cnLinePalette', 'cnLineThicknessF', 'cnLineThicknesses', 'cnLinesOn', 'cnLowLabelAngleF', 'cnLowLabelBackgroundColor', 'cnLowLabelConstantSpacingF', 'cnLowLabelCount', 'cnLowLabelFont', 'cnLowLabelFontAspectF', 'cnLowLabelFontColor', 'cnLowLabelFontHeightF', 'cnLowLabelFontQuality', 'cnLowLabelFontThicknessF', 'cnLowLabelFormat', 'cnLowLabelFuncCode', 'cnLowLabelPerimColor', 'cnLowLabelPerimOn', 'cnLowLabelPerimSpaceF', 'cnLowLabelPerimThicknessF', 'cnLowLabelString', 'cnLowLabelsOn', 'cnLowUseHighLabelRes', 'cnMaxDataValueFormat', 'cnMaxLevelCount', 'cnMaxLevelValF', 'cnMaxPointDistanceF', 'cnMinLevelValF', 'cnMissingValFillColor', 'cnMissingValFillPattern', 'cnMissingValFillScaleF', 'cnMissingValPerimColor', 'cnMissingValPerimDashPattern', 'cnMissingValPerimGridBoundOn', 'cnMissingValPerimOn', 'cnMissingValPerimThicknessF', 'cnMonoFillColor', 'cnMonoFillPattern', 'cnMonoFillScale', 'cnMonoLevelFlag', 'cnMonoLineColor', 'cnMonoLineDashPattern', 'cnMonoLineLabelFontColor', 'cnMonoLineThickness', 'cnNoDataLabelOn', 'cnNoDataLabelString', 'cnOutOfRangeFillColor', 'cnOutOfRangeFillPattern', 'cnOutOfRangeFillScaleF', 'cnOutOfRangePerimColor', 'cnOutOfRangePerimDashPattern', 'cnOutOfRangePerimOn', 'cnOutOfRangePerimThicknessF', 'cnRasterCellSizeF', 'cnRasterMinCellSizeF', 'cnRasterModeOn', 'cnRasterSampleFactorF', 'cnRasterSmoothingOn', 'cnScalarFieldData', 'cnSmoothingDistanceF', 'cnSmoothingOn', 'cnSmoothingTensionF', 'cnSpanFillPalette', 'cnSpanLinePalette', 'ctCopyTables', 'ctXElementSize', 'ctXMaxV', 'ctXMinV', 'ctXMissingV', 'ctXTable', 'ctXTableLengths', 'ctXTableType', 'ctYElementSize', 'ctYMaxV', 'ctYMinV', 'ctYMissingV', 'ctYTable', 'ctYTableLengths', 'ctYTableType', 'dcDelayCompute', 'errBuffer', 'errFileName', 'errFilePtr', 'errLevel', 'errPrint', 'errUnitNumber', 'gsClipOn', 'gsColors', 'gsEdgeColor', 'gsEdgeDashPattern', 'gsEdgeDashSegLenF', 'gsEdgeThicknessF', 'gsEdgesOn', 'gsFillBackgroundColor', 'gsFillColor', 'gsFillDotSizeF', 'gsFillIndex', 'gsFillLineThicknessF', 'gsFillOpacityF', 'gsFillScaleF', 'gsFont', 'gsFontAspectF', 'gsFontColor', 'gsFontHeightF', 'gsFontOpacityF', 'gsFontQuality', 'gsFontThicknessF', 'gsLineColor', 'gsLineDashPattern', 'gsLineDashSegLenF', 'gsLineLabelConstantSpacingF', 'gsLineLabelFont', 'gsLineLabelFontAspectF', 'gsLineLabelFontColor', 'gsLineLabelFontHeightF', 'gsLineLabelFontQuality', 'gsLineLabelFontThicknessF', 'gsLineLabelFuncCode', 'gsLineLabelString', 'gsLineOpacityF', 'gsLineThicknessF', 'gsMarkerColor', 'gsMarkerIndex', 'gsMarkerOpacityF', 'gsMarkerSizeF', 'gsMarkerThicknessF', 'gsSegments', 'gsTextAngleF', 'gsTextConstantSpacingF', 'gsTextDirection', 'gsTextFuncCode', 'gsTextJustification', 'gsnAboveYRefLineBarColors', 'gsnAboveYRefLineBarFillScales', 'gsnAboveYRefLineBarPatterns', 'gsnAboveYRefLineColor', 'gsnAddCyclic', 'gsnAttachBorderOn', 'gsnAttachPlotsXAxis', 'gsnBelowYRefLineBarColors', 'gsnBelowYRefLineBarFillScales', 'gsnBelowYRefLineBarPatterns', 'gsnBelowYRefLineColor', 'gsnBoxMargin', 'gsnCenterString', 'gsnCenterStringFontColor', 'gsnCenterStringFontHeightF', 'gsnCenterStringFuncCode', 'gsnCenterStringOrthogonalPosF', 'gsnCenterStringParallelPosF', 'gsnContourLineThicknessesScale', 'gsnContourNegLineDashPattern', 'gsnContourPosLineDashPattern', 'gsnContourZeroLineThicknessF', 'gsnDebugWriteFileName', 'gsnDraw', 'gsnFrame', 'gsnHistogramBarWidthPercent', 'gsnHistogramBinIntervals', 'gsnHistogramBinMissing', 'gsnHistogramBinWidth', 'gsnHistogramClassIntervals', 'gsnHistogramCompare', 'gsnHistogramComputePercentages', 'gsnHistogramComputePercentagesNoMissing', 'gsnHistogramDiscreteBinValues', 'gsnHistogramDiscreteClassValues', 'gsnHistogramHorizontal', 'gsnHistogramMinMaxBinsOn', 'gsnHistogramNumberOfBins', 'gsnHistogramPercentSign', 'gsnHistogramSelectNiceIntervals', 'gsnLeftString', 'gsnLeftStringFontColor', 'gsnLeftStringFontHeightF', 'gsnLeftStringFuncCode', 'gsnLeftStringOrthogonalPosF', 'gsnLeftStringParallelPosF', 'gsnMajorLatSpacing', 'gsnMajorLonSpacing', 'gsnMaskLambertConformal', 'gsnMaskLambertConformalOutlineOn', 'gsnMaximize', 'gsnMinorLatSpacing', 'gsnMinorLonSpacing', 'gsnPanelBottom', 'gsnPanelCenter', 'gsnPanelDebug', 'gsnPanelFigureStrings', 'gsnPanelFigureStringsBackgroundFillColor', 'gsnPanelFigureStringsFontHeightF', 'gsnPanelFigureStringsJust', 'gsnPanelFigureStringsPerimOn', 'gsnPanelLabelBar', 'gsnPanelLeft', 'gsnPanelMainFont', 'gsnPanelMainFontColor', 'gsnPanelMainFontHeightF', 'gsnPanelMainString', 'gsnPanelRight', 'gsnPanelRowSpec', 'gsnPanelScalePlotIndex', 'gsnPanelTop', 'gsnPanelXF', 'gsnPanelXWhiteSpacePercent', 'gsnPanelYF', 'gsnPanelYWhiteSpacePercent', 'gsnPaperHeight', 'gsnPaperMargin', 'gsnPaperOrientation', 'gsnPaperWidth', 'gsnPolar', 'gsnPolarLabelDistance', 'gsnPolarLabelFont', 'gsnPolarLabelFontHeightF', 'gsnPolarLabelSpacing', 'gsnPolarTime', 'gsnPolarUT', 'gsnRightString', 'gsnRightStringFontColor', 'gsnRightStringFontHeightF', 'gsnRightStringFuncCode', 'gsnRightStringOrthogonalPosF', 'gsnRightStringParallelPosF', 'gsnScalarContour', 'gsnScale', 'gsnShape', 'gsnSpreadColorEnd', 'gsnSpreadColorStart', 'gsnSpreadColors', 'gsnStringFont', 'gsnStringFontColor', 'gsnStringFontHeightF', 'gsnStringFuncCode', 'gsnTickMarksOn', 'gsnXAxisIrregular2Linear', 'gsnXAxisIrregular2Log', 'gsnXRefLine', 'gsnXRefLineColor', 'gsnXRefLineDashPattern', 'gsnXRefLineThicknessF', 'gsnXYAboveFillColors', 'gsnXYBarChart', 'gsnXYBarChartBarWidth', 'gsnXYBarChartColors', 'gsnXYBarChartColors2', 'gsnXYBarChartFillDotSizeF', 'gsnXYBarChartFillLineThicknessF', 'gsnXYBarChartFillOpacityF', 'gsnXYBarChartFillScaleF', 'gsnXYBarChartOutlineOnly', 'gsnXYBarChartOutlineThicknessF', 'gsnXYBarChartPatterns', 'gsnXYBarChartPatterns2', 'gsnXYBelowFillColors', 'gsnXYFillColors', 'gsnXYFillOpacities', 'gsnXYLeftFillColors', 'gsnXYRightFillColors', 'gsnYAxisIrregular2Linear', 'gsnYAxisIrregular2Log', 'gsnYRefLine', 'gsnYRefLineColor', 'gsnYRefLineColors', 'gsnYRefLineDashPattern', 'gsnYRefLineDashPatterns', 'gsnYRefLineThicknessF', 'gsnYRefLineThicknesses', 'gsnZonalMean', 'gsnZonalMeanXMaxF', 'gsnZonalMeanXMinF', 'gsnZonalMeanYRefLine', 'lbAutoManage', 'lbBottomMarginF', 'lbBoxCount', 'lbBoxEndCapStyle', 'lbBoxFractions', 'lbBoxLineColor', 'lbBoxLineDashPattern', 'lbBoxLineDashSegLenF', 'lbBoxLineThicknessF', 'lbBoxLinesOn', 'lbBoxMajorExtentF', 'lbBoxMinorExtentF', 'lbBoxSeparatorLinesOn', 'lbBoxSizing', 'lbFillBackground', 'lbFillColor', 'lbFillColors', 'lbFillDotSizeF', 'lbFillLineThicknessF', 'lbFillPattern', 'lbFillPatterns', 'lbFillScaleF', 'lbFillScales', 'lbJustification', 'lbLabelAlignment', 'lbLabelAngleF', 'lbLabelAutoStride', 'lbLabelBarOn', 'lbLabelConstantSpacingF', 'lbLabelDirection', 'lbLabelFont', 'lbLabelFontAspectF', 'lbLabelFontColor', 'lbLabelFontHeightF', 'lbLabelFontQuality', 'lbLabelFontThicknessF', 'lbLabelFuncCode', 'lbLabelJust', 'lbLabelOffsetF', 'lbLabelPosition', 'lbLabelStride', 'lbLabelStrings', 'lbLabelsOn', 'lbLeftMarginF', 'lbMaxLabelLenF', 'lbMinLabelSpacingF', 'lbMonoFillColor', 'lbMonoFillPattern', 'lbMonoFillScale', 'lbOrientation', 'lbPerimColor', 'lbPerimDashPattern', 'lbPerimDashSegLenF', 'lbPerimFill', 'lbPerimFillColor', 'lbPerimOn', 'lbPerimThicknessF', 'lbRasterFillOn', 'lbRightMarginF', 'lbTitleAngleF', 'lbTitleConstantSpacingF', 'lbTitleDirection', 'lbTitleExtentF', 'lbTitleFont', 'lbTitleFontAspectF', 'lbTitleFontColor', 'lbTitleFontHeightF', 'lbTitleFontQuality', 'lbTitleFontThicknessF', 'lbTitleFuncCode', 'lbTitleJust', 'lbTitleOffsetF', 'lbTitleOn', 'lbTitlePosition', 'lbTitleString', 'lbTopMarginF', 'lgAutoManage', 'lgBottomMarginF', 'lgBoxBackground', 'lgBoxLineColor', 'lgBoxLineDashPattern', 'lgBoxLineDashSegLenF', 'lgBoxLineThicknessF', 'lgBoxLinesOn', 'lgBoxMajorExtentF', 'lgBoxMinorExtentF', 'lgDashIndex', 'lgDashIndexes', 'lgItemCount', 'lgItemOrder', 'lgItemPlacement', 'lgItemPositions', 'lgItemType', 'lgItemTypes', 'lgJustification', 'lgLabelAlignment', 'lgLabelAngleF', 'lgLabelAutoStride', 'lgLabelConstantSpacingF', 'lgLabelDirection', 'lgLabelFont', 'lgLabelFontAspectF', 'lgLabelFontColor', 'lgLabelFontHeightF', 'lgLabelFontQuality', 'lgLabelFontThicknessF', 'lgLabelFuncCode', 'lgLabelJust', 'lgLabelOffsetF', 'lgLabelPosition', 'lgLabelStride', 'lgLabelStrings', 'lgLabelsOn', 'lgLeftMarginF', 'lgLegendOn', 'lgLineColor', 'lgLineColors', 'lgLineDashSegLenF', 'lgLineDashSegLens', 'lgLineLabelConstantSpacingF', 'lgLineLabelFont', 'lgLineLabelFontAspectF', 'lgLineLabelFontColor', 'lgLineLabelFontColors', 'lgLineLabelFontHeightF', 'lgLineLabelFontHeights', 'lgLineLabelFontQuality', 'lgLineLabelFontThicknessF', 'lgLineLabelFuncCode', 'lgLineLabelStrings', 'lgLineLabelsOn', 'lgLineThicknessF', 'lgLineThicknesses', 'lgMarkerColor', 'lgMarkerColors', 'lgMarkerIndex', 'lgMarkerIndexes', 'lgMarkerSizeF', 'lgMarkerSizes', 'lgMarkerThicknessF', 'lgMarkerThicknesses', 'lgMonoDashIndex', 'lgMonoItemType', 'lgMonoLineColor', 'lgMonoLineDashSegLen', 'lgMonoLineLabelFontColor', 'lgMonoLineLabelFontHeight', 'lgMonoLineThickness', 'lgMonoMarkerColor', 'lgMonoMarkerIndex', 'lgMonoMarkerSize', 'lgMonoMarkerThickness', 'lgOrientation', 'lgPerimColor', 'lgPerimDashPattern', 'lgPerimDashSegLenF', 'lgPerimFill', 'lgPerimFillColor', 'lgPerimOn', 'lgPerimThicknessF', 'lgRightMarginF', 'lgTitleAngleF', 'lgTitleConstantSpacingF', 'lgTitleDirection', 'lgTitleExtentF', 'lgTitleFont', 'lgTitleFontAspectF', 'lgTitleFontColor', 'lgTitleFontHeightF', 'lgTitleFontQuality', 'lgTitleFontThicknessF', 'lgTitleFuncCode', 'lgTitleJust', 'lgTitleOffsetF', 'lgTitleOn', 'lgTitlePosition', 'lgTitleString', 'lgTopMarginF', 'mpAreaGroupCount', 'mpAreaMaskingOn', 'mpAreaNames', 'mpAreaTypes', 'mpBottomAngleF', 'mpBottomMapPosF', 'mpBottomNDCF', 'mpBottomNPCF', 'mpBottomPointLatF', 'mpBottomPointLonF', 'mpBottomWindowF', 'mpCenterLatF', 'mpCenterLonF', 'mpCenterRotF', 'mpCountyLineColor', 'mpCountyLineDashPattern', 'mpCountyLineDashSegLenF', 'mpCountyLineThicknessF', 'mpDataBaseVersion', 'mpDataResolution', 'mpDataSetName', 'mpDefaultFillColor', 'mpDefaultFillPattern', 'mpDefaultFillScaleF', 'mpDynamicAreaGroups', 'mpEllipticalBoundary', 'mpFillAreaSpecifiers', 'mpFillBoundarySets', 'mpFillColor', 'mpFillColors', 'mpFillColors-default', 'mpFillDotSizeF', 'mpFillDrawOrder', 'mpFillOn', 'mpFillPatternBackground', 'mpFillPattern', 'mpFillPatterns', 'mpFillPatterns-default', 'mpFillScaleF', 'mpFillScales', 'mpFillScales-default', 'mpFixedAreaGroups', 'mpGeophysicalLineColor', 'mpGeophysicalLineDashPattern', 'mpGeophysicalLineDashSegLenF', 'mpGeophysicalLineThicknessF', 'mpGreatCircleLinesOn', 'mpGridAndLimbDrawOrder', 'mpGridAndLimbOn', 'mpGridLatSpacingF', 'mpGridLineColor', 'mpGridLineDashPattern', 'mpGridLineDashSegLenF', 'mpGridLineThicknessF', 'mpGridLonSpacingF', 'mpGridMaskMode', 'mpGridMaxLatF', 'mpGridPolarLonSpacingF', 'mpGridSpacingF', 'mpInlandWaterFillColor', 'mpInlandWaterFillPattern', 'mpInlandWaterFillScaleF', 'mpLabelDrawOrder', 'mpLabelFontColor', 'mpLabelFontHeightF', 'mpLabelsOn', 'mpLambertMeridianF', 'mpLambertParallel1F', 'mpLambertParallel2F', 'mpLandFillColor', 'mpLandFillPattern', 'mpLandFillScaleF', 'mpLeftAngleF', 'mpLeftCornerLatF', 'mpLeftCornerLonF', 'mpLeftMapPosF', 'mpLeftNDCF', 'mpLeftNPCF', 'mpLeftPointLatF', 'mpLeftPointLonF', 'mpLeftWindowF', 'mpLimbLineColor', 'mpLimbLineDashPattern', 'mpLimbLineDashSegLenF', 'mpLimbLineThicknessF', 'mpLimitMode', 'mpMaskAreaSpecifiers', 'mpMaskOutlineSpecifiers', 'mpMaxLatF', 'mpMaxLonF', 'mpMinLatF', 'mpMinLonF', 'mpMonoFillColor', 'mpMonoFillPattern', 'mpMonoFillScale', 'mpNationalLineColor', 'mpNationalLineDashPattern', 'mpNationalLineThicknessF', 'mpOceanFillColor', 'mpOceanFillPattern', 'mpOceanFillScaleF', 'mpOutlineBoundarySets', 'mpOutlineDrawOrder', 'mpOutlineMaskingOn', 'mpOutlineOn', 'mpOutlineSpecifiers', 'mpPerimDrawOrder', 'mpPerimLineColor', 'mpPerimLineDashPattern', 'mpPerimLineDashSegLenF', 'mpPerimLineThicknessF', 'mpPerimOn', 'mpPolyMode', 'mpProjection', 'mpProvincialLineColor', 'mpProvincialLineDashPattern', 'mpProvincialLineDashSegLenF', 'mpProvincialLineThicknessF', 'mpRelativeCenterLat', 'mpRelativeCenterLon', 'mpRightAngleF', 'mpRightCornerLatF', 'mpRightCornerLonF', 'mpRightMapPosF', 'mpRightNDCF', 'mpRightNPCF', 'mpRightPointLatF', 'mpRightPointLonF', 'mpRightWindowF', 'mpSatelliteAngle1F', 'mpSatelliteAngle2F', 'mpSatelliteDistF', 'mpShapeMode', 'mpSpecifiedFillColors', 'mpSpecifiedFillDirectIndexing', 'mpSpecifiedFillPatterns', 'mpSpecifiedFillPriority', 'mpSpecifiedFillScales', 'mpTopAngleF', 'mpTopMapPosF', 'mpTopNDCF', 'mpTopNPCF', 'mpTopPointLatF', 'mpTopPointLonF', 'mpTopWindowF', 'mpUSStateLineColor', 'mpUSStateLineDashPattern', 'mpUSStateLineDashSegLenF', 'mpUSStateLineThicknessF', 'pmAnnoManagers', 'pmAnnoViews', 'pmLabelBarDisplayMode', 'pmLabelBarHeightF', 'pmLabelBarKeepAspect', 'pmLabelBarOrthogonalPosF', 'pmLabelBarParallelPosF', 'pmLabelBarSide', 'pmLabelBarWidthF', 'pmLabelBarZone', 'pmLegendDisplayMode', 'pmLegendHeightF', 'pmLegendKeepAspect', 'pmLegendOrthogonalPosF', 'pmLegendParallelPosF', 'pmLegendSide', 'pmLegendWidthF', 'pmLegendZone', 'pmOverlaySequenceIds', 'pmTickMarkDisplayMode', 'pmTickMarkZone', 'pmTitleDisplayMode', 'pmTitleZone', 'prGraphicStyle', 'prPolyType', 'prXArray', 'prYArray', 'sfCopyData', 'sfDataArray', 'sfDataMaxV', 'sfDataMinV', 'sfElementNodes', 'sfExchangeDimensions', 'sfFirstNodeIndex', 'sfMissingValueV', 'sfXArray', 'sfXCActualEndF', 'sfXCActualStartF', 'sfXCEndIndex', 'sfXCEndSubsetV', 'sfXCEndV', 'sfXCStartIndex', 'sfXCStartSubsetV', 'sfXCStartV', 'sfXCStride', 'sfXCellBounds', 'sfYArray', 'sfYCActualEndF', 'sfYCActualStartF', 'sfYCEndIndex', 'sfYCEndSubsetV', 'sfYCEndV', 'sfYCStartIndex', 'sfYCStartSubsetV', 'sfYCStartV', 'sfYCStride', 'sfYCellBounds', 'stArrowLengthF', 'stArrowStride', 'stCrossoverCheckCount', 'stExplicitLabelBarLabelsOn', 'stLabelBarEndLabelsOn', 'stLabelFormat', 'stLengthCheckCount', 'stLevelColors', 'stLevelCount', 'stLevelPalette', 'stLevelSelectionMode', 'stLevelSpacingF', 'stLevels', 'stLineColor', 'stLineOpacityF', 'stLineStartStride', 'stLineThicknessF', 'stMapDirection', 'stMaxLevelCount', 'stMaxLevelValF', 'stMinArrowSpacingF', 'stMinDistanceF', 'stMinLevelValF', 'stMinLineSpacingF', 'stMinStepFactorF', 'stMonoLineColor', 'stNoDataLabelOn', 'stNoDataLabelString', 'stScalarFieldData', 'stScalarMissingValColor', 'stSpanLevelPalette', 'stStepSizeF', 'stStreamlineDrawOrder', 'stUseScalarArray', 'stVectorFieldData', 'stZeroFLabelAngleF', 'stZeroFLabelBackgroundColor', 'stZeroFLabelConstantSpacingF', 'stZeroFLabelFont', 'stZeroFLabelFontAspectF', 'stZeroFLabelFontColor', 'stZeroFLabelFontHeightF', 'stZeroFLabelFontQuality', 'stZeroFLabelFontThicknessF', 'stZeroFLabelFuncCode', 'stZeroFLabelJust', 'stZeroFLabelOn', 'stZeroFLabelOrthogonalPosF', 'stZeroFLabelParallelPosF', 'stZeroFLabelPerimColor', 'stZeroFLabelPerimOn', 'stZeroFLabelPerimSpaceF', 'stZeroFLabelPerimThicknessF', 'stZeroFLabelSide', 'stZeroFLabelString', 'stZeroFLabelTextDirection', 'stZeroFLabelZone', 'tfDoNDCOverlay', 'tfPlotManagerOn', 'tfPolyDrawList', 'tfPolyDrawOrder', 'tiDeltaF', 'tiMainAngleF', 'tiMainConstantSpacingF', 'tiMainDirection', 'tiMainFont', 'tiMainFontAspectF', 'tiMainFontColor', 'tiMainFontHeightF', 'tiMainFontQuality', 'tiMainFontThicknessF', 'tiMainFuncCode', 'tiMainJust', 'tiMainOffsetXF', 'tiMainOffsetYF', 'tiMainOn', 'tiMainPosition', 'tiMainSide', 'tiMainString', 'tiUseMainAttributes', 'tiXAxisAngleF', 'tiXAxisConstantSpacingF', 'tiXAxisDirection', 'tiXAxisFont', 'tiXAxisFontAspectF', 'tiXAxisFontColor', 'tiXAxisFontHeightF', 'tiXAxisFontQuality', 'tiXAxisFontThicknessF', 'tiXAxisFuncCode', 'tiXAxisJust', 'tiXAxisOffsetXF', 'tiXAxisOffsetYF', 'tiXAxisOn', 'tiXAxisPosition', 'tiXAxisSide', 'tiXAxisString', 'tiYAxisAngleF', 'tiYAxisConstantSpacingF', 'tiYAxisDirection', 'tiYAxisFont', 'tiYAxisFontAspectF', 'tiYAxisFontColor', 'tiYAxisFontHeightF', 'tiYAxisFontQuality', 'tiYAxisFontThicknessF', 'tiYAxisFuncCode', 'tiYAxisJust', 'tiYAxisOffsetXF', 'tiYAxisOffsetYF', 'tiYAxisOn', 'tiYAxisPosition', 'tiYAxisSide', 'tiYAxisString', 'tmBorderLineColor', 'tmBorderThicknessF', 'tmEqualizeXYSizes', 'tmLabelAutoStride', 'tmSciNoteCutoff', 'tmXBAutoPrecision', 'tmXBBorderOn', 'tmXBDataLeftF', 'tmXBDataRightF', 'tmXBFormat', 'tmXBIrrTensionF', 'tmXBIrregularPoints', 'tmXBLabelAngleF', 'tmXBLabelConstantSpacingF', 'tmXBLabelDeltaF', 'tmXBLabelDirection', 'tmXBLabelFont', 'tmXBLabelFontAspectF', 'tmXBLabelFontColor', 'tmXBLabelFontHeightF', 'tmXBLabelFontQuality', 'tmXBLabelFontThicknessF', 'tmXBLabelFuncCode', 'tmXBLabelJust', 'tmXBLabelStride', 'tmXBLabels', 'tmXBLabelsOn', 'tmXBMajorLengthF', 'tmXBMajorLineColor', 'tmXBMajorOutwardLengthF', 'tmXBMajorThicknessF', 'tmXBMaxLabelLenF', 'tmXBMaxTicks', 'tmXBMinLabelSpacingF', 'tmXBMinorLengthF', 'tmXBMinorLineColor', 'tmXBMinorOn', 'tmXBMinorOutwardLengthF', 'tmXBMinorPerMajor', 'tmXBMinorThicknessF', 'tmXBMinorValues', 'tmXBMode', 'tmXBOn', 'tmXBPrecision', 'tmXBStyle', 'tmXBTickEndF', 'tmXBTickSpacingF', 'tmXBTickStartF', 'tmXBValues', 'tmXMajorGrid', 'tmXMajorGridLineColor', 'tmXMajorGridLineDashPattern', 'tmXMajorGridThicknessF', 'tmXMinorGrid', 'tmXMinorGridLineColor', 'tmXMinorGridLineDashPattern', 'tmXMinorGridThicknessF', 'tmXTAutoPrecision', 'tmXTBorderOn', 'tmXTDataLeftF', 'tmXTDataRightF', 'tmXTFormat', 'tmXTIrrTensionF', 'tmXTIrregularPoints', 'tmXTLabelAngleF', 'tmXTLabelConstantSpacingF', 'tmXTLabelDeltaF', 'tmXTLabelDirection', 'tmXTLabelFont', 'tmXTLabelFontAspectF', 'tmXTLabelFontColor', 'tmXTLabelFontHeightF', 'tmXTLabelFontQuality', 'tmXTLabelFontThicknessF', 'tmXTLabelFuncCode', 'tmXTLabelJust', 'tmXTLabelStride', 'tmXTLabels', 'tmXTLabelsOn', 'tmXTMajorLengthF', 'tmXTMajorLineColor', 'tmXTMajorOutwardLengthF', 'tmXTMajorThicknessF', 'tmXTMaxLabelLenF', 'tmXTMaxTicks', 'tmXTMinLabelSpacingF', 'tmXTMinorLengthF', 'tmXTMinorLineColor', 'tmXTMinorOn', 'tmXTMinorOutwardLengthF', 'tmXTMinorPerMajor', 'tmXTMinorThicknessF', 'tmXTMinorValues', 'tmXTMode', 'tmXTOn', 'tmXTPrecision', 'tmXTStyle', 'tmXTTickEndF', 'tmXTTickSpacingF', 'tmXTTickStartF', 'tmXTValues', 'tmXUseBottom', 'tmYLAutoPrecision', 'tmYLBorderOn', 'tmYLDataBottomF', 'tmYLDataTopF', 'tmYLFormat', 'tmYLIrrTensionF', 'tmYLIrregularPoints', 'tmYLLabelAngleF', 'tmYLLabelConstantSpacingF', 'tmYLLabelDeltaF', 'tmYLLabelDirection', 'tmYLLabelFont', 'tmYLLabelFontAspectF', 'tmYLLabelFontColor', 'tmYLLabelFontHeightF', 'tmYLLabelFontQuality', 'tmYLLabelFontThicknessF', 'tmYLLabelFuncCode', 'tmYLLabelJust', 'tmYLLabelStride', 'tmYLLabels', 'tmYLLabelsOn', 'tmYLMajorLengthF', 'tmYLMajorLineColor', 'tmYLMajorOutwardLengthF', 'tmYLMajorThicknessF', 'tmYLMaxLabelLenF', 'tmYLMaxTicks', 'tmYLMinLabelSpacingF', 'tmYLMinorLengthF', 'tmYLMinorLineColor', 'tmYLMinorOn', 'tmYLMinorOutwardLengthF', 'tmYLMinorPerMajor', 'tmYLMinorThicknessF', 'tmYLMinorValues', 'tmYLMode', 'tmYLOn', 'tmYLPrecision', 'tmYLStyle', 'tmYLTickEndF', 'tmYLTickSpacingF', 'tmYLTickStartF', 'tmYLValues', 'tmYMajorGrid', 'tmYMajorGridLineColor', 'tmYMajorGridLineDashPattern', 'tmYMajorGridThicknessF', 'tmYMinorGrid', 'tmYMinorGridLineColor', 'tmYMinorGridLineDashPattern', 'tmYMinorGridThicknessF', 'tmYRAutoPrecision', 'tmYRBorderOn', 'tmYRDataBottomF', 'tmYRDataTopF', 'tmYRFormat', 'tmYRIrrTensionF', 'tmYRIrregularPoints', 'tmYRLabelAngleF', 'tmYRLabelConstantSpacingF', 'tmYRLabelDeltaF', 'tmYRLabelDirection', 'tmYRLabelFont', 'tmYRLabelFontAspectF', 'tmYRLabelFontColor', 'tmYRLabelFontHeightF', 'tmYRLabelFontQuality', 'tmYRLabelFontThicknessF', 'tmYRLabelFuncCode', 'tmYRLabelJust', 'tmYRLabelStride', 'tmYRLabels', 'tmYRLabelsOn', 'tmYRMajorLengthF', 'tmYRMajorLineColor', 'tmYRMajorOutwardLengthF', 'tmYRMajorThicknessF', 'tmYRMaxLabelLenF', 'tmYRMaxTicks', 'tmYRMinLabelSpacingF', 'tmYRMinorLengthF', 'tmYRMinorLineColor', 'tmYRMinorOn', 'tmYRMinorOutwardLengthF', 'tmYRMinorPerMajor', 'tmYRMinorThicknessF', 'tmYRMinorValues', 'tmYRMode', 'tmYROn', 'tmYRPrecision', 'tmYRStyle', 'tmYRTickEndF', 'tmYRTickSpacingF', 'tmYRTickStartF', 'tmYRValues', 'tmYUseLeft', 'trGridType', 'trLineInterpolationOn', 'trXAxisType', 'trXCoordPoints', 'trXInterPoints', 'trXLog', 'trXMaxF', 'trXMinF', 'trXReverse', 'trXSamples', 'trXTensionF', 'trYAxisType', 'trYCoordPoints', 'trYInterPoints', 'trYLog', 'trYMaxF', 'trYMinF', 'trYReverse', 'trYSamples', 'trYTensionF', 'txAngleF', 'txBackgroundFillColor', 'txConstantSpacingF', 'txDirection', 'txFont', 'HLU-Fonts', 'txFontAspectF', 'txFontColor', 'txFontHeightF', 'txFontOpacityF', 'txFontQuality', 'txFontThicknessF', 'txFuncCode', 'txJust', 'txPerimColor', 'txPerimDashLengthF', 'txPerimDashPattern', 'txPerimOn', 'txPerimSpaceF', 'txPerimThicknessF', 'txPosXF', 'txPosYF', 'txString', 'vcExplicitLabelBarLabelsOn', 'vcFillArrowEdgeColor', 'vcFillArrowEdgeThicknessF', 'vcFillArrowFillColor', 'vcFillArrowHeadInteriorXF', 'vcFillArrowHeadMinFracXF', 'vcFillArrowHeadMinFracYF', 'vcFillArrowHeadXF', 'vcFillArrowHeadYF', 'vcFillArrowMinFracWidthF', 'vcFillArrowWidthF', 'vcFillArrowsOn', 'vcFillOverEdge', 'vcGlyphOpacityF', 'vcGlyphStyle', 'vcLabelBarEndLabelsOn', 'vcLabelFontColor', 'vcLabelFontHeightF', 'vcLabelsOn', 'vcLabelsUseVectorColor', 'vcLevelColors', 'vcLevelCount', 'vcLevelPalette', 'vcLevelSelectionMode', 'vcLevelSpacingF', 'vcLevels', 'vcLineArrowColor', 'vcLineArrowHeadMaxSizeF', 'vcLineArrowHeadMinSizeF', 'vcLineArrowThicknessF', 'vcMagnitudeFormat', 'vcMagnitudeScaleFactorF', 'vcMagnitudeScaleValueF', 'vcMagnitudeScalingMode', 'vcMapDirection', 'vcMaxLevelCount', 'vcMaxLevelValF', 'vcMaxMagnitudeF', 'vcMinAnnoAngleF', 'vcMinAnnoArrowAngleF', 'vcMinAnnoArrowEdgeColor', 'vcMinAnnoArrowFillColor', 'vcMinAnnoArrowLineColor', 'vcMinAnnoArrowMinOffsetF', 'vcMinAnnoArrowSpaceF', 'vcMinAnnoArrowUseVecColor', 'vcMinAnnoBackgroundColor', 'vcMinAnnoConstantSpacingF', 'vcMinAnnoExplicitMagnitudeF', 'vcMinAnnoFont', 'vcMinAnnoFontAspectF', 'vcMinAnnoFontColor', 'vcMinAnnoFontHeightF', 'vcMinAnnoFontQuality', 'vcMinAnnoFontThicknessF', 'vcMinAnnoFuncCode', 'vcMinAnnoJust', 'vcMinAnnoOn', 'vcMinAnnoOrientation', 'vcMinAnnoOrthogonalPosF', 'vcMinAnnoParallelPosF', 'vcMinAnnoPerimColor', 'vcMinAnnoPerimOn', 'vcMinAnnoPerimSpaceF', 'vcMinAnnoPerimThicknessF', 'vcMinAnnoSide', 'vcMinAnnoString1', 'vcMinAnnoString1On', 'vcMinAnnoString2', 'vcMinAnnoString2On', 'vcMinAnnoTextDirection', 'vcMinAnnoZone', 'vcMinDistanceF', 'vcMinFracLengthF', 'vcMinLevelValF', 'vcMinMagnitudeF', 'vcMonoFillArrowEdgeColor', 'vcMonoFillArrowFillColor', 'vcMonoLineArrowColor', 'vcMonoWindBarbColor', 'vcNoDataLabelOn', 'vcNoDataLabelString', 'vcPositionMode', 'vcRefAnnoAngleF', 'vcRefAnnoArrowAngleF', 'vcRefAnnoArrowEdgeColor', 'vcRefAnnoArrowFillColor', 'vcRefAnnoArrowLineColor', 'vcRefAnnoArrowMinOffsetF', 'vcRefAnnoArrowSpaceF', 'vcRefAnnoArrowUseVecColor', 'vcRefAnnoBackgroundColor', 'vcRefAnnoConstantSpacingF', 'vcRefAnnoExplicitMagnitudeF', 'vcRefAnnoFont', 'vcRefAnnoFontAspectF', 'vcRefAnnoFontColor', 'vcRefAnnoFontHeightF', 'vcRefAnnoFontQuality', 'vcRefAnnoFontThicknessF', 'vcRefAnnoFuncCode', 'vcRefAnnoJust', 'vcRefAnnoOn', 'vcRefAnnoOrientation', 'vcRefAnnoOrthogonalPosF', 'vcRefAnnoParallelPosF', 'vcRefAnnoPerimColor', 'vcRefAnnoPerimOn', 'vcRefAnnoPerimSpaceF', 'vcRefAnnoPerimThicknessF', 'vcRefAnnoSide', 'vcRefAnnoString1', 'vcRefAnnoString1On', 'vcRefAnnoString2', 'vcRefAnnoString2On', 'vcRefAnnoTextDirection', 'vcRefAnnoZone', 'vcRefLengthF', 'vcRefMagnitudeF', 'vcScalarFieldData', 'vcScalarMissingValColor', 'vcScalarValueFormat', 'vcScalarValueScaleFactorF', 'vcScalarValueScaleValueF', 'vcScalarValueScalingMode', 'vcSpanLevelPalette', 'vcUseRefAnnoRes', 'vcUseScalarArray', 'vcVectorDrawOrder', 'vcVectorFieldData', 'vcWindBarbCalmCircleSizeF', 'vcWindBarbColor', 'vcWindBarbLineThicknessF', 'vcWindBarbScaleFactorF', 'vcWindBarbTickAngleF', 'vcWindBarbTickLengthF', 'vcWindBarbTickSpacingF', 'vcZeroFLabelAngleF', 'vcZeroFLabelBackgroundColor', 'vcZeroFLabelConstantSpacingF', 'vcZeroFLabelFont', 'vcZeroFLabelFontAspectF', 'vcZeroFLabelFontColor', 'vcZeroFLabelFontHeightF', 'vcZeroFLabelFontQuality', 'vcZeroFLabelFontThicknessF', 'vcZeroFLabelFuncCode', 'vcZeroFLabelJust', 'vcZeroFLabelOn', 'vcZeroFLabelOrthogonalPosF', 'vcZeroFLabelParallelPosF', 'vcZeroFLabelPerimColor', 'vcZeroFLabelPerimOn', 'vcZeroFLabelPerimSpaceF', 'vcZeroFLabelPerimThicknessF', 'vcZeroFLabelSide', 'vcZeroFLabelString', 'vcZeroFLabelTextDirection', 'vcZeroFLabelZone', 'vfCopyData', 'vfDataArray', 'vfExchangeDimensions', 'vfExchangeUVData', 'vfMagMaxV', 'vfMagMinV', 'vfMissingUValueV', 'vfMissingVValueV', 'vfPolarData', 'vfSingleMissingValue', 'vfUDataArray', 'vfUMaxV', 'vfUMinV', 'vfVDataArray', 'vfVMaxV', 'vfVMinV', 'vfXArray', 'vfXCActualEndF', 'vfXCActualStartF', 'vfXCEndIndex', 'vfXCEndSubsetV', 'vfXCEndV', 'vfXCStartIndex', 'vfXCStartSubsetV', 'vfXCStartV', 'vfXCStride', 'vfYArray', 'vfYCActualEndF', 'vfYCActualStartF', 'vfYCEndIndex', 'vfYCEndSubsetV', 'vfYCEndV', 'vfYCStartIndex', 'vfYCStartSubsetV', 'vfYCStartV', 'vfYCStride', 'vpAnnoManagerId', 'vpClipOn', 'vpHeightF', 'vpKeepAspect', 'vpOn', 'vpUseSegments', 'vpWidthF', 'vpXF', 'vpYF', 'wkAntiAlias', 'wkBackgroundColor', 'wkBackgroundOpacityF', 'wkColorMapLen', 'wkColorMap', 'wkColorModel', 'wkDashTableLength', 'wkDefGraphicStyleId', 'wkDeviceLowerX', 'wkDeviceLowerY', 'wkDeviceUpperX', 'wkDeviceUpperY', 'wkFileName', 'wkFillTableLength', 'wkForegroundColor', 'wkFormat', 'wkFullBackground', 'wkGksWorkId', 'wkHeight', 'wkMarkerTableLength', 'wkMetaName', 'wkOrientation', 'wkPDFFileName', 'wkPDFFormat', 'wkPDFResolution', 'wkPSFileName', 'wkPSFormat', 'wkPSResolution', 'wkPaperHeightF', 'wkPaperSize', 'wkPaperWidthF', 'wkPause', 'wkTopLevelViews', 'wkViews', 'wkVisualType', 'wkWidth', 'wkWindowId', 'wkXColorMode', 'wsCurrentSize', 'wsMaximumSize', 'wsThresholdSize', 'xyComputeXMax', 'xyComputeXMin', 'xyComputeYMax', 'xyComputeYMin', 'xyCoordData', 'xyCoordDataSpec', 'xyCurveDrawOrder', 'xyDashPattern', 'xyDashPatterns', 'xyExplicitLabels', 'xyExplicitLegendLabels', 'xyLabelMode', 'xyLineColor', 'xyLineColors', 'xyLineDashSegLenF', 'xyLineLabelConstantSpacingF', 'xyLineLabelFont', 'xyLineLabelFontAspectF', 'xyLineLabelFontColor', 'xyLineLabelFontColors', 'xyLineLabelFontHeightF', 'xyLineLabelFontQuality', 'xyLineLabelFontThicknessF', 'xyLineLabelFuncCode', 'xyLineThicknessF', 'xyLineThicknesses', 'xyMarkLineMode', 'xyMarkLineModes', 'xyMarker', 'xyMarkerColor', 'xyMarkerColors', 'xyMarkerSizeF', 'xyMarkerSizes', 'xyMarkerThicknessF', 'xyMarkerThicknesses', 'xyMarkers', 'xyMonoDashPattern', 'xyMonoLineColor', 'xyMonoLineLabelFontColor', 'xyMonoLineThickness', 'xyMonoMarkLineMode', 'xyMonoMarker', 'xyMonoMarkerColor', 'xyMonoMarkerSize', 'xyMonoMarkerThickness', 'xyXIrrTensionF', 'xyXIrregularPoints', 'xyXStyle', 'xyYIrrTensionF', 'xyYIrregularPoints', 'xyYStyle'), prefix=r'\b'), Name.Builtin),
# Booleans (r'\.(True|False)\.', Name.Builtin), # Comparing Operators (r'\.(eq|ne|lt|le|gt|ge|not|and|or|xor)\.', Operator.Word), ],
'strings': [ (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double), ],
'nums': [ (r'\d+(?![.e])(_[a-z]\w+)?', Number.Integer), (r'[+-]?\d*\.\d+(e[-+]?\d+)?(_[a-z]\w+)?', Number.Float), (r'[+-]?\d+\.\d*(e[-+]?\d+)?(_[a-z]\w+)?', Number.Float), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199""" pygments.lexers.nimrod ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Nim language (formerly known as Nimrod).
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, default, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error
__all__ = ['NimrodLexer']
class NimrodLexer(RegexLexer): """ For Nim source code. """
name = 'Nimrod' url = 'http://nim-lang.org/' aliases = ['nimrod', 'nim'] filenames = ['*.nim', '*.nimrod'] mimetypes = ['text/x-nim'] version_added = '1.5'
flags = re.MULTILINE | re.IGNORECASE
def underscorize(words): newWords = [] new = [] for word in words: for ch in word: new.append(ch) new.append("_?") newWords.append(''.join(new)) new = [] return "|".join(newWords)
keywords = [ 'addr', 'and', 'as', 'asm', 'bind', 'block', 'break', 'case', 'cast', 'concept', 'const', 'continue', 'converter', 'defer', 'discard', 'distinct', 'div', 'do', 'elif', 'else', 'end', 'enum', 'except', 'export', 'finally', 'for', 'if', 'in', 'yield', 'interface', 'is', 'isnot', 'iterator', 'let', 'mixin', 'mod', 'not', 'notin', 'object', 'of', 'or', 'out', 'ptr', 'raise', 'ref', 'return', 'shl', 'shr', 'static', 'try', 'tuple', 'type', 'using', 'when', 'while', 'xor' ]
keywordsPseudo = [ 'nil', 'true', 'false' ]
opWords = [ 'and', 'or', 'not', 'xor', 'shl', 'shr', 'div', 'mod', 'in', 'notin', 'is', 'isnot' ]
types = [ 'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64', 'bool', 'char', 'range', 'array', 'seq', 'set', 'string' ]
tokens = { 'root': [ # Comments (r'##\[', String.Doc, 'doccomment'), (r'##.*$', String.Doc), (r'#\[', Comment.Multiline, 'comment'), (r'#.*$', Comment),
# Pragmas (r'\{\.', String.Other, 'pragma'),
# Operators (r'[*=><+\-/@$~&%!?|\\\[\]]', Operator), (r'\.\.|\.|,|\[\.|\.\]|\{\.|\.\}|\(\.|\.\)|\{|\}|\(|\)|:|\^|`|;', Punctuation),
# Case statement branch (r'(\n\s*)(of)(\s)', bygroups(Text.Whitespace, Keyword, Text.Whitespace), 'casebranch'),
# Strings (r'(?:[\w]+)"', String, 'rdqs'), (r'"""', String.Double, 'tdqs'), ('"', String, 'dqs'),
# Char ("'", String.Char, 'chars'),
# Keywords (rf'({underscorize(opWords)})\b', Operator.Word), (r'(proc|func|method|macro|template)(\s)(?![(\[\]])', bygroups(Keyword, Text.Whitespace), 'funcname'), (rf'({underscorize(keywords)})\b', Keyword), (r'({})\b'.format(underscorize(['from', 'import', 'include', 'export'])), Keyword.Namespace), (r'(v_?a_?r)\b', Keyword.Declaration), (rf'({underscorize(types)})\b', Name.Builtin), (rf'({underscorize(keywordsPseudo)})\b', Keyword.Pseudo),
# Identifiers (r'\b((?![_\d])\w)(((?!_)\w)|(_(?!_)\w))*', Name),
# Numbers (r'[0-9][0-9_]*(?=([e.]|\'f(32|64)))', Number.Float, ('float-suffix', 'float-number')), (r'0x[a-f0-9][a-f0-9_]*', Number.Hex, 'int-suffix'), (r'0b[01][01_]*', Number.Bin, 'int-suffix'), (r'0o[0-7][0-7_]*', Number.Oct, 'int-suffix'), (r'[0-9][0-9_]*', Number.Integer, 'int-suffix'),
# Whitespace (r'\s+', Text.Whitespace), (r'.+$', Error), ], 'chars': [ (r'\\([\\abcefnrtvl"\']|x[a-f0-9]{2}|[0-9]{1,3})', String.Escape), (r"'", String.Char, '#pop'), (r".", String.Char) ], 'strings': [ (r'(?<!\$)\$(\d+|#|\w+)+', String.Interpol), (r'[^\\\'"$\n]+', String), # quotes, dollars and backslashes must be parsed one at a time (r'[\'"\\]', String), # unhandled string formatting sign (r'\$', String) # newlines are an error (use "nl" state) ], 'doccomment': [ (r'[^\]#]+', String.Doc), (r'##\[', String.Doc, '#push'), (r'\]##', String.Doc, '#pop'), (r'[\]#]', String.Doc), ], 'comment': [ (r'[^\]#]+', Comment.Multiline), (r'#\[', Comment.Multiline, '#push'), (r'\]#', Comment.Multiline, '#pop'), (r'[\]#]', Comment.Multiline), ], 'dqs': [ (r'\\([\\abcefnrtvl"\']|\n|x[a-f0-9]{2}|[0-9]{1,3})', String.Escape), (r'"', String, '#pop'), include('strings') ], 'rdqs': [ (r'"(?!")', String, '#pop'), (r'""', String.Escape), include('strings') ], 'tdqs': [ (r'"""', String.Double, '#pop'), include('strings'), (r'\n', String.Double) ], 'funcname': [ (r'((?![\d_])\w)(((?!_)\w)|(_(?!_)\w))*', Name.Function, '#pop'), (r'`.+`', Name.Function, '#pop') ], 'nl': [ (r'\n', String) ], 'float-number': [ (r'\.(?!\.)[0-9_]*[f]*', Number.Float), (r'e[+-]?[0-9][0-9_]*', Number.Float), default('#pop') ], 'float-suffix': [ (r'\'f(32|64)', Number.Float), default('#pop') ], 'int-suffix': [ (r'\'i(32|64)', Number.Integer.Long), (r'\'i(8|16)', Number.Integer), default('#pop') ], 'casebranch': [ (r',', Punctuation), (r'[\n ]+', Text.Whitespace), (r':', Operator, '#pop'), (r'\w+|[^:]', Name.Label), ], 'pragma': [ (r'[:,]', Text), (r'[\n ]+', Text.Whitespace), (r'\.\}', String.Other, '#pop'), (r'\w+|\W+|[^.}]', String.Other), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263""" pygments.lexers.nit ~~~~~~~~~~~~~~~~~~~
Lexer for the Nit language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['NitLexer']
class NitLexer(RegexLexer): """ For nit source. """
name = 'Nit' url = 'http://nitlanguage.org' aliases = ['nit'] filenames = ['*.nit'] version_added = '2.0' tokens = { 'root': [ (r'#.*?$', Comment.Single), (words(( 'package', 'module', 'import', 'class', 'abstract', 'interface', 'universal', 'enum', 'end', 'fun', 'type', 'init', 'redef', 'isa', 'do', 'readable', 'writable', 'var', 'intern', 'extern', 'public', 'protected', 'private', 'intrude', 'if', 'then', 'else', 'while', 'loop', 'for', 'in', 'and', 'or', 'not', 'implies', 'return', 'continue', 'break', 'abort', 'assert', 'new', 'is', 'once', 'super', 'self', 'true', 'false', 'nullable', 'null', 'as', 'isset', 'label', '__debug__'), suffix=r'(?=[\r\n\t( ])'), Keyword), (r'[A-Z]\w*', Name.Class), (r'"""(([^\'\\]|\\.)|\\r|\\n)*((\{\{?)?(""?\{\{?)*""""*)', String), # Simple long string (r'\'\'\'(((\\.|[^\'\\])|\\r|\\n)|\'((\\.|[^\'\\])|\\r|\\n)|' r'\'\'((\\.|[^\'\\])|\\r|\\n))*\'\'\'', String), # Simple long string alt (r'"""(([^\'\\]|\\.)|\\r|\\n)*((""?)?(\{\{?""?)*\{\{\{\{*)', String), # Start long string (r'\}\}\}(((\\.|[^\'\\])|\\r|\\n))*(""?)?(\{\{?""?)*\{\{\{\{*', String), # Mid long string (r'\}\}\}(((\\.|[^\'\\])|\\r|\\n))*(\{\{?)?(""?\{\{?)*""""*', String), # End long string (r'"(\\.|([^"}{\\]))*"', String), # Simple String (r'"(\\.|([^"}{\\]))*\{', String), # Start string (r'\}(\\.|([^"}{\\]))*\{', String), # Mid String (r'\}(\\.|([^"}{\\]))*"', String), # End String (r'(\'[^\'\\]\')|(\'\\.\')', String.Char), (r'[0-9]+', Number.Integer), (r'[0-9]*.[0-9]+', Number.Float), (r'0(x|X)[0-9A-Fa-f]+', Number.Hex), (r'[a-z]\w*', Name), (r'_\w+', Name.Variable.Instance), (r'==|!=|<==>|>=|>>|>|<=|<<|<|\+|-|=|/|\*|%|\+=|-=|!|@', Operator), (r'\(|\)|\[|\]|,|\.\.\.|\.\.|\.|::|:', Punctuation), (r'`\{[^`]*`\}', Text), # Extern blocks won't be Lexed by Nit (r'[\r\n\t ]+', Text), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144""" pygments.lexers.nix ~~~~~~~~~~~~~~~~~~~
Lexers for the NixOS Nix language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, includefrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Literal
__all__ = ['NixLexer']
class NixLexer(RegexLexer): """ For the Nix language. """
name = 'Nix' url = 'http://nixos.org/nix/' aliases = ['nixos', 'nix'] filenames = ['*.nix'] mimetypes = ['text/x-nix'] version_added = '2.0'
keywords = ['rec', 'with', 'let', 'in', 'inherit', 'assert', 'if', 'else', 'then', '...'] builtins = ['import', 'abort', 'baseNameOf', 'dirOf', 'isNull', 'builtins', 'map', 'removeAttrs', 'throw', 'toString', 'derivation'] operators = ['++', '+', '?', '.', '!', '//', '==', '/', '!=', '&&', '||', '->', '=', '<', '>', '*', '-']
punctuations = ["(", ")", "[", "]", ";", "{", "}", ":", ",", "@"]
tokens = { 'root': [ # comments starting with # (r'#.*$', Comment.Single),
# multiline comments (r'/\*', Comment.Multiline, 'comment'),
# whitespace (r'\s+', Text),
# keywords ('({})'.format('|'.join(re.escape(entry) + '\\b' for entry in keywords)), Keyword),
# highlight the builtins ('({})'.format('|'.join(re.escape(entry) + '\\b' for entry in builtins)), Name.Builtin),
(r'\b(true|false|null)\b', Name.Constant),
# floats (r'-?(\d+\.\d*|\.\d+)([eE][-+]?\d+)?', Number.Float),
# integers (r'-?[0-9]+', Number.Integer),
# paths (r'[\w.+-]*(\/[\w.+-]+)+', Literal), (r'~(\/[\w.+-]+)+', Literal), (r'\<[\w.+-]+(\/[\w.+-]+)*\>', Literal),
# operators ('({})'.format('|'.join(re.escape(entry) for entry in operators)), Operator),
# word operators (r'\b(or|and)\b', Operator.Word),
(r'\{', Punctuation, 'block'),
# punctuations ('({})'.format('|'.join(re.escape(entry) for entry in punctuations)), Punctuation),
# strings (r'"', String.Double, 'doublequote'), (r"''", String.Multiline, 'multiline'),
# urls (r'[a-zA-Z][a-zA-Z0-9\+\-\.]*\:[\w%/?:@&=+$,\\.!~*\'-]+', Literal),
# names of variables (r'[\w-]+(?=\s*=)', String.Symbol), (r'[a-zA-Z_][\w\'-]*', Text),
(r"\$\{", String.Interpol, 'antiquote'), ], 'comment': [ (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'multiline': [ (r"''(\$|'|\\n|\\r|\\t|\\)", String.Escape), (r"''", String.Multiline, '#pop'), (r'\$\{', String.Interpol, 'antiquote'), (r"[^'\$]+", String.Multiline), (r"\$[^\{']", String.Multiline), (r"'[^']", String.Multiline), (r"\$(?=')", String.Multiline), ], 'doublequote': [ (r'\\(\\|"|\$|n)', String.Escape), (r'"', String.Double, '#pop'), (r'\$\{', String.Interpol, 'antiquote'), (r'[^"\\\$]+', String.Double), (r'\$[^\{"]', String.Double), (r'\$(?=")', String.Double), (r'\\', String.Double), ], 'antiquote': [ (r"\}", String.Interpol, '#pop'), # TODO: we should probably escape also here ''${ \${ (r"\$\{", String.Interpol, '#push'), include('root'), ], 'block': [ (r"\}", Punctuation, '#pop'), include('root'), ], }
def analyse_text(text): rv = 0.0 # TODO: let/in if re.search(r'import.+?<[^>]+>', text): rv += 0.4 if re.search(r'mkDerivation\s+(\(|\{|rec)', text): rv += 0.4 if re.search(r'=\s+mkIf\s+', text): rv += 0.4 if re.search(r'\{[a-zA-Z,\s]+\}:', text): rv += 0.1 return rv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263""" pygments.lexers.numbair ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for other Numba Intermediate Representation.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroups, wordsfrom pygments.token import Whitespace, Name, String, Punctuation, Keyword, \ Operator, Number
__all__ = ["NumbaIRLexer"]
class NumbaIRLexer(RegexLexer): """ Lexer for Numba IR """ name = 'Numba_IR' url = "https://numba.readthedocs.io/en/stable/developer/architecture.html#stage-2-generate-the-numba-ir" aliases = ['numba_ir', 'numbair'] filenames = ['*.numba_ir'] mimetypes = ['text/x-numba_ir', 'text/x-numbair'] version_added = '2.19'
identifier = r'\$[a-zA-Z0-9._]+' fun_or_var = r'([a-zA-Z_]+[a-zA-Z0-9]*)'
tokens = { 'root' : [ (r'(label)(\ [0-9]+)(:)$', bygroups(Keyword, Name.Label, Punctuation)),
(r'=', Operator), include('whitespace'), include('keyword'),
(identifier, Name.Variable), (fun_or_var + r'(\()', bygroups(Name.Function, Punctuation)), (fun_or_var + r'(\=)', bygroups(Name.Attribute, Punctuation)), (fun_or_var, Name.Constant), (r'[0-9]+', Number),
# <built-in function some> (r'<[^>\n]*>', String),
(r'[=<>{}\[\]()*.,!\':]|x\b', Punctuation) ],
'keyword':[ (words(( 'del', 'jump', 'call', 'branch', ), suffix=' '), Keyword), ],
'whitespace': [ (r'(\n|\s)+', Whitespace), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513""" pygments.lexers.objective ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Objective-C family languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, using, this, words, \ inherit, defaultfrom pygments.token import Text, Keyword, Name, String, Operator, \ Number, Punctuation, Literal, Comment, Whitespace
from pygments.lexers.c_cpp import CLexer, CppLexer
__all__ = ['ObjectiveCLexer', 'ObjectiveCppLexer', 'LogosLexer', 'SwiftLexer']
def objective(baselexer): """ Generate a subclass of baselexer that accepts the Objective-C syntax extensions. """
# Have to be careful not to accidentally match JavaDoc/Doxygen syntax here, # since that's quite common in ordinary C/C++ files. It's OK to match # JavaDoc/Doxygen keywords that only apply to Objective-C, mind. # # The upshot of this is that we CANNOT match @class or @interface _oc_keywords = re.compile(r'@(?:end|implementation|protocol)')
# Matches [ <ws>? identifier <ws> ( identifier <ws>? ] | identifier? : ) # (note the identifier is *optional* when there is a ':'!) _oc_message = re.compile(r'\[\s*[a-zA-Z_]\w*\s+' r'(?:[a-zA-Z_]\w*\s*\]|' r'(?:[a-zA-Z_]\w*)?:)')
class GeneratedObjectiveCVariant(baselexer): """ Implements Objective-C syntax on top of an existing C family lexer. """
tokens = { 'statements': [ (r'@"', String, 'string'), (r'@(YES|NO)', Number), (r"@'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'@(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), (r'@(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'@0x[0-9a-fA-F]+[Ll]?', Number.Hex), (r'@0[0-7]+[Ll]?', Number.Oct), (r'@\d+[Ll]?', Number.Integer), (r'@\(', Literal, 'literal_number'), (r'@\[', Literal, 'literal_array'), (r'@\{', Literal, 'literal_dictionary'), (words(( '@selector', '@private', '@protected', '@public', '@encode', '@synchronized', '@try', '@throw', '@catch', '@finally', '@end', '@property', '@synthesize', '__bridge', '__bridge_transfer', '__autoreleasing', '__block', '__weak', '__strong', 'weak', 'strong', 'copy', 'retain', 'assign', 'unsafe_unretained', 'atomic', 'nonatomic', 'readonly', 'readwrite', 'setter', 'getter', 'typeof', 'in', 'out', 'inout', 'release', 'class', '@dynamic', '@optional', '@required', '@autoreleasepool', '@import'), suffix=r'\b'), Keyword), (words(('id', 'instancetype', 'Class', 'IMP', 'SEL', 'BOOL', 'IBOutlet', 'IBAction', 'unichar'), suffix=r'\b'), Keyword.Type), (r'@(true|false|YES|NO)\n', Name.Builtin), (r'(YES|NO|nil|self|super)\b', Name.Builtin), # Carbon types (r'(Boolean|UInt8|SInt8|UInt16|SInt16|UInt32|SInt32)\b', Keyword.Type), # Carbon built-ins (r'(TRUE|FALSE)\b', Name.Builtin), (r'(@interface|@implementation)(\s+)', bygroups(Keyword, Text), ('#pop', 'oc_classname')), (r'(@class|@protocol)(\s+)', bygroups(Keyword, Text), ('#pop', 'oc_forward_classname')), # @ can also prefix other expressions like @{...} or @(...) (r'@', Punctuation), inherit, ], 'oc_classname': [ # interface definition that inherits (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?(\s*)(\{)', bygroups(Name.Class, Text, Name.Class, Text, Punctuation), ('#pop', 'oc_ivars')), (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?', bygroups(Name.Class, Text, Name.Class), '#pop'), # interface definition for a category (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))(\s*)(\{)', bygroups(Name.Class, Text, Name.Label, Text, Punctuation), ('#pop', 'oc_ivars')), (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))', bygroups(Name.Class, Text, Name.Label), '#pop'), # simple interface / implementation (r'([a-zA-Z$_][\w$]*)(\s*)(\{)', bygroups(Name.Class, Text, Punctuation), ('#pop', 'oc_ivars')), (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop') ], 'oc_forward_classname': [ (r'([a-zA-Z$_][\w$]*)(\s*,\s*)', bygroups(Name.Class, Text), 'oc_forward_classname'), (r'([a-zA-Z$_][\w$]*)(\s*;?)', bygroups(Name.Class, Text), '#pop') ], 'oc_ivars': [ include('whitespace'), include('statements'), (';', Punctuation), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], 'root': [ # methods (r'^([-+])(\s*)' # method marker r'(\(.*?\))?(\s*)' # return type r'([a-zA-Z$_][\w$]*:?)', # begin of method name bygroups(Punctuation, Text, using(this), Text, Name.Function), 'method'), inherit, ], 'method': [ include('whitespace'), # TODO unsure if ellipses are allowed elsewhere, see # discussion in Issue 789 (r',', Punctuation), (r'\.\.\.', Punctuation), (r'(\(.*?\))(\s*)([a-zA-Z$_][\w$]*)', bygroups(using(this), Text, Name.Variable)), (r'[a-zA-Z$_][\w$]*:', Name.Function), (';', Punctuation, '#pop'), (r'\{', Punctuation, 'function'), default('#pop'), ], 'literal_number': [ (r'\(', Punctuation, 'literal_number_inner'), (r'\)', Literal, '#pop'), include('statement'), ], 'literal_number_inner': [ (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), include('statement'), ], 'literal_array': [ (r'\[', Punctuation, 'literal_array_inner'), (r'\]', Literal, '#pop'), include('statement'), ], 'literal_array_inner': [ (r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), include('statement'), ], 'literal_dictionary': [ (r'\}', Literal, '#pop'), include('statement'), ], }
def analyse_text(text): if _oc_keywords.search(text): return 1.0 elif '@"' in text: # strings return 0.8 elif re.search('@[0-9]+', text): return 0.7 elif _oc_message.search(text): return 0.8 return 0
def get_tokens_unprocessed(self, text, stack=('root',)): from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \ COCOA_PROTOCOLS, COCOA_PRIMITIVES
for index, token, value in \ baselexer.get_tokens_unprocessed(self, text, stack): if token is Name or token is Name.Class: if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \ or value in COCOA_PRIMITIVES: token = Name.Builtin.Pseudo
yield index, token, value
return GeneratedObjectiveCVariant
class ObjectiveCLexer(objective(CLexer)): """ For Objective-C source code with preprocessor directives. """
name = 'Objective-C' url = 'https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html' aliases = ['objective-c', 'objectivec', 'obj-c', 'objc'] filenames = ['*.m', '*.h'] mimetypes = ['text/x-objective-c'] version_added = '' priority = 0.05 # Lower than C
class ObjectiveCppLexer(objective(CppLexer)): """ For Objective-C++ source code with preprocessor directives. """
name = 'Objective-C++' aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++'] filenames = ['*.mm', '*.hh'] mimetypes = ['text/x-objective-c++'] version_added = '' priority = 0.05 # Lower than C++
class LogosLexer(ObjectiveCppLexer): """ For Logos + Objective-C source code with preprocessor directives. """
name = 'Logos' aliases = ['logos'] filenames = ['*.x', '*.xi', '*.xm', '*.xmi'] mimetypes = ['text/x-logos'] version_added = '1.6' priority = 0.25
tokens = { 'statements': [ (r'(%orig|%log)\b', Keyword), (r'(%c)\b(\()(\s*)([a-zA-Z$_][\w$]*)(\s*)(\))', bygroups(Keyword, Punctuation, Text, Name.Class, Text, Punctuation)), (r'(%init)\b(\()', bygroups(Keyword, Punctuation), 'logos_init_directive'), (r'(%init)(?=\s*;)', bygroups(Keyword)), (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)', bygroups(Keyword, Text, Name.Class), '#pop'), (r'(%subclass)(\s+)', bygroups(Keyword, Text), ('#pop', 'logos_classname')), inherit, ], 'logos_init_directive': [ (r'\s+', Text), (',', Punctuation, ('logos_init_directive', '#pop')), (r'([a-zA-Z$_][\w$]*)(\s*)(=)(\s*)([^);]*)', bygroups(Name.Class, Text, Punctuation, Text, Text)), (r'([a-zA-Z$_][\w$]*)', Name.Class), (r'\)', Punctuation, '#pop'), ], 'logos_classname': [ (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?', bygroups(Name.Class, Text, Name.Class), '#pop'), (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop') ], 'root': [ (r'(%subclass)(\s+)', bygroups(Keyword, Text), 'logos_classname'), (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)', bygroups(Keyword, Text, Name.Class)), (r'(%config)(\s*\(\s*)(\w+)(\s*=)(.*?)(\)\s*)', bygroups(Keyword, Text, Name.Variable, Text, String, Text)), (r'(%ctor)(\s*)(\{)', bygroups(Keyword, Text, Punctuation), 'function'), (r'(%new)(\s*)(\()(.*?)(\))', bygroups(Keyword, Text, Keyword, String, Keyword)), (r'(\s*)(%end)(\s*)', bygroups(Text, Keyword, Text)), inherit, ], }
_logos_keywords = re.compile(r'%(?:hook|ctor|init|c\()')
def analyse_text(text): if LogosLexer._logos_keywords.search(text): return 1.0 return 0
class SwiftLexer(RegexLexer): """ For Swift source. """ name = 'Swift' url = 'https://www.swift.org/' filenames = ['*.swift'] aliases = ['swift'] mimetypes = ['text/x-swift'] version_added = '2.0'
tokens = { 'root': [ # Whitespace and Comments (r'\n', Text), (r'\s+', Whitespace), (r'//', Comment.Single, 'comment-single'), (r'/\*', Comment.Multiline, 'comment-multi'), (r'#(if|elseif|else|endif|available)\b', Comment.Preproc, 'preproc'),
# Keywords include('keywords'),
# Global Types (words(( 'Array', 'AutoreleasingUnsafeMutablePointer', 'BidirectionalReverseView', 'Bit', 'Bool', 'CFunctionPointer', 'COpaquePointer', 'CVaListPointer', 'Character', 'ClosedInterval', 'CollectionOfOne', 'ContiguousArray', 'Dictionary', 'DictionaryGenerator', 'DictionaryIndex', 'Double', 'EmptyCollection', 'EmptyGenerator', 'EnumerateGenerator', 'EnumerateSequence', 'FilterCollectionView', 'FilterCollectionViewIndex', 'FilterGenerator', 'FilterSequenceView', 'Float', 'Float80', 'FloatingPointClassification', 'GeneratorOf', 'GeneratorOfOne', 'GeneratorSequence', 'HalfOpenInterval', 'HeapBuffer', 'HeapBufferStorage', 'ImplicitlyUnwrappedOptional', 'IndexingGenerator', 'Int', 'Int16', 'Int32', 'Int64', 'Int8', 'LazyBidirectionalCollection', 'LazyForwardCollection', 'LazyRandomAccessCollection', 'LazySequence', 'MapCollectionView', 'MapSequenceGenerator', 'MapSequenceView', 'MirrorDisposition', 'ObjectIdentifier', 'OnHeap', 'Optional', 'PermutationGenerator', 'QuickLookObject', 'RandomAccessReverseView', 'Range', 'RangeGenerator', 'RawByte', 'Repeat', 'ReverseBidirectionalIndex', 'ReverseRandomAccessIndex', 'SequenceOf', 'SinkOf', 'Slice', 'StaticString', 'StrideThrough', 'StrideThroughGenerator', 'StrideTo', 'StrideToGenerator', 'String', 'UInt', 'UInt16', 'UInt32', 'UInt64', 'UInt8', 'UTF16', 'UTF32', 'UTF8', 'UnicodeDecodingResult', 'UnicodeScalar', 'Unmanaged', 'UnsafeBufferPointer', 'UnsafeBufferPointerGenerator', 'UnsafeMutableBufferPointer', 'UnsafeMutablePointer', 'UnsafePointer', 'Zip2', 'ZipGenerator2', # Protocols 'AbsoluteValuable', 'AnyObject', 'ArrayLiteralConvertible', 'BidirectionalIndexType', 'BitwiseOperationsType', 'BooleanLiteralConvertible', 'BooleanType', 'CVarArgType', 'CollectionType', 'Comparable', 'DebugPrintable', 'DictionaryLiteralConvertible', 'Equatable', 'ExtendedGraphemeClusterLiteralConvertible', 'ExtensibleCollectionType', 'FloatLiteralConvertible', 'FloatingPointType', 'ForwardIndexType', 'GeneratorType', 'Hashable', 'IntegerArithmeticType', 'IntegerLiteralConvertible', 'IntegerType', 'IntervalType', 'MirrorType', 'MutableCollectionType', 'MutableSliceable', 'NilLiteralConvertible', 'OutputStreamType', 'Printable', 'RandomAccessIndexType', 'RangeReplaceableCollectionType', 'RawOptionSetType', 'RawRepresentable', 'Reflectable', 'SequenceType', 'SignedIntegerType', 'SignedNumberType', 'SinkType', 'Sliceable', 'Streamable', 'Strideable', 'StringInterpolationConvertible', 'StringLiteralConvertible', 'UnicodeCodecType', 'UnicodeScalarLiteralConvertible', 'UnsignedIntegerType', '_ArrayBufferType', '_BidirectionalIndexType', '_CocoaStringType', '_CollectionType', '_Comparable', '_ExtensibleCollectionType', '_ForwardIndexType', '_Incrementable', '_IntegerArithmeticType', '_IntegerType', '_ObjectiveCBridgeable', '_RandomAccessIndexType', '_RawOptionSetType', '_SequenceType', '_Sequence_Type', '_SignedIntegerType', '_SignedNumberType', '_Sliceable', '_Strideable', '_SwiftNSArrayRequiredOverridesType', '_SwiftNSArrayType', '_SwiftNSCopyingType', '_SwiftNSDictionaryRequiredOverridesType', '_SwiftNSDictionaryType', '_SwiftNSEnumeratorType', '_SwiftNSFastEnumerationType', '_SwiftNSStringRequiredOverridesType', '_SwiftNSStringType', '_UnsignedIntegerType', # Variables 'C_ARGC', 'C_ARGV', 'Process', # Typealiases 'Any', 'AnyClass', 'BooleanLiteralType', 'CBool', 'CChar', 'CChar16', 'CChar32', 'CDouble', 'CFloat', 'CInt', 'CLong', 'CLongLong', 'CShort', 'CSignedChar', 'CUnsignedInt', 'CUnsignedLong', 'CUnsignedShort', 'CWideChar', 'ExtendedGraphemeClusterType', 'Float32', 'Float64', 'FloatLiteralType', 'IntMax', 'IntegerLiteralType', 'StringLiteralType', 'UIntMax', 'UWord', 'UnicodeScalarType', 'Void', 'Word', # Foundation/Cocoa 'NSErrorPointer', 'NSObjectProtocol', 'Selector'), suffix=r'\b'), Name.Builtin), # Functions (words(( 'abs', 'advance', 'alignof', 'alignofValue', 'assert', 'assertionFailure', 'contains', 'count', 'countElements', 'debugPrint', 'debugPrintln', 'distance', 'dropFirst', 'dropLast', 'dump', 'enumerate', 'equal', 'extend', 'fatalError', 'filter', 'find', 'first', 'getVaList', 'indices', 'insert', 'isEmpty', 'join', 'last', 'lazy', 'lexicographicalCompare', 'map', 'max', 'maxElement', 'min', 'minElement', 'numericCast', 'overlaps', 'partition', 'precondition', 'preconditionFailure', 'prefix', 'print', 'println', 'reduce', 'reflect', 'removeAll', 'removeAtIndex', 'removeLast', 'removeRange', 'reverse', 'sizeof', 'sizeofValue', 'sort', 'sorted', 'splice', 'split', 'startsWith', 'stride', 'strideof', 'strideofValue', 'suffix', 'swap', 'toDebugString', 'toString', 'transcode', 'underestimateCount', 'unsafeAddressOf', 'unsafeBitCast', 'unsafeDowncast', 'withExtendedLifetime', 'withUnsafeMutablePointer', 'withUnsafeMutablePointers', 'withUnsafePointer', 'withUnsafePointers', 'withVaList'), suffix=r'\b'), Name.Builtin.Pseudo),
# Implicit Block Variables (r'\$\d+', Name.Variable),
# Binary Literal (r'0b[01_]+', Number.Bin), # Octal Literal (r'0o[0-7_]+', Number.Oct), # Hexadecimal Literal (r'0x[0-9a-fA-F_]+', Number.Hex), # Decimal Literal (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|' r'\.[0-9_]*|[eE][+\-]?[0-9_]+)', Number.Float), (r'[0-9][0-9_]*', Number.Integer), # String Literal (r'"""', String, 'string-multi'), (r'"', String, 'string'),
# Operators and Punctuation (r'[(){}\[\].,:;=@#`?]|->|[<&?](?=\w)|(?<=\w)[>!?]', Punctuation), (r'[/=\-+!*%<>&|^?~]+', Operator),
# Identifier (r'[a-zA-Z_]\w*', Name) ], 'keywords': [ (words(( 'as', 'async', 'await', 'break', 'case', 'catch', 'continue', 'default', 'defer', 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'is', 'repeat', 'return', '#selector', 'switch', 'throw', 'try', 'where', 'while'), suffix=r'\b'), Keyword), (r'@availability\([^)]+\)', Keyword.Reserved), (words(( 'associativity', 'convenience', 'dynamic', 'didSet', 'final', 'get', 'indirect', 'infix', 'inout', 'lazy', 'left', 'mutating', 'none', 'nonmutating', 'optional', 'override', 'postfix', 'precedence', 'prefix', 'Protocol', 'required', 'rethrows', 'right', 'set', 'throws', 'Type', 'unowned', 'weak', 'willSet', '@availability', '@autoclosure', '@noreturn', '@NSApplicationMain', '@NSCopying', '@NSManaged', '@objc', '@UIApplicationMain', '@IBAction', '@IBDesignable', '@IBInspectable', '@IBOutlet'), suffix=r'\b'), Keyword.Reserved), (r'(as|dynamicType|false|is|nil|self|Self|super|true|__COLUMN__' r'|__FILE__|__FUNCTION__|__LINE__|_' r'|#(?:file|line|column|function))\b', Keyword.Constant), (r'import\b', Keyword.Declaration, 'module'), (r'(class|enum|extension|struct|protocol)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Class)), (r'(func)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Function)), (r'(var|let)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Variable)), (words(( 'actor', 'associatedtype', 'class', 'deinit', 'enum', 'extension', 'func', 'import', 'init', 'internal', 'let', 'operator', 'private', 'protocol', 'public', 'static', 'struct', 'subscript', 'typealias', 'var'), suffix=r'\b'), Keyword.Declaration) ], 'comment': [ (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):', Comment.Special) ],
# Nested 'comment-single': [ (r'\n', Whitespace, '#pop'), include('comment'), (r'[^\n]+', Comment.Single) ], 'comment-multi': [ include('comment'), (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]+', Comment.Multiline) ], 'module': [ (r'\n', Whitespace, '#pop'), (r'[a-zA-Z_]\w*', Name.Class), include('root') ], 'preproc': [ (r'\n', Whitespace, '#pop'), include('keywords'), (r'[A-Za-z]\w*', Comment.Preproc), include('root') ], 'string': [ (r'"', String, '#pop'), include("string-common"), ], 'string-multi': [ (r'"""', String, '#pop'), include("string-common"), ], 'string-common': [ (r'\\\(', String.Interpol, 'string-intp'), (r"""\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}""", String.Escape), (r'[^\\"]+', String), (r'\\', String) ], 'string-intp': [ (r'\(', String.Interpol, '#push'), (r'\)', String.Interpol, '#pop'), include('root') ] }
def get_tokens_unprocessed(self, text): from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \ COCOA_PROTOCOLS, COCOA_PRIMITIVES
for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name or token is Name.Class: if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \ or value in COCOA_PRIMITIVES: token = Name.Builtin.Pseudo
yield index, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596""" pygments.lexers.openscad ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for the OpenSCAD languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, words, includefrom pygments.token import Text, Comment, Punctuation, Operator, Keyword, Name, Number, Whitespace, Literal, String
__all__ = ['OpenScadLexer']
class OpenScadLexer(RegexLexer): """For openSCAD code. """ name = "OpenSCAD" url = "https://openscad.org/" aliases = ["openscad"] filenames = ["*.scad"] mimetypes = ["application/x-openscad"] version_added = '2.16'
tokens = { "root": [ (r"[^\S\n]+", Whitespace), (r'//', Comment.Single, 'comment-single'), (r'/\*', Comment.Multiline, 'comment-multi'), (r"[{}\[\]\(\),;:]", Punctuation), (r"[*!#%\-+=?/]", Operator), (r"<=|<|==|!=|>=|>|&&|\|\|", Operator), (r"\$(f[asn]|t|vp[rtd]|children)", Operator), (r"(undef|PI)\b", Keyword.Constant), ( r"(use|include)((?:\s|\\\\s)+)", bygroups(Keyword.Namespace, Text), "includes", ), (r"(module)(\s*)([^\s\(]+)", bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r"(function)(\s*)([^\s\(]+)", bygroups(Keyword.Declaration, Whitespace, Name.Function)), (words(("true", "false"), prefix=r"\b", suffix=r"\b"), Literal), (words(( "function", "module", "include", "use", "for", "intersection_for", "if", "else", "return" ), prefix=r"\b", suffix=r"\b"), Keyword ), (words(( "circle", "square", "polygon", "text", "sphere", "cube", "cylinder", "polyhedron", "translate", "rotate", "scale", "resize", "mirror", "multmatrix", "color", "offset", "hull", "minkowski", "union", "difference", "intersection", "abs", "sign", "sin", "cos", "tan", "acos", "asin", "atan", "atan2", "floor", "round", "ceil", "ln", "log", "pow", "sqrt", "exp", "rands", "min", "max", "concat", "lookup", "str", "chr", "search", "version", "version_num", "norm", "cross", "parent_module", "echo", "import", "import_dxf", "dxf_linear_extrude", "linear_extrude", "rotate_extrude", "surface", "projection", "render", "dxf_cross", "dxf_dim", "let", "assign", "len" ), prefix=r"\b", suffix=r"\b"), Name.Builtin ), (r"\bchildren\b", Name.Builtin.Pseudo), (r'""".*?"""', String.Double), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"-?\d+(\.\d+)?(e[+-]?\d+)?", Number), (r"\w+", Name), ], "includes": [ ( r"(<)([^>]*)(>)", bygroups(Punctuation, Comment.PreprocFile, Punctuation), ), ], 'comment': [ (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):', Comment.Special) ], 'comment-single': [ (r'\n', Text, '#pop'), include('comment'), (r'[^\n]+', Comment.Single) ], 'comment-multi': [ include('comment'), (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], }1234567891011121314151617181920212223242526272829303132333435363738394041""" pygments.lexers.other ~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
# ruff: noqa: F401from pygments.lexers.sql import SqlLexer, MySqlLexer, SqliteConsoleLexerfrom pygments.lexers.shell import BashLexer, BashSessionLexer, BatchLexer, \ TcshLexerfrom pygments.lexers.robotframework import RobotFrameworkLexerfrom pygments.lexers.testing import GherkinLexerfrom pygments.lexers.esoteric import BrainfuckLexer, BefungeLexer, RedcodeLexerfrom pygments.lexers.prolog import LogtalkLexerfrom pygments.lexers.snobol import SnobolLexerfrom pygments.lexers.rebol import RebolLexerfrom pygments.lexers.configs import KconfigLexer, Cfengine3Lexerfrom pygments.lexers.modeling import ModelicaLexerfrom pygments.lexers.scripting import AppleScriptLexer, MOOCodeLexer, \ HybrisLexerfrom pygments.lexers.graphics import PostScriptLexer, GnuplotLexer, \ AsymptoteLexer, PovrayLexerfrom pygments.lexers.business import ABAPLexer, OpenEdgeLexer, \ GoodDataCLLexer, MaqlLexerfrom pygments.lexers.automation import AutoItLexer, AutohotkeyLexerfrom pygments.lexers.dsls import ProtoBufLexer, BroLexer, PuppetLexer, \ MscgenLexer, VGLLexerfrom pygments.lexers.basic import CbmBasicV2Lexerfrom pygments.lexers.pawn import SourcePawnLexer, PawnLexerfrom pygments.lexers.ecl import ECLLexerfrom pygments.lexers.urbi import UrbiscriptLexerfrom pygments.lexers.smalltalk import SmalltalkLexer, NewspeakLexerfrom pygments.lexers.installers import NSISLexer, RPMSpecLexerfrom pygments.lexers.textedit import AwkLexerfrom pygments.lexers.smv import NuSMVLexer
__all__ = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778""" pygments.lexers.parasail ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for ParaSail.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, includefrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Literal
__all__ = ['ParaSailLexer']
class ParaSailLexer(RegexLexer): """ For ParaSail source code. """
name = 'ParaSail' url = 'http://www.parasail-lang.org' aliases = ['parasail'] filenames = ['*.psi', '*.psl'] mimetypes = ['text/x-parasail'] version_added = '2.1'
flags = re.MULTILINE
tokens = { 'root': [ (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'\b(and|or|xor)=', Operator.Word), (r'\b(and(\s+then)?|or(\s+else)?|xor|rem|mod|' r'(is|not)\s+null)\b', Operator.Word), # Keywords (r'\b(abs|abstract|all|block|class|concurrent|const|continue|' r'each|end|exit|extends|exports|forward|func|global|implements|' r'import|in|interface|is|lambda|locked|new|not|null|of|op|' r'optional|private|queued|ref|return|reverse|separate|some|' r'type|until|var|with|' # Control flow r'if|then|else|elsif|case|for|while|loop)\b', Keyword.Reserved), (r'(abstract\s+)?(interface|class|op|func|type)', Keyword.Declaration), # Literals (r'"[^"]*"', String), (r'\\[\'ntrf"0]', String.Escape), (r'#[a-zA-Z]\w*', Literal), # Enumeration include('numbers'), (r"'[^']'", String.Char), (r'[a-zA-Z]\w*', Name), # Operators and Punctuation (r'(<==|==>|<=>|\*\*=|<\|=|<<=|>>=|==|!=|=\?|<=|>=|' r'\*\*|<<|>>|=>|:=|\+=|-=|\*=|\|=|\||/=|\+|-|\*|/|' r'\.\.|<\.\.|\.\.<|<\.\.<)', Operator), (r'(<|>|\[|\]|\(|\)|\||:|;|,|.|\{|\}|->)', Punctuation), (r'\n+', Text), ], 'numbers': [ (r'\d[0-9_]*#[0-9a-fA-F][0-9a-fA-F_]*#', Number.Hex), # any base (r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex), # C-like hex (r'0[bB][01][01_]*', Number.Bin), # C-like bin (r'\d[0-9_]*\.\d[0-9_]*[eE][+-]\d[0-9_]*', # float exp Number.Float), (r'\d[0-9_]*\.\d[0-9_]*', Number.Float), # float (r'\d[0-9_]*', Number.Integer), # integer ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798""" pygments.lexers.parsers ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for parser generators.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, DelegatingLexer, \ include, bygroups, usingfrom pygments.token import Punctuation, Other, Text, Comment, Operator, \ Keyword, Name, String, Number, Whitespacefrom pygments.lexers.jvm import JavaLexerfrom pygments.lexers.c_cpp import CLexer, CppLexerfrom pygments.lexers.objective import ObjectiveCLexerfrom pygments.lexers.d import DLexerfrom pygments.lexers.dotnet import CSharpLexerfrom pygments.lexers.ruby import RubyLexerfrom pygments.lexers.python import PythonLexerfrom pygments.lexers.perl import PerlLexer
__all__ = ['RagelLexer', 'RagelEmbeddedLexer', 'RagelCLexer', 'RagelDLexer', 'RagelCppLexer', 'RagelObjectiveCLexer', 'RagelRubyLexer', 'RagelJavaLexer', 'AntlrLexer', 'AntlrPythonLexer', 'AntlrPerlLexer', 'AntlrRubyLexer', 'AntlrCppLexer', 'AntlrCSharpLexer', 'AntlrObjectiveCLexer', 'AntlrJavaLexer', 'AntlrActionScriptLexer', 'TreetopLexer', 'EbnfLexer']
class RagelLexer(RegexLexer): """A pure `Ragel <www.colm.net/open-source/ragel>`_ lexer.
Use this for fragments of Ragel. For ``.rl`` files, use :class:`RagelEmbeddedLexer` instead (or one of the language-specific subclasses). """
name = 'Ragel' url = 'http://www.colm.net/open-source/ragel/' aliases = ['ragel'] filenames = [] version_added = '1.1'
tokens = { 'whitespace': [ (r'\s+', Whitespace) ], 'comments': [ (r'\#.*$', Comment), ], 'keywords': [ (r'(access|action|alphtype)\b', Keyword), (r'(getkey|write|machine|include)\b', Keyword), (r'(any|ascii|extend|alpha|digit|alnum|lower|upper)\b', Keyword), (r'(xdigit|cntrl|graph|print|punct|space|zlen|empty)\b', Keyword) ], 'numbers': [ (r'0x[0-9A-Fa-f]+', Number.Hex), (r'[+-]?[0-9]+', Number.Integer), ], 'literals': [ (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'\[(\\\\|\\[^\\]|[^\\\]])*\]', String), # square bracket literals (r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/', String.Regex), # regular expressions ], 'identifiers': [ (r'[a-zA-Z_]\w*', Name.Variable), ], 'operators': [ (r',', Operator), # Join (r'\||&|--?', Operator), # Union, Intersection and Subtraction (r'\.|<:|:>>?', Operator), # Concatention (r':', Operator), # Label (r'->', Operator), # Epsilon Transition (r'(>|\$|%|<|@|<>)(/|eof\b)', Operator), # EOF Actions (r'(>|\$|%|<|@|<>)(!|err\b)', Operator), # Global Error Actions (r'(>|\$|%|<|@|<>)(\^|lerr\b)', Operator), # Local Error Actions (r'(>|\$|%|<|@|<>)(~|to\b)', Operator), # To-State Actions (r'(>|\$|%|<|@|<>)(\*|from\b)', Operator), # From-State Actions (r'>|@|\$|%', Operator), # Transition Actions and Priorities (r'\*|\?|\+|\{[0-9]*,[0-9]*\}', Operator), # Repetition (r'!|\^', Operator), # Negation (r'\(|\)', Operator), # Grouping ], 'root': [ include('literals'), include('whitespace'), include('comments'), include('keywords'), include('numbers'), include('identifiers'), include('operators'), (r'\{', Punctuation, 'host'), (r'=', Operator), (r';', Punctuation), ], 'host': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks r'[^{}\'"/#]+', # exclude unsafe characters r'[^\\]\\[{}]', # allow escaped { or }
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'//.*$\n?', # single line comment r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment r'\#.*$\n?', # ruby comment
# regular expression: There's no reason for it to start # with a * and this stops confusion with comments. r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
# / is safe now that we've handled regex and javadoc comments r'/', )) + r')+', Other),
(r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], }
class RagelEmbeddedLexer(RegexLexer): """ A lexer for Ragel embedded in a host language file.
This will only highlight Ragel statements. If you want host language highlighting then call the language-specific Ragel lexer. """
name = 'Embedded Ragel' aliases = ['ragel-em'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
tokens = { 'root': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks r'[^%\'"/#]+', # exclude unsafe characters r'%(?=[^%]|$)', # a single % sign is okay, just not 2 of them
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment r'//.*$\n?', # single line comment r'\#.*$\n?', # ruby/ragel comment r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/', # regular expression
# / is safe now that we've handled regex and javadoc comments r'/', )) + r')+', Other),
# Single Line FSM. # Please don't put a quoted newline in a single line FSM. # That's just mean. It will break this. (r'(%%)(?![{%])(.*)($|;)(\n?)', bygroups(Punctuation, using(RagelLexer), Punctuation, Text)),
# Multi Line FSM. (r'(%%%%|%%)\{', Punctuation, 'multi-line-fsm'), ], 'multi-line-fsm': [ (r'(' + r'|'.join(( # keep ragel code in largest possible chunks. r'(' + r'|'.join(( r'[^}\'"\[/#]', # exclude unsafe characters r'\}(?=[^%]|$)', # } is okay as long as it's not followed by % r'\}%(?=[^%]|$)', # ...well, one %'s okay, just not two... r'[^\\]\\[{}]', # ...and } is okay if it's escaped
# allow / if it's preceded with one of these symbols # (ragel EOF actions) r'(>|\$|%|<|@|<>)/',
# specifically allow regex followed immediately by * # so it doesn't get mistaken for a comment r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/\*',
# allow / as long as it's not followed by another / or by a * r'/(?=[^/*]|$)',
# We want to match as many of these as we can in one block. # Not sure if we need the + sign here, # does it help performance? )) + r')+',
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r"\[(\\\\|\\[^\\]|[^\]\\])*\]", # square bracket literal r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment r'//.*$\n?', # single line comment r'\#.*$\n?', # ruby/ragel comment )) + r')+', using(RagelLexer)),
(r'\}%%', Punctuation, '#pop'), ] }
def analyse_text(text): return '@LANG: indep' in text
class RagelRubyLexer(DelegatingLexer): """ A lexer for Ragel in a Ruby host file. """
name = 'Ragel in Ruby Host' aliases = ['ragel-ruby', 'ragel-rb'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(RubyLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: ruby' in text
class RagelCLexer(DelegatingLexer): """ A lexer for Ragel in a C host file. """
name = 'Ragel in C Host' aliases = ['ragel-c'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(CLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: c' in text
class RagelDLexer(DelegatingLexer): """ A lexer for Ragel in a D host file. """
name = 'Ragel in D Host' aliases = ['ragel-d'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(DLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: d' in text
class RagelCppLexer(DelegatingLexer): """ A lexer for Ragel in a C++ host file. """
name = 'Ragel in CPP Host' aliases = ['ragel-cpp'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(CppLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: c++' in text
class RagelObjectiveCLexer(DelegatingLexer): """ A lexer for Ragel in an Objective C host file. """
name = 'Ragel in Objective C Host' aliases = ['ragel-objc'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(ObjectiveCLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: objc' in text
class RagelJavaLexer(DelegatingLexer): """ A lexer for Ragel in a Java host file. """
name = 'Ragel in Java Host' aliases = ['ragel-java'] filenames = ['*.rl'] url = 'http://www.colm.net/open-source/ragel/' version_added = '1.1'
def __init__(self, **options): super().__init__(JavaLexer, RagelEmbeddedLexer, **options)
def analyse_text(text): return '@LANG: java' in text
class AntlrLexer(RegexLexer): """ Generic ANTLR Lexer. Should not be called directly, instead use DelegatingLexer for your target language. """
name = 'ANTLR' aliases = ['antlr'] filenames = [] url = 'https://www.antlr.org' version_added = '1.1'
_id = r'[A-Za-z]\w*' _TOKEN_REF = r'[A-Z]\w*' _RULE_REF = r'[a-z]\w*' _STRING_LITERAL = r'\'(?:\\\\|\\\'|[^\']*)\'' _INT = r'[0-9]+'
tokens = { 'whitespace': [ (r'\s+', Whitespace), ], 'comments': [ (r'//.*$', Comment), (r'/\*(.|\n)*?\*/', Comment), ], 'root': [ include('whitespace'), include('comments'),
(r'(lexer|parser|tree)?(\s*)(grammar\b)(\s*)(' + _id + ')(;)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Class, Punctuation)), # optionsSpec (r'options\b', Keyword, 'options'), # tokensSpec (r'tokens\b', Keyword, 'tokens'), # attrScope (r'(scope)(\s*)(' + _id + r')(\s*)(\{)', bygroups(Keyword, Whitespace, Name.Variable, Whitespace, Punctuation), 'action'), # exception (r'(catch|finally)\b', Keyword, 'exception'), # action (r'(@' + _id + r')(\s*)(::)?(\s*)(' + _id + r')(\s*)(\{)', bygroups(Name.Label, Whitespace, Punctuation, Whitespace, Name.Label, Whitespace, Punctuation), 'action'), # rule (r'((?:protected|private|public|fragment)\b)?(\s*)(' + _id + ')(!)?', bygroups(Keyword, Whitespace, Name.Label, Punctuation), ('rule-alts', 'rule-prelims')), ], 'exception': [ (r'\n', Whitespace, '#pop'), (r'\s', Whitespace), include('comments'),
(r'\[', Punctuation, 'nested-arg-action'), (r'\{', Punctuation, 'action'), ], 'rule-prelims': [ include('whitespace'), include('comments'),
(r'returns\b', Keyword), (r'\[', Punctuation, 'nested-arg-action'), (r'\{', Punctuation, 'action'), # throwsSpec (r'(throws)(\s+)(' + _id + ')', bygroups(Keyword, Whitespace, Name.Label)), (r'(,)(\s*)(' + _id + ')', bygroups(Punctuation, Whitespace, Name.Label)), # Additional throws # optionsSpec (r'options\b', Keyword, 'options'), # ruleScopeSpec - scope followed by target language code or name of action # TODO finish implementing other possibilities for scope # L173 ANTLRv3.g from ANTLR book (r'(scope)(\s+)(\{)', bygroups(Keyword, Whitespace, Punctuation), 'action'), (r'(scope)(\s+)(' + _id + r')(\s*)(;)', bygroups(Keyword, Whitespace, Name.Label, Whitespace, Punctuation)), # ruleAction (r'(@' + _id + r')(\s*)(\{)', bygroups(Name.Label, Whitespace, Punctuation), 'action'), # finished prelims, go to rule alts! (r':', Punctuation, '#pop') ], 'rule-alts': [ include('whitespace'), include('comments'),
# These might need to go in a separate 'block' state triggered by ( (r'options\b', Keyword, 'options'), (r':', Punctuation),
# literals (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'<<([^>]|>[^>])>>', String), # identifiers # Tokens start with capital letter. (r'\$?[A-Z_]\w*', Name.Constant), # Rules start with small letter. (r'\$?[a-z_]\w*', Name.Variable), # operators (r'(\+|\||->|=>|=|\(|\)|\.\.|\.|\?|\*|\^|!|\#|~)', Operator), (r',', Punctuation), (r'\[', Punctuation, 'nested-arg-action'), (r'\{', Punctuation, 'action'), (r';', Punctuation, '#pop') ], 'tokens': [ include('whitespace'), include('comments'), (r'\{', Punctuation), (r'(' + _TOKEN_REF + r')(\s*)(=)?(\s*)(' + _STRING_LITERAL + r')?(\s*)(;)', bygroups(Name.Label, Whitespace, Punctuation, Whitespace, String, Whitespace, Punctuation)), (r'\}', Punctuation, '#pop'), ], 'options': [ include('whitespace'), include('comments'), (r'\{', Punctuation), (r'(' + _id + r')(\s*)(=)(\s*)(' + '|'.join((_id, _STRING_LITERAL, _INT, r'\*')) + r')(\s*)(;)', bygroups(Name.Variable, Whitespace, Punctuation, Whitespace, Text, Whitespace, Punctuation)), (r'\}', Punctuation, '#pop'), ], 'action': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks r'[^${}\'"/\\]+', # exclude unsafe characters
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'//.*$\n?', # single line comment r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment
# regular expression: There's no reason for it to start # with a * and this stops confusion with comments. r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
# backslashes are okay, as long as we are not backslashing a % r'\\(?!%)',
# Now that we've handled regex and javadoc comments # it's safe to let / through. r'/', )) + r')+', Other), (r'(\\)(%)', bygroups(Punctuation, Other)), (r'(\$[a-zA-Z]+)(\.?)(text|value)?', bygroups(Name.Variable, Punctuation, Name.Property)), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], 'nested-arg-action': [ (r'(' + r'|'.join(( # keep host code in largest possible chunks. r'[^$\[\]\'"/]+', # exclude unsafe characters
# strings and comments may safely contain unsafe characters r'"(\\\\|\\[^\\]|[^"\\])*"', r"'(\\\\|\\[^\\]|[^'\\])*'", r'//.*$\n?', # single line comment r'/\*(.|\n)*?\*/', # multi-line javadoc-style comment
# regular expression: There's no reason for it to start # with a * and this stops confusion with comments. r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
# Now that we've handled regex and javadoc comments # it's safe to let / through. r'/', )) + r')+', Other),
(r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), (r'(\$[a-zA-Z]+)(\.?)(text|value)?', bygroups(Name.Variable, Punctuation, Name.Property)), (r'(\\\\|\\\]|\\\[|[^\[\]])+', Other), ] }
def analyse_text(text): return re.search(r'^\s*grammar\s+[a-zA-Z0-9]+\s*;', text, re.M)
# http://www.antlr.org/wiki/display/ANTLR3/Code+Generation+Targets
class AntlrCppLexer(DelegatingLexer): """ ANTLR with C++ Target """
name = 'ANTLR With CPP Target' aliases = ['antlr-cpp'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(CppLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*C\s*;', text, re.M)
class AntlrObjectiveCLexer(DelegatingLexer): """ ANTLR with Objective-C Target """
name = 'ANTLR With ObjectiveC Target' aliases = ['antlr-objc'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(ObjectiveCLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*ObjC\s*;', text)
class AntlrCSharpLexer(DelegatingLexer): """ ANTLR with C# Target """
name = 'ANTLR With C# Target' aliases = ['antlr-csharp', 'antlr-c#'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(CSharpLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*CSharp2\s*;', text, re.M)
class AntlrPythonLexer(DelegatingLexer): """ ANTLR with Python Target """
name = 'ANTLR With Python Target' aliases = ['antlr-python'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(PythonLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*Python\s*;', text, re.M)
class AntlrJavaLexer(DelegatingLexer): """ ANTLR with Java Target """
name = 'ANTLR With Java Target' aliases = ['antlr-java'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(JavaLexer, AntlrLexer, **options)
def analyse_text(text): # Antlr language is Java by default return AntlrLexer.analyse_text(text) and 0.9
class AntlrRubyLexer(DelegatingLexer): """ ANTLR with Ruby Target """
name = 'ANTLR With Ruby Target' aliases = ['antlr-ruby', 'antlr-rb'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(RubyLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*Ruby\s*;', text, re.M)
class AntlrPerlLexer(DelegatingLexer): """ ANTLR with Perl Target """
name = 'ANTLR With Perl Target' aliases = ['antlr-perl'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): super().__init__(PerlLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*Perl5\s*;', text, re.M)
class AntlrActionScriptLexer(DelegatingLexer): """ ANTLR with ActionScript Target """
name = 'ANTLR With ActionScript Target' aliases = ['antlr-actionscript', 'antlr-as'] filenames = ['*.G', '*.g'] url = 'https://www.antlr.org' version_added = '1.1'
def __init__(self, **options): from pygments.lexers.actionscript import ActionScriptLexer super().__init__(ActionScriptLexer, AntlrLexer, **options)
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*ActionScript\s*;', text, re.M)
class TreetopBaseLexer(RegexLexer): """ A base lexer for `Treetop <http://treetop.rubyforge.org/>`_ grammars. Not for direct use; use :class:`TreetopLexer` instead.
.. versionadded:: 1.6 """
tokens = { 'root': [ include('space'), (r'require[ \t]+[^\n\r]+[\n\r]', Other), (r'module\b', Keyword.Namespace, 'module'), (r'grammar\b', Keyword, 'grammar'), ], 'module': [ include('space'), include('end'), (r'module\b', Keyword, '#push'), (r'grammar\b', Keyword, 'grammar'), (r'[A-Z]\w*(?:::[A-Z]\w*)*', Name.Namespace), ], 'grammar': [ include('space'), include('end'), (r'rule\b', Keyword, 'rule'), (r'include\b', Keyword, 'include'), (r'[A-Z]\w*', Name), ], 'include': [ include('space'), (r'[A-Z]\w*(?:::[A-Z]\w*)*', Name.Class, '#pop'), ], 'rule': [ include('space'), include('end'), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'([A-Za-z_]\w*)(:)', bygroups(Name.Label, Punctuation)), (r'[A-Za-z_]\w*', Name), (r'[()]', Punctuation), (r'[?+*/&!~]', Operator), (r'\[(?:\\.|\[:\^?[a-z]+:\]|[^\\\]])+\]', String.Regex), (r'([0-9]*)(\.\.)([0-9]*)', bygroups(Number.Integer, Operator, Number.Integer)), (r'(<)([^>]+)(>)', bygroups(Punctuation, Name.Class, Punctuation)), (r'\{', Punctuation, 'inline_module'), (r'\.', String.Regex), ], 'inline_module': [ (r'\{', Other, 'ruby'), (r'\}', Punctuation, '#pop'), (r'[^{}]+', Other), ], 'ruby': [ (r'\{', Other, '#push'), (r'\}', Other, '#pop'), (r'[^{}]+', Other), ], 'space': [ (r'[ \t\n\r]+', Whitespace), (r'#[^\n]*', Comment.Single), ], 'end': [ (r'end\b', Keyword, '#pop'), ], }
class TreetopLexer(DelegatingLexer): """ A lexer for Treetop grammars. """
name = 'Treetop' aliases = ['treetop'] filenames = ['*.treetop', '*.tt'] url = 'https://cjheath.github.io/treetop' version_added = '1.6'
def __init__(self, **options): super().__init__(RubyLexer, TreetopBaseLexer, **options)
class EbnfLexer(RegexLexer): """ Lexer for `ISO/IEC 14977 EBNF <https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form>`_ grammars. """
name = 'EBNF' aliases = ['ebnf'] filenames = ['*.ebnf'] mimetypes = ['text/x-ebnf'] url = 'https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form' version_added = '2.0'
tokens = { 'root': [ include('whitespace'), include('comment_start'), include('identifier'), (r'=', Operator, 'production'), ], 'production': [ include('whitespace'), include('comment_start'), include('identifier'), (r'"[^"]*"', String.Double), (r"'[^']*'", String.Single), (r'(\?[^?]*\?)', Name.Entity), (r'[\[\]{}(),|]', Punctuation), (r'-', Operator), (r';', Punctuation, '#pop'), (r'\.', Punctuation, '#pop'), ], 'whitespace': [ (r'\s+', Text), ], 'comment_start': [ (r'\(\*', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^*)]', Comment.Multiline), include('comment_start'), (r'\*\)', Comment.Multiline, '#pop'), (r'[*)]', Comment.Multiline), ], 'identifier': [ (r'([a-zA-Z][\w \-]*)', Keyword), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644""" pygments.lexers.pascal ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Pascal family languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexerfrom pygments.util import get_bool_opt, get_list_optfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error, Whitespacefrom pygments.scanner import Scanner
# compatibility importfrom pygments.lexers.modula2 import Modula2Lexer # noqa: F401
__all__ = ['DelphiLexer', 'PortugolLexer']
class PortugolLexer(Lexer): """For Portugol, a Pascal dialect with keywords in Portuguese.""" name = 'Portugol' aliases = ['portugol'] filenames = ['*.alg', '*.portugol'] mimetypes = [] url = "https://www.apoioinformatica.inf.br/produtos/visualg/linguagem" version_added = ''
def __init__(self, **options): Lexer.__init__(self, **options) self.lexer = DelphiLexer(**options, portugol=True)
def get_tokens_unprocessed(self, text): return self.lexer.get_tokens_unprocessed(text)
class DelphiLexer(Lexer): """ For Delphi (Borland Object Pascal), Turbo Pascal and Free Pascal source code.
Additional options accepted:
`turbopascal` Highlight Turbo Pascal specific keywords (default: ``True``). `delphi` Highlight Borland Delphi specific keywords (default: ``True``). `freepascal` Highlight Free Pascal specific keywords (default: ``True``). `units` A list of units that should be considered builtin, supported are ``System``, ``SysUtils``, ``Classes`` and ``Math``. Default is to consider all of them builtin. """ name = 'Delphi' aliases = ['delphi', 'pas', 'pascal', 'objectpascal'] filenames = ['*.pas', '*.dpr'] mimetypes = ['text/x-pascal'] url = 'https://www.embarcadero.com/products/delphi' version_added = ''
TURBO_PASCAL_KEYWORDS = ( 'absolute', 'and', 'array', 'asm', 'begin', 'break', 'case', 'const', 'constructor', 'continue', 'destructor', 'div', 'do', 'downto', 'else', 'end', 'file', 'for', 'function', 'goto', 'if', 'implementation', 'in', 'inherited', 'inline', 'interface', 'label', 'mod', 'nil', 'not', 'object', 'of', 'on', 'operator', 'or', 'packed', 'procedure', 'program', 'record', 'reintroduce', 'repeat', 'self', 'set', 'shl', 'shr', 'string', 'then', 'to', 'type', 'unit', 'until', 'uses', 'var', 'while', 'with', 'xor' )
DELPHI_KEYWORDS = ( 'as', 'class', 'except', 'exports', 'finalization', 'finally', 'initialization', 'is', 'library', 'on', 'property', 'raise', 'threadvar', 'try' )
FREE_PASCAL_KEYWORDS = ( 'dispose', 'exit', 'false', 'new', 'true' )
BLOCK_KEYWORDS = { 'begin', 'class', 'const', 'constructor', 'destructor', 'end', 'finalization', 'function', 'implementation', 'initialization', 'label', 'library', 'operator', 'procedure', 'program', 'property', 'record', 'threadvar', 'type', 'unit', 'uses', 'var' }
FUNCTION_MODIFIERS = { 'alias', 'cdecl', 'export', 'inline', 'interrupt', 'nostackframe', 'pascal', 'register', 'safecall', 'softfloat', 'stdcall', 'varargs', 'name', 'dynamic', 'near', 'virtual', 'external', 'override', 'assembler' }
# XXX: those aren't global. but currently we know no way for defining # them just for the type context. DIRECTIVES = { 'absolute', 'abstract', 'assembler', 'cppdecl', 'default', 'far', 'far16', 'forward', 'index', 'oldfpccall', 'private', 'protected', 'published', 'public' }
BUILTIN_TYPES = { 'ansichar', 'ansistring', 'bool', 'boolean', 'byte', 'bytebool', 'cardinal', 'char', 'comp', 'currency', 'double', 'dword', 'extended', 'int64', 'integer', 'iunknown', 'longbool', 'longint', 'longword', 'pansichar', 'pansistring', 'pbool', 'pboolean', 'pbyte', 'pbytearray', 'pcardinal', 'pchar', 'pcomp', 'pcurrency', 'pdate', 'pdatetime', 'pdouble', 'pdword', 'pextended', 'phandle', 'pint64', 'pinteger', 'plongint', 'plongword', 'pointer', 'ppointer', 'pshortint', 'pshortstring', 'psingle', 'psmallint', 'pstring', 'pvariant', 'pwidechar', 'pwidestring', 'pword', 'pwordarray', 'pwordbool', 'real', 'real48', 'shortint', 'shortstring', 'single', 'smallint', 'string', 'tclass', 'tdate', 'tdatetime', 'textfile', 'thandle', 'tobject', 'ttime', 'variant', 'widechar', 'widestring', 'word', 'wordbool' }
BUILTIN_UNITS = { 'System': ( 'abs', 'acquireexceptionobject', 'addr', 'ansitoutf8', 'append', 'arctan', 'assert', 'assigned', 'assignfile', 'beginthread', 'blockread', 'blockwrite', 'break', 'chdir', 'chr', 'close', 'closefile', 'comptocurrency', 'comptodouble', 'concat', 'continue', 'copy', 'cos', 'dec', 'delete', 'dispose', 'doubletocomp', 'endthread', 'enummodules', 'enumresourcemodules', 'eof', 'eoln', 'erase', 'exceptaddr', 'exceptobject', 'exclude', 'exit', 'exp', 'filepos', 'filesize', 'fillchar', 'finalize', 'findclasshinstance', 'findhinstance', 'findresourcehinstance', 'flush', 'frac', 'freemem', 'get8087cw', 'getdir', 'getlasterror', 'getmem', 'getmemorymanager', 'getmodulefilename', 'getvariantmanager', 'halt', 'hi', 'high', 'inc', 'include', 'initialize', 'insert', 'int', 'ioresult', 'ismemorymanagerset', 'isvariantmanagerset', 'length', 'ln', 'lo', 'low', 'mkdir', 'move', 'new', 'odd', 'olestrtostring', 'olestrtostrvar', 'ord', 'paramcount', 'paramstr', 'pi', 'pos', 'pred', 'ptr', 'pucs4chars', 'random', 'randomize', 'read', 'readln', 'reallocmem', 'releaseexceptionobject', 'rename', 'reset', 'rewrite', 'rmdir', 'round', 'runerror', 'seek', 'seekeof', 'seekeoln', 'set8087cw', 'setlength', 'setlinebreakstyle', 'setmemorymanager', 'setstring', 'settextbuf', 'setvariantmanager', 'sin', 'sizeof', 'slice', 'sqr', 'sqrt', 'str', 'stringofchar', 'stringtoolestr', 'stringtowidechar', 'succ', 'swap', 'trunc', 'truncate', 'typeinfo', 'ucs4stringtowidestring', 'unicodetoutf8', 'uniquestring', 'upcase', 'utf8decode', 'utf8encode', 'utf8toansi', 'utf8tounicode', 'val', 'vararrayredim', 'varclear', 'widecharlentostring', 'widecharlentostrvar', 'widechartostring', 'widechartostrvar', 'widestringtoucs4string', 'write', 'writeln' ), 'SysUtils': ( 'abort', 'addexitproc', 'addterminateproc', 'adjustlinebreaks', 'allocmem', 'ansicomparefilename', 'ansicomparestr', 'ansicomparetext', 'ansidequotedstr', 'ansiextractquotedstr', 'ansilastchar', 'ansilowercase', 'ansilowercasefilename', 'ansipos', 'ansiquotedstr', 'ansisamestr', 'ansisametext', 'ansistrcomp', 'ansistricomp', 'ansistrlastchar', 'ansistrlcomp', 'ansistrlicomp', 'ansistrlower', 'ansistrpos', 'ansistrrscan', 'ansistrscan', 'ansistrupper', 'ansiuppercase', 'ansiuppercasefilename', 'appendstr', 'assignstr', 'beep', 'booltostr', 'bytetocharindex', 'bytetocharlen', 'bytetype', 'callterminateprocs', 'changefileext', 'charlength', 'chartobyteindex', 'chartobytelen', 'comparemem', 'comparestr', 'comparetext', 'createdir', 'createguid', 'currentyear', 'currtostr', 'currtostrf', 'date', 'datetimetofiledate', 'datetimetostr', 'datetimetostring', 'datetimetosystemtime', 'datetimetotimestamp', 'datetostr', 'dayofweek', 'decodedate', 'decodedatefully', 'decodetime', 'deletefile', 'directoryexists', 'diskfree', 'disksize', 'disposestr', 'encodedate', 'encodetime', 'exceptionerrormessage', 'excludetrailingbackslash', 'excludetrailingpathdelimiter', 'expandfilename', 'expandfilenamecase', 'expanduncfilename', 'extractfiledir', 'extractfiledrive', 'extractfileext', 'extractfilename', 'extractfilepath', 'extractrelativepath', 'extractshortpathname', 'fileage', 'fileclose', 'filecreate', 'filedatetodatetime', 'fileexists', 'filegetattr', 'filegetdate', 'fileisreadonly', 'fileopen', 'fileread', 'filesearch', 'fileseek', 'filesetattr', 'filesetdate', 'filesetreadonly', 'filewrite', 'finalizepackage', 'findclose', 'findcmdlineswitch', 'findfirst', 'findnext', 'floattocurr', 'floattodatetime', 'floattodecimal', 'floattostr', 'floattostrf', 'floattotext', 'floattotextfmt', 'fmtloadstr', 'fmtstr', 'forcedirectories', 'format', 'formatbuf', 'formatcurr', 'formatdatetime', 'formatfloat', 'freeandnil', 'getcurrentdir', 'getenvironmentvariable', 'getfileversion', 'getformatsettings', 'getlocaleformatsettings', 'getmodulename', 'getpackagedescription', 'getpackageinfo', 'gettime', 'guidtostring', 'incamonth', 'includetrailingbackslash', 'includetrailingpathdelimiter', 'incmonth', 'initializepackage', 'interlockeddecrement', 'interlockedexchange', 'interlockedexchangeadd', 'interlockedincrement', 'inttohex', 'inttostr', 'isdelimiter', 'isequalguid', 'isleapyear', 'ispathdelimiter', 'isvalidident', 'languages', 'lastdelimiter', 'loadpackage', 'loadstr', 'lowercase', 'msecstotimestamp', 'newstr', 'nextcharindex', 'now', 'outofmemoryerror', 'quotedstr', 'raiselastoserror', 'raiselastwin32error', 'removedir', 'renamefile', 'replacedate', 'replacetime', 'safeloadlibrary', 'samefilename', 'sametext', 'setcurrentdir', 'showexception', 'sleep', 'stralloc', 'strbufsize', 'strbytetype', 'strcat', 'strcharlength', 'strcomp', 'strcopy', 'strdispose', 'strecopy', 'strend', 'strfmt', 'stricomp', 'stringreplace', 'stringtoguid', 'strlcat', 'strlcomp', 'strlcopy', 'strlen', 'strlfmt', 'strlicomp', 'strlower', 'strmove', 'strnew', 'strnextchar', 'strpas', 'strpcopy', 'strplcopy', 'strpos', 'strrscan', 'strscan', 'strtobool', 'strtobooldef', 'strtocurr', 'strtocurrdef', 'strtodate', 'strtodatedef', 'strtodatetime', 'strtodatetimedef', 'strtofloat', 'strtofloatdef', 'strtoint', 'strtoint64', 'strtoint64def', 'strtointdef', 'strtotime', 'strtotimedef', 'strupper', 'supports', 'syserrormessage', 'systemtimetodatetime', 'texttofloat', 'time', 'timestamptodatetime', 'timestamptomsecs', 'timetostr', 'trim', 'trimleft', 'trimright', 'tryencodedate', 'tryencodetime', 'tryfloattocurr', 'tryfloattodatetime', 'trystrtobool', 'trystrtocurr', 'trystrtodate', 'trystrtodatetime', 'trystrtofloat', 'trystrtoint', 'trystrtoint64', 'trystrtotime', 'unloadpackage', 'uppercase', 'widecomparestr', 'widecomparetext', 'widefmtstr', 'wideformat', 'wideformatbuf', 'widelowercase', 'widesamestr', 'widesametext', 'wideuppercase', 'win32check', 'wraptext' ), 'Classes': ( 'activateclassgroup', 'allocatehwnd', 'bintohex', 'checksynchronize', 'collectionsequal', 'countgenerations', 'deallocatehwnd', 'equalrect', 'extractstrings', 'findclass', 'findglobalcomponent', 'getclass', 'groupdescendantswith', 'hextobin', 'identtoint', 'initinheritedcomponent', 'inttoident', 'invalidpoint', 'isuniqueglobalcomponentname', 'linestart', 'objectbinarytotext', 'objectresourcetotext', 'objecttexttobinary', 'objecttexttoresource', 'pointsequal', 'readcomponentres', 'readcomponentresex', 'readcomponentresfile', 'rect', 'registerclass', 'registerclassalias', 'registerclasses', 'registercomponents', 'registerintegerconsts', 'registernoicon', 'registernonactivex', 'smallpoint', 'startclassgroup', 'teststreamformat', 'unregisterclass', 'unregisterclasses', 'unregisterintegerconsts', 'unregistermoduleclasses', 'writecomponentresfile' ), 'Math': ( 'arccos', 'arccosh', 'arccot', 'arccoth', 'arccsc', 'arccsch', 'arcsec', 'arcsech', 'arcsin', 'arcsinh', 'arctan2', 'arctanh', 'ceil', 'comparevalue', 'cosecant', 'cosh', 'cot', 'cotan', 'coth', 'csc', 'csch', 'cycletodeg', 'cycletograd', 'cycletorad', 'degtocycle', 'degtograd', 'degtorad', 'divmod', 'doubledecliningbalance', 'ensurerange', 'floor', 'frexp', 'futurevalue', 'getexceptionmask', 'getprecisionmode', 'getroundmode', 'gradtocycle', 'gradtodeg', 'gradtorad', 'hypot', 'inrange', 'interestpayment', 'interestrate', 'internalrateofreturn', 'intpower', 'isinfinite', 'isnan', 'iszero', 'ldexp', 'lnxp1', 'log10', 'log2', 'logn', 'max', 'maxintvalue', 'maxvalue', 'mean', 'meanandstddev', 'min', 'minintvalue', 'minvalue', 'momentskewkurtosis', 'netpresentvalue', 'norm', 'numberofperiods', 'payment', 'periodpayment', 'poly', 'popnstddev', 'popnvariance', 'power', 'presentvalue', 'radtocycle', 'radtodeg', 'radtograd', 'randg', 'randomrange', 'roundto', 'samevalue', 'sec', 'secant', 'sech', 'setexceptionmask', 'setprecisionmode', 'setroundmode', 'sign', 'simpleroundto', 'sincos', 'sinh', 'slndepreciation', 'stddev', 'sum', 'sumint', 'sumofsquares', 'sumsandsquares', 'syddepreciation', 'tan', 'tanh', 'totalvariance', 'variance' ) }
ASM_REGISTERS = { 'ah', 'al', 'ax', 'bh', 'bl', 'bp', 'bx', 'ch', 'cl', 'cr0', 'cr1', 'cr2', 'cr3', 'cr4', 'cs', 'cx', 'dh', 'di', 'dl', 'dr0', 'dr1', 'dr2', 'dr3', 'dr4', 'dr5', 'dr6', 'dr7', 'ds', 'dx', 'eax', 'ebp', 'ebx', 'ecx', 'edi', 'edx', 'es', 'esi', 'esp', 'fs', 'gs', 'mm0', 'mm1', 'mm2', 'mm3', 'mm4', 'mm5', 'mm6', 'mm7', 'si', 'sp', 'ss', 'st0', 'st1', 'st2', 'st3', 'st4', 'st5', 'st6', 'st7', 'xmm0', 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5', 'xmm6', 'xmm7' }
ASM_INSTRUCTIONS = { 'aaa', 'aad', 'aam', 'aas', 'adc', 'add', 'and', 'arpl', 'bound', 'bsf', 'bsr', 'bswap', 'bt', 'btc', 'btr', 'bts', 'call', 'cbw', 'cdq', 'clc', 'cld', 'cli', 'clts', 'cmc', 'cmova', 'cmovae', 'cmovb', 'cmovbe', 'cmovc', 'cmovcxz', 'cmove', 'cmovg', 'cmovge', 'cmovl', 'cmovle', 'cmovna', 'cmovnae', 'cmovnb', 'cmovnbe', 'cmovnc', 'cmovne', 'cmovng', 'cmovnge', 'cmovnl', 'cmovnle', 'cmovno', 'cmovnp', 'cmovns', 'cmovnz', 'cmovo', 'cmovp', 'cmovpe', 'cmovpo', 'cmovs', 'cmovz', 'cmp', 'cmpsb', 'cmpsd', 'cmpsw', 'cmpxchg', 'cmpxchg486', 'cmpxchg8b', 'cpuid', 'cwd', 'cwde', 'daa', 'das', 'dec', 'div', 'emms', 'enter', 'hlt', 'ibts', 'icebp', 'idiv', 'imul', 'in', 'inc', 'insb', 'insd', 'insw', 'int', 'int01', 'int03', 'int1', 'int3', 'into', 'invd', 'invlpg', 'iret', 'iretd', 'iretw', 'ja', 'jae', 'jb', 'jbe', 'jc', 'jcxz', 'jcxz', 'je', 'jecxz', 'jg', 'jge', 'jl', 'jle', 'jmp', 'jna', 'jnae', 'jnb', 'jnbe', 'jnc', 'jne', 'jng', 'jnge', 'jnl', 'jnle', 'jno', 'jnp', 'jns', 'jnz', 'jo', 'jp', 'jpe', 'jpo', 'js', 'jz', 'lahf', 'lar', 'lcall', 'lds', 'lea', 'leave', 'les', 'lfs', 'lgdt', 'lgs', 'lidt', 'ljmp', 'lldt', 'lmsw', 'loadall', 'loadall286', 'lock', 'lodsb', 'lodsd', 'lodsw', 'loop', 'loope', 'loopne', 'loopnz', 'loopz', 'lsl', 'lss', 'ltr', 'mov', 'movd', 'movq', 'movsb', 'movsd', 'movsw', 'movsx', 'movzx', 'mul', 'neg', 'nop', 'not', 'or', 'out', 'outsb', 'outsd', 'outsw', 'pop', 'popa', 'popad', 'popaw', 'popf', 'popfd', 'popfw', 'push', 'pusha', 'pushad', 'pushaw', 'pushf', 'pushfd', 'pushfw', 'rcl', 'rcr', 'rdmsr', 'rdpmc', 'rdshr', 'rdtsc', 'rep', 'repe', 'repne', 'repnz', 'repz', 'ret', 'retf', 'retn', 'rol', 'ror', 'rsdc', 'rsldt', 'rsm', 'sahf', 'sal', 'salc', 'sar', 'sbb', 'scasb', 'scasd', 'scasw', 'seta', 'setae', 'setb', 'setbe', 'setc', 'setcxz', 'sete', 'setg', 'setge', 'setl', 'setle', 'setna', 'setnae', 'setnb', 'setnbe', 'setnc', 'setne', 'setng', 'setnge', 'setnl', 'setnle', 'setno', 'setnp', 'setns', 'setnz', 'seto', 'setp', 'setpe', 'setpo', 'sets', 'setz', 'sgdt', 'shl', 'shld', 'shr', 'shrd', 'sidt', 'sldt', 'smi', 'smint', 'smintold', 'smsw', 'stc', 'std', 'sti', 'stosb', 'stosd', 'stosw', 'str', 'sub', 'svdc', 'svldt', 'svts', 'syscall', 'sysenter', 'sysexit', 'sysret', 'test', 'ud1', 'ud2', 'umov', 'verr', 'verw', 'wait', 'wbinvd', 'wrmsr', 'wrshr', 'xadd', 'xbts', 'xchg', 'xlat', 'xlatb', 'xor' }
PORTUGOL_KEYWORDS = ( 'aleatorio', 'algoritmo', 'arquivo', 'ate', 'caso', 'cronometro', 'debug', 'e', 'eco', 'enquanto', 'entao', 'escolha', 'escreva', 'escreval', 'faca', 'falso', 'fimalgoritmo', 'fimenquanto', 'fimescolha', 'fimfuncao', 'fimpara', 'fimprocedimento', 'fimrepita', 'fimse', 'funcao', 'inicio', 'int', 'interrompa', 'leia', 'limpatela', 'mod', 'nao', 'ou', 'outrocaso', 'para', 'passo', 'pausa', 'procedimento', 'repita', 'retorne', 'se', 'senao', 'timer', 'var', 'vetor', 'verdadeiro', 'xou', 'div', 'mod', 'abs', 'arccos', 'arcsen', 'arctan', 'cos', 'cotan', 'Exp', 'grauprad', 'int', 'log', 'logn', 'pi', 'quad', 'radpgrau', 'raizq', 'rand', 'randi', 'sen', 'Tan', 'asc', 'carac', 'caracpnum', 'compr', 'copia', 'maiusc', 'minusc', 'numpcarac', 'pos', )
PORTUGOL_BUILTIN_TYPES = { 'inteiro', 'real', 'caractere', 'logico' }
def __init__(self, **options): Lexer.__init__(self, **options) self.keywords = set() self.builtins = set() if get_bool_opt(options, 'portugol', False): self.keywords.update(self.PORTUGOL_KEYWORDS) self.builtins.update(self.PORTUGOL_BUILTIN_TYPES) self.is_portugol = True else: self.is_portugol = False
if get_bool_opt(options, 'turbopascal', True): self.keywords.update(self.TURBO_PASCAL_KEYWORDS) if get_bool_opt(options, 'delphi', True): self.keywords.update(self.DELPHI_KEYWORDS) if get_bool_opt(options, 'freepascal', True): self.keywords.update(self.FREE_PASCAL_KEYWORDS) for unit in get_list_opt(options, 'units', list(self.BUILTIN_UNITS)): self.builtins.update(self.BUILTIN_UNITS[unit])
def get_tokens_unprocessed(self, text): scanner = Scanner(text, re.DOTALL | re.MULTILINE | re.IGNORECASE) stack = ['initial'] in_function_block = False in_property_block = False was_dot = False next_token_is_function = False next_token_is_property = False collect_labels = False block_labels = set() brace_balance = [0, 0]
while not scanner.eos: token = Error
if stack[-1] == 'initial': if scanner.scan(r'\s+'): token = Whitespace elif not self.is_portugol and scanner.scan(r'\{.*?\}|\(\*.*?\*\)'): if scanner.match.startswith('$'): token = Comment.Preproc else: token = Comment.Multiline elif scanner.scan(r'//.*?$'): token = Comment.Single elif self.is_portugol and scanner.scan(r'(<\-)|(>=)|(<=)|%|<|>|-|\+|\*|\=|(<>)|\/|\.|:|,'): token = Operator elif not self.is_portugol and scanner.scan(r'[-+*\/=<>:;,.@\^]'): token = Operator # stop label highlighting on next ";" if collect_labels and scanner.match == ';': collect_labels = False elif scanner.scan(r'[\(\)\[\]]+'): token = Punctuation # abort function naming ``foo = Function(...)`` next_token_is_function = False # if we are in a function block we count the open # braces because ootherwise it's impossible to # determine the end of the modifier context if in_function_block or in_property_block: if scanner.match == '(': brace_balance[0] += 1 elif scanner.match == ')': brace_balance[0] -= 1 elif scanner.match == '[': brace_balance[1] += 1 elif scanner.match == ']': brace_balance[1] -= 1 elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'): lowercase_name = scanner.match.lower() if lowercase_name == 'result': token = Name.Builtin.Pseudo elif lowercase_name in self.keywords: token = Keyword # if we are in a special block and a # block ending keyword occurs (and the parenthesis # is balanced) we end the current block context if self.is_portugol: if lowercase_name in ('funcao', 'procedimento'): in_function_block = True next_token_is_function = True else: if (in_function_block or in_property_block) and \ lowercase_name in self.BLOCK_KEYWORDS and \ brace_balance[0] <= 0 and \ brace_balance[1] <= 0: in_function_block = False in_property_block = False brace_balance = [0, 0] block_labels = set() if lowercase_name in ('label', 'goto'): collect_labels = True elif lowercase_name == 'asm': stack.append('asm') elif lowercase_name == 'property': in_property_block = True next_token_is_property = True elif lowercase_name in ('procedure', 'operator', 'function', 'constructor', 'destructor'): in_function_block = True next_token_is_function = True # we are in a function block and the current name # is in the set of registered modifiers. highlight # it as pseudo keyword elif not self.is_portugol and in_function_block and \ lowercase_name in self.FUNCTION_MODIFIERS: token = Keyword.Pseudo # if we are in a property highlight some more # modifiers elif not self.is_portugol and in_property_block and \ lowercase_name in ('read', 'write'): token = Keyword.Pseudo next_token_is_function = True # if the last iteration set next_token_is_function # to true we now want this name highlighted as # function. so do that and reset the state elif next_token_is_function: # Look if the next token is a dot. If yes it's # not a function, but a class name and the # part after the dot a function name if not self.is_portugol and scanner.test(r'\s*\.\s*'): token = Name.Class # it's not a dot, our job is done else: token = Name.Function next_token_is_function = False
if self.is_portugol: block_labels.add(scanner.match.lower())
# same for properties elif not self.is_portugol and next_token_is_property: token = Name.Property next_token_is_property = False # Highlight this token as label and add it # to the list of known labels elif not self.is_portugol and collect_labels: token = Name.Label block_labels.add(scanner.match.lower()) # name is in list of known labels elif lowercase_name in block_labels: token = Name.Label elif self.is_portugol and lowercase_name in self.PORTUGOL_BUILTIN_TYPES: token = Keyword.Type elif not self.is_portugol and lowercase_name in self.BUILTIN_TYPES: token = Keyword.Type elif not self.is_portugol and lowercase_name in self.DIRECTIVES: token = Keyword.Pseudo # builtins are just builtins if the token # before isn't a dot elif not self.is_portugol and not was_dot and lowercase_name in self.builtins: token = Name.Builtin else: token = Name elif self.is_portugol and scanner.scan(r"\""): token = String stack.append('string') elif not self.is_portugol and scanner.scan(r"'"): token = String stack.append('string') elif not self.is_portugol and scanner.scan(r'\#(\d+|\$[0-9A-Fa-f]+)'): token = String.Char elif not self.is_portugol and scanner.scan(r'\$[0-9A-Fa-f]+'): token = Number.Hex elif scanner.scan(r'\d+(?![eE]|\.[^.])'): token = Number.Integer elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'): token = Number.Float else: # if the stack depth is deeper than once, pop if len(stack) > 1: stack.pop() scanner.get_char()
elif stack[-1] == 'string': if self.is_portugol: if scanner.scan(r"''"): token = String.Escape elif scanner.scan(r"\""): token = String stack.pop() elif scanner.scan(r"[^\"]*"): token = String else: scanner.get_char() stack.pop() else: if scanner.scan(r"''"): token = String.Escape elif scanner.scan(r"'"): token = String stack.pop() elif scanner.scan(r"[^']*"): token = String else: scanner.get_char() stack.pop() elif not self.is_portugol and stack[-1] == 'asm': if scanner.scan(r'\s+'): token = Whitespace elif scanner.scan(r'end'): token = Keyword stack.pop() elif scanner.scan(r'\{.*?\}|\(\*.*?\*\)'): if scanner.match.startswith('$'): token = Comment.Preproc else: token = Comment.Multiline elif scanner.scan(r'//.*?$'): token = Comment.Single elif scanner.scan(r"'"): token = String stack.append('string') elif scanner.scan(r'@@[A-Za-z_][A-Za-z_0-9]*'): token = Name.Label elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'): lowercase_name = scanner.match.lower() if lowercase_name in self.ASM_INSTRUCTIONS: token = Keyword elif lowercase_name in self.ASM_REGISTERS: token = Name.Builtin else: token = Name elif scanner.scan(r'[-+*\/=<>:;,.@\^]+'): token = Operator elif scanner.scan(r'[\(\)\[\]]+'): token = Punctuation elif scanner.scan(r'\$[0-9A-Fa-f]+'): token = Number.Hex elif scanner.scan(r'\d+(?![eE]|\.[^.])'): token = Number.Integer elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'): token = Number.Float else: scanner.get_char() stack.pop()
# save the dot!!!11 if not self.is_portugol and scanner.match.strip(): was_dot = scanner.match == '.'
yield scanner.start_pos, token, scanner.match or ''12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182""" pygments.lexers.pddl ~~~~~~~~~~~~~~~~~~~~
Lexer for the Planning Domain Definition Language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, includefrom pygments.token import Punctuation, Keyword, Whitespace, Name, Comment, \ Operator, Number
__all__ = ['PddlLexer']
class PddlLexer(RegexLexer): """ A PDDL lexer.
It should support up to PDDL 3.1. """
name = 'PDDL' aliases = ['pddl'] filenames = ['*.pddl'] # there doesn't really seem to be a PDDL homepage. url = 'https://en.wikipedia.org/wiki/Planning_Domain_Definition_Language' version_added = '2.19'
tokens = { 'root': [ (r'\s+', Whitespace), (r';.*$', Comment.Singleline), include('keywords'), include('builtins'), (r'[()]', Punctuation), (r'[=/*+><-]', Operator), (r'[a-zA-Z][a-zA-Z0-9_-]*', Name), (r'\?[a-zA-Z][a-zA-Z0-9_-]*', Name.Variable), (r'[0-9]+\.[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), ], 'keywords': [ (words(( ':requirements', ':types', ':constants', ':predicates', ':functions', ':action', ':agent', ':parameters', ':precondition', ':effect', ':durative-action', ':duration', ':condition', ':derived', ':domain', ':objects', ':init', ':goal', ':metric', ':length', ':serial', ':parallel', # the following are requirements ':strips', ':typing', ':negative-preconditions', ':disjunctive-preconditions', ':equality', ':existential-preconditions', ':universal-preconditions', ':conditional-effects', ':fluents', ':numeric-fluents', ':object-fluents', ':adl', ':durative-actions', ':continuous-effects', ':derived-predicates', ':time-intial-literals', ':preferences', ':constraints', ':action-costs', ':multi-agent', ':unfactored-privacy', ':factored-privacy', ':non-deterministic' ), suffix=r'\b'), Keyword) ], 'builtins': [ (words(( 'define', 'domain', 'object', 'either', 'and', 'forall', 'preference', 'imply', 'or', 'exists', 'not', 'when', 'assign', 'scale-up', 'scale-down', 'increase', 'decrease', 'at', 'over', 'start', 'end', 'all', 'problem', 'always', 'sometime', 'within', 'at-most-once', 'sometime-after', 'sometime-before', 'always-within', 'hold-during', 'hold-after', 'minimize', 'maximize', 'total-time', 'is-violated'), suffix=r'\b'), Name.Builtin) ] }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733""" pygments.lexers.perl ~~~~~~~~~~~~~~~~~~~~
Lexers for Perl, Raku and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, ExtendedRegexLexer, include, bygroups, \ using, this, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespacefrom pygments.util import shebang_matches
__all__ = ['PerlLexer', 'Perl6Lexer']
class PerlLexer(RegexLexer): """ For Perl source code. """
name = 'Perl' url = 'https://www.perl.org' aliases = ['perl', 'pl'] filenames = ['*.pl', '*.pm', '*.t', '*.perl'] mimetypes = ['text/x-perl', 'application/x-perl'] version_added = ''
flags = re.DOTALL | re.MULTILINE # TODO: give this to a perl guy who knows how to parse perl... tokens = { 'balanced-regex': [ (r'/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*', String.Regex, '#pop'), (r'!(\\\\|\\[^\\]|[^\\!])*![egimosx]*', String.Regex, '#pop'), (r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'), (r'\{(\\\\|\\[^\\]|[^\\}])*\}[egimosx]*', String.Regex, '#pop'), (r'<(\\\\|\\[^\\]|[^\\>])*>[egimosx]*', String.Regex, '#pop'), (r'\[(\\\\|\\[^\\]|[^\\\]])*\][egimosx]*', String.Regex, '#pop'), (r'\((\\\\|\\[^\\]|[^\\)])*\)[egimosx]*', String.Regex, '#pop'), (r'@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*', String.Regex, '#pop'), (r'%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*', String.Regex, '#pop'), (r'\$(\\\\|\\[^\\]|[^\\$])*\$[egimosx]*', String.Regex, '#pop'), ], 'root': [ (r'\A\#!.+?$', Comment.Hashbang), (r'\#.*?$', Comment.Single), (r'^=[a-zA-Z0-9]+\s+.*?\n=cut', Comment.Multiline), (words(( 'case', 'continue', 'do', 'else', 'elsif', 'for', 'foreach', 'if', 'last', 'my', 'next', 'our', 'redo', 'reset', 'then', 'unless', 'until', 'while', 'print', 'new', 'BEGIN', 'CHECK', 'INIT', 'END', 'return'), suffix=r'\b'), Keyword), (r'(format)(\s+)(\w+)(\s*)(=)(\s*\n)', bygroups(Keyword, Whitespace, Name, Whitespace, Punctuation, Whitespace), 'format'), (r'(eq|lt|gt|le|ge|ne|not|and|or|cmp)\b', Operator.Word), # common delimiters (r's/(\\\\|\\[^\\]|[^\\/])*/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*', String.Regex), (r's!(\\\\|\\!|[^!])*!(\\\\|\\!|[^!])*![egimosx]*', String.Regex), (r's\\(\\\\|[^\\])*\\(\\\\|[^\\])*\\[egimosx]*', String.Regex), (r's@(\\\\|\\[^\\]|[^\\@])*@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*', String.Regex), (r's%(\\\\|\\[^\\]|[^\\%])*%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*', String.Regex), # balanced delimiters (r's\{(\\\\|\\[^\\]|[^\\}])*\}\s*', String.Regex, 'balanced-regex'), (r's<(\\\\|\\[^\\]|[^\\>])*>\s*', String.Regex, 'balanced-regex'), (r's\[(\\\\|\\[^\\]|[^\\\]])*\]\s*', String.Regex, 'balanced-regex'), (r's\((\\\\|\\[^\\]|[^\\)])*\)\s*', String.Regex, 'balanced-regex'),
(r'm?/(\\\\|\\[^\\]|[^\\/\n])*/[gcimosx]*', String.Regex), (r'm(?=[/!\\{<\[(@%$])', String.Regex, 'balanced-regex'), (r'((?<==~)|(?<=\())\s*/(\\\\|\\[^\\]|[^\\/])*/[gcimosx]*', String.Regex), (r'\s+', Whitespace), (words(( 'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller', 'chdir', 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'close', 'closedir', 'connect', 'continue', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined', 'delete', 'die', 'dump', 'each', 'endgrent', 'endhostent', 'endnetent', 'endprotoent', 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists', 'exit', 'exp', 'fcntl', 'fileno', 'flock', 'fork', 'format', 'formline', 'getc', 'getgrent', 'getgrgid', 'getgrnam', 'gethostbyaddr', 'gethostbyname', 'gethostent', 'getlogin', 'getnetbyaddr', 'getnetbyname', 'getnetent', 'getpeername', 'getpgrp', 'getppid', 'getpriority', 'getprotobyname', 'getprotobynumber', 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid', 'getservbyname', 'getservbyport', 'getservent', 'getsockname', 'getsockopt', 'glob', 'gmtime', 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl', 'join', 'keys', 'kill', 'last', 'lc', 'lcfirst', 'length', 'link', 'listen', 'local', 'localtime', 'log', 'lstat', 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'my', 'next', 'oct', 'open', 'opendir', 'ord', 'our', 'pack', 'pipe', 'pop', 'pos', 'printf', 'prototype', 'push', 'quotemeta', 'rand', 'read', 'readdir', 'readline', 'readlink', 'readpipe', 'recv', 'redo', 'ref', 'rename', 'reverse', 'rewinddir', 'rindex', 'rmdir', 'scalar', 'seek', 'seekdir', 'select', 'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent', 'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent', 'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown', 'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf', 'sqrt', 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysopen', 'sysread', 'sysseek', 'system', 'syswrite', 'tell', 'telldir', 'tie', 'tied', 'time', 'times', 'tr', 'truncate', 'uc', 'ucfirst', 'umask', 'undef', 'unlink', 'unpack', 'unshift', 'untie', 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray', 'warn', 'write'), suffix=r'\b'), Name.Builtin), (r'((__(DATA|DIE|WARN)__)|(STD(IN|OUT|ERR)))\b', Name.Builtin.Pseudo), (r'(<<)([\'"]?)([a-zA-Z_]\w*)(\2;?\n.*?\n)(\3)(\n)', bygroups(String, String, String.Delimiter, String, String.Delimiter, Whitespace)), (r'__END__', Comment.Preproc, 'end-part'), (r'\$\^[ADEFHILMOPSTWX]', Name.Variable.Global), (r"\$[\\\"\[\]'&`+*.,;=%~?@$!<>(^|/-](?!\w)", Name.Variable.Global), (r'[$@%#]+', Name.Variable, 'varname'), (r'0_?[0-7]+(_[0-7]+)*', Number.Oct), (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex), (r'0b[01]+(_[01]+)*', Number.Bin), (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?', Number.Float), (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float), (r'\d+(_\d+)*', Number.Integer), (r"'(\\\\|\\[^\\]|[^'\\])*'", String), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r'`(\\\\|\\[^\\]|[^`\\])*`', String.Backtick), (r'<([^\s>]+)>', String.Regex), (r'(q|qq|qw|qr|qx)\{', String.Other, 'cb-string'), (r'(q|qq|qw|qr|qx)\(', String.Other, 'rb-string'), (r'(q|qq|qw|qr|qx)\[', String.Other, 'sb-string'), (r'(q|qq|qw|qr|qx)\<', String.Other, 'lt-string'), (r'(q|qq|qw|qr|qx)([\W_])(.|\n)*?\2', String.Other), (r'(package)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(use|require|no)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(sub)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (words(( 'no', 'package', 'require', 'use'), suffix=r'\b'), Keyword), (r'(\[\]|\*\*|::|<<|>>|>=|<=>|<=|={3}|!=|=~|' r'!~|&&?|\|\||\.{1,3})', Operator), (r'[-+/*%=<>&^|!\\~]=?', Operator), (r'[()\[\]:;,<>/?{}]', Punctuation), # yes, there's no shortage # of punctuation in Perl! (r'(?=\w)', Name, 'name'), ], 'format': [ (r'\.\n', String.Interpol, '#pop'), (r'[^\n]*\n', String.Interpol), ], 'varname': [ (r'\s+', Whitespace), (r'\{', Punctuation, '#pop'), # hash syntax? (r'\)|,', Punctuation, '#pop'), # argument specifier (r'\w+::', Name.Namespace), (r'[\w:]+', Name.Variable, '#pop'), ], 'name': [ (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*(::)?(?=\s*->)', Name.Namespace, '#pop'), (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*::', Name.Namespace, '#pop'), (r'[\w:]+', Name, '#pop'), (r'[A-Z_]+(?=\W)', Name.Constant, '#pop'), (r'(?=\W)', Text, '#pop'), ], 'funcname': [ (r'[a-zA-Z_]\w*[!?]?', Name.Function), (r'\s+', Whitespace), # argument declaration (r'(\([$@%]*\))(\s*)', bygroups(Punctuation, Whitespace)), (r';', Punctuation, '#pop'), (r'.*?\{', Punctuation, '#pop'), ], 'cb-string': [ (r'\\[{}\\]', String.Other), (r'\\', String.Other), (r'\{', String.Other, 'cb-string'), (r'\}', String.Other, '#pop'), (r'[^{}\\]+', String.Other) ], 'rb-string': [ (r'\\[()\\]', String.Other), (r'\\', String.Other), (r'\(', String.Other, 'rb-string'), (r'\)', String.Other, '#pop'), (r'[^()]+', String.Other) ], 'sb-string': [ (r'\\[\[\]\\]', String.Other), (r'\\', String.Other), (r'\[', String.Other, 'sb-string'), (r'\]', String.Other, '#pop'), (r'[^\[\]]+', String.Other) ], 'lt-string': [ (r'\\[<>\\]', String.Other), (r'\\', String.Other), (r'\<', String.Other, 'lt-string'), (r'\>', String.Other, '#pop'), (r'[^<>]+', String.Other) ], 'end-part': [ (r'.+', Comment.Preproc, '#pop') ] }
def analyse_text(text): if shebang_matches(text, r'perl'): return True
result = 0
if re.search(r'(?:my|our)\s+[$@%(]', text): result += 0.9
if ':=' in text: # := is not valid Perl, but it appears in unicon, so we should # become less confident if we think we found Perl with := result /= 2
return result
class Perl6Lexer(ExtendedRegexLexer): """ For Raku (a.k.a. Perl 6) source code. """
name = 'Perl6' url = 'https://www.raku.org' aliases = ['perl6', 'pl6', 'raku'] filenames = ['*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6', '*.6pm', '*.p6m', '*.pm6', '*.t', '*.raku', '*.rakumod', '*.rakutest', '*.rakudoc'] mimetypes = ['text/x-perl6', 'application/x-perl6'] version_added = '2.0' flags = re.MULTILINE | re.DOTALL
PERL6_IDENTIFIER_RANGE = r"['\w:-]"
PERL6_KEYWORDS = ( #Phasers 'BEGIN','CATCH','CHECK','CLOSE','CONTROL','DOC','END','ENTER','FIRST', 'INIT','KEEP','LAST','LEAVE','NEXT','POST','PRE','QUIT','UNDO', #Keywords 'anon','augment','but','class','constant','default','does','else', 'elsif','enum','for','gather','given','grammar','has','if','import', 'is','let','loop','made','make','method','module','multi','my','need', 'orwith','our','proceed','proto','repeat','require','return', 'return-rw','returns','role','rule','state','sub','submethod','subset', 'succeed','supersede','token','try','unit','unless','until','use', 'when','while','with','without', #Traits 'export','native','repr','required','rw','symbol', )
PERL6_BUILTINS = ( 'ACCEPTS','abs','abs2rel','absolute','accept','accessed','acos', 'acosec','acosech','acosh','acotan','acotanh','acquire','act','action', 'actions','add','add_attribute','add_enum_value','add_fallback', 'add_method','add_parent','add_private_method','add_role','add_trustee', 'adverb','after','all','allocate','allof','allowed','alternative-names', 'annotations','antipair','antipairs','any','anyof','app_lifetime', 'append','arch','archname','args','arity','Array','asec','asech','asin', 'asinh','ASSIGN-KEY','ASSIGN-POS','assuming','ast','at','atan','atan2', 'atanh','AT-KEY','atomic-assign','atomic-dec-fetch','atomic-fetch', 'atomic-fetch-add','atomic-fetch-dec','atomic-fetch-inc', 'atomic-fetch-sub','atomic-inc-fetch','AT-POS','attributes','auth', 'await','backtrace','Bag','BagHash','bail-out','base','basename', 'base-repeating','batch','BIND-KEY','BIND-POS','bind-stderr', 'bind-stdin','bind-stdout','bind-udp','bits','bless','block','Bool', 'bool-only','bounds','break','Bridge','broken','BUILD','build-date', 'bytes','cache','callframe','calling-package','CALL-ME','callsame', 'callwith','can','cancel','candidates','cando','can-ok','canonpath', 'caps','caption','Capture','cas','catdir','categorize','categorize-list', 'catfile','catpath','cause','ceiling','cglobal','changed','Channel', 'chars','chdir','child','child-name','child-typename','chmod','chomp', 'chop','chr','chrs','chunks','cis','classify','classify-list','cleanup', 'clone','close','closed','close-stdin','cmp-ok','code','codes','collate', 'column','comb','combinations','command','comment','compiler','Complex', 'compose','compose_type','composer','condition','config', 'configure_destroy','configure_type_checking','conj','connect', 'constraints','construct','contains','contents','copy','cos','cosec', 'cosech','cosh','cotan','cotanh','count','count-only','cpu-cores', 'cpu-usage','CREATE','create_type','cross','cue','curdir','curupdir','d', 'Date','DateTime','day','daycount','day-of-month','day-of-week', 'day-of-year','days-in-month','declaration','decode','decoder','deepmap', 'default','defined','DEFINITE','delayed','DELETE-KEY','DELETE-POS', 'denominator','desc','DESTROY','destroyers','devnull','diag', 'did-you-mean','die','dies-ok','dir','dirname','dir-sep','DISTROnames', 'do','does','does-ok','done','done-testing','duckmap','dynamic','e', 'eager','earlier','elems','emit','enclosing','encode','encoder', 'encoding','end','ends-with','enum_from_value','enum_value_list', 'enum_values','enums','eof','EVAL','eval-dies-ok','EVALFILE', 'eval-lives-ok','exception','excludes-max','excludes-min','EXISTS-KEY', 'EXISTS-POS','exit','exitcode','exp','expected','explicitly-manage', 'expmod','extension','f','fail','fails-like','fc','feature','file', 'filename','find_method','find_method_qualified','finish','first','flat', 'flatmap','flip','floor','flunk','flush','fmt','format','formatter', 'freeze','from','from-list','from-loop','from-posix','full', 'full-barrier','get','get_value','getc','gist','got','grab','grabpairs', 'grep','handle','handled','handles','hardware','has_accessor','Hash', 'head','headers','hh-mm-ss','hidden','hides','hour','how','hyper','id', 'illegal','im','in','indent','index','indices','indir','infinite', 'infix','infix:<+>','infix:<->','install_method_cache','Instant', 'instead','Int','int-bounds','interval','in-timezone','invalid-str', 'invert','invocant','IO','IO::Notification.watch-path','is_trusted', 'is_type','isa','is-absolute','isa-ok','is-approx','is-deeply', 'is-hidden','is-initial-thread','is-int','is-lazy','is-leap-year', 'isNaN','isnt','is-prime','is-relative','is-routine','is-setting', 'is-win','item','iterator','join','keep','kept','KERNELnames','key', 'keyof','keys','kill','kv','kxxv','l','lang','last','lastcall','later', 'lazy','lc','leading','level','like','line','lines','link','List', 'listen','live','lives-ok','local','lock','log','log10','lookup','lsb', 'made','MAIN','make','Map','match','max','maxpairs','merge','message', 'method','method_table','methods','migrate','min','minmax','minpairs', 'minute','misplaced','Mix','MixHash','mkdir','mode','modified','month', 'move','mro','msb','multi','multiness','my','name','named','named_names', 'narrow','nativecast','native-descriptor','nativesizeof','new','new_type', 'new-from-daycount','new-from-pairs','next','nextcallee','next-handle', 'nextsame','nextwith','NFC','NFD','NFKC','NFKD','nl-in','nl-out', 'nodemap','nok','none','norm','not','note','now','nude','Num', 'numerator','Numeric','of','offset','offset-in-hours','offset-in-minutes', 'ok','old','on-close','one','on-switch','open','opened','operation', 'optional','ord','ords','orig','os-error','osname','out-buffer','pack', 'package','package-kind','package-name','packages','pair','pairs', 'pairup','parameter','params','parent','parent-name','parents','parse', 'parse-base','parsefile','parse-names','parts','pass','path','path-sep', 'payload','peer-host','peer-port','periods','perl','permutations','phaser', 'pick','pickpairs','pid','placeholder','plan','plus','polar','poll', 'polymod','pop','pos','positional','posix','postfix','postmatch', 'precomp-ext','precomp-target','pred','prefix','prematch','prepend', 'print','printf','print-nl','print-to','private','private_method_table', 'proc','produce','Promise','prompt','protect','pull-one','push', 'push-all','push-at-least','push-exactly','push-until-lazy','put', 'qualifier-type','quit','r','race','radix','rand','range','Rat','raw', 're','read','readchars','readonly','ready','Real','reallocate','reals', 'reason','rebless','receive','recv','redispatcher','redo','reduce', 'rel2abs','relative','release','rename','repeated','replacement', 'report','reserved','resolve','restore','result','resume','rethrow', 'reverse','right','rindex','rmdir','role','roles_to_compose','rolish', 'roll','rootdir','roots','rotate','rotor','round','roundrobin', 'routine-type','run','rwx','s','samecase','samemark','samewith','say', 'schedule-on','scheduler','scope','sec','sech','second','seek','self', 'send','Set','set_hidden','set_name','set_package','set_rw','set_value', 'SetHash','set-instruments','setup_finalization','shape','share','shell', 'shift','sibling','sigil','sign','signal','signals','signature','sin', 'sinh','sink','sink-all','skip','skip-at-least','skip-at-least-pull-one', 'skip-one','skip-rest','sleep','sleep-timer','sleep-until','Slip','slurp', 'slurp-rest','slurpy','snap','snapper','so','socket-host','socket-port', 'sort','source','source-package','spawn','SPEC','splice','split', 'splitdir','splitpath','sprintf','spurt','sqrt','squish','srand','stable', 'start','started','starts-with','status','stderr','stdout','Str', 'sub_signature','subbuf','subbuf-rw','subname','subparse','subst', 'subst-mutate','substr','substr-eq','substr-rw','subtest','succ','sum', 'Supply','symlink','t','tail','take','take-rw','tan','tanh','tap', 'target','target-name','tc','tclc','tell','then','throttle','throw', 'throws-like','timezone','tmpdir','to','today','todo','toggle','to-posix', 'total','trailing','trans','tree','trim','trim-leading','trim-trailing', 'truncate','truncated-to','trusts','try_acquire','trying','twigil','type', 'type_captures','typename','uc','udp','uncaught_handler','unimatch', 'uniname','uninames','uniparse','uniprop','uniprops','unique','unival', 'univals','unlike','unlink','unlock','unpack','unpolar','unshift', 'unwrap','updir','USAGE','use-ok','utc','val','value','values','VAR', 'variable','verbose-config','version','VMnames','volume','vow','w','wait', 'warn','watch','watch-path','week','weekday-of-month','week-number', 'week-year','WHAT','when','WHERE','WHEREFORE','WHICH','WHO', 'whole-second','WHY','wordcase','words','workaround','wrap','write', 'write-to','x','yada','year','yield','yyyy-mm-dd','z','zip','zip-latest',
)
PERL6_BUILTIN_CLASSES = ( #Booleans 'False','True', #Classes 'Any','Array','Associative','AST','atomicint','Attribute','Backtrace', 'Backtrace::Frame','Bag','Baggy','BagHash','Blob','Block','Bool','Buf', 'Callable','CallFrame','Cancellation','Capture','CArray','Channel','Code', 'compiler','Complex','ComplexStr','Cool','CurrentThreadScheduler', 'Cursor','Date','Dateish','DateTime','Distro','Duration','Encoding', 'Exception','Failure','FatRat','Grammar','Hash','HyperWhatever','Instant', 'Int','int16','int32','int64','int8','IntStr','IO','IO::ArgFiles', 'IO::CatHandle','IO::Handle','IO::Notification','IO::Path', 'IO::Path::Cygwin','IO::Path::QNX','IO::Path::Unix','IO::Path::Win32', 'IO::Pipe','IO::Socket','IO::Socket::Async','IO::Socket::INET','IO::Spec', 'IO::Spec::Cygwin','IO::Spec::QNX','IO::Spec::Unix','IO::Spec::Win32', 'IO::Special','Iterable','Iterator','Junction','Kernel','Label','List', 'Lock','Lock::Async','long','longlong','Macro','Map','Match', 'Metamodel::AttributeContainer','Metamodel::C3MRO','Metamodel::ClassHOW', 'Metamodel::EnumHOW','Metamodel::Finalization','Metamodel::MethodContainer', 'Metamodel::MROBasedMethodDispatch','Metamodel::MultipleInheritance', 'Metamodel::Naming','Metamodel::Primitives','Metamodel::PrivateMethodContainer', 'Metamodel::RoleContainer','Metamodel::Trusting','Method','Mix','MixHash', 'Mixy','Mu','NFC','NFD','NFKC','NFKD','Nil','Num','num32','num64', 'Numeric','NumStr','ObjAt','Order','Pair','Parameter','Perl','Pod::Block', 'Pod::Block::Code','Pod::Block::Comment','Pod::Block::Declarator', 'Pod::Block::Named','Pod::Block::Para','Pod::Block::Table','Pod::Heading', 'Pod::Item','Pointer','Positional','PositionalBindFailover','Proc', 'Proc::Async','Promise','Proxy','PseudoStash','QuantHash','Range','Rat', 'Rational','RatStr','Real','Regex','Routine','Scalar','Scheduler', 'Semaphore','Seq','Set','SetHash','Setty','Signature','size_t','Slip', 'Stash','Str','StrDistance','Stringy','Sub','Submethod','Supplier', 'Supplier::Preserving','Supply','Systemic','Tap','Telemetry', 'Telemetry::Instrument::Thread','Telemetry::Instrument::Usage', 'Telemetry::Period','Telemetry::Sampler','Thread','ThreadPoolScheduler', 'UInt','uint16','uint32','uint64','uint8','Uni','utf8','Variable', 'Version','VM','Whatever','WhateverCode','WrapHandle' )
PERL6_OPERATORS = ( 'X', 'Z', 'after', 'also', 'and', 'andthen', 'before', 'cmp', 'div', 'eq', 'eqv', 'extra', 'ff', 'fff', 'ge', 'gt', 'le', 'leg', 'lt', 'm', 'mm', 'mod', 'ne', 'or', 'orelse', 'rx', 's', 'tr', 'x', 'xor', 'xx', '++', '--', '**', '!', '+', '-', '~', '?', '|', '||', '+^', '~^', '?^', '^', '*', '/', '%', '%%', '+&', '+<', '+>', '~&', '~<', '~>', '?&', 'gcd', 'lcm', '+', '-', '+|', '+^', '~|', '~^', '?|', '?^', '~', '&', '^', 'but', 'does', '<=>', '..', '..^', '^..', '^..^', '!=', '==', '<', '<=', '>', '>=', '~~', '===', '!eqv', '&&', '||', '^^', '//', 'min', 'max', '??', '!!', 'ff', 'fff', 'so', 'not', '<==', '==>', '<<==', '==>>','unicmp', )
# Perl 6 has a *lot* of possible bracketing characters # this list was lifted from STD.pm6 (https://github.com/perl6/std) PERL6_BRACKETS = { '\u0028': '\u0029', '\u003c': '\u003e', '\u005b': '\u005d', '\u007b': '\u007d', '\u00ab': '\u00bb', '\u0f3a': '\u0f3b', '\u0f3c': '\u0f3d', '\u169b': '\u169c', '\u2018': '\u2019', '\u201a': '\u2019', '\u201b': '\u2019', '\u201c': '\u201d', '\u201e': '\u201d', '\u201f': '\u201d', '\u2039': '\u203a', '\u2045': '\u2046', '\u207d': '\u207e', '\u208d': '\u208e', '\u2208': '\u220b', '\u2209': '\u220c', '\u220a': '\u220d', '\u2215': '\u29f5', '\u223c': '\u223d', '\u2243': '\u22cd', '\u2252': '\u2253', '\u2254': '\u2255', '\u2264': '\u2265', '\u2266': '\u2267', '\u2268': '\u2269', '\u226a': '\u226b', '\u226e': '\u226f', '\u2270': '\u2271', '\u2272': '\u2273', '\u2274': '\u2275', '\u2276': '\u2277', '\u2278': '\u2279', '\u227a': '\u227b', '\u227c': '\u227d', '\u227e': '\u227f', '\u2280': '\u2281', '\u2282': '\u2283', '\u2284': '\u2285', '\u2286': '\u2287', '\u2288': '\u2289', '\u228a': '\u228b', '\u228f': '\u2290', '\u2291': '\u2292', '\u2298': '\u29b8', '\u22a2': '\u22a3', '\u22a6': '\u2ade', '\u22a8': '\u2ae4', '\u22a9': '\u2ae3', '\u22ab': '\u2ae5', '\u22b0': '\u22b1', '\u22b2': '\u22b3', '\u22b4': '\u22b5', '\u22b6': '\u22b7', '\u22c9': '\u22ca', '\u22cb': '\u22cc', '\u22d0': '\u22d1', '\u22d6': '\u22d7', '\u22d8': '\u22d9', '\u22da': '\u22db', '\u22dc': '\u22dd', '\u22de': '\u22df', '\u22e0': '\u22e1', '\u22e2': '\u22e3', '\u22e4': '\u22e5', '\u22e6': '\u22e7', '\u22e8': '\u22e9', '\u22ea': '\u22eb', '\u22ec': '\u22ed', '\u22f0': '\u22f1', '\u22f2': '\u22fa', '\u22f3': '\u22fb', '\u22f4': '\u22fc', '\u22f6': '\u22fd', '\u22f7': '\u22fe', '\u2308': '\u2309', '\u230a': '\u230b', '\u2329': '\u232a', '\u23b4': '\u23b5', '\u2768': '\u2769', '\u276a': '\u276b', '\u276c': '\u276d', '\u276e': '\u276f', '\u2770': '\u2771', '\u2772': '\u2773', '\u2774': '\u2775', '\u27c3': '\u27c4', '\u27c5': '\u27c6', '\u27d5': '\u27d6', '\u27dd': '\u27de', '\u27e2': '\u27e3', '\u27e4': '\u27e5', '\u27e6': '\u27e7', '\u27e8': '\u27e9', '\u27ea': '\u27eb', '\u2983': '\u2984', '\u2985': '\u2986', '\u2987': '\u2988', '\u2989': '\u298a', '\u298b': '\u298c', '\u298d': '\u298e', '\u298f': '\u2990', '\u2991': '\u2992', '\u2993': '\u2994', '\u2995': '\u2996', '\u2997': '\u2998', '\u29c0': '\u29c1', '\u29c4': '\u29c5', '\u29cf': '\u29d0', '\u29d1': '\u29d2', '\u29d4': '\u29d5', '\u29d8': '\u29d9', '\u29da': '\u29db', '\u29f8': '\u29f9', '\u29fc': '\u29fd', '\u2a2b': '\u2a2c', '\u2a2d': '\u2a2e', '\u2a34': '\u2a35', '\u2a3c': '\u2a3d', '\u2a64': '\u2a65', '\u2a79': '\u2a7a', '\u2a7d': '\u2a7e', '\u2a7f': '\u2a80', '\u2a81': '\u2a82', '\u2a83': '\u2a84', '\u2a8b': '\u2a8c', '\u2a91': '\u2a92', '\u2a93': '\u2a94', '\u2a95': '\u2a96', '\u2a97': '\u2a98', '\u2a99': '\u2a9a', '\u2a9b': '\u2a9c', '\u2aa1': '\u2aa2', '\u2aa6': '\u2aa7', '\u2aa8': '\u2aa9', '\u2aaa': '\u2aab', '\u2aac': '\u2aad', '\u2aaf': '\u2ab0', '\u2ab3': '\u2ab4', '\u2abb': '\u2abc', '\u2abd': '\u2abe', '\u2abf': '\u2ac0', '\u2ac1': '\u2ac2', '\u2ac3': '\u2ac4', '\u2ac5': '\u2ac6', '\u2acd': '\u2ace', '\u2acf': '\u2ad0', '\u2ad1': '\u2ad2', '\u2ad3': '\u2ad4', '\u2ad5': '\u2ad6', '\u2aec': '\u2aed', '\u2af7': '\u2af8', '\u2af9': '\u2afa', '\u2e02': '\u2e03', '\u2e04': '\u2e05', '\u2e09': '\u2e0a', '\u2e0c': '\u2e0d', '\u2e1c': '\u2e1d', '\u2e20': '\u2e21', '\u3008': '\u3009', '\u300a': '\u300b', '\u300c': '\u300d', '\u300e': '\u300f', '\u3010': '\u3011', '\u3014': '\u3015', '\u3016': '\u3017', '\u3018': '\u3019', '\u301a': '\u301b', '\u301d': '\u301e', '\ufd3e': '\ufd3f', '\ufe17': '\ufe18', '\ufe35': '\ufe36', '\ufe37': '\ufe38', '\ufe39': '\ufe3a', '\ufe3b': '\ufe3c', '\ufe3d': '\ufe3e', '\ufe3f': '\ufe40', '\ufe41': '\ufe42', '\ufe43': '\ufe44', '\ufe47': '\ufe48', '\ufe59': '\ufe5a', '\ufe5b': '\ufe5c', '\ufe5d': '\ufe5e', '\uff08': '\uff09', '\uff1c': '\uff1e', '\uff3b': '\uff3d', '\uff5b': '\uff5d', '\uff5f': '\uff60', '\uff62': '\uff63', }
def _build_word_match(words, boundary_regex_fragment=None, prefix='', suffix=''): if boundary_regex_fragment is None: return r'\b(' + prefix + r'|'.join(re.escape(x) for x in words) + \ suffix + r')\b' else: return r'(?<!' + boundary_regex_fragment + r')' + prefix + r'(' + \ r'|'.join(re.escape(x) for x in words) + r')' + suffix + r'(?!' + \ boundary_regex_fragment + r')'
def brackets_callback(token_class): def callback(lexer, match, context): groups = match.groupdict() opening_chars = groups['delimiter'] n_chars = len(opening_chars) adverbs = groups.get('adverbs')
closer = Perl6Lexer.PERL6_BRACKETS.get(opening_chars[0]) text = context.text
if closer is None: # it's not a mirrored character, which means we # just need to look for the next occurrence
end_pos = text.find(opening_chars, match.start('delimiter') + n_chars) else: # we need to look for the corresponding closing character, # keep nesting in mind closing_chars = closer * n_chars nesting_level = 1
search_pos = match.start('delimiter')
while nesting_level > 0: next_open_pos = text.find(opening_chars, search_pos + n_chars) next_close_pos = text.find(closing_chars, search_pos + n_chars)
if next_close_pos == -1: next_close_pos = len(text) nesting_level = 0 elif next_open_pos != -1 and next_open_pos < next_close_pos: nesting_level += 1 search_pos = next_open_pos else: # next_close_pos < next_open_pos nesting_level -= 1 search_pos = next_close_pos
end_pos = next_close_pos
if end_pos < 0: # if we didn't find a closer, just highlight the # rest of the text in this class end_pos = len(text)
if adverbs is not None and re.search(r':to\b', adverbs): heredoc_terminator = text[match.start('delimiter') + n_chars:end_pos] end_heredoc = re.search(r'^\s*' + re.escape(heredoc_terminator) + r'\s*$', text[end_pos:], re.MULTILINE)
if end_heredoc: end_pos += end_heredoc.end() else: end_pos = len(text)
yield match.start(), token_class, text[match.start():end_pos + n_chars] context.pos = end_pos + n_chars
return callback
def opening_brace_callback(lexer, match, context): stack = context.stack
yield match.start(), Text, context.text[match.start():match.end()] context.pos = match.end()
# if we encounter an opening brace and we're one level # below a token state, it means we need to increment # the nesting level for braces so we know later when # we should return to the token rules. if len(stack) > 2 and stack[-2] == 'token': context.perl6_token_nesting_level += 1
def closing_brace_callback(lexer, match, context): stack = context.stack
yield match.start(), Text, context.text[match.start():match.end()] context.pos = match.end()
# if we encounter a free closing brace and we're one level # below a token state, it means we need to check the nesting # level to see if we need to return to the token state. if len(stack) > 2 and stack[-2] == 'token': context.perl6_token_nesting_level -= 1 if context.perl6_token_nesting_level == 0: stack.pop()
def embedded_perl6_callback(lexer, match, context): context.perl6_token_nesting_level = 1 yield match.start(), Text, context.text[match.start():match.end()] context.pos = match.end() context.stack.append('root')
# If you're modifying these rules, be careful if you need to process '{' or '}' # characters. We have special logic for processing these characters (due to the fact # that you can nest Perl 6 code in regex blocks), so if you need to process one of # them, make sure you also process the corresponding one! tokens = { 'common': [ (r'#[`|=](?P<delimiter>(?P<first_char>[' + ''.join(PERL6_BRACKETS) + r'])(?P=first_char)*)', brackets_callback(Comment.Multiline)), (r'#[^\n]*$', Comment.Single), (r'^(\s*)=begin\s+(\w+)\b.*?^\1=end\s+\2', Comment.Multiline), (r'^(\s*)=for.*?\n\s*?\n', Comment.Multiline), (r'^=.*?\n\s*?\n', Comment.Multiline), (r'(regex|token|rule)(\s*' + PERL6_IDENTIFIER_RANGE + '+:sym)', bygroups(Keyword, Name), 'token-sym-brackets'), (r'(regex|token|rule)(?!' + PERL6_IDENTIFIER_RANGE + r')(\s*' + PERL6_IDENTIFIER_RANGE + '+)?', bygroups(Keyword, Name), 'pre-token'), # deal with a special case in the Perl 6 grammar (role q { ... }) (r'(role)(\s+)(q)(\s*)', bygroups(Keyword, Whitespace, Name, Whitespace)), (_build_word_match(PERL6_KEYWORDS, PERL6_IDENTIFIER_RANGE), Keyword), (_build_word_match(PERL6_BUILTIN_CLASSES, PERL6_IDENTIFIER_RANGE, suffix='(?::[UD])?'), Name.Builtin), (_build_word_match(PERL6_BUILTINS, PERL6_IDENTIFIER_RANGE), Name.Builtin), # copied from PerlLexer (r'[$@%&][.^:?=!~]?' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable), (r'\$[!/](?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable.Global), (r'::\?\w+', Name.Variable.Global), (r'[$@%&]\*' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable.Global), (r'\$(?:<.*?>)+', Name.Variable), (r'(?:q|qq|Q)[a-zA-Z]?\s*(?P<adverbs>:[\w\s:]+)?\s*(?P<delimiter>(?P<first_char>[^0-9a-zA-Z:\s])' r'(?P=first_char)*)', brackets_callback(String)), # copied from PerlLexer (r'0_?[0-7]+(_[0-7]+)*', Number.Oct), (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex), (r'0b[01]+(_[01]+)*', Number.Bin), (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?', Number.Float), (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float), (r'\d+(_\d+)*', Number.Integer), (r'(?<=~~)\s*/(?:\\\\|\\/|.)*?/', String.Regex), (r'(?<=[=(,])\s*/(?:\\\\|\\/|.)*?/', String.Regex), (r'm\w+(?=\()', Name), (r'(?:m|ms|rx)\s*(?P<adverbs>:[\w\s:]+)?\s*(?P<delimiter>(?P<first_char>[^\w:\s])' r'(?P=first_char)*)', brackets_callback(String.Regex)), (r'(?:s|ss|tr)\s*(?::[\w\s:]+)?\s*/(?:\\\\|\\/|.)*?/(?:\\\\|\\/|.)*?/', String.Regex), (r'<[^\s=].*?\S>', String), (_build_word_match(PERL6_OPERATORS), Operator), (r'\w' + PERL6_IDENTIFIER_RANGE + '*', Name), (r"'(\\\\|\\[^\\]|[^'\\])*'", String), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), ], 'root': [ include('common'), (r'\{', opening_brace_callback), (r'\}', closing_brace_callback), (r'.+?', Text), ], 'pre-token': [ include('common'), (r'\{', Text, ('#pop', 'token')), (r'.+?', Text), ], 'token-sym-brackets': [ (r'(?P<delimiter>(?P<first_char>[' + ''.join(PERL6_BRACKETS) + '])(?P=first_char)*)', brackets_callback(Name), ('#pop', 'pre-token')), default(('#pop', 'pre-token')), ], 'token': [ (r'\}', Text, '#pop'), (r'(?<=:)(?:my|our|state|constant|temp|let).*?;', using(this)), # make sure that quotes in character classes aren't treated as strings (r'<(?:[-!?+.]\s*)?\[.*?\]>', String.Regex), # make sure that '#' characters in quotes aren't treated as comments (r"(?<!\\)'(\\\\|\\[^\\]|[^'\\])*'", String.Regex), (r'(?<!\\)"(\\\\|\\[^\\]|[^"\\])*"', String.Regex), (r'#.*?$', Comment.Single), (r'\{', embedded_perl6_callback), ('.+?', String.Regex), ], }
def analyse_text(text): def strip_pod(lines): in_pod = False stripped_lines = []
for line in lines: if re.match(r'^=(?:end|cut)', line): in_pod = False elif re.match(r'^=\w+', line): in_pod = True elif not in_pod: stripped_lines.append(line)
return stripped_lines
# XXX handle block comments lines = text.splitlines() lines = strip_pod(lines) text = '\n'.join(lines)
if shebang_matches(text, r'perl6|rakudo|niecza|pugs'): return True
saw_perl_decl = False rating = False
# check for my/our/has declarations if re.search(r"(?:my|our|has)\s+(?:" + Perl6Lexer.PERL6_IDENTIFIER_RANGE + r"+\s+)?[$@%&(]", text): rating = 0.8 saw_perl_decl = True
for line in lines: line = re.sub('#.*', '', line) if re.match(r'^\s*$', line): continue
# match v6; use v6; use v6.0; use v6.0.0; if re.match(r'^\s*(?:use\s+)?v6(?:\.\d(?:\.\d)?)?;', line): return True # match class, module, role, enum, grammar declarations class_decl = re.match(r'^\s*(?:(?P<scope>my|our)\s+)?(?:module|class|role|enum|grammar)', line) if class_decl: if saw_perl_decl or class_decl.group('scope') is not None: return True rating = 0.05 continue break
if ':=' in text: # Same logic as above for PerlLexer rating /= 2
return rating
def __init__(self, **options): super().__init__(**options) self.encoding = options.get('encoding', 'utf-8')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363""" pygments.lexers.phix ~~~~~~~~~~~~~~~~~~~~
Lexers for Phix.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Whitespace
__all__ = ['PhixLexer']
class PhixLexer(RegexLexer): """ Pygments Lexer for Phix files (.exw). See http://phix.x10.mx """
name = 'Phix' url = 'http://phix.x10.mx' aliases = ['phix'] filenames = ['*.exw'] mimetypes = ['text/x-phix'] version_added = '2.14'
flags = re.MULTILINE # nb: **NOT** re.DOTALL! (totally spanners comment handling)
preproc = ( 'ifdef', 'elsifdef', 'elsedef' ) # Note these lists are auto-generated by pwa/p2js.exw, when pwa\src\p2js_keywords.e (etc) # change, though of course subsequent copy/commit/pull requests are all manual steps. types = ( 'string', 'nullable_string', 'atom_string', 'atom', 'bool', 'boolean', 'cdCanvan', 'cdCanvas', 'complex', 'CURLcode', 'dictionary', 'int', 'integer', 'Ihandle', 'Ihandles', 'Ihandln', 'mpfr', 'mpq', 'mpz', 'mpz_or_string', 'number', 'rid_string', 'seq', 'sequence', 'timedate', 'object' ) keywords = ( 'abstract', 'class', 'continue', 'export', 'extends', 'nullable', 'private', 'public', 'static', 'struct', 'trace', 'and', 'break', 'by', 'case', 'catch', 'const', 'constant', 'debug', 'default', 'do', 'else', 'elsif', 'end', 'enum', 'exit', 'fallthru', 'fallthrough', 'for', 'forward', 'function', 'global', 'if', 'in', 'include', 'js', 'javascript', 'javascript_semantics', 'let', 'not', 'or', 'procedure', 'profile', 'profile_time', 'return', 'safe_mode', 'switch', 'then', 'to', 'try', 'type', 'type_check', 'until', 'warning', 'while', 'with', 'without', 'xor' ) routines = ( 'abort', 'abs', 'adjust_timedate', 'and_bits', 'and_bitsu', 'apply', 'append', 'arccos', 'arcsin', 'arctan', 'assert', 'atan2', 'atom_to_float32', 'atom_to_float64', 'bankers_rounding', 'beep', 'begins', 'binary_search', 'bits_to_int', 'bk_color', 'bytes_to_int', 'call_func', 'call_proc', 'cdCanvasActivate', 'cdCanvasArc', 'cdCanvasBegin', 'cdCanvasBox', 'cdCanvasChord', 'cdCanvasCircle', 'cdCanvasClear', 'cdCanvasEnd', 'cdCanvasFlush', 'cdCanvasFont', 'cdCanvasGetImageRGB', 'cdCanvasGetSize', 'cdCanvasGetTextAlignment', 'cdCanvasGetTextSize', 'cdCanvasLine', 'cdCanvasMark', 'cdCanvasMarkSize', 'cdCanvasMultiLineVectorText', 'cdCanvasPixel', 'cdCanvasRect', 'cdCanvasRoundedBox', 'cdCanvasRoundedRect', 'cdCanvasSector', 'cdCanvasSetAttribute', 'cdCanvasSetBackground', 'cdCanvasSetFillMode', 'cdCanvasSetForeground', 'cdCanvasSetInteriorStyle', 'cdCanvasSetLineStyle', 'cdCanvasSetLineWidth', 'cdCanvasSetTextAlignment', 'cdCanvasText', 'cdCanvasSetTextOrientation', 'cdCanvasGetTextOrientation', 'cdCanvasVectorText', 'cdCanvasVectorTextDirection', 'cdCanvasVectorTextSize', 'cdCanvasVertex', 'cdCreateCanvas', 'cdDecodeAlpha', 'cdDecodeColor', 'cdDecodeColorAlpha', 'cdEncodeAlpha', 'cdEncodeColor', 'cdEncodeColorAlpha', 'cdKillCanvas', 'cdVersion', 'cdVersionDate', 'ceil', 'change_timezone', 'choose', 'clear_screen', 'columnize', 'command_line', 'compare', 'complex_abs', 'complex_add', 'complex_arg', 'complex_conjugate', 'complex_cos', 'complex_cosh', 'complex_div', 'complex_exp', 'complex_imag', 'complex_inv', 'complex_log', 'complex_mul', 'complex_neg', 'complex_new', 'complex_norm', 'complex_power', 'complex_rho', 'complex_real', 'complex_round', 'complex_sin', 'complex_sinh', 'complex_sprint', 'complex_sqrt', 'complex_sub', 'complex_theta', 'concat', 'cos', 'crash', 'custom_sort', 'date', 'day_of_week', 'day_of_year', 'days_in_month', 'decode_base64', 'decode_flags', 'deep_copy', 'deld', 'deserialize', 'destroy_dict', 'destroy_queue', 'destroy_stack', 'dict_name', 'dict_size', 'elapsed', 'elapsed_short', 'encode_base64', 'equal', 'even', 'exp', 'extract', 'factorial', 'factors', 'file_size_k', 'find', 'find_all', 'find_any', 'find_replace', 'filter', 'flatten', 'float32_to_atom', 'float64_to_atom', 'floor', 'format_timedate', 'free_console', 'from_polar', 'gcd', 'get_file_base', 'get_file_extension', 'get_file_name', 'get_file_name_and_path', 'get_file_path', 'get_file_path_and_name', 'get_maxprime', 'get_prime', 'get_primes', 'get_primes_le', 'get_proper_dir', 'get_proper_path', 'get_rand', 'get_routine_info', 'get_test_abort', 'get_test_logfile', 'get_test_pause', 'get_test_verbosity', 'get_tzid', 'getd', 'getdd', 'getd_all_keys', 'getd_by_index', 'getd_index', 'getd_partial_key', 'glAttachShader', 'glBindBuffer', 'glBindTexture', 'glBufferData', 'glCanvasSpecialText', 'glClear', 'glClearColor', 'glColor', 'glCompileShader', 'glCreateBuffer', 'glCreateProgram', 'glCreateShader', 'glCreateTexture', 'glDeleteProgram', 'glDeleteShader', 'glDrawArrays', 'glEnable', 'glEnableVertexAttribArray', 'glFloat32Array', 'glInt32Array', 'glFlush', 'glGetAttribLocation', 'glGetError', 'glGetProgramInfoLog', 'glGetProgramParameter', 'glGetShaderInfoLog', 'glGetShaderParameter', 'glGetUniformLocation', 'glLinkProgram', 'glLoadIdentity', 'glMatrixMode', 'glOrtho', 'glRotatef', 'glShadeModel', 'glShaderSource', 'glSimpleA7texcoords', 'glTexImage2Dc', 'glTexParameteri', 'glTranslate', 'glUniform1f', 'glUniform1i', 'glUniformMatrix4fv', 'glUseProgram', 'glVertex', 'glVertexAttribPointer', 'glViewport', 'head', 'hsv_to_rgb', 'iff', 'iif', 'include_file', 'incl0de_file', 'insert', 'instance', 'int_to_bits', 'int_to_bytes', 'is_dict', 'is_integer', 's_leap_year', 'is_prime', 'is_prime2', 'islower', 'isupper', 'Icallback', 'iup_isdouble', 'iup_isprint', 'iup_XkeyBase', 'IupAppend', 'IupAlarm', 'IupBackgroundBox', 'IupButton', 'IupCalendar', 'IupCanvas', 'IupClipboard', 'IupClose', 'IupCloseOnEscape', 'IupControlsOpen', 'IupDatePick', 'IupDestroy', 'IupDialog', 'IupDrawArc', 'IupDrawBegin', 'IupDrawEnd', 'IupDrawGetSize', 'IupDrawGetTextSize', 'IupDrawLine', 'IupDrawRectangle', 'IupDrawText', 'IupExpander', 'IupFill', 'IupFlatLabel', 'IupFlatList', 'IupFlatTree', 'IupFlush', 'IupFrame', 'IupGetAttribute', 'IupGetAttributeId', 'IupGetAttributePtr', 'IupGetBrother', 'IupGetChild', 'IupGetChildCount', 'IupGetClassName', 'IupGetDialog', 'IupGetDialogChild', 'IupGetDouble', 'IupGetFocus', 'IupGetGlobal', 'IupGetGlobalInt', 'IupGetGlobalIntInt', 'IupGetInt', 'IupGetInt2', 'IupGetIntId', 'IupGetIntInt', 'IupGetParent', 'IupGLCanvas', 'IupGLCanvasOpen', 'IupGLMakeCurrent', 'IupGraph', 'IupHbox', 'IupHide', 'IupImage', 'IupImageRGBA', 'IupItem', 'iupKeyCodeToName', 'IupLabel', 'IupLink', 'IupList', 'IupMap', 'IupMenu', 'IupMenuItem', 'IupMessage', 'IupMessageDlg', 'IupMultiBox', 'IupMultiLine', 'IupNextField', 'IupNormaliser', 'IupOpen', 'IupPlayInput', 'IupPopup', 'IupPreviousField', 'IupProgressBar', 'IupRadio', 'IupRecordInput', 'IupRedraw', 'IupRefresh', 'IupRefreshChildren', 'IupSeparator', 'IupSetAttribute', 'IupSetAttributes', 'IupSetAttributeHandle', 'IupSetAttributeId', 'IupSetAttributePtr', 'IupSetCallback', 'IupSetCallbacks', 'IupSetDouble', 'IupSetFocus', 'IupSetGlobal', 'IupSetGlobalInt', 'IupSetGlobalFunction', 'IupSetHandle', 'IupSetInt', 'IupSetStrAttribute', 'IupSetStrGlobal', 'IupShow', 'IupShowXY', 'IupSplit', 'IupStoreAttribute', 'IupSubmenu', 'IupTable', 'IupTableClearSelected', 'IupTableClick_cb', 'IupTableGetSelected', 'IupTableResize_cb', 'IupTableSetData', 'IupTabs', 'IupText', 'IupTimer', 'IupToggle', 'IupTreeAddNodes', 'IupTreeView', 'IupUpdate', 'IupValuator', 'IupVbox', 'join', 'join_by', 'join_path', 'k_perm', 'largest', 'lcm', 'length', 'log', 'log10', 'log2', 'lower', 'm4_crossProduct', 'm4_inverse', 'm4_lookAt', 'm4_multiply', 'm4_normalize', 'm4_perspective', 'm4_subtractVectors', 'm4_xRotate', 'm4_yRotate', 'machine_bits', 'machine_word', 'match', 'match_all', 'match_replace', 'max', 'maxsq', 'min', 'minsq', 'mod', 'mpfr_add', 'mpfr_ceil', 'mpfr_cmp', 'mpfr_cmp_si', 'mpfr_const_pi', 'mpfr_div', 'mpfr_div_si', 'mpfr_div_z', 'mpfr_floor', 'mpfr_free', 'mpfr_get_d', 'mpfr_get_default_precision', 'mpfr_get_default_rounding_mode', 'mpfr_get_fixed', 'mpfr_get_precision', 'mpfr_get_si', 'mpfr_init', 'mpfr_inits', 'mpfr_init_set', 'mpfr_init_set_q', 'mpfr_init_set_z', 'mpfr_mul', 'mpfr_mul_si', 'mpfr_pow_si', 'mpfr_set', 'mpfr_set_d', 'mpfr_set_default_precision', 'mpfr_set_default_rounding_mode', 'mpfr_set_precision', 'mpfr_set_q', 'mpfr_set_si', 'mpfr_set_str', 'mpfr_set_z', 'mpfr_si_div', 'mpfr_si_sub', 'mpfr_sqrt', 'mpfr_sub', 'mpfr_sub_si', 'mpq_abs', 'mpq_add', 'mpq_add_si', 'mpq_canonicalize', 'mpq_cmp', 'mpq_cmp_si', 'mpq_div', 'mpq_div_2exp', 'mpq_free', 'mpq_get_den', 'mpq_get_num', 'mpq_get_str', 'mpq_init', 'mpq_init_set', 'mpq_init_set_si', 'mpq_init_set_str', 'mpq_init_set_z', 'mpq_inits', 'mpq_inv', 'mpq_mul', 'mpq_neg', 'mpq_set', 'mpq_set_si', 'mpq_set_str', 'mpq_set_z', 'mpq_sub', 'mpz_abs', 'mpz_add', 'mpz_addmul', 'mpz_addmul_ui', 'mpz_addmul_si', 'mpz_add_si', 'mpz_add_ui', 'mpz_and', 'mpz_bin_uiui', 'mpz_cdiv_q', 'mpz_cmp', 'mpz_cmp_si', 'mpz_divexact', 'mpz_divexact_ui', 'mpz_divisible_p', 'mpz_divisible_ui_p', 'mpz_even', 'mpz_fac_ui', 'mpz_factorstring', 'mpz_fdiv_q', 'mpz_fdiv_q_2exp', 'mpz_fdiv_q_ui', 'mpz_fdiv_qr', 'mpz_fdiv_r', 'mpz_fdiv_ui', 'mpz_fib_ui', 'mpz_fib2_ui', 'mpz_fits_atom', 'mpz_fits_integer', 'mpz_free', 'mpz_gcd', 'mpz_gcd_ui', 'mpz_get_atom', 'mpz_get_integer', 'mpz_get_short_str', 'mpz_get_str', 'mpz_init', 'mpz_init_set', 'mpz_inits', 'mpz_invert', 'mpz_lcm', 'mpz_lcm_ui', 'mpz_max', 'mpz_min', 'mpz_mod', 'mpz_mod_ui', 'mpz_mul', 'mpz_mul_2exp', 'mpz_mul_d', 'mpz_mul_si', 'mpz_neg', 'mpz_nthroot', 'mpz_odd', 'mpz_pollard_rho', 'mpz_pow_ui', 'mpz_powm', 'mpz_powm_ui', 'mpz_prime', 'mpz_prime_factors', 'mpz_prime_mr', 'mpz_rand', 'mpz_rand_ui', 'mpz_re_compose', 'mpz_remove', 'mpz_scan0', 'mpz_scan1', 'mpz_set', 'mpz_set_d', 'mpz_set_si', 'mpz_set_str', 'mpz_set_v', 'mpz_sign', 'mpz_sizeinbase', 'mpz_sqrt', 'mpz_sub', 'mpz_sub_si', 'mpz_sub_ui', 'mpz_si_sub', 'mpz_tdiv_q_2exp', 'mpz_tdiv_r_2exp', 'mpz_tstbit', 'mpz_ui_pow_ui', 'mpz_xor', 'named_dict', 'new_dict', 'new_queue', 'new_stack', 'not_bits', 'not_bitsu', 'odd', 'or_all', 'or_allu', 'or_bits', 'or_bitsu', 'ord', 'ordinal', 'ordinant', 'override_timezone', 'pad', 'pad_head', 'pad_tail', 'parse_date_string', 'papply', 'peep', 'peepn', 'peep_dict', 'permute', 'permutes', 'platform', 'pop', 'popn', 'pop_dict', 'power', 'pp', 'ppEx', 'ppExf', 'ppf', 'ppOpt', 'pq_add', 'pq_destroy', 'pq_empty', 'pq_new', 'pq_peek', 'pq_pop', 'pq_pop_data', 'pq_size', 'prepend', 'prime_factors', 'printf', 'product', 'proper', 'push', 'pushn', 'putd', 'puts', 'queue_empty', 'queue_size', 'rand', 'rand_range', 'reinstate', 'remainder', 'remove', 'remove_all', 'repeat', 'repeatch', 'replace', 'requires', 'reverse', 'rfind', 'rgb', 'rmatch', 'rmdr', 'rnd', 'round', 'routine_id', 'scanf', 'serialize', 'series', 'set_rand', 'set_test_abort', 'set_test_logfile', 'set_test_module', 'set_test_pause', 'set_test_verbosity', 'set_timedate_formats', 'set_timezone', 'setd', 'setd_default', 'shorten', 'sha256', 'shift_bits', 'shuffle', 'sign', 'sin', 'smallest', 'sort', 'sort_columns', 'speak', 'splice', 'split', 'split_any', 'split_by', 'sprint', 'sprintf', 'sq_abs', 'sq_add', 'sq_and', 'sq_and_bits', 'sq_arccos', 'sq_arcsin', 'sq_arctan', 'sq_atom', 'sq_ceil', 'sq_cmp', 'sq_cos', 'sq_div', 'sq_even', 'sq_eq', 'sq_floor', 'sq_floor_div', 'sq_ge', 'sq_gt', 'sq_int', 'sq_le', 'sq_log', 'sq_log10', 'sq_log2', 'sq_lt', 'sq_max', 'sq_min', 'sq_mod', 'sq_mul', 'sq_ne', 'sq_not', 'sq_not_bits', 'sq_odd', 'sq_or', 'sq_or_bits', 'sq_power', 'sq_rand', 'sq_remainder', 'sq_rmdr', 'sq_rnd', 'sq_round', 'sq_seq', 'sq_sign', 'sq_sin', 'sq_sqrt', 'sq_str', 'sq_sub', 'sq_tan', 'sq_trunc', 'sq_uminus', 'sq_xor', 'sq_xor_bits', 'sqrt', 'square_free', 'stack_empty', 'stack_size', 'substitute', 'substitute_all', 'sum', 'tail', 'tan', 'test_equal', 'test_fail', 'test_false', 'test_not_equal', 'test_pass', 'test_summary', 'test_true', 'text_color', 'throw', 'time', 'timedate_diff', 'timedelta', 'to_integer', 'to_number', 'to_rgb', 'to_string', 'traverse_dict', 'traverse_dict_partial_key', 'trim', 'trim_head', 'trim_tail', 'trunc', 'tagset', 'tagstart', 'typeof', 'unique', 'unix_dict', 'upper', 'utf8_to_utf32', 'utf32_to_utf8', 'version', 'vlookup', 'vslice', 'wglGetProcAddress', 'wildcard_file', 'wildcard_match', 'with_rho', 'with_theta', 'xml_new_doc', 'xml_new_element', 'xml_set_attribute', 'xml_sprint', 'xor_bits', 'xor_bitsu', 'accept', 'allocate', 'allocate_string', 'allow_break', 'ARM', 'atom_to_float80', 'c_func', 'c_proc', 'call_back', 'chdir', 'check_break', 'clearDib', 'close', 'closesocket', 'console', 'copy_file', 'create', 'create_directory', 'create_thread', 'curl_easy_cleanup', 'curl_easy_get_file', 'curl_easy_init', 'curl_easy_perform', 'curl_easy_perform_ex', 'curl_easy_setopt', 'curl_easy_strerror', 'curl_global_cleanup', 'curl_global_init', 'curl_slist_append', 'curl_slist_free_all', 'current_dir', 'cursor', 'define_c_func', 'define_c_proc', 'delete', 'delete_cs', 'delete_file', 'dir', 'DLL', 'drawDib', 'drawShadedPolygonToDib', 'ELF32', 'ELF64', 'enter_cs', 'eval', 'exit_thread', 'free', 'file_exists', 'final', 'float80_to_atom', 'format', 'get_bytes', 'get_file_date', 'get_file_size', 'get_file_type', 'get_interpreter', 'get_key', 'get_socket_error', 'get_text', 'get_thread_exitcode', 'get_thread_id', 'getc', 'getenv', 'gets', 'getsockaddr', 'glBegin', 'glCallList', 'glFrustum', 'glGenLists', 'glGetString', 'glLight', 'glMaterial', 'glNewList', 'glNormal', 'glPopMatrix', 'glPushMatrix', 'glRotate', 'glEnd', 'glEndList', 'glTexImage2D', 'goto', 'GUI', 'icons', 'ilASM', 'include_files', 'include_paths', 'init_cs', 'ip_to_string', 'IupConfig', 'IupConfigDialogClosed', 'IupConfigDialogShow', 'IupConfigGetVariableInt', 'IupConfigLoad', 'IupConfigSave', 'IupConfigSetVariableInt', 'IupExitLoop', 'IupFileDlg', 'IupFileList', 'IupGLSwapBuffers', 'IupHelp', 'IupLoopStep', 'IupMainLoop', 'IupNormalizer', 'IupPlot', 'IupPlotAdd', 'IupPlotBegin', 'IupPlotEnd', 'IupPlotInsert', 'IupSaveImage', 'IupTreeGetUserId', 'IupUser', 'IupVersion', 'IupVersionDate', 'IupVersionNumber', 'IupVersionShow', 'killDib', 'leave_cs', 'listen', 'manifest', 'mem_copy', 'mem_set', 'mpfr_gamma', 'mpfr_printf', 'mpfr_sprintf', 'mpz_export', 'mpz_import', 'namespace', 'new', 'newDib', 'open', 'open_dll', 'PE32', 'PE64', 'peek', 'peek_string', 'peek1s', 'peek1u', 'peek2s', 'peek2u', 'peek4s', 'peek4u', 'peek8s', 'peek8u', 'peekNS', 'peekns', 'peeknu', 'poke', 'poke2', 'poke4', 'poke8', 'pokeN', 'poke_string', 'poke_wstring', 'position', 'progress', 'prompt_number', 'prompt_string', 'read_file', 'read_lines', 'recv', 'resume_thread', 'seek', 'select', 'send', 'setHandler', 'shutdown', 'sleep', 'SO', 'sockaddr_in', 'socket', 'split_path', 'suspend_thread', 'system', 'system_exec', 'system_open', 'system_wait', 'task_clock_start', 'task_clock_stop', 'task_create', 'task_delay', 'task_list', 'task_schedule', 'task_self', 'task_status', 'task_suspend', 'task_yield', 'thread_safe_string', 'try_cs', 'utf8_to_utf16', 'utf16_to_utf8', 'utf16_to_utf32', 'utf32_to_utf16', 'video_config', 'WSACleanup', 'wait_thread', 'walk_dir', 'where', 'write_lines', 'wait_key' ) constants = ( 'ANY_QUEUE', 'ASCENDING', 'BLACK', 'BLOCK_CURSOR', 'BLUE', 'BRIGHT_CYAN', 'BRIGHT_BLUE', 'BRIGHT_GREEN', 'BRIGHT_MAGENTA', 'BRIGHT_RED', 'BRIGHT_WHITE', 'BROWN', 'C_DWORD', 'C_INT', 'C_POINTER', 'C_USHORT', 'C_WORD', 'CD_AMBER', 'CD_BLACK', 'CD_BLUE', 'CD_BOLD', 'CD_BOLD_ITALIC', 'CD_BOX', 'CD_CENTER', 'CD_CIRCLE', 'CD_CLOSED_LINES', 'CD_CONTINUOUS', 'CD_CUSTOM', 'CD_CYAN', 'CD_DARK_BLUE', 'CD_DARK_CYAN', 'CD_DARK_GRAY', 'CD_DARK_GREY', 'CD_DARK_GREEN', 'CD_DARK_MAGENTA', 'CD_DARK_RED', 'CD_DARK_YELLOW', 'CD_DASH_DOT', 'CD_DASH_DOT_DOT', 'CD_DASHED', 'CD_DBUFFER', 'CD_DEG2RAD', 'CD_DIAMOND', 'CD_DOTTED', 'CD_EAST', 'CD_EVENODD', 'CD_FILL', 'CD_GL', 'CD_GRAY', 'CD_GREY', 'CD_GREEN', 'CD_HATCH', 'CD_HOLLOW', 'CD_HOLLOW_BOX', 'CD_HOLLOW_CIRCLE', 'CD_HOLLOW_DIAMOND', 'CD_INDIGO', 'CD_ITALIC', 'CD_IUP', 'CD_IUPDBUFFER', 'CD_LIGHT_BLUE', 'CD_LIGHT_GRAY', 'CD_LIGHT_GREY', 'CD_LIGHT_GREEN', 'CD_LIGHT_PARCHMENT', 'CD_MAGENTA', 'CD_NAVY', 'CD_NORTH', 'CD_NORTH_EAST', 'CD_NORTH_WEST', 'CD_OLIVE', 'CD_OPEN_LINES', 'CD_ORANGE', 'CD_PARCHMENT', 'CD_PATTERN', 'CD_PRINTER', 'CD_PURPLE', 'CD_PLAIN', 'CD_PLUS', 'CD_QUERY', 'CD_RAD2DEG', 'CD_RED', 'CD_SILVER', 'CD_SOLID', 'CD_SOUTH_EAST', 'CD_SOUTH_WEST', 'CD_STAR', 'CD_STIPPLE', 'CD_STRIKEOUT', 'CD_UNDERLINE', 'CD_WEST', 'CD_WHITE', 'CD_WINDING', 'CD_VIOLET', 'CD_X', 'CD_YELLOW', 'CURLE_OK', 'CURLOPT_MAIL_FROM', 'CURLOPT_MAIL_RCPT', 'CURLOPT_PASSWORD', 'CURLOPT_READDATA', 'CURLOPT_READFUNCTION', 'CURLOPT_SSL_VERIFYPEER', 'CURLOPT_SSL_VERIFYHOST', 'CURLOPT_UPLOAD', 'CURLOPT_URL', 'CURLOPT_USE_SSL', 'CURLOPT_USERNAME', 'CURLOPT_VERBOSE', 'CURLOPT_WRITEFUNCTION', 'CURLUSESSL_ALL', 'CYAN', 'D_NAME', 'D_ATTRIBUTES', 'D_SIZE', 'D_YEAR', 'D_MONTH', 'D_DAY', 'D_HOUR', 'D_MINUTE', 'D_SECOND', 'D_CREATION', 'D_LASTACCESS', 'D_MODIFICATION', 'DT_YEAR', 'DT_MONTH', 'DT_DAY', 'DT_HOUR', 'DT_MINUTE', 'DT_SECOND', 'DT_DOW', 'DT_MSEC', 'DT_DOY', 'DT_GMT', 'EULER', 'E_CODE', 'E_ADDR', 'E_LINE', 'E_RTN', 'E_NAME', 'E_FILE', 'E_PATH', 'E_USER', 'false', 'False', 'FALSE', 'FIFO_QUEUE', 'FILETYPE_DIRECTORY', 'FILETYPE_FILE', 'GET_EOF', 'GET_FAIL', 'GET_IGNORE', 'GET_SUCCESS', 'GL_AMBIENT_AND_DIFFUSE', 'GL_ARRAY_BUFFER', 'GL_CLAMP', 'GL_CLAMP_TO_BORDER', 'GL_CLAMP_TO_EDGE', 'GL_COLOR_BUFFER_BIT', 'GL_COMPILE', 'GL_COMPILE_STATUS', 'GL_CULL_FACE', 'GL_DEPTH_BUFFER_BIT', 'GL_DEPTH_TEST', 'GL_EXTENSIONS', 'GL_FLAT', 'GL_FLOAT', 'GL_FRAGMENT_SHADER', 'GL_FRONT', 'GL_LIGHT0', 'GL_LIGHTING', 'GL_LINEAR', 'GL_LINK_STATUS', 'GL_MODELVIEW', 'GL_NEAREST', 'GL_NO_ERROR', 'GL_NORMALIZE', 'GL_POSITION', 'GL_PROJECTION', 'GL_QUAD_STRIP', 'GL_QUADS', 'GL_RENDERER', 'GL_REPEAT', 'GL_RGB', 'GL_RGBA', 'GL_SMOOTH', 'GL_STATIC_DRAW', 'GL_TEXTURE_2D', 'GL_TEXTURE_MAG_FILTER', 'GL_TEXTURE_MIN_FILTER', 'GL_TEXTURE_WRAP_S', 'GL_TEXTURE_WRAP_T', 'GL_TRIANGLES', 'GL_UNSIGNED_BYTE', 'GL_VENDOR', 'GL_VERSION', 'GL_VERTEX_SHADER', 'GRAY', 'GREEN', 'GT_LF_STRIPPED', 'GT_WHOLE_FILE', 'INVLN10', 'IUP_CLOSE', 'IUP_CONTINUE', 'IUP_DEFAULT', 'IUP_BLACK', 'IUP_BLUE', 'IUP_BUTTON1', 'IUP_BUTTON3', 'IUP_CENTER', 'IUP_CYAN', 'IUP_DARK_BLUE', 'IUP_DARK_CYAN', 'IUP_DARK_GRAY', 'IUP_DARK_GREY', 'IUP_DARK_GREEN', 'IUP_DARK_MAGENTA', 'IUP_DARK_RED', 'IUP_GRAY', 'IUP_GREY', 'IUP_GREEN', 'IUP_IGNORE', 'IUP_INDIGO', 'IUP_MAGENTA', 'IUP_MASK_INT', 'IUP_MASK_UINT', 'IUP_MOUSEPOS', 'IUP_NAVY', 'IUP_OLIVE', 'IUP_RECTEXT', 'IUP_RED', 'IUP_LIGHT_BLUE', 'IUP_LIGHT_GRAY', 'IUP_LIGHT_GREY', 'IUP_LIGHT_GREEN', 'IUP_ORANGE', 'IUP_PARCHMENT', 'IUP_PURPLE', 'IUP_SILVER', 'IUP_TEAL', 'IUP_VIOLET', 'IUP_WHITE', 'IUP_YELLOW', 'K_BS', 'K_cA', 'K_cC', 'K_cD', 'K_cF5', 'K_cK', 'K_cM', 'K_cN', 'K_cO', 'K_cP', 'K_cR', 'K_cS', 'K_cT', 'K_cW', 'K_CR', 'K_DEL', 'K_DOWN', 'K_END', 'K_ESC', 'K_F1', 'K_F2', 'K_F3', 'K_F4', 'K_F5', 'K_F6', 'K_F7', 'K_F8', 'K_F9', 'K_F10', 'K_F11', 'K_F12', 'K_HOME', 'K_INS', 'K_LEFT', 'K_MIDDLE', 'K_PGDN', 'K_PGUP', 'K_RIGHT', 'K_SP', 'K_TAB', 'K_UP', 'K_h', 'K_i', 'K_j', 'K_p', 'K_r', 'K_s', 'JS', 'LIFO_QUEUE', 'LINUX', 'MAX_HEAP', 'MAGENTA', 'MIN_HEAP', 'Nan', 'NO_CURSOR', 'null', 'NULL', 'PI', 'pp_Ascii', 'pp_Brkt', 'pp_Date', 'pp_File', 'pp_FltFmt', 'pp_Indent', 'pp_IntCh', 'pp_IntFmt', 'pp_Maxlen', 'pp_Nest', 'pp_Pause', 'pp_Q22', 'pp_StrFmt', 'RED', 'SEEK_OK', 'SLASH', 'TEST_ABORT', 'TEST_CRASH', 'TEST_PAUSE', 'TEST_PAUSE_FAIL', 'TEST_QUIET', 'TEST_SHOW_ALL', 'TEST_SHOW_FAILED', 'TEST_SUMMARY', 'true', 'True', 'TRUE', 'VC_SCRNLINES', 'WHITE', 'WINDOWS', 'YELLOW' )
tokens = { 'root': [ (r"\s+", Whitespace), (r'/\*|--/\*|#\[', Comment.Multiline, 'comment'), (r'(?://|--|#!).*$', Comment.Single),#Alt:# (r'//.*$|--.*$|#!.*$', Comment.Single), (r'"([^"\\]|\\.)*"', String.Other), (r'\'[^\']*\'', String.Other), (r'`[^`]*`', String.Other),
(words(types, prefix=r'\b', suffix=r'\b'), Name.Function), (words(routines, prefix=r'\b', suffix=r'\b'), Name.Function), (words(preproc, prefix=r'\b', suffix=r'\b'), Keyword.Declaration), (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword.Declaration), (words(constants, prefix=r'\b', suffix=r'\b'), Name.Constant), # Aside: Phix only supports/uses the ascii/non-unicode tilde (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|\.(){},?:\[\]$\\;#]', Operator), (r'[\w-]+', Text) ], 'comment': [ (r'[^*/#]+', Comment.Multiline), (r'/\*|#\[', Comment.Multiline, '#push'), (r'\*/|#\]', Comment.Multiline, '#pop'), (r'[*/#]', Comment.Multiline) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335""" pygments.lexers.php ~~~~~~~~~~~~~~~~~~~
Lexers for PHP and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, default, \ using, this, words, do_insertions, line_refrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Other, Genericfrom pygments.util import get_bool_opt, get_list_opt, shebang_matches
__all__ = ['ZephirLexer', 'PsyshConsoleLexer', 'PhpLexer']
class ZephirLexer(RegexLexer): """ For Zephir language source code.
Zephir is a compiled high level language aimed to the creation of C-extensions for PHP. """
name = 'Zephir' url = 'http://zephir-lang.com/' aliases = ['zephir'] filenames = ['*.zep'] version_added = '2.0'
zephir_keywords = ['fetch', 'echo', 'isset', 'empty'] zephir_type = ['bit', 'bits', 'string']
flags = re.DOTALL | re.MULTILINE
tokens = { 'commentsandwhitespace': [ (r'\s+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline) ], 'slashstartsregex': [ include('commentsandwhitespace'), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gim]+\b|\B)', String.Regex, '#pop'), (r'/', Operator, '#pop'), default('#pop') ], 'badregex': [ (r'\n', Text, '#pop') ], 'root': [ (r'^(?=\s|/)', Text, 'slashstartsregex'), include('commentsandwhitespace'), (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|' r'(<<|>>>?|==?|!=?|->|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'), (r'[{(\[;,]', Punctuation, 'slashstartsregex'), (r'[})\].]', Punctuation), (r'(for|in|while|do|break|return|continue|switch|case|default|if|else|loop|' r'require|inline|throw|try|catch|finally|new|delete|typeof|instanceof|void|' r'namespace|use|extends|this|fetch|isset|unset|echo|fetch|likely|unlikely|' r'empty)\b', Keyword, 'slashstartsregex'), (r'(var|let|with|function)\b', Keyword.Declaration, 'slashstartsregex'), (r'(abstract|boolean|bool|char|class|const|double|enum|export|extends|final|' r'native|goto|implements|import|int|string|interface|long|ulong|char|uchar|' r'float|unsigned|private|protected|public|short|static|self|throws|reverse|' r'transient|volatile|readonly)\b', Keyword.Reserved), (r'(true|false|null|undefined)\b', Keyword.Constant), (r'(Array|Boolean|Date|_REQUEST|_COOKIE|_SESSION|' r'_GET|_POST|_SERVER|this|stdClass|range|count|iterator|' r'window)\b', Name.Builtin), (r'[$a-zA-Z_][\w\\]*', Name.Other), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ] }
class PsyshConsoleLexer(Lexer): """ For PsySH console output, such as:
.. sourcecode:: psysh
>>> $greeting = function($name): string { ... return "Hello, {$name}"; ... }; => Closure($name): string {#2371 …3} >>> $greeting('World') => "Hello, World" """ name = 'PsySH console session for PHP' url = 'https://psysh.org/' aliases = ['psysh'] version_added = '2.7'
def __init__(self, **options): options['startinline'] = True Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): phplexer = PhpLexer(**self.options) curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() if line.startswith('>>> ') or line.startswith('... '): insertions.append((len(curcode), [(0, Generic.Prompt, line[:4])])) curcode += line[4:] elif line.rstrip() == '...': insertions.append((len(curcode), [(0, Generic.Prompt, '...')])) curcode += line[3:] else: if curcode: yield from do_insertions( insertions, phplexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, phplexer.get_tokens_unprocessed(curcode))
class PhpLexer(RegexLexer): """ For PHP source code. For PHP embedded in HTML, use the `HtmlPhpLexer`.
Additional options accepted:
`startinline` If given and ``True`` the lexer starts highlighting with php code (i.e.: no starting ``<?php`` required). The default is ``False``. `funcnamehighlighting` If given and ``True``, highlight builtin function names (default: ``True``). `disabledmodules` If given, must be a list of module names whose function names should not be highlighted. By default all modules are highlighted except the special ``'unknown'`` module that includes functions that are known to php but are undocumented.
To get a list of allowed modules have a look into the `_php_builtins` module:
.. sourcecode:: pycon
>>> from pygments.lexers._php_builtins import MODULES >>> MODULES.keys() ['PHP Options/Info', 'Zip', 'dba', ...]
In fact the names of those modules match the module names from the php documentation. """
name = 'PHP' url = 'https://www.php.net/' aliases = ['php', 'php3', 'php4', 'php5'] filenames = ['*.php', '*.php[345]', '*.inc'] mimetypes = ['text/x-php'] version_added = ''
# Note that a backslash is included, PHP uses a backslash as a namespace # separator. _ident_inner = r'(?:[\\_a-z]|[^\x00-\x7f])(?:[\\\w]|[^\x00-\x7f])*' # But not inside strings. _ident_nons = r'(?:[_a-z]|[^\x00-\x7f])(?:\w|[^\x00-\x7f])*'
flags = re.IGNORECASE | re.DOTALL | re.MULTILINE tokens = { 'root': [ (r'<\?(php)?', Comment.Preproc, 'php'), (r'[^<]+', Other), (r'<', Other) ], 'php': [ (r'\?>', Comment.Preproc, '#pop'), (r'(<<<)([\'"]?)(' + _ident_nons + r')(\2\n.*?\n\s*)(\3)(;?)(\n)', bygroups(String, String, String.Delimiter, String, String.Delimiter, Punctuation, Text)), (r'\s+', Text), (r'#\[', Punctuation, 'attribute'), (r'#.*?\n', Comment.Single), (r'//.*?\n', Comment.Single), # put the empty comment here, it is otherwise seen as # the start of a docstring (r'/\*\*/', Comment.Multiline), (r'/\*\*.*?\*/', String.Doc), (r'/\*.*?\*/', Comment.Multiline), (r'(->|::)(\s*)(' + _ident_nons + ')', bygroups(Operator, Text, Name.Attribute)), (r'[~!%^&*+=|:.<>/@-]+', Operator), (r'\?', Operator), # don't add to the charclass above! (r'[\[\]{}();,]+', Punctuation), (r'(new)(\s+)(class)\b', bygroups(Keyword, Text, Keyword)), (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'), (r'(function)(\s*)(?=\()', bygroups(Keyword, Text)), (r'(function)(\s+)(&?)(\s*)', bygroups(Keyword, Text, Operator, Text), 'functionname'), (r'(const)(\s+)(' + _ident_inner + ')', bygroups(Keyword, Text, Name.Constant)), # source: https://www.php.net/manual/en/reserved.keywords.php (r'(and|E_PARSE|old_function|E_ERROR|or|as|E_WARNING|parent|' r'eval|PHP_OS|break|exit|case|extends|PHP_VERSION|cfunction|' r'FALSE|print|for|require|continue|foreach|require_once|' r'declare|return|default|static|do|switch|die|stdClass|' r'echo|else|TRUE|elseif|var|empty|if|xor|enddeclare|include|' r'virtual|endfor|include_once|while|endforeach|global|' r'endif|list|endswitch|new|endwhile|not|' r'array|E_ALL|NULL|final|php_user_filter|interface|' r'implements|public|private|protected|abstract|clone|try|' r'catch|throw|this|use|namespace|trait|yield( from)?|' r'finally|match|readonly)\b', Keyword), (r'(true|false|null)\b', Keyword.Constant), include('magicconstants'), (r'\$\{', Name.Variable, 'variablevariable'), (r'\$+' + _ident_inner, Name.Variable), (_ident_inner, Name.Other), (r'(\d+\.\d*|\d*\.\d+)(e[+-]?[0-9]+)?', Number.Float), (r'\d+e[+-]?[0-9]+', Number.Float), (r'0[0-7]+', Number.Oct), (r'0x[a-f0-9]+', Number.Hex), (r'\d+', Number.Integer), (r'0b[01]+', Number.Bin), (r"'([^'\\]*(?:\\.[^'\\]*)*)'", String.Single), (r'`([^`\\]*(?:\\.[^`\\]*)*)`', String.Backtick), (r'"', String.Double, 'string'), ], 'variablevariable': [ (r'\}', Name.Variable, '#pop'), include('php') ], 'magicfuncs': [ # source: http://php.net/manual/en/language.oop5.magic.php (words(( '__construct', '__destruct', '__call', '__callStatic', '__get', '__set', '__isset', '__unset', '__sleep', '__wakeup', '__toString', '__invoke', '__set_state', '__clone', '__debugInfo',), suffix=r'\b'), Name.Function.Magic), ], 'magicconstants': [ # source: https://www.php.net/manual/en/language.constants.magic.php (words(( '__LINE__', '__FILE__', '__DIR__', '__FUNCTION__', '__CLASS__', '__TRAIT__', '__METHOD__', '__NAMESPACE__', '__PROPERTY__',), suffix=r'\b'), Name.Constant), ], 'classname': [ (_ident_inner, Name.Class, '#pop') ], 'functionname': [ include('magicfuncs'), (_ident_inner, Name.Function, '#pop'), default('#pop') ], 'string': [ (r'"', String.Double, '#pop'), (r'[^{$"\\]+', String.Double), (r'\\([nrt"$\\]|[0-7]{1,3}|x[0-9a-f]{1,2})', String.Escape), (r'\$' + _ident_nons + r'(\[\S+?\]|->' + _ident_nons + ')?', String.Interpol), (r'(\{\$\{)(.*?)(\}\})', bygroups(String.Interpol, using(this, _startinline=True), String.Interpol)), (r'(\{)(\$.*?)(\})', bygroups(String.Interpol, using(this, _startinline=True), String.Interpol)), (r'(\$\{)(\S+)(\})', bygroups(String.Interpol, Name.Variable, String.Interpol)), (r'[${\\]', String.Double) ], 'attribute': [ (r'\]', Punctuation, '#pop'), (r'\(', Punctuation, 'attributeparams'), (_ident_inner, Name.Decorator), include('php') ], 'attributeparams': [ (r'\)', Punctuation, '#pop'), include('php') ], }
def __init__(self, **options): self.funcnamehighlighting = get_bool_opt( options, 'funcnamehighlighting', True) self.disabledmodules = get_list_opt( options, 'disabledmodules', ['unknown']) self.startinline = get_bool_opt(options, 'startinline', False)
# private option argument for the lexer itself if '_startinline' in options: self.startinline = options.pop('_startinline')
# collect activated functions in a set self._functions = set() if self.funcnamehighlighting: from pygments.lexers._php_builtins import MODULES for key, value in MODULES.items(): if key not in self.disabledmodules: self._functions.update(value) RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): stack = ['root'] if self.startinline: stack.append('php') for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text, stack): if token is Name.Other: if value in self._functions: yield index, Name.Builtin, value continue yield index, token, value
def analyse_text(text): if shebang_matches(text, r'php'): return True rv = 0.0 if re.search(r'<\?(?!xml)', text): rv += 0.3 return rv12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970""" pygments.lexers.pointless ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Pointless.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Error, Keyword, Name, Number, Operator, \ Punctuation, String, Text
__all__ = ['PointlessLexer']
class PointlessLexer(RegexLexer): """ For Pointless source code. """
name = 'Pointless' url = 'https://ptls.dev' aliases = ['pointless'] filenames = ['*.ptls'] version_added = '2.7'
ops = words([ "+", "-", "*", "/", "**", "%", "+=", "-=", "*=", "/=", "**=", "%=", "|>", "=", "==", "!=", "<", ">", "<=", ">=", "=>", "$", "++", ])
keywords = words([ "if", "then", "else", "where", "with", "cond", "case", "and", "or", "not", "in", "as", "for", "requires", "throw", "try", "catch", "when", "yield", "upval", ], suffix=r'\b')
tokens = { 'root': [ (r'[ \n\r]+', Text), (r'--.*$', Comment.Single), (r'"""', String, 'multiString'), (r'"', String, 'string'), (r'[\[\](){}:;,.]', Punctuation), (ops, Operator), (keywords, Keyword), (r'\d+|\d*\.\d+', Number), (r'(true|false)\b', Name.Builtin), (r'[A-Z][a-zA-Z0-9]*\b', String.Symbol), (r'output\b', Name.Variable.Magic), (r'(export|import)\b', Keyword.Namespace), (r'[a-z][a-zA-Z0-9]*\b', Name.Variable) ], 'multiString': [ (r'\\.', String.Escape), (r'"""', String, '#pop'), (r'"', String), (r'[^\\"]+', String), ], 'string': [ (r'\\.', String.Escape), (r'"', String, '#pop'), (r'\n', Error), (r'[^\\"]+', String), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293""" pygments.lexers.pony ~~~~~~~~~~~~~~~~~~~~
Lexers for Pony and related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['PonyLexer']
class PonyLexer(RegexLexer): """ For Pony source code. """
name = 'Pony' aliases = ['pony'] filenames = ['*.pony'] url = 'https://www.ponylang.io' version_added = '2.4'
_caps = r'(iso|trn|ref|val|box|tag)'
tokens = { 'root': [ (r'\n', Text), (r'[^\S\n]+', Text), (r'//.*\n', Comment.Single), (r'/\*', Comment.Multiline, 'nested_comment'), (r'"""(?:.|\n)*?"""', String.Doc), (r'"', String, 'string'), (r'\'.*\'', String.Char), (r'=>|[]{}:().~;,|&!^?[]', Punctuation), (words(( 'addressof', 'and', 'as', 'consume', 'digestof', 'is', 'isnt', 'not', 'or'), suffix=r'\b'), Operator.Word), (r'!=|==|<<|>>|[-+/*%=<>]', Operator), (words(( 'box', 'break', 'compile_error', 'compile_intrinsic', 'continue', 'do', 'else', 'elseif', 'embed', 'end', 'error', 'for', 'if', 'ifdef', 'in', 'iso', 'lambda', 'let', 'match', 'object', 'recover', 'ref', 'repeat', 'return', 'tag', 'then', 'this', 'trn', 'try', 'until', 'use', 'var', 'val', 'where', 'while', 'with', '#any', '#read', '#send', '#share'), suffix=r'\b'), Keyword), (r'(actor|class|struct|primitive|interface|trait|type)((?:\s)+)', bygroups(Keyword, Text), 'typename'), (r'(new|fun|be)((?:\s)+)', bygroups(Keyword, Text), 'methodname'), (words(( 'I8', 'U8', 'I16', 'U16', 'I32', 'U32', 'I64', 'U64', 'I128', 'U128', 'ILong', 'ULong', 'ISize', 'USize', 'F32', 'F64', 'Bool', 'Pointer', 'None', 'Any', 'Array', 'String', 'Iterator'), suffix=r'\b'), Name.Builtin.Type), (r'_?[A-Z]\w*', Name.Type), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (r'(true|false)\b', Name.Builtin), (r'_\d*', Name), (r'_?[a-z][\w\']*', Name) ], 'typename': [ (_caps + r'?((?:\s)*)(_?[A-Z]\w*)', bygroups(Keyword, Text, Name.Class), '#pop') ], 'methodname': [ (_caps + r'?((?:\s)*)(_?[a-z]\w*)', bygroups(Keyword, Text, Name.Function), '#pop') ], 'nested_comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'string': [ (r'"', String, '#pop'), (r'\\"', String), (r'[^\\"]+', String) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303""" pygments.lexers.praat ~~~~~~~~~~~~~~~~~~~~~
Lexer for Praat
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, bygroups, includefrom pygments.token import Name, Text, Comment, Keyword, String, Punctuation, \ Number, Operator, Whitespace
__all__ = ['PraatLexer']
class PraatLexer(RegexLexer): """ For Praat scripts. """
name = 'Praat' url = 'http://www.praat.org' aliases = ['praat'] filenames = ['*.praat', '*.proc', '*.psc'] version_added = '2.1'
keywords = ( 'if', 'then', 'else', 'elsif', 'elif', 'endif', 'fi', 'for', 'from', 'to', 'endfor', 'endproc', 'while', 'endwhile', 'repeat', 'until', 'select', 'plus', 'minus', 'demo', 'assert', 'stopwatch', 'nocheck', 'nowarn', 'noprogress', 'editor', 'endeditor', 'clearinfo', )
functions_string = ( 'backslashTrigraphsToUnicode', 'chooseDirectory', 'chooseReadFile', 'chooseWriteFile', 'date', 'demoKey', 'do', 'environment', 'extractLine', 'extractWord', 'fixed', 'info', 'left', 'mid', 'percent', 'readFile', 'replace', 'replace_regex', 'right', 'selected', 'string', 'unicodeToBackslashTrigraphs', )
functions_numeric = ( 'abs', 'appendFile', 'appendFileLine', 'appendInfo', 'appendInfoLine', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'barkToHertz', 'beginPause', 'beginSendPraat', 'besselI', 'besselK', 'beta', 'beta2', 'binomialP', 'binomialQ', 'boolean', 'ceiling', 'chiSquareP', 'chiSquareQ', 'choice', 'comment', 'cos', 'cosh', 'createDirectory', 'deleteFile', 'demoClicked', 'demoClickedIn', 'demoCommandKeyPressed', 'demoExtraControlKeyPressed', 'demoInput', 'demoKeyPressed', 'demoOptionKeyPressed', 'demoShiftKeyPressed', 'demoShow', 'demoWaitForInput', 'demoWindowTitle', 'demoX', 'demoY', 'differenceLimensToPhon', 'do', 'editor', 'endPause', 'endSendPraat', 'endsWith', 'erb', 'erbToHertz', 'erf', 'erfc', 'exitScript', 'exp', 'extractNumber', 'fileReadable', 'fisherP', 'fisherQ', 'floor', 'gaussP', 'gaussQ', 'hertzToBark', 'hertzToErb', 'hertzToMel', 'hertzToSemitones', 'imax', 'imin', 'incompleteBeta', 'incompleteGammaP', 'index', 'index_regex', 'integer', 'invBinomialP', 'invBinomialQ', 'invChiSquareQ', 'invFisherQ', 'invGaussQ', 'invSigmoid', 'invStudentQ', 'length', 'ln', 'lnBeta', 'lnGamma', 'log10', 'log2', 'max', 'melToHertz', 'min', 'minusObject', 'natural', 'number', 'numberOfColumns', 'numberOfRows', 'numberOfSelected', 'objectsAreIdentical', 'option', 'optionMenu', 'pauseScript', 'phonToDifferenceLimens', 'plusObject', 'positive', 'randomBinomial', 'randomGauss', 'randomInteger', 'randomPoisson', 'randomUniform', 'real', 'readFile', 'removeObject', 'rindex', 'rindex_regex', 'round', 'runScript', 'runSystem', 'runSystem_nocheck', 'selectObject', 'selected', 'semitonesToHertz', 'sentence', 'sentencetext', 'sigmoid', 'sin', 'sinc', 'sincpi', 'sinh', 'soundPressureToPhon', 'sqrt', 'startsWith', 'studentP', 'studentQ', 'tan', 'tanh', 'text', 'variableExists', 'word', 'writeFile', 'writeFileLine', 'writeInfo', 'writeInfoLine', )
functions_array = ( 'linear', 'randomGauss', 'randomInteger', 'randomUniform', 'zero', )
objects = ( 'Activation', 'AffineTransform', 'AmplitudeTier', 'Art', 'Artword', 'Autosegment', 'BarkFilter', 'BarkSpectrogram', 'CCA', 'Categories', 'Cepstrogram', 'Cepstrum', 'Cepstrumc', 'ChebyshevSeries', 'ClassificationTable', 'Cochleagram', 'Collection', 'ComplexSpectrogram', 'Configuration', 'Confusion', 'ContingencyTable', 'Corpus', 'Correlation', 'Covariance', 'CrossCorrelationTable', 'CrossCorrelationTables', 'DTW', 'DataModeler', 'Diagonalizer', 'Discriminant', 'Dissimilarity', 'Distance', 'Distributions', 'DurationTier', 'EEG', 'ERP', 'ERPTier', 'EditCostsTable', 'EditDistanceTable', 'Eigen', 'Excitation', 'Excitations', 'ExperimentMFC', 'FFNet', 'FeatureWeights', 'FileInMemory', 'FilesInMemory', 'Formant', 'FormantFilter', 'FormantGrid', 'FormantModeler', 'FormantPoint', 'FormantTier', 'GaussianMixture', 'HMM', 'HMM_Observation', 'HMM_ObservationSequence', 'HMM_State', 'HMM_StateSequence', 'Harmonicity', 'ISpline', 'Index', 'Intensity', 'IntensityTier', 'IntervalTier', 'KNN', 'KlattGrid', 'KlattTable', 'LFCC', 'LPC', 'Label', 'LegendreSeries', 'LinearRegression', 'LogisticRegression', 'LongSound', 'Ltas', 'MFCC', 'MSpline', 'ManPages', 'Manipulation', 'Matrix', 'MelFilter', 'MelSpectrogram', 'MixingMatrix', 'Movie', 'Network', 'Object', 'OTGrammar', 'OTHistory', 'OTMulti', 'PCA', 'PairDistribution', 'ParamCurve', 'Pattern', 'Permutation', 'Photo', 'Pitch', 'PitchModeler', 'PitchTier', 'PointProcess', 'Polygon', 'Polynomial', 'PowerCepstrogram', 'PowerCepstrum', 'Procrustes', 'RealPoint', 'RealTier', 'ResultsMFC', 'Roots', 'SPINET', 'SSCP', 'SVD', 'Salience', 'ScalarProduct', 'Similarity', 'SimpleString', 'SortedSetOfString', 'Sound', 'Speaker', 'Spectrogram', 'Spectrum', 'SpectrumTier', 'SpeechSynthesizer', 'SpellingChecker', 'Strings', 'StringsIndex', 'Table', 'TableOfReal', 'TextGrid', 'TextInterval', 'TextPoint', 'TextTier', 'Tier', 'Transition', 'VocalTract', 'VocalTractTier', 'Weight', 'WordList', )
variables_numeric = ( 'macintosh', 'windows', 'unix', 'praatVersion', 'pi', 'e', 'undefined', )
variables_string = ( 'praatVersion', 'tab', 'shellDirectory', 'homeDirectory', 'preferencesDirectory', 'newline', 'temporaryDirectory', 'defaultDirectory', )
object_attributes = ( 'ncol', 'nrow', 'xmin', 'ymin', 'xmax', 'ymax', 'nx', 'ny', 'dx', 'dy', )
tokens = { 'root': [ (r'(\s+)(#.*?$)', bygroups(Whitespace, Comment.Single)), (r'^#.*?$', Comment.Single), (r';[^\n]*', Comment.Single), (r'\s+', Whitespace),
(r'\bprocedure\b', Keyword, 'procedure_definition'), (r'\bcall\b', Keyword, 'procedure_call'), (r'@', Name.Function, 'procedure_call'),
include('function_call'),
(words(keywords, suffix=r'\b'), Keyword),
(r'(\bform\b)(\s+)([^\n]+)', bygroups(Keyword, Whitespace, String), 'old_form'),
(r'(print(?:line|tab)?|echo|exit|asserterror|pause|send(?:praat|socket)|' r'include|execute|system(?:_nocheck)?)(\s+)', bygroups(Keyword, Whitespace), 'string_unquoted'),
(r'(goto|label)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Label)),
include('variable_name'), include('number'),
(r'"', String, 'string'),
(words((objects), suffix=r'(?=\s+\S+\n)'), Name.Class, 'string_unquoted'),
(r'\b[A-Z]', Keyword, 'command'), (r'(\.{3}|[)(,])', Punctuation), ], 'command': [ (r'( ?[\w()-]+ ?)', Keyword),
include('string_interpolated'),
(r'\.{3}', Keyword, ('#pop', 'old_arguments')), (r':', Keyword, ('#pop', 'comma_list')), (r'\s', Whitespace, '#pop'), ], 'procedure_call': [ (r'\s+', Whitespace), (r'([\w.]+)(?:(:)|(?:(\s*)(\()))', bygroups(Name.Function, Punctuation, Text.Whitespace, Punctuation), '#pop'), (r'([\w.]+)', Name.Function, ('#pop', 'old_arguments')), ], 'procedure_definition': [ (r'\s', Whitespace), (r'([\w.]+)(\s*?[(:])', bygroups(Name.Function, Whitespace), '#pop'), (r'([\w.]+)([^\n]*)', bygroups(Name.Function, Text), '#pop'), ], 'function_call': [ (words(functions_string, suffix=r'\$(?=\s*[:(])'), Name.Function, 'function'), (words(functions_array, suffix=r'#(?=\s*[:(])'), Name.Function, 'function'), (words(functions_numeric, suffix=r'(?=\s*[:(])'), Name.Function, 'function'), ], 'function': [ (r'\s+', Whitespace), (r':', Punctuation, ('#pop', 'comma_list')), (r'\s*\(', Punctuation, ('#pop', 'comma_list')), ], 'comma_list': [ (r'(\s*\n\s*)(\.{3})', bygroups(Whitespace, Punctuation)),
(r'(\s*)(?:([)\]])|(\n))', bygroups( Whitespace, Punctuation, Whitespace), '#pop'),
(r'\s+', Whitespace), (r'"', String, 'string'), (r'\b(if|then|else|fi|endif)\b', Keyword),
include('function_call'), include('variable_name'), include('operator'), include('number'),
(r'[()]', Text), (r',', Punctuation), ], 'old_arguments': [ (r'\n', Whitespace, '#pop'),
include('variable_name'), include('operator'), include('number'),
(r'"', String, 'string'), (r'[^\n]', Text), ], 'number': [ (r'\n', Whitespace, '#pop'), (r'\b\d+(\.\d*)?([eE][-+]?\d+)?%?', Number), ], 'object_reference': [ include('string_interpolated'), (r'([a-z][a-zA-Z0-9_]*|\d+)', Name.Builtin),
(words(object_attributes, prefix=r'\.'), Name.Builtin, '#pop'),
(r'\$', Name.Builtin), (r'\[', Text, '#pop'), ], 'variable_name': [ include('operator'), include('number'),
(words(variables_string, suffix=r'\$'), Name.Variable.Global), (words(variables_numeric, suffix=r'(?=[^a-zA-Z0-9_."\'$#\[:(]|\s|^|$)'), Name.Variable.Global),
(words(objects, prefix=r'\b', suffix=r"(_)"), bygroups(Name.Builtin, Name.Builtin), 'object_reference'),
(r'\.?_?[a-z][\w.]*(\$|#)?', Text), (r'[\[\]]', Punctuation, 'comma_list'),
include('string_interpolated'), ], 'operator': [ (r'([+\/*<>=!-]=?|[&*|][&*|]?|\^|<>)', Operator), (r'(?<![\w.])(and|or|not|div|mod)(?![\w.])', Operator.Word), ], 'string_interpolated': [ (r'\'[_a-z][^\[\]\'":]*(\[([\d,]+|"[\w,]+")\])?(:[0-9]+)?\'', String.Interpol), ], 'string_unquoted': [ (r'(\n\s*)(\.{3})', bygroups(Whitespace, Punctuation)),
(r'\n', Whitespace, '#pop'), (r'\s', Whitespace),
include('string_interpolated'),
(r"'", String), (r"[^'\n]+", String), ], 'string': [ (r'(\n\s*)(\.{3})', bygroups(Whitespace, Punctuation)),
(r'"', String, '#pop'),
include('string_interpolated'),
(r"'", String), (r'[^\'"\n]+', String), ], 'old_form': [ (r'(\s+)(#.*?$)', bygroups(Whitespace, Comment.Single)), (r'\s+', Whitespace),
(r'(optionmenu|choice)([ \t]+)(\S+)(:)([ \t]+)', bygroups(Keyword, Whitespace, Text, Punctuation, Whitespace), 'number'),
(r'(option|button)([ \t]+)', bygroups(Keyword, Whitespace), 'string_unquoted'),
(r'(sentence|text)([ \t]+)(\S+)', bygroups(Keyword, Whitespace, String), 'string_unquoted'),
(r'(word)([ \t]+)(\S+)([ \t]*)(\S+)?(?:([ \t]+)(.*))?', bygroups(Keyword, Whitespace, Text, Whitespace, Text, Whitespace, Text)),
(r'(boolean)(\s+\S+\s*)(0|1|"?(?:yes|no)"?)', bygroups(Keyword, Whitespace, Name.Variable)),
# Ideally processing of the number would happen in the 'number' # but that doesn't seem to work (r'(real|natural|positive|integer)([ \t]+\S+[ \t]*)([+-]?)(\d+(?:\.\d*)?' r'(?:[eE][-+]?\d+)?%?)', bygroups(Keyword, Whitespace, Operator, Number)),
(r'(comment)(\s+)', bygroups(Keyword, Whitespace), 'string_unquoted'),
(r'\bendform\b', Keyword, '#pop'), ] }1234567891011121314151617181920212223242526272829303132333435363738394041""" pygments.lexers.procfile ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Procfile file format.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Name, Number, String, Text, Punctuation
__all__ = ["ProcfileLexer"]
class ProcfileLexer(RegexLexer): """ Lexer for Procfile file format.
The format is used to run processes on Heroku or is used by Foreman or Honcho tools. """ name = 'Procfile' url = 'https://devcenter.heroku.com/articles/procfile#procfile-format' aliases = ['procfile'] filenames = ['Procfile'] version_added = '2.10'
tokens = { 'root': [ (r'^([a-z]+)(:)', bygroups(Name.Label, Punctuation)), (r'\s+', Text.Whitespace), (r'"[^"]*"', String), (r"'[^']*'", String), (r'[0-9]+', Number.Integer), (r'\$[a-zA-Z_][\w]*', Name.Variable), (r'(\w+)(=)(\w+)', bygroups(Name.Variable, Punctuation, String)), (r'([\w\-\./]+)', Text), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318""" pygments.lexers.prolog ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Prolog and Prolog-like languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['PrologLexer', 'LogtalkLexer']
class PrologLexer(RegexLexer): """ Lexer for Prolog files. """ name = 'Prolog' aliases = ['prolog'] filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl'] mimetypes = ['text/x-prolog'] url = 'https://en.wikipedia.org/wiki/Prolog' version_added = ''
tokens = { 'root': [ (r'/\*', Comment.Multiline, 'nested-comment'), (r'%.*', Comment.Single), # character literal (r'0\'.', String.Char), (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), # literal with prepended base (r'\d\d?\'[a-zA-Z0-9]+', Number.Integer), (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), (r'\d+', Number.Integer), (r'[\[\](){}|.,;!]', Punctuation), (r':-|-->', Punctuation), (r'"(?:\\x[0-9a-fA-F]+\\|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|' r'\\[0-7]+\\|\\["\\abcefnrstv]|[^\\"])*"', String.Double), (r"'(?:''|[^'])*'", String.Atom), # quoted atom # Needs to not be followed by an atom. # (r'=(?=\s|[a-zA-Z\[])', Operator), (r'is\b', Operator), (r'(<|>|=<|>=|==|=:=|=|/|//|\*|\+|-)(?=\s|[a-zA-Z0-9\[])', Operator), (r'(mod|div|not)\b', Operator), (r'_', Keyword), # The don't-care variable (r'([a-z]+)(:)', bygroups(Name.Namespace, Punctuation)), (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' r'(\s*)(:-|-->)', bygroups(Name.Function, Text, Operator)), # function defn (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' r'(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*', String.Atom), # atom, characters # This one includes ! (r'[#&*+\-./:<=>?@\\^~\u00a1-\u00bf\u2010-\u303f]+', String.Atom), # atom, graphics (r'[A-Z_]\w*', Name.Variable), (r'\s+|[\u2000-\u200f\ufff0-\ufffe\uffef]', Text), ], 'nested-comment': [ (r'\*/', Comment.Multiline, '#pop'), (r'/\*', Comment.Multiline, '#push'), (r'[^*/]+', Comment.Multiline), (r'[*/]', Comment.Multiline), ], }
def analyse_text(text): """Competes with IDL and Visual Prolog on *.pro""" if ':-' in text: # Visual Prolog also uses :- return 0.5 else: return 0
class LogtalkLexer(RegexLexer): """ For Logtalk source code. """
name = 'Logtalk' url = 'http://logtalk.org/' aliases = ['logtalk'] filenames = ['*.lgt', '*.logtalk'] mimetypes = ['text/x-logtalk'] version_added = '0.10'
tokens = { 'root': [ # Directives (r'^\s*:-\s', Punctuation, 'directive'), # Comments (r'%.*?\n', Comment), (r'/\*(.|\n)*?\*/', Comment), # Whitespace (r'\n', Text), (r'\s+', Text), # Numbers (r"0'[\\]?.", Number), (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number), # Variables (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable), # Event handlers (r'(after|before)(?=[(])', Keyword), # Message forwarding handler (r'forward(?=[(])', Keyword), # Execution-context methods (r'(context|parameter|this|se(lf|nder))(?=[(])', Keyword), # Reflection (r'(current_predicate|predicate_property)(?=[(])', Keyword), # DCGs and term expansion (r'(expand_(goal|term)|(goal|term)_expansion|phrase)(?=[(])', Keyword), # Entity (r'(abolish|c(reate|urrent))_(object|protocol|category)(?=[(])', Keyword), (r'(object|protocol|category)_property(?=[(])', Keyword), # Entity relations (r'co(mplements_object|nforms_to_protocol)(?=[(])', Keyword), (r'extends_(object|protocol|category)(?=[(])', Keyword), (r'imp(lements_protocol|orts_category)(?=[(])', Keyword), (r'(instantiat|specializ)es_class(?=[(])', Keyword), # Events (r'(current_event|(abolish|define)_events)(?=[(])', Keyword), # Flags (r'(create|current|set)_logtalk_flag(?=[(])', Keyword), # Compiling, loading, and library paths (r'logtalk_(compile|l(ibrary_path|oad|oad_context)|make(_target_action)?)(?=[(])', Keyword), (r'\blogtalk_make\b', Keyword), # Database (r'(clause|retract(all)?)(?=[(])', Keyword), (r'a(bolish|ssert(a|z))(?=[(])', Keyword), # Control constructs (r'(ca(ll|tch)|throw)(?=[(])', Keyword), (r'(fa(il|lse)|true|(instantiation|system)_error)\b', Keyword), (r'(uninstantiation|type|domain|existence|permission|representation|evaluation|resource|syntax)_error(?=[(])', Keyword), # All solutions (r'((bag|set)of|f(ind|or)all)(?=[(])', Keyword), # Multi-threading predicates (r'threaded(_(ca(ll|ncel)|once|ignore|exit|peek|wait|notify))?(?=[(])', Keyword), # Engine predicates (r'threaded_engine(_(create|destroy|self|next|next_reified|yield|post|fetch))?(?=[(])', Keyword), # Term unification (r'(subsumes_term|unify_with_occurs_check)(?=[(])', Keyword), # Term creation and decomposition (r'(functor|arg|copy_term|numbervars|term_variables)(?=[(])', Keyword), # Evaluable functors (r'(div|rem|m(ax|in|od)|abs|sign)(?=[(])', Keyword), (r'float(_(integer|fractional)_part)?(?=[(])', Keyword), (r'(floor|t(an|runcate)|round|ceiling)(?=[(])', Keyword), # Other arithmetic functors (r'(cos|a(cos|sin|tan|tan2)|exp|log|s(in|qrt)|xor)(?=[(])', Keyword), # Term testing (r'(var|atom(ic)?|integer|float|c(allable|ompound)|n(onvar|umber)|ground|acyclic_term)(?=[(])', Keyword), # Term comparison (r'compare(?=[(])', Keyword), # Stream selection and control (r'(curren|se)t_(in|out)put(?=[(])', Keyword), (r'(open|close)(?=[(])', Keyword), (r'flush_output(?=[(])', Keyword), (r'(at_end_of_stream|flush_output)\b', Keyword), (r'(stream_property|at_end_of_stream|set_stream_position)(?=[(])', Keyword), # Character and byte input/output (r'(nl|(get|peek|put)_(byte|c(har|ode)))(?=[(])', Keyword), (r'\bnl\b', Keyword), # Term input/output (r'read(_term)?(?=[(])', Keyword), (r'write(q|_(canonical|term))?(?=[(])', Keyword), (r'(current_)?op(?=[(])', Keyword), (r'(current_)?char_conversion(?=[(])', Keyword), # Atomic term processing (r'atom_(length|c(hars|o(ncat|des)))(?=[(])', Keyword), (r'(char_code|sub_atom)(?=[(])', Keyword), (r'number_c(har|ode)s(?=[(])', Keyword), # Implementation defined hooks functions (r'(se|curren)t_prolog_flag(?=[(])', Keyword), (r'\bhalt\b', Keyword), (r'halt(?=[(])', Keyword), # Message sending operators (r'(::|:|\^\^)', Operator), # External call (r'[{}]', Keyword), # Logic and control (r'(ignore|once)(?=[(])', Keyword), (r'\brepeat\b', Keyword), # Sorting (r'(key)?sort(?=[(])', Keyword), # Bitwise functors (r'(>>|<<|/\\|\\\\|\\)', Operator), # Predicate aliases (r'\bas\b', Operator), # Arithmetic evaluation (r'\bis\b', Keyword), # Arithmetic comparison (r'(=:=|=\\=|<|=<|>=|>)', Operator), # Term creation and decomposition (r'=\.\.', Operator), # Term unification (r'(=|\\=)', Operator), # Term comparison (r'(==|\\==|@=<|@<|@>=|@>)', Operator), # Evaluable functors (r'(//|[-+*/])', Operator), (r'\b(e|pi|div|mod|rem)\b', Operator), # Other arithmetic functors (r'\b\*\*\b', Operator), # DCG rules (r'-->', Operator), # Control constructs (r'([!;]|->)', Operator), # Logic and control (r'\\+', Operator), # Mode operators (r'[?@]', Operator), # Existential quantifier (r'\^', Operator), # Punctuation (r'[()\[\],.|]', Text), # Atoms (r"[a-z][a-zA-Z0-9_]*", Text), (r"'", String, 'quoted_atom'), # Double-quoted terms (r'"', String, 'double_quoted_term'), ],
'quoted_atom': [ (r"''", String), (r"'", String, '#pop'), (r'\\([\\abfnrtv"\']|(x[a-fA-F0-9]+|[0-7]+)\\)', String.Escape), (r"[^\\'\n]+", String), (r'\\', String), ],
'double_quoted_term': [ (r'""', String), (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|(x[a-fA-F0-9]+|[0-7]+)\\)', String.Escape), (r'[^\\"\n]+', String), (r'\\', String), ],
'directive': [ # Conditional compilation directives (r'(el)?if(?=[(])', Keyword, 'root'), (r'(e(lse|ndif))(?=[.])', Keyword, 'root'), # Entity directives (r'(category|object|protocol)(?=[(])', Keyword, 'entityrelations'), (r'(end_(category|object|protocol))(?=[.])', Keyword, 'root'), # Predicate scope directives (r'(public|protected|private)(?=[(])', Keyword, 'root'), # Other directives (r'e(n(coding|sure_loaded)|xport)(?=[(])', Keyword, 'root'), (r'in(clude|itialization|fo)(?=[(])', Keyword, 'root'), (r'(built_in|dynamic|synchronized|threaded)(?=[.])', Keyword, 'root'), (r'(alias|d(ynamic|iscontiguous)|m(eta_(non_terminal|predicate)|ode|ultifile)|s(et_(logtalk|prolog)_flag|ynchronized))(?=[(])', Keyword, 'root'), (r'op(?=[(])', Keyword, 'root'), (r'(c(alls|oinductive)|module|reexport|use(s|_module))(?=[(])', Keyword, 'root'), (r'[a-z][a-zA-Z0-9_]*(?=[(])', Text, 'root'), (r'[a-z][a-zA-Z0-9_]*(?=[.])', Text, 'root'), ],
'entityrelations': [ (r'(complements|extends|i(nstantiates|mp(lements|orts))|specializes)(?=[(])', Keyword), # Numbers (r"0'[\\]?.", Number), (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number), # Variables (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable), # Atoms (r"[a-z][a-zA-Z0-9_]*", Text), (r"'", String, 'quoted_atom'), # Double-quoted terms (r'"', String, 'double_quoted_term'), # End of entity-opening directive (r'([)]\.)', Text, 'root'), # Scope operator (r'(::)', Operator), # Punctuation (r'[()\[\],.|]', Text), # Comments (r'%.*?\n', Comment), (r'/\*(.|\n)*?\*/', Comment), # Whitespace (r'\n', Text), (r'\s+', Text), ] }
def analyse_text(text): if ':- object(' in text: return 1.0 elif ':- protocol(' in text: return 1.0 elif ':- category(' in text: return 1.0 elif re.search(r'^:-\s[a-z]', text, re.M): return 0.9 else: return 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176""" pygments.lexers.promql ~~~~~~~~~~~~~~~~~~~~~~
Lexer for Prometheus Query Language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, default, wordsfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Whitespace
__all__ = ["PromQLLexer"]
class PromQLLexer(RegexLexer): """ For PromQL queries.
For details about the grammar see: https://github.com/prometheus/prometheus/tree/master/promql/parser
.. versionadded: 2.7 """
name = "PromQL" url = 'https://prometheus.io/docs/prometheus/latest/querying/basics/' aliases = ["promql"] filenames = ["*.promql"] version_added = ''
base_keywords = ( words( ( "bool", "by", "group_left", "group_right", "ignoring", "offset", "on", "without", ), suffix=r"\b", ), Keyword, )
aggregator_keywords = ( words( ( "sum", "min", "max", "avg", "group", "stddev", "stdvar", "count", "count_values", "bottomk", "topk", "quantile", ), suffix=r"\b", ), Keyword, )
function_keywords = ( words( ( "abs", "absent", "absent_over_time", "avg_over_time", "ceil", "changes", "clamp_max", "clamp_min", "count_over_time", "day_of_month", "day_of_week", "days_in_month", "delta", "deriv", "exp", "floor", "histogram_quantile", "holt_winters", "hour", "idelta", "increase", "irate", "label_join", "label_replace", "ln", "log10", "log2", "max_over_time", "min_over_time", "minute", "month", "predict_linear", "quantile_over_time", "rate", "resets", "round", "scalar", "sort", "sort_desc", "sqrt", "stddev_over_time", "stdvar_over_time", "sum_over_time", "time", "timestamp", "vector", "year", ), suffix=r"\b", ), Keyword.Reserved, )
tokens = { "root": [ (r"\n", Whitespace), (r"\s+", Whitespace), (r",", Punctuation), # Keywords base_keywords, aggregator_keywords, function_keywords, # Offsets (r"[1-9][0-9]*[smhdwy]", String), # Numbers (r"-?[0-9]+\.[0-9]+", Number.Float), (r"-?[0-9]+", Number.Integer), # Comments (r"#.*?$", Comment.Single), # Operators (r"(\+|\-|\*|\/|\%|\^)", Operator), (r"==|!=|>=|<=|<|>", Operator), (r"and|or|unless", Operator.Word), # Metrics (r"[_a-zA-Z][a-zA-Z0-9_]+", Name.Variable), # Params (r'(["\'])(.*?)(["\'])', bygroups(Punctuation, String, Punctuation)), # Other states (r"\(", Operator, "function"), (r"\)", Operator), (r"\{", Punctuation, "labels"), (r"\[", Punctuation, "range"), ], "labels": [ (r"\}", Punctuation, "#pop"), (r"\n", Whitespace), (r"\s+", Whitespace), (r",", Punctuation), (r'([_a-zA-Z][a-zA-Z0-9_]*?)(\s*?)(=~|!=|=|!~)(\s*?)("|\')(.*?)("|\')', bygroups(Name.Label, Whitespace, Operator, Whitespace, Punctuation, String, Punctuation)), ], "range": [ (r"\]", Punctuation, "#pop"), (r"[1-9][0-9]*[smhdwy]", String), ], "function": [ (r"\)", Operator, "#pop"), (r"\(", Operator, "#push"), default("#pop"), ], }.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/console.pyAdded+70
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/javascript.pyAdded+1591
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/jsonnet.pyAdded+169
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/jsx.pyAdded+100
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/julia.pyAdded+294
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/jvm.pyAdded+1807
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/kuin.pyAdded+332
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/kusto.pyAdded+93
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/ldap.pyAdded+155
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/lean.pyAdded+241
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/lilypond.pyAdded+225
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/lisp.pyAdded
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/macaulay2.pyAdded+1847
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/make.pyAdded+212
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/maple.pyAdded+291
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/markup.pyAdded+1659
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/math.pyAdded+21
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/matlab.pyAdded
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/maxima.pyAdded+84
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/meson.pyAdded+139
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mime.pyAdded+210
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/minecraft.pyAdded+392
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mips.pyAdded+130
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/ml.pyAdded+958
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/modeling.pyAdded+368
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/modula2.pyAdded+1579
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mojo.pyAdded+707
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/monte.pyAdded+203
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/mosel.pyAdded+447
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/ncl.pyAdded+894
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/nimrod.pyAdded+199
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/nit.pyAdded+63
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/nix.pyAdded+144
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/numbair.pyAdded+63
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/objective.pyAdded+513
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/openscad.pyAdded+96
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/other.pyAdded+41
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/parasail.pyAdded+78
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/parsers.pyAdded+798
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pascal.pyAdded+644
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pddl.pyAdded+82
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/perl.pyAdded+733
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/phix.pyAdded+363
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/php.pyAdded+335
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pointless.pyAdded+70
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/pony.pyAdded+93
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/praat.pyAdded+303
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/procfile.pyAdded+41
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/prolog.pyAdded+318
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/promql.pyAdded+176