syntax_colouring.py
Python script, ASCII text executable
1from pygments import highlight 2from pygments.style import Style 3from pygments import token 4from pygments.lexers import PythonLexer 5from pygments.formatters import HtmlFormatter 6from bs4 import BeautifulSoup 7 8 9class CustomStyle(Style): 10default_style = "" 11styles = { 12token.Text: "", 13token.Keyword: "bold #ff9800", 14token.Name: "", 15token.Operator: "", 16 17token.Name.Class: "#ffeb3b", 18token.Name.Function: "#be9ddb", 19token.Name.Builtin: "#ab47bc", 20token.Name.Attribute: "#4db6ac", 21token.Name.Constant: "italic #ef5350", 22token.Name.Decorator: "#bcaaa4", 23token.Name.Function.Magic: "#e040fb", 24token.Name.Label: "#ff4081", 25 26token.String: "#8bc34a", 27token.Number: "#42a5f5", 28token.Punctuation: "#ff9800", 29token.Comment: "italic #b0bec5", 30token.Generic: "", 31token.Escape: "#ff5722", 32token.String.Escape: "#ff5722", 33token.String.Regex: "#ffffff", 34token.Comment.Preproc: "#536dfe", 35token.Comment.Hashbang: "#536dfe", 36token.Error: "#f44336", 37token.Other: "", 38token.Whitespace: "", 39} 40 41 42code = """ 43___all___ = ["hello_world"] 44 45def interesting_function(func: Callable) -> Callable: 46\"\"\"Print the function's result when called. 47 48Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec nulla 49nec nulla laoreet fermentum. Integer id lacus ut odio interdum ultricies. 50\"\"\" 51def wrapper(*args, **kwargs): 52result = func(*args, **kwargs) # avoid double evaluation 53print(result) 54return result 55return wrapper 56 57@interesting_function 58def hello_world(): 59return "Hello, world!\\a" # a nice bell 60 61if __name__ == "__main__": 62hello_world() 63""" 64 65lexer = PythonLexer() 66formatter = HtmlFormatter(style="colorful") 67html_code = highlight(code, lexer, formatter) 68 69soup = BeautifulSoup(html_code, "html.parser") 70pre = soup.find("pre") 71lines = pre.decode_contents().splitlines() 72 73for line in lines: 74line_soup = BeautifulSoup(line, "html.parser") 75clean_line = line_soup.prettify() 76print(clean_line) 77