From f997f1e39aae2a46423d380a6a21b4b6dd0f1af2 Mon Sep 17 00:00:00 2001
From: David Rotermund <54365609+davrot@users.noreply.github.com>
Date: Fri, 19 May 2023 14:50:36 +0200
Subject: [PATCH] Add files via upload
---
python_code_highlighter.py | 91 ++++++++++++++++++++++++++++++++++++++
1 file changed, 91 insertions(+)
create mode 100644 python_code_highlighter.py
diff --git a/python_code_highlighter.py b/python_code_highlighter.py
new file mode 100644
index 0000000..1b416e6
--- /dev/null
+++ b/python_code_highlighter.py
@@ -0,0 +1,91 @@
+from pygments import highlight
+from pygments.lexers import PythonLexer
+from pygments.formatter import Formatter
+import html
+import argh
+
+
+class NullFormatter(Formatter):
+ def format(self, tokensource, outfile):
+ for ttype, value in tokensource:
+ escape_it: bool = True
+ if str(ttype).startswith("Token.Literal.String"):
+ start: str = ''
+ end: str = ""
+
+ elif str(ttype).startswith("Token.Comment"):
+ start: str = ''
+ end: str = ""
+
+ elif str(ttype).startswith("Token.Operator"):
+ start: str = ''
+ end: str = ""
+
+ elif str(ttype).startswith("Token.Keyword"):
+ start: str = ''
+ end: str = ""
+
+ elif str(ttype).startswith("Token.Name.Builtin"):
+ start: str = ''
+ end: str = ""
+
+ elif str(ttype).startswith("Token.Name"):
+ start: str = ''
+ end: str = ""
+
+ elif str(ttype) == "Token.Text":
+ if (len(value) == 1) and (value[0] == "\n"):
+ value = str("
")
+ start: str = ""
+ end: str = ""
+ escape_it = False
+ else:
+ start: str = ""
+ end: str = ""
+
+ all_space: bool = True
+ for i in range(0, len(value)):
+ if value[0] != " ":
+ all_space = False
+ break
+
+ if all_space is True:
+ replace_length: int = len(value)
+ escape_it = False
+
+ value = ""
+ for _ in range(0, replace_length):
+ value += str(" ")
+
+ else:
+ start: str = ""
+ end: str = ""
+
+ outfile.write(start)
+ if escape_it is True:
+ outfile.write(html.escape(value))
+ outfile.write(str(" "))
+ else:
+ outfile.write(value)
+ outfile.write(end)
+
+
+def main(filename: str):
+ assert len(filename) > 0
+
+ with open(filename, "r") as file:
+ code = file.readlines()
+
+ line_count: int = 0
+ output: str = str("
") + for code_line in code: + output += highlight(code_line, PythonLexer(), NullFormatter()) + line_count += 1 + + output += str("") + + print(output) + + +if __name__ == "__main__": + argh.dispatch_command(main)