shell.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.lexers.shell
  4. ~~~~~~~~~~~~~~~~~~~~~
  5. Lexers for various shells.
  6. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  7. :license: BSD, see LICENSE for details.
  8. """
  9. import re
  10. from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, \
  11. include, default, this, using, words
  12. from pygments.token import Punctuation, \
  13. Text, Comment, Operator, Keyword, Name, String, Number, Generic
  14. from pygments.util import shebang_matches
  15. __all__ = ['BashLexer', 'BashSessionLexer', 'TcshLexer', 'BatchLexer',
  16. 'SlurmBashLexer', 'MSDOSSessionLexer', 'PowerShellLexer',
  17. 'PowerShellSessionLexer', 'TcshSessionLexer', 'FishShellLexer']
  18. line_re = re.compile('.*?\n')
  19. class BashLexer(RegexLexer):
  20. """
  21. Lexer for (ba|k|z|)sh shell scripts.
  22. .. versionadded:: 0.6
  23. """
  24. name = 'Bash'
  25. aliases = ['bash', 'sh', 'ksh', 'zsh', 'shell']
  26. filenames = ['*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass',
  27. '*.exheres-0', '*.exlib', '*.zsh',
  28. '.bashrc', 'bashrc', '.bash_*', 'bash_*', 'zshrc', '.zshrc',
  29. 'PKGBUILD']
  30. mimetypes = ['application/x-sh', 'application/x-shellscript', 'text/x-shellscript']
  31. tokens = {
  32. 'root': [
  33. include('basic'),
  34. (r'`', String.Backtick, 'backticks'),
  35. include('data'),
  36. include('interp'),
  37. ],
  38. 'interp': [
  39. (r'\$\(\(', Keyword, 'math'),
  40. (r'\$\(', Keyword, 'paren'),
  41. (r'\$\{#?', String.Interpol, 'curly'),
  42. (r'\$[a-zA-Z_]\w*', Name.Variable), # user variable
  43. (r'\$(?:\d+|[#$?!_*@-])', Name.Variable), # builtin
  44. (r'\$', Text),
  45. ],
  46. 'basic': [
  47. (r'\b(if|fi|else|while|do|done|for|then|return|function|case|'
  48. r'select|continue|until|esac|elif)(\s*)\b',
  49. bygroups(Keyword, Text)),
  50. (r'\b(alias|bg|bind|break|builtin|caller|cd|command|compgen|'
  51. r'complete|declare|dirs|disown|echo|enable|eval|exec|exit|'
  52. r'export|false|fc|fg|getopts|hash|help|history|jobs|kill|let|'
  53. r'local|logout|popd|printf|pushd|pwd|read|readonly|set|shift|'
  54. r'shopt|source|suspend|test|time|times|trap|true|type|typeset|'
  55. r'ulimit|umask|unalias|unset|wait)(?=[\s)`])',
  56. Name.Builtin),
  57. (r'\A#!.+\n', Comment.Hashbang),
  58. (r'#.*\n', Comment.Single),
  59. (r'\\[\w\W]', String.Escape),
  60. (r'(\b\w+)(\s*)(\+?=)', bygroups(Name.Variable, Text, Operator)),
  61. (r'[\[\]{}()=]', Operator),
  62. (r'<<<', Operator), # here-string
  63. (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
  64. (r'&&|\|\|', Operator),
  65. ],
  66. 'data': [
  67. (r'(?s)\$?"(\\.|[^"\\$])*"', String.Double),
  68. (r'"', String.Double, 'string'),
  69. (r"(?s)\$'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
  70. (r"(?s)'.*?'", String.Single),
  71. (r';', Punctuation),
  72. (r'&', Punctuation),
  73. (r'\|', Punctuation),
  74. (r'\s+', Text),
  75. (r'\d+\b', Number),
  76. (r'[^=\s\[\]{}()$"\'`\\<&|;]+', Text),
  77. (r'<', Text),
  78. ],
  79. 'string': [
  80. (r'"', String.Double, '#pop'),
  81. (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\$])+', String.Double),
  82. include('interp'),
  83. ],
  84. 'curly': [
  85. (r'\}', String.Interpol, '#pop'),
  86. (r':-', Keyword),
  87. (r'\w+', Name.Variable),
  88. (r'[^}:"\'`$\\]+', Punctuation),
  89. (r':', Punctuation),
  90. include('root'),
  91. ],
  92. 'paren': [
  93. (r'\)', Keyword, '#pop'),
  94. include('root'),
  95. ],
  96. 'math': [
  97. (r'\)\)', Keyword, '#pop'),
  98. (r'[-+*/%^|&]|\*\*|\|\|', Operator),
  99. (r'\d+#\d+', Number),
  100. (r'\d+#(?! )', Number),
  101. (r'\d+', Number),
  102. include('root'),
  103. ],
  104. 'backticks': [
  105. (r'`', String.Backtick, '#pop'),
  106. include('root'),
  107. ],
  108. }
  109. def analyse_text(text):
  110. if shebang_matches(text, r'(ba|z|)sh'):
  111. return 1
  112. if text.startswith('$ '):
  113. return 0.2
  114. class SlurmBashLexer(BashLexer):
  115. """
  116. Lexer for (ba|k|z|)sh Slurm scripts.
  117. .. versionadded:: 2.4
  118. """
  119. name = 'Slurm'
  120. aliases = ['slurm', 'sbatch']
  121. filenames = ['*.sl']
  122. mimetypes = []
  123. EXTRA_KEYWORDS = {'srun'}
  124. def get_tokens_unprocessed(self, text):
  125. for index, token, value in BashLexer.get_tokens_unprocessed(self, text):
  126. if token is Text and value in self.EXTRA_KEYWORDS:
  127. yield index, Name.Builtin, value
  128. elif token is Comment.Single and 'SBATCH' in value:
  129. yield index, Keyword.Pseudo, value
  130. else:
  131. yield index, token, value
  132. class ShellSessionBaseLexer(Lexer):
  133. """
  134. Base lexer for simplistic shell sessions.
  135. .. versionadded:: 2.1
  136. """
  137. _venv = re.compile(r'^(\([^)]*\))(\s*)')
  138. def get_tokens_unprocessed(self, text):
  139. innerlexer = self._innerLexerCls(**self.options)
  140. pos = 0
  141. curcode = ''
  142. insertions = []
  143. backslash_continuation = False
  144. for match in line_re.finditer(text):
  145. line = match.group()
  146. if backslash_continuation:
  147. curcode += line
  148. backslash_continuation = curcode.endswith('\\\n')
  149. continue
  150. venv_match = self._venv.match(line)
  151. if venv_match:
  152. venv = venv_match.group(1)
  153. venv_whitespace = venv_match.group(2)
  154. insertions.append((len(curcode),
  155. [(0, Generic.Prompt.VirtualEnv, venv)]))
  156. if venv_whitespace:
  157. insertions.append((len(curcode),
  158. [(0, Text, venv_whitespace)]))
  159. line = line[venv_match.end():]
  160. m = self._ps1rgx.match(line)
  161. if m:
  162. # To support output lexers (say diff output), the output
  163. # needs to be broken by prompts whenever the output lexer
  164. # changes.
  165. if not insertions:
  166. pos = match.start()
  167. insertions.append((len(curcode),
  168. [(0, Generic.Prompt, m.group(1))]))
  169. curcode += m.group(2)
  170. backslash_continuation = curcode.endswith('\\\n')
  171. elif line.startswith(self._ps2):
  172. insertions.append((len(curcode),
  173. [(0, Generic.Prompt, line[:len(self._ps2)])]))
  174. curcode += line[len(self._ps2):]
  175. backslash_continuation = curcode.endswith('\\\n')
  176. else:
  177. if insertions:
  178. toks = innerlexer.get_tokens_unprocessed(curcode)
  179. for i, t, v in do_insertions(insertions, toks):
  180. yield pos+i, t, v
  181. yield match.start(), Generic.Output, line
  182. insertions = []
  183. curcode = ''
  184. if insertions:
  185. for i, t, v in do_insertions(insertions,
  186. innerlexer.get_tokens_unprocessed(curcode)):
  187. yield pos+i, t, v
  188. class BashSessionLexer(ShellSessionBaseLexer):
  189. """
  190. Lexer for simplistic shell sessions.
  191. .. versionadded:: 1.1
  192. """
  193. name = 'Bash Session'
  194. aliases = ['console', 'shell-session']
  195. filenames = ['*.sh-session', '*.shell-session']
  196. mimetypes = ['application/x-shell-session', 'application/x-sh-session']
  197. _innerLexerCls = BashLexer
  198. _ps1rgx = re.compile(
  199. r'^((?:(?:\[.*?\])|(?:\(\S+\))?(?:| |sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)' \
  200. r'?|\[\S+[@:][^\n]+\].+))\s*[$#%])(.*\n?)')
  201. _ps2 = '>'
  202. class BatchLexer(RegexLexer):
  203. """
  204. Lexer for the DOS/Windows Batch file format.
  205. .. versionadded:: 0.7
  206. """
  207. name = 'Batchfile'
  208. aliases = ['bat', 'batch', 'dosbatch', 'winbatch']
  209. filenames = ['*.bat', '*.cmd']
  210. mimetypes = ['application/x-dos-batch']
  211. flags = re.MULTILINE | re.IGNORECASE
  212. _nl = r'\n\x1a'
  213. _punct = r'&<>|'
  214. _ws = r'\t\v\f\r ,;=\xa0'
  215. _space = r'(?:(?:(?:\^[%s])?[%s])+)' % (_nl, _ws)
  216. _keyword_terminator = (r'(?=(?:\^[%s]?)?[%s+./:[\\\]]|[%s%s(])' %
  217. (_nl, _ws, _nl, _punct))
  218. _token_terminator = r'(?=\^?[%s]|[%s%s])' % (_ws, _punct, _nl)
  219. _start_label = r'((?:(?<=^[^:])|^[^:]?)[%s]*)(:)' % _ws
  220. _label = r'(?:(?:[^%s%s%s+:^]|\^[%s]?[\w\W])*)' % (_nl, _punct, _ws, _nl)
  221. _label_compound = (r'(?:(?:[^%s%s%s+:^)]|\^[%s]?[^)])*)' %
  222. (_nl, _punct, _ws, _nl))
  223. _number = r'(?:-?(?:0[0-7]+|0x[\da-f]+|\d+)%s)' % _token_terminator
  224. _opword = r'(?:equ|geq|gtr|leq|lss|neq)'
  225. _string = r'(?:"[^%s"]*(?:"|(?=[%s])))' % (_nl, _nl)
  226. _variable = (r'(?:(?:%%(?:\*|(?:~[a-z]*(?:\$[^:]+:)?)?\d|'
  227. r'[^%%:%s]+(?::(?:~(?:-?\d+)?(?:,(?:-?\d+)?)?|(?:[^%%%s^]|'
  228. r'\^[^%%%s])[^=%s]*=(?:[^%%%s^]|\^[^%%%s])*)?)?%%))|'
  229. r'(?:\^?![^!:%s]+(?::(?:~(?:-?\d+)?(?:,(?:-?\d+)?)?|(?:'
  230. r'[^!%s^]|\^[^!%s])[^=%s]*=(?:[^!%s^]|\^[^!%s])*)?)?\^?!))' %
  231. (_nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl))
  232. _core_token = r'(?:(?:(?:\^[%s]?)?[^"%s%s%s])+)' % (_nl, _nl, _punct, _ws)
  233. _core_token_compound = r'(?:(?:(?:\^[%s]?)?[^"%s%s%s)])+)' % (_nl, _nl,
  234. _punct, _ws)
  235. _token = r'(?:[%s]+|%s)' % (_punct, _core_token)
  236. _token_compound = r'(?:[%s]+|%s)' % (_punct, _core_token_compound)
  237. _stoken = (r'(?:[%s]+|(?:%s|%s|%s)+)' %
  238. (_punct, _string, _variable, _core_token))
  239. def _make_begin_state(compound, _core_token=_core_token,
  240. _core_token_compound=_core_token_compound,
  241. _keyword_terminator=_keyword_terminator,
  242. _nl=_nl, _punct=_punct, _string=_string,
  243. _space=_space, _start_label=_start_label,
  244. _stoken=_stoken, _token_terminator=_token_terminator,
  245. _variable=_variable, _ws=_ws):
  246. rest = '(?:%s|%s|[^"%%%s%s%s])*' % (_string, _variable, _nl, _punct,
  247. ')' if compound else '')
  248. rest_of_line = r'(?:(?:[^%s^]|\^[%s]?[\w\W])*)' % (_nl, _nl)
  249. rest_of_line_compound = r'(?:(?:[^%s^)]|\^[%s]?[^)])*)' % (_nl, _nl)
  250. set_space = r'((?:(?:\^[%s]?)?[^\S\n])*)' % _nl
  251. suffix = ''
  252. if compound:
  253. _keyword_terminator = r'(?:(?=\))|%s)' % _keyword_terminator
  254. _token_terminator = r'(?:(?=\))|%s)' % _token_terminator
  255. suffix = '/compound'
  256. return [
  257. ((r'\)', Punctuation, '#pop') if compound else
  258. (r'\)((?=\()|%s)%s' % (_token_terminator, rest_of_line),
  259. Comment.Single)),
  260. (r'(?=%s)' % _start_label, Text, 'follow%s' % suffix),
  261. (_space, using(this, state='text')),
  262. include('redirect%s' % suffix),
  263. (r'[%s]+' % _nl, Text),
  264. (r'\(', Punctuation, 'root/compound'),
  265. (r'@+', Punctuation),
  266. (r'((?:for|if|rem)(?:(?=(?:\^[%s]?)?/)|(?:(?!\^)|'
  267. r'(?<=m))(?:(?=\()|%s)))(%s?%s?(?:\^[%s]?)?/(?:\^[%s]?)?\?)' %
  268. (_nl, _token_terminator, _space,
  269. _core_token_compound if compound else _core_token, _nl, _nl),
  270. bygroups(Keyword, using(this, state='text')),
  271. 'follow%s' % suffix),
  272. (r'(goto%s)(%s(?:\^[%s]?)?/(?:\^[%s]?)?\?%s)' %
  273. (_keyword_terminator, rest, _nl, _nl, rest),
  274. bygroups(Keyword, using(this, state='text')),
  275. 'follow%s' % suffix),
  276. (words(('assoc', 'break', 'cd', 'chdir', 'cls', 'color', 'copy',
  277. 'date', 'del', 'dir', 'dpath', 'echo', 'endlocal', 'erase',
  278. 'exit', 'ftype', 'keys', 'md', 'mkdir', 'mklink', 'move',
  279. 'path', 'pause', 'popd', 'prompt', 'pushd', 'rd', 'ren',
  280. 'rename', 'rmdir', 'setlocal', 'shift', 'start', 'time',
  281. 'title', 'type', 'ver', 'verify', 'vol'),
  282. suffix=_keyword_terminator), Keyword, 'follow%s' % suffix),
  283. (r'(call)(%s?)(:)' % _space,
  284. bygroups(Keyword, using(this, state='text'), Punctuation),
  285. 'call%s' % suffix),
  286. (r'call%s' % _keyword_terminator, Keyword),
  287. (r'(for%s(?!\^))(%s)(/f%s)' %
  288. (_token_terminator, _space, _token_terminator),
  289. bygroups(Keyword, using(this, state='text'), Keyword),
  290. ('for/f', 'for')),
  291. (r'(for%s(?!\^))(%s)(/l%s)' %
  292. (_token_terminator, _space, _token_terminator),
  293. bygroups(Keyword, using(this, state='text'), Keyword),
  294. ('for/l', 'for')),
  295. (r'for%s(?!\^)' % _token_terminator, Keyword, ('for2', 'for')),
  296. (r'(goto%s)(%s?)(:?)' % (_keyword_terminator, _space),
  297. bygroups(Keyword, using(this, state='text'), Punctuation),
  298. 'label%s' % suffix),
  299. (r'(if(?:(?=\()|%s)(?!\^))(%s?)((?:/i%s)?)(%s?)((?:not%s)?)(%s?)' %
  300. (_token_terminator, _space, _token_terminator, _space,
  301. _token_terminator, _space),
  302. bygroups(Keyword, using(this, state='text'), Keyword,
  303. using(this, state='text'), Keyword,
  304. using(this, state='text')), ('(?', 'if')),
  305. (r'rem(((?=\()|%s)%s?%s?.*|%s%s)' %
  306. (_token_terminator, _space, _stoken, _keyword_terminator,
  307. rest_of_line_compound if compound else rest_of_line),
  308. Comment.Single, 'follow%s' % suffix),
  309. (r'(set%s)%s(/a)' % (_keyword_terminator, set_space),
  310. bygroups(Keyword, using(this, state='text'), Keyword),
  311. 'arithmetic%s' % suffix),
  312. (r'(set%s)%s((?:/p)?)%s((?:(?:(?:\^[%s]?)?[^"%s%s^=%s]|'
  313. r'\^[%s]?[^"=])+)?)((?:(?:\^[%s]?)?=)?)' %
  314. (_keyword_terminator, set_space, set_space, _nl, _nl, _punct,
  315. ')' if compound else '', _nl, _nl),
  316. bygroups(Keyword, using(this, state='text'), Keyword,
  317. using(this, state='text'), using(this, state='variable'),
  318. Punctuation),
  319. 'follow%s' % suffix),
  320. default('follow%s' % suffix)
  321. ]
  322. def _make_follow_state(compound, _label=_label,
  323. _label_compound=_label_compound, _nl=_nl,
  324. _space=_space, _start_label=_start_label,
  325. _token=_token, _token_compound=_token_compound,
  326. _ws=_ws):
  327. suffix = '/compound' if compound else ''
  328. state = []
  329. if compound:
  330. state.append((r'(?=\))', Text, '#pop'))
  331. state += [
  332. (r'%s([%s]*)(%s)(.*)' %
  333. (_start_label, _ws, _label_compound if compound else _label),
  334. bygroups(Text, Punctuation, Text, Name.Label, Comment.Single)),
  335. include('redirect%s' % suffix),
  336. (r'(?=[%s])' % _nl, Text, '#pop'),
  337. (r'\|\|?|&&?', Punctuation, '#pop'),
  338. include('text')
  339. ]
  340. return state
  341. def _make_arithmetic_state(compound, _nl=_nl, _punct=_punct,
  342. _string=_string, _variable=_variable, _ws=_ws):
  343. op = r'=+\-*/!~'
  344. state = []
  345. if compound:
  346. state.append((r'(?=\))', Text, '#pop'))
  347. state += [
  348. (r'0[0-7]+', Number.Oct),
  349. (r'0x[\da-f]+', Number.Hex),
  350. (r'\d+', Number.Integer),
  351. (r'[(),]+', Punctuation),
  352. (r'([%s]|%%|\^\^)+' % op, Operator),
  353. (r'(%s|%s|(\^[%s]?)?[^()%s%%^"%s%s%s]|\^[%s%s]?%s)+' %
  354. (_string, _variable, _nl, op, _nl, _punct, _ws, _nl, _ws,
  355. r'[^)]' if compound else r'[\w\W]'),
  356. using(this, state='variable')),
  357. (r'(?=[\x00|&])', Text, '#pop'),
  358. include('follow')
  359. ]
  360. return state
  361. def _make_call_state(compound, _label=_label,
  362. _label_compound=_label_compound):
  363. state = []
  364. if compound:
  365. state.append((r'(?=\))', Text, '#pop'))
  366. state.append((r'(:?)(%s)' % (_label_compound if compound else _label),
  367. bygroups(Punctuation, Name.Label), '#pop'))
  368. return state
  369. def _make_label_state(compound, _label=_label,
  370. _label_compound=_label_compound, _nl=_nl,
  371. _punct=_punct, _string=_string, _variable=_variable):
  372. state = []
  373. if compound:
  374. state.append((r'(?=\))', Text, '#pop'))
  375. state.append((r'(%s?)((?:%s|%s|\^[%s]?%s|[^"%%^%s%s%s])*)' %
  376. (_label_compound if compound else _label, _string,
  377. _variable, _nl, r'[^)]' if compound else r'[\w\W]', _nl,
  378. _punct, r')' if compound else ''),
  379. bygroups(Name.Label, Comment.Single), '#pop'))
  380. return state
  381. def _make_redirect_state(compound,
  382. _core_token_compound=_core_token_compound,
  383. _nl=_nl, _punct=_punct, _stoken=_stoken,
  384. _string=_string, _space=_space,
  385. _variable=_variable, _ws=_ws):
  386. stoken_compound = (r'(?:[%s]+|(?:%s|%s|%s)+)' %
  387. (_punct, _string, _variable, _core_token_compound))
  388. return [
  389. (r'((?:(?<=[%s%s])\d)?)(>>?&|<&)([%s%s]*)(\d)' %
  390. (_nl, _ws, _nl, _ws),
  391. bygroups(Number.Integer, Punctuation, Text, Number.Integer)),
  392. (r'((?:(?<=[%s%s])(?<!\^[%s])\d)?)(>>?|<)(%s?%s)' %
  393. (_nl, _ws, _nl, _space, stoken_compound if compound else _stoken),
  394. bygroups(Number.Integer, Punctuation, using(this, state='text')))
  395. ]
  396. tokens = {
  397. 'root': _make_begin_state(False),
  398. 'follow': _make_follow_state(False),
  399. 'arithmetic': _make_arithmetic_state(False),
  400. 'call': _make_call_state(False),
  401. 'label': _make_label_state(False),
  402. 'redirect': _make_redirect_state(False),
  403. 'root/compound': _make_begin_state(True),
  404. 'follow/compound': _make_follow_state(True),
  405. 'arithmetic/compound': _make_arithmetic_state(True),
  406. 'call/compound': _make_call_state(True),
  407. 'label/compound': _make_label_state(True),
  408. 'redirect/compound': _make_redirect_state(True),
  409. 'variable-or-escape': [
  410. (_variable, Name.Variable),
  411. (r'%%%%|\^[%s]?(\^!|[\w\W])' % _nl, String.Escape)
  412. ],
  413. 'string': [
  414. (r'"', String.Double, '#pop'),
  415. (_variable, Name.Variable),
  416. (r'\^!|%%', String.Escape),
  417. (r'[^"%%^%s]+|[%%^]' % _nl, String.Double),
  418. default('#pop')
  419. ],
  420. 'sqstring': [
  421. include('variable-or-escape'),
  422. (r'[^%]+|%', String.Single)
  423. ],
  424. 'bqstring': [
  425. include('variable-or-escape'),
  426. (r'[^%]+|%', String.Backtick)
  427. ],
  428. 'text': [
  429. (r'"', String.Double, 'string'),
  430. include('variable-or-escape'),
  431. (r'[^"%%^%s%s%s\d)]+|.' % (_nl, _punct, _ws), Text)
  432. ],
  433. 'variable': [
  434. (r'"', String.Double, 'string'),
  435. include('variable-or-escape'),
  436. (r'[^"%%^%s]+|.' % _nl, Name.Variable)
  437. ],
  438. 'for': [
  439. (r'(%s)(in)(%s)(\()' % (_space, _space),
  440. bygroups(using(this, state='text'), Keyword,
  441. using(this, state='text'), Punctuation), '#pop'),
  442. include('follow')
  443. ],
  444. 'for2': [
  445. (r'\)', Punctuation),
  446. (r'(%s)(do%s)' % (_space, _token_terminator),
  447. bygroups(using(this, state='text'), Keyword), '#pop'),
  448. (r'[%s]+' % _nl, Text),
  449. include('follow')
  450. ],
  451. 'for/f': [
  452. (r'(")((?:%s|[^"])*?")([%s%s]*)(\))' % (_variable, _nl, _ws),
  453. bygroups(String.Double, using(this, state='string'), Text,
  454. Punctuation)),
  455. (r'"', String.Double, ('#pop', 'for2', 'string')),
  456. (r"('(?:%%%%|%s|[\w\W])*?')([%s%s]*)(\))" % (_variable, _nl, _ws),
  457. bygroups(using(this, state='sqstring'), Text, Punctuation)),
  458. (r'(`(?:%%%%|%s|[\w\W])*?`)([%s%s]*)(\))' % (_variable, _nl, _ws),
  459. bygroups(using(this, state='bqstring'), Text, Punctuation)),
  460. include('for2')
  461. ],
  462. 'for/l': [
  463. (r'-?\d+', Number.Integer),
  464. include('for2')
  465. ],
  466. 'if': [
  467. (r'((?:cmdextversion|errorlevel)%s)(%s)(\d+)' %
  468. (_token_terminator, _space),
  469. bygroups(Keyword, using(this, state='text'),
  470. Number.Integer), '#pop'),
  471. (r'(defined%s)(%s)(%s)' % (_token_terminator, _space, _stoken),
  472. bygroups(Keyword, using(this, state='text'),
  473. using(this, state='variable')), '#pop'),
  474. (r'(exist%s)(%s%s)' % (_token_terminator, _space, _stoken),
  475. bygroups(Keyword, using(this, state='text')), '#pop'),
  476. (r'(%s%s)(%s)(%s%s)' % (_number, _space, _opword, _space, _number),
  477. bygroups(using(this, state='arithmetic'), Operator.Word,
  478. using(this, state='arithmetic')), '#pop'),
  479. (_stoken, using(this, state='text'), ('#pop', 'if2')),
  480. ],
  481. 'if2': [
  482. (r'(%s?)(==)(%s?%s)' % (_space, _space, _stoken),
  483. bygroups(using(this, state='text'), Operator,
  484. using(this, state='text')), '#pop'),
  485. (r'(%s)(%s)(%s%s)' % (_space, _opword, _space, _stoken),
  486. bygroups(using(this, state='text'), Operator.Word,
  487. using(this, state='text')), '#pop')
  488. ],
  489. '(?': [
  490. (_space, using(this, state='text')),
  491. (r'\(', Punctuation, ('#pop', 'else?', 'root/compound')),
  492. default('#pop')
  493. ],
  494. 'else?': [
  495. (_space, using(this, state='text')),
  496. (r'else%s' % _token_terminator, Keyword, '#pop'),
  497. default('#pop')
  498. ]
  499. }
  500. class MSDOSSessionLexer(ShellSessionBaseLexer):
  501. """
  502. Lexer for simplistic MSDOS sessions.
  503. .. versionadded:: 2.1
  504. """
  505. name = 'MSDOS Session'
  506. aliases = ['doscon']
  507. filenames = []
  508. mimetypes = []
  509. _innerLexerCls = BatchLexer
  510. _ps1rgx = re.compile(r'^([^>]*>)(.*\n?)')
  511. _ps2 = 'More? '
  512. class TcshLexer(RegexLexer):
  513. """
  514. Lexer for tcsh scripts.
  515. .. versionadded:: 0.10
  516. """
  517. name = 'Tcsh'
  518. aliases = ['tcsh', 'csh']
  519. filenames = ['*.tcsh', '*.csh']
  520. mimetypes = ['application/x-csh']
  521. tokens = {
  522. 'root': [
  523. include('basic'),
  524. (r'\$\(', Keyword, 'paren'),
  525. (r'\$\{#?', Keyword, 'curly'),
  526. (r'`', String.Backtick, 'backticks'),
  527. include('data'),
  528. ],
  529. 'basic': [
  530. (r'\b(if|endif|else|while|then|foreach|case|default|'
  531. r'continue|goto|breaksw|end|switch|endsw)\s*\b',
  532. Keyword),
  533. (r'\b(alias|alloc|bg|bindkey|break|builtins|bye|caller|cd|chdir|'
  534. r'complete|dirs|echo|echotc|eval|exec|exit|fg|filetest|getxvers|'
  535. r'glob|getspath|hashstat|history|hup|inlib|jobs|kill|'
  536. r'limit|log|login|logout|ls-F|migrate|newgrp|nice|nohup|notify|'
  537. r'onintr|popd|printenv|pushd|rehash|repeat|rootnode|popd|pushd|'
  538. r'set|shift|sched|setenv|setpath|settc|setty|setxvers|shift|'
  539. r'source|stop|suspend|source|suspend|telltc|time|'
  540. r'umask|unalias|uncomplete|unhash|universe|unlimit|unset|unsetenv|'
  541. r'ver|wait|warp|watchlog|where|which)\s*\b',
  542. Name.Builtin),
  543. (r'#.*', Comment),
  544. (r'\\[\w\W]', String.Escape),
  545. (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)),
  546. (r'[\[\]{}()=]+', Operator),
  547. (r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
  548. (r';', Punctuation),
  549. ],
  550. 'data': [
  551. (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double),
  552. (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
  553. (r'\s+', Text),
  554. (r'[^=\s\[\]{}()$"\'`\\;#]+', Text),
  555. (r'\d+(?= |\Z)', Number),
  556. (r'\$#?(\w+|.)', Name.Variable),
  557. ],
  558. 'curly': [
  559. (r'\}', Keyword, '#pop'),
  560. (r':-', Keyword),
  561. (r'\w+', Name.Variable),
  562. (r'[^}:"\'`$]+', Punctuation),
  563. (r':', Punctuation),
  564. include('root'),
  565. ],
  566. 'paren': [
  567. (r'\)', Keyword, '#pop'),
  568. include('root'),
  569. ],
  570. 'backticks': [
  571. (r'`', String.Backtick, '#pop'),
  572. include('root'),
  573. ],
  574. }
  575. class TcshSessionLexer(ShellSessionBaseLexer):
  576. """
  577. Lexer for Tcsh sessions.
  578. .. versionadded:: 2.1
  579. """
  580. name = 'Tcsh Session'
  581. aliases = ['tcshcon']
  582. filenames = []
  583. mimetypes = []
  584. _innerLexerCls = TcshLexer
  585. _ps1rgx = re.compile(r'^([^>]+>)(.*\n?)')
  586. _ps2 = '? '
  587. class PowerShellLexer(RegexLexer):
  588. """
  589. For Windows PowerShell code.
  590. .. versionadded:: 1.5
  591. """
  592. name = 'PowerShell'
  593. aliases = ['powershell', 'posh', 'ps1', 'psm1']
  594. filenames = ['*.ps1', '*.psm1']
  595. mimetypes = ['text/x-powershell']
  596. flags = re.DOTALL | re.IGNORECASE | re.MULTILINE
  597. keywords = (
  598. 'while validateset validaterange validatepattern validatelength '
  599. 'validatecount until trap switch return ref process param parameter in '
  600. 'if global: function foreach for finally filter end elseif else '
  601. 'dynamicparam do default continue cmdletbinding break begin alias \\? '
  602. '% #script #private #local #global mandatory parametersetname position '
  603. 'valuefrompipeline valuefrompipelinebypropertyname '
  604. 'valuefromremainingarguments helpmessage try catch throw').split()
  605. operators = (
  606. 'and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle '
  607. 'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains '
  608. 'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt '
  609. 'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like '
  610. 'lt match ne not notcontains notlike notmatch or regex replace '
  611. 'wildcard').split()
  612. verbs = (
  613. 'write where watch wait use update unregister unpublish unprotect '
  614. 'unlock uninstall undo unblock trace test tee take sync switch '
  615. 'suspend submit stop step start split sort skip show set send select '
  616. 'search scroll save revoke resume restore restart resolve resize '
  617. 'reset request repair rename remove register redo receive read push '
  618. 'publish protect pop ping out optimize open new move mount merge '
  619. 'measure lock limit join invoke install initialize import hide group '
  620. 'grant get format foreach find export expand exit enter enable edit '
  621. 'dismount disconnect disable deny debug cxnew copy convertto '
  622. 'convertfrom convert connect confirm compress complete compare close '
  623. 'clear checkpoint block backup assert approve aggregate add').split()
  624. aliases_ = (
  625. 'ac asnp cat cd cfs chdir clc clear clhy cli clp cls clv cnsn '
  626. 'compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo epal '
  627. 'epcsv epsn erase etsn exsn fc fhx fl foreach ft fw gal gbp gc gci gcm '
  628. 'gcs gdr ghy gi gjb gl gm gmo gp gps gpv group gsn gsnp gsv gu gv gwmi '
  629. 'h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp '
  630. 'ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv '
  631. 'oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo '
  632. 'rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc select '
  633. 'set shcm si sl sleep sls sort sp spjb spps spsv start sujb sv swmi tee '
  634. 'trcm type wget where wjb write').split()
  635. commenthelp = (
  636. 'component description example externalhelp forwardhelpcategory '
  637. 'forwardhelptargetname functionality inputs link '
  638. 'notes outputs parameter remotehelprunspace role synopsis').split()
  639. tokens = {
  640. 'root': [
  641. # we need to count pairs of parentheses for correct highlight
  642. # of '$(...)' blocks in strings
  643. (r'\(', Punctuation, 'child'),
  644. (r'\s+', Text),
  645. (r'^(\s*#[#\s]*)(\.(?:%s))([^\n]*$)' % '|'.join(commenthelp),
  646. bygroups(Comment, String.Doc, Comment)),
  647. (r'#[^\n]*?$', Comment),
  648. (r'(&lt;|<)#', Comment.Multiline, 'multline'),
  649. (r'@"\n', String.Heredoc, 'heredoc-double'),
  650. (r"@'\n.*?\n'@", String.Heredoc),
  651. # escaped syntax
  652. (r'`[\'"$@-]', Punctuation),
  653. (r'"', String.Double, 'string'),
  654. (r"'([^']|'')*'", String.Single),
  655. (r'(\$|@@|@)((global|script|private|env):)?\w+',
  656. Name.Variable),
  657. (r'(%s)\b' % '|'.join(keywords), Keyword),
  658. (r'-(%s)\b' % '|'.join(operators), Operator),
  659. (r'(%s)-[a-z_]\w*\b' % '|'.join(verbs), Name.Builtin),
  660. (r'(%s)\s' % '|'.join(aliases_), Name.Builtin),
  661. (r'\[[a-z_\[][\w. `,\[\]]*\]', Name.Constant), # .net [type]s
  662. (r'-[a-z_]\w*', Name),
  663. (r'\w+', Name),
  664. (r'[.,;@{}\[\]$()=+*/\\&%!~?^`|<>-]|::', Punctuation),
  665. ],
  666. 'child': [
  667. (r'\)', Punctuation, '#pop'),
  668. include('root'),
  669. ],
  670. 'multline': [
  671. (r'[^#&.]+', Comment.Multiline),
  672. (r'#(>|&gt;)', Comment.Multiline, '#pop'),
  673. (r'\.(%s)' % '|'.join(commenthelp), String.Doc),
  674. (r'[#&.]', Comment.Multiline),
  675. ],
  676. 'string': [
  677. (r"`[0abfnrtv'\"$`]", String.Escape),
  678. (r'[^$`"]+', String.Double),
  679. (r'\$\(', Punctuation, 'child'),
  680. (r'""', String.Double),
  681. (r'[`$]', String.Double),
  682. (r'"', String.Double, '#pop'),
  683. ],
  684. 'heredoc-double': [
  685. (r'\n"@', String.Heredoc, '#pop'),
  686. (r'\$\(', Punctuation, 'child'),
  687. (r'[^@\n]+"]', String.Heredoc),
  688. (r".", String.Heredoc),
  689. ]
  690. }
  691. class PowerShellSessionLexer(ShellSessionBaseLexer):
  692. """
  693. Lexer for simplistic Windows PowerShell sessions.
  694. .. versionadded:: 2.1
  695. """
  696. name = 'PowerShell Session'
  697. aliases = ['ps1con']
  698. filenames = []
  699. mimetypes = []
  700. _innerLexerCls = PowerShellLexer
  701. _ps1rgx = re.compile(r'^(PS [^>]+> )(.*\n?)')
  702. _ps2 = '>> '
  703. class FishShellLexer(RegexLexer):
  704. """
  705. Lexer for Fish shell scripts.
  706. .. versionadded:: 2.1
  707. """
  708. name = 'Fish'
  709. aliases = ['fish', 'fishshell']
  710. filenames = ['*.fish', '*.load']
  711. mimetypes = ['application/x-fish']
  712. tokens = {
  713. 'root': [
  714. include('basic'),
  715. include('data'),
  716. include('interp'),
  717. ],
  718. 'interp': [
  719. (r'\$\(\(', Keyword, 'math'),
  720. (r'\(', Keyword, 'paren'),
  721. (r'\$#?(\w+|.)', Name.Variable),
  722. ],
  723. 'basic': [
  724. (r'\b(begin|end|if|else|while|break|for|in|return|function|block|'
  725. r'case|continue|switch|not|and|or|set|echo|exit|pwd|true|false|'
  726. r'cd|count|test)(\s*)\b',
  727. bygroups(Keyword, Text)),
  728. (r'\b(alias|bg|bind|breakpoint|builtin|command|commandline|'
  729. r'complete|contains|dirh|dirs|emit|eval|exec|fg|fish|fish_config|'
  730. r'fish_indent|fish_pager|fish_prompt|fish_right_prompt|'
  731. r'fish_update_completions|fishd|funced|funcsave|functions|help|'
  732. r'history|isatty|jobs|math|mimedb|nextd|open|popd|prevd|psub|'
  733. r'pushd|random|read|set_color|source|status|trap|type|ulimit|'
  734. r'umask|vared|fc|getopts|hash|kill|printf|time|wait)\s*\b(?!\.)',
  735. Name.Builtin),
  736. (r'#.*\n', Comment),
  737. (r'\\[\w\W]', String.Escape),
  738. (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)),
  739. (r'[\[\]()=]', Operator),
  740. (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
  741. ],
  742. 'data': [
  743. (r'(?s)\$?"(\\\\|\\[0-7]+|\\.|[^"\\$])*"', String.Double),
  744. (r'"', String.Double, 'string'),
  745. (r"(?s)\$'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
  746. (r"(?s)'.*?'", String.Single),
  747. (r';', Punctuation),
  748. (r'&|\||\^|<|>', Operator),
  749. (r'\s+', Text),
  750. (r'\d+(?= |\Z)', Number),
  751. (r'[^=\s\[\]{}()$"\'`\\<&|;]+', Text),
  752. ],
  753. 'string': [
  754. (r'"', String.Double, '#pop'),
  755. (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\$])+', String.Double),
  756. include('interp'),
  757. ],
  758. 'paren': [
  759. (r'\)', Keyword, '#pop'),
  760. include('root'),
  761. ],
  762. 'math': [
  763. (r'\)\)', Keyword, '#pop'),
  764. (r'[-+*/%^|&]|\*\*|\|\|', Operator),
  765. (r'\d+#\d+', Number),
  766. (r'\d+#(?! )', Number),
  767. (r'\d+', Number),
  768. include('root'),
  769. ],
  770. }