parse-rtf 0.1.0__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.
- parse_rtf/__init__.py +33 -0
- parse_rtf/parser.py +669 -0
- parse_rtf/py.typed +0 -0
- parse_rtf-0.1.0.dist-info/METADATA +50 -0
- parse_rtf-0.1.0.dist-info/RECORD +7 -0
- parse_rtf-0.1.0.dist-info/WHEEL +4 -0
- parse_rtf-0.1.0.dist-info/licenses/LICENSE +21 -0
parse_rtf/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""A bounded, source-aware Rich Text Format parser."""
|
|
2
|
+
|
|
3
|
+
from .parser import (
|
|
4
|
+
BinaryData,
|
|
5
|
+
ControlSymbol,
|
|
6
|
+
ControlWord,
|
|
7
|
+
Diagnostic,
|
|
8
|
+
Document,
|
|
9
|
+
Group,
|
|
10
|
+
HexByte,
|
|
11
|
+
Limits,
|
|
12
|
+
ParseError,
|
|
13
|
+
SourceSpan,
|
|
14
|
+
Text,
|
|
15
|
+
loads,
|
|
16
|
+
parse,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"BinaryData",
|
|
21
|
+
"ControlSymbol",
|
|
22
|
+
"ControlWord",
|
|
23
|
+
"Diagnostic",
|
|
24
|
+
"Document",
|
|
25
|
+
"Group",
|
|
26
|
+
"HexByte",
|
|
27
|
+
"Limits",
|
|
28
|
+
"ParseError",
|
|
29
|
+
"SourceSpan",
|
|
30
|
+
"Text",
|
|
31
|
+
"loads",
|
|
32
|
+
"parse",
|
|
33
|
+
]
|
parse_rtf/parser.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
"""Parsing and safe text projection for Rich Text Format."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from array import array
|
|
6
|
+
from bisect import bisect_right
|
|
7
|
+
import codecs
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TypeAlias
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True, slots=True)
|
|
13
|
+
class SourceSpan:
|
|
14
|
+
"""A half-open source range with one-based line and column locations."""
|
|
15
|
+
|
|
16
|
+
start: int
|
|
17
|
+
end: int
|
|
18
|
+
start_line: int
|
|
19
|
+
start_column: int
|
|
20
|
+
end_line: int
|
|
21
|
+
end_column: int
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class Text:
|
|
26
|
+
"""Literal source text inside an RTF group."""
|
|
27
|
+
|
|
28
|
+
value: str
|
|
29
|
+
span: SourceSpan
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class ControlWord:
|
|
34
|
+
"""An RTF control word, with its optional signed decimal parameter."""
|
|
35
|
+
|
|
36
|
+
name: str
|
|
37
|
+
parameter: int | None
|
|
38
|
+
span: SourceSpan
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, slots=True)
|
|
42
|
+
class ControlSymbol:
|
|
43
|
+
"""An RTF control symbol such as ``\\\\``, ``\\{`` or ``\\~``."""
|
|
44
|
+
|
|
45
|
+
symbol: str
|
|
46
|
+
span: SourceSpan
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class HexByte:
|
|
51
|
+
"""A byte encoded using an RTF ``\\'hh`` escape."""
|
|
52
|
+
|
|
53
|
+
value: int
|
|
54
|
+
span: SourceSpan
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class BinaryData:
|
|
59
|
+
"""Opaque data consumed by an RTF ``\\binN`` control word."""
|
|
60
|
+
|
|
61
|
+
value: str
|
|
62
|
+
span: SourceSpan
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
Node: TypeAlias = "Text | ControlWord | ControlSymbol | HexByte | BinaryData | Group"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class Group:
|
|
70
|
+
"""A brace-delimited RTF group whose children retain their source order."""
|
|
71
|
+
|
|
72
|
+
children: tuple[Node, ...]
|
|
73
|
+
span: SourceSpan
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True, slots=True)
|
|
77
|
+
class Diagnostic:
|
|
78
|
+
"""A non-fatal unsupported or malformed-content diagnostic."""
|
|
79
|
+
|
|
80
|
+
code: str
|
|
81
|
+
message: str
|
|
82
|
+
span: SourceSpan
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ParseError(ValueError):
|
|
86
|
+
"""An RTF syntax, version, or resource-limit error."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, code: str, message: str, span: SourceSpan) -> None:
|
|
89
|
+
self.code = code
|
|
90
|
+
self.message = message
|
|
91
|
+
self.span = span
|
|
92
|
+
super().__init__(
|
|
93
|
+
f"{message} at line {span.start_line}, column {span.start_column}"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True, slots=True)
|
|
98
|
+
class Limits:
|
|
99
|
+
"""Resource bounds applied while parsing an RTF source string."""
|
|
100
|
+
|
|
101
|
+
max_input_chars: int = 10_000_000
|
|
102
|
+
max_nesting: int = 128
|
|
103
|
+
max_nodes: int = 1_000_000
|
|
104
|
+
|
|
105
|
+
def __post_init__(self) -> None:
|
|
106
|
+
for name, value in (
|
|
107
|
+
("max_input_chars", self.max_input_chars),
|
|
108
|
+
("max_nesting", self.max_nesting),
|
|
109
|
+
("max_nodes", self.max_nodes),
|
|
110
|
+
):
|
|
111
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
112
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True, slots=True)
|
|
116
|
+
class Document:
|
|
117
|
+
"""A parsed RTF document with its original source, syntax tree, and text.
|
|
118
|
+
|
|
119
|
+
Formatting and control structure remain available in :attr:`root`.
|
|
120
|
+
:attr:`text` is a safe, best-effort plain-text projection. It does not
|
|
121
|
+
evaluate fields, load objects, or fetch external resources.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
source: str
|
|
125
|
+
root: Group
|
|
126
|
+
text: str
|
|
127
|
+
diagnostics: tuple[Diagnostic, ...]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class _Locations:
|
|
131
|
+
def __init__(self, source: str) -> None:
|
|
132
|
+
self.length = len(source)
|
|
133
|
+
self.line_starts = array("Q", [0])
|
|
134
|
+
self.line_starts.extend(
|
|
135
|
+
index + 1 for index, character in enumerate(source) if character == "\n"
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def span(self, start: int, end: int) -> SourceSpan:
|
|
139
|
+
start = min(max(start, 0), self.length)
|
|
140
|
+
end = min(max(end, start), self.length)
|
|
141
|
+
start_line_index = bisect_right(self.line_starts, start) - 1
|
|
142
|
+
end_line_index = bisect_right(self.line_starts, end) - 1
|
|
143
|
+
return SourceSpan(
|
|
144
|
+
start=start,
|
|
145
|
+
end=end,
|
|
146
|
+
start_line=start_line_index + 1,
|
|
147
|
+
start_column=start - self.line_starts[start_line_index] + 1,
|
|
148
|
+
end_line=end_line_index + 1,
|
|
149
|
+
end_column=end - self.line_starts[end_line_index] + 1,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(slots=True)
|
|
154
|
+
class _Frame:
|
|
155
|
+
start: int
|
|
156
|
+
children: list[Node]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
_KNOWN_DESTINATIONS = frozenset(
|
|
160
|
+
{
|
|
161
|
+
"annotation",
|
|
162
|
+
"atnauthor",
|
|
163
|
+
"author",
|
|
164
|
+
"colortbl",
|
|
165
|
+
"comment",
|
|
166
|
+
"doccomm",
|
|
167
|
+
"filetbl",
|
|
168
|
+
"fldinst",
|
|
169
|
+
"fonttbl",
|
|
170
|
+
"objalias",
|
|
171
|
+
"objclass",
|
|
172
|
+
"objdata",
|
|
173
|
+
"objname",
|
|
174
|
+
"footer",
|
|
175
|
+
"footerf",
|
|
176
|
+
"footerl",
|
|
177
|
+
"footerr",
|
|
178
|
+
"footnote",
|
|
179
|
+
"header",
|
|
180
|
+
"headerf",
|
|
181
|
+
"headerl",
|
|
182
|
+
"headerr",
|
|
183
|
+
"info",
|
|
184
|
+
"listoverridetable",
|
|
185
|
+
"listtable",
|
|
186
|
+
"object",
|
|
187
|
+
"pict",
|
|
188
|
+
"revtbl",
|
|
189
|
+
"stylesheet",
|
|
190
|
+
"themedata",
|
|
191
|
+
"xmlattrname",
|
|
192
|
+
"xmlattrvalue",
|
|
193
|
+
"xmlclose",
|
|
194
|
+
"xmlname",
|
|
195
|
+
"xmlopen",
|
|
196
|
+
"xmltext",
|
|
197
|
+
}
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
_TEXT_CONTROLS = {
|
|
201
|
+
"emdash": "\u2014",
|
|
202
|
+
"endash": "\u2013",
|
|
203
|
+
"bullet": "\u2022",
|
|
204
|
+
"lquote": "\u2018",
|
|
205
|
+
"rquote": "\u2019",
|
|
206
|
+
"ldblquote": "\u201c",
|
|
207
|
+
"rdblquote": "\u201d",
|
|
208
|
+
"tab": "\t",
|
|
209
|
+
"line": "\n",
|
|
210
|
+
"par": "\n",
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class _Parser:
|
|
215
|
+
def __init__(self, source: str, limits: Limits) -> None:
|
|
216
|
+
self.source = source
|
|
217
|
+
self.limits = limits
|
|
218
|
+
self.locations = _Locations(source)
|
|
219
|
+
self.node_count = 0
|
|
220
|
+
|
|
221
|
+
def error(
|
|
222
|
+
self, code: str, message: str, start: int, end: int | None = None
|
|
223
|
+
) -> ParseError:
|
|
224
|
+
return ParseError(
|
|
225
|
+
code,
|
|
226
|
+
message,
|
|
227
|
+
self.locations.span(
|
|
228
|
+
start, min(len(self.source), start + 1 if end is None else end)
|
|
229
|
+
),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def add(self, children: list[Node], node: Node) -> None:
|
|
233
|
+
self.node_count += 1
|
|
234
|
+
if self.node_count > self.limits.max_nodes:
|
|
235
|
+
raise self.error(
|
|
236
|
+
"node-limit-exceeded",
|
|
237
|
+
f"RTF exceeds the {self.limits.max_nodes}-node limit",
|
|
238
|
+
node.span.start,
|
|
239
|
+
node.span.end,
|
|
240
|
+
)
|
|
241
|
+
children.append(node)
|
|
242
|
+
|
|
243
|
+
def parse_tree(self) -> Group:
|
|
244
|
+
if len(self.source) > self.limits.max_input_chars:
|
|
245
|
+
raise self.error(
|
|
246
|
+
"input-limit-exceeded",
|
|
247
|
+
f"RTF exceeds the {self.limits.max_input_chars}-character limit",
|
|
248
|
+
0,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
frames: list[_Frame] = []
|
|
252
|
+
roots: list[Group] = []
|
|
253
|
+
index = 0
|
|
254
|
+
while index < len(self.source):
|
|
255
|
+
character = self.source[index]
|
|
256
|
+
if character == "{":
|
|
257
|
+
if len(frames) >= self.limits.max_nesting:
|
|
258
|
+
raise self.error(
|
|
259
|
+
"nesting-limit-exceeded",
|
|
260
|
+
f"RTF exceeds the {self.limits.max_nesting}-group nesting limit",
|
|
261
|
+
index,
|
|
262
|
+
)
|
|
263
|
+
self.node_count += 1
|
|
264
|
+
if self.node_count > self.limits.max_nodes:
|
|
265
|
+
raise self.error(
|
|
266
|
+
"node-limit-exceeded",
|
|
267
|
+
f"RTF exceeds the {self.limits.max_nodes}-node limit",
|
|
268
|
+
index,
|
|
269
|
+
)
|
|
270
|
+
frames.append(_Frame(index, []))
|
|
271
|
+
index += 1
|
|
272
|
+
continue
|
|
273
|
+
|
|
274
|
+
if character == "}":
|
|
275
|
+
if not frames:
|
|
276
|
+
raise self.error("unexpected-close", "Unexpected closing brace", index)
|
|
277
|
+
frame = frames.pop()
|
|
278
|
+
group = Group(
|
|
279
|
+
tuple(frame.children), self.locations.span(frame.start, index + 1)
|
|
280
|
+
)
|
|
281
|
+
if frames:
|
|
282
|
+
frames[-1].children.append(group)
|
|
283
|
+
else:
|
|
284
|
+
roots.append(group)
|
|
285
|
+
index += 1
|
|
286
|
+
continue
|
|
287
|
+
|
|
288
|
+
if not frames:
|
|
289
|
+
if character in " \t\r\n":
|
|
290
|
+
index += 1
|
|
291
|
+
continue
|
|
292
|
+
raise self.error(
|
|
293
|
+
"content-outside-group", "Content outside the RTF group", index
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
if character != "\\":
|
|
297
|
+
end = index + 1
|
|
298
|
+
while end < len(self.source) and self.source[end] not in "{}\\":
|
|
299
|
+
end += 1
|
|
300
|
+
self.add(
|
|
301
|
+
frames[-1].children,
|
|
302
|
+
Text(self.source[index:end], self.locations.span(index, end)),
|
|
303
|
+
)
|
|
304
|
+
index = end
|
|
305
|
+
continue
|
|
306
|
+
|
|
307
|
+
token_start = index
|
|
308
|
+
index += 1
|
|
309
|
+
if index >= len(self.source):
|
|
310
|
+
raise self.error("trailing-escape", "Trailing backslash in RTF", token_start)
|
|
311
|
+
|
|
312
|
+
if self.source[index] == "'":
|
|
313
|
+
if index + 2 >= len(self.source):
|
|
314
|
+
raise self.error(
|
|
315
|
+
"invalid-hex-escape", "Incomplete hexadecimal byte escape", token_start
|
|
316
|
+
)
|
|
317
|
+
digits = self.source[index + 1 : index + 3]
|
|
318
|
+
if any(character not in "0123456789abcdefABCDEF" for character in digits):
|
|
319
|
+
raise self.error(
|
|
320
|
+
"invalid-hex-escape",
|
|
321
|
+
f"Invalid hexadecimal byte escape {digits!r}",
|
|
322
|
+
token_start,
|
|
323
|
+
index + 3,
|
|
324
|
+
)
|
|
325
|
+
value = int(digits, 16)
|
|
326
|
+
end = index + 3
|
|
327
|
+
self.add(
|
|
328
|
+
frames[-1].children,
|
|
329
|
+
HexByte(value, self.locations.span(token_start, end)),
|
|
330
|
+
)
|
|
331
|
+
index = end
|
|
332
|
+
continue
|
|
333
|
+
|
|
334
|
+
if self.source[index].isascii() and self.source[index].isalpha():
|
|
335
|
+
name_start = index
|
|
336
|
+
while (
|
|
337
|
+
index < len(self.source)
|
|
338
|
+
and self.source[index].isascii()
|
|
339
|
+
and self.source[index].isalpha()
|
|
340
|
+
):
|
|
341
|
+
index += 1
|
|
342
|
+
name = self.source[name_start:index]
|
|
343
|
+
sign_start = index
|
|
344
|
+
if index < len(self.source) and self.source[index] == "-":
|
|
345
|
+
if (
|
|
346
|
+
index + 1 < len(self.source)
|
|
347
|
+
and self.source[index + 1].isascii()
|
|
348
|
+
and self.source[index + 1].isdigit()
|
|
349
|
+
):
|
|
350
|
+
index += 1
|
|
351
|
+
digit_start = index
|
|
352
|
+
while (
|
|
353
|
+
index < len(self.source)
|
|
354
|
+
and self.source[index].isascii()
|
|
355
|
+
and self.source[index].isdigit()
|
|
356
|
+
):
|
|
357
|
+
index += 1
|
|
358
|
+
digits = self.source[digit_start:index]
|
|
359
|
+
parameter: int | None = None
|
|
360
|
+
if digits:
|
|
361
|
+
if len(digits) > 10:
|
|
362
|
+
raise self.error(
|
|
363
|
+
"invalid-parameter",
|
|
364
|
+
"Control-word parameter exceeds the supported integer range",
|
|
365
|
+
token_start,
|
|
366
|
+
index,
|
|
367
|
+
)
|
|
368
|
+
try:
|
|
369
|
+
parameter = int(self.source[sign_start:index], 10)
|
|
370
|
+
except ValueError as error:
|
|
371
|
+
raise self.error(
|
|
372
|
+
"invalid-parameter",
|
|
373
|
+
"Invalid control-word parameter",
|
|
374
|
+
token_start,
|
|
375
|
+
index,
|
|
376
|
+
) from error
|
|
377
|
+
|
|
378
|
+
if index < len(self.source) and self.source[index] == " ":
|
|
379
|
+
index += 1
|
|
380
|
+
control = ControlWord(
|
|
381
|
+
name, parameter, self.locations.span(token_start, index)
|
|
382
|
+
)
|
|
383
|
+
self.add(frames[-1].children, control)
|
|
384
|
+
|
|
385
|
+
if name.lower() == "bin":
|
|
386
|
+
if parameter is None or parameter < 0:
|
|
387
|
+
raise self.error(
|
|
388
|
+
"invalid-binary-length",
|
|
389
|
+
"\\bin requires a non-negative length",
|
|
390
|
+
token_start,
|
|
391
|
+
index,
|
|
392
|
+
)
|
|
393
|
+
binary_end = index + parameter
|
|
394
|
+
if binary_end > len(self.source):
|
|
395
|
+
raise self.error(
|
|
396
|
+
"truncated-binary-data",
|
|
397
|
+
"\\bin length extends beyond the end of the source",
|
|
398
|
+
token_start,
|
|
399
|
+
len(self.source),
|
|
400
|
+
)
|
|
401
|
+
if parameter:
|
|
402
|
+
self.add(
|
|
403
|
+
frames[-1].children,
|
|
404
|
+
BinaryData(
|
|
405
|
+
self.source[index:binary_end],
|
|
406
|
+
self.locations.span(index, binary_end),
|
|
407
|
+
),
|
|
408
|
+
)
|
|
409
|
+
index = binary_end
|
|
410
|
+
continue
|
|
411
|
+
|
|
412
|
+
symbol = self.source[index]
|
|
413
|
+
index += 1
|
|
414
|
+
self.add(
|
|
415
|
+
frames[-1].children,
|
|
416
|
+
ControlSymbol(symbol, self.locations.span(token_start, index)),
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if frames:
|
|
420
|
+
frame = frames[-1]
|
|
421
|
+
raise self.error("unclosed-group", "Unclosed RTF group", frame.start)
|
|
422
|
+
if len(roots) != 1:
|
|
423
|
+
raise self.error("invalid-root", "RTF must contain exactly one root group", 0)
|
|
424
|
+
root = roots[0]
|
|
425
|
+
first = next(
|
|
426
|
+
(node for node in root.children if not isinstance(node, Text) or node.value.strip()),
|
|
427
|
+
None,
|
|
428
|
+
)
|
|
429
|
+
if not isinstance(first, ControlWord) or first.name.lower() != "rtf":
|
|
430
|
+
raise self.error(
|
|
431
|
+
"missing-rtf-header",
|
|
432
|
+
"Root group must begin with an RTF header",
|
|
433
|
+
root.span.start,
|
|
434
|
+
)
|
|
435
|
+
if first.parameter != 1:
|
|
436
|
+
raise self.error(
|
|
437
|
+
"unsupported-version",
|
|
438
|
+
f"Unsupported RTF version {first.parameter!r}; only RTF 1 is supported",
|
|
439
|
+
first.span.start,
|
|
440
|
+
first.span.end,
|
|
441
|
+
)
|
|
442
|
+
return root
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@dataclass(slots=True)
|
|
446
|
+
class _TextState:
|
|
447
|
+
codepage: int = 1252
|
|
448
|
+
unicode_fallback: int = 1
|
|
449
|
+
fallback_to_skip: int = 0
|
|
450
|
+
|
|
451
|
+
def copy(self) -> _TextState:
|
|
452
|
+
return _TextState(self.codepage, self.unicode_fallback, self.fallback_to_skip)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
class _TextProjector:
|
|
456
|
+
def __init__(self) -> None:
|
|
457
|
+
self.output: list[str] = []
|
|
458
|
+
self.diagnostics: list[Diagnostic] = []
|
|
459
|
+
self.reported_codepages: set[int] = set()
|
|
460
|
+
|
|
461
|
+
def diagnose(self, code: str, message: str, span: SourceSpan) -> None:
|
|
462
|
+
self.diagnostics.append(Diagnostic(code, message, span))
|
|
463
|
+
|
|
464
|
+
def emit(self, value: str, state: _TextState) -> None:
|
|
465
|
+
if not value:
|
|
466
|
+
return
|
|
467
|
+
if state.fallback_to_skip:
|
|
468
|
+
skipped = min(state.fallback_to_skip, len(value))
|
|
469
|
+
state.fallback_to_skip -= skipped
|
|
470
|
+
value = value[skipped:]
|
|
471
|
+
if value:
|
|
472
|
+
self.output.append(value)
|
|
473
|
+
|
|
474
|
+
def codec(self, codepage: int, span: SourceSpan) -> str:
|
|
475
|
+
codec = "utf-8" if codepage == 65001 else f"cp{codepage}"
|
|
476
|
+
try:
|
|
477
|
+
return codecs.lookup(codec).name
|
|
478
|
+
except LookupError:
|
|
479
|
+
if codepage not in self.reported_codepages:
|
|
480
|
+
self.reported_codepages.add(codepage)
|
|
481
|
+
self.diagnose(
|
|
482
|
+
"unsupported-codepage",
|
|
483
|
+
f"Python does not provide a codec for RTF code page {codepage}; "
|
|
484
|
+
"Windows-1252 is used for text projection",
|
|
485
|
+
span,
|
|
486
|
+
)
|
|
487
|
+
return "cp1252"
|
|
488
|
+
|
|
489
|
+
def decode_hex(self, nodes: list[HexByte], state: _TextState) -> None:
|
|
490
|
+
if not nodes:
|
|
491
|
+
return
|
|
492
|
+
codec = self.codec(state.codepage, nodes[0].span)
|
|
493
|
+
data = bytes(node.value for node in nodes)
|
|
494
|
+
try:
|
|
495
|
+
decoded = data.decode(codec)
|
|
496
|
+
except UnicodeDecodeError:
|
|
497
|
+
decoded = data.decode(codec, errors="replace")
|
|
498
|
+
self.diagnose(
|
|
499
|
+
"invalid-encoded-text",
|
|
500
|
+
f"Hexadecimal bytes are not valid {codec} text; "
|
|
501
|
+
"replacement characters were inserted",
|
|
502
|
+
self._cover(nodes[0].span, nodes[-1].span),
|
|
503
|
+
)
|
|
504
|
+
self.emit(decoded, state)
|
|
505
|
+
|
|
506
|
+
@staticmethod
|
|
507
|
+
def _cover(first: SourceSpan, last: SourceSpan) -> SourceSpan:
|
|
508
|
+
return SourceSpan(
|
|
509
|
+
first.start,
|
|
510
|
+
last.end,
|
|
511
|
+
first.start_line,
|
|
512
|
+
first.start_column,
|
|
513
|
+
last.end_line,
|
|
514
|
+
last.end_column,
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
@staticmethod
|
|
518
|
+
def _first_content(children: tuple[Node, ...]) -> tuple[int, Node] | None:
|
|
519
|
+
for index, node in enumerate(children):
|
|
520
|
+
if isinstance(node, Text) and not node.value.strip():
|
|
521
|
+
continue
|
|
522
|
+
return index, node
|
|
523
|
+
return None
|
|
524
|
+
|
|
525
|
+
def project_group(self, group: Group, inherited: _TextState) -> None:
|
|
526
|
+
state = inherited.copy()
|
|
527
|
+
first = self._first_content(group.children)
|
|
528
|
+
skip_through = -1
|
|
529
|
+
|
|
530
|
+
if first is not None:
|
|
531
|
+
index, node = first
|
|
532
|
+
destination: str | None = None
|
|
533
|
+
destination_node: Node = node
|
|
534
|
+
if isinstance(node, ControlWord) and node.name.lower() in _KNOWN_DESTINATIONS:
|
|
535
|
+
destination = node.name.lower()
|
|
536
|
+
elif isinstance(node, ControlSymbol) and node.symbol == "*":
|
|
537
|
+
next_content = self._first_content(group.children[index + 1 :])
|
|
538
|
+
if next_content is not None:
|
|
539
|
+
next_index, next_node = next_content
|
|
540
|
+
if isinstance(next_node, ControlWord):
|
|
541
|
+
destination = next_node.name.lower()
|
|
542
|
+
destination_node = next_node
|
|
543
|
+
skip_through = index + 1 + next_index
|
|
544
|
+
if destination is not None:
|
|
545
|
+
if destination in _KNOWN_DESTINATIONS:
|
|
546
|
+
self.diagnose(
|
|
547
|
+
"destination-skipped",
|
|
548
|
+
f"RTF {destination!r} destination is retained in the syntax tree "
|
|
549
|
+
"but omitted from plain text",
|
|
550
|
+
destination_node.span,
|
|
551
|
+
)
|
|
552
|
+
return
|
|
553
|
+
self.diagnose(
|
|
554
|
+
"unsupported-destination",
|
|
555
|
+
f"Unknown starred destination {destination!r} is omitted from plain text",
|
|
556
|
+
destination_node.span,
|
|
557
|
+
)
|
|
558
|
+
return
|
|
559
|
+
|
|
560
|
+
pending_hex: list[HexByte] = []
|
|
561
|
+
|
|
562
|
+
def flush_hex() -> None:
|
|
563
|
+
if pending_hex:
|
|
564
|
+
self.decode_hex(pending_hex, state)
|
|
565
|
+
pending_hex.clear()
|
|
566
|
+
|
|
567
|
+
for index, node in enumerate(group.children):
|
|
568
|
+
if index <= skip_through:
|
|
569
|
+
continue
|
|
570
|
+
if isinstance(node, Group):
|
|
571
|
+
flush_hex()
|
|
572
|
+
self.project_group(node, state)
|
|
573
|
+
continue
|
|
574
|
+
if isinstance(node, HexByte):
|
|
575
|
+
pending_hex.append(node)
|
|
576
|
+
continue
|
|
577
|
+
|
|
578
|
+
flush_hex()
|
|
579
|
+
if isinstance(node, Text):
|
|
580
|
+
self.emit(node.value.replace("\r", "").replace("\n", ""), state)
|
|
581
|
+
elif isinstance(node, BinaryData):
|
|
582
|
+
continue
|
|
583
|
+
elif isinstance(node, ControlSymbol):
|
|
584
|
+
value = {
|
|
585
|
+
"\\": "\\",
|
|
586
|
+
"{": "{",
|
|
587
|
+
"}": "}",
|
|
588
|
+
"~": "\u00a0",
|
|
589
|
+
"_": "\u2011",
|
|
590
|
+
"-": "\u00ad",
|
|
591
|
+
}.get(node.symbol, "")
|
|
592
|
+
self.emit(value, state)
|
|
593
|
+
elif isinstance(node, ControlWord):
|
|
594
|
+
name = node.name.lower()
|
|
595
|
+
if name == "uc":
|
|
596
|
+
if node.parameter is None or node.parameter < 0:
|
|
597
|
+
raise ParseError(
|
|
598
|
+
"invalid-unicode-fallback",
|
|
599
|
+
"\\uc requires a non-negative value",
|
|
600
|
+
node.span,
|
|
601
|
+
)
|
|
602
|
+
state.unicode_fallback = node.parameter
|
|
603
|
+
elif name == "u":
|
|
604
|
+
if node.parameter is None or not -32768 <= node.parameter <= 32767:
|
|
605
|
+
raise ParseError(
|
|
606
|
+
"invalid-unicode-escape",
|
|
607
|
+
"\\u requires a signed 16-bit value",
|
|
608
|
+
node.span,
|
|
609
|
+
)
|
|
610
|
+
self.emit(chr(node.parameter & 0xFFFF), state)
|
|
611
|
+
state.fallback_to_skip = state.unicode_fallback
|
|
612
|
+
elif name in {"ansicpg", "cpg"}:
|
|
613
|
+
if node.parameter is None or node.parameter < 1:
|
|
614
|
+
raise ParseError(
|
|
615
|
+
"invalid-codepage",
|
|
616
|
+
f"\\{name} requires a positive code page",
|
|
617
|
+
node.span,
|
|
618
|
+
)
|
|
619
|
+
state.codepage = node.parameter
|
|
620
|
+
self.codec(state.codepage, node.span)
|
|
621
|
+
elif name in {"par", "line", "tab", "emdash", "endash", "bullet",
|
|
622
|
+
"lquote", "rquote", "ldblquote", "rdblquote"}:
|
|
623
|
+
self.emit(_TEXT_CONTROLS[name], state)
|
|
624
|
+
|
|
625
|
+
flush_hex()
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def loads(source: str, *, limits: Limits | None = None) -> Document:
|
|
629
|
+
"""Parse an RTF 1 source string into a source-aware :class:`Document`.
|
|
630
|
+
|
|
631
|
+
The input is a Python string. Hexadecimal byte escapes are decoded using
|
|
632
|
+
the active ``\\ansicpgN`` value (Windows-1252 by default). Malformed
|
|
633
|
+
syntax and exceeded resource limits raise :class:`ParseError`.
|
|
634
|
+
"""
|
|
635
|
+
|
|
636
|
+
if not isinstance(source, str):
|
|
637
|
+
raise TypeError("RTF source must be a str")
|
|
638
|
+
parser = _Parser(source, limits or Limits())
|
|
639
|
+
root = parser.parse_tree()
|
|
640
|
+
projector = _TextProjector()
|
|
641
|
+
projector.project_group(root, _TextState())
|
|
642
|
+
return Document(
|
|
643
|
+
source,
|
|
644
|
+
root,
|
|
645
|
+
_join_surrogates("".join(projector.output)),
|
|
646
|
+
tuple(projector.diagnostics),
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def parse(source: str, *, limits: Limits | None = None) -> Document:
|
|
651
|
+
"""Alias for :func:`loads`."""
|
|
652
|
+
|
|
653
|
+
return loads(source, limits=limits)
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _join_surrogates(value: str) -> str:
|
|
657
|
+
result: list[str] = []
|
|
658
|
+
index = 0
|
|
659
|
+
while index < len(value):
|
|
660
|
+
codepoint = ord(value[index])
|
|
661
|
+
if 0xD800 <= codepoint <= 0xDBFF and index + 1 < len(value):
|
|
662
|
+
low = ord(value[index + 1])
|
|
663
|
+
if 0xDC00 <= low <= 0xDFFF:
|
|
664
|
+
result.append(chr(0x10000 + ((codepoint - 0xD800) << 10) + low - 0xDC00))
|
|
665
|
+
index += 2
|
|
666
|
+
continue
|
|
667
|
+
result.append("\ufffd" if 0xD800 <= codepoint <= 0xDFFF else value[index])
|
|
668
|
+
index += 1
|
|
669
|
+
return "".join(result)
|
parse_rtf/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parse-rtf
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Bounded, source-aware Rich Text Format parsing for Python
|
|
5
|
+
Author: wispsy
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.14
|
|
12
|
+
Project-URL: Repository, https://github.com/wispsy/parse-rtf
|
|
13
|
+
Project-URL: Issues, https://github.com/wispsy/parse-rtf/issues
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# parse-rtf
|
|
17
|
+
|
|
18
|
+
`parse-rtf` is a bounded, source-aware Rich Text Format (RTF 1) parser for
|
|
19
|
+
Python 3.14+. It has no runtime dependencies.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from parse_rtf import loads
|
|
23
|
+
|
|
24
|
+
document = loads(r"{\rtf1\ansi Hello, {\b world}!\par}")
|
|
25
|
+
print(document.text) # Hello, world!\n
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`Document.source` preserves the exact input. `Document.root` is an immutable
|
|
29
|
+
syntax tree of groups, literal text, control words and symbols, hexadecimal
|
|
30
|
+
bytes, and opaque binary data. Every node has a `SourceSpan` with source offsets
|
|
31
|
+
and one-based line/column positions. `Document.text` provides a safe plain-text
|
|
32
|
+
projection; non-text destinations and formatting controls remain available in
|
|
33
|
+
the syntax tree. Non-fatal limitations are reported in `Document.diagnostics`.
|
|
34
|
+
|
|
35
|
+
The parser enforces configurable input-size, nesting, and node limits. See
|
|
36
|
+
[supported syntax and API](docs/supported-syntax.md) and
|
|
37
|
+
[security boundaries](docs/security.md).
|
|
38
|
+
|
|
39
|
+
## Development
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
uv sync --locked
|
|
43
|
+
uv run --frozen python -W error::ResourceWarning -m pytest -q
|
|
44
|
+
uv run --frozen python scripts/check_distribution.py --output-dir dist
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The distribution is named `parse-rtf`; the Python import package is
|
|
48
|
+
`parse_rtf`.
|
|
49
|
+
|
|
50
|
+
See [release instructions](docs/releasing.md) for trusted PyPI publishing setup.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
parse_rtf/__init__.py,sha256=FFf9vvUZ3uNlHhjcB4nImQOY5SU_9q6yTTYYv8Y-7uw,485
|
|
2
|
+
parse_rtf/parser.py,sha256=t4gwsxiDEC7_FieikjQsZ69O3m7mge-E44hryJPHJXs,22728
|
|
3
|
+
parse_rtf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
parse_rtf-0.1.0.dist-info/licenses/LICENSE,sha256=dJjxPlUliHO6iuJiKxsIn0HSnRRb-dp_8lpVtAunRj8,1063
|
|
5
|
+
parse_rtf-0.1.0.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
|
|
6
|
+
parse_rtf-0.1.0.dist-info/METADATA,sha256=C08tnnM2gTfmy7sq2oUP3UYKHIxNhULgxV6L9MLcHVU,1756
|
|
7
|
+
parse_rtf-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wispsy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|