"""Markdown Parser Utilities""" import re from typing import List, Dict, Optional, Tuple from dataclasses import dataclass from pathlib import Path @dataclass class CodeBlock: """Represents a code block in markdown""" language: str content: str start_line: int end_line: int @dataclass class MarkdownHeading: """Represents a heading in markdown""" level: int text: str line: int class MarkdownParser: """Parse and process markdown files""" def __init__(self, content: Optional[str] = None): self.content = content or "" def parse(self, content: str) -> "MarkdownParser": """Parse content and return self""" self.content = content return self def extract_code_blocks(self) -> List[CodeBlock]: """Extract all code blocks""" pattern = r"```(\w*)\n([\s\S]*?)```" blocks = [] for match in re.finditer(pattern, self.content): blocks.append( CodeBlock( language=match.group(1), content=match.group(2).rstrip(), start_line=self.content[:match.start()].count("\n") + 1, end_line=self.content[:match.end()].count("\n") + 1, ) ) return blocks def extract_headings(self) -> List[MarkdownHeading]: """Extract all headings""" pattern = r"^(#{1,6})\s+(.+)$" headings = [] for i, line in enumerate(self.content.split("\n"), 1): match = re.match(pattern, line.strip()) if match: headings.append( MarkdownHeading( level=len(match.group(1)), text=match.group(2), line=i, ) ) return headings def extract_links(self) -> List[Tuple[str, str]]: """Extract all markdown links""" pattern = r"\[([^\]]+)\]\(([^\)]+)\)" return [(title, url) for title, url in re.findall(pattern, self.content)] def extract_images(self) -> List[Tuple[str, str]]: """Extract all markdown images""" pattern = r"!\[([^\]]*)\]\(([^\)]+)\)" return [(alt, url) for alt, url in re.findall(pattern, self.content)] def extract_tables(self) -> List[List[List[str]]]: """Extract all tables""" lines = self.content.split("\n") tables = [] in_table = False current_table: List[List[str]] = [] alignment: List[str] = [] for line in lines: if re.match(r"\|.*\|$", line.strip()): if re.match(r"\|[-:\s]+\|$", line.strip()): alignment = [ "left" if ":" in c and c.count(":") == 1 and c.strip().startswith(":") else "right" if ":" in c and c.count(":") == 1 and c.strip().endswith(":") else "center" if ":" in c and c.count(":") == 2 else "left" for c in line.strip().split("|")[1:-1] ] tables.append(current_table) current_table = [] in_table = False continue in_table = True row = [cell.strip() for cell in line.strip().split("|")[1:-1]] current_table.append(row) else: if in_table and current_table: tables.append(current_table) current_table = [] in_table = False if current_table: tables.append(current_table) return tables def extract_lists(self) -> Dict[str, List[str]]: """Extract all lists""" ordered: List[str] = [] unordered: List[str] = [] for line in self.content.split("\n"): ordered_match = re.match(r"^\d+\.\s+(.+)$", line.strip()) if ordered_match: ordered.append(ordered_match.group(1)) continue unordered_match = re.match(r"^[-*+]\s+(.+)$", line.strip()) if unordered_match: unordered.append(unordered_match.group(1)) return {"ordered": ordered, "unordered": unordered} def get_table_of_contents(self) -> List[Dict[str, Any]]: """Get table of contents from headings""" toc = [] for heading in self.extract_headings(): toc.append( { "level": heading.level, "text": heading.text, "line": heading.line, } ) return toc def convert_to_plain_text(self) -> str: """Strip markdown formatting for plain text""" text = self.content text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"`([^`]+)`", r"\1", text) text = re.sub(r"!\[([^\]]*)\]\([^\)]+\)", r"\1", text) text = re.sub(r"\[([^\]]+)\]\([^\)]+\)", r"\1", text) text = re.sub(r"^#{1,6}\s+", "", text, flags=re.MULTILINE) text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) text = re.sub(r"\*([^*]+)\*", r"\1", text) text = re.sub(r"__([^_]+)__", r"\1", text) text = re.sub(r"_([^_]+)_", r"\1", text) return text def search(self, query: str, case_sensitive: bool = False) -> List[Dict[str, Any]]: """Search for text in markdown""" results = [] if not case_sensitive: search_content = self.content.lower() query = query.lower() else: search_content = self.content for i, line in enumerate(search_content.split("\n"), 1): if query in line: results.append({"line": i, "content": line.strip()}) return results @classmethod def from_file(cls, file_path: str) -> "MarkdownParser": """Create parser from file""" content = Path(file_path).read_text(encoding="utf-8") return cls(content)