""" Markdown to Plain Text Converter Converts Markdown formatting to user-friendly plain text """ import re from typing import Optional class MarkdownConverter: """Converts Markdown to plain text for copy/download""" def __init__(self): # Compile regex patterns for efficiency self.patterns = { # Headers: # Header → Header (with underline for H1) 'header': [ (re.compile(r'^#{6}\s+(.+)$', re.MULTILINE), r'\1'), # H6 (re.compile(r'^#{5}\s+(.+)$', re.MULTILINE), r'\1'), # H5 (re.compile(r'^#{4}\s+(.+)$', re.MULTILINE), r'\1'), # H4 (re.compile(r'^#{3}\s+(.+)$', re.MULTILINE), r'\1'), # H3 (re.compile(r'^#{2}\s+(.+)$', re.MULTILINE), r'\1'), # H2 (re.compile(r'^#{1}\s+(.+)$', re.MULTILINE), r'\1\n' + '=' * 50), # H1 with underline ], # Bold/Italic: **bold** → bold, *italic* → italic 'bold_italic': [ (re.compile(r'\*\*\*(.+?)\*\*\*'), r'\1'), # ***bold italic*** (re.compile(r'\*\*(.+?)\*\*'), r'\1'), # **bold** (re.compile(r'\*(.+?)\*'), r'\1'), # *italic* (re.compile(r'_(.+?)_'), r'\1'), # _italic_ ], # Code: `code` → "code", ```code``` → code block 'code': [ (re.compile(r'```(?:\w+)?\n?(.*?)\n?```', re.DOTALL), r'\1'), # Code blocks (re.compile(r'`([^`]+)`'), r'"\1"'), # Inline code ], # Lists: - item → • item, 1. item → 1. item 'lists': [ (re.compile(r'^[\s]*[-*+]\s+(.+)$', re.MULTILINE), r'• \1'), # Bullet lists # Numbered lists keep numbers ], # Links: [text](url) → text (url) 'links': [ (re.compile(r'\[([^\]]+)\]\(([^)]+)\)'), r'\1 (\2)'), ], # Images: ![alt](src) → [Image: alt] 'images': [ (re.compile(r'!\[([^\]]*)\]\(([^)]+)\)'), r'[Image: \1]'), ], # Blockquotes: > quote → "quote" 'blockquotes': [ (re.compile(r'^>\s+(.+)$', re.MULTILINE), r'"\1"'), ], # Horizontal rules: --- → ---------- 'horizontal_rules': [ (re.compile(r'^[-*_]{3,}\s*$', re.MULTILINE), '-' * 50), ], # Tables: | Header | → Header (tab-separated) 'tables': self._convert_table, } def _convert_table(self, text: str) -> str: """Convert Markdown tables to plain text""" lines = text.split('\n') if not lines or '|' not in lines[0]: return text # Find table rows table_rows = [] for line in lines: if '|' in line and not re.match(r'^\|?[-:|]+\|?$', line): # Extract cells, remove leading/trailing | cells = [cell.strip() for cell in line.split('|') if cell.strip()] table_rows.append(cells) if not table_rows: return text # Convert to plain text (tab-separated) plain_rows = [] for row in table_rows: plain_rows.append('\t'.join(row)) return '\n'.join(plain_rows) def to_plain_text(self, markdown_text: str) -> str: """ Convert Markdown to user-friendly plain text """ if not markdown_text: return '' text = markdown_text # Apply conversions in order conversion_order = [ 'code', # Code first (preserve content) 'links', # Links before bold/italic 'images', # Images 'bold_italic', # Bold/italic 'header', # Headers 'lists', # Lists 'blockquotes', # Blockquotes 'horizontal_rules', # Horizontal rules ] for pattern_type in conversion_order: if pattern_type == 'tables': # Tables need special handling text = self._convert_table(text) else: patterns = self.patterns.get(pattern_type, []) for pattern, replacement in patterns: text = pattern.sub(replacement, text) # Clean up extra whitespace text = re.sub(r'\n{3,}', '\n\n', text) # Max 2 blank lines text = text.strip() return text def to_rich_text(self, markdown_text: str) -> str: """ Convert Markdown to rich text (preserves some formatting) Returns text with minimal markup """ if not markdown_text: return '' text = markdown_text # Keep only essential formatting # Headers: Add underline for H1 text = re.sub(r'^#\s+(.+)$', r'\1\n' + '=' * 50, text, flags=re.MULTILINE) # Remove other header markers for i in range(2, 7): text = re.sub(r'^' + '#' * i + r'\s+(.+)$', r'\1', text, flags=re.MULTILINE) # Convert bold/italic to uppercase for emphasis text = re.sub(r'\*\*(.+?)\*\*', r'\1', text) text = re.sub(r'\*(.+?)\*', r'\1', text) # Convert code blocks with indentation def indent_code(match): code = match.group(1) lines = code.split('\n') indented = [' ' + line for line in lines] return '\n'.join(indented) text = re.sub(r'```(?:\w+)?\n?(.*?)\n?```', indent_code, text, flags=re.DOTALL) # Inline code with quotes text = re.sub(r'`([^`]+)`', r'"\1"', text) # Bullet lists with • (keep) text = re.sub(r'^[\s]*[-*+]\s+(.+)$', r'• \1', text, flags=re.MULTILINE) # Remove link markup, keep text text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text) # Blockquotes with > text = re.sub(r'^>\s+(.+)$', r'"\1"', text, flags=re.MULTILINE) # Clean up text = re.sub(r'\n{3,}', '\n\n', text) text = text.strip() return text def get_formatting_summary(self, markdown_text: str) -> dict: """ Analyze Markdown content and return formatting summary """ if not markdown_text: return {} patterns = { 'headers': re.compile(r'^#{1,6}\s', re.MULTILINE), 'bold': re.compile(r'\*\*.+?\*\*'), 'italic': re.compile(r'\*.+?\*'), 'code_blocks': re.compile(r'```'), 'inline_code': re.compile(r'`[^`]+`'), 'lists': re.compile(r'^[\s]*[-*+]\s', re.MULTILINE), 'numbered_lists': re.compile(r'^[\s]*\d+[.)]\s', re.MULTILINE), 'links': re.compile(r'\[.+?\]\(.+?\)'), 'images': re.compile(r'!\[.+?\]\(.+?\)'), 'blockquotes': re.compile(r'^>\s', re.MULTILINE), 'tables': re.compile(r'^\|.+\|$', re.MULTILINE), } summary = {} for name, pattern in patterns.items(): matches = pattern.findall(markdown_text) summary[name] = len(matches) # Calculate formatting percentage total_chars = len(markdown_text) formatting_chars = 0 # Estimate formatting characters (markup) formatting_patterns = [ (r'#{1,6}\s', 2), # Headers: # + space (r'\*\*', 2), # Bold: ** (r'\*[^*]', 1), # Italic: * (r'```', 3), # Code blocks: ``` (r'`[^`]', 1), # Inline code: ` (r'\[.*?\]\(.*?\)', 4), # Links: []() (r'^>\s', 2), # Blockquotes: > + space (r'^\|', 1), # Tables: | ] for pattern, char_weight in formatting_patterns: matches = re.findall(pattern, markdown_text, re.MULTILINE) formatting_chars += len(matches) * char_weight if total_chars > 0: summary['formatting_percentage'] = round((formatting_chars / total_chars) * 100, 2) else: summary['formatting_percentage'] = 0 return summary # Create global instance markdown_converter = MarkdownConverter() # Helper functions def convert_for_copy(markdown_text: str) -> str: """Convert Markdown to plain text suitable for copying""" return markdown_converter.to_plain_text(markdown_text) def convert_for_display(markdown_text: str) -> str: """Convert Markdown to display-friendly text (keeps some formatting)""" return markdown_converter.to_rich_text(markdown_text) def analyze_formatting(markdown_text: str) -> dict: """Analyze Markdown formatting in text""" return markdown_converter.get_formatting_summary(markdown_text) # Test function def test_converter(): """Test the Markdown converter""" test_markdown = """# Project Report ## Executive Summary This **important** report contains *critical* data. ### Key Findings 1. Revenue increased by 25% 2. User engagement improved 3. Customer satisfaction is high ## Technical Details Use `print("hello")` in your code: ```python def calculate(): return 42 * 3.14 ``` Visit [our website](https://example.com) for more. > Note: All data is confidential. """ print("🧪 Testing Markdown to Plain Text Converter") print("=" * 60) print("\n📋 Original Markdown:") print(test_markdown) print("\n📝 Plain Text (for copy/download):") plain = convert_for_copy(test_markdown) print(plain) print("\n🎨 Rich Text (for display):") rich = convert_for_display(test_markdown) print(rich) print("\n📊 Formatting Analysis:") analysis = analyze_formatting(test_markdown) for key, value in analysis.items(): print(f" {key}: {value}") print("\n" + "=" * 60) print("✅ Converter test completed!") if __name__ == "__main__": test_converter()