diff --git a/pyproject.toml b/pyproject.toml index 6deab98..b1d31b7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,4 +19,5 @@ requires-python = ">=3.9" # Dependencies that your package needs at install‑time dependencies = [ "termcolor>=3.1.0", + "pygments>=2.12", ] diff --git a/term_color_md/__init__.py b/term_color_md/__init__.py index 2a8ac9f..87740f8 100644 --- a/term_color_md/__init__.py +++ b/term_color_md/__init__.py @@ -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 + diff --git a/term_color_md/__pycache__/__init__.cpython-311.pyc b/term_color_md/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..670c634 Binary files /dev/null and b/term_color_md/__pycache__/__init__.cpython-311.pyc differ