Repository navigation
Expand file tree
/
Copy pathhtml_export.py
More file actions
1559 lines (1361 loc) · 65.4 KB
/
Copy pathhtml_export.py
File metadata and controls
1559 lines (1361 loc) · 65.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2024 John Balis
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""XHTML/FODT export and image stripping for Writer documents.
Public entries: ``document_to_content`` and ``xtext_to_content``.
CJK ruby: the XHTML filter concatenates ``text:ruby`` children and range copy
drops ``RubyText``. ``inject_ruby_into_html`` restores ``<ruby><rt>`` after
semantic post-process. Apply swaps ``<ruby>`` for placeholders then sets
``RubyText`` on the base run (``html_ruby.ruby_placeholders`` / ``html_import._place_ruby``).
"""
from __future__ import annotations
import logging
import re
import zlib
from contextlib import nullcontext
from dataclasses import dataclass, field
from html import escape as html_escape, unescape as html_unescape
from typing import Any, Callable, Iterator, NamedTuple
from plugin.doc.temp_files import with_temp_buffer
from plugin.doc.text_helpers import (
DeletionState,
TrackedDeletions,
get_string_without_tracked_deletions,
get_writer_selection_positions,
iter_elements,
iter_table_paragraphs,
iter_xtext_paragraphs,
starts_at_or_after,
table_visible_text,
visible_portions,
walk_cap_warning,
)
from plugin.framework.constants import HTML_WRITER_FILTER
from plugin.framework.errors import ToolExecutionError, best_effort, reraise_if_disposed, uno_read
from plugin.framework.scratch_writer import (
close_scratch_document,
load_scratch_document,
new_blank_writer,
)
from plugin.framework.uno_context import create_property_value, get_desktop, lo_version_below, supports_service
from plugin.writer.math.math_mml_export import (
OBJECT_REPLACEMENT,
inject_exported_math_tex,
portion_math_embed,
substitute_math_placeholders,
)
from . import html_ruby
from . import range_copy
from . import xhtml_style_postprocess as xhtml_post
from .image_placeholders import FRAME_HEAD
log = logging.getLogger("writeragent.writer")
XHTML_FILTER = "XHTML Writer File"
XHTML_EXTENSION = ".xhtml"
FLAT_ODF_FILTER = "OpenDocument Text Flat XML"
FODT_EXTENSION = ".fodt"
PAGE_NUMBER_NUMBERING_TYPE_NAMES: dict[int, str] = {
0: "CHARS_UPPER_LETTER",
1: "CHARS_LOWER_LETTER",
2: "ROMAN_UPPER",
3: "ROMAN_LOWER",
4: "ARABIC",
5: "NUMBER_NONE",
6: "CHAR_SPECIAL",
7: "PAGE_DESCRIPTOR",
8: "BITMAP",
9: "CHARS_UPPER_LETTER_N",
10: "CHARS_LOWER_LETTER_N",
11: "TRANSLITERATION",
12: "NATIVE_NUMBERING",
13: "FULLWIDTH_ARABIC",
14: "CIRCLE_NUMBER",
64: "ARABIC_ZERO",
}
PAGE_NUMBER_NUMBERING_TYPE_VALS: dict[str, int] = {
name: val for val, name in PAGE_NUMBER_NUMBERING_TYPE_NAMES.items()
}
def strip_html_boilerplate(html_string: str) -> str:
"""Extract content between ``<body>`` tags if present."""
if not html_string:
return html_string
match = re.search(r"<body[^>]*>(.*?)</body>", html_string, re.DOTALL | re.IGNORECASE)
if match:
return match.group(1).strip()
return html_string
_DATA_URI_IMAGE_RE = re.compile(
r"data:image/[^\"'\s);>]+;base64,[A-Za-z0-9+/=\s]+",
re.IGNORECASE,
)
# The XHTML filter rewrites a fragment such as ``#2.3.4.Title.|outline`` into
# an HTML-safe id. The raw HyperLinkURL is put back on each exported anchor,
# in the order the source portions were copied.
# An <a> right before a picture's frame is the picture's own link only when that
# picture has a HyperLinkURL; otherwise it is a text link that starts with a picture.
_FRAME_IMG_AHEAD = (
r'(?=[^>]*>(?:%s<(?:div|span)\b[^>]*\bid="(?P<picture>[^"]+)"[^>]*>'
r"\s*(?:<p\b[^>]*>\s*)?<img\b)?)"
) % FRAME_HEAD
_ANCHOR_HREF_RE = re.compile(r'(<a\b[^>]*?\bhref=")([^"]*)(")' + _FRAME_IMG_AHEAD, re.IGNORECASE)
def strip_embedded_image_data(html: str) -> str:
"""Remove inline ``data:image`` base64 payloads from exported HTML; external URLs unchanged."""
if not html:
return html
return _DATA_URI_IMAGE_RE.sub("", html)
# LibreOffice's XHTML export gives every heading an empty outline anchor, ``<a id="a__…">``,
# named after the heading's text. A picture anchored inside the heading puts its whole base64
# data into that name, so a heading holding one embedded screenshot gets a
# 40-65 KB id (the picture twice: once in the id and once in src), even with
# include_images=false. Nothing in WriterAgent, nor the agent, uses these ids.
# shorten_outline_anchor_ids gives a long id a short, stable name, in the id and in any
# ``href="#…"`` that points to it.
_MAX_OUTLINE_ANCHOR_ID = 200
_LONG_OUTLINE_ANCHOR_RE = re.compile(r'(\b(?:id|href)="#?)(a__[^"]{%d,})(")' % _MAX_OUTLINE_ANCHOR_ID)
def shorten_outline_anchor_ids(html: str) -> str:
"""Replace outline anchor ids longer than ``_MAX_OUTLINE_ANCHOR_ID`` with ``a__<crc32>``."""
if not html or "a__" not in html:
return html
return _LONG_OUTLINE_ANCHOR_RE.sub(lambda m: "%sa__%08x%s" % (m.group(1), zlib.crc32(m.group(2).encode("utf-8")), m.group(3)), html)
def _apply_image_export_options(content: str, *, include_images: bool) -> str:
content = shorten_outline_anchor_ids(content)
return content if include_images else strip_embedded_image_data(content)
def _truncate_html(content: str, max_chars: int) -> str:
"""Cut *content* to *max_chars* without ending inside a tag or an entity.
A plain slice ``content[:max_chars]`` can hand the model an unclosed
``<a href="…`` or a trailing ``&nb``. The marker stays so
get_content can set ``truncated``.
"""
window = content[:max_chars]
last_lt = window.rfind("<")
last_gt = window.rfind(">")
if last_lt > last_gt:
window = window[:last_lt]
amp = window.rfind("&")
if amp >= 0 and ";" not in window[amp:]:
window = window[:amp]
return window + "\n\n[... truncated ...]"
def _has_pending_deletion(doc: Any) -> bool:
"""Same filter as ``TrackedDeletions``; cheaper because it reads no bounds."""
redlines = uno_read(doc.getRedlines, None)
if redlines is None or not uno_read(redlines.hasElements, False):
return False
return any(
uno_read(lambda: rl.getPropertyValue("RedlineType"), None) == "Delete"
for rl in iter_elements(redlines.createEnumeration())
)
def _store_with_hidden_deletions(doc: Any, file_url: str, props: tuple[Any, ...]) -> None:
# LO < 25.8 does not hide deletions during flat-ODF/XHTML export (core 7b31fb0c);
# match 26.2's SwXMLExport::exportDoc by switching to show-insertions-only (1).
# The display switch moves struck text, so it runs only when a Delete redline is
# present (the hidden-copy path), avoiding bookmark/style side effects on live docs.
if not lo_version_below(25, 8) or not _has_pending_deletion(doc):
doc.storeToURL(file_url, props)
return
display = uno_read(lambda: doc.getPropertyValue("RedlineDisplayType"), None)
if display not in (2, 3):
doc.storeToURL(file_url, props)
return
was_modified_enabled = doc.disableSetModified()
try:
doc.setPropertyValue("RedlineDisplayType", 1)
try:
doc.storeToURL(file_url, props)
finally:
doc.setPropertyValue("RedlineDisplayType", display)
finally:
if was_modified_enabled:
doc.enableSetModified()
def _read_filter_text(doc: Any, filter_name: str, ext: str = ".html") -> str:
with with_temp_buffer(ext=ext) as (path, file_url):
props = (create_property_value("FilterName", filter_name),)
if filter_name in (FLAT_ODF_FILTER, XHTML_FILTER):
_store_with_hidden_deletions(doc, file_url, props)
else:
doc.storeToURL(file_url, props)
with open(path, "r", encoding="utf-8", errors="replace") as f:
return f.read()
def _store_flat_odf_showing_changes(model: Any, ctx: Any, file_url: str) -> None:
"""Write *model* to *file_url* as flat ODF without hiding pending deletions.
Every ODF store hides pending deletions while it runs and shows them again
afterwards (``SwXMLExport::exportDoc`` in ``xmlexp.cxx`` and
``SwXMLWriter::Write_`` in ``wrtxml.cxx``). Showing them again
(``SwRangeRedline::MoveFromSection``, ``docredln.cxx``) renames bookmarks in
struck text to ``… Copy 1`` and gives a paragraph struck with its mark the
next paragraph's style. ``exportDoc`` skips that switch when the info set
has ``ShowChanges``, so this calls the exporter the flat-ODF filter uses
(``ODT_FlatXML.xcu``) with that property added; it also skips ``FixZOrder``,
which would reorder the live draw page; the copy keeps the document's own
z-order. Deletions are written inline as ``text:change-start/end``, and
LibreOffice loads them back as the same pending deletions. The export marks
the document modified, which ``disableSetModified`` prevents.
"""
smgr = ctx.getServiceManager()
writer = smgr.createInstanceWithContext("com.sun.star.xml.sax.Writer", ctx)
# SAXWriter::endDocument closes the stream (sax/source/expatwrap/saxwriter.cxx).
writer.setOutputStream(
smgr.createInstanceWithContext("com.sun.star.ucb.SimpleFileAccess", ctx).openFileWrite(file_url)
)
info = smgr.createInstanceWithContext("com.sun.star.beans.PropertyBag", ctx)
# Presence suppresses the switch; True sets the copy's ShowRedlineChanges view setting.
info.addProperty("ShowChanges", 0, True)
info.addProperty("BaseURI", 0, file_url)
exporter = smgr.createInstanceWithArgumentsAndContext(
"com.sun.star.comp.Writer.XMLOasisExporter", (writer, info), ctx
)
exporter.setSourceDocument(model)
was = model.disableSetModified()
try:
if not exporter.filter(()):
raise ToolExecutionError("Could not read the document (the flat-ODF copy could not be written).")
finally:
if was:
model.enableSetModified()
class _hidden_copy_showing_changes:
"""Context manager yielding a hidden scratch copy of *model* that keeps its pending deletions.
Implemented as a class rather than ``@contextmanager`` because generator
``__exit__`` assigns ``__traceback__`` while unwinding, which pyuno routes
into the UNO struct (``pyuno/source/module/uno.py:_uno_struct__setattr__``),
rewriting UNO exceptions (see ``docs/framework/exception-policy.md``).
"""
def __init__(self, model: Any, ctx: Any) -> None:
self._model: Any = model
self._ctx: Any = ctx
self._temp_buf: with_temp_buffer | None = None
self._copy: Any = None
def __enter__(self) -> Any:
temp_buf = with_temp_buffer(ext=FODT_EXTENSION)
_path, url = temp_buf.__enter__()
try:
_store_flat_odf_showing_changes(self._model, self._ctx, url)
copy = load_scratch_document(get_desktop(self._ctx), url)
except Exception as e:
temp_buf.__exit__(None, None, None)
reraise_if_disposed(e)
if isinstance(e, ToolExecutionError):
raise
raise ToolExecutionError("Could not read the document (%s)." % _reason(e)) from e
except BaseException:
temp_buf.__exit__(None, None, None)
raise
if copy is None:
temp_buf.__exit__(None, None, None)
raise ToolExecutionError("Could not read the document (no scratch document).")
self._temp_buf = temp_buf
self._copy = copy
return copy
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: Any,
) -> None:
copy = self._copy
temp_buf = self._temp_buf
self._copy = None
self._temp_buf = None
try:
if copy is not None:
best_effort(
lambda: close_scratch_document(copy),
"_hidden_copy_showing_changes: close copy failed",
)
finally:
if temp_buf is not None:
temp_buf.__exit__(exc_type, exc, tb)
def _export_starwriter_html(doc: Any) -> str:
return strip_html_boilerplate(_read_filter_text(doc, HTML_WRITER_FILTER))
def _export_xhtml(doc: Any) -> str:
"""Export *doc* via the XHTML Writer File filter; return the raw XHTML string."""
return _read_filter_text(doc, XHTML_FILTER, ext=XHTML_EXTENSION)
@dataclass(frozen=True)
class _AutostyleMaps:
"""Sidecar data parsed from one flat-ODF export."""
parents: dict[str, str] = field(default_factory=dict)
overrides: dict[str, str] = field(default_factory=dict)
list_styles: dict[str, str] = field(default_factory=dict)
list_restarts: dict[int, int] = field(default_factory=dict)
has_ruby: bool | None = None
has_tabs: bool | None = None
def _autostyle_maps(doc: Any, fodt: str | None = None) -> _AutostyleMaps:
"""Return an ``_AutostyleMaps`` from *doc*'s flat-ODF sidecar.
Exports *doc* as flat ODF when *fodt* is None; otherwise parses *fodt*.
``parents`` (Pn -> base style name) lets the read path recover an autostyle paragraph's real
style name when the XHTML CSS fingerprint matches nothing. ``overrides`` (Pn -> CSS text) is
the paragraph's DIRECT formatting, which the flattened XHTML cannot distinguish from inherited
values. ``list_styles`` (style/Pn -> named UNO NumberingStyleName; an autostyle whose own list
style is automatic, ``Outline``, or empty maps to ``""``, so it does not inherit its parent's)
and ``list_restarts`` (body li index -> start value) preserve custom numbering formats and
continuation vs restart.
``has_ruby`` is True when the sidecar contains ``<text:ruby`` (None on failure so the caller
walks portions); ``has_tabs`` is True when ``<text:tab`` is present (False lets the read
side keep 8 leading spaces at paragraph start as spaces).
All fields come from one export. Returns an empty ``_AutostyleMaps()`` on any failure.
Both scopes report overrides: the range path copies the source paragraphs' direct formatting
onto the temp document first (see paint_direct_formatting)."""
def read_maps() -> _AutostyleMaps:
sidecar = _read_filter_text(doc, FLAT_ODF_FILTER, ext=FODT_EXTENSION) if fodt is None else fodt
parents, overrides = xhtml_post.parse_fodt_autostyles(sidecar)
return _AutostyleMaps(
parents=parents,
overrides=overrides,
list_styles=xhtml_post.parse_fodt_list_styles(sidecar),
list_restarts=xhtml_post.parse_fodt_list_restarts(sidecar),
has_ruby="<text:ruby" in sidecar,
has_tabs="<text:tab" in sidecar,
)
return best_effort(read_maps, "_autostyle_maps: flat-ODF export failed", _AutostyleMaps())
_COPY_PORTION_LIMIT = 50000
def _visible_portions(
para: Any,
limit: int = _COPY_PORTION_LIMIT,
truncated_out: list[str] | None = None,
state: DeletionState | None = None,
) -> Iterator[Any]:
"""Visible portions for offset paint. Same walk as the text helper.
Aborts on portion enum / type failure so later runs are not painted at a
drifted offset. ``get_string_without_tracked_deletions`` continues past a
bad portion instead — that is the only intentional divergence.
When the portion walk hits *limit*, log and append ``walk_cap_warning`` to
*truncated_out* so truncated range reads are visible instead of omitting later
Char* runs without a signal.
"""
hit: list[int] = []
yield from visible_portions(
para, abort_on_portion_error=True, limit=limit, truncated_out=hit, state=state
)
if hit:
msg = walk_cap_warning("text portions", hit[0], limit)
log.warning("%s", msg)
if truncated_out is not None:
truncated_out.append(msg)
def _hyperlink_urls(portions: list[tuple[Any, str]]) -> list[str]:
"""One URL per hyperlink run of a paragraph, in order.
The XHTML filter emits one ``<a>`` per run, not per text portion, and it
rewrites the fragment. A bold split or a preserve-format replace leaves two
portions with the same URL and one anchor; writing every portion would put
the extra URL on the next anchor. A portion with no URL separates runs, so
two copies of the same URL with plain text between them stay two anchors.
A picture in the scratch copy ends the link run and the filter writes two
anchors: an empty ``Frame`` portion resets *previous* when its URL differs
from the surrounding link. The source document reports the text link's URL on
the ``Frame``, whereas the scratch copy reports ``''``, and that difference
tells one anchor from two.
"""
urls = []
previous = None
for portion, chunk in portions:
if not chunk:
if uno_read(lambda: portion.getPropertyValue("TextPortionType"), "") == "Frame":
url = uno_read(lambda: portion.getPropertyValue("HyperLinkURL"), "")
if url != previous:
previous = None
continue
url = uno_read(lambda: portion.getPropertyValue("HyperLinkURL"), "")
if not url:
previous = None
continue
if url == previous:
continue
urls.append(url)
previous = url
return urls
def _picture_urls(doc: Any) -> dict[str, str]:
"""Map graphic object names to non-empty ``HyperLinkURL`` values for name-based lookup.
``create-href`` (``common/body.xsl``) builds ``#a_`` from all descendant text including
base64 image data, so picture links cannot be paired by count.
"""
graphics = doc.getGraphicObjects()
urls: dict[str, str] = {}
for name in graphics.getElementNames():
url = graphics.getByName(name).getPropertyValue("HyperLinkURL")
if url:
urls[name] = url
return urls
def _picture_url(match: re.Match[str], picture_urls: dict[str, str]) -> str | None:
"""Return the picture's own ``HyperLinkURL`` when *match* immediately precedes a linked picture wrapper."""
name = match["picture"]
return picture_urls.get(html_unescape(name)) if name else None
def _restore_anchor_hrefs(
content: str,
urls: list[str],
anchor_re: re.Pattern[str],
picture_urls: dict[str, str],
) -> str:
"""Write *urls* back onto exported anchors matching *anchor_re*. The filter does not keep ``|outline``."""
if not content:
return content
remaining = iter(urls)
def _replace(match: re.Match[str]) -> str:
url = _picture_url(match, picture_urls) or next(remaining, None)
if url is None:
return match.group(0)
return match.group(1) + html_escape(url, quote=True) + match.group(3)
return anchor_re.sub(_replace, content)
# In LibreOffice's XSLT export (filter/source/xslt/odf2xhtml/export/common/body.xsl
# template create-href and common/table_of_content.xsl), an "|outline" link is written
# as "#a_" + the link's own visible text, so the heading target is lost. Footnote anchors
# (#ftn0) sit between them in the exported HTML, so only #a_ hrefs are paired with
# only outline URLs, and only when the counts agree. A tracked deletion that splits
# across a hyperlink leaves empty <a href="#a_"/> anchors in the split paragraphs;
# requiring at least one char after #a_ skips them so the count guard still matches.
_EXPORTED_OUTLINE_HREF_RE = re.compile(
r'(<a\b[^>]*?\bhref=")(#a_[^"]+)(")' + _FRAME_IMG_AHEAD, re.IGNORECASE
)
def _is_outline_url(url: str) -> bool:
return "|outline" in url or "%7Coutline" in url
def _put_outline_urls(content: str, urls: list[str], picture_urls: dict[str, str]) -> str:
"""Pure: write the outline URLs among *urls* onto exported #a_ anchors, in order; text unchanged on count mismatch."""
outline_urls = [u for u in urls if _is_outline_url(u)]
anchor_count = sum(
1 for m in _EXPORTED_OUTLINE_HREF_RE.finditer(content) if _picture_url(m, picture_urls) is None
)
if anchor_count != len(outline_urls):
log.debug(
"_put_outline_urls: count mismatch (%d #a_ hrefs vs %d outline URLs); leaving text links unchanged",
anchor_count,
len(outline_urls),
)
outline_urls = []
return _restore_anchor_hrefs(content, outline_urls, _EXPORTED_OUTLINE_HREF_RE, picture_urls)
def _body_hyperlink_urls(model: Any) -> list[str]:
body = model.getText()
urls: list[str] = []
for para, state in iter_xtext_paragraphs(body, TrackedDeletions(model).state_at(body)):
urls.extend(_hyperlink_urls(list(_visible_portions(para, state=state))))
return urls
def _restore_outline_hrefs(model: Any, content: str) -> str:
"""Full-read counterpart of the range path's _restore_anchor_hrefs.
Walks only body and table paragraphs; outline links in frames, footnotes, or
headers make the counts differ, and the guard in ``_put_outline_urls`` then
leaves text links unchanged. Note that ``iter_xtext_paragraphs`` walks tables
via ``getCellNames()`` (``lcl_InspectLines`` in
``sw/source/core/unocore/unotbl.cxx:567``), which visits sub-cells of an
old-style split cell before later columns in the same visual row, so
outline links in such a table can be paired in ``getCellNames()`` order
rather than export order. A walk failure returns *content* rather than
raising so a cosmetic restore failure cannot push the whole read onto the
StarWriter fallback (which would drop every style token).
"""
if 'href="#a_' not in content:
return content
try:
urls = _body_hyperlink_urls(model)
picture_urls = _picture_urls(model)
except Exception as exc:
reraise_if_disposed(exc)
log.debug("_restore_outline_hrefs: portion walk failed", exc_info=True)
return content
return _put_outline_urls(content, urls, picture_urls)
def _starts_before(text: Any, left: Any, right: Any) -> bool:
"""True when *left* is strictly before *right* (``compareRegionStarts`` == 1)."""
return text.compareRegionStarts(left, right) == 1
def _ends_after(text: Any, left: Any, right: Any) -> bool:
"""True when *left* ends strictly after *right* (``compareRegionEnds`` == -1)."""
return text.compareRegionEnds(left, right) == -1
def _element_overlaps(text: Any, element: Any, source: Any) -> bool:
"""True when *element* and *source* share a character.
SwXText::ComparePositions (sw/source/core/unocore/unotext.cxx) throws only
when a range is not in this text. The caller's window comes from that same
text, so a failure means the read cannot place the paragraph, and the
range read raises instead of guessing.
"""
return (
_starts_before(text, element.getStart(), source.getEnd())
and _ends_after(text, element.getEnd(), source.getStart())
)
class _TableStartRange(NamedTuple):
"""Range-like value for a selection that starts inside a body table and ends in the body."""
text: Any
anchor: Any
end: Any
def getText(self) -> Any:
return self.text
def getStart(self) -> Any:
return self.anchor
def getEnd(self) -> Any:
return self.end
def _table_start_range(body: Any, start: Any, end: Any) -> _TableStartRange | None:
"""Resolve a table-start/body-end selection to the outer body table's anchor."""
body.createTextCursorByRange(end)
last_anchor: Any = None
for el in iter_elements(body.createEnumeration()):
if not supports_service(el, "com.sun.star.text.TextTable"):
continue
anchor = el.getAnchor()
if not starts_at_or_after(body, start, anchor):
break
last_anchor = anchor
return _TableStartRange(body, last_anchor, end) if last_anchor is not None else None
def _selection_cursor(model: Any, selection: Any | None = None) -> Any | None:
"""The current selection (or explicit *selection* range) as a cursor in its own text, or None.
Selection scope builds a cursor in the selection's own XText instead of body
character offsets, so index/TOC selections do not export a later body paragraph.
A selection starting in a body table and ending in the body has two forms:
Ctrl+A (``SwCursorShell::ExtendedSelectAll``, ``sw/source/core/crsr/crsrsh.cxx``)
gives ``SwXCell`` whose ``createXTextCursorByRangeImpl`` (``unotbl.cxx``) returns
None for an end outside the cell, and a programmatic ``SwXBodyText`` range whose
``start`` is inside a cell causes ``createTextCursorByRange`` to raise (interactive
Shift+arrow cannot leave a table because ``SwCursor::IsSelOvr`` in
``sw/source/core/crsr/swcrsr.cxx`` restores the saved position). Both fall back
to ``_table_start_range``.
"""
found = get_writer_selection_positions(model, selection=selection)
if not found:
return None
text, start, end = found
def select() -> Any:
if (
uno_read(lambda: text.createTextCursorByRange(start), None) is None
or uno_read(lambda: text.createTextCursorByRange(end), None) is None
):
return _table_start_range(model.getText(), start, end)
cursor = text.createTextCursorByRange(start)
cursor.gotoRange(end, True)
return cursor
return best_effort(select, "_selection_cursor failed")
def _trim_to_source(
text: Any, element: Any, para_text: str, source: Any, opened: bool
) -> tuple[int, int]:
"""Visible-text window of *element* that lies inside *source*."""
# getStart/getEnd and region comparisons run on ranges from the same text;
# any failure raises to the outer handler so the slice does not guess.
start_inside = _starts_before(text, element.getStart(), source.getStart())
end_inside = _ends_after(text, element.getEnd(), source.getEnd())
if not start_inside and not end_inside:
return 0, len(para_text)
trim_start = 0
trim_end = len(para_text)
if start_inside:
cur = text.createTextCursorByRange(element.getStart())
cur.gotoRange(source.getStart(), True)
trim_start = len(get_string_without_tracked_deletions(cur, DeletionState(opened)))
if end_inside:
cur = text.createTextCursorByRange(element.getStart())
cur.gotoRange(source.getEnd(), True)
trim_end = len(get_string_without_tracked_deletions(cur, DeletionState(opened)))
return trim_start, trim_end
# (element, visible para text, tables just before it, opened inside a tracked
# deletion, the request's shared TrackedDeletions) -> (tables inside the window,
# (trim_start, trim_end) in visible coordinates (_visible_portions, tracked
# deletions removed) or None to skip the element). Tables are read whole.
_Window = Callable[[Any, str, "list[Any]", bool, "TrackedDeletions | None"], "tuple[list[Any], tuple[int, int] | None]"]
def _selection_window(text: Any, source: Any) -> tuple[Callable[[Any], bool], _Window]:
"""Window filter and stop predicate for selection-range export."""
def past_end(el: Any) -> bool:
return starts_at_or_after(text, el.getStart(), source.getEnd())
def window(
el: Any, para_text: str, tables: list[Any], opened: bool, _deletions: TrackedDeletions | None
) -> tuple[list[Any], tuple[int, int] | None]:
# A table has no getStart; its anchor is a point inside its first cell.
# >= at start is needed because _TableStartRange.getStart() can be the table's own anchor.
inside = [
t for t in tables
if _starts_before(text, t.getAnchor(), source.getEnd())
and starts_at_or_after(text, t.getAnchor(), source.getStart())
]
if past_end(el) or not _element_overlaps(text, el, source):
return inside, None
return inside, _trim_to_source(text, el, para_text, source, opened)
return past_end, window
def _offset_window(start: int, end: int) -> tuple[Callable[[Any], bool], _Window]:
"""Window filter for character-offset slice export.
Counts as ``text_helpers._body_blocks`` does: each element is its visible
text plus one break. Tables are read whole when the range touches them.
The walk stops once the running offset reaches ``end``, because every later
element starts at or after ``pos``, so ``window`` could not include it.
Element and table offsets only grow.
"""
pos = 0
def window(
el: Any, para_text: str, tables: list[Any], opened: bool, deletions: TrackedDeletions | None
) -> tuple[list[Any], tuple[int, int] | None]:
nonlocal pos
inside = []
for table in tables:
table_start = pos
# Same TrackedDeletions as _body_blocks, so table cells are counted the same way and not re-walked per cell.
pos += len(table_visible_text(table, opened, deletions=deletions)) + 1
if table_start < end and pos > start:
inside.append(table)
para_start = pos
para_end = para_start + len(para_text)
pos = para_end + 1
if para_end < start or (para_text and para_end == start) or para_start >= end:
return inside, None
return inside, (max(0, start - para_start), len(para_text) - max(0, para_end - end))
return (lambda _el: pos >= end), window
def _copy_formula_runs(
portions: list[tuple[Any, str]],
trim_start: int,
trim_end: int,
temp_doc: Any,
temp_text: Any,
temp_cursor: Any,
math_records: list[tuple[str, str, bool]],
) -> None:
"""Copy formula, graphic, and text runs into *temp_text*, recording placeholders."""
# Standalone formula: paragraph has no other visible text.
display_block = not any(
chunk.strip() and chunk != OBJECT_REPLACEMENT and not portion_math_embed(p)
for p, chunk in portions
)
cur_offset = 0
for p, chunk in portions:
run_len = len(chunk)
run_start = cur_offset
run_end = cur_offset + run_len
cur_offset += run_len
emb = portion_math_embed(p)
if emb is not None:
# A formula portion can be zero-length; keep it when it sits inside the window.
if run_start < trim_start or run_start > trim_end:
continue
slice_text = range_copy.record_math_placeholder(math_records, emb, display_block=display_block)
elif not chunk and uno_read(lambda: p.getPropertyValue("TextPortionType"), "") == "Frame":
if trim_start <= run_start <= trim_end:
range_copy.clone_graphics(p, temp_doc, temp_text, temp_cursor)
continue
else:
if run_end <= trim_start or run_start >= trim_end:
continue
s_start = max(0, trim_start - run_start)
s_end = run_len - max(0, run_end - trim_end)
slice_text = chunk[s_start:s_end]
if not slice_text:
continue
range_copy.copy_text_run(p, temp_text, temp_cursor, slice_text)
def _copy_window_to_scratch(
model: Any,
text: Any,
temp_doc: Any,
past_end: Callable[[Any], bool],
window: _Window,
walk_warnings: list[str] | None,
) -> tuple[list[Any], list[tuple[str, str, bool]]] | None:
"""Copy elements matching *window* into *temp_doc*.
Returns (copied_ruby, math_records), or None when no element was copied.
"""
temp_text = temp_doc.getText()
temp_cursor = temp_text.createTextCursor()
style_cache: dict[str, Any] = {}
enum = text.createEnumeration()
added_any = False
copied_ruby = []
math_records: list[tuple[str, str, bool]] = []
deletions = TrackedDeletions(model)
state = deletions.state_at(text)
tables: list[Any] = []
need_break = False
for el in iter_elements(enum):
if supports_service(el, "com.sun.star.text.TextTable"):
tables.append(el)
continue
done = past_end(el)
if done and not tables:
break
# Paragraphs always have ParaStyleName.
style = el.getPropertyValue("ParaStyleName") or ""
# Same _visible_portions walk as get_string_without_tracked_deletions so
# paint offsets match the helper string. Still walk here (not just the
# helper) because we need the portion objects to copy Char* properties.
opened = state.in_delete
portions = list(_visible_portions(el, truncated_out=walk_warnings, state=state))
has_formula = any(portion_math_embed(p) is not None for p, _unused in portions)
para_text = "".join(chunk for _unused, chunk in portions)
struck = state.strikes_paragraph(el, opened)
inside, trim = window(el, para_text, tables, opened, deletions)
if deletions:
# A table struck by a spanning deletion or by Delete Table is not live content.
inside = [t for t in inside if not range_copy.table_is_struck(model, t, DeletionState(opened))]
tables = []
for table in inside:
temp_cursor.gotoEnd(False)
if need_break:
range_copy.begin_next_paragraph(temp_text, temp_cursor)
# Range reads with include_images=False emit placeholders named after the clone;
# keeping the source name (when unused in temp_doc) prevents a later write-back
# (image_placeholders) from restoring a different picture of that name.
range_copy.copy_table(model, table, temp_doc, temp_text, temp_cursor, deletions, math_records, mark_struck=True)
for para, table_state in iter_table_paragraphs(table):
copied_ruby.extend(
html_ruby.ruby_spans_in_window(para, 0, len(para.getString()), table_state)
)
need_break = False
added_any = True
if done:
break
if trim is None:
continue
trim_start, trim_end = trim
para_text = para_text[trim_start:trim_end]
temp_cursor.gotoEnd(False)
if need_break:
range_copy.begin_next_paragraph(temp_text, temp_cursor)
need_break = True
applied = range_copy.apply_temp_para_style(temp_doc, temp_cursor, style, model)
if not has_formula:
temp_cursor.setString(para_text + xhtml_post.DELETED_MARK if struck else para_text)
src_style = range_copy.source_style(model, style, style_cache) if applied else None
range_copy.paint_direct_formatting(el, portions, temp_text, trim_start, trim_end, src_style)
range_copy.clone_window_graphics(el, portions, temp_doc, temp_text, trim_start, trim_end, deletions)
else:
_copy_formula_runs(
portions, trim_start, trim_end, temp_doc, temp_text, temp_cursor, math_records
)
if trim_start == 0:
range_copy.clone_graphics(el, temp_doc, temp_text, temp_cursor, deletions)
# RubyText lives on the empty Ruby start mark, not the Text run, so
# _COPIED_CHAR_PROPERTIES cannot recreate ruby on the temp doc.
# Collect source spans and rewrite the exported HTML after XHTML.
copied_ruby.extend(
html_ruby.ruby_spans_in_window(el, trim_start, trim_end, DeletionState(opened))
)
added_any = True
return (copied_ruby, math_records) if added_any else None
def _list_paragraph_ids(model: Any) -> list[tuple[str, str | None]]:
"""Return ``(NumberingStyleName, ListId | None)`` per body paragraph inside a list.
Matches ``xmloff/source/text/XMLTextNumRuleInfo.cxx`` (``XMLTextNumRuleInfo::Set``),
which puts a paragraph inside ``text:list`` when its numbering rule is neither empty
nor ``"Outline"`` (``sw/source/core/doc/number.cxx:83`` ``SwNumRule::GetOutlineRuleName``).
Tables are skipped (table lists do not carry ``data-lo-list-id``). A ``ListId`` matching
the style's ``DefaultListId`` is reported as ``None`` because setting the style alone
already places the paragraph in that default list.
"""
num_styles: Any = None
default_ids: dict[str, str | None] = {}
result: list[tuple[str, str | None]] = []
for el in iter_elements(model.getText().createEnumeration()):
if not supports_service(el, "com.sun.star.text.Paragraph"):
continue
num_style, list_id = el.getPropertyValues(("NumberingStyleName", "ListId"))
if not num_style or num_style == "Outline":
continue
if num_style not in default_ids:
if num_styles is None:
num_styles = model.getStyleFamilies().getByName("NumberingStyles")
if num_styles.hasByName(num_style):
rules = num_styles.getByName(num_style).getPropertyValue("NumberingRules")
default_ids[num_style] = rules.getPropertyValue("DefaultListId")
else:
default_ids[num_style] = None
default_id = default_ids[num_style]
result.append((num_style, None if not list_id or list_id == default_id else list_id))
return result
def _export_semantic(
doc: Any,
*,
read_ruby: bool,
fodt: str | None = None,
live_doc: Any = None,
) -> tuple[str, bool | None]:
"""Export *doc* as XHTML and convert to semantic HTML using flat-ODF autostyles.
The sidecar is a second full export unless the caller already has *fodt*. It
runs when there are autostyles to name, or when the caller needs the ruby
flag (the full read skips a portion walk with it). has_ruby is None when the
sidecar did not run, and finish() then walks portions itself. *live_doc* is
the user's document; scratch copies regenerate ``ListId`` on import
(``xmloff/source/text/XMLTextListBlockContext.cxx``), so list identity is
walked on *live_doc*. The function raises on export failure, and each caller
owns its fallback.
"""
xhtml = _export_xhtml(doc)
# Named list styles and list-restart markers live only in the flat-ODF sidecar (the XHTML
# export strips style:list-style-name and text:continue-numbering), so list reads need it too.
if read_ruby or xhtml_post.xhtml_has_paragraph_autostyle(xhtml) or "<ol" in xhtml or "<ul" in xhtml:
maps = _autostyle_maps(doc, fodt)
else:
maps = _AutostyleMaps()
# Empty-string entries in list_styles are only markers that block the parent fallback;
# only walk live_doc when at least one style maps to a named UNO list style.
list_paragraphs = (
_list_paragraph_ids(live_doc)
if live_doc is not None and any(maps.list_styles.values())
else None
)
return (
xhtml_post.xhtml_to_semantic_html(
xhtml,
maps.parents,
maps.overrides,
maps.list_styles,
list_restarts=maps.list_restarts,
has_tabs=maps.has_tabs,
list_paragraphs=list_paragraphs,
),
maps.has_ruby,
)
def _range_to_content_via_temp_doc(
model: Any,
ctx: Any,
start: int,
end: int,
max_chars: int | None,
*,
include_images: bool = False,
walk_warnings: list[str] | None = None,
source_range: Any = None,
) -> str:
"""Export a character range, or *source_range* itself, via a hidden temp document.
*source_range* is the selection. It is copied from that cursor's text, not
re-found by character offset.
"""
temp_doc = None
try:
# Blank scratch doc: the factory URL honours the user's default template,
# and this function reads the whole body back (see new_blank_writer).
temp_doc = new_blank_writer(ctx)
if not temp_doc:
# Missing scratch Writer raises ToolExecutionError instead of returning
# empty content with status ok.
raise ToolExecutionError(
"Could not read that part of the document (no scratch document)."
)
text = source_range.getText() if source_range is not None else model.getText()
past_end, window = (
_selection_window(text, source_range)
if source_range is not None
else _offset_window(start, end)
)
copied = _copy_window_to_scratch(model, text, temp_doc, past_end, window, walk_warnings)
if copied is None:
return ""
copied_ruby, math_records = copied
try:
content, _unused_ruby = _export_semantic(temp_doc, read_ruby=False)
except Exception as e:
# A closed document must not start a second export.
reraise_if_disposed(e)
log.exception("_range_to_content_via_temp_doc (XHTML) failed; falling back to StarWriter")
# Degraded path: strips the mark and leaves a blank paragraph rather than omitting it.
content = _export_starwriter_html(temp_doc).replace(xhtml_post.DELETED_MARK, "")
content = _restore_anchor_hrefs(
content, _body_hyperlink_urls(temp_doc), _ANCHOR_HREF_RE, _picture_urls(temp_doc)
)
content = _apply_image_export_options(content, include_images=include_images)
content = substitute_math_placeholders(content, math_records, ctx)
content = html_ruby.inject_ruby_into_html(content, copied_ruby)
if max_chars and len(content) > max_chars:
content = _truncate_html(content, max_chars)
return content
except Exception as e:
# Disposal is not "could not read that part". A ToolExecutionError
# raised above (missing scratch doc) must not be wrapped again.
reraise_if_disposed(e)
if isinstance(e, ToolExecutionError):
raise
# Same rule as the full read: a failed read raises with its reason instead of returning ok with empty content.
raise ToolExecutionError("Could not read that part of the document (%s)." % _reason(e)) from e
finally:
if temp_doc is not None:
best_effort(lambda: close_scratch_document(temp_doc), "_range_to_content_via_temp_doc: close temp doc failed")
range_copy.release_scratch_style_holds(temp_doc)
def _export_full(
model: Any, ctx: Any, deletions: bool, live_doc: Any = None
) -> tuple[str, bool | None]:
"""Export the full document via XHTML, simplifying drawings and expanding deletions/hidden sections first.
``SwXMLExport::exportDoc`` hides deletions by joining paragraphs across a
multi-paragraph deletion and ``odf2xhtml`` drops empty headings/blocks and
``text:section[@text:display='none']``, emits bare shape titles/text
without wrappers, and leaks non-math OLE metadata. When tracked deletions