markup.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  1. """
  2. pygments.lexers.markup
  3. ~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for non-HTML markup 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.lexers.html import XmlLexer
  10. from pygments.lexers.javascript import JavascriptLexer
  11. from pygments.lexers.css import CssLexer
  12. from pygments.lexers.lilypond import LilyPondLexer
  13. from pygments.lexers.data import JsonLexer
  14. from pygments.lexer import RegexLexer, DelegatingLexer, include, bygroups, \
  15. using, this, do_insertions, default, words
  16. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  17. Number, Punctuation, Generic, Other, Whitespace, Literal
  18. from pygments.util import get_bool_opt, ClassNotFound
  19. __all__ = ['BBCodeLexer', 'MoinWikiLexer', 'RstLexer', 'TexLexer', 'GroffLexer',
  20. 'MozPreprocHashLexer', 'MozPreprocPercentLexer',
  21. 'MozPreprocXulLexer', 'MozPreprocJavascriptLexer',
  22. 'MozPreprocCssLexer', 'MarkdownLexer', 'OrgLexer', 'TiddlyWiki5Lexer',
  23. 'WikitextLexer']
  24. def _shift_indices(tokens, offset):
  25. """Re-base token indices yielded by a delegated sub-lexer.
  26. A sub-lexer's ``get_tokens_unprocessed`` returns indices relative to the
  27. snippet it was given (starting at 0), but the surrounding lexer must yield
  28. indices that are absolute within the whole input text.
  29. """
  30. for index, token, value in tokens:
  31. yield index + offset, token, value
  32. class BBCodeLexer(RegexLexer):
  33. """
  34. A lexer that highlights BBCode(-like) syntax.
  35. """
  36. name = 'BBCode'
  37. aliases = ['bbcode']
  38. mimetypes = ['text/x-bbcode']
  39. url = 'https://www.bbcode.org/'
  40. version_added = '0.6'
  41. tokens = {
  42. 'root': [
  43. (r'[^[]+', Text),
  44. # tag/end tag begin
  45. (r'\[/?\w+', Keyword, 'tag'),
  46. # stray bracket
  47. (r'\[', Text),
  48. ],
  49. 'tag': [
  50. (r'\s+', Text),
  51. # attribute with value
  52. (r'(\w+)(=)("?[^\s"\]]+"?)',
  53. bygroups(Name.Attribute, Operator, String)),
  54. # tag argument (a la [color=green])
  55. (r'(=)("?[^\s"\]]+"?)',
  56. bygroups(Operator, String)),
  57. # tag end
  58. (r'\]', Keyword, '#pop'),
  59. ],
  60. }
  61. class MoinWikiLexer(RegexLexer):
  62. """
  63. For MoinMoin (and Trac) Wiki markup.
  64. """
  65. name = 'MoinMoin/Trac Wiki markup'
  66. aliases = ['trac-wiki', 'moin']
  67. filenames = []
  68. mimetypes = ['text/x-trac-wiki']
  69. url = 'https://moinmo.in'
  70. version_added = '0.7'
  71. flags = re.MULTILINE | re.IGNORECASE
  72. tokens = {
  73. 'root': [
  74. (r'^#.*$', Comment),
  75. (r'(!)(\S+)', bygroups(Keyword, Text)), # Ignore-next
  76. # Titles
  77. (r'^(=+)([^=]+)(=+)(\s*#.+)?$',
  78. bygroups(Generic.Heading, using(this), Generic.Heading, String)),
  79. # Literal code blocks, with optional shebang
  80. (r'(\{\{\{)(\n#!.+)?', bygroups(Name.Builtin, Name.Namespace), 'codeblock'),
  81. (r'(\'\'\'?|\|\||`|__|~~|\^|,,|::)', Comment), # Formatting
  82. # Lists
  83. (r'^( +)([.*-])( )', bygroups(Text, Name.Builtin, Text)),
  84. (r'^( +)([a-z]{1,5}\.)( )', bygroups(Text, Name.Builtin, Text)),
  85. # Other Formatting
  86. (r'\[\[\w+.*?\]\]', Keyword), # Macro
  87. (r'(\[[^\s\]]+)(\s+[^\]]+?)?(\])',
  88. bygroups(Keyword, String, Keyword)), # Link
  89. (r'^----+$', Keyword), # Horizontal rules
  90. (r'[^\n\'\[{!_~^,|]+', Text),
  91. (r'\n', Text),
  92. (r'.', Text),
  93. ],
  94. 'codeblock': [
  95. (r'\}\}\}', Name.Builtin, '#pop'),
  96. # these blocks are allowed to be nested in Trac, but not MoinMoin
  97. (r'\{\{\{', Text, '#push'),
  98. (r'[^{}]+', Comment.Preproc), # slurp boring text
  99. (r'.', Comment.Preproc), # allow loose { or }
  100. ],
  101. }
  102. class RstLexer(RegexLexer):
  103. """
  104. For reStructuredText markup.
  105. Additional options accepted:
  106. `handlecodeblocks`
  107. Highlight the contents of ``.. sourcecode:: language``,
  108. ``.. code:: language`` and ``.. code-block:: language``
  109. directives with a lexer for the given language (default:
  110. ``True``).
  111. .. versionadded:: 0.8
  112. """
  113. name = 'reStructuredText'
  114. url = 'https://docutils.sourceforge.io/rst.html'
  115. aliases = ['restructuredtext', 'rst', 'rest']
  116. filenames = ['*.rst', '*.rest']
  117. mimetypes = ["text/x-rst", "text/prs.fallenstein.rst"]
  118. version_added = '0.7'
  119. flags = re.MULTILINE
  120. def _handle_sourcecode(self, match):
  121. from pygments.lexers import get_lexer_by_name
  122. # section header
  123. yield match.start(1), Punctuation, match.group(1)
  124. yield match.start(2), Text, match.group(2)
  125. yield match.start(3), Operator.Word, match.group(3)
  126. yield match.start(4), Punctuation, match.group(4)
  127. yield match.start(5), Text, match.group(5)
  128. yield match.start(6), Keyword, match.group(6)
  129. yield match.start(7), Text, match.group(7)
  130. # lookup lexer if wanted and existing
  131. lexer = None
  132. if self.handlecodeblocks:
  133. try:
  134. lexer = get_lexer_by_name(match.group(6).strip())
  135. except ClassNotFound:
  136. pass
  137. indention = match.group(8)
  138. indention_size = len(indention)
  139. code = (indention + match.group(9) + match.group(10) + match.group(11))
  140. # no lexer for this language. handle it like it was a code block
  141. if lexer is None:
  142. yield match.start(8), String, code
  143. return
  144. # highlight the lines with the lexer.
  145. ins = []
  146. codelines = code.splitlines(True)
  147. code = ''
  148. for line in codelines:
  149. if len(line) > indention_size:
  150. ins.append((len(code), [(0, Text, line[:indention_size])]))
  151. code += line[indention_size:]
  152. else:
  153. code += line
  154. yield from _shift_indices(
  155. do_insertions(ins, lexer.get_tokens_unprocessed(code)),
  156. match.start(8))
  157. # from docutils.parsers.rst.states
  158. closers = '\'")]}>\u2019\u201d\xbb!?'
  159. unicode_delimiters = '\u2010\u2011\u2012\u2013\u2014\u00a0'
  160. end_string_suffix = (rf'($|(?=[-/:.,; \n\x00{re.escape(unicode_delimiters)}{re.escape(closers)}]))')
  161. tokens = {
  162. 'root': [
  163. # Heading with overline
  164. (r'^(=+|-+|`+|:+|\.+|\'+|"+|~+|\^+|_+|\*+|\++|#+)([ \t]*\n)'
  165. r'(.+)(\n)(\1)(\n)',
  166. bygroups(Generic.Heading, Text, Generic.Heading,
  167. Text, Generic.Heading, Text)),
  168. # Plain heading
  169. (r'^(\S.*)(\n)(={3,}|-{3,}|`{3,}|:{3,}|\.{3,}|\'{3,}|"{3,}|'
  170. r'~{3,}|\^{3,}|_{3,}|\*{3,}|\+{3,}|#{3,})(\n)',
  171. bygroups(Generic.Heading, Text, Generic.Heading, Text)),
  172. # Bulleted lists
  173. (r'^(\s*)([-*+])( .+\n(?:\1 .+\n)*)',
  174. bygroups(Text, Number, using(this, state='inline'))),
  175. # Numbered lists
  176. (r'^(\s*)([0-9#ivxlcmIVXLCM]+\.)( .+\n(?:\1 .+\n)*)',
  177. bygroups(Text, Number, using(this, state='inline'))),
  178. (r'^(\s*)(\(?[0-9#ivxlcmIVXLCM]+\))( .+\n(?:\1 .+\n)*)',
  179. bygroups(Text, Number, using(this, state='inline'))),
  180. # Numbered, but keep words at BOL from becoming lists
  181. (r'^(\s*)([A-Z]+\.)( .+\n(?:\1 .+\n)+)',
  182. bygroups(Text, Number, using(this, state='inline'))),
  183. (r'^(\s*)(\(?[A-Za-z]+\))( .+\n(?:\1 .+\n)+)',
  184. bygroups(Text, Number, using(this, state='inline'))),
  185. # Line blocks
  186. (r'^(\s*)(\|)( .+\n(?:\| .+\n)*)',
  187. bygroups(Text, Operator, using(this, state='inline'))),
  188. # Sourcecode directives
  189. (r'^( *\.\.)(\s*)((?:source)?code(?:-block)?)(::)([ \t]*)([^\n]+)'
  190. r'(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\8.*)?\n)+)',
  191. _handle_sourcecode),
  192. # A directive
  193. (r'^( *\.\.)(\s*)([\w:.+-]+?)(::)(?:([ \t]*)(.*))',
  194. bygroups(Punctuation, Text, Operator.Word, Punctuation, Text,
  195. using(this, state='inline'))),
  196. # A reference target
  197. (r'^( *\.\.)(\s*)(_(?:[^:\\]|\\.)+:)(.*?)$',
  198. bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))),
  199. # A footnote/citation target
  200. (r'^( *\.\.)(\s*)(\[.+\])(.*?)$',
  201. bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))),
  202. # A substitution def
  203. (r'^( *\.\.)(\s*)(\|.+\|)(\s*)([\w:-]+?)(::)(?:([ \t]*)(.*))',
  204. bygroups(Punctuation, Text, Name.Tag, Text, Operator.Word,
  205. Punctuation, Text, using(this, state='inline'))),
  206. # Comments
  207. (r'^ *\.\..*(\n( +.*\n|\n)+)?', Comment),
  208. # Field list marker
  209. (r'^( *)(:(?:\\\\|\\:|[^:\n])+:(?=\s))([ \t]*)',
  210. bygroups(Text, Name.Class, Text)),
  211. # Definition list
  212. (r'^(\S.*(?<!::)\n)((?:(?: +.*)\n)+)',
  213. bygroups(using(this, state='inline'), using(this, state='inline'))),
  214. # Code blocks
  215. (r'(::)(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\3.*)?\n)+)',
  216. bygroups(String.Escape, Text, String, String, Text, String)),
  217. include('inline'),
  218. ],
  219. 'inline': [
  220. (r'\\.', Text), # escape
  221. (r'``', String, 'literal'), # code
  222. (r'(`.+?)(<.+?>)(`__?)', # reference with inline target
  223. bygroups(String, String.Interpol, String)),
  224. (r'`.+?`__?', String), # reference
  225. (r'(`.+?`)(:[a-zA-Z0-9:.+-]+?:)?',
  226. bygroups(Name.Variable, Name.Attribute)), # role
  227. (r'(:[a-zA-Z0-9:.+-]+?:)(`.+?`)',
  228. bygroups(Name.Attribute, Name.Variable)), # role (content first)
  229. (r'\*\*.+?\*\*', Generic.Strong), # Strong emphasis
  230. (r'\*.+?\*', Generic.Emph), # Emphasis
  231. (r'\[.*?\]_', String), # Footnote or citation
  232. (r'<.+?>', Name.Tag), # Hyperlink
  233. (r'[^\\\n\[*`:]+', Text),
  234. (r'.', Text),
  235. ],
  236. 'literal': [
  237. (r'[^`]+', String),
  238. (r'``' + end_string_suffix, String, '#pop'),
  239. (r'`', String),
  240. ]
  241. }
  242. def __init__(self, **options):
  243. self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True)
  244. RegexLexer.__init__(self, **options)
  245. def analyse_text(text):
  246. if text[:2] == '..' and text[2:3] != '.':
  247. return 0.3
  248. p1 = text.find("\n")
  249. p2 = text.find("\n", p1 + 1)
  250. if (p2 > -1 and # has two lines
  251. p1 * 2 + 1 == p2 and # they are the same length
  252. text[p1+1] in '-=' and # the next line both starts and ends with
  253. text[p1+1] == text[p2-1]): # ...a sufficiently high header
  254. return 0.5
  255. class TexLexer(RegexLexer):
  256. """
  257. Lexer for the TeX and LaTeX typesetting languages.
  258. """
  259. name = 'TeX'
  260. aliases = ['tex', 'latex']
  261. filenames = ['*.tex', '*.aux', '*.toc']
  262. mimetypes = ['text/x-tex', 'text/x-latex']
  263. url = 'https://tug.org'
  264. version_added = ''
  265. tokens = {
  266. 'general': [
  267. (r'%.*?\n', Comment),
  268. (r'[{}]', Name.Builtin),
  269. (r'[&_^]', Name.Builtin),
  270. ],
  271. 'root': [
  272. (r'(\\begin)(\{)((?:display)?math|equation\*?|align\*?)(\})',
  273. bygroups(Keyword, Name.Builtin, Name.Builtin, Name.Builtin),
  274. 'environmentmath'),
  275. (r'\\\[', String.Backtick, 'displaymath'),
  276. (r'\\\(', String, 'inlinemath'),
  277. (r'\$\$', String.Backtick, 'displaymath'),
  278. (r'\$', String, 'inlinemath'),
  279. (r'\\([a-zA-Z@_:]+|\S?)', Keyword, 'command'),
  280. (r'\\$', Keyword),
  281. include('general'),
  282. (r'[^\\$%&_^{}]+', Text),
  283. ],
  284. 'math': [
  285. (r'\\([a-zA-Z]+|\S?)', Name.Variable),
  286. include('general'),
  287. (r'[0-9]+', Number),
  288. (r'[-=!+*/()\[\]]', Operator),
  289. (r'[^=!+*/()\[\]\\$%&_^{}0-9-]+', Name.Builtin),
  290. ],
  291. 'inlinemath': [
  292. (r'\\\)', String, '#pop'),
  293. (r'\$', String, '#pop'),
  294. include('math'),
  295. ],
  296. 'displaymath': [
  297. (r'\\\]', String, '#pop'),
  298. (r'\$\$', String, '#pop'),
  299. (r'\$', Name.Builtin),
  300. include('math'),
  301. ],
  302. 'environmentmath': [
  303. (r'(\\end)(\{)((?:display)?math|equation\*?|align\*?)(\})',
  304. bygroups(Keyword, Name.Builtin, Name.Builtin, Name.Builtin), '#pop'),
  305. include('math'),
  306. ],
  307. 'command': [
  308. (r'\[.*?\]', Name.Attribute),
  309. (r'\*', Keyword),
  310. default('#pop'),
  311. ],
  312. }
  313. def analyse_text(text):
  314. for start in ("\\documentclass", "\\input", "\\documentstyle",
  315. "\\relax"):
  316. if text[:len(start)] == start:
  317. return True
  318. class GroffLexer(RegexLexer):
  319. """
  320. Lexer for the (g)roff typesetting language, supporting groff
  321. extensions. Mainly useful for highlighting manpage sources.
  322. """
  323. name = 'Groff'
  324. aliases = ['groff', 'nroff', 'man']
  325. filenames = ['*.[1-9]', '*.man', '*.1p', '*.3pm']
  326. mimetypes = ['application/x-troff', 'text/troff']
  327. url = 'https://www.gnu.org/software/groff'
  328. version_added = '0.6'
  329. tokens = {
  330. 'root': [
  331. (r'(\.)(\w+)', bygroups(Text, Keyword), 'request'),
  332. (r'\.', Punctuation, 'request'),
  333. # Regular characters, slurp till we find a backslash or newline
  334. (r'[^\\\n]+', Text, 'textline'),
  335. default('textline'),
  336. ],
  337. 'textline': [
  338. include('escapes'),
  339. (r'[^\\\n]+', Text),
  340. (r'\n', Text, '#pop'),
  341. ],
  342. 'escapes': [
  343. # groff has many ways to write escapes.
  344. (r'\\"[^\n]*', Comment),
  345. (r'\\[fn]\w', String.Escape),
  346. (r'\\\(.{2}', String.Escape),
  347. (r'\\.\[.*\]', String.Escape),
  348. (r'\\.', String.Escape),
  349. (r'\\\n', Text, 'request'),
  350. ],
  351. 'request': [
  352. (r'\n', Text, '#pop'),
  353. include('escapes'),
  354. (r'"[^\n"]+"', String.Double),
  355. (r'\d+', Number),
  356. (r'\S+', String),
  357. (r'\s+', Text),
  358. ],
  359. }
  360. def analyse_text(text):
  361. if text[:1] != '.':
  362. return False
  363. if text[:3] == '.\\"':
  364. return True
  365. if text[:4] == '.TH ':
  366. return True
  367. if text[1:3].isalnum() and text[3].isspace():
  368. return 0.9
  369. class MozPreprocHashLexer(RegexLexer):
  370. """
  371. Lexer for Mozilla Preprocessor files (with '#' as the marker).
  372. Other data is left untouched.
  373. """
  374. name = 'mozhashpreproc'
  375. aliases = [name]
  376. filenames = []
  377. mimetypes = []
  378. url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html'
  379. version_added = '2.0'
  380. tokens = {
  381. 'root': [
  382. (r'^#', Comment.Preproc, ('expr', 'exprstart')),
  383. (r'.+', Other),
  384. ],
  385. 'exprstart': [
  386. (r'(literal)(.*)', bygroups(Comment.Preproc, Text), '#pop:2'),
  387. (words((
  388. 'define', 'undef', 'if', 'ifdef', 'ifndef', 'else', 'elif',
  389. 'elifdef', 'elifndef', 'endif', 'expand', 'filter', 'unfilter',
  390. 'include', 'includesubst', 'error')),
  391. Comment.Preproc, '#pop'),
  392. ],
  393. 'expr': [
  394. (words(('!', '!=', '==', '&&', '||')), Operator),
  395. (r'(defined)(\()', bygroups(Keyword, Punctuation)),
  396. (r'\)', Punctuation),
  397. (r'[0-9]+', Number.Decimal),
  398. (r'__\w+?__', Name.Variable),
  399. (r'@\w+?@', Name.Class),
  400. (r'\w+', Name),
  401. (r'\n', Text, '#pop'),
  402. (r'\s+', Text),
  403. (r'\S', Punctuation),
  404. ],
  405. }
  406. class MozPreprocPercentLexer(MozPreprocHashLexer):
  407. """
  408. Lexer for Mozilla Preprocessor files (with '%' as the marker).
  409. Other data is left untouched.
  410. """
  411. name = 'mozpercentpreproc'
  412. aliases = [name]
  413. filenames = []
  414. mimetypes = []
  415. url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html'
  416. version_added = '2.0'
  417. tokens = {
  418. 'root': [
  419. (r'^%', Comment.Preproc, ('expr', 'exprstart')),
  420. (r'.+', Other),
  421. ],
  422. }
  423. class MozPreprocXulLexer(DelegatingLexer):
  424. """
  425. Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the
  426. `XmlLexer`.
  427. """
  428. name = "XUL+mozpreproc"
  429. aliases = ['xul+mozpreproc']
  430. filenames = ['*.xul.in']
  431. mimetypes = []
  432. url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html'
  433. version_added = '2.0'
  434. def __init__(self, **options):
  435. super().__init__(XmlLexer, MozPreprocHashLexer, **options)
  436. class MozPreprocJavascriptLexer(DelegatingLexer):
  437. """
  438. Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the
  439. `JavascriptLexer`.
  440. """
  441. name = "Javascript+mozpreproc"
  442. aliases = ['javascript+mozpreproc']
  443. filenames = ['*.js.in']
  444. mimetypes = []
  445. url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html'
  446. version_added = '2.0'
  447. def __init__(self, **options):
  448. super().__init__(JavascriptLexer, MozPreprocHashLexer, **options)
  449. class MozPreprocCssLexer(DelegatingLexer):
  450. """
  451. Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the
  452. `CssLexer`.
  453. """
  454. name = "CSS+mozpreproc"
  455. aliases = ['css+mozpreproc']
  456. filenames = ['*.css.in']
  457. mimetypes = []
  458. url = 'https://firefox-source-docs.mozilla.org/build/buildsystem/preprocessor.html'
  459. version_added = '2.0'
  460. def __init__(self, **options):
  461. super().__init__(CssLexer, MozPreprocPercentLexer, **options)
  462. class MarkdownLexer(RegexLexer):
  463. """
  464. For Markdown markup.
  465. """
  466. name = 'Markdown'
  467. url = 'https://daringfireball.net/projects/markdown/'
  468. aliases = ['markdown', 'md']
  469. filenames = ['*.md', '*.markdown']
  470. mimetypes = ["text/x-markdown"]
  471. version_added = '2.2'
  472. flags = re.MULTILINE
  473. def _handle_codeblock(self, match):
  474. from pygments.lexers import get_lexer_by_name
  475. yield match.start('initial'), String.Backtick, match.group('initial')
  476. yield match.start('lang'), String.Backtick, match.group('lang')
  477. if match.group('afterlang') is not None:
  478. yield match.start('whitespace'), Whitespace, match.group('whitespace')
  479. yield match.start('extra'), Text, match.group('extra')
  480. yield match.start('newline'), Whitespace, match.group('newline')
  481. # lookup lexer if wanted and existing
  482. lexer = None
  483. if self.handlecodeblocks:
  484. try:
  485. lexer = get_lexer_by_name(match.group('lang').strip())
  486. except ClassNotFound:
  487. pass
  488. code = match.group('code')
  489. # no lexer for this language. handle it like it was a code block
  490. if lexer is None:
  491. yield match.start('code'), String, code
  492. else:
  493. yield from _shift_indices(
  494. do_insertions([], lexer.get_tokens_unprocessed(code)),
  495. match.start('code'))
  496. yield match.start('terminator'), String.Backtick, match.group('terminator')
  497. tokens = {
  498. 'root': [
  499. # heading with '#' prefix (atx-style)
  500. (r'(^#[^#].+)(\n)', bygroups(Generic.Heading, Text)),
  501. # subheading with '#' prefix (atx-style)
  502. (r'(^#{2,6}[^#].+)(\n)', bygroups(Generic.Subheading, Text)),
  503. # heading with '=' underlines (Setext-style)
  504. (r'^(.+)(\n)(=+)(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text)),
  505. # subheading with '-' underlines (Setext-style)
  506. (r'^(.+)(\n)(-+)(\n)', bygroups(Generic.Subheading, Text, Generic.Subheading, Text)),
  507. # task list
  508. (r'^(\s*)([*-] )(\[[ xX]\])( .+\n)',
  509. bygroups(Whitespace, Keyword, Keyword, using(this, state='inline'))),
  510. # bulleted list
  511. (r'^(\s*)([*-])(\s)(.+\n)',
  512. bygroups(Whitespace, Keyword, Whitespace, using(this, state='inline'))),
  513. # numbered list
  514. (r'^(\s*)([0-9]+\.)( .+\n)',
  515. bygroups(Whitespace, Keyword, using(this, state='inline'))),
  516. # quote
  517. (r'^(\s*>\s)(.+\n)', bygroups(Keyword, Generic.Emph)),
  518. # code block fenced by 3 backticks
  519. (r'^(\s*```\n[\w\W]*?^\s*```$\n)', String.Backtick),
  520. # code block with language
  521. # Some tools include extra stuff after the language name, just
  522. # highlight that as text. For example: https://docs.enola.dev/use/execmd
  523. (r'''(?x)
  524. ^(?P<initial>\s*```)
  525. (?P<lang>[\w\-]+)
  526. (?P<afterlang>
  527. (?P<whitespace>[^\S\n]+)
  528. (?P<extra>.*))?
  529. (?P<newline>\n)
  530. (?P<code>([\s\S])*?)
  531. (?P<terminator>^\s*```$\n)
  532. ''',
  533. _handle_codeblock),
  534. include('inline'),
  535. ],
  536. 'inline': [
  537. # escape
  538. (r'\\.', Text),
  539. # inline code
  540. (r'([^`]?)(`[^`\n]+`)', bygroups(Text, String.Backtick)),
  541. # warning: the following rules eat outer tags.
  542. # eg. **foo _bar_ baz** => foo and baz are not recognized as bold
  543. # bold-italics fenced by '***'
  544. (r'([^\*]?)(\*\*\*[^* \n][^*\n]*\*\*\*)', bygroups(Text, Generic.EmphStrong)),
  545. # bold-italics fenced by '___'
  546. (r'([^_]?)(___[^_ \n][^_\n]*___)', bygroups(Text, Generic.EmphStrong)),
  547. # bold fenced by '**'
  548. (r'([^\*]?)(\*\*[^* \n][^*\n]*\*\*)', bygroups(Text, Generic.Strong)),
  549. # bold fenced by '__'
  550. (r'([^_]?)(__[^_ \n][^_\n]*__)', bygroups(Text, Generic.Strong)),
  551. # italics fenced by '*'
  552. (r'([^\*]?)(\*[^* \n][^*\n]*\*)', bygroups(Text, Generic.Emph)),
  553. # italics fenced by '_'
  554. (r'([^_]?)(_[^_ \n][^_\n]*_)', bygroups(Text, Generic.Emph)),
  555. # strikethrough
  556. (r'([^~]?)(~~[^~ \n][^~\n]*~~)', bygroups(Text, Generic.Deleted)),
  557. # mentions and topics (twitter and github stuff)
  558. (r'[@#][\w/:-]+', Name.Entity),
  559. # (image?) links eg: ![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)
  560. (r'(!?\[)([^]]+)(\])(\()([^)]+)(\))',
  561. bygroups(Text, Name.Tag, Text, Text, Name.Attribute, Text)),
  562. # reference-style links, e.g.:
  563. # [an example][id]
  564. # [id]: http://example.com/
  565. (r'(\[)([^]]+)(\])(\[)([^]]*)(\])',
  566. bygroups(Text, Name.Tag, Text, Text, Name.Label, Text)),
  567. (r'^(\s*\[)([^]]*)(\]:\s*)(.+)',
  568. bygroups(Text, Name.Label, Text, Name.Attribute)),
  569. # general text, must come last!
  570. (r'[^\\\s]+', Text),
  571. (r'.', Text),
  572. ],
  573. }
  574. def __init__(self, **options):
  575. self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True)
  576. RegexLexer.__init__(self, **options)
  577. class OrgLexer(RegexLexer):
  578. """
  579. For Org Mode markup.
  580. """
  581. name = 'Org Mode'
  582. url = 'https://orgmode.org'
  583. aliases = ['org', 'orgmode', 'org-mode']
  584. filenames = ['*.org']
  585. mimetypes = ["text/org"]
  586. version_added = '2.18'
  587. def _inline(start, end):
  588. return rf'(?<!\w){start}(.|\n(?!\n))+?{end}(?!\w)'
  589. tokens = {
  590. 'root': [
  591. (r'^# .*', Comment.Single),
  592. # Headings
  593. (r'^(\* )(COMMENT)( .*)',
  594. bygroups(Generic.Heading, Comment.Preproc, Generic.Heading)),
  595. (r'^(\*\*+ )(COMMENT)( .*)',
  596. bygroups(Generic.Subheading, Comment.Preproc, Generic.Subheading)),
  597. (r'^(\* )(DONE)( .*)',
  598. bygroups(Generic.Heading, Generic.Deleted, Generic.Heading)),
  599. (r'^(\*\*+ )(DONE)( .*)',
  600. bygroups(Generic.Subheading, Generic.Deleted, Generic.Subheading)),
  601. (r'^(\* )(TODO)( .*)',
  602. bygroups(Generic.Heading, Generic.Error, Generic.Heading)),
  603. (r'^(\*\*+ )(TODO)( .*)',
  604. bygroups(Generic.Subheading, Generic.Error, Generic.Subheading)),
  605. (r'^(\* .+?)( :[a-zA-Z0-9_@:]+:)?$', bygroups(Generic.Heading, Generic.Emph)),
  606. (r'^(\*\*+ .+?)( :[a-zA-Z0-9_@:]+:)?$', bygroups(Generic.Subheading, Generic.Emph)),
  607. # Unordered lists items, including TODO items and description items
  608. (r'^(?:( *)([+-] )|( +)(\* ))(\[[ X-]\])?(.+ ::)?',
  609. bygroups(Whitespace, Keyword, Whitespace, Keyword, Generic.Prompt, Name.Label)),
  610. # Ordered list items
  611. (r'^( *)([0-9]+[.)])( \[@[0-9]+\])?', bygroups(Whitespace, Keyword, Generic.Emph)),
  612. # Dynamic blocks
  613. (r'(?i)^( *#\+begin: *)([\s\S]*?)(^ *#\+end: *$)',
  614. bygroups(Operator.Word, using(this), Operator.Word)),
  615. # Comment blocks
  616. (r'(?i)^( *#\+begin_comment *\n)([\s\S]*?)(^ *#\+end_comment *$)',
  617. bygroups(Operator.Word, Comment.Multiline, Operator.Word)),
  618. # Source code blocks
  619. # TODO: language-dependent syntax highlighting (see Markdown lexer)
  620. (r'(?i)^( *#\+begin_src .*)([\s\S]*?)(^ *#\+end_src *$)',
  621. bygroups(Operator.Word, Text, Operator.Word)),
  622. # Other blocks
  623. (r'(?i)^( *#\+begin_\w+)( *\n)([\s\S]*?)(^ *#\+end_\w+)( *$)',
  624. bygroups(Operator.Word, Whitespace, Text, Operator.Word, Whitespace)),
  625. # Keywords
  626. (r'^(#\+\w+:)(.*)$', bygroups(Name.Namespace, Text)),
  627. # Properties and drawers
  628. (r'(?i)^( *:\w+: *\n)([\s\S]*?)(^ *:end: *$)',
  629. bygroups(Name.Decorator, Comment.Special, Name.Decorator)),
  630. # Line break operator
  631. (r'\\\\$', Operator),
  632. (r'^\s*CLOSED:\s+', Generic.Deleted, 'dateline'),
  633. (r'^\s*(?:DEADLINE:|SCHEDULED:)\s+', Generic.Error, 'dateline'),
  634. # Bold
  635. (_inline(r'\*', r'\*+'), Generic.Strong),
  636. # Italic
  637. (_inline(r'/', r'/'), Generic.Emph),
  638. # Verbatim
  639. (_inline(r'=', r'='), String), # TODO token
  640. # Code
  641. (_inline(r'~', r'~'), String),
  642. # Strikethrough
  643. (_inline(r'\+', r'\+'), Generic.Deleted),
  644. # Underline
  645. (_inline(r'_', r'_+'), Generic.EmphStrong),
  646. # Dates
  647. (r'<.+?>', Literal.Date),
  648. # Macros
  649. (r'\{\{\{.+?\}\}\}', Comment.Preproc),
  650. # Footnotes
  651. (r'(?<!\[)\[fn:.+?\]', Name.Tag),
  652. # Links
  653. (r'(?s)(\[\[)(.*?)(\]\[)(.*?)(\]\])',
  654. bygroups(Punctuation, Name.Attribute, Punctuation, Name.Tag, Punctuation)),
  655. (r'(?s)(\[\[)(.+?)(\]\])', bygroups(Punctuation, Name.Attribute, Punctuation)),
  656. (r'(<<)(.+?)(>>)', bygroups(Punctuation, Name.Attribute, Punctuation)),
  657. # Tables
  658. (r'^( *)(\|[ -].*?[ -]\|)$', bygroups(Whitespace, String)),
  659. # Any other text
  660. (r'[^#*+\-0-9:\\/=~_<{\[|\n]+', Text),
  661. (r'[#*+\-0-9:\\/=~_<{\[|\n]', Text),
  662. ],
  663. 'dateline': [
  664. (r'\s*CLOSED:\s+', Generic.Deleted),
  665. (r'\s*(?:DEADLINE:|SCHEDULED:)\s+', Generic.Error),
  666. (r'\[.+?\]', Literal.Date),
  667. (r'<[^>]+?>', Literal.Date),
  668. (r'(\s*)$', Text, '#pop'),
  669. (r'.', Text),
  670. ],
  671. }
  672. class TiddlyWiki5Lexer(RegexLexer):
  673. """
  674. For TiddlyWiki5 markup.
  675. """
  676. name = 'tiddler'
  677. url = 'https://tiddlywiki.com/#TiddlerFiles'
  678. aliases = ['tid']
  679. filenames = ['*.tid']
  680. mimetypes = ["text/vnd.tiddlywiki"]
  681. version_added = '2.7'
  682. flags = re.MULTILINE
  683. def _handle_codeblock(self, match):
  684. """
  685. match args: 1:backticks, 2:lang_name, 3:newline, 4:code, 5:backticks
  686. """
  687. from pygments.lexers import get_lexer_by_name
  688. # section header
  689. yield match.start(1), String, match.group(1)
  690. yield match.start(2), String, match.group(2)
  691. yield match.start(3), Text, match.group(3)
  692. # lookup lexer if wanted and existing
  693. lexer = None
  694. if self.handlecodeblocks:
  695. try:
  696. lexer = get_lexer_by_name(match.group(2).strip())
  697. except ClassNotFound:
  698. pass
  699. code = match.group(4)
  700. # no lexer for this language. handle it like it was a code block
  701. if lexer is None:
  702. yield match.start(4), String, code
  703. return
  704. yield from _shift_indices(
  705. do_insertions([], lexer.get_tokens_unprocessed(code)),
  706. match.start(4))
  707. yield match.start(5), String, match.group(5)
  708. def _handle_cssblock(self, match):
  709. """
  710. match args: 1:style tag 2:newline, 3:code, 4:closing style tag
  711. """
  712. from pygments.lexers import get_lexer_by_name
  713. # section header
  714. yield match.start(1), String, match.group(1)
  715. yield match.start(2), String, match.group(2)
  716. lexer = None
  717. if self.handlecodeblocks:
  718. try:
  719. lexer = get_lexer_by_name('css')
  720. except ClassNotFound:
  721. pass
  722. code = match.group(3)
  723. # no lexer for this language. handle it like it was a code block
  724. if lexer is None:
  725. yield match.start(3), String, code
  726. return
  727. yield from _shift_indices(
  728. do_insertions([], lexer.get_tokens_unprocessed(code)),
  729. match.start(3))
  730. yield match.start(4), String, match.group(4)
  731. tokens = {
  732. 'root': [
  733. # title in metadata section
  734. (r'^(title)(:\s)(.+\n)', bygroups(Keyword, Text, Generic.Heading)),
  735. # headings
  736. (r'^(!)([^!].+\n)', bygroups(Generic.Heading, Text)),
  737. (r'^(!{2,6})(.+\n)', bygroups(Generic.Subheading, Text)),
  738. # bulleted or numbered lists or single-line block quotes
  739. # (can be mixed)
  740. (r'^(\s*)([*#>]+)(\s*)(.+\n)',
  741. bygroups(Text, Keyword, Text, using(this, state='inline'))),
  742. # multi-line block quotes
  743. (r'^(<<<.*\n)([\w\W]*?)(^<<<.*$)', bygroups(String, Text, String)),
  744. # table header
  745. (r'^(\|.*?\|h)$', bygroups(Generic.Strong)),
  746. # table footer or caption
  747. (r'^(\|.*?\|[cf])$', bygroups(Generic.Emph)),
  748. # table class
  749. (r'^(\|.*?\|k)$', bygroups(Name.Tag)),
  750. # definitions
  751. (r'^(;.*)$', bygroups(Generic.Strong)),
  752. # text block
  753. (r'^(```\n)([\w\W]*?)(^```$)', bygroups(String, Text, String)),
  754. # code block with language
  755. (r'^(```)(\w+)(\n)([\w\W]*?)(^```$)', _handle_codeblock),
  756. # CSS style block
  757. (r'^(<style>)(\n)([\w\W]*?)(^</style>$)', _handle_cssblock),
  758. include('keywords'),
  759. include('inline'),
  760. ],
  761. 'keywords': [
  762. (words((
  763. '\\define', '\\end', 'caption', 'created', 'modified', 'tags',
  764. 'title', 'type'), prefix=r'^', suffix=r'\b'),
  765. Keyword),
  766. ],
  767. 'inline': [
  768. # escape
  769. (r'\\.', Text),
  770. # created or modified date
  771. (r'\d{17}', Number.Integer),
  772. # italics
  773. (r'(\s)(//[^/]+//)((?=\W|\n))',
  774. bygroups(Text, Generic.Emph, Text)),
  775. # superscript
  776. (r'(\s)(\^\^[^\^]+\^\^)', bygroups(Text, Generic.Emph)),
  777. # subscript
  778. (r'(\s)(,,[^,]+,,)', bygroups(Text, Generic.Emph)),
  779. # underscore
  780. (r'(\s)(__[^_]+__)', bygroups(Text, Generic.Strong)),
  781. # bold
  782. (r"(\s)(''[^']+'')((?=\W|\n))",
  783. bygroups(Text, Generic.Strong, Text)),
  784. # strikethrough
  785. (r'(\s)(~~[^~]+~~)((?=\W|\n))',
  786. bygroups(Text, Generic.Deleted, Text)),
  787. # TiddlyWiki variables
  788. (r'<<[^>]+>>', Name.Tag),
  789. (r'\$\$[^$]+\$\$', Name.Tag),
  790. (r'\$\([^)]+\)\$', Name.Tag),
  791. # TiddlyWiki style or class
  792. (r'^@@.*$', Name.Tag),
  793. # HTML tags
  794. (r'</?[^>]+>', Name.Tag),
  795. # inline code
  796. (r'`[^`]+`', String.Backtick),
  797. # HTML escaped symbols
  798. (r'&\S*?;', String.Regex),
  799. # Wiki links
  800. (r'(\[{2})([^]\|]+)(\]{2})', bygroups(Text, Name.Tag, Text)),
  801. # External links
  802. (r'(\[{2})([^]\|]+)(\|)([^]\|]+)(\]{2})',
  803. bygroups(Text, Name.Tag, Text, Name.Attribute, Text)),
  804. # Transclusion
  805. (r'(\{{2})([^}]+)(\}{2})', bygroups(Text, Name.Tag, Text)),
  806. # URLs
  807. (r'(\b.?.?tps?://[^\s"]+)', bygroups(Name.Attribute)),
  808. # general text, must come last!
  809. (r'[\w]+', Text),
  810. (r'.', Text)
  811. ],
  812. }
  813. def __init__(self, **options):
  814. self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True)
  815. RegexLexer.__init__(self, **options)
  816. class WikitextLexer(RegexLexer):
  817. """
  818. For MediaWiki Wikitext.
  819. Parsing Wikitext is tricky, and results vary between different MediaWiki
  820. installations, so we only highlight common syntaxes (built-in or from
  821. popular extensions), and also assume templates produce no unbalanced
  822. syntaxes.
  823. """
  824. name = 'Wikitext'
  825. url = 'https://www.mediawiki.org/wiki/Wikitext'
  826. aliases = ['wikitext', 'mediawiki']
  827. filenames = []
  828. mimetypes = ['text/x-wiki']
  829. version_added = '2.15'
  830. flags = re.MULTILINE
  831. def nowiki_tag_rules(tag_name):
  832. return [
  833. (rf'(?i)(</)({tag_name})(\s*)(>)', bygroups(Punctuation,
  834. Name.Tag, Whitespace, Punctuation), '#pop'),
  835. include('entity'),
  836. include('text'),
  837. ]
  838. def plaintext_tag_rules(tag_name):
  839. return [
  840. (rf'(?si)(.*?)(</)({tag_name})(\s*)(>)', bygroups(Text,
  841. Punctuation, Name.Tag, Whitespace, Punctuation), '#pop'),
  842. ]
  843. def delegate_tag_rules(tag_name, lexer, **lexer_kwargs):
  844. return [
  845. (rf'(?i)(</)({tag_name})(\s*)(>)', bygroups(Punctuation,
  846. Name.Tag, Whitespace, Punctuation), '#pop'),
  847. (rf'(?si).+?(?=</{tag_name}\s*>)', using(lexer, **lexer_kwargs)),
  848. ]
  849. def text_rules(token):
  850. return [
  851. (r'\w+', token),
  852. (r'[^\S\n]+', token),
  853. (r'(?s).', token),
  854. ]
  855. def handle_syntaxhighlight(self, match, ctx):
  856. from pygments.lexers import get_lexer_by_name
  857. attr_content = match.group()
  858. start = 0
  859. index = 0
  860. while True:
  861. index = attr_content.find('>', start)
  862. # Exclude comment end (-->)
  863. if attr_content[index-2:index] != '--':
  864. break
  865. start = index + 1
  866. if index == -1:
  867. # No tag end
  868. yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr'])
  869. return
  870. attr = attr_content[:index]
  871. yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr'])
  872. yield match.start(3) + index, Punctuation, '>'
  873. lexer = None
  874. content = attr_content[index+1:]
  875. lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr)
  876. if len(lang_match) >= 1:
  877. # Pick the last match in case of multiple matches
  878. lang = lang_match[-1][1]
  879. try:
  880. lexer = get_lexer_by_name(lang)
  881. except ClassNotFound:
  882. pass
  883. if lexer is None:
  884. yield match.start() + index + 1, Text, content
  885. else:
  886. yield from lexer.get_tokens_unprocessed(content)
  887. def handle_score(self, match, ctx):
  888. attr_content = match.group()
  889. start = 0
  890. index = 0
  891. while True:
  892. index = attr_content.find('>', start)
  893. # Exclude comment end (-->)
  894. if attr_content[index-2:index] != '--':
  895. break
  896. start = index + 1
  897. if index == -1:
  898. # No tag end
  899. yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr'])
  900. return
  901. attr = attr_content[:index]
  902. content = attr_content[index+1:]
  903. yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr'])
  904. yield match.start(3) + index, Punctuation, '>'
  905. lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr)
  906. # Pick the last match in case of multiple matches
  907. lang = lang_match[-1][1] if len(lang_match) >= 1 else 'lilypond'
  908. if lang == 'lilypond': # Case sensitive
  909. yield from LilyPondLexer().get_tokens_unprocessed(content)
  910. else: # ABC
  911. # FIXME: Use ABC lexer in the future
  912. yield match.start() + index + 1, Text, content
  913. # a-z removed to prevent linter from complaining, REMEMBER to use (?i)
  914. title_char = r' %!"$&\'()*,\-./0-9:;=?@A-Z\\\^_`~+\u0080-\uFFFF'
  915. nbsp_char = r'(?:\t|&nbsp;|&\#0*160;|&\#[Xx]0*[Aa]0;|[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000])'
  916. link_address = r'(?:[0-9.]+|\[[0-9a-f:.]+\]|[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD])'
  917. link_char_class = r'[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD]'
  918. double_slashes_i = {
  919. '__FORCETOC__', '__NOCONTENTCONVERT__', '__NOCC__', '__NOEDITSECTION__', '__NOGALLERY__',
  920. '__NOTITLECONVERT__', '__NOTC__', '__NOTOC__', '__TOC__',
  921. }
  922. double_slashes = {
  923. '__EXPECTUNUSEDCATEGORY__', '__HIDDENCAT__', '__INDEX__', '__NEWSECTIONLINK__',
  924. '__NOINDEX__', '__NONEWSECTIONLINK__', '__STATICREDIRECT__', '__NOGLOBAL__',
  925. '__DISAMBIG__', '__EXPECTED_UNCONNECTED_PAGE__',
  926. }
  927. protocols = {
  928. 'bitcoin:', 'ftp://', 'ftps://', 'geo:', 'git://', 'gopher://', 'http://', 'https://',
  929. 'irc://', 'ircs://', 'magnet:', 'mailto:', 'mms://', 'news:', 'nntp://', 'redis://',
  930. 'sftp://', 'sip:', 'sips:', 'sms:', 'ssh://', 'svn://', 'tel:', 'telnet://', 'urn:',
  931. 'worldwind://', 'xmpp:', '//',
  932. }
  933. non_relative_protocols = protocols - {'//'}
  934. html_tags = {
  935. 'abbr', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code',
  936. 'data', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5',
  937. 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'link', 'mark', 'meta', 'ol', 'p', 'q', 'rb', 'rp',
  938. 'rt', 'rtc', 'ruby', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup',
  939. 'table', 'td', 'th', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr',
  940. }
  941. parser_tags = {
  942. 'graph', 'charinsert', 'rss', 'chem', 'categorytree', 'nowiki', 'inputbox', 'math',
  943. 'hiero', 'score', 'pre', 'ref', 'translate', 'imagemap', 'templatestyles', 'languages',
  944. 'noinclude', 'mapframe', 'section', 'poem', 'syntaxhighlight', 'includeonly', 'tvar',
  945. 'onlyinclude', 'templatedata', 'langconvert', 'timeline', 'dynamicpagelist', 'gallery',
  946. 'maplink', 'ce', 'references',
  947. }
  948. variant_langs = {
  949. # ZhConverter.php
  950. 'zh', 'zh-hans', 'zh-hant', 'zh-cn', 'zh-hk', 'zh-mo', 'zh-my', 'zh-sg', 'zh-tw',
  951. # WuuConverter.php
  952. 'wuu', 'wuu-hans', 'wuu-hant',
  953. # UzConverter.php
  954. 'uz', 'uz-latn', 'uz-cyrl',
  955. # TlyConverter.php
  956. 'tly', 'tly-cyrl',
  957. # TgConverter.php
  958. 'tg', 'tg-latn',
  959. # SrConverter.php
  960. 'sr', 'sr-ec', 'sr-el',
  961. # ShiConverter.php
  962. 'shi', 'shi-tfng', 'shi-latn',
  963. # ShConverter.php
  964. 'sh-latn', 'sh-cyrl',
  965. # KuConverter.php
  966. 'ku', 'ku-arab', 'ku-latn',
  967. # IuConverter.php
  968. 'iu', 'ike-cans', 'ike-latn',
  969. # GanConverter.php
  970. 'gan', 'gan-hans', 'gan-hant',
  971. # EnConverter.php
  972. 'en', 'en-x-piglatin',
  973. # CrhConverter.php
  974. 'crh', 'crh-cyrl', 'crh-latn',
  975. # BanConverter.php
  976. 'ban', 'ban-bali', 'ban-x-dharma', 'ban-x-palmleaf', 'ban-x-pku',
  977. }
  978. magic_vars_i = {
  979. 'ARTICLEPATH', 'INT', 'PAGEID', 'SCRIPTPATH', 'SERVER', 'SERVERNAME', 'STYLEPATH',
  980. }
  981. magic_vars = {
  982. '!', '=', 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'CONTENTLANGUAGE',
  983. 'CONTENTLANG', 'CURRENTDAY', 'CURRENTDAY2', 'CURRENTDAYNAME', 'CURRENTDOW', 'CURRENTHOUR',
  984. 'CURRENTMONTH', 'CURRENTMONTH2', 'CURRENTMONTH1', 'CURRENTMONTHABBREV', 'CURRENTMONTHNAME',
  985. 'CURRENTMONTHNAMEGEN', 'CURRENTTIME', 'CURRENTTIMESTAMP', 'CURRENTVERSION', 'CURRENTWEEK',
  986. 'CURRENTYEAR', 'DIRECTIONMARK', 'DIRMARK', 'FULLPAGENAME', 'FULLPAGENAMEE', 'LOCALDAY',
  987. 'LOCALDAY2', 'LOCALDAYNAME', 'LOCALDOW', 'LOCALHOUR', 'LOCALMONTH', 'LOCALMONTH2',
  988. 'LOCALMONTH1', 'LOCALMONTHABBREV', 'LOCALMONTHNAME', 'LOCALMONTHNAMEGEN', 'LOCALTIME',
  989. 'LOCALTIMESTAMP', 'LOCALWEEK', 'LOCALYEAR', 'NAMESPACE', 'NAMESPACEE', 'NAMESPACENUMBER',
  990. 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS', 'NUMBEROFARTICLES', 'NUMBEROFEDITS',
  991. 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS', 'PAGELANGUAGE', 'PAGENAME', 'PAGENAMEE',
  992. 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH', 'REVISIONMONTH1',
  993. 'REVISIONSIZE', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME',
  994. 'ROOTPAGENAMEE', 'SITENAME', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE',
  995. 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE',
  996. 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE',
  997. }
  998. parser_functions_i = {
  999. 'ANCHORENCODE', 'BIDI', 'CANONICALURL', 'CANONICALURLE', 'FILEPATH', 'FORMATNUM',
  1000. 'FULLURL', 'FULLURLE', 'GENDER', 'GRAMMAR', 'INT', r'\#LANGUAGE', 'LC', 'LCFIRST', 'LOCALURL',
  1001. 'LOCALURLE', 'NS', 'NSE', 'PADLEFT', 'PADRIGHT', 'PAGEID', 'PLURAL', 'UC', 'UCFIRST',
  1002. 'URLENCODE',
  1003. }
  1004. parser_functions = {
  1005. 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'DEFAULTSORT', 'DEFAULTSORTKEY',
  1006. 'DEFAULTCATEGORYSORT', 'FULLPAGENAME', 'FULLPAGENAMEE', 'NAMESPACE', 'NAMESPACEE',
  1007. 'NAMESPACENUMBER', 'NUMBERINGROUP', 'NUMINGROUP', 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS',
  1008. 'NUMBEROFARTICLES', 'NUMBEROFEDITS', 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS',
  1009. 'PAGENAME', 'PAGENAMEE', 'PAGESINCATEGORY', 'PAGESINCAT', 'PAGESIZE', 'PROTECTIONEXPIRY',
  1010. 'PROTECTIONLEVEL', 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH',
  1011. 'REVISIONMONTH1', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME',
  1012. 'ROOTPAGENAMEE', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE',
  1013. 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE',
  1014. 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE',
  1015. 'INT', 'DISPLAYTITLE', 'PAGESINNAMESPACE', 'PAGESINNS',
  1016. }
  1017. tokens = {
  1018. 'root': [
  1019. # Redirects
  1020. (r"""(?xi)
  1021. (\A\s*?)(\#REDIRECT:?) # may contain a colon
  1022. (\s+)(\[\[) (?=[^\]\n]* \]\]$)
  1023. """,
  1024. bygroups(Whitespace, Keyword, Whitespace, Punctuation), 'redirect-inner'),
  1025. # Subheadings
  1026. (r'^(={2,6})(.+?)(\1)(\s*$\n)',
  1027. bygroups(Generic.Subheading, Generic.Subheading, Generic.Subheading, Whitespace)),
  1028. # Headings
  1029. (r'^(=.+?=)(\s*$\n)',
  1030. bygroups(Generic.Heading, Whitespace)),
  1031. # Double-slashed magic words
  1032. (words(double_slashes_i, prefix=r'(?i)'), Name.Function.Magic),
  1033. (words(double_slashes), Name.Function.Magic),
  1034. # Raw URLs
  1035. (r'(?i)\b(?:{}){}{}*'.format('|'.join(protocols),
  1036. link_address, link_char_class), Name.Label),
  1037. # Magic links
  1038. (rf'\b(?:RFC|PMID){nbsp_char}+[0-9]+\b',
  1039. Name.Function.Magic),
  1040. (r"""(?x)
  1041. \bISBN {nbsp_char}
  1042. (?: 97[89] {nbsp_dash}? )?
  1043. (?: [0-9] {nbsp_dash}? ){{9}} # escape format()
  1044. [0-9Xx]\b
  1045. """.format(nbsp_char=nbsp_char, nbsp_dash=f'(?:-|{nbsp_char})'), Name.Function.Magic),
  1046. include('list'),
  1047. include('inline'),
  1048. include('text'),
  1049. ],
  1050. 'redirect-inner': [
  1051. (r'(\]\])(\s*?\n)', bygroups(Punctuation, Whitespace), '#pop'),
  1052. (r'(\#)([^#]*?)', bygroups(Punctuation, Name.Label)),
  1053. (rf'(?i)[{title_char}]+', Name.Tag),
  1054. ],
  1055. 'list': [
  1056. # Description lists
  1057. (r'^;', Keyword, 'dt'),
  1058. # Ordered lists, unordered lists and indents
  1059. (r'^[#:*]+', Keyword),
  1060. # Horizontal rules
  1061. (r'^-{4,}', Keyword),
  1062. ],
  1063. 'inline': [
  1064. # Signatures
  1065. (r'~{3,5}', Keyword),
  1066. # Entities
  1067. include('entity'),
  1068. # Bold & italic
  1069. (r"('')(''')(?!')", bygroups(Generic.Emph,
  1070. Generic.EmphStrong), 'inline-italic-bold'),
  1071. (r"'''(?!')", Generic.Strong, 'inline-bold'),
  1072. (r"''(?!')", Generic.Emph, 'inline-italic'),
  1073. # Comments & parameters & templates
  1074. include('replaceable'),
  1075. # Media links
  1076. (
  1077. r"""(?xi)
  1078. (\[\[)
  1079. (File|Image) (:)
  1080. ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | <!--[\s\S]*?--> )*)
  1081. (?: (\#) ([{}]*?) )?
  1082. """.format(title_char, f'{title_char}#'),
  1083. bygroups(Punctuation, Name.Namespace, Punctuation,
  1084. using(this, state=['wikilink-name']), Punctuation, Name.Label),
  1085. 'medialink-inner'
  1086. ),
  1087. # Wikilinks
  1088. (
  1089. r"""(?xi)
  1090. (\[\[)(?!{}) # Should not contain URLs
  1091. (?: ([{}]*) (:))?
  1092. ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | <!--[\s\S]*?--> )*?)
  1093. (?: (\#) ([{}]*?) )?
  1094. (\]\])
  1095. """.format('|'.join(protocols), title_char.replace('/', ''),
  1096. title_char, f'{title_char}#'),
  1097. bygroups(Punctuation, Name.Namespace, Punctuation,
  1098. using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation)
  1099. ),
  1100. (
  1101. r"""(?xi)
  1102. (\[\[)(?!{})
  1103. (?: ([{}]*) (:))?
  1104. ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | <!--[\s\S]*?--> )*?)
  1105. (?: (\#) ([{}]*?) )?
  1106. (\|)
  1107. """.format('|'.join(protocols), title_char.replace('/', ''),
  1108. title_char, f'{title_char}#'),
  1109. bygroups(Punctuation, Name.Namespace, Punctuation,
  1110. using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation),
  1111. 'wikilink-inner'
  1112. ),
  1113. # External links
  1114. (
  1115. r"""(?xi)
  1116. (\[)
  1117. ((?:{}) {} {}*)
  1118. (\s*)
  1119. """.format('|'.join(protocols), link_address, link_char_class),
  1120. bygroups(Punctuation, Name.Label, Whitespace),
  1121. 'extlink-inner'
  1122. ),
  1123. # Tables
  1124. (r'^(:*)(\s*?)(\{\|)([^\n]*)$', bygroups(Keyword,
  1125. Whitespace, Punctuation, using(this, state=['root', 'attr'])), 'table'),
  1126. # HTML tags
  1127. (r'(?i)(<)({})\b'.format('|'.join(html_tags)),
  1128. bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'),
  1129. (r'(?i)(</)({})\b(\s*)(>)'.format('|'.join(html_tags)),
  1130. bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
  1131. # <nowiki>
  1132. (r'(?i)(<)(nowiki)\b', bygroups(Punctuation,
  1133. Name.Tag), ('tag-nowiki', 'tag-inner')),
  1134. # <pre>
  1135. (r'(?i)(<)(pre)\b', bygroups(Punctuation,
  1136. Name.Tag), ('tag-pre', 'tag-inner')),
  1137. # <categorytree>
  1138. (r'(?i)(<)(categorytree)\b', bygroups(
  1139. Punctuation, Name.Tag), ('tag-categorytree', 'tag-inner')),
  1140. # <hiero>
  1141. (r'(?i)(<)(hiero)\b', bygroups(Punctuation,
  1142. Name.Tag), ('tag-hiero', 'tag-inner')),
  1143. # <math>
  1144. (r'(?i)(<)(math)\b', bygroups(Punctuation,
  1145. Name.Tag), ('tag-math', 'tag-inner')),
  1146. # <chem>
  1147. (r'(?i)(<)(chem)\b', bygroups(Punctuation,
  1148. Name.Tag), ('tag-chem', 'tag-inner')),
  1149. # <ce>
  1150. (r'(?i)(<)(ce)\b', bygroups(Punctuation,
  1151. Name.Tag), ('tag-ce', 'tag-inner')),
  1152. # <charinsert>
  1153. (r'(?i)(<)(charinsert)\b', bygroups(
  1154. Punctuation, Name.Tag), ('tag-charinsert', 'tag-inner')),
  1155. # <templatedata>
  1156. (r'(?i)(<)(templatedata)\b', bygroups(
  1157. Punctuation, Name.Tag), ('tag-templatedata', 'tag-inner')),
  1158. # <gallery>
  1159. (r'(?i)(<)(gallery)\b', bygroups(
  1160. Punctuation, Name.Tag), ('tag-gallery', 'tag-inner')),
  1161. # <graph>
  1162. (r'(?i)(<)(gallery)\b', bygroups(
  1163. Punctuation, Name.Tag), ('tag-graph', 'tag-inner')),
  1164. # <dynamicpagelist>
  1165. (r'(?i)(<)(dynamicpagelist)\b', bygroups(
  1166. Punctuation, Name.Tag), ('tag-dynamicpagelist', 'tag-inner')),
  1167. # <inputbox>
  1168. (r'(?i)(<)(inputbox)\b', bygroups(
  1169. Punctuation, Name.Tag), ('tag-inputbox', 'tag-inner')),
  1170. # <rss>
  1171. (r'(?i)(<)(rss)\b', bygroups(
  1172. Punctuation, Name.Tag), ('tag-rss', 'tag-inner')),
  1173. # <imagemap>
  1174. (r'(?i)(<)(imagemap)\b', bygroups(
  1175. Punctuation, Name.Tag), ('tag-imagemap', 'tag-inner')),
  1176. # <syntaxhighlight>
  1177. (r'(?i)(</)(syntaxhighlight)\b(\s*)(>)',
  1178. bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
  1179. (r'(?si)(<)(syntaxhighlight)\b([^>]*?(?<!/)>.*?)(?=</\2\s*>)',
  1180. bygroups(Punctuation, Name.Tag, handle_syntaxhighlight)),
  1181. # <syntaxhighlight>: Fallback case for self-closing tags
  1182. (r'(?i)(<)(syntaxhighlight)\b(\s*?)((?:[^>]|-->)*?)(/\s*?(?<!--)>)', bygroups(
  1183. Punctuation, Name.Tag, Whitespace, using(this, state=['root', 'attr']), Punctuation)),
  1184. # <source>
  1185. (r'(?i)(</)(source)\b(\s*)(>)',
  1186. bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
  1187. (r'(?si)(<)(source)\b([^>]*?(?<!/)>.*?)(?=</\2\s*>)',
  1188. bygroups(Punctuation, Name.Tag, handle_syntaxhighlight)),
  1189. # <source>: Fallback case for self-closing tags
  1190. (r'(?i)(<)(source)\b(\s*?)((?:[^>]|-->)*?)(/\s*?(?<!--)>)', bygroups(
  1191. Punctuation, Name.Tag, Whitespace, using(this, state=['root', 'attr']), Punctuation)),
  1192. # <score>
  1193. (r'(?i)(</)(score)\b(\s*)(>)',
  1194. bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
  1195. (r'(?si)(<)(score)\b([^>]*?(?<!/)>.*?)(?=</\2\s*>)',
  1196. bygroups(Punctuation, Name.Tag, handle_score)),
  1197. # <score>: Fallback case for self-closing tags
  1198. (r'(?i)(<)(score)\b(\s*?)((?:[^>]|-->)*?)(/\s*?(?<!--)>)', bygroups(
  1199. Punctuation, Name.Tag, Whitespace, using(this, state=['root', 'attr']), Punctuation)),
  1200. # Other parser tags
  1201. (r'(?i)(<)({})\b'.format('|'.join(parser_tags)),
  1202. bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'),
  1203. (r'(?i)(</)({})\b(\s*)(>)'.format('|'.join(parser_tags)),
  1204. bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
  1205. # LanguageConverter markups
  1206. (
  1207. r"""(?xi)
  1208. (-\{{) # Use {{ to escape format()
  1209. ([^|]) (\|)
  1210. (?:
  1211. (?: ([^;]*?) (=>))?
  1212. (\s* (?:{variants}) \s*) (:)
  1213. )?
  1214. """.format(variants='|'.join(variant_langs)),
  1215. bygroups(Punctuation, Keyword, Punctuation,
  1216. using(this, state=['root', 'lc-raw']),
  1217. Operator, Name.Label, Punctuation),
  1218. 'lc-inner'
  1219. ),
  1220. # LanguageConverter markups: composite conversion grammar
  1221. (
  1222. r"""(?xi)
  1223. (-\{)
  1224. ([a-z\s;-]*?) (\|)
  1225. """,
  1226. bygroups(Punctuation,
  1227. using(this, state=['root', 'lc-flag']),
  1228. Punctuation),
  1229. 'lc-raw'
  1230. ),
  1231. # LanguageConverter markups: fallbacks
  1232. (
  1233. r"""(?xi)
  1234. (-\{{) (?!\{{) # Use {{ to escape format()
  1235. (?: (\s* (?:{variants}) \s*) (:))?
  1236. """.format(variants='|'.join(variant_langs)),
  1237. bygroups(Punctuation, Name.Label, Punctuation),
  1238. 'lc-inner'
  1239. ),
  1240. ],
  1241. 'wikilink-name': [
  1242. include('replaceable'),
  1243. (r'[^{<]+', Name.Tag),
  1244. (r'(?s).', Name.Tag),
  1245. ],
  1246. 'wikilink-inner': [
  1247. # Quit in case of another wikilink
  1248. (r'(?=\[\[)', Punctuation, '#pop'),
  1249. (r'\]\]', Punctuation, '#pop'),
  1250. include('inline'),
  1251. include('text'),
  1252. ],
  1253. 'medialink-inner': [
  1254. (r'\]\]', Punctuation, '#pop'),
  1255. (r'(\|)([^\n=|]*)(=)',
  1256. bygroups(Punctuation, Name.Attribute, Operator)),
  1257. (r'\|', Punctuation),
  1258. include('inline'),
  1259. include('text'),
  1260. ],
  1261. 'quote-common': [
  1262. # Quit in case of link/template endings
  1263. (r'(?=\]\]|\{\{|\}\})', Punctuation, '#pop'),
  1264. (r'\n', Text, '#pop'),
  1265. ],
  1266. 'inline-italic': [
  1267. include('quote-common'),
  1268. (r"('')(''')(?!')", bygroups(Generic.Emph,
  1269. Generic.Strong), ('#pop', 'inline-bold')),
  1270. (r"'''(?!')", Generic.EmphStrong, ('#pop', 'inline-italic-bold')),
  1271. (r"''(?!')", Generic.Emph, '#pop'),
  1272. include('inline'),
  1273. include('text-italic'),
  1274. ],
  1275. 'inline-bold': [
  1276. include('quote-common'),
  1277. (r"(''')('')(?!')", bygroups(
  1278. Generic.Strong, Generic.Emph), ('#pop', 'inline-italic')),
  1279. (r"'''(?!')", Generic.Strong, '#pop'),
  1280. (r"''(?!')", Generic.EmphStrong, ('#pop', 'inline-bold-italic')),
  1281. include('inline'),
  1282. include('text-bold'),
  1283. ],
  1284. 'inline-bold-italic': [
  1285. include('quote-common'),
  1286. (r"('')(''')(?!')", bygroups(Generic.EmphStrong,
  1287. Generic.Strong), '#pop'),
  1288. (r"'''(?!')", Generic.EmphStrong, ('#pop', 'inline-italic')),
  1289. (r"''(?!')", Generic.EmphStrong, ('#pop', 'inline-bold')),
  1290. include('inline'),
  1291. include('text-bold-italic'),
  1292. ],
  1293. 'inline-italic-bold': [
  1294. include('quote-common'),
  1295. (r"(''')('')(?!')", bygroups(
  1296. Generic.EmphStrong, Generic.Emph), '#pop'),
  1297. (r"'''(?!')", Generic.EmphStrong, ('#pop', 'inline-italic')),
  1298. (r"''(?!')", Generic.EmphStrong, ('#pop', 'inline-bold')),
  1299. include('inline'),
  1300. include('text-bold-italic'),
  1301. ],
  1302. 'lc-flag': [
  1303. (r'\s+', Whitespace),
  1304. (r';', Punctuation),
  1305. *text_rules(Keyword),
  1306. ],
  1307. 'lc-inner': [
  1308. (
  1309. r"""(?xi)
  1310. (;)
  1311. (?: ([^;]*?) (=>))?
  1312. (\s* (?:{variants}) \s*) (:)
  1313. """.format(variants='|'.join(variant_langs)),
  1314. bygroups(Punctuation, using(this, state=['root', 'lc-raw']),
  1315. Operator, Name.Label, Punctuation)
  1316. ),
  1317. (r';?\s*?\}-', Punctuation, '#pop'),
  1318. include('inline'),
  1319. include('text'),
  1320. ],
  1321. 'lc-raw': [
  1322. (r'\}-', Punctuation, '#pop'),
  1323. include('inline'),
  1324. include('text'),
  1325. ],
  1326. 'replaceable': [
  1327. # Comments
  1328. (r'<!--[\s\S]*?(?:-->|\Z)', Comment.Multiline),
  1329. # Parameters
  1330. (
  1331. r"""(?x)
  1332. (\{{3})
  1333. ([^|]*?)
  1334. (?=\}{3}|\|)
  1335. """,
  1336. bygroups(Punctuation, Name.Variable),
  1337. 'parameter-inner',
  1338. ),
  1339. # Magic variables
  1340. (r'(?i)(\{{\{{)(\s*)({})(\s*)(\}}\}})'.format('|'.join(magic_vars_i)),
  1341. bygroups(Punctuation, Whitespace, Name.Function, Whitespace, Punctuation)),
  1342. (r'(\{{\{{)(\s*)({})(\s*)(\}}\}})'.format('|'.join(magic_vars)),
  1343. bygroups(Punctuation, Whitespace, Name.Function, Whitespace, Punctuation)),
  1344. # Parser functions & templates
  1345. (r'\{\{', Punctuation, 'template-begin-space'),
  1346. # <tvar> legacy syntax
  1347. (r'(?i)(<)(tvar)\b(\|)([^>]*?)(>)', bygroups(Punctuation,
  1348. Name.Tag, Punctuation, String, Punctuation)),
  1349. (r'</>', Punctuation, '#pop'),
  1350. # <tvar>
  1351. (r'(?i)(<)(tvar)\b', bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'),
  1352. (r'(?i)(</)(tvar)\b(\s*)(>)',
  1353. bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
  1354. ],
  1355. 'parameter-inner': [
  1356. (r'\}{3}', Punctuation, '#pop'),
  1357. (r'\|', Punctuation),
  1358. include('inline'),
  1359. include('text'),
  1360. ],
  1361. 'template-begin-space': [
  1362. # Templates allow line breaks at the beginning, and due to how MediaWiki handles
  1363. # comments, an extra state is required to handle things like {{\n<!---->\n name}}
  1364. (r'<!--[\s\S]*?(?:-->|\Z)', Comment.Multiline),
  1365. (r'\s+', Whitespace),
  1366. # Parser functions
  1367. (
  1368. r'(?i)(\#[{}]*?|{})(:)'.format(title_char,
  1369. '|'.join(parser_functions_i)),
  1370. bygroups(Name.Function, Punctuation), ('#pop', 'template-inner')
  1371. ),
  1372. (
  1373. r'({})(:)'.format('|'.join(parser_functions)),
  1374. bygroups(Name.Function, Punctuation), ('#pop', 'template-inner')
  1375. ),
  1376. # Templates
  1377. (
  1378. rf'(?i)([{title_char}]*?)(:)',
  1379. bygroups(Name.Namespace, Punctuation), ('#pop', 'template-name')
  1380. ),
  1381. default(('#pop', 'template-name'),),
  1382. ],
  1383. 'template-name': [
  1384. (r'(\s*?)(\|)', bygroups(Text, Punctuation), ('#pop', 'template-inner')),
  1385. (r'\}\}', Punctuation, '#pop'),
  1386. (r'\n', Text, '#pop'),
  1387. include('replaceable'),
  1388. *text_rules(Name.Tag),
  1389. ],
  1390. 'template-inner': [
  1391. (r'\}\}', Punctuation, '#pop'),
  1392. (r'\|', Punctuation),
  1393. (
  1394. r"""(?x)
  1395. (?<=\|)
  1396. ( (?: (?! \{\{ | \}\} )[^=\|<])*? ) # Exclude templates and tags
  1397. (=)
  1398. """,
  1399. bygroups(Name.Label, Operator)
  1400. ),
  1401. include('inline'),
  1402. include('text'),
  1403. ],
  1404. 'table': [
  1405. # Use [ \t\n\r\0\x0B] instead of \s to follow PHP trim() behavior
  1406. # Endings
  1407. (r'^([ \t\n\r\0\x0B]*?)(\|\})',
  1408. bygroups(Whitespace, Punctuation), '#pop'),
  1409. # Table rows
  1410. (r'^([ \t\n\r\0\x0B]*?)(\|-+)(.*)$', bygroups(Whitespace, Punctuation,
  1411. using(this, state=['root', 'attr']))),
  1412. # Captions
  1413. (
  1414. r"""(?x)
  1415. ^([ \t\n\r\0\x0B]*?)(\|\+)
  1416. # Exclude links, template and tags
  1417. (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|) )?
  1418. (.*?)$
  1419. """,
  1420. bygroups(Whitespace, Punctuation, using(this, state=[
  1421. 'root', 'attr']), Punctuation, Generic.Heading),
  1422. ),
  1423. # Table data
  1424. (
  1425. r"""(?x)
  1426. ( ^(?:[ \t\n\r\0\x0B]*?)\| | \|\| )
  1427. (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|)(?!\|) )?
  1428. """,
  1429. bygroups(Punctuation, using(this, state=[
  1430. 'root', 'attr']), Punctuation),
  1431. ),
  1432. # Table headers
  1433. (
  1434. r"""(?x)
  1435. ( ^(?:[ \t\n\r\0\x0B]*?)! )
  1436. (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|)(?!\|) )?
  1437. """,
  1438. bygroups(Punctuation, using(this, state=[
  1439. 'root', 'attr']), Punctuation),
  1440. 'table-header',
  1441. ),
  1442. include('list'),
  1443. include('inline'),
  1444. include('text'),
  1445. ],
  1446. 'table-header': [
  1447. # Requires another state for || handling inside headers
  1448. (r'\n', Text, '#pop'),
  1449. (
  1450. r"""(?x)
  1451. (!!|\|\|)
  1452. (?:
  1453. ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )
  1454. (\|)(?!\|)
  1455. )?
  1456. """,
  1457. bygroups(Punctuation, using(this, state=[
  1458. 'root', 'attr']), Punctuation)
  1459. ),
  1460. *text_rules(Generic.Subheading),
  1461. ],
  1462. 'entity': [
  1463. (r'&\S*?;', Name.Entity),
  1464. ],
  1465. 'dt': [
  1466. (r'\n', Text, '#pop'),
  1467. include('inline'),
  1468. (r':', Keyword, '#pop'),
  1469. include('text'),
  1470. ],
  1471. 'extlink-inner': [
  1472. (r'\]', Punctuation, '#pop'),
  1473. include('inline'),
  1474. include('text'),
  1475. ],
  1476. 'nowiki-ish': [
  1477. include('entity'),
  1478. include('text'),
  1479. ],
  1480. 'attr': [
  1481. include('replaceable'),
  1482. (r'\s+', Whitespace),
  1483. (r'(=)(\s*)(")', bygroups(Operator, Whitespace, String.Double), 'attr-val-2'),
  1484. (r"(=)(\s*)(')", bygroups(Operator, Whitespace, String.Single), 'attr-val-1'),
  1485. (r'(=)(\s*)', bygroups(Operator, Whitespace), 'attr-val-0'),
  1486. (r'[\w:-]+', Name.Attribute),
  1487. ],
  1488. 'attr-val-0': [
  1489. (r'\s', Whitespace, '#pop'),
  1490. include('replaceable'),
  1491. *text_rules(String),
  1492. ],
  1493. 'attr-val-1': [
  1494. (r"'", String.Single, '#pop'),
  1495. include('replaceable'),
  1496. *text_rules(String.Single),
  1497. ],
  1498. 'attr-val-2': [
  1499. (r'"', String.Double, '#pop'),
  1500. include('replaceable'),
  1501. *text_rules(String.Double),
  1502. ],
  1503. 'tag-inner-ordinary': [
  1504. (r'/?\s*>', Punctuation, '#pop'),
  1505. include('tag-attr'),
  1506. ],
  1507. 'tag-inner': [
  1508. # Return to root state for self-closing tags
  1509. (r'/\s*>', Punctuation, '#pop:2'),
  1510. (r'\s*>', Punctuation, '#pop'),
  1511. include('tag-attr'),
  1512. ],
  1513. # There states below are just like their non-tag variants, the key difference is
  1514. # they forcibly quit when encountering tag closing markup
  1515. 'tag-attr': [
  1516. include('replaceable'),
  1517. (r'\s+', Whitespace),
  1518. (r'(=)(\s*)(")', bygroups(Operator,
  1519. Whitespace, String.Double), 'tag-attr-val-2'),
  1520. (r"(=)(\s*)(')", bygroups(Operator,
  1521. Whitespace, String.Single), 'tag-attr-val-1'),
  1522. (r'(=)(\s*)', bygroups(Operator, Whitespace), 'tag-attr-val-0'),
  1523. (r'[\w:-]+', Name.Attribute),
  1524. ],
  1525. 'tag-attr-val-0': [
  1526. (r'\s', Whitespace, '#pop'),
  1527. (r'/?>', Punctuation, '#pop:2'),
  1528. include('replaceable'),
  1529. *text_rules(String),
  1530. ],
  1531. 'tag-attr-val-1': [
  1532. (r"'", String.Single, '#pop'),
  1533. (r'/?>', Punctuation, '#pop:2'),
  1534. include('replaceable'),
  1535. *text_rules(String.Single),
  1536. ],
  1537. 'tag-attr-val-2': [
  1538. (r'"', String.Double, '#pop'),
  1539. (r'/?>', Punctuation, '#pop:2'),
  1540. include('replaceable'),
  1541. *text_rules(String.Double),
  1542. ],
  1543. 'tag-nowiki': nowiki_tag_rules('nowiki'),
  1544. 'tag-pre': nowiki_tag_rules('pre'),
  1545. 'tag-categorytree': plaintext_tag_rules('categorytree'),
  1546. 'tag-dynamicpagelist': plaintext_tag_rules('dynamicpagelist'),
  1547. 'tag-hiero': plaintext_tag_rules('hiero'),
  1548. 'tag-inputbox': plaintext_tag_rules('inputbox'),
  1549. 'tag-imagemap': plaintext_tag_rules('imagemap'),
  1550. 'tag-charinsert': plaintext_tag_rules('charinsert'),
  1551. 'tag-timeline': plaintext_tag_rules('timeline'),
  1552. 'tag-gallery': plaintext_tag_rules('gallery'),
  1553. 'tag-graph': plaintext_tag_rules('graph'),
  1554. 'tag-rss': plaintext_tag_rules('rss'),
  1555. 'tag-math': delegate_tag_rules('math', TexLexer, state='math'),
  1556. 'tag-chem': delegate_tag_rules('chem', TexLexer, state='math'),
  1557. 'tag-ce': delegate_tag_rules('ce', TexLexer, state='math'),
  1558. 'tag-templatedata': delegate_tag_rules('templatedata', JsonLexer),
  1559. 'text-italic': text_rules(Generic.Emph),
  1560. 'text-bold': text_rules(Generic.Strong),
  1561. 'text-bold-italic': text_rules(Generic.EmphStrong),
  1562. 'text': text_rules(Text),
  1563. }