File size: 6,080 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""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)