ai-editor-tree-engine-dev 1.0.176__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,748 @@
1
+ """Lossless Markdown format plugin for the tree engine (``format_id='markdown'``).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Model (``markdown:`` kinds): ``document`` root; ``front_matter`` (a leading ``---`` ... ``---``
7
+ block at byte 0); ``section`` (one per heading, nested by heading level -- it holds its
8
+ ``heading``, then its blocks, then its deeper sections, and ends before the next heading of equal
9
+ or lower level); ``heading`` (ATX or setext, fields ``level`` 1-6 and ``text``); ``paragraph``;
10
+ ``list`` (field ``ordered``) with ``list_item`` children (a nested list is a child of its item);
11
+ ``code_block`` (fenced with ``` or ~~~, field ``info_string``; or indented); ``block_quote``;
12
+ ``table``; ``thematic_break``; ``html_block``. Content before the first heading is a child of the
13
+ document root. Markdown has no syntax error: unterminated fences run to the end of the file and
14
+ nothing here ever raises a content parse failure.
15
+
16
+ Byte fidelity: every leaf block keeps its exact source lines in ``raw`` and the run of blank lines
17
+ that follows it in ``trailing``; a container (``list``, ``list_item``, ``section``, ``document``)
18
+ renders its own ``head_raw`` (a list item's marker line), the blank lines between that line and its
19
+ first child (``gap``), its children and its ``trailing``. A byte order mark and the blank lines
20
+ before the first block live on the document (``bom``, ``leading``). Rendering replays these
21
+ strings, so ``dumps(loads(x)) == x`` for every input; as a final guard the parse itself verifies
22
+ that and, should the line model ever disagree with the source, keeps the whole text in one
23
+ paragraph instead of losing a byte.
24
+
25
+ A leaf block holds ``raw`` and a container never does, so a pointwise edit that invalidates the
26
+ cached source of the ancestors of the edited node (``core.live_tree.CACHED_SOURCE_FIELDS``) never
27
+ strips a head line. ``trailing`` absent on the last block of a freshly parsed fragment means "the
28
+ fragment carried no separator of its own": ``adjust_replace_fragment`` and ``adjust_after_insert``
29
+ give it the replaced block's, or the previous block's.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import re
35
+ from dataclasses import dataclass, field, replace
36
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
37
+
38
+ from tree_engine.core.identity import generate_node_id
39
+ from tree_engine.core.nodes import Document, Node, make_node
40
+ from tree_engine.core.plugin_boundary import FormatBoundary
41
+ from tree_engine.exceptions import (
42
+ FormatContentParseFailed,
43
+ FormatFragmentParseFailed,
44
+ FormatPluginContractError,
45
+ UnsupportedTranslation,
46
+ )
47
+ from tree_engine.plugins.contract import (
48
+ FormatPluginContract,
49
+ FormatPluginMetadata,
50
+ SemanticRoleMapping,
51
+ )
52
+
53
+ __all__ = ["FORMAT_ID", "MarkdownFormatPlugin", "MARKDOWN_FORMAT_PLUGIN"]
54
+
55
+ FORMAT_ID = "markdown"
56
+ _P = FORMAT_ID + ":"
57
+ K_DOCUMENT = _P + "document"
58
+ K_FRONT = _P + "front_matter"
59
+ K_SECTION = _P + "section"
60
+ K_HEADING = _P + "heading"
61
+ K_PARAGRAPH = _P + "paragraph"
62
+ K_LIST = _P + "list"
63
+ K_ITEM = _P + "list_item"
64
+ K_CODE = _P + "code_block"
65
+ K_QUOTE = _P + "block_quote"
66
+ K_TABLE = _P + "table"
67
+ K_BREAK = _P + "thematic_break"
68
+ K_HTML = _P + "html_block"
69
+ _BOM = ""
70
+ _SEPARATED = (K_PARAGRAPH, K_LIST, K_QUOTE, K_TABLE)
71
+
72
+ _METADATA = FormatPluginMetadata(
73
+ format_id=FORMAT_ID,
74
+ aliases=(),
75
+ file_extensions=("md", "markdown"),
76
+ plugin_version="1.0.0",
77
+ contract_version="1.0.0",
78
+ capabilities={
79
+ # Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
80
+ # instead of keeping its own list of unsupported suffixes.
81
+ "ca_save_supported": True,
82
+ "semantic_role_mapping": True,
83
+ "byte_identical_round_trip": True,
84
+ "navigable": True,
85
+ "editable": True,
86
+ },
87
+ )
88
+ _ROLE_MAP = SemanticRoleMapping({})
89
+ _Source = Union[str, bytes]
90
+
91
+ _FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
92
+ _ATX = re.compile(r"^ {0,3}(#{1,6})(?=[ \t]|$)(.*)$")
93
+ _BREAK = re.compile(r"^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$")
94
+ _QUOTE = re.compile(r"^ {0,3}>")
95
+ _MARKER = re.compile(r"^( {0,3})([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*)|$)")
96
+ _SETEXT = re.compile(r"^ {0,3}(=+|-+)[ \t]*$")
97
+ _TABLE_DELIM = re.compile(r"^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$")
98
+ _HTML_TAGS = (
99
+ "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|"
100
+ "dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|"
101
+ "header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|"
102
+ "param|pre|script|section|source|style|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"
103
+ )
104
+ _HTML = re.compile(r"^ {0,3}(?:<!--|</?(?:" + _HTML_TAGS + r")(?:[ \t/>]|$))", re.IGNORECASE)
105
+
106
+
107
+ def _contract_error(message: str) -> FormatPluginContractError:
108
+ return FormatPluginContractError(message, plugin_id=FORMAT_ID)
109
+
110
+
111
+ def _body(line: str) -> str:
112
+ return line.rstrip("\r\n")
113
+
114
+
115
+ def _is_blank(line: str) -> bool:
116
+ return not line.strip()
117
+
118
+
119
+ def _columns(body: str) -> int:
120
+ col = 0
121
+ for ch in body:
122
+ if ch == " ":
123
+ col += 1
124
+ elif ch == "\t":
125
+ col += 4 - col % 4
126
+ else:
127
+ break
128
+ return col
129
+
130
+
131
+ def _view(line: str, strip: int) -> str:
132
+ """The line as block classification sees it: tabs in the indent expanded, ``strip`` columns
133
+ of enclosing-container indent removed. Never used for rendering."""
134
+ body = _body(line)
135
+ rest = body.lstrip(" \t")
136
+ cols = max(_columns(body) - strip, 0)
137
+ return " " * cols + rest
138
+
139
+
140
+ def _starts_block(view: str) -> bool:
141
+ """A line that interrupts a paragraph."""
142
+ if _FENCE.match(view) and not ("`" in _FENCE.match(view).group(2) and _FENCE.match(view).group(1)[0] == "`"):
143
+ return True
144
+ if _ATX.match(view) or _BREAK.match(view) or _QUOTE.match(view):
145
+ return True
146
+ m = _MARKER.match(view)
147
+ if m and m.group(4) and (m.group(2) in "-+*" or m.group(2) in ("1.", "1)")):
148
+ return True
149
+ return bool(_HTML.match(view) and not view.lstrip().lower().startswith("<!--x"))
150
+
151
+
152
+ @dataclass
153
+ class _Blk:
154
+ kind: str
155
+ lines: List[str] = field(default_factory=list)
156
+ fields: Dict[str, Any] = field(default_factory=dict)
157
+ children: List["_Blk"] = field(default_factory=list)
158
+ trailing: List[str] = field(default_factory=list)
159
+ head: List[str] = field(default_factory=list)
160
+ gap: List[str] = field(default_factory=list)
161
+
162
+
163
+ def _fence_open(view: str) -> Optional[Tuple[str, int, str]]:
164
+ m = _FENCE.match(view)
165
+ if not m:
166
+ return None
167
+ marker, info = m.group(1), m.group(2)
168
+ if marker[0] == "`" and "`" in info:
169
+ return None
170
+ return marker[0], len(marker), info.strip()
171
+
172
+
173
+ def _parse_blocks(lines: Sequence[str], strip: int, top: bool) -> Tuple[List[str], List[_Blk]]:
174
+ """Blocks of ``lines``; returns (blank lines before the first block, blocks)."""
175
+ blocks: List[_Blk] = []
176
+ leading: List[str] = []
177
+ i, n = 0, len(lines)
178
+ while i < n:
179
+ line = lines[i]
180
+ view = _view(line, strip)
181
+ if _is_blank(line):
182
+ j = i
183
+ while j < n and _is_blank(lines[j]):
184
+ j += 1
185
+ (blocks[-1].trailing if blocks else leading).extend(lines[i:j])
186
+ i = j
187
+ continue
188
+ blk, i = _block_at(lines, i, strip, top)
189
+ blocks.append(blk)
190
+ return leading, blocks
191
+
192
+
193
+ def _block_at(lines: Sequence[str], i: int, strip: int, top: bool) -> Tuple[_Blk, int]:
194
+ n = len(lines)
195
+ view = _view(lines[i], strip)
196
+ # front matter: only at the very first line of the whole document
197
+ if top and strip == 0 and i == 0 and _body(lines[0]) == "---":
198
+ for j in range(1, n):
199
+ if _body(lines[j]) == "---":
200
+ return _Blk(K_FRONT, list(lines[: j + 1])), j + 1
201
+ opened = _fence_open(view)
202
+ if opened:
203
+ char, size, info = opened
204
+ j = i + 1
205
+ while j < n:
206
+ m = _FENCE.match(_view(lines[j], strip))
207
+ if m and m.group(1)[0] == char and len(m.group(1)) >= size and not m.group(2).strip():
208
+ j += 1
209
+ break
210
+ j += 1
211
+ return _Blk(K_CODE, list(lines[i:j]), {"info_string": info, "fence": char * 3}), j
212
+ m = _ATX.match(view)
213
+ if m:
214
+ text = m.group(2).strip()
215
+ text = re.sub(r"(?:^|[ \t]+)#+$", "", text).strip()
216
+ return _Blk(K_HEADING, [lines[i]], {"level": len(m.group(1)), "text": text, "style": "atx"}), i + 1
217
+ if _BREAK.match(view):
218
+ return _Blk(K_BREAK, [lines[i]]), i + 1
219
+ if _QUOTE.match(view):
220
+ j = i + 1
221
+ while j < n and not _is_blank(lines[j]):
222
+ v = _view(lines[j], strip)
223
+ if _QUOTE.match(v) or not (_starts_block(v) or _MARKER.match(v)):
224
+ j += 1
225
+ else:
226
+ break
227
+ return _Blk(K_QUOTE, list(lines[i:j])), j
228
+ if _MARKER.match(view):
229
+ return _list_at(lines, i, strip)
230
+ if _columns(_body(lines[i])) - strip >= 4:
231
+ j, last = i + 1, i
232
+ while j < n:
233
+ if _is_blank(lines[j]):
234
+ j += 1
235
+ continue
236
+ if _columns(_body(lines[j])) - strip >= 4:
237
+ last = j
238
+ j += 1
239
+ continue
240
+ break
241
+ return _Blk(K_CODE, list(lines[i : last + 1]), {"info_string": "", "fence": "indent"}), last + 1
242
+ if _HTML.match(view):
243
+ j = i + 1
244
+ if view.lstrip().startswith("<!--"):
245
+ if "-->" not in view:
246
+ while j < n:
247
+ j += 1
248
+ if "-->" in lines[j - 1]:
249
+ break
250
+ else:
251
+ while j < n and not _is_blank(lines[j]):
252
+ j += 1
253
+ return _Blk(K_HTML, list(lines[i:j])), j
254
+ if "|" in view and i + 1 < n and _TABLE_DELIM.match(_view(lines[i + 1], strip)) and "|" in (view + lines[i + 1]):
255
+ j = i + 2
256
+ while j < n and not _is_blank(lines[j]) and not _starts_block(_view(lines[j], strip)):
257
+ j += 1
258
+ return _Blk(K_TABLE, list(lines[i:j])), j
259
+ return _paragraph_at(lines, i, strip)
260
+
261
+
262
+ def _paragraph_at(lines: Sequence[str], i: int, strip: int) -> Tuple[_Blk, int]:
263
+ n = len(lines)
264
+ j = i + 1
265
+ while j < n and not _is_blank(lines[j]):
266
+ v = _view(lines[j], strip)
267
+ m = _SETEXT.match(v)
268
+ if m:
269
+ level = 1 if m.group(1)[0] == "=" else 2
270
+ head_line = lines[j - 1]
271
+ text = _view(head_line, 0).strip()
272
+ heading = _Blk(K_HEADING, [head_line, lines[j]], {"level": level, "text": text, "style": "setext"})
273
+ if j - 1 > i:
274
+ # only the line right above the underline is the heading; earlier lines stay a paragraph
275
+ return _Blk(K_PARAGRAPH, list(lines[i : j - 1]), {}, [], [], [], []), j - 1
276
+ return heading, j + 1
277
+ if _starts_block(v):
278
+ break
279
+ j += 1
280
+ return _Blk(K_PARAGRAPH, list(lines[i:j])), j
281
+
282
+
283
+ def _list_at(lines: Sequence[str], i: int, strip: int) -> Tuple[_Blk, int]:
284
+ n = len(lines)
285
+ first = _MARKER.match(_view(lines[i], strip))
286
+ assert first is not None
287
+ ordered = first.group(2)[0].isdigit()
288
+ kind_key = first.group(2)[-1] if ordered else first.group(2)
289
+ lst = _Blk(K_LIST, [], {"ordered": ordered})
290
+ while i < n:
291
+ view = _view(lines[i], strip)
292
+ m = _MARKER.match(view)
293
+ if m is None or (m.group(2)[0].isdigit() != ordered) or (m.group(2)[-1] if ordered else m.group(2)) != kind_key:
294
+ break
295
+ if _BREAK.match(view):
296
+ break
297
+ marker_end = len(m.group(1)) + len(m.group(2))
298
+ spaces = len(m.group(3) or "")
299
+ width = marker_end + (spaces if m.group(4) and 1 <= spaces <= 4 else 1)
300
+ j = i + 1
301
+ while j < n:
302
+ line = lines[j]
303
+ if _is_blank(line):
304
+ k = j
305
+ while k < n and _is_blank(lines[k]):
306
+ k += 1
307
+ if k < n and _columns(_body(lines[k])) - strip >= width:
308
+ j = k
309
+ continue
310
+ break
311
+ v = _view(line, strip)
312
+ if _columns(_body(line)) - strip >= width:
313
+ j += 1
314
+ elif not _is_blank(lines[j - 1]) and not _starts_block(v) and not _MARKER.match(v):
315
+ j += 1
316
+ else:
317
+ break
318
+ item = _Blk(K_ITEM, [], {}, [], [], [lines[i]], [])
319
+ gap, kids = _parse_blocks(lines[i + 1 : j], strip + width, False)
320
+ item.gap, item.children = gap, kids
321
+ lst.children.append(item)
322
+ k = j
323
+ while k < n and _is_blank(lines[k]):
324
+ k += 1
325
+ nxt = _MARKER.match(_view(lines[k], strip)) if k < n else None
326
+ if (
327
+ nxt is not None
328
+ and not _BREAK.match(_view(lines[k], strip))
329
+ and nxt.group(2)[0].isdigit() == ordered
330
+ and (nxt.group(2)[-1] if ordered else nxt.group(2)) == kind_key
331
+ ):
332
+ item.trailing = list(lines[j:k])
333
+ i = k
334
+ continue
335
+ i = j
336
+ break
337
+ return lst, i
338
+
339
+
340
+ # -- node building and rendering ---------------------------------------------
341
+
342
+
343
+ def _node(kind: str, fields: Mapping[str, Any], children: Sequence[Node] = ()) -> Node:
344
+ return replace(
345
+ make_node(kind, fields=dict(fields), children=tuple(children)),
346
+ node_id=generate_node_id(),
347
+ short_id=None,
348
+ )
349
+
350
+
351
+ def _to_node(blk: _Blk) -> Node:
352
+ fields: Dict[str, Any] = dict(blk.fields)
353
+ if blk.kind in (K_ITEM, K_LIST):
354
+ if blk.kind == K_ITEM:
355
+ fields["head_raw"] = "".join(blk.head)
356
+ fields["gap"] = "".join(blk.gap)
357
+ fields["trailing"] = "".join(blk.trailing)
358
+ return _node(blk.kind, fields, [_to_node(c) for c in blk.children])
359
+ fields["raw"] = "".join(blk.lines)
360
+ fields["trailing"] = "".join(blk.trailing)
361
+ return _node(blk.kind, fields)
362
+
363
+
364
+ def _sectioned(blocks: Sequence[_Blk]) -> List[Node]:
365
+ out: List[Tuple[Optional[int], List[Node]]] = []
366
+ root: List[Node] = []
367
+ stack: List[Tuple[int, List[Node], Dict[str, Any]]] = []
368
+ for blk in blocks:
369
+ node = _to_node(blk)
370
+ if blk.kind == K_HEADING:
371
+ level = blk.fields["level"]
372
+ while stack and stack[-1][0] >= level:
373
+ stack.pop()
374
+ kids: List[Node] = [node]
375
+ (stack[-1][1] if stack else root).append(("section", level, kids)) # type: ignore[arg-type]
376
+ stack.append((level, kids, {}))
377
+ else:
378
+ (stack[-1][1] if stack else root).append(node)
379
+ del out
380
+ return [_finish(item) if isinstance(item, tuple) else item for item in root]
381
+
382
+
383
+ def _finish(item: Any) -> Node:
384
+ _tag, level, kids = item
385
+ return _node(K_SECTION, {"level": level}, [_finish(k) if isinstance(k, tuple) else k for k in kids])
386
+
387
+
388
+ def _parse(text: str) -> Document:
389
+ fields: Dict[str, Any] = {}
390
+ body = text
391
+ if body.startswith(_BOM):
392
+ fields["bom"] = _BOM
393
+ body = body[1:]
394
+ lines = _split_lines(body)
395
+ leading, blocks = _parse_blocks(lines, 0, True)
396
+ fields["leading"] = "".join(leading)
397
+ root = _node(K_DOCUMENT, fields, _sectioned(blocks))
398
+ if _render(root) != text:
399
+ # Safety net, never expected: keep every byte rather than lose one.
400
+ flat = _node(K_PARAGRAPH, {"raw": body, "trailing": ""})
401
+ root = _node(K_DOCUMENT, {**({"bom": _BOM} if "bom" in fields else {}), "leading": ""}, [flat])
402
+ return Document(root=root, source_format_id=FORMAT_ID)
403
+
404
+
405
+ def _split_lines(text: str) -> List[str]:
406
+ out: List[str] = []
407
+ pos, size = 0, len(text)
408
+ while pos < size:
409
+ end = text.find("\n", pos)
410
+ end = size if end < 0 else end + 1
411
+ out.append(text[pos:end])
412
+ pos = end
413
+ return out
414
+
415
+
416
+ def _render(node: Node) -> str:
417
+ f = node.fields
418
+ if node.kind == K_DOCUMENT:
419
+ bom = f.get("bom") if isinstance(f.get("bom"), str) else ""
420
+ pieces = [f.get("leading", "")] + [_render(c) for c in node.children]
421
+ return bom + _join(pieces)
422
+ raw = f.get("raw")
423
+ pieces = [raw if isinstance(raw, str) else f.get("head_raw", ""), f.get("gap", "")]
424
+ pieces += [_render(c) for c in node.children]
425
+ pieces.append(f.get("trailing", ""))
426
+ return _join(pieces)
427
+
428
+
429
+ def _join(pieces: List[Any]) -> str:
430
+ parts = [p if isinstance(p, str) else "" for p in pieces]
431
+ last = max((i for i, p in enumerate(parts) if p), default=-1)
432
+ for index in range(last):
433
+ if parts[index] and not parts[index].endswith("\n"):
434
+ parts[index] += "\n"
435
+ return "".join(parts)
436
+
437
+
438
+ # -- tail ownership helpers (hooks run on live nodes) ---------------------------
439
+
440
+
441
+ def _short(kind: Any) -> str:
442
+ return str(kind).split(":", 1)[-1]
443
+
444
+
445
+ def _tail(node: Any) -> Any:
446
+ """The node that owns the blank lines after ``node``: itself, or for a section its last child's."""
447
+ while node.kind == K_SECTION and node.children:
448
+ node = node.children[-1]
449
+ return node
450
+
451
+
452
+ def _first_leaf_kind(node: Any) -> str:
453
+ while node.kind in (K_SECTION, K_LIST, K_ITEM) and node.children:
454
+ if node.kind == K_SECTION:
455
+ return K_SECTION
456
+ node = node.children[0]
457
+ return str(node.kind)
458
+
459
+
460
+ def _set(node: Any, **updates: Any) -> None:
461
+ node.fields = {**node.fields, **updates}
462
+
463
+
464
+ class MarkdownFormatPlugin(FormatPluginContract, FormatBoundary):
465
+ """Registered lossless ``format_id='markdown'`` plugin."""
466
+
467
+ @property
468
+ def metadata(self) -> FormatPluginMetadata:
469
+ return _METADATA
470
+
471
+ @staticmethod
472
+ def _decode(source: _Source, label: str, error: type) -> str:
473
+ if isinstance(source, str):
474
+ return source
475
+ if isinstance(source, (bytes, bytearray)):
476
+ try:
477
+ return bytes(source).decode("utf-8")
478
+ except UnicodeDecodeError as exc:
479
+ raise error(f"cannot decode Markdown: {exc}", format_id=FORMAT_ID) from exc
480
+ raise _contract_error(f"{label} must be str or bytes, got {type(source).__name__}")
481
+
482
+ def parse_document(
483
+ self,
484
+ source: _Source,
485
+ options: Optional[Mapping[str, Any]] = None,
486
+ *,
487
+ source_format_id: Optional[str] = None,
488
+ ) -> Document:
489
+ del options, source_format_id
490
+ return _parse(self._decode(source, "source", FormatContentParseFailed))
491
+
492
+ def parse_fragment(
493
+ self,
494
+ source: _Source,
495
+ options: Optional[Mapping[str, Any]] = None,
496
+ *,
497
+ source_format_id: Optional[str] = None,
498
+ ) -> Union[Node, List[Node]]:
499
+ """Parse ``source`` as the kind of node it is about to replace or land beside
500
+ (``options['context_kind']``): a heading position accepts exactly one heading, a list item
501
+ position only list items, a section position only sections, any other block position blocks
502
+ without headings. Anything else is refused with FORMAT_FRAGMENT_PARSE_FAILED."""
503
+ del source_format_id
504
+ text = self._decode(source, "fragment", FormatFragmentParseFailed)
505
+ context = _short((options or {}).get("context_kind") or "document")
506
+ top = list(_parse(text).root.children)
507
+ blocks = self._flat(top)
508
+
509
+ def refuse(why: str) -> FormatFragmentParseFailed:
510
+ return FormatFragmentParseFailed(
511
+ f"fragment does not parse as {context}: {why}", format_id=FORMAT_ID
512
+ )
513
+
514
+ if not top:
515
+ raise refuse("no content")
516
+ if context == "heading":
517
+ if len(blocks) != 1 or blocks[0].kind != K_HEADING:
518
+ raise refuse("expected exactly one heading")
519
+ result = blocks
520
+ elif context == "list_item":
521
+ if len(blocks) != 1 or blocks[0].kind != K_LIST:
522
+ raise refuse("expected list items")
523
+ result = list(blocks[0].children)
524
+ elif context == "section":
525
+ if any(n.kind != K_SECTION for n in top):
526
+ raise refuse("expected sections starting with a heading")
527
+ result = top
528
+ elif context in ("document", "list"):
529
+ result = top
530
+ else:
531
+ if any(b.kind == K_HEADING for b in blocks):
532
+ raise refuse("a heading is not a block of this kind")
533
+ result = blocks
534
+ if context == "list_item" and not result:
535
+ raise refuse("no list items")
536
+ tail = _tail_frozen(result[-1])
537
+ if tail is not None and tail.fields.get("trailing") == "":
538
+ fields = {k: v for k, v in tail.fields.items() if k != "trailing"}
539
+ result = _replace_tail(result, fields)
540
+ return result if len(result) != 1 else result[0]
541
+
542
+ @staticmethod
543
+ def _flat(top: Sequence[Node]) -> List[Node]:
544
+ out: List[Node] = []
545
+ for node in top:
546
+ if node.kind == K_SECTION:
547
+ out.extend(MarkdownFormatPlugin._flat(node.children))
548
+ else:
549
+ out.append(node)
550
+ return out
551
+
552
+ # -- layout hooks (duck-typed, called by the facade) ---------------------
553
+
554
+ @staticmethod
555
+ def adjust_replace_fragment(deleted: Sequence[Any], incoming: Sequence[Any]) -> None:
556
+ """The replacement takes over the blank lines that followed the replaced block."""
557
+ if not deleted or not incoming:
558
+ return
559
+ new_tail = _tail(incoming[-1])
560
+ if "trailing" not in new_tail.fields:
561
+ _set(new_tail, trailing=_tail(deleted[-1]).fields.get("trailing", ""))
562
+
563
+ @staticmethod
564
+ def adjust_after_insert(parent: Any, inserted: Sequence[Any]) -> None:
565
+ """Keep blocks separated the way their neighbours are, so an insert or a move never
566
+ glues two paragraphs together."""
567
+ if parent is None:
568
+ return
569
+ siblings = list(parent.children)
570
+ for node in inserted:
571
+ index = next((i for i, s in enumerate(siblings) if s is node), None)
572
+ if index is None or node.kind in (K_ITEM,):
573
+ if index is not None:
574
+ prev = siblings[index - 1] if index > 0 else None
575
+ nxt = siblings[index + 1] if index + 1 < len(siblings) else None
576
+ if "trailing" not in node.fields:
577
+ _set(node, trailing=prev.fields.get("trailing", "") if (prev is not None and nxt is not None) else "")
578
+ continue
579
+ prev = siblings[index - 1] if index > 0 else None
580
+ nxt = siblings[index + 1] if index + 1 < len(siblings) else None
581
+ tail = _tail(node)
582
+ prev_tail = _tail(prev) if prev is not None else None
583
+ if "trailing" not in tail.fields:
584
+ borrowed = prev_tail.fields.get("trailing", "") if (prev_tail is not None and nxt is not None) else ""
585
+ _set(tail, trailing=borrowed)
586
+ elif (
587
+ nxt is not None
588
+ and tail.fields.get("trailing") == ""
589
+ and prev_tail is not None
590
+ and prev_tail.fields.get("trailing")
591
+ and node.kind != K_SECTION
592
+ ):
593
+ _set(tail, trailing=prev_tail.fields["trailing"])
594
+ if (
595
+ nxt is None
596
+ and prev_tail is not None
597
+ and not prev_tail.fields.get("trailing")
598
+ and prev_tail.kind in _SEPARATED
599
+ and _first_leaf_kind(node) in _SEPARATED
600
+ ):
601
+ raw = prev_tail.fields.get("raw") or ""
602
+ _set(prev_tail, trailing="\r\n" if raw.endswith("\r\n") else "\n")
603
+
604
+ @staticmethod
605
+ def adjust_after_move(
606
+ source_parent: Any,
607
+ target_parent: Any,
608
+ moved: Sequence[Any],
609
+ *,
610
+ source_children_before: Sequence[Any],
611
+ ) -> None:
612
+ """A block that was not last and now closes ``target_parent`` hands its blank-line run
613
+ to the block it now follows (bug df5c91d0), then the generic insert repair runs.
614
+
615
+ Without this, the follower's missing ``trailing`` is filled by ``adjust_after_insert``
616
+ (so the two blocks stay apart) while the moved block keeps its own run, which renders
617
+ as a doubled blank line at the end of the document.
618
+ """
619
+ # Mirror case: the source's last block leaves, so the block before it becomes last and its
620
+ # blank-line run travels with the mover to wherever it lands in front of a successor.
621
+ if source_parent is not None and moved and source_children_before:
622
+ before = list(source_children_before)
623
+ ids = {id(node) for node in moved}
624
+ head = next((i for i, n in enumerate(before) if id(n) in ids), None)
625
+ now = list(source_parent.children)
626
+ if (
627
+ head is not None
628
+ and head > 0
629
+ and before[-1] is moved[-1]
630
+ and now
631
+ and now[-1] is before[head - 1]
632
+ and target_parent is not None
633
+ and _has_successor(moved[-1])
634
+ and moved[-1].kind not in (K_ITEM,)
635
+ ):
636
+ mover_tail = _tail(moved[-1])
637
+ pred_tail = _tail(before[head - 1])
638
+ if not mover_tail.fields.get("trailing") and pred_tail.fields.get("trailing"):
639
+ _set(mover_tail, trailing=pred_tail.fields["trailing"])
640
+ _set(pred_tail, trailing="")
641
+ if target_parent is not None and moved:
642
+ siblings = list(target_parent.children)
643
+ last = moved[-1]
644
+ if siblings and siblings[-1] is last and last.kind not in (K_ITEM,):
645
+ moved_ids = {id(node) for node in moved}
646
+ index = len(siblings) - 1
647
+ while index >= 0 and id(siblings[index]) in moved_ids:
648
+ index -= 1
649
+ tail = _tail(last)
650
+ run = tail.fields.get("trailing") or ""
651
+ if index >= 0 and run:
652
+ prev_tail = _tail(siblings[index])
653
+ if (
654
+ prev_tail.kind in _SEPARATED
655
+ and not prev_tail.fields.get("trailing")
656
+ ):
657
+ _set(prev_tail, trailing=run)
658
+ _set(tail, trailing="")
659
+ MarkdownFormatPlugin.adjust_after_insert(target_parent, moved)
660
+
661
+ # -- contract surface -----------------------------------------------------
662
+
663
+ def import_external_tree(
664
+ self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
665
+ ) -> Union[Node, Document]:
666
+ return self.import_to_common(external_tree, options)
667
+
668
+ def import_to_common(
669
+ self, external_representation: Any, options: Optional[Mapping[str, Any]] = None
670
+ ) -> Union[Node, Document]:
671
+ del options
672
+ if isinstance(external_representation, (str, bytes, bytearray)):
673
+ return self.parse_document(external_representation)
674
+ raise UnsupportedTranslation(
675
+ "expected Markdown source text",
676
+ node_type=type(external_representation).__name__,
677
+ format_id=FORMAT_ID,
678
+ )
679
+
680
+ def export_from_common(
681
+ self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
682
+ ) -> Any:
683
+ del options
684
+ if not isinstance(nodes, (Node, Document)):
685
+ raise _contract_error(f"expected Node or Document, got {type(nodes).__name__}")
686
+ return _render(nodes.root if isinstance(nodes, Document) else nodes)
687
+
688
+ def generate_output(
689
+ self, target: Union[Node, Document, Any], options: Optional[Mapping[str, Any]] = None
690
+ ) -> Union[str, bytes]:
691
+ options = options or {}
692
+ if isinstance(target, (Node, Document)):
693
+ text = _render(target.root if isinstance(target, Document) else target)
694
+ elif isinstance(target, str):
695
+ text = target
696
+ else:
697
+ raise _contract_error(
698
+ f"cannot render {type(target).__name__}; expected Node/Document/str"
699
+ )
700
+ return text.encode("utf-8") if options.get("as_bytes") else text
701
+
702
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
703
+ return _ROLE_MAP
704
+
705
+ def render_document(self, document: Document) -> bytes:
706
+ result = self.generate_output(document, {"as_bytes": True})
707
+ if not isinstance(result, bytes):
708
+ raise _contract_error("render_document did not return bytes")
709
+ return result
710
+
711
+ def render_fragment(self, node: Node) -> str:
712
+ result = self.generate_output(node)
713
+ if not isinstance(result, str):
714
+ raise _contract_error("render_fragment did not return str")
715
+ return result
716
+
717
+
718
+ def _has_successor(node: Any) -> bool:
719
+ """True when some block follows ``node`` in document order: a later sibling of the node or of
720
+ one of its ancestors. A mover that closes a section still has a successor when the section is
721
+ followed by another, so the blank-line run that separates them has to travel with it."""
722
+ while getattr(node, "parent", None) is not None:
723
+ siblings = list(node.parent.children)
724
+ if siblings and siblings[-1] is not node:
725
+ return True
726
+ node = node.parent
727
+ return False
728
+
729
+
730
+ def _tail_frozen(node: Node) -> Optional[Node]:
731
+ while node.kind == K_SECTION and node.children:
732
+ node = node.children[-1]
733
+ return node
734
+
735
+
736
+ def _replace_tail(nodes: List[Node], fields: Mapping[str, Any]) -> List[Node]:
737
+ """``nodes`` with the tail-owning descendant of the last node given ``fields``."""
738
+
739
+ def rebuild(node: Node) -> Node:
740
+ if node.kind == K_SECTION and node.children:
741
+ kids = tuple(node.children[:-1]) + (rebuild(node.children[-1]),)
742
+ return replace(node, children=kids)
743
+ return replace(node, fields=dict(fields))
744
+
745
+ return list(nodes[:-1]) + [rebuild(nodes[-1])]
746
+
747
+
748
+ MARKDOWN_FORMAT_PLUGIN = MarkdownFormatPlugin()