-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkdownTextSplitter.py
More file actions
1631 lines (1370 loc) · 58.9 KB
/
MarkdownTextSplitter.py
File metadata and controls
1631 lines (1370 loc) · 58.9 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Markdown Text Splitter for RAG Applications.
A production-ready Markdown text splitter with comprehensive syntax support,
designed for Retrieval-Augmented Generation (RAG) pipelines.
Features:
- Token-based chunk size control with configurable overlap (using tiktoken)
- Complete Markdown syntax support (tables, lists, blockquotes, code blocks)
- Alternative header syntax (underline style: === and ---)
- YAML frontmatter extraction to metadata
- Thread-safe implementation (safe for concurrent use)
- Semantic context preservation (keeps related content together)
- Intelligent sentence splitting with abbreviation handling
- Token-level fallback for edge cases (base64, minified JSON)
Example:
>>> from MarkdownTextSplitter import MarkdownTextSplitter, split_markdown
>>>
>>> # Using the class (chunk_size and chunk_overlap are in tokens)
>>> splitter = MarkdownTextSplitter(chunk_size=500, chunk_overlap=50)
>>> chunks = splitter.split_text(markdown_content)
>>>
>>> # Using the convenience function
>>> chunks = split_markdown(markdown_content, chunk_size=500)
Note:
For full YAML frontmatter support (lists, nested objects), install PyYAML:
``pip install pyyaml``
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Iterator
import tiktoken
from langchain_core.documents import Document
# Default tiktoken encoding (compatible with GPT-4, GPT-3.5-turbo, etc.)
TIKTOKEN_ENCODING = "cl100k_base"
if TYPE_CHECKING:
from typing import Any
__all__ = [
"MarkdownTextSplitter",
"split_markdown",
]
__version__ = "1.0.0"
# =============================================================================
# Internal Data Structures
# =============================================================================
@dataclass
class _ParserState:
"""Thread-safe parser state container.
Using a dataclass instead of instance variables ensures thread safety
since each call to split_text gets its own state instance.
"""
chunks: list[Document] = field(default_factory=list)
current_content: list[str] = field(default_factory=list)
header_stack: list[tuple[int, str, str]] = field(default_factory=list)
header_counts: dict[str, int] = field(
default_factory=dict
) # Track header occurrences
in_code_block: bool = False
code_fence: str = ""
code_fence_length: int = 0
code_language: str = ""
in_table: bool = False
table_content: list[str] = field(default_factory=list)
in_list: bool = False
list_content: list[str] = field(default_factory=list)
list_indent: int = 0
in_blockquote: bool = False
blockquote_content: list[str] = field(default_factory=list)
frontmatter_metadata: dict[str, str] = field(default_factory=dict)
# =============================================================================
# Main Splitter Class
# =============================================================================
class MarkdownTextSplitter:
"""A production-ready Markdown text splitter with comprehensive syntax support.
This splitter is designed for RAG (Retrieval-Augmented Generation) pipelines
and provides several advantages over basic text splitters:
1. **Token-based chunk size control**: Supports ``chunk_size`` and ``chunk_overlap``
parameters measured in tokens (using tiktoken) to prevent oversized chunks
that exceed LLM token limits.
2. **Complete Markdown support**: Properly handles tables, lists, blockquotes,
code blocks, and alternative header syntax.
3. **YAML frontmatter**: Extracts frontmatter metadata and propagates it
to all chunks for filtering and context.
4. **Thread-safe**: Uses local state instead of instance variables during
parsing, allowing safe concurrent use in web applications.
5. **Semantic preservation**: Keeps related content together (e.g., table rows,
list items) and provides rich metadata for context reconstruction.
6. **Intelligent splitting**: Uses paragraph -> sentence -> word -> token
fallback chain with abbreviation-aware sentence detection.
Attributes:
chunk_size: Maximum chunk size in tokens (None for header-only splits).
chunk_overlap: Number of tokens to overlap between chunks.
encoding_name: Tiktoken encoding name (default: cl100k_base).
strip_headers: Whether to exclude headers from chunk content.
preserve_frontmatter: Whether to extract YAML frontmatter as metadata.
keep_separator: Whether to keep horizontal rules in output.
semantic_chunking: Whether to keep semantic units together.
Example:
>>> splitter = MarkdownTextSplitter(
... chunk_size=500,
... chunk_overlap=50,
... headers_to_split_on=[
... ("#", "title"),
... ("##", "section"),
... ]
... )
>>> chunks = splitter.split_text(markdown_text)
>>> for chunk in chunks:
... print(chunk.metadata) # Contains header hierarchy
"""
# -------------------------------------------------------------------------
# Class-level compiled regex patterns for performance
# -------------------------------------------------------------------------
_HEADER_PATTERN = re.compile(r"^(#{1,6})\s+(.+)$")
_ALT_HEADER_1_PATTERN = re.compile(r"^=+\s*$")
_ALT_HEADER_2_PATTERN = re.compile(r"^-+\s*$")
_CODE_FENCE_PATTERN = re.compile(r"^(`{3,}|~{3,})(.*)$")
_HORIZONTAL_RULE_PATTERN = re.compile(r"^(\*{3,}|-{3,}|_{3,})\s*$")
_TABLE_ROW_PATTERN = re.compile(r"^\|.*\|.*$")
_TABLE_SEPARATOR_PATTERN = re.compile(r"^\|[\s\-:|]+\|$")
_LIST_ITEM_PATTERN = re.compile(r"^(\s*)([-*+]|\d+\.)\s+(.*)$")
_BLOCKQUOTE_PATTERN = re.compile(r"^(\s*>)+\s?(.*)$")
_FRONTMATTER_FENCE = re.compile(r"^-{3}\s*$")
_INLINE_CODE_PATTERN = re.compile(r"`[^`]+`")
# Common abbreviations that shouldn't trigger sentence splits
_ABBREVIATIONS = frozenset(
{
"mr",
"mrs",
"ms",
"dr",
"prof",
"sr",
"jr",
"vs",
"etc",
"inc",
"ltd",
"corp",
"eg",
"ie",
"al",
"cf",
"vol",
"no",
"fig",
"eq",
"dept",
"univ",
"est",
"approx",
"govt",
"avg",
"min",
"max",
}
)
# -------------------------------------------------------------------------
# Initialization
# -------------------------------------------------------------------------
def __init__(
self,
headers_to_split_on: list[tuple[str, str]] | None = None,
chunk_size: int | None = None,
chunk_overlap: int = 0,
encoding_name: str = TIKTOKEN_ENCODING,
strip_headers: bool = True,
preserve_frontmatter: bool = True,
keep_separator: bool = True,
semantic_chunking: bool = True,
deduplicate_headers: bool = False,
strict_mode: bool = False,
split_code_blocks: bool = False,
filter_separators: bool = False,
merge_small_chunks: bool = False,
min_chunk_size: int = 50,
isolate_code_blocks: bool = False,
isolate_tables: bool = False,
) -> None:
"""Initialize the Markdown text splitter.
Args:
headers_to_split_on: List of tuples ``(header_marker, metadata_key)``.
Example: ``[("#", "title"), ("##", "section")]``.
Defaults to standard Markdown headers (# through ######).
chunk_size: Maximum size of chunks in tokens. If ``None``,
chunks are only split on headers (original behavior).
chunk_overlap: Number of tokens to overlap between chunks.
Only used when ``chunk_size`` is set.
encoding_name: Tiktoken encoding name for token counting.
Defaults to "cl100k_base" (GPT-4, GPT-3.5-turbo compatible).
strip_headers: Whether to exclude headers from chunk content.
Headers are always included in metadata regardless.
preserve_frontmatter: Whether to extract YAML frontmatter as
metadata instead of discarding it.
keep_separator: Whether to keep horizontal rules (---) in output.
semantic_chunking: Whether to keep semantic units together (tables,
code blocks) even if they exceed ``chunk_size`` slightly.
deduplicate_headers: Whether to add numeric suffixes to duplicate
header names for unique identification in RAG systems.
Example: "Conclusion" -> "Conclusion", "Conclusion (2)", etc.
strict_mode: Enable all strict token compliance features:
split_code_blocks, filter_separators, and merge_small_chunks.
split_code_blocks: Split code blocks that exceed chunk_size.
Overrides semantic_chunking for code blocks only.
filter_separators: Remove separator-only chunks (like ---).
merge_small_chunks: Merge consecutive small chunks that share
the same header hierarchy.
min_chunk_size: Minimum chunk size in tokens for merging.
Chunks below this threshold will be merged with adjacent chunks
if they share the same headers. Only used when merge_small_chunks
is enabled.
isolate_code_blocks: If True, each code block (delimited by ```)
becomes a separate chunk, even in header-only mode.
isolate_tables: If True, each table becomes a separate chunk,
even in header-only mode.
"""
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.encoding_name = encoding_name
self.strip_headers = strip_headers
self.preserve_frontmatter = preserve_frontmatter
self.keep_separator = keep_separator
self.semantic_chunking = semantic_chunking
self.deduplicate_headers = deduplicate_headers
self.isolate_code_blocks = isolate_code_blocks
self.isolate_tables = isolate_tables
# Strict mode enables all strict features
self.strict_mode = strict_mode
self.split_code_blocks = split_code_blocks or strict_mode
self.filter_separators = filter_separators or strict_mode
self.merge_small_chunks = merge_small_chunks or strict_mode
self.min_chunk_size = min_chunk_size
# Initialize tiktoken encoding for token counting
self._encoding = tiktoken.get_encoding(self.encoding_name)
if headers_to_split_on:
self._splittable_headers = dict(headers_to_split_on)
else:
self._splittable_headers = {
"#": "Header 1",
"##": "Header 2",
"###": "Header 3",
"####": "Header 4",
"#####": "Header 5",
"######": "Header 6",
}
# -------------------------------------------------------------------------
# Token Counting Helpers
# -------------------------------------------------------------------------
def _count_tokens(self, text: str) -> int:
"""Count the number of tokens in a text string.
Args:
text: The text to count tokens for.
Returns:
Number of tokens in the text.
"""
if not text:
return 0
return len(self._encoding.encode(text))
def _get_last_n_tokens_text(self, text: str, n_tokens: int) -> str:
"""Get the text corresponding to the last n tokens.
Args:
text: The source text.
n_tokens: Number of tokens to extract from the end.
Returns:
The text corresponding to the last n tokens.
"""
if not text or n_tokens <= 0:
return ""
tokens = self._encoding.encode(text)
if len(tokens) <= n_tokens:
return text
return self._encoding.decode(tokens[-n_tokens:])
def _wrap_code_fence(
self,
content: str,
opening_fence: str,
closing_fence: str,
) -> str:
"""Wrap content in code fences.
Args:
content: The code content to wrap.
opening_fence: The opening fence line (e.g., "```python\\n").
closing_fence: The closing fence line (e.g., "```\\n").
Returns:
Content wrapped in code fences.
"""
return opening_fence + content.rstrip("\n") + "\n" + closing_fence
def _accumulate_parts(
self,
parts: list[str],
max_tokens: int,
separator: str,
metadata: dict[str, Any],
start_index: int = 0,
split_type: str | None = None,
wrapper: tuple[str, str] | None = None,
oversized_handler: Any | None = None,
) -> list[Document]:
"""Accumulate parts into chunks respecting token limits.
This is the common pattern used across multiple splitting methods.
Args:
parts: List of text parts to accumulate.
max_tokens: Maximum tokens per chunk.
separator: Separator between parts (e.g., "\\n\\n", " ").
metadata: Base metadata for chunks.
start_index: Starting chunk index.
split_type: Optional split type for metadata.
wrapper: Optional (opening, closing) tuple for wrapping content.
oversized_handler: Optional callable(part, metadata, index) -> list[Document]
for handling parts that exceed max_tokens.
Returns:
List of Document chunks.
"""
result = []
current_chunk = ""
chunk_index = start_index
for part in parts:
part = part.strip() if separator == "\n\n" else part
if not part:
continue
part_tokens = self._count_tokens(part)
# Handle oversized parts
if part_tokens > max_tokens:
if current_chunk:
result.append(
self._create_chunk(
current_chunk, metadata, chunk_index, split_type, wrapper
)
)
chunk_index += 1
current_chunk = ""
if oversized_handler:
sub_chunks = oversized_handler(part, metadata, chunk_index)
result.extend(sub_chunks)
chunk_index += len(sub_chunks)
else:
# Default: add as-is with warning
result.append(
self._create_chunk(
part, metadata, chunk_index, split_type, wrapper
)
)
chunk_index += 1
continue
# Try to accumulate
test_content = current_chunk + (separator if current_chunk else "") + part
if self._count_tokens(test_content) <= max_tokens:
current_chunk = test_content
else:
if current_chunk:
result.append(
self._create_chunk(
current_chunk, metadata, chunk_index, split_type, wrapper
)
)
chunk_index += 1
# Apply overlap if configured
if self.chunk_overlap > 0:
overlap = self._get_last_n_tokens_text(
current_chunk, self.chunk_overlap
)
candidate = overlap + separator + part
# Fall back to no overlap if it would exceed chunk_size
if max_tokens and self._count_tokens(candidate) > max_tokens:
current_chunk = part
else:
current_chunk = candidate
else:
current_chunk = part
else:
current_chunk = part
if current_chunk:
result.append(
self._create_chunk(
current_chunk, metadata, chunk_index, split_type, wrapper
)
)
return result
def _create_chunk(
self,
content: str,
metadata: dict[str, Any],
chunk_index: int,
split_type: str | None = None,
wrapper: tuple[str, str] | None = None,
) -> Document:
"""Create a Document chunk with consistent metadata.
Args:
content: The chunk content.
metadata: Base metadata.
chunk_index: Index of this chunk.
split_type: Optional split type for metadata.
wrapper: Optional (opening, closing) tuple for wrapping.
Returns:
Document with content and metadata.
"""
if wrapper:
content = self._wrap_code_fence(content, wrapper[0], wrapper[1])
chunk_metadata = {**metadata, "chunk_index": chunk_index}
if split_type:
chunk_metadata["split_type"] = split_type
return Document(page_content=content, metadata=chunk_metadata)
# -------------------------------------------------------------------------
# Public Methods
# -------------------------------------------------------------------------
def split_text(self, text: str) -> list[Document]:
"""Split Markdown text into chunks with metadata.
This method is thread-safe and can be called concurrently.
Args:
text: The Markdown text to split.
Returns:
List of Document objects with ``page_content`` and ``metadata``.
Metadata includes header hierarchy and content type information.
"""
state = _ParserState()
lines = text.splitlines(keepends=True)
lines = self._extract_frontmatter(lines, state)
self._process_lines(lines, state)
if state.in_code_block:
self._finalize_code_block(state)
else:
self._finalize_current_block(state)
if self.chunk_size:
state.chunks = self._apply_chunk_size_limits(state.chunks)
# Apply strict mode post-processing
if self.filter_separators:
state.chunks = self._filter_separator_chunks(state.chunks)
if self.merge_small_chunks and self.chunk_size:
state.chunks = self._merge_small_chunks_by_headers(state.chunks)
return state.chunks
def split_documents(self, documents: list[Document]) -> list[Document]:
"""Split multiple documents, preserving original metadata.
Args:
documents: List of Document objects to split.
Returns:
List of split documents with merged metadata (original + chunk).
"""
result = []
for doc in documents:
chunks = self.split_text(doc.page_content)
for chunk in chunks:
merged_metadata = {**doc.metadata, **chunk.metadata}
result.append(
Document(
page_content=chunk.page_content,
metadata=merged_metadata,
)
)
return result
def lazy_split_text(self, text: str) -> Iterator[Document]:
"""Split text and yield chunks one at a time.
Note: The full document is processed internally by split_text() first.
This method provides a generator interface for convenience when iterating
over results, but does not reduce peak memory usage.
Args:
text: The Markdown text to split.
Yields:
Document objects one at a time.
"""
for chunk in self.split_text(text):
yield chunk
# -------------------------------------------------------------------------
# Frontmatter Handling
# -------------------------------------------------------------------------
def _extract_frontmatter(
self,
lines: list[str],
state: _ParserState,
) -> list[str]:
"""Extract YAML frontmatter from the beginning of the document."""
if not lines:
return lines
first_line = lines[0].strip()
if not self._FRONTMATTER_FENCE.match(first_line):
return lines
for i, line in enumerate(lines[1:], start=1):
if self._FRONTMATTER_FENCE.match(line.strip()):
frontmatter_lines = lines[1:i]
if self.preserve_frontmatter:
state.frontmatter_metadata = self._parse_yaml(frontmatter_lines)
return lines[i + 1 :]
return lines
def _parse_yaml(self, lines: list[str]) -> dict[str, str]:
"""Parse YAML frontmatter into metadata dictionary.
Attempts to use PyYAML if available for full YAML support.
Falls back to a simple key: value parser otherwise.
"""
yaml_text = "\n".join(lines)
# Try PyYAML first if available
try:
import yaml
parsed = yaml.safe_load(yaml_text)
if isinstance(parsed, dict):
return {
str(k): str(v) if not isinstance(v, (list, dict)) else repr(v)
for k, v in parsed.items()
if v is not None
}
except ImportError:
pass
except Exception:
pass
# Simple fallback parser
metadata: dict[str, str] = {}
current_key: str | None = None
multiline_value: list[str] = []
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if ":" in stripped and not stripped.startswith("-"):
if current_key and multiline_value:
metadata[current_key] = " ".join(multiline_value).strip()
multiline_value = []
key, _, value = stripped.partition(":")
key = key.strip()
value = value.strip()
if not key:
continue
if value.startswith("[") and value.endswith("]"):
metadata[key] = value
current_key = None
elif value and value[0] in "\"'":
metadata[key] = value.strip("\"'")
current_key = None
elif value:
metadata[key] = value
current_key = None
else:
current_key = key
elif current_key:
multiline_value.append(stripped)
if current_key and multiline_value:
metadata[current_key] = " ".join(multiline_value).strip()
return metadata
# -------------------------------------------------------------------------
# Line Processing
# -------------------------------------------------------------------------
def _process_lines(self, lines: list[str], state: _ParserState) -> None:
"""Process all lines and build chunks.
Handles code blocks, tables, lists, blockquotes, headers, and regular text.
In header-only mode (chunk_size is None), only splits on headers unless
isolate_code_blocks or isolate_tables is enabled.
"""
header_only_mode = self.chunk_size is None
i = 0
while i < len(lines):
line = lines[i]
raw_line = line
stripped = line.strip()
# Handle code blocks (highest priority)
if state.in_code_block:
i = self._handle_code_block_content(lines, i, state)
continue
# Check for code block start
code_match = self._CODE_FENCE_PATTERN.match(stripped)
if code_match:
# Finalize current block if NOT in header-only mode OR if isolating code blocks
if not header_only_mode or self.isolate_code_blocks:
self._finalize_current_block(state)
state.in_code_block = True
state.code_fence = code_match.group(1)[0]
state.code_fence_length = len(code_match.group(1))
state.code_language = code_match.group(2).strip()
if header_only_mode and not self.isolate_code_blocks:
# In header-only mode (without isolation), add code fence to current content
state.current_content.append(raw_line)
else:
state.current_content = [raw_line]
i += 1
continue
# Handle tables
if self._is_table_line(stripped, state):
if not state.in_table:
# Finalize current block if NOT in header-only mode OR if isolating tables
if not header_only_mode or self.isolate_tables:
self._finalize_current_block(state)
state.in_table = True
if header_only_mode and not self.isolate_tables:
# In header-only mode (without isolation), add to current content
state.current_content.append(raw_line)
else:
state.table_content.append(raw_line)
i += 1
continue
elif state.in_table:
state.in_table = False
if not header_only_mode or self.isolate_tables:
self._finalize_table(state)
else:
state.table_content = []
# Handle lists
list_match = self._LIST_ITEM_PATTERN.match(line)
if list_match or (
state.in_list and self._is_list_continuation(line, state)
):
if not state.in_list:
if not header_only_mode:
self._finalize_current_block(state)
state.in_list = True
state.list_indent = len(list_match.group(1)) if list_match else 0
if header_only_mode:
state.current_content.append(raw_line)
else:
state.list_content.append(raw_line)
i += 1
continue
elif state.in_list:
state.in_list = False
state.list_indent = 0
if not header_only_mode:
self._finalize_list(state)
else:
state.list_content = []
# Handle blockquotes
blockquote_match = self._BLOCKQUOTE_PATTERN.match(line)
if blockquote_match:
if not state.in_blockquote:
if not header_only_mode:
self._finalize_current_block(state)
state.in_blockquote = True
if header_only_mode:
state.current_content.append(raw_line)
else:
state.blockquote_content.append(raw_line)
i += 1
continue
elif state.in_blockquote:
state.in_blockquote = False
if not header_only_mode:
self._finalize_blockquote(state)
else:
state.blockquote_content = []
# Handle horizontal rules
if self._HORIZONTAL_RULE_PATTERN.match(stripped) and not state.in_list:
if header_only_mode:
# In header-only mode, treat separator as regular content
state.current_content.append(raw_line)
else:
self._finalize_current_block(state)
if self.keep_separator:
state.current_content = [raw_line]
self._finalize_current_block(state, is_separator=True)
i += 1
continue
# Handle headers
# Use protected_line (inline code stripped) for detection to avoid
# false matches on # inside inline code, but extract text from
# the original stripped line to preserve inline code content
protected_line = self._INLINE_CODE_PATTERN.sub("", stripped)
header_match = self._HEADER_PATTERN.match(protected_line)
if header_match and self._HEADER_PATTERN.match(stripped):
actual_match = self._HEADER_PATTERN.match(stripped)
self._handle_header(
state,
len(header_match.group(1)),
actual_match.group(2),
raw_line,
)
i += 1
continue
# Alternative header (underline style)
if i + 1 < len(lines):
next_stripped = lines[i + 1].strip()
if self._ALT_HEADER_1_PATTERN.match(next_stripped) and stripped:
self._handle_header(state, 1, stripped, raw_line)
i += 2
continue
elif (
self._ALT_HEADER_2_PATTERN.match(next_stripped)
and stripped
and not self._HORIZONTAL_RULE_PATTERN.match(next_stripped)
):
self._handle_header(state, 2, stripped, raw_line)
i += 2
continue
# Regular text
state.current_content.append(raw_line)
i += 1
def _handle_code_block_content(
self,
lines: list[str],
start_idx: int,
state: _ParserState,
) -> int:
"""Handle content inside a code block.
Processes lines until closing fence is found, respecting header-only mode
and code block isolation settings.
"""
line = lines[start_idx]
stripped = line.strip()
header_only_mode = self.chunk_size is None
close_match = self._CODE_FENCE_PATTERN.match(stripped)
if close_match:
fence_char = close_match.group(1)[0]
fence_len = len(close_match.group(1))
if fence_char == state.code_fence and fence_len >= state.code_fence_length:
state.current_content.append(line)
if header_only_mode and not self.isolate_code_blocks:
# In header-only mode (without isolation), keep code block as part of current content
state.in_code_block = False
state.code_fence = ""
state.code_fence_length = 0
state.code_language = ""
else:
# Either not in header-only mode OR isolating code blocks
self._finalize_code_block(state)
return start_idx + 1
state.current_content.append(line)
return start_idx + 1
def _handle_header(
self,
state: _ParserState,
level: int,
text: str,
raw_line: str,
) -> None:
"""Handle a header line.
Finalizes current block if header should split, updates header stack,
and applies deduplication if enabled.
"""
header_key = self._splittable_headers.get("#" * level)
# Only finalize (create new chunk) if this header level should split
if header_key:
self._finalize_current_block(state)
# Apply header deduplication if enabled
display_text = text
if self.deduplicate_headers:
# Create unique key combining header level and text
dedup_key = f"{header_key}:{text}"
count = state.header_counts.get(dedup_key, 0) + 1
state.header_counts[dedup_key] = count
if count > 1:
display_text = f"{text} ({count})"
state.header_stack = [
(lvl, key, val) for lvl, key, val in state.header_stack if lvl < level
]
state.header_stack.append((level, header_key, display_text))
if not self.strip_headers:
state.current_content.append(raw_line)
# -------------------------------------------------------------------------
# Block Detection Helpers
# -------------------------------------------------------------------------
def _is_table_line(self, line: str, state: _ParserState) -> bool:
"""Check if line is part of a Markdown table with strict detection.
Uses multiple heuristics: pipe delimiters, cell count, separator patterns,
and cell length ratios to avoid false positives.
"""
if state.in_table:
return bool(
self._TABLE_ROW_PATTERN.match(line)
or self._TABLE_SEPARATOR_PATTERN.match(line)
)
if not line.startswith("|") or not line.endswith("|"):
return False
if line.count("|") < 3:
return False
if self._TABLE_SEPARATOR_PATTERN.match(line):
return True
cells = line.strip("|").split("|")
if len(cells) < 2:
return False
cell_lengths = [len(c.strip()) for c in cells]
if cell_lengths:
max_len = max(cell_lengths)
min_len = min(cell_lengths)
if min_len > 0 and max_len / min_len > 10:
return False
return True
def _is_list_continuation(self, line: str, state: _ParserState) -> bool:
"""Check if line continues a list.
Returns True for blank lines or lines with greater indentation than
the list's base indent level.
"""
if not line.strip():
return True
indent = len(line) - len(line.lstrip())
return indent > state.list_indent
# -------------------------------------------------------------------------
# Block Finalization
# -------------------------------------------------------------------------
def _finalize_current_block(
self,
state: _ParserState,
is_separator: bool = False,
) -> None:
"""Finalize the current content block and create a chunk."""
if not state.current_content:
return
content = "".join(state.current_content)
if not content or content.isspace():
state.current_content = []
return
metadata = self._build_metadata(state, is_separator=is_separator)
state.chunks.append(Document(page_content=content, metadata=metadata))
state.current_content = []
def _finalize_code_block(self, state: _ParserState) -> None:
"""Finalize a code block."""
content = "".join(state.current_content)
metadata = self._build_metadata(state, block_type="code")
if state.code_language:
metadata["language"] = state.code_language
state.chunks.append(Document(page_content=content, metadata=metadata))
state.current_content = []
state.in_code_block = False
state.code_fence = ""
state.code_fence_length = 0
state.code_language = ""
def _finalize_table(self, state: _ParserState) -> None:
"""Finalize a table block."""
if not state.table_content:
state.in_table = False
return
content = "".join(state.table_content)
metadata = self._build_metadata(state, block_type="table")
state.chunks.append(Document(page_content=content, metadata=metadata))
state.table_content = []
state.in_table = False
def _finalize_list(self, state: _ParserState) -> None:
"""Finalize a list block."""
if not state.list_content:
state.in_list = False
return
while state.list_content and not state.list_content[-1].strip():
state.list_content.pop()
if not state.list_content:
state.in_list = False
return
content = "".join(state.list_content)
metadata = self._build_metadata(state, block_type="list")
state.chunks.append(Document(page_content=content, metadata=metadata))
state.list_content = []
state.in_list = False
state.list_indent = 0
def _finalize_blockquote(self, state: _ParserState) -> None:
"""Finalize a blockquote block."""
if not state.blockquote_content:
state.in_blockquote = False
return
content = "".join(state.blockquote_content)
metadata = self._build_metadata(state, block_type="blockquote")
state.chunks.append(Document(page_content=content, metadata=metadata))
state.blockquote_content = []
state.in_blockquote = False
def _build_metadata(