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/pip/http-v2/c/d/5/d/e/cd5de44b899cbe1869765c21b55cffc53c0c0ffa9d3c6f1fd40a42a2.bodyAdded+3
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/codeql.pyAdded+80
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/csound.pyAdded+466
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/css.pyAdded+632
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dalvik.pyAdded+126
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/data.pyAdded+763
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dax.pyAdded+135
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/devicetree.pyAdded+120
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/diff.pyAdded+169
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dns.pyAdded+109
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dotnet.pyAdded+873
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dsls.pyAdded+970
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dylan.pyAdded+279
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/ecl.pyAdded+144
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/eiffel.pyAdded+68
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/elm.pyAdded+123
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/elpi.pyAdded+201
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/email.pyAdded+132
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/erlang.pyAdded+526
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/esoteric.pyAdded+300
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/ezhil.pyAdded+76
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/factor.pyAdded+363
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/fantom.pyAdded+251
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/felix.pyAdded+275
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/fift.pyAdded+68
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/floscript.pyAdded+81
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/forth.pyAdded+178
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/fortran.pyAdded+212
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/foxpro.pyAdded+427
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/freefem.pyAdded+893
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/func.pyAdded+110
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/functional.pyAdded+21
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/futhark.pyAdded+105
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gcodelexer.pyAdded+35
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gdscript.pyAdded+189
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gleam.pyAdded+74
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/go.pyAdded+97
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/grammar_notation.pyAdded+262
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graph.pyAdded+108
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graphics.pyAdded+794
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graphql.pyAdded+176
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graphviz.pyAdded+58
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gsql.pyAdded+103
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/hare.pyAdded+73
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/haskell.pyAdded+867
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/haxe.pyAdded+941
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/hdl.pyAdded+466
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/hexdump.pyAdded+102
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/html.pyAdded+670
- .cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/idl.pyAdded+284
123version https://git-lfs.github.com/spec/v1oid sha256:21b77a8f111192b2cc42bc7d485cd77b82d824e95168bcbcd8a41a6cc8db6471size 2686651234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980""" pygments.lexers.codeql ~~~~~~~~~~~~~~~~~~~~~~
Lexer for CodeQL query language.
The grammar is originating from: https://github.com/github/vscode-codeql/blob/main/syntaxes/README.md
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
__all__ = ['CodeQLLexer']
import re
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
class CodeQLLexer(RegexLexer): name = 'CodeQL' aliases = ['codeql', 'ql'] filenames = ['*.ql', '*.qll'] mimetypes = [] url = 'https://github.com/github/codeql' version_added = '2.19'
flags = re.MULTILINE | re.UNICODE
tokens = { 'root': [ # Whitespace and comments (r'\s+', Whitespace), (r'//.*?\n', Comment.Single), (r'/\*', Comment.Multiline, 'multiline-comments'),
# Keywords (words(( 'module', 'import', 'class', 'extends', 'implements', 'predicate', 'select', 'where', 'from', 'as', 'and', 'or', 'not', 'in', 'if', 'then', 'else', 'exists', 'forall', 'instanceof', 'private', 'predicate', 'abstract', 'cached', 'external', 'final', 'library', 'override', 'query' ), suffix=r'\b'), Keyword.Builtin),
# Special Keywords (words(('this'), # class related keywords prefix=r'\b', suffix=r'\b\??:?'), Name.Builtin.Pseudo),
# Types (words(( 'boolean', 'date', 'float', 'int', 'string' ), suffix=r'\b'), Keyword.Type),
# Literals (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r'[0-9]+\.[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), # Operators (r'<=|>=|<|>|=|!=|\+|-|\*|/', Operator),
# Punctuation (r'[.,;:\[\]{}()]+', Punctuation),
# Identifiers (r'@[a-zA-Z_]\w*', Name.Variable), # Variables with @ prefix (r'[A-Z][a-zA-Z0-9_]*', Name.Class), # Types and classes (r'[a-z][a-zA-Z0-9_]*', Name.Variable), # Variables and predicates ], 'multiline-comments': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ],
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466""" pygments.lexers.csound ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Csound languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroups, default, include, using, wordsfrom pygments.token import Comment, Error, Keyword, Name, Number, Operator, Punctuation, \ String, Text, Whitespacefrom pygments.lexers._csound_builtins import OPCODES, DEPRECATED_OPCODES, REMOVED_OPCODESfrom pygments.lexers.html import HtmlLexerfrom pygments.lexers.python import PythonLexerfrom pygments.lexers.scripting import LuaLexer
__all__ = ['CsoundScoreLexer', 'CsoundOrchestraLexer', 'CsoundDocumentLexer']
newline = (r'((?:(?:;|//).*)*)(\n)', bygroups(Comment.Single, Text))
class CsoundLexer(RegexLexer): url = 'https://csound.com/'
tokens = { 'whitespace': [ (r'[ \t]+', Whitespace), (r'/[*](?:.|\n)*?[*]/', Comment.Multiline), (r'(?:;|//).*$', Comment.Single), (r'(\\)(\n)', bygroups(Text, Whitespace)) ],
'preprocessor directives': [ (r'#(?:e(?:nd(?:if)?|lse)\b|##)|@@?[ \t]*\d+', Comment.Preproc), (r'#includestr', Comment.Preproc, 'includestr directive'), (r'#include', Comment.Preproc, 'include directive'), (r'#[ \t]*define', Comment.Preproc, 'define directive'), (r'#(?:ifn?def|undef)\b', Comment.Preproc, 'macro directive') ],
'include directive': [ include('whitespace'), (r'([^ \t]).*?\1', String, '#pop') ], 'includestr directive': [ include('whitespace'), (r'"', String, ('#pop', 'quoted string')) ],
'define directive': [ (r'\n', Whitespace), include('whitespace'), (r'([A-Z_a-z]\w*)(\()', bygroups(Comment.Preproc, Punctuation), ('#pop', 'macro parameter name list')), (r'[A-Z_a-z]\w*', Comment.Preproc, ('#pop', 'before macro body')) ], 'macro parameter name list': [ include('whitespace'), (r'[A-Z_a-z]\w*', Comment.Preproc), (r"['#]", Punctuation), (r'\)', Punctuation, ('#pop', 'before macro body')) ], 'before macro body': [ (r'\n', Whitespace), include('whitespace'), (r'#', Punctuation, ('#pop', 'macro body')) ], 'macro body': [ (r'(?:\\(?!#)|[^#\\]|\n)+', Comment.Preproc), (r'\\#', Comment.Preproc), (r'(?<!\\)#', Punctuation, '#pop') ],
'macro directive': [ include('whitespace'), (r'[A-Z_a-z]\w*', Comment.Preproc, '#pop') ],
'macro uses': [ (r'(\$[A-Z_a-z]\w*\.?)(\()', bygroups(Comment.Preproc, Punctuation), 'macro parameter value list'), (r'\$[A-Z_a-z]\w*(?:\.|\b)', Comment.Preproc) ], 'macro parameter value list': [ (r'(?:[^\'#"{()]|\{(?!\{))+', Comment.Preproc), (r"['#]", Punctuation), (r'"', String, 'macro parameter value quoted string'), (r'\{\{', String, 'macro parameter value braced string'), (r'\(', Comment.Preproc, 'macro parameter value parenthetical'), (r'\)', Punctuation, '#pop') ], 'macro parameter value quoted string': [ (r"\\[#'()]", Comment.Preproc), (r"[#'()]", Error), include('quoted string') ], 'macro parameter value braced string': [ (r"\\[#'()]", Comment.Preproc), (r"[#'()]", Error), include('braced string') ], 'macro parameter value parenthetical': [ (r'(?:[^\\()]|\\\))+', Comment.Preproc), (r'\(', Comment.Preproc, '#push'), (r'\)', Comment.Preproc, '#pop') ],
'whitespace and macro uses': [ include('whitespace'), include('macro uses') ],
'numbers': [ (r'\d+[Ee][+-]?\d+|(\d+\.\d*|\d*\.\d+)([Ee][+-]?\d+)?', Number.Float), (r'(0[Xx])([0-9A-Fa-f]+)', bygroups(Keyword.Type, Number.Hex)), (r'\d+', Number.Integer) ],
'quoted string': [ (r'"', String, '#pop'), (r'[^"$]+', String), include('macro uses'), (r'[$]', String) ],
'braced string': [ # Do nothing. This must be defined in subclasses. ] }
class CsoundScoreLexer(CsoundLexer): """ For `Csound <https://csound.com>`_ scores. """
name = 'Csound Score' aliases = ['csound-score', 'csound-sco'] filenames = ['*.sco'] version_added = '2.1'
tokens = { 'root': [ (r'\n', Whitespace), include('whitespace and macro uses'), include('preprocessor directives'),
(r'[aBbCdefiqstvxy]', Keyword), # There is also a w statement that is generated internally and should not be # used; see https://github.com/csound/csound/issues/750.
(r'z', Keyword.Constant), # z is a constant equal to 800,000,000,000. 800 billion seconds is about # 25,367.8 years. See also # https://csound.com/docs/manual/ScoreTop.html and # https://github.com/csound/csound/search?q=stof+path%3AEngine+filename%3Asread.c.
(r'([nNpP][pP])(\d+)', bygroups(Keyword, Number.Integer)),
(r'[mn]', Keyword, 'mark statement'),
include('numbers'), (r'[!+\-*/^%&|<>#~.]', Operator), (r'[()\[\]]', Punctuation), (r'"', String, 'quoted string'), (r'\{', Comment.Preproc, 'loop after left brace'), ],
'mark statement': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', Name.Label), (r'\n', Whitespace, '#pop') ],
'loop after left brace': [ include('whitespace and macro uses'), (r'\d+', Number.Integer, ('#pop', 'loop after repeat count')), ], 'loop after repeat count': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', Comment.Preproc, ('#pop', 'loop')) ], 'loop': [ (r'\}', Comment.Preproc, '#pop'), include('root') ],
# Braced strings are not allowed in Csound scores, but this is needed because the # superclass includes it. 'braced string': [ (r'\}\}', String, '#pop'), (r'[^}]|\}(?!\})', String) ] }
class CsoundOrchestraLexer(CsoundLexer): """ For `Csound <https://csound.com>`_ orchestras. """
name = 'Csound Orchestra' aliases = ['csound', 'csound-orc'] filenames = ['*.orc', '*.udo'] version_added = '2.1'
user_defined_opcodes = set()
def opcode_name_callback(lexer, match): opcode = match.group(0) lexer.user_defined_opcodes.add(opcode) yield match.start(), Name.Function, opcode
def name_callback(lexer, match): type_annotation_token = Keyword.Type
name = match.group(1) if name in OPCODES or name in DEPRECATED_OPCODES or name in REMOVED_OPCODES: yield match.start(), Name.Builtin, name elif name in lexer.user_defined_opcodes: yield match.start(), Name.Function, name else: type_annotation_token = Name name_match = re.search(r'^(g?[afikSw])(\w+)', name) if name_match: yield name_match.start(1), Keyword.Type, name_match.group(1) yield name_match.start(2), Name, name_match.group(2) else: yield match.start(), Name, name
if match.group(2): yield match.start(2), Punctuation, match.group(2) yield match.start(3), type_annotation_token, match.group(3)
tokens = { 'root': [ (r'\n', Whitespace),
(r'^([ \t]*)(\w+)(:)([ \t]+|$)', bygroups(Whitespace, Name.Label, Punctuation, Whitespace)),
include('whitespace and macro uses'), include('preprocessor directives'),
(r'\binstr\b', Keyword.Declaration, 'instrument numbers and identifiers'), (r'\bopcode\b', Keyword.Declaration, 'after opcode keyword'), (r'\b(?:end(?:in|op))\b', Keyword.Declaration),
include('partial statements') ],
'partial statements': [ (r'\b(?:0dbfs|A4|k(?:r|smps)|nchnls(?:_i)?|sr)\b', Name.Variable.Global),
include('numbers'),
(r'\+=|-=|\*=|/=|<<|>>|<=|>=|==|!=|&&|\|\||[~¬]|[=!+\-*/^%&|<>#?:]', Operator), (r'[(),\[\]]', Punctuation),
(r'"', String, 'quoted string'), (r'\{\{', String, 'braced string'),
(words(( 'do', 'else', 'elseif', 'endif', 'enduntil', 'fi', 'if', 'ithen', 'kthen', 'od', 'then', 'until', 'while', ), prefix=r'\b', suffix=r'\b'), Keyword), (words(('return', 'rireturn'), prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
(r'\b[ik]?goto\b', Keyword, 'goto label'), (r'\b(r(?:einit|igoto)|tigoto)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), 'goto label'), (r'\b(c(?:g|in?|k|nk?)goto)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument')), (r'\b(timout)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument', 'goto argument')), (r'\b(loop_[gl][et])(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument', 'goto argument', 'goto argument')),
(r'\bprintk?s\b', Name.Builtin, 'prints opcode'), (r'\b(?:readscore|scoreline(?:_i)?)\b', Name.Builtin, 'Csound score opcode'), (r'\bpyl?run[it]?\b', Name.Builtin, 'Python opcode'), (r'\blua_(?:exec|opdef)\b', Name.Builtin, 'Lua opcode'), (r'\bp\d+\b', Name.Variable.Instance), (r'\b([A-Z_a-z]\w*)(?:(:)([A-Za-z]))?\b', name_callback) ],
'instrument numbers and identifiers': [ include('whitespace and macro uses'), (r'\d+|[A-Z_a-z]\w*', Name.Function), (r'[+,]', Punctuation), (r'\n', Whitespace, '#pop') ],
'after opcode keyword': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', opcode_name_callback, ('#pop', 'opcode type signatures')), (r'\n', Whitespace, '#pop') ], 'opcode type signatures': [ include('whitespace and macro uses'),
# https://github.com/csound/csound/search?q=XIDENT+path%3AEngine+filename%3Acsound_orc.lex (r'0|[afijkKoOpPStV\[\]]+', Keyword.Type),
(r',', Punctuation), (r'\n', Whitespace, '#pop') ],
'quoted string': [ (r'"', String, '#pop'), (r'[^\\"$%)]+', String), include('macro uses'), include('escape sequences'), include('format specifiers'), (r'[\\$%)]', String) ], 'braced string': [ (r'\}\}', String, '#pop'), (r'(?:[^\\%)}]|\}(?!\}))+', String), include('escape sequences'), include('format specifiers'), (r'[\\%)]', String) ], 'escape sequences': [ # https://github.com/csound/csound/search?q=unquote_string+path%3AEngine+filename%3Acsound_orc_compile.c (r'\\(?:[\\abnrt"]|[0-7]{1,3})', String.Escape) ], # Format specifiers are highlighted in all strings, even though only # fprintks https://csound.com/docs/manual/fprintks.html # fprints https://csound.com/docs/manual/fprints.html # printf/printf_i https://csound.com/docs/manual/printf.html # printks https://csound.com/docs/manual/printks.html # prints https://csound.com/docs/manual/prints.html # sprintf https://csound.com/docs/manual/sprintf.html # sprintfk https://csound.com/docs/manual/sprintfk.html # work with strings that contain format specifiers. In addition, these opcodes’ # handling of format specifiers is inconsistent: # - fprintks and fprints accept %a and %A specifiers, and accept %s specifiers # starting in Csound 6.15.0. # - printks and prints accept %a and %A specifiers, but don’t accept %s # specifiers. # - printf, printf_i, sprintf, and sprintfk don’t accept %a and %A specifiers, # but accept %s specifiers. # See https://github.com/csound/csound/issues/747 for more information. 'format specifiers': [ (r'%[#0\- +]*\d*(?:\.\d+)?[AE-GXac-giosux]', String.Interpol), (r'%%', String.Escape) ],
'goto argument': [ include('whitespace and macro uses'), (r',', Punctuation, '#pop'), include('partial statements') ], 'goto label': [ include('whitespace and macro uses'), (r'\w+', Name.Label, '#pop'), default('#pop') ],
'prints opcode': [ include('whitespace and macro uses'), (r'"', String, 'prints quoted string'), default('#pop') ], 'prints quoted string': [ (r'\\\\[aAbBnNrRtT]', String.Escape), (r'%[!nNrRtT]|[~^]{1,2}', String.Escape), include('quoted string') ],
'Csound score opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Csound score'), (r'\n', Whitespace, '#pop') ], 'Csound score': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(CsoundScoreLexer)) ],
'Python opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Python'), (r'\n', Whitespace, '#pop') ], 'Python': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(PythonLexer)) ],
'Lua opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Lua'), (r'\n', Whitespace, '#pop') ], 'Lua': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(LuaLexer)) ] }
class CsoundDocumentLexer(RegexLexer): """ For Csound documents. """
name = 'Csound Document' aliases = ['csound-document', 'csound-csd'] filenames = ['*.csd'] url = 'https://csound.com' version_added = '2.1'
# These tokens are based on those in XmlLexer in pygments/lexers/html.py. Making # CsoundDocumentLexer a subclass of XmlLexer rather than RegexLexer may seem like a # better idea, since Csound Document files look like XML files. However, Csound # Documents can contain Csound comments (preceded by //, for example) before and # after the root element, unescaped bitwise AND & and less than < operators, etc. In # other words, while Csound Document files look like XML files, they may not actually # be XML files. tokens = { 'root': [ (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'(?:;|//).*$', Comment.Single), (r'[^/;<]+|/(?!/)', Text),
(r'<\s*CsInstruments', Name.Tag, ('orchestra', 'tag')), (r'<\s*CsScore', Name.Tag, ('score', 'tag')), (r'<\s*[Hh][Tt][Mm][Ll]', Name.Tag, ('HTML', 'tag')),
(r'<\s*[\w:.-]+', Name.Tag, 'tag'), (r'<\s*/\s*[\w:.-]+\s*>', Name.Tag) ],
'orchestra': [ (r'<\s*/\s*CsInstruments\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*CsInstruments\s*>)', using(CsoundOrchestraLexer)) ], 'score': [ (r'<\s*/\s*CsScore\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*CsScore\s*>)', using(CsoundScoreLexer)) ], 'HTML': [ (r'<\s*/\s*[Hh][Tt][Mm][Ll]\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*[Hh][Tt][Mm][Ll]\s*>)', using(HtmlLexer)) ],
'tag': [ (r'\s+', Whitespace), (r'[\w.:-]+\s*=', Name.Attribute, 'attr'), (r'/?\s*>', Name.Tag, '#pop') ], 'attr': [ (r'\s+', Whitespace), (r'".*?"', String, '#pop'), (r"'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop') ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632""" pygments.lexers.css ~~~~~~~~~~~~~~~~~~~
Lexers for CSS and related stylesheet formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import reimport copy
from pygments.lexer import ExtendedRegexLexer, RegexLexer, include, bygroups, \ default, words, inheritfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespacefrom pygments.lexers._css_builtins import _css_properties
__all__ = ['CssLexer', 'SassLexer', 'ScssLexer', 'LessCssLexer']
# List of vendor prefixes obtained from:# https://www.w3.org/TR/CSS21/syndata.html#vendor-keyword-history_vendor_prefixes = ( '-ms-', 'mso-', '-moz-', '-o-', '-xv-', '-atsc-', '-wap-', '-khtml-', '-webkit-', 'prince-', '-ah-', '-hp-', '-ro-', '-rim-', '-tc-',)
# List of extended color keywords obtained from:# https://drafts.csswg.org/css-color/#named-colors_color_keywords = ( 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'rebeccapurple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen',) + ('transparent',)
# List of keyword values obtained from:# http://cssvalues.com/_keyword_values = ( 'absolute', 'alias', 'all', 'all-petite-caps', 'all-scroll', 'all-small-caps', 'allow-end', 'alpha', 'alternate', 'alternate-reverse', 'always', 'armenian', 'auto', 'avoid', 'avoid-column', 'avoid-page', 'backwards', 'balance', 'baseline', 'below', 'blink', 'block', 'bold', 'bolder', 'border-box', 'both', 'bottom', 'box-decoration', 'break-word', 'capitalize', 'cell', 'center', 'circle', 'clip', 'clone', 'close-quote', 'col-resize', 'collapse', 'color', 'color-burn', 'color-dodge', 'column', 'column-reverse', 'compact', 'condensed', 'contain', 'container', 'content-box', 'context-menu', 'copy', 'cover', 'crisp-edges', 'crosshair', 'currentColor', 'cursive', 'darken', 'dashed', 'decimal', 'decimal-leading-zero', 'default', 'descendants', 'difference', 'digits', 'disc', 'distribute', 'dot', 'dotted', 'double', 'double-circle', 'e-resize', 'each-line', 'ease', 'ease-in', 'ease-in-out', 'ease-out', 'edges', 'ellipsis', 'end', 'ew-resize', 'exclusion', 'expanded', 'extra-condensed', 'extra-expanded', 'fantasy', 'fill', 'fill-box', 'filled', 'first', 'fixed', 'flat', 'flex', 'flex-end', 'flex-start', 'flip', 'force-end', 'forwards', 'from-image', 'full-width', 'geometricPrecision', 'georgian', 'groove', 'hanging', 'hard-light', 'help', 'hidden', 'hide', 'horizontal', 'hue', 'icon', 'infinite', 'inherit', 'initial', 'ink', 'inline', 'inline-block', 'inline-flex', 'inline-table', 'inset', 'inside', 'inter-word', 'invert', 'isolate', 'italic', 'justify', 'large', 'larger', 'last', 'left', 'lighten', 'lighter', 'line-through', 'linear', 'list-item', 'local', 'loose', 'lower-alpha', 'lower-greek', 'lower-latin', 'lower-roman', 'lowercase', 'ltr', 'luminance', 'luminosity', 'mandatory', 'manipulation', 'manual', 'margin-box', 'match-parent', 'medium', 'mixed', 'monospace', 'move', 'multiply', 'n-resize', 'ne-resize', 'nesw-resize', 'no-close-quote', 'no-drop', 'no-open-quote', 'no-repeat', 'none', 'normal', 'not-allowed', 'nowrap', 'ns-resize', 'nw-resize', 'nwse-resize', 'objects', 'oblique', 'off', 'on', 'open', 'open-quote', 'optimizeLegibility', 'optimizeSpeed', 'outset', 'outside', 'over', 'overlay', 'overline', 'padding-box', 'page', 'pan-down', 'pan-left', 'pan-right', 'pan-up', 'pan-x', 'pan-y', 'paused', 'petite-caps', 'pixelated', 'pointer', 'preserve-3d', 'progress', 'proximity', 'relative', 'repeat', 'repeat no-repeat', 'repeat-x', 'repeat-y', 'reverse', 'revert', 'ridge', 'right', 'round', 'row', 'row-resize', 'row-reverse', 'rtl', 'ruby', 'ruby-base', 'ruby-base-container', 'ruby-text', 'ruby-text-container', 'run-in', 'running', 's-resize', 'sans-serif', 'saturation', 'scale-down', 'screen', 'scroll', 'se-resize', 'semi-condensed', 'semi-expanded', 'separate', 'serif', 'sesame', 'show', 'sideways', 'sideways-left', 'sideways-right', 'slice', 'small', 'small-caps', 'smaller', 'smooth', 'snap', 'soft-light', 'solid', 'space', 'space-around', 'space-between', 'spaces', 'square', 'start', 'static', 'step-end', 'step-start', 'sticky', 'stretch', 'strict', 'stroke-box', 'style', 'sw-resize', 'table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row', 'table-row-group', 'text', 'thick', 'thin', 'titling-caps', 'to', 'top', 'triangle', 'ultra-condensed', 'ultra-expanded', 'under', 'underline', 'unicase', 'unset', 'upper-alpha', 'upper-latin', 'upper-roman', 'uppercase', 'upright', 'use-glyph-orientation', 'vertical', 'vertical-text', 'view-box', 'visible', 'w-resize', 'wait', 'wavy', 'weight', 'weight style', 'wrap', 'wrap-reverse', 'x-large', 'x-small', 'xx-large', 'xx-small', 'zoom-in', 'zoom-out',)
# List of other keyword values from other sources:_other_keyword_values = ( 'above', 'aural', 'behind', 'bidi-override', 'center-left', 'center-right', 'cjk-ideographic', 'continuous', 'crop', 'cross', 'embed', 'far-left', 'far-right', 'fast', 'faster', 'hebrew', 'high', 'higher', 'hiragana', 'hiragana-iroha', 'katakana', 'katakana-iroha', 'landscape', 'left-side', 'leftwards', 'level', 'loud', 'low', 'lower', 'message-box', 'middle', 'mix', 'narrower', 'once', 'portrait', 'right-side', 'rightwards', 'silent', 'slow', 'slower', 'small-caption', 'soft', 'spell-out', 'status-bar', 'super', 'text-bottom', 'text-top', 'wider', 'x-fast', 'x-high', 'x-loud', 'x-low', 'x-soft', 'yes', 'pre', 'pre-wrap', 'pre-line',)
# List of functional notation and function keyword values:_functional_notation_keyword_values = ( 'attr', 'blackness', 'blend', 'blenda', 'blur', 'brightness', 'calc', 'circle', 'color-mod', 'contrast', 'counter', 'cubic-bezier', 'device-cmyk', 'drop-shadow', 'ellipse', 'gray', 'grayscale', 'hsl', 'hsla', 'hue', 'hue-rotate', 'hwb', 'image', 'inset', 'invert', 'lightness', 'linear-gradient', 'matrix', 'matrix3d', 'opacity', 'perspective', 'polygon', 'radial-gradient', 'rect', 'repeating-linear-gradient', 'repeating-radial-gradient', 'rgb', 'rgba', 'rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'saturate', 'saturation', 'scale', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'sepia', 'shade', 'skewX', 'skewY', 'steps', 'tint', 'toggle', 'translate', 'translate3d', 'translateX', 'translateY', 'translateZ', 'whiteness',)# Note! Handle url(...) separately.
# List of units obtained from:# https://www.w3.org/TR/css3-values/_angle_units = ( 'deg', 'grad', 'rad', 'turn',)_frequency_units = ( 'Hz', 'kHz',)_length_units = ( 'em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax', 'px', 'mm', 'cm', 'in', 'pt', 'pc', 'q',)_resolution_units = ( 'dpi', 'dpcm', 'dppx',)_time_units = ( 's', 'ms',)_all_units = _angle_units + _frequency_units + _length_units + \ _resolution_units + _time_units
class CssLexer(RegexLexer): """ For CSS (Cascading Style Sheets). """
name = 'CSS' url = 'https://www.w3.org/TR/CSS/#css' aliases = ['css'] filenames = ['*.css'] mimetypes = ['text/css'] version_added = ''
tokens = { 'root': [ include('basics'), ], 'basics': [ (r'\s+', Whitespace), (r'/\*(?:.|\n)*?\*/', Comment), (r'\{', Punctuation, 'content'), (r'(\:{1,2})([\w-]+)', bygroups(Punctuation, Name.Decorator)), (r'(\.)([\w-]+)', bygroups(Punctuation, Name.Class)), (r'(\#)([\w-]+)', bygroups(Punctuation, Name.Namespace)), (r'(@)([\w-]+)', bygroups(Punctuation, Keyword), 'atrule'), (r'[\w-]+', Name.Tag), (r'[~^*!%&$\[\]()<>|+=@:;,./?-]', Operator), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ], 'atrule': [ (r'\{', Punctuation, 'atcontent'), (r';', Punctuation, '#pop'), include('basics'), ], 'atcontent': [ include('basics'), (r'\}', Punctuation, '#pop:2'), ], 'content': [ (r'\s+', Whitespace), (r'\}', Punctuation, '#pop'), (r';', Punctuation), (r'^@.*?$', Comment.Preproc),
(words(_vendor_prefixes,), Keyword.Pseudo), (r'('+r'|'.join(_css_properties)+r')(\s*)(\:)', bygroups(Keyword, Whitespace, Punctuation), 'value-start'), (r'([-]+[a-zA-Z_][\w-]*)(\s*)(\:)', bygroups(Name.Variable, Whitespace, Punctuation), 'value-start'), (r'([a-zA-Z_][\w-]*)(\s*)(\:)', bygroups(Name, Whitespace, Punctuation), 'value-start'),
(r'/\*(?:.|\n)*?\*/', Comment), ], 'value-start': [ (r'\s+', Whitespace), (words(_vendor_prefixes,), Name.Builtin.Pseudo), include('urls'), (r'('+r'|'.join(_functional_notation_keyword_values)+r')(\()', bygroups(Name.Builtin, Punctuation), 'function-start'), (r'([a-zA-Z_][\w-]+)(\()', bygroups(Name.Function, Punctuation), 'function-start'), (words(_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_other_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_color_keywords, suffix=r'\b'), Keyword.Constant), # for transition-property etc. (words(_css_properties, suffix=r'\b'), Keyword), (r'\!important', Comment.Preproc), (r'/\*(?:.|\n)*?\*/', Comment),
include('numeric-values'),
(r'[~^*!%&<>|+=@:./?-]+', Operator), (r'[\[\](),]+', Punctuation), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_][\w-]*', Name), (r';', Punctuation, '#pop'), (r'\}', Punctuation, '#pop:2'), ], 'function-start': [ (r'\s+', Whitespace), (r'[-]+([A-Za-z][\w+]*[-]*)+', Name.Variable), include('urls'), (words(_vendor_prefixes,), Keyword.Pseudo), (words(_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_other_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_color_keywords, suffix=r'\b'), Keyword.Constant),
# function-start may be entered recursively (r'(' + r'|'.join(_functional_notation_keyword_values) + r')(\()', bygroups(Name.Builtin, Punctuation), 'function-start'), (r'([a-zA-Z_][\w-]+)(\()', bygroups(Name.Function, Punctuation), 'function-start'),
(r'/\*(?:.|\n)*?\*/', Comment), include('numeric-values'), (r'[*+/-]', Operator), (r',', Punctuation), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_-]\w*', Name), (r'\)', Punctuation, '#pop'), ], 'urls': [ (r'(url)(\()(".*?")(\))', bygroups(Name.Builtin, Punctuation, String.Double, Punctuation)), (r"(url)(\()('.*?')(\))", bygroups(Name.Builtin, Punctuation, String.Single, Punctuation)), (r'(url)(\()(.*?)(\))', bygroups(Name.Builtin, Punctuation, String.Other, Punctuation)), ], 'numeric-values': [ (r'\#[a-zA-Z0-9]{1,6}', Number.Hex), (r'[+\-]?[0-9]*[.][0-9]+', Number.Float, 'numeric-end'), (r'[+\-]?[0-9]+', Number.Integer, 'numeric-end'), ], 'numeric-end': [ (words(_all_units, suffix=r'\b'), Keyword.Type), (r'%', Keyword.Type), default('#pop'), ], }
common_sass_tokens = { 'value': [ (r'[ \t]+', Whitespace), (r'[!$][\w-]+', Name.Variable), (r'url\(', String.Other, 'string-url'), (r'[a-z_-][\w-]*(?=\()', Name.Function), (words(_css_properties + ( 'above', 'absolute', 'always', 'armenian', 'aural', 'auto', 'avoid', 'baseline', 'behind', 'below', 'bidi-override', 'blink', 'block', 'bold', 'bolder', 'both', 'capitalize', 'center-left', 'center-right', 'center', 'circle', 'cjk-ideographic', 'close-quote', 'collapse', 'condensed', 'continuous', 'crosshair', 'cross', 'cursive', 'dashed', 'decimal-leading-zero', 'decimal', 'default', 'digits', 'disc', 'dotted', 'double', 'e-resize', 'embed', 'extra-condensed', 'extra-expanded', 'expanded', 'fantasy', 'far-left', 'far-right', 'faster', 'fast', 'fixed', 'georgian', 'groove', 'hebrew', 'help', 'hidden', 'hide', 'higher', 'high', 'hiragana-iroha', 'hiragana', 'icon', 'inherit', 'inline-table', 'inline', 'inset', 'inside', 'invert', 'italic', 'justify', 'katakana-iroha', 'katakana', 'landscape', 'larger', 'large', 'left-side', 'leftwards', 'level', 'lighter', 'line-through', 'list-item', 'loud', 'lower-alpha', 'lower-greek', 'lower-roman', 'lowercase', 'ltr', 'lower', 'low', 'medium', 'message-box', 'middle', 'mix', 'monospace', 'n-resize', 'narrower', 'ne-resize', 'no-close-quote', 'no-open-quote', 'no-repeat', 'none', 'normal', 'nowrap', 'nw-resize', 'oblique', 'once', 'open-quote', 'outset', 'outside', 'overline', 'pointer', 'portrait', 'px', 'relative', 'repeat-x', 'repeat-y', 'repeat', 'rgb', 'ridge', 'right-side', 'rightwards', 's-resize', 'sans-serif', 'scroll', 'se-resize', 'semi-condensed', 'semi-expanded', 'separate', 'serif', 'show', 'silent', 'slow', 'slower', 'small-caps', 'small-caption', 'smaller', 'soft', 'solid', 'spell-out', 'square', 'static', 'status-bar', 'super', 'sw-resize', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row', 'table-row-group', 'text', 'text-bottom', 'text-top', 'thick', 'thin', 'transparent', 'ultra-condensed', 'ultra-expanded', 'underline', 'upper-alpha', 'upper-latin', 'upper-roman', 'uppercase', 'url', 'visible', 'w-resize', 'wait', 'wider', 'x-fast', 'x-high', 'x-large', 'x-loud', 'x-low', 'x-small', 'x-soft', 'xx-large', 'xx-small', 'yes'), suffix=r'\b'), Name.Constant), (words(_color_keywords, suffix=r'\b'), Name.Entity), (words(( 'black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua'), suffix=r'\b'), Name.Builtin), (r'\!(important|default)', Name.Exception), (r'(true|false)', Name.Pseudo), (r'(and|or|not)', Operator.Word), (r'/\*', Comment.Multiline, 'inline-comment'), (r'//[^\n]*', Comment.Single), (r'\#[a-z0-9]{1,6}', Number.Hex), (r'(-?\d+)(\%|[a-z]+)?', bygroups(Number.Integer, Keyword.Type)), (r'(-?\d*\.\d+)(\%|[a-z]+)?', bygroups(Number.Float, Keyword.Type)), (r'#\{', String.Interpol, 'interpolation'), (r'[~^*!&%<>|+=@:,./?-]+', Operator), (r'[\[\]()]+', Punctuation), (r'"', String.Double, 'string-double'), (r"'", String.Single, 'string-single'), (r'[a-z_-][\w-]*', Name), ],
'interpolation': [ (r'\}', String.Interpol, '#pop'), include('value'), ],
'selector': [ (r'[ \t]+', Whitespace), (r'\:', Name.Decorator, 'pseudo-class'), (r'\.', Name.Class, 'class'), (r'\#', Name.Namespace, 'id'), (r'[\w-]+', Name.Tag), (r'#\{', String.Interpol, 'interpolation'), (r'&', Keyword), (r'[~^*!&\[\]()<>|+=@:;,./?-]', Operator), (r'"', String.Double, 'string-double'), (r"'", String.Single, 'string-single'), ],
'string-double': [ (r'(\\.|#(?=[^\n{])|[^\n"#])+', String.Double), (r'#\{', String.Interpol, 'interpolation'), (r'"', String.Double, '#pop'), ],
'string-single': [ (r"(\\.|#(?=[^\n{])|[^\n'#])+", String.Single), (r'#\{', String.Interpol, 'interpolation'), (r"'", String.Single, '#pop'), ],
'string-url': [ (r'(\\#|#(?=[^\n{])|[^\n#)])+', String.Other), (r'#\{', String.Interpol, 'interpolation'), (r'\)', String.Other, '#pop'), ],
'pseudo-class': [ (r'[\w-]+', Name.Decorator), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'class': [ (r'[\w-]+', Name.Class), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'id': [ (r'[\w-]+', Name.Namespace), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'for': [ (r'(from|to|through)', Operator.Word), include('value'), ],}
def _indentation(lexer, match, ctx): indentation = match.group(0) yield match.start(), Whitespace, indentation ctx.last_indentation = indentation ctx.pos = match.end()
if hasattr(ctx, 'block_state') and ctx.block_state and \ indentation.startswith(ctx.block_indentation) and \ indentation != ctx.block_indentation: ctx.stack.append(ctx.block_state) else: ctx.block_state = None ctx.block_indentation = None ctx.stack.append('content')
def _starts_block(token, state): def callback(lexer, match, ctx): yield match.start(), token, match.group(0)
if hasattr(ctx, 'last_indentation'): ctx.block_indentation = ctx.last_indentation else: ctx.block_indentation = ''
ctx.block_state = state ctx.pos = match.end()
return callback
class SassLexer(ExtendedRegexLexer): """ For Sass stylesheets. """
name = 'Sass' url = 'https://sass-lang.com/' aliases = ['sass'] filenames = ['*.sass'] mimetypes = ['text/x-sass'] version_added = '1.3'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'[ \t]*\n', Whitespace), (r'[ \t]*', _indentation), ],
'content': [ (r'//[^\n]*', _starts_block(Comment.Single, 'single-comment'), 'root'), (r'/\*[^\n]*', _starts_block(Comment.Multiline, 'multi-comment'), 'root'), (r'@import', Keyword, 'import'), (r'@for', Keyword, 'for'), (r'@(debug|warn|if|while)', Keyword, 'value'), (r'(@mixin)( )([\w-]+)', bygroups(Keyword, Whitespace, Name.Function), 'value'), (r'(@include)( )([\w-]+)', bygroups(Keyword, Whitespace, Name.Decorator), 'value'), (r'@extend', Keyword, 'selector'), (r'@[\w-]+', Keyword, 'selector'), (r'=[\w-]+', Name.Function, 'value'), (r'\+[\w-]+', Name.Decorator, 'value'), (r'([!$][\w-]\w*)([ \t]*(?:(?:\|\|)?=|:))', bygroups(Name.Variable, Operator), 'value'), (r':', Name.Attribute, 'old-style-attr'), (r'(?=.+?[=:]([^a-z]|$))', Name.Attribute, 'new-style-attr'), default('selector'), ],
'single-comment': [ (r'.+', Comment.Single), (r'\n', Whitespace, 'root'), ],
'multi-comment': [ (r'.+', Comment.Multiline), (r'\n', Whitespace, 'root'), ],
'import': [ (r'[ \t]+', Whitespace), (r'\S+', String), (r'\n', Whitespace, 'root'), ],
'old-style-attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'([ \t]*)(=)', bygroups(Whitespace, Operator), 'value'), default('value'), ],
'new-style-attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'([ \t]*)([=:])', bygroups(Whitespace, Operator), 'value'), ],
'inline-comment': [ (r"(\\#|#(?=[^\n{])|\*(?=[^\n/])|[^\n#*])+", Comment.Multiline), (r'#\{', String.Interpol, 'interpolation'), (r"\*/", Comment, '#pop'), ], } for group, common in common_sass_tokens.items(): tokens[group] = copy.copy(common) tokens['value'].append((r'\n', Whitespace, 'root')) tokens['selector'].append((r'\n', Whitespace, 'root'))
class ScssLexer(RegexLexer): """ For SCSS stylesheets. """
name = 'SCSS' url = 'https://sass-lang.com/' aliases = ['scss'] filenames = ['*.scss'] mimetypes = ['text/x-scss'] version_added = ''
flags = re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'\s+', Whitespace), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@import', Keyword, 'value'), (r'@for', Keyword, 'for'), (r'@(debug|warn|if|while)', Keyword, 'value'), (r'(@mixin)( [\w-]+)', bygroups(Keyword, Name.Function), 'value'), (r'(@include)( [\w-]+)', bygroups(Keyword, Name.Decorator), 'value'), (r'@extend', Keyword, 'selector'), (r'(@media)(\s+)', bygroups(Keyword, Whitespace), 'value'), (r'@[\w-]+', Keyword, 'selector'), (r'(\$[\w-]*\w)([ \t]*:)', bygroups(Name.Variable, Operator), 'value'), # TODO: broken, and prone to infinite loops. # (r'(?=[^;{}][;}])', Name.Attribute, 'attr'), # (r'(?=[^;{}:]+:[^a-z])', Name.Attribute, 'attr'), default('selector'), ],
'attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'[ \t]*:', Operator, 'value'), default('#pop'), ],
'inline-comment': [ (r"(\\#|#(?=[^{])|\*(?=[^/])|[^#*])+", Comment.Multiline), (r'#\{', String.Interpol, 'interpolation'), (r"\*/", Comment, '#pop'), ], } for group, common in common_sass_tokens.items(): tokens[group] = copy.copy(common) tokens['value'].extend([(r'\n', Whitespace), (r'[;{}]', Punctuation, '#pop')]) tokens['selector'].extend([(r'\n', Whitespace), (r'[;{}]', Punctuation, '#pop')])
class LessCssLexer(CssLexer): """ For LESS styleshets. """
name = 'LessCss' url = 'http://lesscss.org/' aliases = ['less'] filenames = ['*.less'] mimetypes = ['text/x-less-css'] version_added = '2.1'
tokens = { # FIXME: It's not currently possible to simply do the following, # as `include('basics')` doesn't take overrides into account: # 'basics': [ # (r'//.*\n', Comment.Single), # (r'/\*(?:.|\n)*?\*/', Comment.Multiline), # inherit, # ], 'root': [ (r'@\w+', Name.Variable), (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'atcontent': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'atrule': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'content': [ (r'\{', Punctuation, '#push'), (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'value-start': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'function-start': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126""" pygments.lexers.dalvik ~~~~~~~~~~~~~~~~~~~~~~
Pygments lexers for Dalvik VM-related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Keyword, Text, Comment, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['SmaliLexer']
class SmaliLexer(RegexLexer): """ For Smali (Android/Dalvik) assembly code. """ name = 'Smali' url = 'http://code.google.com/p/smali/' aliases = ['smali'] filenames = ['*.smali'] mimetypes = ['text/smali'] version_added = '1.6'
tokens = { 'root': [ include('comment'), include('label'), include('field'), include('method'), include('class'), include('directive'), include('access-modifier'), include('instruction'), include('literal'), include('punctuation'), include('type'), include('whitespace') ], 'directive': [ (r'^([ \t]*)(\.(?:class|super|implements|field|subannotation|annotation|' r'enum|method|registers|locals|array-data|packed-switch|' r'sparse-switch|catchall|catch|line|parameter|local|prologue|' r'epilogue|source))', bygroups(Whitespace, Keyword)), (r'^([ \t]*)(\.end)( )(field|subannotation|annotation|method|array-data|' 'packed-switch|sparse-switch|parameter|local)', bygroups(Whitespace, Keyword, Whitespace, Keyword)), (r'^([ \t]*)(\.restart)( )(local)', bygroups(Whitespace, Keyword, Whitespace, Keyword)), ], 'access-modifier': [ (r'(public|private|protected|static|final|synchronized|bridge|' r'varargs|native|abstract|strictfp|synthetic|constructor|' r'declared-synchronized|interface|enum|annotation|volatile|' r'transient)', Keyword), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), ], 'instruction': [ (r'\b[vp]\d+\b', Name.Builtin), # registers (r'(\b[a-z][A-Za-z0-9/-]+)(\s+)', bygroups(Text, Whitespace)), # instructions ], 'literal': [ (r'".*"', String), (r'0x[0-9A-Fa-f]+t?', Number.Hex), (r'[0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'[0-9]+L?', Number.Integer), ], 'field': [ (r'(\$?\b)([\w$]*)(:)', bygroups(Punctuation, Name.Variable, Punctuation)), ], 'method': [ (r'<(?:cl)?init>', Name.Function), # constructor (r'(\$?\b)([\w$]*)(\()', bygroups(Punctuation, Name.Function, Punctuation)), ], 'label': [ (r':\w+', Name.Label), ], 'class': [ # class names in the form Lcom/namespace/ClassName; # I only want to color the ClassName part, so the namespace part is # treated as 'Text' (r'(L)((?:[\w$]+/)*)([\w$]+)(;)', bygroups(Keyword.Type, Text, Name.Class, Text)), ], 'punctuation': [ (r'->', Punctuation), (r'[{},():=.-]', Punctuation), ], 'type': [ (r'[ZBSCIJFDV\[]+', Keyword.Type), ], 'comment': [ (r'#.*?\n', Comment), ], }
def analyse_text(text): score = 0 if re.search(r'^\s*\.class\s', text, re.MULTILINE): score += 0.5 if re.search(r'\b((check-cast|instance-of|throw-verification-error' r')\b|(-to|add|[ais]get|[ais]put|and|cmpl|const|div|' r'if|invoke|move|mul|neg|not|or|rem|return|rsub|shl|' r'shr|sub|ushr)[-/])|{|}', text, re.MULTILINE): score += 0.3 if re.search(r'(\.(catchall|epilogue|restart local|prologue)|' r'\b(array-data|class-change-error|declared-synchronized|' r'(field|inline|vtable)@0x[0-9a-fA-F]|generic-error|' r'illegal-class-access|illegal-field-access|' r'illegal-method-access|instantiation-error|no-error|' r'no-such-class|no-such-field|no-such-method|' r'packed-switch|sparse-switch))\b', text, re.MULTILINE): score += 0.6 return score123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763""" pygments.lexers.data ~~~~~~~~~~~~~~~~~~~~
Lexers for data file format.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import Lexer, ExtendedRegexLexer, LexerContext, \ include, bygroupsfrom pygments.token import Comment, Error, Keyword, Literal, Name, Number, \ Punctuation, String, Whitespace
__all__ = ['YamlLexer', 'JsonLexer', 'JsonBareObjectLexer', 'JsonLdLexer']
class YamlLexerContext(LexerContext): """Indentation context for the YAML lexer."""
def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.indent_stack = [] self.indent = -1 self.next_indent = 0 self.block_scalar_indent = None
class YamlLexer(ExtendedRegexLexer): """ Lexer for YAML, a human-friendly data serialization language. """
name = 'YAML' url = 'http://yaml.org/' aliases = ['yaml'] filenames = ['*.yaml', '*.yml'] mimetypes = ['text/x-yaml'] version_added = '0.11'
def something(token_class): """Do not produce empty tokens.""" def callback(lexer, match, context): text = match.group() if not text: return yield match.start(), token_class, text context.pos = match.end() return callback
def reset_indent(token_class): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), token_class, text context.pos = match.end() return callback
def save_indent(token_class, start=False): """Save a possible indentation level.""" def callback(lexer, match, context): text = match.group() extra = '' if start: context.next_indent = len(text) if context.next_indent < context.indent: while context.next_indent < context.indent: context.indent = context.indent_stack.pop() if context.next_indent > context.indent: extra = text[context.indent:] text = text[:context.indent] else: context.next_indent += len(text) if text: yield match.start(), token_class, text if extra: yield match.start()+len(text), token_class.Error, extra context.pos = match.end() return callback
def set_indent(token_class, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_indent if not implicit: context.next_indent += len(text) yield match.start(), token_class, text context.pos = match.end() return callback
def set_block_scalar_indent(token_class): """Set an explicit indentation level for a block scalar.""" def callback(lexer, match, context): text = match.group() context.block_scalar_indent = None if not text: return increment = match.group(1) if increment: current_indent = max(context.indent, 0) increment = int(increment) context.block_scalar_indent = current_indent + increment if text: yield match.start(), token_class, text context.pos = match.end() return callback
def parse_block_scalar_empty_line(indent_token_class, content_token_class): """Process an empty line in a block scalar.""" def callback(lexer, match, context): text = match.group() if (context.block_scalar_indent is None or len(text) <= context.block_scalar_indent): if text: yield match.start(), indent_token_class, text else: indentation = text[:context.block_scalar_indent] content = text[context.block_scalar_indent:] yield match.start(), indent_token_class, indentation yield (match.start()+context.block_scalar_indent, content_token_class, content) context.pos = match.end() return callback
def parse_block_scalar_indent(token_class): """Process indentation spaces in a block scalar.""" def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() context.stack.pop() return context.block_scalar_indent = len(text) else: if len(text) < context.block_scalar_indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback
def parse_plain_scalar_indent(token_class): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback
tokens = { # the root rules 'root': [ # ignored whitespaces (r'[ ]+(?=#|$)', Whitespace), # line breaks (r'\n+', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # the '%YAML' directive (r'^%YAML(?=[ ]|$)', reset_indent(Name.Tag), 'yaml-directive'), # the %TAG directive (r'^%TAG(?=[ ]|$)', reset_indent(Name.Tag), 'tag-directive'), # document start and document end indicators (r'^(?:---|\.\.\.)(?=[ ]|$)', reset_indent(Name.Namespace), 'block-line'), # indentation spaces (r'[ ]*(?!\s|$)', save_indent(Whitespace, start=True), ('block-line', 'indentation')), ],
# trailing whitespaces after directives or a block scalar indicator 'ignored-line': [ # ignored whitespaces (r'[ ]+(?=#|$)', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # line break (r'\n', Whitespace, '#pop:2'), ],
# the %YAML directive 'yaml-directive': [ # the version number (r'([ ]+)([0-9]+\.[0-9]+)', bygroups(Whitespace, Number), 'ignored-line'), ],
# the %TAG directive 'tag-directive': [ # a tag handle and the corresponding prefix (r'([ ]+)(!|![\w-]*!)' r'([ ]+)(!|!?[\w;/?:@&=+$,.!~*\'()\[\]%-]+)', bygroups(Whitespace, Keyword.Type, Whitespace, Keyword.Type), 'ignored-line'), ],
# block scalar indicators and indentation spaces 'indentation': [ # trailing whitespaces are ignored (r'[ ]*$', something(Whitespace), '#pop:2'), # whitespaces preceding block collection indicators (r'[ ]+(?=[?:-](?:[ ]|$))', save_indent(Whitespace)), # block collection indicators (r'[?:-](?=[ ]|$)', set_indent(Punctuation.Indicator)), # the beginning a block line (r'[ ]*', save_indent(Whitespace), '#pop'), ],
# an indented line in the block context 'block-line': [ # the line end (r'[ ]*(?=#|$)', something(Whitespace), '#pop'), # whitespaces separating tokens (r'[ ]+', Whitespace), # key with colon (r'''([^#,?\[\]{}"'\n]+)(:)(?=[ ]|$)''', bygroups(Name.Tag, set_indent(Punctuation, implicit=True))), # tags, anchors and aliases, include('descriptors'), # block collections and scalars include('block-nodes'), # flow collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`-]|[?:-]\S)', something(Name.Variable), 'plain-scalar-in-block-context'), ],
# tags, anchors, aliases 'descriptors': [ # a full-form tag (r'!<[\w#;/?:@&=+$,.!~*\'()\[\]%-]+>', Keyword.Type), # a tag in the form '!', '!suffix' or '!handle!suffix' (r'!(?:[\w-]+!)?' r'[\w#;/?:@&=+$,.!~*\'()\[\]%-]*', Keyword.Type), # an anchor (r'&[\w-]+', Name.Label), # an alias (r'\*[\w-]+', Name.Variable), ],
# block collections and scalars 'block-nodes': [ # implicit key (r':(?=[ ]|$)', set_indent(Punctuation.Indicator, implicit=True)), # literal and folded scalars (r'[|>]', Punctuation.Indicator, ('block-scalar-content', 'block-scalar-header')), ],
# flow collections and quoted scalars 'flow-nodes': [ # a flow sequence (r'\[', Punctuation.Indicator, 'flow-sequence'), # a flow mapping (r'\{', Punctuation.Indicator, 'flow-mapping'), # a single-quoted scalar (r'\'', String, 'single-quoted-scalar'), # a double-quoted scalar (r'\"', String, 'double-quoted-scalar'), ],
# the content of a flow collection 'flow-collection': [ # whitespaces (r'[ ]+', Whitespace), # line breaks (r'\n+', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # simple indicators (r'[?:,]', Punctuation.Indicator), # tags, anchors and aliases include('descriptors'), # nested collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`])', something(Name.Variable), 'plain-scalar-in-flow-context'), ],
# a flow sequence indicated by '[' and ']' 'flow-sequence': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\]', Punctuation.Indicator, '#pop'), ],
# a flow mapping indicated by '{' and '}' 'flow-mapping': [ # key with colon (r'''([^,:?\[\]{}"'\n]+)(:)(?=[ ]|$)''', bygroups(Name.Tag, Punctuation)), # include flow collection rules include('flow-collection'), # the closing indicator (r'\}', Punctuation.Indicator, '#pop'), ],
# block scalar lines 'block-scalar-content': [ # line break (r'\n', Whitespace), # empty line (r'^[ ]+$', parse_block_scalar_empty_line(Whitespace, Name.Constant)), # indentation spaces (we may leave the state here) (r'^[ ]*', parse_block_scalar_indent(Whitespace)), # line content (r'[\S\t ]+', Name.Constant), ],
# the content of a literal or folded scalar 'block-scalar-header': [ # indentation indicator followed by chomping flag (r'([1-9])?[+-]?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), # chomping flag followed by indentation indicator (r'[+-]?([1-9])?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), ],
# ignored and regular whitespaces in quoted scalars 'quoted-scalar-whitespaces': [ # leading and trailing whitespaces are ignored (r'^[ ]+', Whitespace), (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), ],
# single-quoted scalars 'single-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of the quote character (r'\'\'', String.Escape), # regular non-whitespace characters (r'[^\s\']+', String), # the closing quote (r'\'', String, '#pop'), ],
# double-quoted scalars 'double-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of special characters (r'\\[0abt\tn\nvfre "\\N_LP]', String), # escape codes (r'\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})', String.Escape), # regular non-whitespace characters (r'[^\s"\\]+', String), # the closing quote (r'"', String, '#pop'), ],
# the beginning of a new line while scanning a plain scalar 'plain-scalar-in-block-context-new-line': [ # empty lines (r'^[ ]+$', Whitespace), # line breaks (r'\n+', Whitespace), # document start and document end indicators (r'^(?=---|\.\.\.)', something(Name.Namespace), '#pop:3'), # indentation spaces (we may leave the block line state here) (r'^[ ]*', parse_plain_scalar_indent(Whitespace), '#pop'), ],
# a plain scalar in the block context 'plain-scalar-in-block-context': [ # the scalar ends with the ':' indicator (r'[ ]*(?=:[ ]|:$)', something(Whitespace), '#pop'), # the scalar ends with whitespaces followed by a comment (r'[ ]+(?=#)', Whitespace, '#pop'), # trailing whitespaces are ignored (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace, 'plain-scalar-in-block-context-new-line'), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Plain), # regular non-whitespace characters (r'(?::(?!\s)|[^\s:])+', Literal.Scalar.Plain), ],
# a plain scalar is the flow context 'plain-scalar-in-flow-context': [ # the scalar ends with an indicator character (r'[ ]*(?=[,:?\[\]{}])', something(Whitespace), '#pop'), # the scalar ends with a comment (r'[ ]+(?=#)', Whitespace, '#pop'), # leading and trailing whitespaces are ignored (r'^[ ]+', Whitespace), (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), # regular non-whitespace characters (r'[^\s,:?\[\]{}]+', Name.Variable), ],
}
def get_tokens_unprocessed(self, text=None, context=None): if context is None: context = YamlLexerContext(text, 0) return super().get_tokens_unprocessed(text, context)
class JsonLexer(Lexer): """ For JSON data structures.
Javascript-style comments are supported (like ``/* */`` and ``//``), though comments are not part of the JSON specification. This allows users to highlight JSON as it is used in the wild.
No validation is performed on the input JSON document. """
name = 'JSON' url = 'https://www.json.org' aliases = ['json', 'json-object'] filenames = ['*.json', '*.jsonl', '*.ndjson', 'Pipfile.lock', '*.module', '*.xc'] mimetypes = ['application/json', 'application/json-object', 'application/x-ndjson', 'application/jsonl', 'application/json-seq'] version_added = '1.5'
# No validation of integers, floats, or constants is done. # As long as the characters are members of the following # sets, the token will be considered valid. For example, # # "--1--" is parsed as an integer # "1...eee" is parsed as a float # "trustful" is parsed as a constant # integers = set('-0123456789') floats = set('.eE+') constants = set('truefalsenull') # true|false|null hexadecimals = set('0123456789abcdefABCDEF') punctuations = set('{}[],') whitespaces = {'\u0020', '\u000a', '\u000d', '\u0009'}
def get_tokens_unprocessed(self, text): """Parse JSON data."""
in_string = False in_escape = False in_unicode_escape = 0 in_whitespace = False in_constant = False in_number = False in_float = False in_punctuation = False in_comment_single = False in_comment_multiline = False expecting_second_comment_opener = False # // or /* expecting_second_comment_closer = False # */
start = 0
# The queue is used to store data that may need to be tokenized # differently based on what follows. In particular, JSON object # keys are tokenized differently than string values, but cannot # be distinguished until punctuation is encountered outside the # string. # # A ":" character after the string indicates that the string is # an object key; any other character indicates the string is a # regular string value. # # The queue holds tuples that contain the following data: # # (start_index, token_type, text) # # By default the token type of text in double quotes is # String.Double. The token type will be replaced if a colon # is encountered after the string closes. # queue = []
for stop, character in enumerate(text): if in_string: if in_unicode_escape: if character in self.hexadecimals: in_unicode_escape -= 1 if not in_unicode_escape: in_escape = False else: in_unicode_escape = 0 in_escape = False
elif in_escape: if character == 'u': in_unicode_escape = 4 else: in_escape = False
elif character == '\\': in_escape = True
elif character == '"': queue.append((start, String.Double, text[start:stop + 1])) in_string = False in_escape = False in_unicode_escape = 0
continue
elif in_whitespace: if character in self.whitespaces: continue
if queue: queue.append((start, Whitespace, text[start:stop])) else: yield start, Whitespace, text[start:stop] in_whitespace = False # Fall through so the new character can be evaluated.
elif in_constant: if character in self.constants: continue
yield start, Keyword.Constant, text[start:stop] in_constant = False # Fall through so the new character can be evaluated.
elif in_number: if character in self.integers: continue elif character in self.floats: in_float = True continue
if in_float: yield start, Number.Float, text[start:stop] else: yield start, Number.Integer, text[start:stop] in_number = False in_float = False # Fall through so the new character can be evaluated.
elif in_punctuation: if character in self.punctuations: continue
yield start, Punctuation, text[start:stop] in_punctuation = False # Fall through so the new character can be evaluated.
elif in_comment_single: if character != '\n': continue
if queue: queue.append((start, Comment.Single, text[start:stop])) else: yield start, Comment.Single, text[start:stop]
in_comment_single = False # Fall through so the new character can be evaluated.
elif in_comment_multiline: if character == '*': expecting_second_comment_closer = True elif expecting_second_comment_closer: expecting_second_comment_closer = False if character == '/': if queue: queue.append((start, Comment.Multiline, text[start:stop + 1])) else: yield start, Comment.Multiline, text[start:stop + 1]
in_comment_multiline = False
continue
elif expecting_second_comment_opener: expecting_second_comment_opener = False if character == '/': in_comment_single = True continue elif character == '*': in_comment_multiline = True continue
# Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
yield start, Error, text[start:stop] # Fall through so the new character can be evaluated.
start = stop
if character == '"': in_string = True
elif character in self.whitespaces: in_whitespace = True
elif character in {'f', 'n', 't'}: # The first letters of true|false|null # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_constant = True
elif character in self.integers: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_number = True
elif character == ':': # Yield from the queue. Replace string token types. for _start, _token, _text in queue: # There can be only three types of tokens before a ':': # Whitespace, Comment, or a quoted string. # # If it's a quoted string we emit Name.Tag. # Otherwise, we yield the original token. # # In all other cases this would be invalid JSON, # but this is not a validating JSON lexer, so it's OK. if _token is String.Double: yield _start, Name.Tag, _text else: yield _start, _token, _text queue.clear()
in_punctuation = True
elif character in self.punctuations: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_punctuation = True
elif character == '/': # This is the beginning of a comment. expecting_second_comment_opener = True
else: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
yield start, Error, character
# Yield any remaining text. yield from queue if in_string: yield start, Error, text[start:] elif in_float: yield start, Number.Float, text[start:] elif in_number: yield start, Number.Integer, text[start:] elif in_constant: yield start, Keyword.Constant, text[start:] elif in_whitespace: yield start, Whitespace, text[start:] elif in_punctuation: yield start, Punctuation, text[start:] elif in_comment_single: yield start, Comment.Single, text[start:] elif in_comment_multiline: yield start, Error, text[start:] elif expecting_second_comment_opener: yield start, Error, text[start:]
class JsonBareObjectLexer(JsonLexer): """ For JSON data structures (with missing object curly braces).
.. deprecated:: 2.8.0
Behaves the same as `JsonLexer` now. """
name = 'JSONBareObject' aliases = [] filenames = [] mimetypes = [] version_added = '2.2'
class JsonLdLexer(JsonLexer): """ For JSON-LD linked data. """
name = 'JSON-LD' url = 'https://json-ld.org/' aliases = ['jsonld', 'json-ld'] filenames = ['*.jsonld'] mimetypes = ['application/ld+json'] version_added = '2.0'
json_ld_keywords = { f'"@{keyword}"' for keyword in ( 'base', 'container', 'context', 'direction', 'graph', 'id', 'import', 'included', 'index', 'json', 'language', 'list', 'nest', 'none', 'prefix', 'propagate', 'protected', 'reverse', 'set', 'type', 'value', 'version', 'vocab', ) }
def get_tokens_unprocessed(self, text): for start, token, value in super().get_tokens_unprocessed(text): if token is Name.Tag and value in self.json_ld_keywords: yield start, Name.Decorator, value else: yield start, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135""" pygments.lexers.dax ~~~~~~~~~~~~~~~~~~~
Lexer for LilyPond.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Punctuation, Whitespace,\ Name, Operator, String, Number, Text
__all__ = ['DaxLexer']
class DaxLexer(RegexLexer): """ Lexer for Power BI DAX Referenced from: https://github.com/sql-bi/SyntaxHighlighterBrushDax """ name = 'Dax' aliases = ['dax'] filenames = ['*.dax'] url = 'https://learn.microsoft.com/en-us/dax/dax-function-reference' mimetypes = [] version_added = '2.15'
tokens = { 'root': [ (r'\s+', Whitespace), (r"--.*\n?", Comment.Single), # Comment: Double dash comment (r"//.*\n?", Comment.Single), # Comment: Double backslash comment (r'/\*', Comment.Multiline, 'multiline-comments'), (words(('abs', 'accrint', 'accrintm', 'acos', 'acosh', 'acot', 'acoth', 'addcolumns', 'addmissingitems', 'all', 'allcrossfiltered', 'allexcept', 'allnoblankrow', 'allselected', 'amordegrc', 'amorlinc', 'and','approximatedistinctcount', 'asin', 'asinh', 'atan', 'atanh', 'average', 'averagea', 'averagex', 'beta.dist', 'beta.inv', 'bitand', 'bitlshift', 'bitor', 'bitrshift', 'bitxor', 'blank', 'calculate', 'calculatetable', 'calendar', 'calendarauto', 'ceiling', 'chisq.dist', 'chisq.dist.rt', 'chisq.inv', 'chisq.inv.rt', 'closingbalancemonth', 'closingbalancequarter', 'closingbalanceyear', 'coalesce', 'columnstatistics', 'combin', 'combina', 'combinevalues', 'concatenate', 'concatenatex', 'confidence.norm', 'confidence.t', 'contains', 'containsrow', 'containsstring', 'containsstringexact', 'convert', 'cos', 'cosh', 'cot', 'coth', 'count', 'counta', 'countax', 'countblank', 'countrows', 'countx', 'coupdaybs', 'coupdays', 'coupdaysnc', 'coupncd', 'coupnum', 'couppcd', 'crossfilter', 'crossjoin', 'cumipmt', 'cumprinc', 'currency', 'currentgroup', 'customdata', 'datatable', 'date', 'dateadd', 'datediff', 'datesbetween', 'datesinperiod', 'datesmtd', 'datesqtd', 'datesytd', 'datevalue', 'day', 'db', 'ddb', 'degrees', 'detailrows', 'disc', 'distinct', 'distinctcount', 'distinctcountnoblank', 'divide', 'dollarde', 'dollarfr', 'duration', 'earlier', 'earliest', 'edate', 'effect', 'endofmonth', 'endofquarter', 'endofyear', 'eomonth', 'error', 'evaluateandlog', 'even', 'exact', 'except', 'exp', 'expon.dist', 'fact', 'false', 'filter', 'filters', 'find', 'firstdate', 'firstnonblank', 'firstnonblankvalue', 'fixed', 'floor', 'format', 'fv', 'gcd', 'generate', 'generateall', 'generateseries', 'geomean', 'geomeanx', 'groupby', 'hash', 'hasonefilter', 'hasonevalue', 'hour', 'if', 'if.eager', 'iferror', 'ignore', 'index', 'int', 'intersect', 'intrate', 'ipmt', 'isafter', 'isblank', 'iscrossfiltered', 'isempty', 'iserror', 'iseven', 'isfiltered', 'isinscope', 'islogical', 'isnontext', 'isnumber', 'iso.ceiling', 'isodd', 'isonorafter', 'ispmt', 'isselectedmeasure', 'issubtotal', 'istext', 'keepfilters', 'keywordmatch', 'lastdate', 'lastnonblank', 'lastnonblankvalue', 'lcm', 'left', 'len', 'linest', 'linestx', 'ln', 'log', 'log10', 'lookupvalue', 'lower', 'max', 'maxa', 'maxx', 'mduration', 'median', 'medianx', 'mid', 'min', 'mina', 'minute', 'minx', 'mod', 'month', 'mround', 'nameof', 'naturalinnerjoin', 'naturalleftouterjoin', 'networkdays', 'nextday', 'nextmonth', 'nextquarter', 'nextyear', 'nominal', 'nonvisual', 'norm.dist', 'norm.inv', 'norm.s.dist', 'norm.s.inv', 'not', 'now', 'nper', 'odd', 'oddfprice', 'oddfyield', 'oddlprice', 'oddlyield', 'offset', 'openingbalancemonth', 'openingbalancequarter', 'openingbalanceyear', 'or', 'orderby', 'parallelperiod', 'partitionby', 'path', 'pathcontains', 'pathitem', 'pathitemreverse', 'pathlength', 'pduration', 'percentile.exc', 'percentile.inc', 'percentilex.exc', 'percentilex.inc', 'permut', 'pi', 'pmt', 'poisson.dist', 'power', 'ppmt', 'previousday', 'previousmonth', 'previousquarter', 'previousyear', 'price', 'pricedisc', 'pricemat', 'product', 'productx', 'pv', 'quarter', 'quotient', 'radians', 'rand', 'randbetween', 'rank.eq', 'rankx', 'rate', 'received', 'related', 'relatedtable', 'removefilters', 'replace', 'rept', 'right', 'rollup', 'rollupaddissubtotal', 'rollupgroup', 'rollupissubtotal', 'round', 'rounddown', 'roundup', 'row', 'rri', 'sameperiodlastyear', 'sample', 'sampleaxiswithlocalminmax', 'search', 'second', 'selectcolumns', 'selectedmeasure', 'selectedmeasureformatstring', 'selectedmeasurename', 'selectedvalue', 'sign', 'sin', 'sinh', 'sln', 'sqrt', 'sqrtpi', 'startofmonth', 'startofquarter', 'startofyear', 'stdev.p', 'stdev.s', 'stdevx.p', 'stdevx.s', 'substitute', 'substitutewithindex', 'sum', 'summarize', 'summarizecolumns', 'sumx', 'switch', 'syd', 't.dist', 't.dist.2t', 't.dist.rt', 't.inv', 't.inv.2t', 'tan', 'tanh', 'tbilleq', 'tbillprice', 'tbillyield', 'time', 'timevalue', 'tocsv', 'today', 'tojson', 'topn', 'topnperlevel', 'topnskip', 'totalmtd', 'totalqtd', 'totalytd', 'treatas', 'trim', 'true', 'trunc', 'unichar', 'unicode', 'union', 'upper', 'userculture', 'userelationship', 'username', 'userobjectid', 'userprincipalname', 'utcnow', 'utctoday', 'value', 'values', 'var.p', 'var.s', 'varx.p', 'varx.s', 'vdb', 'weekday', 'weeknum', 'window', 'xirr', 'xnpv', 'year', 'yearfrac', 'yield', 'yielddisc', 'yieldmat'), prefix=r'(?i)', suffix=r'\b'), Name.Function), #Functions
(words(('at','asc','boolean','both','by','create','currency', 'datetime','day','define','desc','double', 'evaluate','false','integer','measure', 'month','none','order','return','single','start','string', 'table','true','var','year'), prefix=r'(?i)', suffix=r'\b'), Name.Builtin), # Keyword
(r':=|[-+*\/=^]', Operator), (r'\b(IN|NOT)\b', Operator.Word), (r'"', String, 'string'), #StringLiteral (r"'(?:[^']|'')*'(?!')(?:\[[ \w]+\])?|\w+\[[ \w]+\]", Name.Attribute), # Column reference (r"\[[ \w]+\]", Name.Attribute), #Measure reference (r'(?<!\w)(\d+\.?\d*|\.\d+\b)', Number),# Number (r'[\[\](){}`,.]', Punctuation), #Parenthesis (r'.*\n', Text),
], 'multiline-comments': [ (r'/\*', Comment.Multiline, 'multiline-comments'), (r'\*/', Comment.Multiline, '#pop'), (r'[^/*]+', Comment.Multiline), (r'[/*]', Comment.Multiline) ], 'string': [ (r'""', String.Escape), (r'"', String, '#pop'), (r'[^"]+', String), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120""" pygments.lexers.devicetree ~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Devicetree language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, default, wordsfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace
__all__ = ['DevicetreeLexer']
class DevicetreeLexer(RegexLexer): """ Lexer for Devicetree files. """
name = 'Devicetree' url = 'https://www.devicetree.org/' aliases = ['devicetree', 'dts'] filenames = ['*.dts', '*.dtsi'] mimetypes = ['text/x-c'] version_added = '2.7'
#: optional Whitespace or /*...*/ style comment _ws = r'\s*(?:/[*][^*/]*?[*]/\s*)*'
tokens = { 'macro': [ # Include preprocessor directives (C style): (r'(#include)(' + _ws + r')([^\n]+)', bygroups(Comment.Preproc, Comment.Multiline, Comment.PreprocFile)), # Define preprocessor directives (C style): (r'(#define)(' + _ws + r')([^\n]+)', bygroups(Comment.Preproc, Comment.Multiline, Comment.Preproc)), # devicetree style with file: (r'(/[^*/{]+/)(' + _ws + r')("[^\n{]+")', bygroups(Comment.Preproc, Comment.Multiline, Comment.PreprocFile)), # devicetree style with property: (r'(/[^*/{]+/)(' + _ws + r')([^\n;{]*)([;]?)', bygroups(Comment.Preproc, Comment.Multiline, Comment.Preproc, Punctuation)), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'\\\n', Text), # line continuation (r'//(\n|[\w\W]*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*][\w\W]*?[*](\\\n)?/', Comment.Multiline), # Open until EOF, so no ending delimiter (r'/(\\\n)?[*][\w\W]*', Comment.Multiline), ], 'statements': [ (r'(L?)(")', bygroups(String.Affix, String), 'string'), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (r'([^\s{}/*]*)(\s*)(:)', bygroups(Name.Label, Text, Punctuation), '#pop'), (words(('compatible', 'model', 'phandle', 'status', '#address-cells', '#size-cells', 'reg', 'virtual-reg', 'ranges', 'dma-ranges', 'device_type', 'name'), suffix=r'\b'), Keyword.Reserved), (r'([~!%^&*+=|?:<>/#-])', Operator), (r'[(){},.\]]', Punctuation), (r'\[', Punctuation, 'bytestring'), (r'[a-zA-Z_][\w-]*(?=(?:\s*,' + _ws + r'[a-zA-Z_][\w-]*)*' + _ws + r'[=;])', Name), (r'[a-zA-Z_]\w*', Name.Attribute), ], 'root': [ include('whitespace'), include('macro'), # Overlay/fragment: &label { ... } or &{/path/to/node} { ... } (r'(&)(?:([A-Za-z_]\w*)|(\{)([^}]+)(\}))(' + _ws + r')(\{)', bygroups(Operator, Name.Function, Punctuation, Name.Namespace, Punctuation, Comment.Multiline, Punctuation), 'node'), # Nodes (r'([^/*@\s&]+|/)(@?)((?:0x)?[0-9a-fA-F,]*)(' + _ws + r')(\{)', bygroups(Name.Function, Operator, Number.Integer, Comment.Multiline, Punctuation), 'node'),
default('statement'), ], 'statement': [ include('whitespace'), include('statements'), (';', Punctuation, '#pop'), ], 'node': [ include('whitespace'), include('macro'), # Overlay/fragment: &label { ... } or &{/path/to/node} { ... } (r'(&)(?:([A-Za-z_]\w*)|(\{)([^}]+)(\}))(' + _ws + r')(\{)', bygroups(Operator, Name.Function, Punctuation, Name.Namespace, Punctuation, Comment.Multiline, Punctuation), '#push'), (r'([^/*@\s&]+|/)(@?)((?:0x)?[0-9a-fA-F,]*)(' + _ws + r')(\{)', bygroups(Name.Function, Operator, Number.Integer, Comment.Multiline, Punctuation), '#push'),
include('statements'),
(r'\};', Punctuation, '#pop'), (';', Punctuation), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ], 'bytestring': [ (r'\]', Punctuation, '#pop'), (r'[0-9a-fA-F]{2}', Number.Hex), (r'\s+', Whitespace), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169""" pygments.lexers.diff ~~~~~~~~~~~~~~~~~~~~
Lexers for diff/patch formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, Generic, \ Literal, Whitespace
__all__ = ['DiffLexer', 'DarcsPatchLexer', 'WDiffLexer']
class DiffLexer(RegexLexer): """ Lexer for unified or context-style diffs or patches. """
name = 'Diff' aliases = ['diff', 'udiff'] filenames = ['*.diff', '*.patch'] mimetypes = ['text/x-diff', 'text/x-patch'] url = 'https://en.wikipedia.org/wiki/Diff' version_added = ''
tokens = { 'root': [ (r'( )(.*)(\n)', bygroups(Whitespace, Text, Whitespace)), (r'(!.*|---)(\n)', bygroups(Generic.Strong, Whitespace)), (r'((?:< |-).*)(\n)', bygroups(Generic.Deleted, Whitespace)), (r'((?:> |\+).*)(\n)', bygroups(Generic.Inserted, Whitespace)), ( r'(@.*|\d(?:,\d+)?(?:a|c|d)\d+(?:,\d+)?)(\n)', bygroups(Generic.Subheading, Whitespace), ), (r'((?:[Ii]ndex|diff).*)(\n)', bygroups(Generic.Heading, Whitespace)), (r'(=.*)(\n)', bygroups(Generic.Heading, Whitespace)), (r'(.*)(\n)', bygroups(Text, Whitespace)), ] }
def analyse_text(text): if text[:7] == 'Index: ': return True if text[:5] == 'diff ': return True if text[:4] == '--- ': return 0.9
class DarcsPatchLexer(RegexLexer): """ DarcsPatchLexer is a lexer for the various versions of the darcs patch format. Examples of this format are derived by commands such as ``darcs annotate --patch`` and ``darcs send``. """
name = 'Darcs Patch' aliases = ['dpatch'] filenames = ['*.dpatch', '*.darcspatch'] url = 'https://darcs.net' version_added = '0.10'
DPATCH_KEYWORDS = ('hunk', 'addfile', 'adddir', 'rmfile', 'rmdir', 'move', 'replace')
tokens = { 'root': [ (r'<', Operator), (r'>', Operator), (r'\{', Operator), (r'\}', Operator), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)(\])', bygroups(Operator, Keyword, Name, Whitespace, Name, Operator, Literal.Date, Whitespace, Operator)), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)', bygroups(Operator, Keyword, Name, Whitespace, Name, Operator, Literal.Date, Whitespace), 'comment'), (r'New patches:', Generic.Heading), (r'Context:', Generic.Heading), (r'Patch bundle hash:', Generic.Heading), (r'(\s*)({})(.*)(\n)'.format('|'.join(DPATCH_KEYWORDS)), bygroups(Whitespace, Keyword, Text, Whitespace)), (r'\+', Generic.Inserted, "insert"), (r'-', Generic.Deleted, "delete"), (r'(.*)(\n)', bygroups(Text, Whitespace)), ], 'comment': [ (r'[^\]].*\n', Comment), (r'\]', Operator, "#pop"), ], 'specialText': [ # darcs add [_CODE_] special operators for clarity (r'\n', Whitespace, "#pop"), # line-based (r'\[_[^_]*_]', Operator), ], 'insert': [ include('specialText'), (r'\[', Generic.Inserted), (r'[^\n\[]+', Generic.Inserted), ], 'delete': [ include('specialText'), (r'\[', Generic.Deleted), (r'[^\n\[]+', Generic.Deleted), ], }
class WDiffLexer(RegexLexer): """ A wdiff lexer.
Note that:
* It only works with normal output (without options like ``-l``). * If the target files contain "[-", "-]", "{+", or "+}", especially they are unbalanced, the lexer will get confused. """
name = 'WDiff' url = 'https://www.gnu.org/software/wdiff/' aliases = ['wdiff'] filenames = ['*.wdiff'] mimetypes = [] version_added = '2.2'
flags = re.MULTILINE | re.DOTALL
# We can only assume "[-" after "[-" before "-]" is `nested`, # for instance wdiff to wdiff outputs. We have no way to # distinct these marker is of wdiff output from original text.
ins_op = r"\{\+" ins_cl = r"\+\}" del_op = r"\[\-" del_cl = r"\-\]" normal = r'[^{}[\]+-]+' # for performance tokens = { 'root': [ (ins_op, Generic.Inserted, 'inserted'), (del_op, Generic.Deleted, 'deleted'), (normal, Text), (r'.', Text), ], 'inserted': [ (ins_op, Generic.Inserted, '#push'), (del_op, Generic.Inserted, '#push'), (del_cl, Generic.Inserted, '#pop'),
(ins_cl, Generic.Inserted, '#pop'), (normal, Generic.Inserted), (r'.', Generic.Inserted), ], 'deleted': [ (del_op, Generic.Deleted, '#push'), (ins_op, Generic.Deleted, '#push'), (ins_cl, Generic.Deleted, '#pop'),
(del_cl, Generic.Deleted, '#pop'), (normal, Generic.Deleted), (r'.', Generic.Deleted), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109""" pygments.lexers.dns ~~~~~~~~~~~~~~~~~~~
Pygments lexers for DNS
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace, Literalfrom pygments.lexer import RegexLexer, bygroups, include
__all__ = ['DnsZoneLexer']
CLASSES = [ "IN", "CS", "CH", "HS",]
CLASSES_RE = "(" + "|".join(CLASSES) + ')'
class DnsZoneLexer(RegexLexer):
""" Lexer for DNS zone file """
flags = re.MULTILINE
name = 'Zone' aliases = ['zone'] filenames = [ "*.zone" ] url = "https://datatracker.ietf.org/doc/html/rfc1035" mimetypes = ['text/dns'] version_added = '2.16'
tokens = { 'root': [ # Empty/comment line: (r'([ \t]*)(;.*)(\n)', bygroups(Whitespace, Comment.Single, Whitespace)), # Special directives: (r'^\$ORIGIN\b', Keyword, 'values'), (r'^\$TTL\b', Keyword, 'values'), (r'^\$INCLUDE\b', Comment.Preproc, 'include'), # TODO, $GENERATE https://bind9.readthedocs.io/en/v9.18.14/chapter3.html#soa-rr (r'^\$[A-Z]+\b', Keyword, 'values'), # Records: # <domain-name> [<TTL>] [<class>] <type> <RDATA> [<comment>] (r'^(@)([ \t]+)(?:([0-9]+[smhdw]?)([ \t]+))?(?:' + CLASSES_RE + "([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Operator, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), (r'^([^ \t\n]*)([ \t]+)(?:([0-9]+[smhdw]?)([ \t]+))?(?:' + CLASSES_RE + "([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), # <domain-name> [<class>] [<TTL>] <type> <RDATA> [<comment>] (r'^(Operator)([ \t]+)(?:' + CLASSES_RE + "([ \t]+))?(?:([0-9]+[smhdw]?)([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), (r'^([^ \t\n]*)([ \t]+)(?:' + CLASSES_RE + "([ \t]+))?(?:([0-9]+[smhdw]?)([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), ], # Parsing values: 'values': [ (r'\n', Whitespace, "#pop"), (r'\(', Punctuation, 'nested'), include('simple-value'), ], # Parsing nested values (...): 'nested': [ (r'\)', Punctuation, "#pop"), include('multiple-simple-values'), ], # Parsing values: 'simple-value': [ (r'(;.*)', bygroups(Comment.Single)), (r'[ \t]+', Whitespace), (r"@\b", Operator), ('"', String, 'string'), (r'[0-9]+[smhdw]?$', Number.Integer), (r'([0-9]+[smhdw]?)([ \t]+)', bygroups(Number.Integer, Whitespace)), (r'\S+', Literal), ], 'multiple-simple-values': [ include('simple-value'), (r'[\n]+', Whitespace), ], 'include': [ (r'([ \t]+)([^ \t\n]+)([ \t]+)([-\._a-zA-Z]+)([ \t]+)(;.*)?$', bygroups(Whitespace, Comment.PreprocFile, Whitespace, Name, Whitespace, Comment.Single), '#pop'), (r'([ \t]+)([^ \t\n]+)([ \t\n]+)$', bygroups(Whitespace, Comment.PreprocFile, Whitespace), '#pop'), ], "string": [ (r'\\"', String), (r'"', String, "#pop"), (r'[^"]+', String), ] }
def analyse_text(text): return text.startswith("$ORIGIN")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873""" pygments.lexers.dotnet ~~~~~~~~~~~~~~~~~~~~~~
Lexers for .net languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""import re
from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \ using, this, default, wordsfrom pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ Name, String, Number, Literal, Other, Whitespacefrom pygments.util import get_choice_optfrom pygments import unistring as uni
from pygments.lexers.html import XmlLexer
__all__ = ['CSharpLexer', 'NemerleLexer', 'BooLexer', 'VbNetLexer', 'CSharpAspxLexer', 'VbNetAspxLexer', 'FSharpLexer', 'XppLexer']
class CSharpLexer(RegexLexer): """ For C# source code.
Additional options accepted:
`unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``.
.. versionadded:: 0.8 """
name = 'C#' url = 'https://docs.microsoft.com/en-us/dotnet/csharp/' aliases = ['csharp', 'c#', 'cs'] filenames = ['*.cs'] mimetypes = ['text/x-csharp'] # inferred version_added = ''
flags = re.MULTILINE | re.DOTALL
# for the range of allowed unicode characters in identifiers, see # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = { 'none': r'@?[_a-zA-Z]\w*', 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), }
tokens = {} token_variants = True
for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ include('numbers'), # method names (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, Punctuation)), (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Whitespace), (words(( '>>>=', '>>=', '<<=', '<=', '>=', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '??=', '=>', '??', '?.', '!=', '==', '&&', '||', '>>>', '>>', '<<', '++', '--', '+', '-', '*', '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', )), Operator), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'[()\[\];:,.]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b(.*?)(\n)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Comment.Preproc, Whitespace)), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)), (words(( 'abstract', 'as', 'async', 'await', 'base', 'break', 'by', 'case', 'catch', 'checked', 'const', 'continue', 'default', 'delegate', 'do', 'else', 'enum', 'event', 'explicit', 'extern', 'false', 'finally', 'fixed', 'for', 'foreach', 'goto', 'if', 'implicit', 'in', 'interface', 'internal', 'is', 'let', 'lock', 'new', 'null', 'on', 'operator', 'out', 'override', 'params', 'private', 'protected', 'public', 'readonly', 'ref', 'return', 'sealed', 'sizeof', 'stackalloc', 'static', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'unchecked', 'unsafe', 'virtual', 'void', 'while', 'get', 'set', 'new', 'partial', 'yield', 'add', 'remove', 'value', 'alias', 'ascending', 'descending', 'from', 'group', 'into', 'orderby', 'select', 'thenby', 'where', 'join', 'equals', 'record', 'allows', 'and', 'init', 'managed', 'nameof', 'nint', 'not', 'notnull', 'nuint', 'or', 'scoped', 'unmanaged', 'when', 'with' ), suffix=r'\b'), Keyword), # version 1: assumes that 'file' is the only contextual keyword # that is a class modifier (r'(file)(\s+)(record|class|abstract|enum|new|sealed|static)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|dynamic|float|int|long|object|' r'sbyte|short|string|uint|ulong|ushort|var)\b\??', Keyword.Type), (r'(class|struct)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (cs_ident, Name), ], 'numbers_int': [ (r"0[xX][0-9a-fA-F]+(([uU][lL]?)|[lL][uU]?)?", Number.Hex), (r"0[bB][01]+(([uU][lL]?)|[lL][uU]?)?", Number.Bin), (r"[0-9]+(([uU][lL]?)|[lL][uU]?)?", Number.Integer), ], 'numbers_float': [ (r"([0-9]+\.[0-9]+([eE][+-]?[0-9]+)?[fFdDmM]?)|" r"(\.[0-9]+([eE][+-]?[0-9]+)?[fFdDmM]?)|" r"([0-9]+([eE][+-]?[0-9]+)[fFdDmM]?)|" r"([0-9]+[fFdDmM])", Number.Float), ], 'numbers': [ include('numbers_float'), include('numbers_int'), ], 'class': [ (cs_ident, Name.Class, '#pop'), default('#pop'), ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop'), ] }
def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
class NemerleLexer(RegexLexer): """ For Nemerle source code.
Additional options accepted:
`unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``. """
name = 'Nemerle' url = 'http://nemerle.org' aliases = ['nemerle'] filenames = ['*.n'] mimetypes = ['text/x-nemerle'] # inferred version_added = '1.5'
flags = re.MULTILINE | re.DOTALL
# for the range of allowed unicode characters in identifiers, see # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = { 'none': r'@?[_a-zA-Z]\w*', 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), }
tokens = {} token_variants = True
for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ # method names (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, \ Punctuation)), (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Whitespace), (r'(\$)(\s*)(")', bygroups(String, Whitespace, String), 'splice-string'), (r'(\$)(\s*)(<#)', bygroups(String, Whitespace, String), 'splice-string2'), (r'<#', String, 'recursive-string'),
(r'(<\[)(\s*)(' + cs_ident + ':)?', bygroups(Keyword, Whitespace, Keyword)), (r'\]\>', Keyword),
# quasiquotation only (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'),
(r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number), (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b', bygroups(Comment.Preproc, Whitespace, Comment.Preproc), 'preproc'), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(abstract|and|as|base|catch|def|delegate|' r'enum|event|extern|false|finally|' r'fun|implements|interface|internal|' r'is|macro|match|matches|module|mutable|new|' r'null|out|override|params|partial|private|' r'protected|public|ref|sealed|static|' r'syntax|this|throw|true|try|type|typeof|' r'virtual|volatile|when|where|with|' r'assert|assert2|async|break|checked|continue|do|else|' r'ensures|for|foreach|if|late|lock|new|nolate|' r'otherwise|regexp|repeat|requires|return|surroundwith|' r'unchecked|unless|using|while|yield)\b', Keyword), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|' r'short|string|uint|ulong|ushort|void|array|list)\b\??', Keyword.Type), (r'(:>?)(\s*)(' + cs_ident + r'\??)', bygroups(Punctuation, Whitespace, Keyword.Type)), (r'(class|struct|variant|module)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (cs_ident, Name), ], 'class': [ (cs_ident, Name.Class, '#pop') ], 'preproc': [ (r'\w+', Comment.Preproc), (r'[ \t]+', Whitespace), (r'\n', Whitespace, '#pop') ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop') ], 'splice-string': [ (r'[^"$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'\\"', String), (r'"', String, '#pop') ], 'splice-string2': [ (r'[^#<>$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'recursive-string': [ (r'[^#<>]', String), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'splice-string-content': [ (r'if|match', Keyword), (r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation), (cs_ident, Name), (r'\d+', Number), (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop') ] }
def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
def analyse_text(text): """Nemerle is quite similar to Python, but @if is relatively uncommon elsewhere.""" result = 0
if '@if' in text: result += 0.1
return result
class BooLexer(RegexLexer): """ For Boo source code. """
name = 'Boo' url = 'https://github.com/boo-lang/boo' aliases = ['boo'] filenames = ['*.boo'] mimetypes = ['text/x-boo'] version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace), (r'(#|//).*$', Comment.Single), (r'/[*]', Comment.Multiline, 'comment'), (r'[]{}:(),.;[]', Punctuation), (r'(\\)(\n)', bygroups(Text, Whitespace)), (r'\\', Text), (r'(in|is|and|or|not)\b', Operator.Word), (r'/(\\\\|\\[^\\]|[^/\\\s])/', String.Regex), (r'@/(\\\\|\\[^\\]|[^/\\])*/', String.Regex), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'(as|abstract|callable|constructor|destructor|do|import|' r'enum|event|final|get|interface|internal|of|override|' r'partial|private|protected|public|return|set|static|' r'struct|transient|virtual|yield|super|and|break|cast|' r'continue|elif|else|ensure|except|for|given|goto|if|in|' r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|' r'while|from|as)\b', Keyword), (r'def(?=\s+\(.*?\))', Keyword), (r'(def)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(namespace)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|' r'assert|checked|enumerate|filter|getter|len|lock|map|' r'matrix|max|min|normalArrayIndexing|print|property|range|' r'rawArrayIndexing|required|typeof|unchecked|using|' r'yieldAll|zip)\b', Name.Builtin), (r'"""(\\\\|\\"|.*?)"""', String.Double), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_]\w*', Name), (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float), (r'[0-9][0-9.]*(ms?|d|h|s)', Number), (r'0\d+', Number.Oct), (r'0x[a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+', Number.Integer), ], 'comment': [ ('/[*]', Comment.Multiline, '#push'), ('[*]/', Comment.Multiline, '#pop'), ('[^/*]', Comment.Multiline), ('[*/]', Comment.Multiline) ], 'funcname': [ (r'[a-zA-Z_]\w*', Name.Function, '#pop') ], 'classname': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'namespace': [ (r'[a-zA-Z_][\w.]*', Name.Namespace, '#pop') ] }
class VbNetLexer(RegexLexer): """ For Visual Basic.NET source code. Also LibreOffice Basic, OpenOffice Basic, and StarOffice Basic. """
name = 'VB.net' url = 'https://docs.microsoft.com/en-us/dotnet/visual-basic/' aliases = ['vb.net', 'vbnet', 'lobas', 'oobas', 'sobas', 'visual-basic', 'visualbasic'] filenames = ['*.vb', '*.bas'] mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?) version_added = ''
uni_name = '[_' + uni.combine('Ll', 'Lt', 'Lm', 'Nl') + ']' + \ '[' + uni.combine('Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'
flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'^\s*<.*?>', Name.Attribute), (r'\s+', Whitespace), (r'\n', Whitespace), (r'(rem\b.*?)(\n)', bygroups(Comment, Whitespace)), (r"('.*?)(\n)", bygroups(Comment, Whitespace)), (r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#Else|#End\s+If|#Const|' r'#ExternalSource.*?\n|#End\s+ExternalSource|' r'#Region.*?\n|#End\s+Region|#ExternalChecksum', Comment.Preproc), (r'[(){}!#,.:]', Punctuation), (r'(Option)(\s+)(Strict|Explicit|Compare)(\s+)' r'(On|Off|Binary|Text)', bygroups(Keyword.Declaration, Whitespace, Keyword.Declaration, Whitespace, Keyword.Declaration)), (words(( 'AddHandler', 'Alias', 'ByRef', 'ByVal', 'Call', 'Case', 'Catch', 'CBool', 'CByte', 'CChar', 'CDate', 'CDec', 'CDbl', 'CInt', 'CLng', 'CObj', 'Continue', 'CSByte', 'CShort', 'CSng', 'CStr', 'CType', 'CUInt', 'CULng', 'CUShort', 'Declare', 'Default', 'Delegate', 'DirectCast', 'Do', 'Each', 'Else', 'ElseIf', 'EndIf', 'Erase', 'Error', 'Event', 'Exit', 'False', 'Finally', 'For', 'Friend', 'Get', 'Global', 'GoSub', 'GoTo', 'Handles', 'If', 'Implements', 'Inherits', 'Interface', 'Let', 'Lib', 'Loop', 'Me', 'MustInherit', 'MustOverride', 'MyBase', 'MyClass', 'Narrowing', 'New', 'Next', 'Not', 'Nothing', 'NotInheritable', 'NotOverridable', 'Of', 'On', 'Operator', 'Option', 'Optional', 'Overloads', 'Overridable', 'Overrides', 'ParamArray', 'Partial', 'Private', 'Protected', 'Public', 'RaiseEvent', 'ReadOnly', 'ReDim', 'RemoveHandler', 'Resume', 'Return', 'Select', 'Set', 'Shadows', 'Shared', 'Single', 'Static', 'Step', 'Stop', 'SyncLock', 'Then', 'Throw', 'To', 'True', 'Try', 'TryCast', 'Wend', 'Using', 'When', 'While', 'Widening', 'With', 'WithEvents', 'WriteOnly'), prefix=r'(?<!\.)', suffix=r'\b'), Keyword), (r'(?<!\.)End\b', Keyword, 'end'), (r'(?<!\.)(Dim|Const)\b', Keyword, 'dim'), (r'(?<!\.)(Function|Sub|Property)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(?<!\.)(Class|Structure|Enum)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(?<!\.)(Module|Namespace|Imports)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|' r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|' r'UShort)\b', Keyword.Type), (r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|' r'Or|OrElse|TypeOf|Xor)\b', Operator.Word), (r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|' r'<=|>=|<>|[-&*/\\^+=<>\[\]]', Operator), ('"', String, 'string'), (r'(_)(\n)', bygroups(Text, Whitespace)), # Line continuation (must be before Name) (uni_name + '[%&@!#$]?', Name), ('#.*?#', Literal.Date), (r'(\d+\.\d*|\d*\.\d+)(F[+-]?[0-9]+)?', Number.Float), (r'\d+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer), ], 'string': [ (r'""', String), (r'"C?', String, '#pop'), (r'[^"]+', String), ], 'dim': [ (uni_name, Name.Variable, '#pop'), default('#pop'), # any other syntax ], 'funcname': [ (uni_name, Name.Function, '#pop'), ], 'classname': [ (uni_name, Name.Class, '#pop'), ], 'namespace': [ (uni_name, Name.Namespace), (r'\.', Name.Namespace), default('#pop'), ], 'end': [ (r'\s+', Whitespace), (r'(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b', Keyword, '#pop'), default('#pop'), ] }
def analyse_text(text): if re.search(r'^\s*(#If|Module|Namespace)', text, re.MULTILINE): return 0.5
class GenericAspxLexer(RegexLexer): """ Lexer for ASP.NET pages. """
name = 'aspx-gen' filenames = [] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet'
flags = re.DOTALL
tokens = { 'root': [ (r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)), (r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer), Other, using(XmlLexer))), (r'(.+?)(?=<)', using(XmlLexer)), (r'.+', using(XmlLexer)), ], }
# TODO support multiple languages within the same source fileclass CSharpAspxLexer(DelegatingLexer): """ Lexer for highlighting C# within ASP.NET pages. """
name = 'aspx-cs' aliases = ['aspx-cs'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet' version_added = ''
def __init__(self, **options): super().__init__(CSharpLexer, GenericAspxLexer, **options)
def analyse_text(text): if re.search(r'Page\s*Language="C#"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None: return 0.15
class VbNetAspxLexer(DelegatingLexer): """ Lexer for highlighting Visual Basic.net within ASP.NET pages. """
name = 'aspx-vb' aliases = ['aspx-vb'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet' version_added = ''
def __init__(self, **options): super().__init__(VbNetLexer, GenericAspxLexer, **options)
def analyse_text(text): if re.search(r'Page\s*Language="Vb"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None: return 0.15
# Very close to functional.OcamlLexerclass FSharpLexer(RegexLexer): """ For the F# language (version 3.0). """
name = 'F#' url = 'https://fsharp.org/' aliases = ['fsharp', 'f#'] filenames = ['*.fs', '*.fsi', '*.fsx'] mimetypes = ['text/x-fsharp'] version_added = '1.5'
keywords = [ 'abstract', 'as', 'assert', 'base', 'begin', 'class', 'default', 'delegate', 'do!', 'do', 'done', 'downcast', 'downto', 'elif', 'else', 'end', 'exception', 'extern', 'false', 'finally', 'for', 'function', 'fun', 'global', 'if', 'inherit', 'inline', 'interface', 'internal', 'in', 'lazy', 'let!', 'let', 'match', 'member', 'module', 'mutable', 'namespace', 'new', 'null', 'of', 'open', 'override', 'private', 'public', 'rec', 'return!', 'return', 'select', 'static', 'struct', 'then', 'to', 'true', 'try', 'type', 'upcast', 'use!', 'use', 'val', 'void', 'when', 'while', 'with', 'yield!', 'yield', ] # Reserved words; cannot hurt to color them as keywords too. keywords += [ 'atomic', 'break', 'checked', 'component', 'const', 'constraint', 'constructor', 'continue', 'eager', 'event', 'external', 'fixed', 'functor', 'include', 'method', 'mixin', 'object', 'parallel', 'process', 'protected', 'pure', 'sealed', 'tailcall', 'trait', 'virtual', 'volatile', ] keyopts = [ '!=', '#', '&&', '&', r'\(', r'\)', r'\*', r'\+', ',', r'-\.', '->', '-', r'\.\.', r'\.', '::', ':=', ':>', ':', ';;', ';', '<-', r'<\]', '<', r'>\]', '>', r'\?\?', r'\?', r'\[<', r'\[\|', r'\[', r'\]', '_', '`', r'\{', r'\|\]', r'\|', r'\}', '~', '<@@', '<@', '=', '@>', '@@>', ]
operators = r'[!$%&*+\./:<=>?@^|~-]' word_operators = ['and', 'or', 'not'] prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]' primitives = [ 'sbyte', 'byte', 'char', 'nativeint', 'unativeint', 'float32', 'single', 'float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'decimal', 'unit', 'bool', 'string', 'list', 'exn', 'obj', 'enum', ]
# See http://msdn.microsoft.com/en-us/library/dd233181.aspx and/or # http://fsharp.org/about/files/spec.pdf for reference. Good luck.
tokens = { 'escape-sequence': [ (r'\\[\\"\'ntbrafv]', String.Escape), (r'\\[0-9]{3}', String.Escape), (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\U[0-9a-fA-F]{8}', String.Escape), ], 'root': [ (r'\s+', Whitespace), (r'\(\)|\[\]', Name.Builtin.Pseudo), (r'\b(?<!\.)([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][\w\']*)', Name), (r'(///.*?)(\n)', bygroups(String.Doc, Whitespace)), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'\(\*(?!\))', Comment, 'comment'),
(r'@"', String, 'lstring'), (r'"""', String, 'tqs'), (r'"', String, 'string'),
(r'\b(open|module)(\s+)([\w.]+)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'\b(let!?)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Variable)), (r'\b(type)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Class)), (r'\b(member|override)(\s+)(\w+)(\.)(\w+)', bygroups(Keyword, Whitespace, Name, Punctuation, Name.Function)), (r'\b({})\b'.format('|'.join(keywords)), Keyword), (r'``([^`\n\r\t]|`[^`\n\r\t])+``', Name), (r'({})'.format('|'.join(keyopts)), Operator), (rf'({infix_syms}|{prefix_syms})?{operators}', Operator), (r'\b({})\b'.format('|'.join(word_operators)), Operator.Word), (r'\b({})\b'.format('|'.join(primitives)), Keyword.Type), (r'(#)([ \t]*)(if|endif|else|line|nowarn|light|\d+)\b(.*?)(\n)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Comment.Preproc, Whitespace)),
(r"[^\W\d][\w']*", Name),
(r'\d[\d_]*[uU]?[yslLnQRZINGmM]?', Number.Integer), (r'0[xX][\da-fA-F][\da-fA-F_]*[uU]?[yslLn]?[fF]?', Number.Hex), (r'0[oO][0-7][0-7_]*[uU]?[yslLn]?', Number.Oct), (r'0[bB][01][01_]*[uU]?[yslLn]?', Number.Bin), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)[fFmM]?', Number.Float),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'B?", String.Char), (r"'.'", String.Char), (r"'", Keyword), # a stray quote is another syntax element
(r'@?"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name.Variable), ], 'dotted': [ (r'\s+', Whitespace), (r'\.', Punctuation), (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace), (r'[A-Z][\w\']*', Name, '#pop'), (r'[a-z_][\w\']*', Name, '#pop'), # e.g. dictionary index access default('#pop'), ], 'comment': [ (r'[^(*)@"]+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), # comments cannot be closed within strings in comments (r'@"', String, 'lstring'), (r'"""', String, 'tqs'), (r'"', String, 'string'), (r'[(*)@]', Comment), ], 'string': [ (r'[^\\"]+', String), include('escape-sequence'), (r'\\\n', String), (r'\n', String), # newlines are allowed in any string (r'"B?', String, '#pop'), ], 'lstring': [ (r'[^"]+', String), (r'\n', String), (r'""', String), (r'"B?', String, '#pop'), ], 'tqs': [ (r'[^"]+', String), (r'\n', String), (r'"""B?', String, '#pop'), (r'"', String), ], }
def analyse_text(text): """F# doesn't have that many unique features -- |> and <| are weak indicators.""" result = 0 if '|>' in text: result += 0.05 if '<|' in text: result += 0.05
return result
class XppLexer(RegexLexer):
""" For X++ source code. This is based loosely on the CSharpLexer """
name = 'X++' url = 'https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/dev-ref/xpp-language-reference' aliases = ['xpp', 'x++'] filenames = ['*.xpp'] version_added = '2.15'
flags = re.MULTILINE
XPP_CHARS = ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*') # Temporary, see # https://github.com/thatch/regexlint/pull/49 XPP_CHARS = XPP_CHARS.replace('\x00', '\x01')
OPERATORS = ( '<=', '>=', '+=', '-=', '*=', '/=', '!=', '==', '&&', '||', '>>', '<<', '++', '--', '+', '-', '*', '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', ) KEYWORDS = ('abstract','anytype','as','async','asc','at','avg','break','breakpoint','by','byref','case','catch', 'changecompany','client','container','continue','count','crosscompany','default','delegate', 'delete_from','desc','display','div','do','edit','else','element','eventhandler','exists','false','final', 'firstfast','firstonly','firstonly10','firstonly100','firstonly1000','flush','for','forceliterals', 'forcenestedloop','forceplaceholders','forceselectorder','forupdate','from','group','if','insert_recordset', 'interface','is','join','like','maxof','minof','mod','new','next','nofetch','notexists','null','optimisticlock','order', 'outer','pause','pessimisticlock','print','private','protected','public','repeatableread','retry','return', 'reverse','select','server','setting','static','sum','super','switch','tablelock','this','throw','true','try','ttsabort','ttsbegin', 'ttscommit','update_recordset','validtimestate','void','where','while','window') RUNTIME_FUNCTIONS = ('_duration','abs','acos','any2Date','any2Enum','any2Guid','any2Int','any2Int64','any2Real','any2Str','anytodate', 'anytoenum','anytoguid','anytoint','anytoint64','anytoreal','anytostr','asin','atan','beep','cTerm','char2Num','classIdGet', 'corrFlagGet','corrFlagSet','cos','cosh','curExt','curUserId','date2Num','date2Str','datetime2Str','dayName','dayOfMth', 'dayOfWk','dayOfYr','ddb','decRound','dg','dimOf','endMth','enum2str','exp','exp10','fV','fieldId2Name','fieldId2PName', 'fieldName2Id','frac','funcName','getCurrentPartition','getCurrentPartitionRecId','getPrefix','guid2Str','idg','indexId2Name', 'indexName2Id','int2Str','int642Str','intvMax','intvName','intvNo','intvNorm','log10','logN','match','max','min','mkDate','mthName', 'mthOfYr','newGuid','nextMth','nextQtr','nextYr','num2Char','num2Date','num2Str','pmt','power','prevMth','prevQtr','prevYr', 'prmIsDefault','pt','pv','rate','refPrintAll','round','runAs','sessionId','setPrefix','sin','sinh','sleep','sln','str2Date', 'str2Datetime','str2Enum','str2Guid','str2Int','str2Int64','str2Num','str2Time','strAlpha','strCmp','strColSeq','strDel', 'strFind','strFmt','strIns','strKeep','strLTrim','strLen','strLine','strLwr','strNFind','strPoke','strPrompt','strRTrim', 'strRem','strRep','strScan','strUpr','subStr','syd','systemDateGet','systemDateSet','tableId2Name', 'tableId2PName','tableName2Id','tan','tanh','term','time2Str','timeNow','today','trunc','typeOf','uint2Str','wkOfYr','year') COMPILE_FUNCTIONS = ('attributeStr','classNum','classStr','configurationKeyNum','configurationKeyStr','dataEntityDataSourceStr','delegateStr', 'dimensionHierarchyLevelStr','dimensionHierarchyStr','dimensionReferenceStr','dutyStr','enumCnt','enumLiteralStr','enumNum','enumStr', 'extendedTypeNum','extendedTypeStr','fieldNum','fieldPName','fieldStr','formControlStr','formDataFieldStr','formDataSourceStr', 'formMethodStr','formStr','identifierStr','indexNum','indexStr','licenseCodeNum','licenseCodeStr','literalStr','maxDate','maxInt', 'measureStr','measurementStr','menuItemActionStr','menuItemDisplayStr','menuItemOutputStr','menuStr','methodStr','minInt','privilegeStr', 'queryDatasourceStr','queryMethodStr','queryStr','reportStr','resourceStr','roleStr','ssrsReportStr','staticDelegateStr','staticMethodStr', 'tableCollectionStr','tableFieldGroupStr','tableMethodStr','tableNum','tablePName','tableStaticMethodStr','tableStr','tileStr','varStr', 'webActionItemStr','webDisplayContentItemStr','webFormStr','webMenuStr','webOutputContentItemStr','webReportStr','webSiteTempStr', 'webStaticFileStr','webUrlItemStr','webWebPartStr','webletItemStr','webpageDefStr','websiteDefStr','workflowApprovalStr', 'workflowCategoryStr','workflowTaskStr','workflowTypeStr')
tokens = {}
tokens = { 'root': [ # method names (r'(\s*)\b(else|if)\b([^\n])', bygroups(Whitespace, Keyword, using(this))), # ensure that if is not treated like a function (r'^([ \t]*)((?:' + XPP_CHARS + r'(?:\[\])?\s+)+?)' # return type r'(' + XPP_CHARS + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, Punctuation)), (r'^(\s*)(\[)([^\n]*?)(\])', bygroups(Whitespace, Name.Attribute, Name.Variable.Class, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//[^\n]*?\n', Comment.Single), (r'/[*][^\n]*?[*]/', Comment.Multiline), (r'\n', Whitespace), (words(OPERATORS), Operator), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'[()\[\];:,.#@]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (words(KEYWORDS, suffix=r'\b'), Keyword), (r'(boolean|int|int64|str|real|guid|date)\b\??', Keyword.Type), (r'(class|struct|extends|implements)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'('+XPP_CHARS+')(::)', bygroups(Name.Variable.Class, Punctuation)), (r'(\s*)(\w+)(\s+\w+(,|=)?[^\n]*;)', bygroups(Whitespace, Name.Variable.Class, using(this))), # declaration # x++ specific function to get field should highlight the classname (r'(fieldNum\()('+XPP_CHARS+r')(\s*,\s*)('+XPP_CHARS+r')(\s*\))', bygroups(using(this), Name.Variable.Class, using(this), Name.Property, using(this))), # x++ specific function to get table should highlight the classname (r'(tableNum\()('+XPP_CHARS+r')(\s*\))', bygroups(using(this), Name.Variable.Class, using(this))), (words(RUNTIME_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), (words(COMPILE_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), (XPP_CHARS, Name), ], 'class': [ (XPP_CHARS, Name.Class, '#pop'), default('#pop'), ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + XPP_CHARS + r'|\.)+', Name.Namespace, '#pop'), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970""" pygments.lexers.dsls ~~~~~~~~~~~~~~~~~~~~
Lexers for various domain-specific languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, RegexLexer, bygroups, words, \ include, default, this, using, combinedfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ProtoBufLexer', 'ZeekLexer', 'PuppetLexer', 'RslLexer', 'MscgenLexer', 'VGLLexer', 'AlloyLexer', 'PanLexer', 'CrmshLexer', 'ThriftLexer', 'FlatlineLexer', 'SnowballLexer']
class ProtoBufLexer(RegexLexer): """ Lexer for Protocol Buffer definition files. """
name = 'Protocol Buffer' url = 'https://developers.google.com/protocol-buffers/' aliases = ['protobuf', 'proto'] filenames = ['*.proto'] version_added = '1.4'
tokens = { 'root': [ (r'[ \t]+', Whitespace), (r'[,;{}\[\]()<>]', Punctuation), (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline), (words(( 'import', 'option', 'optional', 'required', 'repeated', 'reserved', 'default', 'packed', 'ctype', 'extensions', 'to', 'max', 'rpc', 'returns', 'oneof', 'syntax'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'fixed32', 'fixed64', 'sfixed32', 'sfixed64', 'float', 'double', 'bool', 'string', 'bytes'), suffix=r'\b'), Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'package'), (r'(message|extend)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'message'), (r'(enum|group|service)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'type'), (r'\".*?\"', String), (r'\'.*?\'', String), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'(\-?(inf|nan))\b', Number.Float), (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex), (r'0[0-7]+[LlUu]*', Number.Oct), (r'\d+[LlUu]*', Number.Integer), (r'[+-=]', Operator), (r'([a-zA-Z_][\w.]*)([ \t]*)(=)', bygroups(Name.Attribute, Whitespace, Operator)), (r'[a-zA-Z_][\w.]*', Name), ], 'package': [ (r'[a-zA-Z_][\w\.]*', Name.Namespace, '#pop'), default('#pop'), ], 'message': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop'), default('#pop'), ], 'type': [ (r'[a-zA-Z_]\w*', Name, '#pop'), default('#pop'), ], }
class ThriftLexer(RegexLexer): """ For Thrift interface definitions. """ name = 'Thrift' url = 'https://thrift.apache.org/' aliases = ['thrift'] filenames = ['*.thrift'] mimetypes = ['application/x-thrift'] version_added = '2.1'
tokens = { 'root': [ include('whitespace'), include('comments'), (r'"', String.Double, combined('stringescape', 'dqs')), (r'\'', String.Single, combined('stringescape', 'sqs')), (r'(namespace)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'namespace'), (r'(enum|union|struct|service|exception)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'((?:(?:[^\W\d]|\$)[\w.\[\]$<>]*\s+)+?)' # return arguments r'((?:[^\W\d]|\$)[\w$]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), include('keywords'), include('numbers'), (r'[&=]', Operator), (r'[:;,{}()<>\[\]]', Punctuation), (r'[a-zA-Z_](\.\w|\w)*', Name), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), ], 'comments': [ (r'#.*$', Comment), (r'//.*?\n', Comment), (r'/\*[\w\W]*?\*/', Comment.Multiline), ], 'stringescape': [ (r'\\([\\nrt"\'])', String.Escape), ], 'dqs': [ (r'"', String.Double, '#pop'), (r'[^\\"\n]+', String.Double), ], 'sqs': [ (r"'", String.Single, '#pop'), (r'[^\\\'\n]+', String.Single), ], 'namespace': [ (r'[a-z*](\.\w|\w)*', Name.Namespace, '#pop'), default('#pop'), ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop'), default('#pop'), ], 'keywords': [ (r'(async|oneway|extends|throws|required|optional)\b', Keyword), (r'(true|false)\b', Keyword.Constant), (r'(const|typedef)\b', Keyword.Declaration), (words(( 'cpp_namespace', 'cpp_include', 'cpp_type', 'java_package', 'cocoa_prefix', 'csharp_namespace', 'delphi_namespace', 'php_namespace', 'py_module', 'perl_package', 'ruby_namespace', 'smalltalk_category', 'smalltalk_prefix', 'xsd_all', 'xsd_optional', 'xsd_nillable', 'xsd_namespace', 'xsd_attrs', 'include'), suffix=r'\b'), Keyword.Namespace), (words(( 'void', 'bool', 'byte', 'i16', 'i32', 'i64', 'double', 'string', 'binary', 'map', 'list', 'set', 'slist', 'senum'), suffix=r'\b'), Keyword.Type), (words(( 'BEGIN', 'END', '__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', 'abstract', 'alias', 'and', 'args', 'as', 'assert', 'begin', 'break', 'case', 'catch', 'class', 'clone', 'continue', 'declare', 'def', 'default', 'del', 'delete', 'do', 'dynamic', 'elif', 'else', 'elseif', 'elsif', 'end', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'ensure', 'except', 'exec', 'finally', 'float', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'import', 'in', 'inline', 'instanceof', 'interface', 'is', 'lambda', 'module', 'native', 'new', 'next', 'nil', 'not', 'or', 'pass', 'public', 'print', 'private', 'protected', 'raise', 'redo', 'rescue', 'retry', 'register', 'return', 'self', 'sizeof', 'static', 'super', 'switch', 'synchronized', 'then', 'this', 'throw', 'transient', 'try', 'undef', 'unless', 'unsigned', 'until', 'use', 'var', 'virtual', 'volatile', 'when', 'while', 'with', 'xor', 'yield'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), ], 'numbers': [ (r'[+-]?(\d+\.\d+([eE][+-]?\d+)?|\.?\d+[eE][+-]?\d+)', Number.Float), (r'[+-]?0x[0-9A-Fa-f]+', Number.Hex), (r'[+-]?[0-9]+', Number.Integer), ], }
class ZeekLexer(RegexLexer): """ For Zeek scripts. """ name = 'Zeek' url = 'https://www.zeek.org/' aliases = ['zeek', 'bro'] filenames = ['*.zeek', '*.bro'] version_added = '2.5'
_hex = r'[0-9a-fA-F]' _float = r'((\d*\.?\d+)|(\d+\.?\d*))([eE][-+]?\d+)?' _h = r'[A-Za-z0-9][-A-Za-z0-9]*'
tokens = { 'root': [ include('whitespace'), include('comments'), include('directives'), include('attributes'), include('types'), include('keywords'), include('literals'), include('operators'), include('punctuation'), (r'((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(?=\s*\()', Name.Function), include('identifiers'), ],
'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), ],
'comments': [ (r'#.*$', Comment), ],
'directives': [ (r'@(load-plugin|load-sigs|load|unload)\b.*$', Comment.Preproc), (r'@(DEBUG|DIR|FILENAME|deprecated|if|ifdef|ifndef|else|endif)\b', Comment.Preproc), (r'(@prefixes)(\s*)((\+?=).*)$', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)), ],
'attributes': [ (words(('redef', 'priority', 'log', 'optional', 'default', 'add_func', 'delete_func', 'expire_func', 'read_expire', 'write_expire', 'create_expire', 'synchronized', 'persistent', 'rotate_interval', 'rotate_size', 'encrypt', 'raw_output', 'mergeable', 'error_handler', 'type_column', 'deprecated'), prefix=r'&', suffix=r'\b'), Keyword.Pseudo), ],
'types': [ (words(('any', 'enum', 'record', 'set', 'table', 'vector', 'function', 'hook', 'event', 'addr', 'bool', 'count', 'double', 'file', 'int', 'interval', 'pattern', 'port', 'string', 'subnet', 'time'), suffix=r'\b'), Keyword.Type),
(r'(opaque)(\s+)(of)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b', bygroups(Keyword.Type, Whitespace, Operator.Word, Whitespace, Keyword.Type)),
(r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)(\s*)\b(record|enum)\b', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Operator, Whitespace, Keyword.Type)),
(r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)', bygroups(Keyword, Whitespace, Name, Whitespace, Operator)),
(r'(redef)(\s+)(record|enum)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b', bygroups(Keyword, Whitespace, Keyword.Type, Whitespace, Name.Class)), ],
'keywords': [ (words(('redef', 'export', 'if', 'else', 'for', 'while', 'return', 'break', 'next', 'continue', 'fallthrough', 'switch', 'default', 'case', 'add', 'delete', 'when', 'timeout', 'schedule'), suffix=r'\b'), Keyword), (r'(print)\b', Keyword), (r'(global|local|const|option)\b', Keyword.Declaration), (r'(module)(\s+)(([A-Za-z_]\w*)(?:::([A-Za-z_]\w*))*)\b', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), ],
'literals': [ (r'"', String, 'string'),
# Not the greatest match for patterns, but generally helps # disambiguate between start of a pattern and just a division # operator. (r'/(?=.*/)', String.Regex, 'regex'),
(r'(T|F)\b', Keyword.Constant),
# Port (r'\d{1,5}/(udp|tcp|icmp|unknown)\b', Number),
# IPv4 Address (r'(\d{1,3}.){3}(\d{1,3})\b', Number),
# IPv6 Address (r'\[([0-9a-fA-F]{0,4}:){2,7}([0-9a-fA-F]{0,4})?((\d{1,3}.){3}(\d{1,3}))?\]', Number),
# Numeric (r'0[xX]' + _hex + r'+\b', Number.Hex), (_float + r'\s*(day|hr|min|sec|msec|usec)s?\b', Number.Float), (_float + r'\b', Number.Float), (r'(\d+)\b', Number.Integer),
# Hostnames (_h + r'(\.' + _h + r')+', String), ],
'operators': [ (r'[!%*/+<=>~|&^-]', Operator), (r'([-+=&|]{2}|[+=!><-]=)', Operator), (r'(in|as|is|of)\b', Operator.Word), (r'\??\$', Operator), ],
'punctuation': [ (r'[{}()\[\],;.]', Punctuation), # The "ternary if", which uses '?' and ':', could instead be # treated as an Operator, but colons are more frequently used to # separate field/identifier names from their types, so the (often) # less-prominent Punctuation is used even with '?' for consistency. (r'[?:]', Punctuation), ],
'identifiers': [ (r'([a-zA-Z_]\w*)(::)', bygroups(Name, Punctuation)), (r'[a-zA-Z_]\w*', Name) ],
'string': [ (r'\\.', String.Escape), (r'%-?[0-9]*(\.[0-9]+)?[DTd-gsx]', String.Escape), (r'"', String, '#pop'), (r'.', String), ],
'regex': [ (r'\\.', String.Escape), (r'/', String.Regex, '#pop'), (r'.', String.Regex), ], }
BroLexer = ZeekLexer
class PuppetLexer(RegexLexer): """ For Puppet configuration DSL. """ name = 'Puppet' url = 'https://puppet.com/' aliases = ['puppet'] filenames = ['*.pp'] version_added = '1.6'
tokens = { 'root': [ include('comments'), include('keywords'), include('names'), include('numbers'), include('operators'), include('strings'),
(r'[]{}:(),;[]', Punctuation), (r'\s+', Whitespace), ],
'comments': [ (r'(\s*)(#.*)$', bygroups(Whitespace, Comment)), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), ],
'operators': [ (r'(=>|\?|<|>|=|\+|-|/|\*|~|!|\|)', Operator), (r'(in|and|or|not)\b', Operator.Word), ],
'names': [ (r'[a-zA-Z_]\w*', Name.Attribute), (r'(\$\S+)(\[)(\S+)(\])', bygroups(Name.Variable, Punctuation, String, Punctuation)), (r'\$\S+', Name.Variable), ],
'numbers': [ # Copypasta from the Python lexer (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float), (r'\d+[eE][+-]?[0-9]+j?', Number.Float), (r'0[0-7]+j?', Number.Oct), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+j?', Number.Integer) ],
'keywords': [ # Left out 'group' and 'require' # Since they're often used as attributes (words(( 'absent', 'alert', 'alias', 'audit', 'augeas', 'before', 'case', 'check', 'class', 'computer', 'configured', 'contained', 'create_resources', 'crit', 'cron', 'debug', 'default', 'define', 'defined', 'directory', 'else', 'elsif', 'emerg', 'err', 'exec', 'extlookup', 'fail', 'false', 'file', 'filebucket', 'fqdn_rand', 'generate', 'host', 'if', 'import', 'include', 'info', 'inherits', 'inline_template', 'installed', 'interface', 'k5login', 'latest', 'link', 'loglevel', 'macauthorization', 'mailalias', 'maillist', 'mcx', 'md5', 'mount', 'mounted', 'nagios_command', 'nagios_contact', 'nagios_contactgroup', 'nagios_host', 'nagios_hostdependency', 'nagios_hostescalation', 'nagios_hostextinfo', 'nagios_hostgroup', 'nagios_service', 'nagios_servicedependency', 'nagios_serviceescalation', 'nagios_serviceextinfo', 'nagios_servicegroup', 'nagios_timeperiod', 'node', 'noop', 'notice', 'notify', 'package', 'present', 'purged', 'realize', 'regsubst', 'resources', 'role', 'router', 'running', 'schedule', 'scheduled_task', 'search', 'selboolean', 'selmodule', 'service', 'sha1', 'shellquote', 'split', 'sprintf', 'ssh_authorized_key', 'sshkey', 'stage', 'stopped', 'subscribe', 'tag', 'tagged', 'template', 'tidy', 'true', 'undef', 'unmounted', 'user', 'versioncmp', 'vlan', 'warning', 'yumrepo', 'zfs', 'zone', 'zpool'), prefix='(?i)', suffix=r'\b'), Keyword), ],
'strings': [ (r'"([^"])*"', String), (r"'(\\'|[^'])*'", String), ],
}
class RslLexer(RegexLexer): """ RSL is the formal specification language used in RAISE (Rigorous Approach to Industrial Software Engineering) method. """ name = 'RSL' url = 'http://en.wikipedia.org/wiki/RAISE' aliases = ['rsl'] filenames = ['*.rsl'] mimetypes = ['text/rsl'] version_added = '2.0'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ (words(( 'Bool', 'Char', 'Int', 'Nat', 'Real', 'Text', 'Unit', 'abs', 'all', 'always', 'any', 'as', 'axiom', 'card', 'case', 'channel', 'chaos', 'class', 'devt_relation', 'dom', 'elems', 'else', 'elif', 'end', 'exists', 'extend', 'false', 'for', 'hd', 'hide', 'if', 'in', 'is', 'inds', 'initialise', 'int', 'inter', 'isin', 'len', 'let', 'local', 'ltl_assertion', 'object', 'of', 'out', 'post', 'pre', 'read', 'real', 'rng', 'scheme', 'skip', 'stop', 'swap', 'then', 'theory', 'test_case', 'tl', 'transition_system', 'true', 'type', 'union', 'until', 'use', 'value', 'variable', 'while', 'with', 'write', '~isin', '-inflist', '-infset', '-list', '-set'), prefix=r'\b', suffix=r'\b'), Keyword), (r'(variable|value)\b', Keyword.Declaration), (r'--.*?\n', Comment), (r'<:.*?:>', Comment), (r'\{!.*?!\}', Comment), (r'/\*.*?\*/', Comment), (r'^([ \t]*)([\w]+)([ \t]*)(:[^:])', bygroups(Whitespace, Name.Function, Whitespace, Name.Function)), (r'(^[ \t]*)([\w]+)([ \t]*)(\([\w\s,]*\))([ \t]*)(is|as)', bygroups(Whitespace, Name.Function, Whitespace, Text, Whitespace, Keyword)), (r'\b[A-Z]\w*\b', Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'".*"', String), (r'\'.\'', String.Char), (r'(><|->|-m->|/\\|<=|<<=|<\.|\|\||\|\^\||-~->|-~m->|\\/|>=|>>|' r'\.>|\+\+|-\\|<->|=>|:-|~=|\*\*|<<|>>=|\+>|!!|\|=\||#)', Operator), (r'[0-9]+\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-f]+', Number.Hex), (r'[0-9]+', Number.Integer), (r'\s+', Whitespace), (r'.', Text), ], }
def analyse_text(text): """ Check for the most common text in the beginning of a RSL file. """ if re.search(r'scheme\s*.*?=\s*class\s*type', text, re.I) is not None: return 1.0
class MscgenLexer(RegexLexer): """ For Mscgen files. """ name = 'Mscgen' url = 'http://www.mcternan.me.uk/mscgen/' aliases = ['mscgen', 'msc'] filenames = ['*.msc'] version_added = '1.6'
_var = r'(\w+|"(?:\\"|[^"])*")'
tokens = { 'root': [ (r'msc\b', Keyword.Type), # Options (r'(hscale|HSCALE|width|WIDTH|wordwraparcs|WORDWRAPARCS' r'|arcgradient|ARCGRADIENT)\b', Name.Property), # Operators (r'(abox|ABOX|rbox|RBOX|box|BOX|note|NOTE)\b', Operator.Word), (r'(\.|-|\|){3}', Keyword), (r'(?:-|=|\.|:){2}' r'|<<=>>|<->|<=>|<<>>|<:>' r'|->|=>>|>>|=>|:>|-x|-X' r'|<-|<<=|<<|<=|<:|x-|X-|=', Operator), # Names (r'\*', Name.Builtin), (_var, Name.Variable), # Other (r'\[', Punctuation, 'attrs'), (r'\{|\}|,|;', Punctuation), include('comments') ], 'attrs': [ (r'\]', Punctuation, '#pop'), (_var + r'(\s*)(=)(\s*)' + _var, bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), (r',', Punctuation), include('comments') ], 'comments': [ (r'(?://|#).*?\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), (r'[ \t\r\n]+', Whitespace) ] }
class VGLLexer(RegexLexer): """ For SampleManager VGL source code. """ name = 'VGL' url = 'http://www.thermoscientific.com/samplemanager' aliases = ['vgl'] filenames = ['*.rpf'] version_added = '1.6'
flags = re.MULTILINE | re.DOTALL | re.IGNORECASE
tokens = { 'root': [ (r'\{[^}]*\}', Comment.Multiline), (r'declare', Keyword.Constant), (r'(if|then|else|endif|while|do|endwhile|and|or|prompt|object' r'|create|on|line|with|global|routine|value|endroutine|constant' r'|global|set|join|library|compile_option|file|exists|create|copy' r'|delete|enable|windows|name|notprotected)(?! *[=<>.,()])', Keyword), (r'(true|false|null|empty|error|locked)', Keyword.Constant), (r'[~^*#!%&\[\]()<>|+=:;,./?-]', Operator), (r'"[^"]*"', String), (r'(\.)([a-z_$][\w$]*)', bygroups(Operator, Name.Attribute)), (r'[0-9][0-9]*(\.[0-9]+(e[+\-]?[0-9]+)?)?', Number), (r'[a-z_$][\w$]*', Name), (r'[\r\n]+', Whitespace), (r'\s+', Whitespace) ] }
class AlloyLexer(RegexLexer): """ For Alloy source code. """
name = 'Alloy' url = 'http://alloy.mit.edu' aliases = ['alloy'] filenames = ['*.als'] mimetypes = ['text/x-alloy'] version_added = '2.0'
flags = re.MULTILINE | re.DOTALL
iden_rex = r'[a-zA-Z_][\w]*"*' string_rex = r'"\b(\\\\|\\[^\\]|[^"\\])*"' text_tuple = (r'[^\S\n]+', Whitespace)
tokens = { 'sig': [ (r'(extends)\b', Keyword, '#pop'), (iden_rex, Name), text_tuple, (r',', Punctuation), (r'\{', Operator, '#pop'), ], 'module': [ text_tuple, (iden_rex, Name, '#pop'), ], 'fun': [ text_tuple, (r'\{', Operator, '#pop'), (iden_rex, Name, '#pop'), ], 'fact': [ include('fun'), (string_rex, String, '#pop'), ], 'root': [ (r'--.*?$', Comment.Single), (r'//.*?$', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), text_tuple, (r'(module|open)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'module'), (r'(sig|enum)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'sig'), (r'(iden|univ|none)\b', Keyword.Constant), (r'(int|Int)\b', Keyword.Type), (r'(var|this|abstract|extends|set|seq|one|lone|let)\b', Keyword), (r'(all|some|no|sum|disj|when|else)\b', Keyword), (r'(run|check|for|but|exactly|expect|as|steps)\b', Keyword), (r'(always|after|eventually|until|release)\b', Keyword), # future time operators (r'(historically|before|once|since|triggered)\b', Keyword), # past time operators (r'(and|or|implies|iff|in)\b', Operator.Word), (r'(fun|pred|assert)(\s+)', bygroups(Keyword, Whitespace), 'fun'), (r'(fact)(\s+)', bygroups(Keyword, Whitespace), 'fact'), (r'!|#|&&|\+\+|<<|>>|>=|<=>|<=|\.\.|\.|->', Operator), (r'[-+/*%=<>&!^|~{}\[\]().\';]', Operator), (iden_rex, Name), (r'[:,]', Punctuation), (r'[0-9]+', Number.Integer), (string_rex, String), (r'\n', Whitespace), ] }
class PanLexer(RegexLexer): """ Lexer for pan source files.
Based on tcsh lexer. """
name = 'Pan' url = 'https://github.com/quattor/pan/' aliases = ['pan'] filenames = ['*.pan'] version_added = '2.0'
tokens = { 'root': [ include('basic'), (r'\(', Keyword, 'paren'), (r'\{', Keyword, 'curly'), include('data'), ], 'basic': [ (words(( 'if', 'for', 'with', 'else', 'type', 'bind', 'while', 'valid', 'final', 'prefix', 'unique', 'object', 'foreach', 'include', 'template', 'function', 'variable', 'structure', 'extensible', 'declaration'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'file_contents', 'format', 'index', 'length', 'match', 'matches', 'replace', 'splice', 'split', 'substr', 'to_lowercase', 'to_uppercase', 'debug', 'error', 'traceback', 'deprecated', 'base64_decode', 'base64_encode', 'digest', 'escape', 'unescape', 'append', 'create', 'first', 'nlist', 'key', 'list', 'merge', 'next', 'prepend', 'is_boolean', 'is_defined', 'is_double', 'is_list', 'is_long', 'is_nlist', 'is_null', 'is_number', 'is_property', 'is_resource', 'is_string', 'to_boolean', 'to_double', 'to_long', 'to_string', 'clone', 'delete', 'exists', 'path_exists', 'if_exists', 'return', 'value'), prefix=r'\b', suffix=r'\b'), Name.Builtin), (r'#.*', Comment), (r'\\[\w\W]', String.Escape), (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Whitespace, Operator)), (r'[\[\]{}()=]+', Operator), (r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String), (r';', Punctuation), ], 'data': [ (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double), (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single), (r'\s+', Whitespace), (r'[^=\s\[\]{}()$"\'`\\;#]+', Text), (r'\d+(?= |\Z)', Number), ], 'curly': [ (r'\}', Keyword, '#pop'), (r':-', Keyword), (r'\w+', Name.Variable), (r'[^}:"\'`$]+', Punctuation), (r':', Punctuation), include('root'), ], 'paren': [ (r'\)', Keyword, '#pop'), include('root'), ], }
class CrmshLexer(RegexLexer): """ Lexer for crmsh configuration files for Pacemaker clusters. """ name = 'Crmsh' url = 'http://crmsh.github.io/' aliases = ['crmsh', 'pcmk'] filenames = ['*.crmsh', '*.pcmk'] mimetypes = [] version_added = '2.1'
elem = words(( 'node', 'primitive', 'group', 'clone', 'ms', 'location', 'colocation', 'order', 'fencing_topology', 'rsc_ticket', 'rsc_template', 'property', 'rsc_defaults', 'op_defaults', 'acl_target', 'acl_group', 'user', 'role', 'tag'), suffix=r'(?![\w#$-])') sub = words(( 'params', 'meta', 'operations', 'op', 'rule', 'attributes', 'utilization'), suffix=r'(?![\w#$-])') acl = words(('read', 'write', 'deny'), suffix=r'(?![\w#$-])') bin_rel = words(('and', 'or'), suffix=r'(?![\w#$-])') un_ops = words(('defined', 'not_defined'), suffix=r'(?![\w#$-])') date_exp = words(('in_range', 'date', 'spec', 'in'), suffix=r'(?![\w#$-])') acl_mod = (r'(?:tag|ref|reference|attribute|type|xpath)') bin_ops = (r'(?:lt|gt|lte|gte|eq|ne)') val_qual = (r'(?:string|version|number)') rsc_role_action = (r'(?:Master|Started|Slave|Stopped|' r'start|promote|demote|stop)')
tokens = { 'root': [ (r'^(#.*)(\n)?', bygroups(Comment, Whitespace)), # attr=value (nvpair) (r'([\w#$-]+)(=)("(?:""|[^"])*"|\S+)', bygroups(Name.Attribute, Punctuation, String)), # need this construct, otherwise numeric node ids # are matched as scores # elem id: (r'(node)(\s+)([\w#$-]+)(:)', bygroups(Keyword, Whitespace, Name, Punctuation)), # scores (r'([+-]?([0-9]+|inf)):', Number), # keywords (elements and other) (elem, Keyword), (sub, Keyword), (acl, Keyword), # binary operators (rf'(?:{val_qual}:)?({bin_ops})(?![\w#$-])', Operator.Word), # other operators (bin_rel, Operator.Word), (un_ops, Operator.Word), (date_exp, Operator.Word), # builtin attributes (e.g. #uname) (r'#[a-z]+(?![\w#$-])', Name.Builtin), # acl_mod:blah (rf'({acl_mod})(:)("(?:""|[^"])*"|\S+)', bygroups(Keyword, Punctuation, Name)), # rsc_id[:(role|action)] # NB: this matches all other identifiers (rf'([\w#$-]+)(?:(:)({rsc_role_action}))?(?![\w#$-])', bygroups(Name, Punctuation, Operator.Word)), # punctuation (r'(\\(?=\n)|[\[\](){}/:@])', Punctuation), (r'\s+|\n', Whitespace), ], }
class FlatlineLexer(RegexLexer): """ Lexer for Flatline expressions. """ name = 'Flatline' url = 'https://github.com/bigmlcom/flatline' aliases = ['flatline'] filenames = [] mimetypes = ['text/x-flatline'] version_added = '2.2'
special_forms = ('let',)
builtins = ( "!=", "*", "+", "-", "<", "<=", "=", ">", ">=", "abs", "acos", "all", "all-but", "all-with-defaults", "all-with-numeric-default", "and", "asin", "atan", "avg", "avg-window", "bin-center", "bin-count", "call", "category-count", "ceil", "cond", "cond-window", "cons", "cos", "cosh", "count", "diff-window", "div", "ensure-value", "ensure-weighted-value", "epoch", "epoch-day", "epoch-fields", "epoch-hour", "epoch-millisecond", "epoch-minute", "epoch-month", "epoch-second", "epoch-weekday", "epoch-year", "exp", "f", "field", "field-prop", "fields", "filter", "first", "floor", "head", "if", "in", "integer", "language", "length", "levenshtein", "linear-regression", "list", "ln", "log", "log10", "map", "matches", "matches?", "max", "maximum", "md5", "mean", "median", "min", "minimum", "missing", "missing-count", "missing?", "missing_count", "mod", "mode", "normalize", "not", "nth", "occurrences", "or", "percentile", "percentile-label", "population", "population-fraction", "pow", "preferred", "preferred?", "quantile-label", "rand", "rand-int", "random-value", "re-quote", "real", "replace", "replace-first", "rest", "round", "row-number", "segment-label", "sha1", "sha256", "sin", "sinh", "sqrt", "square", "standard-deviation", "standard_deviation", "str", "subs", "sum", "sum-squares", "sum-window", "sum_squares", "summary", "summary-no", "summary-str", "tail", "tan", "tanh", "to-degrees", "to-radians", "variance", "vectorize", "weighted-random-value", "window", "winnow", "within-percentiles?", "z-score", )
valid_name = r'(?!#)[\w!$%*+<=>?/.#-]+'
tokens = { 'root': [ # whitespaces - usually not relevant (r'[,]+', Text), (r'\s+', Whitespace),
# numbers (r'-?\d+\.\d+', Number.Float), (r'-?\d+', Number.Integer), (r'0x-?[a-f\d]+', Number.Hex),
# strings, symbols and characters (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r"\\(.|[a-z]+)", String.Char),
# expression template placeholder (r'_', String.Symbol),
# highlight the special forms (words(special_forms, suffix=' '), Keyword),
# highlight the builtins (words(builtins, suffix=' '), Name.Builtin),
# the remaining functions (r'(?<=\()' + valid_name, Name.Function),
# find the remaining variables (valid_name, Name.Variable),
# parentheses (r'(\(|\))', Punctuation), ], }
class SnowballLexer(ExtendedRegexLexer): """ Lexer for Snowball source code. """
name = 'Snowball' url = 'https://snowballstem.org/' aliases = ['snowball'] filenames = ['*.sbl'] version_added = '2.2'
_ws = r'\n\r\t '
def __init__(self, **options): self._reset_stringescapes() ExtendedRegexLexer.__init__(self, **options)
def _reset_stringescapes(self): self._start = "'" self._end = "'"
def _string(do_string_first): def callback(lexer, match, ctx): s = match.start() text = match.group() string = re.compile(rf'([^{re.escape(lexer._start)}]*)(.)').match escape = re.compile(rf'([^{re.escape(lexer._end)}]*)(.)').match pos = 0 do_string = do_string_first while pos < len(text): if do_string: match = string(text, pos) yield s + match.start(1), String.Single, match.group(1) if match.group(2) == "'": yield s + match.start(2), String.Single, match.group(2) ctx.stack.pop() break yield s + match.start(2), String.Escape, match.group(2) pos = match.end() match = escape(text, pos) yield s + match.start(), String.Escape, match.group() if match.group(2) != lexer._end: ctx.stack[-1] = 'escape' break pos = match.end() do_string = True ctx.pos = s + match.end() return callback
def _stringescapes(lexer, match, ctx): lexer._start = match.group(3) lexer._end = match.group(5) return bygroups(Keyword.Reserved, Whitespace, String.Escape, Whitespace, String.Escape)(lexer, match, ctx)
tokens = { 'root': [ (r'len\b', Name.Builtin), (r'lenof\b', Operator.Word), include('root1'), ], 'root1': [ (rf'[{_ws}]+', Whitespace), (r'\d+', Number.Integer), (r"'", String.Single, 'string'), (r'[()]', Punctuation), (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'//.*', Comment.Single), (r'[!*+\-/<=>]=|[-=]>|<[+-]|[$*+\-/<=>?\[\]]', Operator), (words(('as', 'get', 'hex', 'among', 'define', 'decimal', 'backwardmode'), suffix=r'\b'), Keyword.Reserved), (words(('strings', 'booleans', 'integers', 'routines', 'externals', 'groupings'), suffix=r'\b'), Keyword.Reserved, 'declaration'), (words(('do', 'or', 'and', 'for', 'hop', 'non', 'not', 'set', 'try', 'fail', 'goto', 'loop', 'next', 'test', 'true', 'false', 'unset', 'atmark', 'attach', 'delete', 'gopast', 'insert', 'repeat', 'sizeof', 'tomark', 'atleast', 'atlimit', 'reverse', 'setmark', 'tolimit', 'setlimit', 'backwards', 'substring'), suffix=r'\b'), Operator.Word), (words(('size', 'limit', 'cursor', 'maxint', 'minint'), suffix=r'\b'), Name.Builtin), (rf'(stringdef\b)([{_ws}]*)([^{_ws}]+)', bygroups(Keyword.Reserved, Whitespace, String.Escape)), (rf'(stringescapes\b)([{_ws}]*)(.)([{_ws}]*)(.)', _stringescapes), (r'[A-Za-z]\w*', Name), ], 'declaration': [ (r'\)', Punctuation, '#pop'), (words(('len', 'lenof'), suffix=r'\b'), Name, ('root1', 'declaration')), include('root1'), ], 'string': [ (r"[^']*'", _string(True)), ], 'escape': [ (r"[^']*'", _string(False)), ], }
def get_tokens_unprocessed(self, text=None, context=None): self._reset_stringescapes() return ExtendedRegexLexer.get_tokens_unprocessed(self, text, context)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279""" pygments.lexers.dylan ~~~~~~~~~~~~~~~~~~~~~
Lexers for the Dylan language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, bygroups, do_insertions, \ default, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Literal, Whitespace
__all__ = ['DylanLexer', 'DylanConsoleLexer', 'DylanLidLexer']
class DylanLexer(RegexLexer): """ For the Dylan language. """
name = 'Dylan' url = 'http://www.opendylan.org/' aliases = ['dylan'] filenames = ['*.dylan', '*.dyl', '*.intr'] mimetypes = ['text/x-dylan'] version_added = '0.7'
flags = re.IGNORECASE
builtins = { 'subclass', 'abstract', 'block', 'concrete', 'constant', 'class', 'compiler-open', 'compiler-sideways', 'domain', 'dynamic', 'each-subclass', 'exception', 'exclude', 'function', 'generic', 'handler', 'inherited', 'inline', 'inline-only', 'instance', 'interface', 'import', 'keyword', 'library', 'macro', 'method', 'module', 'open', 'primary', 'required', 'sealed', 'sideways', 'singleton', 'slot', 'thread', 'variable', 'virtual'}
keywords = { 'above', 'afterwards', 'begin', 'below', 'by', 'case', 'cleanup', 'create', 'define', 'else', 'elseif', 'end', 'export', 'finally', 'for', 'from', 'if', 'in', 'let', 'local', 'otherwise', 'rename', 'select', 'signal', 'then', 'to', 'unless', 'until', 'use', 'when', 'while'}
operators = { '~', '+', '-', '*', '|', '^', '=', '==', '~=', '~==', '<', '<=', '>', '>=', '&', '|'}
functions = { 'abort', 'abs', 'add', 'add!', 'add-method', 'add-new', 'add-new!', 'all-superclasses', 'always', 'any?', 'applicable-method?', 'apply', 'aref', 'aref-setter', 'as', 'as-lowercase', 'as-lowercase!', 'as-uppercase', 'as-uppercase!', 'ash', 'backward-iteration-protocol', 'break', 'ceiling', 'ceiling/', 'cerror', 'check-type', 'choose', 'choose-by', 'complement', 'compose', 'concatenate', 'concatenate-as', 'condition-format-arguments', 'condition-format-string', 'conjoin', 'copy-sequence', 'curry', 'default-handler', 'dimension', 'dimensions', 'direct-subclasses', 'direct-superclasses', 'disjoin', 'do', 'do-handlers', 'element', 'element-setter', 'empty?', 'error', 'even?', 'every?', 'false-or', 'fill!', 'find-key', 'find-method', 'first', 'first-setter', 'floor', 'floor/', 'forward-iteration-protocol', 'function-arguments', 'function-return-values', 'function-specializers', 'gcd', 'generic-function-mandatory-keywords', 'generic-function-methods', 'head', 'head-setter', 'identity', 'initialize', 'instance?', 'integral?', 'intersection', 'key-sequence', 'key-test', 'last', 'last-setter', 'lcm', 'limited', 'list', 'logand', 'logbit?', 'logior', 'lognot', 'logxor', 'make', 'map', 'map-as', 'map-into', 'max', 'member?', 'merge-hash-codes', 'min', 'modulo', 'negative', 'negative?', 'next-method', 'object-class', 'object-hash', 'odd?', 'one-of', 'pair', 'pop', 'pop-last', 'positive?', 'push', 'push-last', 'range', 'rank', 'rcurry', 'reduce', 'reduce1', 'remainder', 'remove', 'remove!', 'remove-duplicates', 'remove-duplicates!', 'remove-key!', 'remove-method', 'replace-elements!', 'replace-subsequence!', 'restart-query', 'return-allowed?', 'return-description', 'return-query', 'reverse', 'reverse!', 'round', 'round/', 'row-major-index', 'second', 'second-setter', 'shallow-copy', 'signal', 'singleton', 'size', 'size-setter', 'slot-initialized?', 'sort', 'sort!', 'sorted-applicable-methods', 'subsequence-position', 'subtype?', 'table-protocol', 'tail', 'tail-setter', 'third', 'third-setter', 'truncate', 'truncate/', 'type-error-expected-type', 'type-error-value', 'type-for-copy', 'type-union', 'union', 'values', 'vector', 'zero?'}
valid_name = '\\\\?[\\w!&*<>|^$%@\\-+~?/=]+'
def get_tokens_unprocessed(self, text): for index, token, value in RegexLexer.get_tokens_unprocessed(self, text): if token is Name: lowercase_value = value.lower() if lowercase_value in self.builtins: yield index, Name.Builtin, value continue if lowercase_value in self.keywords: yield index, Keyword, value continue if lowercase_value in self.functions: yield index, Name.Builtin, value continue if lowercase_value in self.operators: yield index, Operator, value continue yield index, token, value
tokens = { 'root': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'//.*?\n', Comment.Single),
# lid header (r'([a-z0-9-]+)(:)([ \t]*)(.*(?:\n[ \t].+)*)', bygroups(Name.Attribute, Operator, Whitespace, String)),
default('code') # no header match, switch to code ], 'code': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# multi-line comment (r'/\*', Comment.Multiline, 'comment'),
# strings and characters (r'"', String, 'string'), (r"'(\\.|\\[0-7]{1,3}|\\x[a-f0-9]{1,2}|[^\\\'\n])'", String.Char),
# binary integer (r'#b[01]+', Number.Bin),
# octal integer (r'#o[0-7]+', Number.Oct),
# floating point (r'[-+]?(\d*\.\d+(e[-+]?\d+)?|\d+(\.\d*)?e[-+]?\d+)', Number.Float),
# decimal integer (r'[-+]?\d+', Number.Integer),
# hex integer (r'#x[0-9a-f]+', Number.Hex),
# Macro parameters (r'(\?' + valid_name + ')(:)' r'(token|name|variable|expression|body|case-body|\*)', bygroups(Name.Tag, Operator, Name.Builtin)), (r'(\?)(:)(token|name|variable|expression|body|case-body|\*)', bygroups(Name.Tag, Operator, Name.Builtin)), (r'\?' + valid_name, Name.Tag),
# Punctuation (r'(=>|::|#\(|#\[|##|\?\?|\?=|\?|[(){}\[\],.;])', Punctuation),
# Most operators are picked up as names and then re-flagged. # This one isn't valid in a name though, so we pick it up now. (r':=', Operator),
# Pick up #t / #f before we match other stuff with #. (r'#[tf]', Literal),
# #"foo" style keywords (r'#"', String.Symbol, 'keyword'),
# #rest, #key, #all-keys, etc. (r'#[a-z0-9-]+', Keyword),
# required-init-keyword: style keywords. (valid_name + ':', Keyword),
# class names ('<' + valid_name + '>', Name.Class),
# define variable forms. (r'\*' + valid_name + r'\*', Name.Variable.Global),
# define constant forms. (r'\$' + valid_name, Name.Constant),
# everything else. We re-flag some of these in the method above. (valid_name, Name), ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'keyword': [ (r'"', String.Symbol, '#pop'), (r'[^\\"]+', String.Symbol), # all other characters ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-f0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ] }
class DylanLidLexer(RegexLexer): """ For Dylan LID (Library Interchange Definition) files. """
name = 'DylanLID' aliases = ['dylan-lid', 'lid'] filenames = ['*.lid', '*.hdp'] mimetypes = ['text/x-dylan-lid'] url = 'http://www.opendylan.org/' version_added = '1.6' flags = re.IGNORECASE
tokens = { 'root': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# lid header (r'(.*?)(:)([ \t]*)(.*(?:\n[ \t].+)*)', bygroups(Name.Attribute, Operator, Whitespace, String)), ] }
class DylanConsoleLexer(Lexer): """ For Dylan interactive console output.
This is based on a copy of the ``RubyConsoleLexer``. """ name = 'Dylan session' aliases = ['dylan-console', 'dylan-repl'] filenames = ['*.dylan-console'] mimetypes = ['text/x-dylan-console'] url = 'http://www.opendylan.org/' version_added = '1.6' _example = 'dylan-console/console.dylan-console'
_prompt_re = re.compile(r'\?| ')
def get_tokens_unprocessed(self, text): dylexer = DylanLexer(**self.options)
curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() m = self._prompt_re.match(line) if m is not None: end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: yield from do_insertions(insertions, dylexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, dylexer.get_tokens_unprocessed(curcode))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144""" pygments.lexers.ecl ~~~~~~~~~~~~~~~~~~~
Lexers for the ECL language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ECLLexer']
class ECLLexer(RegexLexer): """ Lexer for the declarative big-data ECL language. """
name = 'ECL' url = 'https://hpccsystems.com/training/documentation/ecl-language-reference/html' aliases = ['ecl'] filenames = ['*.ecl'] mimetypes = ['application/x-ecl'] version_added = '1.5'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ include('whitespace'), include('statements'), ], 'whitespace': [ (r'\s+', Whitespace), (r'\/\/.*', Comment.Single), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline), ], 'statements': [ include('types'), include('keywords'), include('functions'), include('hash'), (r'"', String, 'string'), (r'\'', String, 'string'), (r'(\d+\.\d*|\.\d+|\d+)e[+-]?\d+[lu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+f)f?', Number.Float), (r'0x[0-9a-f]+[lu]*', Number.Hex), (r'0[0-7]+[lu]*', Number.Oct), (r'\d+[lu]*', Number.Integer), (r'[~!%^&*+=|?:<>/-]+', Operator), (r'[{}()\[\],.;]', Punctuation), (r'[a-z_]\w*', Name), ], 'hash': [ (r'^#.*$', Comment.Preproc), ], 'types': [ (r'(RECORD|END)\D', Keyword.Declaration), (r'((?:ASCII|BIG_ENDIAN|BOOLEAN|DATA|DECIMAL|EBCDIC|INTEGER|PATTERN|' r'QSTRING|REAL|RECORD|RULE|SET OF|STRING|TOKEN|UDECIMAL|UNICODE|' r'UNSIGNED|VARSTRING|VARUNICODE)\d*)(\s+)', bygroups(Keyword.Type, Whitespace)), ], 'keywords': [ (words(( 'APPLY', 'ASSERT', 'BUILD', 'BUILDINDEX', 'EVALUATE', 'FAIL', 'KEYDIFF', 'KEYPATCH', 'LOADXML', 'NOTHOR', 'NOTIFY', 'OUTPUT', 'PARALLEL', 'SEQUENTIAL', 'SOAPCALL', 'CHECKPOINT', 'DEPRECATED', 'FAILCODE', 'FAILMESSAGE', 'FAILURE', 'GLOBAL', 'INDEPENDENT', 'ONWARNING', 'PERSIST', 'PRIORITY', 'RECOVERY', 'STORED', 'SUCCESS', 'WAIT', 'WHEN'), suffix=r'\b'), Keyword.Reserved), # These are classed differently, check later (words(( 'ALL', 'AND', 'ANY', 'AS', 'ATMOST', 'BEFORE', 'BEGINC++', 'BEST', 'BETWEEN', 'CASE', 'CONST', 'COUNTER', 'CSV', 'DESCEND', 'ENCRYPT', 'ENDC++', 'ENDMACRO', 'EXCEPT', 'EXCLUSIVE', 'EXPIRE', 'EXPORT', 'EXTEND', 'FALSE', 'FEW', 'FIRST', 'FLAT', 'FULL', 'FUNCTION', 'GROUP', 'HEADER', 'HEADING', 'HOLE', 'IFBLOCK', 'IMPORT', 'IN', 'JOINED', 'KEEP', 'KEYED', 'LAST', 'LEFT', 'LIMIT', 'LOAD', 'LOCAL', 'LOCALE', 'LOOKUP', 'MACRO', 'MANY', 'MAXCOUNT', 'MAXLENGTH', 'MIN SKEW', 'MODULE', 'INTERFACE', 'NAMED', 'NOCASE', 'NOROOT', 'NOSCAN', 'NOSORT', 'NOT', 'OF', 'ONLY', 'OPT', 'OR', 'OUTER', 'OVERWRITE', 'PACKED', 'PARTITION', 'PENALTY', 'PHYSICALLENGTH', 'PIPE', 'QUOTE', 'RELATIONSHIP', 'REPEAT', 'RETURN', 'RIGHT', 'SCAN', 'SELF', 'SEPARATOR', 'SERVICE', 'SHARED', 'SKEW', 'SKIP', 'SQL', 'STORE', 'TERMINATOR', 'THOR', 'THRESHOLD', 'TOKEN', 'TRANSFORM', 'TRIM', 'TRUE', 'TYPE', 'UNICODEORDER', 'UNSORTED', 'VALIDATE', 'VIRTUAL', 'WHOLE', 'WILD', 'WITHIN', 'XML', 'XPATH', '__COMPRESSED__'), suffix=r'\b'), Keyword.Reserved), ], 'functions': [ (words(( 'ABS', 'ACOS', 'ALLNODES', 'ASCII', 'ASIN', 'ASSTRING', 'ATAN', 'ATAN2', 'AVE', 'CASE', 'CHOOSE', 'CHOOSEN', 'CHOOSESETS', 'CLUSTERSIZE', 'COMBINE', 'CORRELATION', 'COS', 'COSH', 'COUNT', 'COVARIANCE', 'CRON', 'DATASET', 'DEDUP', 'DEFINE', 'DENORMALIZE', 'DISTRIBUTE', 'DISTRIBUTED', 'DISTRIBUTION', 'EBCDIC', 'ENTH', 'ERROR', 'EVALUATE', 'EVENT', 'EVENTEXTRA', 'EVENTNAME', 'EXISTS', 'EXP', 'FAILCODE', 'FAILMESSAGE', 'FETCH', 'FROMUNICODE', 'GETISVALID', 'GLOBAL', 'GRAPH', 'GROUP', 'HASH', 'HASH32', 'HASH64', 'HASHCRC', 'HASHMD5', 'HAVING', 'IF', 'INDEX', 'INTFORMAT', 'ISVALID', 'ITERATE', 'JOIN', 'KEYUNICODE', 'LENGTH', 'LIBRARY', 'LIMIT', 'LN', 'LOCAL', 'LOG', 'LOOP', 'MAP', 'MATCHED', 'MATCHLENGTH', 'MATCHPOSITION', 'MATCHTEXT', 'MATCHUNICODE', 'MAX', 'MERGE', 'MERGEJOIN', 'MIN', 'NOLOCAL', 'NONEMPTY', 'NORMALIZE', 'PARSE', 'PIPE', 'POWER', 'PRELOAD', 'PROCESS', 'PROJECT', 'PULL', 'RANDOM', 'RANGE', 'RANK', 'RANKED', 'REALFORMAT', 'RECORDOF', 'REGEXFIND', 'REGEXREPLACE', 'REGROUP', 'REJECTED', 'ROLLUP', 'ROUND', 'ROUNDUP', 'ROW', 'ROWDIFF', 'SAMPLE', 'SET', 'SIN', 'SINH', 'SIZEOF', 'SOAPCALL', 'SORT', 'SORTED', 'SQRT', 'STEPPED', 'STORED', 'SUM', 'TABLE', 'TAN', 'TANH', 'THISNODE', 'TOPN', 'TOUNICODE', 'TRANSFER', 'TRIM', 'TRUNCATE', 'TYPEOF', 'UNGROUP', 'UNICODEORDER', 'VARIANCE', 'WHICH', 'WORKUNIT', 'XMLDECODE', 'XMLENCODE', 'XMLTEXT', 'XMLUNICODE'), suffix=r'\b'), Name.Function), ], 'string': [ (r'"', String, '#pop'), (r'\'', String, '#pop'), (r'[^"\']+', String), ], }
def analyse_text(text): """This is very difficult to guess relative to other business languages. -> in conjunction with BEGIN/END seems relatively rare though.""" result = 0
if '->' in text: result += 0.01 if 'BEGIN' in text: result += 0.01 if 'END' in text: result += 0.01
return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768""" pygments.lexers.eiffel ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Eiffel language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['EiffelLexer']
class EiffelLexer(RegexLexer): """ For Eiffel source code. """ name = 'Eiffel' url = 'https://www.eiffel.com' aliases = ['eiffel'] filenames = ['*.e'] mimetypes = ['text/x-eiffel'] version_added = '2.0'
tokens = { 'root': [ (r'[^\S\n]+', Whitespace), (r'--.*?$', Comment.Single), (r'[^\S\n]+', Whitespace), # Please note that keyword and operator are case insensitive. (r'(?i)(true|false|void|current|result|precursor)\b', Keyword.Constant), (r'(?i)(not|xor|implies|or)\b', Operator.Word), (r'(?i)(and)(?:(\s+)(then))?\b', bygroups(Operator.Word, Whitespace, Operator.Word)), (r'(?i)(or)(?:(\s+)(else))?\b', bygroups(Operator.Word, Whitespace, Operator.Word)), (words(( 'across', 'agent', 'alias', 'all', 'as', 'assign', 'attached', 'attribute', 'check', 'class', 'convert', 'create', 'debug', 'deferred', 'detachable', 'do', 'else', 'elseif', 'end', 'ensure', 'expanded', 'export', 'external', 'feature', 'from', 'frozen', 'if', 'inherit', 'inspect', 'invariant', 'like', 'local', 'loop', 'none', 'note', 'obsolete', 'old', 'once', 'only', 'redefine', 'rename', 'require', 'rescue', 'retry', 'select', 'separate', 'then', 'undefine', 'until', 'variant', 'when'), prefix=r'(?i)\b', suffix=r'\b'), Keyword.Reserved), (r'"\[([^\]%]|%(.|\n)|\][^"])*?\]"', String), (r'"([^"%\n]|%.)*?"', String), include('numbers'), (r"'([^'%]|%'|%%)'", String.Char), (r"(//|\\\\|>=|<=|:=|/=|~|/~|[\\?!#%&@|+/\-=>*$<^\[\]])", Operator), (r"([{}():;,.])", Punctuation), (r'([a-z]\w*)|([A-Z][A-Z0-9_]*[a-z]\w*)', Name), (r'([A-Z][A-Z0-9_]*)', Name.Class), (r'\n+', Whitespace), ], 'numbers': [ (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'0[bB][01]+', Number.Bin), (r'0[cC][0-7]+', Number.Oct), (r'([0-9]+\.[0-9]*)|([0-9]*\.[0-9]+)', Number.Float), (r'[0-9]+', Number.Integer), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123""" pygments.lexers.elm ~~~~~~~~~~~~~~~~~~~
Lexer for the Elm programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, include, bygroupsfrom pygments.token import Comment, Keyword, Name, Number, Punctuation, \ String, Whitespace
__all__ = ['ElmLexer']
class ElmLexer(RegexLexer): """ For Elm source code. """
name = 'Elm' url = 'https://elm-lang.org/' aliases = ['elm'] filenames = ['*.elm'] mimetypes = ['text/x-elm'] version_added = '2.1'
validName = r'[a-z_][a-zA-Z0-9_\']*'
specialName = r'^main '
builtinOps = ( '~', '||', '|>', '|', '`', '^', '\\', '\'', '>>', '>=', '>', '==', '=', '<~', '<|', '<=', '<<', '<-', '<', '::', ':', '/=', '//', '/', '..', '.', '->', '-', '++', '+', '*', '&&', '%', )
reservedWords = words(( 'alias', 'as', 'case', 'else', 'if', 'import', 'in', 'let', 'module', 'of', 'port', 'then', 'type', 'where', ), suffix=r'\b')
tokens = { 'root': [
# Comments (r'\{-', Comment.Multiline, 'comment'), (r'--.*', Comment.Single),
# Whitespace (r'\s+', Whitespace),
# Strings (r'"', String, 'doublequote'),
# Modules (r'^(\s*)(module)(\s*)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'imports'),
# Imports (r'^(\s*)(import)(\s*)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'imports'),
# Shaders (r'\[glsl\|.*', Name.Entity, 'shader'),
# Keywords (reservedWords, Keyword.Reserved),
# Types (r'[A-Z][a-zA-Z0-9_]*', Keyword.Type),
# Main (specialName, Keyword.Reserved),
# Prefix Operators (words((builtinOps), prefix=r'\(', suffix=r'\)'), Name.Function),
# Infix Operators (words(builtinOps), Name.Function),
# Numbers include('numbers'),
# Variable Names (validName, Name.Variable),
# Parens (r'[,()\[\]{}]', Punctuation),
],
'comment': [ (r'-(?!\})', Comment.Multiline), (r'\{-', Comment.Multiline, 'comment'), (r'[^-}]', Comment.Multiline), (r'-\}', Comment.Multiline, '#pop'), ],
'doublequote': [ (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\[nrfvb\\"]', String.Escape), (r'[^"]', String), (r'"', String, '#pop'), ],
'imports': [ (r'\w+(\.\w+)*', Name.Class, '#pop'), ],
'numbers': [ (r'_?\d+\.(?=\d+)', Number.Float), (r'_?\d+', Number.Integer), ],
'shader': [ (r'\|(?!\])', Name.Entity), (r'\|\]', Name.Entity, '#pop'), (r'(.*)(\n)', bygroups(Name.Entity, Whitespace)), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201""" pygments.lexers.elpi ~~~~~~~~~~~~~~~~~~~~
Lexer for the `Elpi <http://github.com/LPCIC/elpi>`_ programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, usingfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['ElpiLexer']
from pygments.lexers.theorem import RocqLexer
class ElpiLexer(RegexLexer): """ Lexer for the Elpi programming language. """
name = 'Elpi' url = 'http://github.com/LPCIC/elpi' aliases = ['elpi'] filenames = ['*.elpi'] mimetypes = ['text/x-elpi'] version_added = '2.11'
lcase_re = r"[a-z]" ucase_re = r"[A-Z]" digit_re = r"[0-9]" schar2_re = r"([+*^?/<>`'@#~=&!])" schar_re = rf"({schar2_re}|-|\$|_)" idchar_re = rf"({lcase_re}|{ucase_re}|{digit_re}|{schar_re})" idcharstarns_re = rf"({idchar_re}*(\.({lcase_re}|{ucase_re}){idchar_re}*)*)" symbchar_re = rf"({lcase_re}|{ucase_re}|{digit_re}|{schar_re}|:)" constant_re = rf"({ucase_re}{idchar_re}*|{lcase_re}{idcharstarns_re}|{schar2_re}{symbchar_re}*|_{idchar_re}+)" symbol_re = r"(,|<=>|->|:-|;|\?-|->|&|=>|\bas\b|\buvar\b|<|=<|=|==|>=|>|\bi<|\bi=<|\bi>=|\bi>|\bis\b|\br<|\br=<|\br>=|\br>|\bs<|\bs=<|\bs>=|\bs>|@|::|\[\]|`->|`:|`:=|\^|-|\+|\bi-|\bi\+|r-|r\+|/|\*|\bdiv\b|\bi\*|\bmod\b|\br\*|~|\bi~|\br~)" escape_re = rf"\(({constant_re}|{symbol_re})\)" const_sym_re = rf"({constant_re}|{symbol_re}|{escape_re})"
tokens = { 'root': [ include('elpi') ],
'elpi': [ include('_elpi-comment'),
(r"(:before|:after|:if|:name)(\s*)(\")", bygroups(Keyword.Mode, Text.Whitespace, String.Double), 'elpi-string'), (r"(:index)(\s*)(\()", bygroups(Keyword.Mode, Text.Whitespace, Punctuation), 'elpi-indexing-expr'), (rf"\b(external pred|pred)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-pred-item'), (rf"\b(func)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-func-item'), (rf"\b(external type|type)(\s+)(({const_sym_re}(,\s*)?)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (rf"\b(kind)(\s+)(({const_sym_re}|,)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (rf"\b(typeabbrev)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (r"\b(typeabbrev)(\s+)(\([^)]+\))", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (r"\b(accumulate)(\s+)(\")", bygroups(Keyword.Declaration, Text.Whitespace, String.Double), 'elpi-string'), (rf"\b(accumulate|namespace|local)(\s+)({constant_re})", bygroups(Keyword.Declaration, Text.Whitespace, Text)), (rf"\b(shorten)(\s+)({constant_re}\.)", bygroups(Keyword.Declaration, Text.Whitespace, Text)), (r"\b(pi|sigma)(\s+)([a-zA-Z][A-Za-z0-9_ ]*)(\\)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Variable, Text)), (rf"\b(constraint)(\s+)(({const_sym_re}(\s+)?)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-chr-rule-start'),
(rf"(?=[A-Z_]){constant_re}", Name.Variable), (rf"(?=[a-z_])({constant_re}|_)\\", Name.Variable), (r"_", Name.Variable), (rf"({symbol_re}|!|=>|;)", Keyword.Declaration), (constant_re, Text), (r"\[|\]|\||=>", Keyword.Declaration), (r'"', String.Double, 'elpi-string'), (r'`', String.Double, 'elpi-btick'), (r'\'', String.Double, 'elpi-tick'), (r'\{\{', Punctuation, 'elpi-quote'), (r'\{[^\{]', Text, 'elpi-spill'), (r"\(", Punctuation, 'elpi-in-parens'), (r'\d[\d_]*', Number.Integer), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float), (r"[\+\*\-/\^\.]", Operator), ], '_elpi-comment': [ (r'%[^\n]*\n', Comment), (r'/(?:\\\n)?[*](?:[^*]|[*](?!(?:\\\n)?/))*[*](?:\\\n)?/', Comment), (r"\s+", Text.Whitespace), ], 'elpi-indexing-expr':[ (r'[0-9 _]+', Number.Integer), (r'\)', Punctuation, '#pop'), ], 'elpi-type': [ (r"(ctype\s+)(\")", bygroups(Keyword.Type, String.Double), 'elpi-string'), (r'->', Keyword.Type), (r'prop', Keyword.Mode), (constant_re, Keyword.Type), (r"\(|\)", Keyword.Type), (r"\.", Text, '#pop'), include('_elpi-comment'), ], 'elpi-chr-rule-start': [ (r"\{", Punctuation, 'elpi-chr-rule'), include('_elpi-comment'), ], 'elpi-chr-rule': [ (r"\brule\b", Keyword.Declaration), (r"\\", Keyword.Declaration), (r"\}", Punctuation, '#pop:2'), include('elpi'), ], 'elpi-pred-item': [ (r"[io]:", Keyword.Mode), (r"\.", Text, '#pop'), (r",", Keyword.Mode), include('_elpi-inner-pred-fun'), (r"\)", Keyword.Mode, '#pop'), (r"\(", Keyword.Type, '_elpi-type-item'), include('_elpi-comment'), include('_elpi-type-item'), ], 'elpi-func-item': [ (constant_re, Keyword.Type), (r"\.", Text, '#pop'), (r",", Keyword.Mode), (r'->', Keyword.Mode), include('_elpi-inner-pred-fun'), (r"\)", Keyword.Mode, '#pop'), (r"\(", Keyword.Type, '_elpi-type-item'), include('_elpi-comment'), include('_elpi-type-item'), ], '_elpi-inner-pred-fun': [ (r"(\()(\s*)(pred)", bygroups(Keyword.Mode,Text.Whitespace,Keyword.Declaration), 'elpi-pred-item'), (r"(\()(\s*)(func)", bygroups(Keyword.Mode,Text.Whitespace,Keyword.Declaration), 'elpi-func-item'), ], '_elpi-type-item': [ (r'->', Keyword.Type), (constant_re, Keyword.Type), include('_elpi-inner-pred-fun'), (r"\(", Keyword.Type, '#push'), (r"\)", Keyword.Type, '#pop'), include('_elpi-comment'), ],
''
'elpi-btick': [ (r'[^` ]+', String.Double), (r'`', String.Double, '#pop'), ], 'elpi-tick': [ (r'[^\' ]+', String.Double), (r'\'', String.Double, '#pop'), ], 'elpi-string': [ (r'[^\"]+', String.Double), (r'"', String.Double, '#pop'), ], 'elpi-quote': [ (r'\}\}', Punctuation, '#pop'), (r"\s+", Text.Whitespace), (r"(lp:)(\{\{)", bygroups(Number, Punctuation), 'elpi-quote-exit'), (rf"(lp:)((?=[A-Z_]){constant_re})", bygroups(Number, Name.Variable)), (r"((?!lp:|\}\}).)+", using(RocqLexer)), ], 'elpi-quote-exit': [ include('elpi'), (r'\}\}', Punctuation, '#pop'), ], 'elpi-spill': [ (r'\{[^\{]', Text, '#push'), (r'\}[^\}]', Text, '#pop'), include('elpi'), ], 'elpi-in-parens': [ (r"\(", Punctuation, '#push'), include('elpi'), (r"\)", Punctuation, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132""" pygments.lexers.email ~~~~~~~~~~~~~~~~~~~~~
Lexer for the raw E-mail.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, DelegatingLexer, bygroupsfrom pygments.lexers.mime import MIMELexerfrom pygments.token import Text, Keyword, Name, String, Number, Commentfrom pygments.util import get_bool_opt
__all__ = ["EmailLexer"]
class EmailHeaderLexer(RegexLexer): """ Sub-lexer for raw E-mail. This lexer only process header part of e-mail.
.. versionadded:: 2.5 """
def __init__(self, **options): super().__init__(**options) self.highlight_x = get_bool_opt(options, "highlight-X-header", False)
def get_x_header_tokens(self, match): if self.highlight_x: # field yield match.start(1), Name.Tag, match.group(1)
# content default_actions = self.get_tokens_unprocessed( match.group(2), stack=("root", "header")) yield from default_actions else: # lowlight yield match.start(1), Comment.Special, match.group(1) yield match.start(2), Comment.Multiline, match.group(2)
tokens = { "root": [ (r"^(?:[A-WYZ]|X400)[\w\-]*:", Name.Tag, "header"), (r"^(X-(?:\w[\w\-]*:))([\s\S]*?\n)(?![ \t])", get_x_header_tokens), ], "header": [ # folding (r"\n[ \t]", Text.Whitespace), (r"\n(?![ \t])", Text.Whitespace, "#pop"),
# keywords (r"\bE?SMTPS?\b", Keyword), (r"\b(?:HE|EH)LO\b", Keyword),
# mailbox (r"[\w\.\-\+=]+@[\w\.\-]+", Name.Label), (r"<[\w\.\-\+=]+@[\w\.\-]+>", Name.Label),
# domain (r"\b(\w[\w\.-]*\.[\w\.-]*\w[a-zA-Z]+)\b", Name.Function),
# IPv4 (r"(?<=\b)(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(?:25[0" r"-5]|2[0-4][0-9]|1?[0-9][0-9]?)(?=\b)", Number.Integer),
# IPv6 (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,7}:(?!\b)", Number.Hex), (r"(?<=\b):((:[0-9a-fA-F]{1,4}){1,7}|:)(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}(?=\b)", Number.Hex), (r"(?<=\b)[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})(?=\b)", Number.Hex), (r"(?<=\b)fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}(?=\b)", Number.Hex), (r"(?<=\b)::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}" r"[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}" r"[0-9])(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9])" r"{0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])(?=\b)", Number.Hex),
# Date time (r"(?:(Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s+)?(0[1-9]|[1-2]?[0-9]|3[" r"01])\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(" r"19[0-9]{2}|[2-9][0-9]{3})\s+(2[0-3]|[0-1][0-9]):([0-5][0-9])" r"(?::(60|[0-5][0-9]))?(?:\.\d{1,5})?\s+([-\+][0-9]{2}[0-5][0-" r"9]|\(?(?:UTC?|GMT|(?:E|C|M|P)(?:ST|ET|DT)|[A-IK-Z])\)?)", Name.Decorator),
# RFC-2047 encoded string (r"(=\?)([\w-]+)(\?)([BbQq])(\?)([\[\w!\"#$%&\'()*+,-./:;<=>@[\\" r"\]^_`{|}~]+)(\?=)", bygroups(String.Affix, Name.Constant, String.Affix, Keyword.Constant, String.Affix, Number.Hex, String.Affix)),
# others (r'[\s]+', Text.Whitespace), (r'[\S]', Text), ], }
class EmailLexer(DelegatingLexer): """ Lexer for raw E-mail.
Additional options accepted:
`highlight-X-header` Highlight the fields of ``X-`` user-defined email header. (default: ``False``). """
name = "E-mail" aliases = ["email", "eml"] filenames = ["*.eml"] mimetypes = ["message/rfc822"] url = "https://en.wikipedia.org/wiki/Email#Message_format" version_added = '2.5'
def __init__(self, **options): super().__init__(EmailHeaderLexer, MIMELexer, Comment, **options)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526""" pygments.lexers.erlang ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Erlang.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions, \ include, default, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace
__all__ = ['ErlangLexer', 'ErlangShellLexer', 'ElixirConsoleLexer', 'ElixirLexer']
class ErlangLexer(RegexLexer): """ For the Erlang functional programming language. """
name = 'Erlang' url = 'https://www.erlang.org/' aliases = ['erlang'] filenames = ['*.erl', '*.hrl', '*.es', '*.escript'] mimetypes = ['text/x-erlang'] version_added = '0.9'
keywords = ( 'after', 'begin', 'case', 'catch', 'cond', 'end', 'fun', 'if', 'let', 'of', 'query', 'receive', 'try', 'when', )
builtins = ( # See erlang(3) man page 'abs', 'append_element', 'apply', 'atom_to_list', 'binary_to_list', 'bitstring_to_list', 'binary_to_term', 'bit_size', 'bump_reductions', 'byte_size', 'cancel_timer', 'check_process_code', 'delete_module', 'demonitor', 'disconnect_node', 'display', 'element', 'erase', 'exit', 'float', 'float_to_list', 'fun_info', 'fun_to_list', 'function_exported', 'garbage_collect', 'get', 'get_keys', 'group_leader', 'hash', 'hd', 'integer_to_list', 'iolist_to_binary', 'iolist_size', 'is_atom', 'is_binary', 'is_bitstring', 'is_boolean', 'is_builtin', 'is_float', 'is_function', 'is_integer', 'is_list', 'is_number', 'is_pid', 'is_port', 'is_process_alive', 'is_record', 'is_reference', 'is_tuple', 'length', 'link', 'list_to_atom', 'list_to_binary', 'list_to_bitstring', 'list_to_existing_atom', 'list_to_float', 'list_to_integer', 'list_to_pid', 'list_to_tuple', 'load_module', 'localtime_to_universaltime', 'make_tuple', 'md5', 'md5_final', 'md5_update', 'memory', 'module_loaded', 'monitor', 'monitor_node', 'node', 'nodes', 'open_port', 'phash', 'phash2', 'pid_to_list', 'port_close', 'port_command', 'port_connect', 'port_control', 'port_call', 'port_info', 'port_to_list', 'process_display', 'process_flag', 'process_info', 'purge_module', 'put', 'read_timer', 'ref_to_list', 'register', 'resume_process', 'round', 'send', 'send_after', 'send_nosuspend', 'set_cookie', 'setelement', 'size', 'spawn', 'spawn_link', 'spawn_monitor', 'spawn_opt', 'split_binary', 'start_timer', 'statistics', 'suspend_process', 'system_flag', 'system_info', 'system_monitor', 'system_profile', 'term_to_binary', 'tl', 'trace', 'trace_delivered', 'trace_info', 'trace_pattern', 'trunc', 'tuple_size', 'tuple_to_list', 'universaltime_to_localtime', 'unlink', 'unregister', 'whereis' )
operators = r'(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)' word_operators = ( 'and', 'andalso', 'band', 'bnot', 'bor', 'bsl', 'bsr', 'bxor', 'div', 'not', 'or', 'orelse', 'rem', 'xor' )
atom_re = r"(?:[a-z]\w*|'[^\n']*[^\\]')"
variable_re = r'(?:[A-Z_]\w*)'
esc_char_re = r'[bdefnrstv\'"\\]' esc_octal_re = r'[0-7][0-7]?[0-7]?' esc_hex_re = r'(?:x[0-9a-fA-F]{2}|x\{[0-9a-fA-F]+\})' esc_ctrl_re = r'\^[a-zA-Z]' escape_re = r'(?:\\(?:'+esc_char_re+r'|'+esc_octal_re+r'|'+esc_hex_re+r'|'+esc_ctrl_re+r'))'
macro_re = r'(?:'+variable_re+r'|'+atom_re+r')'
base_re = r'(?:[2-9]|[12][0-9]|3[0-6])'
tokens = { 'root': [ (r'\s+', Whitespace), (r'(%.*)(\n)', bygroups(Comment, Whitespace)), (words(keywords, suffix=r'\b'), Keyword), (words(builtins, suffix=r'\b'), Name.Builtin), (words(word_operators, suffix=r'\b'), Operator.Word), (r'^-', Punctuation, 'directive'), (operators, Operator), (r'"', String, 'string'), (r'<<', Name.Label), (r'>>', Name.Label), ('(' + atom_re + ')(:)', bygroups(Name.Namespace, Punctuation)), ('(?:^|(?<=:))(' + atom_re + r')(\s*)(\()', bygroups(Name.Function, Whitespace, Punctuation)), (r'[+-]?' + base_re + r'#[0-9a-zA-Z]+', Number.Integer), (r'[+-]?\d+', Number.Integer), (r'[+-]?\d+.\d+', Number.Float), (r'[]\[:_@\".{}()|;,]', Punctuation), (variable_re, Name.Variable), (atom_re, Name), (r'\?'+macro_re, Name.Constant), (r'\$(?:'+escape_re+r'|\\[ %]|[^\\])', String.Char), (r'#'+atom_re+r'(:?\.'+atom_re+r')?', Name.Label),
# Erlang script shebang (r'\A#!.+\n', Comment.Hashbang),
# EEP 43: Maps # http://www.erlang.org/eeps/eep-0043.html (r'#\{', Punctuation, 'map_key'), ], 'string': [ (escape_re, String.Escape), (r'"', String, '#pop'), (r'~[0-9.*]*[~#+BPWXb-ginpswx]', String.Interpol), (r'[^"\\~]+', String), (r'~', String), ], 'directive': [ (r'(define)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Whitespace, Punctuation, Name.Constant), '#pop'), (r'(record)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Whitespace, Punctuation, Name.Label), '#pop'), (atom_re, Name.Entity, '#pop'), ], 'map_key': [ include('root'), (r'=>', Punctuation, 'map_val'), (r':=', Punctuation, 'map_val'), (r'\}', Punctuation, '#pop'), ], 'map_val': [ include('root'), (r',', Punctuation, '#pop'), (r'(?=\})', Punctuation, '#pop'), ], }
class ErlangShellLexer(Lexer): """ Shell sessions in erl (for Erlang code). """ name = 'Erlang erl session' aliases = ['erl'] filenames = ['*.erl-sh'] mimetypes = ['text/x-erl-shellsession'] url = 'https://www.erlang.org/' version_added = '1.1'
_prompt_re = re.compile(r'(?:\([\w@_.]+\))?\d+>(?=\s|\Z)')
def get_tokens_unprocessed(self, text): erlexer = ErlangLexer(**self.options)
curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() m = self._prompt_re.match(line) if m is not None: end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: yield from do_insertions(insertions, erlexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] if line.startswith('*'): yield match.start(), Generic.Traceback, line else: yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, erlexer.get_tokens_unprocessed(curcode))
def gen_elixir_string_rules(name, symbol, token): states = {} states['string_' + name] = [ (rf'[^#{symbol}\\]+', token), include('escapes'), (r'\\.', token), (rf'({symbol})', bygroups(token), "#pop"), include('interpol') ] return states
def gen_elixir_sigstr_rules(term, term_class, token, interpol=True): if interpol: return [ (rf'[^#{term_class}\\]+', token), include('escapes'), (r'\\.', token), (rf'{term}[a-zA-Z]*', token, '#pop'), include('interpol') ] else: return [ (rf'[^{term_class}\\]+', token), (r'\\.', token), (rf'{term}[a-zA-Z]*', token, '#pop'), ]
class ElixirLexer(RegexLexer): """ For the Elixir language. """
name = 'Elixir' url = 'https://elixir-lang.org' aliases = ['elixir', 'ex', 'exs'] filenames = ['*.ex', '*.eex', '*.exs', '*.leex'] mimetypes = ['text/x-elixir'] version_added = '1.5'
KEYWORD = ('fn', 'do', 'end', 'after', 'else', 'rescue', 'catch') KEYWORD_OPERATOR = ('not', 'and', 'or', 'when', 'in') BUILTIN = ( 'case', 'cond', 'for', 'if', 'unless', 'try', 'receive', 'raise', 'quote', 'unquote', 'unquote_splicing', 'throw', 'super', ) BUILTIN_DECLARATION = ( 'def', 'defp', 'defmodule', 'defprotocol', 'defmacro', 'defmacrop', 'defdelegate', 'defexception', 'defstruct', 'defimpl', 'defcallback', )
BUILTIN_NAMESPACE = ('import', 'require', 'use', 'alias') CONSTANT = ('nil', 'true', 'false')
PSEUDO_VAR = ('_', '__MODULE__', '__DIR__', '__ENV__', '__CALLER__')
OPERATORS3 = ( '<<<', '>>>', '|||', '&&&', '^^^', '~~~', '===', '!==', '~>>', '<~>', '|~>', '<|>', ) OPERATORS2 = ( '==', '!=', '<=', '>=', '&&', '||', '<>', '++', '--', '|>', '=~', '->', '<-', '|', '.', '=', '~>', '<~', ) OPERATORS1 = ('<', '>', '+', '-', '*', '/', '!', '^', '&')
PUNCTUATION = ( '\\\\', '<<', '>>', '=>', '(', ')', ':', ';', ',', '[', ']', )
def get_tokens_unprocessed(self, text): for index, token, value in RegexLexer.get_tokens_unprocessed(self, text): if token is Name: if value in self.KEYWORD: yield index, Keyword, value elif value in self.KEYWORD_OPERATOR: yield index, Operator.Word, value elif value in self.BUILTIN: yield index, Keyword, value elif value in self.BUILTIN_DECLARATION: yield index, Keyword.Declaration, value elif value in self.BUILTIN_NAMESPACE: yield index, Keyword.Namespace, value elif value in self.CONSTANT: yield index, Name.Constant, value elif value in self.PSEUDO_VAR: yield index, Name.Builtin.Pseudo, value else: yield index, token, value else: yield index, token, value
def gen_elixir_sigil_rules(): # all valid sigil terminators (excluding heredocs) terminators = [ (r'\{', r'\}', '}', 'cb'), (r'\[', r'\]', r'\]', 'sb'), (r'\(', r'\)', ')', 'pa'), ('<', '>', '>', 'ab'), ('/', '/', '/', 'slas'), (r'\|', r'\|', '|', 'pipe'), ('"', '"', '"', 'quot'), ("'", "'", "'", 'apos'), ]
# heredocs have slightly different rules triquotes = [(r'"""', 'triquot'), (r"'''", 'triapos')]
token = String.Other states = {'sigils': []}
for term, name in triquotes: states['sigils'] += [ (rf'(~[a-z])({term})', bygroups(token, String.Heredoc), (name + '-end', name + '-intp')), (rf'(~[A-Z])({term})', bygroups(token, String.Heredoc), (name + '-end', name + '-no-intp')), ]
states[name + '-end'] = [ (r'[a-zA-Z]+', token, '#pop'), default('#pop'), ] states[name + '-intp'] = [ (r'^(\s*)(' + term + ')', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_interpol'), ] states[name + '-no-intp'] = [ (r'^(\s*)(' + term +')', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_no_interpol'), ]
for lterm, rterm, rterm_class, name in terminators: states['sigils'] += [ (r'~[a-z]' + lterm, token, name + '-intp'), (r'~[A-Z]' + lterm, token, name + '-no-intp'), ] states[name + '-intp'] = \ gen_elixir_sigstr_rules(rterm, rterm_class, token) states[name + '-no-intp'] = \ gen_elixir_sigstr_rules(rterm, rterm_class, token, interpol=False)
return states
op3_re = "|".join(re.escape(s) for s in OPERATORS3) op2_re = "|".join(re.escape(s) for s in OPERATORS2) op1_re = "|".join(re.escape(s) for s in OPERATORS1) ops_re = rf'(?:{op3_re}|{op2_re}|{op1_re})' punctuation_re = "|".join(re.escape(s) for s in PUNCTUATION) alnum = r'\w' name_re = rf'(?:\.\.\.|[a-z_]{alnum}*[!?]?)' modname_re = rf'[A-Z]{alnum}*(?:\.[A-Z]{alnum}*)*' complex_name_re = rf'(?:{name_re}|{modname_re}|{ops_re})' special_atom_re = r'(?:\.\.\.|<<>>|%\{\}|%|\{\})'
long_hex_char_re = r'(\\x\{)([\da-fA-F]+)(\})' hex_char_re = r'(\\x[\da-fA-F]{1,2})' escape_char_re = r'(\\[abdefnrstv])'
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*$', Comment.Single),
# Various kinds of characters (r'(\?)' + long_hex_char_re, bygroups(String.Char, String.Escape, Number.Hex, String.Escape)), (r'(\?)' + hex_char_re, bygroups(String.Char, String.Escape)), (r'(\?)' + escape_char_re, bygroups(String.Char, String.Escape)), (r'\?\\?.', String.Char),
# '::' has to go before atoms (r':::', String.Symbol), (r'::', Operator),
# atoms (r':' + special_atom_re, String.Symbol), (r':' + complex_name_re, String.Symbol), (r':"', String.Symbol, 'string_double_atom'), (r":'", String.Symbol, 'string_single_atom'),
# [keywords: ...] (rf'({special_atom_re}|{complex_name_re})(:)(?=\s|\n)', bygroups(String.Symbol, Punctuation)),
# @attributes (r'@' + name_re, Name.Attribute),
# identifiers (name_re, Name), (rf'(%?)({modname_re})', bygroups(Punctuation, Name.Class)),
# operators and punctuation (op3_re, Operator), (op2_re, Operator), (punctuation_re, Punctuation), (r'&\d', Name.Entity), # anon func arguments (op1_re, Operator),
# numbers (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[\da-fA-F]+', Number.Hex), (r'\d(_?\d)*\.\d(_?\d)*([eE][-+]?\d(_?\d)*)?', Number.Float), (r'\d(_?\d)*', Number.Integer),
# strings and heredocs (r'(""")(\s*)', bygroups(String.Heredoc, Whitespace), 'heredoc_double'), (r"(''')(\s*)$", bygroups(String.Heredoc, Whitespace), 'heredoc_single'), (r'"', String.Double, 'string_double'), (r"'", String.Single, 'string_single'),
include('sigils'),
(r'%\{', Punctuation, 'map_key'), (r'\{', Punctuation, 'tuple'), ], 'heredoc_double': [ (r'^(\s*)(""")', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_interpol'), ], 'heredoc_single': [ (r"^\s*'''", String.Heredoc, '#pop'), include('heredoc_interpol'), ], 'heredoc_interpol': [ (r'[^#\\\n]+', String.Heredoc), include('escapes'), (r'\\.', String.Heredoc), (r'\n+', String.Heredoc), include('interpol'), ], 'heredoc_no_interpol': [ (r'[^\\\n]+', String.Heredoc), (r'\\.', String.Heredoc), (r'\n+', Whitespace), ], 'escapes': [ (long_hex_char_re, bygroups(String.Escape, Number.Hex, String.Escape)), (hex_char_re, String.Escape), (escape_char_re, String.Escape), ], 'interpol': [ (r'#\{', String.Interpol, 'interpol_string'), ], 'interpol_string': [ (r'\}', String.Interpol, "#pop"), include('root') ], 'map_key': [ include('root'), (r':', Punctuation, 'map_val'), (r'=>', Punctuation, 'map_val'), (r'\}', Punctuation, '#pop'), ], 'map_val': [ include('root'), (r',', Punctuation, '#pop'), (r'(?=\})', Punctuation, '#pop'), ], 'tuple': [ include('root'), (r'\}', Punctuation, '#pop'), ], } tokens.update(gen_elixir_string_rules('double', '"', String.Double)) tokens.update(gen_elixir_string_rules('single', "'", String.Single)) tokens.update(gen_elixir_string_rules('double_atom', '"', String.Symbol)) tokens.update(gen_elixir_string_rules('single_atom', "'", String.Symbol)) tokens.update(gen_elixir_sigil_rules())
class ElixirConsoleLexer(Lexer): """ For Elixir interactive console (iex) output like:
.. sourcecode:: iex
iex> [head | tail] = [1,2,3] [1,2,3] iex> head 1 iex> tail [2,3] iex> [head | tail] [1,2,3] iex> length [head | tail] 3 """
name = 'Elixir iex session' aliases = ['iex'] mimetypes = ['text/x-elixir-shellsession'] url = 'https://elixir-lang.org' version_added = '1.5'
_prompt_re = re.compile(r'(iex|\.{3})((?:\([\w@_.]+\))?\d+|\(\d+\))?> ')
def get_tokens_unprocessed(self, text): exlexer = ElixirLexer(**self.options)
curcode = '' in_error = False insertions = [] for match in line_re.finditer(text): line = match.group() if line.startswith('** '): in_error = True insertions.append((len(curcode), [(0, Generic.Error, line[:-1])])) curcode += line[-1:] else: m = self._prompt_re.match(line) if m is not None: in_error = False end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: yield from do_insertions( insertions, exlexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] token = Generic.Error if in_error else Generic.Output yield match.start(), token, line if curcode: yield from do_insertions( insertions, exlexer.get_tokens_unprocessed(curcode))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300""" pygments.lexers.esoteric ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for esoteric languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Error, Whitespace
__all__ = ['BrainfuckLexer', 'BefungeLexer', 'RedcodeLexer', 'CAmkESLexer', 'CapDLLexer', 'AheuiLexer']
class BrainfuckLexer(RegexLexer): """ Lexer for the esoteric BrainFuck language. """
name = 'Brainfuck' url = 'http://www.muppetlabs.com/~breadbox/bf/' aliases = ['brainfuck', 'bf'] filenames = ['*.bf', '*.b'] mimetypes = ['application/x-brainfuck'] version_added = ''
tokens = { 'common': [ # use different colors for different instruction types (r'[.,]+', Name.Tag), (r'[+-]+', Name.Builtin), (r'[<>]+', Name.Variable), (r'[^.,+\-<>\[\]]+', Comment), ], 'root': [ (r'\[', Keyword, 'loop'), (r'\]', Error), include('common'), ], 'loop': [ (r'\[', Keyword, '#push'), (r'\]', Keyword, '#pop'), include('common'), ] }
def analyse_text(text): """It's safe to assume that a program which mostly consists of + - and < > is brainfuck.""" plus_minus_count = 0 greater_less_count = 0
range_to_check = max(256, len(text))
for c in text[:range_to_check]: if c == '+' or c == '-': plus_minus_count += 1 if c == '<' or c == '>': greater_less_count += 1
if plus_minus_count > (0.25 * range_to_check): return 1.0 if greater_less_count > (0.25 * range_to_check): return 1.0
result = 0 if '[-]' in text: result += 0.5
return result
class BefungeLexer(RegexLexer): """ Lexer for the esoteric Befunge language. """ name = 'Befunge' url = 'http://en.wikipedia.org/wiki/Befunge' aliases = ['befunge'] filenames = ['*.befunge'] mimetypes = ['application/x-befunge'] version_added = '0.7'
tokens = { 'root': [ (r'[0-9a-f]', Number), (r'[+*/%!`-]', Operator), # Traditional math (r'[<>^v?\[\]rxjk]', Name.Variable), # Move, imperatives (r'[:\\$.,n]', Name.Builtin), # Stack ops, imperatives (r'[|_mw]', Keyword), (r'[{}]', Name.Tag), # Befunge-98 stack ops (r'".*?"', String.Double), # Strings don't appear to allow escapes (r'\'.', String.Single), # Single character (r'[#;]', Comment), # Trampoline... depends on direction hit (r'[pg&~=@iotsy]', Keyword), # Misc (r'[()A-Z]', Comment), # Fingerprints (r'\s+', Whitespace), # Whitespace doesn't matter ], }
class CAmkESLexer(RegexLexer): """ Basic lexer for the input language for the CAmkES component platform. """ name = 'CAmkES' url = 'https://sel4.systems/CAmkES/' aliases = ['camkes', 'idl4'] filenames = ['*.camkes', '*.idl4'] version_added = '2.1'
tokens = { 'root': [ # C pre-processor directive (r'^(\s*)(#.*)(\n)', bygroups(Whitespace, Comment.Preproc, Whitespace)),
# Whitespace, comments (r'\s+', Whitespace), (r'/\*(.|\n)*?\*/', Comment), (r'//.*$', Comment),
(r'[\[(){},.;\]]', Punctuation), (r'[~!%^&*+=|?:<>/-]', Operator),
(words(('assembly', 'attribute', 'component', 'composition', 'configuration', 'connection', 'connector', 'consumes', 'control', 'dataport', 'Dataport', 'Dataports', 'emits', 'event', 'Event', 'Events', 'export', 'from', 'group', 'hardware', 'has', 'interface', 'Interface', 'maybe', 'procedure', 'Procedure', 'Procedures', 'provides', 'template', 'thread', 'threads', 'to', 'uses', 'with'), suffix=r'\b'), Keyword),
(words(('bool', 'boolean', 'Buf', 'char', 'character', 'double', 'float', 'in', 'inout', 'int', 'int16_6', 'int32_t', 'int64_t', 'int8_t', 'integer', 'mutex', 'out', 'real', 'refin', 'semaphore', 'signed', 'string', 'struct', 'uint16_t', 'uint32_t', 'uint64_t', 'uint8_t', 'uintptr_t', 'unsigned', 'void'), suffix=r'\b'), Keyword.Type),
# Recognised attributes (r'[a-zA-Z_]\w*_(priority|domain|buffer)', Keyword.Reserved), (words(('dma_pool', 'from_access', 'to_access'), suffix=r'\b'), Keyword.Reserved),
# CAmkES-level include (r'(import)(\s+)((?:<[^>]*>|"[^"]*");)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)),
# C-level include (r'(include)(\s+)((?:<[^>]*>|"[^"]*");)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)),
# Literals (r'0[xX][\da-fA-F]+', Number.Hex), (r'-?[\d]+', Number), (r'-?[\d]+\.[\d]+', Number.Float), (r'"[^"]*"', String), (r'[Tt]rue|[Ff]alse', Name.Builtin),
# Identifiers (r'[a-zA-Z_]\w*', Name), ], }
class CapDLLexer(RegexLexer): """ Basic lexer for CapDL.
The source of the primary tool that reads such specifications is available at https://github.com/seL4/capdl/tree/master/capDL-tool. Note that this lexer only supports a subset of the grammar. For example, identifiers can shadow type names, but these instances are currently incorrectly highlighted as types. Supporting this would need a stateful lexer that is considered unnecessarily complex for now. """ name = 'CapDL' url = 'https://ssrg.nicta.com.au/publications/nictaabstracts/Kuz_KLW_10.abstract.pml' aliases = ['capdl'] filenames = ['*.cdl'] version_added = '2.2'
tokens = { 'root': [ # C pre-processor directive (r'^(\s*)(#.*)(\n)', bygroups(Whitespace, Comment.Preproc, Whitespace)),
# Whitespace, comments (r'\s+', Whitespace), (r'/\*(.|\n)*?\*/', Comment), (r'(//|--).*$', Comment),
(r'[<>\[(){},:;=\]]', Punctuation), (r'\.\.', Punctuation),
(words(('arch', 'arm11', 'caps', 'child_of', 'ia32', 'irq', 'maps', 'objects'), suffix=r'\b'), Keyword),
(words(('aep', 'asid_pool', 'cnode', 'ep', 'frame', 'io_device', 'io_ports', 'io_pt', 'notification', 'pd', 'pt', 'tcb', 'ut', 'vcpu'), suffix=r'\b'), Keyword.Type),
# Properties (words(('asid', 'addr', 'badge', 'cached', 'dom', 'domainID', 'elf', 'fault_ep', 'G', 'guard', 'guard_size', 'init', 'ip', 'prio', 'sp', 'R', 'RG', 'RX', 'RW', 'RWG', 'RWX', 'W', 'WG', 'WX', 'level', 'masked', 'master_reply', 'paddr', 'ports', 'reply', 'uncached'), suffix=r'\b'), Keyword.Reserved),
# Literals (r'0[xX][\da-fA-F]+', Number.Hex), (r'\d+(\.\d+)?(k|M)?', Number), (words(('bits',), suffix=r'\b'), Number), (words(('cspace', 'vspace', 'reply_slot', 'caller_slot', 'ipc_buffer_slot'), suffix=r'\b'), Number),
# Identifiers (r'[a-zA-Z_][-@\.\w]*', Name), ], }
class RedcodeLexer(RegexLexer): """ A simple Redcode lexer based on ICWS'94. Contributed by Adam Blinkinsop <blinks@acm.org>. """ name = 'Redcode' aliases = ['redcode'] filenames = ['*.cw'] url = 'https://en.wikipedia.org/wiki/Core_War' version_added = '0.8'
opcodes = ('DAT', 'MOV', 'ADD', 'SUB', 'MUL', 'DIV', 'MOD', 'JMP', 'JMZ', 'JMN', 'DJN', 'CMP', 'SLT', 'SPL', 'ORG', 'EQU', 'END') modifiers = ('A', 'B', 'AB', 'BA', 'F', 'X', 'I')
tokens = { 'root': [ # Whitespace: (r'\s+', Whitespace), (r';.*$', Comment.Single), # Lexemes: # Identifiers (r'\b({})\b'.format('|'.join(opcodes)), Name.Function), (r'\b({})\b'.format('|'.join(modifiers)), Name.Decorator), (r'[A-Za-z_]\w+', Name), # Operators (r'[-+*/%]', Operator), (r'[#$@<>]', Operator), # mode (r'[.,]', Punctuation), # mode # Numbers (r'[-+]?\d+', Number.Integer), ], }
class AheuiLexer(RegexLexer): """ Aheui is esoteric language based on Korean alphabets. """
name = 'Aheui' url = 'http://aheui.github.io/' aliases = ['aheui'] filenames = ['*.aheui'] version_added = ''
tokens = { 'root': [ ('[' '나-낳냐-냫너-넣녀-녛노-놓뇨-눟뉴-닇' '다-닿댜-댷더-덯뎌-뎧도-돟됴-둫듀-딓' '따-땋땨-떃떠-떻뗘-뗳또-똫뚀-뚷뜌-띟' '라-랗랴-럏러-렇려-렿로-롷료-뤃류-릫' '마-맣먀-먛머-멓며-몋모-뫃묘-뭏뮤-믷' '바-밯뱌-뱧버-벟벼-볗보-봏뵤-붛뷰-빃' '빠-빻뺘-뺳뻐-뻫뼈-뼣뽀-뽛뾰-뿧쀼-삏' '사-샇샤-샿서-섷셔-셯소-솧쇼-숳슈-싛' '싸-쌓쌰-썋써-쎃쎠-쎻쏘-쏳쑈-쑿쓔-씧' '자-잫쟈-쟣저-젛져-졓조-좋죠-줗쥬-즿' '차-챃챠-챻처-첳쳐-쳫초-촣쵸-춯츄-칗' '카-캏캬-컇커-컿켜-켷코-콯쿄-쿻큐-킣' '타-탛탸-턓터-텋텨-톃토-톻툐-퉇튜-틯' '파-팧퍄-퍟퍼-펗펴-폏포-퐇표-풓퓨-픻' '하-핳햐-햫허-헣혀-혛호-홓효-훟휴-힇' ']', Operator), ('.', Comment), ], }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576""" pygments.lexers.ezhil ~~~~~~~~~~~~~~~~~~~~~
Pygments lexers for Ezhil language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Keyword, Comment, Name, String, Number, \ Punctuation, Operator, Whitespace
__all__ = ['EzhilLexer']
class EzhilLexer(RegexLexer): """ Lexer for Ezhil, a Tamil script-based programming language. """ name = 'Ezhil' url = 'http://ezhillang.org' aliases = ['ezhil'] filenames = ['*.n'] mimetypes = ['text/x-ezhil'] version_added = '2.1' # Refer to tamil.utf8.tamil_letters from open-tamil for a stricter version of this. # This much simpler version is close enough, and includes combining marks. _TALETTERS = '[a-zA-Z_]|[\u0b80-\u0bff]' tokens = { 'root': [ include('keywords'), (r'#.*$', Comment.Single), (r'[@+/*,^\-%]|[!<>=]=?|&&?|\|\|?', Operator), ('இல்', Operator.Word), (words(('assert', 'max', 'min', 'நீளம்', 'சரம்_இடமாற்று', 'சரம்_கண்டுபிடி', 'பட்டியல்', 'பின்இணை', 'வரிசைப்படுத்து', 'எடு', 'தலைகீழ்', 'நீட்டிக்க', 'நுழைக்க', 'வை', 'கோப்பை_திற', 'கோப்பை_எழுது', 'கோப்பை_மூடு', 'pi', 'sin', 'cos', 'tan', 'sqrt', 'hypot', 'pow', 'exp', 'log', 'log10', 'exit', ), suffix=r'\b'), Name.Builtin), (r'(True|False)\b', Keyword.Constant), (r'[^\S\n]+', Whitespace), include('identifier'), include('literal'), (r'[(){}\[\]:;.]', Punctuation), ], 'keywords': [ ('பதிப்பி|தேர்ந்தெடு|தேர்வு|ஏதேனில்|ஆனால்|இல்லைஆனால்|இல்லை|ஆக|ஒவ்வொன்றாக|இல்|வரை|செய்|முடியேனில்|பின்கொடு|முடி|நிரல்பாகம்|தொடர்|நிறுத்து|நிரல்பாகம்', Keyword), ], 'identifier': [ ('(?:'+_TALETTERS+')(?:[0-9]|'+_TALETTERS+')*', Name), ], 'literal': [ (r'".*?"', String), (r'\d+((\.\d*)?[eE][+-]?\d+|\.\d*)', Number.Float), (r'\d+', Number.Integer), ] }
def analyse_text(text): """This language uses Tamil-script. We'll assume that if there's a decent amount of Tamil-characters, it's this language. This assumption is obviously horribly off if someone uses string literals in tamil in another language.""" if len(re.findall(r'[\u0b80-\u0bff]', text)) > 10: return 0.25
def __init__(self, **options): super().__init__(**options) self.encoding = options.get('encoding', 'utf-8')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363""" pygments.lexers.factor ~~~~~~~~~~~~~~~~~~~~~~
Lexers for the Factor language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, default, wordsfrom pygments.token import Text, Comment, Keyword, Name, String, Number, \ Whitespace, Punctuation
__all__ = ['FactorLexer']
class FactorLexer(RegexLexer): """ Lexer for the Factor language. """ name = 'Factor' url = 'http://factorcode.org' aliases = ['factor'] filenames = ['*.factor'] mimetypes = ['text/x-factor'] version_added = '1.4'
builtin_kernel = words(( '-rot', '2bi', '2bi@', '2bi*', '2curry', '2dip', '2drop', '2dup', '2keep', '2nip', '2over', '2tri', '2tri@', '2tri*', '3bi', '3curry', '3dip', '3drop', '3dup', '3keep', '3tri', '4dip', '4drop', '4dup', '4keep', '<wrapper>', '=', '>boolean', 'clone', '?', '?execute', '?if', 'and', 'assert', 'assert=', 'assert?', 'bi', 'bi-curry', 'bi-curry@', 'bi-curry*', 'bi@', 'bi*', 'boa', 'boolean', 'boolean?', 'both?', 'build', 'call', 'callstack', 'callstack>array', 'callstack?', 'clear', '(clone)', 'compose', 'compose?', 'curry', 'curry?', 'datastack', 'die', 'dip', 'do', 'drop', 'dup', 'dupd', 'either?', 'eq?', 'equal?', 'execute', 'hashcode', 'hashcode*', 'identity-hashcode', 'identity-tuple', 'identity-tuple?', 'if', 'if*', 'keep', 'loop', 'most', 'new', 'nip', 'not', 'null', 'object', 'or', 'over', 'pick', 'prepose', 'retainstack', 'rot', 'same?', 'swap', 'swapd', 'throw', 'tri', 'tri-curry', 'tri-curry@', 'tri-curry*', 'tri@', 'tri*', 'tuple', 'tuple?', 'unless', 'unless*', 'until', 'when', 'when*', 'while', 'with', 'wrapper', 'wrapper?', 'xor'), suffix=r'(\s+)')
builtin_assocs = words(( '2cache', '<enum>', '>alist', '?at', '?of', 'assoc', 'assoc-all?', 'assoc-any?', 'assoc-clone-like', 'assoc-combine', 'assoc-diff', 'assoc-diff!', 'assoc-differ', 'assoc-each', 'assoc-empty?', 'assoc-filter', 'assoc-filter!', 'assoc-filter-as', 'assoc-find', 'assoc-hashcode', 'assoc-intersect', 'assoc-like', 'assoc-map', 'assoc-map-as', 'assoc-partition', 'assoc-refine', 'assoc-size', 'assoc-stack', 'assoc-subset?', 'assoc-union', 'assoc-union!', 'assoc=', 'assoc>map', 'assoc?', 'at', 'at+', 'at*', 'cache', 'change-at', 'clear-assoc', 'delete-at', 'delete-at*', 'enum', 'enum?', 'extract-keys', 'inc-at', 'key?', 'keys', 'map>assoc', 'maybe-set-at', 'new-assoc', 'of', 'push-at', 'rename-at', 'set-at', 'sift-keys', 'sift-values', 'substitute', 'unzip', 'value-at', 'value-at*', 'value?', 'values', 'zip'), suffix=r'(\s+)')
builtin_combinators = words(( '2cleave', '2cleave>quot', '3cleave', '3cleave>quot', '4cleave', '4cleave>quot', 'alist>quot', 'call-effect', 'case', 'case-find', 'case>quot', 'cleave', 'cleave>quot', 'cond', 'cond>quot', 'deep-spread>quot', 'execute-effect', 'linear-case-quot', 'no-case', 'no-case?', 'no-cond', 'no-cond?', 'recursive-hashcode', 'shallow-spread>quot', 'spread', 'to-fixed-point', 'wrong-values', 'wrong-values?'), suffix=r'(\s+)')
builtin_math = words(( '-', '/', '/f', '/i', '/mod', '2/', '2^', '<', '<=', '<fp-nan>', '>', '>=', '>bignum', '>fixnum', '>float', '>integer', '(all-integers?)', '(each-integer)', '(find-integer)', '*', '+', '?1+', 'abs', 'align', 'all-integers?', 'bignum', 'bignum?', 'bit?', 'bitand', 'bitnot', 'bitor', 'bits>double', 'bits>float', 'bitxor', 'complex', 'complex?', 'denominator', 'double>bits', 'each-integer', 'even?', 'find-integer', 'find-last-integer', 'fixnum', 'fixnum?', 'float', 'float>bits', 'float?', 'fp-bitwise=', 'fp-infinity?', 'fp-nan-payload', 'fp-nan?', 'fp-qnan?', 'fp-sign', 'fp-snan?', 'fp-special?', 'if-zero', 'imaginary-part', 'integer', 'integer>fixnum', 'integer>fixnum-strict', 'integer?', 'log2', 'log2-expects-positive', 'log2-expects-positive?', 'mod', 'neg', 'neg?', 'next-float', 'next-power-of-2', 'number', 'number=', 'number?', 'numerator', 'odd?', 'out-of-fixnum-range', 'out-of-fixnum-range?', 'power-of-2?', 'prev-float', 'ratio', 'ratio?', 'rational', 'rational?', 'real', 'real-part', 'real?', 'recip', 'rem', 'sgn', 'shift', 'sq', 'times', 'u<', 'u<=', 'u>', 'u>=', 'unless-zero', 'unordered?', 'when-zero', 'zero?'), suffix=r'(\s+)')
builtin_sequences = words(( '1sequence', '2all?', '2each', '2map', '2map-as', '2map-reduce', '2reduce', '2selector', '2sequence', '3append', '3append-as', '3each', '3map', '3map-as', '3sequence', '4sequence', '<repetition>', '<reversed>', '<slice>', '?first', '?last', '?nth', '?second', '?set-nth', 'accumulate', 'accumulate!', 'accumulate-as', 'all?', 'any?', 'append', 'append!', 'append-as', 'assert-sequence', 'assert-sequence=', 'assert-sequence?', 'binary-reduce', 'bounds-check', 'bounds-check?', 'bounds-error', 'bounds-error?', 'but-last', 'but-last-slice', 'cartesian-each', 'cartesian-map', 'cartesian-product', 'change-nth', 'check-slice', 'check-slice-error', 'clone-like', 'collapse-slice', 'collector', 'collector-for', 'concat', 'concat-as', 'copy', 'count', 'cut', 'cut-slice', 'cut*', 'delete-all', 'delete-slice', 'drop-prefix', 'each', 'each-from', 'each-index', 'empty?', 'exchange', 'filter', 'filter!', 'filter-as', 'find', 'find-from', 'find-index', 'find-index-from', 'find-last', 'find-last-from', 'first', 'first2', 'first3', 'first4', 'flip', 'follow', 'fourth', 'glue', 'halves', 'harvest', 'head', 'head-slice', 'head-slice*', 'head*', 'head?', 'if-empty', 'immutable', 'immutable-sequence', 'immutable-sequence?', 'immutable?', 'index', 'index-from', 'indices', 'infimum', 'infimum-by', 'insert-nth', 'interleave', 'iota', 'iota-tuple', 'iota-tuple?', 'join', 'join-as', 'last', 'last-index', 'last-index-from', 'length', 'lengthen', 'like', 'longer', 'longer?', 'longest', 'map', 'map!', 'map-as', 'map-find', 'map-find-last', 'map-index', 'map-integers', 'map-reduce', 'map-sum', 'max-length', 'member-eq?', 'member?', 'midpoint@', 'min-length', 'mismatch', 'move', 'new-like', 'new-resizable', 'new-sequence', 'non-negative-integer-expected', 'non-negative-integer-expected?', 'nth', 'nths', 'pad-head', 'pad-tail', 'padding', 'partition', 'pop', 'pop*', 'prefix', 'prepend', 'prepend-as', 'produce', 'produce-as', 'product', 'push', 'push-all', 'push-either', 'push-if', 'reduce', 'reduce-index', 'remove', 'remove!', 'remove-eq', 'remove-eq!', 'remove-nth', 'remove-nth!', 'repetition', 'repetition?', 'replace-slice', 'replicate', 'replicate-as', 'rest', 'rest-slice', 'reverse', 'reverse!', 'reversed', 'reversed?', 'second', 'selector', 'selector-for', 'sequence', 'sequence-hashcode', 'sequence=', 'sequence?', 'set-first', 'set-fourth', 'set-last', 'set-length', 'set-nth', 'set-second', 'set-third', 'short', 'shorten', 'shorter', 'shorter?', 'shortest', 'sift', 'slice', 'slice-error', 'slice-error?', 'slice?', 'snip', 'snip-slice', 'start', 'start*', 'subseq', 'subseq?', 'suffix', 'suffix!', 'sum', 'sum-lengths', 'supremum', 'supremum-by', 'surround', 'tail', 'tail-slice', 'tail-slice*', 'tail*', 'tail?', 'third', 'trim', 'trim-head', 'trim-head-slice', 'trim-slice', 'trim-tail', 'trim-tail-slice', 'unclip', 'unclip-last', 'unclip-last-slice', 'unclip-slice', 'unless-empty', 'virtual-exemplar', 'virtual-sequence', 'virtual-sequence?', 'virtual@', 'when-empty'), suffix=r'(\s+)')
builtin_namespaces = words(( '+@', 'change', 'change-global', 'counter', 'dec', 'get', 'get-global', 'global', 'inc', 'init-namespaces', 'initialize', 'is-global', 'make-assoc', 'namespace', 'namestack', 'off', 'on', 'set', 'set-global', 'set-namestack', 'toggle', 'with-global', 'with-scope', 'with-variable', 'with-variables'), suffix=r'(\s+)')
builtin_arrays = words(( '1array', '2array', '3array', '4array', '<array>', '>array', 'array', 'array?', 'pair', 'pair?', 'resize-array'), suffix=r'(\s+)')
builtin_io = words(( '(each-stream-block-slice)', '(each-stream-block)', '(stream-contents-by-block)', '(stream-contents-by-element)', '(stream-contents-by-length-or-block)', '(stream-contents-by-length)', '+byte+', '+character+', 'bad-seek-type', 'bad-seek-type?', 'bl', 'contents', 'each-block', 'each-block-size', 'each-block-slice', 'each-line', 'each-morsel', 'each-stream-block', 'each-stream-block-slice', 'each-stream-line', 'error-stream', 'flush', 'input-stream', 'input-stream?', 'invalid-read-buffer', 'invalid-read-buffer?', 'lines', 'nl', 'output-stream', 'output-stream?', 'print', 'read', 'read-into', 'read-partial', 'read-partial-into', 'read-until', 'read1', 'readln', 'seek-absolute', 'seek-absolute?', 'seek-end', 'seek-end?', 'seek-input', 'seek-output', 'seek-relative', 'seek-relative?', 'stream-bl', 'stream-contents', 'stream-contents*', 'stream-copy', 'stream-copy*', 'stream-element-type', 'stream-flush', 'stream-length', 'stream-lines', 'stream-nl', 'stream-print', 'stream-read', 'stream-read-into', 'stream-read-partial', 'stream-read-partial-into', 'stream-read-partial-unsafe', 'stream-read-unsafe', 'stream-read-until', 'stream-read1', 'stream-readln', 'stream-seek', 'stream-seekable?', 'stream-tell', 'stream-write', 'stream-write1', 'tell-input', 'tell-output', 'with-error-stream', 'with-error-stream*', 'with-error>output', 'with-input-output+error-streams', 'with-input-output+error-streams*', 'with-input-stream', 'with-input-stream*', 'with-output-stream', 'with-output-stream*', 'with-output>error', 'with-output+error-stream', 'with-output+error-stream*', 'with-streams', 'with-streams*', 'write', 'write1'), suffix=r'(\s+)')
builtin_strings = words(( '1string', '<string>', '>string', 'resize-string', 'string', 'string?'), suffix=r'(\s+)')
builtin_vectors = words(( '1vector', '<vector>', '>vector', '?push', 'vector', 'vector?'), suffix=r'(\s+)')
builtin_continuations = words(( '<condition>', '<continuation>', '<restart>', 'attempt-all', 'attempt-all-error', 'attempt-all-error?', 'callback-error-hook', 'callcc0', 'callcc1', 'cleanup', 'compute-restarts', 'condition', 'condition?', 'continuation', 'continuation?', 'continue', 'continue-restart', 'continue-with', 'current-continuation', 'error', 'error-continuation', 'error-in-thread', 'error-thread', 'ifcc', 'ignore-errors', 'in-callback?', 'original-error', 'recover', 'restart', 'restart?', 'restarts', 'rethrow', 'rethrow-restarts', 'return', 'return-continuation', 'thread-error-hook', 'throw-continue', 'throw-restarts', 'with-datastack', 'with-return'), suffix=r'(\s+)')
tokens = { 'root': [ # factor allows a file to start with a shebang (r'#!.*$', Comment.Preproc), default('base'), ], 'base': [ (r'\s+', Whitespace),
# defining words (r'((?:MACRO|MEMO|TYPED)?:[:]?)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(M:[:]?)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Name.Function)), (r'(C:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Name.Class)), (r'(GENERIC:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(HOOK:|GENERIC#)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Name.Function)), (r'(\()(\s)', bygroups(Name.Function, Whitespace), 'stackeffect'), (r'(;)(\s)', bygroups(Keyword, Whitespace)),
# imports and namespaces (r'(USING:)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'vocabs'), (r'(USE:|UNUSE:|IN:|QUALIFIED:)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r'(QUALIFIED-WITH:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace, Whitespace, Name.Namespace)), (r'(FROM:|EXCLUDE:)(\s+)(\S+)(\s+=>\s)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace, Whitespace), 'words'), (r'(RENAME:)(\s+)(\S+)(\s+)(\S+)(\s+)(=>)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Function, Whitespace, Name.Namespace, Whitespace, Punctuation, Whitespace, Name.Function)), (r'(ALIAS:|TYPEDEF:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Function, Whitespace, Name.Function)), (r'(DEFER:|FORGET:|POSTPONE:)(\s+)(\S+)', bygroups(Keyword.Namespace, Whitespace, Name.Function)),
# tuples and classes (r'(TUPLE:|ERROR:)(\s+)(\S+)(\s+)(<)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Punctuation, Whitespace, Name.Class), 'slots'), (r'(TUPLE:|ERROR:|BUILTIN:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class), 'slots'), (r'(MIXIN:|UNION:|INTERSECTION:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class)), (r'(PREDICATE:)(\s+)(\S+)(\s+)(<)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Punctuation, Whitespace, Name.Class)), (r'(C:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Name.Class)), (r'(INSTANCE:)(\s+)(\S+)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Name.Class)), (r'(SLOT:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(SINGLETON:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class)), (r'SINGLETONS:', Keyword, 'classes'),
# other syntax (r'(CONSTANT:|SYMBOL:|MAIN:|HELP:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Function)), (r'(SYMBOLS:)(\s+)', bygroups(Keyword, Whitespace), 'words'), (r'(SYNTAX:)(\s+)', bygroups(Keyword, Whitespace)), (r'(ALIEN:)(\s+)', bygroups(Keyword, Whitespace)), (r'(STRUCT:)(\s+)(\S+)', bygroups(Keyword, Whitespace, Name.Class)), (r'(FUNCTION:)(\s+)' r'(\S+)(\s+)(\S+)(\s+)' r'(\()(\s+)([^)]+)(\))(\s)', bygroups(Keyword.Namespace, Whitespace, Text, Whitespace, Name.Function, Whitespace, Punctuation, Whitespace, Text, Punctuation, Whitespace)), (r'(FUNCTION-ALIAS:)(\s+)' r'(\S+)(\s+)(\S+)(\s+)' r'(\S+)(\s+)' r'(\()(\s+)([^)]+)(\))(\s)', bygroups(Keyword.Namespace, Whitespace, Text, Whitespace, Name.Function, Whitespace, Name.Function, Whitespace, Punctuation, Whitespace, Text, Punctuation, Whitespace)),
# vocab.private (r'(<PRIVATE|PRIVATE>)(\s)', bygroups(Keyword.Namespace, Whitespace)),
# strings (r'"""\s(?:.|\n)*?\s"""', String), (r'"(?:\\\\|\\"|[^"])*"', String), (r'(\S+")(\s+)((?:\\\\|\\"|[^"])*")', bygroups(String, Whitespace, String)), (r'(CHAR:)(\s+)(\\[\\abfnrstv]|[^\\]\S*)(\s)', bygroups(String.Char, Whitespace, String.Char, Whitespace)),
# comments (r'!\s+.*$', Comment), (r'#!\s+.*$', Comment), (r'/\*\s+(?:.|\n)*?\s\*/', Comment),
# boolean constants (r'[tf]\b', Name.Constant),
# symbols and literals (r'[\\$]\s+\S+', Name.Constant), (r'M\\\s+\S+\s+\S+', Name.Constant),
# numbers (r'[+-]?(?:[\d,]*\d)?\.(?:\d([\d,]*\d)?)?(?:[eE][+-]?\d+)?\s', Number), (r'[+-]?\d(?:[\d,]*\d)?(?:[eE][+-]?\d+)?\s', Number), (r'0x[a-fA-F\d](?:[a-fA-F\d,]*[a-fA-F\d])?(?:p\d([\d,]*\d)?)?\s', Number), (r'NAN:\s+[a-fA-F\d](?:[a-fA-F\d,]*[a-fA-F\d])?(?:p\d([\d,]*\d)?)?\s', Number), (r'0b[01]+\s', Number.Bin), (r'0o[0-7]+\s', Number.Oct), (r'(?:\d([\d,]*\d)?)?\+\d(?:[\d,]*\d)?/\d(?:[\d,]*\d)?\s', Number), (r'(?:\-\d([\d,]*\d)?)?\-\d(?:[\d,]*\d)?/\d(?:[\d,]*\d)?\s', Number),
# keywords (r'(?:deprecated|final|foldable|flushable|inline|recursive)\s', Keyword),
# builtins (builtin_kernel, bygroups(Name.Builtin, Whitespace)), (builtin_assocs, bygroups(Name.Builtin, Whitespace)), (builtin_combinators, bygroups(Name.Builtin, Whitespace)), (builtin_math, bygroups(Name.Builtin, Whitespace)), (builtin_sequences, bygroups(Name.Builtin, Whitespace)), (builtin_namespaces, bygroups(Name.Builtin, Whitespace)), (builtin_arrays, bygroups(Name.Builtin, Whitespace)), (builtin_io, bygroups(Name.Builtin, Whitespace)), (builtin_strings, bygroups(Name.Builtin, Whitespace)), (builtin_vectors, bygroups(Name.Builtin, Whitespace)), (builtin_continuations, bygroups(Name.Builtin, Whitespace)),
# everything else is text (r'\S+', Text), ], 'stackeffect': [ (r'\s+', Whitespace), (r'(\()(\s+)', bygroups(Name.Function, Whitespace), 'stackeffect'), (r'(\))(\s+)', bygroups(Name.Function, Whitespace), '#pop'), (r'(--)(\s+)', bygroups(Name.Function, Whitespace)), (r'\S+', Name.Variable), ], 'slots': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'(\{)(\s+)(\S+)(\s+)([^}]+)(\s+)(\})(\s+)', bygroups(Text, Whitespace, Name.Variable, Whitespace, Text, Whitespace, Text, Whitespace)), (r'\S+', Name.Variable), ], 'vocabs': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'\S+', Name.Namespace), ], 'classes': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'\S+', Name.Class), ], 'words': [ (r'\s+', Whitespace), (r'(;)(\s+)', bygroups(Keyword, Whitespace), '#pop'), (r'\S+', Name.Function), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251""" pygments.lexers.fantom ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Fantom language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from string import Template
from pygments.lexer import RegexLexer, include, bygroups, using, \ this, default, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Literal, Whitespace
__all__ = ['FantomLexer']
class FantomLexer(RegexLexer): """ For Fantom source code. """ name = 'Fantom' aliases = ['fan'] filenames = ['*.fan'] mimetypes = ['application/x-fantom'] url = 'https://www.fantom.org' version_added = '1.5'
# often used regexes def s(str): return Template(str).substitute( dict( pod=r'[\"\w\.]+', eos=r'\n|;', id=r'[a-zA-Z_]\w*', # all chars which can be part of type definition. Starts with # either letter, or [ (maps), or | (funcs) type=r'(?:\[|[a-zA-Z_]|\|)[:\w\[\]|\->?]*?', ) )
tokens = { 'comments': [ (r'(?s)/\*.*?\*/', Comment.Multiline), # Multiline (r'//.*?$', Comment.Single), # Single line # TODO: highlight references in fandocs (r'\*\*.*?$', Comment.Special), # Fandoc (r'#.*$', Comment.Single) # Shell-style ], 'literals': [ (r'\b-?[\d_]+(ns|ms|sec|min|hr|day)', Number), # Duration (r'\b-?[\d_]*\.[\d_]+(ns|ms|sec|min|hr|day)', Number), # Duration with dot (r'\b-?(\d+)?\.\d+(f|F|d|D)?', Number.Float), # Float/Decimal (r'\b-?0x[0-9a-fA-F_]+', Number.Hex), # Hex (r'\b-?[\d_]+', Number.Integer), # Int (r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char), # Char (r'"', Punctuation, 'insideStr'), # Opening quote (r'`', Punctuation, 'insideUri'), # Opening accent (r'\b(true|false|null)\b', Keyword.Constant), # Bool & null (r'(?:(\w+)(::))?(\w+)(<\|)(.*?)(\|>)', # DSL bygroups(Name.Namespace, Punctuation, Name.Class, Punctuation, String, Punctuation)), (r'(?:(\w+)(::))?(\w+)?(#)(\w+)?', # Type/slot literal bygroups(Name.Namespace, Punctuation, Name.Class, Punctuation, Name.Function)), (r'\[,\]', Literal), # Empty list (s(r'($type)(\[,\])'), # Typed empty list bygroups(using(this, state='inType'), Literal)), (r'\[:\]', Literal), # Empty Map (s(r'($type)(\[:\])'), bygroups(using(this, state='inType'), Literal)), ], 'insideStr': [ (r'\\\\', String.Escape), # Escaped backslash (r'\\"', String.Escape), # Escaped " (r'\\`', String.Escape), # Escaped ` (r'\$\w+', String.Interpol), # Subst var (r'\$\{.*?\}', String.Interpol), # Subst expr (r'"', Punctuation, '#pop'), # Closing quot (r'.', String) # String content ], 'insideUri': [ # TODO: remove copy/paste str/uri (r'\\\\', String.Escape), # Escaped backslash (r'\\"', String.Escape), # Escaped " (r'\\`', String.Escape), # Escaped ` (r'\$\w+', String.Interpol), # Subst var (r'\$\{.*?\}', String.Interpol), # Subst expr (r'`', Punctuation, '#pop'), # Closing tick (r'.', String.Backtick) # URI content ], 'protectionKeywords': [ (r'\b(public|protected|private|internal)\b', Keyword), ], 'typeKeywords': [ (r'\b(abstract|final|const|native|facet|enum)\b', Keyword), ], 'methodKeywords': [ (r'\b(abstract|native|once|override|static|virtual|final)\b', Keyword), ], 'fieldKeywords': [ (r'\b(abstract|const|final|native|override|static|virtual|' r'readonly)\b', Keyword) ], 'otherKeywords': [ (words(( 'try', 'catch', 'throw', 'finally', 'for', 'if', 'else', 'while', 'as', 'is', 'isnot', 'switch', 'case', 'default', 'continue', 'break', 'do', 'return', 'get', 'set'), prefix=r'\b', suffix=r'\b'), Keyword), (r'\b(it|this|super)\b', Name.Builtin.Pseudo), ], 'operators': [ (r'\+\+|\-\-|\+|\-|\*|/|\|\||&&|<=>|<=|<|>=|>|=|!|\[|\]', Operator) ], 'inType': [ (r'[\[\]|\->:?]', Punctuation), (s(r'$id'), Name.Class), default('#pop'),
], 'root': [ include('comments'), include('protectionKeywords'), include('typeKeywords'), include('methodKeywords'), include('fieldKeywords'), include('literals'), include('otherKeywords'), include('operators'), (r'using\b', Keyword.Namespace, 'using'), # Using stmt (r'@\w+', Name.Decorator, 'facet'), # Symbol (r'(class|mixin)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Class), 'inheritance'), # Inheritance list
# Type var := val (s(r'($type)([ \t]+)($id)(\s*)(:=)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Operator)),
# var := val (s(r'($id)(\s*)(:=)'), bygroups(Name.Variable, Whitespace, Operator)),
# .someId( or ->someId( ### (s(r'(\.|(?:\->))($id)(\s*)(\()'), bygroups(Operator, Name.Function, Whitespace, Punctuation), 'insideParen'),
# .someId or ->someId (s(r'(\.|(?:\->))($id)'), bygroups(Operator, Name.Function)),
# new makeXXX ( (r'(new)(\s+)(make\w*)(\s*)(\()', bygroups(Keyword, Whitespace, Name.Function, Whitespace, Punctuation), 'insideMethodDeclArgs'),
# Type name ( (s(r'($type)([ \t]+)' # Return type and whitespace r'($id)(\s*)(\()'), # method name + open brace bygroups(using(this, state='inType'), Whitespace, Name.Function, Whitespace, Punctuation), 'insideMethodDeclArgs'),
# ArgType argName, (s(r'($type)(\s+)($id)(\s*)(,)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation)),
# ArgType argName) # Covered in 'insideParen' state
# ArgType argName -> ArgType| (s(r'($type)(\s+)($id)(\s*)(\->)(\s*)($type)(\|)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation, Whitespace, using(this, state='inType'), Punctuation)),
# ArgType argName| (s(r'($type)(\s+)($id)(\s*)(\|)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation)),
# Type var (s(r'($type)([ \t]+)($id)'), bygroups(using(this, state='inType'), Whitespace, Name.Variable)),
(r'\(', Punctuation, 'insideParen'), (r'\{', Punctuation, 'insideBrace'), (r'\s+', Whitespace), (r'.', Text) ], 'insideParen': [ (r'\)', Punctuation, '#pop'), include('root'), ], 'insideMethodDeclArgs': [ (r'\)', Punctuation, '#pop'), (s(r'($type)(\s+)($id)(\s*)(\))'), bygroups(using(this, state='inType'), Whitespace, Name.Variable, Whitespace, Punctuation), '#pop'), include('root'), ], 'insideBrace': [ (r'\}', Punctuation, '#pop'), include('root'), ], 'inheritance': [ (r'\s+', Whitespace), # Whitespace (r':|,', Punctuation), (r'(?:(\w+)(::))?(\w+)', bygroups(Name.Namespace, Punctuation, Name.Class)), (r'\{', Punctuation, '#pop') ], 'using': [ (r'[ \t]+', Whitespace), # consume whitespaces (r'(\[)(\w+)(\])', bygroups(Punctuation, Comment.Special, Punctuation)), # ffi (r'(\")?([\w.]+)(\")?', bygroups(Punctuation, Name.Namespace, Punctuation)), # podname (r'::', Punctuation, 'usingClass'), default('#pop') ], 'usingClass': [ (r'[ \t]+', Whitespace), # consume whitespaces (r'(as)(\s+)(\w+)', bygroups(Keyword.Declaration, Whitespace, Name.Class), '#pop:2'), (r'[\w$]+', Name.Class), default('#pop:2') # jump out to root state ], 'facet': [ (r'\s+', Whitespace), (r'\{', Punctuation, 'facetFields'), default('#pop') ], 'facetFields': [ include('comments'), include('literals'), include('operators'), (r'\s+', Whitespace), (r'(\s*)(\w+)(\s*)(=)', bygroups(Whitespace, Name, Whitespace, Operator)), (r'\}', Punctuation, '#pop'), (r'\s+', Whitespace), (r'.', Text) ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275""" pygments.lexers.felix ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Felix language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroups, default, words, \ combinedfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['FelixLexer']
class FelixLexer(RegexLexer): """ For Felix source code. """
name = 'Felix' url = 'http://www.felix-lang.org' aliases = ['felix', 'flx'] filenames = ['*.flx', '*.flxh'] mimetypes = ['text/x-felix'] version_added = '1.2'
preproc = ( 'elif', 'else', 'endif', 'if', 'ifdef', 'ifndef', )
keywords = ( '_', '_deref', 'all', 'as', 'assert', 'attempt', 'call', 'callback', 'case', 'caseno', 'cclass', 'code', 'compound', 'ctypes', 'do', 'done', 'downto', 'elif', 'else', 'endattempt', 'endcase', 'endif', 'endmatch', 'enum', 'except', 'exceptions', 'expect', 'finally', 'for', 'forall', 'forget', 'fork', 'functor', 'goto', 'ident', 'if', 'incomplete', 'inherit', 'instance', 'interface', 'jump', 'lambda', 'loop', 'match', 'module', 'namespace', 'new', 'noexpand', 'nonterm', 'obj', 'of', 'open', 'parse', 'raise', 'regexp', 'reglex', 'regmatch', 'rename', 'return', 'the', 'then', 'to', 'type', 'typecase', 'typedef', 'typematch', 'typeof', 'upto', 'when', 'whilst', 'with', 'yield', )
keyword_directives = ( '_gc_pointer', '_gc_type', 'body', 'comment', 'const', 'export', 'header', 'inline', 'lval', 'macro', 'noinline', 'noreturn', 'package', 'private', 'pod', 'property', 'public', 'publish', 'requires', 'todo', 'virtual', 'use', )
keyword_declarations = ( 'def', 'let', 'ref', 'val', 'var', )
keyword_types = ( 'unit', 'void', 'any', 'bool', 'byte', 'offset', 'address', 'caddress', 'cvaddress', 'vaddress', 'tiny', 'short', 'int', 'long', 'vlong', 'utiny', 'ushort', 'vshort', 'uint', 'ulong', 'uvlong', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float', 'double', 'ldouble', 'complex', 'dcomplex', 'lcomplex', 'imaginary', 'dimaginary', 'limaginary', 'char', 'wchar', 'uchar', 'charp', 'charcp', 'ucharp', 'ucharcp', 'string', 'wstring', 'ustring', 'cont', 'array', 'varray', 'list', 'lvalue', 'opt', 'slice', )
keyword_constants = ( 'false', 'true', )
operator_words = ( 'and', 'not', 'in', 'is', 'isin', 'or', 'xor', )
name_builtins = ( '_svc', 'while', )
name_pseudo = ( 'root', 'self', 'this', )
decimal_suffixes = '([tTsSiIlLvV]|ll|LL|([iIuU])(8|16|32|64))?'
tokens = { 'root': [ include('whitespace'),
# Keywords (words(('axiom', 'ctor', 'fun', 'gen', 'proc', 'reduce', 'union'), suffix=r'\b'), Keyword, 'funcname'), (words(('class', 'cclass', 'cstruct', 'obj', 'struct'), suffix=r'\b'), Keyword, 'classname'), (r'(instance|module|typeclass)\b', Keyword, 'modulename'),
(words(keywords, suffix=r'\b'), Keyword), (words(keyword_directives, suffix=r'\b'), Name.Decorator), (words(keyword_declarations, suffix=r'\b'), Keyword.Declaration), (words(keyword_types, suffix=r'\b'), Keyword.Type), (words(keyword_constants, suffix=r'\b'), Keyword.Constant),
# Operators include('operators'),
# Float Literal # -- Hex Float (r'0[xX]([0-9a-fA-F_]*\.[0-9a-fA-F_]+|[0-9a-fA-F_]+)' r'[pP][+\-]?[0-9_]+[lLfFdD]?', Number.Float), # -- DecimalFloat (r'[0-9_]+(\.[0-9_]+[eE][+\-]?[0-9_]+|' r'\.[0-9_]*|[eE][+\-]?[0-9_]+)[lLfFdD]?', Number.Float), (r'\.(0|[1-9][0-9_]*)([eE][+\-]?[0-9_]+)?[lLfFdD]?', Number.Float),
# IntegerLiteral # -- Binary (rf'0[Bb][01_]+{decimal_suffixes}', Number.Bin), # -- Octal (rf'0[0-7_]+{decimal_suffixes}', Number.Oct), # -- Hexadecimal (rf'0[xX][0-9a-fA-F_]+{decimal_suffixes}', Number.Hex), # -- Decimal (rf'(0|[1-9][0-9_]*){decimal_suffixes}', Number.Integer),
# Strings ('([rR][cC]?|[cC][rR])"""', String, 'tdqs'), ("([rR][cC]?|[cC][rR])'''", String, 'tsqs'), ('([rR][cC]?|[cC][rR])"', String, 'dqs'), ("([rR][cC]?|[cC][rR])'", String, 'sqs'), ('[cCfFqQwWuU]?"""', String, combined('stringescape', 'tdqs')), ("[cCfFqQwWuU]?'''", String, combined('stringescape', 'tsqs')), ('[cCfFqQwWuU]?"', String, combined('stringescape', 'dqs')), ("[cCfFqQwWuU]?'", String, combined('stringescape', 'sqs')),
# Punctuation (r'[\[\]{}:(),;?]', Punctuation),
# Labels (r'[a-zA-Z_]\w*:>', Name.Label),
# Identifiers (r'({})\b'.format('|'.join(name_builtins)), Name.Builtin), (r'({})\b'.format('|'.join(name_pseudo)), Name.Builtin.Pseudo), (r'[a-zA-Z_]\w*', Name), ], 'whitespace': [ (r'\s+', Whitespace),
include('comment'),
# Preprocessor (r'(#)(\s*)(if)(\s+)(0)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Whitespace, Comment.Preproc), 'if0'), (r'#', Comment.Preproc, 'macro'), ], 'operators': [ (r'({})\b'.format('|'.join(operator_words)), Operator.Word), (r'!=|==|<<|>>|\|\||&&|[-~+/*%=<>&^|.$]', Operator), ], 'comment': [ (r'//(.*?)$', Comment.Single), (r'/[*]', Comment.Multiline, 'comment2'), ], 'comment2': [ (r'[^/*]', Comment.Multiline), (r'/[*]', Comment.Multiline, '#push'), (r'[*]/', Comment.Multiline, '#pop'), (r'[/*]', Comment.Multiline), ], 'if0': [ (r'^(\s*)(#if.*?(?<!\\))(\n)', bygroups(Whitespace, Comment, Whitespace), '#push'), (r'^(\s*)(#endif.*?(?<!\\))(\n)', bygroups(Whitespace, Comment, Whitespace), '#pop'), (r'(.*?)(\n)', bygroups(Comment, Whitespace)), ], 'macro': [ include('comment'), (r'(import|include)(\s+)(<[^>]*?>)', bygroups(Comment.Preproc, Whitespace, String), '#pop'), (r'(import|include)(\s+)("[^"]*?")', bygroups(Comment.Preproc, Whitespace, String), '#pop'), (r"(import|include)(\s+)('[^']*?')", bygroups(Comment.Preproc, Whitespace, String), '#pop'), (r'[^/\n]+', Comment.Preproc), # (r'/[*](.|\n)*?[*]/', Comment), # (r'//.*?\n', Comment, '#pop'), (r'/', Comment.Preproc), (r'(?<=\\)\n', Comment.Preproc), (r'\n', Whitespace, '#pop'), ], 'funcname': [ include('whitespace'), (r'[a-zA-Z_]\w*', Name.Function, '#pop'), # anonymous functions (r'(?=\()', Text, '#pop'), ], 'classname': [ include('whitespace'), (r'[a-zA-Z_]\w*', Name.Class, '#pop'), # anonymous classes (r'(?=\{)', Text, '#pop'), ], 'modulename': [ include('whitespace'), (r'\[', Punctuation, ('modulename2', 'tvarlist')), default('modulename2'), ], 'modulename2': [ include('whitespace'), (r'([a-zA-Z_]\w*)', Name.Namespace, '#pop:2'), ], 'tvarlist': [ include('whitespace'), include('operators'), (r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), (r',', Punctuation), (r'(with|where)\b', Keyword), (r'[a-zA-Z_]\w*', Name), ], 'stringescape': [ (r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|' r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], 'strings': [ (r'%(\([a-zA-Z0-9]+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' '[hlL]?[E-GXc-giorsux%]', String.Interpol), (r'[^\\\'"%\n]+', String), # quotes, percents and backslashes must be parsed one at a time (r'[\'"\\]', String), # unhandled string formatting sign (r'%', String) # newlines are an error (use "nl" state) ], 'nl': [ (r'\n', String) ], 'dqs': [ (r'"', String, '#pop'), # included here again for raw strings (r'\\\\|\\"|\\\n', String.Escape), include('strings') ], 'sqs': [ (r"'", String, '#pop'), # included here again for raw strings (r"\\\\|\\'|\\\n", String.Escape), include('strings') ], 'tdqs': [ (r'"""', String, '#pop'), include('strings'), include('nl') ], 'tsqs': [ (r"'''", String, '#pop'), include('strings'), include('nl') ], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768""" pygments.lexers.fift ~~~~~~~~~~~~~~~~~~~~
Lexers for fift.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, includefrom pygments.token import Literal, Comment, Name, String, Number, Whitespace
__all__ = ['FiftLexer']
class FiftLexer(RegexLexer): """ For Fift source code. """
name = 'Fift' aliases = ['fift', 'fif'] filenames = ['*.fif'] url = 'https://ton-blockchain.github.io/docs/fiftbase.pdf' version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace),
include('comments'),
(r'[\.+]?\"', String, 'string'),
# numbers (r'0x[0-9a-fA-F]+', Number.Hex), (r'0b[01]+', Number.Bin), (r'-?[0-9]+("/"-?[0-9]+)?', Number.Decimal),
# slices (r'b\{[01]+\}', Literal), (r'x\{[0-9a-fA-F_]+\}', Literal),
# byte literal (r'B\{[0-9a-fA-F_]+\}', Literal),
# treat anything as word (r'\S+', Name) ],
'string': [ (r'\\.', String.Escape), (r'\"', String, '#pop'), (r'[^\"\r\n\\]+', String) ],
'comments': [ (r'//.*', Comment.Singleline), (r'/\*', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081""" pygments.lexers.floscript ~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for FloScript
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['FloScriptLexer']
class FloScriptLexer(RegexLexer): """ For FloScript configuration language source code. """
name = 'FloScript' url = 'https://github.com/ioflo/ioflo' aliases = ['floscript', 'flo'] filenames = ['*.flo'] version_added = '2.4'
def innerstring_rules(ttype): return [ # the old style '%s' % (...) string formatting (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' '[hlL]?[E-GXc-giorsux%]', String.Interpol), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"%\n]+', ttype), (r'[\'"\\]', ttype), # unhandled string formatting sign (r'%', ttype), # newlines are an error (use "nl" state) ]
tokens = { 'root': [ (r'\s+', Whitespace),
(r'[]{}:(),;[]', Punctuation), (r'(\\)(\n)', bygroups(Text, Whitespace)), (r'\\', Text), (r'(to|by|with|from|per|for|cum|qua|via|as|at|in|of|on|re|is|if|be|into|' r'and|not)\b', Operator.Word), (r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator), (r'(load|init|server|logger|log|loggee|first|over|under|next|done|timeout|' r'repeat|native|benter|enter|recur|exit|precur|renter|rexit|print|put|inc|' r'copy|set|aux|rear|raze|go|let|do|bid|ready|start|stop|run|abort|use|flo|' r'give|take)\b', Name.Builtin), (r'(frame|framer|house)\b', Keyword), ('"', String, 'string'),
include('name'), include('numbers'), (r'#.+$', Comment.Single), ], 'string': [ ('[^"]+', String), ('"', String, '#pop'), ], 'numbers': [ (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float), (r'\d+[eE][+-]?[0-9]+j?', Number.Float), (r'0[0-7]+j?', Number.Oct), (r'0[bB][01]+', Number.Bin), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+j?', Number.Integer) ],
'name': [ (r'@[\w.]+', Name.Decorator), (r'[a-zA-Z_]\w*', Name), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178""" pygments.lexers.forth ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Forth language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Text, Comment, Keyword, Name, String, Number, \ Whitespace
__all__ = ['ForthLexer']
class ForthLexer(RegexLexer): """ Lexer for Forth files. """ name = 'Forth' url = 'https://www.forth.com/forth/' aliases = ['forth'] filenames = ['*.frt', '*.fs'] mimetypes = ['application/x-forth'] version_added = '2.2'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'\s+', Whitespace), # All comment types (r'\\.*?$', Comment.Single), (r'\([\s].*?\)', Comment.Single), # defining words. The next word is a new command name (r'(:|variable|constant|value|buffer:)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'worddef'), # strings are rather simple (r'([.sc]")(\s+?)', bygroups(String, Whitespace), 'stringdef'), # keywords from the various wordsets # *** Wordset BLOCK (r'(blk|block|buffer|evaluate|flush|load|save-buffers|update|' # *** Wordset BLOCK-EXT r'empty-buffers|list|refill|scr|thru|' # *** Wordset CORE r'\#s|\*\/mod|\+loop|\/mod|0<|0=|1\+|1-|2!|' r'2\*|2\/|2@|2drop|2dup|2over|2swap|>body|' r'>in|>number|>r|\?dup|abort|abort\"|abs|' r'accept|align|aligned|allot|and|base|begin|' r'bl|c!|c,|c@|cell\+|cells|char|char\+|' r'chars|constant|count|cr|create|decimal|' r'depth|do|does>|drop|dup|else|emit|environment\?|' r'evaluate|execute|exit|fill|find|fm\/mod|' r'here|hold|i|if|immediate|invert|j|key|' r'leave|literal|loop|lshift|m\*|max|min|' r'mod|move|negate|or|over|postpone|quit|' r'r>|r@|recurse|repeat|rot|rshift|s\"|s>d|' r'sign|sm\/rem|source|space|spaces|state|swap|' r'then|type|u\.|u\<|um\*|um\/mod|unloop|until|' r'variable|while|word|xor|\[char\]|\[\'\]|' r'@|!|\#|<\#|\#>|:|;|\+|-|\*|\/|,|<|>|\|1\+|1-|\.|' # *** Wordset CORE-EXT r'\.r|0<>|' r'0>|2>r|2r>|2r@|:noname|\?do|again|c\"|' r'case|compile,|endcase|endof|erase|false|' r'hex|marker|nip|of|pad|parse|pick|refill|' r'restore-input|roll|save-input|source-id|to|' r'true|tuck|u\.r|u>|unused|value|within|' r'\[compile\]|' # *** Wordset CORE-EXT-obsolescent r'\#tib|convert|expect|query|span|' r'tib|' # *** Wordset DOUBLE r'2constant|2literal|2variable|d\+|d-|' r'd\.|d\.r|d0<|d0=|d2\*|d2\/|d<|d=|d>s|' r'dabs|dmax|dmin|dnegate|m\*\/|m\+|' # *** Wordset DOUBLE-EXT r'2rot|du<|' # *** Wordset EXCEPTION r'catch|throw|' # *** Wordset EXCEPTION-EXT r'abort|abort\"|' # *** Wordset FACILITY r'at-xy|key\?|page|' # *** Wordset FACILITY-EXT r'ekey|ekey>char|ekey\?|emit\?|ms|time&date|' # *** Wordset FILE r'BIN|CLOSE-FILE|CREATE-FILE|DELETE-FILE|FILE-POSITION|' r'FILE-SIZE|INCLUDE-FILE|INCLUDED|OPEN-FILE|R\/O|' r'R\/W|READ-FILE|READ-LINE|REPOSITION-FILE|RESIZE-FILE|' r'S\"|SOURCE-ID|W/O|WRITE-FILE|WRITE-LINE|' # *** Wordset FILE-EXT r'FILE-STATUS|FLUSH-FILE|REFILL|RENAME-FILE|' # *** Wordset FLOAT r'>float|d>f|' r'f!|f\*|f\+|f-|f\/|f0<|f0=|f<|f>d|f@|' r'falign|faligned|fconstant|fdepth|fdrop|fdup|' r'fliteral|float\+|floats|floor|fmax|fmin|' r'fnegate|fover|frot|fround|fswap|fvariable|' r'represent|' # *** Wordset FLOAT-EXT r'df!|df@|dfalign|dfaligned|dfloat\+|' r'dfloats|f\*\*|f\.|fabs|facos|facosh|falog|' r'fasin|fasinh|fatan|fatan2|fatanh|fcos|fcosh|' r'fe\.|fexp|fexpm1|fln|flnp1|flog|fs\.|fsin|' r'fsincos|fsinh|fsqrt|ftan|ftanh|f~|precision|' r'set-precision|sf!|sf@|sfalign|sfaligned|sfloat\+|' r'sfloats|' # *** Wordset LOCAL r'\(local\)|to|' # *** Wordset LOCAL-EXT r'locals\||' # *** Wordset MEMORY r'allocate|free|resize|' # *** Wordset SEARCH r'definitions|find|forth-wordlist|get-current|' r'get-order|search-wordlist|set-current|set-order|' r'wordlist|' # *** Wordset SEARCH-EXT r'also|forth|only|order|previous|' # *** Wordset STRING r'-trailing|\/string|blank|cmove|cmove>|compare|' r'search|sliteral|' # *** Wordset TOOLS r'.s|dump|see|words|' # *** Wordset TOOLS-EXT r';code|' r'ahead|assembler|bye|code|cs-pick|cs-roll|' r'editor|state|\[else\]|\[if\]|\[then\]|' # *** Wordset TOOLS-EXT-obsolescent r'forget|' # Forth 2012 r'defer|defer@|defer!|action-of|begin-structure|field:|buffer:|' r'parse-name|buffer:|traverse-wordlist|n>r|nr>|2value|fvalue|' r'name>interpret|name>compile|name>string|' r'cfield:|end-structure)(?!\S)', Keyword),
# Numbers (r'(\$[0-9A-F]+)', Number.Hex), (r'(\#|%|&|\-|\+)?[0-9]+', Number.Integer), (r'(\#|%|&|\-|\+)?[0-9.]+', Keyword.Type), # amforth specific (r'(@i|!i|@e|!e|pause|noop|turnkey|sleep|' r'itype|icompare|sp@|sp!|rp@|rp!|up@|up!|' r'>a|a>|a@|a!|a@+|a@-|>b|b>|b@|b!|b@+|b@-|' r'find-name|1ms|' r'sp0|rp0|\(evaluate\)|int-trap|int!)(?!\S)', Name.Constant), # a proposal (r'(do-recognizer|r:fail|recognizer:|get-recognizers|' r'set-recognizers|r:float|r>comp|r>int|r>post|' r'r:name|r:word|r:dnum|r:num|recognizer|forth-recognizer|' r'rec:num|rec:float|rec:word)(?!\S)', Name.Decorator), # defining words. The next word is a new command name (r'(Evalue|Rvalue|Uvalue|Edefer|Rdefer|Udefer)(\s+)', bygroups(Keyword.Namespace, Text), 'worddef'),
(r'\S+', Name.Function), # Anything else is executed
], 'worddef': [ (r'\S+', Name.Class, '#pop'), ], 'stringdef': [ (r'[^"]+', String, '#pop'), ], }
def analyse_text(text): """Forth uses : COMMAND ; quite a lot in a single line, so we're trying to find that.""" if re.search('\n:[^\n]+;\n', text): return 0.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212""" pygments.lexers.fortran ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Fortran languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroups, include, words, using, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic
__all__ = ['FortranLexer', 'FortranFixedLexer']
class FortranLexer(RegexLexer): """ Lexer for FORTRAN 90 code. """ name = 'Fortran' url = 'https://fortran-lang.org/' aliases = ['fortran', 'f90'] filenames = ['*.f03', '*.f90', '*.F03', '*.F90'] mimetypes = ['text/x-fortran'] version_added = '0.10' flags = re.IGNORECASE | re.MULTILINE
# Data Types: INTEGER, REAL, COMPLEX, LOGICAL, CHARACTER and DOUBLE PRECISION # Operators: **, *, +, -, /, <, >, <=, >=, ==, /= # Logical (?): NOT, AND, OR, EQV, NEQV
# Builtins: # http://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Table-of-Intrinsic-Functions.html
tokens = { 'root': [ (r'^#.*\n', Comment.Preproc), (r'!.*\n', Comment), include('strings'), include('core'), (r'[a-z][\w$]*', Name), include('nums'), (r'[\s]+', Text.Whitespace), ], 'core': [ # Statements
(r'\b(DO)(\s+)(CONCURRENT)\b', bygroups(Keyword, Text.Whitespace, Keyword)), (r'\b(GO)(\s*)(TO)\b', bygroups(Keyword, Text.Whitespace, Keyword)),
(words(( 'ABSTRACT', 'ACCEPT', 'ALL', 'ALLSTOP', 'ALLOCATABLE', 'ALLOCATE', 'ARRAY', 'ASSIGN', 'ASSOCIATE', 'ASYNCHRONOUS', 'BACKSPACE', 'BIND', 'BLOCK', 'BLOCKDATA', 'BYTE', 'CALL', 'CASE', 'CLASS', 'CLOSE', 'CODIMENSION', 'COMMON', 'CONTIGUOUS', 'CONTAINS', 'CONTINUE', 'CRITICAL', 'CYCLE', 'DATA', 'DEALLOCATE', 'DECODE', 'DEFERRED', 'DIMENSION', 'DO', 'ELEMENTAL', 'ELSE', 'ELSEIF', 'ENCODE', 'END', 'ENDASSOCIATE', 'ENDBLOCK', 'ENDDO', 'ENDENUM', 'ENDFORALL', 'ENDFUNCTION', 'ENDIF', 'ENDINTERFACE', 'ENDMODULE', 'ENDPROGRAM', 'ENDSELECT', 'ENDSUBMODULE', 'ENDSUBROUTINE', 'ENDTYPE', 'ENDWHERE', 'ENTRY', 'ENUM', 'ENUMERATOR', 'EQUIVALENCE', 'ERROR STOP', 'EXIT', 'EXTENDS', 'EXTERNAL', 'EXTRINSIC', 'FILE', 'FINAL', 'FORALL', 'FORMAT', 'FUNCTION', 'GENERIC', 'IF', 'IMAGES', 'IMPLICIT', 'IMPORT', 'IMPURE', 'INCLUDE', 'INQUIRE', 'INTENT', 'INTERFACE', 'INTRINSIC', 'IS', 'LOCK', 'MEMORY', 'MODULE', 'NAMELIST', 'NULLIFY', 'NONE', 'NON_INTRINSIC', 'NON_OVERRIDABLE', 'NOPASS', 'ONLY', 'OPEN', 'OPTIONAL', 'OPTIONS', 'PARAMETER', 'PASS', 'PAUSE', 'POINTER', 'PRINT', 'PRIVATE', 'PROGRAM', 'PROCEDURE', 'PROTECTED', 'PUBLIC', 'PURE', 'READ', 'RECURSIVE', 'RESULT', 'RETURN', 'REWIND', 'SAVE', 'SELECT', 'SEQUENCE', 'STOP', 'SUBMODULE', 'SUBROUTINE', 'SYNC', 'SYNCALL', 'SYNCIMAGES', 'SYNCMEMORY', 'TARGET', 'THEN', 'TYPE', 'UNLOCK', 'USE', 'VALUE', 'VOLATILE', 'WHERE', 'WRITE', 'WHILE'), prefix=r'\b', suffix=r'\s*\b'), Keyword),
# Data Types (words(( 'CHARACTER', 'COMPLEX', 'DOUBLE PRECISION', 'DOUBLE COMPLEX', 'INTEGER', 'LOGICAL', 'REAL', 'C_INT', 'C_SHORT', 'C_LONG', 'C_LONG_LONG', 'C_SIGNED_CHAR', 'C_SIZE_T', 'C_INT8_T', 'C_INT16_T', 'C_INT32_T', 'C_INT64_T', 'C_INT_LEAST8_T', 'C_INT_LEAST16_T', 'C_INT_LEAST32_T', 'C_INT_LEAST64_T', 'C_INT_FAST8_T', 'C_INT_FAST16_T', 'C_INT_FAST32_T', 'C_INT_FAST64_T', 'C_INTMAX_T', 'C_INTPTR_T', 'C_FLOAT', 'C_DOUBLE', 'C_LONG_DOUBLE', 'C_FLOAT_COMPLEX', 'C_DOUBLE_COMPLEX', 'C_LONG_DOUBLE_COMPLEX', 'C_BOOL', 'C_CHAR', 'C_PTR', 'C_FUNPTR'), prefix=r'\b', suffix=r'\s*\b'), Keyword.Type),
# Operators (r'(\*\*|\*|\+|-|\/|<|>|<=|>=|==|\/=|=)', Operator),
(r'(::)', Keyword.Declaration),
(r'[()\[\],:&%;.]', Punctuation), # Intrinsics (words(( 'Abort', 'Abs', 'Access', 'AChar', 'ACos', 'ACosH', 'AdjustL', 'AdjustR', 'AImag', 'AInt', 'Alarm', 'All', 'Allocated', 'ALog', 'AMax', 'AMin', 'AMod', 'And', 'ANInt', 'Any', 'ASin', 'ASinH', 'Associated', 'ATan', 'ATanH', 'Atomic_Define', 'Atomic_Ref', 'BesJ', 'BesJN', 'Bessel_J0', 'Bessel_J1', 'Bessel_JN', 'Bessel_Y0', 'Bessel_Y1', 'Bessel_YN', 'BesY', 'BesYN', 'BGE', 'BGT', 'BLE', 'BLT', 'Bit_Size', 'BTest', 'CAbs', 'CCos', 'Ceiling', 'CExp', 'Char', 'ChDir', 'ChMod', 'CLog', 'Cmplx', 'Command_Argument_Count', 'Complex', 'Conjg', 'Cos', 'CosH', 'Count', 'CPU_Time', 'CShift', 'CSin', 'CSqRt', 'CTime', 'C_Loc', 'C_Associated', 'C_Null_Ptr', 'C_Null_Funptr', 'C_F_Pointer', 'C_F_ProcPointer', 'C_Null_Char', 'C_Alert', 'C_Backspace', 'C_Form_Feed', 'C_FunLoc', 'C_Sizeof', 'C_New_Line', 'C_Carriage_Return', 'C_Horizontal_Tab', 'C_Vertical_Tab', 'DAbs', 'DACos', 'DASin', 'DATan', 'Date_and_Time', 'DbesJ', 'DbesJN', 'DbesY', 'DbesYN', 'Dble', 'DCos', 'DCosH', 'DDiM', 'DErF', 'DErFC', 'DExp', 'Digits', 'DiM', 'DInt', 'DLog', 'DMax', 'DMin', 'DMod', 'DNInt', 'Dot_Product', 'DProd', 'DSign', 'DSinH', 'DShiftL', 'DShiftR', 'DSin', 'DSqRt', 'DTanH', 'DTan', 'DTime', 'EOShift', 'Epsilon', 'ErF', 'ErFC', 'ErFC_Scaled', 'ETime', 'Execute_Command_Line', 'Exit', 'Exp', 'Exponent', 'Extends_Type_Of', 'FDate', 'FGet', 'FGetC', 'FindLoc', 'Float', 'Floor', 'Flush', 'FNum', 'FPutC', 'FPut', 'Fraction', 'FSeek', 'FStat', 'FTell', 'Gamma', 'GError', 'GetArg', 'Get_Command', 'Get_Command_Argument', 'Get_Environment_Variable', 'GetCWD', 'GetEnv', 'GetGId', 'GetLog', 'GetPId', 'GetUId', 'GMTime', 'HostNm', 'Huge', 'Hypot', 'IAbs', 'IAChar', 'IAll', 'IAnd', 'IAny', 'IArgC', 'IBClr', 'IBits', 'IBSet', 'IChar', 'IDate', 'IDiM', 'IDInt', 'IDNInt', 'IEOr', 'IErrNo', 'IFix', 'Imag', 'ImagPart', 'Image_Index', 'Index', 'Int', 'IOr', 'IParity', 'IRand', 'IsaTty', 'IShft', 'IShftC', 'ISign', 'Iso_C_Binding', 'Is_Contiguous', 'Is_Iostat_End', 'Is_Iostat_Eor', 'ITime', 'Kill', 'Kind', 'LBound', 'LCoBound', 'Len', 'Len_Trim', 'LGe', 'LGt', 'Link', 'LLe', 'LLt', 'LnBlnk', 'Loc', 'Log', 'Log_Gamma', 'Logical', 'Long', 'LShift', 'LStat', 'LTime', 'MaskL', 'MaskR', 'MatMul', 'Max', 'MaxExponent', 'MaxLoc', 'MaxVal', 'MClock', 'Merge', 'Merge_Bits', 'Move_Alloc', 'Min', 'MinExponent', 'MinLoc', 'MinVal', 'Mod', 'Modulo', 'MvBits', 'Nearest', 'New_Line', 'NInt', 'Norm2', 'Not', 'Null', 'Num_Images', 'Or', 'Pack', 'Parity', 'PError', 'Precision', 'Present', 'Product', 'Radix', 'Rand', 'Random_Number', 'Random_Seed', 'Range', 'Real', 'RealPart', 'Rename', 'Repeat', 'Reshape', 'RRSpacing', 'RShift', 'Same_Type_As', 'Scale', 'Scan', 'Second', 'Selected_Char_Kind', 'Selected_Int_Kind', 'Selected_Real_Kind', 'Set_Exponent', 'Shape', 'ShiftA', 'ShiftL', 'ShiftR', 'Short', 'Sign', 'Signal', 'SinH', 'Sin', 'Sleep', 'Sngl', 'Spacing', 'Spread', 'SqRt', 'SRand', 'Stat', 'Storage_Size', 'Sum', 'SymLnk', 'System', 'System_Clock', 'Tan', 'TanH', 'Time', 'This_Image', 'Tiny', 'TrailZ', 'Transfer', 'Transpose', 'Trim', 'TtyNam', 'UBound', 'UCoBound', 'UMask', 'Unlink', 'Unpack', 'Verify', 'XOr', 'ZAbs', 'ZCos', 'ZExp', 'ZLog', 'ZSin', 'ZSqRt'), prefix=r'\b', suffix=r'\s*\b'), Name.Builtin),
# Booleans (r'\.(true|false)\.', Name.Builtin), # Comparing Operators (r'\.(eq|ne|lt|le|gt|ge|not|and|or|eqv|neqv)\.', Operator.Word), ],
'strings': [ (r'"(\\[0-7]+|\\[^0-7]|[^"\\])*"', String.Double), (r"'(\\[0-7]+|\\[^0-7]|[^'\\])*'", String.Single), ],
'nums': [ (r'\d+(?![.e])(_([1-9]|[a-z]\w*))?', Number.Integer), (r'[+-]?\d*\.\d+([ed][-+]?\d+)?(_([1-9]|[a-z]\w*))?', Number.Float), (r'[+-]?\d+\.\d*([ed][-+]?\d+)?(_([1-9]|[a-z]\w*))?', Number.Float), (r'[+-]?\d+(\.\d*)?[ed][-+]?\d+(_([1-9]|[a-z]\w*))?', Number.Float), ], }
class FortranFixedLexer(RegexLexer): """ Lexer for fixed format Fortran. """ name = 'FortranFixed' aliases = ['fortranfixed'] filenames = ['*.f', '*.F'] url = 'https://fortran-lang.org/' version_added = '2.1'
flags = re.IGNORECASE
def _lex_fortran(self, match, ctx=None): """Lex a line just as free form fortran without line break.""" lexer = FortranLexer() text = match.group(0) + "\n" for index, token, value in lexer.get_tokens_unprocessed(text): value = value.replace('\n', '') if value != '': yield index, token, value
tokens = { 'root': [ (r'[C*].*\n', Comment), (r'#.*\n', Comment.Preproc), (r' {0,4}!.*\n', Comment), (r'(.{5})', Name.Label, 'cont-char'), (r'.*\n', using(FortranLexer)), ], 'cont-char': [ (' ', Text, 'code'), ('0', Comment, 'code'), ('.', Generic.Strong, 'code'), ], 'code': [ (r'(.{66})(.*)(\n)', bygroups(_lex_fortran, Comment, Text.Whitespace), 'root'), (r'(.*)(\n)', bygroups(_lex_fortran, Text.Whitespace), 'root'), default('root'), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427""" pygments.lexers.foxpro ~~~~~~~~~~~~~~~~~~~~~~
Simple lexer for Microsoft Visual FoxPro source code.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexerfrom pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ Name, String
__all__ = ['FoxProLexer']
class FoxProLexer(RegexLexer): """Lexer for Microsoft Visual FoxPro language.
FoxPro syntax allows to shorten all keywords and function names to 4 characters. Shortened forms are not recognized by this lexer. """
name = 'FoxPro' aliases = ['foxpro', 'vfp', 'clipper', 'xbase'] filenames = ['*.PRG', '*.prg'] version_added = '1.6' mimetype = [] url = 'https://learn.microsoft.com/en-us/previous-versions/visualstudio/foxpro'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r';\s*\n', Punctuation), # consume newline (r'(^|\n)\s*', Text, 'newline'),
# Square brackets may be used for array indices # and for string literal. Look for arrays # before matching string literals. (r'(?<=\w)\[[0-9, ]+\]', Text), (r'\'[^\'\n]*\'|"[^"\n]*"|\[[^]*]\]', String), (r'(^\s*\*|&&|&&).*?\n', Comment.Single),
(r'(ABS|ACLASS|ACOPY|ACOS|ADATABASES|ADBOBJECTS|ADDBS|' r'ADDPROPERTY|ADEL|ADIR|ADLLS|ADOCKSTATE|AELEMENT|AERROR|' r'AEVENTS|AFIELDS|AFONT|AGETCLASS|AGETFILEVERSION|AINS|' r'AINSTANCE|ALANGUAGE|ALEN|ALIAS|ALINES|ALLTRIM|' r'AMEMBERS|AMOUSEOBJ|ANETRESOURCES|APRINTERS|APROCINFO|' r'ASC|ASCAN|ASELOBJ|ASESSIONS|ASIN|ASORT|ASQLHANDLES|' r'ASTACKINFO|ASUBSCRIPT|AT|AT_C|ATAGINFO|ATAN|ATC|ATCC|' r'ATCLINE|ATLINE|ATN2|AUSED|AVCXCLASSES|BAR|BARCOUNT|' r'BARPROMPT|BETWEEN|BINDEVENT|BINTOC|BITAND|BITCLEAR|' r'BITLSHIFT|BITNOT|BITOR|BITRSHIFT|BITSET|BITTEST|BITXOR|' r'BOF|CANDIDATE|CAPSLOCK|CAST|CDOW|CDX|CEILING|CHR|CHRSAW|' r'CHRTRAN|CHRTRANC|CLEARRESULTSET|CMONTH|CNTBAR|CNTPAD|COL|' r'COM|Functions|COMARRAY|COMCLASSINFO|COMPOBJ|COMPROP|' r'COMRETURNERROR|COS|CPCONVERT|CPCURRENT|CPDBF|CREATEBINARY|' r'CREATEOBJECT|CREATEOBJECTEX|CREATEOFFLINE|CTOBIN|CTOD|' r'CTOT|CURDIR|CURSORGETPROP|CURSORSETPROP|CURSORTOXML|' r'CURVAL|DATE|DATETIME|DAY|DBC|DBF|DBGETPROP|DBSETPROP|' r'DBUSED|DDEAbortTrans|DDEAdvise|DDEEnabled|DDEExecute|' r'DDEInitiate|DDELastError|DDEPoke|DDERequest|DDESetOption|' r'DDESetService|DDESetTopic|DDETerminate|DEFAULTEXT|' r'DELETED|DESCENDING|DIFFERENCE|DIRECTORY|DISKSPACE|' r'DisplayPath|DMY|DODEFAULT|DOW|DRIVETYPE|DROPOFFLINE|' r'DTOC|DTOR|DTOS|DTOT|EDITSOURCE|EMPTY|EOF|ERROR|EVAL(UATE)?|' r'EVENTHANDLER|EVL|EXECSCRIPT|EXP|FCHSIZE|FCLOSE|FCOUNT|' r'FCREATE|FDATE|FEOF|FERROR|FFLUSH|FGETS|FIELD|FILE|' r'FILETOSTR|FILTER|FKLABEL|FKMAX|FLDLIST|FLOCK|FLOOR|' r'FONTMETRIC|FOPEN|FOR|FORCEEXT|FORCEPATH|FOUND|FPUTS|' r'FREAD|FSEEK|FSIZE|FTIME|FULLPATH|FV|FWRITE|' r'GETAUTOINCVALUE|GETBAR|GETCOLOR|GETCP|GETDIR|GETENV|' r'GETFILE|GETFLDSTATE|GETFONT|GETINTERFACE|' r'GETNEXTMODIFIED|GETOBJECT|GETPAD|GETPEM|GETPICT|' r'GETPRINTER|GETRESULTSET|GETWORDCOUNT|GETWORDNUM|' r'GETCURSORADAPTER|GOMONTH|HEADER|HOME|HOUR|ICASE|' r'IDXCOLLATE|IIF|IMESTATUS|INDBC|INDEXSEEK|INKEY|INLIST|' r'INPUTBOX|INSMODE|INT|ISALPHA|ISBLANK|ISCOLOR|ISDIGIT|' r'ISEXCLUSIVE|ISFLOCKED|ISLEADBYTE|ISLOWER|ISMEMOFETCHED|' r'ISMOUSE|ISNULL|ISPEN|ISREADONLY|ISRLOCKED|' r'ISTRANSACTABLE|ISUPPER|JUSTDRIVE|JUSTEXT|JUSTFNAME|' r'JUSTPATH|JUSTSTEM|KEY|KEYMATCH|LASTKEY|LEFT|LEFTC|LEN|' r'LENC|LIKE|LIKEC|LINENO|LOADPICTURE|LOCFILE|LOCK|LOG|' r'LOG10|LOOKUP|LOWER|LTRIM|LUPDATE|MAKETRANSACTABLE|MAX|' r'MCOL|MDOWN|MDX|MDY|MEMLINES|MEMORY|MENU|MESSAGE|' r'MESSAGEBOX|MIN|MINUTE|MLINE|MOD|MONTH|MRKBAR|MRKPAD|' r'MROW|MTON|MWINDOW|NDX|NEWOBJECT|NORMALIZE|NTOM|NUMLOCK|' r'NVL|OBJNUM|OBJTOCLIENT|OBJVAR|OCCURS|OEMTOANSI|OLDVAL|' r'ON|ORDER|OS|PAD|PADL|PARAMETERS|PAYMENT|PCOL|PCOUNT|' r'PEMSTATUS|PI|POPUP|PRIMARY|PRINTSTATUS|PRMBAR|PRMPAD|' r'PROGRAM|PROMPT|PROPER|PROW|PRTINFO|PUTFILE|PV|QUARTER|' r'RAISEEVENT|RAND|RAT|RATC|RATLINE|RDLEVEL|READKEY|RECCOUNT|' r'RECNO|RECSIZE|REFRESH|RELATION|REPLICATE|REQUERY|RGB|' r'RGBSCHEME|RIGHT|RIGHTC|RLOCK|ROUND|ROW|RTOD|RTRIM|' r'SAVEPICTURE|SCHEME|SCOLS|SEC|SECONDS|SEEK|SELECT|SET|' r'SETFLDSTATE|SETRESULTSET|SIGN|SIN|SKPBAR|SKPPAD|SOUNDEX|' r'SPACE|SQLCANCEL|SQLCOLUMNS|SQLCOMMIT|SQLCONNECT|' r'SQLDISCONNECT|SQLEXEC|SQLGETPROP|SQLIDLEDISCONNECT|' r'SQLMORERESULTS|SQLPREPARE|SQLROLLBACK|SQLSETPROP|' r'SQLSTRINGCONNECT|SQLTABLES|SQRT|SROWS|STR|STRCONV|' r'STREXTRACT|STRTOFILE|STRTRAN|STUFF|STUFFC|SUBSTR|' r'SUBSTRC|SYS|SYSMETRIC|TABLEREVERT|TABLEUPDATE|TAG|' r'TAGCOUNT|TAGNO|TAN|TARGET|TEXTMERGE|TIME|TRANSFORM|' r'TRIM|TTOC|TTOD|TXNLEVEL|TXTWIDTH|TYPE|UNBINDEVENTS|' r'UNIQUE|UPDATED|UPPER|USED|VAL|VARREAD|VARTYPE|VERSION|' r'WBORDER|WCHILD|WCOLS|WDOCKABLE|WEEK|WEXIST|WFONT|WLAST|' r'WLCOL|WLROW|WMAXIMUM|WMINIMUM|WONTOP|WOUTPUT|WPARENT|' r'WREAD|WROWS|WTITLE|WVISIBLE|XMLTOCURSOR|XMLUPDATEGRAM|' r'YEAR)(?=\s*\()', Name.Function),
(r'_ALIGNMENT|_ASCIICOLS|_ASCIIROWS|_ASSIST|_BEAUTIFY|_BOX|' r'_BROWSER|_BUILDER|_CALCMEM|_CALCVALUE|_CLIPTEXT|_CONVERTER|' r'_COVERAGE|_CUROBJ|_DBLCLICK|_DIARYDATE|_DOS|_FOXDOC|_FOXREF|' r'_GALLERY|_GENGRAPH|_GENHTML|_GENMENU|_GENPD|_GENSCRN|' r'_GENXTAB|_GETEXPR|_INCLUDE|_INCSEEK|_INDENT|_LMARGIN|_MAC|' r'_MENUDESIGNER|_MLINE|_PADVANCE|_PAGENO|_PAGETOTAL|_PBPAGE|' r'_PCOLNO|_PCOPIES|_PDRIVER|_PDSETUP|_PECODE|_PEJECT|_PEPAGE|' r'_PLENGTH|_PLINENO|_PLOFFSET|_PPITCH|_PQUALITY|_PRETEXT|' r'_PSCODE|_PSPACING|_PWAIT|_RMARGIN|_REPORTBUILDER|' r'_REPORTOUTPUT|_REPORTPREVIEW|_SAMPLES|_SCCTEXT|_SCREEN|' r'_SHELL|_SPELLCHK|_STARTUP|_TABS|_TALLY|_TASKPANE|_TEXT|' r'_THROTTLE|_TOOLBOX|_TOOLTIPTIMEOUT|_TRANSPORT|_TRIGGERLEVEL|' r'_UNIX|_VFP|_WINDOWS|_WIZARD|_WRAP', Keyword.Pseudo),
(r'THISFORMSET|THISFORM|THIS', Name.Builtin),
(r'Application|CheckBox|Collection|Column|ComboBox|' r'CommandButton|CommandGroup|Container|Control|CursorAdapter|' r'Cursor|Custom|DataEnvironment|DataObject|EditBox|' r'Empty|Exception|Fields|Files|File|FormSet|Form|FoxCode|' r'Grid|Header|Hyperlink|Image|Label|Line|ListBox|Objects|' r'OptionButton|OptionGroup|PageFrame|Page|ProjectHook|Projects|' r'Project|Relation|ReportListener|Separator|Servers|Server|' r'Session|Shape|Spinner|Tables|TextBox|Timer|ToolBar|' r'XMLAdapter|XMLField|XMLTable', Name.Class),
(r'm\.[a-z_]\w*', Name.Variable), (r'\.(F|T|AND|OR|NOT|NULL)\.|\b(AND|OR|NOT|NULL)\b', Operator.Word),
(r'\.(ActiveColumn|ActiveControl|ActiveForm|ActivePage|' r'ActiveProject|ActiveRow|AddLineFeeds|ADOCodePage|Alias|' r'Alignment|Align|AllowAddNew|AllowAutoColumnFit|' r'AllowCellSelection|AllowDelete|AllowHeaderSizing|' r'AllowInsert|AllowModalMessages|AllowOutput|AllowRowSizing|' r'AllowSimultaneousFetch|AllowTabs|AllowUpdate|' r'AlwaysOnBottom|AlwaysOnTop|Anchor|Application|' r'AutoActivate|AutoCenter|AutoCloseTables|AutoComplete|' r'AutoCompSource|AutoCompTable|AutoHideScrollBar|' r'AutoIncrement|AutoOpenTables|AutoRelease|AutoSize|' r'AutoVerbMenu|AutoYield|BackColor|ForeColor|BackStyle|' r'BaseClass|BatchUpdateCount|BindControls|BorderColor|' r'BorderStyle|BorderWidth|BoundColumn|BoundTo|Bound|' r'BreakOnError|BufferModeOverride|BufferMode|' r'BuildDateTime|ButtonCount|Buttons|Cancel|Caption|' r'Centered|Century|ChildAlias|ChildOrder|ChildTable|' r'ClassLibrary|Class|ClipControls|Closable|CLSID|CodePage|' r'ColorScheme|ColorSource|ColumnCount|ColumnLines|' r'ColumnOrder|Columns|ColumnWidths|CommandClauses|' r'Comment|CompareMemo|ConflictCheckCmd|ConflictCheckType|' r'ContinuousScroll|ControlBox|ControlCount|Controls|' r'ControlSource|ConversionFunc|Count|CurrentControl|' r'CurrentDataSession|CurrentPass|CurrentX|CurrentY|' r'CursorSchema|CursorSource|CursorStatus|Curvature|' r'Database|DataSessionID|DataSession|DataSourceType|' r'DataSource|DataType|DateFormat|DateMark|Debug|' r'DeclareXMLPrefix|DEClassLibrary|DEClass|DefaultFilePath|' r'Default|DefOLELCID|DeleteCmdDataSourceType|DeleteCmdDataSource|' r'DeleteCmd|DeleteMark|Description|Desktop|' r'Details|DisabledBackColor|DisabledForeColor|' r'DisabledItemBackColor|DisabledItemForeColor|' r'DisabledPicture|DisableEncode|DisplayCount|' r'DisplayValue|Dockable|Docked|DockPosition|' r'DocumentFile|DownPicture|DragIcon|DragMode|DrawMode|' r'DrawStyle|DrawWidth|DynamicAlignment|DynamicBackColor|' r'DynamicForeColor|DynamicCurrentControl|DynamicFontBold|' r'DynamicFontItalic|DynamicFontStrikethru|' r'DynamicFontUnderline|DynamicFontName|DynamicFontOutline|' r'DynamicFontShadow|DynamicFontSize|DynamicInputMask|' r'DynamicLineHeight|EditorOptions|Enabled|' r'EnableHyperlinks|Encrypted|ErrorNo|Exclude|Exclusive|' r'FetchAsNeeded|FetchMemoCmdList|FetchMemoDataSourceType|' r'FetchMemoDataSource|FetchMemo|FetchSize|' r'FileClassLibrary|FileClass|FillColor|FillStyle|Filter|' r'FirstElement|FirstNestedTable|Flags|FontBold|FontItalic|' r'FontStrikethru|FontUnderline|FontCharSet|FontCondense|' r'FontExtend|FontName|FontOutline|FontShadow|FontSize|' r'ForceCloseTag|Format|FormCount|FormattedOutput|Forms|' r'FractionDigits|FRXDataSession|FullName|GDIPlusGraphics|' r'GridLineColor|GridLines|GridLineWidth|HalfHeightCaption|' r'HeaderClassLibrary|HeaderClass|HeaderHeight|Height|' r'HelpContextID|HideSelection|HighlightBackColor|' r'HighlightForeColor|HighlightStyle|HighlightRowLineWidth|' r'HighlightRow|Highlight|HomeDir|Hours|HostName|' r'HScrollSmallChange|hWnd|Icon|IncrementalSearch|Increment|' r'InitialSelectedAlias|InputMask|InsertCmdDataSourceType|' r'InsertCmdDataSource|InsertCmdRefreshCmd|' r'InsertCmdRefreshFieldList|InsertCmdRefreshKeyFieldList|' r'InsertCmd|Instancing|IntegralHeight|' r'Interval|IMEMode|IsAttribute|IsBase64|IsBinary|IsNull|' r'IsDiffGram|IsLoaded|ItemBackColor,|ItemData|ItemIDData|' r'ItemTips|IXMLDOMElement|KeyboardHighValue|KeyboardLowValue|' r'Keyfield|KeyFieldList|KeyPreview|KeySort|LanguageOptions|' r'LeftColumn|Left|LineContents|LineNo|LineSlant|LinkMaster|' r'ListCount|ListenerType|ListIndex|ListItemID|ListItem|' r'List|LockColumnsLeft|LockColumns|LockScreen|MacDesktop|' r'MainFile|MapN19_4ToCurrency|MapBinary|MapVarchar|Margin|' r'MaxButton|MaxHeight|MaxLeft|MaxLength|MaxRecords|MaxTop|' r'MaxWidth|MDIForm|MemberClassLibrary|MemberClass|' r'MemoWindow|Message|MinButton|MinHeight|MinWidth|' r'MouseIcon|MousePointer|Movable|MoverBars|MultiSelect|' r'Name|NestedInto|NewIndex|NewItemID|NextSiblingTable|' r'NoCpTrans|NoDataOnLoad|NoData|NullDisplay|' r'NumberOfElements|Object|OLEClass|OLEDragMode|' r'OLEDragPicture|OLEDropEffects|OLEDropHasData|' r'OLEDropMode|OLEDropTextInsertion|OLELCID|' r'OLERequestPendingTimeout|OLEServerBusyRaiseError|' r'OLEServerBusyTimeout|OLETypeAllowed|OneToMany|' r'OpenViews|OpenWindow|Optimize|OrderDirection|Order|' r'OutputPageCount|OutputType|PageCount|PageHeight|' r'PageNo|PageOrder|Pages|PageTotal|PageWidth|' r'PanelLink|Panel|ParentAlias|ParentClass|ParentTable|' r'Parent|Partition|PasswordChar|PictureMargin|' r'PicturePosition|PictureSpacing|PictureSelectionDisplay|' r'PictureVal|Picture|Prepared|' r'PolyPoints|PreserveWhiteSpace|PreviewContainer|' r'PrintJobName|Procedure|PROCESSID|ProgID|ProjectHookClass|' r'ProjectHookLibrary|ProjectHook|QuietMode|' r'ReadCycle|ReadLock|ReadMouse|ReadObject|ReadOnly|' r'ReadSave|ReadTimeout|RecordMark|RecordSourceType|' r'RecordSource|RefreshAlias|' r'RefreshCmdDataSourceType|RefreshCmdDataSource|RefreshCmd|' r'RefreshIgnoreFieldList|RefreshTimeStamp|RelationalExpr|' r'RelativeColumn|RelativeRow|ReleaseType|Resizable|' r'RespectCursorCP|RespectNesting|RightToLeft|RotateFlip|' r'Rotation|RowColChange|RowHeight|RowSourceType|' r'RowSource|ScaleMode|SCCProvider|SCCStatus|ScrollBars|' r'Seconds|SelectCmd|SelectedID|' r'SelectedItemBackColor|SelectedItemForeColor|Selected|' r'SelectionNamespaces|SelectOnEntry|SelLength|SelStart|' r'SelText|SendGDIPlusImage|SendUpdates|ServerClassLibrary|' r'ServerClass|ServerHelpFile|ServerName|' r'ServerProject|ShowTips|ShowInTaskbar|ShowWindow|' r'Sizable|SizeBox|SOM|Sorted|Sparse|SpecialEffect|' r'SpinnerHighValue|SpinnerLowValue|SplitBar|StackLevel|' r'StartMode|StatusBarText|StatusBar|Stretch|StrictDateEntry|' r'Style|TabIndex|Tables|TabOrientation|Tabs|TabStop|' r'TabStretch|TabStyle|Tag|TerminateRead|Text|Themes|' r'ThreadID|TimestampFieldList|TitleBar|ToolTipText|' r'TopIndex|TopItemID|Top|TwoPassProcess|TypeLibCLSID|' r'TypeLibDesc|TypeLibName|Type|Unicode|UpdatableFieldList|' r'UpdateCmdDataSourceType|UpdateCmdDataSource|' r'UpdateCmdRefreshCmd|UpdateCmdRefreshFieldList|' r'UpdateCmdRefreshKeyFieldList|UpdateCmd|' r'UpdateGramSchemaLocation|UpdateGram|UpdateNameList|UpdateType|' r'UseCodePage|UseCursorSchema|UseDeDataSource|UseMemoSize|' r'UserValue|UseTransactions|UTF8Encoded|Value|VersionComments|' r'VersionCompany|VersionCopyright|VersionDescription|' r'VersionNumber|VersionProduct|VersionTrademarks|Version|' r'VFPXMLProgID|ViewPortHeight|ViewPortLeft|' r'ViewPortTop|ViewPortWidth|VScrollSmallChange|View|Visible|' r'VisualEffect|WhatsThisButton|WhatsThisHelpID|WhatsThisHelp|' r'WhereType|Width|WindowList|WindowState|WindowType|WordWrap|' r'WrapCharInCDATA|WrapInCDATA|WrapMemoInCDATA|XMLAdapter|' r'XMLConstraints|XMLNameIsXPath|XMLNamespace|XMLName|' r'XMLPrefix|XMLSchemaLocation|XMLTable|XMLType|' r'XSDfractionDigits|XSDmaxLength|XSDtotalDigits|' r'XSDtype|ZoomBox)', Name.Attribute),
(r'\.(ActivateCell|AddColumn|AddItem|AddListItem|AddObject|' r'AddProperty|AddTableSchema|AddToSCC|Add|' r'ApplyDiffgram|Attach|AutoFit|AutoOpen|Box|Build|' r'CancelReport|ChangesToCursor|CheckIn|CheckOut|Circle|' r'CleanUp|ClearData|ClearStatus|Clear|CloneObject|CloseTables|' r'Close|Cls|CursorAttach|CursorDetach|CursorFill|' r'CursorRefresh|DataToClip|DelayedMemoFetch|DeleteColumn|' r'Dock|DoMessage|DoScroll|DoStatus|DoVerb|Drag|Draw|Eval|' r'GetData|GetDockState|GetFormat|GetKey|GetLatestVersion|' r'GetPageHeight|GetPageWidth|Help|Hide|IncludePageInOutput|' r'IndexToItemID|ItemIDToIndex|Item|LoadXML|Line|Modify|' r'MoveItem|Move|Nest|OLEDrag|OnPreviewClose|OutputPage|' r'Point|Print|PSet|Quit|ReadExpression|ReadMethod|' r'RecordRefresh|Refresh|ReleaseXML|Release|RemoveFromSCC|' r'RemoveItem|RemoveListItem|RemoveObject|Remove|' r'Render|Requery|RequestData|ResetToDefault|Reset|Run|' r'SaveAsClass|SaveAs|SetAll|SetData|SetFocus|SetFormat|' r'SetMain|SetVar|SetViewPort|ShowWhatsThis|Show|' r'SupportsListenerType|TextHeight|TextWidth|ToCursor|' r'ToXML|UndoCheckOut|Unnest|UpdateStatus|WhatsThisMode|' r'WriteExpression|WriteMethod|ZOrder)', Name.Function),
(r'\.(Activate|AdjustObjectSize|AfterBand|AfterBuild|' r'AfterCloseTables|AfterCursorAttach|AfterCursorClose|' r'AfterCursorDetach|AfterCursorFill|AfterCursorRefresh|' r'AfterCursorUpdate|AfterDelete|AfterInsert|' r'AfterRecordRefresh|AfterUpdate|AfterDock|AfterReport|' r'AfterRowColChange|BeforeBand|BeforeCursorAttach|' r'BeforeCursorClose|BeforeCursorDetach|BeforeCursorFill|' r'BeforeCursorRefresh|BeforeCursorUpdate|BeforeDelete|' r'BeforeInsert|BeforeDock|BeforeOpenTables|' r'BeforeRecordRefresh|BeforeReport|BeforeRowColChange|' r'BeforeUpdate|Click|dbc_Activate|dbc_AfterAddTable|' r'dbc_AfterAppendProc|dbc_AfterCloseTable|dbc_AfterCopyProc|' r'dbc_AfterCreateConnection|dbc_AfterCreateOffline|' r'dbc_AfterCreateTable|dbc_AfterCreateView|dbc_AfterDBGetProp|' r'dbc_AfterDBSetProp|dbc_AfterDeleteConnection|' r'dbc_AfterDropOffline|dbc_AfterDropTable|' r'dbc_AfterModifyConnection|dbc_AfterModifyProc|' r'dbc_AfterModifyTable|dbc_AfterModifyView|dbc_AfterOpenTable|' r'dbc_AfterRemoveTable|dbc_AfterRenameConnection|' r'dbc_AfterRenameTable|dbc_AfterRenameView|' r'dbc_AfterValidateData|dbc_BeforeAddTable|' r'dbc_BeforeAppendProc|dbc_BeforeCloseTable|' r'dbc_BeforeCopyProc|dbc_BeforeCreateConnection|' r'dbc_BeforeCreateOffline|dbc_BeforeCreateTable|' r'dbc_BeforeCreateView|dbc_BeforeDBGetProp|' r'dbc_BeforeDBSetProp|dbc_BeforeDeleteConnection|' r'dbc_BeforeDropOffline|dbc_BeforeDropTable|' r'dbc_BeforeModifyConnection|dbc_BeforeModifyProc|' r'dbc_BeforeModifyTable|dbc_BeforeModifyView|' r'dbc_BeforeOpenTable|dbc_BeforeRemoveTable|' r'dbc_BeforeRenameConnection|dbc_BeforeRenameTable|' r'dbc_BeforeRenameView|dbc_BeforeValidateData|' r'dbc_CloseData|dbc_Deactivate|dbc_ModifyData|dbc_OpenData|' r'dbc_PackData|DblClick|Deactivate|Deleted|Destroy|DoCmd|' r'DownClick|DragDrop|DragOver|DropDown|ErrorMessage|Error|' r'EvaluateContents|GotFocus|Init|InteractiveChange|KeyPress|' r'LoadReport|Load|LostFocus|Message|MiddleClick|MouseDown|' r'MouseEnter|MouseLeave|MouseMove|MouseUp|MouseWheel|Moved|' r'OLECompleteDrag|OLEDragOver|OLEGiveFeedback|OLESetData|' r'OLEStartDrag|OnMoveItem|Paint|ProgrammaticChange|' r'QueryAddFile|QueryModifyFile|QueryNewFile|QueryRemoveFile|' r'QueryRunFile|QueryUnload|RangeHigh|RangeLow|ReadActivate|' r'ReadDeactivate|ReadShow|ReadValid|ReadWhen|Resize|' r'RightClick|SCCInit|SCCDestroy|Scrolled|Timer|UIEnable|' r'UnDock|UnloadReport|Unload|UpClick|Valid|When)', Name.Function),
(r'\s+', Text), # everything else is not colored (r'.', Text), ], 'newline': [ (r'\*.*?$', Comment.Single, '#pop'), (r'(ACCEPT|ACTIVATE\s*MENU|ACTIVATE\s*POPUP|ACTIVATE\s*SCREEN|' r'ACTIVATE\s*WINDOW|APPEND|APPEND\s*FROM|APPEND\s*FROM\s*ARRAY|' r'APPEND\s*GENERAL|APPEND\s*MEMO|ASSIST|AVERAGE|BLANK|BROWSE|' r'BUILD\s*APP|BUILD\s*EXE|BUILD\s*PROJECT|CALCULATE|CALL|' r'CANCEL|CHANGE|CLEAR|CLOSE|CLOSE\s*MEMO|COMPILE|CONTINUE|' r'COPY\s*FILE|COPY\s*INDEXES|COPY\s*MEMO|COPY\s*STRUCTURE|' r'COPY\s*STRUCTURE\s*EXTENDED|COPY\s*TAG|COPY\s*TO|' r'COPY\s*TO\s*ARRAY|COUNT|CREATE|CREATE\s*COLOR\s*SET|' r'CREATE\s*CURSOR|CREATE\s*FROM|CREATE\s*LABEL|CREATE\s*MENU|' r'CREATE\s*PROJECT|CREATE\s*QUERY|CREATE\s*REPORT|' r'CREATE\s*SCREEN|CREATE\s*TABLE|CREATE\s*VIEW|DDE|' r'DEACTIVATE\s*MENU|DEACTIVATE\s*POPUP|DEACTIVATE\s*WINDOW|' r'DECLARE|DEFINE\s*BAR|DEFINE\s*BOX|DEFINE\s*MENU|' r'DEFINE\s*PAD|DEFINE\s*POPUP|DEFINE\s*WINDOW|DELETE|' r'DELETE\s*FILE|DELETE\s*TAG|DIMENSION|DIRECTORY|DISPLAY|' r'DISPLAY\s*FILES|DISPLAY\s*MEMORY|DISPLAY\s*STATUS|' r'DISPLAY\s*STRUCTURE|DO|EDIT|EJECT|EJECT\s*PAGE|ERASE|' r'EXIT|EXPORT|EXTERNAL|FILER|FIND|FLUSH|FUNCTION|GATHER|' r'GETEXPR|GO|GOTO|HELP|HIDE\s*MENU|HIDE\s*POPUP|' r'HIDE\s*WINDOW|IMPORT|INDEX|INPUT|INSERT|JOIN|KEYBOARD|' r'LABEL|LIST|LOAD|LOCATE|LOOP|MENU|MENU\s*TO|MODIFY\s*COMMAND|' r'MODIFY\s*FILE|MODIFY\s*GENERAL|MODIFY\s*LABEL|MODIFY\s*MEMO|' r'MODIFY\s*MENU|MODIFY\s*PROJECT|MODIFY\s*QUERY|' r'MODIFY\s*REPORT|MODIFY\s*SCREEN|MODIFY\s*STRUCTURE|' r'MODIFY\s*WINDOW|MOVE\s*POPUP|MOVE\s*WINDOW|NOTE|' r'ON\s*APLABOUT|ON\s*BAR|ON\s*ERROR|ON\s*ESCAPE|' r'ON\s*EXIT\s*BAR|ON\s*EXIT\s*MENU|ON\s*EXIT\s*PAD|' r'ON\s*EXIT\s*POPUP|ON\s*KEY|ON\s*KEY\s*=|ON\s*KEY\s*LABEL|' r'ON\s*MACHELP|ON\s*PAD|ON\s*PAGE|ON\s*READERROR|' r'ON\s*SELECTION\s*BAR|ON\s*SELECTION\s*MENU|' r'ON\s*SELECTION\s*PAD|ON\s*SELECTION\s*POPUP|ON\s*SHUTDOWN|' r'PACK|PARAMETERS|PLAY\s*MACRO|POP\s*KEY|POP\s*MENU|' r'POP\s*POPUP|PRIVATE|PROCEDURE|PUBLIC|PUSH\s*KEY|' r'PUSH\s*MENU|PUSH\s*POPUP|QUIT|READ|READ\s*MENU|RECALL|' r'REINDEX|RELEASE|RELEASE\s*MODULE|RENAME|REPLACE|' r'REPLACE\s*FROM\s*ARRAY|REPORT|RESTORE\s*FROM|' r'RESTORE\s*MACROS|RESTORE\s*SCREEN|RESTORE\s*WINDOW|' r'RESUME|RETRY|RETURN|RUN|RUN\s*\/N"|RUNSCRIPT|' r'SAVE\s*MACROS|SAVE\s*SCREEN|SAVE\s*TO|SAVE\s*WINDOWS|' r'SCATTER|SCROLL|SEEK|SELECT|SET|SET\s*ALTERNATE|' r'SET\s*ANSI|SET\s*APLABOUT|SET\s*AUTOSAVE|SET\s*BELL|' r'SET\s*BLINK|SET\s*BLOCKSIZE|SET\s*BORDER|SET\s*BRSTATUS|' r'SET\s*CARRY|SET\s*CENTURY|SET\s*CLEAR|SET\s*CLOCK|' r'SET\s*COLLATE|SET\s*COLOR\s*OF|SET\s*COLOR\s*OF\s*SCHEME|' r'SET\s*COLOR\s*SET|SET\s*COLOR\s*TO|SET\s*COMPATIBLE|' r'SET\s*CONFIRM|SET\s*CONSOLE|SET\s*CURRENCY|SET\s*CURSOR|' r'SET\s*DATE|SET\s*DEBUG|SET\s*DECIMALS|SET\s*DEFAULT|' r'SET\s*DELETED|SET\s*DELIMITERS|SET\s*DEVELOPMENT|' r'SET\s*DEVICE|SET\s*DISPLAY|SET\s*DOHISTORY|SET\s*ECHO|' r'SET\s*ESCAPE|SET\s*EXACT|SET\s*EXCLUSIVE|SET\s*FIELDS|' r'SET\s*FILTER|SET\s*FIXED|SET\s*FORMAT|SET\s*FULLPATH|' r'SET\s*FUNCTION|SET\s*HEADINGS|SET\s*HELP|SET\s*HELPFILTER|' r'SET\s*HOURS|SET\s*INDEX|SET\s*INTENSITY|SET\s*KEY|' r'SET\s*KEYCOMP|SET\s*LIBRARY|SET\s*LOCK|SET\s*LOGERRORS|' r'SET\s*MACDESKTOP|SET\s*MACHELP|SET\s*MACKEY|SET\s*MARGIN|' r'SET\s*MARK\s*OF|SET\s*MARK\s*TO|SET\s*MEMOWIDTH|' r'SET\s*MESSAGE|SET\s*MOUSE|SET\s*MULTILOCKS|SET\s*NEAR|' r'SET\s*NOCPTRANS|SET\s*NOTIFY|SET\s*ODOMETER|SET\s*OPTIMIZE|' r'SET\s*ORDER|SET\s*PALETTE|SET\s*PATH|SET\s*PDSETUP|' r'SET\s*POINT|SET\s*PRINTER|SET\s*PROCEDURE|SET\s*READBORDER|' r'SET\s*REFRESH|SET\s*RELATION|SET\s*RELATION\s*OFF|' r'SET\s*REPROCESS|SET\s*RESOURCE|SET\s*SAFETY|SET\s*SCOREBOARD|' r'SET\s*SEPARATOR|SET\s*SHADOWS|SET\s*SKIP|SET\s*SKIP\s*OF|' r'SET\s*SPACE|SET\s*STATUS|SET\s*STATUS\s*BAR|SET\s*STEP|' r'SET\s*STICKY|SET\s*SYSMENU|SET\s*TALK|SET\s*TEXTMERGE|' r'SET\s*TEXTMERGE\s*DELIMITERS|SET\s*TOPIC|SET\s*TRBETWEEN|' r'SET\s*TYPEAHEAD|SET\s*UDFPARMS|SET\s*UNIQUE|SET\s*VIEW|' r'SET\s*VOLUME|SET\s*WINDOW\s*OF\s*MEMO|SET\s*XCMDFILE|' r'SHOW\s*GET|SHOW\s*GETS|SHOW\s*MENU|SHOW\s*OBJECT|' r'SHOW\s*POPUP|SHOW\s*WINDOW|SIZE\s*POPUP|SKIP|SORT|' r'STORE|SUM|SUSPEND|TOTAL|TYPE|UNLOCK|UPDATE|USE|WAIT|' r'ZAP|ZOOM\s*WINDOW|DO\s*CASE|CASE|OTHERWISE|ENDCASE|' r'DO\s*WHILE|ENDDO|FOR|ENDFOR|NEXT|IF|ELSE|ENDIF|PRINTJOB|' r'ENDPRINTJOB|SCAN|ENDSCAN|TEXT|ENDTEXT|=)', Keyword.Reserved, '#pop'), (r'#\s*(IF|ELIF|ELSE|ENDIF|DEFINE|IFDEF|IFNDEF|INCLUDE)', Comment.Preproc, '#pop'), (r'(m\.)?[a-z_]\w*', Name.Variable, '#pop'), (r'.', Text, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893""" pygments.lexers.freefem ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for FreeFem++ language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.token import Comment, Operator, Keyword, Name
from pygments.lexers.c_cpp import CppLexer
__all__ = ['FreeFemLexer']
class FreeFemLexer(CppLexer): """ For FreeFem++ source.
This is an extension of the CppLexer, as the FreeFem Language is a superset of C++. """
name = 'Freefem' url = 'https://freefem.org/' aliases = ['freefem'] filenames = ['*.edp'] mimetypes = ['text/x-freefem'] version_added = '2.4'
# Language operators operators = {'+', '-', '*', '.*', '/', './', '%', '^', '^-1', ':', '\''}
# types types = {'bool', 'border', 'complex', 'dmatrix', 'fespace', 'func', 'gslspline', 'ifstream', 'int', 'macro', 'matrix', 'mesh', 'mesh3', 'mpiComm', 'mpiGroup', 'mpiRequest', 'NewMacro', 'EndMacro', 'ofstream', 'Pmmap', 'problem', 'Psemaphore', 'real', 'solve', 'string', 'varf'}
# finite element spaces fespaces = {'BDM1', 'BDM1Ortho', 'Edge03d', 'Edge13d', 'Edge23d', 'FEQF', 'HCT', 'P0', 'P03d', 'P0Edge', 'P1', 'P13d', 'P1b', 'P1b3d', 'P1bl', 'P1bl3d', 'P1dc', 'P1Edge', 'P1nc', 'P2', 'P23d', 'P2b', 'P2BR', 'P2dc', 'P2Edge', 'P2h', 'P2Morley', 'P2pnc', 'P3', 'P3dc', 'P3Edge', 'P4', 'P4dc', 'P4Edge', 'P5Edge', 'RT0', 'RT03d', 'RT0Ortho', 'RT1', 'RT1Ortho', 'RT2', 'RT2Ortho'}
# preprocessor preprocessor = {'ENDIFMACRO', 'include', 'IFMACRO', 'load'}
# Language keywords keywords = { 'adj', 'append', 'area', 'ARGV', 'be', 'binary', 'BoundaryEdge', 'bordermeasure', 'CG', 'Cholesky', 'cin', 'cout', 'Crout', 'default', 'diag', 'edgeOrientation', 'endl', 'false', 'ffind', 'FILE', 'find', 'fixed', 'flush', 'GMRES', 'good', 'hTriangle', 'im', 'imax', 'imin', 'InternalEdge', 'l1', 'l2', 'label', 'lenEdge', 'length', 'LINE', 'linfty', 'LU', 'm', 'max', 'measure', 'min', 'mpiAnySource', 'mpiBAND', 'mpiBXOR', 'mpiCommWorld', 'mpiLAND', 'mpiLOR', 'mpiLXOR', 'mpiMAX', 'mpiMIN', 'mpiPROD', 'mpirank', 'mpisize', 'mpiSUM', 'mpiUndefined', 'n', 'N', 'nbe', 'ndof', 'ndofK', 'noshowbase', 'noshowpos', 'notaregion', 'nt', 'nTonEdge', 'nuEdge', 'nuTriangle', 'nv', 'P', 'pi', 'precision', 'qf1pE', 'qf1pElump', 'qf1pT', 'qf1pTlump', 'qfV1', 'qfV1lump', 'qf2pE', 'qf2pT', 'qf2pT4P1', 'qfV2', 'qf3pE', 'qf4pE', 'qf5pE', 'qf5pT', 'qfV5', 'qf7pT', 'qf9pT', 'qfnbpE', 'quantile', 're', 'region', 'rfind', 'scientific', 'searchMethod', 'setw', 'showbase', 'showpos', 'sparsesolver', 'sum', 'tellp', 'true', 'UMFPACK', 'unused', 'whoinElement', 'verbosity', 'version', 'volume', 'x', 'y', 'z' }
# Language shipped functions and class ( ) functions = { 'abs', 'acos', 'acosh', 'adaptmesh', 'adj', 'AffineCG', 'AffineGMRES', 'arg', 'asin', 'asinh', 'assert', 'atan', 'atan2', 'atanh', 'atof', 'atoi', 'BFGS', 'broadcast', 'buildlayers', 'buildmesh', 'ceil', 'chi', 'complexEigenValue', 'copysign', 'change', 'checkmovemesh', 'clock', 'cmaes', 'conj', 'convect', 'cos', 'cosh', 'cube', 'd', 'dd', 'dfft', 'diffnp', 'diffpos', 'dimKrylov', 'dist', 'dumptable', 'dx', 'dxx', 'dxy', 'dxz', 'dy', 'dyx', 'dyy', 'dyz', 'dz', 'dzx', 'dzy', 'dzz', 'EigenValue', 'emptymesh', 'erf', 'erfc', 'exec', 'exit', 'exp', 'fdim', 'floor', 'fmax', 'fmin', 'fmod', 'freeyams', 'getARGV', 'getline', 'gmshload', 'gmshload3', 'gslcdfugaussianP', 'gslcdfugaussianQ', 'gslcdfugaussianPinv', 'gslcdfugaussianQinv', 'gslcdfgaussianP', 'gslcdfgaussianQ', 'gslcdfgaussianPinv', 'gslcdfgaussianQinv', 'gslcdfgammaP', 'gslcdfgammaQ', 'gslcdfgammaPinv', 'gslcdfgammaQinv', 'gslcdfcauchyP', 'gslcdfcauchyQ', 'gslcdfcauchyPinv', 'gslcdfcauchyQinv', 'gslcdflaplaceP', 'gslcdflaplaceQ', 'gslcdflaplacePinv', 'gslcdflaplaceQinv', 'gslcdfrayleighP', 'gslcdfrayleighQ', 'gslcdfrayleighPinv', 'gslcdfrayleighQinv', 'gslcdfchisqP', 'gslcdfchisqQ', 'gslcdfchisqPinv', 'gslcdfchisqQinv', 'gslcdfexponentialP', 'gslcdfexponentialQ', 'gslcdfexponentialPinv', 'gslcdfexponentialQinv', 'gslcdfexppowP', 'gslcdfexppowQ', 'gslcdftdistP', 'gslcdftdistQ', 'gslcdftdistPinv', 'gslcdftdistQinv', 'gslcdffdistP', 'gslcdffdistQ', 'gslcdffdistPinv', 'gslcdffdistQinv', 'gslcdfbetaP', 'gslcdfbetaQ', 'gslcdfbetaPinv', 'gslcdfbetaQinv', 'gslcdfflatP', 'gslcdfflatQ', 'gslcdfflatPinv', 'gslcdfflatQinv', 'gslcdflognormalP', 'gslcdflognormalQ', 'gslcdflognormalPinv', 'gslcdflognormalQinv', 'gslcdfgumbel1P', 'gslcdfgumbel1Q', 'gslcdfgumbel1Pinv', 'gslcdfgumbel1Qinv', 'gslcdfgumbel2P', 'gslcdfgumbel2Q', 'gslcdfgumbel2Pinv', 'gslcdfgumbel2Qinv', 'gslcdfweibullP', 'gslcdfweibullQ', 'gslcdfweibullPinv', 'gslcdfweibullQinv', 'gslcdfparetoP', 'gslcdfparetoQ', 'gslcdfparetoPinv', 'gslcdfparetoQinv', 'gslcdflogisticP', 'gslcdflogisticQ', 'gslcdflogisticPinv', 'gslcdflogisticQinv', 'gslcdfbinomialP', 'gslcdfbinomialQ', 'gslcdfpoissonP', 'gslcdfpoissonQ', 'gslcdfgeometricP', 'gslcdfgeometricQ', 'gslcdfnegativebinomialP', 'gslcdfnegativebinomialQ', 'gslcdfpascalP', 'gslcdfpascalQ', 'gslinterpakima', 'gslinterpakimaperiodic', 'gslinterpcsplineperiodic', 'gslinterpcspline', 'gslinterpsteffen', 'gslinterplinear', 'gslinterppolynomial', 'gslranbernoullipdf', 'gslranbeta', 'gslranbetapdf', 'gslranbinomialpdf', 'gslranexponential', 'gslranexponentialpdf', 'gslranexppow', 'gslranexppowpdf', 'gslrancauchy', 'gslrancauchypdf', 'gslranchisq', 'gslranchisqpdf', 'gslranerlang', 'gslranerlangpdf', 'gslranfdist', 'gslranfdistpdf', 'gslranflat', 'gslranflatpdf', 'gslrangamma', 'gslrangammaint', 'gslrangammapdf', 'gslrangammamt', 'gslrangammaknuth', 'gslrangaussian', 'gslrangaussianratiomethod', 'gslrangaussianziggurat', 'gslrangaussianpdf', 'gslranugaussian', 'gslranugaussianratiomethod', 'gslranugaussianpdf', 'gslrangaussiantail', 'gslrangaussiantailpdf', 'gslranugaussiantail', 'gslranugaussiantailpdf', 'gslranlandau', 'gslranlandaupdf', 'gslrangeometricpdf', 'gslrangumbel1', 'gslrangumbel1pdf', 'gslrangumbel2', 'gslrangumbel2pdf', 'gslranlogistic', 'gslranlogisticpdf', 'gslranlognormal', 'gslranlognormalpdf', 'gslranlogarithmicpdf', 'gslrannegativebinomialpdf', 'gslranpascalpdf', 'gslranpareto', 'gslranparetopdf', 'gslranpoissonpdf', 'gslranrayleigh', 'gslranrayleighpdf', 'gslranrayleightail', 'gslranrayleightailpdf', 'gslrantdist', 'gslrantdistpdf', 'gslranlaplace', 'gslranlaplacepdf', 'gslranlevy', 'gslranweibull', 'gslranweibullpdf', 'gslsfairyAi', 'gslsfairyBi', 'gslsfairyAiscaled', 'gslsfairyBiscaled', 'gslsfairyAideriv', 'gslsfairyBideriv', 'gslsfairyAiderivscaled', 'gslsfairyBiderivscaled', 'gslsfairyzeroAi', 'gslsfairyzeroBi', 'gslsfairyzeroAideriv', 'gslsfairyzeroBideriv', 'gslsfbesselJ0', 'gslsfbesselJ1', 'gslsfbesselJn', 'gslsfbesselY0', 'gslsfbesselY1', 'gslsfbesselYn', 'gslsfbesselI0', 'gslsfbesselI1', 'gslsfbesselIn', 'gslsfbesselI0scaled', 'gslsfbesselI1scaled', 'gslsfbesselInscaled', 'gslsfbesselK0', 'gslsfbesselK1', 'gslsfbesselKn', 'gslsfbesselK0scaled', 'gslsfbesselK1scaled', 'gslsfbesselKnscaled', 'gslsfbesselj0', 'gslsfbesselj1', 'gslsfbesselj2', 'gslsfbesseljl', 'gslsfbessely0', 'gslsfbessely1', 'gslsfbessely2', 'gslsfbesselyl', 'gslsfbesseli0scaled', 'gslsfbesseli1scaled', 'gslsfbesseli2scaled', 'gslsfbesselilscaled', 'gslsfbesselk0scaled', 'gslsfbesselk1scaled', 'gslsfbesselk2scaled', 'gslsfbesselklscaled', 'gslsfbesselJnu', 'gslsfbesselYnu', 'gslsfbesselInuscaled', 'gslsfbesselInu', 'gslsfbesselKnuscaled', 'gslsfbesselKnu', 'gslsfbessellnKnu', 'gslsfbesselzeroJ0', 'gslsfbesselzeroJ1', 'gslsfbesselzeroJnu', 'gslsfclausen', 'gslsfhydrogenicR1', 'gslsfdawson', 'gslsfdebye1', 'gslsfdebye2', 'gslsfdebye3', 'gslsfdebye4', 'gslsfdebye5', 'gslsfdebye6', 'gslsfdilog', 'gslsfmultiply', 'gslsfellintKcomp', 'gslsfellintEcomp', 'gslsfellintPcomp', 'gslsfellintDcomp', 'gslsfellintF', 'gslsfellintE', 'gslsfellintRC', 'gslsferfc', 'gslsflogerfc', 'gslsferf', 'gslsferfZ', 'gslsferfQ', 'gslsfhazard', 'gslsfexp', 'gslsfexpmult', 'gslsfexpm1', 'gslsfexprel', 'gslsfexprel2', 'gslsfexpreln', 'gslsfexpintE1', 'gslsfexpintE2', 'gslsfexpintEn', 'gslsfexpintE1scaled', 'gslsfexpintE2scaled', 'gslsfexpintEnscaled', 'gslsfexpintEi', 'gslsfexpintEiscaled', 'gslsfShi', 'gslsfChi', 'gslsfexpint3', 'gslsfSi', 'gslsfCi', 'gslsfatanint', 'gslsffermidiracm1', 'gslsffermidirac0', 'gslsffermidirac1', 'gslsffermidirac2', 'gslsffermidiracint', 'gslsffermidiracmhalf', 'gslsffermidirachalf', 'gslsffermidirac3half', 'gslsffermidiracinc0', 'gslsflngamma', 'gslsfgamma', 'gslsfgammastar', 'gslsfgammainv', 'gslsftaylorcoeff', 'gslsffact', 'gslsfdoublefact', 'gslsflnfact', 'gslsflndoublefact', 'gslsflnchoose', 'gslsfchoose', 'gslsflnpoch', 'gslsfpoch', 'gslsfpochrel', 'gslsfgammaincQ', 'gslsfgammaincP', 'gslsfgammainc', 'gslsflnbeta', 'gslsfbeta', 'gslsfbetainc', 'gslsfgegenpoly1', 'gslsfgegenpoly2', 'gslsfgegenpoly3', 'gslsfgegenpolyn', 'gslsfhyperg0F1', 'gslsfhyperg1F1int', 'gslsfhyperg1F1', 'gslsfhypergUint', 'gslsfhypergU', 'gslsfhyperg2F0', 'gslsflaguerre1', 'gslsflaguerre2', 'gslsflaguerre3', 'gslsflaguerren', 'gslsflambertW0', 'gslsflambertWm1', 'gslsflegendrePl', 'gslsflegendreP1', 'gslsflegendreP2', 'gslsflegendreP3', 'gslsflegendreQ0', 'gslsflegendreQ1', 'gslsflegendreQl', 'gslsflegendrePlm', 'gslsflegendresphPlm', 'gslsflegendrearraysize', 'gslsfconicalPhalf', 'gslsfconicalPmhalf', 'gslsfconicalP0', 'gslsfconicalP1', 'gslsfconicalPsphreg', 'gslsfconicalPcylreg', 'gslsflegendreH3d0', 'gslsflegendreH3d1', 'gslsflegendreH3d', 'gslsflog', 'gslsflogabs', 'gslsflog1plusx', 'gslsflog1plusxmx', 'gslsfpowint', 'gslsfpsiint', 'gslsfpsi', 'gslsfpsi1piy', 'gslsfpsi1int', 'gslsfpsi1', 'gslsfpsin', 'gslsfsynchrotron1', 'gslsfsynchrotron2', 'gslsftransport2', 'gslsftransport3', 'gslsftransport4', 'gslsftransport5', 'gslsfsin', 'gslsfcos', 'gslsfhypot', 'gslsfsinc', 'gslsflnsinh', 'gslsflncosh', 'gslsfanglerestrictsymm', 'gslsfanglerestrictpos', 'gslsfzetaint', 'gslsfzeta', 'gslsfzetam1', 'gslsfzetam1int', 'gslsfhzeta', 'gslsfetaint', 'gslsfeta', 'imag', 'int1d', 'int2d', 'int3d', 'intalledges', 'intallfaces', 'interpolate', 'invdiff', 'invdiffnp', 'invdiffpos', 'Isend', 'isInf', 'isNaN', 'isoline', 'Irecv', 'j0', 'j1', 'jn', 'jump', 'lgamma', 'LinearCG', 'LinearGMRES', 'log', 'log10', 'lrint', 'lround', 'max', 'mean', 'medit', 'min', 'mmg3d', 'movemesh', 'movemesh23', 'mpiAlltoall', 'mpiAlltoallv', 'mpiAllgather', 'mpiAllgatherv', 'mpiAllReduce', 'mpiBarrier', 'mpiGather', 'mpiGatherv', 'mpiRank', 'mpiReduce', 'mpiScatter', 'mpiScatterv', 'mpiSize', 'mpiWait', 'mpiWaitAny', 'mpiWtick', 'mpiWtime', 'mshmet', 'NaN', 'NLCG', 'on', 'plot', 'polar', 'Post', 'pow', 'processor', 'processorblock', 'projection', 'randinit', 'randint31', 'randint32', 'random', 'randreal1', 'randreal2', 'randreal3', 'randres53', 'Read', 'readmesh', 'readmesh3', 'Recv', 'rint', 'round', 'savemesh', 'savesol', 'savevtk', 'seekg', 'Sent', 'set', 'sign', 'signbit', 'sin', 'sinh', 'sort', 'splitComm', 'splitmesh', 'sqrt', 'square', 'srandom', 'srandomdev', 'Stringification', 'swap', 'system', 'tan', 'tanh', 'tellg', 'tetg', 'tetgconvexhull', 'tetgreconstruction', 'tetgtransfo', 'tgamma', 'triangulate', 'trunc', 'Wait', 'Write', 'y0', 'y1', 'yn' }
# function parameters parameters = { 'A', 'A1', 'abserror', 'absolute', 'aniso', 'aspectratio', 'B', 'B1', 'bb', 'beginend', 'bin', 'boundary', 'bw', 'close', 'cmm', 'coef', 'composante', 'cutoff', 'datafilename', 'dataname', 'dim', 'distmax', 'displacement', 'doptions', 'dparams', 'eps', 'err', 'errg', 'facemerge', 'facetcl', 'factorize', 'file', 'fill', 'fixedborder', 'flabel', 'flags', 'floatmesh', 'floatsol', 'fregion', 'gradation', 'grey', 'hmax', 'hmin', 'holelist', 'hsv', 'init', 'inquire', 'inside', 'IsMetric', 'iso', 'ivalue', 'keepbackvertices', 'label', 'labeldown', 'labelmid', 'labelup', 'levelset', 'loptions', 'lparams', 'maxit', 'maxsubdiv', 'meditff', 'mem', 'memory', 'metric', 'mode', 'nbarrow', 'nbiso', 'nbiter', 'nbjacoby', 'nboffacetcl', 'nbofholes', 'nbofregions', 'nbregul', 'nbsmooth', 'nbvx', 'ncv', 'nev', 'nomeshgeneration', 'normalization', 'omega', 'op', 'optimize', 'option', 'options', 'order', 'orientation', 'periodic', 'power', 'precon', 'prev', 'ps', 'ptmerge', 'qfe', 'qforder', 'qft', 'qfV', 'ratio', 'rawvector', 'reffacelow', 'reffacemid', 'reffaceup', 'refnum', 'reftet', 'reftri', 'region', 'regionlist', 'renumv', 'rescaling', 'ridgeangle', 'save', 'sigma', 'sizeofvolume', 'smoothing', 'solver', 'sparams', 'split', 'splitin2', 'splitpbedge', 'stop', 'strategy', 'swap', 'switch', 'sym', 't', 'tgv', 'thetamax', 'tol', 'tolpivot', 'tolpivotsym', 'transfo', 'U2Vc', 'value', 'varrow', 'vector', 'veps', 'viso', 'wait', 'width', 'withsurfacemesh', 'WindowIndex', 'which', 'zbound' }
# deprecated deprecated = {'fixeborder'}
# do not highlight suppress_highlight = { 'alignof', 'asm', 'constexpr', 'decltype', 'div', 'double', 'grad', 'mutable', 'namespace', 'noexcept', 'restrict', 'static_assert', 'template', 'this', 'thread_local', 'typeid', 'typename', 'using' }
def get_tokens_unprocessed(self, text, stack=('root',)): for index, token, value in CppLexer.get_tokens_unprocessed(self, text, stack): if value in self.operators: yield index, Operator, value elif value in self.types: yield index, Keyword.Type, value elif value in self.fespaces: yield index, Name.Class, value elif value in self.preprocessor: yield index, Comment.Preproc, value elif value in self.keywords: yield index, Keyword.Reserved, value elif value in self.functions: yield index, Name.Function, value elif value in self.parameters: yield index, Keyword.Pseudo, value elif value in self.suppress_highlight: yield index, Name, value else: yield index, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110""" pygments.lexers.func ~~~~~~~~~~~~~~~~~~~~
Lexers for FunC.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Whitespace, Punctuation
__all__ = ['FuncLexer']
class FuncLexer(RegexLexer): """ For FunC source code. """
name = 'FunC' aliases = ['func', 'fc'] filenames = ['*.fc', '*.func'] url = 'https://docs.ton.org/develop/func/overview' version_added = ''
# 1. Does not start from " # 2. Can start from ` and end with `, containing any character # 3. Starts with underscore or { or } and have more than 1 character after it # 4. Starts with letter, contains letters, numbers and underscores identifier = r'(?!")(`([^`]+)`|((?=_)_|(?=\{)\{|(?=\})\}|(?![_`{}]))([^;,\[\]\(\)\s~.]+))'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace),
include('keywords'), include('strings'), include('directives'), include('numeric'), include('comments'), include('storage'), include('functions'), include('variables'),
(r'[.;(),\[\]~{}]', Punctuation) ], 'keywords': [ (words(( '<=>', '>=', '<=', '!=', '==', '^>>', '~>>', '>>', '<<', '/%', '^%', '~%', '^/', '~/', '+=', '-=', '*=', '/=', '~/=', '^/=', '%=', '^%=', '<<=', '>>=', '~>>=', '^>>=', '&=', '|=', '^=', '^', '=', '~', '/', '%', '-', '*', '+','>', '<', '&', '|', ':', '?'), prefix=r'(?<=\s)', suffix=r'(?=\s)'), Operator), (words(( 'if', 'ifnot', 'else', 'elseif', 'elseifnot', 'while', 'do', 'until', 'repeat', 'return', 'impure', 'method_id', 'forall', 'asm', 'inline', 'inline_ref'), prefix=r'\b', suffix=r'\b'), Keyword), (words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), ], 'directives': [ (r'#include|#pragma', Keyword, 'directive'), ], 'directive': [ include('strings'), (r'\s+', Whitespace), (r'version|not-version', Keyword), (r'(>=|<=|=|>|<|\^)?([0-9]+)(.[0-9]+)?(.[0-9]+)?', Number), # version (r';', Text, '#pop') ], 'strings': [ (r'\"([^\n\"]+)\"[Hhcusa]?', String), ], 'numeric': [ (r'\b(-?(?!_)([\d_]+|0x[\d_a-fA-F]+)|0b[1_0]+)(?<!_)(?=[\s\)\],;])', Number) ], 'comments': [ (r';;([^\n]*)', Comment.Singleline), (r'\{-', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^-}{]+', Comment.Multiline), (r'\{-', Comment.Multiline, '#push'), (r'-\}', Comment.Multiline, '#pop'), (r'[-}{]', Comment.Multiline), ], 'storage': [ (words(( 'var', 'int', 'slice', 'tuple', 'cell', 'builder', 'cont', '_'), prefix=r'\b', suffix=r'(?=[\s\(\),\[\]])'), Keyword.Type), (words(('global', 'const'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), ], 'variables': [ (identifier, Name.Variable), ], 'functions': [ # identifier followed by ( (identifier + r'(?=[\(])', Name.Function), ] }123456789101112131415161718192021""" pygments.lexers.functional ~~~~~~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
# ruff: noqa: F401from pygments.lexers.lisp import SchemeLexer, CommonLispLexer, RacketLexer, \ NewLispLexer, ShenLexerfrom pygments.lexers.haskell import HaskellLexer, LiterateHaskellLexer, \ KokaLexerfrom pygments.lexers.theorem import RocqLexerfrom pygments.lexers.erlang import ErlangLexer, ErlangShellLexer, \ ElixirConsoleLexer, ElixirLexerfrom pygments.lexers.ml import SMLLexer, OcamlLexer, OpaLexer
__all__ = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105""" pygments.lexers.futhark ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Futhark language
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespacefrom pygments import unistring as uni
__all__ = ['FutharkLexer']
class FutharkLexer(RegexLexer): """ A Futhark lexer """ name = 'Futhark' url = 'https://futhark-lang.org/' aliases = ['futhark'] filenames = ['*.fut'] mimetypes = ['text/x-futhark'] version_added = '2.8'
num_types = ('i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64', 'f32', 'f64')
other_types = ('bool', )
reserved = ('if', 'then', 'else', 'def', 'let', 'loop', 'in', 'with', 'type', 'type~', 'type^', 'val', 'entry', 'for', 'while', 'do', 'case', 'match', 'include', 'import', 'module', 'open', 'local', 'assert', '_')
ascii = ('NUL', 'SOH', '[SE]TX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT', 'FF', 'CR', 'S[OI]', 'DLE', 'DC[1-4]', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', '[FGRU]S', 'SP', 'DEL')
num_postfix = r'({})?'.format('|'.join(num_types))
identifier_re = '[a-zA-Z_][a-zA-Z_0-9\']*'
# opstart_re = '+\-\*/%=\!><\|&\^'
tokens = { 'root': [ (r'--(.*?)$', Comment.Single), (r'\s+', Whitespace), (r'\(\)', Punctuation), (r'\b({})(?!\')\b'.format('|'.join(reserved)), Keyword.Reserved), (r'\b({})(?!\')\b'.format('|'.join(num_types + other_types)), Keyword.Type),
# Identifiers (r'#\[([a-zA-Z_\(\) ]*)\]', Comment.Preproc), (rf'[#!]?({identifier_re}\.)*{identifier_re}', Name),
(r'\\', Operator), (r'[-+/%=!><|&*^][-+/%=!><|&*^.]*', Operator), (r'[][(),:;`{}?.\'~^]', Punctuation),
# Numbers (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*_*[pP][+-]?\d(_*\d)*' + num_postfix, Number.Float), (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*\.[\da-fA-F](_*[\da-fA-F])*' r'(_*[pP][+-]?\d(_*\d)*)?' + num_postfix, Number.Float), (r'\d(_*\d)*_*[eE][+-]?\d(_*\d)*' + num_postfix, Number.Float), (r'\d(_*\d)*\.\d(_*\d)*(_*[eE][+-]?\d(_*\d)*)?' + num_postfix, Number.Float), (r'0[bB]_*[01](_*[01])*' + num_postfix, Number.Bin), (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*' + num_postfix, Number.Hex), (r'\d(_*\d)*' + num_postfix, Number.Integer),
# Character/String Literals (r"'", String.Char, 'character'), (r'"', String, 'string'), # Special (r'\[[a-zA-Z_\d]*\]', Keyword.Type), (r'\(\)', Name.Builtin), ], 'character': [ # Allows multi-chars, incorrectly. (r"[^\\']'", String.Char, '#pop'), (r"\\", String.Escape, 'escape'), ("'", String.Char, '#pop'), ], 'string': [ (r'[^\\"]+', String), (r"\\", String.Escape, 'escape'), ('"', String, '#pop'), ],
'escape': [ (r'[abfnrtv"\'&\\]', String.Escape, '#pop'), (r'\^[][' + uni.Lu + r'@^_]', String.Escape, '#pop'), ('|'.join(ascii), String.Escape, '#pop'), (r'o[0-7]+', String.Escape, '#pop'), (r'x[\da-fA-F]+', String.Escape, '#pop'), (r'\d+', String.Escape, '#pop'), (r'(\s+)(\\)', bygroups(Whitespace, String.Escape), '#pop'), ], }1234567891011121314151617181920212223242526272829303132333435""" pygments.lexers.gcodelexer ~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for the G Code Language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Comment, Name, Text, Keyword, Number
__all__ = ['GcodeLexer']
class GcodeLexer(RegexLexer): """ For gcode source code. """ name = 'g-code' aliases = ['gcode'] filenames = ['*.gcode'] url = 'https://en.wikipedia.org/wiki/G-code' version_added = '2.9'
tokens = { 'root': [ (r';.*\n', Comment), (r'^[gmGM]\d{1,4}\s', Name.Builtin), # M or G commands (r'([^gGmM])([+-]?\d*[.]?\d+)', bygroups(Keyword, Number)), (r'\s', Text.Whitespace), (r'.*\n', Text), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189""" pygments.lexers.gdscript ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for GDScript.
Modified by Daniel J. Ramirez <djrmuv@gmail.com> based on the original python.py.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, default, words, \ combinedfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ["GDScriptLexer"]
class GDScriptLexer(RegexLexer): """ For GDScript source code. """
name = "GDScript" url = 'https://www.godotengine.org' aliases = ["gdscript", "gd"] filenames = ["*.gd"] mimetypes = ["text/x-gdscript", "application/x-gdscript"] version_added = ''
def innerstring_rules(ttype): return [ # the old style '%s' % (...) string formatting (r"%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?" "[hlL]?[E-GXc-giorsux%]", String.Interpol), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"%\n]+', ttype), (r'[\'"\\]', ttype), # unhandled string formatting sign (r"%", ttype), # newlines are an error (use "nl" state) ]
tokens = { "root": [ (r"\n", Whitespace), (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")', bygroups(Whitespace, String.Affix, String.Doc)), (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')", bygroups(Whitespace, String.Affix, String.Doc)), (r"[^\S\n]+", Whitespace), (r"#.*$", Comment.Single), (r"[]{}:(),;[]", Punctuation), (r"(\\)(\n)", bygroups(Text, Whitespace)), (r"\\", Text), (r"(in|and|or|not)\b", Operator.Word), (r"!=|==|<<|>>|&&|\+=|-=|\*=|/=|%=|&=|\|=|\|\||[-~+/*%=<>&^.!|$]", Operator), include("keywords"), (r"(func)(\s+)", bygroups(Keyword, Whitespace), "funcname"), (r"(class)(\s+)", bygroups(Keyword, Whitespace), "classname"), include("builtins"), ('([rR]|[uUbB][rR]|[rR][uUbB])(""")', bygroups(String.Affix, String.Double), "tdqs"), ("([rR]|[uUbB][rR]|[rR][uUbB])(''')", bygroups(String.Affix, String.Single), "tsqs"), ('([rR]|[uUbB][rR]|[rR][uUbB])(")', bygroups(String.Affix, String.Double), "dqs"), ("([rR]|[uUbB][rR]|[rR][uUbB])(')", bygroups(String.Affix, String.Single), "sqs"), ('([uUbB]?)(""")', bygroups(String.Affix, String.Double), combined("stringescape", "tdqs")), ("([uUbB]?)(''')", bygroups(String.Affix, String.Single), combined("stringescape", "tsqs")), ('([uUbB]?)(")', bygroups(String.Affix, String.Double), combined("stringescape", "dqs")), ("([uUbB]?)(')", bygroups(String.Affix, String.Single), combined("stringescape", "sqs")), include("name"), include("numbers"), ], "keywords": [ (words(("and", "in", "not", "or", "as", "breakpoint", "class", "class_name", "extends", "is", "func", "setget", "signal", "tool", "const", "enum", "export", "onready", "static", "var", "break", "continue", "if", "elif", "else", "for", "pass", "return", "match", "while", "remote", "master", "puppet", "remotesync", "mastersync", "puppetsync"), suffix=r"\b"), Keyword), ], "builtins": [ (words(("Color8", "ColorN", "abs", "acos", "asin", "assert", "atan", "atan2", "bytes2var", "ceil", "char", "clamp", "convert", "cos", "cosh", "db2linear", "decimals", "dectime", "deg2rad", "dict2inst", "ease", "exp", "floor", "fmod", "fposmod", "funcref", "hash", "inst2dict", "instance_from_id", "is_inf", "is_nan", "lerp", "linear2db", "load", "log", "max", "min", "nearest_po2", "pow", "preload", "print", "print_stack", "printerr", "printraw", "prints", "printt", "rad2deg", "rand_range", "rand_seed", "randf", "randi", "randomize", "range", "round", "seed", "sign", "sin", "sinh", "sqrt", "stepify", "str", "str2var", "tan", "tan", "tanh", "type_exist", "typeof", "var2bytes", "var2str", "weakref", "yield"), prefix=r"(?<!\.)", suffix=r"\b"), Name.Builtin), (r"((?<!\.)(self|false|true)|(PI|TAU|NAN|INF)" r")\b", Name.Builtin.Pseudo), (words(("bool", "int", "float", "String", "NodePath", "Vector2", "Rect2", "Transform2D", "Vector3", "Rect3", "Plane", "Quat", "Basis", "Transform", "Color", "RID", "Object", "NodePath", "Dictionary", "Array", "PackedByteArray", "PackedInt32Array", "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray", "PackedVector2Array", "PackedVector3Array", "PackedColorArray", "null", "void"), prefix=r"(?<!\.)", suffix=r"\b"), Name.Builtin.Type), ], "numbers": [ (r"(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?", Number.Float), (r"\d+[eE][+-]?[0-9]+j?", Number.Float), (r"0[xX][a-fA-F0-9]+", Number.Hex), (r"\d+j?", Number.Integer), ], "name": [(r"[a-zA-Z_]\w*", Name)], "funcname": [(r"[a-zA-Z_]\w*", Name.Function, "#pop"), default("#pop")], "classname": [(r"[a-zA-Z_]\w*", Name.Class, "#pop")], "stringescape": [ ( r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|' r"U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})", String.Escape, ) ], "strings-single": innerstring_rules(String.Single), "strings-double": innerstring_rules(String.Double), "dqs": [ (r'"', String.Double, "#pop"), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include("strings-double"), ], "sqs": [ (r"'", String.Single, "#pop"), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include("strings-single"), ], "tdqs": [ (r'"""', String.Double, "#pop"), include("strings-double"), (r"\n", Whitespace), ], "tsqs": [ (r"'''", String.Single, "#pop"), include("strings-single"), (r"\n", Whitespace), ], }
def analyse_text(text): score = 0.0
if re.search( r"func (_ready|_init|_input|_process|_unhandled_input)", text ): score += 0.8
if re.search( r"(extends |class_name |onready |preload|load|setget|func [^_])", text ): score += 0.4
if re.search(r"(var|const|enum|export|signal|tool)", text): score += 0.2
return min(score, 1.0)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374""" pygments.lexers.gleam ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Gleam programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['GleamLexer']
class GleamLexer(RegexLexer): """ Lexer for the Gleam programming language (version 1.0.0). """
name = 'Gleam' url = 'https://gleam.run/' filenames = ['*.gleam'] aliases = ['gleam'] mimetypes = ['text/x-gleam'] version_added = '2.19'
keywords = words(( 'as', 'assert', 'auto', 'case', 'const', 'delegate', 'derive', 'echo', 'else', 'fn', 'if', 'implement', 'import', 'let', 'macro', 'opaque', 'panic', 'pub', 'test', 'todo', 'type', 'use', ), suffix=r'\b')
tokens = { 'root': [ # Comments (r'(///.*?)(\n)', bygroups(String.Doc, Whitespace)), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# Keywords (keywords, Keyword), (r'([a-zA-Z_]+)(\.)', bygroups(Keyword, Punctuation)),
# Punctuation (r'[()\[\]{}:;,@]+', Punctuation), (r'(#|!=|!|==|\|>|\|\||\||\->|<\-|&&|<<|>>|\.\.|\.|=)', Punctuation),
# Operators (r'(<>|\+\.?|\-\.?|\*\.?|/\.?|%\.?|<=\.?|>=\.?|<\.?|>\.?|=)', Operator),
# Strings (r'"(\\"|[^"])*"', String),
# Identifiers (r'\b(let)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Variable)), (r'\b(fn)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Function)), (r'[a-zA-Z_/]\w*', Name),
# numbers (r'(\d+(_\d+)*\.(?!\.)(\d+(_\d+)*)?|\.\d+(_\d+)*)([eEf][+-]?[0-9]+)?', Number.Float), (r'\d+(_\d+)*[eEf][+-]?[0-9]+', Number.Float), (r'0[xX][a-fA-F0-9]+(_[a-fA-F0-9]+)*(\.([a-fA-F0-9]+(_[a-fA-F0-9]+)*)?)?p[+-]?\d+', Number.Float), (r'0[bB][01]+(_[01]+)*', Number.Bin), (r'0[oO][0-7]+(_[0-7]+)*', Number.Oct), (r'0[xX][a-fA-F0-9]+(_[a-fA-F0-9]+)*', Number.Hex), (r'\d+(_\d+)*', Number.Integer),
# Whitespace (r'\s+', Whitespace),
], }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697""" pygments.lexers.go ~~~~~~~~~~~~~~~~~~
Lexers for the Google Go language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['GoLexer']
class GoLexer(RegexLexer): """ For Go source. """ name = 'Go' url = 'https://go.dev/' filenames = ['*.go'] aliases = ['go', 'golang'] mimetypes = ['text/x-gosrc'] version_added = '1.2'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuations (r'//(.*?)$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'(import|package)\b', Keyword.Namespace), (r'(var|func|struct|map|chan|type|interface|const)\b', Keyword.Declaration), (words(( 'break', 'default', 'select', 'case', 'defer', 'go', 'else', 'goto', 'switch', 'fallthrough', 'if', 'range', 'continue', 'for', 'return'), suffix=r'\b'), Keyword), (r'(true|false|iota|nil)\b', Keyword.Constant), # It seems the builtin types aren't actually keywords, but # can be used as functions. So we need two declarations. (words(( 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64', 'complex64', 'complex128', 'byte', 'rune', 'string', 'bool', 'error', 'uintptr', 'any', 'comparable', 'print', 'println', 'panic', 'recover', 'close', 'complex', 'real', 'imag', 'len', 'cap', 'append', 'copy', 'delete', 'new', 'make', 'min', 'max', 'clear'), suffix=r'\b(\()'), bygroups(Name.Builtin, Punctuation)), (words(( 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64', 'complex64', 'complex128', 'byte', 'rune', 'string', 'bool', 'error', 'uintptr', 'any', 'comparable'), suffix=r'\b'), Keyword.Type), # imaginary_lit (r'\d+i', Number), (r'\d+\.\d*([Ee][-+]\d+)?i', Number), (r'\.\d+([Ee][-+]\d+)?i', Number), (r'\d+[Ee][-+]\d+i', Number), # float_lit (r'\d+(\.\d+[eE][+\-]?\d+|' r'\.\d*|[eE][+\-]?\d+)', Number.Float), (r'\.\d+([eE][+\-]?\d+)?', Number.Float), # int_lit # -- octal_lit (r'0[0-7]+', Number.Oct), # -- hex_lit (r'0[xX][0-9a-fA-F]+', Number.Hex), # -- decimal_lit (r'(0|[1-9][0-9]*)', Number.Integer), # char_lit (r"""'(\\['"\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|[^\\])'""", String.Char), # StringLiteral # -- raw_string_lit (r'`[^`]*`', String), # -- interpreted_string_lit (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # Tokens (r'(<<=|>>=|<<|>>|<=|>=|&\^=|&\^|\+=|-=|\*=|/=|%=|&=|\|=|&&|\|\|' r'|<-|\+\+|--|==|!=|:=|\.\.\.|[+\-*/%&]' r'|~|\|)', Operator), (r'[|^<>=!()\[\]{}.,;:]', Punctuation), # identifier (r'[^\W\d]\w*', Name.Other), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262""" pygments.lexers.grammar_notation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for grammar notations like BNF.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, this, using, wordsfrom pygments.token import Comment, Keyword, Literal, Name, Number, \ Operator, Punctuation, String, Text, Whitespace
__all__ = ['BnfLexer', 'AbnfLexer', 'JsgfLexer', 'PegLexer']
class BnfLexer(RegexLexer): """ This lexer is for grammar notations which are similar to original BNF.
In order to maximize a number of targets of this lexer, let's decide some designs:
* We don't distinguish `Terminal Symbol`.
* We do assume that `NonTerminal Symbol` are always enclosed with arrow brackets.
* We do assume that `NonTerminal Symbol` may include any printable characters except arrow brackets and ASCII 0x20. This assumption is for `RBNF <http://www.rfc-base.org/txt/rfc-5511.txt>`_.
* We do assume that target notation doesn't support comment.
* We don't distinguish any operators and punctuation except `::=`.
Though these decision making might cause too minimal highlighting and you might be disappointed, but it is reasonable for us. """
name = 'BNF' aliases = ['bnf'] filenames = ['*.bnf'] mimetypes = ['text/x-bnf'] url = 'https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form' version_added = '2.1'
tokens = { 'root': [ (r'(<)([ -;=?-~]+)(>)', bygroups(Punctuation, Name.Class, Punctuation)),
# an only operator (r'::=', Operator),
# fallback (r'[^<>:]+', Text), # for performance (r'.', Text), ], }
class AbnfLexer(RegexLexer): """ Lexer for IETF 7405 ABNF.
(Updates `5234 <http://www.ietf.org/rfc/rfc5234.txt>`_) grammars. """
name = 'ABNF' url = 'http://www.ietf.org/rfc/rfc7405.txt' aliases = ['abnf'] filenames = ['*.abnf'] mimetypes = ['text/x-abnf'] version_added = '2.1'
_core_rules = ( 'ALPHA', 'BIT', 'CHAR', 'CR', 'CRLF', 'CTL', 'DIGIT', 'DQUOTE', 'HEXDIG', 'HTAB', 'LF', 'LWSP', 'OCTET', 'SP', 'VCHAR', 'WSP')
tokens = { 'root': [ # comment (r';.*$', Comment.Single),
# quoted # double quote itself in this state, it is as '%x22'. (r'(%[si])?"[^"]*"', Literal),
# binary (but i have never seen...) (r'%b[01]+\-[01]+\b', Literal), # range (r'%b[01]+(\.[01]+)*\b', Literal), # concat
# decimal (r'%d[0-9]+\-[0-9]+\b', Literal), # range (r'%d[0-9]+(\.[0-9]+)*\b', Literal), # concat
# hexadecimal (r'%x[0-9a-fA-F]+\-[0-9a-fA-F]+\b', Literal), # range (r'%x[0-9a-fA-F]+(\.[0-9a-fA-F]+)*\b', Literal), # concat
# repetition (<a>*<b>element) including nRule (r'\b[0-9]+\*[0-9]+', Operator), (r'\b[0-9]+\*', Operator), (r'\b[0-9]+', Operator), (r'\*', Operator),
# Strictly speaking, these are not keyword but # are called `Core Rule'. (words(_core_rules, suffix=r'\b'), Keyword),
# nonterminals (ALPHA *(ALPHA / DIGIT / "-")) (r'[a-zA-Z][a-zA-Z0-9-]*\b', Name.Class),
# operators (r'(=/|=|/)', Operator),
# punctuation (r'[\[\]()]', Punctuation),
# fallback (r'\s+', Whitespace), (r'.', Text), ], }
class JsgfLexer(RegexLexer): """ For JSpeech Grammar Format grammars. """ name = 'JSGF' url = 'https://www.w3.org/TR/jsgf/' aliases = ['jsgf'] filenames = ['*.jsgf'] mimetypes = ['application/jsgf', 'application/x-jsgf', 'text/jsgf'] version_added = '2.2'
tokens = { 'root': [ include('comments'), include('non-comments'), ], 'comments': [ (r'/\*\*(?!/)', Comment.Multiline, 'documentation comment'), (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'//.*$', Comment.Single), ], 'non-comments': [ (r'\A#JSGF[^;]*', Comment.Preproc), (r'\s+', Whitespace), (r';', Punctuation), (r'[=|()\[\]*+]', Operator), (r'/[^/]+/', Number.Float), (r'"', String.Double, 'string'), (r'\{', String.Other, 'tag'), (words(('import', 'public'), suffix=r'\b'), Keyword.Reserved), (r'grammar\b', Keyword.Reserved, 'grammar name'), (r'(<)(NULL|VOID)(>)', bygroups(Punctuation, Name.Builtin, Punctuation)), (r'<', Punctuation, 'rulename'), (r'\w+|[^\s;=|()\[\]*+/"{<\w]+', Text), ], 'string': [ (r'"', String.Double, '#pop'), (r'\\.', String.Escape), (r'[^\\"]+', String.Double), ], 'tag': [ (r'\}', String.Other, '#pop'), (r'\\.', String.Escape), (r'[^\\}]+', String.Other), ], 'grammar name': [ (r';', Punctuation, '#pop'), (r'\s+', Whitespace), (r'\.', Punctuation), (r'[^;\s.]+', Name.Namespace), ], 'rulename': [ (r'>', Punctuation, '#pop'), (r'\*', Punctuation), (r'\s+', Whitespace), (r'([^.>]+)(\s*)(\.)', bygroups(Name.Namespace, Text, Punctuation)), (r'[^.>]+', Name.Constant), ], 'documentation comment': [ (r'\*/', Comment.Multiline, '#pop'), (r'^(\s*)(\*?)(\s*)(@(?:example|see))(\s+)' r'([\w\W]*?(?=(?:^\s*\*?\s*@|\*/)))', bygroups(Whitespace, Comment.Multiline, Whitespace, Comment.Special, Whitespace, using(this, state='example'))), (r'(^\s*\*?\s*)(@\S*)', bygroups(Comment.Multiline, Comment.Special)), (r'[^*\n@]+|\w|\W', Comment.Multiline), ], 'example': [ (r'(\n\s*)(\*)', bygroups(Whitespace, Comment.Multiline)), include('non-comments'), (r'.', Comment.Multiline), ], }
class PegLexer(RegexLexer): """ This lexer is for Parsing Expression Grammars (PEG).
Various implementations of PEG have made different decisions regarding the syntax, so let's try to be accommodating:
* `<-`, `←`, `:`, and `=` are all accepted as rule operators.
* Both `|` and `/` are choice operators.
* `^`, `↑`, and `~` are cut operators.
* A single `a-z` character immediately before a string, or multiple `a-z` characters following a string, are part of the string (e.g., `r"..."` or `"..."ilmsuxa`). """
name = 'PEG' url = 'https://bford.info/pub/lang/peg.pdf' aliases = ['peg'] filenames = ['*.peg'] mimetypes = ['text/x-peg'] version_added = '2.6'
tokens = { 'root': [ # Comments (r'#.*$', Comment.Single),
# All operators (r'<-|[←:=/|&!?*+^↑~]', Operator),
# Other punctuation (r'[()]', Punctuation),
# Keywords (r'\.', Keyword),
# Character classes (r'(\[)([^\]]*(?:\\.[^\]\\]*)*)(\])', bygroups(Punctuation, String, Punctuation)),
# Single and double quoted strings (with optional modifiers) (r'[a-z]?"[^"\\]*(?:\\.[^"\\]*)*"[a-z]*', String.Double), (r"[a-z]?'[^'\\]*(?:\\.[^'\\]*)*'[a-z]*", String.Single),
# Nonterminals are not whitespace, operators, or punctuation (r'[^\s<←:=/|&!?*+\^↑~()\[\]"\'#]+', Name.Class),
# Fallback (r'.', Text), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108""" pygments.lexers.graph ~~~~~~~~~~~~~~~~~~~~~
Lexers for graph query languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, using, this, wordsfrom pygments.token import Keyword, Punctuation, Comment, Operator, Name,\ String, Number, Whitespace
__all__ = ['CypherLexer']
class CypherLexer(RegexLexer): """ For Cypher Query Language
For the Cypher version in Neo4j 3.3 """ name = 'Cypher' url = 'https://neo4j.com/docs/developer-manual/3.3/cypher/' aliases = ['cypher'] filenames = ['*.cyp', '*.cypher'] version_added = '2.0'
flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ include('clauses'), include('keywords'), include('relations'), include('strings'), include('whitespace'), include('barewords'), include('comment'), ], 'keywords': [ (r'(create|order|match|limit|set|skip|start|return|with|where|' r'delete|foreach|not|by|true|false)\b', Keyword), ], 'clauses': [ # based on https://neo4j.com/docs/cypher-refcard/3.3/ (r'(create)(\s+)(index|unique)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(drop)(\s+)(contraint|index)(\s+)(on)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(ends)(\s+)(with)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(is)(\s+)(node)(\s+)(key)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(is)(\s+)(null|unique)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(load)(\s+)(csv)(\s+)(from)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(on)(\s+)(match|create)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(optional)(\s+)(match)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(order)(\s+)(by)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(starts)(\s+)(with)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(union)(\s+)(all)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(using)(\s+)(periodic)(\s+)(commit)\b', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(using)(\s+)(index)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(using)(\s+)(range|text|point)(\s+)(index)\b', bygroups(Keyword, Whitespace, Name, Whitespace, Keyword)), (words(( 'all', 'any', 'as', 'asc', 'ascending', 'assert', 'call', 'case', 'create', 'delete', 'desc', 'descending', 'distinct', 'end', 'fieldterminator', 'foreach', 'in', 'limit', 'match', 'merge', 'none', 'not', 'null', 'remove', 'return', 'set', 'skip', 'single', 'start', 'then', 'union', 'unwind', 'yield', 'where', 'when', 'with', 'collect'), suffix=r'\b'), Keyword), ], 'relations': [ (r'(-\[)(.*?)(\]->)', bygroups(Operator, using(this), Operator)), (r'(<-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)), (r'(-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)), (r'-->|<--|\[|\]', Operator), (r'<|>|<>|=|<=|=>|\(|\)|\||:|,|;', Punctuation), (r'[.*{}]', Punctuation), ], 'strings': [ (r'([\'"])(?:\\[tbnrf\'"\\]|[^\\])*?\1', String), (r'`(?:``|[^`])+`', Name.Variable), ], 'whitespace': [ (r'\s+', Whitespace), ], 'barewords': [ (r'[a-z]\w*', Name), (r'\d+', Number), ], 'comment': [ (r'//.*$', Comment.Single), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794""" pygments.lexers.graphics ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for computer graphics and plotting related languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, include, bygroups, using, \ this, defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, \ Number, Punctuation, String, Whitespace
__all__ = ['GLShaderLexer', 'PostScriptLexer', 'AsymptoteLexer', 'GnuplotLexer', 'PovrayLexer', 'HLSLShaderLexer']
class GLShaderLexer(RegexLexer): """ GLSL (OpenGL Shader) lexer. """ name = 'GLSL' aliases = ['glsl'] filenames = ['*.vert', '*.frag', '*.geo'] mimetypes = ['text/x-glslsrc'] url = 'https://www.khronos.org/api/opengl' version_added = '1.1'
tokens = { 'root': [ (r'#(?:.*\\\n)*.*$', Comment.Preproc), (r'//.*$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?', Operator), (r'[?:]', Operator), # quick hack for ternary (r'\bdefined\b', Operator), (r'[;{}(),\[\]]', Punctuation), # FIXME when e is present, no decimal point needed (r'[+-]?\d*\.\d+([eE][-+]?\d+)?', Number.Float), (r'[+-]?\d+\.\d*([eE][-+]?\d+)?', Number.Float), (r'0[xX][0-9a-fA-F]*', Number.Hex), (r'0[0-7]*', Number.Oct), (r'[1-9][0-9]*', Number.Integer), (words(( # Storage qualifiers 'attribute', 'const', 'uniform', 'varying', 'buffer', 'shared', 'in', 'out', # Layout qualifiers 'layout', # Interpolation qualifiers 'flat', 'smooth', 'noperspective', # Auxiliary qualifiers 'centroid', 'sample', 'patch', # Parameter qualifiers. Some double as Storage qualifiers 'inout', # Precision qualifiers 'lowp', 'mediump', 'highp', 'precision', # Invariance qualifiers 'invariant', # Precise qualifiers 'precise', # Memory qualifiers 'coherent', 'volatile', 'restrict', 'readonly', 'writeonly', # Statements 'break', 'continue', 'do', 'for', 'while', 'switch', 'case', 'default', 'if', 'else', 'subroutine', 'discard', 'return', 'struct'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( # Boolean values 'true', 'false'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), (words(( # Miscellaneous types 'void', 'atomic_uint', # Floating-point scalars and vectors 'float', 'vec2', 'vec3', 'vec4', 'double', 'dvec2', 'dvec3', 'dvec4', # Integer scalars and vectors 'int', 'ivec2', 'ivec3', 'ivec4', 'uint', 'uvec2', 'uvec3', 'uvec4', # Boolean scalars and vectors 'bool', 'bvec2', 'bvec3', 'bvec4', # Matrices 'mat2', 'mat3', 'mat4', 'dmat2', 'dmat3', 'dmat4', 'mat2x2', 'mat2x3', 'mat2x4', 'dmat2x2', 'dmat2x3', 'dmat2x4', 'mat3x2', 'mat3x3', 'mat3x4', 'dmat3x2', 'dmat3x3', 'dmat3x4', 'mat4x2', 'mat4x3', 'mat4x4', 'dmat4x2', 'dmat4x3', 'dmat4x4', # Floating-point samplers 'sampler1D', 'sampler2D', 'sampler3D', 'samplerCube', 'sampler1DArray', 'sampler2DArray', 'samplerCubeArray', 'sampler2DRect', 'samplerBuffer', 'sampler2DMS', 'sampler2DMSArray', # Shadow samplers 'sampler1DShadow', 'sampler2DShadow', 'samplerCubeShadow', 'sampler1DArrayShadow', 'sampler2DArrayShadow', 'samplerCubeArrayShadow', 'sampler2DRectShadow', # Signed integer samplers 'isampler1D', 'isampler2D', 'isampler3D', 'isamplerCube', 'isampler1DArray', 'isampler2DArray', 'isamplerCubeArray', 'isampler2DRect', 'isamplerBuffer', 'isampler2DMS', 'isampler2DMSArray', # Unsigned integer samplers 'usampler1D', 'usampler2D', 'usampler3D', 'usamplerCube', 'usampler1DArray', 'usampler2DArray', 'usamplerCubeArray', 'usampler2DRect', 'usamplerBuffer', 'usampler2DMS', 'usampler2DMSArray', # Floating-point image types 'image1D', 'image2D', 'image3D', 'imageCube', 'image1DArray', 'image2DArray', 'imageCubeArray', 'image2DRect', 'imageBuffer', 'image2DMS', 'image2DMSArray', # Signed integer image types 'iimage1D', 'iimage2D', 'iimage3D', 'iimageCube', 'iimage1DArray', 'iimage2DArray', 'iimageCubeArray', 'iimage2DRect', 'iimageBuffer', 'iimage2DMS', 'iimage2DMSArray', # Unsigned integer image types 'uimage1D', 'uimage2D', 'uimage3D', 'uimageCube', 'uimage1DArray', 'uimage2DArray', 'uimageCubeArray', 'uimage2DRect', 'uimageBuffer', 'uimage2DMS', 'uimage2DMSArray'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(( # Reserved for future use. 'common', 'partition', 'active', 'asm', 'class', 'union', 'enum', 'typedef', 'template', 'this', 'resource', 'goto', 'inline', 'noinline', 'public', 'static', 'extern', 'external', 'interface', 'long', 'short', 'half', 'fixed', 'unsigned', 'superp', 'input', 'output', 'hvec2', 'hvec3', 'hvec4', 'fvec2', 'fvec3', 'fvec4', 'sampler3DRect', 'filter', 'sizeof', 'cast', 'namespace', 'using'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), # All names beginning with "gl_" are reserved. (r'gl_\w*', Name.Builtin), (r'[a-zA-Z_]\w*', Name), (r'\.', Punctuation), (r'\s+', Whitespace), ], }
class HLSLShaderLexer(RegexLexer): """ HLSL (Microsoft Direct3D Shader) lexer. """ name = 'HLSL' aliases = ['hlsl'] filenames = ['*.hlsl', '*.hlsli'] mimetypes = ['text/x-hlsl'] url = 'https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl' version_added = '2.3'
tokens = { 'root': [ (r'#(?:.*\\\n)*.*$', Comment.Preproc), (r'//.*$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?', Operator), (r'[?:]', Operator), # quick hack for ternary (r'\bdefined\b', Operator), (r'[;{}(),.\[\]]', Punctuation), # FIXME when e is present, no decimal point needed (r'[+-]?\d*\.\d+([eE][-+]?\d+)?f?', Number.Float), (r'[+-]?\d+\.\d*([eE][-+]?\d+)?f?', Number.Float), (r'0[xX][0-9a-fA-F]*', Number.Hex), (r'0[0-7]*', Number.Oct), (r'[1-9][0-9]*', Number.Integer), (r'"', String, 'string'), (words(( 'asm','asm_fragment','break','case','cbuffer','centroid','class', 'column_major','compile','compile_fragment','const','continue', 'default','discard','do','else','export','extern','for','fxgroup', 'globallycoherent','groupshared','if','in','inline','inout', 'interface','line','lineadj','linear','namespace','nointerpolation', 'noperspective','NULL','out','packoffset','pass','pixelfragment', 'point','precise','return','register','row_major','sample', 'sampler','shared','stateblock','stateblock_state','static', 'struct','switch','tbuffer','technique','technique10', 'technique11','texture','typedef','triangle','triangleadj', 'uniform','vertexfragment','volatile','while'), prefix=r'\b', suffix=r'\b'), Keyword), (words(('true','false'), prefix=r'\b', suffix=r'\b'), Keyword.Constant), (words(( 'auto','catch','char','const_cast','delete','dynamic_cast','enum', 'explicit','friend','goto','long','mutable','new','operator', 'private','protected','public','reinterpret_cast','short','signed', 'sizeof','static_cast','template','this','throw','try','typename', 'union','unsigned','using','virtual'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), (words(( 'dword','matrix','snorm','string','unorm','unsigned','void','vector', 'BlendState','Buffer','ByteAddressBuffer','ComputeShader', 'DepthStencilState','DepthStencilView','DomainShader', 'GeometryShader','HullShader','InputPatch','LineStream', 'OutputPatch','PixelShader','PointStream','RasterizerState', 'RenderTargetView','RasterizerOrderedBuffer', 'RasterizerOrderedByteAddressBuffer', 'RasterizerOrderedStructuredBuffer','RasterizerOrderedTexture1D', 'RasterizerOrderedTexture1DArray','RasterizerOrderedTexture2D', 'RasterizerOrderedTexture2DArray','RasterizerOrderedTexture3D', 'RWBuffer','RWByteAddressBuffer','RWStructuredBuffer', 'RWTexture1D','RWTexture1DArray','RWTexture2D','RWTexture2DArray', 'RWTexture3D','SamplerState','SamplerComparisonState', 'StructuredBuffer','Texture1D','Texture1DArray','Texture2D', 'Texture2DArray','Texture2DMS','Texture2DMSArray','Texture3D', 'TextureCube','TextureCubeArray','TriangleStream','VertexShader'), prefix=r'\b', suffix=r'\b'), Keyword.Type), (words(( 'bool','double','float','int','half','min16float','min10float', 'min16int','min12int','min16uint','uint'), prefix=r'\b', suffix=r'([1-4](x[1-4])?)?\b'), Keyword.Type), # vector and matrix types (words(( 'abort','abs','acos','all','AllMemoryBarrier', 'AllMemoryBarrierWithGroupSync','any','AppendStructuredBuffer', 'asdouble','asfloat','asin','asint','asuint','asuint','atan', 'atan2','ceil','CheckAccessFullyMapped','clamp','clip', 'CompileShader','ConsumeStructuredBuffer','cos','cosh','countbits', 'cross','D3DCOLORtoUBYTE4','ddx','ddx_coarse','ddx_fine','ddy', 'ddy_coarse','ddy_fine','degrees','determinant', 'DeviceMemoryBarrier','DeviceMemoryBarrierWithGroupSync','distance', 'dot','dst','errorf','EvaluateAttributeAtCentroid', 'EvaluateAttributeAtSample','EvaluateAttributeSnapped','exp', 'exp2','f16tof32','f32tof16','faceforward','firstbithigh', 'firstbitlow','floor','fma','fmod','frac','frexp','fwidth', 'GetRenderTargetSampleCount','GetRenderTargetSamplePosition', 'GlobalOrderedCountIncrement','GroupMemoryBarrier', 'GroupMemoryBarrierWithGroupSync','InterlockedAdd','InterlockedAnd', 'InterlockedCompareExchange','InterlockedCompareStore', 'InterlockedExchange','InterlockedMax','InterlockedMin', 'InterlockedOr','InterlockedXor','isfinite','isinf','isnan', 'ldexp','length','lerp','lit','log','log10','log2','mad','max', 'min','modf','msad4','mul','noise','normalize','pow','printf', 'Process2DQuadTessFactorsAvg','Process2DQuadTessFactorsMax', 'Process2DQuadTessFactorsMin','ProcessIsolineTessFactors', 'ProcessQuadTessFactorsAvg','ProcessQuadTessFactorsMax', 'ProcessQuadTessFactorsMin','ProcessTriTessFactorsAvg', 'ProcessTriTessFactorsMax','ProcessTriTessFactorsMin', 'QuadReadLaneAt','QuadSwapX','QuadSwapY','radians','rcp', 'reflect','refract','reversebits','round','rsqrt','saturate', 'sign','sin','sincos','sinh','smoothstep','sqrt','step','tan', 'tanh','tex1D','tex1D','tex1Dbias','tex1Dgrad','tex1Dlod', 'tex1Dproj','tex2D','tex2D','tex2Dbias','tex2Dgrad','tex2Dlod', 'tex2Dproj','tex3D','tex3D','tex3Dbias','tex3Dgrad','tex3Dlod', 'tex3Dproj','texCUBE','texCUBE','texCUBEbias','texCUBEgrad', 'texCUBElod','texCUBEproj','transpose','trunc','WaveAllBitAnd', 'WaveAllMax','WaveAllMin','WaveAllBitOr','WaveAllBitXor', 'WaveAllEqual','WaveAllProduct','WaveAllSum','WaveAllTrue', 'WaveAnyTrue','WaveBallot','WaveGetLaneCount','WaveGetLaneIndex', 'WaveGetOrderedIndex','WaveIsHelperLane','WaveOnce', 'WavePrefixProduct','WavePrefixSum','WaveReadFirstLane', 'WaveReadLaneAt'), prefix=r'\b', suffix=r'\b'), Name.Builtin), # built-in functions (words(( 'SV_ClipDistance','SV_ClipDistance0','SV_ClipDistance1', 'SV_Culldistance','SV_CullDistance0','SV_CullDistance1', 'SV_Coverage','SV_Depth','SV_DepthGreaterEqual', 'SV_DepthLessEqual','SV_DispatchThreadID','SV_DomainLocation', 'SV_GroupID','SV_GroupIndex','SV_GroupThreadID','SV_GSInstanceID', 'SV_InnerCoverage','SV_InsideTessFactor','SV_InstanceID', 'SV_IsFrontFace','SV_OutputControlPointID','SV_Position', 'SV_PrimitiveID','SV_RenderTargetArrayIndex','SV_SampleIndex', 'SV_StencilRef','SV_TessFactor','SV_VertexID', 'SV_ViewportArrayIndex'), prefix=r'\b', suffix=r'\b'), Name.Decorator), # system-value semantics (r'\bSV_Target[0-7]?\b', Name.Decorator), (words(( 'allow_uav_condition','branch','call','domain','earlydepthstencil', 'fastopt','flatten','forcecase','instance','loop','maxtessfactor', 'numthreads','outputcontrolpoints','outputtopology','partitioning', 'patchconstantfunc','unroll'), prefix=r'\b', suffix=r'\b'), Name.Decorator), # attributes (r'[a-zA-Z_]\w*', Name), (r'\\$', Comment.Preproc), # backslash at end of line -- usually macro continuation (r'\s+', Whitespace), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ], }
class PostScriptLexer(RegexLexer): """ Lexer for PostScript files. """ name = 'PostScript' url = 'https://en.wikipedia.org/wiki/PostScript' aliases = ['postscript', 'postscr'] filenames = ['*.ps', '*.eps'] mimetypes = ['application/postscript'] version_added = '1.4'
delimiter = r'()<>\[\]{}/%\s' delimiter_end = rf'(?=[{delimiter}])'
valid_name_chars = rf'[^{delimiter}]' valid_name = rf"{valid_name_chars}+{delimiter_end}"
tokens = { 'root': [ # All comment types (r'^%!.+$', Comment.Preproc), (r'%%.*$', Comment.Special), (r'(^%.*\n){2,}', Comment.Multiline), (r'%.*$', Comment.Single),
# String literals are awkward; enter separate state. (r'\(', String, 'stringliteral'),
(r'[{}<>\[\]]', Punctuation),
# Numbers (r'<[0-9A-Fa-f]+>' + delimiter_end, Number.Hex), # Slight abuse: use Oct to signify any explicit base system (r'[0-9]+\#(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)' r'((e|E)[0-9]+)?' + delimiter_end, Number.Oct), (r'(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)((e|E)[0-9]+)?' + delimiter_end, Number.Float), (r'(\-|\+)?[0-9]+' + delimiter_end, Number.Integer),
# References (rf'\/{valid_name}', Name.Variable),
# Names (valid_name, Name.Function), # Anything else is executed
# These keywords taken from # <http://www.math.ubc.ca/~cass/graphics/manual/pdf/a1.pdf> # Is there an authoritative list anywhere that doesn't involve # trawling documentation?
(r'(false|true)' + delimiter_end, Keyword.Constant),
# Conditionals / flow control (r'(eq|ne|g[et]|l[et]|and|or|not|if(?:else)?|for(?:all)?)' + delimiter_end, Keyword.Reserved),
(words(( 'abs', 'add', 'aload', 'arc', 'arcn', 'array', 'atan', 'begin', 'bind', 'ceiling', 'charpath', 'clip', 'closepath', 'concat', 'concatmatrix', 'copy', 'cos', 'currentlinewidth', 'currentmatrix', 'currentpoint', 'curveto', 'cvi', 'cvs', 'def', 'defaultmatrix', 'dict', 'dictstackoverflow', 'div', 'dtransform', 'dup', 'end', 'exch', 'exec', 'exit', 'exp', 'fill', 'findfont', 'floor', 'get', 'getinterval', 'grestore', 'gsave', 'gt', 'identmatrix', 'idiv', 'idtransform', 'index', 'invertmatrix', 'itransform', 'length', 'lineto', 'ln', 'load', 'log', 'loop', 'matrix', 'mod', 'moveto', 'mul', 'neg', 'newpath', 'pathforall', 'pathbbox', 'pop', 'print', 'pstack', 'put', 'quit', 'rand', 'rangecheck', 'rcurveto', 'repeat', 'restore', 'rlineto', 'rmoveto', 'roll', 'rotate', 'round', 'run', 'save', 'scale', 'scalefont', 'setdash', 'setfont', 'setgray', 'setlinecap', 'setlinejoin', 'setlinewidth', 'setmatrix', 'setrgbcolor', 'shfill', 'show', 'showpage', 'sin', 'sqrt', 'stack', 'stringwidth', 'stroke', 'strokepath', 'sub', 'syntaxerror', 'transform', 'translate', 'truncate', 'typecheck', 'undefined', 'undefinedfilename', 'undefinedresult'), suffix=delimiter_end), Name.Builtin),
(r'\s+', Whitespace), ],
'stringliteral': [ (r'[^()\\]+', String), (r'\\', String.Escape, 'escape'), (r'\(', String, '#push'), (r'\)', String, '#pop'), ],
'escape': [ (r'[0-8]{3}|n|r|t|b|f|\\|\(|\)', String.Escape, '#pop'), default('#pop'), ], }
class AsymptoteLexer(RegexLexer): """ For Asymptote source code. """ name = 'Asymptote' url = 'http://asymptote.sf.net/' aliases = ['asymptote', 'asy'] filenames = ['*.asy'] mimetypes = ['text/x-asymptote'] version_added = '1.2'
#: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/\*.*?\*/)+'
tokens = { 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//(\n|(.|\n)*?[^\\]\n)', Comment), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment), ], 'statements': [ # simple string (TeX friendly) (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # C style string (with character escapes) (r"'", String, 'string'), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'0x[0-9a-fA-F]+[Ll]?', Number.Hex), (r'0[0-7]+[Ll]?', Number.Oct), (r'\d+[Ll]?', Number.Integer), (r'[~!%^&*+=|?:<>/-]', Operator), (r'[()\[\],.]', Punctuation), (r'\b(case)(.+?)(:)', bygroups(Keyword, using(this), Text)), (r'(and|controls|tension|atleast|curl|if|else|while|for|do|' r'return|break|continue|struct|typedef|new|access|import|' r'unravel|from|include|quote|static|public|private|restricted|' r'this|explicit|true|false|null|cycle|newframe|operator)\b', Keyword), # Since an asy-type-name can be also an asy-function-name, # in the following we test if the string " [a-zA-Z]" follows # the Keyword.Type. # Of course it is not perfect ! (r'(Braid|FitResult|Label|Legend|TreeNode|abscissa|arc|arrowhead|' r'binarytree|binarytreeNode|block|bool|bool3|bounds|bqe|circle|' r'conic|coord|coordsys|cputime|ellipse|file|filltype|frame|grid3|' r'guide|horner|hsv|hyperbola|indexedTransform|int|inversion|key|' r'light|line|linefit|marginT|marker|mass|object|pair|parabola|path|' r'path3|pen|picture|point|position|projection|real|revolution|' r'scaleT|scientific|segment|side|slice|splitface|string|surface|' r'tensionSpecifier|ticklocate|ticksgridT|tickvalues|transform|' r'transformation|tree|triangle|trilinear|triple|vector|' r'vertex|void)(?=\s+[a-zA-Z])', Keyword.Type), # Now the asy-type-name which are not asy-function-name # except yours ! # Perhaps useless (r'(Braid|FitResult|TreeNode|abscissa|arrowhead|block|bool|bool3|' r'bounds|coord|frame|guide|horner|int|linefit|marginT|pair|pen|' r'picture|position|real|revolution|slice|splitface|ticksgridT|' r'tickvalues|tree|triple|vertex|void)\b', Keyword.Type), (r'[a-zA-Z_]\w*:(?!:)', Name.Label), (r'[a-zA-Z_]\w*', Name), ], 'root': [ include('whitespace'), # functions (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments r'([a-zA-Z_]\w*)' # method name r'(\s*\([^;]*?\))' # signature r'(' + _ws + r')(\{)', bygroups(using(this), Name.Function, using(this), using(this), Punctuation), 'function'), # function declarations (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments r'([a-zA-Z_]\w*)' # method name r'(\s*\([^;]*?\))' # signature r'(' + _ws + r')(;)', bygroups(using(this), Name.Function, using(this), using(this), Punctuation)), default('statement'), ], 'statement': [ include('whitespace'), include('statements'), ('[{}]', Punctuation), (';', Punctuation, '#pop'), ], 'function': [ include('whitespace'), include('statements'), (';', Punctuation), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], 'string': [ (r"'", String, '#pop'), (r'\\([\\abfnrtv"\'?]|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'\n', String), (r"[^\\'\n]+", String), # all other characters (r'\\\n', String), (r'\\n', String), # line continuation (r'\\', String), # stray backslash ], }
def get_tokens_unprocessed(self, text): from pygments.lexers._asy_builtins import ASYFUNCNAME, ASYVARNAME for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name and value in ASYFUNCNAME: token = Name.Function elif token is Name and value in ASYVARNAME: token = Name.Variable yield index, token, value
def _shortened(word): dpos = word.find('$') return '|'.join(word[:dpos] + word[dpos+1:i] + r'\b' for i in range(len(word), dpos, -1))
def _shortened_many(*words): return '|'.join(map(_shortened, words))
class GnuplotLexer(RegexLexer): """ For Gnuplot plotting scripts. """
name = 'Gnuplot' url = 'http://gnuplot.info/' aliases = ['gnuplot'] filenames = ['*.plot', '*.plt'] mimetypes = ['text/x-gnuplot'] version_added = '0.11'
tokens = { 'root': [ include('whitespace'), (_shortened('bi$nd'), Keyword, 'bind'), (_shortened_many('ex$it', 'q$uit'), Keyword, 'quit'), (_shortened('f$it'), Keyword, 'fit'), (r'(if)(\s*)(\()', bygroups(Keyword, Text, Punctuation), 'if'), (r'else\b', Keyword), (_shortened('pa$use'), Keyword, 'pause'), (_shortened_many('p$lot', 'rep$lot', 'sp$lot'), Keyword, 'plot'), (_shortened('sa$ve'), Keyword, 'save'), (_shortened('se$t'), Keyword, ('genericargs', 'optionarg')), (_shortened_many('sh$ow', 'uns$et'), Keyword, ('noargs', 'optionarg')), (_shortened_many('low$er', 'ra$ise', 'ca$ll', 'cd$', 'cl$ear', 'h$elp', '\\?$', 'hi$story', 'l$oad', 'pr$int', 'pwd$', 're$read', 'res$et', 'scr$eendump', 'she$ll', 'sy$stem', 'up$date'), Keyword, 'genericargs'), (_shortened_many('pwd$', 're$read', 'res$et', 'scr$eendump', 'she$ll', 'test$'), Keyword, 'noargs'), (r'([a-zA-Z_]\w*)(\s*)(=)', bygroups(Name.Variable, Whitespace, Operator), 'genericargs'), (r'([a-zA-Z_]\w*)(\s*)(\()(.*?)(\))(\s*)(=)', bygroups(Name.Function, Whitespace, Punctuation, Text, Punctuation, Whitespace, Operator), 'genericargs'), (r'@[a-zA-Z_]\w*', Name.Constant), # macros (r';', Keyword), ], 'comment': [ (r'[^\\\n]+', Comment), (r'\\\n', Comment), (r'\\', Comment), # don't add the newline to the Comment token default('#pop'), ], 'whitespace': [ ('#', Comment, 'comment'), (r'[ \t\v\f]+', Whitespace), ], 'noargs': [ include('whitespace'), # semicolon and newline end the argument list (r';', Punctuation, '#pop'), (r'\n', Whitespace, '#pop'), ], 'dqstring': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash (r'\n', Whitespace, '#pop'), # newline ends the string too ], 'sqstring': [ (r"''", String), # escaped single quote (r"'", String, '#pop'), (r"[^\\'\n]+", String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # normal backslash (r'\n', Whitespace, '#pop'), # newline ends the string too ], 'genericargs': [ include('noargs'), (r'"', String, 'dqstring'), (r"'", String, 'sqstring'), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float), (r'(\d+\.\d*|\.\d+)', Number.Float), (r'-?\d+', Number.Integer), ('[,.~!%^&*+=|?:<>/-]', Operator), (r'[{}()\[\]]', Punctuation), (r'(eq|ne)\b', Operator.Word), (r'([a-zA-Z_]\w*)(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[a-zA-Z_]\w*', Name), (r'@[a-zA-Z_]\w*', Name.Constant), # macros (r'(\\)(\n)', bygroups(Text, Whitespace)), ], 'optionarg': [ include('whitespace'), (_shortened_many( "a$ll", "an$gles", "ar$row", "au$toscale", "b$ars", "bor$der", "box$width", "cl$abel", "c$lip", "cn$trparam", "co$ntour", "da$ta", "data$file", "dg$rid3d", "du$mmy", "enc$oding", "dec$imalsign", "fit$", "font$path", "fo$rmat", "fu$nction", "fu$nctions", "g$rid", "hid$den3d", "his$torysize", "is$osamples", "k$ey", "keyt$itle", "la$bel", "li$nestyle", "ls$", "loa$dpath", "loc$ale", "log$scale", "mac$ros", "map$ping", "map$ping3d", "mar$gin", "lmar$gin", "rmar$gin", "tmar$gin", "bmar$gin", "mo$use", "multi$plot", "mxt$ics", "nomxt$ics", "mx2t$ics", "nomx2t$ics", "myt$ics", "nomyt$ics", "my2t$ics", "nomy2t$ics", "mzt$ics", "nomzt$ics", "mcbt$ics", "nomcbt$ics", "of$fsets", "or$igin", "o$utput", "pa$rametric", "pm$3d", "pal$ette", "colorb$ox", "p$lot", "poi$ntsize", "pol$ar", "pr$int", "obj$ect", "sa$mples", "si$ze", "st$yle", "su$rface", "table$", "t$erminal", "termo$ptions", "ti$cs", "ticsc$ale", "ticsl$evel", "timef$mt", "tim$estamp", "tit$le", "v$ariables", "ve$rsion", "vi$ew", "xyp$lane", "xda$ta", "x2da$ta", "yda$ta", "y2da$ta", "zda$ta", "cbda$ta", "xl$abel", "x2l$abel", "yl$abel", "y2l$abel", "zl$abel", "cbl$abel", "xti$cs", "noxti$cs", "x2ti$cs", "nox2ti$cs", "yti$cs", "noyti$cs", "y2ti$cs", "noy2ti$cs", "zti$cs", "nozti$cs", "cbti$cs", "nocbti$cs", "xdti$cs", "noxdti$cs", "x2dti$cs", "nox2dti$cs", "ydti$cs", "noydti$cs", "y2dti$cs", "noy2dti$cs", "zdti$cs", "nozdti$cs", "cbdti$cs", "nocbdti$cs", "xmti$cs", "noxmti$cs", "x2mti$cs", "nox2mti$cs", "ymti$cs", "noymti$cs", "y2mti$cs", "noy2mti$cs", "zmti$cs", "nozmti$cs", "cbmti$cs", "nocbmti$cs", "xr$ange", "x2r$ange", "yr$ange", "y2r$ange", "zr$ange", "cbr$ange", "rr$ange", "tr$ange", "ur$ange", "vr$ange", "xzeroa$xis", "x2zeroa$xis", "yzeroa$xis", "y2zeroa$xis", "zzeroa$xis", "zeroa$xis", "z$ero"), Name.Builtin, '#pop'), ], 'bind': [ ('!', Keyword, '#pop'), (_shortened('all$windows'), Name.Builtin), include('genericargs'), ], 'quit': [ (r'gnuplot\b', Keyword), include('noargs'), ], 'fit': [ (r'via\b', Name.Builtin), include('plot'), ], 'if': [ (r'\)', Punctuation, '#pop'), include('genericargs'), ], 'pause': [ (r'(mouse|any|button1|button2|button3)\b', Name.Builtin), (_shortened('key$press'), Name.Builtin), include('genericargs'), ], 'plot': [ (_shortened_many('ax$es', 'axi$s', 'bin$ary', 'ev$ery', 'i$ndex', 'mat$rix', 's$mooth', 'thru$', 't$itle', 'not$itle', 'u$sing', 'w$ith'), Name.Builtin), include('genericargs'), ], 'save': [ (_shortened_many('f$unctions', 's$et', 't$erminal', 'v$ariables'), Name.Builtin), include('genericargs'), ], }
class PovrayLexer(RegexLexer): """ For Persistence of Vision Raytracer files. """ name = 'POVRay' url = 'http://www.povray.org/' aliases = ['pov'] filenames = ['*.pov', '*.inc'] mimetypes = ['text/x-povray'] version_added = '0.11'
tokens = { 'root': [ (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'//.*$', Comment.Single), (r'(?s)"(?:\\.|[^"\\])+"', String.Double), (words(( 'break', 'case', 'debug', 'declare', 'default', 'define', 'else', 'elseif', 'end', 'error', 'fclose', 'fopen', 'for', 'if', 'ifdef', 'ifndef', 'include', 'local', 'macro', 'range', 'read', 'render', 'statistics', 'switch', 'undef', 'version', 'warning', 'while', 'write'), prefix=r'#', suffix=r'\b'), Comment.Preproc), (words(( 'aa_level', 'aa_threshold', 'abs', 'acos', 'acosh', 'adaptive', 'adc_bailout', 'agate', 'agate_turb', 'all', 'alpha', 'ambient', 'ambient_light', 'angle', 'aperture', 'arc_angle', 'area_light', 'asc', 'asin', 'asinh', 'assumed_gamma', 'atan', 'atan2', 'atanh', 'atmosphere', 'atmospheric_attenuation', 'attenuating', 'average', 'background', 'black_hole', 'blue', 'blur_samples', 'bounded_by', 'box_mapping', 'bozo', 'break', 'brick', 'brick_size', 'brightness', 'brilliance', 'bumps', 'bumpy1', 'bumpy2', 'bumpy3', 'bump_map', 'bump_size', 'case', 'caustics', 'ceil', 'checker', 'chr', 'clipped_by', 'clock', 'color', 'color_map', 'colour', 'colour_map', 'component', 'composite', 'concat', 'confidence', 'conic_sweep', 'constant', 'control0', 'control1', 'cos', 'cosh', 'count', 'crackle', 'crand', 'cube', 'cubic_spline', 'cylindrical_mapping', 'debug', 'declare', 'default', 'degrees', 'dents', 'diffuse', 'direction', 'distance', 'distance_maximum', 'div', 'dust', 'dust_type', 'eccentricity', 'else', 'emitting', 'end', 'error', 'error_bound', 'exp', 'exponent', 'fade_distance', 'fade_power', 'falloff', 'falloff_angle', 'false', 'file_exists', 'filter', 'finish', 'fisheye', 'flatness', 'flip', 'floor', 'focal_point', 'fog', 'fog_alt', 'fog_offset', 'fog_type', 'frequency', 'gif', 'global_settings', 'glowing', 'gradient', 'granite', 'gray_threshold', 'green', 'halo', 'hexagon', 'hf_gray_16', 'hierarchy', 'hollow', 'hypercomplex', 'if', 'ifdef', 'iff', 'image_map', 'incidence', 'include', 'int', 'interpolate', 'inverse', 'ior', 'irid', 'irid_wavelength', 'jitter', 'lambda', 'leopard', 'linear', 'linear_spline', 'linear_sweep', 'location', 'log', 'looks_like', 'look_at', 'low_error_factor', 'mandel', 'map_type', 'marble', 'material_map', 'matrix', 'max', 'max_intersections', 'max_iteration', 'max_trace_level', 'max_value', 'metallic', 'min', 'minimum_reuse', 'mod', 'mortar', 'nearest_count', 'no', 'normal', 'normal_map', 'no_shadow', 'number_of_waves', 'octaves', 'off', 'offset', 'omega', 'omnimax', 'on', 'once', 'onion', 'open', 'orthographic', 'panoramic', 'pattern1', 'pattern2', 'pattern3', 'perspective', 'pgm', 'phase', 'phong', 'phong_size', 'pi', 'pigment', 'pigment_map', 'planar_mapping', 'png', 'point_at', 'pot', 'pow', 'ppm', 'precision', 'pwr', 'quadratic_spline', 'quaternion', 'quick_color', 'quick_colour', 'quilted', 'radial', 'radians', 'radiosity', 'radius', 'rainbow', 'ramp_wave', 'rand', 'range', 'reciprocal', 'recursion_limit', 'red', 'reflection', 'refraction', 'render', 'repeat', 'rgb', 'rgbf', 'rgbft', 'rgbt', 'right', 'ripples', 'rotate', 'roughness', 'samples', 'scale', 'scallop_wave', 'scattering', 'seed', 'shadowless', 'sin', 'sine_wave', 'sinh', 'sky', 'sky_sphere', 'slice', 'slope_map', 'smooth', 'specular', 'spherical_mapping', 'spiral', 'spiral1', 'spiral2', 'spotlight', 'spotted', 'sqr', 'sqrt', 'statistics', 'str', 'strcmp', 'strength', 'strlen', 'strlwr', 'strupr', 'sturm', 'substr', 'switch', 'sys', 't', 'tan', 'tanh', 'test_camera_1', 'test_camera_2', 'test_camera_3', 'test_camera_4', 'texture', 'texture_map', 'tga', 'thickness', 'threshold', 'tightness', 'tile2', 'tiles', 'track', 'transform', 'translate', 'transmit', 'triangle_wave', 'true', 'ttf', 'turbulence', 'turb_depth', 'type', 'ultra_wide_angle', 'up', 'use_color', 'use_colour', 'use_index', 'u_steps', 'val', 'variance', 'vaxis_rotate', 'vcross', 'vdot', 'version', 'vlength', 'vnormalize', 'volume_object', 'volume_rendered', 'vol_with_light', 'vrotate', 'v_steps', 'warning', 'warp', 'water_level', 'waves', 'while', 'width', 'wood', 'wrinkles', 'yes'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'bicubic_patch', 'blob', 'box', 'camera', 'cone', 'cubic', 'cylinder', 'difference', 'disc', 'height_field', 'intersection', 'julia_fractal', 'lathe', 'light_source', 'merge', 'mesh', 'object', 'plane', 'poly', 'polygon', 'prism', 'quadric', 'quartic', 'smooth_triangle', 'sor', 'sphere', 'superellipsoid', 'text', 'torus', 'triangle', 'union'), suffix=r'\b'), Name.Builtin), (r'\b(x|y|z|u|v)\b', Name.Builtin.Pseudo), (r'[a-zA-Z_]\w*', Name), (r'[0-9]*\.[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), (r'[\[\](){}<>;,]', Punctuation), (r'[-+*/=.|&]|<=|>=|!=', Operator), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r'\s+', Whitespace), ] }
def analyse_text(text): """POVRAY is similar to JSON/C, but the combination of camera and light_source is probably not very likely elsewhere. HLSL or GLSL are similar (GLSL even has #version), but they miss #declare, and light_source/camera are not keywords anywhere else -- it's fair to assume though that any POVRAY scene must have a camera and lightsource.""" result = 0 if '#version' in text: result += 0.05 if '#declare' in text: result += 0.05 if 'camera' in text: result += 0.05 if 'light_source' in text: result += 0.1
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176""" pygments.lexers.graphql ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for GraphQL, an open-source data query and manipulation language for APIs.
More information: https://graphql.org/
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, words, include, bygroups, defaultfrom pygments.token import (Comment, Keyword, Name, Number, Punctuation, String, Whitespace)
__all__ = ["GraphQLLexer"]
OPERATION_TYPES = ("query", "mutation", "subscription")BUILTIN_TYPES = ("Int", "Float", "String", "Boolean", "ID")BOOLEAN_VALUES = ("true", "false", "null")KEYWORDS = ( "type", "schema", "extend", "enum", "scalar", "implements", "interface", "union", "input", "directive", "QUERY", "MUTATION", "SUBSCRIPTION", "FIELD", "FRAGMENT_DEFINITION", "FRAGMENT_SPREAD", "INLINE_FRAGMENT", "SCHEMA", "SCALAR", "OBJECT", "FIELD_DEFINITION", "ARGUMENT_DEFINITION", "INTERFACE", "UNION", "ENUM", "ENUM_VALUE", "INPUT_OBJECT", "INPUT_FIELD_DEFINITION",)
class GraphQLLexer(RegexLexer): """ Lexer for GraphQL syntax """ name = "GraphQL" aliases = ["graphql"] filenames = ["*.graphql"] url = "https://graphql.org" version_added = '2.16'
tokens = { "ignored_tokens": [ (r"\s+", Whitespace), # Whitespaces (r"#.*$", Comment), (",", Punctuation), # Insignificant commas ], "value": [ include("ignored_tokens"), (r"-?\d+(?![.eE])", Number.Integer, "#pop"), ( r"-?\d+(\.\d+)?([eE][+-]?\d+)?", Number.Float, "#pop", ), (r'"', String, ("#pop", "string")), (words(BOOLEAN_VALUES, suffix=r"\b"), Name.Builtin, "#pop"), (r"\$[a-zA-Z_]\w*", Name.Variable, "#pop"), (r"[a-zA-Z_]\w*", Name.Constant, "#pop"), (r"\[", Punctuation, ("#pop", "list_value")), (r"\{", Punctuation, ("#pop", "object_value")), ], "list_value": [ include("ignored_tokens"), ("]", Punctuation, "#pop"), default("value"), ], "object_value": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name), (r":", Punctuation, "value"), (r"\}", Punctuation, "#pop"), ], "string": [ (r'\\(["\\/bfnrt]|u[a-fA-F0-9]{4})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'"', String, "#pop"), ], "root": [ include("ignored_tokens"), (words(OPERATION_TYPES, suffix=r"\b"), Keyword, "operation"), (words(KEYWORDS, suffix=r"\b"), Keyword), (r"\{", Punctuation, "selection_set"), (r"fragment\b", Keyword, "fragment_definition"), ], "operation": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name.Function), (r"\(", Punctuation, "variable_definition"), (r"\{", Punctuation, ("#pop", "selection_set")), ], "variable_definition": [ include("ignored_tokens"), (r"\$[a-zA-Z_]\w*", Name.Variable), (r"[\]!]", Punctuation), (r":", Punctuation, "type"), (r"=", Punctuation, "value"), (r"\)", Punctuation, "#pop"), ], "type": [ include("ignored_tokens"), (r"\[", Punctuation), (words(BUILTIN_TYPES, suffix=r"\b"), Name.Builtin, "#pop"), (r"[a-zA-Z_]\w*", Name.Class, "#pop"), ], "selection_set": [ include("ignored_tokens"), (r"([a-zA-Z_]\w*)(\s*)(:)", bygroups(Name.Label, Whitespace, Punctuation)), (r"[a-zA-Z_]\w*", Name), # Field ( r"(\.\.\.)(\s+)(on)\b", bygroups(Punctuation, Whitespace, Keyword), "inline_fragment", ), (r"\.\.\.", Punctuation, "fragment_spread"), (r"\(", Punctuation, "arguments"), (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"\{", Punctuation, "selection_set"), (r"\}", Punctuation, "#pop"), ], "directive": [ include("ignored_tokens"), (r"\(", Punctuation, ("#pop", "arguments")), ], "arguments": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name), (r":", Punctuation, "value"), (r"\)", Punctuation, "#pop"), ], # Fragments "fragment_definition": [ include("ignored_tokens"), (r"[\]!]", Punctuation), # For NamedType (r"on\b", Keyword, "type"), (r"[a-zA-Z_]\w*", Name.Function), (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"\{", Punctuation, ("#pop", "selection_set")), ], "fragment_spread": [ include("ignored_tokens"), (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"[a-zA-Z_]\w*", Name, "#pop"), # Fragment name ], "inline_fragment": [ include("ignored_tokens"), (r"[a-zA-Z_]\w*", Name.Class), # Type condition (r"@[a-zA-Z_]\w*", Name.Decorator, "directive"), (r"\{", Punctuation, ("#pop", "selection_set")), ], }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758""" pygments.lexers.graphviz ~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for the DOT language (graphviz).
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Comment, Keyword, Operator, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['GraphvizLexer']
class GraphvizLexer(RegexLexer): """ For graphviz DOT graph description language. """ name = 'Graphviz' url = 'https://www.graphviz.org/doc/info/lang.html' aliases = ['graphviz', 'dot'] filenames = ['*.gv', '*.dot'] mimetypes = ['text/x-graphviz', 'text/vnd.graphviz'] version_added = '2.8' tokens = { 'root': [ (r'\s+', Whitespace), (r'(#|//).*?$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'(?i)(node|edge|graph|digraph|subgraph|strict)\b', Keyword), (r'--|->', Operator), (r'[{}[\]:;,]', Punctuation), (r'(\b\D\w*)(\s*)(=)(\s*)', bygroups(Name.Attribute, Whitespace, Punctuation, Whitespace), 'attr_id'), (r'\b(n|ne|e|se|s|sw|w|nw|c|_)\b', Name.Builtin), (r'\b\D\w*', Name.Tag), # node (r'[-]?((\.[0-9]+)|([0-9]+(\.[0-9]*)?))', Number), (r'"(\\"|[^"])*?"', Name.Tag), # quoted node (r'<', Punctuation, 'xml'), ], 'attr_id': [ (r'\b\D\w*', String, '#pop'), (r'[-]?((\.[0-9]+)|([0-9]+(\.[0-9]*)?))', Number, '#pop'), (r'"(\\"|[^"])*?"', String.Double, '#pop'), (r'<', Punctuation, ('#pop', 'xml')), ], 'xml': [ (r'<', Punctuation, '#push'), (r'>', Punctuation, '#pop'), (r'\s+', Whitespace), (r'[^<>\s]', Name.Tag), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103""" pygments.lexers.gsql ~~~~~~~~~~~~~~~~~~~~
Lexers for TigerGraph GSQL graph query language
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroups, using, this, wordsfrom pygments.token import Keyword, Punctuation, Comment, Operator, Name, \ String, Number, Whitespace
__all__ = ["GSQLLexer"]
class GSQLLexer(RegexLexer):
""" For GSQL queries (version 3.x). """
name = 'GSQL' url = 'https://docs.tigergraph.com/dev/gsql-ref' aliases = ['gsql'] filenames = ['*.gsql'] version_added = '2.10'
flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ include('comment'), include('keywords'), include('clauses'), include('accums'), include('relations'), include('strings'), include('whitespace'), include('barewords'), include('operators'), ], 'comment': [ (r'\#.*', Comment.Single), (r'/\*(.|\n)*?\*/', Comment.Multiline), ], 'keywords': [ (words(( 'ACCUM', 'AND', 'ANY', 'API', 'AS', 'ASC', 'AVG', 'BAG', 'BATCH', 'BETWEEN', 'BOOL', 'BOTH', 'BREAK', 'BY', 'CASE', 'CATCH', 'COALESCE', 'COMPRESS', 'CONTINUE', 'COUNT', 'CREATE', 'DATETIME', 'DATETIME_ADD', 'DATETIME_SUB', 'DELETE', 'DESC', 'DISTRIBUTED', 'DO', 'DOUBLE', 'EDGE', 'ELSE', 'END', 'ESCAPE', 'EXCEPTION', 'FALSE', 'FILE', 'FILTER', 'FLOAT', 'FOREACH', 'FOR', 'FROM', 'GRAPH', 'GROUP', 'GSQL_INT_MAX', 'GSQL_INT_MIN', 'GSQL_UINT_MAX', 'HAVING', 'IF', 'IN', 'INSERT', 'INT', 'INTERPRET', 'INTERSECT', 'INTERVAL', 'INTO', 'IS', 'ISEMPTY', 'JSONARRAY', 'JSONOBJECT', 'LASTHOP', 'LEADING', 'LIKE', 'LIMIT', 'LIST', 'LOAD_ACCUM', 'LOG', 'MAP', 'MATCH', 'MAX', 'MIN', 'MINUS', 'NOT', 'NOW', 'NULL', 'OFFSET', 'OR', 'ORDER', 'PATH', 'PER', 'PINNED', 'POST_ACCUM', 'POST-ACCUM', 'PRIMARY_ID', 'PRINT', 'QUERY', 'RAISE', 'RANGE', 'REPLACE', 'RESET_COLLECTION_ACCUM', 'RETURN', 'RETURNS', 'RUN', 'SAMPLE', 'SELECT', 'SELECT_VERTEX', 'SET', 'SRC', 'STATIC', 'STRING', 'SUM', 'SYNTAX', 'TARGET', 'TAGSTGT', 'THEN', 'TO', 'TO_CSV', 'TO_DATETIME', 'TRAILING', 'TRIM', 'TRUE', 'TRY', 'TUPLE', 'TYPEDEF', 'UINT', 'UNION', 'UPDATE', 'VALUES', 'VERTEX', 'WHEN', 'WHERE', 'WHILE', 'WITH'), prefix=r'(?<!\.)', suffix=r'\b'), Keyword), ], 'clauses': [ (words(('accum', 'having', 'limit', 'order', 'postAccum', 'sample', 'where')), Name.Builtin), ], 'accums': [ (words(('andaccum', 'arrayaccum', 'avgaccum', 'bagaccum', 'bitwiseandaccum', 'bitwiseoraccum', 'groupbyaccum', 'heapaccum', 'listaccum', 'MapAccum', 'maxaccum', 'minaccum', 'oraccum', 'setaccum', 'sumaccum')), Name.Builtin), ], 'relations': [ (r'(-\s?)(\(.*\:\w?\))(\s?-)', bygroups(Operator, using(this), Operator)), (r'->|<-', Operator), (r'[.*{}\[\]\<\>\_]', Punctuation), ], 'strings': [ (r'"([^"\\]|\\.)*"', String), (r'@{1,2}\w+', Name.Variable), ], 'whitespace': [ (r'\s+', Whitespace), ], 'barewords': [ (r'[a-z]\w*', Name), (r'(\d+\.\d+|\d+)', Number), ], 'operators': [ (r'\$|[^0-9|\/|\-](\-\=|\+\=|\*\=|\\\=|\=|\=\=|\=\=\=|' r'\+|\-|\*|\\|\+\=|\>|\<)[^\>|\/]', Operator), (r'(\||\(|\)|\,|\;|\=|\-|\+|\*|\/|\>|\<|\:)', Operator), ], }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273""" pygments.lexers.hare ~~~~~~~~~~~~~~~~~~~~
Lexers for the Hare language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['HareLexer']
class HareLexer(RegexLexer): """ Lexer for the Hare programming language. """ name = 'Hare' url = 'https://harelang.org/' aliases = ['hare'] filenames = ['*.ha'] mimetypes = ['text/x-hare'] version_added = '2.19'
_ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+' _ws1 = r'\s*(?:/[*].*?[*]/\s*)?'
tokens = { 'whitespace': [ (r'^use.*;', Comment.Preproc), (r'@[a-z]+', Comment.Preproc), (r'\n', Whitespace), (r'\s+', Whitespace), (r'//.*?$', Comment.Single), ], 'statements': [ (r'"', String, 'string'), (r'`[^`]*`', String), (r"'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex), (r'0o[0-7]+[LlUu]*', Number.Oct), (r'\d+[zui]?(\d+)?', Number.Integer), (r'[~!%^&*+=|?:<>/-]', Operator), (words(('as', 'is', '=>', '..', '...')), Operator), (r'[()\[\],.{};]+', Punctuation), (words(('abort', 'align', 'alloc', 'append', 'assert', 'case', 'const', 'def', 'defer', 'delete', 'else', 'enum', 'export', 'fn', 'for', 'free', 'if', 'let', 'len', 'match', 'offset', 'return', 'static', 'struct', 'switch', 'type', 'union', 'yield', 'vastart', 'vaarg', 'vaend'), suffix=r'\b'), Keyword), (r'(bool|int|uint|uintptr|u8|u16|u32|u64|i8|i16|i32|i64|f32|f64|null|done|never|void|nullable|rune|size|valist)\b', Keyword.Type), (r'(true|false|null)\b', Name.Builtin), (r'[a-zA-Z_]\w*', Name), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\', String), # stray backslash ], 'root': [ include('whitespace'), include('statements'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867""" pygments.lexers.haskell ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Haskell 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, bygroups, do_insertions, \ default, include, inherit, line_refrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespacefrom pygments import unistring as uni
__all__ = ['HaskellLexer', 'HspecLexer', 'IdrisLexer', 'AgdaLexer', 'CryptolLexer', 'LiterateHaskellLexer', 'LiterateIdrisLexer', 'LiterateAgdaLexer', 'LiterateCryptolLexer', 'KokaLexer']
class HaskellLexer(RegexLexer): """ A Haskell lexer based on the lexemes defined in the Haskell 98 Report. """ name = 'Haskell' url = 'https://www.haskell.org/' aliases = ['haskell', 'hs'] filenames = ['*.hs'] mimetypes = ['text/x-haskell'] version_added = '0.8'
reserved = ('case', 'class', 'data', 'default', 'deriving', 'do', 'else', 'family', 'if', 'in', 'infix[lr]?', 'instance', 'let', 'newtype', 'of', 'then', 'type', 'where', '_') ascii = ('NUL', 'SOH', '[SE]TX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT', 'FF', 'CR', 'S[OI]', 'DLE', 'DC[1-4]', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', '[FGRU]S', 'SP', 'DEL')
tokens = { 'root': [ # Whitespace: (r'\s+', Whitespace), # (r'--\s*|.*$', Comment.Doc), (r'--(?![!#$%&*+./<=>?@^|_~:\\]).*?$', Comment.Single), (r'\{-', Comment.Multiline, 'comment'), # Lexemes: # Identifiers (r'\bimport\b', Keyword.Reserved, 'import'), (r'\bmodule\b', Keyword.Reserved, 'module'), (r'\berror\b', Name.Exception), (r'\b({})(?!\')\b'.format('|'.join(reserved)), Keyword.Reserved), (r"'[^\\]'", String.Char), # character literal (r"'\\.'", String.Char), # escape character literal (e.g. '\n') (r'^[_' + uni.Ll + r'][\w\']*', Name.Function), (r"'?[_" + uni.Ll + r"][\w']*", Name), (r"('')?[" + uni.Lu + r"][\w\']*", Keyword.Type), (r"(')[" + uni.Lu + r"][\w\']*", Keyword.Type), (r"(')\[[^\]]*\]", Keyword.Type), # tuples and lists get special treatment in GHC (r"(')\([^)]*\)", Keyword.Type), # .. (r"(')[:!#$%&*+.\\/<=>?@^|~-]+", Keyword.Type), # promoted type operators # Operators (r'\\(?![:!#$%&*+.\\/<=>?@^|~-]+)', Name.Function), # lambda operator (r'(<-|::|->|=>|=)(?![:!#$%&*+.\\/<=>?@^|~-]+)', Operator.Word), # specials (r':[:!#$%&*+.\\/<=>?@^|~-]*', Keyword.Type), # Constructor operators (r'[:!#$%&*+.\\/<=>?@^|~-]+', Operator), # Other operators # Numbers (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*_*[pP][+-]?\d(_*\d)*', Number.Float), (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*\.[\da-fA-F](_*[\da-fA-F])*' r'(_*[pP][+-]?\d(_*\d)*)?', Number.Float), (r'\d(_*\d)*_*[eE][+-]?\d(_*\d)*', Number.Float), (r'\d(_*\d)*\.\d(_*\d)*(_*[eE][+-]?\d(_*\d)*)?', Number.Float), (r'0[bB]_*[01](_*[01])*', Number.Bin), (r'0[oO]_*[0-7](_*[0-7])*', Number.Oct), (r'0[xX]_*[\da-fA-F](_*[\da-fA-F])*', Number.Hex), (r'\d(_*\d)*', Number.Integer), # Character/String Literals (r"'", String.Char, 'character'), (r'"', String, 'string'), # Special (r'\[\]', Keyword.Type), (r'\(\)', Name.Builtin), (r'[][(),;`{}]', Punctuation), ], 'import': [ # Import statements (r'\s+', Whitespace), (r'"', String, 'string'), # after "funclist" state (r'\)', Punctuation, '#pop'), (r'qualified\b', Keyword), # import X as Y (r'([' + uni.Lu + r'][\w.]*)(\s+)(as)(\s+)([' + uni.Lu + r'][\w.]*)', bygroups(Name.Namespace, Whitespace, Keyword, Whitespace, Name), '#pop'), # import X hiding (functions) (r'([' + uni.Lu + r'][\w.]*)(\s+)(hiding)(\s+)(\()', bygroups(Name.Namespace, Whitespace, Keyword, Whitespace, Punctuation), 'funclist'), # import X (functions) (r'([' + uni.Lu + r'][\w.]*)(\s+)(\()', bygroups(Name.Namespace, Whitespace, Punctuation), 'funclist'), # import X (r'[\w.]+', Name.Namespace, '#pop'), ], 'module': [ (r'\s+', Whitespace), (r'([' + uni.Lu + r'][\w.]*)(\s+)(\()', bygroups(Name.Namespace, Whitespace, Punctuation), 'funclist'), (r'[' + uni.Lu + r'][\w.]*', Name.Namespace, '#pop'), ], 'funclist': [ (r'\s+', Whitespace), (r'[' + uni.Lu + r']\w*', Keyword.Type), (r'(_[\w\']+|[' + uni.Ll + r'][\w\']*)', Name.Function), (r'--(?![!#$%&*+./<=>?@^|_~:\\]).*?$', Comment.Single), (r'\{-', Comment.Multiline, 'comment'), (r',', Punctuation), (r'[:!#$%&*+.\\/<=>?@^|~-]+', Operator), # (HACK, but it makes sense to push two instances, believe me) (r'\(', Punctuation, ('funclist', 'funclist')), (r'\)', Punctuation, '#pop:2'), ], # NOTE: the next four states are shared in the AgdaLexer; make sure # any change is compatible with Agda as well or copy over and change 'comment': [ # Multiline Comments (r'[^-{}]+', Comment.Multiline), (r'\{-', Comment.Multiline, '#push'), (r'-\}', Comment.Multiline, '#pop'), (r'[-{}]', Comment.Multiline), ], 'character': [ # Allows multi-chars, incorrectly. (r"[^\\']'", String.Char, '#pop'), (r"\\", String.Escape, 'escape'), ("'", String.Char, '#pop'), ], 'string': [ (r'[^\\"]+', String), (r"\\", String.Escape, 'escape'), ('"', String, '#pop'), ], 'escape': [ (r'[abfnrtv"\'&\\]', String.Escape, '#pop'), (r'\^[][' + uni.Lu + r'@^_]', String.Escape, '#pop'), ('|'.join(ascii), String.Escape, '#pop'), (r'o[0-7]+', String.Escape, '#pop'), (r'x[\da-fA-F]+', String.Escape, '#pop'), (r'\d+', String.Escape, '#pop'), (r'(\s+)(\\)', bygroups(Whitespace, String.Escape), '#pop'), ], }
class HspecLexer(HaskellLexer): """ A Haskell lexer with support for Hspec constructs. """
name = 'Hspec' aliases = ['hspec'] filenames = ['*Spec.hs'] mimetypes = [] version_added = '2.4'
tokens = { 'root': [ (r'(it)(\s*)("[^"]*")', bygroups(Text, Whitespace, String.Doc)), (r'(describe)(\s*)("[^"]*")', bygroups(Text, Whitespace, String.Doc)), (r'(context)(\s*)("[^"]*")', bygroups(Text, Whitespace, String.Doc)), inherit, ], }
class IdrisLexer(RegexLexer): """ A lexer for the dependently typed programming language Idris.
Based on the Haskell and Agda Lexer. """ name = 'Idris' url = 'https://www.idris-lang.org/' aliases = ['idris', 'idr'] filenames = ['*.idr'] mimetypes = ['text/x-idris'] version_added = '2.0'
reserved = ('case', 'class', 'data', 'default', 'using', 'do', 'else', 'if', 'in', 'infix[lr]?', 'instance', 'rewrite', 'auto', 'namespace', 'codata', 'mutual', 'private', 'public', 'abstract', 'total', 'partial', 'interface', 'implementation', 'export', 'covering', 'constructor', 'let', 'proof', 'of', 'then', 'static', 'where', '_', 'with', 'pattern', 'term', 'syntax', 'prefix', 'postulate', 'parameters', 'record', 'dsl', 'impossible', 'implicit', 'tactics', 'intros', 'intro', 'compute', 'refine', 'exact', 'trivial')
ascii = ('NUL', 'SOH', '[SE]TX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT', 'FF', 'CR', 'S[OI]', 'DLE', 'DC[1-4]', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', '[FGRU]S', 'SP', 'DEL')
directives = ('lib', 'link', 'flag', 'include', 'hide', 'freeze', 'access', 'default', 'logging', 'dynamic', 'name', 'error_handlers', 'language')
tokens = { 'root': [ # Comments (r'^(\s*)(%({}))'.format('|'.join(directives)), bygroups(Whitespace, Keyword.Reserved)), (r'(\s*)(--(?![!#$%&*+./<=>?@^|_~:\\]).*?)$', bygroups(Whitespace, Comment.Single)), (r'(\s*)(\|{3}.*?)$', bygroups(Whitespace, Comment.Single)), (r'(\s*)(\{-)', bygroups(Whitespace, Comment.Multiline), 'comment'), # Declaration (r'^(\s*)([^\s(){}]+)(\s*)(:)(\s*)', bygroups(Whitespace, Name.Function, Whitespace, Operator.Word, Whitespace)), # Identifiers (r'\b({})(?!\')\b'.format('|'.join(reserved)), Keyword.Reserved), (r'(import|module)(\s+)', bygroups(Keyword.Reserved, Whitespace), 'module'), (r"('')?[A-Z][\w\']*", Keyword.Type), (r'[a-z][\w\']*', Text), # Special Symbols (r'(<-|::|->|=>|=)', Operator.Word), # specials (r'([(){}\[\]:!#$%&*+.\\/<=>?@^|~-]+)', Operator.Word), # specials # Numbers (r'\d+[eE][+-]?\d+', Number.Float), (r'\d+\.\d+([eE][+-]?\d+)?', Number.Float), (r'0[xX][\da-fA-F]+', Number.Hex), (r'\d+', Number.Integer), # Strings (r"'", String.Char, 'character'), (r'"', String, 'string'), (r'[^\s(){}]+', Text), (r'\s+?', Whitespace), # Whitespace ], 'module': [ (r'\s+', Whitespace), (r'([A-Z][\w.]*)(\s+)(\()', bygroups(Name.Namespace, Whitespace, Punctuation), 'funclist'), (r'[A-Z][\w.]*', Name.Namespace, '#pop'), ], 'funclist': [ (r'\s+', Whitespace), (r'[A-Z]\w*', Keyword.Type), (r'(_[\w\']+|[a-z][\w\']*)', Name.Function), (r'--.*$', Comment.Single), (r'\{-', Comment.Multiline, 'comment'), (r',', Punctuation), (r'[:!#$%&*+.\\/<=>?@^|~-]+', Operator), # (HACK, but it makes sense to push two instances, believe me) (r'\(', Punctuation, ('funclist', 'funclist')), (r'\)', Punctuation, '#pop:2'), ], # NOTE: the next four states are shared in the AgdaLexer; make sure # any change is compatible with Agda as well or copy over and change 'comment': [ # Multiline Comments (r'[^-{}]+', Comment.Multiline), (r'\{-', Comment.Multiline, '#push'), (r'-\}', Comment.Multiline, '#pop'), (r'[-{}]', Comment.Multiline), ], 'character': [ # Allows multi-chars, incorrectly. (r"[^\\']", String.Char), (r"\\", String.Escape, 'escape'), ("'", String.Char, '#pop'), ], 'string': [ (r'[^\\"]+', String), (r"\\", String.Escape, 'escape'), ('"', String, '#pop'), ], 'escape': [ (r'[abfnrtv"\'&\\]', String.Escape, '#pop'), (r'\^[][A-Z@^_]', String.Escape, '#pop'), ('|'.join(ascii), String.Escape, '#pop'), (r'o[0-7]+', String.Escape, '#pop'), (r'x[\da-fA-F]+', String.Escape, '#pop'), (r'\d+', String.Escape, '#pop'), (r'(\s+)(\\)', bygroups(Whitespace, String.Escape), '#pop') ], }
class AgdaLexer(RegexLexer): """ For the Agda dependently typed functional programming language and proof assistant. """
name = 'Agda' url = 'http://wiki.portal.chalmers.se/agda/pmwiki.php' aliases = ['agda'] filenames = ['*.agda'] mimetypes = ['text/x-agda'] version_added = '2.0'
reserved = ( 'abstract', 'codata', 'coinductive', 'constructor', 'data', 'do', 'eta-equality', 'field', 'forall', 'hiding', 'in', 'inductive', 'infix', 'infixl', 'infixr', 'instance', 'interleaved', 'let', 'macro', 'mutual', 'no-eta-equality', 'opaque', 'open', 'overlap', 'pattern', 'postulate', 'primitive', 'private', 'quote', 'quoteTerm', 'record', 'renaming', 'rewrite', 'syntax', 'tactic', 'unfolding', 'unquote', 'unquoteDecl', 'unquoteDef', 'using', 'variable', 'where', 'with', )
tokens = { 'root': [ # Declaration (r'^(\s*)([^\s(){}]+)(\s*)(:)(\s*)', bygroups(Whitespace, Name.Function, Whitespace, Operator.Word, Whitespace)), # Comments (r'--(?![!#$%&*+./<=>?@^|_~:\\]).*?$', Comment.Single), (r'\{-', Comment.Multiline, 'comment'), # Holes (r'\{!', Comment.Directive, 'hole'), # Lexemes: # Identifiers (r'\b({})(?!\')\b'.format('|'.join(reserved)), Keyword.Reserved), (r'(import|module)(\s+)', bygroups(Keyword.Reserved, Whitespace), 'module'), (r'\b(Set|Prop)[\u2080-\u2089]*\b', Keyword.Type), # Special Symbols (r'(\(|\)|\{|\})', Operator), (r'(\.{1,3}|\||\u03BB|\u2200|\u2192|:|=|->)', Operator.Word), # Numbers (r'\d+[eE][+-]?\d+', Number.Float), (r'\d+\.\d+([eE][+-]?\d+)?', Number.Float), (r'0[xX][\da-fA-F]+', Number.Hex), (r'\d+', Number.Integer), # Strings (r"'", String.Char, 'character'), (r'"', String, 'string'), (r'[^\s(){}]+', Text), (r'\s+?', Whitespace), # Whitespace ], 'hole': [ # Holes (r'[^!{}]+', Comment.Directive), (r'\{!', Comment.Directive, '#push'), (r'!\}', Comment.Directive, '#pop'), (r'[!{}]', Comment.Directive), ], 'module': [ (r'\{-', Comment.Multiline, 'comment'), (r'[a-zA-Z][\w.\']*', Name, '#pop'), (r'[\W0-9_]+', Text) ], 'comment': HaskellLexer.tokens['comment'], 'character': HaskellLexer.tokens['character'], 'string': HaskellLexer.tokens['string'], 'escape': HaskellLexer.tokens['escape'] }
class CryptolLexer(RegexLexer): """ FIXME: A Cryptol2 lexer based on the lexemes defined in the Haskell 98 Report. """ name = 'Cryptol' aliases = ['cryptol', 'cry'] filenames = ['*.cry'] mimetypes = ['text/x-cryptol'] url = 'https://www.cryptol.net' version_added = '2.0'
reserved = ('Arith', 'Bit', 'Cmp', 'False', 'Inf', 'True', 'else', 'export', 'extern', 'fin', 'if', 'import', 'inf', 'lg2', 'max', 'min', 'module', 'newtype', 'pragma', 'property', 'then', 'type', 'where', 'width') ascii = ('NUL', 'SOH', '[SE]TX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT', 'FF', 'CR', 'S[OI]', 'DLE', 'DC[1-4]', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', '[FGRU]S', 'SP', 'DEL')
tokens = { 'root': [ # Whitespace: (r'\s+', Whitespace), # (r'--\s*|.*$', Comment.Doc), (r'//.*$', Comment.Single), (r'/\*', Comment.Multiline, 'comment'), # Lexemes: # Identifiers (r'\bimport\b', Keyword.Reserved, 'import'), (r'\bmodule\b', Keyword.Reserved, 'module'), (r'\berror\b', Name.Exception), (r'\b({})(?!\')\b'.format('|'.join(reserved)), Keyword.Reserved), (r'^[_a-z][\w\']*', Name.Function), (r"'?[_a-z][\w']*", Name), (r"('')?[A-Z][\w\']*", Keyword.Type), # Operators (r'\\(?![:!#$%&*+.\\/<=>?@^|~-]+)', Name.Function), # lambda operator (r'(<-|::|->|=>|=)(?![:!#$%&*+.\\/<=>?@^|~-]+)', Operator.Word), # specials (r':[:!#$%&*+.\\/<=>?@^|~-]*', Keyword.Type), # Constructor operators (r'[:!#$%&*+.\\/<=>?@^|~-]+', Operator), # Other operators # Numbers (r'\d+[eE][+-]?\d+', Number.Float), (r'\d+\.\d+([eE][+-]?\d+)?', Number.Float), (r'0[oO][0-7]+', Number.Oct), (r'0[xX][\da-fA-F]+', Number.Hex), (r'\d+', Number.Integer), # Character/String Literals (r"'", String.Char, 'character'), (r'"', String, 'string'), # Special (r'\[\]', Keyword.Type), (r'\(\)', Name.Builtin), (r'[][(),;`{}]', Punctuation), ], 'import': [ # Import statements (r'\s+', Whitespace), (r'"', String, 'string'), # after "funclist" state (r'\)', Punctuation, '#pop'), (r'qualified\b', Keyword), # import X as Y (r'([A-Z][\w.]*)(\s+)(as)(\s+)([A-Z][\w.]*)', bygroups(Name.Namespace, Whitespace, Keyword, Whitespace, Name), '#pop'), # import X hiding (functions) (r'([A-Z][\w.]*)(\s+)(hiding)(\s+)(\()', bygroups(Name.Namespace, Whitespace, Keyword, Whitespace, Punctuation), 'funclist'), # import X (functions) (r'([A-Z][\w.]*)(\s+)(\()', bygroups(Name.Namespace, Whitespace, Punctuation), 'funclist'), # import X (r'[\w.]+', Name.Namespace, '#pop'), ], 'module': [ (r'\s+', Whitespace), (r'([A-Z][\w.]*)(\s+)(\()', bygroups(Name.Namespace, Whitespace, Punctuation), 'funclist'), (r'[A-Z][\w.]*', Name.Namespace, '#pop'), ], 'funclist': [ (r'\s+', Whitespace), (r'[A-Z]\w*', Keyword.Type), (r'(_[\w\']+|[a-z][\w\']*)', Name.Function), # TODO: these don't match the comments in docs, remove. # (r'--(?![!#$%&*+./<=>?@^|_~:\\]).*?$', Comment.Single), # (r'{-', Comment.Multiline, 'comment'), (r',', Punctuation), (r'[:!#$%&*+.\\/<=>?@^|~-]+', Operator), # (HACK, but it makes sense to push two instances, believe me) (r'\(', Punctuation, ('funclist', 'funclist')), (r'\)', Punctuation, '#pop:2'), ], 'comment': [ # Multiline Comments (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'character': [ # Allows multi-chars, incorrectly. (r"[^\\']'", String.Char, '#pop'), (r"\\", String.Escape, 'escape'), ("'", String.Char, '#pop'), ], 'string': [ (r'[^\\"]+', String), (r"\\", String.Escape, 'escape'), ('"', String, '#pop'), ], 'escape': [ (r'[abfnrtv"\'&\\]', String.Escape, '#pop'), (r'\^[][A-Z@^_]', String.Escape, '#pop'), ('|'.join(ascii), String.Escape, '#pop'), (r'o[0-7]+', String.Escape, '#pop'), (r'x[\da-fA-F]+', String.Escape, '#pop'), (r'\d+', String.Escape, '#pop'), (r'(\s+)(\\)', bygroups(Whitespace, String.Escape), '#pop'), ], }
EXTRA_KEYWORDS = {'join', 'split', 'reverse', 'transpose', 'width', 'length', 'tail', '<<', '>>', '<<<', '>>>', 'const', 'reg', 'par', 'seq', 'ASSERT', 'undefined', 'error', 'trace'}
def get_tokens_unprocessed(self, text): stack = ['root'] for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text, stack): if token is Name and value in self.EXTRA_KEYWORDS: yield index, Name.Builtin, value else: yield index, token, value
class LiterateLexer(Lexer): """ Base class for lexers of literate file formats based on LaTeX or Bird-style (prefixing each code line with ">").
Additional options accepted:
`litstyle` If given, must be ``"bird"`` or ``"latex"``. If not given, the style is autodetected: if the first non-whitespace character in the source is a backslash or percent character, LaTeX is assumed, else Bird. """
bird_re = re.compile(r'(>[ \t]*)(.*\n)')
def __init__(self, baselexer, **options): self.baselexer = baselexer Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): style = self.options.get('litstyle') if style is None: style = (text.lstrip()[0:1] in '%\\') and 'latex' or 'bird'
code = '' insertions = [] if style == 'bird': # bird-style for match in line_re.finditer(text): line = match.group() m = self.bird_re.match(line) if m: insertions.append((len(code), [(0, Comment.Special, m.group(1))])) code += m.group(2) else: insertions.append((len(code), [(0, Text, line)])) else: # latex-style from pygments.lexers.markup import TexLexer lxlexer = TexLexer(**self.options) codelines = 0 latex = '' for match in line_re.finditer(text): line = match.group() if codelines: if line.lstrip().startswith('\\end{code}'): codelines = 0 latex += line else: code += line elif line.lstrip().startswith('\\begin{code}'): codelines = 1 latex += line insertions.append((len(code), list(lxlexer.get_tokens_unprocessed(latex)))) latex = '' else: latex += line insertions.append((len(code), list(lxlexer.get_tokens_unprocessed(latex)))) yield from do_insertions(insertions, self.baselexer.get_tokens_unprocessed(code))
class LiterateHaskellLexer(LiterateLexer): """ For Literate Haskell (Bird-style or LaTeX) source.
Additional options accepted:
`litstyle` If given, must be ``"bird"`` or ``"latex"``. If not given, the style is autodetected: if the first non-whitespace character in the source is a backslash or percent character, LaTeX is assumed, else Bird. """ name = 'Literate Haskell' aliases = ['literate-haskell', 'lhaskell', 'lhs'] filenames = ['*.lhs'] mimetypes = ['text/x-literate-haskell'] url = 'https://wiki.haskell.org/Literate_programming' version_added = '0.9'
def __init__(self, **options): hslexer = HaskellLexer(**options) LiterateLexer.__init__(self, hslexer, **options)
class LiterateIdrisLexer(LiterateLexer): """ For Literate Idris (Bird-style or LaTeX) source.
Additional options accepted:
`litstyle` If given, must be ``"bird"`` or ``"latex"``. If not given, the style is autodetected: if the first non-whitespace character in the source is a backslash or percent character, LaTeX is assumed, else Bird. """ name = 'Literate Idris' aliases = ['literate-idris', 'lidris', 'lidr'] filenames = ['*.lidr'] mimetypes = ['text/x-literate-idris'] url = 'https://idris2.readthedocs.io/en/latest/reference/literate.html' version_added = '2.0'
def __init__(self, **options): hslexer = IdrisLexer(**options) LiterateLexer.__init__(self, hslexer, **options)
class LiterateAgdaLexer(LiterateLexer): """ For Literate Agda source.
Additional options accepted:
`litstyle` If given, must be ``"bird"`` or ``"latex"``. If not given, the style is autodetected: if the first non-whitespace character in the source is a backslash or percent character, LaTeX is assumed, else Bird. """ name = 'Literate Agda' aliases = ['literate-agda', 'lagda'] filenames = ['*.lagda'] mimetypes = ['text/x-literate-agda'] url = 'https://agda.readthedocs.io/en/latest/tools/literate-programming.html' version_added = '2.0'
def __init__(self, **options): agdalexer = AgdaLexer(**options) LiterateLexer.__init__(self, agdalexer, litstyle='latex', **options)
class LiterateCryptolLexer(LiterateLexer): """ For Literate Cryptol (Bird-style or LaTeX) source.
Additional options accepted:
`litstyle` If given, must be ``"bird"`` or ``"latex"``. If not given, the style is autodetected: if the first non-whitespace character in the source is a backslash or percent character, LaTeX is assumed, else Bird. """ name = 'Literate Cryptol' aliases = ['literate-cryptol', 'lcryptol', 'lcry'] filenames = ['*.lcry'] mimetypes = ['text/x-literate-cryptol'] url = 'https://www.cryptol.net' version_added = '2.0'
def __init__(self, **options): crylexer = CryptolLexer(**options) LiterateLexer.__init__(self, crylexer, **options)
class KokaLexer(RegexLexer): """ Lexer for the Koka language. """
name = 'Koka' url = 'https://koka-lang.github.io/koka/doc/index.html' aliases = ['koka'] filenames = ['*.kk', '*.kki'] mimetypes = ['text/x-koka'] version_added = '1.6'
keywords = [ 'infix', 'infixr', 'infixl', 'type', 'cotype', 'rectype', 'alias', 'struct', 'con', 'fun', 'function', 'val', 'var', 'external', 'if', 'then', 'else', 'elif', 'return', 'match', 'private', 'public', 'private', 'module', 'import', 'as', 'include', 'inline', 'rec', 'try', 'yield', 'enum', 'interface', 'instance', ]
# keywords that are followed by a type typeStartKeywords = [ 'type', 'cotype', 'rectype', 'alias', 'struct', 'enum', ]
# keywords valid in a type typekeywords = [ 'forall', 'exists', 'some', 'with', ]
# builtin names and special names builtin = [ 'for', 'while', 'repeat', 'foreach', 'foreach-indexed', 'error', 'catch', 'finally', 'cs', 'js', 'file', 'ref', 'assigned', ]
# symbols that can be in an operator symbols = r'[$%&*+@!/\\^~=.:\-?|<>]+'
# symbol boundary: an operator keyword should not be followed by any of these sboundary = '(?!' + symbols + ')'
# name boundary: a keyword should not be followed by any of these boundary = r'(?![\w/])'
# koka token abstractions tokenType = Name.Attribute tokenTypeDef = Name.Class tokenConstructor = Generic.Emph
# main lexer tokens = { 'root': [ include('whitespace'),
# go into type mode (r'::?' + sboundary, tokenType, 'type'), (r'(alias)(\s+)([a-z]\w*)?', bygroups(Keyword, Whitespace, tokenTypeDef), 'alias-type'), (r'(struct)(\s+)([a-z]\w*)?', bygroups(Keyword, Whitespace, tokenTypeDef), 'struct-type'), ((r'({})'.format('|'.join(typeStartKeywords))) + r'(\s+)([a-z]\w*)?', bygroups(Keyword, Whitespace, tokenTypeDef), 'type'),
# special sequences of tokens (we use ?: for non-capturing group as # required by 'bygroups') (r'(module)(\s+)(interface(?=\s))?(\s+)?((?:[a-z]\w*/)*[a-z]\w*)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Namespace)), (r'(import)(\s+)((?:[a-z]\w*/)*[a-z]\w*)' r'(?:(\s*)(=)(\s*)(qualified)?(\s*)' r'((?:[a-z]\w*/)*[a-z]\w*))?', bygroups(Keyword, Whitespace, Name.Namespace, Whitespace, Keyword, Whitespace, Keyword, Whitespace, Name.Namespace)),
(r'^(public|private)?(\s+)?(function|fun|val)' r'(\s+)([a-z]\w*|\((?:' + symbols + r'|/)\))', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function)), (r'^(?:(public|private)(?=\s+external))?((?<!^)\s+)?(external)(\s+)(inline(?=\s))?(\s+)?' r'([a-z]\w*|\((?:' + symbols + r'|/)\))', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword, Whitespace, Name.Function)),
# keywords (r'({})'.format('|'.join(typekeywords)) + boundary, Keyword.Type), (r'({})'.format('|'.join(keywords)) + boundary, Keyword), (r'({})'.format('|'.join(builtin)) + boundary, Keyword.Pseudo), (r'::?|:=|\->|[=.]' + sboundary, Keyword),
# names (r'((?:[a-z]\w*/)*)([A-Z]\w*)', bygroups(Name.Namespace, tokenConstructor)), (r'((?:[a-z]\w*/)*)([a-z]\w*)', bygroups(Name.Namespace, Name)), (r'((?:[a-z]\w*/)*)(\((?:' + symbols + r'|/)\))', bygroups(Name.Namespace, Name)), (r'_\w*', Name.Variable),
# literal string (r'@"', String.Double, 'litstring'),
# operators (symbols + "|/(?![*/])", Operator), (r'`', Operator), (r'[{}()\[\];,]', Punctuation),
# literals. No check for literal characters with len > 1 (r'[0-9]+\.[0-9]+([eE][\-+]?[0-9]+)?', Number.Float), (r'0[xX][0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer),
(r"'", String.Char, 'char'), (r'"', String.Double, 'string'), ],
# type started by alias 'alias-type': [ (r'=', Keyword), include('type') ],
# type started by struct 'struct-type': [ (r'(?=\((?!,*\)))', Punctuation, '#pop'), include('type') ],
# type started by colon 'type': [ (r'[(\[<]', tokenType, 'type-nested'), include('type-content') ],
# type nested in brackets: can contain parameters, comma etc. 'type-nested': [ (r'[)\]>]', tokenType, '#pop'), (r'[(\[<]', tokenType, 'type-nested'), (r',', tokenType), (r'([a-z]\w*)(\s*)(:)(?!:)', bygroups(Name, Whitespace, tokenType)), # parameter name include('type-content') ],
# shared contents of a type 'type-content': [ include('whitespace'),
# keywords (r'({})'.format('|'.join(typekeywords)) + boundary, Keyword), (r'(?=(({})'.format('|'.join(keywords)) + boundary + '))', Keyword, '#pop'), # need to match because names overlap...
# kinds (r'[EPHVX]' + boundary, tokenType),
# type names (r'[a-z][0-9]*(?![\w/])', tokenType), (r'_\w*', tokenType.Variable), # Generic.Emph (r'((?:[a-z]\w*/)*)([A-Z]\w*)', bygroups(Name.Namespace, tokenType)), (r'((?:[a-z]\w*/)*)([a-z]\w+)', bygroups(Name.Namespace, tokenType)),
# type keyword operators (r'::|->|[.:|]', tokenType),
# catchall default('#pop') ],
# comments and literals 'whitespace': [ (r'(\n\s*)(#.*)$', bygroups(Whitespace, Comment.Preproc)), (r'\s+', Whitespace), (r'/\*', Comment.Multiline, 'comment'), (r'//.*$', Comment.Single) ], 'comment': [ (r'[^/*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'litstring': [ (r'[^"]+', String.Double), (r'""', String.Escape), (r'"', String.Double, '#pop'), ], 'string': [ (r'[^\\"\n]+', String.Double), include('escape-sequence'), (r'["\n]', String.Double, '#pop'), ], 'char': [ (r'[^\\\'\n]+', String.Char), include('escape-sequence'), (r'[\'\n]', String.Char, '#pop'), ], 'escape-sequence': [ (r'\\[nrt\\"\']', String.Escape), (r'\\x[0-9a-fA-F]{2}', String.Escape), (r'\\u[0-9a-fA-F]{4}', String.Escape), # Yes, \U literals are 6 hex digits. (r'\\U[0-9a-fA-F]{6}', String.Escape) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941""" pygments.lexers.haxe ~~~~~~~~~~~~~~~~~~~~
Lexers for Haxe and related stuff.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, RegexLexer, include, bygroups, \ defaultfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace
__all__ = ['HaxeLexer', 'HxmlLexer']
class HaxeLexer(ExtendedRegexLexer): """ For Haxe source code. """
name = 'Haxe' url = 'http://haxe.org/' aliases = ['haxe', 'hxsl', 'hx'] filenames = ['*.hx', '*.hxsl'] mimetypes = ['text/haxe', 'text/x-haxe', 'text/x-hx'] version_added = '1.3'
# keywords extracted from lexer.mll in the haxe compiler source keyword = (r'(?:function|class|static|var|if|else|while|do|for|' r'break|return|continue|extends|implements|import|' r'switch|case|default|public|private|try|untyped|' r'catch|new|this|throw|extern|enum|in|interface|' r'cast|override|dynamic|typedef|package|' r'inline|using|null|true|false|abstract)\b')
# idtype in lexer.mll typeid = r'_*[A-Z]\w*'
# combined ident and dollar and idtype ident = r'(?:_*[a-z]\w*|_+[0-9]\w*|' + typeid + r'|_+|\$\w+)'
binop = (r'(?:%=|&=|\|=|\^=|\+=|\-=|\*=|/=|<<=|>\s*>\s*=|>\s*>\s*>\s*=|==|' r'!=|<=|>\s*=|&&|\|\||<<|>>>|>\s*>|\.\.\.|<|>|%|&|\||\^|\+|\*|' r'/|\-|=>|=)')
# ident except keywords ident_no_keyword = r'(?!' + keyword + ')' + ident
flags = re.DOTALL | re.MULTILINE
preproc_stack = []
def preproc_callback(self, match, ctx): proc = match.group(2)
if proc == 'if': # store the current stack self.preproc_stack.append(ctx.stack[:]) elif proc in ['else', 'elseif']: # restore the stack back to right before #if if self.preproc_stack: ctx.stack = self.preproc_stack[-1][:] elif proc == 'end': # remove the saved stack of previous #if if self.preproc_stack: self.preproc_stack.pop()
# #if and #elseif should follow by an expr if proc in ['if', 'elseif']: ctx.stack.append('preproc-expr')
# #error can be optionally follow by the error msg if proc in ['error']: ctx.stack.append('preproc-error')
yield match.start(), Comment.Preproc, '#' + proc ctx.pos = match.end()
tokens = { 'root': [ include('spaces'), include('meta'), (r'(?:package)\b', Keyword.Namespace, ('semicolon', 'package')), (r'(?:import)\b', Keyword.Namespace, ('semicolon', 'import')), (r'(?:using)\b', Keyword.Namespace, ('semicolon', 'using')), (r'(?:extern|private)\b', Keyword.Declaration), (r'(?:abstract)\b', Keyword.Declaration, 'abstract'), (r'(?:class|interface)\b', Keyword.Declaration, 'class'), (r'(?:enum)\b', Keyword.Declaration, 'enum'), (r'(?:typedef)\b', Keyword.Declaration, 'typedef'),
# top-level expression # although it is not supported in haxe, but it is common to write # expression in web pages the positive lookahead here is to prevent # an infinite loop at the EOF (r'(?=.)', Text, 'expr-statement'), ],
# space/tab/comment/preproc 'spaces': [ (r'\s+', Whitespace), (r'//[^\n\r]*', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'(#)(if|elseif|else|end|error)\b', preproc_callback), ],
'string-single-interpol': [ (r'\$\{', String.Interpol, ('string-interpol-close', 'expr')), (r'\$\$', String.Escape), (r'\$(?=' + ident + ')', String.Interpol, 'ident'), include('string-single'), ],
'string-single': [ (r"'", String.Single, '#pop'), (r'\\.', String.Escape), (r'.', String.Single), ],
'string-double': [ (r'"', String.Double, '#pop'), (r'\\.', String.Escape), (r'.', String.Double), ],
'string-interpol-close': [ (r'\$'+ident, String.Interpol), (r'\}', String.Interpol, '#pop'), ],
'package': [ include('spaces'), (ident, Name.Namespace), (r'\.', Punctuation, 'import-ident'), default('#pop'), ],
'import': [ include('spaces'), (ident, Name.Namespace), (r'\*', Keyword), # wildcard import (r'\.', Punctuation, 'import-ident'), (r'in', Keyword.Namespace, 'ident'), default('#pop'), ],
'import-ident': [ include('spaces'), (r'\*', Keyword, '#pop'), # wildcard import (ident, Name.Namespace, '#pop'), ],
'using': [ include('spaces'), (ident, Name.Namespace), (r'\.', Punctuation, 'import-ident'), default('#pop'), ],
'preproc-error': [ (r'\s+', Whitespace), (r"'", String.Single, ('#pop', 'string-single')), (r'"', String.Double, ('#pop', 'string-double')), default('#pop'), ],
'preproc-expr': [ (r'\s+', Whitespace), (r'\!', Comment.Preproc), (r'\(', Comment.Preproc, ('#pop', 'preproc-parenthesis')),
(ident, Comment.Preproc, '#pop'),
# Float (r'\.[0-9]+', Number.Float), (r'[0-9]+[eE][+\-]?[0-9]+', Number.Float), (r'[0-9]+\.[0-9]*[eE][+\-]?[0-9]+', Number.Float), (r'[0-9]+\.[0-9]+', Number.Float), (r'[0-9]+\.(?!' + ident + r'|\.\.)', Number.Float),
# Int (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer),
# String (r"'", String.Single, ('#pop', 'string-single')), (r'"', String.Double, ('#pop', 'string-double')), ],
'preproc-parenthesis': [ (r'\s+', Whitespace), (r'\)', Comment.Preproc, '#pop'), default('preproc-expr-in-parenthesis'), ],
'preproc-expr-chain': [ (r'\s+', Whitespace), (binop, Comment.Preproc, ('#pop', 'preproc-expr-in-parenthesis')), default('#pop'), ],
# same as 'preproc-expr' but able to chain 'preproc-expr-chain' 'preproc-expr-in-parenthesis': [ (r'\s+', Whitespace), (r'\!', Comment.Preproc), (r'\(', Comment.Preproc, ('#pop', 'preproc-expr-chain', 'preproc-parenthesis')),
(ident, Comment.Preproc, ('#pop', 'preproc-expr-chain')),
# Float (r'\.[0-9]+', Number.Float, ('#pop', 'preproc-expr-chain')), (r'[0-9]+[eE][+\-]?[0-9]+', Number.Float, ('#pop', 'preproc-expr-chain')), (r'[0-9]+\.[0-9]*[eE][+\-]?[0-9]+', Number.Float, ('#pop', 'preproc-expr-chain')), (r'[0-9]+\.[0-9]+', Number.Float, ('#pop', 'preproc-expr-chain')), (r'[0-9]+\.(?!' + ident + r'|\.\.)', Number.Float, ('#pop', 'preproc-expr-chain')),
# Int (r'0x[0-9a-fA-F]+', Number.Hex, ('#pop', 'preproc-expr-chain')), (r'[0-9]+', Number.Integer, ('#pop', 'preproc-expr-chain')),
# String (r"'", String.Single, ('#pop', 'preproc-expr-chain', 'string-single')), (r'"', String.Double, ('#pop', 'preproc-expr-chain', 'string-double')), ],
'abstract': [ include('spaces'), default(('#pop', 'abstract-body', 'abstract-relation', 'abstract-opaque', 'type-param-constraint', 'type-name')), ],
'abstract-body': [ include('spaces'), (r'\{', Punctuation, ('#pop', 'class-body')), ],
'abstract-opaque': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'parenthesis-close', 'type')), default('#pop'), ],
'abstract-relation': [ include('spaces'), (r'(?:to|from)', Keyword.Declaration, 'type'), (r',', Punctuation), default('#pop'), ],
'meta': [ include('spaces'), (r'@', Name.Decorator, ('meta-body', 'meta-ident', 'meta-colon')), ],
# optional colon 'meta-colon': [ include('spaces'), (r':', Name.Decorator, '#pop'), default('#pop'), ],
# same as 'ident' but set token as Name.Decorator instead of Name 'meta-ident': [ include('spaces'), (ident, Name.Decorator, '#pop'), ],
'meta-body': [ include('spaces'), (r'\(', Name.Decorator, ('#pop', 'meta-call')), default('#pop'), ],
'meta-call': [ include('spaces'), (r'\)', Name.Decorator, '#pop'), default(('#pop', 'meta-call-sep', 'expr')), ],
'meta-call-sep': [ include('spaces'), (r'\)', Name.Decorator, '#pop'), (r',', Punctuation, ('#pop', 'meta-call')), ],
'typedef': [ include('spaces'), default(('#pop', 'typedef-body', 'type-param-constraint', 'type-name')), ],
'typedef-body': [ include('spaces'), (r'=', Operator, ('#pop', 'optional-semicolon', 'type')), ],
'enum': [ include('spaces'), default(('#pop', 'enum-body', 'bracket-open', 'type-param-constraint', 'type-name')), ],
'enum-body': [ include('spaces'), include('meta'), (r'\}', Punctuation, '#pop'), (ident_no_keyword, Name, ('enum-member', 'type-param-constraint')), ],
'enum-member': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'semicolon', 'flag', 'function-param')), default(('#pop', 'semicolon', 'flag')), ],
'class': [ include('spaces'), default(('#pop', 'class-body', 'bracket-open', 'extends', 'type-param-constraint', 'type-name')), ],
'extends': [ include('spaces'), (r'(?:extends|implements)\b', Keyword.Declaration, 'type'), (r',', Punctuation), # the comma is made optional here, since haxe2 # requires the comma but haxe3 does not allow it default('#pop'), ],
'bracket-open': [ include('spaces'), (r'\{', Punctuation, '#pop'), ],
'bracket-close': [ include('spaces'), (r'\}', Punctuation, '#pop'), ],
'class-body': [ include('spaces'), include('meta'), (r'\}', Punctuation, '#pop'), (r'(?:static|public|private|override|dynamic|inline|macro)\b', Keyword.Declaration), default('class-member'), ],
'class-member': [ include('spaces'), (r'(var)\b', Keyword.Declaration, ('#pop', 'optional-semicolon', 'var')), (r'(function)\b', Keyword.Declaration, ('#pop', 'optional-semicolon', 'class-method')), ],
# local function, anonymous or not 'function-local': [ include('spaces'), (ident_no_keyword, Name.Function, ('#pop', 'optional-expr', 'flag', 'function-param', 'parenthesis-open', 'type-param-constraint')), default(('#pop', 'optional-expr', 'flag', 'function-param', 'parenthesis-open', 'type-param-constraint')), ],
'optional-expr': [ include('spaces'), include('expr'), default('#pop'), ],
'class-method': [ include('spaces'), (ident, Name.Function, ('#pop', 'optional-expr', 'flag', 'function-param', 'parenthesis-open', 'type-param-constraint')), ],
# function arguments 'function-param': [ include('spaces'), (r'\)', Punctuation, '#pop'), (r'\?', Punctuation), (ident_no_keyword, Name, ('#pop', 'function-param-sep', 'assign', 'flag')), ],
'function-param-sep': [ include('spaces'), (r'\)', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'function-param')), ],
'prop-get-set': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'parenthesis-close', 'prop-get-set-opt', 'comma', 'prop-get-set-opt')), default('#pop'), ],
'prop-get-set-opt': [ include('spaces'), (r'(?:default|null|never|dynamic|get|set)\b', Keyword, '#pop'), (ident_no_keyword, Text, '#pop'), # custom getter/setter ],
'expr-statement': [ include('spaces'), # makes semicolon optional here, just to avoid checking the last # one is bracket or not. default(('#pop', 'optional-semicolon', 'expr')), ],
'expr': [ include('spaces'), (r'@', Name.Decorator, ('#pop', 'optional-expr', 'meta-body', 'meta-ident', 'meta-colon')), (r'(?:\+\+|\-\-|~(?!/)|!|\-)', Operator), (r'\(', Punctuation, ('#pop', 'expr-chain', 'parenthesis')), (r'(?:static|public|private|override|dynamic|inline)\b', Keyword.Declaration), (r'(?:function)\b', Keyword.Declaration, ('#pop', 'expr-chain', 'function-local')), (r'\{', Punctuation, ('#pop', 'expr-chain', 'bracket')), (r'(?:true|false|null)\b', Keyword.Constant, ('#pop', 'expr-chain')), (r'(?:this)\b', Keyword, ('#pop', 'expr-chain')), (r'(?:cast)\b', Keyword, ('#pop', 'expr-chain', 'cast')), (r'(?:try)\b', Keyword, ('#pop', 'catch', 'expr')), (r'(?:var)\b', Keyword.Declaration, ('#pop', 'var')), (r'(?:new)\b', Keyword, ('#pop', 'expr-chain', 'new')), (r'(?:switch)\b', Keyword, ('#pop', 'switch')), (r'(?:if)\b', Keyword, ('#pop', 'if')), (r'(?:do)\b', Keyword, ('#pop', 'do')), (r'(?:while)\b', Keyword, ('#pop', 'while')), (r'(?:for)\b', Keyword, ('#pop', 'for')), (r'(?:untyped|throw)\b', Keyword), (r'(?:return)\b', Keyword, ('#pop', 'optional-expr')), (r'(?:macro)\b', Keyword, ('#pop', 'macro')), (r'(?:continue|break)\b', Keyword, '#pop'), (r'(?:\$\s*[a-z]\b|\$(?!'+ident+'))', Name, ('#pop', 'dollar')), (ident_no_keyword, Name, ('#pop', 'expr-chain')),
# Float (r'\.[0-9]+', Number.Float, ('#pop', 'expr-chain')), (r'[0-9]+[eE][+\-]?[0-9]+', Number.Float, ('#pop', 'expr-chain')), (r'[0-9]+\.[0-9]*[eE][+\-]?[0-9]+', Number.Float, ('#pop', 'expr-chain')), (r'[0-9]+\.[0-9]+', Number.Float, ('#pop', 'expr-chain')), (r'[0-9]+\.(?!' + ident + r'|\.\.)', Number.Float, ('#pop', 'expr-chain')),
# Int (r'0x[0-9a-fA-F]+', Number.Hex, ('#pop', 'expr-chain')), (r'[0-9]+', Number.Integer, ('#pop', 'expr-chain')),
# String (r"'", String.Single, ('#pop', 'expr-chain', 'string-single-interpol')), (r'"', String.Double, ('#pop', 'expr-chain', 'string-double')),
# EReg (r'~/(\\\\|\\[^\\]|[^/\\\n])*/[gimsu]*', String.Regex, ('#pop', 'expr-chain')),
# Array (r'\[', Punctuation, ('#pop', 'expr-chain', 'array-decl')), ],
'expr-chain': [ include('spaces'), (r'(?:\+\+|\-\-)', Operator), (binop, Operator, ('#pop', 'expr')), (r'(?:in)\b', Keyword, ('#pop', 'expr')), (r'\?', Operator, ('#pop', 'expr', 'ternary', 'expr')), (r'(\.)(' + ident_no_keyword + ')', bygroups(Punctuation, Name)), (r'\[', Punctuation, 'array-access'), (r'\(', Punctuation, 'call'), default('#pop'), ],
# macro reification 'macro': [ include('spaces'), include('meta'), (r':', Punctuation, ('#pop', 'type')),
(r'(?:extern|private)\b', Keyword.Declaration), (r'(?:abstract)\b', Keyword.Declaration, ('#pop', 'optional-semicolon', 'abstract')), (r'(?:class|interface)\b', Keyword.Declaration, ('#pop', 'optional-semicolon', 'macro-class')), (r'(?:enum)\b', Keyword.Declaration, ('#pop', 'optional-semicolon', 'enum')), (r'(?:typedef)\b', Keyword.Declaration, ('#pop', 'optional-semicolon', 'typedef')),
default(('#pop', 'expr')), ],
'macro-class': [ (r'\{', Punctuation, ('#pop', 'class-body')), include('class') ],
# cast can be written as "cast expr" or "cast(expr, type)" 'cast': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'parenthesis-close', 'cast-type', 'expr')), default(('#pop', 'expr')), ],
# optionally give a type as the 2nd argument of cast() 'cast-type': [ include('spaces'), (r',', Punctuation, ('#pop', 'type')), default('#pop'), ],
'catch': [ include('spaces'), (r'(?:catch)\b', Keyword, ('expr', 'function-param', 'parenthesis-open')), default('#pop'), ],
# do-while loop 'do': [ include('spaces'), default(('#pop', 'do-while', 'expr')), ],
# the while after do 'do-while': [ include('spaces'), (r'(?:while)\b', Keyword, ('#pop', 'parenthesis', 'parenthesis-open')), ],
'while': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'expr', 'parenthesis')), ],
'for': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'expr', 'parenthesis')), ],
'if': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'else', 'optional-semicolon', 'expr', 'parenthesis')), ],
'else': [ include('spaces'), (r'(?:else)\b', Keyword, ('#pop', 'expr')), default('#pop'), ],
'switch': [ include('spaces'), default(('#pop', 'switch-body', 'bracket-open', 'expr')), ],
'switch-body': [ include('spaces'), (r'(?:case|default)\b', Keyword, ('case-block', 'case')), (r'\}', Punctuation, '#pop'), ],
'case': [ include('spaces'), (r':', Punctuation, '#pop'), default(('#pop', 'case-sep', 'case-guard', 'expr')), ],
'case-sep': [ include('spaces'), (r':', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'case')), ],
'case-guard': [ include('spaces'), (r'(?:if)\b', Keyword, ('#pop', 'parenthesis', 'parenthesis-open')), default('#pop'), ],
# optional multiple expr under a case 'case-block': [ include('spaces'), (r'(?!(?:case|default)\b|\})', Keyword, 'expr-statement'), default('#pop'), ],
'new': [ include('spaces'), default(('#pop', 'call', 'parenthesis-open', 'type')), ],
'array-decl': [ include('spaces'), (r'\]', Punctuation, '#pop'), default(('#pop', 'array-decl-sep', 'expr')), ],
'array-decl-sep': [ include('spaces'), (r'\]', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'array-decl')), ],
'array-access': [ include('spaces'), default(('#pop', 'array-access-close', 'expr')), ],
'array-access-close': [ include('spaces'), (r'\]', Punctuation, '#pop'), ],
'comma': [ include('spaces'), (r',', Punctuation, '#pop'), ],
'colon': [ include('spaces'), (r':', Punctuation, '#pop'), ],
'semicolon': [ include('spaces'), (r';', Punctuation, '#pop'), ],
'optional-semicolon': [ include('spaces'), (r';', Punctuation, '#pop'), default('#pop'), ],
# identity that CAN be a Haxe keyword 'ident': [ include('spaces'), (ident, Name, '#pop'), ],
'dollar': [ include('spaces'), (r'\{', Punctuation, ('#pop', 'expr-chain', 'bracket-close', 'expr')), default(('#pop', 'expr-chain')), ],
'type-name': [ include('spaces'), (typeid, Name, '#pop'), ],
'type-full-name': [ include('spaces'), (r'\.', Punctuation, 'ident'), default('#pop'), ],
'type': [ include('spaces'), (r'\?', Punctuation), (ident, Name, ('#pop', 'type-check', 'type-full-name')), (r'\{', Punctuation, ('#pop', 'type-check', 'type-struct')), (r'\(', Punctuation, ('#pop', 'type-check', 'type-parenthesis')), ],
'type-parenthesis': [ include('spaces'), default(('#pop', 'parenthesis-close', 'type')), ],
'type-check': [ include('spaces'), (r'->', Punctuation, ('#pop', 'type')), (r'<(?!=)', Punctuation, 'type-param'), default('#pop'), ],
'type-struct': [ include('spaces'), (r'\}', Punctuation, '#pop'), (r'\?', Punctuation), (r'>', Punctuation, ('comma', 'type')), (ident_no_keyword, Name, ('#pop', 'type-struct-sep', 'type', 'colon')), include('class-body'), ],
'type-struct-sep': [ include('spaces'), (r'\}', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'type-struct')), ],
# type-param can be a normal type or a constant literal... 'type-param-type': [ # Float (r'\.[0-9]+', Number.Float, '#pop'), (r'[0-9]+[eE][+\-]?[0-9]+', Number.Float, '#pop'), (r'[0-9]+\.[0-9]*[eE][+\-]?[0-9]+', Number.Float, '#pop'), (r'[0-9]+\.[0-9]+', Number.Float, '#pop'), (r'[0-9]+\.(?!' + ident + r'|\.\.)', Number.Float, '#pop'),
# Int (r'0x[0-9a-fA-F]+', Number.Hex, '#pop'), (r'[0-9]+', Number.Integer, '#pop'),
# String (r"'", String.Single, ('#pop', 'string-single')), (r'"', String.Double, ('#pop', 'string-double')),
# EReg (r'~/(\\\\|\\[^\\]|[^/\\\n])*/[gim]*', String.Regex, '#pop'),
# Array (r'\[', Operator, ('#pop', 'array-decl')),
include('type'), ],
# type-param part of a type # ie. the <A,B> path in Map<A,B> 'type-param': [ include('spaces'), default(('#pop', 'type-param-sep', 'type-param-type')), ],
'type-param-sep': [ include('spaces'), (r'>', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'type-param')), ],
# optional type-param that may include constraint # ie. <T:Constraint, T2:(ConstraintA,ConstraintB)> 'type-param-constraint': [ include('spaces'), (r'<(?!=)', Punctuation, ('#pop', 'type-param-constraint-sep', 'type-param-constraint-flag', 'type-name')), default('#pop'), ],
'type-param-constraint-sep': [ include('spaces'), (r'>', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'type-param-constraint-sep', 'type-param-constraint-flag', 'type-name')), ],
# the optional constraint inside type-param 'type-param-constraint-flag': [ include('spaces'), (r':', Punctuation, ('#pop', 'type-param-constraint-flag-type')), default('#pop'), ],
'type-param-constraint-flag-type': [ include('spaces'), (r'\(', Punctuation, ('#pop', 'type-param-constraint-flag-type-sep', 'type')), default(('#pop', 'type')), ],
'type-param-constraint-flag-type-sep': [ include('spaces'), (r'\)', Punctuation, '#pop'), (r',', Punctuation, 'type'), ],
# a parenthesis expr that contain exactly one expr 'parenthesis': [ include('spaces'), default(('#pop', 'parenthesis-close', 'flag', 'expr')), ],
'parenthesis-open': [ include('spaces'), (r'\(', Punctuation, '#pop'), ],
'parenthesis-close': [ include('spaces'), (r'\)', Punctuation, '#pop'), ],
'var': [ include('spaces'), (ident_no_keyword, Text, ('#pop', 'var-sep', 'assign', 'flag', 'prop-get-set')), ],
# optional more var decl. 'var-sep': [ include('spaces'), (r',', Punctuation, ('#pop', 'var')), default('#pop'), ],
# optional assignment 'assign': [ include('spaces'), (r'=', Operator, ('#pop', 'expr')), default('#pop'), ],
# optional type flag 'flag': [ include('spaces'), (r':', Punctuation, ('#pop', 'type')), default('#pop'), ],
# colon as part of a ternary operator (?:) 'ternary': [ include('spaces'), (r':', Operator, '#pop'), ],
# function call 'call': [ include('spaces'), (r'\)', Punctuation, '#pop'), default(('#pop', 'call-sep', 'expr')), ],
# after a call param 'call-sep': [ include('spaces'), (r'\)', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'call')), ],
# bracket can be block or object 'bracket': [ include('spaces'), (r'(?!(?:\$\s*[a-z]\b|\$(?!'+ident+')))' + ident_no_keyword, Name, ('#pop', 'bracket-check')), (r"'", String.Single, ('#pop', 'bracket-check', 'string-single')), (r'"', String.Double, ('#pop', 'bracket-check', 'string-double')), default(('#pop', 'block')), ],
'bracket-check': [ include('spaces'), (r':', Punctuation, ('#pop', 'object-sep', 'expr')), # is object default(('#pop', 'block', 'optional-semicolon', 'expr-chain')), # is block ],
# code block 'block': [ include('spaces'), (r'\}', Punctuation, '#pop'), default('expr-statement'), ],
# object in key-value pairs 'object': [ include('spaces'), (r'\}', Punctuation, '#pop'), default(('#pop', 'object-sep', 'expr', 'colon', 'ident-or-string')) ],
# a key of an object 'ident-or-string': [ include('spaces'), (ident_no_keyword, Name, '#pop'), (r"'", String.Single, ('#pop', 'string-single')), (r'"', String.Double, ('#pop', 'string-double')), ],
# after a key-value pair in object 'object-sep': [ include('spaces'), (r'\}', Punctuation, '#pop'), (r',', Punctuation, ('#pop', 'object')), ],
}
def analyse_text(text): rv = 0 if re.search(r'\bimport\s+haxe\.', text): rv = max(rv, 0.2) if re.search(r'\bStd\.', text): rv = max(rv, 0.1) if re.search(r'\btrace\s*\(', text): rv = max(rv, 0.05) return rv
class HxmlLexer(RegexLexer): """ Lexer for haXe build files. """ name = 'Hxml' url = 'https://haxe.org/manual/compiler-usage-hxml.html' aliases = ['haxeml', 'hxml'] filenames = ['*.hxml'] version_added = '1.6'
tokens = { 'root': [ # Separator (r'(--)(next)', bygroups(Punctuation, Generic.Heading)), # Compiler switches with one dash (r'(-)(prompt|debug|v)', bygroups(Punctuation, Keyword.Keyword)), # Compilerswitches with two dashes (r'(--)(neko-source|flash-strict|flash-use-stage|no-opt|no-traces|' r'no-inline|times|no-output)', bygroups(Punctuation, Keyword)), # Targets and other options that take an argument (r'(-)(cpp|js|neko|x|as3|swf9?|swf-lib|php|xml|main|lib|D|resource|' r'cp|cmd)( +)(.+)', bygroups(Punctuation, Keyword, Whitespace, String)), # Options that take only numerical arguments (r'(-)(swf-version)( +)(\d+)', bygroups(Punctuation, Keyword, Whitespace, Number.Integer)), # An Option that defines the size, the fps and the background # color of an flash movie (r'(-)(swf-header)( +)(\d+)(:)(\d+)(:)(\d+)(:)([A-Fa-f0-9]{6})', bygroups(Punctuation, Keyword, Whitespace, Number.Integer, Punctuation, Number.Integer, Punctuation, Number.Integer, Punctuation, Number.Hex)), # options with two dashes that takes arguments (r'(--)(js-namespace|php-front|php-lib|remap|gen-hx-classes)( +)' r'(.+)', bygroups(Punctuation, Keyword, Whitespace, String)), # Single line comment, multiline ones are not allowed. (r'#.*', Comment.Single) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466""" pygments.lexers.hdl ~~~~~~~~~~~~~~~~~~~
Lexers for hardware descriptor languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, bygroups, include, using, this, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['VerilogLexer', 'SystemVerilogLexer', 'VhdlLexer']
class VerilogLexer(RegexLexer): """ For verilog source code with preprocessor directives. """ name = 'verilog' aliases = ['verilog', 'v'] filenames = ['*.v'] mimetypes = ['text/x-verilog'] url = 'https://en.wikipedia.org/wiki/Verilog' version_added = '1.4'
#: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+'
tokens = { 'root': [ (r'^\s*`define', Comment.Preproc, 'macro'), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'[{}#@]', Punctuation), (r'L?"', String, 'string'), (r"L?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'([0-9]+)|(\'h)[0-9a-fA-F]+', Number.Hex), (r'([0-9]+)|(\'b)[01]+', Number.Bin), (r'([0-9]+)|(\'d)[0-9]+', Number.Integer), (r'([0-9]+)|(\'o)[0-7]+', Number.Oct), (r'\'[01xz]', Number), (r'\d+[Ll]?', Number.Integer), (r'[~!%^&*+=|?:<>/-]', Operator), (r'[()\[\],.;\']', Punctuation), (r'`[a-zA-Z_]\w*', Name.Constant),
(r'^(\s*)(package)(\s+)', bygroups(Whitespace, Keyword.Namespace, Text)), (r'^(\s*)(import)(\s+)', bygroups(Whitespace, Keyword.Namespace, Text), 'import'),
(words(( 'always', 'always_comb', 'always_ff', 'always_latch', 'and', 'assign', 'automatic', 'begin', 'break', 'buf', 'bufif0', 'bufif1', 'case', 'casex', 'casez', 'cmos', 'const', 'continue', 'deassign', 'default', 'defparam', 'disable', 'do', 'edge', 'else', 'end', 'endcase', 'endfunction', 'endgenerate', 'endmodule', 'endpackage', 'endprimitive', 'endspecify', 'endtable', 'endtask', 'enum', 'event', 'final', 'for', 'force', 'forever', 'fork', 'function', 'generate', 'genvar', 'highz0', 'highz1', 'if', 'initial', 'inout', 'input', 'integer', 'join', 'large', 'localparam', 'macromodule', 'medium', 'module', 'nand', 'negedge', 'nmos', 'nor', 'not', 'notif0', 'notif1', 'or', 'output', 'packed', 'parameter', 'pmos', 'posedge', 'primitive', 'pull0', 'pull1', 'pulldown', 'pullup', 'rcmos', 'ref', 'release', 'repeat', 'return', 'rnmos', 'rpmos', 'rtran', 'rtranif0', 'rtranif1', 'scalared', 'signed', 'small', 'specify', 'specparam', 'strength', 'string', 'strong0', 'strong1', 'struct', 'table', 'task', 'tran', 'tranif0', 'tranif1', 'type', 'typedef', 'unsigned', 'var', 'vectored', 'void', 'wait', 'weak0', 'weak1', 'while', 'xnor', 'xor'), suffix=r'\b'), Keyword),
(words(( 'accelerate', 'autoexpand_vectornets', 'celldefine', 'default_nettype', 'else', 'elsif', 'endcelldefine', 'endif', 'endprotect', 'endprotected', 'expand_vectornets', 'ifdef', 'ifndef', 'include', 'noaccelerate', 'noexpand_vectornets', 'noremove_gatenames', 'noremove_netnames', 'nounconnected_drive', 'protect', 'protected', 'remove_gatenames', 'remove_netnames', 'resetall', 'timescale', 'unconnected_drive', 'undef'), prefix=r'`', suffix=r'\b'), Comment.Preproc),
(words(( 'bits', 'bitstoreal', 'bitstoshortreal', 'countdrivers', 'display', 'fclose', 'fdisplay', 'finish', 'floor', 'fmonitor', 'fopen', 'fstrobe', 'fwrite', 'getpattern', 'history', 'incsave', 'input', 'itor', 'key', 'list', 'log', 'monitor', 'monitoroff', 'monitoron', 'nokey', 'nolog', 'printtimescale', 'random', 'readmemb', 'readmemh', 'realtime', 'realtobits', 'reset', 'reset_count', 'reset_value', 'restart', 'rtoi', 'save', 'scale', 'scope', 'shortrealtobits', 'showscopes', 'showvariables', 'showvars', 'sreadmemb', 'sreadmemh', 'stime', 'stop', 'strobe', 'time', 'timeformat', 'write'), prefix=r'\$', suffix=r'\b'), Name.Builtin),
(words(( 'byte', 'shortint', 'int', 'longint', 'integer', 'time', 'bit', 'logic', 'reg', 'supply0', 'supply1', 'tri', 'triand', 'trior', 'tri0', 'tri1', 'trireg', 'uwire', 'wire', 'wand', 'wor' 'shortreal', 'real', 'realtime'), suffix=r'\b'), Keyword.Type), (r'[a-zA-Z_]\w*:(?!:)', Name.Label), (r'\$?[a-zA-Z_]\w*', Name), (r'\\(\S+)', Name), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation (r'\\', String), # stray backslash ], 'macro': [ (r'[^/\n]+', Comment.Preproc), (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'//.*?\n', Comment.Single, '#pop'), (r'/', Comment.Preproc), (r'(?<=\\)\n', Comment.Preproc), (r'\n', Whitespace, '#pop'), ], 'import': [ (r'[\w:]+\*?', Name.Namespace, '#pop') ] }
def analyse_text(text): """Verilog code will use one of reg/wire/assign for sure, and that is not common elsewhere.""" result = 0 if 'reg' in text: result += 0.1 if 'wire' in text: result += 0.1 if 'assign' in text: result += 0.1
return result
class SystemVerilogLexer(RegexLexer): """ Extends verilog lexer to recognise all SystemVerilog keywords from IEEE 1800-2009 standard. """ name = 'systemverilog' aliases = ['systemverilog', 'sv'] filenames = ['*.sv', '*.svh'] mimetypes = ['text/x-systemverilog'] url = 'https://en.wikipedia.org/wiki/SystemVerilog' version_added = '1.5'
#: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+'
tokens = { 'root': [ (r'^(\s*)(`define)', bygroups(Whitespace, Comment.Preproc), 'macro'), (r'^(\s*)(package)(\s+)', bygroups(Whitespace, Keyword.Namespace, Whitespace)), (r'^(\s*)(import)(\s+)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'import'),
(r'\s+', Whitespace), (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'[{}#@]', Punctuation), (r'L?"', String, 'string'), (r"L?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char),
(r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
(r'([1-9][_0-9]*)?\s*\'[sS]?[bB]\s*[xXzZ?01][_xXzZ?01]*', Number.Bin), (r'([1-9][_0-9]*)?\s*\'[sS]?[oO]\s*[xXzZ?0-7][_xXzZ?0-7]*', Number.Oct), (r'([1-9][_0-9]*)?\s*\'[sS]?[dD]\s*[xXzZ?0-9][_xXzZ?0-9]*', Number.Integer), (r'([1-9][_0-9]*)?\s*\'[sS]?[hH]\s*[xXzZ?0-9a-fA-F][_xXzZ?0-9a-fA-F]*', Number.Hex),
(r'\'[01xXzZ]', Number), (r'[0-9][_0-9]*', Number.Integer),
(r'[~!%^&*+=|?:<>/-]', Operator), (words(('inside', 'dist'), suffix=r'\b'), Operator.Word),
(r'[()\[\],.;\'$]', Punctuation), (r'`[a-zA-Z_]\w*', Name.Constant),
(words(( 'accept_on', 'alias', 'always', 'always_comb', 'always_ff', 'always_latch', 'and', 'assert', 'assign', 'assume', 'automatic', 'before', 'begin', 'bind', 'bins', 'binsof', 'break', 'buf', 'bufif0', 'bufif1', 'case', 'casex', 'casez', 'cell', 'checker', 'clocking', 'cmos', 'config', 'constraint', 'context', 'continue', 'cover', 'covergroup', 'coverpoint', 'cross', 'deassign', 'default', 'defparam', 'design', 'disable', 'do', 'edge', 'else', 'end', 'endcase', 'endchecker', 'endclocking', 'endconfig', 'endfunction', 'endgenerate', 'endgroup', 'endinterface', 'endmodule', 'endpackage', 'endprimitive', 'endprogram', 'endproperty', 'endsequence', 'endspecify', 'endtable', 'endtask', 'enum', 'eventually', 'expect', 'export', 'extern', 'final', 'first_match', 'for', 'force', 'foreach', 'forever', 'fork', 'forkjoin', 'function', 'generate', 'genvar', 'global', 'highz0', 'highz1', 'if', 'iff', 'ifnone', 'ignore_bins', 'illegal_bins', 'implies', 'implements', 'import', 'incdir', 'include', 'initial', 'inout', 'input', 'instance', 'interconnect', 'interface', 'intersect', 'join', 'join_any', 'join_none', 'large', 'let', 'liblist', 'library', 'local', 'localparam', 'macromodule', 'matches', 'medium', 'modport', 'module', 'nand', 'negedge', 'nettype', 'new', 'nexttime', 'nmos', 'nor', 'noshowcancelled', 'not', 'notif0', 'notif1', 'null', 'or', 'output', 'package', 'packed', 'parameter', 'pmos', 'posedge', 'primitive', 'priority', 'program', 'property', 'protected', 'pull0', 'pull1', 'pulldown', 'pullup', 'pulsestyle_ondetect', 'pulsestyle_onevent', 'pure', 'rand', 'randc', 'randcase', 'randsequence', 'rcmos', 'ref', 'reject_on', 'release', 'repeat', 'restrict', 'return', 'rnmos', 'rpmos', 'rtran', 'rtranif0', 'rtranif1', 's_always', 's_eventually', 's_nexttime', 's_until', 's_until_with', 'scalared', 'sequence', 'showcancelled', 'small', 'soft', 'solve', 'specify', 'specparam', 'static', 'strong', 'strong0', 'strong1', 'struct', 'super', 'sync_accept_on', 'sync_reject_on', 'table', 'tagged', 'task', 'this', 'throughout', 'timeprecision', 'timeunit', 'tran', 'tranif0', 'tranif1', 'typedef', 'union', 'unique', 'unique0', 'until', 'until_with', 'untyped', 'use', 'vectored', 'virtual', 'wait', 'wait_order', 'weak', 'weak0', 'weak1', 'while', 'wildcard', 'with', 'within', 'xnor', 'xor'), suffix=r'\b'), Keyword),
(r'(class)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Class)), (r'(extends)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, Whitespace, Name.Class)), (r'(endclass\b)(?:(\s*)(:)(\s*)([a-zA-Z_]\w*))?', bygroups(Keyword.Declaration, Whitespace, Punctuation, Whitespace, Name.Class)),
(words(( # Variable types 'bit', 'byte', 'chandle', 'const', 'event', 'int', 'integer', 'logic', 'longint', 'real', 'realtime', 'reg', 'shortint', 'shortreal', 'signed', 'string', 'time', 'type', 'unsigned', 'var', 'void', # Net types 'supply0', 'supply1', 'tri', 'triand', 'trior', 'trireg', 'tri0', 'tri1', 'uwire', 'wand', 'wire', 'wor'), suffix=r'\b'), Keyword.Type),
(words(( '`__FILE__', '`__LINE__', '`begin_keywords', '`celldefine', '`default_nettype', '`define', '`else', '`elsif', '`end_keywords', '`endcelldefine', '`endif', '`ifdef', '`ifndef', '`include', '`line', '`nounconnected_drive', '`pragma', '`resetall', '`timescale', '`unconnected_drive', '`undef', '`undefineall'), suffix=r'\b'), Comment.Preproc),
(words(( # Simulation control tasks (20.2) '$exit', '$finish', '$stop', # Simulation time functions (20.3) '$realtime', '$stime', '$time', # Timescale tasks (20.4) '$printtimescale', '$timeformat', # Conversion functions '$bitstoreal', '$bitstoshortreal', '$cast', '$itor', '$realtobits', '$rtoi', '$shortrealtobits', '$signed', '$unsigned', # Data query functions (20.6) '$bits', '$isunbounded', '$typename', # Array query functions (20.7) '$dimensions', '$high', '$increment', '$left', '$low', '$right', '$size', '$unpacked_dimensions', # Math functions (20.8) '$acos', '$acosh', '$asin', '$asinh', '$atan', '$atan2', '$atanh', '$ceil', '$clog2', '$cos', '$cosh', '$exp', '$floor', '$hypot', '$ln', '$log10', '$pow', '$sin', '$sinh', '$sqrt', '$tan', '$tanh', # Bit vector system functions (20.9) '$countbits', '$countones', '$isunknown', '$onehot', '$onehot0', # Severity tasks (20.10) '$info', '$error', '$fatal', '$warning', # Assertion control tasks (20.12) '$assertcontrol', '$assertfailoff', '$assertfailon', '$assertkill', '$assertnonvacuouson', '$assertoff', '$asserton', '$assertpassoff', '$assertpasson', '$assertvacuousoff', # Sampled value system functions (20.13) '$changed', '$changed_gclk', '$changing_gclk', '$falling_gclk', '$fell', '$fell_gclk', '$future_gclk', '$past', '$past_gclk', '$rising_gclk', '$rose', '$rose_gclk', '$sampled', '$stable', '$stable_gclk', '$steady_gclk', # Coverage control functions (20.14) '$coverage_control', '$coverage_get', '$coverage_get_max', '$coverage_merge', '$coverage_save', '$get_coverage', '$load_coverage_db', '$set_coverage_db_name', # Probabilistic distribution functions (20.15) '$dist_chi_square', '$dist_erlang', '$dist_exponential', '$dist_normal', '$dist_poisson', '$dist_t', '$dist_uniform', '$random', # Stochastic analysis tasks and functions (20.16) '$q_add', '$q_exam', '$q_full', '$q_initialize', '$q_remove', # PLA modeling tasks (20.17) '$async$and$array', '$async$and$plane', '$async$nand$array', '$async$nand$plane', '$async$nor$array', '$async$nor$plane', '$async$or$array', '$async$or$plane', '$sync$and$array', '$sync$and$plane', '$sync$nand$array', '$sync$nand$plane', '$sync$nor$array', '$sync$nor$plane', '$sync$or$array', '$sync$or$plane', # Miscellaneous tasks and functions (20.18) '$system', # Display tasks (21.2) '$display', '$displayb', '$displayh', '$displayo', '$monitor', '$monitorb', '$monitorh', '$monitoro', '$monitoroff', '$monitoron', '$strobe', '$strobeb', '$strobeh', '$strobeo', '$write', '$writeb', '$writeh', '$writeo', # File I/O tasks and functions (21.3) '$fclose', '$fdisplay', '$fdisplayb', '$fdisplayh', '$fdisplayo', '$feof', '$ferror', '$fflush', '$fgetc', '$fgets', '$fmonitor', '$fmonitorb', '$fmonitorh', '$fmonitoro', '$fopen', '$fread', '$fscanf', '$fseek', '$fstrobe', '$fstrobeb', '$fstrobeh', '$fstrobeo', '$ftell', '$fwrite', '$fwriteb', '$fwriteh', '$fwriteo', '$rewind', '$sformat', '$sformatf', '$sscanf', '$swrite', '$swriteb', '$swriteh', '$swriteo', '$ungetc', # Memory load tasks (21.4) '$readmemb', '$readmemh', # Memory dump tasks (21.5) '$writememb', '$writememh', # Command line input (21.6) '$test$plusargs', '$value$plusargs', # VCD tasks (21.7) '$dumpall', '$dumpfile', '$dumpflush', '$dumplimit', '$dumpoff', '$dumpon', '$dumpports', '$dumpportsall', '$dumpportsflush', '$dumpportslimit', '$dumpportsoff', '$dumpportson', '$dumpvars', ), suffix=r'\b'), Name.Builtin),
(r'[a-zA-Z_]\w*:(?!:)', Name.Label), (r'\$?[a-zA-Z_]\w*', Name), (r'\\(\S+)', Name), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation (r'\\', String), # stray backslash ], 'macro': [ (r'[^/\n]+', Comment.Preproc), (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'//.*?$', Comment.Single, '#pop'), (r'/', Comment.Preproc), (r'(?<=\\)\n', Comment.Preproc), (r'\n', Whitespace, '#pop'), ], 'import': [ (r'[\w:]+\*?', Name.Namespace, '#pop') ] }
class VhdlLexer(RegexLexer): """ For VHDL source code. """ name = 'vhdl' aliases = ['vhdl'] filenames = ['*.vhdl', '*.vhd'] mimetypes = ['text/x-vhdl'] url = 'https://en.wikipedia.org/wiki/VHDL' version_added = '1.5' flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation (r'--.*?$', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r"'(U|X|0|1|Z|W|L|H|-)'", String.Char), (r'[~!%^&*+=|?:<>/-]', Operator), (r"'[a-z_]\w*", Name.Attribute), (r'[()\[\],.;\']', Punctuation), (r'"[^\n\\"]*"', String),
(r'(library)(\s+)([a-z_]\w*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(use)(\s+)(entity)', bygroups(Keyword, Whitespace, Keyword)), (r'(use)(\s+)([a-z_][\w.]*\.)(all)', bygroups(Keyword, Whitespace, Name.Namespace, Keyword)), (r'(use)(\s+)([a-z_][\w.]*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(std|ieee)(\.[a-z_]\w*)', bygroups(Name.Namespace, Name.Namespace)), (words(('std', 'ieee', 'work'), suffix=r'\b'), Name.Namespace), (r'(entity|component)(\s+)([a-z_]\w*)', bygroups(Keyword, Whitespace, Name.Class)), (r'(architecture|configuration)(\s+)([a-z_]\w*)(\s+)' r'(of)(\s+)([a-z_]\w*)(\s+)(is)', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Keyword, Whitespace, Name.Class, Whitespace, Keyword)), (r'([a-z_]\w*)(:)(\s+)(process|for)', bygroups(Name.Class, Operator, Whitespace, Keyword)), (r'(end)(\s+)', bygroups(using(this), Whitespace), 'endblock'),
include('types'), include('keywords'), include('numbers'),
(r'[a-z_]\w*', Name), ], 'endblock': [ include('keywords'), (r'[a-z_]\w*', Name.Class), (r'\s+', Whitespace), (r';', Punctuation, '#pop'), ], 'types': [ (words(( 'boolean', 'bit', 'character', 'severity_level', 'integer', 'time', 'delay_length', 'natural', 'positive', 'string', 'bit_vector', 'file_open_kind', 'file_open_status', 'std_ulogic', 'std_ulogic_vector', 'std_logic', 'std_logic_vector', 'signed', 'unsigned'), suffix=r'\b'), Keyword.Type), ], 'keywords': [ (words(( 'abs', 'access', 'after', 'alias', 'all', 'and', 'architecture', 'array', 'assert', 'attribute', 'begin', 'block', 'body', 'buffer', 'bus', 'case', 'component', 'configuration', 'constant', 'disconnect', 'downto', 'else', 'elsif', 'end', 'entity', 'exit', 'file', 'for', 'function', 'generate', 'generic', 'group', 'guarded', 'if', 'impure', 'in', 'inertial', 'inout', 'is', 'label', 'library', 'linkage', 'literal', 'loop', 'map', 'mod', 'nand', 'new', 'next', 'nor', 'not', 'null', 'of', 'on', 'open', 'or', 'others', 'out', 'package', 'port', 'postponed', 'procedure', 'process', 'pure', 'range', 'record', 'register', 'reject', 'rem', 'return', 'rol', 'ror', 'select', 'severity', 'signal', 'shared', 'sla', 'sll', 'sra', 'srl', 'subtype', 'then', 'to', 'transport', 'type', 'units', 'until', 'use', 'variable', 'wait', 'when', 'while', 'with', 'xnor', 'xor'), suffix=r'\b'), Keyword), ], 'numbers': [ (r'\d{1,2}#[0-9a-f_]+#?', Number.Integer), (r'\d+', Number.Integer), (r'(\d+\.\d*|\.\d+|\d+)E[+-]?\d+', Number.Float), (r'X"[0-9a-f_]+"', Number.Hex), (r'O"[0-7_]+"', Number.Oct), (r'B"[01_]+"', Number.Bin), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102""" pygments.lexers.hexdump ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for hexadecimal dumps.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, includefrom pygments.token import Name, Number, String, Punctuation, Whitespace
__all__ = ['HexdumpLexer']
class HexdumpLexer(RegexLexer): """ For typical hex dump output formats by the UNIX and GNU/Linux tools ``hexdump``, ``hd``, ``hexcat``, ``od`` and ``xxd``, and the DOS tool ``DEBUG``. For example:
.. sourcecode:: hexdump
00000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 |.ELF............| 00000010 02 00 3e 00 01 00 00 00 c5 48 40 00 00 00 00 00 |..>......H@.....|
The specific supported formats are the outputs of:
* ``hexdump FILE`` * ``hexdump -C FILE`` -- the `canonical` format used in the example. * ``hd FILE`` -- same as ``hexdump -C FILE``. * ``hexcat FILE`` * ``od -t x1z FILE`` * ``xxd FILE`` * ``DEBUG.EXE FILE.COM`` and entering ``d`` to the prompt. """ name = 'Hexdump' aliases = ['hexdump'] url = 'https://en.wikipedia.org/wiki/Hex_dump' version_added = '2.1'
hd = r'[0-9A-Ha-h]'
tokens = { 'root': [ (r'\n', Whitespace), include('offset'), (r'('+hd+r'{2})(\-)('+hd+r'{2})', bygroups(Number.Hex, Punctuation, Number.Hex)), (hd+r'{2}', Number.Hex), (r'(\s{2,3})(\>)(.{16})(\<)$', bygroups(Whitespace, Punctuation, String, Punctuation), 'bracket-strings'), (r'(\s{2,3})(\|)(.{16})(\|)$', bygroups(Whitespace, Punctuation, String, Punctuation), 'piped-strings'), (r'(\s{2,3})(\>)(.{1,15})(\<)$', bygroups(Whitespace, Punctuation, String, Punctuation)), (r'(\s{2,3})(\|)(.{1,15})(\|)$', bygroups(Whitespace, Punctuation, String, Punctuation)), (r'(\s{2,3})(.{1,15})$', bygroups(Whitespace, String)), (r'(\s{2,3})(.{16}|.{20})$', bygroups(Whitespace, String), 'nonpiped-strings'), (r'\s', Whitespace), (r'^\*', Punctuation), ], 'offset': [ (r'^('+hd+'+)(:)', bygroups(Name.Label, Punctuation), 'offset-mode'), (r'^'+hd+'+', Name.Label), ], 'offset-mode': [ (r'\s', Whitespace, '#pop'), (hd+'+', Name.Label), (r':', Punctuation) ], 'piped-strings': [ (r'\n', Whitespace), include('offset'), (hd+r'{2}', Number.Hex), (r'(\s{2,3})(\|)(.{1,16})(\|)$', bygroups(Whitespace, Punctuation, String, Punctuation)), (r'\s', Whitespace), (r'^\*', Punctuation), ], 'bracket-strings': [ (r'\n', Whitespace), include('offset'), (hd+r'{2}', Number.Hex), (r'(\s{2,3})(\>)(.{1,16})(\<)$', bygroups(Whitespace, Punctuation, String, Punctuation)), (r'\s', Whitespace), (r'^\*', Punctuation), ], 'nonpiped-strings': [ (r'\n', Whitespace), include('offset'), (r'('+hd+r'{2})(\-)('+hd+r'{2})', bygroups(Number.Hex, Punctuation, Number.Hex)), (hd+r'{2}', Number.Hex), (r'(\s{19,})(.{1,20}?)$', bygroups(Whitespace, String)), (r'(\s{2,3})(.{1,20})$', bygroups(Whitespace, String)), (r'\s', Whitespace), (r'^\*', Punctuation), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670""" pygments.lexers.html ~~~~~~~~~~~~~~~~~~~~
Lexers for HTML, XML and related markup.
: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, \ default, using, inherit, thisfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Punctuation, Whitespacefrom pygments.util import looks_like_xml, html_doctype_matches
from pygments.lexers.javascript import JavascriptLexerfrom pygments.lexers.jvm import ScalaLexerfrom pygments.lexers.css import CssLexer, _indentation, _starts_blockfrom pygments.lexers.ruby import RubyLexer
__all__ = ['HtmlLexer', 'DtdLexer', 'XmlLexer', 'XsltLexer', 'HamlLexer', 'ScamlLexer', 'PugLexer', 'VueLexer', 'UrlEncodedLexer']
class HtmlLexer(RegexLexer): """ For HTML 4 and XHTML 1 markup. Nested JavaScript and CSS is highlighted by the appropriate lexer. """
name = 'HTML' url = 'https://html.spec.whatwg.org/' aliases = ['html'] filenames = ['*.html', '*.htm', '*.xhtml', '*.xslt'] mimetypes = ['text/html', 'application/xhtml+xml'] version_added = ''
flags = re.IGNORECASE | re.DOTALL tokens = { 'root': [ ('[^<&]+', Text), (r'&\S*?;', Name.Entity), (r'\<\!\[CDATA\[.*?\]\]\>', Comment.Preproc), (r'<!--.*?-->', Comment.Multiline), (r'<\?.*?\?>', Comment.Preproc), ('<![^>]*>', Comment.Preproc), (r'(<)(\s*)(script)(\s*)', bygroups(Punctuation, Text, Name.Tag, Text), ('script-content', 'tag')), (r'(<)(\s*)(style)(\s*)', bygroups(Punctuation, Text, Name.Tag, Text), ('style-content', 'tag')), # note: this allows tag names not used in HTML like <x:with-dash>, # this is to support yet-unknown template engines and the like (r'(<)(\s*)([\w:.-]+)', bygroups(Punctuation, Text, Name.Tag), 'tag'), (r'(<)(\s*)(/)(\s*)([\w:.-]+)(\s*)(>)', bygroups(Punctuation, Text, Punctuation, Text, Name.Tag, Text, Punctuation)), ], 'tag': [ (r'\s+', Text), (r'([\w:-]+\s*)(=)(\s*)', bygroups(Name.Attribute, Operator, Text), 'attr'), (r'[\w:-]+', Name.Attribute), (r'(/?)(\s*)(>)', bygroups(Punctuation, Text, Punctuation), '#pop'), ], 'script-content': [ (r'(<)(\s*)(/)(\s*)(script)(\s*)(>)', bygroups(Punctuation, Text, Punctuation, Text, Name.Tag, Text, Punctuation), '#pop'), (r'.+?(?=<\s*/\s*script\s*>)', using(JavascriptLexer)), # fallback cases for when there is no closing script tag # first look for newline and then go back into root state # if that fails just read the rest of the file # this is similar to the error handling logic in lexer.py (r'.+?\n', using(JavascriptLexer), '#pop'), (r'.+', using(JavascriptLexer), '#pop'), ], 'style-content': [ (r'(<)(\s*)(/)(\s*)(style)(\s*)(>)', bygroups(Punctuation, Text, Punctuation, Text, Name.Tag, Text, Punctuation),'#pop'), (r'.+?(?=<\s*/\s*style\s*>)', using(CssLexer)), # fallback cases for when there is no closing style tag # first look for newline and then go back into root state # if that fails just read the rest of the file # this is similar to the error handling logic in lexer.py (r'.+?\n', using(CssLexer), '#pop'), (r'.+', using(CssLexer), '#pop'), ], 'attr': [ ('".*?"', String, '#pop'), ("'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop'), ], }
def analyse_text(text): if html_doctype_matches(text): return 0.5
class DtdLexer(RegexLexer): """ A lexer for DTDs (Document Type Definitions). """
flags = re.MULTILINE | re.DOTALL
name = 'DTD' aliases = ['dtd'] filenames = ['*.dtd'] mimetypes = ['application/xml-dtd'] url = 'https://en.wikipedia.org/wiki/Document_type_definition' version_added = '1.5'
tokens = { 'root': [ include('common'),
(r'(<!ELEMENT)(\s+)(\S+)', bygroups(Keyword, Text, Name.Tag), 'element'), (r'(<!ATTLIST)(\s+)(\S+)', bygroups(Keyword, Text, Name.Tag), 'attlist'), (r'(<!ENTITY)(\s+)(\S+)', bygroups(Keyword, Text, Name.Entity), 'entity'), (r'(<!NOTATION)(\s+)(\S+)', bygroups(Keyword, Text, Name.Tag), 'notation'), (r'(<!\[)([^\[\s]+)(\s*)(\[)', # conditional sections bygroups(Keyword, Name.Entity, Text, Keyword)),
(r'(<!DOCTYPE)(\s+)([^>\s]+)', bygroups(Keyword, Text, Name.Tag)), (r'PUBLIC|SYSTEM', Keyword.Constant), (r'[\[\]>]', Keyword), ],
'common': [ (r'\s+', Text), (r'(%|&)[^;]*;', Name.Entity), ('<!--', Comment, 'comment'), (r'[(|)*,?+]', Operator), (r'"[^"]*"', String.Double), (r'\'[^\']*\'', String.Single), ],
'comment': [ ('[^-]+', Comment), ('-->', Comment, '#pop'), ('-', Comment), ],
'element': [ include('common'), (r'EMPTY|ANY|#PCDATA', Keyword.Constant), (r'[^>\s|()?+*,]+', Name.Tag), (r'>', Keyword, '#pop'), ],
'attlist': [ include('common'), (r'CDATA|IDREFS|IDREF|ID|NMTOKENS|NMTOKEN|ENTITIES|ENTITY|NOTATION', Keyword.Constant), (r'#REQUIRED|#IMPLIED|#FIXED', Keyword.Constant), (r'xml:space|xml:lang', Keyword.Reserved), (r'[^>\s|()?+*,]+', Name.Attribute), (r'>', Keyword, '#pop'), ],
'entity': [ include('common'), (r'SYSTEM|PUBLIC|NDATA', Keyword.Constant), (r'[^>\s|()?+*,]+', Name.Entity), (r'>', Keyword, '#pop'), ],
'notation': [ include('common'), (r'SYSTEM|PUBLIC', Keyword.Constant), (r'[^>\s|()?+*,]+', Name.Attribute), (r'>', Keyword, '#pop'), ], }
def analyse_text(text): if not looks_like_xml(text) and \ ('<!ELEMENT' in text or '<!ATTLIST' in text or '<!ENTITY' in text): return 0.8
class XmlLexer(RegexLexer): """ Generic lexer for XML (eXtensible Markup Language). """
flags = re.MULTILINE | re.DOTALL
name = 'XML' aliases = ['xml'] filenames = ['*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd', '*.wsdl', '*.wsf', '*.xbrl', '*.pom'] mimetypes = ['text/xml', 'application/xml', 'image/svg+xml', 'application/rss+xml', 'application/atom+xml'] url = 'https://www.w3.org/XML' version_added = ''
tokens = { 'root': [ (r'[^<&\s]+', Text), (r'[^<&\S]+', Whitespace), (r'&\S*?;', Name.Entity), (r'\<\!\[CDATA\[.*?\]\]\>', Comment.Preproc), (r'<!--.*?-->', Comment.Multiline), (r'<\?.*?\?>', Comment.Preproc), ('<![^>]*>', Comment.Preproc), (r'<\s*[\w:.-]+', Name.Tag, 'tag'), (r'<\s*/\s*[\w:.-]+\s*>', Name.Tag), ], 'tag': [ (r'\s+', Whitespace), (r'[\w.:-]+\s*=', Name.Attribute, 'attr'), (r'/?\s*>', Name.Tag, '#pop'), ], 'attr': [ (r'\s+', Whitespace), ('".*?"', String, '#pop'), ("'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop'), ], }
def analyse_text(text): if looks_like_xml(text): return 0.45 # less than HTML
class XsltLexer(XmlLexer): """ A lexer for XSLT. """
name = 'XSLT' aliases = ['xslt'] filenames = ['*.xsl', '*.xslt', '*.xpl'] # xpl is XProc mimetypes = ['application/xsl+xml', 'application/xslt+xml'] url = 'https://www.w3.org/TR/xslt-30' version_added = '0.10'
EXTRA_KEYWORDS = { 'apply-imports', 'apply-templates', 'attribute', 'attribute-set', 'call-template', 'choose', 'comment', 'copy', 'copy-of', 'decimal-format', 'element', 'fallback', 'for-each', 'if', 'import', 'include', 'key', 'message', 'namespace-alias', 'number', 'otherwise', 'output', 'param', 'preserve-space', 'processing-instruction', 'sort', 'strip-space', 'stylesheet', 'template', 'text', 'transform', 'value-of', 'variable', 'when', 'with-param' }
def get_tokens_unprocessed(self, text): for index, token, value in XmlLexer.get_tokens_unprocessed(self, text): m = re.match('</?xsl:([^>]*)/?>?', value)
if token is Name.Tag and m and m.group(1) in self.EXTRA_KEYWORDS: yield index, Keyword, value else: yield index, token, value
def analyse_text(text): if looks_like_xml(text) and '<xsl' in text: return 0.8
class HamlLexer(ExtendedRegexLexer): """ For Haml markup. """
name = 'Haml' aliases = ['haml'] filenames = ['*.haml'] mimetypes = ['text/x-haml'] url = 'https://haml.info' version_added = '1.3'
flags = re.IGNORECASE # Haml can include " |\n" anywhere, # which is ignored and used to wrap long lines. # To accommodate this, use this custom faux dot instead. _dot = r'(?: \|\n(?=.* \|)|.)'
# In certain places, a comma at the end of the line # allows line wrapping as well. _comma_dot = r'(?:,\s*\n|' + _dot + ')' tokens = { 'root': [ (r'[ \t]*\n', Text), (r'[ \t]*', _indentation), ],
'css': [ (r'\.[\w:-]+', Name.Class, 'tag'), (r'\#[\w:-]+', Name.Function, 'tag'), ],
'eval-or-plain': [ (r'[&!]?==', Punctuation, 'plain'), (r'([&!]?[=~])(' + _comma_dot + r'*\n)', bygroups(Punctuation, using(RubyLexer)), 'root'), default('plain'), ],
'content': [ include('css'), (r'%[\w:-]+', Name.Tag, 'tag'), (r'!!!' + _dot + r'*\n', Name.Namespace, '#pop'), (r'(/)(\[' + _dot + r'*?\])(' + _dot + r'*\n)', bygroups(Comment, Comment.Special, Comment), '#pop'), (r'/' + _dot + r'*\n', _starts_block(Comment, 'html-comment-block'), '#pop'), (r'-#' + _dot + r'*\n', _starts_block(Comment.Preproc, 'haml-comment-block'), '#pop'), (r'(-)(' + _comma_dot + r'*\n)', bygroups(Punctuation, using(RubyLexer)), '#pop'), (r':' + _dot + r'*\n', _starts_block(Name.Decorator, 'filter-block'), '#pop'), include('eval-or-plain'), ],
'tag': [ include('css'), (r'\{(,\n|' + _dot + r')*?\}', using(RubyLexer)), (r'\[' + _dot + r'*?\]', using(RubyLexer)), (r'\(', Text, 'html-attributes'), (r'/[ \t]*\n', Punctuation, '#pop:2'), (r'[<>]{1,2}(?=[ \t=])', Punctuation), include('eval-or-plain'), ],
'plain': [ (r'([^#\n]|#[^{\n]|(\\\\)*\\#\{)+', Text), (r'(#\{)(' + _dot + r'*?)(\})', bygroups(String.Interpol, using(RubyLexer), String.Interpol)), (r'\n', Text, 'root'), ],
'html-attributes': [ (r'\s+', Text), (r'[\w:-]+[ \t]*=', Name.Attribute, 'html-attribute-value'), (r'[\w:-]+', Name.Attribute), (r'\)', Text, '#pop'), ],
'html-attribute-value': [ (r'[ \t]+', Text), (r'\w+', Name.Variable, '#pop'), (r'@\w+', Name.Variable.Instance, '#pop'), (r'\$\w+', Name.Variable.Global, '#pop'), (r"'(\\\\|\\[^\\]|[^'\\\n])*'", String, '#pop'), (r'"(\\\\|\\[^\\]|[^"\\\n])*"', String, '#pop'), ],
'html-comment-block': [ (_dot + '+', Comment), (r'\n', Text, 'root'), ],
'haml-comment-block': [ (_dot + '+', Comment.Preproc), (r'\n', Text, 'root'), ],
'filter-block': [ (r'([^#\n]|#[^{\n]|(\\\\)*\\#\{)+', Name.Decorator), (r'(#\{)(' + _dot + r'*?)(\})', bygroups(String.Interpol, using(RubyLexer), String.Interpol)), (r'\n', Text, 'root'), ], }
class ScamlLexer(ExtendedRegexLexer): """ For Scaml markup. Scaml is Haml for Scala. """
name = 'Scaml' aliases = ['scaml'] filenames = ['*.scaml'] mimetypes = ['text/x-scaml'] url = 'https://scalate.github.io/scalate/' version_added = '1.4'
flags = re.IGNORECASE # Scaml does not yet support the " |\n" notation to # wrap long lines. Once it does, use the custom faux # dot instead. # _dot = r'(?: \|\n(?=.* \|)|.)' _dot = r'.'
tokens = { 'root': [ (r'[ \t]*\n', Text), (r'[ \t]*', _indentation), ],
'css': [ (r'\.[\w:-]+', Name.Class, 'tag'), (r'\#[\w:-]+', Name.Function, 'tag'), ],
'eval-or-plain': [ (r'[&!]?==', Punctuation, 'plain'), (r'([&!]?[=~])(' + _dot + r'*\n)', bygroups(Punctuation, using(ScalaLexer)), 'root'), default('plain'), ],
'content': [ include('css'), (r'%[\w:-]+', Name.Tag, 'tag'), (r'!!!' + _dot + r'*\n', Name.Namespace, '#pop'), (r'(/)(\[' + _dot + r'*?\])(' + _dot + r'*\n)', bygroups(Comment, Comment.Special, Comment), '#pop'), (r'/' + _dot + r'*\n', _starts_block(Comment, 'html-comment-block'), '#pop'), (r'-#' + _dot + r'*\n', _starts_block(Comment.Preproc, 'scaml-comment-block'), '#pop'), (r'(-@\s*)(import)?(' + _dot + r'*\n)', bygroups(Punctuation, Keyword, using(ScalaLexer)), '#pop'), (r'(-)(' + _dot + r'*\n)', bygroups(Punctuation, using(ScalaLexer)), '#pop'), (r':' + _dot + r'*\n', _starts_block(Name.Decorator, 'filter-block'), '#pop'), include('eval-or-plain'), ],
'tag': [ include('css'), (r'\{(,\n|' + _dot + r')*?\}', using(ScalaLexer)), (r'\[' + _dot + r'*?\]', using(ScalaLexer)), (r'\(', Text, 'html-attributes'), (r'/[ \t]*\n', Punctuation, '#pop:2'), (r'[<>]{1,2}(?=[ \t=])', Punctuation), include('eval-or-plain'), ],
'plain': [ (r'([^#\n]|#[^{\n]|(\\\\)*\\#\{)+', Text), (r'(#\{)(' + _dot + r'*?)(\})', bygroups(String.Interpol, using(ScalaLexer), String.Interpol)), (r'\n', Text, 'root'), ],
'html-attributes': [ (r'\s+', Text), (r'[\w:-]+[ \t]*=', Name.Attribute, 'html-attribute-value'), (r'[\w:-]+', Name.Attribute), (r'\)', Text, '#pop'), ],
'html-attribute-value': [ (r'[ \t]+', Text), (r'\w+', Name.Variable, '#pop'), (r'@\w+', Name.Variable.Instance, '#pop'), (r'\$\w+', Name.Variable.Global, '#pop'), (r"'(\\\\|\\[^\\]|[^'\\\n])*'", String, '#pop'), (r'"(\\\\|\\[^\\]|[^"\\\n])*"', String, '#pop'), ],
'html-comment-block': [ (_dot + '+', Comment), (r'\n', Text, 'root'), ],
'scaml-comment-block': [ (_dot + '+', Comment.Preproc), (r'\n', Text, 'root'), ],
'filter-block': [ (r'([^#\n]|#[^{\n]|(\\\\)*\\#\{)+', Name.Decorator), (r'(#\{)(' + _dot + r'*?)(\})', bygroups(String.Interpol, using(ScalaLexer), String.Interpol)), (r'\n', Text, 'root'), ], }
class PugLexer(ExtendedRegexLexer): """ For Pug markup. Pug is a variant of Scaml, see: http://scalate.fusesource.org/documentation/scaml-reference.html """
name = 'Pug' aliases = ['pug', 'jade'] filenames = ['*.pug', '*.jade'] mimetypes = ['text/x-pug', 'text/x-jade'] url = 'https://pugjs.org' version_added = '1.4'
flags = re.IGNORECASE _dot = r'.'
tokens = { 'root': [ (r'[ \t]*\n', Text), (r'[ \t]*', _indentation), ],
'css': [ (r'\.[\w:-]+', Name.Class, 'tag'), (r'\#[\w:-]+', Name.Function, 'tag'), ],
'eval-or-plain': [ (r'[&!]?==', Punctuation, 'plain'), (r'([&!]?[=~])(' + _dot + r'*\n)', bygroups(Punctuation, using(ScalaLexer)), 'root'), default('plain'), ],
'content': [ include('css'), (r'!!!' + _dot + r'*\n', Name.Namespace, '#pop'), (r'(/)(\[' + _dot + r'*?\])(' + _dot + r'*\n)', bygroups(Comment, Comment.Special, Comment), '#pop'), (r'/' + _dot + r'*\n', _starts_block(Comment, 'html-comment-block'), '#pop'), (r'-#' + _dot + r'*\n', _starts_block(Comment.Preproc, 'scaml-comment-block'), '#pop'), (r'(-@\s*)(import)?(' + _dot + r'*\n)', bygroups(Punctuation, Keyword, using(ScalaLexer)), '#pop'), (r'(-)(' + _dot + r'*\n)', bygroups(Punctuation, using(ScalaLexer)), '#pop'), (r':' + _dot + r'*\n', _starts_block(Name.Decorator, 'filter-block'), '#pop'), (r'[\w:-]+', Name.Tag, 'tag'), (r'\|', Text, 'eval-or-plain'), ],
'tag': [ include('css'), (r'\{(,\n|' + _dot + r')*?\}', using(ScalaLexer)), (r'\[' + _dot + r'*?\]', using(ScalaLexer)), (r'\(', Text, 'html-attributes'), (r'/[ \t]*\n', Punctuation, '#pop:2'), (r'[<>]{1,2}(?=[ \t=])', Punctuation), include('eval-or-plain'), ],
'plain': [ (r'([^#\n]|#[^{\n]|(\\\\)*\\#\{)+', Text), (r'(#\{)(' + _dot + r'*?)(\})', bygroups(String.Interpol, using(ScalaLexer), String.Interpol)), (r'\n', Text, 'root'), ],
'html-attributes': [ (r'\s+', Text), (r'[\w:-]+[ \t]*=', Name.Attribute, 'html-attribute-value'), (r'[\w:-]+', Name.Attribute), (r'\)', Text, '#pop'), ],
'html-attribute-value': [ (r'[ \t]+', Text), (r'\w+', Name.Variable, '#pop'), (r'@\w+', Name.Variable.Instance, '#pop'), (r'\$\w+', Name.Variable.Global, '#pop'), (r"'(\\\\|\\[^\\]|[^'\\\n])*'", String, '#pop'), (r'"(\\\\|\\[^\\]|[^"\\\n])*"', String, '#pop'), ],
'html-comment-block': [ (_dot + '+', Comment), (r'\n', Text, 'root'), ],
'scaml-comment-block': [ (_dot + '+', Comment.Preproc), (r'\n', Text, 'root'), ],
'filter-block': [ (r'([^#\n]|#[^{\n]|(\\\\)*\\#\{)+', Name.Decorator), (r'(#\{)(' + _dot + r'*?)(\})', bygroups(String.Interpol, using(ScalaLexer), String.Interpol)), (r'\n', Text, 'root'), ], }JadeLexer = PugLexer # compat
class UrlEncodedLexer(RegexLexer): """ Lexer for urlencoded data """
name = 'urlencoded' aliases = ['urlencoded'] mimetypes = ['application/x-www-form-urlencoded'] url = 'https://en.wikipedia.org/wiki/Percent-encoding' version_added = '2.16'
tokens = { 'root': [ ('([^&=]*)(=)([^=&]*)(&?)', bygroups(Name.Tag, Operator, String, Punctuation)), ], }
class VueLexer(HtmlLexer): """ For Vue Single-File Component. """
name = 'Vue' url = 'https://vuejs.org/api/sfc-spec.html' aliases = ['vue'] filenames = ['*.vue'] mimetypes = [] version_added = '2.19'
flags = re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'(\{\{)(.*?)(\}\})', bygroups(Comment.Preproc, using(JavascriptLexer), Comment.Preproc)), ('[^<&{]+', Text), inherit, ], 'tag': [ (r'\s+', Text), (r'((?:[@:]|v-)(?:[.\w:-]|\[[^\]]*?\])+\s*)(=)(\s*)', bygroups(using(this, state=['name']), Operator, Text), 'attr-directive'), (r'([\w:-]+\s*)(=)(\s*)', bygroups(Name.Attribute, Operator, Text), 'attr'), (r'[\w:-]+', Name.Attribute), (r'(/?)(\s*)(>)', bygroups(Punctuation, Text, Punctuation), '#pop'), ], 'name': [ (r'[\w-]+', Name.Attribute), (r'[:@.]', Punctuation), (r'(\[)([^\]]*?)(\])', bygroups(Comment.Preproc, using(JavascriptLexer), Comment.Preproc)), ], 'attr-directive': [ (r'(["\'])(.*?)(\1)', bygroups(String, using(JavascriptLexer), String), '#pop'), (r'[^\s>]+', using(JavascriptLexer), '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284""" pygments.lexers.idl ~~~~~~~~~~~~~~~~~~~
Lexers for IDL.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, words, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, Number, \ String, Whitespace
__all__ = ['IDLLexer']
class IDLLexer(RegexLexer): """ Pygments Lexer for IDL (Interactive Data Language). """ name = 'IDL' url = 'https://www.l3harrisgeospatial.com/Software-Technology/IDL' aliases = ['idl'] filenames = ['*.pro'] mimetypes = ['text/idl'] version_added = '1.6'
flags = re.IGNORECASE | re.MULTILINE
_RESERVED = ( 'and', 'begin', 'break', 'case', 'common', 'compile_opt', 'continue', 'do', 'else', 'end', 'endcase', 'endelse', 'endfor', 'endforeach', 'endif', 'endrep', 'endswitch', 'endwhile', 'eq', 'for', 'foreach', 'forward_function', 'function', 'ge', 'goto', 'gt', 'if', 'inherits', 'le', 'lt', 'mod', 'ne', 'not', 'of', 'on_ioerror', 'or', 'pro', 'repeat', 'switch', 'then', 'until', 'while', 'xor') """Reserved words from: http://www.exelisvis.com/docs/reswords.html"""
_BUILTIN_LIB = ( 'abs', 'acos', 'adapt_hist_equal', 'alog', 'alog10', 'amoeba', 'annotate', 'app_user_dir', 'app_user_dir_query', 'arg_present', 'array_equal', 'array_indices', 'arrow', 'ascii_template', 'asin', 'assoc', 'atan', 'axis', 'a_correlate', 'bandpass_filter', 'bandreject_filter', 'barplot', 'bar_plot', 'beseli', 'beselj', 'beselk', 'besely', 'beta', 'bilinear', 'binary_template', 'bindgen', 'binomial', 'bin_date', 'bit_ffs', 'bit_population', 'blas_axpy', 'blk_con', 'box_cursor', 'breakpoint', 'broyden', 'butterworth', 'bytarr', 'byte', 'byteorder', 'bytscl', 'caldat', 'calendar', 'call_external', 'call_function', 'call_method', 'call_procedure', 'canny', 'catch', 'cd', r'cdf_\w*', 'ceil', 'chebyshev', 'check_math', 'chisqr_cvf', 'chisqr_pdf', 'choldc', 'cholsol', 'cindgen', 'cir_3pnt', 'close', 'cluster', 'cluster_tree', 'clust_wts', 'cmyk_convert', 'colorbar', 'colorize_sample', 'colormap_applicable', 'colormap_gradient', 'colormap_rotation', 'colortable', 'color_convert', 'color_exchange', 'color_quan', 'color_range_map', 'comfit', 'command_line_args', 'complex', 'complexarr', 'complexround', 'compute_mesh_normals', 'cond', 'congrid', 'conj', 'constrained_min', 'contour', 'convert_coord', 'convol', 'convol_fft', 'coord2to3', 'copy_lun', 'correlate', 'cos', 'cosh', 'cpu', 'cramer', 'create_cursor', 'create_struct', 'create_view', 'crossp', 'crvlength', 'cti_test', 'ct_luminance', 'cursor', 'curvefit', 'cvttobm', 'cv_coord', 'cw_animate', 'cw_animate_getp', 'cw_animate_load', 'cw_animate_run', 'cw_arcball', 'cw_bgroup', 'cw_clr_index', 'cw_colorsel', 'cw_defroi', 'cw_field', 'cw_filesel', 'cw_form', 'cw_fslider', 'cw_light_editor', 'cw_light_editor_get', 'cw_light_editor_set', 'cw_orient', 'cw_palette_editor', 'cw_palette_editor_get', 'cw_palette_editor_set', 'cw_pdmenu', 'cw_rgbslider', 'cw_tmpl', 'cw_zoom', 'c_correlate', 'dblarr', 'db_exists', 'dcindgen', 'dcomplex', 'dcomplexarr', 'define_key', 'define_msgblk', 'define_msgblk_from_file', 'defroi', 'defsysv', 'delvar', 'dendrogram', 'dendro_plot', 'deriv', 'derivsig', 'determ', 'device', 'dfpmin', 'diag_matrix', 'dialog_dbconnect', 'dialog_message', 'dialog_pickfile', 'dialog_printersetup', 'dialog_printjob', 'dialog_read_image', 'dialog_write_image', 'digital_filter', 'dilate', 'dindgen', 'dissolve', 'dist', 'distance_measure', 'dlm_load', 'dlm_register', 'doc_library', 'double', 'draw_roi', 'edge_dog', 'efont', 'eigenql', 'eigenvec', 'ellipse', 'elmhes', 'emboss', 'empty', 'enable_sysrtn', 'eof', r'eos_\w*', 'erase', 'erf', 'erfc', 'erfcx', 'erode', 'errorplot', 'errplot', 'estimator_filter', 'execute', 'exit', 'exp', 'expand', 'expand_path', 'expint', 'extrac', 'extract_slice', 'factorial', 'fft', 'filepath', 'file_basename', 'file_chmod', 'file_copy', 'file_delete', 'file_dirname', 'file_expand_path', 'file_info', 'file_lines', 'file_link', 'file_mkdir', 'file_move', 'file_poll_input', 'file_readlink', 'file_same', 'file_search', 'file_test', 'file_which', 'findgen', 'finite', 'fix', 'flick', 'float', 'floor', 'flow3', 'fltarr', 'flush', 'format_axis_values', 'free_lun', 'fstat', 'fulstr', 'funct', 'fv_test', 'fx_root', 'fz_roots', 'f_cvf', 'f_pdf', 'gamma', 'gamma_ct', 'gauss2dfit', 'gaussfit', 'gaussian_function', 'gaussint', 'gauss_cvf', 'gauss_pdf', 'gauss_smooth', 'getenv', 'getwindows', 'get_drive_list', 'get_dxf_objects', 'get_kbrd', 'get_login_info', 'get_lun', 'get_screen_size', 'greg2jul', r'grib_\w*', 'grid3', 'griddata', 'grid_input', 'grid_tps', 'gs_iter', r'h5[adfgirst]_\w*', 'h5_browser', 'h5_close', 'h5_create', 'h5_get_libversion', 'h5_open', 'h5_parse', 'hanning', 'hash', r'hdf_\w*', 'heap_free', 'heap_gc', 'heap_nosave', 'heap_refcount', 'heap_save', 'help', 'hilbert', 'histogram', 'hist_2d', 'hist_equal', 'hls', 'hough', 'hqr', 'hsv', 'h_eq_ct', 'h_eq_int', 'i18n_multibytetoutf8', 'i18n_multibytetowidechar', 'i18n_utf8tomultibyte', 'i18n_widechartomultibyte', 'ibeta', 'icontour', 'iconvertcoord', 'idelete', 'identity', 'idlexbr_assistant', 'idlitsys_createtool', 'idl_base64', 'idl_validname', 'iellipse', 'igamma', 'igetcurrent', 'igetdata', 'igetid', 'igetproperty', 'iimage', 'image', 'image_cont', 'image_statistics', 'imaginary', 'imap', 'indgen', 'intarr', 'interpol', 'interpolate', 'interval_volume', 'int_2d', 'int_3d', 'int_tabulated', 'invert', 'ioctl', 'iopen', 'iplot', 'ipolygon', 'ipolyline', 'iputdata', 'iregister', 'ireset', 'iresolve', 'irotate', 'ir_filter', 'isa', 'isave', 'iscale', 'isetcurrent', 'isetproperty', 'ishft', 'isocontour', 'isosurface', 'isurface', 'itext', 'itranslate', 'ivector', 'ivolume', 'izoom', 'i_beta', 'journal', 'json_parse', 'json_serialize', 'jul2greg', 'julday', 'keyword_set', 'krig2d', 'kurtosis', 'kw_test', 'l64indgen', 'label_date', 'label_region', 'ladfit', 'laguerre', 'laplacian', 'la_choldc', 'la_cholmprove', 'la_cholsol', 'la_determ', 'la_eigenproblem', 'la_eigenql', 'la_eigenvec', 'la_elmhes', 'la_gm_linear_model', 'la_hqr', 'la_invert', 'la_least_squares', 'la_least_square_equality', 'la_linear_equation', 'la_ludc', 'la_lumprove', 'la_lusol', 'la_svd', 'la_tridc', 'la_trimprove', 'la_triql', 'la_trired', 'la_trisol', 'least_squares_filter', 'leefilt', 'legend', 'legendre', 'linbcg', 'lindgen', 'linfit', 'linkimage', 'list', 'll_arc_distance', 'lmfit', 'lmgr', 'lngamma', 'lnp_test', 'loadct', 'locale_get', 'logical_and', 'logical_or', 'logical_true', 'lon64arr', 'lonarr', 'long', 'long64', 'lsode', 'ludc', 'lumprove', 'lusol', 'lu_complex', 'machar', 'make_array', 'make_dll', 'make_rt', 'map', 'mapcontinents', 'mapgrid', 'map_2points', 'map_continents', 'map_grid', 'map_image', 'map_patch', 'map_proj_forward', 'map_proj_image', 'map_proj_info', 'map_proj_init', 'map_proj_inverse', 'map_set', 'matrix_multiply', 'matrix_power', 'max', 'md_test', 'mean', 'meanabsdev', 'mean_filter', 'median', 'memory', 'mesh_clip', 'mesh_decimate', 'mesh_issolid', 'mesh_merge', 'mesh_numtriangles', 'mesh_obj', 'mesh_smooth', 'mesh_surfacearea', 'mesh_validate', 'mesh_volume', 'message', 'min', 'min_curve_surf', 'mk_html_help', 'modifyct', 'moment', 'morph_close', 'morph_distance', 'morph_gradient', 'morph_hitormiss', 'morph_open', 'morph_thin', 'morph_tophat', 'multi', 'm_correlate', r'ncdf_\w*', 'newton', 'noise_hurl', 'noise_pick', 'noise_scatter', 'noise_slur', 'norm', 'n_elements', 'n_params', 'n_tags', 'objarr', 'obj_class', 'obj_destroy', 'obj_hasmethod', 'obj_isa', 'obj_new', 'obj_valid', 'online_help', 'on_error', 'open', 'oplot', 'oploterr', 'parse_url', 'particle_trace', 'path_cache', 'path_sep', 'pcomp', 'plot', 'plot3d', 'ploterr', 'plots', 'plot_3dbox', 'plot_field', 'pnt_line', 'point_lun', 'polarplot', 'polar_contour', 'polar_surface', 'poly', 'polyfill', 'polyfillv', 'polygon', 'polyline', 'polyshade', 'polywarp', 'poly_2d', 'poly_area', 'poly_fit', 'popd', 'powell', 'pref_commit', 'pref_get', 'pref_set', 'prewitt', 'primes', 'print', 'printd', 'product', 'profile', 'profiler', 'profiles', 'project_vol', 'psafm', 'pseudo', 'ps_show_fonts', 'ptrarr', 'ptr_free', 'ptr_new', 'ptr_valid', 'pushd', 'p_correlate', 'qgrid3', 'qhull', 'qromb', 'qromo', 'qsimp', 'query_ascii', 'query_bmp', 'query_csv', 'query_dicom', 'query_gif', 'query_image', 'query_jpeg', 'query_jpeg2000', 'query_mrsid', 'query_pict', 'query_png', 'query_ppm', 'query_srf', 'query_tiff', 'query_wav', 'radon', 'randomn', 'randomu', 'ranks', 'rdpix', 'read', 'reads', 'readu', 'read_ascii', 'read_binary', 'read_bmp', 'read_csv', 'read_dicom', 'read_gif', 'read_image', 'read_interfile', 'read_jpeg', 'read_jpeg2000', 'read_mrsid', 'read_pict', 'read_png', 'read_ppm', 'read_spr', 'read_srf', 'read_sylk', 'read_tiff', 'read_wav', 'read_wave', 'read_x11_bitmap', 'read_xwd', 'real_part', 'rebin', 'recall_commands', 'recon3', 'reduce_colors', 'reform', 'region_grow', 'register_cursor', 'regress', 'replicate', 'replicate_inplace', 'resolve_all', 'resolve_routine', 'restore', 'retall', 'return', 'reverse', 'rk4', 'roberts', 'rot', 'rotate', 'round', 'routine_filepath', 'routine_info', 'rs_test', 'r_correlate', 'r_test', 'save', 'savgol', 'scale3', 'scale3d', 'scope_level', 'scope_traceback', 'scope_varfetch', 'scope_varname', 'search2d', 'search3d', 'sem_create', 'sem_delete', 'sem_lock', 'sem_release', 'setenv', 'set_plot', 'set_shading', 'sfit', 'shade_surf', 'shade_surf_irr', 'shade_volume', 'shift', 'shift_diff', 'shmdebug', 'shmmap', 'shmunmap', 'shmvar', 'show3', 'showfont', 'simplex', 'sin', 'sindgen', 'sinh', 'size', 'skewness', 'skip_lun', 'slicer3', 'slide_image', 'smooth', 'sobel', 'socket', 'sort', 'spawn', 'spher_harm', 'sph_4pnt', 'sph_scat', 'spline', 'spline_p', 'spl_init', 'spl_interp', 'sprsab', 'sprsax', 'sprsin', 'sprstp', 'sqrt', 'standardize', 'stddev', 'stop', 'strarr', 'strcmp', 'strcompress', 'streamline', 'stregex', 'stretch', 'string', 'strjoin', 'strlen', 'strlowcase', 'strmatch', 'strmessage', 'strmid', 'strpos', 'strput', 'strsplit', 'strtrim', 'struct_assign', 'struct_hide', 'strupcase', 'surface', 'surfr', 'svdc', 'svdfit', 'svsol', 'swap_endian', 'swap_endian_inplace', 'symbol', 'systime', 's_test', 't3d', 'tag_names', 'tan', 'tanh', 'tek_color', 'temporary', 'tetra_clip', 'tetra_surface', 'tetra_volume', 'text', 'thin', 'threed', 'timegen', 'time_test2', 'tm_test', 'total', 'trace', 'transpose', 'triangulate', 'trigrid', 'triql', 'trired', 'trisol', 'tri_surf', 'truncate_lun', 'ts_coef', 'ts_diff', 'ts_fcast', 'ts_smooth', 'tv', 'tvcrs', 'tvlct', 'tvrd', 'tvscl', 'typename', 't_cvt', 't_pdf', 'uindgen', 'uint', 'uintarr', 'ul64indgen', 'ulindgen', 'ulon64arr', 'ulonarr', 'ulong', 'ulong64', 'uniq', 'unsharp_mask', 'usersym', 'value_locate', 'variance', 'vector', 'vector_field', 'vel', 'velovect', 'vert_t3d', 'voigt', 'voronoi', 'voxel_proj', 'wait', 'warp_tri', 'watershed', 'wdelete', 'wf_draw', 'where', 'widget_base', 'widget_button', 'widget_combobox', 'widget_control', 'widget_displaycontextmen', 'widget_draw', 'widget_droplist', 'widget_event', 'widget_info', 'widget_label', 'widget_list', 'widget_propertysheet', 'widget_slider', 'widget_tab', 'widget_table', 'widget_text', 'widget_tree', 'widget_tree_move', 'widget_window', 'wiener_filter', 'window', 'writeu', 'write_bmp', 'write_csv', 'write_gif', 'write_image', 'write_jpeg', 'write_jpeg2000', 'write_nrif', 'write_pict', 'write_png', 'write_ppm', 'write_spr', 'write_srf', 'write_sylk', 'write_tiff', 'write_wav', 'write_wave', 'wset', 'wshow', 'wtn', 'wv_applet', 'wv_cwt', 'wv_cw_wavelet', 'wv_denoise', 'wv_dwt', 'wv_fn_coiflet', 'wv_fn_daubechies', 'wv_fn_gaussian', 'wv_fn_haar', 'wv_fn_morlet', 'wv_fn_paul', 'wv_fn_symlet', 'wv_import_data', 'wv_import_wavelet', 'wv_plot3d_wps', 'wv_plot_multires', 'wv_pwt', 'wv_tool_denoise', 'xbm_edit', 'xdisplayfile', 'xdxf', 'xfont', 'xinteranimate', 'xloadct', 'xmanager', 'xmng_tmpl', 'xmtool', 'xobjview', 'xobjview_rotate', 'xobjview_write_image', 'xpalette', 'xpcolor', 'xplot3d', 'xregistered', 'xroi', 'xsq_test', 'xsurface', 'xvaredit', 'xvolume', 'xvolume_rotate', 'xvolume_write_image', 'xyouts', 'zoom', 'zoom_24') """Functions from: http://www.exelisvis.com/docs/routines-1.html"""
tokens = { 'root': [ (r'(^\s*)(;.*?)(\n)', bygroups(Whitespace, Comment.Single, Whitespace)), (words(_RESERVED, prefix=r'\b', suffix=r'\b'), Keyword), (words(_BUILTIN_LIB, prefix=r'\b', suffix=r'\b'), Name.Builtin), (r'\+=|-=|\^=|\*=|/=|#=|##=|<=|>=|=', Operator), (r'\+\+|--|->|\+|-|##|#|\*|/|<|>|&&|\^|~|\|\|\?|:', Operator), (r'\b(mod=|lt=|le=|eq=|ne=|ge=|gt=|not=|and=|or=|xor=)', Operator), (r'\b(mod|lt|le|eq|ne|ge|gt|not|and|or|xor)\b', Operator), (r'"[^\"]*"', String.Double), (r"'[^\']*'", String.Single), (r'\b[+\-]?([0-9]*\.[0-9]+|[0-9]+\.[0-9]*)(D|E)?([+\-]?[0-9]+)?\b', Number.Float), (r'\b\'[+\-]?[0-9A-F]+\'X(U?(S?|L{1,2})|B)\b', Number.Hex), (r'\b\'[+\-]?[0-7]+\'O(U?(S?|L{1,2})|B)\b', Number.Oct), (r'\b[+\-]?[0-9]+U?L{1,2}\b', Number.Integer.Long), (r'\b[+\-]?[0-9]+U?S?\b', Number.Integer), (r'\b[+\-]?[0-9]+B\b', Number), (r'[ \t]+', Whitespace), (r'\n', Whitespace), (r'.', Text), ] }
def analyse_text(text): """endelse seems to be unique to IDL, endswitch is rare at least.""" result = 0
if 'endelse' in text: result += 0.2 if 'endswitch' in text: result += 0.01
return result.cache/pip/http-v2/c/d/5/d/e/cd5de44b899cbe1869765c21b55cffc53c0c0ffa9d3c6f1fd40a42a2.bodyAdded+3
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/codeql.pyAdded+80
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/csound.pyAdded+466
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/css.pyAdded+632
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dalvik.pyAdded+126
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/data.pyAdded+763
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dax.pyAdded+135
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/devicetree.pyAdded+120
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/diff.pyAdded+169
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dns.pyAdded+109
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dotnet.pyAdded+873
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dsls.pyAdded+970
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/dylan.pyAdded+279
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/ecl.pyAdded+144
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/eiffel.pyAdded+68
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/elm.pyAdded+123
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/elpi.pyAdded+201
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/email.pyAdded+132
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/erlang.pyAdded+526
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/esoteric.pyAdded+300
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/ezhil.pyAdded+76
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/factor.pyAdded+363
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/fantom.pyAdded+251
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/felix.pyAdded+275
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/fift.pyAdded+68
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/floscript.pyAdded+81
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/forth.pyAdded+178
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/fortran.pyAdded+212
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/foxpro.pyAdded+427
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/freefem.pyAdded+893
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/func.pyAdded+110
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/functional.pyAdded+21
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/futhark.pyAdded+105
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gcodelexer.pyAdded+35
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gdscript.pyAdded+189
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gleam.pyAdded+74
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/go.pyAdded+97
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/grammar_notation.pyAdded+262
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graph.pyAdded+108
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graphics.pyAdded+794
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graphql.pyAdded+176
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/graphviz.pyAdded+58
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/gsql.pyAdded+103
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/hare.pyAdded+73
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/haskell.pyAdded+867
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/haxe.pyAdded+941
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/hdl.pyAdded+466
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/hexdump.pyAdded+102
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/html.pyAdded+670
.cache/uv/archive-v0/dduKQ1LodrYB4Bpm7LcBO/pygments/lexers/idl.pyAdded+284