Files
discord-syntax-highlighter/main.py

57 lines
1.5 KiB
Python
Raw Normal View History

2026-03-19 10:12:47 +11:00
def split_by_space(line):
token: str = ""
tokens: list[str] = []
isString = False
for char in line:
if isString:
if char == "\"":
isString = False
continue
token += char
continue
match char:
case "\"" | "\'":
token = "?"
isString = True
case " ":
if token == "":
if tokens == []:
token += " "
continue
tokens.append(token)
token = ""
case _:
token += char
if tokens != "":
tokens.append(token)
return tokens
def get_color(arg: str):
match arg[0]:
# ? preceds a string
case '?':
return f"\033[32m\"{arg[1:]}\"\033[0m"
case '$' | '&' | '!' | '-':
return f"\033[34m{arg[0]}\033[0m{arg[1:]}"
case '%':
return f"\033[33m{arg[0]}\033[0m{arg[1:]}"
case '@':
return f"\033[33m{arg}\033[0m"
case _:
return f"\033[35m{arg}\033[0m"
def highlight_text(code: str):
print("```ansi")
lines = code.split("\n")
for line in lines:
args = split_by_space(line)
if args == ['']:
print()
continue
for arg in args:
print(get_color(arg), end=" ")
print()
print("```")
highlight_text("@label\n\n set &str \"Hello, world!\"\n println $str\n jump %label")