added syntax highlighting in code blocks using pygments
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
BIN
term_color_md/__pycache__/__init__.cpython-311.pyc
Normal file
BIN
term_color_md/__pycache__/__init__.cpython-311.pyc
Normal file
Binary file not shown.
Reference in New Issue
Block a user