configs.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. """
  2. pygments.lexers.configs
  3. ~~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for configuration file formats.
  5. :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. from pygments.lexer import ExtendedRegexLexer, RegexLexer, default, words, \
  10. bygroups, include, using, line_re
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation, Whitespace, Literal, Error, Generic
  13. from pygments.lexers.shell import BashLexer
  14. from pygments.lexers.data import JsonLexer
  15. __all__ = ['IniLexer', 'SystemdLexer', 'DesktopLexer', 'RegeditLexer', 'PropertiesLexer',
  16. 'KconfigLexer', 'Cfengine3Lexer', 'ApacheConfLexer', 'SquidConfLexer',
  17. 'NginxConfLexer', 'LighttpdConfLexer', 'DockerLexer',
  18. 'TerraformLexer', 'TermcapLexer', 'TerminfoLexer',
  19. 'PkgConfigLexer', 'PacmanConfLexer', 'AugeasLexer', 'TOMLLexer',
  20. 'NestedTextLexer', 'SingularityLexer', 'UnixConfigLexer']
  21. class IniLexer(RegexLexer):
  22. """
  23. Lexer for configuration files in INI style.
  24. """
  25. name = 'INI'
  26. aliases = ['ini', 'cfg', 'dosini']
  27. filenames = [
  28. '*.ini', '*.cfg', '*.inf', '.editorconfig',
  29. ]
  30. mimetypes = ['text/x-ini', 'text/inf']
  31. url = 'https://en.wikipedia.org/wiki/INI_file'
  32. version_added = ''
  33. tokens = {
  34. 'root': [
  35. (r'\s+', Whitespace),
  36. (r'[;#].*', Comment.Single),
  37. (r'(\[.*?\])([ \t]*)$', bygroups(Keyword, Whitespace)),
  38. (r'''(.*?)([ \t]*)([=:])([ \t]*)(["'])''',
  39. bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String),
  40. "quoted_value"),
  41. (r'(.*?)([ \t]*)([=:])([ \t]*)([^;#\n]*)(\\)(\s+)',
  42. bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String,
  43. Text, Whitespace),
  44. "value"),
  45. (r'(.*?)([ \t]*)([=:])([ \t]*)([^ ;#\n]*(?: +[^ ;#\n]+)*)',
  46. bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)),
  47. # standalone option, supported by some INI parsers
  48. (r'(.+?)$', Name.Attribute),
  49. ],
  50. 'quoted_value': [
  51. (r'''([^"'\n]*)(["'])(\s*)''',
  52. bygroups(String, String, Whitespace), "#pop"),
  53. (r'[;#].*', Comment.Single),
  54. (r'$', String, "#pop"),
  55. ],
  56. 'value': [ # line continuation
  57. (r'\s+', Whitespace),
  58. (r'(\s*)(.*)(\\)([ \t]*)',
  59. bygroups(Whitespace, String, Text, Whitespace)),
  60. (r'.*$', String, "#pop"),
  61. ],
  62. }
  63. def analyse_text(text):
  64. npos = text.find('\n')
  65. if npos < 3:
  66. return False
  67. if text[0] == '[' and text[npos-1] == ']':
  68. return 0.8
  69. return False
  70. class DesktopLexer(RegexLexer):
  71. """
  72. Lexer for .desktop files.
  73. """
  74. name = 'Desktop file'
  75. url = "https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html"
  76. aliases = ['desktop']
  77. filenames = ['*.desktop']
  78. mimetypes = ['application/x-desktop']
  79. version_added = '2.16'
  80. tokens = {
  81. 'root': [
  82. (r'^[ \t]*\n', Whitespace),
  83. (r'^(#.*)(\n)', bygroups(Comment.Single, Whitespace)),
  84. (r'(\[[^\]\n]+\])(\n)', bygroups(Keyword, Whitespace)),
  85. (r'([-A-Za-z0-9]+)(\[[^\] \t=]+\])?([ \t]*)(=)([ \t]*)([^\n]*)([ \t\n]*\n)',
  86. bygroups(Name.Attribute, Name.Namespace, Whitespace, Operator, Whitespace, String, Whitespace)),
  87. ],
  88. }
  89. def analyse_text(text):
  90. if text.startswith("[Desktop Entry]"):
  91. return 1.0
  92. if re.search(r"^\[Desktop Entry\][ \t]*$", text[:500], re.MULTILINE) is not None:
  93. return 0.9
  94. return 0.0
  95. class SystemdLexer(RegexLexer):
  96. """
  97. Lexer for systemd unit files.
  98. """
  99. name = 'Systemd'
  100. url = "https://www.freedesktop.org/software/systemd/man/systemd.syntax.html"
  101. aliases = ['systemd']
  102. filenames = [
  103. '*.service', '*.socket', '*.device', '*.mount', '*.automount',
  104. '*.swap', '*.target', '*.path', '*.timer', '*.slice', '*.scope',
  105. ]
  106. version_added = '2.16'
  107. tokens = {
  108. 'root': [
  109. (r'^[ \t]*\n', Whitespace),
  110. (r'^([;#].*)(\n)', bygroups(Comment.Single, Whitespace)),
  111. (r'(\[[^\]\n]+\])(\n)', bygroups(Keyword, Whitespace)),
  112. (r'([^=]+)([ \t]*)(=)([ \t]*)([^\n]*)(\\)(\n)',
  113. bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String,
  114. Text, Whitespace),
  115. "value"),
  116. (r'([^=]+)([ \t]*)(=)([ \t]*)([^\n]*)(\n)',
  117. bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, Whitespace)),
  118. ],
  119. 'value': [
  120. # line continuation
  121. (r'^([;#].*)(\n)', bygroups(Comment.Single, Whitespace)),
  122. (r'([ \t]*)([^\n]*)(\\)(\n)',
  123. bygroups(Whitespace, String, Text, Whitespace)),
  124. (r'([ \t]*)([^\n]*)(\n)',
  125. bygroups(Whitespace, String, Whitespace), "#pop"),
  126. ],
  127. }
  128. def analyse_text(text):
  129. if text.startswith("[Unit]"):
  130. return 1.0
  131. if re.search(r"^\[Unit\][ \t]*$", text[:500], re.MULTILINE) is not None:
  132. return 0.9
  133. return 0.0
  134. class RegeditLexer(RegexLexer):
  135. """
  136. Lexer for Windows Registry files produced by regedit.
  137. """
  138. name = 'reg'
  139. url = 'http://en.wikipedia.org/wiki/Windows_Registry#.REG_files'
  140. aliases = ['registry']
  141. filenames = ['*.reg']
  142. mimetypes = ['text/x-windows-registry']
  143. version_added = '1.6'
  144. tokens = {
  145. 'root': [
  146. (r'Windows Registry Editor.*', Text),
  147. (r'\s+', Whitespace),
  148. (r'[;#].*', Comment.Single),
  149. (r'(\[)(-?)(HKEY_[A-Z_]+)(.*?\])$',
  150. bygroups(Keyword, Operator, Name.Builtin, Keyword)),
  151. # String keys, which obey somewhat normal escaping
  152. (r'("(?:\\"|\\\\|[^"])+")([ \t]*)(=)([ \t]*)',
  153. bygroups(Name.Attribute, Whitespace, Operator, Whitespace),
  154. 'value'),
  155. # Bare keys (includes @)
  156. (r'(.*?)([ \t]*)(=)([ \t]*)',
  157. bygroups(Name.Attribute, Whitespace, Operator, Whitespace),
  158. 'value'),
  159. ],
  160. 'value': [
  161. (r'-', Operator, '#pop'), # delete value
  162. (r'(dword|hex(?:\([0-9a-fA-F]\))?)(:)([0-9a-fA-F,]+)',
  163. bygroups(Name.Variable, Punctuation, Number), '#pop'),
  164. # As far as I know, .reg files do not support line continuation.
  165. (r'.+', String, '#pop'),
  166. default('#pop'),
  167. ]
  168. }
  169. def analyse_text(text):
  170. return text.startswith('Windows Registry Editor')
  171. class PropertiesLexer(RegexLexer):
  172. """
  173. Lexer for configuration files in Java's properties format.
  174. Note: trailing whitespace counts as part of the value as per spec
  175. """
  176. name = 'Properties'
  177. aliases = ['properties', 'jproperties']
  178. filenames = ['*.properties']
  179. mimetypes = ['text/x-java-properties']
  180. url = 'https://en.wikipedia.org/wiki/.properties'
  181. version_added = '1.4'
  182. tokens = {
  183. 'root': [
  184. # comments
  185. (r'[!#].*|/{2}.*', Comment.Single),
  186. # ending a comment or whitespace-only line
  187. (r'\n', Whitespace),
  188. # eat whitespace at the beginning of a line
  189. (r'^[^\S\n]+', Whitespace),
  190. # start lexing a key
  191. default('key'),
  192. ],
  193. 'key': [
  194. # non-escaped key characters
  195. (r'[^\\:=\s]+', Name.Attribute),
  196. # escapes
  197. include('escapes'),
  198. # separator is the first non-escaped whitespace or colon or '=' on the line;
  199. # if it's whitespace, = and : are gobbled after it
  200. (r'([^\S\n]*)([:=])([^\S\n]*)',
  201. bygroups(Whitespace, Operator, Whitespace),
  202. ('#pop', 'value')),
  203. (r'[^\S\n]+', Whitespace, ('#pop', 'value')),
  204. # maybe we got no value after all
  205. (r'\n', Whitespace, '#pop'),
  206. ],
  207. 'value': [
  208. # non-escaped value characters
  209. (r'[^\\\n]+', String),
  210. # escapes
  211. include('escapes'),
  212. # end the value on an unescaped newline
  213. (r'\n', Whitespace, '#pop'),
  214. ],
  215. 'escapes': [
  216. # line continuations; these gobble whitespace at the beginning of the next line
  217. (r'(\\\n)([^\S\n]*)', bygroups(String.Escape, Whitespace)),
  218. # other escapes
  219. (r'\\(.|\n)', String.Escape),
  220. ],
  221. }
  222. def _rx_indent(level):
  223. # Kconfig *always* interprets a tab as 8 spaces, so this is the default.
  224. # Edit this if you are in an environment where KconfigLexer gets expanded
  225. # input (tabs expanded to spaces) and the expansion tab width is != 8,
  226. # e.g. in connection with Trac (trac.ini, [mimeviewer], tab_width).
  227. # Value range here is 2 <= {tab_width} <= 8.
  228. tab_width = 8
  229. # Regex matching a given indentation {level}, assuming that indentation is
  230. # a multiple of {tab_width}. In other cases there might be problems.
  231. if tab_width == 2:
  232. space_repeat = '+'
  233. else:
  234. space_repeat = '{1,%d}' % (tab_width - 1)
  235. if level == 1:
  236. level_repeat = ''
  237. else:
  238. level_repeat = f'{{{level}}}'
  239. return rf'(?:\t| {space_repeat}\t| {{{tab_width}}}){level_repeat}.*\n'
  240. class KconfigLexer(RegexLexer):
  241. """
  242. For Linux-style Kconfig files.
  243. """
  244. name = 'Kconfig'
  245. aliases = ['kconfig', 'menuconfig', 'linux-config', 'kernel-config']
  246. version_added = '1.6'
  247. # Adjust this if new kconfig file names appear in your environment
  248. filenames = ['Kconfig*', '*Config.in*', 'external.in*',
  249. 'standard-modules.in']
  250. mimetypes = ['text/x-kconfig']
  251. url = 'https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html'
  252. # No re.MULTILINE, indentation-aware help text needs line-by-line handling
  253. flags = 0
  254. def call_indent(level):
  255. # If indentation >= {level} is detected, enter state 'indent{level}'
  256. return (_rx_indent(level), String.Doc, f'indent{level}')
  257. def do_indent(level):
  258. # Print paragraphs of indentation level >= {level} as String.Doc,
  259. # ignoring blank lines. Then return to 'root' state.
  260. return [
  261. (_rx_indent(level), String.Doc),
  262. (r'\s*\n', Text),
  263. default('#pop:2')
  264. ]
  265. tokens = {
  266. 'root': [
  267. (r'\s+', Whitespace),
  268. (r'#.*?\n', Comment.Single),
  269. (words((
  270. 'mainmenu', 'config', 'menuconfig', 'choice', 'endchoice',
  271. 'comment', 'menu', 'endmenu', 'visible if', 'if', 'endif',
  272. 'source', 'prompt', 'select', 'depends on', 'default',
  273. 'range', 'option'), suffix=r'\b'),
  274. Keyword),
  275. (r'(---help---|help)[\t ]*\n', Keyword, 'help'),
  276. (r'(bool|tristate|string|hex|int|defconfig_list|modules|env)\b',
  277. Name.Builtin),
  278. (r'[!=&|]', Operator),
  279. (r'[()]', Punctuation),
  280. (r'[0-9]+', Number.Integer),
  281. (r"'(''|[^'])*'", String.Single),
  282. (r'"(""|[^"])*"', String.Double),
  283. (r'\S+', Text),
  284. ],
  285. # Help text is indented, multi-line and ends when a lower indentation
  286. # level is detected.
  287. 'help': [
  288. # Skip blank lines after help token, if any
  289. (r'\s*\n', Text),
  290. # Determine the first help line's indentation level heuristically(!).
  291. # Attention: this is not perfect, but works for 99% of "normal"
  292. # indentation schemes up to a max. indentation level of 7.
  293. call_indent(7),
  294. call_indent(6),
  295. call_indent(5),
  296. call_indent(4),
  297. call_indent(3),
  298. call_indent(2),
  299. call_indent(1),
  300. default('#pop'), # for incomplete help sections without text
  301. ],
  302. # Handle text for indentation levels 7 to 1
  303. 'indent7': do_indent(7),
  304. 'indent6': do_indent(6),
  305. 'indent5': do_indent(5),
  306. 'indent4': do_indent(4),
  307. 'indent3': do_indent(3),
  308. 'indent2': do_indent(2),
  309. 'indent1': do_indent(1),
  310. }
  311. class Cfengine3Lexer(RegexLexer):
  312. """
  313. Lexer for CFEngine3 policy files.
  314. """
  315. name = 'CFEngine3'
  316. url = 'http://cfengine.org'
  317. aliases = ['cfengine3', 'cf3']
  318. filenames = ['*.cf']
  319. mimetypes = []
  320. version_added = '1.5'
  321. tokens = {
  322. 'root': [
  323. (r'#.*?\n', Comment),
  324. (r'(body)(\s+)(\S+)(\s+)(control)',
  325. bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
  326. (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)(\()',
  327. bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function, Punctuation),
  328. 'arglist'),
  329. (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)',
  330. bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function)),
  331. (r'(")([^"]+)(")(\s+)(string|slist|int|real)(\s*)(=>)(\s*)',
  332. bygroups(Punctuation, Name.Variable, Punctuation,
  333. Whitespace, Keyword.Type, Whitespace, Operator, Whitespace)),
  334. (r'(\S+)(\s*)(=>)(\s*)',
  335. bygroups(Keyword.Reserved, Whitespace, Operator, Text)),
  336. (r'"', String, 'string'),
  337. (r'(\w+)(\()', bygroups(Name.Function, Punctuation)),
  338. (r'([\w.!&|()]+)(::)', bygroups(Name.Class, Punctuation)),
  339. (r'(\w+)(:)', bygroups(Keyword.Declaration, Punctuation)),
  340. (r'@[{(][^)}]+[})]', Name.Variable),
  341. (r'[(){},;]', Punctuation),
  342. (r'=>', Operator),
  343. (r'->', Operator),
  344. (r'\d+\.\d+', Number.Float),
  345. (r'\d+', Number.Integer),
  346. (r'\w+', Name.Function),
  347. (r'\s+', Whitespace),
  348. ],
  349. 'string': [
  350. (r'\$[{(]', String.Interpol, 'interpol'),
  351. (r'\\.', String.Escape),
  352. (r'"', String, '#pop'),
  353. (r'\n', String),
  354. (r'.', String),
  355. ],
  356. 'interpol': [
  357. (r'\$[{(]', String.Interpol, '#push'),
  358. (r'[})]', String.Interpol, '#pop'),
  359. (r'[^${()}]+', String.Interpol),
  360. ],
  361. 'arglist': [
  362. (r'\)', Punctuation, '#pop'),
  363. (r',', Punctuation),
  364. (r'\w+', Name.Variable),
  365. (r'\s+', Whitespace),
  366. ],
  367. }
  368. class ApacheConfLexer(RegexLexer):
  369. """
  370. Lexer for configuration files following the Apache config file
  371. format.
  372. """
  373. name = 'ApacheConf'
  374. aliases = ['apacheconf', 'aconf', 'apache']
  375. filenames = ['.htaccess', 'apache.conf', 'apache2.conf']
  376. mimetypes = ['text/x-apacheconf']
  377. url = 'https://httpd.apache.org/docs/current/configuring.html'
  378. version_added = '0.6'
  379. flags = re.MULTILINE | re.IGNORECASE
  380. tokens = {
  381. 'root': [
  382. (r'\s+', Whitespace),
  383. (r'#(.*\\\n)+.*$|(#.*?)$', Comment),
  384. (r'(<[^\s>/][^\s>]*)(?:(\s+)(.*))?(>)',
  385. bygroups(Name.Tag, Whitespace, String, Name.Tag)),
  386. (r'(</[^\s>]+)(>)',
  387. bygroups(Name.Tag, Name.Tag)),
  388. (r'[a-z]\w*', Name.Builtin, 'value'),
  389. (r'\.+', Text),
  390. ],
  391. 'value': [
  392. (r'\\\n', Text),
  393. (r'\n+', Whitespace, '#pop'),
  394. (r'\\', Text),
  395. (r'[^\S\n]+', Whitespace),
  396. (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number),
  397. (r'\d+', Number),
  398. (r'/([*a-z0-9][*\w./-]+)', String.Other),
  399. (r'(on|off|none|any|all|double|email|dns|min|minimal|'
  400. r'os|productonly|full|emerg|alert|crit|error|warn|'
  401. r'notice|info|debug|registry|script|inetd|standalone|'
  402. r'user|group)\b', Keyword),
  403. (r'"([^"\\]*(?:\\(.|\n)[^"\\]*)*)"', String.Double),
  404. (r'[^\s"\\]+', Text)
  405. ],
  406. }
  407. class SquidConfLexer(RegexLexer):
  408. """
  409. Lexer for squid configuration files.
  410. """
  411. name = 'SquidConf'
  412. url = 'http://www.squid-cache.org/'
  413. aliases = ['squidconf', 'squid.conf', 'squid']
  414. filenames = ['squid.conf']
  415. mimetypes = ['text/x-squidconf']
  416. version_added = '0.9'
  417. flags = re.IGNORECASE
  418. keywords = (
  419. "access_log", "acl", "always_direct", "announce_host",
  420. "announce_period", "announce_port", "announce_to", "anonymize_headers",
  421. "append_domain", "as_whois_server", "auth_param_basic",
  422. "authenticate_children", "authenticate_program", "authenticate_ttl",
  423. "broken_posts", "buffered_logs", "cache_access_log", "cache_announce",
  424. "cache_dir", "cache_dns_program", "cache_effective_group",
  425. "cache_effective_user", "cache_host", "cache_host_acl",
  426. "cache_host_domain", "cache_log", "cache_mem", "cache_mem_high",
  427. "cache_mem_low", "cache_mgr", "cachemgr_passwd", "cache_peer",
  428. "cache_peer_access", "cache_replacement_policy", "cache_stoplist",
  429. "cache_stoplist_pattern", "cache_store_log", "cache_swap",
  430. "cache_swap_high", "cache_swap_log", "cache_swap_low", "client_db",
  431. "client_lifetime", "client_netmask", "connect_timeout", "coredump_dir",
  432. "dead_peer_timeout", "debug_options", "delay_access", "delay_class",
  433. "delay_initial_bucket_level", "delay_parameters", "delay_pools",
  434. "deny_info", "dns_children", "dns_defnames", "dns_nameservers",
  435. "dns_testnames", "emulate_httpd_log", "err_html_text",
  436. "fake_user_agent", "firewall_ip", "forwarded_for", "forward_snmpd_port",
  437. "fqdncache_size", "ftpget_options", "ftpget_program", "ftp_list_width",
  438. "ftp_passive", "ftp_user", "half_closed_clients", "header_access",
  439. "header_replace", "hierarchy_stoplist", "high_response_time_warning",
  440. "high_page_fault_warning", "hosts_file", "htcp_port", "http_access",
  441. "http_anonymizer", "httpd_accel", "httpd_accel_host",
  442. "httpd_accel_port", "httpd_accel_uses_host_header",
  443. "httpd_accel_with_proxy", "http_port", "http_reply_access",
  444. "icp_access", "icp_hit_stale", "icp_port", "icp_query_timeout",
  445. "ident_lookup", "ident_lookup_access", "ident_timeout",
  446. "incoming_http_average", "incoming_icp_average", "inside_firewall",
  447. "ipcache_high", "ipcache_low", "ipcache_size", "local_domain",
  448. "local_ip", "logfile_rotate", "log_fqdn", "log_icp_queries",
  449. "log_mime_hdrs", "maximum_object_size", "maximum_single_addr_tries",
  450. "mcast_groups", "mcast_icp_query_timeout", "mcast_miss_addr",
  451. "mcast_miss_encode_key", "mcast_miss_port", "memory_pools",
  452. "memory_pools_limit", "memory_replacement_policy", "mime_table",
  453. "min_http_poll_cnt", "min_icp_poll_cnt", "minimum_direct_hops",
  454. "minimum_object_size", "minimum_retry_timeout", "miss_access",
  455. "negative_dns_ttl", "negative_ttl", "neighbor_timeout",
  456. "neighbor_type_domain", "netdb_high", "netdb_low", "netdb_ping_period",
  457. "netdb_ping_rate", "never_direct", "no_cache", "passthrough_proxy",
  458. "pconn_timeout", "pid_filename", "pinger_program", "positive_dns_ttl",
  459. "prefer_direct", "proxy_auth", "proxy_auth_realm", "query_icmp",
  460. "quick_abort", "quick_abort_max", "quick_abort_min",
  461. "quick_abort_pct", "range_offset_limit", "read_timeout",
  462. "redirect_children", "redirect_program",
  463. "redirect_rewrites_host_header", "reference_age",
  464. "refresh_pattern", "reload_into_ims", "request_body_max_size",
  465. "request_size", "request_timeout", "shutdown_lifetime",
  466. "single_parent_bypass", "siteselect_timeout", "snmp_access",
  467. "snmp_incoming_address", "snmp_port", "source_ping", "ssl_proxy",
  468. "store_avg_object_size", "store_objects_per_bucket",
  469. "strip_query_terms", "swap_level1_dirs", "swap_level2_dirs",
  470. "tcp_incoming_address", "tcp_outgoing_address", "tcp_recv_bufsize",
  471. "test_reachability", "udp_hit_obj", "udp_hit_obj_size",
  472. "udp_incoming_address", "udp_outgoing_address", "unique_hostname",
  473. "unlinkd_program", "uri_whitespace", "useragent_log",
  474. "visible_hostname", "wais_relay", "wais_relay_host", "wais_relay_port",
  475. )
  476. opts = (
  477. "proxy-only", "weight", "ttl", "no-query", "default", "round-robin",
  478. "multicast-responder", "on", "off", "all", "deny", "allow", "via",
  479. "parent", "no-digest", "heap", "lru", "realm", "children", "q1", "q2",
  480. "credentialsttl", "none", "disable", "offline_toggle", "diskd",
  481. )
  482. actions = (
  483. "shutdown", "info", "parameter", "server_list", "client_list",
  484. r'squid.conf',
  485. )
  486. actions_stats = (
  487. "objects", "vm_objects", "utilization", "ipcache", "fqdncache", "dns",
  488. "redirector", "io", "reply_headers", "filedescriptors", "netdb",
  489. )
  490. actions_log = ("status", "enable", "disable", "clear")
  491. acls = (
  492. "url_regex", "urlpath_regex", "referer_regex", "port", "proto",
  493. "req_mime_type", "rep_mime_type", "method", "browser", "user", "src",
  494. "dst", "time", "dstdomain", "ident", "snmp_community",
  495. )
  496. ipv4_group = r'(\d+|0x[0-9a-f]+)'
  497. ipv4 = rf'({ipv4_group}(\.{ipv4_group}){{3}})'
  498. ipv6_group = r'([0-9a-f]{0,4})'
  499. ipv6 = rf'({ipv6_group}(:{ipv6_group}){{1,7}})'
  500. bare_ip = rf'({ipv4}|{ipv6})'
  501. # XXX: /integer is a subnet mark, but what is /IP ?
  502. # There is no test where it is used.
  503. ip = rf'{bare_ip}(/({bare_ip}|\d+))?'
  504. tokens = {
  505. 'root': [
  506. (r'\s+', Whitespace),
  507. (r'#', Comment, 'comment'),
  508. (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword),
  509. (words(opts, prefix=r'\b', suffix=r'\b'), Name.Constant),
  510. # Actions
  511. (words(actions, prefix=r'\b', suffix=r'\b'), String),
  512. (words(actions_stats, prefix=r'stats/', suffix=r'\b'), String),
  513. (words(actions_log, prefix=r'log/', suffix=r'='), String),
  514. (words(acls, prefix=r'\b', suffix=r'\b'), Keyword),
  515. (ip, Number.Float),
  516. (r'(?:\b\d+\b(?:-\b\d+|%)?)', Number),
  517. (r'\S+', Text),
  518. ],
  519. 'comment': [
  520. (r'\s*TAG:.*', String.Escape, '#pop'),
  521. (r'.+', Comment, '#pop'),
  522. default('#pop'),
  523. ],
  524. }
  525. class NginxConfLexer(RegexLexer):
  526. """
  527. Lexer for Nginx configuration files.
  528. """
  529. name = 'Nginx configuration file'
  530. url = 'http://nginx.net/'
  531. aliases = ['nginx']
  532. filenames = ['nginx.conf']
  533. mimetypes = ['text/x-nginx-conf']
  534. version_added = '0.11'
  535. tokens = {
  536. 'root': [
  537. (r'(include)(\s+)([^\s;]+)', bygroups(Keyword, Whitespace, Name)),
  538. (r'[^\s;#]+', Keyword, 'stmt'),
  539. include('base'),
  540. ],
  541. 'block': [
  542. (r'\}', Punctuation, '#pop:2'),
  543. (r'[^\s;#]+', Keyword.Namespace, 'stmt'),
  544. include('base'),
  545. ],
  546. 'stmt': [
  547. (r'\{', Punctuation, 'block'),
  548. (r';', Punctuation, '#pop'),
  549. include('base'),
  550. ],
  551. 'base': [
  552. (r'#.*\n', Comment.Single),
  553. (r'on|off', Name.Constant),
  554. (r'\$[^\s;#()]+', Name.Variable),
  555. (r'([a-z0-9.-]+)(:)([0-9]+)',
  556. bygroups(Name, Punctuation, Number.Integer)),
  557. (r'[a-z-]+/[a-z-+]+', String), # mimetype
  558. # (r'[a-zA-Z._-]+', Keyword),
  559. (r'[0-9]+[km]?\b', Number.Integer),
  560. (r'(~)(\s*)([^\s{]+)', bygroups(Punctuation, Whitespace, String.Regex)),
  561. (r'[:=~]', Punctuation),
  562. (r'[^\s;#{}$]+', String), # catch all
  563. (r'/[^\s;#]*', Name), # pathname
  564. (r'\s+', Whitespace),
  565. (r'[$;]', Text), # leftover characters
  566. ],
  567. }
  568. class LighttpdConfLexer(RegexLexer):
  569. """
  570. Lexer for Lighttpd configuration files.
  571. """
  572. name = 'Lighttpd configuration file'
  573. url = 'http://lighttpd.net/'
  574. aliases = ['lighttpd', 'lighty']
  575. filenames = ['lighttpd.conf']
  576. mimetypes = ['text/x-lighttpd-conf']
  577. version_added = '0.11'
  578. tokens = {
  579. 'root': [
  580. (r'#.*\n', Comment.Single),
  581. (r'/\S*', Name), # pathname
  582. (r'[a-zA-Z._-]+', Keyword),
  583. (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number),
  584. (r'[0-9]+', Number),
  585. (r'=>|=~|\+=|==|=|\+', Operator),
  586. (r'\$[A-Z]+', Name.Builtin),
  587. (r'[(){}\[\],]', Punctuation),
  588. (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double),
  589. (r'\s+', Whitespace),
  590. ],
  591. }
  592. class DockerLexer(RegexLexer):
  593. """
  594. Lexer for Docker configuration files.
  595. """
  596. name = 'Docker'
  597. url = 'http://docker.io'
  598. aliases = ['docker', 'dockerfile']
  599. filenames = ['Dockerfile', '*.docker']
  600. mimetypes = ['text/x-dockerfile-config']
  601. version_added = '2.0'
  602. _keywords = (r'(?:MAINTAINER|EXPOSE|WORKDIR|USER|STOPSIGNAL)')
  603. _bash_keywords = (r'(?:RUN|CMD|ENTRYPOINT|ENV|ARG|LABEL|ADD|COPY)')
  604. _lb = r'(?:\s*\\?\s*)' # dockerfile line break regex
  605. flags = re.IGNORECASE | re.MULTILINE
  606. tokens = {
  607. 'root': [
  608. (r'#.*', Comment),
  609. (r'(FROM)([ \t]*)(\S*)([ \t]*)(?:(AS)([ \t]*)(\S*))?',
  610. bygroups(Keyword, Whitespace, String, Whitespace, Keyword, Whitespace, String)),
  611. (rf'(ONBUILD)(\s+)({_lb})', bygroups(Keyword, Whitespace, using(BashLexer))),
  612. (rf'(HEALTHCHECK)(\s+)(({_lb}--\w+=\w+{_lb})*)',
  613. bygroups(Keyword, Whitespace, using(BashLexer))),
  614. (rf'(VOLUME|ENTRYPOINT|CMD|SHELL)(\s+)({_lb})(\[.*?\])',
  615. bygroups(Keyword, Whitespace, using(BashLexer), using(JsonLexer))),
  616. (rf'(LABEL|ENV|ARG)(\s+)(({_lb}\w+=\w+{_lb})*)',
  617. bygroups(Keyword, Whitespace, using(BashLexer))),
  618. (rf'({_keywords}|VOLUME)\b(\s+)(.*)', bygroups(Keyword, Whitespace, String)),
  619. (rf'({_bash_keywords})(\s+)', bygroups(Keyword, Whitespace)),
  620. (r'(.*\\\n)*.+', using(BashLexer)),
  621. ]
  622. }
  623. class TerraformLexer(ExtendedRegexLexer):
  624. """
  625. Lexer for terraformi ``.tf`` files.
  626. """
  627. name = 'Terraform'
  628. url = 'https://www.terraform.io/'
  629. aliases = ['terraform', 'tf', 'hcl']
  630. filenames = ['*.tf', '*.hcl']
  631. mimetypes = ['application/x-tf', 'application/x-terraform']
  632. version_added = '2.1'
  633. classes = ('backend', 'data', 'module', 'output', 'provider',
  634. 'provisioner', 'resource', 'variable')
  635. classes_re = "({})".format(('|').join(classes))
  636. types = ('string', 'number', 'bool', 'list', 'tuple', 'map', 'set', 'object', 'null')
  637. numeric_functions = ('abs', 'ceil', 'floor', 'log', 'max',
  638. 'mix', 'parseint', 'pow', 'signum')
  639. string_functions = ('chomp', 'format', 'formatlist', 'indent',
  640. 'join', 'lower', 'regex', 'regexall', 'replace',
  641. 'split', 'strrev', 'substr', 'title', 'trim',
  642. 'trimprefix', 'trimsuffix', 'trimspace', 'upper'
  643. )
  644. collection_functions = ('alltrue', 'anytrue', 'chunklist', 'coalesce',
  645. 'coalescelist', 'compact', 'concat', 'contains',
  646. 'distinct', 'element', 'flatten', 'index', 'keys',
  647. 'length', 'list', 'lookup', 'map', 'matchkeys',
  648. 'merge', 'range', 'reverse', 'setintersection',
  649. 'setproduct', 'setsubtract', 'setunion', 'slice',
  650. 'sort', 'sum', 'transpose', 'values', 'zipmap'
  651. )
  652. encoding_functions = ('base64decode', 'base64encode', 'base64gzip',
  653. 'csvdecode', 'jsondecode', 'jsonencode', 'textdecodebase64',
  654. 'textencodebase64', 'urlencode', 'yamldecode', 'yamlencode')
  655. filesystem_functions = ('abspath', 'dirname', 'pathexpand', 'basename',
  656. 'file', 'fileexists', 'fileset', 'filebase64', 'templatefile')
  657. date_time_functions = ('formatdate', 'timeadd', 'timestamp')
  658. hash_crypto_functions = ('base64sha256', 'base64sha512', 'bcrypt', 'filebase64sha256',
  659. 'filebase64sha512', 'filemd5', 'filesha1', 'filesha256', 'filesha512',
  660. 'md5', 'rsadecrypt', 'sha1', 'sha256', 'sha512', 'uuid', 'uuidv5')
  661. ip_network_functions = ('cidrhost', 'cidrnetmask', 'cidrsubnet', 'cidrsubnets')
  662. type_conversion_functions = ('can', 'defaults', 'tobool', 'tolist', 'tomap',
  663. 'tonumber', 'toset', 'tostring', 'try')
  664. builtins = numeric_functions + string_functions + collection_functions + encoding_functions +\
  665. filesystem_functions + date_time_functions + hash_crypto_functions + ip_network_functions +\
  666. type_conversion_functions
  667. builtins_re = "({})".format(('|').join(builtins))
  668. def heredoc_callback(self, match, ctx):
  669. # Parse a terraform heredoc
  670. # match: 1 = <<[-]?, 2 = name 3 = rest of line
  671. start = match.start(1)
  672. yield start, Operator, match.group(1) # <<[-]?
  673. yield match.start(2), String.Delimiter, match.group(2) # heredoc name
  674. ctx.pos = match.start(3)
  675. ctx.end = match.end(3)
  676. yield ctx.pos, String.Heredoc, match.group(3)
  677. ctx.pos = match.end()
  678. hdname = match.group(2)
  679. tolerant = True # leading whitespace is always accepted
  680. lines = []
  681. for match in line_re.finditer(ctx.text, ctx.pos):
  682. if tolerant:
  683. check = match.group().strip()
  684. else:
  685. check = match.group().rstrip()
  686. if check == hdname:
  687. for amatch in lines:
  688. yield amatch.start(), String.Heredoc, amatch.group()
  689. yield match.start(), String.Delimiter, match.group()
  690. ctx.pos = match.end()
  691. break
  692. else:
  693. lines.append(match)
  694. else:
  695. # end of heredoc not found -- error!
  696. for amatch in lines:
  697. yield amatch.start(), Error, amatch.group()
  698. ctx.end = len(ctx.text)
  699. tokens = {
  700. 'root': [
  701. include('basic'),
  702. include('whitespace'),
  703. # Strings
  704. (r'(".*")', bygroups(String.Double)),
  705. # Constants
  706. (words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Name.Constant),
  707. # Types
  708. (words(types, prefix=r'\b', suffix=r'\b'), Keyword.Type),
  709. include('identifier'),
  710. include('punctuation'),
  711. (r'[0-9]+', Number),
  712. ],
  713. 'basic': [
  714. (r'\s*/\*', Comment.Multiline, 'comment'),
  715. (r'\s*(#|//).*\n', Comment.Single),
  716. include('whitespace'),
  717. # e.g. terraform {
  718. # e.g. egress {
  719. (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=?)(\s*)(\{)',
  720. bygroups(Whitespace, Name.Builtin, Whitespace, Operator, Whitespace, Punctuation)),
  721. # Assignment with attributes, e.g. something = ...
  722. (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=)(\s*)',
  723. bygroups(Whitespace, Name.Attribute, Whitespace, Operator, Whitespace)),
  724. # Assignment with environment variables and similar, e.g. "something" = ...
  725. # or key value assignment, e.g. "SlotName" : ...
  726. (r'(\s*)("\S+")(\s*)([=:])(\s*)',
  727. bygroups(Whitespace, Literal.String.Double, Whitespace, Operator, Whitespace)),
  728. # Functions, e.g. jsonencode(element("value"))
  729. (builtins_re + r'(\()', bygroups(Name.Function, Punctuation)),
  730. # List of attributes, e.g. ignore_changes = [last_modified, filename]
  731. (r'(\[)([a-z_,\s]+)(\])', bygroups(Punctuation, Name.Builtin, Punctuation)),
  732. # e.g. resource "aws_security_group" "allow_tls" {
  733. # e.g. backend "consul" {
  734. (classes_re + r'(\s+)("[0-9a-zA-Z-_]+")?(\s*)("[0-9a-zA-Z-_]+")(\s+)(\{)',
  735. bygroups(Keyword.Reserved, Whitespace, Name.Class, Whitespace, Name.Variable, Whitespace, Punctuation)),
  736. # here-doc style delimited strings
  737. (r'(<<-?)\s*([a-zA-Z_]\w*)(.*?\n)', heredoc_callback),
  738. ],
  739. 'identifier': [
  740. (r'\b(var\.[0-9a-zA-Z-_\.\[\]]+)\b', bygroups(Name.Variable)),
  741. (r'\b([0-9a-zA-Z-_\[\]]+\.[0-9a-zA-Z-_\.\[\]]+)\b',
  742. bygroups(Name.Variable)),
  743. ],
  744. 'punctuation': [
  745. (r'[\[\]()\{\},.?:!=]', Punctuation),
  746. ],
  747. 'comment': [
  748. (r'[^*/]', Comment.Multiline),
  749. (r'/\*', Comment.Multiline, '#push'),
  750. (r'\*/', Comment.Multiline, '#pop'),
  751. (r'[*/]', Comment.Multiline)
  752. ],
  753. 'whitespace': [
  754. (r'\n', Whitespace),
  755. (r'\s+', Whitespace),
  756. (r'(\\)(\n)', bygroups(Text, Whitespace)),
  757. ],
  758. }
  759. class TermcapLexer(RegexLexer):
  760. """
  761. Lexer for termcap database source.
  762. This is very simple and minimal.
  763. """
  764. name = 'Termcap'
  765. aliases = ['termcap']
  766. filenames = ['termcap', 'termcap.src']
  767. mimetypes = []
  768. url = 'https://en.wikipedia.org/wiki/Termcap'
  769. version_added = '2.1'
  770. # NOTE:
  771. # * multiline with trailing backslash
  772. # * separator is ':'
  773. # * to embed colon as data, we must use \072
  774. # * space after separator is not allowed (mayve)
  775. tokens = {
  776. 'root': [
  777. (r'^#.*', Comment),
  778. (r'^[^\s#:|]+', Name.Tag, 'names'),
  779. (r'\s+', Whitespace),
  780. ],
  781. 'names': [
  782. (r'\n', Whitespace, '#pop'),
  783. (r':', Punctuation, 'defs'),
  784. (r'\|', Punctuation),
  785. (r'[^:|]+', Name.Attribute),
  786. ],
  787. 'defs': [
  788. (r'(\\)(\n[ \t]*)', bygroups(Text, Whitespace)),
  789. (r'\n[ \t]*', Whitespace, '#pop:2'),
  790. (r'(#)([0-9]+)', bygroups(Operator, Number)),
  791. (r'=', Operator, 'data'),
  792. (r':', Punctuation),
  793. (r'[^\s:=#]+', Name.Class),
  794. ],
  795. 'data': [
  796. (r'\\072', Literal),
  797. (r':', Punctuation, '#pop'),
  798. (r'[^:\\]+', Literal), # for performance
  799. (r'.', Literal),
  800. ],
  801. }
  802. class TerminfoLexer(RegexLexer):
  803. """
  804. Lexer for terminfo database source.
  805. This is very simple and minimal.
  806. """
  807. name = 'Terminfo'
  808. aliases = ['terminfo']
  809. filenames = ['terminfo', 'terminfo.src']
  810. mimetypes = []
  811. url = 'https://en.wikipedia.org/wiki/Terminfo'
  812. version_added = '2.1'
  813. # NOTE:
  814. # * multiline with leading whitespace
  815. # * separator is ','
  816. # * to embed comma as data, we can use \,
  817. # * space after separator is allowed
  818. tokens = {
  819. 'root': [
  820. (r'^#.*$', Comment),
  821. (r'^[^\s#,|]+', Name.Tag, 'names'),
  822. (r'\s+', Whitespace),
  823. ],
  824. 'names': [
  825. (r'\n', Whitespace, '#pop'),
  826. (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), 'defs'),
  827. (r'\|', Punctuation),
  828. (r'[^,|]+', Name.Attribute),
  829. ],
  830. 'defs': [
  831. (r'\n[ \t]+', Whitespace),
  832. (r'\n', Whitespace, '#pop:2'),
  833. (r'(#)([0-9]+)', bygroups(Operator, Number)),
  834. (r'=', Operator, 'data'),
  835. (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace)),
  836. (r'[^\s,=#]+', Name.Class),
  837. ],
  838. 'data': [
  839. (r'\\[,\\]', Literal),
  840. (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), '#pop'),
  841. (r'[^\\,]+', Literal), # for performance
  842. (r'.', Literal),
  843. ],
  844. }
  845. class PkgConfigLexer(RegexLexer):
  846. """
  847. Lexer for pkg-config
  848. (see also `manual page <http://linux.die.net/man/1/pkg-config>`_).
  849. """
  850. name = 'PkgConfig'
  851. url = 'http://www.freedesktop.org/wiki/Software/pkg-config/'
  852. aliases = ['pkgconfig']
  853. filenames = ['*.pc']
  854. mimetypes = []
  855. version_added = '2.1'
  856. tokens = {
  857. 'root': [
  858. (r'#.*$', Comment.Single),
  859. # variable definitions
  860. (r'^(\w+)(=)', bygroups(Name.Attribute, Operator)),
  861. # keyword lines
  862. (r'^([\w.]+)(:)',
  863. bygroups(Name.Tag, Punctuation), 'spvalue'),
  864. # variable references
  865. include('interp'),
  866. # fallback
  867. (r'\s+', Whitespace),
  868. (r'[^${}#=:\n.]+', Text),
  869. (r'.', Text),
  870. ],
  871. 'interp': [
  872. # you can escape literal "$" as "$$"
  873. (r'\$\$', Text),
  874. # variable references
  875. (r'\$\{', String.Interpol, 'curly'),
  876. ],
  877. 'curly': [
  878. (r'\}', String.Interpol, '#pop'),
  879. (r'\w+', Name.Attribute),
  880. ],
  881. 'spvalue': [
  882. include('interp'),
  883. (r'#.*$', Comment.Single, '#pop'),
  884. (r'\n', Whitespace, '#pop'),
  885. # fallback
  886. (r'\s+', Whitespace),
  887. (r'[^${}#\n\s]+', Text),
  888. (r'.', Text),
  889. ],
  890. }
  891. class PacmanConfLexer(RegexLexer):
  892. """
  893. Lexer for pacman.conf.
  894. Actually, IniLexer works almost fine for this format,
  895. but it yield error token. It is because pacman.conf has
  896. a form without assignment like:
  897. UseSyslog
  898. Color
  899. TotalDownload
  900. CheckSpace
  901. VerbosePkgLists
  902. These are flags to switch on.
  903. """
  904. name = 'PacmanConf'
  905. url = 'https://www.archlinux.org/pacman/pacman.conf.5.html'
  906. aliases = ['pacmanconf']
  907. filenames = ['pacman.conf']
  908. mimetypes = []
  909. version_added = '2.1'
  910. tokens = {
  911. 'root': [
  912. # comment
  913. (r'#.*$', Comment.Single),
  914. # section header
  915. (r'^(\s*)(\[.*?\])(\s*)$', bygroups(Whitespace, Keyword, Whitespace)),
  916. # variable definitions
  917. # (Leading space is allowed...)
  918. (r'(\w+)(\s*)(=)',
  919. bygroups(Name.Attribute, Whitespace, Operator)),
  920. # flags to on
  921. (r'^(\s*)(\w+)(\s*)$',
  922. bygroups(Whitespace, Name.Attribute, Whitespace)),
  923. # built-in special values
  924. (words((
  925. '$repo', # repository
  926. '$arch', # architecture
  927. '%o', # outfile
  928. '%u', # url
  929. ), suffix=r'\b'),
  930. Name.Variable),
  931. # fallback
  932. (r'\s+', Whitespace),
  933. (r'.', Text),
  934. ],
  935. }
  936. class AugeasLexer(RegexLexer):
  937. """
  938. Lexer for Augeas.
  939. """
  940. name = 'Augeas'
  941. url = 'http://augeas.net'
  942. aliases = ['augeas']
  943. filenames = ['*.aug']
  944. version_added = '2.4'
  945. tokens = {
  946. 'root': [
  947. (r'(module)(\s*)([^\s=]+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)),
  948. (r'(let)(\s*)([^\s=]+)', bygroups(Keyword.Declaration, Whitespace, Name.Variable)),
  949. (r'(del|store|value|counter|seq|key|label|autoload|incl|excl|transform|test|get|put)(\s+)', bygroups(Name.Builtin, Whitespace)),
  950. (r'(\()([^:]+)(\:)(unit|string|regexp|lens|tree|filter)(\))', bygroups(Punctuation, Name.Variable, Punctuation, Keyword.Type, Punctuation)),
  951. (r'\(\*', Comment.Multiline, 'comment'),
  952. (r'[*+\-.;=?|]', Operator),
  953. (r'[()\[\]{}]', Operator),
  954. (r'"', String.Double, 'string'),
  955. (r'\/', String.Regex, 'regex'),
  956. (r'([A-Z]\w*)(\.)(\w+)', bygroups(Name.Namespace, Punctuation, Name.Variable)),
  957. (r'.', Name.Variable),
  958. (r'\s+', Whitespace),
  959. ],
  960. 'string': [
  961. (r'\\.', String.Escape),
  962. (r'[^"]', String.Double),
  963. (r'"', String.Double, '#pop'),
  964. ],
  965. 'regex': [
  966. (r'\\.', String.Escape),
  967. (r'[^/]', String.Regex),
  968. (r'\/', String.Regex, '#pop'),
  969. ],
  970. 'comment': [
  971. (r'[^*)]', Comment.Multiline),
  972. (r'\(\*', Comment.Multiline, '#push'),
  973. (r'\*\)', Comment.Multiline, '#pop'),
  974. (r'[)*]', Comment.Multiline)
  975. ],
  976. }
  977. class TOMLLexer(RegexLexer):
  978. """
  979. Lexer for TOML, a simple language for config files.
  980. """
  981. name = 'TOML'
  982. aliases = ['toml']
  983. filenames = ['*.toml', 'Pipfile', 'poetry.lock']
  984. mimetypes = ['application/toml']
  985. url = 'https://toml.io'
  986. version_added = '2.4'
  987. # Based on the TOML spec: https://toml.io/en/v1.0.0
  988. # The following is adapted from CPython's tomllib:
  989. _time = r"\d\d:\d\d:\d\d(\.\d+)?"
  990. _datetime = rf"""(?x)
  991. \d\d\d\d-\d\d-\d\d # date, e.g., 1988-10-27
  992. (
  993. [Tt ] {_time} # optional time
  994. (
  995. [Zz]|[+-]\d\d:\d\d # optional time offset
  996. )?
  997. )?
  998. """
  999. tokens = {
  1000. 'root': [
  1001. # Note that we make an effort in order to distinguish
  1002. # moments at which we're parsing a key and moments at
  1003. # which we're parsing a value. In the TOML code
  1004. #
  1005. # 1234 = 1234
  1006. #
  1007. # the first "1234" should be Name, the second Integer.
  1008. # Whitespace
  1009. (r'\s+', Whitespace),
  1010. # Comment
  1011. (r'#.*', Comment.Single),
  1012. # Assignment keys
  1013. include('key'),
  1014. # After "=", find a value
  1015. (r'(=)(\s*)', bygroups(Operator, Whitespace), 'value'),
  1016. # Table header
  1017. (r'\[\[?', Keyword, 'table-key'),
  1018. ],
  1019. 'key': [
  1020. # Start of bare key (only ASCII is allowed here).
  1021. (r'[A-Za-z0-9_-]+', Name),
  1022. # Quoted key
  1023. (r'"', String.Double, 'basic-string'),
  1024. (r"'", String.Single, 'literal-string'),
  1025. # Dots act as separators in keys
  1026. (r'\.', Punctuation),
  1027. ],
  1028. 'table-key': [
  1029. # This is like 'key', but highlights the name components
  1030. # and separating dots as Keyword because it looks better
  1031. # when the whole table header is Keyword. We do highlight
  1032. # strings as strings though.
  1033. # Start of bare key (only ASCII is allowed here).
  1034. (r'[A-Za-z0-9_-]+', Keyword),
  1035. (r'"', String.Double, 'basic-string'),
  1036. (r"'", String.Single, 'literal-string'),
  1037. (r'\.', Keyword),
  1038. (r'\]\]?', Keyword, '#pop'),
  1039. # Inline whitespace allowed
  1040. (r'[ \t]+', Whitespace),
  1041. ],
  1042. 'value': [
  1043. # Datetime, baretime
  1044. (_datetime, Literal.Date, '#pop'),
  1045. (_time, Literal.Date, '#pop'),
  1046. # Recognize as float if there is a fractional part
  1047. # and/or an exponent.
  1048. (r'[+-]?\d[0-9_]*[eE][+-]?\d[0-9_]*', Number.Float, '#pop'),
  1049. (r'[+-]?\d[0-9_]*\.\d[0-9_]*([eE][+-]?\d[0-9_]*)?',
  1050. Number.Float, '#pop'),
  1051. # Infinities and NaN
  1052. (r'[+-]?(inf|nan)', Number.Float, '#pop'),
  1053. # Integers
  1054. (r'-?0b[01_]+', Number.Bin, '#pop'),
  1055. (r'-?0o[0-7_]+', Number.Oct, '#pop'),
  1056. (r'-?0x[0-9a-fA-F_]+', Number.Hex, '#pop'),
  1057. (r'[+-]?[0-9_]+', Number.Integer, '#pop'),
  1058. # Strings
  1059. (r'"""', String.Double, ('#pop', 'multiline-basic-string')),
  1060. (r'"', String.Double, ('#pop', 'basic-string')),
  1061. (r"'''", String.Single, ('#pop', 'multiline-literal-string')),
  1062. (r"'", String.Single, ('#pop', 'literal-string')),
  1063. # Booleans
  1064. (r'true|false', Keyword.Constant, '#pop'),
  1065. # Start of array
  1066. (r'\[', Punctuation, ('#pop', 'array')),
  1067. # Start of inline table
  1068. (r'\{', Punctuation, ('#pop', 'inline-table')),
  1069. ],
  1070. 'array': [
  1071. # Whitespace, including newlines, is ignored inside arrays,
  1072. # and comments are allowed.
  1073. (r'\s+', Whitespace),
  1074. (r'#.*', Comment.Single),
  1075. # Delimiters
  1076. (r',', Punctuation),
  1077. # End of array
  1078. (r'\]', Punctuation, '#pop'),
  1079. # Parse a value and come back
  1080. default('value'),
  1081. ],
  1082. 'inline-table': [
  1083. # Note that unlike inline arrays, inline tables do not
  1084. # allow newlines or comments.
  1085. (r'[ \t]+', Whitespace),
  1086. # Keys
  1087. include('key'),
  1088. # Values
  1089. (r'(=)(\s*)', bygroups(Punctuation, Whitespace), 'value'),
  1090. # Delimiters
  1091. (r',', Punctuation),
  1092. # End of inline table
  1093. (r'\}', Punctuation, '#pop'),
  1094. ],
  1095. 'basic-string': [
  1096. (r'"', String.Double, '#pop'),
  1097. include('escapes'),
  1098. (r'[^"\\]+', String.Double),
  1099. ],
  1100. 'literal-string': [
  1101. (r".*?'", String.Single, '#pop'),
  1102. ],
  1103. 'multiline-basic-string': [
  1104. (r'"""', String.Double, '#pop'),
  1105. (r'(\\)(\n)', bygroups(String.Escape, Whitespace)),
  1106. include('escapes'),
  1107. (r'[^"\\]+', String.Double),
  1108. (r'"', String.Double),
  1109. ],
  1110. 'multiline-literal-string': [
  1111. (r"'''", String.Single, '#pop'),
  1112. (r"[^']+", String.Single),
  1113. (r"'", String.Single),
  1114. ],
  1115. 'escapes': [
  1116. (r'\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}', String.Escape),
  1117. (r'\\.', String.Escape),
  1118. ],
  1119. }
  1120. class NestedTextLexer(RegexLexer):
  1121. """
  1122. Lexer for *NextedText*, a human-friendly data format.
  1123. .. versionchanged:: 2.16
  1124. Added support for *NextedText* v3.0.
  1125. """
  1126. name = 'NestedText'
  1127. url = 'https://nestedtext.org'
  1128. aliases = ['nestedtext', 'nt']
  1129. filenames = ['*.nt']
  1130. version_added = '2.9'
  1131. tokens = {
  1132. 'root': [
  1133. # Comment: # ...
  1134. (r'^([ ]*)(#.*)$', bygroups(Whitespace, Comment)),
  1135. # Inline dictionary: {...}
  1136. (r'^([ ]*)(\{)', bygroups(Whitespace, Punctuation), 'inline_dict'),
  1137. # Inline list: [...]
  1138. (r'^([ ]*)(\[)', bygroups(Whitespace, Punctuation), 'inline_list'),
  1139. # empty multiline string item: >
  1140. (r'^([ ]*)(>)$', bygroups(Whitespace, Punctuation)),
  1141. # multiline string item: > ...
  1142. (r'^([ ]*)(>)( )(.*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Text, Whitespace)),
  1143. # empty list item: -
  1144. (r'^([ ]*)(-)$', bygroups(Whitespace, Punctuation)),
  1145. # list item: - ...
  1146. (r'^([ ]*)(-)( )(.*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Text, Whitespace)),
  1147. # empty multiline key item: :
  1148. (r'^([ ]*)(:)$', bygroups(Whitespace, Punctuation)),
  1149. # multiline key item: : ...
  1150. (r'^([ ]*)(:)( )([^\n]*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Name.Tag, Whitespace)),
  1151. # empty dict key item: ...:
  1152. (r'^([ ]*)([^\{\[\s].*?)(:)$', bygroups(Whitespace, Name.Tag, Punctuation)),
  1153. # dict key item: ...: ...
  1154. (r'^([ ]*)([^\{\[\s].*?)(:)( )(.*?)([ \t]*)$', bygroups(Whitespace, Name.Tag, Punctuation, Whitespace, Text, Whitespace)),
  1155. ],
  1156. 'inline_list': [
  1157. include('whitespace'),
  1158. (r'[^\{\}\[\],\s]+', Text),
  1159. include('inline_value'),
  1160. (r',', Punctuation),
  1161. (r'\]', Punctuation, '#pop'),
  1162. (r'\n', Error, '#pop'),
  1163. ],
  1164. 'inline_dict': [
  1165. include('whitespace'),
  1166. (r'[^\{\}\[\],:\s]+', Name.Tag),
  1167. (r':', Punctuation, 'inline_dict_value'),
  1168. (r'\}', Punctuation, '#pop'),
  1169. (r'\n', Error, '#pop'),
  1170. ],
  1171. 'inline_dict_value': [
  1172. include('whitespace'),
  1173. (r'[^\{\}\[\],:\s]+', Text),
  1174. include('inline_value'),
  1175. (r',', Punctuation, '#pop'),
  1176. (r'\}', Punctuation, '#pop:2'),
  1177. ],
  1178. 'inline_value': [
  1179. include('whitespace'),
  1180. (r'\{', Punctuation, 'inline_dict'),
  1181. (r'\[', Punctuation, 'inline_list'),
  1182. ],
  1183. 'whitespace': [
  1184. (r'[ \t]+', Whitespace),
  1185. ],
  1186. }
  1187. class SingularityLexer(RegexLexer):
  1188. """
  1189. Lexer for Singularity definition files.
  1190. """
  1191. name = 'Singularity'
  1192. url = 'https://www.sylabs.io/guides/3.0/user-guide/definition_files.html'
  1193. aliases = ['singularity']
  1194. filenames = ['*.def', 'Singularity']
  1195. version_added = '2.6'
  1196. flags = re.IGNORECASE | re.MULTILINE | re.DOTALL
  1197. _headers = r'^(\s*)(bootstrap|from|osversion|mirrorurl|include|registry|namespace|includecmd)(:)'
  1198. _section = r'^(%(?:pre|post|setup|environment|help|labels|test|runscript|files|startscript))(\s*)'
  1199. _appsect = r'^(%app(?:install|help|run|labels|env|test|files))(\s*)'
  1200. tokens = {
  1201. 'root': [
  1202. (_section, bygroups(Generic.Heading, Whitespace), 'script'),
  1203. (_appsect, bygroups(Generic.Heading, Whitespace), 'script'),
  1204. (_headers, bygroups(Whitespace, Keyword, Text)),
  1205. (r'\s*#.*?\n', Comment),
  1206. (r'\b(([0-9]+\.?[0-9]*)|(\.[0-9]+))\b', Number),
  1207. (r'[ \t]+', Whitespace),
  1208. (r'(?!^\s*%).', Text),
  1209. ],
  1210. 'script': [
  1211. (r'(.+?(?=^\s*%))|(.*)', using(BashLexer), '#pop'),
  1212. ],
  1213. }
  1214. def analyse_text(text):
  1215. """This is a quite simple script file, but there are a few keywords
  1216. which seem unique to this language."""
  1217. result = 0
  1218. if re.search(r'\b(?:osversion|includecmd|mirrorurl)\b', text, re.IGNORECASE):
  1219. result += 0.5
  1220. if re.search(SingularityLexer._section[1:], text):
  1221. result += 0.49
  1222. return result
  1223. class UnixConfigLexer(RegexLexer):
  1224. """
  1225. Lexer for Unix/Linux config files using colon-separated values, e.g.
  1226. * ``/etc/group``
  1227. * ``/etc/passwd``
  1228. * ``/etc/shadow``
  1229. """
  1230. name = 'Unix/Linux config files'
  1231. aliases = ['unixconfig', 'linuxconfig']
  1232. filenames = []
  1233. url = 'https://en.wikipedia.org/wiki/Configuration_file#Unix_and_Unix-like_operating_systems'
  1234. version_added = '2.12'
  1235. tokens = {
  1236. 'root': [
  1237. (r'^#.*', Comment),
  1238. (r'\n', Whitespace),
  1239. (r':', Punctuation),
  1240. (r'[0-9]+', Number),
  1241. (r'((?!\n)[a-zA-Z0-9\_\-\s\(\),]){2,}', Text),
  1242. (r'[^:\n]+', String),
  1243. ],
  1244. }