Files
discord-syntax-highlighter/main.py

82 lines
2.0 KiB
Python
Raw Normal View History

2026-03-19 13:40:54 +11:00
def split_by_space(line: str):
2026-03-19 10:12:47 +11:00
token: str = ""
tokens: list[str] = []
isString = False
2026-03-19 13:40:54 +11:00
isComment = False
2026-03-19 10:12:47 +11:00
for char in line:
if isString:
if char == "\"":
isString = False
continue
token += char
continue
2026-03-19 13:40:54 +11:00
if isComment:
token += char
continue
2026-03-19 10:12:47 +11:00
match char:
2026-03-19 13:40:54 +11:00
case "#":
isComment = True
token += char
2026-03-19 10:12:47 +11:00
case "\"" | "\'":
token = "?"
isString = True
case " ":
if token == "":
if tokens == []:
token += " "
continue
tokens.append(token)
token = ""
case _:
token += char
2026-03-19 13:40:54 +11:00
if token != "":
2026-03-19 10:12:47 +11:00
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"
2026-03-19 13:40:54 +11:00
case '#':
return f"\033[30m{arg}\033[0m"
2026-03-19 10:12:47 +11:00
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("```")
2026-03-19 13:40:54 +11:00
if __name__ == "__main__":
highlight_text(
"""# A cool list
setlist &favWords "hello" "there" "general"
listappend &favWords "kenobi"
println $favWords
set &count 0
set &passedThrough true
@jmpbck
getlistat &favWords $count &tmp
println $tmp
add $count 1 &count
getlistsize &favWords &tmp2
inequal $count $tmp2 &tmp3 #comment
if $tmp3 %jmpbck""")