initial commit

This commit is contained in:
2025-11-12 19:19:45 +08:00
commit 558834975e
5 changed files with 781 additions and 0 deletions

72
term_color_md/__init__.py Normal file
View File

@@ -0,0 +1,72 @@
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import re
from termcolor import colored
def render(text):
lines = text.splitlines()
formatted_text = ""
in_code_block = False
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")
continue
# Check for headers
if line.startswith("# "):
# level = len(line) - len(line.lstrip("#"))
header_text = line.strip() #.lstrip("#").strip()
formatted_text += colored(header_text, "blue", attrs=["bold", "underline"]) + "\n"
continue
if line.startswith("## "):
# level = len(line) - len(line.lstrip("#"))
header_text = line.strip() #.lstrip("#").strip()
formatted_text += colored(header_text, "blue", attrs=["bold"]) + "\n"
continue
if line.startswith("### "):
# level = len(line) - len(line.lstrip("#"))
header_text = line.strip() #.lstrip("#").strip()
formatted_text += colored(header_text, "cyan", attrs=["bold"]) + "\n"
continue
# Check for blockquotes
if line.startswith(">"):
quote_text = line.strip() #.lstrip(">").strip()
formatted_text += colored(quote_text, "yellow") + "\n"
continue
# Check for tables (rows separated by "|")
if "|" in line:
table_row = "\t| ".join(line.split("|")).strip()
formatted_text += table_row + "\n"
continue
# Inline formatting for bold, italic, and code (keeping the symbols)
# Bold (**text** or __text__)
line = re.sub(r"[^\*_](\*\*|__)(.+?)(\*\*|__)[^\*_]", lambda m: colored(m.group(), attrs=["bold"]), line)
# Italic (*text* or _text_)
line = re.sub(r"[^\*_](\*|_)([^\*_].+?[^\*_])(\*|_)[^\*_]", lambda m: colored(m.group(), attrs=["underline"]), line)
# Inline code (`code`)
line = re.sub(r"[^\*_](`)(.+?)`[^\*_]", lambda m: colored(m.group() + "`", "green"), line)
# List items (bullets and numbers)
# Bulleted list
line = re.sub(r"^(\s*[-*])\s", lambda m: colored(m.group(1), "cyan") + " ", line)
# Numbered list
line = re.sub(r"^(\s*\d+\.)\s", lambda m: colored(m.group(1), "cyan") + " ", line)
# Add processed line to formatted text
formatted_text += line + "\n"
return formatted_text