scripting.py 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. """
  2. pygments.lexers.scripting
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Lexer for scripting and embedded languages.
  5. :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. from pygments.lexer import RegexLexer, include, bygroups, default, combined, \
  10. words
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation, Error, Whitespace, Other
  13. from pygments.util import get_bool_opt, get_list_opt
  14. __all__ = ['LuaLexer', 'LuauLexer', 'MoonScriptLexer', 'ChaiscriptLexer', 'LSLLexer',
  15. 'AppleScriptLexer', 'RexxLexer', 'MOOCodeLexer', 'HybrisLexer',
  16. 'EasytrieveLexer', 'JclLexer', 'MiniScriptLexer']
  17. def all_lua_builtins():
  18. from pygments.lexers._lua_builtins import MODULES
  19. return [w for values in MODULES.values() for w in values]
  20. class LuaLexer(RegexLexer):
  21. """
  22. For Lua source code.
  23. Additional options accepted:
  24. `func_name_highlighting`
  25. If given and ``True``, highlight builtin function names
  26. (default: ``True``).
  27. `disabled_modules`
  28. If given, must be a list of module names whose function names
  29. should not be highlighted. By default all modules are highlighted.
  30. To get a list of allowed modules have a look into the
  31. `_lua_builtins` module:
  32. .. sourcecode:: pycon
  33. >>> from pygments.lexers._lua_builtins import MODULES
  34. >>> MODULES.keys()
  35. ['string', 'coroutine', 'modules', 'io', 'basic', ...]
  36. """
  37. name = 'Lua'
  38. url = 'https://www.lua.org/'
  39. aliases = ['lua']
  40. filenames = ['*.lua', '*.wlua']
  41. mimetypes = ['text/x-lua', 'application/x-lua']
  42. version_added = ''
  43. _comment_multiline = r'(?:--\[(?P<level>=*)\[[\w\W]*?\](?P=level)\])'
  44. _comment_single = r'(?:--.*$)'
  45. _space = r'(?:\s+)'
  46. _s = rf'(?:{_comment_multiline}|{_comment_single}|{_space})'
  47. _name = r'(?:[^\W\d]\w*)'
  48. tokens = {
  49. 'root': [
  50. # Lua allows a file to start with a shebang.
  51. (r'#!.*', Comment.Preproc),
  52. default('base'),
  53. ],
  54. 'ws': [
  55. (_comment_multiline, Comment.Multiline),
  56. (_comment_single, Comment.Single),
  57. (_space, Whitespace),
  58. ],
  59. 'base': [
  60. include('ws'),
  61. (r'(?i)0x[\da-f]*(\.[\da-f]*)?(p[+-]?\d+)?', Number.Hex),
  62. (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
  63. (r'(?i)\d+e[+-]?\d+', Number.Float),
  64. (r'\d+', Number.Integer),
  65. # multiline strings
  66. (r'(?s)\[(=*)\[.*?\]\1\]', String),
  67. (r'::', Punctuation, 'label'),
  68. (r'\.{3}', Punctuation),
  69. (r'[=<>|~&+\-*/%#^]+|\.\.', Operator),
  70. (r'[\[\]{}().,:;]+', Punctuation),
  71. (r'(and|or|not)\b', Operator.Word),
  72. ('(break|do|else|elseif|end|for|if|in|repeat|return|then|until|'
  73. r'while)\b', Keyword.Reserved),
  74. (r'goto\b', Keyword.Reserved, 'goto'),
  75. (r'(local)\b', Keyword.Declaration),
  76. (r'(true|false|nil)\b', Keyword.Constant),
  77. (r'(function)\b', Keyword.Reserved, 'funcname'),
  78. (words(all_lua_builtins(), suffix=r"\b"), Name.Builtin),
  79. (fr'[A-Za-z_]\w*(?={_s}*[.:])', Name.Variable, 'varname'),
  80. (fr'[A-Za-z_]\w*(?={_s}*\()', Name.Function),
  81. (r'[A-Za-z_]\w*', Name.Variable),
  82. ("'", String.Single, combined('stringescape', 'sqs')),
  83. ('"', String.Double, combined('stringescape', 'dqs'))
  84. ],
  85. 'varname': [
  86. include('ws'),
  87. (r'\.\.', Operator, '#pop'),
  88. (r'[.:]', Punctuation),
  89. (rf'{_name}(?={_s}*[.:])', Name.Property),
  90. (rf'{_name}(?={_s}*\()', Name.Function, '#pop'),
  91. (_name, Name.Property, '#pop'),
  92. ],
  93. 'funcname': [
  94. include('ws'),
  95. (r'[.:]', Punctuation),
  96. (rf'{_name}(?={_s}*[.:])', Name.Class),
  97. (_name, Name.Function, '#pop'),
  98. # inline function
  99. (r'\(', Punctuation, '#pop'),
  100. ],
  101. 'goto': [
  102. include('ws'),
  103. (_name, Name.Label, '#pop'),
  104. ],
  105. 'label': [
  106. include('ws'),
  107. (r'::', Punctuation, '#pop'),
  108. (_name, Name.Label),
  109. ],
  110. 'stringescape': [
  111. (r'\\([abfnrtv\\"\']|[\r\n]{1,2}|z\s*|x[0-9a-fA-F]{2}|\d{1,3}|'
  112. r'u\{[0-9a-fA-F]+\})', String.Escape),
  113. ],
  114. 'sqs': [
  115. (r"'", String.Single, '#pop'),
  116. (r"[^\\']+", String.Single),
  117. ],
  118. 'dqs': [
  119. (r'"', String.Double, '#pop'),
  120. (r'[^\\"]+', String.Double),
  121. ]
  122. }
  123. def __init__(self, **options):
  124. self.func_name_highlighting = get_bool_opt(
  125. options, 'func_name_highlighting', True)
  126. self.disabled_modules = get_list_opt(options, 'disabled_modules', [])
  127. self._functions = set()
  128. if self.func_name_highlighting:
  129. from pygments.lexers._lua_builtins import MODULES
  130. for mod, func in MODULES.items():
  131. if mod not in self.disabled_modules:
  132. self._functions.update(func)
  133. RegexLexer.__init__(self, **options)
  134. def get_tokens_unprocessed(self, text):
  135. for index, token, value in \
  136. RegexLexer.get_tokens_unprocessed(self, text):
  137. if token is Name.Builtin and value not in self._functions:
  138. if '.' in value:
  139. a, b = value.split('.')
  140. yield index, Name, a
  141. yield index + len(a), Punctuation, '.'
  142. yield index + len(a) + 1, Name, b
  143. else:
  144. yield index, Name, value
  145. continue
  146. yield index, token, value
  147. def _luau_make_expression(should_pop, _s):
  148. temp_list = [
  149. (r'0[xX][\da-fA-F_]*', Number.Hex, '#pop'),
  150. (r'0[bB][\d_]*', Number.Bin, '#pop'),
  151. (r'\.?\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?[\d_]+)?', Number.Float, '#pop'),
  152. (words((
  153. 'true', 'false', 'nil'
  154. ), suffix=r'\b'), Keyword.Constant, '#pop'),
  155. (r'\[(=*)\[[.\n]*?\]\1\]', String, '#pop'),
  156. (r'(\.)([a-zA-Z_]\w*)(?=%s*[({"\'])', bygroups(Punctuation, Name.Function), '#pop'),
  157. (r'(\.)([a-zA-Z_]\w*)', bygroups(Punctuation, Name.Variable), '#pop'),
  158. (rf'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*(?={_s}*[({{"\'])', Name.Other, '#pop'),
  159. (r'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*', Name, '#pop'),
  160. ]
  161. if should_pop:
  162. return temp_list
  163. return [entry[:2] for entry in temp_list]
  164. def _luau_make_expression_special(should_pop):
  165. temp_list = [
  166. (r'\{', Punctuation, ('#pop', 'closing_brace_base', 'expression')),
  167. (r'\(', Punctuation, ('#pop', 'closing_parenthesis_base', 'expression')),
  168. (r'::?', Punctuation, ('#pop', 'type_end', 'type_start')),
  169. (r"'", String.Single, ('#pop', 'string_single')),
  170. (r'"', String.Double, ('#pop', 'string_double')),
  171. (r'`', String.Backtick, ('#pop', 'string_interpolated')),
  172. ]
  173. if should_pop:
  174. return temp_list
  175. return [(entry[0], entry[1], entry[2][1:]) for entry in temp_list]
  176. class LuauLexer(RegexLexer):
  177. """
  178. For Luau source code.
  179. Additional options accepted:
  180. `include_luau_builtins`
  181. If given and ``True``, automatically highlight Luau builtins
  182. (default: ``True``).
  183. `include_roblox_builtins`
  184. If given and ``True``, automatically highlight Roblox-specific builtins
  185. (default: ``False``).
  186. `additional_builtins`
  187. If given, must be a list of additional builtins to highlight.
  188. `disabled_builtins`
  189. If given, must be a list of builtins that will not be highlighted.
  190. """
  191. name = 'Luau'
  192. url = 'https://luau-lang.org/'
  193. aliases = ['luau']
  194. filenames = ['*.luau']
  195. version_added = '2.18'
  196. _comment_multiline = r'(?:--\[(?P<level>=*)\[[\w\W]*?\](?P=level)\])'
  197. _comment_single = r'(?:--.*$)'
  198. _s = r'(?:{}|{}|{})'.format(_comment_multiline, _comment_single, r'\s+')
  199. tokens = {
  200. 'root': [
  201. (r'#!.*', Comment.Hashbang, 'base'),
  202. default('base'),
  203. ],
  204. 'ws': [
  205. (_comment_multiline, Comment.Multiline),
  206. (_comment_single, Comment.Single),
  207. (r'\s+', Whitespace),
  208. ],
  209. 'base': [
  210. include('ws'),
  211. *_luau_make_expression_special(False),
  212. (r'\.\.\.', Punctuation),
  213. (rf'type\b(?={_s}+[a-zA-Z_])', Keyword.Reserved, 'type_declaration'),
  214. (rf'export\b(?={_s}+[a-zA-Z_])', Keyword.Reserved),
  215. (r'(?:\.\.|//|[+\-*\/%^<>=])=?', Operator, 'expression'),
  216. (r'~=', Operator, 'expression'),
  217. (words((
  218. 'and', 'or', 'not'
  219. ), suffix=r'\b'), Operator.Word, 'expression'),
  220. (words((
  221. 'elseif', 'for', 'if', 'in', 'repeat', 'return', 'until',
  222. 'while'), suffix=r'\b'), Keyword.Reserved, 'expression'),
  223. (r'local\b', Keyword.Declaration, 'expression'),
  224. (r'function\b', Keyword.Reserved, ('expression', 'func_name')),
  225. (r'[\])};]+', Punctuation),
  226. include('expression_static'),
  227. *_luau_make_expression(False, _s),
  228. (r'[\[.,]', Punctuation, 'expression'),
  229. ],
  230. 'expression_static': [
  231. (words((
  232. 'break', 'continue', 'do', 'else', 'elseif', 'end', 'for',
  233. 'if', 'in', 'repeat', 'return', 'then', 'until', 'while'),
  234. suffix=r'\b'), Keyword.Reserved),
  235. ],
  236. 'expression': [
  237. include('ws'),
  238. (r'if\b', Keyword.Reserved, ('ternary', 'expression')),
  239. (r'local\b', Keyword.Declaration),
  240. *_luau_make_expression_special(True),
  241. (r'\.\.\.', Punctuation, '#pop'),
  242. (r'function\b', Keyword.Reserved, 'func_name'),
  243. include('expression_static'),
  244. *_luau_make_expression(True, _s),
  245. default('#pop'),
  246. ],
  247. 'ternary': [
  248. include('ws'),
  249. (r'else\b', Keyword.Reserved, '#pop'),
  250. (words((
  251. 'then', 'elseif',
  252. ), suffix=r'\b'), Operator.Reserved, 'expression'),
  253. default('#pop'),
  254. ],
  255. 'closing_brace_pop': [
  256. (r'\}', Punctuation, '#pop'),
  257. ],
  258. 'closing_parenthesis_pop': [
  259. (r'\)', Punctuation, '#pop'),
  260. ],
  261. 'closing_gt_pop': [
  262. (r'>', Punctuation, '#pop'),
  263. ],
  264. 'closing_parenthesis_base': [
  265. include('closing_parenthesis_pop'),
  266. include('base'),
  267. ],
  268. 'closing_parenthesis_type': [
  269. include('closing_parenthesis_pop'),
  270. include('type'),
  271. ],
  272. 'closing_brace_base': [
  273. include('closing_brace_pop'),
  274. include('base'),
  275. ],
  276. 'closing_brace_type': [
  277. include('closing_brace_pop'),
  278. include('type'),
  279. ],
  280. 'closing_gt_type': [
  281. include('closing_gt_pop'),
  282. include('type'),
  283. ],
  284. 'string_escape': [
  285. (r'\\z\s*', String.Escape),
  286. (r'\\(?:[abfnrtvz\\"\'`\{\n])|[\r\n]{1,2}|x[\da-fA-F]{2}|\d{1,3}|'
  287. r'u\{\}[\da-fA-F]*\}', String.Escape),
  288. ],
  289. 'string_single': [
  290. include('string_escape'),
  291. (r"'", String.Single, "#pop"),
  292. (r"[^\\']+", String.Single),
  293. ],
  294. 'string_double': [
  295. include('string_escape'),
  296. (r'"', String.Double, "#pop"),
  297. (r'[^\\"]+', String.Double),
  298. ],
  299. 'string_interpolated': [
  300. include('string_escape'),
  301. (r'\{', Punctuation, ('closing_brace_base', 'expression')),
  302. (r'`', String.Backtick, "#pop"),
  303. (r'[^\\`\{]+', String.Backtick),
  304. ],
  305. 'func_name': [
  306. include('ws'),
  307. (r'[.:]', Punctuation),
  308. (rf'[a-zA-Z_]\w*(?={_s}*[.:])', Name.Class),
  309. (r'[a-zA-Z_]\w*', Name.Function),
  310. (r'<', Punctuation, 'closing_gt_type'),
  311. (r'\(', Punctuation, '#pop'),
  312. ],
  313. 'type': [
  314. include('ws'),
  315. (r'\(', Punctuation, 'closing_parenthesis_type'),
  316. (r'\{', Punctuation, 'closing_brace_type'),
  317. (r'<', Punctuation, 'closing_gt_type'),
  318. (r"'", String.Single, 'string_single'),
  319. (r'"', String.Double, 'string_double'),
  320. (r'[|&\.,\[\]:=]+', Punctuation),
  321. (r'->', Punctuation),
  322. (r'typeof\(', Name.Builtin, ('closing_parenthesis_base',
  323. 'expression')),
  324. (r'[a-zA-Z_]\w*', Name.Class),
  325. ],
  326. 'type_start': [
  327. include('ws'),
  328. (r'\(', Punctuation, ('#pop', 'closing_parenthesis_type')),
  329. (r'\{', Punctuation, ('#pop', 'closing_brace_type')),
  330. (r'<', Punctuation, ('#pop', 'closing_gt_type')),
  331. (r"'", String.Single, ('#pop', 'string_single')),
  332. (r'"', String.Double, ('#pop', 'string_double')),
  333. (r'typeof\(', Name.Builtin, ('#pop', 'closing_parenthesis_base',
  334. 'expression')),
  335. (r'[a-zA-Z_]\w*', Name.Class, '#pop'),
  336. ],
  337. 'type_end': [
  338. include('ws'),
  339. (r'[|&\.]', Punctuation, 'type_start'),
  340. (r'->', Punctuation, 'type_start'),
  341. (r'<', Punctuation, 'closing_gt_type'),
  342. default('#pop'),
  343. ],
  344. 'type_declaration': [
  345. include('ws'),
  346. (r'[a-zA-Z_]\w*', Name.Class),
  347. (r'<', Punctuation, 'closing_gt_type'),
  348. (r'=', Punctuation, ('#pop', 'type_end', 'type_start')),
  349. ],
  350. }
  351. def __init__(self, **options):
  352. self.include_luau_builtins = get_bool_opt(
  353. options, 'include_luau_builtins', True)
  354. self.include_roblox_builtins = get_bool_opt(
  355. options, 'include_roblox_builtins', False)
  356. self.additional_builtins = get_list_opt(options, 'additional_builtins', [])
  357. self.disabled_builtins = get_list_opt(options, 'disabled_builtins', [])
  358. self._builtins = set(self.additional_builtins)
  359. if self.include_luau_builtins:
  360. from pygments.lexers._luau_builtins import LUAU_BUILTINS
  361. self._builtins.update(LUAU_BUILTINS)
  362. if self.include_roblox_builtins:
  363. from pygments.lexers._luau_builtins import ROBLOX_BUILTINS
  364. self._builtins.update(ROBLOX_BUILTINS)
  365. if self.additional_builtins:
  366. self._builtins.update(self.additional_builtins)
  367. self._builtins.difference_update(self.disabled_builtins)
  368. RegexLexer.__init__(self, **options)
  369. def get_tokens_unprocessed(self, text):
  370. for index, token, value in \
  371. RegexLexer.get_tokens_unprocessed(self, text):
  372. if token is Name or token is Name.Other:
  373. split_value = value.split('.')
  374. complete_value = []
  375. new_index = index
  376. for position in range(len(split_value), 0, -1):
  377. potential_string = '.'.join(split_value[:position])
  378. if potential_string in self._builtins:
  379. yield index, Name.Builtin, potential_string
  380. new_index += len(potential_string)
  381. if complete_value:
  382. yield new_index, Punctuation, '.'
  383. new_index += 1
  384. break
  385. complete_value.insert(0, split_value[position - 1])
  386. for position, substring in enumerate(complete_value):
  387. if position + 1 == len(complete_value):
  388. if token is Name:
  389. yield new_index, Name.Variable, substring
  390. continue
  391. yield new_index, Name.Function, substring
  392. continue
  393. yield new_index, Name.Variable, substring
  394. new_index += len(substring)
  395. yield new_index, Punctuation, '.'
  396. new_index += 1
  397. continue
  398. yield index, token, value
  399. class MoonScriptLexer(LuaLexer):
  400. """
  401. For MoonScript source code.
  402. """
  403. name = 'MoonScript'
  404. url = 'http://moonscript.org'
  405. aliases = ['moonscript', 'moon']
  406. filenames = ['*.moon']
  407. mimetypes = ['text/x-moonscript', 'application/x-moonscript']
  408. version_added = '1.5'
  409. tokens = {
  410. 'root': [
  411. (r'#!(.*?)$', Comment.Preproc),
  412. default('base'),
  413. ],
  414. 'base': [
  415. ('--.*$', Comment.Single),
  416. (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
  417. (r'(?i)\d+e[+-]?\d+', Number.Float),
  418. (r'(?i)0x[0-9a-f]*', Number.Hex),
  419. (r'\d+', Number.Integer),
  420. (r'\n', Whitespace),
  421. (r'[^\S\n]+', Text),
  422. (r'(?s)\[(=*)\[.*?\]\1\]', String),
  423. (r'(->|=>)', Name.Function),
  424. (r':[a-zA-Z_]\w*', Name.Variable),
  425. (r'(==|!=|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#!.\\:])', Operator),
  426. (r'[;,]', Punctuation),
  427. (r'[\[\]{}()]', Keyword.Type),
  428. (r'[a-zA-Z_]\w*:', Name.Variable),
  429. (words((
  430. 'class', 'extends', 'if', 'then', 'super', 'do', 'with',
  431. 'import', 'export', 'while', 'elseif', 'return', 'for', 'in',
  432. 'from', 'when', 'using', 'else', 'and', 'or', 'not', 'switch',
  433. 'break'), suffix=r'\b'),
  434. Keyword),
  435. (r'(true|false|nil)\b', Keyword.Constant),
  436. (r'(and|or|not)\b', Operator.Word),
  437. (r'(self)\b', Name.Builtin.Pseudo),
  438. (r'@@?([a-zA-Z_]\w*)?', Name.Variable.Class),
  439. (r'[A-Z]\w*', Name.Class), # proper name
  440. (words(all_lua_builtins(), suffix=r"\b"), Name.Builtin),
  441. (r'[A-Za-z_]\w*', Name),
  442. ("'", String.Single, combined('stringescape', 'sqs')),
  443. ('"', String.Double, combined('stringescape', 'dqs'))
  444. ],
  445. 'stringescape': [
  446. (r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
  447. ],
  448. 'sqs': [
  449. ("'", String.Single, '#pop'),
  450. ("[^']+", String)
  451. ],
  452. 'dqs': [
  453. ('"', String.Double, '#pop'),
  454. ('[^"]+', String)
  455. ]
  456. }
  457. def get_tokens_unprocessed(self, text):
  458. # set . as Operator instead of Punctuation
  459. for index, token, value in LuaLexer.get_tokens_unprocessed(self, text):
  460. if token == Punctuation and value == ".":
  461. token = Operator
  462. yield index, token, value
  463. class ChaiscriptLexer(RegexLexer):
  464. """
  465. For ChaiScript source code.
  466. """
  467. name = 'ChaiScript'
  468. url = 'http://chaiscript.com/'
  469. aliases = ['chaiscript', 'chai']
  470. filenames = ['*.chai']
  471. mimetypes = ['text/x-chaiscript', 'application/x-chaiscript']
  472. version_added = '2.0'
  473. flags = re.DOTALL | re.MULTILINE
  474. tokens = {
  475. 'commentsandwhitespace': [
  476. (r'\s+', Text),
  477. (r'//.*?\n', Comment.Single),
  478. (r'/\*.*?\*/', Comment.Multiline),
  479. (r'^\#.*?\n', Comment.Single)
  480. ],
  481. 'slashstartsregex': [
  482. include('commentsandwhitespace'),
  483. (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
  484. r'([gim]+\b|\B)', String.Regex, '#pop'),
  485. (r'(?=/)', Text, ('#pop', 'badregex')),
  486. default('#pop')
  487. ],
  488. 'badregex': [
  489. (r'\n', Text, '#pop')
  490. ],
  491. 'root': [
  492. include('commentsandwhitespace'),
  493. (r'\n', Text),
  494. (r'[^\S\n]+', Text),
  495. (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|\.\.'
  496. r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'),
  497. (r'[{(\[;,]', Punctuation, 'slashstartsregex'),
  498. (r'[})\].]', Punctuation),
  499. (r'[=+\-*/]', Operator),
  500. (r'(for|in|while|do|break|return|continue|if|else|'
  501. r'throw|try|catch'
  502. r')\b', Keyword, 'slashstartsregex'),
  503. (r'(var)\b', Keyword.Declaration, 'slashstartsregex'),
  504. (r'(attr|def|fun)\b', Keyword.Reserved),
  505. (r'(true|false)\b', Keyword.Constant),
  506. (r'(eval|throw)\b', Name.Builtin),
  507. (r'`\S+`', Name.Builtin),
  508. (r'[$a-zA-Z_]\w*', Name.Other),
  509. (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
  510. (r'0x[0-9a-fA-F]+', Number.Hex),
  511. (r'[0-9]+', Number.Integer),
  512. (r'"', String.Double, 'dqstring'),
  513. (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
  514. ],
  515. 'dqstring': [
  516. (r'\$\{[^"}]+?\}', String.Interpol),
  517. (r'\$', String.Double),
  518. (r'\\\\', String.Double),
  519. (r'\\"', String.Double),
  520. (r'[^\\"$]+', String.Double),
  521. (r'"', String.Double, '#pop'),
  522. ],
  523. }
  524. class LSLLexer(RegexLexer):
  525. """
  526. For Second Life's Linden Scripting Language source code.
  527. """
  528. name = 'LSL'
  529. aliases = ['lsl']
  530. filenames = ['*.lsl']
  531. mimetypes = ['text/x-lsl']
  532. url = 'https://wiki.secondlife.com/wiki/Linden_Scripting_Language'
  533. version_added = '2.0'
  534. flags = re.MULTILINE
  535. lsl_keywords = r'\b(?:do|else|for|if|jump|return|while)\b'
  536. lsl_types = r'\b(?:float|integer|key|list|quaternion|rotation|string|vector)\b'
  537. lsl_states = r'\b(?:(?:state)\s+\w+|default)\b'
  538. lsl_events = r'\b(?:state_(?:entry|exit)|touch(?:_(?:start|end))?|(?:land_)?collision(?:_(?:start|end))?|timer|listen|(?:no_)?sensor|control|(?:not_)?at_(?:rot_)?target|money|email|run_time_permissions|changed|attach|dataserver|moving_(?:start|end)|link_message|(?:on|object)_rez|remote_data|http_re(?:sponse|quest)|path_update|transaction_result)\b'
  539. lsl_functions_builtin = r'\b(?:ll(?:ReturnObjectsBy(?:ID|Owner)|Json(?:2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(?:Mag|Norm|Dist)|Rot(?:Between|2(?:Euler|Fwd|Left|Up))|(?:Euler|Axes)2Rot|Whisper|(?:Region|Owner)?Say|Shout|Listen(?:Control|Remove)?|Sensor(?:Repeat|Remove)?|Detected(?:Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|(?:[GS]et)(?:AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(?:Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(?:Scale|Offset|Rotate)Texture|(?:Rot)?Target(?:Remove)?|(?:Stop)?MoveToTarget|Apply(?:Rotational)?Impulse|Set(?:KeyframedMotion|ContentType|RegionPos|(?:Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(?:Queueing|Radius)|Vehicle(?:Type|(?:Float|Vector|Rotation)Param)|(?:Touch|Sit)?Text|Camera(?:Eye|At)Offset|PrimitiveParams|ClickAction|Link(?:Alpha|Color|PrimitiveParams(?:Fast)?|Texture(?:Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get(?:(?:Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(?:PrimitiveParams|Number(?:OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(?:Details|PermMask|PrimCount)|Parcel(?:MaxPrims|Details|Prim(?:Count|Owners))|Attached|(?:SPMax|Free|Used)Memory|Region(?:Name|TimeDilation|FPS|Corner|AgentCount)|Root(?:Position|Rotation)|UnixTime|(?:Parcel|Region)Flags|(?:Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(?:Prims|NotecardLines|Sides)|Animation(?:List)?|(?:Camera|Local)(?:Pos|Rot)|Vel|Accel|Omega|Time(?:stamp|OfDay)|(?:Object|CenterOf)?Mass|MassMKS|Energy|Owner|(?:Owner)?Key|SunDirection|Texture(?:Offset|Scale|Rot)|Inventory(?:Number|Name|Key|Type|Creator|PermMask)|Permissions(?:Key)?|StartParameter|List(?:Length|EntryType)|Date|Agent(?:Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(?:Name|State))|(?:Get|Reset|GetAndReset)Time|PlaySound(?:Slave)?|LoopSound(?:Master|Slave)?|(?:Trigger|Stop|Preload)Sound|(?:(?:Get|Delete)Sub|Insert)String|To(?:Upper|Lower)|Give(?:InventoryList|Money)|RezObject|(?:Stop)?LookAt|Sleep|CollisionFilter|(?:Take|Release)Controls|DetachFromAvatar|AttachToAvatar(?:Temp)?|InstantMessage|(?:GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(?:Length|Trim)|(?:Start|Stop)Animation|TargetOmega|RequestPermissions|(?:Create|Break)Link|BreakAllLinks|(?:Give|Remove)Inventory|Water|PassTouches|Request(?:Agent|Inventory)Data|TeleportAgent(?:Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(?:Axis|Angle)|A(?:cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(?:CSV|Integer|Json|Float|String|Key|Vector|Rot|List(?:Strided)?)|DeleteSubList|List(?:Statistics|Sort|Randomize|(?:Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(?:CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(?:Slope|Normal|Contour)|GroundRepel|(?:Set|Remove)VehicleFlags|(?:AvatarOn)?(?:Link)?SitTarget|Script(?:Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(?:Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(?:Integer|String)ToBase64|XorBase64|Log(?:10)?|Base64To(?:String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(?:Load|Release|(?:E|Une)scape)URL|ParcelMedia(?:CommandList|Query)|ModPow|MapDestination|(?:RemoveFrom|AddTo|Reset)Land(?:Pass|Ban)List|(?:Set|Clear)CameraParams|HTTP(?:Request|Response)|TextBox|DetectedTouch(?:UV|Face|Pos|(?:N|Bin)ormal|ST)|(?:MD5|SHA1|DumpList2)String|Request(?:Secure)?URL|Clear(?:Prim|Link)Media|(?:Link)?ParticleSystem|(?:Get|Request)(?:Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(?:Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\b'
  540. lsl_constants_float = r'\b(?:DEG_TO_RAD|PI(?:_BY_TWO)?|RAD_TO_DEG|SQRT2|TWO_PI)\b'
  541. lsl_constants_integer = r'\b(?:JSON_APPEND|STATUS_(?:PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(?:_OBJECT)?|(?:DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(?:FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(?:_(?:BY_(?:LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(?:PARCEL(?:_OWNER)?|REGION)))?|CAMERA_(?:PITCH|DISTANCE|BEHINDNESS_(?:ANGLE|LAG)|(?:FOCUS|POSITION)(?:_(?:THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(?:ROOT|SET|ALL_(?:OTHERS|CHILDREN)|THIS)|ACTIVE|PASSIVE|SCRIPTED|CONTROL_(?:FWD|BACK|(?:ROT_)?(?:LEFT|RIGHT)|UP|DOWN|(?:ML_)?LBUTTON)|PERMISSION_(?:RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(?:CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(?:TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(?:INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(?:_START)?|TELEPORT|MEDIA)|OBJECT_(?:(?:PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_ON_REZ|NAME|DESC|POS|PRIM_EQUIVALENCE|RETURN_(?:PARCEL(?:_OWNER)?|REGION)|ROO?T|VELOCITY|OWNER|GROUP|CREATOR|ATTACHED_POINT|RENDER_WEIGHT|PATHFINDING_TYPE|(?:RUNNING|TOTAL)_SCRIPT_COUNT|SCRIPT_(?:MEMORY|TIME))|TYPE_(?:INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(?:DEBUG|PUBLIC)_CHANNEL|ATTACH_(?:AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](?:SHOULDER|HAND|FOOT|EAR|EYE|[UL](?:ARM|LEG)|HIP)|(?:LEFT|RIGHT)_PEC|HUD_(?:CENTER_[12]|TOP_(?:RIGHT|CENTER|LEFT)|BOTTOM(?:_(?:RIGHT|LEFT))?))|LAND_(?:LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(?:ONLINE|NAME|BORN|SIM_(?:POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(?:ON_FILE|USED)|REMOTE_DATA_(?:CHANNEL|REQUEST|REPLY)|PSYS_(?:PART_(?:BF_(?:ZERO|ONE(?:_MINUS_(?:DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(?:START|END)_(?:COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(?:RIBBON|WIND|INTERP_(?:COLOR|SCALE)|BOUNCE|FOLLOW_(?:SRC|VELOCITY)|TARGET_(?:POS|LINEAR)|EMISSIVE)_MASK)|SRC_(?:MAX_AGE|PATTERN|ANGLE_(?:BEGIN|END)|BURST_(?:RATE|PART_COUNT|RADIUS|SPEED_(?:MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(?:DROP|EXPLODE|ANGLE(?:_CONE(?:_EMPTY)?)?)))|VEHICLE_(?:REFERENCE_FRAME|TYPE_(?:NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(?:LINEAR|ANGULAR)_(?:FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(?:HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(?:LINEAR|ANGULAR)_(?:DEFLECTION_(?:EFFICIENCY|TIMESCALE)|MOTOR_(?:DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(?:EFFICIENCY|TIMESCALE)|BANKING_(?:EFFICIENCY|MIX|TIMESCALE)|FLAG_(?:NO_DEFLECTION_UP|LIMIT_(?:ROLL_ONLY|MOTOR_UP)|HOVER_(?:(?:WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(?:STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(?:TYPE(?:_(?:BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(?:DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(?:_(?:STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(?:NONE|LOW|MEDIUM|HIGH)|BUMP_(?:NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(?:DEFAULT|PLANAR)|SCULPT_(?:TYPE_(?:SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(?:MIRROR|INVERT))|PHYSICS(?:_(?:SHAPE_(?:CONVEX|NONE|PRIM|TYPE)))?|(?:POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(?:ALT_IMAGE_ENABLE|CONTROLS|(?:CURRENT|HOME)_URL|AUTO_(?:LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(?:WIDTH|HEIGHT)_PIXELS|WHITELIST(?:_ENABLE)?|PERMS_(?:INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(?:STANDARD|MINI)|PERM_(?:NONE|OWNER|GROUP|ANYONE)|MAX_(?:URL_LENGTH|WHITELIST_(?:SIZE|COUNT)|(?:WIDTH|HEIGHT)_PIXELS)))|MASK_(?:BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(?:TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(?:MEDIA_COMMAND_(?:STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(?:ALLOW_(?:FLY|(?:GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(?:GROUP_)?OBJECTS)|USE_(?:ACCESS_(?:GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(?:GROUP|ALL)_OBJECT_ENTRY)|COUNT_(?:TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(?:NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(?:MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(?:_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(?:HIDE|DEFAULT)|REGION_FLAG_(?:ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(?:COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(?:METHOD|MIMETYPE|BODY_(?:MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|STRING_(?:TRIM(?:_(?:HEAD|TAIL))?)|CLICK_ACTION_(?:NONE|TOUCH|SIT|BUY|PAY|OPEN(?:_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(?:NONE|SCRIPT_MEMORY)|RC_(?:DATA_FLAGS|DETECT_PHANTOM|GET_(?:LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(?:TYPES|AGENTS|(?:NON)?PHYSICAL|LAND))|RCERR_(?:CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(?:ALLOWED_(?:AGENT|GROUP)_(?:ADD|REMOVE)|BANNED_AGENT_(?:ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(?:COMMAND|CMD_(?:PLAY|STOP|PAUSE|SET_MODE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(?:GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(?:CMD_(?:(?:SMOOTH_)?STOP|JUMP)|DESIRED_(?:TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(?:_(?:[A-D]|NONE))?|MAX_(?:DECEL|TURN_RADIUS|(?:ACCEL|SPEED)))|PURSUIT_(?:OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(?:CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(?:EVADE_(?:HIDDEN|SPOTTED)|FAILURE_(?:DYNAMIC_PATHFINDING_DISABLED|INVALID_(?:GOAL|START)|NO_(?:NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(?:PARCEL_)?UNREACHABLE)|(?:GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(?:_(?:FAST|NONE|SLOW))?|CONTENT_TYPE_(?:ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(?:RADIUS|STATIC)|(?:PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(?:AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\b'
  542. lsl_constants_integer_boolean = r'\b(?:FALSE|TRUE)\b'
  543. lsl_constants_rotation = r'\b(?:ZERO_ROTATION)\b'
  544. lsl_constants_string = r'\b(?:EOF|JSON_(?:ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(?:BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(?:GRANTED|DENIED))\b'
  545. lsl_constants_vector = r'\b(?:TOUCH_INVALID_(?:TEXCOORD|VECTOR)|ZERO_VECTOR)\b'
  546. lsl_invalid_broken = r'\b(?:LAND_(?:LARGE|MEDIUM|SMALL)_BRUSH)\b'
  547. lsl_invalid_deprecated = r'\b(?:ATTACH_[LR]PEC|DATA_RATING|OBJECT_ATTACHMENT_(?:GEOMETRY_BYTES|SURFACE_AREA)|PRIM_(?:CAST_SHADOWS|MATERIAL_LIGHT|TYPE_LEGACY)|PSYS_SRC_(?:INNER|OUTER)ANGLE|VEHICLE_FLAG_NO_FLY_UP|ll(?:Cloud|Make(?:Explosion|Fountain|Smoke|Fire)|RemoteDataSetRegion|Sound(?:Preload)?|XorBase64Strings(?:Correct)?))\b'
  548. lsl_invalid_illegal = r'\b(?:event)\b'
  549. lsl_invalid_unimplemented = r'\b(?:CHARACTER_(?:MAX_ANGULAR_(?:ACCEL|SPEED)|TURN_SPEED_MULTIPLIER)|PERMISSION_(?:CHANGE_(?:JOINTS|PERMISSIONS)|RELEASE_OWNERSHIP|REMAP_CONTROLS)|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|ll(?:CollisionSprite|(?:Stop)?PointAt|(?:(?:Refresh|Set)Prim)URL|(?:Take|Release)Camera|RemoteLoadScript))\b'
  550. lsl_reserved_godmode = r'\b(?:ll(?:GodLikeRezObject|Set(?:Inventory|Object)PermMask))\b'
  551. lsl_reserved_log = r'\b(?:print)\b'
  552. lsl_operators = r'\+\+|\-\-|<<|>>|&&?|\|\|?|\^|~|[!%<>=*+\-/]=?'
  553. tokens = {
  554. 'root':
  555. [
  556. (r'//.*?\n', Comment.Single),
  557. (r'/\*', Comment.Multiline, 'comment'),
  558. (r'"', String.Double, 'string'),
  559. (lsl_keywords, Keyword),
  560. (lsl_types, Keyword.Type),
  561. (lsl_states, Name.Class),
  562. (lsl_events, Name.Builtin),
  563. (lsl_functions_builtin, Name.Function),
  564. (lsl_constants_float, Keyword.Constant),
  565. (lsl_constants_integer, Keyword.Constant),
  566. (lsl_constants_integer_boolean, Keyword.Constant),
  567. (lsl_constants_rotation, Keyword.Constant),
  568. (lsl_constants_string, Keyword.Constant),
  569. (lsl_constants_vector, Keyword.Constant),
  570. (lsl_invalid_broken, Error),
  571. (lsl_invalid_deprecated, Error),
  572. (lsl_invalid_illegal, Error),
  573. (lsl_invalid_unimplemented, Error),
  574. (lsl_reserved_godmode, Keyword.Reserved),
  575. (lsl_reserved_log, Keyword.Reserved),
  576. (r'\b([a-zA-Z_]\w*)\b', Name.Variable),
  577. (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d*', Number.Float),
  578. (r'(\d+\.\d*|\.\d+)', Number.Float),
  579. (r'0[xX][0-9a-fA-F]+', Number.Hex),
  580. (r'\d+', Number.Integer),
  581. (lsl_operators, Operator),
  582. (r':=?', Error),
  583. (r'[,;{}()\[\]]', Punctuation),
  584. (r'\n+', Whitespace),
  585. (r'\s+', Whitespace)
  586. ],
  587. 'comment':
  588. [
  589. (r'[^*/]+', Comment.Multiline),
  590. (r'/\*', Comment.Multiline, '#push'),
  591. (r'\*/', Comment.Multiline, '#pop'),
  592. (r'[*/]', Comment.Multiline)
  593. ],
  594. 'string':
  595. [
  596. (r'\\([nt"\\])', String.Escape),
  597. (r'"', String.Double, '#pop'),
  598. (r'\\.', Error),
  599. (r'[^"\\]+', String.Double),
  600. ]
  601. }
  602. class AppleScriptLexer(RegexLexer):
  603. """
  604. For AppleScript source code,
  605. including `AppleScript Studio
  606. <http://developer.apple.com/documentation/AppleScript/
  607. Reference/StudioReference>`_.
  608. Contributed by Andreas Amann <aamann@mac.com>.
  609. """
  610. name = 'AppleScript'
  611. url = 'https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html'
  612. aliases = ['applescript']
  613. filenames = ['*.applescript']
  614. version_added = '1.0'
  615. flags = re.MULTILINE | re.DOTALL
  616. Identifiers = r'[a-zA-Z]\w*'
  617. # XXX: use words() for all of these
  618. Literals = ('AppleScript', 'current application', 'false', 'linefeed',
  619. 'missing value', 'pi', 'quote', 'result', 'return', 'space',
  620. 'tab', 'text item delimiters', 'true', 'version')
  621. Classes = ('alias ', 'application ', 'boolean ', 'class ', 'constant ',
  622. 'date ', 'file ', 'integer ', 'list ', 'number ', 'POSIX file ',
  623. 'real ', 'record ', 'reference ', 'RGB color ', 'script ',
  624. 'text ', 'unit types', '(?:Unicode )?text', 'string')
  625. BuiltIn = ('attachment', 'attribute run', 'character', 'day', 'month',
  626. 'paragraph', 'word', 'year')
  627. HandlerParams = ('about', 'above', 'against', 'apart from', 'around',
  628. 'aside from', 'at', 'below', 'beneath', 'beside',
  629. 'between', 'for', 'given', 'instead of', 'on', 'onto',
  630. 'out of', 'over', 'since')
  631. Commands = ('ASCII (character|number)', 'activate', 'beep', 'choose URL',
  632. 'choose application', 'choose color', 'choose file( name)?',
  633. 'choose folder', 'choose from list',
  634. 'choose remote application', 'clipboard info',
  635. 'close( access)?', 'copy', 'count', 'current date', 'delay',
  636. 'delete', 'display (alert|dialog)', 'do shell script',
  637. 'duplicate', 'exists', 'get eof', 'get volume settings',
  638. 'info for', 'launch', 'list (disks|folder)', 'load script',
  639. 'log', 'make', 'mount volume', 'new', 'offset',
  640. 'open( (for access|location))?', 'path to', 'print', 'quit',
  641. 'random number', 'read', 'round', 'run( script)?',
  642. 'say', 'scripting components',
  643. 'set (eof|the clipboard to|volume)', 'store script',
  644. 'summarize', 'system attribute', 'system info',
  645. 'the clipboard', 'time to GMT', 'write', 'quoted form')
  646. References = ('(in )?back of', '(in )?front of', '[0-9]+(st|nd|rd|th)',
  647. 'first', 'second', 'third', 'fourth', 'fifth', 'sixth',
  648. 'seventh', 'eighth', 'ninth', 'tenth', 'after', 'back',
  649. 'before', 'behind', 'every', 'front', 'index', 'last',
  650. 'middle', 'some', 'that', 'through', 'thru', 'where', 'whose')
  651. Operators = ("and", "or", "is equal", "equals", "(is )?equal to", "is not",
  652. "isn't", "isn't equal( to)?", "is not equal( to)?",
  653. "doesn't equal", "does not equal", "(is )?greater than",
  654. "comes after", "is not less than or equal( to)?",
  655. "isn't less than or equal( to)?", "(is )?less than",
  656. "comes before", "is not greater than or equal( to)?",
  657. "isn't greater than or equal( to)?",
  658. "(is )?greater than or equal( to)?", "is not less than",
  659. "isn't less than", "does not come before",
  660. "doesn't come before", "(is )?less than or equal( to)?",
  661. "is not greater than", "isn't greater than",
  662. "does not come after", "doesn't come after", "starts? with",
  663. "begins? with", "ends? with", "contains?", "does not contain",
  664. "doesn't contain", "is in", "is contained by", "is not in",
  665. "is not contained by", "isn't contained by", "div", "mod",
  666. "not", "(a )?(ref( to)?|reference to)", "is", "does")
  667. Control = ('considering', 'else', 'error', 'exit', 'from', 'if',
  668. 'ignoring', 'in', 'repeat', 'tell', 'then', 'times', 'to',
  669. 'try', 'until', 'using terms from', 'while', 'whith',
  670. 'with timeout( of)?', 'with transaction', 'by', 'continue',
  671. 'end', 'its?', 'me', 'my', 'return', 'of', 'as')
  672. Declarations = ('global', 'local', 'prop(erty)?', 'set', 'get')
  673. Reserved = ('but', 'put', 'returning', 'the')
  674. StudioClasses = ('action cell', 'alert reply', 'application', 'box',
  675. 'browser( cell)?', 'bundle', 'button( cell)?', 'cell',
  676. 'clip view', 'color well', 'color-panel',
  677. 'combo box( item)?', 'control',
  678. 'data( (cell|column|item|row|source))?', 'default entry',
  679. 'dialog reply', 'document', 'drag info', 'drawer',
  680. 'event', 'font(-panel)?', 'formatter',
  681. 'image( (cell|view))?', 'matrix', 'menu( item)?', 'item',
  682. 'movie( view)?', 'open-panel', 'outline view', 'panel',
  683. 'pasteboard', 'plugin', 'popup button',
  684. 'progress indicator', 'responder', 'save-panel',
  685. 'scroll view', 'secure text field( cell)?', 'slider',
  686. 'sound', 'split view', 'stepper', 'tab view( item)?',
  687. 'table( (column|header cell|header view|view))',
  688. 'text( (field( cell)?|view))?', 'toolbar( item)?',
  689. 'user-defaults', 'view', 'window')
  690. StudioEvents = ('accept outline drop', 'accept table drop', 'action',
  691. 'activated', 'alert ended', 'awake from nib', 'became key',
  692. 'became main', 'begin editing', 'bounds changed',
  693. 'cell value', 'cell value changed', 'change cell value',
  694. 'change item value', 'changed', 'child of item',
  695. 'choose menu item', 'clicked', 'clicked toolbar item',
  696. 'closed', 'column clicked', 'column moved',
  697. 'column resized', 'conclude drop', 'data representation',
  698. 'deminiaturized', 'dialog ended', 'document nib name',
  699. 'double clicked', 'drag( (entered|exited|updated))?',
  700. 'drop', 'end editing', 'exposed', 'idle', 'item expandable',
  701. 'item value', 'item value changed', 'items changed',
  702. 'keyboard down', 'keyboard up', 'launched',
  703. 'load data representation', 'miniaturized', 'mouse down',
  704. 'mouse dragged', 'mouse entered', 'mouse exited',
  705. 'mouse moved', 'mouse up', 'moved',
  706. 'number of browser rows', 'number of items',
  707. 'number of rows', 'open untitled', 'opened', 'panel ended',
  708. 'parameters updated', 'plugin loaded', 'prepare drop',
  709. 'prepare outline drag', 'prepare outline drop',
  710. 'prepare table drag', 'prepare table drop',
  711. 'read from file', 'resigned active', 'resigned key',
  712. 'resigned main', 'resized( sub views)?',
  713. 'right mouse down', 'right mouse dragged',
  714. 'right mouse up', 'rows changed', 'scroll wheel',
  715. 'selected tab view item', 'selection changed',
  716. 'selection changing', 'should begin editing',
  717. 'should close', 'should collapse item',
  718. 'should end editing', 'should expand item',
  719. 'should open( untitled)?',
  720. 'should quit( after last window closed)?',
  721. 'should select column', 'should select item',
  722. 'should select row', 'should select tab view item',
  723. 'should selection change', 'should zoom', 'shown',
  724. 'update menu item', 'update parameters',
  725. 'update toolbar item', 'was hidden', 'was miniaturized',
  726. 'will become active', 'will close', 'will dismiss',
  727. 'will display browser cell', 'will display cell',
  728. 'will display item cell', 'will display outline cell',
  729. 'will finish launching', 'will hide', 'will miniaturize',
  730. 'will move', 'will open', 'will pop up', 'will quit',
  731. 'will resign active', 'will resize( sub views)?',
  732. 'will select tab view item', 'will show', 'will zoom',
  733. 'write to file', 'zoomed')
  734. StudioCommands = ('animate', 'append', 'call method', 'center',
  735. 'close drawer', 'close panel', 'display',
  736. 'display alert', 'display dialog', 'display panel', 'go',
  737. 'hide', 'highlight', 'increment', 'item for',
  738. 'load image', 'load movie', 'load nib', 'load panel',
  739. 'load sound', 'localized string', 'lock focus', 'log',
  740. 'open drawer', 'path for', 'pause', 'perform action',
  741. 'play', 'register', 'resume', 'scroll', 'select( all)?',
  742. 'show', 'size to fit', 'start', 'step back',
  743. 'step forward', 'stop', 'synchronize', 'unlock focus',
  744. 'update')
  745. StudioProperties = ('accepts arrow key', 'action method', 'active',
  746. 'alignment', 'allowed identifiers',
  747. 'allows branch selection', 'allows column reordering',
  748. 'allows column resizing', 'allows column selection',
  749. 'allows customization',
  750. 'allows editing text attributes',
  751. 'allows empty selection', 'allows mixed state',
  752. 'allows multiple selection', 'allows reordering',
  753. 'allows undo', 'alpha( value)?', 'alternate image',
  754. 'alternate increment value', 'alternate title',
  755. 'animation delay', 'associated file name',
  756. 'associated object', 'auto completes', 'auto display',
  757. 'auto enables items', 'auto repeat',
  758. 'auto resizes( outline column)?',
  759. 'auto save expanded items', 'auto save name',
  760. 'auto save table columns', 'auto saves configuration',
  761. 'auto scroll', 'auto sizes all columns to fit',
  762. 'auto sizes cells', 'background color', 'bezel state',
  763. 'bezel style', 'bezeled', 'border rect', 'border type',
  764. 'bordered', 'bounds( rotation)?', 'box type',
  765. 'button returned', 'button type',
  766. 'can choose directories', 'can choose files',
  767. 'can draw', 'can hide',
  768. 'cell( (background color|size|type))?', 'characters',
  769. 'class', 'click count', 'clicked( data)? column',
  770. 'clicked data item', 'clicked( data)? row',
  771. 'closeable', 'collating', 'color( (mode|panel))',
  772. 'command key down', 'configuration',
  773. 'content(s| (size|view( margins)?))?', 'context',
  774. 'continuous', 'control key down', 'control size',
  775. 'control tint', 'control view',
  776. 'controller visible', 'coordinate system',
  777. 'copies( on scroll)?', 'corner view', 'current cell',
  778. 'current column', 'current( field)? editor',
  779. 'current( menu)? item', 'current row',
  780. 'current tab view item', 'data source',
  781. 'default identifiers', 'delta (x|y|z)',
  782. 'destination window', 'directory', 'display mode',
  783. 'displayed cell', 'document( (edited|rect|view))?',
  784. 'double value', 'dragged column', 'dragged distance',
  785. 'dragged items', 'draws( cell)? background',
  786. 'draws grid', 'dynamically scrolls', 'echos bullets',
  787. 'edge', 'editable', 'edited( data)? column',
  788. 'edited data item', 'edited( data)? row', 'enabled',
  789. 'enclosing scroll view', 'ending page',
  790. 'error handling', 'event number', 'event type',
  791. 'excluded from windows menu', 'executable path',
  792. 'expanded', 'fax number', 'field editor', 'file kind',
  793. 'file name', 'file type', 'first responder',
  794. 'first visible column', 'flipped', 'floating',
  795. 'font( panel)?', 'formatter', 'frameworks path',
  796. 'frontmost', 'gave up', 'grid color', 'has data items',
  797. 'has horizontal ruler', 'has horizontal scroller',
  798. 'has parent data item', 'has resize indicator',
  799. 'has shadow', 'has sub menu', 'has vertical ruler',
  800. 'has vertical scroller', 'header cell', 'header view',
  801. 'hidden', 'hides when deactivated', 'highlights by',
  802. 'horizontal line scroll', 'horizontal page scroll',
  803. 'horizontal ruler view', 'horizontally resizable',
  804. 'icon image', 'id', 'identifier',
  805. 'ignores multiple clicks',
  806. 'image( (alignment|dims when disabled|frame style|scaling))?',
  807. 'imports graphics', 'increment value',
  808. 'indentation per level', 'indeterminate', 'index',
  809. 'integer value', 'intercell spacing', 'item height',
  810. 'key( (code|equivalent( modifier)?|window))?',
  811. 'knob thickness', 'label', 'last( visible)? column',
  812. 'leading offset', 'leaf', 'level', 'line scroll',
  813. 'loaded', 'localized sort', 'location', 'loop mode',
  814. 'main( (bunde|menu|window))?', 'marker follows cell',
  815. 'matrix mode', 'maximum( content)? size',
  816. 'maximum visible columns',
  817. 'menu( form representation)?', 'miniaturizable',
  818. 'miniaturized', 'minimized image', 'minimized title',
  819. 'minimum column width', 'minimum( content)? size',
  820. 'modal', 'modified', 'mouse down state',
  821. 'movie( (controller|file|rect))?', 'muted', 'name',
  822. 'needs display', 'next state', 'next text',
  823. 'number of tick marks', 'only tick mark values',
  824. 'opaque', 'open panel', 'option key down',
  825. 'outline table column', 'page scroll', 'pages across',
  826. 'pages down', 'palette label', 'pane splitter',
  827. 'parent data item', 'parent window', 'pasteboard',
  828. 'path( (names|separator))?', 'playing',
  829. 'plays every frame', 'plays selection only', 'position',
  830. 'preferred edge', 'preferred type', 'pressure',
  831. 'previous text', 'prompt', 'properties',
  832. 'prototype cell', 'pulls down', 'rate',
  833. 'released when closed', 'repeated',
  834. 'requested print time', 'required file type',
  835. 'resizable', 'resized column', 'resource path',
  836. 'returns records', 'reuses columns', 'rich text',
  837. 'roll over', 'row height', 'rulers visible',
  838. 'save panel', 'scripts path', 'scrollable',
  839. 'selectable( identifiers)?', 'selected cell',
  840. 'selected( data)? columns?', 'selected data items?',
  841. 'selected( data)? rows?', 'selected item identifier',
  842. 'selection by rect', 'send action on arrow key',
  843. 'sends action when done editing', 'separates columns',
  844. 'separator item', 'sequence number', 'services menu',
  845. 'shared frameworks path', 'shared support path',
  846. 'sheet', 'shift key down', 'shows alpha',
  847. 'shows state by', 'size( mode)?',
  848. 'smart insert delete enabled', 'sort case sensitivity',
  849. 'sort column', 'sort order', 'sort type',
  850. 'sorted( data rows)?', 'sound', 'source( mask)?',
  851. 'spell checking enabled', 'starting page', 'state',
  852. 'string value', 'sub menu', 'super menu', 'super view',
  853. 'tab key traverses cells', 'tab state', 'tab type',
  854. 'tab view', 'table view', 'tag', 'target( printer)?',
  855. 'text color', 'text container insert',
  856. 'text container origin', 'text returned',
  857. 'tick mark position', 'time stamp',
  858. 'title(d| (cell|font|height|position|rect))?',
  859. 'tool tip', 'toolbar', 'trailing offset', 'transparent',
  860. 'treat packages as directories', 'truncated labels',
  861. 'types', 'unmodified characters', 'update views',
  862. 'use sort indicator', 'user defaults',
  863. 'uses data source', 'uses ruler',
  864. 'uses threaded animation',
  865. 'uses title from previous column', 'value wraps',
  866. 'version',
  867. 'vertical( (line scroll|page scroll|ruler view))?',
  868. 'vertically resizable', 'view',
  869. 'visible( document rect)?', 'volume', 'width', 'window',
  870. 'windows menu', 'wraps', 'zoomable', 'zoomed')
  871. tokens = {
  872. 'root': [
  873. (r'\s+', Text),
  874. (r'¬\n', String.Escape),
  875. (r"'s\s+", Text), # This is a possessive, consider moving
  876. (r'(--|#).*?$', Comment),
  877. (r'\(\*', Comment.Multiline, 'comment'),
  878. (r'[(){}!,.:]', Punctuation),
  879. (r'(«)([^»]+)(»)',
  880. bygroups(Text, Name.Builtin, Text)),
  881. (r'\b((?:considering|ignoring)\s*)'
  882. r'(application responses|case|diacriticals|hyphens|'
  883. r'numeric strings|punctuation|white space)',
  884. bygroups(Keyword, Name.Builtin)),
  885. (r'(-|\*|\+|&|≠|>=?|<=?|=|≥|≤|/|÷|\^)', Operator),
  886. (r"\b({})\b".format('|'.join(Operators)), Operator.Word),
  887. (r'^(\s*(?:on|end)\s+)'
  888. r'({})'.format('|'.join(StudioEvents[::-1])),
  889. bygroups(Keyword, Name.Function)),
  890. (r'^(\s*)(in|on|script|to)(\s+)', bygroups(Text, Keyword, Text)),
  891. (r'\b(as )({})\b'.format('|'.join(Classes)),
  892. bygroups(Keyword, Name.Class)),
  893. (r'\b({})\b'.format('|'.join(Literals)), Name.Constant),
  894. (r'\b({})\b'.format('|'.join(Commands)), Name.Builtin),
  895. (r'\b({})\b'.format('|'.join(Control)), Keyword),
  896. (r'\b({})\b'.format('|'.join(Declarations)), Keyword),
  897. (r'\b({})\b'.format('|'.join(Reserved)), Name.Builtin),
  898. (r'\b({})s?\b'.format('|'.join(BuiltIn)), Name.Builtin),
  899. (r'\b({})\b'.format('|'.join(HandlerParams)), Name.Builtin),
  900. (r'\b({})\b'.format('|'.join(StudioProperties)), Name.Attribute),
  901. (r'\b({})s?\b'.format('|'.join(StudioClasses)), Name.Builtin),
  902. (r'\b({})\b'.format('|'.join(StudioCommands)), Name.Builtin),
  903. (r'\b({})\b'.format('|'.join(References)), Name.Builtin),
  904. (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
  905. (rf'\b({Identifiers})\b', Name.Variable),
  906. (r'[-+]?(\d+\.\d*|\d*\.\d+)(E[-+][0-9]+)?', Number.Float),
  907. (r'[-+]?\d+', Number.Integer),
  908. ],
  909. 'comment': [
  910. (r'\(\*', Comment.Multiline, '#push'),
  911. (r'\*\)', Comment.Multiline, '#pop'),
  912. ('[^*(]+', Comment.Multiline),
  913. ('[*(]', Comment.Multiline),
  914. ],
  915. }
  916. class RexxLexer(RegexLexer):
  917. """
  918. Rexx is a scripting language available for
  919. a wide range of different platforms with its roots found on mainframe
  920. systems. It is popular for I/O- and data based tasks and can act as glue
  921. language to bind different applications together.
  922. """
  923. name = 'Rexx'
  924. url = 'http://www.rexxinfo.org/'
  925. aliases = ['rexx', 'arexx']
  926. filenames = ['*.rexx', '*.rex', '*.rx', '*.arexx']
  927. mimetypes = ['text/x-rexx']
  928. version_added = '2.0'
  929. flags = re.IGNORECASE
  930. tokens = {
  931. 'root': [
  932. (r'\s+', Whitespace),
  933. (r'/\*', Comment.Multiline, 'comment'),
  934. (r'"', String, 'string_double'),
  935. (r"'", String, 'string_single'),
  936. (r'[0-9]+(\.[0-9]+)?(e[+-]?[0-9])?', Number),
  937. (r'([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b',
  938. bygroups(Name.Function, Whitespace, Operator, Whitespace,
  939. Keyword.Declaration)),
  940. (r'([a-z_]\w*)(\s*)(:)',
  941. bygroups(Name.Label, Whitespace, Operator)),
  942. include('function'),
  943. include('keyword'),
  944. include('operator'),
  945. (r'[a-z_]\w*', Text),
  946. ],
  947. 'function': [
  948. (words((
  949. 'abbrev', 'abs', 'address', 'arg', 'b2x', 'bitand', 'bitor', 'bitxor',
  950. 'c2d', 'c2x', 'center', 'charin', 'charout', 'chars', 'compare',
  951. 'condition', 'copies', 'd2c', 'd2x', 'datatype', 'date', 'delstr',
  952. 'delword', 'digits', 'errortext', 'form', 'format', 'fuzz', 'insert',
  953. 'lastpos', 'left', 'length', 'linein', 'lineout', 'lines', 'max',
  954. 'min', 'overlay', 'pos', 'queued', 'random', 'reverse', 'right', 'sign',
  955. 'sourceline', 'space', 'stream', 'strip', 'substr', 'subword', 'symbol',
  956. 'time', 'trace', 'translate', 'trunc', 'value', 'verify', 'word',
  957. 'wordindex', 'wordlength', 'wordpos', 'words', 'x2b', 'x2c', 'x2d',
  958. 'xrange'), suffix=r'(\s*)(\()'),
  959. bygroups(Name.Builtin, Whitespace, Operator)),
  960. ],
  961. 'keyword': [
  962. (r'(address|arg|by|call|do|drop|else|end|exit|for|forever|if|'
  963. r'interpret|iterate|leave|nop|numeric|off|on|options|parse|'
  964. r'pull|push|queue|return|say|select|signal|to|then|trace|until|'
  965. r'while)\b', Keyword.Reserved),
  966. ],
  967. 'operator': [
  968. (r'(-|//|/|\(|\)|\*\*|\*|\\<<|\\<|\\==|\\=|\\>>|\\>|\\|\|\||\||'
  969. r'&&|&|%|\+|<<=|<<|<=|<>|<|==|=|><|>=|>>=|>>|>|¬<<|¬<|¬==|¬=|'
  970. r'¬>>|¬>|¬|\.|,)', Operator),
  971. ],
  972. 'string_double': [
  973. (r'[^"\n]+', String),
  974. (r'""', String),
  975. (r'"', String, '#pop'),
  976. (r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
  977. ],
  978. 'string_single': [
  979. (r'[^\'\n]+', String),
  980. (r'\'\'', String),
  981. (r'\'', String, '#pop'),
  982. (r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
  983. ],
  984. 'comment': [
  985. (r'[^*]+', Comment.Multiline),
  986. (r'\*/', Comment.Multiline, '#pop'),
  987. (r'\*', Comment.Multiline),
  988. ]
  989. }
  990. def _c(s):
  991. return re.compile(s, re.MULTILINE)
  992. _ADDRESS_COMMAND_PATTERN = _c(r'^\s*address\s+command\b')
  993. _ADDRESS_PATTERN = _c(r'^\s*address\s+')
  994. _DO_WHILE_PATTERN = _c(r'^\s*do\s+while\b')
  995. _IF_THEN_DO_PATTERN = _c(r'^\s*if\b.+\bthen\s+do\s*$')
  996. _PROCEDURE_PATTERN = _c(r'^\s*([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b')
  997. _ELSE_DO_PATTERN = _c(r'\belse\s+do\s*$')
  998. _PARSE_ARG_PATTERN = _c(r'^\s*parse\s+(upper\s+)?(arg|value)\b')
  999. PATTERNS_AND_WEIGHTS = (
  1000. (_ADDRESS_COMMAND_PATTERN, 0.2),
  1001. (_ADDRESS_PATTERN, 0.05),
  1002. (_DO_WHILE_PATTERN, 0.1),
  1003. (_ELSE_DO_PATTERN, 0.1),
  1004. (_IF_THEN_DO_PATTERN, 0.1),
  1005. (_PROCEDURE_PATTERN, 0.5),
  1006. (_PARSE_ARG_PATTERN, 0.2),
  1007. )
  1008. def analyse_text(text):
  1009. """
  1010. Check for initial comment and patterns that distinguish Rexx from other
  1011. C-like languages.
  1012. """
  1013. if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE):
  1014. # Header matches MVS Rexx requirements, this is certainly a Rexx
  1015. # script.
  1016. return 1.0
  1017. elif text.startswith('/*'):
  1018. # Header matches general Rexx requirements; the source code might
  1019. # still be any language using C comments such as C++, C# or Java.
  1020. lowerText = text.lower()
  1021. result = sum(weight
  1022. for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS
  1023. if pattern.search(lowerText)) + 0.01
  1024. return min(result, 1.0)
  1025. class MOOCodeLexer(RegexLexer):
  1026. """
  1027. For MOOCode (the MOO scripting language).
  1028. """
  1029. name = 'MOOCode'
  1030. url = 'http://www.moo.mud.org/'
  1031. filenames = ['*.moo']
  1032. aliases = ['moocode', 'moo']
  1033. mimetypes = ['text/x-moocode']
  1034. version_added = '0.9'
  1035. tokens = {
  1036. 'root': [
  1037. # Numbers
  1038. (r'(0|[1-9][0-9_]*)', Number.Integer),
  1039. # Strings
  1040. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  1041. # exceptions
  1042. (r'(E_PERM|E_DIV)', Name.Exception),
  1043. # db-refs
  1044. (r'((#[-0-9]+)|(\$\w+))', Name.Entity),
  1045. # Keywords
  1046. (r'\b(if|else|elseif|endif|for|endfor|fork|endfork|while'
  1047. r'|endwhile|break|continue|return|try'
  1048. r'|except|endtry|finally|in)\b', Keyword),
  1049. # builtins
  1050. (r'(random|length)', Name.Builtin),
  1051. # special variables
  1052. (r'(player|caller|this|args)', Name.Variable.Instance),
  1053. # skip whitespace
  1054. (r'\s+', Text),
  1055. (r'\n', Text),
  1056. # other operators
  1057. (r'([!;=,{}&|:.\[\]@()<>?]+)', Operator),
  1058. # function call
  1059. (r'(\w+)(\()', bygroups(Name.Function, Operator)),
  1060. # variables
  1061. (r'(\w+)', Text),
  1062. ]
  1063. }
  1064. class HybrisLexer(RegexLexer):
  1065. """
  1066. For Hybris source code.
  1067. """
  1068. name = 'Hybris'
  1069. aliases = ['hybris']
  1070. filenames = ['*.hyb']
  1071. mimetypes = ['text/x-hybris', 'application/x-hybris']
  1072. url = 'https://github.com/evilsocket/hybris'
  1073. version_added = '1.4'
  1074. flags = re.MULTILINE | re.DOTALL
  1075. tokens = {
  1076. 'root': [
  1077. # method names
  1078. (r'^(\s*(?:function|method|operator\s+)+?)'
  1079. r'([a-zA-Z_]\w*)'
  1080. r'(\s*)(\()', bygroups(Keyword, Name.Function, Text, Operator)),
  1081. (r'[^\S\n]+', Text),
  1082. (r'//.*?\n', Comment.Single),
  1083. (r'/\*.*?\*/', Comment.Multiline),
  1084. (r'@[a-zA-Z_][\w.]*', Name.Decorator),
  1085. (r'(break|case|catch|next|default|do|else|finally|for|foreach|of|'
  1086. r'unless|if|new|return|switch|me|throw|try|while)\b', Keyword),
  1087. (r'(extends|private|protected|public|static|throws|function|method|'
  1088. r'operator)\b', Keyword.Declaration),
  1089. (r'(true|false|null|__FILE__|__LINE__|__VERSION__|__LIB_PATH__|'
  1090. r'__INC_PATH__)\b', Keyword.Constant),
  1091. (r'(class|struct)(\s+)',
  1092. bygroups(Keyword.Declaration, Text), 'class'),
  1093. (r'(import|include)(\s+)',
  1094. bygroups(Keyword.Namespace, Text), 'import'),
  1095. (words((
  1096. 'gc_collect', 'gc_mm_items', 'gc_mm_usage', 'gc_collect_threshold',
  1097. 'urlencode', 'urldecode', 'base64encode', 'base64decode', 'sha1', 'crc32',
  1098. 'sha2', 'md5', 'md5_file', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
  1099. 'cosh', 'exp', 'fabs', 'floor', 'fmod', 'log', 'log10', 'pow', 'sin',
  1100. 'sinh', 'sqrt', 'tan', 'tanh', 'isint', 'isfloat', 'ischar', 'isstring',
  1101. 'isarray', 'ismap', 'isalias', 'typeof', 'sizeof', 'toint', 'tostring',
  1102. 'fromxml', 'toxml', 'binary', 'pack', 'load', 'eval', 'var_names',
  1103. 'var_values', 'user_functions', 'dyn_functions', 'methods', 'call',
  1104. 'call_method', 'mknod', 'mkfifo', 'mount', 'umount2', 'umount', 'ticks',
  1105. 'usleep', 'sleep', 'time', 'strtime', 'strdate', 'dllopen', 'dlllink',
  1106. 'dllcall', 'dllcall_argv', 'dllclose', 'env', 'exec', 'fork', 'getpid',
  1107. 'wait', 'popen', 'pclose', 'exit', 'kill', 'pthread_create',
  1108. 'pthread_create_argv', 'pthread_exit', 'pthread_join', 'pthread_kill',
  1109. 'smtp_send', 'http_get', 'http_post', 'http_download', 'socket', 'bind',
  1110. 'listen', 'accept', 'getsockname', 'getpeername', 'settimeout', 'connect',
  1111. 'server', 'recv', 'send', 'close', 'print', 'println', 'printf', 'input',
  1112. 'readline', 'serial_open', 'serial_fcntl', 'serial_get_attr',
  1113. 'serial_get_ispeed', 'serial_get_ospeed', 'serial_set_attr',
  1114. 'serial_set_ispeed', 'serial_set_ospeed', 'serial_write', 'serial_read',
  1115. 'serial_close', 'xml_load', 'xml_parse', 'fopen', 'fseek', 'ftell',
  1116. 'fsize', 'fread', 'fwrite', 'fgets', 'fclose', 'file', 'readdir',
  1117. 'pcre_replace', 'size', 'pop', 'unmap', 'has', 'keys', 'values',
  1118. 'length', 'find', 'substr', 'replace', 'split', 'trim', 'remove',
  1119. 'contains', 'join'), suffix=r'\b'),
  1120. Name.Builtin),
  1121. (words((
  1122. 'MethodReference', 'Runner', 'Dll', 'Thread', 'Pipe', 'Process',
  1123. 'Runnable', 'CGI', 'ClientSocket', 'Socket', 'ServerSocket',
  1124. 'File', 'Console', 'Directory', 'Exception'), suffix=r'\b'),
  1125. Keyword.Type),
  1126. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  1127. (r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char),
  1128. (r'(\.)([a-zA-Z_]\w*)',
  1129. bygroups(Operator, Name.Attribute)),
  1130. (r'[a-zA-Z_]\w*:', Name.Label),
  1131. (r'[a-zA-Z_$]\w*', Name),
  1132. (r'[~^*!%&\[\](){}<>|+=:;,./?\-@]+', Operator),
  1133. (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
  1134. (r'0x[0-9a-f]+', Number.Hex),
  1135. (r'[0-9]+L?', Number.Integer),
  1136. (r'\n', Text),
  1137. ],
  1138. 'class': [
  1139. (r'[a-zA-Z_]\w*', Name.Class, '#pop')
  1140. ],
  1141. 'import': [
  1142. (r'[\w.]+\*?', Name.Namespace, '#pop')
  1143. ],
  1144. }
  1145. def analyse_text(text):
  1146. """public method and private method don't seem to be quite common
  1147. elsewhere."""
  1148. result = 0
  1149. if re.search(r'\b(?:public|private)\s+method\b', text):
  1150. result += 0.01
  1151. return result
  1152. class EasytrieveLexer(RegexLexer):
  1153. """
  1154. Easytrieve Plus is a programming language for extracting, filtering and
  1155. converting sequential data. Furthermore it can layout data for reports.
  1156. It is mainly used on mainframe platforms and can access several of the
  1157. mainframe's native file formats. It is somewhat comparable to awk.
  1158. """
  1159. name = 'Easytrieve'
  1160. aliases = ['easytrieve']
  1161. filenames = ['*.ezt', '*.mac']
  1162. mimetypes = ['text/x-easytrieve']
  1163. url = 'https://www.broadcom.com/products/mainframe/application-development/easytrieve-report-generator'
  1164. version_added = '2.1'
  1165. flags = 0
  1166. # Note: We cannot use r'\b' at the start and end of keywords because
  1167. # Easytrieve Plus delimiter characters are:
  1168. #
  1169. # * space ( )
  1170. # * apostrophe (')
  1171. # * period (.)
  1172. # * comma (,)
  1173. # * parenthesis ( and )
  1174. # * colon (:)
  1175. #
  1176. # Additionally words end once a '*' appears, indicatins a comment.
  1177. _DELIMITERS = r' \'.,():\n'
  1178. _DELIMITERS_OR_COMENT = _DELIMITERS + '*'
  1179. _DELIMITER_PATTERN = '[' + _DELIMITERS + ']'
  1180. _DELIMITER_PATTERN_CAPTURE = '(' + _DELIMITER_PATTERN + ')'
  1181. _NON_DELIMITER_OR_COMMENT_PATTERN = '[^' + _DELIMITERS_OR_COMENT + ']'
  1182. _OPERATORS_PATTERN = '[.+\\-/=\\[\\](){}<>;,&%¬]'
  1183. _KEYWORDS = [
  1184. 'AFTER-BREAK', 'AFTER-LINE', 'AFTER-SCREEN', 'AIM', 'AND', 'ATTR',
  1185. 'BEFORE', 'BEFORE-BREAK', 'BEFORE-LINE', 'BEFORE-SCREEN', 'BUSHU',
  1186. 'BY', 'CALL', 'CASE', 'CHECKPOINT', 'CHKP', 'CHKP-STATUS', 'CLEAR',
  1187. 'CLOSE', 'COL', 'COLOR', 'COMMIT', 'CONTROL', 'COPY', 'CURSOR', 'D',
  1188. 'DECLARE', 'DEFAULT', 'DEFINE', 'DELETE', 'DENWA', 'DISPLAY', 'DLI',
  1189. 'DO', 'DUPLICATE', 'E', 'ELSE', 'ELSE-IF', 'END', 'END-CASE',
  1190. 'END-DO', 'END-IF', 'END-PROC', 'ENDPAGE', 'ENDTABLE', 'ENTER', 'EOF',
  1191. 'EQ', 'ERROR', 'EXIT', 'EXTERNAL', 'EZLIB', 'F1', 'F10', 'F11', 'F12',
  1192. 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F2', 'F20', 'F21',
  1193. 'F22', 'F23', 'F24', 'F25', 'F26', 'F27', 'F28', 'F29', 'F3', 'F30',
  1194. 'F31', 'F32', 'F33', 'F34', 'F35', 'F36', 'F4', 'F5', 'F6', 'F7',
  1195. 'F8', 'F9', 'FETCH', 'FILE-STATUS', 'FILL', 'FINAL', 'FIRST',
  1196. 'FIRST-DUP', 'FOR', 'GE', 'GET', 'GO', 'GOTO', 'GQ', 'GR', 'GT',
  1197. 'HEADING', 'HEX', 'HIGH-VALUES', 'IDD', 'IDMS', 'IF', 'IN', 'INSERT',
  1198. 'JUSTIFY', 'KANJI-DATE', 'KANJI-DATE-LONG', 'KANJI-TIME', 'KEY',
  1199. 'KEY-PRESSED', 'KOKUGO', 'KUN', 'LAST-DUP', 'LE', 'LEVEL', 'LIKE',
  1200. 'LINE', 'LINE-COUNT', 'LINE-NUMBER', 'LINK', 'LIST', 'LOW-VALUES',
  1201. 'LQ', 'LS', 'LT', 'MACRO', 'MASK', 'MATCHED', 'MEND', 'MESSAGE',
  1202. 'MOVE', 'MSTART', 'NE', 'NEWPAGE', 'NOMASK', 'NOPRINT', 'NOT',
  1203. 'NOTE', 'NOVERIFY', 'NQ', 'NULL', 'OF', 'OR', 'OTHERWISE', 'PA1',
  1204. 'PA2', 'PA3', 'PAGE-COUNT', 'PAGE-NUMBER', 'PARM-REGISTER',
  1205. 'PATH-ID', 'PATTERN', 'PERFORM', 'POINT', 'POS', 'PRIMARY', 'PRINT',
  1206. 'PROCEDURE', 'PROGRAM', 'PUT', 'READ', 'RECORD', 'RECORD-COUNT',
  1207. 'RECORD-LENGTH', 'REFRESH', 'RELEASE', 'RENUM', 'REPEAT', 'REPORT',
  1208. 'REPORT-INPUT', 'RESHOW', 'RESTART', 'RETRIEVE', 'RETURN-CODE',
  1209. 'ROLLBACK', 'ROW', 'S', 'SCREEN', 'SEARCH', 'SECONDARY', 'SELECT',
  1210. 'SEQUENCE', 'SIZE', 'SKIP', 'SOKAKU', 'SORT', 'SQL', 'STOP', 'SUM',
  1211. 'SYSDATE', 'SYSDATE-LONG', 'SYSIN', 'SYSIPT', 'SYSLST', 'SYSPRINT',
  1212. 'SYSSNAP', 'SYSTIME', 'TALLY', 'TERM-COLUMNS', 'TERM-NAME',
  1213. 'TERM-ROWS', 'TERMINATION', 'TITLE', 'TO', 'TRANSFER', 'TRC',
  1214. 'UNIQUE', 'UNTIL', 'UPDATE', 'UPPERCASE', 'USER', 'USERID', 'VALUE',
  1215. 'VERIFY', 'W', 'WHEN', 'WHILE', 'WORK', 'WRITE', 'X', 'XDM', 'XRST'
  1216. ]
  1217. tokens = {
  1218. 'root': [
  1219. (r'\*.*\n', Comment.Single),
  1220. (r'\n+', Whitespace),
  1221. # Macro argument
  1222. (r'&' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+\.', Name.Variable,
  1223. 'after_macro_argument'),
  1224. # Macro call
  1225. (r'%' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Variable),
  1226. (r'(FILE|MACRO|REPORT)(\s+)',
  1227. bygroups(Keyword.Declaration, Whitespace), 'after_declaration'),
  1228. (r'(JOB|PARM)' + r'(' + _DELIMITER_PATTERN + r')',
  1229. bygroups(Keyword.Declaration, Operator)),
  1230. (words(_KEYWORDS, suffix=_DELIMITER_PATTERN_CAPTURE),
  1231. bygroups(Keyword.Reserved, Operator)),
  1232. (_OPERATORS_PATTERN, Operator),
  1233. # Procedure declaration
  1234. (r'(' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+)(\s*)(\.?)(\s*)(PROC)(\s*\n)',
  1235. bygroups(Name.Function, Whitespace, Operator, Whitespace,
  1236. Keyword.Declaration, Whitespace)),
  1237. (r'[0-9]+\.[0-9]*', Number.Float),
  1238. (r'[0-9]+', Number.Integer),
  1239. (r"'(''|[^'])*'", String),
  1240. (r'\s+', Whitespace),
  1241. # Everything else just belongs to a name
  1242. (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
  1243. ],
  1244. 'after_declaration': [
  1245. (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Function),
  1246. default('#pop'),
  1247. ],
  1248. 'after_macro_argument': [
  1249. (r'\*.*\n', Comment.Single, '#pop'),
  1250. (r'\s+', Whitespace, '#pop'),
  1251. (_OPERATORS_PATTERN, Operator, '#pop'),
  1252. (r"'(''|[^'])*'", String, '#pop'),
  1253. # Everything else just belongs to a name
  1254. (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
  1255. ],
  1256. }
  1257. _COMMENT_LINE_REGEX = re.compile(r'^\s*\*')
  1258. _MACRO_HEADER_REGEX = re.compile(r'^\s*MACRO')
  1259. def analyse_text(text):
  1260. """
  1261. Perform a structural analysis for basic Easytrieve constructs.
  1262. """
  1263. result = 0.0
  1264. lines = text.split('\n')
  1265. hasEndProc = False
  1266. hasHeaderComment = False
  1267. hasFile = False
  1268. hasJob = False
  1269. hasProc = False
  1270. hasParm = False
  1271. hasReport = False
  1272. def isCommentLine(line):
  1273. return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None
  1274. def isEmptyLine(line):
  1275. return not bool(line.strip())
  1276. # Remove possible empty lines and header comments.
  1277. while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])):
  1278. if not isEmptyLine(lines[0]):
  1279. hasHeaderComment = True
  1280. del lines[0]
  1281. if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]):
  1282. # Looks like an Easytrieve macro.
  1283. result = 0.4
  1284. if hasHeaderComment:
  1285. result += 0.4
  1286. else:
  1287. # Scan the source for lines starting with indicators.
  1288. for line in lines:
  1289. words = line.split()
  1290. if (len(words) >= 2):
  1291. firstWord = words[0]
  1292. if not hasReport:
  1293. if not hasJob:
  1294. if not hasFile:
  1295. if not hasParm:
  1296. if firstWord == 'PARM':
  1297. hasParm = True
  1298. if firstWord == 'FILE':
  1299. hasFile = True
  1300. if firstWord == 'JOB':
  1301. hasJob = True
  1302. elif firstWord == 'PROC':
  1303. hasProc = True
  1304. elif firstWord == 'END-PROC':
  1305. hasEndProc = True
  1306. elif firstWord == 'REPORT':
  1307. hasReport = True
  1308. # Weight the findings.
  1309. if hasJob and (hasProc == hasEndProc):
  1310. if hasHeaderComment:
  1311. result += 0.1
  1312. if hasParm:
  1313. if hasProc:
  1314. # Found PARM, JOB and PROC/END-PROC:
  1315. # pretty sure this is Easytrieve.
  1316. result += 0.8
  1317. else:
  1318. # Found PARAM and JOB: probably this is Easytrieve
  1319. result += 0.5
  1320. else:
  1321. # Found JOB and possibly other keywords: might be Easytrieve
  1322. result += 0.11
  1323. if hasParm:
  1324. # Note: PARAM is not a proper English word, so this is
  1325. # regarded a much better indicator for Easytrieve than
  1326. # the other words.
  1327. result += 0.2
  1328. if hasFile:
  1329. result += 0.01
  1330. if hasReport:
  1331. result += 0.01
  1332. assert 0.0 <= result <= 1.0
  1333. return result
  1334. class JclLexer(RegexLexer):
  1335. """
  1336. Job Control Language (JCL)
  1337. is a scripting language used on mainframe platforms to instruct the system
  1338. on how to run a batch job or start a subsystem. It is somewhat
  1339. comparable to MS DOS batch and Unix shell scripts.
  1340. """
  1341. name = 'JCL'
  1342. aliases = ['jcl']
  1343. filenames = ['*.jcl']
  1344. mimetypes = ['text/x-jcl']
  1345. url = 'https://en.wikipedia.org/wiki/Job_Control_Language'
  1346. version_added = '2.1'
  1347. flags = re.IGNORECASE
  1348. tokens = {
  1349. 'root': [
  1350. (r'//\*.*\n', Comment.Single),
  1351. (r'//', Keyword.Pseudo, 'statement'),
  1352. (r'/\*', Keyword.Pseudo, 'jes2_statement'),
  1353. # TODO: JES3 statement
  1354. (r'.*\n', Other) # Input text or inline code in any language.
  1355. ],
  1356. 'statement': [
  1357. (r'\s*\n', Whitespace, '#pop'),
  1358. (r'([a-z]\w*)(\s+)(exec|job)(\s*)',
  1359. bygroups(Name.Label, Whitespace, Keyword.Reserved, Whitespace),
  1360. 'option'),
  1361. (r'[a-z]\w*', Name.Variable, 'statement_command'),
  1362. (r'\s+', Whitespace, 'statement_command'),
  1363. ],
  1364. 'statement_command': [
  1365. (r'\s+(command|cntl|dd|endctl|endif|else|include|jcllib|'
  1366. r'output|pend|proc|set|then|xmit)\s+', Keyword.Reserved, 'option'),
  1367. include('option')
  1368. ],
  1369. 'jes2_statement': [
  1370. (r'\s*\n', Whitespace, '#pop'),
  1371. (r'\$', Keyword, 'option'),
  1372. (r'\b(jobparam|message|netacct|notify|output|priority|route|'
  1373. r'setup|signoff|xeq|xmit)\b', Keyword, 'option'),
  1374. ],
  1375. 'option': [
  1376. # (r'\n', Text, 'root'),
  1377. (r'\*', Name.Builtin),
  1378. (r'[\[\](){}<>;,]', Punctuation),
  1379. (r'[-+*/=&%]', Operator),
  1380. (r'[a-z_]\w*', Name),
  1381. (r'\d+\.\d*', Number.Float),
  1382. (r'\.\d+', Number.Float),
  1383. (r'\d+', Number.Integer),
  1384. (r"'", String, 'option_string'),
  1385. (r'[ \t]+', Whitespace, 'option_comment'),
  1386. (r'\.', Punctuation),
  1387. ],
  1388. 'option_string': [
  1389. (r"(\n)(//)", bygroups(Text, Keyword.Pseudo)),
  1390. (r"''", String),
  1391. (r"[^']", String),
  1392. (r"'", String, '#pop'),
  1393. ],
  1394. 'option_comment': [
  1395. # (r'\n', Text, 'root'),
  1396. (r'.+', Comment.Single),
  1397. ]
  1398. }
  1399. _JOB_HEADER_PATTERN = re.compile(r'^//[a-z#$@][a-z0-9#$@]{0,7}\s+job(\s+.*)?$',
  1400. re.IGNORECASE)
  1401. def analyse_text(text):
  1402. """
  1403. Recognize JCL job by header.
  1404. """
  1405. result = 0.0
  1406. lines = text.split('\n')
  1407. if len(lines) > 0:
  1408. if JclLexer._JOB_HEADER_PATTERN.match(lines[0]):
  1409. result = 1.0
  1410. assert 0.0 <= result <= 1.0
  1411. return result
  1412. class MiniScriptLexer(RegexLexer):
  1413. """
  1414. For MiniScript source code.
  1415. """
  1416. name = 'MiniScript'
  1417. url = 'https://miniscript.org'
  1418. aliases = ['miniscript', 'ms']
  1419. filenames = ['*.ms']
  1420. mimetypes = ['text/x-minicript', 'application/x-miniscript']
  1421. version_added = '2.6'
  1422. tokens = {
  1423. 'root': [
  1424. (r'#!(.*?)$', Comment.Preproc),
  1425. default('base'),
  1426. ],
  1427. 'base': [
  1428. ('//.*$', Comment.Single),
  1429. (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number),
  1430. (r'(?i)\d+e[+-]?\d+', Number),
  1431. (r'\d+', Number),
  1432. (r'\n', Text),
  1433. (r'[^\S\n]+', Text),
  1434. (r'"', String, 'string_double'),
  1435. (r'(==|!=|<=|>=|[=+\-*/%^<>.:])', Operator),
  1436. (r'[;,\[\]{}()]', Punctuation),
  1437. (words((
  1438. 'break', 'continue', 'else', 'end', 'for', 'function', 'if',
  1439. 'in', 'isa', 'then', 'repeat', 'return', 'while'), suffix=r'\b'),
  1440. Keyword),
  1441. (words((
  1442. 'abs', 'acos', 'asin', 'atan', 'ceil', 'char', 'cos', 'floor',
  1443. 'log', 'round', 'rnd', 'pi', 'sign', 'sin', 'sqrt', 'str', 'tan',
  1444. 'hasIndex', 'indexOf', 'len', 'val', 'code', 'remove', 'lower',
  1445. 'upper', 'replace', 'split', 'indexes', 'values', 'join', 'sum',
  1446. 'sort', 'shuffle', 'push', 'pop', 'pull', 'range',
  1447. 'print', 'input', 'time', 'wait', 'locals', 'globals', 'outer',
  1448. 'yield'), suffix=r'\b'),
  1449. Name.Builtin),
  1450. (r'(true|false|null)\b', Keyword.Constant),
  1451. (r'(and|or|not|new)\b', Operator.Word),
  1452. (r'(self|super|__isa)\b', Name.Builtin.Pseudo),
  1453. (r'[a-zA-Z_]\w*', Name.Variable)
  1454. ],
  1455. 'string_double': [
  1456. (r'[^"\n]+', String),
  1457. (r'""', String),
  1458. (r'"', String, '#pop'),
  1459. (r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
  1460. ]
  1461. }