From 0ad435896077f4e25c20222ce5c5e7208c6f77f9 Mon Sep 17 00:00:00 2001 From: Mohammed Rabil Date: Wed, 20 Dec 2023 12:33:57 +0530 Subject: [PATCH] Refactor markdown header formatting in html_format.py --- gemini_pro_bot/html_format.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/gemini_pro_bot/html_format.py b/gemini_pro_bot/html_format.py index 9b5fe57..42e71c3 100644 --- a/gemini_pro_bot/html_format.py +++ b/gemini_pro_bot/html_format.py @@ -34,8 +34,8 @@ def apply_italic(text: str) -> str: def apply_code(text: str) -> str: """Replace markdown code ``` with HTML code tags.""" - pattern = r"```[\w]*\n((?:.|[\n])*?)\n```" - replaced_text = re.sub(pattern, r"
\1
", text) + pattern = r"```([\w]*?)\n([\s\S]*?)```" + replaced_text = re.sub(pattern, r"
\2
", text, flags=re.DOTALL) return replaced_text @@ -69,9 +69,18 @@ def apply_strikethrough(text: str) -> str: def apply_header(text: str) -> str: """Replace markdown header # with HTML header tags.""" - pattern = r"#{2,6} (.*)" - replaced_text = re.sub(pattern, r"\1", text) - return replaced_text + lines = text.split('\n') + in_code_block = False + + for i, line in enumerate(lines): + if line.startswith('```'): + in_code_block = not in_code_block + + if not in_code_block: + pattern = r"^(#{1,6})\s+(.*)" + lines[i] = re.sub(pattern, r"\2", line, flags=re.DOTALL) + + return '\n'.join(lines) def format_message(message: str) -> str: @@ -86,4 +95,4 @@ def format_message(message: str) -> str: message = apply_strikethrough(message) message = apply_monospace(message) message = apply_hand_points(message) - return message + return message \ No newline at end of file