`` tags. By default, the content is enclosed
+ in a ```` tag, itself wrapped in a ```` tag (but see the `nowrap` option).
+ The ``
``'s CSS class can be set by the `cssclass` option.
+
+ If the `linenos` option is set to ``"table"``, the ``
`` is
+ additionally wrapped inside a ``
`` which has one row and two
+ cells: one containing the line numbers and one containing the code.
+ Example:
+
+ .. sourcecode:: html
+
+
+
+
+ 1
+ 2
+ |
+
+ def foo(bar):
+ pass
+
+ |
+
+
+ (whitespace added to improve clarity).
+
+ A list of lines can be specified using the `hl_lines` option to make these
+ lines highlighted (as of Pygments 0.11).
+
+ With the `full` option, a complete HTML 4 document is output, including
+ the style definitions inside a ``$)', _handle_cssblock),
+
+ include('keywords'),
+ include('inline'),
+ ],
+ 'keywords': [
+ (words((
+ '\\define', '\\end', 'caption', 'created', 'modified', 'tags',
+ 'title', 'type'), prefix=r'^', suffix=r'\b'),
+ Keyword),
+ ],
+ 'inline': [
+ # escape
+ (r'\\.', Text),
+ # created or modified date
+ (r'\d{17}', Number.Integer),
+ # italics
+ (r'(\s)(//[^/]+//)((?=\W|\n))',
+ bygroups(Text, Generic.Emph, Text)),
+ # superscript
+ (r'(\s)(\^\^[^\^]+\^\^)', bygroups(Text, Generic.Emph)),
+ # subscript
+ (r'(\s)(,,[^,]+,,)', bygroups(Text, Generic.Emph)),
+ # underscore
+ (r'(\s)(__[^_]+__)', bygroups(Text, Generic.Strong)),
+ # bold
+ (r"(\s)(''[^']+'')((?=\W|\n))",
+ bygroups(Text, Generic.Strong, Text)),
+ # strikethrough
+ (r'(\s)(~~[^~]+~~)((?=\W|\n))',
+ bygroups(Text, Generic.Deleted, Text)),
+ # TiddlyWiki variables
+ (r'<<[^>]+>>', Name.Tag),
+ (r'\$\$[^$]+\$\$', Name.Tag),
+ (r'\$\([^)]+\)\$', Name.Tag),
+ # TiddlyWiki style or class
+ (r'^@@.*$', Name.Tag),
+ # HTML tags
+ (r'?[^>]+>', Name.Tag),
+ # inline code
+ (r'`[^`]+`', String.Backtick),
+ # HTML escaped symbols
+ (r'&\S*?;', String.Regex),
+ # Wiki links
+ (r'(\[{2})([^]\|]+)(\]{2})', bygroups(Text, Name.Tag, Text)),
+ # External links
+ (r'(\[{2})([^]\|]+)(\|)([^]\|]+)(\]{2})',
+ bygroups(Text, Name.Tag, Text, Name.Attribute, Text)),
+ # Transclusion
+ (r'(\{{2})([^}]+)(\}{2})', bygroups(Text, Name.Tag, Text)),
+ # URLs
+ (r'(\b.?.?tps?://[^\s"]+)', bygroups(Name.Attribute)),
+
+ # general text, must come last!
+ (r'[\w]+', Text),
+ (r'.', Text)
+ ],
+ }
+
+ def __init__(self, **options):
+ self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True)
+ RegexLexer.__init__(self, **options)
+
+
+class WikitextLexer(RegexLexer):
+ """
+ For MediaWiki Wikitext.
+
+ Parsing Wikitext is tricky, and results vary between different MediaWiki
+ installations, so we only highlight common syntaxes (built-in or from
+ popular extensions), and also assume templates produce no unbalanced
+ syntaxes.
+ """
+ name = 'Wikitext'
+ url = 'https://www.mediawiki.org/wiki/Wikitext'
+ aliases = ['wikitext', 'mediawiki']
+ filenames = []
+ mimetypes = ['text/x-wiki']
+ version_added = '2.15'
+ flags = re.MULTILINE
+
+ def nowiki_tag_rules(tag_name):
+ return [
+ (rf'(?i)()({tag_name})(\s*)(>)', bygroups(Punctuation,
+ Name.Tag, Whitespace, Punctuation), '#pop'),
+ include('entity'),
+ include('text'),
+ ]
+
+ def plaintext_tag_rules(tag_name):
+ return [
+ (rf'(?si)(.*?)()({tag_name})(\s*)(>)', bygroups(Text,
+ Punctuation, Name.Tag, Whitespace, Punctuation), '#pop'),
+ ]
+
+ def delegate_tag_rules(tag_name, lexer, **lexer_kwargs):
+ return [
+ (rf'(?i)()({tag_name})(\s*)(>)', bygroups(Punctuation,
+ Name.Tag, Whitespace, Punctuation), '#pop'),
+ (rf'(?si).+?(?={tag_name}\s*>)', using(lexer, **lexer_kwargs)),
+ ]
+
+ def text_rules(token):
+ return [
+ (r'\w+', token),
+ (r'[^\S\n]+', token),
+ (r'(?s).', token),
+ ]
+
+ def handle_syntaxhighlight(self, match, ctx):
+ from pygments.lexers import get_lexer_by_name
+
+ attr_content = match.group()
+ start = 0
+ index = 0
+ while True:
+ index = attr_content.find('>', start)
+ # Exclude comment end (-->)
+ if attr_content[index-2:index] != '--':
+ break
+ start = index + 1
+
+ if index == -1:
+ # No tag end
+ yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr'])
+ return
+ attr = attr_content[:index]
+ yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr'])
+ yield match.start(3) + index, Punctuation, '>'
+
+ lexer = None
+ content = attr_content[index+1:]
+ lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr)
+
+ if len(lang_match) >= 1:
+ # Pick the last match in case of multiple matches
+ lang = lang_match[-1][1]
+ try:
+ lexer = get_lexer_by_name(lang)
+ except ClassNotFound:
+ pass
+
+ if lexer is None:
+ yield match.start() + index + 1, Text, content
+ else:
+ yield from lexer.get_tokens_unprocessed(content)
+
+ def handle_score(self, match, ctx):
+ attr_content = match.group()
+ start = 0
+ index = 0
+ while True:
+ index = attr_content.find('>', start)
+ # Exclude comment end (-->)
+ if attr_content[index-2:index] != '--':
+ break
+ start = index + 1
+
+ if index == -1:
+ # No tag end
+ yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr'])
+ return
+ attr = attr_content[:index]
+ content = attr_content[index+1:]
+ yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr'])
+ yield match.start(3) + index, Punctuation, '>'
+
+ lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr)
+ # Pick the last match in case of multiple matches
+ lang = lang_match[-1][1] if len(lang_match) >= 1 else 'lilypond'
+
+ if lang == 'lilypond': # Case sensitive
+ yield from LilyPondLexer().get_tokens_unprocessed(content)
+ else: # ABC
+ # FIXME: Use ABC lexer in the future
+ yield match.start() + index + 1, Text, content
+
+ # a-z removed to prevent linter from complaining, REMEMBER to use (?i)
+ title_char = r' %!"$&\'()*,\-./0-9:;=?@A-Z\\\^_`~+\u0080-\uFFFF'
+ nbsp_char = r'(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000])'
+ link_address = r'(?:[0-9.]+|\[[0-9a-f:.]+\]|[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD])'
+ link_char_class = r'[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD]'
+ double_slashes_i = {
+ '__FORCETOC__', '__NOCONTENTCONVERT__', '__NOCC__', '__NOEDITSECTION__', '__NOGALLERY__',
+ '__NOTITLECONVERT__', '__NOTC__', '__NOTOC__', '__TOC__',
+ }
+ double_slashes = {
+ '__EXPECTUNUSEDCATEGORY__', '__HIDDENCAT__', '__INDEX__', '__NEWSECTIONLINK__',
+ '__NOINDEX__', '__NONEWSECTIONLINK__', '__STATICREDIRECT__', '__NOGLOBAL__',
+ '__DISAMBIG__', '__EXPECTED_UNCONNECTED_PAGE__',
+ }
+ protocols = {
+ 'bitcoin:', 'ftp://', 'ftps://', 'geo:', 'git://', 'gopher://', 'http://', 'https://',
+ 'irc://', 'ircs://', 'magnet:', 'mailto:', 'mms://', 'news:', 'nntp://', 'redis://',
+ 'sftp://', 'sip:', 'sips:', 'sms:', 'ssh://', 'svn://', 'tel:', 'telnet://', 'urn:',
+ 'worldwind://', 'xmpp:', '//',
+ }
+ non_relative_protocols = protocols - {'//'}
+ html_tags = {
+ 'abbr', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code',
+ 'data', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5',
+ 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'link', 'mark', 'meta', 'ol', 'p', 'q', 'rb', 'rp',
+ 'rt', 'rtc', 'ruby', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup',
+ 'table', 'td', 'th', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr',
+ }
+ parser_tags = {
+ 'graph', 'charinsert', 'rss', 'chem', 'categorytree', 'nowiki', 'inputbox', 'math',
+ 'hiero', 'score', 'pre', 'ref', 'translate', 'imagemap', 'templatestyles', 'languages',
+ 'noinclude', 'mapframe', 'section', 'poem', 'syntaxhighlight', 'includeonly', 'tvar',
+ 'onlyinclude', 'templatedata', 'langconvert', 'timeline', 'dynamicpagelist', 'gallery',
+ 'maplink', 'ce', 'references',
+ }
+ variant_langs = {
+ # ZhConverter.php
+ 'zh', 'zh-hans', 'zh-hant', 'zh-cn', 'zh-hk', 'zh-mo', 'zh-my', 'zh-sg', 'zh-tw',
+ # WuuConverter.php
+ 'wuu', 'wuu-hans', 'wuu-hant',
+ # UzConverter.php
+ 'uz', 'uz-latn', 'uz-cyrl',
+ # TlyConverter.php
+ 'tly', 'tly-cyrl',
+ # TgConverter.php
+ 'tg', 'tg-latn',
+ # SrConverter.php
+ 'sr', 'sr-ec', 'sr-el',
+ # ShiConverter.php
+ 'shi', 'shi-tfng', 'shi-latn',
+ # ShConverter.php
+ 'sh-latn', 'sh-cyrl',
+ # KuConverter.php
+ 'ku', 'ku-arab', 'ku-latn',
+ # IuConverter.php
+ 'iu', 'ike-cans', 'ike-latn',
+ # GanConverter.php
+ 'gan', 'gan-hans', 'gan-hant',
+ # EnConverter.php
+ 'en', 'en-x-piglatin',
+ # CrhConverter.php
+ 'crh', 'crh-cyrl', 'crh-latn',
+ # BanConverter.php
+ 'ban', 'ban-bali', 'ban-x-dharma', 'ban-x-palmleaf', 'ban-x-pku',
+ }
+ magic_vars_i = {
+ 'ARTICLEPATH', 'INT', 'PAGEID', 'SCRIPTPATH', 'SERVER', 'SERVERNAME', 'STYLEPATH',
+ }
+ magic_vars = {
+ '!', '=', 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'CONTENTLANGUAGE',
+ 'CONTENTLANG', 'CURRENTDAY', 'CURRENTDAY2', 'CURRENTDAYNAME', 'CURRENTDOW', 'CURRENTHOUR',
+ 'CURRENTMONTH', 'CURRENTMONTH2', 'CURRENTMONTH1', 'CURRENTMONTHABBREV', 'CURRENTMONTHNAME',
+ 'CURRENTMONTHNAMEGEN', 'CURRENTTIME', 'CURRENTTIMESTAMP', 'CURRENTVERSION', 'CURRENTWEEK',
+ 'CURRENTYEAR', 'DIRECTIONMARK', 'DIRMARK', 'FULLPAGENAME', 'FULLPAGENAMEE', 'LOCALDAY',
+ 'LOCALDAY2', 'LOCALDAYNAME', 'LOCALDOW', 'LOCALHOUR', 'LOCALMONTH', 'LOCALMONTH2',
+ 'LOCALMONTH1', 'LOCALMONTHABBREV', 'LOCALMONTHNAME', 'LOCALMONTHNAMEGEN', 'LOCALTIME',
+ 'LOCALTIMESTAMP', 'LOCALWEEK', 'LOCALYEAR', 'NAMESPACE', 'NAMESPACEE', 'NAMESPACENUMBER',
+ 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS', 'NUMBEROFARTICLES', 'NUMBEROFEDITS',
+ 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS', 'PAGELANGUAGE', 'PAGENAME', 'PAGENAMEE',
+ 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH', 'REVISIONMONTH1',
+ 'REVISIONSIZE', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME',
+ 'ROOTPAGENAMEE', 'SITENAME', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE',
+ 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE',
+ 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE',
+ }
+ parser_functions_i = {
+ 'ANCHORENCODE', 'BIDI', 'CANONICALURL', 'CANONICALURLE', 'FILEPATH', 'FORMATNUM',
+ 'FULLURL', 'FULLURLE', 'GENDER', 'GRAMMAR', 'INT', r'\#LANGUAGE', 'LC', 'LCFIRST', 'LOCALURL',
+ 'LOCALURLE', 'NS', 'NSE', 'PADLEFT', 'PADRIGHT', 'PAGEID', 'PLURAL', 'UC', 'UCFIRST',
+ 'URLENCODE',
+ }
+ parser_functions = {
+ 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'DEFAULTSORT', 'DEFAULTSORTKEY',
+ 'DEFAULTCATEGORYSORT', 'FULLPAGENAME', 'FULLPAGENAMEE', 'NAMESPACE', 'NAMESPACEE',
+ 'NAMESPACENUMBER', 'NUMBERINGROUP', 'NUMINGROUP', 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS',
+ 'NUMBEROFARTICLES', 'NUMBEROFEDITS', 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS',
+ 'PAGENAME', 'PAGENAMEE', 'PAGESINCATEGORY', 'PAGESINCAT', 'PAGESIZE', 'PROTECTIONEXPIRY',
+ 'PROTECTIONLEVEL', 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH',
+ 'REVISIONMONTH1', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME',
+ 'ROOTPAGENAMEE', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE',
+ 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE',
+ 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE',
+ 'INT', 'DISPLAYTITLE', 'PAGESINNAMESPACE', 'PAGESINNS',
+ }
+
+ tokens = {
+ 'root': [
+ # Redirects
+ (r"""(?xi)
+ (\A\s*?)(\#REDIRECT:?) # may contain a colon
+ (\s+)(\[\[) (?=[^\]\n]* \]\]$)
+ """,
+ bygroups(Whitespace, Keyword, Whitespace, Punctuation), 'redirect-inner'),
+ # Subheadings
+ (r'^(={2,6})(.+?)(\1)(\s*$\n)',
+ bygroups(Generic.Subheading, Generic.Subheading, Generic.Subheading, Whitespace)),
+ # Headings
+ (r'^(=.+?=)(\s*$\n)',
+ bygroups(Generic.Heading, Whitespace)),
+ # Double-slashed magic words
+ (words(double_slashes_i, prefix=r'(?i)'), Name.Function.Magic),
+ (words(double_slashes), Name.Function.Magic),
+ # Raw URLs
+ (r'(?i)\b(?:{}){}{}*'.format('|'.join(protocols),
+ link_address, link_char_class), Name.Label),
+ # Magic links
+ (rf'\b(?:RFC|PMID){nbsp_char}+[0-9]+\b',
+ Name.Function.Magic),
+ (r"""(?x)
+ \bISBN {nbsp_char}
+ (?: 97[89] {nbsp_dash}? )?
+ (?: [0-9] {nbsp_dash}? ){{9}} # escape format()
+ [0-9Xx]\b
+ """.format(nbsp_char=nbsp_char, nbsp_dash=f'(?:-|{nbsp_char})'), Name.Function.Magic),
+ include('list'),
+ include('inline'),
+ include('text'),
+ ],
+ 'redirect-inner': [
+ (r'(\]\])(\s*?\n)', bygroups(Punctuation, Whitespace), '#pop'),
+ (r'(\#)([^#]*?)', bygroups(Punctuation, Name.Label)),
+ (rf'(?i)[{title_char}]+', Name.Tag),
+ ],
+ 'list': [
+ # Description lists
+ (r'^;', Keyword, 'dt'),
+ # Ordered lists, unordered lists and indents
+ (r'^[#:*]+', Keyword),
+ # Horizontal rules
+ (r'^-{4,}', Keyword),
+ ],
+ 'inline': [
+ # Signatures
+ (r'~{3,5}', Keyword),
+ # Entities
+ include('entity'),
+ # Bold & italic
+ (r"('')(''')(?!')", bygroups(Generic.Emph,
+ Generic.EmphStrong), 'inline-italic-bold'),
+ (r"'''(?!')", Generic.Strong, 'inline-bold'),
+ (r"''(?!')", Generic.Emph, 'inline-italic'),
+ # Comments & parameters & templates
+ include('replaceable'),
+ # Media links
+ (
+ r"""(?xi)
+ (\[\[)
+ (File|Image) (:)
+ ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | )*)
+ (?: (\#) ([{}]*?) )?
+ """.format(title_char, f'{title_char}#'),
+ bygroups(Punctuation, Name.Namespace, Punctuation,
+ using(this, state=['wikilink-name']), Punctuation, Name.Label),
+ 'medialink-inner'
+ ),
+ # Wikilinks
+ (
+ r"""(?xi)
+ (\[\[)(?!{}) # Should not contain URLs
+ (?: ([{}]*) (:))?
+ ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | )*?)
+ (?: (\#) ([{}]*?) )?
+ (\]\])
+ """.format('|'.join(protocols), title_char.replace('/', ''),
+ title_char, f'{title_char}#'),
+ bygroups(Punctuation, Name.Namespace, Punctuation,
+ using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation)
+ ),
+ (
+ r"""(?xi)
+ (\[\[)(?!{})
+ (?: ([{}]*) (:))?
+ ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | )*?)
+ (?: (\#) ([{}]*?) )?
+ (\|)
+ """.format('|'.join(protocols), title_char.replace('/', ''),
+ title_char, f'{title_char}#'),
+ bygroups(Punctuation, Name.Namespace, Punctuation,
+ using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation),
+ 'wikilink-inner'
+ ),
+ # External links
+ (
+ r"""(?xi)
+ (\[)
+ ((?:{}) {} {}*)
+ (\s*)
+ """.format('|'.join(protocols), link_address, link_char_class),
+ bygroups(Punctuation, Name.Label, Whitespace),
+ 'extlink-inner'
+ ),
+ # Tables
+ (r'^(:*)(\s*?)(\{\|)([^\n]*)$', bygroups(Keyword,
+ Whitespace, Punctuation, using(this, state=['root', 'attr'])), 'table'),
+ # HTML tags
+ (r'(?i)(<)({})\b'.format('|'.join(html_tags)),
+ bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'),
+ (r'(?i)()({})\b(\s*)(>)'.format('|'.join(html_tags)),
+ bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
+ #
+ (r'(?i)(<)(nowiki)\b', bygroups(Punctuation,
+ Name.Tag), ('tag-nowiki', 'tag-inner')),
+ #
+ (r'(?i)(<)(pre)\b', bygroups(Punctuation,
+ Name.Tag), ('tag-pre', 'tag-inner')),
+ #
+ (r'(?i)(<)(categorytree)\b', bygroups(
+ Punctuation, Name.Tag), ('tag-categorytree', 'tag-inner')),
+ #
+ (r'(?i)(<)(hiero)\b', bygroups(Punctuation,
+ Name.Tag), ('tag-hiero', 'tag-inner')),
+ #