Syntax highlighting using Mediawiki formatting: Difference between revisions
Content added Content deleted
m (replaced task sub-headings) |
m (→{{header|Python}}: Handle indentation in the formatter and set formatter name and aliases .) |
||
Line 458: | Line 458: | ||
'''from''' html '''import''' escape |
'''from''' html '''import''' escape |
||
'''from''' textwrap '''import''' indent |
'''from''' textwrap '''import''' indent |
||
'''from''' io '''import''' StringIO |
|||
'''from''' pygments '''import''' highlight |
'''from''' pygments '''import''' highlight |
||
Line 468: | Line 469: | ||
'''class''' MediaWikiFormatter(Formatter): |
'''class''' MediaWikiFormatter(Formatter): |
||
''"""Format source code using MediaWiki markup."""'' |
''"""Format source code using MediaWiki markup."""'' |
||
⚫ | |||
aliases = ["mediawiki", "wiki"] |
|||
filenames = [] |
|||
'''def''' __init__(self, **options): |
'''def''' __init__(self, **options): |
||
super().__init__(**options) |
super().__init__(**options) |
||
self.indent = options.get("indent", " ") |
|||
self.styles = { |
self.styles = { |
||
Line 480: | Line 486: | ||
'''def''' format(self, token_source, outfile): |
'''def''' format(self, token_source, outfile): |
||
⚫ | |||
last_val = "" |
last_val = "" |
||
last_type = '''None''' |
last_type = '''None''' |
||
Line 494: | Line 501: | ||
'''if''' last_val: |
'''if''' last_val: |
||
style_begin, style_end = self.styles[last_type] |
style_begin, style_end = self.styles[last_type] |
||
buffer.write(style_begin + last_val + style_end) |
|||
last_val = value |
last_val = value |
||
Line 502: | Line 509: | ||
'''if''' last_val: |
'''if''' last_val: |
||
style_begin, style_end = self.styles[last_type] |
style_begin, style_end = self.styles[last_type] |
||
buffer.write(style_begin + last_val + style_end) |
|||
''# Write indented lines to the output file.'' |
|||
outfile.write( |
|||
⚫ | |||
buffer.getvalue(), |
|||
⚫ | |||
⚫ | |||
⚫ | |||
) |
|||
Line 517: | Line 533: | ||
'''def''' main(language_name="python", infile='''None'''): |
'''def''' main(language_name="python", infile='''None'''): |
||
formatter = MediaWikiFormatter( |
formatter = MediaWikiFormatter() |
||
lexer = get_lexer_by_name(language_name) |
lexer = get_lexer_by_name(language_name) |
||
lexer.add_filter(HTMLEscapeFilter()) |
lexer.add_filter(HTMLEscapeFilter()) |
||
'''with''' open(infile or __file__) '''as''' fd: |
'''with''' open(infile or __file__) '''as''' fd: |
||
print( |
print(highlight(fd.read(), lexer, formatter), end="") |
||
⚫ | |||
highlight(fd.read(), lexer, formatter), |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||