scripting.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. """
  2. pygments.lexers.scripting
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Lexer for scripting and embedded languages.
  5. :copyright: Copyright 2006-present 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+(?!\s))'
  46. _s = rf'(?:{_comment_multiline}|{_comment_single}|{_space})'
  47. # A lookahead-safe version of _s that avoids catastrophic backtracking.
  48. # The _comment_multiline pattern contains [\w\W]*? which, when used
  49. # inside a lookahead with a * quantifier, causes exponential blowup.
  50. # This version skips only whitespace; comments between an identifier
  51. # and a following [.:] or ( are rare enough to sacrifice.
  52. _s_la = r'\s'
  53. _name = r'(?:[^\W\d]\w*)'
  54. tokens = {
  55. 'root': [
  56. # Lua allows a file to start with a shebang.
  57. (r'#!.*', Comment.Preproc),
  58. default('base'),
  59. ],
  60. 'ws': [
  61. (_comment_multiline, Comment.Multiline),
  62. (_comment_single, Comment.Single),
  63. (_space, Whitespace),
  64. ],
  65. 'base': [
  66. include('ws'),
  67. (r'(?i)0x[\da-f]*(\.[\da-f]*)?(p[+-]?\d+)?', Number.Hex),
  68. (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
  69. (r'(?i)\d+e[+-]?\d+', Number.Float),
  70. (r'\d+', Number.Integer),
  71. # multiline strings
  72. (r'(?s)\[(=*)\[.*?\]\1\]', String),
  73. (r'::', Punctuation, 'label'),
  74. (r'\.{3}', Punctuation),
  75. (r'[=<>|~&+\-*/%#^]+|\.\.', Operator),
  76. (r'[\[\]{}().,:;]+', Punctuation),
  77. (r'(and|or|not)\b', Operator.Word),
  78. (words([
  79. 'break', 'do', 'else', 'elseif', 'end', 'for', 'if', 'in',
  80. 'repeat', 'return', 'then', 'until', 'while'
  81. ], suffix=r'\b'), Keyword.Reserved),
  82. (r'goto\b', Keyword.Reserved, 'goto'),
  83. (r'(local)\b', Keyword.Declaration),
  84. (r'(true|false|nil)\b', Keyword.Constant),
  85. (r'(function)\b', Keyword.Reserved, 'funcname'),
  86. (words(all_lua_builtins(), suffix=r"\b"), Name.Builtin),
  87. (fr'[A-Za-z_]\w*(?={_s_la}*[.:])', Name.Variable, 'varname'),
  88. (fr'[A-Za-z_]\w*(?={_s_la}*\()', Name.Function),
  89. (r'[A-Za-z_]\w*', Name.Variable),
  90. ("'", String.Single, combined('stringescape', 'sqs')),
  91. ('"', String.Double, combined('stringescape', 'dqs'))
  92. ],
  93. 'varname': [
  94. include('ws'),
  95. (r'\.\.', Operator, '#pop'),
  96. (r'[.:]', Punctuation),
  97. (rf'{_name}(?={_s_la}*[.:])', Name.Property),
  98. (rf'{_name}(?={_s_la}*\()', Name.Function, '#pop'),
  99. (_name, Name.Property, '#pop'),
  100. ],
  101. 'funcname': [
  102. include('ws'),
  103. (r'[.:]', Punctuation),
  104. (rf'{_name}(?={_s_la}*[.:])', Name.Class),
  105. (_name, Name.Function, '#pop'),
  106. # inline function
  107. (r'\(', Punctuation, '#pop'),
  108. ],
  109. 'goto': [
  110. include('ws'),
  111. (_name, Name.Label, '#pop'),
  112. ],
  113. 'label': [
  114. include('ws'),
  115. (r'::', Punctuation, '#pop'),
  116. (_name, Name.Label),
  117. ],
  118. 'stringescape': [
  119. (r'\\([abfnrtv\\"\']|[\r\n]{1,2}|z\s*|x[0-9a-fA-F]{2}|\d{1,3}|'
  120. r'u\{[0-9a-fA-F]+\})', String.Escape),
  121. ],
  122. 'sqs': [
  123. (r"'", String.Single, '#pop'),
  124. (r"[^\\']+", String.Single),
  125. ],
  126. 'dqs': [
  127. (r'"', String.Double, '#pop'),
  128. (r'[^\\"]+', String.Double),
  129. ]
  130. }
  131. def __init__(self, **options):
  132. self.func_name_highlighting = get_bool_opt(
  133. options, 'func_name_highlighting', True)
  134. self.disabled_modules = get_list_opt(options, 'disabled_modules', [])
  135. self._functions = set()
  136. if self.func_name_highlighting:
  137. from pygments.lexers._lua_builtins import MODULES
  138. for mod, func in MODULES.items():
  139. if mod not in self.disabled_modules:
  140. self._functions.update(func)
  141. RegexLexer.__init__(self, **options)
  142. def get_tokens_unprocessed(self, text):
  143. for index, token, value in \
  144. RegexLexer.get_tokens_unprocessed(self, text):
  145. if token is Name.Builtin and value not in self._functions:
  146. if '.' in value:
  147. a, b = value.split('.')
  148. yield index, Name, a
  149. yield index + len(a), Punctuation, '.'
  150. yield index + len(a) + 1, Name, b
  151. else:
  152. yield index, Name, value
  153. continue
  154. yield index, token, value
  155. def _luau_make_expression(should_pop, _s, _s_la):
  156. temp_list = [
  157. (r'0[xX][\da-fA-F_]*', Number.Hex, '#pop'),
  158. (r'0[bB][\d_]*', Number.Bin, '#pop'),
  159. (r'\.?\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?[\d_]+)?', Number.Float, '#pop'),
  160. (words((
  161. 'true', 'false', 'nil'
  162. ), suffix=r'\b'), Keyword.Constant, '#pop'),
  163. (r'\[(=*)\[[.\n]*?\]\1\]', String, '#pop'),
  164. (r'(\.)([a-zA-Z_]\w*)(?=%s*[({"\'])', bygroups(Punctuation, Name.Function), '#pop'),
  165. (r'(\.)([a-zA-Z_]\w*)', bygroups(Punctuation, Name.Variable), '#pop'),
  166. (rf'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*(?={_s_la}*[({{"\'])', Name.Other, '#pop'),
  167. (r'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*', Name, '#pop'),
  168. ]
  169. if should_pop:
  170. return temp_list
  171. return [entry[:2] for entry in temp_list]
  172. def _luau_make_expression_special(should_pop):
  173. temp_list = [
  174. (r'\{', Punctuation, ('#pop', 'closing_brace_base', 'expression')),
  175. (r'\(', Punctuation, ('#pop', 'closing_parenthesis_base', 'expression')),
  176. (r'::?', Punctuation, ('#pop', 'type_end', 'type_start')),
  177. (r"'", String.Single, ('#pop', 'string_single')),
  178. (r'"', String.Double, ('#pop', 'string_double')),
  179. (r'`', String.Backtick, ('#pop', 'string_interpolated')),
  180. ]
  181. if should_pop:
  182. return temp_list
  183. return [(entry[0], entry[1], entry[2][1:]) for entry in temp_list]
  184. class LuauLexer(RegexLexer):
  185. """
  186. For Luau source code.
  187. Additional options accepted:
  188. `include_luau_builtins`
  189. If given and ``True``, automatically highlight Luau builtins
  190. (default: ``True``).
  191. `include_roblox_builtins`
  192. If given and ``True``, automatically highlight Roblox-specific builtins
  193. (default: ``False``).
  194. `additional_builtins`
  195. If given, must be a list of additional builtins to highlight.
  196. `disabled_builtins`
  197. If given, must be a list of builtins that will not be highlighted.
  198. """
  199. name = 'Luau'
  200. url = 'https://luau-lang.org/'
  201. aliases = ['luau']
  202. filenames = ['*.luau']
  203. version_added = '2.18'
  204. _comment_multiline = r'(?:--\[(?P<level>=*)\[[\w\W]*?\](?P=level)\])'
  205. _comment_single = r'(?:--.*$)'
  206. _s = r'(?:{}|{}|{})'.format(_comment_multiline, _comment_single, r'\s+')
  207. # Lookahead-safe version — avoids catastrophic backtracking from
  208. # [\w\W]*? inside _comment_multiline when combined with * quantifier.
  209. _s_la = r'\s'
  210. tokens = {
  211. 'root': [
  212. (r'#!.*', Comment.Hashbang, 'base'),
  213. default('base'),
  214. ],
  215. 'ws': [
  216. (_comment_multiline, Comment.Multiline),
  217. (_comment_single, Comment.Single),
  218. (r'\s+', Whitespace),
  219. ],
  220. 'base': [
  221. include('ws'),
  222. *_luau_make_expression_special(False),
  223. (r'\.\.\.', Punctuation),
  224. (rf'type\b(?={_s}+[a-zA-Z_])', Keyword.Reserved, 'type_declaration'),
  225. (rf'export\b(?={_s}+[a-zA-Z_])', Keyword.Reserved),
  226. (r'(?:\.\.|//|[+\-*\/%^<>=])=?', Operator, 'expression'),
  227. (r'~=', Operator, 'expression'),
  228. (words((
  229. 'and', 'or', 'not'
  230. ), suffix=r'\b'), Operator.Word, 'expression'),
  231. (words((
  232. 'elseif', 'for', 'if', 'in', 'repeat', 'return', 'until',
  233. 'while'), suffix=r'\b'), Keyword.Reserved, 'expression'),
  234. (r'local\b', Keyword.Declaration, 'expression'),
  235. (r'function\b', Keyword.Reserved, ('expression', 'func_name')),
  236. (r'[\])};]+', Punctuation),
  237. include('expression_static'),
  238. *_luau_make_expression(False, _s, _s_la),
  239. (r'[\[.,]', Punctuation, 'expression'),
  240. ],
  241. 'expression_static': [
  242. (words((
  243. 'break', 'continue', 'do', 'else', 'elseif', 'end', 'for',
  244. 'if', 'in', 'repeat', 'return', 'then', 'until', 'while'),
  245. suffix=r'\b'), Keyword.Reserved),
  246. ],
  247. 'expression': [
  248. include('ws'),
  249. (r'if\b', Keyword.Reserved, ('ternary', 'expression')),
  250. (r'local\b', Keyword.Declaration),
  251. *_luau_make_expression_special(True),
  252. (r'\.\.\.', Punctuation, '#pop'),
  253. (r'function\b', Keyword.Reserved, 'func_name'),
  254. include('expression_static'),
  255. *_luau_make_expression(True, _s, _s_la),
  256. default('#pop'),
  257. ],
  258. 'ternary': [
  259. include('ws'),
  260. (r'else\b', Keyword.Reserved, '#pop'),
  261. (words((
  262. 'then', 'elseif',
  263. ), suffix=r'\b'), Operator.Reserved, 'expression'),
  264. default('#pop'),
  265. ],
  266. 'closing_brace_pop': [
  267. (r'\}', Punctuation, '#pop'),
  268. ],
  269. 'closing_parenthesis_pop': [
  270. (r'\)', Punctuation, '#pop'),
  271. ],
  272. 'closing_gt_pop': [
  273. (r'>', Punctuation, '#pop'),
  274. ],
  275. 'closing_parenthesis_base': [
  276. include('closing_parenthesis_pop'),
  277. include('base'),
  278. ],
  279. 'closing_parenthesis_type': [
  280. include('closing_parenthesis_pop'),
  281. include('type'),
  282. ],
  283. 'closing_brace_base': [
  284. include('closing_brace_pop'),
  285. include('base'),
  286. ],
  287. 'closing_brace_type': [
  288. include('closing_brace_pop'),
  289. include('type'),
  290. ],
  291. 'closing_gt_type': [
  292. include('closing_gt_pop'),
  293. include('type'),
  294. ],
  295. 'string_escape': [
  296. (r'\\z\s*', String.Escape),
  297. (r'\\(?:[abfnrtvz\\"\'`\{\n])|[\r\n]{1,2}|x[\da-fA-F]{2}|\d{1,3}|'
  298. r'u\{\}[\da-fA-F]*\}', String.Escape),
  299. ],
  300. 'string_single': [
  301. include('string_escape'),
  302. (r"'", String.Single, "#pop"),
  303. (r"[^\\']+", String.Single),
  304. ],
  305. 'string_double': [
  306. include('string_escape'),
  307. (r'"', String.Double, "#pop"),
  308. (r'[^\\"]+', String.Double),
  309. ],
  310. 'string_interpolated': [
  311. include('string_escape'),
  312. (r'\{', Punctuation, ('closing_brace_base', 'expression')),
  313. (r'`', String.Backtick, "#pop"),
  314. (r'[^\\`\{]+', String.Backtick),
  315. ],
  316. 'func_name': [
  317. include('ws'),
  318. (r'[.:]', Punctuation),
  319. (rf'[a-zA-Z_]\w*(?={_s_la}*[.:])', Name.Class),
  320. (r'[a-zA-Z_]\w*', Name.Function),
  321. (r'<', Punctuation, 'closing_gt_type'),
  322. (r'\(', Punctuation, '#pop'),
  323. ],
  324. 'type': [
  325. include('ws'),
  326. (r'\(', Punctuation, 'closing_parenthesis_type'),
  327. (r'\{', Punctuation, 'closing_brace_type'),
  328. (r'<', Punctuation, 'closing_gt_type'),
  329. (r"'", String.Single, 'string_single'),
  330. (r'"', String.Double, 'string_double'),
  331. (r'[|&\.,\[\]:=]+', Punctuation),
  332. (r'->', Punctuation),
  333. (r'typeof\(', Name.Builtin, ('closing_parenthesis_base',
  334. 'expression')),
  335. (r'[a-zA-Z_]\w*', Name.Class),
  336. ],
  337. 'type_start': [
  338. include('ws'),
  339. (r'\(', Punctuation, ('#pop', 'closing_parenthesis_type')),
  340. (r'\{', Punctuation, ('#pop', 'closing_brace_type')),
  341. (r'<', Punctuation, ('#pop', 'closing_gt_type')),
  342. (r"'", String.Single, ('#pop', 'string_single')),
  343. (r'"', String.Double, ('#pop', 'string_double')),
  344. (r'typeof\(', Name.Builtin, ('#pop', 'closing_parenthesis_base',
  345. 'expression')),
  346. (r'[a-zA-Z_]\w*', Name.Class, '#pop'),
  347. ],
  348. 'type_end': [
  349. include('ws'),
  350. (r'[|&\.]', Punctuation, 'type_start'),
  351. (r'->', Punctuation, 'type_start'),
  352. (r'<', Punctuation, 'closing_gt_type'),
  353. default('#pop'),
  354. ],
  355. 'type_declaration': [
  356. include('ws'),
  357. (r'[a-zA-Z_]\w*', Name.Class),
  358. (r'<', Punctuation, 'closing_gt_type'),
  359. (r'=', Punctuation, ('#pop', 'type_end', 'type_start')),
  360. ],
  361. }
  362. def __init__(self, **options):
  363. self.include_luau_builtins = get_bool_opt(
  364. options, 'include_luau_builtins', True)
  365. self.include_roblox_builtins = get_bool_opt(
  366. options, 'include_roblox_builtins', False)
  367. self.additional_builtins = get_list_opt(options, 'additional_builtins', [])
  368. self.disabled_builtins = get_list_opt(options, 'disabled_builtins', [])
  369. self._builtins = set(self.additional_builtins)
  370. if self.include_luau_builtins:
  371. from pygments.lexers._luau_builtins import LUAU_BUILTINS
  372. self._builtins.update(LUAU_BUILTINS)
  373. if self.include_roblox_builtins:
  374. from pygments.lexers._luau_builtins import ROBLOX_BUILTINS
  375. self._builtins.update(ROBLOX_BUILTINS)
  376. if self.additional_builtins:
  377. self._builtins.update(self.additional_builtins)
  378. self._builtins.difference_update(self.disabled_builtins)
  379. RegexLexer.__init__(self, **options)
  380. def get_tokens_unprocessed(self, text):
  381. for index, token, value in \
  382. RegexLexer.get_tokens_unprocessed(self, text):
  383. if token is Name or token is Name.Other:
  384. split_value = value.split('.')
  385. complete_value = []
  386. new_index = index
  387. for position in range(len(split_value), 0, -1):
  388. potential_string = '.'.join(split_value[:position])
  389. if potential_string in self._builtins:
  390. yield index, Name.Builtin, potential_string
  391. new_index += len(potential_string)
  392. if complete_value:
  393. yield new_index, Punctuation, '.'
  394. new_index += 1
  395. break
  396. complete_value.insert(0, split_value[position - 1])
  397. for position, substring in enumerate(complete_value):
  398. if position + 1 == len(complete_value):
  399. if token is Name:
  400. yield new_index, Name.Variable, substring
  401. continue
  402. yield new_index, Name.Function, substring
  403. continue
  404. yield new_index, Name.Variable, substring
  405. new_index += len(substring)
  406. yield new_index, Punctuation, '.'
  407. new_index += 1
  408. continue
  409. yield index, token, value
  410. class MoonScriptLexer(LuaLexer):
  411. """
  412. For MoonScript source code.
  413. """
  414. name = 'MoonScript'
  415. url = 'http://moonscript.org'
  416. aliases = ['moonscript', 'moon']
  417. filenames = ['*.moon']
  418. mimetypes = ['text/x-moonscript', 'application/x-moonscript']
  419. version_added = '1.5'
  420. tokens = {
  421. 'root': [
  422. (r'#!(.*?)$', Comment.Preproc),
  423. default('base'),
  424. ],
  425. 'base': [
  426. ('--.*$', Comment.Single),
  427. (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
  428. (r'(?i)\d+e[+-]?\d+', Number.Float),
  429. (r'(?i)0x[0-9a-f]*', Number.Hex),
  430. (r'\d+', Number.Integer),
  431. (r'\n', Whitespace),
  432. (r'[^\S\n]+', Text),
  433. (r'(?s)\[(=*)\[.*?\]\1\]', String),
  434. (r'(->|=>)', Name.Function),
  435. (r':[a-zA-Z_]\w*', Name.Variable),
  436. (r'(==|!=|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#!.\\:])', Operator),
  437. (r'[;,]', Punctuation),
  438. (r'[\[\]{}()]', Keyword.Type),
  439. (r'[a-zA-Z_]\w*:', Name.Variable),
  440. (words((
  441. 'class', 'extends', 'if', 'then', 'super', 'do', 'with',
  442. 'import', 'export', 'while', 'elseif', 'return', 'for', 'in',
  443. 'from', 'when', 'using', 'else', 'and', 'or', 'not', 'switch',
  444. 'break'), suffix=r'\b'),
  445. Keyword),
  446. (r'(true|false|nil)\b', Keyword.Constant),
  447. (r'(and|or|not)\b', Operator.Word),
  448. (r'(self)\b', Name.Builtin.Pseudo),
  449. (r'@@?([a-zA-Z_]\w*)?', Name.Variable.Class),
  450. (r'[A-Z]\w*', Name.Class), # proper name
  451. (words(all_lua_builtins(), suffix=r"\b"), Name.Builtin),
  452. (r'[A-Za-z_]\w*', Name),
  453. ("'", String.Single, combined('stringescape', 'sqs')),
  454. ('"', String.Double, combined('stringescape', 'dqs'))
  455. ],
  456. 'stringescape': [
  457. (r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
  458. ],
  459. 'strings': [
  460. (r'[^#\\\'"]+', String),
  461. # note that strings are multi-line.
  462. # hashmarks, quotes and backslashes must be parsed one at a time
  463. ],
  464. 'interpoling_string': [
  465. (r'\}', String.Interpol, "#pop"),
  466. include('base')
  467. ],
  468. 'dqs': [
  469. (r'"', String.Double, '#pop'),
  470. (r'\\.|\'', String), # double-quoted string don't need ' escapes
  471. (r'#\{', String.Interpol, "interpoling_string"),
  472. (r'#', String),
  473. include('strings')
  474. ],
  475. 'sqs': [
  476. (r"'", String.Single, '#pop'),
  477. (r'#|\\.|"', String), # single quoted strings don't need " escapses
  478. include('strings')
  479. ]
  480. }
  481. def get_tokens_unprocessed(self, text):
  482. # set . as Operator instead of Punctuation
  483. for index, token, value in LuaLexer.get_tokens_unprocessed(self, text):
  484. if token == Punctuation and value == ".":
  485. token = Operator
  486. yield index, token, value
  487. class ChaiscriptLexer(RegexLexer):
  488. """
  489. For ChaiScript source code.
  490. """
  491. name = 'ChaiScript'
  492. url = 'http://chaiscript.com/'
  493. aliases = ['chaiscript', 'chai']
  494. filenames = ['*.chai']
  495. mimetypes = ['text/x-chaiscript', 'application/x-chaiscript']
  496. version_added = '2.0'
  497. flags = re.DOTALL | re.MULTILINE
  498. tokens = {
  499. 'commentsandwhitespace': [
  500. (r'\s+', Text),
  501. (r'//.*?\n', Comment.Single),
  502. (r'/\*.*?\*/', Comment.Multiline),
  503. (r'^\#.*?\n', Comment.Single)
  504. ],
  505. 'slashstartsregex': [
  506. include('commentsandwhitespace'),
  507. (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
  508. r'([gim]+\b|\B)', String.Regex, '#pop'),
  509. (r'(?=/)', Text, ('#pop', 'badregex')),
  510. default('#pop')
  511. ],
  512. 'badregex': [
  513. (r'\n', Text, '#pop')
  514. ],
  515. 'root': [
  516. include('commentsandwhitespace'),
  517. (r'\n', Text),
  518. (r'[^\S\n]+', Text),
  519. (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|\.\.'
  520. r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'),
  521. (r'[{(\[;,]', Punctuation, 'slashstartsregex'),
  522. (r'[})\].]', Punctuation),
  523. (r'[=+\-*/]', Operator),
  524. (r'(for|in|while|do|break|return|continue|if|else|'
  525. r'throw|try|catch'
  526. r')\b', Keyword, 'slashstartsregex'),
  527. (r'(var)\b', Keyword.Declaration, 'slashstartsregex'),
  528. (r'(attr|def|fun)\b', Keyword.Reserved),
  529. (r'(true|false)\b', Keyword.Constant),
  530. (r'(eval|throw)\b', Name.Builtin),
  531. (r'`\S+`', Name.Builtin),
  532. (r'[$a-zA-Z_]\w*', Name.Other),
  533. (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
  534. (r'0x[0-9a-fA-F]+', Number.Hex),
  535. (r'[0-9]+', Number.Integer),
  536. (r'"', String.Double, 'dqstring'),
  537. (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
  538. ],
  539. 'dqstring': [
  540. (r'\$\{[^"}]+?\}', String.Interpol),
  541. (r'\$', String.Double),
  542. (r'\\\\', String.Double),
  543. (r'\\"', String.Double),
  544. (r'[^\\"$]+', String.Double),
  545. (r'"', String.Double, '#pop'),
  546. ],
  547. }
  548. class LSLLexer(RegexLexer):
  549. """
  550. For Second Life's Linden Scripting Language source code.
  551. """
  552. name = 'LSL'
  553. aliases = ['lsl']
  554. filenames = ['*.lsl']
  555. mimetypes = ['text/x-lsl']
  556. url = 'https://wiki.secondlife.com/wiki/Linden_Scripting_Language'
  557. version_added = '2.0'
  558. flags = re.MULTILINE
  559. lsl_keywords = r'\b(?:do|else|for|if|jump|return|while)\b'
  560. lsl_types = r'\b(?:float|integer|key|list|quaternion|rotation|string|vector)\b'
  561. lsl_states = r'\b(?:(?:state)\s+\w+|default)\b'
  562. 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'
  563. 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'
  564. lsl_constants_float = r'\b(?:DEG_TO_RAD|PI(?:_BY_TWO)?|RAD_TO_DEG|SQRT2|TWO_PI)\b'
  565. 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'
  566. lsl_constants_integer_boolean = r'\b(?:FALSE|TRUE)\b'
  567. lsl_constants_rotation = r'\b(?:ZERO_ROTATION)\b'
  568. 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'
  569. lsl_constants_vector = r'\b(?:TOUCH_INVALID_(?:TEXCOORD|VECTOR)|ZERO_VECTOR)\b'
  570. lsl_invalid_broken = r'\b(?:LAND_(?:LARGE|MEDIUM|SMALL)_BRUSH)\b'
  571. 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'
  572. lsl_invalid_illegal = r'\b(?:event)\b'
  573. 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'
  574. lsl_reserved_godmode = r'\b(?:ll(?:GodLikeRezObject|Set(?:Inventory|Object)PermMask))\b'
  575. lsl_reserved_log = r'\b(?:print)\b'
  576. lsl_operators = r'\+\+|\-\-|<<|>>|&&?|\|\|?|\^|~|[!%<>=*+\-/]=?'
  577. tokens = {
  578. 'root':
  579. [
  580. (r'//.*?\n', Comment.Single),
  581. (r'/\*', Comment.Multiline, 'comment'),
  582. (r'"', String.Double, 'string'),
  583. (lsl_keywords, Keyword),
  584. (lsl_types, Keyword.Type),
  585. (lsl_states, Name.Class),
  586. (lsl_events, Name.Builtin),
  587. (lsl_functions_builtin, Name.Function),
  588. (lsl_constants_float, Keyword.Constant),
  589. (lsl_constants_integer, Keyword.Constant),
  590. (lsl_constants_integer_boolean, Keyword.Constant),
  591. (lsl_constants_rotation, Keyword.Constant),
  592. (lsl_constants_string, Keyword.Constant),
  593. (lsl_constants_vector, Keyword.Constant),
  594. (lsl_invalid_broken, Error),
  595. (lsl_invalid_deprecated, Error),
  596. (lsl_invalid_illegal, Error),
  597. (lsl_invalid_unimplemented, Error),
  598. (lsl_reserved_godmode, Keyword.Reserved),
  599. (lsl_reserved_log, Keyword.Reserved),
  600. (r'\b([a-zA-Z_]\w*)\b', Name.Variable),
  601. (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d*', Number.Float),
  602. (r'(\d+\.\d*|\.\d+)', Number.Float),
  603. (r'0[xX][0-9a-fA-F]+', Number.Hex),
  604. (r'\d+', Number.Integer),
  605. (lsl_operators, Operator),
  606. (r':=?', Error),
  607. (r'[,;{}()\[\]]', Punctuation),
  608. (r'\n+', Whitespace),
  609. (r'\s+', Whitespace)
  610. ],
  611. 'comment':
  612. [
  613. (r'[^*/]+', Comment.Multiline),
  614. (r'/\*', Comment.Multiline, '#push'),
  615. (r'\*/', Comment.Multiline, '#pop'),
  616. (r'[*/]', Comment.Multiline)
  617. ],
  618. 'string':
  619. [
  620. (r'\\([nt"\\])', String.Escape),
  621. (r'"', String.Double, '#pop'),
  622. (r'\\.', Error),
  623. (r'[^"\\]+', String.Double),
  624. ]
  625. }
  626. class AppleScriptLexer(RegexLexer):
  627. """
  628. For AppleScript source code,
  629. including `AppleScript Studio
  630. <http://developer.apple.com/documentation/AppleScript/
  631. Reference/StudioReference>`_.
  632. Contributed by Andreas Amann <aamann@mac.com>.
  633. """
  634. name = 'AppleScript'
  635. url = 'https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html'
  636. aliases = ['applescript']
  637. filenames = ['*.applescript']
  638. version_added = '1.0'
  639. flags = re.MULTILINE | re.DOTALL
  640. Identifiers = r'[a-zA-Z]\w*'
  641. # XXX: use words() for all of these
  642. Literals = ('AppleScript', 'current application', 'false', 'linefeed',
  643. 'missing value', 'pi', 'quote', 'result', 'return', 'space',
  644. 'tab', 'text item delimiters', 'true', 'version')
  645. Classes = ('alias ', 'application ', 'boolean ', 'class ', 'constant ',
  646. 'date ', 'file ', 'integer ', 'list ', 'number ', 'POSIX file ',
  647. 'real ', 'record ', 'reference ', 'RGB color ', 'script ',
  648. 'text ', 'unit types', '(?:Unicode )?text', 'string')
  649. BuiltIn = ('attachment', 'attribute run', 'character', 'day', 'month',
  650. 'paragraph', 'word', 'year')
  651. HandlerParams = ('about', 'above', 'against', 'apart from', 'around',
  652. 'aside from', 'at', 'below', 'beneath', 'beside',
  653. 'between', 'for', 'given', 'instead of', 'on', 'onto',
  654. 'out of', 'over', 'since')
  655. Commands = ('ASCII (character|number)', 'activate', 'beep', 'choose URL',
  656. 'choose application', 'choose color', 'choose file( name)?',
  657. 'choose folder', 'choose from list',
  658. 'choose remote application', 'clipboard info',
  659. 'close( access)?', 'copy', 'count', 'current date', 'delay',
  660. 'delete', 'display (alert|dialog)', 'do shell script',
  661. 'duplicate', 'exists', 'get eof', 'get volume settings',
  662. 'info for', 'launch', 'list (disks|folder)', 'load script',
  663. 'log', 'make', 'mount volume', 'new', 'offset',
  664. 'open( (for access|location))?', 'path to', 'print', 'quit',
  665. 'random number', 'read', 'round', 'run( script)?',
  666. 'say', 'scripting components',
  667. 'set (eof|the clipboard to|volume)', 'store script',
  668. 'summarize', 'system attribute', 'system info',
  669. 'the clipboard', 'time to GMT', 'write', 'quoted form')
  670. References = ('(in )?back of', '(in )?front of', '[0-9]+(st|nd|rd|th)',
  671. 'first', 'second', 'third', 'fourth', 'fifth', 'sixth',
  672. 'seventh', 'eighth', 'ninth', 'tenth', 'after', 'back',
  673. 'before', 'behind', 'every', 'front', 'index', 'last',
  674. 'middle', 'some', 'that', 'through', 'thru', 'where', 'whose')
  675. Operators = ("and", "or", "is equal", "equals", "(is )?equal to", "is not",
  676. "isn't", "isn't equal( to)?", "is not equal( to)?",
  677. "doesn't equal", "does not equal", "(is )?greater than",
  678. "comes after", "is not less than or equal( to)?",
  679. "isn't less than or equal( to)?", "(is )?less than",
  680. "comes before", "is not greater than or equal( to)?",
  681. "isn't greater than or equal( to)?",
  682. "(is )?greater than or equal( to)?", "is not less than",
  683. "isn't less than", "does not come before",
  684. "doesn't come before", "(is )?less than or equal( to)?",
  685. "is not greater than", "isn't greater than",
  686. "does not come after", "doesn't come after", "starts? with",
  687. "begins? with", "ends? with", "contains?", "does not contain",
  688. "doesn't contain", "is in", "is contained by", "is not in",
  689. "is not contained by", "isn't contained by", "div", "mod",
  690. "not", "(a )?(ref( to)?|reference to)", "is", "does")
  691. Control = ('considering', 'else', 'error', 'exit', 'from', 'if',
  692. 'ignoring', 'in', 'repeat', 'tell', 'then', 'times', 'to',
  693. 'try', 'until', 'using terms from', 'while', 'whith',
  694. 'with timeout( of)?', 'with transaction', 'by', 'continue',
  695. 'end', 'its?', 'me', 'my', 'return', 'of', 'as')
  696. Declarations = ('global', 'local', 'prop(erty)?', 'set', 'get')
  697. Reserved = ('but', 'put', 'returning', 'the')
  698. StudioClasses = ('action cell', 'alert reply', 'application', 'box',
  699. 'browser( cell)?', 'bundle', 'button( cell)?', 'cell',
  700. 'clip view', 'color well', 'color-panel',
  701. 'combo box( item)?', 'control',
  702. 'data( (cell|column|item|row|source))?', 'default entry',
  703. 'dialog reply', 'document', 'drag info', 'drawer',
  704. 'event', 'font(-panel)?', 'formatter',
  705. 'image( (cell|view))?', 'matrix', 'menu( item)?', 'item',
  706. 'movie( view)?', 'open-panel', 'outline view', 'panel',
  707. 'pasteboard', 'plugin', 'popup button',
  708. 'progress indicator', 'responder', 'save-panel',
  709. 'scroll view', 'secure text field( cell)?', 'slider',
  710. 'sound', 'split view', 'stepper', 'tab view( item)?',
  711. 'table( (column|header cell|header view|view))',
  712. 'text( (field( cell)?|view))?', 'toolbar( item)?',
  713. 'user-defaults', 'view', 'window')
  714. StudioEvents = ('accept outline drop', 'accept table drop', 'action',
  715. 'activated', 'alert ended', 'awake from nib', 'became key',
  716. 'became main', 'begin editing', 'bounds changed',
  717. 'cell value', 'cell value changed', 'change cell value',
  718. 'change item value', 'changed', 'child of item',
  719. 'choose menu item', 'clicked', 'clicked toolbar item',
  720. 'closed', 'column clicked', 'column moved',
  721. 'column resized', 'conclude drop', 'data representation',
  722. 'deminiaturized', 'dialog ended', 'document nib name',
  723. 'double clicked', 'drag( (entered|exited|updated))?',
  724. 'drop', 'end editing', 'exposed', 'idle', 'item expandable',
  725. 'item value', 'item value changed', 'items changed',
  726. 'keyboard down', 'keyboard up', 'launched',
  727. 'load data representation', 'miniaturized', 'mouse down',
  728. 'mouse dragged', 'mouse entered', 'mouse exited',
  729. 'mouse moved', 'mouse up', 'moved',
  730. 'number of browser rows', 'number of items',
  731. 'number of rows', 'open untitled', 'opened', 'panel ended',
  732. 'parameters updated', 'plugin loaded', 'prepare drop',
  733. 'prepare outline drag', 'prepare outline drop',
  734. 'prepare table drag', 'prepare table drop',
  735. 'read from file', 'resigned active', 'resigned key',
  736. 'resigned main', 'resized( sub views)?',
  737. 'right mouse down', 'right mouse dragged',
  738. 'right mouse up', 'rows changed', 'scroll wheel',
  739. 'selected tab view item', 'selection changed',
  740. 'selection changing', 'should begin editing',
  741. 'should close', 'should collapse item',
  742. 'should end editing', 'should expand item',
  743. 'should open( untitled)?',
  744. 'should quit( after last window closed)?',
  745. 'should select column', 'should select item',
  746. 'should select row', 'should select tab view item',
  747. 'should selection change', 'should zoom', 'shown',
  748. 'update menu item', 'update parameters',
  749. 'update toolbar item', 'was hidden', 'was miniaturized',
  750. 'will become active', 'will close', 'will dismiss',
  751. 'will display browser cell', 'will display cell',
  752. 'will display item cell', 'will display outline cell',
  753. 'will finish launching', 'will hide', 'will miniaturize',
  754. 'will move', 'will open', 'will pop up', 'will quit',
  755. 'will resign active', 'will resize( sub views)?',
  756. 'will select tab view item', 'will show', 'will zoom',
  757. 'write to file', 'zoomed')
  758. StudioCommands = ('animate', 'append', 'call method', 'center',
  759. 'close drawer', 'close panel', 'display',
  760. 'display alert', 'display dialog', 'display panel', 'go',
  761. 'hide', 'highlight', 'increment', 'item for',
  762. 'load image', 'load movie', 'load nib', 'load panel',
  763. 'load sound', 'localized string', 'lock focus', 'log',
  764. 'open drawer', 'path for', 'pause', 'perform action',
  765. 'play', 'register', 'resume', 'scroll', 'select( all)?',
  766. 'show', 'size to fit', 'start', 'step back',
  767. 'step forward', 'stop', 'synchronize', 'unlock focus',
  768. 'update')
  769. StudioProperties = ('accepts arrow key', 'action method', 'active',
  770. 'alignment', 'allowed identifiers',
  771. 'allows branch selection', 'allows column reordering',
  772. 'allows column resizing', 'allows column selection',
  773. 'allows customization',
  774. 'allows editing text attributes',
  775. 'allows empty selection', 'allows mixed state',
  776. 'allows multiple selection', 'allows reordering',
  777. 'allows undo', 'alpha( value)?', 'alternate image',
  778. 'alternate increment value', 'alternate title',
  779. 'animation delay', 'associated file name',
  780. 'associated object', 'auto completes', 'auto display',
  781. 'auto enables items', 'auto repeat',
  782. 'auto resizes( outline column)?',
  783. 'auto save expanded items', 'auto save name',
  784. 'auto save table columns', 'auto saves configuration',
  785. 'auto scroll', 'auto sizes all columns to fit',
  786. 'auto sizes cells', 'background color', 'bezel state',
  787. 'bezel style', 'bezeled', 'border rect', 'border type',
  788. 'bordered', 'bounds( rotation)?', 'box type',
  789. 'button returned', 'button type',
  790. 'can choose directories', 'can choose files',
  791. 'can draw', 'can hide',
  792. 'cell( (background color|size|type))?', 'characters',
  793. 'class', 'click count', 'clicked( data)? column',
  794. 'clicked data item', 'clicked( data)? row',
  795. 'closeable', 'collating', 'color( (mode|panel))',
  796. 'command key down', 'configuration',
  797. 'content(s| (size|view( margins)?))?', 'context',
  798. 'continuous', 'control key down', 'control size',
  799. 'control tint', 'control view',
  800. 'controller visible', 'coordinate system',
  801. 'copies( on scroll)?', 'corner view', 'current cell',
  802. 'current column', 'current( field)? editor',
  803. 'current( menu)? item', 'current row',
  804. 'current tab view item', 'data source',
  805. 'default identifiers', 'delta (x|y|z)',
  806. 'destination window', 'directory', 'display mode',
  807. 'displayed cell', 'document( (edited|rect|view))?',
  808. 'double value', 'dragged column', 'dragged distance',
  809. 'dragged items', 'draws( cell)? background',
  810. 'draws grid', 'dynamically scrolls', 'echos bullets',
  811. 'edge', 'editable', 'edited( data)? column',
  812. 'edited data item', 'edited( data)? row', 'enabled',
  813. 'enclosing scroll view', 'ending page',
  814. 'error handling', 'event number', 'event type',
  815. 'excluded from windows menu', 'executable path',
  816. 'expanded', 'fax number', 'field editor', 'file kind',
  817. 'file name', 'file type', 'first responder',
  818. 'first visible column', 'flipped', 'floating',
  819. 'font( panel)?', 'formatter', 'frameworks path',
  820. 'frontmost', 'gave up', 'grid color', 'has data items',
  821. 'has horizontal ruler', 'has horizontal scroller',
  822. 'has parent data item', 'has resize indicator',
  823. 'has shadow', 'has sub menu', 'has vertical ruler',
  824. 'has vertical scroller', 'header cell', 'header view',
  825. 'hidden', 'hides when deactivated', 'highlights by',
  826. 'horizontal line scroll', 'horizontal page scroll',
  827. 'horizontal ruler view', 'horizontally resizable',
  828. 'icon image', 'id', 'identifier',
  829. 'ignores multiple clicks',
  830. 'image( (alignment|dims when disabled|frame style|scaling))?',
  831. 'imports graphics', 'increment value',
  832. 'indentation per level', 'indeterminate', 'index',
  833. 'integer value', 'intercell spacing', 'item height',
  834. 'key( (code|equivalent( modifier)?|window))?',
  835. 'knob thickness', 'label', 'last( visible)? column',
  836. 'leading offset', 'leaf', 'level', 'line scroll',
  837. 'loaded', 'localized sort', 'location', 'loop mode',
  838. 'main( (bunde|menu|window))?', 'marker follows cell',
  839. 'matrix mode', 'maximum( content)? size',
  840. 'maximum visible columns',
  841. 'menu( form representation)?', 'miniaturizable',
  842. 'miniaturized', 'minimized image', 'minimized title',
  843. 'minimum column width', 'minimum( content)? size',
  844. 'modal', 'modified', 'mouse down state',
  845. 'movie( (controller|file|rect))?', 'muted', 'name',
  846. 'needs display', 'next state', 'next text',
  847. 'number of tick marks', 'only tick mark values',
  848. 'opaque', 'open panel', 'option key down',
  849. 'outline table column', 'page scroll', 'pages across',
  850. 'pages down', 'palette label', 'pane splitter',
  851. 'parent data item', 'parent window', 'pasteboard',
  852. 'path( (names|separator))?', 'playing',
  853. 'plays every frame', 'plays selection only', 'position',
  854. 'preferred edge', 'preferred type', 'pressure',
  855. 'previous text', 'prompt', 'properties',
  856. 'prototype cell', 'pulls down', 'rate',
  857. 'released when closed', 'repeated',
  858. 'requested print time', 'required file type',
  859. 'resizable', 'resized column', 'resource path',
  860. 'returns records', 'reuses columns', 'rich text',
  861. 'roll over', 'row height', 'rulers visible',
  862. 'save panel', 'scripts path', 'scrollable',
  863. 'selectable( identifiers)?', 'selected cell',
  864. 'selected( data)? columns?', 'selected data items?',
  865. 'selected( data)? rows?', 'selected item identifier',
  866. 'selection by rect', 'send action on arrow key',
  867. 'sends action when done editing', 'separates columns',
  868. 'separator item', 'sequence number', 'services menu',
  869. 'shared frameworks path', 'shared support path',
  870. 'sheet', 'shift key down', 'shows alpha',
  871. 'shows state by', 'size( mode)?',
  872. 'smart insert delete enabled', 'sort case sensitivity',
  873. 'sort column', 'sort order', 'sort type',
  874. 'sorted( data rows)?', 'sound', 'source( mask)?',
  875. 'spell checking enabled', 'starting page', 'state',
  876. 'string value', 'sub menu', 'super menu', 'super view',
  877. 'tab key traverses cells', 'tab state', 'tab type',
  878. 'tab view', 'table view', 'tag', 'target( printer)?',
  879. 'text color', 'text container insert',
  880. 'text container origin', 'text returned',
  881. 'tick mark position', 'time stamp',
  882. 'title(d| (cell|font|height|position|rect))?',
  883. 'tool tip', 'toolbar', 'trailing offset', 'transparent',
  884. 'treat packages as directories', 'truncated labels',
  885. 'types', 'unmodified characters', 'update views',
  886. 'use sort indicator', 'user defaults',
  887. 'uses data source', 'uses ruler',
  888. 'uses threaded animation',
  889. 'uses title from previous column', 'value wraps',
  890. 'version',
  891. 'vertical( (line scroll|page scroll|ruler view))?',
  892. 'vertically resizable', 'view',
  893. 'visible( document rect)?', 'volume', 'width', 'window',
  894. 'windows menu', 'wraps', 'zoomable', 'zoomed')
  895. tokens = {
  896. 'root': [
  897. (r'\s+', Text),
  898. (r'¬\n', String.Escape),
  899. (r"'s\s+", Text), # This is a possessive, consider moving
  900. (r'(--|#).*?$', Comment),
  901. (r'\(\*', Comment.Multiline, 'comment'),
  902. (r'[(){}!,.:]', Punctuation),
  903. (r'(«)([^»]+)(»)',
  904. bygroups(Text, Name.Builtin, Text)),
  905. (r'\b((?:considering|ignoring)\s*)'
  906. r'(application responses|case|diacriticals|hyphens|'
  907. r'numeric strings|punctuation|white space)',
  908. bygroups(Keyword, Name.Builtin)),
  909. (r'(-|\*|\+|&|≠|>=?|<=?|=|≥|≤|/|÷|\^)', Operator),
  910. (r"\b({})\b".format('|'.join(Operators)), Operator.Word),
  911. (r'^(\s*(?:on|end)\s+)'
  912. r'({})'.format('|'.join(StudioEvents[::-1])),
  913. bygroups(Keyword, Name.Function)),
  914. (r'^(\s*)(in|on|script|to)(\s+)', bygroups(Text, Keyword, Text)),
  915. (r'\b(as )({})\b'.format('|'.join(Classes)),
  916. bygroups(Keyword, Name.Class)),
  917. (r'\b({})\b'.format('|'.join(Literals)), Name.Constant),
  918. (r'\b({})\b'.format('|'.join(Commands)), Name.Builtin),
  919. (r'\b({})\b'.format('|'.join(Control)), Keyword),
  920. (r'\b({})\b'.format('|'.join(Declarations)), Keyword),
  921. (r'\b({})\b'.format('|'.join(Reserved)), Name.Builtin),
  922. (r'\b({})s?\b'.format('|'.join(BuiltIn)), Name.Builtin),
  923. (r'\b({})\b'.format('|'.join(HandlerParams)), Name.Builtin),
  924. (r'\b({})\b'.format('|'.join(StudioProperties)), Name.Attribute),
  925. (r'\b({})s?\b'.format('|'.join(StudioClasses)), Name.Builtin),
  926. (r'\b({})\b'.format('|'.join(StudioCommands)), Name.Builtin),
  927. (r'\b({})\b'.format('|'.join(References)), Name.Builtin),
  928. (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
  929. (rf'\b({Identifiers})\b', Name.Variable),
  930. (r'[-+]?(\d+\.\d*|\d*\.\d+)(E[-+][0-9]+)?', Number.Float),
  931. (r'[-+]?\d+', Number.Integer),
  932. ],
  933. 'comment': [
  934. (r'\(\*', Comment.Multiline, '#push'),
  935. (r'\*\)', Comment.Multiline, '#pop'),
  936. ('[^*(]+', Comment.Multiline),
  937. ('[*(]', Comment.Multiline),
  938. ],
  939. }
  940. class RexxLexer(RegexLexer):
  941. """
  942. Rexx is a scripting language available for
  943. a wide range of different platforms with its roots found on mainframe
  944. systems. It is popular for I/O- and data based tasks and can act as glue
  945. language to bind different applications together.
  946. """
  947. name = 'Rexx'
  948. url = 'http://www.rexxinfo.org/'
  949. aliases = ['rexx', 'arexx']
  950. filenames = ['*.rexx', '*.rex', '*.rx', '*.arexx']
  951. mimetypes = ['text/x-rexx']
  952. version_added = '2.0'
  953. flags = re.IGNORECASE
  954. tokens = {
  955. 'root': [
  956. (r'\s+', Whitespace),
  957. (r'/\*', Comment.Multiline, 'comment'),
  958. (r'"', String, 'string_double'),
  959. (r"'", String, 'string_single'),
  960. (r'[0-9]+(\.[0-9]+)?(e[+-]?[0-9])?', Number),
  961. (r'([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b',
  962. bygroups(Name.Function, Whitespace, Operator, Whitespace,
  963. Keyword.Declaration)),
  964. (r'([a-z_]\w*)(\s*)(:)',
  965. bygroups(Name.Label, Whitespace, Operator)),
  966. include('function'),
  967. include('keyword'),
  968. include('operator'),
  969. (r'[a-z_]\w*', Text),
  970. ],
  971. 'function': [
  972. (words((
  973. 'abbrev', 'abs', 'address', 'arg', 'b2x', 'bitand', 'bitor', 'bitxor',
  974. 'c2d', 'c2x', 'center', 'charin', 'charout', 'chars', 'compare',
  975. 'condition', 'copies', 'd2c', 'd2x', 'datatype', 'date', 'delstr',
  976. 'delword', 'digits', 'errortext', 'form', 'format', 'fuzz', 'insert',
  977. 'lastpos', 'left', 'length', 'linein', 'lineout', 'lines', 'max',
  978. 'min', 'overlay', 'pos', 'queued', 'random', 'reverse', 'right', 'sign',
  979. 'sourceline', 'space', 'stream', 'strip', 'substr', 'subword', 'symbol',
  980. 'time', 'trace', 'translate', 'trunc', 'value', 'verify', 'word',
  981. 'wordindex', 'wordlength', 'wordpos', 'words', 'x2b', 'x2c', 'x2d',
  982. 'xrange'), suffix=r'(\s*)(\()'),
  983. bygroups(Name.Builtin, Whitespace, Operator)),
  984. ],
  985. 'keyword': [
  986. (r'(address|arg|by|call|do|drop|else|end|exit|for|forever|if|'
  987. r'interpret|iterate|leave|nop|numeric|off|on|options|parse|'
  988. r'pull|push|queue|return|say|select|signal|to|then|trace|until|'
  989. r'while)\b', Keyword.Reserved),
  990. ],
  991. 'operator': [
  992. (r'(-|//|/|\(|\)|\*\*|\*|\\<<|\\<|\\==|\\=|\\>>|\\>|\\|\|\||\||'
  993. r'&&|&|%|\+|<<=|<<|<=|<>|<|==|=|><|>=|>>=|>>|>|¬<<|¬<|¬==|¬=|'
  994. r'¬>>|¬>|¬|\.|,)', Operator),
  995. ],
  996. 'string_double': [
  997. (r'[^"\n]+', String),
  998. (r'""', String),
  999. (r'"', String, '#pop'),
  1000. (r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
  1001. ],
  1002. 'string_single': [
  1003. (r'[^\'\n]+', String),
  1004. (r'\'\'', String),
  1005. (r'\'', String, '#pop'),
  1006. (r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
  1007. ],
  1008. 'comment': [
  1009. (r'[^*]+', Comment.Multiline),
  1010. (r'\*/', Comment.Multiline, '#pop'),
  1011. (r'\*', Comment.Multiline),
  1012. ]
  1013. }
  1014. def _c(s):
  1015. return re.compile(s, re.MULTILINE)
  1016. _ADDRESS_COMMAND_PATTERN = _c(r'^\s*address\s+command\b')
  1017. _ADDRESS_PATTERN = _c(r'^\s*address\s+')
  1018. _DO_WHILE_PATTERN = _c(r'^\s*do\s+while\b')
  1019. _IF_THEN_DO_PATTERN = _c(r'^\s*if\b.+\bthen\s+do\s*$')
  1020. _PROCEDURE_PATTERN = _c(r'^\s*([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b')
  1021. _ELSE_DO_PATTERN = _c(r'\belse\s+do\s*$')
  1022. _PARSE_ARG_PATTERN = _c(r'^\s*parse\s+(upper\s+)?(arg|value)\b')
  1023. PATTERNS_AND_WEIGHTS = (
  1024. (_ADDRESS_COMMAND_PATTERN, 0.2),
  1025. (_ADDRESS_PATTERN, 0.05),
  1026. (_DO_WHILE_PATTERN, 0.1),
  1027. (_ELSE_DO_PATTERN, 0.1),
  1028. (_IF_THEN_DO_PATTERN, 0.1),
  1029. (_PROCEDURE_PATTERN, 0.5),
  1030. (_PARSE_ARG_PATTERN, 0.2),
  1031. )
  1032. def analyse_text(text):
  1033. """
  1034. Check for initial comment and patterns that distinguish Rexx from other
  1035. C-like languages.
  1036. """
  1037. if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE):
  1038. # Header matches MVS Rexx requirements, this is certainly a Rexx
  1039. # script.
  1040. return 1.0
  1041. elif text.startswith('/*'):
  1042. # Header matches general Rexx requirements; the source code might
  1043. # still be any language using C comments such as C++, C# or Java.
  1044. lowerText = text.lower()
  1045. result = sum(weight
  1046. for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS
  1047. if pattern.search(lowerText)) + 0.01
  1048. return min(result, 1.0)
  1049. class MOOCodeLexer(RegexLexer):
  1050. """
  1051. For MOOCode (the MOO scripting language).
  1052. """
  1053. name = 'MOOCode'
  1054. url = 'http://www.moo.mud.org/'
  1055. filenames = ['*.moo']
  1056. aliases = ['moocode', 'moo']
  1057. mimetypes = ['text/x-moocode']
  1058. version_added = '0.9'
  1059. tokens = {
  1060. 'root': [
  1061. # Numbers
  1062. (r'(0|[1-9][0-9_]*)', Number.Integer),
  1063. # Strings
  1064. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  1065. # exceptions
  1066. (r'(E_PERM|E_DIV)', Name.Exception),
  1067. # db-refs
  1068. (r'((#[-0-9]+)|(\$\w+))', Name.Entity),
  1069. # Keywords
  1070. (r'\b(if|else|elseif|endif|for|endfor|fork|endfork|while'
  1071. r'|endwhile|break|continue|return|try'
  1072. r'|except|endtry|finally|in)\b', Keyword),
  1073. # builtins
  1074. (r'(random|length)', Name.Builtin),
  1075. # special variables
  1076. (r'(player|caller|this|args)', Name.Variable.Instance),
  1077. # skip whitespace
  1078. (r'\s+', Text),
  1079. (r'\n', Text),
  1080. # other operators
  1081. (r'([!;=,{}&|:.\[\]@()<>?]+)', Operator),
  1082. # function call
  1083. (r'(\w+)(\()', bygroups(Name.Function, Operator)),
  1084. # variables
  1085. (r'(\w+)', Text),
  1086. ]
  1087. }
  1088. class HybrisLexer(RegexLexer):
  1089. """
  1090. For Hybris source code.
  1091. """
  1092. name = 'Hybris'
  1093. aliases = ['hybris']
  1094. filenames = ['*.hyb']
  1095. mimetypes = ['text/x-hybris', 'application/x-hybris']
  1096. url = 'https://github.com/evilsocket/hybris'
  1097. version_added = '1.4'
  1098. flags = re.MULTILINE | re.DOTALL
  1099. tokens = {
  1100. 'root': [
  1101. # method names
  1102. (r'^(\s*(?:function|method|operator\s+)+?)'
  1103. r'([a-zA-Z_]\w*)'
  1104. r'(\s*)(\()', bygroups(Keyword, Name.Function, Text, Operator)),
  1105. (r'[^\S\n]+', Text),
  1106. (r'//.*?\n', Comment.Single),
  1107. (r'/\*.*?\*/', Comment.Multiline),
  1108. (r'@[a-zA-Z_][\w.]*', Name.Decorator),
  1109. (r'(break|case|catch|next|default|do|else|finally|for|foreach|of|'
  1110. r'unless|if|new|return|switch|me|throw|try|while)\b', Keyword),
  1111. (r'(extends|private|protected|public|static|throws|function|method|'
  1112. r'operator)\b', Keyword.Declaration),
  1113. (r'(true|false|null|__FILE__|__LINE__|__VERSION__|__LIB_PATH__|'
  1114. r'__INC_PATH__)\b', Keyword.Constant),
  1115. (r'(class|struct)(\s+)',
  1116. bygroups(Keyword.Declaration, Text), 'class'),
  1117. (r'(import|include)(\s+)',
  1118. bygroups(Keyword.Namespace, Text), 'import'),
  1119. (words((
  1120. 'gc_collect', 'gc_mm_items', 'gc_mm_usage', 'gc_collect_threshold',
  1121. 'urlencode', 'urldecode', 'base64encode', 'base64decode', 'sha1', 'crc32',
  1122. 'sha2', 'md5', 'md5_file', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
  1123. 'cosh', 'exp', 'fabs', 'floor', 'fmod', 'log', 'log10', 'pow', 'sin',
  1124. 'sinh', 'sqrt', 'tan', 'tanh', 'isint', 'isfloat', 'ischar', 'isstring',
  1125. 'isarray', 'ismap', 'isalias', 'typeof', 'sizeof', 'toint', 'tostring',
  1126. 'fromxml', 'toxml', 'binary', 'pack', 'load', 'eval', 'var_names',
  1127. 'var_values', 'user_functions', 'dyn_functions', 'methods', 'call',
  1128. 'call_method', 'mknod', 'mkfifo', 'mount', 'umount2', 'umount', 'ticks',
  1129. 'usleep', 'sleep', 'time', 'strtime', 'strdate', 'dllopen', 'dlllink',
  1130. 'dllcall', 'dllcall_argv', 'dllclose', 'env', 'exec', 'fork', 'getpid',
  1131. 'wait', 'popen', 'pclose', 'exit', 'kill', 'pthread_create',
  1132. 'pthread_create_argv', 'pthread_exit', 'pthread_join', 'pthread_kill',
  1133. 'smtp_send', 'http_get', 'http_post', 'http_download', 'socket', 'bind',
  1134. 'listen', 'accept', 'getsockname', 'getpeername', 'settimeout', 'connect',
  1135. 'server', 'recv', 'send', 'close', 'print', 'println', 'printf', 'input',
  1136. 'readline', 'serial_open', 'serial_fcntl', 'serial_get_attr',
  1137. 'serial_get_ispeed', 'serial_get_ospeed', 'serial_set_attr',
  1138. 'serial_set_ispeed', 'serial_set_ospeed', 'serial_write', 'serial_read',
  1139. 'serial_close', 'xml_load', 'xml_parse', 'fopen', 'fseek', 'ftell',
  1140. 'fsize', 'fread', 'fwrite', 'fgets', 'fclose', 'file', 'readdir',
  1141. 'pcre_replace', 'size', 'pop', 'unmap', 'has', 'keys', 'values',
  1142. 'length', 'find', 'substr', 'replace', 'split', 'trim', 'remove',
  1143. 'contains', 'join'), suffix=r'\b'),
  1144. Name.Builtin),
  1145. (words((
  1146. 'MethodReference', 'Runner', 'Dll', 'Thread', 'Pipe', 'Process',
  1147. 'Runnable', 'CGI', 'ClientSocket', 'Socket', 'ServerSocket',
  1148. 'File', 'Console', 'Directory', 'Exception'), suffix=r'\b'),
  1149. Keyword.Type),
  1150. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  1151. (r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char),
  1152. (r'(\.)([a-zA-Z_]\w*)',
  1153. bygroups(Operator, Name.Attribute)),
  1154. (r'[a-zA-Z_]\w*:', Name.Label),
  1155. (r'[a-zA-Z_$]\w*', Name),
  1156. (r'[~^*!%&\[\](){}<>|+=:;,./?\-@]+', Operator),
  1157. (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
  1158. (r'0x[0-9a-f]+', Number.Hex),
  1159. (r'[0-9]+L?', Number.Integer),
  1160. (r'\n', Text),
  1161. ],
  1162. 'class': [
  1163. (r'[a-zA-Z_]\w*', Name.Class, '#pop')
  1164. ],
  1165. 'import': [
  1166. (r'[\w.]+\*?', Name.Namespace, '#pop')
  1167. ],
  1168. }
  1169. def analyse_text(text):
  1170. """public method and private method don't seem to be quite common
  1171. elsewhere."""
  1172. result = 0
  1173. if re.search(r'\b(?:public|private)\s+method\b', text):
  1174. result += 0.01
  1175. return result
  1176. class EasytrieveLexer(RegexLexer):
  1177. """
  1178. Easytrieve Plus is a programming language for extracting, filtering and
  1179. converting sequential data. Furthermore it can layout data for reports.
  1180. It is mainly used on mainframe platforms and can access several of the
  1181. mainframe's native file formats. It is somewhat comparable to awk.
  1182. """
  1183. name = 'Easytrieve'
  1184. aliases = ['easytrieve']
  1185. filenames = ['*.ezt', '*.mac']
  1186. mimetypes = ['text/x-easytrieve']
  1187. url = 'https://www.broadcom.com/products/mainframe/application-development/easytrieve-report-generator'
  1188. version_added = '2.1'
  1189. flags = 0
  1190. # Note: We cannot use r'\b' at the start and end of keywords because
  1191. # Easytrieve Plus delimiter characters are:
  1192. #
  1193. # * space ( )
  1194. # * apostrophe (')
  1195. # * period (.)
  1196. # * comma (,)
  1197. # * parenthesis ( and )
  1198. # * colon (:)
  1199. #
  1200. # Additionally words end once a '*' appears, indicatins a comment.
  1201. _DELIMITERS = r' \'.,():\n'
  1202. _DELIMITERS_OR_COMENT = _DELIMITERS + '*'
  1203. _DELIMITER_PATTERN = '[' + _DELIMITERS + ']'
  1204. _DELIMITER_PATTERN_CAPTURE = '(' + _DELIMITER_PATTERN + ')'
  1205. _NON_DELIMITER_OR_COMMENT_PATTERN = '[^' + _DELIMITERS_OR_COMENT + ']'
  1206. _OPERATORS_PATTERN = '[.+\\-/=\\[\\](){}<>;,&%¬]'
  1207. _KEYWORDS = [
  1208. 'AFTER-BREAK', 'AFTER-LINE', 'AFTER-SCREEN', 'AIM', 'AND', 'ATTR',
  1209. 'BEFORE', 'BEFORE-BREAK', 'BEFORE-LINE', 'BEFORE-SCREEN', 'BUSHU',
  1210. 'BY', 'CALL', 'CASE', 'CHECKPOINT', 'CHKP', 'CHKP-STATUS', 'CLEAR',
  1211. 'CLOSE', 'COL', 'COLOR', 'COMMIT', 'CONTROL', 'COPY', 'CURSOR', 'D',
  1212. 'DECLARE', 'DEFAULT', 'DEFINE', 'DELETE', 'DENWA', 'DISPLAY', 'DLI',
  1213. 'DO', 'DUPLICATE', 'E', 'ELSE', 'ELSE-IF', 'END', 'END-CASE',
  1214. 'END-DO', 'END-IF', 'END-PROC', 'ENDPAGE', 'ENDTABLE', 'ENTER', 'EOF',
  1215. 'EQ', 'ERROR', 'EXIT', 'EXTERNAL', 'EZLIB', 'F1', 'F10', 'F11', 'F12',
  1216. 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F2', 'F20', 'F21',
  1217. 'F22', 'F23', 'F24', 'F25', 'F26', 'F27', 'F28', 'F29', 'F3', 'F30',
  1218. 'F31', 'F32', 'F33', 'F34', 'F35', 'F36', 'F4', 'F5', 'F6', 'F7',
  1219. 'F8', 'F9', 'FETCH', 'FILE-STATUS', 'FILL', 'FINAL', 'FIRST',
  1220. 'FIRST-DUP', 'FOR', 'GE', 'GET', 'GO', 'GOTO', 'GQ', 'GR', 'GT',
  1221. 'HEADING', 'HEX', 'HIGH-VALUES', 'IDD', 'IDMS', 'IF', 'IN', 'INSERT',
  1222. 'JUSTIFY', 'KANJI-DATE', 'KANJI-DATE-LONG', 'KANJI-TIME', 'KEY',
  1223. 'KEY-PRESSED', 'KOKUGO', 'KUN', 'LAST-DUP', 'LE', 'LEVEL', 'LIKE',
  1224. 'LINE', 'LINE-COUNT', 'LINE-NUMBER', 'LINK', 'LIST', 'LOW-VALUES',
  1225. 'LQ', 'LS', 'LT', 'MACRO', 'MASK', 'MATCHED', 'MEND', 'MESSAGE',
  1226. 'MOVE', 'MSTART', 'NE', 'NEWPAGE', 'NOMASK', 'NOPRINT', 'NOT',
  1227. 'NOTE', 'NOVERIFY', 'NQ', 'NULL', 'OF', 'OR', 'OTHERWISE', 'PA1',
  1228. 'PA2', 'PA3', 'PAGE-COUNT', 'PAGE-NUMBER', 'PARM-REGISTER',
  1229. 'PATH-ID', 'PATTERN', 'PERFORM', 'POINT', 'POS', 'PRIMARY', 'PRINT',
  1230. 'PROCEDURE', 'PROGRAM', 'PUT', 'READ', 'RECORD', 'RECORD-COUNT',
  1231. 'RECORD-LENGTH', 'REFRESH', 'RELEASE', 'RENUM', 'REPEAT', 'REPORT',
  1232. 'REPORT-INPUT', 'RESHOW', 'RESTART', 'RETRIEVE', 'RETURN-CODE',
  1233. 'ROLLBACK', 'ROW', 'S', 'SCREEN', 'SEARCH', 'SECONDARY', 'SELECT',
  1234. 'SEQUENCE', 'SIZE', 'SKIP', 'SOKAKU', 'SORT', 'SQL', 'STOP', 'SUM',
  1235. 'SYSDATE', 'SYSDATE-LONG', 'SYSIN', 'SYSIPT', 'SYSLST', 'SYSPRINT',
  1236. 'SYSSNAP', 'SYSTIME', 'TALLY', 'TERM-COLUMNS', 'TERM-NAME',
  1237. 'TERM-ROWS', 'TERMINATION', 'TITLE', 'TO', 'TRANSFER', 'TRC',
  1238. 'UNIQUE', 'UNTIL', 'UPDATE', 'UPPERCASE', 'USER', 'USERID', 'VALUE',
  1239. 'VERIFY', 'W', 'WHEN', 'WHILE', 'WORK', 'WRITE', 'X', 'XDM', 'XRST'
  1240. ]
  1241. tokens = {
  1242. 'root': [
  1243. (r'\*.*\n', Comment.Single),
  1244. (r'\n+', Whitespace),
  1245. # Macro argument
  1246. (r'&' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+\.', Name.Variable,
  1247. 'after_macro_argument'),
  1248. # Macro call
  1249. (r'%' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Variable),
  1250. (r'(FILE|MACRO|REPORT)(\s+)',
  1251. bygroups(Keyword.Declaration, Whitespace), 'after_declaration'),
  1252. (r'(JOB|PARM)' + r'(' + _DELIMITER_PATTERN + r')',
  1253. bygroups(Keyword.Declaration, Operator)),
  1254. (words(_KEYWORDS, suffix=_DELIMITER_PATTERN_CAPTURE),
  1255. bygroups(Keyword.Reserved, Operator)),
  1256. (_OPERATORS_PATTERN, Operator),
  1257. # Procedure declaration
  1258. (r'(' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+)(\s*)(\.?)(\s*)(PROC)(\s*\n)',
  1259. bygroups(Name.Function, Whitespace, Operator, Whitespace,
  1260. Keyword.Declaration, Whitespace)),
  1261. (r'[0-9]+\.[0-9]*', Number.Float),
  1262. (r'[0-9]+', Number.Integer),
  1263. (r"'(''|[^'])*'", String),
  1264. (r'\s+', Whitespace),
  1265. # Everything else just belongs to a name
  1266. (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
  1267. ],
  1268. 'after_declaration': [
  1269. (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Function),
  1270. default('#pop'),
  1271. ],
  1272. 'after_macro_argument': [
  1273. (r'\*.*\n', Comment.Single, '#pop'),
  1274. (r'\s+', Whitespace, '#pop'),
  1275. (_OPERATORS_PATTERN, Operator, '#pop'),
  1276. (r"'(''|[^'])*'", String, '#pop'),
  1277. # Everything else just belongs to a name
  1278. (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
  1279. ],
  1280. }
  1281. _COMMENT_LINE_REGEX = re.compile(r'^\s*\*')
  1282. _MACRO_HEADER_REGEX = re.compile(r'^\s*MACRO')
  1283. def analyse_text(text):
  1284. """
  1285. Perform a structural analysis for basic Easytrieve constructs.
  1286. """
  1287. result = 0.0
  1288. lines = text.split('\n')
  1289. hasEndProc = False
  1290. hasHeaderComment = False
  1291. hasFile = False
  1292. hasJob = False
  1293. hasProc = False
  1294. hasParm = False
  1295. hasReport = False
  1296. def isCommentLine(line):
  1297. return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None
  1298. def isEmptyLine(line):
  1299. return not bool(line.strip())
  1300. # Remove possible empty lines and header comments.
  1301. while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])):
  1302. if not isEmptyLine(lines[0]):
  1303. hasHeaderComment = True
  1304. del lines[0]
  1305. if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]):
  1306. # Looks like an Easytrieve macro.
  1307. result = 0.4
  1308. if hasHeaderComment:
  1309. result += 0.4
  1310. else:
  1311. # Scan the source for lines starting with indicators.
  1312. for line in lines:
  1313. words = line.split()
  1314. if (len(words) >= 2):
  1315. firstWord = words[0]
  1316. if not hasReport:
  1317. if not hasJob:
  1318. if not hasFile:
  1319. if not hasParm:
  1320. if firstWord == 'PARM':
  1321. hasParm = True
  1322. if firstWord == 'FILE':
  1323. hasFile = True
  1324. if firstWord == 'JOB':
  1325. hasJob = True
  1326. elif firstWord == 'PROC':
  1327. hasProc = True
  1328. elif firstWord == 'END-PROC':
  1329. hasEndProc = True
  1330. elif firstWord == 'REPORT':
  1331. hasReport = True
  1332. # Weight the findings.
  1333. if hasJob and (hasProc == hasEndProc):
  1334. if hasHeaderComment:
  1335. result += 0.1
  1336. if hasParm:
  1337. if hasProc:
  1338. # Found PARM, JOB and PROC/END-PROC:
  1339. # pretty sure this is Easytrieve.
  1340. result += 0.8
  1341. else:
  1342. # Found PARAM and JOB: probably this is Easytrieve
  1343. result += 0.5
  1344. else:
  1345. # Found JOB and possibly other keywords: might be Easytrieve
  1346. result += 0.11
  1347. if hasParm:
  1348. # Note: PARAM is not a proper English word, so this is
  1349. # regarded a much better indicator for Easytrieve than
  1350. # the other words.
  1351. result += 0.2
  1352. if hasFile:
  1353. result += 0.01
  1354. if hasReport:
  1355. result += 0.01
  1356. assert 0.0 <= result <= 1.0
  1357. return result
  1358. class JclLexer(RegexLexer):
  1359. """
  1360. Job Control Language (JCL)
  1361. is a scripting language used on mainframe platforms to instruct the system
  1362. on how to run a batch job or start a subsystem. It is somewhat
  1363. comparable to MS DOS batch and Unix shell scripts.
  1364. """
  1365. name = 'JCL'
  1366. aliases = ['jcl']
  1367. filenames = ['*.jcl']
  1368. mimetypes = ['text/x-jcl']
  1369. url = 'https://en.wikipedia.org/wiki/Job_Control_Language'
  1370. version_added = '2.1'
  1371. flags = re.IGNORECASE
  1372. tokens = {
  1373. 'root': [
  1374. (r'//\*.*\n', Comment.Single),
  1375. (r'//', Keyword.Pseudo, 'statement'),
  1376. (r'/\*', Keyword.Pseudo, 'jes2_statement'),
  1377. # TODO: JES3 statement
  1378. (r'.*\n', Other) # Input text or inline code in any language.
  1379. ],
  1380. 'statement': [
  1381. (r'\s*\n', Whitespace, '#pop'),
  1382. (r'([a-z]\w*)(\s+)(exec|job)(\s*)',
  1383. bygroups(Name.Label, Whitespace, Keyword.Reserved, Whitespace),
  1384. 'option'),
  1385. (r'[a-z]\w*', Name.Variable, 'statement_command'),
  1386. (r'\s+', Whitespace, 'statement_command'),
  1387. ],
  1388. 'statement_command': [
  1389. (r'\s+(command|cntl|dd|endctl|endif|else|include|jcllib|'
  1390. r'output|pend|proc|set|then|xmit)\s+', Keyword.Reserved, 'option'),
  1391. include('option')
  1392. ],
  1393. 'jes2_statement': [
  1394. (r'\s*\n', Whitespace, '#pop'),
  1395. (r'\$', Keyword, 'option'),
  1396. (r'\b(jobparam|message|netacct|notify|output|priority|route|'
  1397. r'setup|signoff|xeq|xmit)\b', Keyword, 'option'),
  1398. ],
  1399. 'option': [
  1400. # (r'\n', Text, 'root'),
  1401. (r'\*', Name.Builtin),
  1402. (r'[\[\](){}<>;,]', Punctuation),
  1403. (r'[-+*/=&%]', Operator),
  1404. (r'[a-z_]\w*', Name),
  1405. (r'\d+\.\d*', Number.Float),
  1406. (r'\.\d+', Number.Float),
  1407. (r'\d+', Number.Integer),
  1408. (r"'", String, 'option_string'),
  1409. (r'[ \t]+', Whitespace, 'option_comment'),
  1410. (r'\.', Punctuation),
  1411. ],
  1412. 'option_string': [
  1413. (r"(\n)(//)", bygroups(Text, Keyword.Pseudo)),
  1414. (r"''", String),
  1415. (r"[^']", String),
  1416. (r"'", String, '#pop'),
  1417. ],
  1418. 'option_comment': [
  1419. # (r'\n', Text, 'root'),
  1420. (r'.+', Comment.Single),
  1421. ]
  1422. }
  1423. _JOB_HEADER_PATTERN = re.compile(r'^//[a-z#$@][a-z0-9#$@]{0,7}\s+job(\s+.*)?$',
  1424. re.IGNORECASE)
  1425. def analyse_text(text):
  1426. """
  1427. Recognize JCL job by header.
  1428. """
  1429. result = 0.0
  1430. lines = text.split('\n')
  1431. if len(lines) > 0:
  1432. if JclLexer._JOB_HEADER_PATTERN.match(lines[0]):
  1433. result = 1.0
  1434. assert 0.0 <= result <= 1.0
  1435. return result
  1436. class MiniScriptLexer(RegexLexer):
  1437. """
  1438. For MiniScript source code.
  1439. """
  1440. name = 'MiniScript'
  1441. url = 'https://miniscript.org'
  1442. aliases = ['miniscript', 'ms']
  1443. filenames = ['*.ms']
  1444. mimetypes = ['text/x-minicript', 'application/x-miniscript']
  1445. version_added = '2.6'
  1446. tokens = {
  1447. 'root': [
  1448. (r'#!(.*?)$', Comment.Preproc),
  1449. default('base'),
  1450. ],
  1451. 'base': [
  1452. ('//.*$', Comment.Single),
  1453. (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number),
  1454. (r'(?i)\d+e[+-]?\d+', Number),
  1455. (r'\d+', Number),
  1456. (r'\n', Text),
  1457. (r'[^\S\n]+', Text),
  1458. (r'"', String, 'string_double'),
  1459. (r'(==|!=|<=|>=|[=+\-*/%^<>.:])', Operator),
  1460. (r'[;,\[\]{}()]', Punctuation),
  1461. (words((
  1462. 'break', 'continue', 'else', 'end', 'for', 'function', 'if',
  1463. 'in', 'isa', 'then', 'repeat', 'return', 'while'), suffix=r'\b'),
  1464. Keyword),
  1465. (words((
  1466. 'abs', 'acos', 'asin', 'atan', 'ceil', 'char', 'cos', 'floor',
  1467. 'log', 'round', 'rnd', 'pi', 'sign', 'sin', 'sqrt', 'str', 'tan',
  1468. 'hasIndex', 'indexOf', 'len', 'val', 'code', 'remove', 'lower',
  1469. 'upper', 'replace', 'split', 'indexes', 'values', 'join', 'sum',
  1470. 'sort', 'shuffle', 'push', 'pop', 'pull', 'range',
  1471. 'print', 'input', 'time', 'wait', 'locals', 'globals', 'outer',
  1472. 'yield'), suffix=r'\b'),
  1473. Name.Builtin),
  1474. (r'(true|false|null)\b', Keyword.Constant),
  1475. (r'(and|or|not|new)\b', Operator.Word),
  1476. (r'(self|super|__isa)\b', Name.Builtin.Pseudo),
  1477. (r'[a-zA-Z_]\w*', Name.Variable)
  1478. ],
  1479. 'string_double': [
  1480. (r'[^"\n]+', String),
  1481. (r'""', String),
  1482. (r'"', String, '#pop'),
  1483. (r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
  1484. ]
  1485. }