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.
- ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
- tree_engine/PUBLIC_API.md +161 -0
- tree_engine/__init__.py +327 -0
- tree_engine/checks/__init__.py +60 -0
- tree_engine/checks/builtin/__init__.py +5 -0
- tree_engine/checks/builtin/compile_check.py +53 -0
- tree_engine/checks/builtin/csv_syntax.py +51 -0
- tree_engine/checks/builtin/docstrings.py +211 -0
- tree_engine/checks/builtin/encoding.py +55 -0
- tree_engine/checks/builtin/fleet_rules.py +227 -0
- tree_engine/checks/builtin/format_syntax.py +82 -0
- tree_engine/checks/builtin/jsonl_syntax.py +49 -0
- tree_engine/checks/builtin/shipped.py +52 -0
- tree_engine/checks/builtin/syntax.py +118 -0
- tree_engine/checks/builtin/xml_wellformed.py +51 -0
- tree_engine/checks/chain.py +332 -0
- tree_engine/checks/external/__init__.py +5 -0
- tree_engine/checks/external/_base.py +61 -0
- tree_engine/checks/external/bandit.py +53 -0
- tree_engine/checks/external/black.py +48 -0
- tree_engine/checks/external/flake8.py +38 -0
- tree_engine/checks/external/isort.py +38 -0
- tree_engine/checks/external/mypy.py +45 -0
- tree_engine/checks/external/ruff.py +45 -0
- tree_engine/checks/external/runner.py +197 -0
- tree_engine/checks/model.py +110 -0
- tree_engine/checks/options.py +73 -0
- tree_engine/checks/plugin.py +171 -0
- tree_engine/checks/registry.py +349 -0
- tree_engine/core/address.py +376 -0
- tree_engine/core/identifier_map.py +266 -0
- tree_engine/core/identity.py +226 -0
- tree_engine/core/instrumentation.py +399 -0
- tree_engine/core/integrity.py +341 -0
- tree_engine/core/integrity_full.py +382 -0
- tree_engine/core/journal.py +260 -0
- tree_engine/core/journal_compose.py +571 -0
- tree_engine/core/live_tree.py +785 -0
- tree_engine/core/locking.py +188 -0
- tree_engine/core/move.py +585 -0
- tree_engine/core/move_references.py +323 -0
- tree_engine/core/node_types.py +408 -0
- tree_engine/core/nodes.py +348 -0
- tree_engine/core/offsets.py +24 -0
- tree_engine/core/operations.py +825 -0
- tree_engine/core/plugin_boundary.py +160 -0
- tree_engine/core/position_map.py +263 -0
- tree_engine/core/position_transfer.py +512 -0
- tree_engine/core/range_refresh.py +366 -0
- tree_engine/core/reference_cache.py +360 -0
- tree_engine/core/references.py +223 -0
- tree_engine/core/reparse.py +378 -0
- tree_engine/core/short_id.py +296 -0
- tree_engine/core/subtree_apply.py +397 -0
- tree_engine/core/subtree_copy.py +399 -0
- tree_engine/core/transactions.py +397 -0
- tree_engine/core/trivia.py +396 -0
- tree_engine/core/updates.py +398 -0
- tree_engine/core/validation.py +377 -0
- tree_engine/errors.py +104 -0
- tree_engine/exceptions.py +376 -0
- tree_engine/facade.py +4524 -0
- tree_engine/plugins/_statements.py +369 -0
- tree_engine/plugins/bsl/block_edit.py +449 -0
- tree_engine/plugins/bsl/blocks.py +127 -0
- tree_engine/plugins/bsl/checker.py +297 -0
- tree_engine/plugins/bsl/dialects.py +303 -0
- tree_engine/plugins/bsl/generator.py +481 -0
- tree_engine/plugins/bsl/import_map.py +995 -0
- tree_engine/plugins/bsl/plugin.py +452 -0
- tree_engine/plugins/contract.py +355 -0
- tree_engine/plugins/cpp/import_map.py +505 -0
- tree_engine/plugins/cpp/languages.py +99 -0
- tree_engine/plugins/cpp/plugin.py +501 -0
- tree_engine/plugins/csv_format.py +676 -0
- tree_engine/plugins/detachable.py +156 -0
- tree_engine/plugins/fallback.py +421 -0
- tree_engine/plugins/ini_format.py +330 -0
- tree_engine/plugins/json_format.py +813 -0
- tree_engine/plugins/json_pointer.py +203 -0
- tree_engine/plugins/jsonl_format.py +392 -0
- tree_engine/plugins/markdown_format.py +748 -0
- tree_engine/plugins/onec_query_format.py +61 -0
- tree_engine/plugins/parse_position.py +54 -0
- tree_engine/plugins/plain_text.py +1543 -0
- tree_engine/plugins/python/export_map.py +306 -0
- tree_engine/plugins/python/import_map.py +429 -0
- tree_engine/plugins/python/plugin.py +1710 -0
- tree_engine/plugins/registry.py +497 -0
- tree_engine/plugins/scan.py +87 -0
- tree_engine/plugins/selection.py +228 -0
- tree_engine/plugins/sql_format.py +61 -0
- tree_engine/plugins/toml_format.py +1072 -0
- tree_engine/plugins/xml_format.py +911 -0
- tree_engine/plugins/yaml/builder.py +49 -0
- tree_engine/plugins/yaml/emitter.py +225 -0
- tree_engine/plugins/yaml/flow.py +227 -0
- tree_engine/plugins/yaml/plugin.py +458 -0
- tree_engine/plugins/yaml/ranges.py +52 -0
- tree_engine/plugins/yaml/reader.py +359 -0
- tree_engine/plugins/yaml/scanner.py +298 -0
- tree_engine/query/adapter.py +283 -0
- tree_engine/query/engine.py +853 -0
- tree_engine/query/inspection.py +498 -0
- tree_engine/query/outline.py +288 -0
- tree_engine/query/predicates.py +263 -0
- tree_engine/query/rendered_lines.py +46 -0
- tree_engine/query/results.py +206 -0
- tree_engine/query/selector.py +400 -0
- tree_engine/query/xml_query.py +747 -0
- tree_engine/storage/codec.py +400 -0
- tree_engine/storage/document_bridge.py +579 -0
- tree_engine/storage/file_txn.py +459 -0
- tree_engine/storage/history.py +106 -0
- tree_engine/storage/lifecycle.py +622 -0
- tree_engine/storage/schema.py +403 -0
- tree_engine/storage/session_guard.py +398 -0
|
@@ -0,0 +1,1543 @@
|
|
|
1
|
+
"""The plain_text format plugin object itself (concept C-016, atomic step A-001).
|
|
2
|
+
|
|
3
|
+
Scope: this module is the mandatory baseline/fallback plugin ({p060}) -- the
|
|
4
|
+
degraded representation any known or explicitly-selected format falls back to
|
|
5
|
+
once its own ``parse_document`` has reported
|
|
6
|
+
``ErrorCode.FORMAT_CONTENT_PARSE_FAILED`` -- and an ordinary plugin in its own
|
|
7
|
+
right for ``.txt``/explicitly-declared text files. Unlike the Python (LibCST)
|
|
8
|
+
and BSL (tree-sitter-bsl) plugins it has no external parser/codegen library to
|
|
9
|
+
wrap: its own "parser-library representation", the intermediate form
|
|
10
|
+
``parse_document``/``parse_fragment`` build before handing off to
|
|
11
|
+
``import_to_common``, is :class:`PlainTextTree`.
|
|
12
|
+
|
|
13
|
+
**Text is a tree of paragraphs and lines.** The common-model shape this plugin
|
|
14
|
+
produces has THREE levels, not two::
|
|
15
|
+
|
|
16
|
+
plain_text:root
|
|
17
|
+
plain_text:paragraph one blank-line-delimited paragraph
|
|
18
|
+
plain_text:line one input line, terminator included verbatim
|
|
19
|
+
|
|
20
|
+
The paragraph level exists because a long document is unusable as a flat list
|
|
21
|
+
of line nodes: drilling into a thousand-line file has to land on paragraphs
|
|
22
|
+
first and descend into the lines of the one paragraph a caller cares about.
|
|
23
|
+
The boundary rule is declared once, in :func:`group_lines_into_paragraphs`,
|
|
24
|
+
and is the same rule ``plugins/fallback.py`` already applied to the degraded
|
|
25
|
+
representation -- that function is now the single implementation both use.
|
|
26
|
+
|
|
27
|
+
Order is carried three ways at once and never rebuilt: dict insertion order in
|
|
28
|
+
``PlainTextTree.paragraphs`` and in each :class:`PlainTextParagraph.lines`,
|
|
29
|
+
tuple order in the common-model ``Node.children`` at both levels, and
|
|
30
|
+
concatenation order in ``generate_output`` -- all populated from one single
|
|
31
|
+
pass over ``str.splitlines(keepends=True)``. Every input line becomes exactly
|
|
32
|
+
one line node and every line node belongs to exactly one paragraph, so
|
|
33
|
+
concatenating the line texts in order reproduces the original decoded string
|
|
34
|
+
exactly, whatever mix of line endings, blank lines, missing trailing newline,
|
|
35
|
+
or unicode content it contains. No normalization, escaping, or reflow happens
|
|
36
|
+
anywhere in this file. In particular a paragraph node built here carries NO
|
|
37
|
+
text of its own: its content IS its lines, which is what makes it impossible
|
|
38
|
+
for the paragraph level to double-count or drop a byte.
|
|
39
|
+
|
|
40
|
+
Two ABCs, one class: as ``PythonFormatPlugin``/``BSLFormatPlugin`` already do,
|
|
41
|
+
``FormatPluginContract`` and ``FormatBoundary`` each declare an abstractmethod
|
|
42
|
+
named ``parse_document`` (likewise ``parse_fragment``) with different call
|
|
43
|
+
conventions -- ``(source, options)`` positional for the contract, ``(source,
|
|
44
|
+
*, source_format_id)`` for the core boundary. ``PlainTextFormatPlugin``
|
|
45
|
+
satisfies both with one concrete method per name whose signature is a superset
|
|
46
|
+
of both; Python's ABC machinery tracks abstractness by method *name*.
|
|
47
|
+
|
|
48
|
+
Failure classification: undecodable input (a text-decoding error, including
|
|
49
|
+
truncated multi-byte content) is the only parse failure this format can have,
|
|
50
|
+
signaled as ``FormatPluginContractError(error_code=ErrorCode.FORMAT_CONTENT_PARSE_FAILED)``
|
|
51
|
+
from :func:`_decode_source`, shared by ``parse_document`` and
|
|
52
|
+
``parse_fragment`` alike -- plain_text has no syntax to fail on once decoding
|
|
53
|
+
succeeds, so there is no fragment-only failure code.
|
|
54
|
+
|
|
55
|
+
No external parser representation escapes this module beyond
|
|
56
|
+
:class:`PlainTextTree`: ``import_to_common``/``export_from_common`` translate
|
|
57
|
+
between it and common-model ``Node``/``Document`` only, and
|
|
58
|
+
``generate_output`` produces plain ``str`` (encoded to ``bytes`` only by
|
|
59
|
+
``render_document``, the ``FormatBoundary``-facing counterpart).
|
|
60
|
+
|
|
61
|
+
Source-of-truth requirement labels honored here: {p022}, {p049}, {p060}.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
from __future__ import annotations
|
|
65
|
+
|
|
66
|
+
import itertools
|
|
67
|
+
import re
|
|
68
|
+
from collections import OrderedDict
|
|
69
|
+
from dataclasses import dataclass, field
|
|
70
|
+
from typing import Any, Iterator, Mapping, Optional, Sequence, Tuple, Union
|
|
71
|
+
from uuid import UUID
|
|
72
|
+
|
|
73
|
+
from tree_engine.core.identity import generate_node_id
|
|
74
|
+
from tree_engine.core.offsets import char_to_byte_offset
|
|
75
|
+
from tree_engine.core.nodes import Document, Node, make_node
|
|
76
|
+
from tree_engine.core.plugin_boundary import FormatBoundary
|
|
77
|
+
from tree_engine.errors import ErrorCode
|
|
78
|
+
from tree_engine.plugins.contract import (
|
|
79
|
+
FormatPluginContract,
|
|
80
|
+
FormatPluginContractError,
|
|
81
|
+
FormatPluginMetadata,
|
|
82
|
+
SemanticRole,
|
|
83
|
+
SemanticRoleMapping,
|
|
84
|
+
UnsupportedTranslationError,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
__all__ = [
|
|
88
|
+
"FORMAT_ID",
|
|
89
|
+
"ROOT_KIND",
|
|
90
|
+
"PARAGRAPH_KIND",
|
|
91
|
+
"LINE_KIND",
|
|
92
|
+
"VERBATIM_TEXT_FIELD",
|
|
93
|
+
"SEPARATOR_FIELD",
|
|
94
|
+
"LEADING_SEPARATOR_FIELD",
|
|
95
|
+
"TRAILING_SEPARATOR_FIELD",
|
|
96
|
+
"ParagraphSpan",
|
|
97
|
+
"TextLayout",
|
|
98
|
+
"split_text_paragraphs",
|
|
99
|
+
"PlainTextParagraph",
|
|
100
|
+
"PlainTextTree",
|
|
101
|
+
"PlainTextFormatPlugin",
|
|
102
|
+
"PLAIN_TEXT_FORMAT_PLUGIN",
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
FORMAT_ID = "plain_text"
|
|
106
|
+
#: The three node kinds of a plain-text tree, published because both this
|
|
107
|
+
#: plugin and ``plugins/fallback.py`` build nodes of them and no caller should
|
|
108
|
+
#: have to re-spell the strings.
|
|
109
|
+
ROOT_KIND = f"{FORMAT_ID}:root"
|
|
110
|
+
PARAGRAPH_KIND = f"{FORMAT_ID}:paragraph"
|
|
111
|
+
LINE_KIND = f"{FORMAT_ID}:line"
|
|
112
|
+
_ROOT_KIND = ROOT_KIND
|
|
113
|
+
_PARAGRAPH_KIND = PARAGRAPH_KIND
|
|
114
|
+
_LINE_KIND = LINE_KIND
|
|
115
|
+
#: Every kind this format owns. A node of any other kind found inside a
|
|
116
|
+
#: plain-text tree is a foreign node and is refused, never rendered.
|
|
117
|
+
_OWN_KINDS = frozenset({ROOT_KIND, PARAGRAPH_KIND, LINE_KIND})
|
|
118
|
+
|
|
119
|
+
#: Optional paragraph-node field naming the *verbatim* source slice a
|
|
120
|
+
#: paragraph stands for. ``export_from_common`` renders it in preference to
|
|
121
|
+
#: ``"text"``, so a producer of ``plain_text:paragraph`` nodes that does not
|
|
122
|
+
#: come through ``parse_document`` -- ``plugins/fallback.py``, whose ``"text"``
|
|
123
|
+
#: is a normalized, human-facing view of a blank-line-delimited paragraph --
|
|
124
|
+
#: still renders back as the exact original bytes. Nodes built by this plugin
|
|
125
|
+
#: never carry it, their ``"text"`` being verbatim already, so none of this
|
|
126
|
+
#: plugin's own paths change.
|
|
127
|
+
VERBATIM_TEXT_FIELD = "source_text"
|
|
128
|
+
|
|
129
|
+
#: Paragraph field holding the verbatim newline run BETWEEN this paragraph and
|
|
130
|
+
#: the next one. Data, not trivia: it is what makes a four-newline gap render
|
|
131
|
+
#: back as four newlines rather than being normalized to two. The last
|
|
132
|
+
#: paragraph's is ``""``; the document's own trailing run lives on the root.
|
|
133
|
+
SEPARATOR_FIELD = "separator"
|
|
134
|
+
|
|
135
|
+
#: The document's two edge attributes, on the ROOT node: the newline run before
|
|
136
|
+
#: the first paragraph's text and the run after the last paragraph's text. Both
|
|
137
|
+
#: are commonly ``""``. They belong to the document rather than to whichever
|
|
138
|
+
#: paragraph sits at an end, and they are the reason a file with no final
|
|
139
|
+
#: newline, one final newline, or five of them all round-trip exactly.
|
|
140
|
+
LEADING_SEPARATOR_FIELD = "leading_separator"
|
|
141
|
+
TRAILING_SEPARATOR_FIELD = "trailing_separator"
|
|
142
|
+
|
|
143
|
+
# Baseline extension table entries ({p062}): ".txt" plus one explicitly
|
|
144
|
+
# declared text-variant extension. More may be added here later without
|
|
145
|
+
# touching any other module -- the shared registry treats an extension
|
|
146
|
+
# conflict with a *different* format_id as a configuration error.
|
|
147
|
+
_METADATA = FormatPluginMetadata(
|
|
148
|
+
format_id=FORMAT_ID,
|
|
149
|
+
aliases=(),
|
|
150
|
+
file_extensions=("txt", "text"),
|
|
151
|
+
plugin_version="1.0.0",
|
|
152
|
+
contract_version="1.0.0",
|
|
153
|
+
capabilities={
|
|
154
|
+
# Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
|
|
155
|
+
# instead of keeping its own list of unsupported suffixes.
|
|
156
|
+
"ca_save_supported": True,
|
|
157
|
+
"semantic_role_mapping": True,
|
|
158
|
+
# Measured: pipeline/checks/check_roundtrip.py's STRICT policy for
|
|
159
|
+
# plain_text round-tripped the FULL real corpus (654/654 tracked
|
|
160
|
+
# .txt/.md files, no sampling) byte-identical -- True is honest.
|
|
161
|
+
"byte_identical_round_trip": True,
|
|
162
|
+
"fallback_representation": True,
|
|
163
|
+
# Addressable paragraph/line tree, walkable for preview/search.
|
|
164
|
+
"navigable": True,
|
|
165
|
+
# Round trip is byte-identical and the paragraph/line tree
|
|
166
|
+
# supports structural mutation -- safe for write-back.
|
|
167
|
+
"editable": True,
|
|
168
|
+
},
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# Plain text has no function/method/class construct, so only the root kind
|
|
172
|
+
# maps to the module role, per SemanticRoleMapping's documented
|
|
173
|
+
# "absent role -> empty tuple" contract for the roles it does not have.
|
|
174
|
+
_ROLE_MAP = SemanticRoleMapping({_ROOT_KIND: SemanticRole.MODULE})
|
|
175
|
+
|
|
176
|
+
# Every node built here gets a node_id plus a compact short_id ({p097}),
|
|
177
|
+
# from one module-level counter shared by all of them.
|
|
178
|
+
_short_id_counter = itertools.count(1)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _contract_error(
|
|
182
|
+
message: str, *, code: ErrorCode = ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR
|
|
183
|
+
) -> FormatPluginContractError:
|
|
184
|
+
return FormatPluginContractError(
|
|
185
|
+
plugin_id=FORMAT_ID, error_code=code, message=message
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
#: The document's two edge runs. Deliberately just ``\r`` and ``\n``: the rule
|
|
190
|
+
#: is about NEWLINES, so a line of spaces is content, not a boundary, and a
|
|
191
|
+
#: document whose author put spaces on a line is never silently reflowed.
|
|
192
|
+
_LEADING_RUN = re.compile(r"\A[\r\n]*")
|
|
193
|
+
_TRAILING_RUN = re.compile(r"[\r\n]*\Z")
|
|
194
|
+
#: The first line terminator of a run: ``\r\n``, ``\n`` or a lone ``\r``.
|
|
195
|
+
_FIRST_TERMINATOR = re.compile(r"\r\n|\n|\r")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@dataclass(frozen=True)
|
|
199
|
+
class ParagraphSpan:
|
|
200
|
+
"""One paragraph: its content lines, their line numbers, and its separator.
|
|
201
|
+
|
|
202
|
+
``lines`` are the verbatim content lines, never empty and never blank.
|
|
203
|
+
``line_numbers`` are their 0-based indices in the document's own line list,
|
|
204
|
+
so a caller that addresses text by line number can place the paragraph
|
|
205
|
+
without re-splitting anything. ``separator`` is the verbatim blank-line run
|
|
206
|
+
BETWEEN this paragraph and the next one; the last paragraph's is ``""``,
|
|
207
|
+
because the document's trailing run is an attribute of the TREE, not of
|
|
208
|
+
whichever paragraph happens to sit at the end.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
lines: Tuple[str, ...]
|
|
212
|
+
line_numbers: Tuple[int, ...]
|
|
213
|
+
separator: str
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@dataclass(frozen=True)
|
|
217
|
+
class TextLayout:
|
|
218
|
+
"""How one text document is cut into paragraphs, edges included.
|
|
219
|
+
|
|
220
|
+
``leading_separator`` and ``trailing_separator`` are the document's two
|
|
221
|
+
edge attributes: the run of newlines before the first paragraph's text and
|
|
222
|
+
the run after the last paragraph's text. Both are commonly ``""`` -- a file
|
|
223
|
+
that starts with text and ends without a final newline has neither -- and
|
|
224
|
+
both are stored as the exact bytes, never as a count to regenerate.
|
|
225
|
+
|
|
226
|
+
The tiling identity, which is the whole point::
|
|
227
|
+
|
|
228
|
+
leading_separator
|
|
229
|
+
+ "".join(p.lines) + p.separator for each paragraph in order
|
|
230
|
+
+ trailing_separator
|
|
231
|
+
== the original text
|
|
232
|
+
|
|
233
|
+
A document with no content at all has no paragraphs; its entire payload is
|
|
234
|
+
the leading separator, because an empty paragraph is not allowed to exist.
|
|
235
|
+
"""
|
|
236
|
+
|
|
237
|
+
leading_separator: str
|
|
238
|
+
trailing_separator: str
|
|
239
|
+
paragraphs: Tuple[ParagraphSpan, ...]
|
|
240
|
+
|
|
241
|
+
def render(self) -> str:
|
|
242
|
+
"""Reassemble the exact source text from the layout."""
|
|
243
|
+
|
|
244
|
+
return (
|
|
245
|
+
self.leading_separator
|
|
246
|
+
+ "".join(
|
|
247
|
+
"".join(paragraph.lines) + paragraph.separator
|
|
248
|
+
for paragraph in self.paragraphs
|
|
249
|
+
)
|
|
250
|
+
+ self.trailing_separator
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def split_text_paragraphs(
|
|
255
|
+
text: str,
|
|
256
|
+
*,
|
|
257
|
+
split_lines: Optional[Any] = None,
|
|
258
|
+
) -> TextLayout:
|
|
259
|
+
"""Cut ``text`` into paragraphs, capturing every separator verbatim.
|
|
260
|
+
|
|
261
|
+
The single declared paragraph-boundary rule of the plain-text format, and
|
|
262
|
+
the only place it is implemented -- ``plugins/fallback.py`` calls this
|
|
263
|
+
function rather than carrying a second copy. The rule, as the owner states
|
|
264
|
+
it:
|
|
265
|
+
|
|
266
|
+
* the start of the text is the start of the first paragraph;
|
|
267
|
+
* the text after each run of newlines starts the NEXT paragraph, but ONLY
|
|
268
|
+
IF text actually follows that run. A run of three, four or ten newlines
|
|
269
|
+
is therefore ONE boundary with a LONGER separator, never a chain of empty
|
|
270
|
+
paragraphs;
|
|
271
|
+
* consequently a paragraph NEVER has empty content: every paragraph
|
|
272
|
+
returned here has at least one content line;
|
|
273
|
+
* a run of newlines with nothing after it opens no paragraph. It is the
|
|
274
|
+
document's ``trailing_separator``;
|
|
275
|
+
* newlines before the first content likewise open no paragraph. They are
|
|
276
|
+
the document's ``leading_separator``.
|
|
277
|
+
|
|
278
|
+
Both edges therefore belong to the DOCUMENT and both may be ``""``; only
|
|
279
|
+
the boundary BETWEEN two paragraphs is paragraph-level data. The exact
|
|
280
|
+
bytes are carried, never a count: a document written with ``\\r\\n`` has
|
|
281
|
+
edges and separators made of ``\\r\\n`` pairs, and a run of five newlines
|
|
282
|
+
comes back as five.
|
|
283
|
+
|
|
284
|
+
``split_lines`` lets a caller keep its own line-splitting rule --
|
|
285
|
+
``str.splitlines(keepends=True)`` by default, a stricter three-terminator
|
|
286
|
+
regex in the fallback builder, which must not re-cut a rescued binary file
|
|
287
|
+
at a form feed. Only the paragraph cut is shared.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
splitter = split_lines if split_lines is not None else _default_split_lines
|
|
291
|
+
leading = _leading_run(text)
|
|
292
|
+
rest = text[len(leading) :]
|
|
293
|
+
trailing = _trailing_run(rest)
|
|
294
|
+
body = rest[: len(rest) - len(trailing)] if trailing else rest
|
|
295
|
+
offset = len(splitter(leading))
|
|
296
|
+
|
|
297
|
+
paragraphs: list[ParagraphSpan] = []
|
|
298
|
+
current: list[Tuple[int, str]] = []
|
|
299
|
+
pending: list[str] = []
|
|
300
|
+
for index, line in enumerate(splitter(body), start=offset):
|
|
301
|
+
if line.rstrip("\r\n") == "":
|
|
302
|
+
pending.append(line)
|
|
303
|
+
continue
|
|
304
|
+
if pending:
|
|
305
|
+
# Text follows the run, so the run WAS a boundary and this line
|
|
306
|
+
# opens the next paragraph. Body has no leading or trailing blank
|
|
307
|
+
# run left, so `pending` can only ever be an inter-paragraph one.
|
|
308
|
+
paragraphs.append(_span(current, "".join(pending)))
|
|
309
|
+
current, pending = [], []
|
|
310
|
+
current.append((index, line))
|
|
311
|
+
if current:
|
|
312
|
+
paragraphs.append(_span(current, ""))
|
|
313
|
+
return TextLayout(leading, trailing, tuple(paragraphs))
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _fold_edges_into_lines(tree: PlainTextTree) -> PlainTextTree:
|
|
317
|
+
"""Move a FRAGMENT's edge runs into its content lines.
|
|
318
|
+
|
|
319
|
+
The two edge attributes are a DOCUMENT's, and they live on the root node.
|
|
320
|
+
A fragment has no document of its own: ``facade._fragment`` unwraps the
|
|
321
|
+
root container this plugin returns and splices its PARAGRAPHS into someone
|
|
322
|
+
else's tree, so anything left on that root is dropped on the floor -- a
|
|
323
|
+
fragment ending in a newline would arrive without it. Folding the runs back
|
|
324
|
+
into the first and last line keeps every byte of the fragment inside the
|
|
325
|
+
nodes that actually travel.
|
|
326
|
+
|
|
327
|
+
A fragment made of nothing but newlines has no content line to fold into,
|
|
328
|
+
so it becomes one paragraph holding that run. The "no empty paragraph" rule
|
|
329
|
+
governs how a DOCUMENT is cut; a caller who explicitly asks to insert blank
|
|
330
|
+
lines is inserting content, and dropping it would be the real error.
|
|
331
|
+
"""
|
|
332
|
+
|
|
333
|
+
if not tree.leading_separator and not tree.trailing_separator:
|
|
334
|
+
return tree
|
|
335
|
+
if not tree.paragraphs:
|
|
336
|
+
paragraph = tree.append_paragraph()
|
|
337
|
+
paragraph.append_line(tree.leading_separator + tree.trailing_separator)
|
|
338
|
+
else:
|
|
339
|
+
first = next(iter(tree.paragraphs.values()))
|
|
340
|
+
last = next(reversed(tree.paragraphs.values()))
|
|
341
|
+
if tree.leading_separator:
|
|
342
|
+
key = next(iter(first.lines))
|
|
343
|
+
first.lines[key] = tree.leading_separator + first.lines[key]
|
|
344
|
+
if tree.trailing_separator:
|
|
345
|
+
key = next(reversed(last.lines))
|
|
346
|
+
last.lines[key] = last.lines[key] + tree.trailing_separator
|
|
347
|
+
tree.leading_separator = ""
|
|
348
|
+
tree.trailing_separator = ""
|
|
349
|
+
return tree
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _default_split_lines(text: str) -> list:
|
|
353
|
+
"""The plugin's own line rule: one entry per ``splitlines`` line, verbatim."""
|
|
354
|
+
|
|
355
|
+
return text.splitlines(keepends=True)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _span(numbered: Sequence[Tuple[int, str]], separator: str) -> ParagraphSpan:
|
|
359
|
+
"""Build one span from ``(line_number, line)`` pairs and its separator."""
|
|
360
|
+
|
|
361
|
+
return ParagraphSpan(
|
|
362
|
+
lines=tuple(line for _number, line in numbered),
|
|
363
|
+
line_numbers=tuple(number for number, _line in numbered),
|
|
364
|
+
separator=separator,
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _leading_run(text: str) -> str:
|
|
369
|
+
"""The run of newlines the document opens with, possibly ``""``."""
|
|
370
|
+
|
|
371
|
+
match = _LEADING_RUN.match(text)
|
|
372
|
+
return "" if match is None else match.group(0)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _trailing_run(text: str) -> str:
|
|
376
|
+
"""The run of newlines the document closes with, possibly ``""``."""
|
|
377
|
+
|
|
378
|
+
match = _TRAILING_RUN.search(text)
|
|
379
|
+
return "" if match is None else match.group(0)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
@dataclass
|
|
383
|
+
class PlainTextParagraph:
|
|
384
|
+
"""One paragraph of the intermediate representation: identity plus lines.
|
|
385
|
+
|
|
386
|
+
``node_id`` is the fresh UUID4 the paragraph node will carry; ``lines`` is
|
|
387
|
+
the ordered dictionary of its CONTENT line texts, each under its own fresh
|
|
388
|
+
UUID4, and is never empty. ``separator`` is the verbatim newline run
|
|
389
|
+
BETWEEN this paragraph and the next -- data, not trivia: it is stored so
|
|
390
|
+
the render reproduces ``\\n\\n\\n\\n`` where the source had four newlines
|
|
391
|
+
instead of normalizing it to two. The last paragraph's is ``""``: the
|
|
392
|
+
document's own trailing run is an attribute of the TREE. A paragraph holds
|
|
393
|
+
no text of its own beyond that; :attr:`text` is derived, never stored.
|
|
394
|
+
"""
|
|
395
|
+
|
|
396
|
+
node_id: UUID
|
|
397
|
+
lines: "OrderedDict[UUID, str]" = field(default_factory=OrderedDict)
|
|
398
|
+
separator: str = ""
|
|
399
|
+
|
|
400
|
+
def append_line(self, text: str) -> UUID:
|
|
401
|
+
"""Append ``text`` as a new line under a fresh UUID4 key."""
|
|
402
|
+
|
|
403
|
+
node_id = generate_node_id()
|
|
404
|
+
self.lines[node_id] = text
|
|
405
|
+
return node_id
|
|
406
|
+
|
|
407
|
+
@property
|
|
408
|
+
def text(self) -> str:
|
|
409
|
+
"""This paragraph's verbatim source slice: its content lines."""
|
|
410
|
+
|
|
411
|
+
return "".join(self.lines.values())
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
@dataclass
|
|
415
|
+
class PlainTextTree:
|
|
416
|
+
"""The plugin's own parser-library-equivalent representation: a root
|
|
417
|
+
container plus an ordered dictionary of paragraphs keyed by fresh UUID4
|
|
418
|
+
identifiers, each paragraph holding its own ordered dictionary of content
|
|
419
|
+
lines and the separator to the next one -- the exact shape {p060} requires
|
|
420
|
+
of the mandatory degraded representation, with the paragraph level long
|
|
421
|
+
texts need to be navigable.
|
|
422
|
+
|
|
423
|
+
The tree carries the document's TWO EDGE ATTRIBUTES:
|
|
424
|
+
``leading_separator``, the newline run before the first paragraph's text,
|
|
425
|
+
and ``trailing_separator``, the run after the last paragraph's text. Both
|
|
426
|
+
are commonly ``""`` -- a file that starts with text and ends without a
|
|
427
|
+
final newline has neither -- and both hold exact bytes, never a count. They
|
|
428
|
+
live here rather than on a paragraph because they are properties of the
|
|
429
|
+
DOCUMENT, not of whichever paragraph happens to sit at an end; for a
|
|
430
|
+
document with no content at all ``leading_separator`` holds the whole
|
|
431
|
+
payload and there are no paragraphs, because an empty paragraph is not
|
|
432
|
+
allowed to exist.
|
|
433
|
+
|
|
434
|
+
Insertion order is dict order at both levels, the single source of truth
|
|
435
|
+
for order through ``import_to_common`` and back out through
|
|
436
|
+
``generate_output``."""
|
|
437
|
+
|
|
438
|
+
paragraphs: "OrderedDict[UUID, PlainTextParagraph]" = field(
|
|
439
|
+
default_factory=OrderedDict
|
|
440
|
+
)
|
|
441
|
+
leading_separator: str = ""
|
|
442
|
+
trailing_separator: str = ""
|
|
443
|
+
|
|
444
|
+
def append_paragraph(self, separator: str = "") -> PlainTextParagraph:
|
|
445
|
+
"""Append and return a new, empty paragraph under a fresh UUID4 key."""
|
|
446
|
+
|
|
447
|
+
paragraph = PlainTextParagraph(node_id=generate_node_id(), separator=separator)
|
|
448
|
+
self.paragraphs[paragraph.node_id] = paragraph
|
|
449
|
+
return paragraph
|
|
450
|
+
|
|
451
|
+
def render(self) -> str:
|
|
452
|
+
"""The document's verbatim text: leading run, paragraphs, trailing run."""
|
|
453
|
+
|
|
454
|
+
return (
|
|
455
|
+
self.leading_separator
|
|
456
|
+
+ "".join(
|
|
457
|
+
paragraph.text + paragraph.separator
|
|
458
|
+
for paragraph in self.paragraphs.values()
|
|
459
|
+
)
|
|
460
|
+
+ self.trailing_separator
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
def line_texts(self) -> Tuple[str, ...]:
|
|
464
|
+
"""Every line of every paragraph, in source order."""
|
|
465
|
+
|
|
466
|
+
return tuple(
|
|
467
|
+
text
|
|
468
|
+
for paragraph in self.paragraphs.values()
|
|
469
|
+
for text in paragraph.lines.values()
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _decode_source(
|
|
474
|
+
source: Union[str, bytes, bytearray], options: Optional[Mapping[str, Any]]
|
|
475
|
+
) -> str:
|
|
476
|
+
"""Decode ``source`` to ``str``, raising ``FORMAT_CONTENT_PARSE_FAILED`` for
|
|
477
|
+
undecodable input (bad encoding or truncated multi-byte content).
|
|
478
|
+
``options["encoding"]`` selects the codec, default ``"utf-8"``."""
|
|
479
|
+
|
|
480
|
+
if isinstance(source, str):
|
|
481
|
+
return source
|
|
482
|
+
if isinstance(source, (bytes, bytearray)):
|
|
483
|
+
encoding = (options or {}).get("encoding", "utf-8")
|
|
484
|
+
try:
|
|
485
|
+
return bytes(source).decode(encoding)
|
|
486
|
+
except (UnicodeDecodeError, LookupError) as exc:
|
|
487
|
+
raise _contract_error(
|
|
488
|
+
f"cannot decode plain_text source as {encoding!r}: {exc}",
|
|
489
|
+
code=ErrorCode.FORMAT_CONTENT_PARSE_FAILED,
|
|
490
|
+
) from exc
|
|
491
|
+
raise _contract_error(
|
|
492
|
+
f"plain_text source must be str or bytes, got {type(source).__name__}"
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _split_paragraphs(text: str) -> PlainTextTree:
|
|
497
|
+
"""Split ``text`` into paragraphs of content lines plus their separators.
|
|
498
|
+
|
|
499
|
+
One line node per non-blank ``splitlines(keepends=True)`` entry -- each
|
|
500
|
+
line's own terminator (or lack of one, for a final unterminated line) stays
|
|
501
|
+
attached verbatim -- cut into paragraphs by :func:`split_text_paragraphs`.
|
|
502
|
+
Because that cut tiles the input exactly, the paragraph level costs nothing
|
|
503
|
+
in fidelity: ``leading_separator`` plus each paragraph's content and its
|
|
504
|
+
separator is still ``text``, byte for byte.
|
|
505
|
+
"""
|
|
506
|
+
|
|
507
|
+
layout = split_text_paragraphs(text)
|
|
508
|
+
tree = PlainTextTree(
|
|
509
|
+
leading_separator=layout.leading_separator,
|
|
510
|
+
trailing_separator=layout.trailing_separator,
|
|
511
|
+
)
|
|
512
|
+
for span in layout.paragraphs:
|
|
513
|
+
paragraph = tree.append_paragraph(span.separator)
|
|
514
|
+
for line in span.lines:
|
|
515
|
+
paragraph.append_line(line)
|
|
516
|
+
return tree
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _iter_content_nodes(root: Node) -> Iterator[Node]:
|
|
520
|
+
"""Yield the nodes actually carrying text under ``root``, in source order.
|
|
521
|
+
|
|
522
|
+
Structural rather than positional: a node with children is a container and
|
|
523
|
+
contributes its descendants' text, a node without children carries its own.
|
|
524
|
+
That is what lets ONE walker serve every legitimate shape a plain-text tree
|
|
525
|
+
can take --
|
|
526
|
+
|
|
527
|
+
* the canonical parse result, ``root -> paragraph -> line``;
|
|
528
|
+
* the fragment case, where ``root`` is itself a paragraph or a line;
|
|
529
|
+
* a fallback document (``plugins/fallback.py``), whose paragraphs carry
|
|
530
|
+
their verbatim slice on the node itself and have no line children;
|
|
531
|
+
* a tree a caller has spliced into, where ``facade._fragment`` unwrapped a
|
|
532
|
+
parsed fragment's root container and inserted its paragraphs beside a
|
|
533
|
+
line -- nesting that renders correctly here instead of raising
|
|
534
|
+
``UNSUPPORTED_TRANSLATION`` on the next ``dumps()``.
|
|
535
|
+
|
|
536
|
+
A node of a kind this format does not own is a foreign node: it raises
|
|
537
|
+
:class:`UnsupportedTranslationError` rather than being silently dropped
|
|
538
|
+
({p049}).
|
|
539
|
+
"""
|
|
540
|
+
|
|
541
|
+
if root.kind not in _OWN_KINDS:
|
|
542
|
+
raise UnsupportedTranslationError(node_type=str(root.kind), format_id=FORMAT_ID)
|
|
543
|
+
if not root.children:
|
|
544
|
+
# The root container of an empty document has no children and no text
|
|
545
|
+
# of its own; it contributes nothing rather than an empty phantom line.
|
|
546
|
+
if root.kind != _ROOT_KIND:
|
|
547
|
+
yield root
|
|
548
|
+
return
|
|
549
|
+
for child in root.children:
|
|
550
|
+
yield from _iter_content_nodes(child)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _iter_export_paragraphs(root: Node) -> Iterator[Node]:
|
|
554
|
+
"""Yield the nodes that stand for one paragraph each, in source order.
|
|
555
|
+
|
|
556
|
+
For the canonical document that is the root container's children. For the
|
|
557
|
+
fragment cases -- ``root`` is itself a paragraph, or a bare line -- the
|
|
558
|
+
node handed in stands for the whole thing and is yielded as it is, so an
|
|
559
|
+
exported fragment is one paragraph rather than none. The kind check that
|
|
560
|
+
refuses a foreign node lives in :func:`_iter_content_nodes`, which every
|
|
561
|
+
branch below feeds.
|
|
562
|
+
"""
|
|
563
|
+
|
|
564
|
+
if root.kind == _ROOT_KIND:
|
|
565
|
+
yield from root.children
|
|
566
|
+
return
|
|
567
|
+
yield root
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _node_identity(node: Node) -> UUID:
|
|
571
|
+
"""``node``'s UUID4, or a fresh one when it carries no usable identity."""
|
|
572
|
+
|
|
573
|
+
return node.node_id if isinstance(node.node_id, UUID) else generate_node_id()
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _node_text(node: Node) -> str:
|
|
577
|
+
"""The verbatim source slice ``node`` stands for.
|
|
578
|
+
|
|
579
|
+
:data:`VERBATIM_TEXT_FIELD` wins over ``"text"`` so a producer whose
|
|
580
|
+
``"text"`` is a normalized, human-facing view -- ``plugins/fallback.py`` --
|
|
581
|
+
still renders back as the exact original bytes.
|
|
582
|
+
"""
|
|
583
|
+
|
|
584
|
+
verbatim = node.fields.get(VERBATIM_TEXT_FIELD)
|
|
585
|
+
if isinstance(verbatim, str):
|
|
586
|
+
return verbatim
|
|
587
|
+
text = node.fields.get("text", "")
|
|
588
|
+
return text if isinstance(text, str) else ""
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _last_content_text(node: Any) -> str:
|
|
592
|
+
"""The verbatim text of the last leaf line under ``node``, walking through nested
|
|
593
|
+
paragraph/line shapes the same way :func:`_iter_content_nodes` does (duck-typed on
|
|
594
|
+
``.children``/``.fields`` so it works on both the common ``Node`` and a live
|
|
595
|
+
``core.live_tree.LiveNode``, unlike :func:`_iter_content_nodes` itself, which is
|
|
596
|
+
``Node``-only and raises on a foreign kind -- this helper is read-only trivia
|
|
597
|
+
inspection, never a translation boundary, so it has no need of that check).
|
|
598
|
+
|
|
599
|
+
Recurses to the last child until a childless leaf is reached, then reads that leaf's
|
|
600
|
+
own text via :func:`_node_text` -- ``""`` for a genuinely empty container (the root of
|
|
601
|
+
an empty document), never raising.
|
|
602
|
+
"""
|
|
603
|
+
|
|
604
|
+
children = getattr(node, "children", None)
|
|
605
|
+
if children:
|
|
606
|
+
return _last_content_text(children[-1])
|
|
607
|
+
return _node_text(node)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _release_trailing_after_removal(parent: Any) -> None:
|
|
611
|
+
"""Restore the separator-ownership invariant on ``parent`` (the ROOT) after nodes have been
|
|
612
|
+
detached from the END of its ``children`` -- the paragraph that used to be last, and with it
|
|
613
|
+
the run this format tracks as ``trailing_separator``, is gone.
|
|
614
|
+
|
|
615
|
+
The run leaves WITH the detached content: this function only ever CLEARS
|
|
616
|
+
``trailing_separator``, it never migrates it onto whatever paragraph is now last -- that
|
|
617
|
+
paragraph already renders correctly with its own ``separator`` field untouched, because
|
|
618
|
+
``paragraph.separator + trailing_separator`` is read back-to-back with nothing between them,
|
|
619
|
+
so the split between the two fields is redundant for rendering. What is NOT redundant is the
|
|
620
|
+
invariant itself: the new-last paragraph must end up with an EMPTY ``separator`` (mirroring
|
|
621
|
+
every other last paragraph the plugin ever builds), so a second detach reads the same
|
|
622
|
+
``separator == ""`` signal reliably instead of drifting after repeated cycles. Restoring it
|
|
623
|
+
costs nothing byte-wise, since moving a run from a paragraph's own ``separator`` into
|
|
624
|
+
``trailing_separator`` -- both read adjacently at render time -- changes no rendered byte.
|
|
625
|
+
"""
|
|
626
|
+
|
|
627
|
+
remaining = list(parent.children)
|
|
628
|
+
parent.fields = {**parent.fields, TRAILING_SEPARATOR_FIELD: ""}
|
|
629
|
+
if not remaining:
|
|
630
|
+
return
|
|
631
|
+
new_last = remaining[-1]
|
|
632
|
+
carried = _field_str(new_last, SEPARATOR_FIELD)
|
|
633
|
+
if carried:
|
|
634
|
+
parent.fields = {**parent.fields, TRAILING_SEPARATOR_FIELD: carried}
|
|
635
|
+
new_last.fields = {**new_last.fields, SEPARATOR_FIELD: ""}
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _fold_trailing_into_moved(parent: Any, moved_last: Any) -> None:
|
|
639
|
+
"""Move's own detach-side repair: like :func:`_release_trailing_after_removal`, restores the
|
|
640
|
+
invariant on ``parent`` after its trailing run's owner has been detached -- but the detached
|
|
641
|
+
content is not leaving the document, so the run must travel WITH ``moved_last`` (folded onto
|
|
642
|
+
its own ``separator``) rather than being dropped. The new-last paragraph left behind in
|
|
643
|
+
``parent`` still gets the same invariant-restoring treatment as a plain deletion.
|
|
644
|
+
"""
|
|
645
|
+
|
|
646
|
+
trailing = _field_str(parent, TRAILING_SEPARATOR_FIELD)
|
|
647
|
+
if trailing:
|
|
648
|
+
moved_last.fields = {
|
|
649
|
+
**moved_last.fields,
|
|
650
|
+
SEPARATOR_FIELD: _field_str(moved_last, SEPARATOR_FIELD) + trailing,
|
|
651
|
+
}
|
|
652
|
+
parent.fields = {**parent.fields, TRAILING_SEPARATOR_FIELD: ""}
|
|
653
|
+
_release_trailing_after_removal(parent)
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _claim_trailing_for_new_last(parent: Any, fresh_ids: Any) -> None:
|
|
657
|
+
"""Restore the invariant on ``parent`` (the ROOT) after nodes identified by ``fresh_ids``
|
|
658
|
+
landed at the END of its ``children``, becoming the new last paragraph: the mirror of
|
|
659
|
+
:func:`_release_trailing_after_removal`. ``trailing_separator`` described what used to follow
|
|
660
|
+
the OLD last paragraph, which is no longer last, so it is migrated onto that paragraph's own
|
|
661
|
+
``separator`` and cleared from the root -- the new last paragraph needs no field change of
|
|
662
|
+
its own, since a freshly parsed or freshly detached fragment already carries ``separator ==
|
|
663
|
+
""`` for the paragraph now playing that role (the same invariant, restored from the source
|
|
664
|
+
side already, or true by construction for a brand new fragment).
|
|
665
|
+
"""
|
|
666
|
+
|
|
667
|
+
children = list(parent.children)
|
|
668
|
+
if not children or id(children[-1]) not in fresh_ids:
|
|
669
|
+
return
|
|
670
|
+
trailing = _field_str(parent, TRAILING_SEPARATOR_FIELD)
|
|
671
|
+
if not trailing:
|
|
672
|
+
return
|
|
673
|
+
position = len(children) - 1
|
|
674
|
+
while position >= 0 and id(children[position]) in fresh_ids:
|
|
675
|
+
position -= 1
|
|
676
|
+
if position < 0:
|
|
677
|
+
# Every child is fresh (the document was empty before this splice): trailing describes
|
|
678
|
+
# what follows the LAST fresh node still, and it already sits on `parent`; nothing moves.
|
|
679
|
+
return
|
|
680
|
+
predecessor = children[position]
|
|
681
|
+
predecessor.fields = {
|
|
682
|
+
**predecessor.fields,
|
|
683
|
+
SEPARATOR_FIELD: _field_str(predecessor, SEPARATOR_FIELD) + trailing,
|
|
684
|
+
}
|
|
685
|
+
parent.fields = {**parent.fields, TRAILING_SEPARATOR_FIELD: ""}
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _hand_moved_gap_to_predecessor(parent: Any, moved_ids: Any) -> None:
|
|
689
|
+
"""Attach-side repair for a paragraph that was NOT the source's last and now closes ``parent``
|
|
690
|
+
(bug df5c91d0): its ``separator`` described the blank gap to its OLD successor, and its own
|
|
691
|
+
last line still ends with a terminator, so a last paragraph must carry ``separator == ""``.
|
|
692
|
+
The gap becomes the separator of the paragraph now preceding the moved run (after the
|
|
693
|
+
trailing run it already claimed), instead of being rendered after the moved paragraph.
|
|
694
|
+
"""
|
|
695
|
+
|
|
696
|
+
children = list(parent.children)
|
|
697
|
+
if not children or id(children[-1]) not in moved_ids:
|
|
698
|
+
return
|
|
699
|
+
position = len(children) - 1
|
|
700
|
+
while position >= 0 and id(children[position]) in moved_ids:
|
|
701
|
+
position -= 1
|
|
702
|
+
if position < 0:
|
|
703
|
+
return
|
|
704
|
+
moved_last = children[-1]
|
|
705
|
+
gap = _field_str(moved_last, SEPARATOR_FIELD)
|
|
706
|
+
if not gap:
|
|
707
|
+
return
|
|
708
|
+
predecessor = children[position]
|
|
709
|
+
predecessor.fields = {
|
|
710
|
+
**predecessor.fields,
|
|
711
|
+
SEPARATOR_FIELD: _field_str(predecessor, SEPARATOR_FIELD) + gap,
|
|
712
|
+
}
|
|
713
|
+
moved_last.fields = {**moved_last.fields, SEPARATOR_FIELD: ""}
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _fold_separator_into_moved_line(parent: Any, moved_last: Any) -> None:
|
|
717
|
+
"""Move's own detach-side repair for a PARAGRAPH parent (within-paragraph LINE move).
|
|
718
|
+
|
|
719
|
+
Mirrors :func:`_fold_trailing_into_moved` but works differently for lines,
|
|
720
|
+
since lines don't have a separator field. When a line is moved out of being
|
|
721
|
+
the last child of a paragraph, and the parent's own parent (the ROOT) has a
|
|
722
|
+
trailing_separator, that separator travels WITH the moved line, folded into
|
|
723
|
+
its text field.
|
|
724
|
+
"""
|
|
725
|
+
|
|
726
|
+
# Check if this paragraph has a parent (which should be the ROOT)
|
|
727
|
+
para_parent = getattr(parent, "parent", None)
|
|
728
|
+
if para_parent is not None and para_parent.kind == _ROOT_KIND:
|
|
729
|
+
trailing = _field_str(para_parent, TRAILING_SEPARATOR_FIELD)
|
|
730
|
+
if trailing:
|
|
731
|
+
# Append the root's trailing separator to the moved line's text
|
|
732
|
+
moved_last.fields = {
|
|
733
|
+
**moved_last.fields,
|
|
734
|
+
"text": _field_str(moved_last, "text") + trailing,
|
|
735
|
+
}
|
|
736
|
+
para_parent.fields = {**para_parent.fields, TRAILING_SEPARATOR_FIELD: ""}
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def _claim_separator_for_new_last_line(parent: Any, fresh_ids: Any) -> None:
|
|
740
|
+
"""Move's attach-side repair for a PARAGRAPH parent (within-paragraph LINE move).
|
|
741
|
+
|
|
742
|
+
When a line lands at the END of a paragraph's children (making it the new-last line),
|
|
743
|
+
and the old-last line is STILL in the paragraph (not moved out), transfer the root's
|
|
744
|
+
trailing_separator to the old-last line's text. This mirrors the logic for PARAGRAPH
|
|
745
|
+
moves at the ROOT level: the node that loses "last" status gets the separator that
|
|
746
|
+
used to follow the old-last node.
|
|
747
|
+
|
|
748
|
+
If the moved line was the old-last (and _fold_separator_into_moved_line already handled it),
|
|
749
|
+
or if there's no trailing_separator, nothing to do.
|
|
750
|
+
"""
|
|
751
|
+
|
|
752
|
+
children = list(parent.children)
|
|
753
|
+
if not children:
|
|
754
|
+
return
|
|
755
|
+
# Check if the last child is one of the fresh/moved nodes
|
|
756
|
+
if id(children[-1]) not in fresh_ids:
|
|
757
|
+
# The new-last is NOT one of the moved nodes. So something else is now last.
|
|
758
|
+
# This shouldn't happen in a within-paragraph move of a single line.
|
|
759
|
+
return
|
|
760
|
+
|
|
761
|
+
# The last line is now one of the moved nodes (or new lines).
|
|
762
|
+
# Find the old-last line (the one right before the moved range if possible).
|
|
763
|
+
# Actually, since we only moved one node at a time typically, we need to find
|
|
764
|
+
# which line is the old-last (the one that lost last status).
|
|
765
|
+
# For simplicity: the node at position [-2] is the old-last if the new-last
|
|
766
|
+
# is one of the moved nodes. But actually we need to distinguish:
|
|
767
|
+
# 1. If the moved line was originally last, _fold_separator_into_moved_line
|
|
768
|
+
# already handled it and cleared the trailing_separator. We're done.
|
|
769
|
+
# 2. If the moved line was NOT originally last, then the old-last is still
|
|
770
|
+
# in the paragraph somewhere. We need to transfer trailing_separator to it.
|
|
771
|
+
|
|
772
|
+
para_parent = getattr(parent, "parent", None)
|
|
773
|
+
if para_parent is None or para_parent.kind != _ROOT_KIND:
|
|
774
|
+
return
|
|
775
|
+
|
|
776
|
+
trailing = _field_str(para_parent, TRAILING_SEPARATOR_FIELD)
|
|
777
|
+
if not trailing:
|
|
778
|
+
# No trailing_separator at the root, nothing to transfer.
|
|
779
|
+
return
|
|
780
|
+
|
|
781
|
+
# Find the old-last line: it's the one that's NOT in fresh_ids and is
|
|
782
|
+
# now not-last (position < len(children) - 1).
|
|
783
|
+
# Actually, the old-last is at position len(children) - 2 now.
|
|
784
|
+
if len(children) >= 2:
|
|
785
|
+
old_last = children[-2]
|
|
786
|
+
if id(old_last) not in fresh_ids:
|
|
787
|
+
# This line was not moved, so it lost "last" status.
|
|
788
|
+
# Transfer the trailing_separator to its text.
|
|
789
|
+
old_last.fields = {
|
|
790
|
+
**old_last.fields,
|
|
791
|
+
"text": _field_str(old_last, "text") + trailing,
|
|
792
|
+
}
|
|
793
|
+
para_parent.fields = {**para_parent.fields, TRAILING_SEPARATOR_FIELD: ""}
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def _field_str(node: Any, name: str) -> str:
|
|
797
|
+
"""A separator field read off a node, or ``""`` when it carries none.
|
|
798
|
+
|
|
799
|
+
``node`` is a frozen ``core.nodes.Node`` on the export path and the mutable
|
|
800
|
+
``core.live_tree.LiveNode`` on the mutation path
|
|
801
|
+
(:meth:`PlainTextFormatPlugin.adjust_after_insert`); both carry ``fields``,
|
|
802
|
+
and this reader only ever reads it.
|
|
803
|
+
"""
|
|
804
|
+
|
|
805
|
+
value = node.fields.get(name)
|
|
806
|
+
return value if isinstance(value, str) else ""
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
class PlainTextFormatPlugin(FormatPluginContract, FormatBoundary):
|
|
810
|
+
"""The registered ``format_id="plain_text"`` plugin (concept C-016),
|
|
811
|
+
reachable through the same common tree interface as any other format
|
|
812
|
+
plugin ({p060}): a root container ``Node`` holding an ordered tuple of
|
|
813
|
+
paragraph ``Node`` children, each holding an ordered tuple of line ``Node``
|
|
814
|
+
children, every one of them carrying its own ``node_id`` identity."""
|
|
815
|
+
|
|
816
|
+
#: Kinds :meth:`parse_fragment` wraps a caller's content in rather than
|
|
817
|
+
#: returning as content itself. ``plain_text`` has no fragment node type of
|
|
818
|
+
#: its own -- a fragment is parsed by the very same split as a document --
|
|
819
|
+
#: so its result is always the root container, and splicing that container
|
|
820
|
+
#: in beside a paragraph produces a tree ``generate_output`` refuses with
|
|
821
|
+
#: ``UnsupportedTranslationError``: a root container is a wrapper, never
|
|
822
|
+
#: content. Declaring the kind here lets a caller performing a splice
|
|
823
|
+
#: (``facade._fragment``) take the children instead, without having to know
|
|
824
|
+
#: that plain_text in particular does this, and without any format whose
|
|
825
|
+
#: fragment result IS content -- JSON's object, Python's statement -- being
|
|
826
|
+
#: unwrapped by the same rule. ``_ROOT_KIND`` remains a perfectly legal
|
|
827
|
+
#: PARSE result; this says only that it is a wrapper, never content.
|
|
828
|
+
fragment_container_kinds = (_ROOT_KIND,)
|
|
829
|
+
|
|
830
|
+
@property
|
|
831
|
+
def metadata(self) -> FormatPluginMetadata:
|
|
832
|
+
"""This plugin's static identity/capability surface."""
|
|
833
|
+
|
|
834
|
+
return _METADATA
|
|
835
|
+
|
|
836
|
+
def parse_document(
|
|
837
|
+
self,
|
|
838
|
+
source: Union[str, bytes],
|
|
839
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
840
|
+
*,
|
|
841
|
+
source_format_id: Optional[str] = None,
|
|
842
|
+
) -> Document:
|
|
843
|
+
"""Parse full source text/bytes into a common-model ``Document``:
|
|
844
|
+
``source`` is decoded (raising ``FORMAT_CONTENT_PARSE_FAILED`` on
|
|
845
|
+
undecodable content), split into a temporary :class:`PlainTextTree`,
|
|
846
|
+
and handed to ``import_to_common``; no intermediate form survives."""
|
|
847
|
+
|
|
848
|
+
text = _decode_source(source, options)
|
|
849
|
+
tree = _split_paragraphs(text)
|
|
850
|
+
result = self.import_to_common(tree, options, as_document=True, ranged_text=text)
|
|
851
|
+
if not isinstance(result, Document):
|
|
852
|
+
raise _contract_error(
|
|
853
|
+
f"parsing a full plain_text document must yield a Document, got {type(result).__name__}"
|
|
854
|
+
)
|
|
855
|
+
return result
|
|
856
|
+
|
|
857
|
+
def import_external_tree(
|
|
858
|
+
self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
|
|
859
|
+
) -> Union[Node, Document]:
|
|
860
|
+
"""Translate an already-built :class:`PlainTextTree` into common
|
|
861
|
+
nodes, reusing :meth:`import_to_common`, the single shared input
|
|
862
|
+
translator ({p056}, {p057})."""
|
|
863
|
+
|
|
864
|
+
return self.import_to_common(external_tree, options, as_document=True)
|
|
865
|
+
|
|
866
|
+
def parse_fragment(
|
|
867
|
+
self,
|
|
868
|
+
fragment: Union[str, bytes],
|
|
869
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
870
|
+
*,
|
|
871
|
+
source_format_id: Optional[str] = None,
|
|
872
|
+
) -> Node:
|
|
873
|
+
"""Parse a local fragment through the same decode/split pipeline as
|
|
874
|
+
``parse_document``, then reuse ``import_to_common``. Plain text has no
|
|
875
|
+
construct it fails to recognize once decoding succeeds, so this never
|
|
876
|
+
returns the fragment's own text; it always yields a root container
|
|
877
|
+
``Node`` (childless for an empty fragment)."""
|
|
878
|
+
|
|
879
|
+
text = _decode_source(fragment, options)
|
|
880
|
+
tree = _fold_edges_into_lines(_split_paragraphs(text))
|
|
881
|
+
result = self.import_to_common(tree, options, as_document=False)
|
|
882
|
+
if not isinstance(result, Node):
|
|
883
|
+
raise _contract_error(
|
|
884
|
+
f"parsing a plain_text fragment must yield a Node, got {type(result).__name__}"
|
|
885
|
+
)
|
|
886
|
+
return result
|
|
887
|
+
|
|
888
|
+
def import_to_common(
|
|
889
|
+
self,
|
|
890
|
+
external_representation: Any,
|
|
891
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
892
|
+
*,
|
|
893
|
+
as_document: bool = True,
|
|
894
|
+
ranged_text: Optional[str] = None,
|
|
895
|
+
) -> Union[Node, Document]:
|
|
896
|
+
"""The single input translator shared by ``parse_document``,
|
|
897
|
+
``import_external_tree``, and ``parse_fragment``.
|
|
898
|
+
|
|
899
|
+
Builds one line ``Node`` per line of each :class:`PlainTextTree`
|
|
900
|
+
paragraph and one paragraph ``Node`` holding them, each validated via
|
|
901
|
+
``make_node`` then reconstructed carrying the UUID4 the tree already
|
|
902
|
+
assigned it -- the "attach an identity produced elsewhere" pattern
|
|
903
|
+
``core/identity.py`` documents. Order is preserved at both levels by
|
|
904
|
+
iterating the dictionaries in insertion order into ``children``.
|
|
905
|
+
``as_document`` selects a ``Document`` wrapper or a bare root (the
|
|
906
|
+
fragment case); that keyword-only parameter is this plugin's own
|
|
907
|
+
pass-through, as BSL adds ``fragment`` to its own.
|
|
908
|
+
|
|
909
|
+
A paragraph node gets ``line_count`` plus ``separator`` -- the exact
|
|
910
|
+
boundary to the next paragraph -- and no text field at all: its content
|
|
911
|
+
is its lines, so there is no second copy of a byte anywhere in the tree
|
|
912
|
+
and no way for the two to disagree. The root carries the document's two
|
|
913
|
+
edge attributes, :data:`LEADING_SEPARATOR_FIELD` and
|
|
914
|
+
:data:`TRAILING_SEPARATOR_FIELD`.
|
|
915
|
+
"""
|
|
916
|
+
|
|
917
|
+
if not isinstance(external_representation, PlainTextTree):
|
|
918
|
+
raise _contract_error(
|
|
919
|
+
f"expected a PlainTextTree, got {type(external_representation).__name__}"
|
|
920
|
+
)
|
|
921
|
+
# ``ranged_text`` (set only by ``parse_document``) asks for ``buffer_range`` on every node
|
|
922
|
+
# (bug b548f445): half-open UTF-8 byte offsets. The tiling identity of ``TextLayout`` fixes
|
|
923
|
+
# them from lengths alone: root = leading + paragraphs + trailing, paragraph = its lines +
|
|
924
|
+
# its separator, line = its text.
|
|
925
|
+
conv = char_to_byte_offset(ranged_text) if ranged_text is not None else None
|
|
926
|
+
cursor = len(external_representation.leading_separator)
|
|
927
|
+
children = []
|
|
928
|
+
for paragraph in external_representation.paragraphs.values():
|
|
929
|
+
lines = []
|
|
930
|
+
paragraph_start = cursor
|
|
931
|
+
for line_id, text in paragraph.lines.items():
|
|
932
|
+
validated_line = make_node(_LINE_KIND, fields={"text": text})
|
|
933
|
+
lines.append(
|
|
934
|
+
Node(
|
|
935
|
+
kind=validated_line.kind,
|
|
936
|
+
fields=validated_line.fields,
|
|
937
|
+
children=validated_line.children,
|
|
938
|
+
node_id=line_id,
|
|
939
|
+
short_id=next(_short_id_counter),
|
|
940
|
+
buffer_range=(conv(cursor), conv(cursor + len(text))) if conv else None,
|
|
941
|
+
)
|
|
942
|
+
)
|
|
943
|
+
cursor += len(text)
|
|
944
|
+
cursor += len(paragraph.separator)
|
|
945
|
+
validated = make_node(
|
|
946
|
+
_PARAGRAPH_KIND,
|
|
947
|
+
fields={"line_count": len(lines), SEPARATOR_FIELD: paragraph.separator},
|
|
948
|
+
children=lines,
|
|
949
|
+
)
|
|
950
|
+
children.append(
|
|
951
|
+
Node(
|
|
952
|
+
kind=validated.kind,
|
|
953
|
+
fields=validated.fields,
|
|
954
|
+
children=validated.children,
|
|
955
|
+
node_id=paragraph.node_id,
|
|
956
|
+
short_id=next(_short_id_counter),
|
|
957
|
+
buffer_range=(conv(paragraph_start), conv(cursor)) if conv else None,
|
|
958
|
+
)
|
|
959
|
+
)
|
|
960
|
+
validated_root = make_node(
|
|
961
|
+
_ROOT_KIND,
|
|
962
|
+
fields={
|
|
963
|
+
LEADING_SEPARATOR_FIELD: external_representation.leading_separator,
|
|
964
|
+
TRAILING_SEPARATOR_FIELD: external_representation.trailing_separator,
|
|
965
|
+
},
|
|
966
|
+
children=children,
|
|
967
|
+
)
|
|
968
|
+
root = Node(
|
|
969
|
+
kind=validated_root.kind,
|
|
970
|
+
fields=validated_root.fields,
|
|
971
|
+
children=validated_root.children,
|
|
972
|
+
node_id=generate_node_id(),
|
|
973
|
+
short_id=next(_short_id_counter),
|
|
974
|
+
buffer_range=(conv(0), conv(len(ranged_text))) if conv else None,
|
|
975
|
+
)
|
|
976
|
+
if as_document:
|
|
977
|
+
return Document(root=root, source_format_id=FORMAT_ID)
|
|
978
|
+
return root
|
|
979
|
+
|
|
980
|
+
def export_from_common(
|
|
981
|
+
self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
|
|
982
|
+
) -> PlainTextTree:
|
|
983
|
+
"""Translate common-model nodes back into a fresh
|
|
984
|
+
:class:`PlainTextTree`, preserving ``children``/dict order exactly at
|
|
985
|
+
both levels. Accepts a ``Document`` (uses its ``root``) or a bare
|
|
986
|
+
``Node`` (root container, or a single paragraph or line node for the
|
|
987
|
+
fragment case). A node of a foreign kind raises
|
|
988
|
+
:class:`UnsupportedTranslationError` rather than being silently dropped
|
|
989
|
+
({p049}); an existing ``node_id`` is reused as the tree's key at both
|
|
990
|
+
levels, so identity survives a round trip.
|
|
991
|
+
|
|
992
|
+
A paragraph carrying :data:`VERBATIM_TEXT_FIELD` and no line children
|
|
993
|
+
-- the shape ``plugins/fallback.py`` builds -- exports that slice as
|
|
994
|
+
the paragraph's single line, so a producer that keeps a normalized,
|
|
995
|
+
human-facing ``"text"`` still renders byte-identically. Its one line
|
|
996
|
+
is keyed by the paragraph's own UUID4, because for that shape the
|
|
997
|
+
paragraph IS the leaf carrying the bytes.
|
|
998
|
+
|
|
999
|
+
The separators come back off the nodes that carry them -- the two edge
|
|
1000
|
+
attributes off the root, each paragraph's boundary off the paragraph --
|
|
1001
|
+
so a document that went in with a five-newline gap comes out with one.
|
|
1002
|
+
"""
|
|
1003
|
+
|
|
1004
|
+
if isinstance(nodes, Document):
|
|
1005
|
+
root = nodes.root
|
|
1006
|
+
elif isinstance(nodes, Node):
|
|
1007
|
+
root = nodes
|
|
1008
|
+
else:
|
|
1009
|
+
raise _contract_error(
|
|
1010
|
+
f"export_from_common expects a Node or Document, got {type(nodes).__name__}"
|
|
1011
|
+
)
|
|
1012
|
+
tree = PlainTextTree(
|
|
1013
|
+
leading_separator=_field_str(root, LEADING_SEPARATOR_FIELD),
|
|
1014
|
+
trailing_separator=_field_str(root, TRAILING_SEPARATOR_FIELD),
|
|
1015
|
+
)
|
|
1016
|
+
for paragraph_node in _iter_export_paragraphs(root):
|
|
1017
|
+
paragraph = PlainTextParagraph(
|
|
1018
|
+
node_id=_node_identity(paragraph_node),
|
|
1019
|
+
separator=_field_str(paragraph_node, SEPARATOR_FIELD),
|
|
1020
|
+
)
|
|
1021
|
+
for content in _iter_content_nodes(paragraph_node):
|
|
1022
|
+
paragraph.lines[_node_identity(content)] = _node_text(content)
|
|
1023
|
+
tree.paragraphs[paragraph.node_id] = paragraph
|
|
1024
|
+
return tree
|
|
1025
|
+
|
|
1026
|
+
def generate_output(
|
|
1027
|
+
self,
|
|
1028
|
+
target: Union[Node, Document, PlainTextTree, str],
|
|
1029
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
1030
|
+
) -> str:
|
|
1031
|
+
"""Serialize ``target`` to final plain text: runs ``export_from_common``
|
|
1032
|
+
when given common-model nodes, then reassembles the exported
|
|
1033
|
+
:class:`PlainTextTree` -- leading run, then each paragraph's lines
|
|
1034
|
+
followed by its separator, then trailing run. Byte-identical to the
|
|
1035
|
+
original input whenever ``target`` traces back to an untouched parse
|
|
1036
|
+
result, because that concatenation IS the source: no separator is ever
|
|
1037
|
+
regenerated by convention. A ``str`` passes through.
|
|
1038
|
+
"""
|
|
1039
|
+
|
|
1040
|
+
if isinstance(target, PlainTextTree):
|
|
1041
|
+
tree = target
|
|
1042
|
+
elif isinstance(target, (Node, Document)):
|
|
1043
|
+
tree = self.export_from_common(target, options)
|
|
1044
|
+
elif isinstance(target, str):
|
|
1045
|
+
return target
|
|
1046
|
+
else:
|
|
1047
|
+
raise _contract_error(
|
|
1048
|
+
f"cannot generate output for {type(target).__name__}; expected a "
|
|
1049
|
+
"Node, Document, PlainTextTree, or str"
|
|
1050
|
+
)
|
|
1051
|
+
return tree.render()
|
|
1052
|
+
|
|
1053
|
+
def semantic_role_mapping(self) -> SemanticRoleMapping:
|
|
1054
|
+
"""The declarative, context-free kind -> role table: only the root
|
|
1055
|
+
container maps to the module role; plain text has no function, method,
|
|
1056
|
+
or class construct, so those roles get no entry."""
|
|
1057
|
+
|
|
1058
|
+
return _ROLE_MAP
|
|
1059
|
+
|
|
1060
|
+
# -- parent/child admissibility (bug dbc47fcb) -------------------------------
|
|
1061
|
+
|
|
1062
|
+
def is_type_compatible(self, parent: Any, position: Optional[str], incoming: Any) -> bool:
|
|
1063
|
+
"""Whether ``incoming`` may legally become a child of ``parent`` at ``position``
|
|
1064
|
+
(``facade.insert``/``replace``/``set_body``'s shared ``core/validation.py`` preflight,
|
|
1065
|
+
stage 3).
|
|
1066
|
+
|
|
1067
|
+
Deliberately narrow: a ``line`` (``_LINE_KIND``) is ALWAYS a leaf -- the format has no
|
|
1068
|
+
construct nested inside a line, and this is the one shape this bug's own repro names --
|
|
1069
|
+
so it is the only rule enforced here: no parent of kind ``_LINE_KIND`` ever admits a
|
|
1070
|
+
child, of any kind.
|
|
1071
|
+
|
|
1072
|
+
``paragraph``/``root`` are deliberately left PERMISSIVE, not narrowed to "only a
|
|
1073
|
+
line"/"only a paragraph" as the format's steady-state shape might suggest: a single
|
|
1074
|
+
physical line spliced next to an EXISTING line inside a paragraph (``facade.insert``,
|
|
1075
|
+
``position="before"``/``"after"``, ``sibling=<a line>``) parses to a fresh
|
|
1076
|
+
``paragraph``-wrapped fragment -- every ``parse_fragment`` result is paragraph-shaped,
|
|
1077
|
+
this module's own docstring -- and lands as a ``paragraph`` nested directly under the
|
|
1078
|
+
target ``paragraph``, which ``render``/``generate_output`` already compose correctly
|
|
1079
|
+
(they walk to whatever depth the text lives at, never assuming a fixed two-level shape).
|
|
1080
|
+
This is exactly what the editor's pointwise before/after-a-line insert relies on
|
|
1081
|
+
today (``tests/test_editor_journal_surface.py::test_pointwise_text_batch_avoids_replace_source_and_full_load``);
|
|
1082
|
+
narrowing ``paragraph`` to admit only a bare ``line`` would silently break it. A rule for
|
|
1083
|
+
``paragraph``/``root`` is left for a future bug with its own concrete repro and its own
|
|
1084
|
+
evidence, per this fix's own discipline: only what evidence proves broken gets narrowed.
|
|
1085
|
+
|
|
1086
|
+
``parent is None`` (no parent/position dimension applies to this change, e.g.
|
|
1087
|
+
``replace_node_id``) and ``position == "body"`` (``updates._apply_text_and_reparse``'s
|
|
1088
|
+
own text-BODY check, never reached by plain text's node-based mutation entry points) are
|
|
1089
|
+
both always compatible -- this plugin has no rule to enforce for either.
|
|
1090
|
+
"""
|
|
1091
|
+
if parent is None or position == "body":
|
|
1092
|
+
return True
|
|
1093
|
+
return getattr(parent, "kind", None) != _LINE_KIND
|
|
1094
|
+
|
|
1095
|
+
# -- mutation adjustment ----------------------------------------------------
|
|
1096
|
+
#
|
|
1097
|
+
# THE INVARIANT (A-018): exactly the paragraph that is CURRENTLY the root's last child may
|
|
1098
|
+
# have an empty ``separator`` field, and whenever one does, the ENTIRE newline run that
|
|
1099
|
+
# follows the document's last paragraph lives in the root's ``trailing_separator`` -- never
|
|
1100
|
+
# split between the two. A paragraph's own ``separator`` and the root's ``trailing_separator``
|
|
1101
|
+
# are always read back-to-back at render time with nothing between them (see
|
|
1102
|
+
# :meth:`PlainTextTree.render`), so which of the two fields holds a given byte is otherwise
|
|
1103
|
+
# redundant; what is NOT redundant is keeping that split canonical, because it is the only
|
|
1104
|
+
# signal a later mutation has for "is this paragraph currently last" without re-walking the
|
|
1105
|
+
# whole tree. Three of the four hooks below exist to restore THAT invariant after the
|
|
1106
|
+
# structural change each repairs for, and none of them do anything else; the fourth,
|
|
1107
|
+
# ``adjust_replace_fragment``, defends a DIFFERENT invariant -- a paragraph's own
|
|
1108
|
+
# ``separator`` is POSITIONAL trivia describing what lies between it and its successor, not
|
|
1109
|
+
# part of its content, so replacing the paragraph must not silently drop that run just
|
|
1110
|
+
# because the fresh fragment taking its place parsed with no successor of its own to record
|
|
1111
|
+
# one against (bug 52f75995).
|
|
1112
|
+
#
|
|
1113
|
+
# ``adjust_after_insert`` restores it when a splice makes a NEW paragraph the last child (its
|
|
1114
|
+
# own fresh ``separator`` is already ``""`` by construction -- a parsed fragment's last line
|
|
1115
|
+
# never carries a stray terminator, see :func:`_fold_edges_into_lines` and
|
|
1116
|
+
# :func:`split_text_paragraphs` -- so only the OLD last paragraph needs to give up the
|
|
1117
|
+
# ``trailing_separator`` run it can no longer claim).
|
|
1118
|
+
#
|
|
1119
|
+
# ``adjust_after_delete`` restores it when the last paragraph(s) are removed outright: the run
|
|
1120
|
+
# they owned leaves WITH them (bug f8b37aac).
|
|
1121
|
+
#
|
|
1122
|
+
# ``adjust_after_move`` restores it for a detach immediately followed by an attach -- the one
|
|
1123
|
+
# case ``adjust_after_delete``/``adjust_after_insert`` cannot correctly compose, because the
|
|
1124
|
+
# detach half's field writes would race the attach half's reads of those same fields (bug
|
|
1125
|
+
# 7dcb35e4). It also owns the one case beyond simple ownership transfer: two paragraphs that
|
|
1126
|
+
# were already adjacent trading places (``TestMoveMatrix``), where the whole separator run
|
|
1127
|
+
# between them must travel as a unit to whichever of the two is now first.
|
|
1128
|
+
|
|
1129
|
+
def adjust_after_insert(self, parent: Any, inserted: Sequence[Any]) -> None:
|
|
1130
|
+
"""Hand the document's trailing edge to the paragraph that is no longer last.
|
|
1131
|
+
|
|
1132
|
+
The declared extension point ``facade.insert`` calls right after its splice, on the
|
|
1133
|
+
format's own terms (``facade._adjust_after_insert``). Most formats need nothing here --
|
|
1134
|
+
JSON and TOML regenerate their punctuation from ``children`` at render time, so a splice
|
|
1135
|
+
invalidates no stored byte. plain_text does not regenerate anything: it stores separator
|
|
1136
|
+
BYTES verbatim, which is what makes a four-newline gap come back as four newlines, and a
|
|
1137
|
+
stored byte can therefore be left in the wrong place by a mutation.
|
|
1138
|
+
|
|
1139
|
+
Fires only when the new last child is one of the nodes just inserted (an "append at end"
|
|
1140
|
+
splice, per position): see :func:`_claim_trailing_for_new_last` for the repair itself.
|
|
1141
|
+
|
|
1142
|
+
``parent`` is the ``core.live_tree.LiveNode`` the fragment was spliced into (``None`` only
|
|
1143
|
+
where the facade's own signature admits it) and ``inserted`` are the live nodes spliced in,
|
|
1144
|
+
the very objects now in ``parent.children`` -- which is what lets the run of new children
|
|
1145
|
+
be located by identity rather than guessed at from the bytes.
|
|
1146
|
+
|
|
1147
|
+
Deliberately does nothing for an INTERIOR splice (``inserted`` landing between two
|
|
1148
|
+
existing paragraphs, neither at the front nor the tail): unlike ``replace``, nothing is
|
|
1149
|
+
being removed here, so there is no PRE-EXISTING separator this format owes anyone --
|
|
1150
|
+
``insert`` splices exactly the caller's own bytes at the requested point and invents no
|
|
1151
|
+
blank line on either side (pinned by ``tests/test_facade.py``'s ``_INSERT_BYTE_CASES``
|
|
1152
|
+
"between" rows and ``tests/core/test_render_fidelity.py
|
|
1153
|
+
::TestInsertMatrix::test_insert_between_two_paragraphs_preserves_separators``). A caller
|
|
1154
|
+
that wants paragraph-style spacing around brand new content supplies it in the fragment
|
|
1155
|
+
itself, exactly as typing it into the raw text would.
|
|
1156
|
+
"""
|
|
1157
|
+
|
|
1158
|
+
if parent is None or parent.kind != _ROOT_KIND or not inserted:
|
|
1159
|
+
return
|
|
1160
|
+
_claim_trailing_for_new_last(parent, {id(node) for node in inserted})
|
|
1161
|
+
|
|
1162
|
+
def adjust_after_delete(
|
|
1163
|
+
self, parent: Any, deleted: Sequence[Any], *, children_before: Sequence[Any]
|
|
1164
|
+
) -> str | None:
|
|
1165
|
+
"""Clear the document's trailing edge when it was owned by a now-deleted paragraph.
|
|
1166
|
+
|
|
1167
|
+
The mirror repair to ``adjust_after_insert``: when the paragraph(s) that included the
|
|
1168
|
+
document's last child are deleted, ``trailing_separator`` -- the closing newline run
|
|
1169
|
+
stored on the root -- must leave with them rather than being stacked onto whatever
|
|
1170
|
+
paragraph is now last, which is the byte-for-byte double count that was bug f8b37aac.
|
|
1171
|
+
|
|
1172
|
+
Whether the deleted range reached the original tail is read off ``children_before`` --
|
|
1173
|
+
``parent.children`` exactly as it stood immediately before this delete ran -- by POSITION,
|
|
1174
|
+
never by a field value. An empty ``separator`` looks like a tempting proxy (a freshly
|
|
1175
|
+
parsed or freshly folded paragraph's own separator is ``""`` when nothing has yet made it
|
|
1176
|
+
NOT the last paragraph), but it is not reliable: a paragraph inserted or moved to a
|
|
1177
|
+
position OTHER than the document's end can just as legitimately carry an empty
|
|
1178
|
+
``separator`` -- it correctly says "nothing separates me from my new successor" -- while
|
|
1179
|
+
not being last at all. Keying this check off that field instead of position let deleting
|
|
1180
|
+
such a paragraph steal ``trailing_separator``'s byte away from the real last paragraph,
|
|
1181
|
+
which only a repeated delete/reinsert cycle surfaces (a single round trip never revisits
|
|
1182
|
+
a paragraph in that state).
|
|
1183
|
+
|
|
1184
|
+
``parent`` is the root node (``None`` for a non-root parent, in which case this format has
|
|
1185
|
+
nothing to repair) and ``deleted`` are the nodes already removed from its ``children``.
|
|
1186
|
+
|
|
1187
|
+
Returns the PRIOR value of the root's trailing_separator when it is released by delete,
|
|
1188
|
+
or None if the trailing separator was not modified.
|
|
1189
|
+
"""
|
|
1190
|
+
|
|
1191
|
+
if parent is not None and parent.kind == "plain_text:paragraph" and deleted:
|
|
1192
|
+
return self._release_trailing_after_line_delete(parent, deleted, children_before)
|
|
1193
|
+
if parent is None or parent.kind != _ROOT_KIND or not deleted:
|
|
1194
|
+
return None
|
|
1195
|
+
deleted_ids = {id(node) for node in deleted}
|
|
1196
|
+
positions = [
|
|
1197
|
+
index
|
|
1198
|
+
for index, node in enumerate(children_before)
|
|
1199
|
+
if id(node) in deleted_ids
|
|
1200
|
+
]
|
|
1201
|
+
if not positions or positions[-1] != len(children_before) - 1:
|
|
1202
|
+
# The deleted range did not reach the paragraph that was last; nothing to repair.
|
|
1203
|
+
return None
|
|
1204
|
+
# Capture the prior value before releasing
|
|
1205
|
+
prior_trailing = _field_str(parent, TRAILING_SEPARATOR_FIELD)
|
|
1206
|
+
_release_trailing_after_removal(parent)
|
|
1207
|
+
# Return the prior value only if it was non-empty (indicating it was actually set)
|
|
1208
|
+
return prior_trailing if prior_trailing else None
|
|
1209
|
+
|
|
1210
|
+
@staticmethod
|
|
1211
|
+
def _release_trailing_after_line_delete(
|
|
1212
|
+
paragraph: Any, deleted: Sequence[Any], children_before: Sequence[Any]
|
|
1213
|
+
) -> str | None:
|
|
1214
|
+
"""Bug 08619f56: deleting the LAST line(s) of the document's last paragraph.
|
|
1215
|
+
|
|
1216
|
+
The terminator of the document's last line is not in the line's text but in the root's
|
|
1217
|
+
``trailing_separator``; the new last line keeps its own terminator, so leaving the root
|
|
1218
|
+
run in place renders it twice (``'a\\nb\\n'`` minus ``b`` gave ``'a\\n\\n'``). The run
|
|
1219
|
+
leaves with the deleted last line. Returns its prior value (for the journal's inverse),
|
|
1220
|
+
or ``None`` when nothing was released."""
|
|
1221
|
+
root = getattr(paragraph, "parent", None)
|
|
1222
|
+
if root is None or root.kind != _ROOT_KIND or not children_before:
|
|
1223
|
+
return None
|
|
1224
|
+
deleted_ids = {id(node) for node in deleted}
|
|
1225
|
+
if id(children_before[-1]) not in deleted_ids:
|
|
1226
|
+
return None # the document's last line stays
|
|
1227
|
+
if list(root.children)[-1] is not paragraph:
|
|
1228
|
+
return None
|
|
1229
|
+
remaining = list(paragraph.children)
|
|
1230
|
+
if not remaining:
|
|
1231
|
+
return None
|
|
1232
|
+
trailing = _field_str(root, TRAILING_SEPARATOR_FIELD)
|
|
1233
|
+
if not trailing:
|
|
1234
|
+
return None
|
|
1235
|
+
last_text = _field_str(remaining[-1], "text")
|
|
1236
|
+
if not last_text or last_text[-1] not in "\r\n":
|
|
1237
|
+
return None # the new last line has no terminator of its own: the run stays
|
|
1238
|
+
# Only the deleted line's own terminator leaves; any blank lines after it stay.
|
|
1239
|
+
first = trailing.splitlines(keepends=True)[0]
|
|
1240
|
+
root.fields = {**root.fields, TRAILING_SEPARATOR_FIELD: trailing[len(first):]}
|
|
1241
|
+
return trailing
|
|
1242
|
+
|
|
1243
|
+
def adjust_after_move(
|
|
1244
|
+
self,
|
|
1245
|
+
source_parent: Any,
|
|
1246
|
+
target_parent: Any,
|
|
1247
|
+
moved: Sequence[Any],
|
|
1248
|
+
*,
|
|
1249
|
+
source_children_before: Sequence[Any],
|
|
1250
|
+
) -> None:
|
|
1251
|
+
"""Restore the separator-ownership invariant for a whole move in one pass.
|
|
1252
|
+
|
|
1253
|
+
Replaces independent ``adjust_after_delete``/``adjust_after_insert`` calls for a move
|
|
1254
|
+
(``facade._adjust_after_move`` falls back to that pair only when a plugin does not define
|
|
1255
|
+
this method): computing the detach-side and attach-side repairs from ONE snapshot, taken
|
|
1256
|
+
before either writes a field, is what bug 7dcb35e4 needed -- the two generic hooks running
|
|
1257
|
+
independently let the detach step's writes race the attach step's reads of the very same
|
|
1258
|
+
``trailing_separator``/``separator`` fields.
|
|
1259
|
+
|
|
1260
|
+
``source_children_before`` is ``source_parent.children`` exactly as it stood before the
|
|
1261
|
+
move ran -- the one piece of "before" state this hook cannot recover any other way, since
|
|
1262
|
+
the move itself only ever changes ``children`` lists and ``parent`` back-links, never a
|
|
1263
|
+
node's own fields. ``moved`` are the live nodes that relocated, in source-document order.
|
|
1264
|
+
|
|
1265
|
+
Two shapes are handled:
|
|
1266
|
+
|
|
1267
|
+
1. ADJACENT SWAP -- a single paragraph trading places with the neighbour that used to sit
|
|
1268
|
+
immediately after it (``TestMoveMatrix``): the whole separator run that used to lie
|
|
1269
|
+
between the pair -- the old predecessor's ``separator`` plus whatever ``moved`` itself
|
|
1270
|
+
owned, plus the source's ``trailing_separator`` if ``moved`` was the document's last
|
|
1271
|
+
paragraph -- travels as a unit onto ``moved``, which is now first of the pair; the old
|
|
1272
|
+
predecessor, now last of the pair, is emptied to ``""`` per the invariant.
|
|
1273
|
+
|
|
1274
|
+
2. GENERAL CASE -- every other shape: the detach half releases ``trailing_separator``
|
|
1275
|
+
exactly as a delete would, except the run travels WITH the moved paragraph (it is not
|
|
1276
|
+
leaving the document) rather than being dropped; the attach half claims it back exactly
|
|
1277
|
+
as a fresh append would, if and only if the moved run landed at the target's own end.
|
|
1278
|
+
"""
|
|
1279
|
+
|
|
1280
|
+
if not moved:
|
|
1281
|
+
return
|
|
1282
|
+
moved_ids = {id(node) for node in moved}
|
|
1283
|
+
moved_last = moved[-1]
|
|
1284
|
+
|
|
1285
|
+
old_predecessor = old_successor = None
|
|
1286
|
+
moved_was_source_tail = False
|
|
1287
|
+
if source_children_before:
|
|
1288
|
+
positions = [
|
|
1289
|
+
index
|
|
1290
|
+
for index, node in enumerate(source_children_before)
|
|
1291
|
+
if id(node) in moved_ids
|
|
1292
|
+
]
|
|
1293
|
+
if positions:
|
|
1294
|
+
head, tail = positions[0], positions[-1]
|
|
1295
|
+
if head > 0:
|
|
1296
|
+
old_predecessor = source_children_before[head - 1]
|
|
1297
|
+
if tail + 1 < len(source_children_before):
|
|
1298
|
+
old_successor = source_children_before[tail + 1]
|
|
1299
|
+
moved_was_source_tail = old_successor is None
|
|
1300
|
+
|
|
1301
|
+
same_root = (
|
|
1302
|
+
source_parent is not None
|
|
1303
|
+
and target_parent is not None
|
|
1304
|
+
and source_parent is target_parent
|
|
1305
|
+
and source_parent.kind == _ROOT_KIND
|
|
1306
|
+
)
|
|
1307
|
+
|
|
1308
|
+
new_successor = None
|
|
1309
|
+
if target_parent is not None and target_parent.kind == _ROOT_KIND:
|
|
1310
|
+
new_children = list(target_parent.children)
|
|
1311
|
+
new_positions = [
|
|
1312
|
+
index
|
|
1313
|
+
for index, node in enumerate(new_children)
|
|
1314
|
+
if id(node) in moved_ids
|
|
1315
|
+
]
|
|
1316
|
+
if new_positions and new_positions[-1] + 1 < len(new_children):
|
|
1317
|
+
new_successor = new_children[new_positions[-1] + 1]
|
|
1318
|
+
|
|
1319
|
+
if (
|
|
1320
|
+
same_root
|
|
1321
|
+
and len(moved) == 1
|
|
1322
|
+
and old_predecessor is not None
|
|
1323
|
+
and new_successor is not None
|
|
1324
|
+
and moved_was_source_tail
|
|
1325
|
+
):
|
|
1326
|
+
combined = (
|
|
1327
|
+
_field_str(old_predecessor, SEPARATOR_FIELD)
|
|
1328
|
+
+ _field_str(moved_last, SEPARATOR_FIELD)
|
|
1329
|
+
+ _field_str(source_parent, TRAILING_SEPARATOR_FIELD)
|
|
1330
|
+
)
|
|
1331
|
+
moved_last.fields = {**moved_last.fields, SEPARATOR_FIELD: combined}
|
|
1332
|
+
old_predecessor.fields = {**old_predecessor.fields, SEPARATOR_FIELD: ""}
|
|
1333
|
+
target_parent.fields = {
|
|
1334
|
+
**target_parent.fields,
|
|
1335
|
+
TRAILING_SEPARATOR_FIELD: "",
|
|
1336
|
+
}
|
|
1337
|
+
return
|
|
1338
|
+
|
|
1339
|
+
if source_parent is not None and moved_was_source_tail:
|
|
1340
|
+
if source_parent.kind == _ROOT_KIND:
|
|
1341
|
+
_fold_trailing_into_moved(source_parent, moved_last)
|
|
1342
|
+
elif source_parent.kind == _PARAGRAPH_KIND:
|
|
1343
|
+
_fold_separator_into_moved_line(source_parent, moved_last)
|
|
1344
|
+
|
|
1345
|
+
if target_parent is not None:
|
|
1346
|
+
if target_parent.kind == _ROOT_KIND:
|
|
1347
|
+
_claim_trailing_for_new_last(target_parent, moved_ids)
|
|
1348
|
+
if not moved_was_source_tail:
|
|
1349
|
+
_hand_moved_gap_to_predecessor(target_parent, moved_ids)
|
|
1350
|
+
elif target_parent.kind == _PARAGRAPH_KIND:
|
|
1351
|
+
_claim_separator_for_new_last_line(target_parent, moved_ids)
|
|
1352
|
+
|
|
1353
|
+
def adjust_replace_fragment(
|
|
1354
|
+
self,
|
|
1355
|
+
deleted: Sequence[Any],
|
|
1356
|
+
incoming: Sequence[Any],
|
|
1357
|
+
*,
|
|
1358
|
+
fragment_carries_boundary: bool = False,
|
|
1359
|
+
) -> None:
|
|
1360
|
+
"""Transplant the replaced range's own trailing boundary onto the fragment taking its
|
|
1361
|
+
place (bug 52f75995): a paragraph's ``separator`` is the verbatim blank-line run that
|
|
1362
|
+
lies BETWEEN it and its successor -- positional trivia, not the paragraph's own content
|
|
1363
|
+
-- and ``facade.replace`` calls this, per format, exactly so that run survives a replace
|
|
1364
|
+
instead of vanishing with the node that used to carry it.
|
|
1365
|
+
|
|
1366
|
+
``incoming`` is freshly parsed, in isolation, by :meth:`parse_fragment`: its own last
|
|
1367
|
+
paragraph's ``separator`` is unconditionally ``""``, because nothing inside the fragment
|
|
1368
|
+
itself follows it -- any bytes that trailed the fragment's own source text already folded
|
|
1369
|
+
into that paragraph's last LINE by :func:`_fold_edges_into_lines`, never into
|
|
1370
|
+
``SEPARATOR_FIELD``. Left alone, that ``""`` splices in verbatim where ``deleted``'s own
|
|
1371
|
+
boundary run used to be, gluing the incoming text straight onto whatever paragraph comes
|
|
1372
|
+
next with no separator at all -- the exact byte loss this hook exists to prevent.
|
|
1373
|
+
|
|
1374
|
+
Copying ``deleted``'s own ``separator`` field verbatim is not always enough on its own:
|
|
1375
|
+
that field only ever recorded the run ADDITIONAL to the paragraph's own last line
|
|
1376
|
+
terminator (every non-last paragraph's last line always ends in one, by construction --
|
|
1377
|
+
see :func:`_fold_edges_into_lines`), so it silently assumes the incoming paragraph's own
|
|
1378
|
+
last line ends the same way. A caller's replacement text need not -- ``"...changed."``
|
|
1379
|
+
with no trailing newline at all is exactly this bug's own second repro case -- so this
|
|
1380
|
+
also folds in ``deleted``'s own last-line terminator, then subtracts back out however
|
|
1381
|
+
much of that combined run ``incoming``'s own last line already supplies, byte for byte
|
|
1382
|
+
(matched as a literal prefix, not merely "some newline or other": a source honestly typed
|
|
1383
|
+
with a DIFFERENT line-ending style is data, not a typo, and is never silently normalized).
|
|
1384
|
+
|
|
1385
|
+
TWO shapes, read off ``deleted[-1]``'s position (still attached to its real parent --
|
|
1386
|
+
this hook runs BEFORE the splice, see ``facade._adjust_replace_fragment``):
|
|
1387
|
+
|
|
1388
|
+
1. ``deleted[-1]`` is some paragraph OTHER than the document's last: the run described
|
|
1389
|
+
above (its own last-line terminator plus its own ``separator``, minus whatever
|
|
1390
|
+
``incoming``'s own last line already supplies) becomes ``incoming[-1]``'s own
|
|
1391
|
+
``separator`` -- exactly the boundary the surviving NEXT sibling still needs.
|
|
1392
|
+
2. ``deleted[-1]`` IS the document's actual last paragraph: there is no next sibling to
|
|
1393
|
+
satisfy, only the root's ``trailing_separator`` -- the same positional run, just
|
|
1394
|
+
parked on the parent instead of a sibling because nothing follows it at all (A-018).
|
|
1395
|
+
The same subtraction applies (``deleted``'s own last-line terminator, PLUS root's
|
|
1396
|
+
current ``trailing_separator`` -- the terminator is not always ``""`` here: an
|
|
1397
|
+
earlier tail replace can have folded part of it onto this very paragraph's own last
|
|
1398
|
+
line, per this same branch, leaving a real run for this call to reclaim before it is
|
|
1399
|
+
lost with the node being removed, minus ``incoming``'s own matching prefix), but the
|
|
1400
|
+
leftover is written back onto the ROOT (the one field this replace does not otherwise
|
|
1401
|
+
touch) rather than onto ``incoming[-1]``, whose own ``separator`` must stay empty per
|
|
1402
|
+
the invariant it is now the last paragraph. Left unhandled, a replacement that itself
|
|
1403
|
+
ends in a newline (an ordinary way to type one) double-counts that byte against the
|
|
1404
|
+
untouched root field -- and skipping ``deleted``'s own terminator here (unlike branch
|
|
1405
|
+
1) loses the document's final newline on an undo that replays a SECOND tail replace.
|
|
1406
|
+
|
|
1407
|
+
A no-op whenever the replaced range's own last node is not itself a paragraph (replacing
|
|
1408
|
+
a single LINE inside an untouched paragraph produces a nested paragraph-wrapped fragment
|
|
1409
|
+
landing INSIDE that paragraph -- its enclosing paragraph's own ``separator`` was never
|
|
1410
|
+
part of the replaced range and needs no repair) or the incoming fragment's own last node
|
|
1411
|
+
is not paragraph-shaped (every ``plain_text`` fragment is, per :meth:`parse_fragment`'s
|
|
1412
|
+
contract, but the guard costs nothing and documents the assumption).
|
|
1413
|
+
"""
|
|
1414
|
+
if not deleted or not incoming:
|
|
1415
|
+
return
|
|
1416
|
+
last_deleted = deleted[-1]
|
|
1417
|
+
last_incoming = incoming[-1]
|
|
1418
|
+
if getattr(last_deleted, "kind", None) != _PARAGRAPH_KIND:
|
|
1419
|
+
return
|
|
1420
|
+
if getattr(last_incoming, "kind", None) != _PARAGRAPH_KIND:
|
|
1421
|
+
return
|
|
1422
|
+
incoming_run = _trailing_run(_last_content_text(last_incoming))
|
|
1423
|
+
if fragment_carries_boundary:
|
|
1424
|
+
# A journal replay (undo/redo) hands back a fragment rendered from the tree, so its
|
|
1425
|
+
# trailing run IS the replaced range's whole boundary: absorb it as a literal prefix.
|
|
1426
|
+
incoming_terminator = incoming_run
|
|
1427
|
+
else:
|
|
1428
|
+
# Caller-supplied content (unit C26): only the FIRST line terminator of ``incoming``'s
|
|
1429
|
+
# trailing run takes the place of the replaced range's own closing terminator. Every
|
|
1430
|
+
# further newline of that run is the supplied content's OWN trailing blank line, already
|
|
1431
|
+
# carried by ``incoming``'s last line, and must not be subtracted from the positional
|
|
1432
|
+
# run that survives. Subtracting the whole run lost the separator for one supplied
|
|
1433
|
+
# blank line and left one blank line too many for two or more.
|
|
1434
|
+
first_terminator = _FIRST_TERMINATOR.match(incoming_run)
|
|
1435
|
+
incoming_terminator = first_terminator.group(0) if first_terminator else ""
|
|
1436
|
+
# ``deleted``'s own last line's trailing run: ordinarily empty for the document's actual
|
|
1437
|
+
# tail paragraph (A-018 -- its whole terminator lives in ``trailing_separator`` instead),
|
|
1438
|
+
# but NOT always: a PRIOR replace at the tail can have folded part of that terminator
|
|
1439
|
+
# into this same paragraph's own last line (exactly what the ``at_document_tail`` branch
|
|
1440
|
+
# below does one call earlier), leaving a real run here for THIS call to reclaim before
|
|
1441
|
+
# it is lost with the node being removed -- skipping this for the tail case is what let
|
|
1442
|
+
# an undo through two tail replacements drop the document's final newline.
|
|
1443
|
+
deleted_terminator = _trailing_run(_last_content_text(last_deleted))
|
|
1444
|
+
|
|
1445
|
+
root = getattr(last_deleted, "parent", None)
|
|
1446
|
+
at_document_tail = (
|
|
1447
|
+
root is not None
|
|
1448
|
+
and getattr(root, "kind", None) == _ROOT_KIND
|
|
1449
|
+
and list(root.children)[-1] is last_deleted
|
|
1450
|
+
)
|
|
1451
|
+
if at_document_tail:
|
|
1452
|
+
full_run = deleted_terminator + _field_str(root, TRAILING_SEPARATOR_FIELD)
|
|
1453
|
+
if fragment_carries_boundary:
|
|
1454
|
+
# Unit C27 (bug 68b86aec): the undo fragment was journaled with the document's
|
|
1455
|
+
# whole closing run (see :meth:`replace_closing_run`), so it supplies the entire
|
|
1456
|
+
# tail; nothing of the replaced extent's run (the supplied content's own blank
|
|
1457
|
+
# lines included) may survive on top of it.
|
|
1458
|
+
root.fields = {**root.fields, TRAILING_SEPARATOR_FIELD: ""}
|
|
1459
|
+
return
|
|
1460
|
+
if incoming_run and full_run.startswith(incoming_run):
|
|
1461
|
+
full_run = full_run[len(incoming_run):]
|
|
1462
|
+
elif incoming_run and incoming_run.startswith(full_run):
|
|
1463
|
+
# Unit C26: the supplied content already ends with at least the whole run that
|
|
1464
|
+
# closes the document, so nothing of it may survive on top of the content.
|
|
1465
|
+
full_run = ""
|
|
1466
|
+
root.fields = {**root.fields, TRAILING_SEPARATOR_FIELD: full_run}
|
|
1467
|
+
return
|
|
1468
|
+
|
|
1469
|
+
# No early return on an empty ``own_separator`` (bug 52f75995 verifier finding F5): a
|
|
1470
|
+
# non-tail paragraph CAN legitimately carry separator=="" (``adjust_after_delete``'s own
|
|
1471
|
+
# docstring already warns it is not a reliable "am I last" proxy) -- e.g. a paragraph
|
|
1472
|
+
# ``insert`` lands directly beside an existing successor with no blank line of its own
|
|
1473
|
+
# (``adjust_after_insert`` invents no separator for that interior case, by contract; see
|
|
1474
|
+
# its own docstring), which is a normal, un-buggy shape, not a special one. Returning
|
|
1475
|
+
# early there threw away a non-empty ``deleted_terminator`` too, gluing the incoming text
|
|
1476
|
+
# onto whatever came next -- run the same subtraction unconditionally; it is a harmless
|
|
1477
|
+
# no-op when both terms are empty.
|
|
1478
|
+
own_separator = _field_str(last_deleted, SEPARATOR_FIELD)
|
|
1479
|
+
full_run = deleted_terminator + own_separator
|
|
1480
|
+
if incoming_terminator and full_run.startswith(incoming_terminator):
|
|
1481
|
+
# An undo fragment is rendered from the tree and spans the whole extent it replaces,
|
|
1482
|
+
# boundary included: nothing of the replaced extent may survive on top of it.
|
|
1483
|
+
full_run = "" if fragment_carries_boundary else full_run[len(incoming_terminator):]
|
|
1484
|
+
last_incoming.fields = {**last_incoming.fields, SEPARATOR_FIELD: full_run}
|
|
1485
|
+
|
|
1486
|
+
def replace_closing_run(self, deleted: Sequence[Any]) -> str:
|
|
1487
|
+
"""The root's closing run when ``deleted`` ends at the document's tail, else ``""``.
|
|
1488
|
+
|
|
1489
|
+
``facade.replace`` appends it to the journaled ``before`` fragment (unit C27, bug
|
|
1490
|
+
68b86aec): a tail paragraph's closing newline run lives on the root's
|
|
1491
|
+
``trailing_separator``, outside the paragraph's own rendering, so an undo that replays
|
|
1492
|
+
``before`` could not otherwise restore it byte for byte.
|
|
1493
|
+
"""
|
|
1494
|
+
if not deleted:
|
|
1495
|
+
return ""
|
|
1496
|
+
last_deleted = deleted[-1]
|
|
1497
|
+
root = getattr(last_deleted, "parent", None)
|
|
1498
|
+
if (
|
|
1499
|
+
getattr(last_deleted, "kind", None) != _PARAGRAPH_KIND
|
|
1500
|
+
or root is None
|
|
1501
|
+
or getattr(root, "kind", None) != _ROOT_KIND
|
|
1502
|
+
or list(root.children)[-1] is not last_deleted
|
|
1503
|
+
):
|
|
1504
|
+
return ""
|
|
1505
|
+
return _field_str(root, TRAILING_SEPARATOR_FIELD)
|
|
1506
|
+
|
|
1507
|
+
# -- FormatBoundary ---------------------------------------------------------
|
|
1508
|
+
|
|
1509
|
+
def render_document(self, document: Document) -> bytes:
|
|
1510
|
+
"""CORE-facing counterpart of ``parse_document``: renders a full
|
|
1511
|
+
``Document`` back to UTF-8 bytes via ``generate_output``.
|
|
1512
|
+
|
|
1513
|
+
Encoded with ``errors="surrogateescape"`` so content that reached
|
|
1514
|
+
the common model through a surrogateescape decode (the fallback
|
|
1515
|
+
rescuing a file whose bytes are not valid UTF-8) is written back as
|
|
1516
|
+
exactly those bytes instead of raising; for a string without lone
|
|
1517
|
+
surrogates this is identical to a strict UTF-8 encode.
|
|
1518
|
+
"""
|
|
1519
|
+
|
|
1520
|
+
text = self.generate_output(document, {})
|
|
1521
|
+
if not isinstance(text, str):
|
|
1522
|
+
raise _contract_error(
|
|
1523
|
+
f"render_document expected str from generate_output, got {type(text).__name__}"
|
|
1524
|
+
)
|
|
1525
|
+
return text.encode("utf-8", errors="surrogateescape")
|
|
1526
|
+
|
|
1527
|
+
def render_fragment(self, node: Node) -> str:
|
|
1528
|
+
"""CORE-facing counterpart of ``parse_fragment``: renders one
|
|
1529
|
+
fragment ``Node`` back to source text via ``generate_output``."""
|
|
1530
|
+
|
|
1531
|
+
text = self.generate_output(node, {})
|
|
1532
|
+
if not isinstance(text, str):
|
|
1533
|
+
raise _contract_error(
|
|
1534
|
+
f"render_fragment expected str from generate_output, got {type(text).__name__}"
|
|
1535
|
+
)
|
|
1536
|
+
return text
|
|
1537
|
+
|
|
1538
|
+
|
|
1539
|
+
# Registration data: a ready-made, stateless singleton a sibling registry
|
|
1540
|
+
# step (out of scope here, per {p055}/{p059}/{p101}) can import and register
|
|
1541
|
+
# under ``format_id="plain_text"``, exactly as
|
|
1542
|
+
# ``PYTHON_FORMAT_PLUGIN``/``BSL_FORMAT_PLUGIN`` already establish.
|
|
1543
|
+
PLAIN_TEXT_FORMAT_PLUGIN = PlainTextFormatPlugin()
|