added syntax highlighting in code blocks using pygments
This commit is contained in:
parent
558834975e
commit
5f3175379b
|
|
@ -19,4 +19,5 @@ requires-python = ">=3.9"
|
||||||
# Dependencies that your package needs at install‑time
|
# Dependencies that your package needs at install‑time
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"termcolor>=3.1.0",
|
"termcolor>=3.1.0",
|
||||||
|
"pygments>=2.12",
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -6,19 +6,48 @@
|
||||||
|
|
||||||
import re
|
import re
|
||||||
from termcolor import colored
|
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):
|
def render(text):
|
||||||
lines = text.splitlines()
|
lines = text.splitlines()
|
||||||
formatted_text = ""
|
formatted_text = ""
|
||||||
in_code_block = False
|
in_code_block = False
|
||||||
|
|
||||||
|
# Track code block state
|
||||||
|
code_block_lang = None
|
||||||
|
code_block_lines: list[str] = []
|
||||||
for line in lines:
|
for line in lines:
|
||||||
# Check for code blocks
|
# Check for code blocks (opening/closing)
|
||||||
if line.startswith("```"):
|
if line.lstrip().startswith("```"):
|
||||||
in_code_block = not in_code_block
|
# Opening or closing
|
||||||
continue # Skip the line with ```
|
if not in_code_block: # opening
|
||||||
elif in_code_block:
|
formatted_text += colored(line.strip(), "light_grey") + "\n"
|
||||||
formatted_text += colored(line + "\n", "green")
|
# 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
|
continue
|
||||||
|
|
||||||
# Check for headers
|
# Check for headers
|
||||||
|
|
@ -70,3 +99,4 @@ def render(text):
|
||||||
formatted_text += line + "\n"
|
formatted_text += line + "\n"
|
||||||
|
|
||||||
return formatted_text
|
return formatted_text
|
||||||
|
|
||||||
|
|
|
||||||
Binary file not shown.
Loading…
Reference in New Issue