added syntax highlighting in code blocks using pygments

This commit is contained in:
Ian Griffin 2025-11-12 20:10:00 +08:00
parent 558834975e
commit 5f3175379b
3 changed files with 37 additions and 6 deletions

View File

@ -19,4 +19,5 @@ requires-python = ">=3.9"
# Dependencies that your package needs at installtime
dependencies = [
"termcolor>=3.1.0",
"pygments>=2.12",
]

View File

@ -6,19 +6,48 @@
import re
from termcolor import colored
from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
from pygments.formatters import Terminal256Formatter
def render(text):
lines = text.splitlines()
formatted_text = ""
in_code_block = False
# Track code block state
code_block_lang = None
code_block_lines: list[str] = []
for line in lines:
# Check for code blocks
if line.startswith("```"):
in_code_block = not in_code_block
continue # Skip the line with ```
elif in_code_block:
formatted_text += colored(line + "\n", "green")
# Check for code blocks (opening/closing)
if line.lstrip().startswith("```"):
# Opening or closing
if not in_code_block: # opening
formatted_text += colored(line.strip(), "light_grey") + "\n"
# Extract optional language
match = re.match(r"^\s*```\s*(\w+)?", line)
if match:
code_block_lang = match.group(1)
else:
code_block_lang = None
in_code_block = True
code_block_lines = []
continue # Skip fence line
else: # closing
# Highlight accumulated code
code_source = "\n".join(code_block_lines)
if code_source:
lexer = get_lexer_by_name(code_block_lang, stripall=True) if code_block_lang else TextLexer()
highlighted = highlight(code_source, lexer, Terminal256Formatter())
formatted_text += highlighted
formatted_text += colored(line.strip(), "light_grey") + "\n"
in_code_block = False
code_block_lang = None
code_block_lines = []
continue
# Inside code block: accumulate lines
if in_code_block:
code_block_lines.append(line)
continue
# Check for headers
@ -70,3 +99,4 @@ def render(text):
formatted_text += line + "\n"
return formatted_text

Binary file not shown.