1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
29use std::fmt;
30
31use serde::{Deserialize, Serialize};
32use unicode_segmentation::UnicodeSegmentation;
33
34use crate::changes::{Change, ChangeError, ChangeFilter, ChangeKind, MoveSide};
35
36#[doc(hidden)]
37pub use crate::inspect::SCHEMA_VERSION;
38use crate::inspect::{BODY_STORY, Opened, Piece, Projection, project_paragraph, source_sha256};
39use crate::namespaces::W;
40use crate::xmllinq::{Dom, NodeId, XNamespace};
41
42#[doc(hidden)]
43pub mod anchor;
44#[doc(hidden)]
45pub mod anchor_error;
46mod apply;
47mod comments;
48mod controls;
49pub mod flags;
50mod formatting;
51mod hint;
52mod images;
53mod locating;
54mod notes;
55mod origin;
56mod plan;
57pub mod prepared;
60mod ranges;
61pub mod record;
62pub mod refusal;
64mod replacement_order;
65pub mod resolution;
66mod rewrite;
67mod runs;
68pub(crate) mod sections;
69mod settlement;
70mod skip;
71mod structural;
72mod tracked;
73mod transaction;
74mod visible;
75mod watermark;
76mod whole;
77
78pub mod v2;
79use crate::comment_settlement::AnchorChanges;
80pub use crate::comment_settlement::{KeptComment, RemovedComment};
81pub mod v2_apply;
82
83pub mod for_edit;
85pub(crate) mod native_keys;
89#[doc(hidden)]
90pub mod source_refs;
91pub mod template;
93
94pub use anchor::{NearMatches, NearOccurrence, v2_candidates, v2_select, v2_select_all};
96pub use anchor_error::{AnchorRefusal, Working, v2_resolve, v2_resolve_all};
98pub use controls::ControlSelector;
100pub use hint::PlanSyntax;
102pub use prepared::{
104 CandidateChecks, PrepareOptions, PreparedEdit, PrimaryBytes, PrimaryRole, introduced_findings,
105 prepare, prepare_v2,
106};
107pub use sections::{CustomPage, Margins, Orientation, PageSize, Paper, SectionScope};
110pub use skip::{SkippedOperation, failed_plan_json, keep_notes};
112
113use apply::*;
114use comments::*;
115use formatting::*;
116use locating::*;
117use plan::*;
118use settlement::*;
119
120#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(deny_unknown_fields)]
123pub struct EditPlan {
124 pub schema_version: u32,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub source_sha256: Option<String>,
130 pub author: String,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub date: Option<String>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub initials: Option<String>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub resolve_revisions: Option<ResolveRevisions>,
144 #[serde(default, skip_serializing_if = "RemovedAnchorComments::is_remove")]
147 pub removed_anchor_comments: RemovedAnchorComments,
148 #[serde(default)]
150 pub existing_revisions: ExistingRevisions,
151 pub operations: Vec<Operation>,
153 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
157 pub update_fields: bool,
158 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
162 pub rewrite_others_comments: bool,
163 #[serde(default, skip_serializing_if = "Others::is_allow")]
168 pub others: Others,
169}
170
171#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "snake_case")]
178pub enum Others {
179 #[default]
182 Allow,
183 Keep,
185}
186
187impl Others {
188 fn keeps(self) -> bool {
190 self == Self::Keep
191 }
192
193 fn is_allow(&self) -> bool {
194 *self == Self::Allow
195 }
196}
197
198#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "snake_case")]
201pub enum RemovedAnchorComments {
202 #[default]
204 Remove,
205 Keep,
207}
208impl RemovedAnchorComments {
209 fn is_remove(&self) -> bool {
210 *self == Self::Remove
211 }
212}
213
214#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(from = "ResolveRevisionsWire", into = "ResolveRevisionsWire")]
221pub struct ResolveRevisions {
222 pub accept: Option<ChangeFilter>,
224 pub reject: Option<ChangeFilter>,
226 pub reject_visible: bool,
230}
231
232#[derive(Serialize, Deserialize)]
234#[serde(deny_unknown_fields)]
235struct ResolveRevisionsWire {
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 accept: Option<ChangeFilter>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 reject: Option<RejectWire>,
240}
241
242#[derive(Serialize, Deserialize)]
244#[serde(deny_unknown_fields)]
245struct RejectWire {
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 ids: Option<Vec<String>>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
249 authors: Option<Vec<String>>,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
251 kinds: Option<Vec<ChangeKind>>,
252 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
253 visible: bool,
254}
255
256impl From<ResolveRevisionsWire> for ResolveRevisions {
257 fn from(wire: ResolveRevisionsWire) -> Self {
258 let reject_visible = wire.reject.as_ref().is_some_and(|r| r.visible);
259 Self {
260 accept: wire.accept,
261 reject: wire.reject.map(|r| ChangeFilter {
262 ids: r.ids,
263 authors: r.authors,
264 kinds: r.kinds,
265 }),
266 reject_visible,
267 }
268 }
269}
270
271impl From<ResolveRevisions> for ResolveRevisionsWire {
272 fn from(selection: ResolveRevisions) -> Self {
273 Self {
274 accept: selection.accept,
275 reject: selection.reject.map(|r| RejectWire {
276 ids: r.ids,
277 authors: r.authors,
278 kinds: r.kinds,
279 visible: selection.reject_visible,
280 }),
281 }
282 }
283}
284
285#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
287pub struct ParagraphMove {
288 pub from: String,
290 pub to: Option<String>,
293}
294
295#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
298pub struct RevisionSplit {
299 pub from: String,
301 pub to: Vec<String>,
303}
304
305#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
307pub struct ResolvedRevisions {
308 #[serde(default, skip_serializing_if = "Vec::is_empty")]
310 pub accepted: Vec<String>,
311 #[serde(default, skip_serializing_if = "Vec::is_empty")]
313 pub rejected: Vec<String>,
314}
315
316impl ResolvedRevisions {
317 pub fn is_empty(&self) -> bool {
319 self.accepted.is_empty() && self.rejected.is_empty()
320 }
321}
322
323#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "snake_case")]
326pub enum ExistingRevisions {
327 #[default]
329 Refuse,
330 Accept,
332 Reject,
334 Keep,
337}
338
339#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
341pub struct Operation {
342 #[serde(default, skip_serializing_if = "Option::is_none")]
343 pub id: Option<String>,
345 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub group: Option<String>,
350 #[serde(flatten)]
351 pub kind: OperationKind,
353}
354
355#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
357#[serde(tag = "kind", rename_all = "snake_case")]
358pub enum OperationKind {
359 Replace {
361 paragraph: Selector,
363 find: String,
365 replacement: String,
367 #[serde(default, skip_serializing_if = "Option::is_none")]
368 format: Option<RunFormat>,
370 #[serde(
371 default,
372 deserialize_with = "blank_is_none",
373 skip_serializing_if = "Option::is_none"
374 )]
375 comment: Option<String>,
377 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
378 whole: bool,
381 #[serde(default, skip_serializing_if = "Option::is_none")]
382 #[schemars(range(min = 1))]
383 occurrence: Option<usize>,
386 },
387 #[schemars(extend("oneOf" = exactly_one(&["after", "before", "position"])))]
391 Insert {
392 paragraph: Selector,
394 #[serde(default, skip_serializing_if = "Option::is_none")]
395 after: Option<String>,
397 #[serde(default, skip_serializing_if = "Option::is_none")]
398 before: Option<String>,
400 #[serde(default, skip_serializing_if = "Option::is_none")]
401 position: Option<Edge>,
403 text: String,
405 #[serde(default, skip_serializing_if = "Option::is_none")]
406 format: Option<RunFormat>,
408 #[serde(
409 default,
410 deserialize_with = "blank_is_none",
411 skip_serializing_if = "Option::is_none"
412 )]
413 comment: Option<String>,
415 #[serde(default, skip_serializing_if = "Option::is_none")]
416 #[schemars(range(min = 1))]
417 occurrence: Option<usize>,
420 },
421 Delete {
423 paragraph: Selector,
425 find: String,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 #[schemars(range(min = 1))]
429 occurrence: Option<usize>,
432 #[serde(
433 default,
434 deserialize_with = "blank_is_none",
435 skip_serializing_if = "Option::is_none"
436 )]
437 comment: Option<String>,
440 },
441 #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]))]
445 Comment {
446 paragraph: Selector,
448 #[serde(default, skip_serializing_if = "Option::is_none")]
449 find: Option<String>,
451 text: String,
453 #[serde(default, skip_serializing_if = "Option::is_none")]
454 through: Option<Selector>,
458 #[serde(default, skip_serializing_if = "Option::is_none")]
459 #[schemars(range(min = 1))]
460 occurrence: Option<usize>,
463 },
464 InsertParagraph {
468 paragraph: Selector,
470 #[serde(default)]
471 position: Side,
473 runs: Vec<RunSpec>,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
476 like: Option<Selector>,
480 #[serde(default, skip_serializing_if = "Option::is_none")]
481 style: Option<String>,
483 #[serde(
484 default,
485 deserialize_with = "blank_is_none",
486 skip_serializing_if = "Option::is_none"
487 )]
488 comment: Option<String>,
490 },
491 DeleteParagraph {
493 paragraph: Selector,
495 #[serde(
496 default,
497 deserialize_with = "blank_is_none",
498 skip_serializing_if = "Option::is_none"
499 )]
500 comment: Option<String>,
503 },
504 #[schemars(extend("anyOf" = at_least_one(&["style", "alignment", "line_spacing", "space_before", "space_after"])))]
508 FormatParagraph {
509 paragraph: Selector,
511 #[serde(default, skip_serializing_if = "Option::is_none")]
512 style: Option<String>,
514 #[serde(default, skip_serializing_if = "Option::is_none")]
515 alignment: Option<Alignment>,
517 #[serde(default, skip_serializing_if = "Option::is_none")]
518 line_spacing: Option<LineSpacing>,
520 #[serde(default, skip_serializing_if = "Option::is_none")]
521 space_before: Option<Points>,
523 #[serde(default, skip_serializing_if = "Option::is_none")]
524 space_after: Option<Points>,
526 },
527 MergeParagraphs {
532 paragraph: Selector,
534 #[serde(default, skip_serializing_if = "Option::is_none")]
535 separator: Option<String>,
537 },
538 Rewrite {
545 paragraph: Selector,
547 text: String,
549 #[serde(
550 default,
551 deserialize_with = "blank_is_none",
552 skip_serializing_if = "Option::is_none"
553 )]
554 comment: Option<String>,
556 },
557 ReplyComment {
561 #[serde(deserialize_with = "crate::ids::comment_id_de")]
564 #[schemars(with = "crate::ids::RawCommentId")]
565 comment_id: u32,
566 text: String,
568 },
569 ResolveComment {
572 #[serde(deserialize_with = "crate::ids::comment_id_de")]
574 #[schemars(with = "crate::ids::RawCommentId")]
575 comment_id: u32,
576 #[serde(default = "resolve_done")]
577 done: bool,
579 },
580 EditComment {
583 #[serde(deserialize_with = "crate::ids::comment_id_de")]
585 #[schemars(with = "crate::ids::RawCommentId")]
586 comment_id: u32,
587 text: String,
589 },
590 DeleteComment {
593 #[serde(deserialize_with = "crate::ids::comment_id_de")]
595 #[schemars(with = "crate::ids::RawCommentId")]
596 comment_id: u32,
597 },
598 #[schemars(extend("x-jubarte-keep-only" = true))]
603 Strike {
604 revision: String,
608 #[serde(
609 default,
610 deserialize_with = "blank_is_none",
611 skip_serializing_if = "Option::is_none"
612 )]
613 comment: Option<String>,
615 },
616 #[schemars(extend("x-jubarte-keep-only" = true))]
620 Restore {
621 revision: String,
625 #[serde(
626 default,
627 deserialize_with = "blank_is_none",
628 skip_serializing_if = "Option::is_none"
629 )]
630 comment: Option<String>,
632 },
633 #[schemars(extend("x-jubarte-targets" = ["body"]))]
637 InsertTable {
638 paragraph: Selector,
640 #[serde(default)]
641 position: Side,
643 rows: Vec<Vec<String>>,
645 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
646 header_row: bool,
648 #[serde(default, skip_serializing_if = "Option::is_none")]
649 #[schemars(inner(range(min = 1, max = structural::MAX_WIDTH_DXA)))]
650 widths_dxa: Option<Vec<u32>>,
653 #[serde(default, skip_serializing_if = "Option::is_none")]
654 style: Option<String>,
657 },
658 #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]))]
662 List {
663 paragraphs: Vec<Selector>,
666 #[serde(default)]
667 kind_of_list: ListKind,
669 #[serde(default)]
670 #[schemars(range(min = 0, max = 8))]
671 level: u32,
673 #[serde(default = "default_true")]
674 restart: bool,
677 },
678 Watermark {
683 #[schemars(length(min = 1, max = watermark::MAX_TEXT))]
684 text: String,
686 #[serde(default, skip_serializing_if = "Option::is_none")]
687 color: Option<String>,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
690 diagonal: Option<bool>,
692 #[serde(default, skip_serializing_if = "Option::is_none")]
693 font: Option<String>,
695 },
696 #[schemars(extend("x-jubarte-keep" = false), extend("oneOf" = exactly_one(&["text", "choice", "checked", "date"])))]
700 FillControl {
701 control: ControlSelector,
704 #[serde(default, skip_serializing_if = "Option::is_none")]
705 text: Option<String>,
707 #[serde(default, skip_serializing_if = "Option::is_none")]
708 choice: Option<String>,
711 #[serde(default, skip_serializing_if = "Option::is_none")]
712 checked: Option<bool>,
714 #[serde(default, skip_serializing_if = "Option::is_none")]
715 date: Option<String>,
717 },
718 FormatRun {
721 paragraph: Selector,
723 find: String,
725 format: RunFormat,
727 #[serde(default, skip_serializing_if = "Option::is_none")]
728 #[schemars(range(min = 1))]
729 occurrence: Option<usize>,
731 },
732 #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]), extend("x-jubarte-keep" = false))]
735 InsertFootnote {
736 paragraph: Selector,
738 after: String,
740 text: String,
742 #[serde(default, skip_serializing_if = "Option::is_none")]
743 #[schemars(range(min = 1))]
744 occurrence: Option<usize>,
746 },
747 #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]), extend("x-jubarte-keep" = false))]
750 InsertImage {
751 paragraph: Selector,
753 #[serde(default)]
754 position: Side,
756 image_base64: String,
758 #[serde(default, skip_serializing_if = "Option::is_none")]
759 content_type: Option<String>,
761 #[serde(default, skip_serializing_if = "Option::is_none")]
762 #[schemars(range(min = 1, max = images::MAX_WIDTH_EMU))]
763 width_emu: Option<u64>,
766 #[serde(default, skip_serializing_if = "Option::is_none")]
767 alt: Option<String>,
769 },
770 #[schemars(extend("x-jubarte-keep" = false), extend("anyOf" = at_least_one(&["page", "orientation", "margins_dxa"])))]
774 PageSetup {
775 #[serde(default)]
776 section: SectionScope,
778 #[serde(default, skip_serializing_if = "Option::is_none")]
779 page: Option<PageSize>,
781 #[serde(default, skip_serializing_if = "Option::is_none")]
782 orientation: Option<Orientation>,
784 #[serde(default, skip_serializing_if = "is_default_margins")]
785 margins_dxa: Margins,
787 },
788 #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]))]
793 InsertToc {
794 paragraph: Selector,
796 #[serde(default)]
797 position: Side,
799 #[serde(default = "default_toc_levels")]
800 #[schemars(range(min = 1, max = 9))]
801 levels: u8,
803 #[serde(default, skip_serializing_if = "Option::is_none")]
804 title: Option<String>,
806 },
807 Redact {
814 paragraph: Selector,
816 find: String,
818 #[serde(default, skip_serializing_if = "Option::is_none")]
819 #[schemars(range(min = 1))]
820 occurrence: Option<usize>,
822 },
823 #[schemars(extend("anyOf" = at_least_one(&["track_revisions", "update_fields", "protection"])))]
828 Settings {
829 #[serde(default, skip_serializing_if = "Option::is_none")]
830 track_revisions: Option<bool>,
832 #[serde(default, skip_serializing_if = "Option::is_none")]
833 update_fields: Option<bool>,
836 #[serde(default, skip_serializing_if = "Option::is_none")]
837 protection: Option<crate::settings::Protection>,
839 },
840}
841
842fn default_toc_levels() -> u8 {
843 3
844}
845
846fn is_default_margins(margins: &Margins) -> bool {
847 *margins == Margins::default()
848}
849
850fn resolve_done() -> bool {
851 true
852}
853
854fn default_true() -> bool {
855 true
856}
857
858#[derive(
860 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
861)]
862#[serde(rename_all = "snake_case")]
863pub enum ListKind {
864 #[default]
865 Bullet,
867 Decimal,
869 LowerLetter,
871}
872
873impl ListKind {
874 fn format(self) -> crate::markdown::xml::ListFormat {
875 use crate::markdown::xml::ListFormat;
876 match self {
877 Self::Bullet => ListFormat::Bullet,
878 Self::Decimal => ListFormat::Decimal,
879 Self::LowerLetter => ListFormat::LowerLetter,
880 }
881 }
882
883 fn name(self) -> &'static str {
884 match self {
885 Self::Bullet => "bullet",
886 Self::Decimal => "decimal",
887 Self::LowerLetter => "lower_letter",
888 }
889 }
890}
891
892#[derive(Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
894#[schemars(transparent)]
895pub struct LineSpacing(#[schemars(with = "f64", range(min = 0.25, max = 10.0))] pub u32);
896
897impl Serialize for LineSpacing {
898 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
899 s.serialize_f64(f64::from(self.0) / 240.0)
900 }
901}
902
903impl<'de> Deserialize<'de> for LineSpacing {
904 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
905 let multiple = f64::deserialize(d)?;
906 if !(0.25..=10.0).contains(&multiple) {
907 return Err(serde::de::Error::custom(format!(
908 "line_spacing {multiple} is outside 0.25..=10"
909 )));
910 }
911 Ok(Self((multiple * 240.0).round() as u32))
912 }
913}
914
915#[derive(Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
917#[schemars(transparent)]
918pub struct Points(#[schemars(with = "f64", range(min = 0.0, max = 1584.0))] pub u32);
919
920impl Serialize for Points {
921 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
922 s.serialize_f64(f64::from(self.0) / 20.0)
923 }
924}
925
926impl<'de> Deserialize<'de> for Points {
927 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
928 let points = f64::deserialize(d)?;
929 if !(0.0..=1584.0).contains(&points) {
930 return Err(serde::de::Error::custom(format!(
931 "spacing {points}pt is outside 0..=1584"
932 )));
933 }
934 Ok(Self((points * 20.0).round() as u32))
935 }
936}
937
938#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
940#[doc(hidden)]
941pub struct Spacing {
942 line: Option<LineSpacing>,
943 before: Option<Points>,
944 after: Option<Points>,
945}
946
947#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
949#[serde(rename_all = "snake_case")]
950pub enum Alignment {
951 Left,
953 Center,
955 Right,
957 Justify,
959}
960
961impl Alignment {
962 fn jc(self) -> &'static str {
964 match self {
965 Self::Left => "left",
966 Self::Center => "center",
967 Self::Right => "right",
968 Self::Justify => "both",
969 }
970 }
971}
972
973#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
976#[serde(deny_unknown_fields)]
977pub struct RunFormat {
978 #[serde(default, skip_serializing_if = "Option::is_none")]
979 pub bold: Option<bool>,
981 #[serde(default, skip_serializing_if = "Option::is_none")]
982 pub italic: Option<bool>,
984 #[serde(default, skip_serializing_if = "Option::is_none")]
985 pub underline: Option<bool>,
987 #[serde(default, skip_serializing_if = "Option::is_none")]
988 pub highlight: Option<String>,
990 #[serde(default, skip_serializing_if = "Option::is_none")]
991 pub font: Option<String>,
993 #[serde(default, skip_serializing_if = "Option::is_none")]
994 pub size_pt: Option<HalfPoints>,
996 #[serde(default, skip_serializing_if = "Option::is_none")]
997 pub color: Option<String>,
999 #[serde(default, skip_serializing_if = "Option::is_none")]
1000 pub strike: Option<bool>,
1002 #[serde(default, skip_serializing_if = "Option::is_none")]
1003 pub caps: Option<bool>,
1005}
1006
1007#[derive(Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
1009#[schemars(transparent)]
1010pub struct HalfPoints(#[schemars(with = "f64", range(min = 0.0, max = 1638.0))] pub u32);
1011
1012impl Serialize for HalfPoints {
1013 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1014 s.serialize_f64(f64::from(self.0) / 2.0)
1015 }
1016}
1017
1018impl<'de> Deserialize<'de> for HalfPoints {
1019 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1020 let points = f64::deserialize(d)?;
1021 if !points.is_finite() || !(0.0..=1638.0).contains(&points) {
1022 return Err(serde::de::Error::custom(format!(
1023 "size_pt {points} is outside 0..=1638"
1024 )));
1025 }
1026 Ok(Self((points * 2.0).round() as u32))
1027 }
1028}
1029
1030#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1032#[serde(rename_all = "snake_case")]
1033pub enum Edge {
1034 Start,
1036 End,
1038}
1039
1040#[derive(
1042 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
1043)]
1044#[serde(rename_all = "snake_case")]
1045pub enum Side {
1046 Before,
1048 #[default]
1049 After,
1051}
1052
1053#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1068#[serde(untagged, deny_unknown_fields)]
1069pub enum Selector {
1070 Name(String),
1072 Id {
1074 id: String,
1076 },
1077 Index {
1079 index: usize,
1081 #[serde(default, skip_serializing_if = "Option::is_none")]
1082 story: Option<String>,
1084 },
1085 StartsWith {
1087 starts_with: String,
1089 #[serde(default, skip_serializing_if = "Option::is_none")]
1090 story: Option<String>,
1092 },
1093 Contains {
1095 contains: String,
1097 #[serde(default, skip_serializing_if = "Option::is_none")]
1098 story: Option<String>,
1100 },
1101}
1102
1103#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1106#[serde(deny_unknown_fields)]
1107pub struct RunSpec {
1108 pub text: String,
1110 #[serde(default, skip_serializing_if = "Option::is_none")]
1111 pub bold: Option<bool>,
1113 #[serde(default, skip_serializing_if = "Option::is_none")]
1114 pub italic: Option<bool>,
1116 #[serde(default, skip_serializing_if = "Option::is_none")]
1117 pub underline: Option<bool>,
1119 #[serde(default, skip_serializing_if = "Option::is_none")]
1120 pub highlight: Option<String>,
1122}
1123
1124impl RunSpec {
1125 pub fn format(&self) -> RunFormat {
1127 RunFormat {
1128 bold: self.bold,
1129 italic: self.italic,
1130 underline: self.underline,
1131 highlight: self.highlight.clone(),
1132 ..RunFormat::default()
1133 }
1134 }
1135}
1136
1137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1142pub struct AnchorCandidate {
1143 pub at: String,
1145 pub ctx: String,
1147}
1148
1149#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1151pub struct EditOutcome {
1152 pub id: String,
1154 pub kind: String,
1156 pub status: String,
1159 #[serde(default, skip_serializing_if = "Option::is_none")]
1160 pub paragraph: Option<String>,
1162 pub matches: usize,
1164 #[serde(default, skip_serializing_if = "Option::is_none")]
1166 pub context: Option<String>,
1167 #[serde(default, skip_serializing_if = "Option::is_none")]
1168 pub comment_id: Option<u32>,
1170 #[serde(default, skip_serializing_if = "Option::is_none")]
1171 pub anchor_given: Option<String>,
1176 #[serde(default, skip_serializing_if = "Option::is_none")]
1177 pub anchor_read_as: Option<String>,
1179 #[serde(default, skip_serializing_if = "Option::is_none")]
1181 pub near: Option<NearMatches>,
1182 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1185 pub candidates: Vec<AnchorCandidate>,
1186 #[serde(default, skip_serializing_if = "Option::is_none")]
1187 pub code: Option<String>,
1189 #[serde(default, skip_serializing_if = "Option::is_none")]
1190 pub message: Option<String>,
1193}
1194
1195#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1197pub struct RevisionCounts {
1198 pub inserted: usize,
1200 pub deleted: usize,
1202 pub moved: usize,
1204 pub format_changed: usize,
1207 #[serde(default)]
1210 pub replaced: usize,
1211 pub total: usize,
1214}
1215
1216impl RevisionCounts {
1217 fn from_changes<'a>(changes: impl IntoIterator<Item = &'a Change>) -> Self {
1219 let mut counts = Self::default();
1220 for change in changes {
1221 let slot = match change.kind {
1222 ChangeKind::Insertion => &mut counts.inserted,
1223 ChangeKind::Deletion => &mut counts.deleted,
1224 ChangeKind::Move => &mut counts.moved,
1225 ChangeKind::Formatting => &mut counts.format_changed,
1226 ChangeKind::Replacement => &mut counts.replaced,
1227 };
1228 *slot += 1;
1229 counts.total += 1;
1230 }
1231 counts
1232 }
1233}
1234
1235#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1237pub struct ParagraphDelta {
1238 pub from: usize,
1240 pub to: usize,
1242}
1243
1244#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1246pub struct EditReport {
1247 pub schema_version: u32,
1249 pub ok: bool,
1251 pub source_sha256: String,
1253 pub base_sha256: String,
1257 pub guarded: bool,
1259 pub author: String,
1261 pub date: String,
1263 pub existing_revisions: ExistingRevisions,
1265 #[serde(default, skip_serializing_if = "ResolvedRevisions::is_empty")]
1267 pub resolved_revisions: ResolvedRevisions,
1268 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1270 pub removed_comments: Vec<RemovedComment>,
1271 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1275 pub clean_removed_comments: Vec<RemovedComment>,
1276 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1279 pub kept_comments: Vec<KeptComment>,
1280 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1285 pub paragraph_ids: Vec<ParagraphMove>,
1286 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1288 pub split_revisions: Vec<RevisionSplit>,
1289 pub paragraphs: ParagraphDelta,
1291 pub operations: Vec<EditOutcome>,
1293 pub comments_added: usize,
1295 pub revisions: RevisionCounts,
1297 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1299 #[cfg(feature = "render")]
1300 pub fields: Vec<crate::fields::FieldUpdate>,
1301 #[serde(default, skip_serializing_if = "is_zero")]
1304 pub skipped: usize,
1305 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1308 pub notes: Vec<String>,
1309 #[serde(default, skip_serializing_if = "Option::is_none")]
1312 pub output_sha256: Option<String>,
1313}
1314
1315fn is_zero(n: &usize) -> bool {
1316 *n == 0
1317}
1318
1319impl EditReport {
1320 pub fn to_jsonl(&self) -> String {
1323 let mut out = String::new();
1324 let mut push = |v: serde_json::Value| {
1325 out.push_str(&v.to_string());
1326 out.push('\n');
1327 };
1328 let mut load = serde_json::json!({
1329 "ev": "load",
1330 "sha256": self.source_sha256,
1331 "base_sha256": self.base_sha256,
1332 "guarded": self.guarded,
1333 "paras": self.paragraphs.from,
1334 "author": self.author,
1335 "date": self.date,
1336 "existing_revisions": self.existing_revisions,
1337 });
1338 if !self.resolved_revisions.is_empty() {
1339 load.as_object_mut().expect("object").insert(
1340 "resolved_revisions".into(),
1341 serde_json::to_value(&self.resolved_revisions).expect("serializes"),
1342 );
1343 }
1344 if !self.paragraph_ids.is_empty() {
1345 load.as_object_mut().expect("object").insert(
1346 "paragraph_ids".into(),
1347 serde_json::to_value(&self.paragraph_ids).expect("serializes"),
1348 );
1349 }
1350 push(load);
1351 for (i, op) in self.operations.iter().enumerate() {
1352 let mut v = serde_json::json!({
1353 "ev": "op",
1354 "i": i + 1,
1355 "id": op.id,
1356 "op": op.kind,
1357 "status": op.status,
1358 "matches": op.matches,
1359 });
1360 let map = v.as_object_mut().expect("object");
1361 if let Some(p) = &op.paragraph {
1362 map.insert("at".into(), p.clone().into());
1363 }
1364 if let Some(c) = &op.context {
1365 map.insert("ctx".into(), c.clone().into());
1366 }
1367 if let Some(c) = op.comment_id {
1368 map.insert("comment_id".into(), c.into());
1369 }
1370 if let Some(given) = &op.anchor_given {
1371 map.insert("anchor_given".into(), given.clone().into());
1372 }
1373 if let Some(read_as) = &op.anchor_read_as {
1374 map.insert("anchor_read_as".into(), read_as.clone().into());
1375 }
1376 if let Some(near) = &op.near {
1377 map.insert(
1378 "near".into(),
1379 serde_json::to_value(near).expect("near serializes"),
1380 );
1381 }
1382 if !op.candidates.is_empty() {
1383 map.insert(
1384 "candidates".into(),
1385 serde_json::to_value(&op.candidates).expect("candidates serialize"),
1386 );
1387 }
1388 if let Some(c) = &op.code {
1389 map.insert("code".into(), c.clone().into());
1390 }
1391 if let Some(m) = &op.message {
1392 map.insert("message".into(), m.clone().into());
1393 }
1394 push(v);
1395 }
1396 let failed = self
1397 .operations
1398 .iter()
1399 .filter(|o| o.status == "failed")
1400 .count();
1401 let ok = self.operations.iter().filter(|o| o.status == "ok").count();
1402 let status = match (self.ok, self.skipped) {
1404 (true, _) => "ok",
1405 (false, 0) => "failed",
1406 (false, _) if ok > 0 => "partial",
1407 (false, _) => "failed",
1408 };
1409 let mut ops = serde_json::json!({"ok": ok, "failed": failed});
1410 if self.skipped > 0 {
1411 ops["skipped"] = self.skipped.into();
1412 }
1413 let mut summary = serde_json::json!({
1414 "ev": "summary",
1415 "status": status,
1416 "ops": ops,
1417 "paras": {"from": self.paragraphs.from, "to": self.paragraphs.to,
1418 "d": self.paragraphs.to as i64 - self.paragraphs.from as i64},
1419 "revs": self.revisions,
1420 "comments": {"added": self.comments_added},
1421 "removed_comments": self.removed_comments,
1422 "kept_comments": self.kept_comments,
1423 });
1424 if !self.split_revisions.is_empty() {
1425 summary.as_object_mut().expect("object").insert(
1426 "split_revisions".into(),
1427 serde_json::to_value(&self.split_revisions).expect("serializes"),
1428 );
1429 }
1430 if let Some(digest) = &self.output_sha256 {
1431 summary["output_sha256"] = digest.clone().into();
1432 }
1433 if !self.notes.is_empty() {
1434 summary["notes"] = self.notes.clone().into();
1435 }
1436 if !self.clean_removed_comments.is_empty() {
1437 summary["clean_removed_comments"] =
1438 serde_json::to_value(&self.clean_removed_comments).expect("serializes");
1439 }
1440 push(summary);
1441 out
1442 }
1443}
1444
1445#[derive(Clone, Debug, PartialEq, Eq)]
1447pub struct EditResult {
1448 pub clean: Vec<u8>,
1450 pub redline: Vec<u8>,
1452 pub report: EditReport,
1454}
1455
1456#[cfg(test)]
1457thread_local! {
1458 static COMMENT_MARK_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1459}
1460
1461const COMMENT_ANCHOR_CONFLICT: &str = "COMMENT_ANCHOR_CONFLICT";
1463
1464#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1467pub struct EditError {
1468 pub code: String,
1470 #[serde(default, skip_serializing_if = "Option::is_none")]
1471 pub operation: Option<String>,
1473 pub message: String,
1475 #[serde(default)]
1476 pub outcomes: Vec<EditOutcome>,
1478 #[serde(default, skip_serializing_if = "Option::is_none")]
1480 pub near: Option<Box<NearMatches>>,
1481 #[serde(
1483 default,
1484 skip_serializing_if = "<[refusal::RevisionRefusal]>::is_empty"
1485 )]
1486 pub revision_refusals: Box<[refusal::RevisionRefusal]>,
1487}
1488
1489impl fmt::Display for EditError {
1490 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1491 match &self.operation {
1492 Some(op) => write!(f, "{} ({op}): {}", self.code, self.message),
1493 None => write!(f, "{}: {}", self.code, self.message),
1494 }
1495 }
1496}
1497
1498impl std::error::Error for EditError {}
1499
1500const STYLES_STORY: &str = "styles.";
1503
1504const KEEP_REVISIONS: &str = concat!(
1507 r#"add "existing_revisions": "keep" to the plan "#,
1508 "(it keeps every tracked change, yours and theirs; accept and reject resolve them all first)"
1509);
1510
1511fn revisions_left(source: &[u8], plan: &EditPlan) -> bool {
1517 let resolved = resolve_selected(
1518 source,
1519 plan.resolve_revisions.as_ref(),
1520 plan.removed_anchor_comments,
1521 PlanSyntax::V1,
1522 )
1523 .ok()
1524 .and_then(|(bytes, _, _)| bytes);
1525 crate::changes::list_changes(resolved.as_deref().unwrap_or(source))
1526 .is_ok_and(|changes| changes.iter().any(|c| !c.id.starts_with(STYLES_STORY)))
1527}
1528
1529pub fn replies_on_deleted_paragraphs(source: &[u8], plan: &EditPlan) -> Vec<(u32, Option<String>)> {
1535 let Ok(lowered) = visible::lower(source, plan, PlanSyntax::V1) else {
1536 return Vec::new();
1537 };
1538 let plan = lowered.as_ref().unwrap_or(plan);
1539 let Ok(tx) = resolved(source, plan, PlanSyntax::V1) else {
1540 return Vec::new();
1541 };
1542 (0..plan.operations.len())
1543 .filter_map(|op| tx.reply_on_deleted(op))
1544 .map(|(parent, by)| (parent, tx.outcomes[by].paragraph.clone()))
1545 .collect()
1546}
1547
1548fn guard_keep_others(
1561 source: &[u8],
1562 author: &str,
1563 selection: Option<&ResolveRevisions>,
1564 wholesale: Option<&str>,
1565 settle_comment_bodies: bool,
1566 syntax: PlanSyntax,
1567) -> Result<(), EditError> {
1568 if selection.is_none() && wholesale.is_none() {
1569 return Ok(());
1570 }
1571 let listed =
1572 crate::changes::list_changes(source).map_err(|e| selection_error(e, syntax, ""))?;
1573 if let Some(selection) = selection {
1574 let accept = selected_ids(&listed, selection.accept.as_ref(), syntax)?;
1575 let reject = if selection.reject_visible {
1576 Vec::new()
1577 } else {
1578 selected_ids(&listed, selection.reject.as_ref(), syntax)?
1579 };
1580 let mut removals = Vec::new();
1581 for (id, accepting) in accept
1582 .iter()
1583 .map(|id| (id, true))
1584 .chain(reject.iter().map(|id| (id, false)))
1585 {
1586 let Some(change) = listed.iter().find(|c| &c.id == id) else {
1587 continue;
1588 };
1589 if change.id.starts_with(STYLES_STORY) {
1590 continue;
1591 }
1592 if !owns_change(change.author.as_deref(), author) {
1593 return Err(err("CHANGE_NOT_YOURS", None, change_not_yours(change)));
1594 }
1595 if !removes_content(change, accepting) {
1596 continue;
1597 }
1598 let nested = taken_along(&listed, change);
1599 if let Some(foreign) = nested
1600 .iter()
1601 .find(|inner| !owns_change(inner.author.as_deref(), author))
1602 {
1603 return Err(err("CHANGE_NOT_YOURS", None, change_not_yours(foreign)));
1604 }
1605 removals.push((change, accepting, nested));
1606 }
1607 guard_removed_comments(source, author, &removals)?;
1608 }
1609 let Some(policy) = wholesale else {
1610 return Ok(());
1611 };
1612 let comment_changes =
1616 if settle_comment_bodies || listed.iter().any(|c| !c.id.starts_with(STYLES_STORY)) {
1617 let opened = Opened::open(source).map_err(open_error)?;
1618 crate::changes::comment_changes_in(&opened.pkg)
1619 } else {
1620 Vec::new()
1621 };
1622 let mut authors = Vec::new();
1623 let mut nameless = false;
1624 for change in listed.iter().chain(&comment_changes) {
1625 note_foreign(change, author, &mut authors, &mut nameless);
1626 }
1627 if authors.is_empty() && !nameless {
1628 return Ok(());
1629 }
1630 Err(err(
1631 "CHANGE_NOT_YOURS",
1632 None,
1633 format!(
1634 r#""existing_revisions": "{policy}" would erase changes by {}; {KEEP_REVISIONS}"#,
1635 join_authors(&authors, nameless)
1636 ),
1637 ))
1638}
1639
1640pub fn paragraph_ids(docx: &[u8], ids: &[&str]) -> Result<Vec<Result<String, String>>, EditError> {
1649 let mut opened = Opened::open(docx).map_err(open_error)?;
1650 let Loaded {
1651 stories,
1652 paragraph_nodes,
1653 paragraph_story,
1654 } = load_stories(&mut opened)?;
1655 let resolver = origin::Ids {
1656 dom: &opened.dom,
1657 body: opened.body,
1658 story_ids: stories.iter().map(|s| s.id.as_str()).collect(),
1659 paragraph_nodes: ¶graph_nodes,
1660 paragraph_story: ¶graph_story,
1661 };
1662 Ok(ids
1663 .iter()
1664 .map(|id| match resolver.paragraph_id(id) {
1665 Some(found) => found,
1666 None => match id.rsplit_once(":p:") {
1667 Some((story, n)) if n.parse::<usize>().is_ok() => {
1668 if resolver.story_ids.contains(&story) {
1669 Ok(id.to_string())
1670 } else {
1671 Err(format!(
1672 "unknown story {story:?}; this document has {}",
1673 resolver.story_ids.join(", ")
1674 ))
1675 }
1676 }
1677 Some(_) => Err(format!("unknown paragraph id {id}")),
1678 None => Err(format!("{id} is not a paragraph id")),
1679 },
1680 })
1681 .collect())
1682}
1683
1684impl From<crate::comment_settlement::SettlementError> for EditError {
1685 fn from(error: crate::comment_settlement::SettlementError) -> Self {
1686 err(&error.code, None, error.message)
1687 }
1688}
1689
1690fn err(code: &str, operation: Option<&str>, message: impl Into<String>) -> EditError {
1691 EditError {
1692 code: code.to_string(),
1693 operation: operation.map(str::to_string),
1694 message: message.into(),
1695 outcomes: Vec::new(),
1696 near: None,
1697 revision_refusals: Box::default(),
1698 }
1699}
1700
1701pub(crate) fn operation_schemas() -> &'static [serde_json::Value] {
1705 static SCHEMAS: std::sync::LazyLock<Vec<serde_json::Value>> = std::sync::LazyLock::new(|| {
1706 let settings = schemars::generate::SchemaSettings::draft2020_12()
1707 .with(|s| s.inline_subschemas = true)
1708 .for_deserialize();
1709 let common = settings
1710 .clone()
1711 .into_generator()
1712 .into_root_schema_for::<Operation>();
1713 let common = serde_json::to_value(common).expect("common schema serializes");
1714 let schema = settings
1715 .into_generator()
1716 .into_root_schema_for::<OperationKind>();
1717 let value = serde_json::to_value(schema).expect("operation schema serializes");
1718 let mut variants = value["oneOf"]
1719 .as_array()
1720 .expect("tagged operation variants")
1721 .clone();
1722 for variant in &mut variants {
1723 variant["properties"]["id"] = common["properties"]["id"].clone();
1724 variant["properties"]["group"] = common["properties"]["group"].clone();
1725 variant["properties"]["why"] = serde_json::json!({
1727 "type": "string",
1728 "description": "Why `--skip-failed` left this operation out; ignored."
1729 });
1730 variant["additionalProperties"] = serde_json::json!(false);
1734 }
1735 variants
1736 });
1737 &SCHEMAS
1738}
1739
1740pub fn dispatched_operation_kinds() -> Vec<String> {
1742 operation_schemas()
1743 .iter()
1744 .map(|schema| {
1745 schema["properties"]["kind"]["const"]
1746 .as_str()
1747 .expect("operation tag")
1748 .to_string()
1749 })
1750 .collect()
1751}
1752
1753pub(crate) fn operation_needs_keep(kind: &str) -> bool {
1756 operation_schemas()
1757 .iter()
1758 .find(|s| s["properties"]["kind"]["const"] == kind)
1759 .is_some_and(|s| s["x-jubarte-keep-only"] == true)
1760}
1761
1762pub(crate) fn operation_supports_keep(kind: &str) -> bool {
1763 operation_schemas()
1764 .iter()
1765 .find(|s| s["properties"]["kind"]["const"] == kind)
1766 .is_some_and(|s| s["x-jubarte-keep"] != false)
1767}
1768
1769pub fn apply_plan_json(source: &[u8], plan_json: &str) -> Result<EditResult, EditError> {
1777 apply_plan_json_with(source, plan_json, &PrepareOptions::default())
1778}
1779
1780pub fn apply_plan_json_with(
1790 source: &[u8],
1791 plan_json: &str,
1792 options: &PrepareOptions,
1793) -> Result<EditResult, EditError> {
1794 let (plan, mut notes) = EditPlan::from_json_with_notes(plan_json)?;
1795 let mut result = prepared::prepare(source, &plan, options)?.result;
1796 notes.append(&mut result.report.notes);
1797 result.report.notes = notes;
1798 Ok(result)
1799}
1800
1801pub fn apply_plan(source: &[u8], plan: &EditPlan) -> Result<EditResult, EditError> {
1828 prepared::prepare(source, plan, &PrepareOptions::default()).map(|p| p.result)
1829}
1830
1831fn check_update_fields(plan: &EditPlan) -> Result<(), EditError> {
1835 if plan.update_fields && plan.existing_revisions == ExistingRevisions::Keep {
1836 return Err(err(
1837 "INVALID_PLAN",
1838 None,
1839 "update_fields cannot be combined with existing_revisions \"keep\"; refresh the fields with `jubarte convert FILE --update-fields -o OUT.docx` after accepting or rejecting the kept changes",
1840 ));
1841 }
1842 Ok(())
1843}
1844
1845pub fn check_plan(source: &[u8], plan: &EditPlan) -> Result<(), EditError> {
1849 check_plan_quoting(source, plan, PlanSyntax::V1)
1850}
1851
1852pub fn check_plan_quoting(
1855 source: &[u8],
1856 plan: &EditPlan,
1857 syntax: PlanSyntax,
1858) -> Result<(), EditError> {
1859 let lowered = visible::lower(source, plan, syntax)?;
1860 resolved(source, lowered.as_ref().unwrap_or(plan), syntax).map(|_| ())
1861}
1862
1863fn resolved<'a>(
1864 source: &'a [u8],
1865 plan: &'a EditPlan,
1866 syntax: PlanSyntax,
1867) -> Result<Transaction<'a>, EditError> {
1868 check_update_fields(plan)?;
1869 let mut tx = Transaction::start_quoting(source, plan, syntax)?;
1870 tx.resolve()?;
1871 tracked::check(&tx)?;
1872 tx.emits_directly()?;
1873 Ok(tx)
1874}
1875
1876pub fn preview_plan(source: &[u8], plan: &EditPlan) -> Result<EditReport, EditError> {
1878 preview_plan_with(source, plan, &PrepareOptions::default())
1879}
1880
1881pub fn preview_plan_with(
1885 source: &[u8],
1886 plan: &EditPlan,
1887 options: &PrepareOptions,
1888) -> Result<EditReport, EditError> {
1889 let report = prepared::prepare(source, plan, options)?.result.report;
1895 #[cfg(feature = "render")]
1896 let report = EditReport {
1897 fields: Vec::new(),
1898 ..report
1899 };
1900 Ok(report)
1901}
1902
1903fn revision_counts(redline: &[u8]) -> RevisionCounts {
1905 RevisionCounts::from_changes(&crate::changes::list_logical_changes(redline).unwrap_or_default())
1906}
1907
1908#[derive(Clone, Debug)]
1910struct ScheduledEdit {
1911 start: usize,
1912 end: usize,
1913 op: usize,
1915 replacement: String,
1916 attach_before: bool,
1917 comment: Option<String>,
1918 format: Option<RunFormat>,
1919}
1920
1921#[derive(Clone, Debug)]
1923#[doc(hidden)]
1924pub enum Resolved {
1925 Text {
1926 para: usize,
1927 start: usize,
1928 end: usize,
1929 replacement: String,
1931 comment: Option<String>,
1933 attach_before: bool,
1935 format: Option<RunFormat>,
1937 },
1938 CommentRange {
1939 para: usize,
1940 start: usize,
1941 end: usize,
1942 text: String,
1944 },
1945 DeleteParagraph {
1946 para: usize,
1947 },
1948 FormatParagraph {
1949 para: usize,
1950 style: Option<String>,
1952 alignment: Option<Alignment>,
1953 spacing: Spacing,
1954 },
1955 MergeParagraphs {
1956 para: usize,
1957 next: usize,
1958 separator: String,
1959 strike: bool,
1962 },
1963 InsertParagraph {
1964 anchor: usize,
1965 side: Side,
1966 runs: Vec<RunSpec>,
1968 like: usize,
1970 style: Option<String>,
1972 comment: Option<String>,
1974 toc: Option<TocSpec>,
1977 keep_mark: bool,
1980 },
1981 InsertTable {
1982 anchor: usize,
1983 side: Side,
1984 rows: Vec<Vec<String>>,
1985 header_row: bool,
1986 widths: Vec<u32>,
1988 style: String,
1990 add_style: bool,
1992 },
1993 List {
1994 paras: Vec<usize>,
1996 kind: ListKind,
1997 level: u32,
1998 join: Option<String>,
2000 style: String,
2002 add_style: bool,
2004 },
2005 CommentSpan {
2007 para: usize,
2008 last: usize,
2009 text: String,
2011 },
2012 Thread {
2014 op: ThreadOp,
2015 stories: Vec<usize>,
2017 anchor: Option<usize>,
2019 },
2020 FillControl {
2021 control: usize,
2023 paragraphs: Vec<usize>,
2025 block: bool,
2027 value: controls::FillValue,
2028 },
2029 FormatRun {
2030 para: usize,
2031 start: usize,
2032 end: usize,
2033 format: RunFormat,
2034 },
2035 InsertFootnote {
2036 para: usize,
2037 at: usize,
2039 text: String,
2040 },
2041 InsertImage {
2042 anchor: usize,
2043 side: Side,
2044 picture: crate::markdown::Picture,
2045 },
2046 PageSetup {
2047 targets: sections::Targets,
2048 },
2049 StrikeComment {
2053 para: usize,
2054 start: usize,
2055 end: usize,
2056 },
2057 Restore {
2060 para: usize,
2061 wid: String,
2063 at: usize,
2064 text: String,
2066 comment: Option<String>,
2068 },
2069}
2070
2071#[derive(Clone, Debug)]
2073#[doc(hidden)]
2074pub enum ThreadOp {
2075 Reply { parent: u32, text: String },
2076 Resolve { id: u32, done: bool },
2077 Edit { id: u32, text: String },
2078 Delete { id: u32 },
2079}
2080
2081impl ThreadOp {
2082 fn target(&self) -> u32 {
2084 match self {
2085 ThreadOp::Reply { parent: id, .. }
2086 | ThreadOp::Resolve { id, .. }
2087 | ThreadOp::Edit { id, .. }
2088 | ThreadOp::Delete { id } => *id,
2089 }
2090 }
2091}
2092
2093#[derive(Clone, Debug)]
2097#[doc(hidden)]
2098pub struct OthersComment {
2099 comment: u32,
2101 author: String,
2103 change: OthersChange,
2104}
2105
2106#[derive(Clone, Copy, Debug)]
2107enum OthersChange {
2108 Reword,
2109 Delete,
2110 Resolve,
2111 Reopen,
2112 DeletedWith(u32),
2114}
2115
2116impl OthersComment {
2117 fn refusal(&self, reply: &str, resolve: &str) -> String {
2121 let (comment, author) = (self.comment, &self.author);
2122 if let OthersChange::DeletedWith(root) = self.change {
2123 let whose = if author.is_empty() {
2124 "a reply that names no author".to_string()
2125 } else {
2126 format!("a reply by {author:?}")
2127 };
2128 return format!(
2129 "deleting c{root} deletes c{comment}, {whose}; resolve c{root} instead ({resolve})"
2130 );
2131 }
2132 format!("{}; reply instead ({reply})", self.whose())
2133 }
2134
2135 fn note(&self) -> String {
2137 let named = !self.author.is_empty();
2138 let what = match (self.change, named) {
2139 (OthersChange::Reword, true) => "their words were changed under their name".into(),
2140 (OthersChange::Reword, false) => "its words were changed".into(),
2141 (OthersChange::Delete, true) => "their comment was deleted".into(),
2142 (OthersChange::Resolve, true) => "their comment was resolved".into(),
2143 (OthersChange::Reopen, true) => "their comment was reopened".into(),
2144 (OthersChange::Delete, false) => "it was deleted".into(),
2145 (OthersChange::Resolve, false) => "it was resolved".into(),
2146 (OthersChange::Reopen, false) => "it was reopened".into(),
2147 (OthersChange::DeletedWith(root), true) => {
2148 format!("their reply was deleted with c{root}")
2149 }
2150 (OthersChange::DeletedWith(root), false) => format!("it was deleted with c{root}"),
2151 };
2152 format!("{}; {what}", self.whose())
2153 }
2154
2155 fn whose(&self) -> String {
2157 if self.author.is_empty() {
2158 format!("c{} names no author", self.comment)
2159 } else {
2160 format!("c{} is by {:?}", self.comment, self.author)
2161 }
2162 }
2163}
2164
2165#[derive(Clone, Debug)]
2167#[doc(hidden)]
2168pub struct TocSpec {
2169 levels: u8,
2170 title: Option<String>,
2171}
2172
2173type Resolution<T> = Result<(T, EditOutcome), Box<(EditError, EditOutcome)>>;
2176
2177#[derive(Clone, Copy, Debug)]
2180struct Covered {
2181 first: usize,
2182 start: usize,
2183 last: usize,
2184 end: usize,
2185}
2186
2187#[doc(hidden)]
2188pub struct Transaction<'p> {
2189 pub plan: &'p EditPlan,
2190 pub revision_refusal: std::cell::RefCell<Option<refusal::RevisionRefusal>>,
2191 pub source_sha256: String,
2192 pub base: Vec<u8>,
2193 pub base_sha256: String,
2194 pub resolved_revisions: ResolvedRevisions,
2195 pub removed_comments: Vec<RemovedComment>,
2196 pub kept_comments: Vec<KeptComment>,
2197 pub date: String,
2199 pub initials: String,
2200 pub opened: Opened,
2201 pub stories: Vec<StoryPart>,
2203 pub paragraph_nodes: Vec<NodeId>,
2205 pub paragraph_story: Vec<(usize, usize)>,
2207 pub projections: Vec<Projection>,
2208 pub anchor_candidate_cache: std::cell::RefCell<HashMap<String, (Vec<AnchorCandidate>, usize)>>,
2212 pub origin: Option<origin::Origin>,
2215 pub outcomes: Vec<EditOutcome>,
2216 pub resolved: Vec<(usize, Resolved)>,
2217 pub claims: BTreeMap<usize, (usize, usize, usize)>,
2221 pub anchor_window: std::cell::Cell<Option<(u32, usize, usize)>>,
2225 pub syntax: PlanSyntax,
2227 pub comments: Vec<(u32, String)>,
2228 pub deletion_comments: Vec<(u32, usize)>,
2230 pub preset_comment_ids: Vec<u32>,
2232 pub next_comment_id: u64,
2234 pub comments_added: usize,
2235 pub whole_marks: Vec<whole::Mark>,
2237 pub new_numbering: (Vec<String>, Vec<String>),
2239 pub needed_styles: std::collections::BTreeSet<String>,
2241 pub family: Option<crate::comments::CommentFamily>,
2243 pub reply_parents: BTreeMap<u32, u32>,
2245 pub rewritten: Vec<(usize, OthersComment)>,
2249 pub watermark: Option<watermark::Spec>,
2251 pub controls: Vec<NodeId>,
2253 pub control_records: Vec<crate::inspect::ContentControl>,
2255 pub notes_story: Option<usize>,
2257 pub settings: Option<crate::settings::SettingsRequest>,
2259 pub written_stories: std::collections::BTreeSet<usize>,
2262 pub revision_ids: RevisionCounter,
2266 pub used_revision_ids: HashSet<u64>,
2269}
2270
2271#[doc(hidden)]
2273pub struct StoryPart {
2274 id: String,
2276 part: String,
2278 document: NodeId,
2279 root: NodeId,
2280}
2281
2282pub(crate) fn kind_name(kind: &OperationKind) -> &'static str {
2283 match kind {
2284 OperationKind::Replace { .. } => "replace",
2285 OperationKind::Insert { .. } => "insert",
2286 OperationKind::Delete { .. } => "delete",
2287 OperationKind::Comment { .. } => "comment",
2288 OperationKind::InsertParagraph { .. } => "insert_paragraph",
2289 OperationKind::DeleteParagraph { .. } => "delete_paragraph",
2290 OperationKind::FormatParagraph { .. } => "format_paragraph",
2291 OperationKind::MergeParagraphs { .. } => "merge_paragraphs",
2292 OperationKind::Rewrite { .. } => "rewrite",
2293 OperationKind::ReplyComment { .. } => "reply_comment",
2294 OperationKind::ResolveComment { .. } => "resolve_comment",
2295 OperationKind::EditComment { .. } => "edit_comment",
2296 OperationKind::DeleteComment { .. } => "delete_comment",
2297 OperationKind::InsertTable { .. } => "insert_table",
2298 OperationKind::List { .. } => "list",
2299 OperationKind::Watermark { .. } => "watermark",
2300 OperationKind::FillControl { .. } => "fill_control",
2301 OperationKind::FormatRun { .. } => "format_run",
2302 OperationKind::InsertFootnote { .. } => "insert_footnote",
2303 OperationKind::InsertImage { .. } => "insert_image",
2304 OperationKind::PageSetup { .. } => "page_setup",
2305 OperationKind::InsertToc { .. } => "insert_toc",
2306 OperationKind::Redact { .. } => "redact",
2307 OperationKind::Settings { .. } => "settings",
2308 OperationKind::Strike { .. } => "strike",
2309 OperationKind::Restore { .. } => "restore",
2310 }
2311}
2312
2313#[doc(hidden)]
2318pub struct RevisionCounter {
2319 ids: crate::revision_processor::RevisionIds,
2320 copied_from: HashMap<u64, u64>,
2322 own: BTreeSet<u64>,
2325}
2326
2327impl Default for RevisionCounter {
2328 fn default() -> Self {
2329 Self::new(HashSet::new())
2330 }
2331}
2332
2333impl RevisionCounter {
2334 pub(super) fn new(used: HashSet<u64>) -> Self {
2336 Self {
2337 ids: crate::revision_processor::RevisionIds::from_used(used),
2338 copied_from: HashMap::new(),
2339 own: BTreeSet::new(),
2340 }
2341 }
2342
2343 pub(super) fn allocate(&mut self) -> u64 {
2345 let id = self.ids.allocate();
2346 self.own.insert(id);
2347 id
2348 }
2349
2350 fn copy(&mut self, of: Option<u64>) -> u64 {
2354 let id = if of.is_some_and(|id| self.own.contains(&id)) {
2355 self.allocate()
2356 } else {
2357 self.ids.allocate()
2358 };
2359 if let Some(of) = of {
2360 self.copied_from.insert(id, of);
2361 }
2362 id
2363 }
2364
2365 fn original(&self, mut id: u64) -> u64 {
2369 while let Some(&of) = self.copied_from.get(&id) {
2370 id = of;
2371 }
2372 id
2373 }
2374
2375 pub(super) fn own(&self) -> &BTreeSet<u64> {
2378 &self.own
2379 }
2380}
2381
2382#[cfg(test)]
2383#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2384#[path = "tests/tests.rs"]
2385mod tests;
2386#[cfg(test)]
2387thread_local! {
2388 static CANDIDATE_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2389}
2390
2391#[cfg(test)]
2393#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2394#[path = "../../../../tests/common/docx.rs"]
2395mod deeper_boundary_fixture;
2396
2397#[cfg(test)]
2398#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2399#[path = "tests/deeper_boundary_tests.rs"]
2400mod deeper_boundary_tests;
2401
2402#[cfg(test)]
2403#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2404mod jsonl_branch_tests {
2405 use super::deeper_boundary_fixture::{docx, para};
2406 use super::*;
2407
2408 fn lines(report: &EditReport) -> Vec<serde_json::Value> {
2409 report
2410 .to_jsonl()
2411 .lines()
2412 .map(|l| serde_json::from_str(l).unwrap())
2413 .collect()
2414 }
2415
2416 #[test]
2417 fn a_skipped_run_with_landed_operations_reports_partial() {
2418 let plan = EditPlan::from_json(
2419 &serde_json::json!({
2420 "schema_version": 1,
2421 "author": "Ed",
2422 "date": "2026-02-02T00:00:00Z",
2423 "operations": [
2424 {"kind": "replace", "paragraph": "p0", "find": "one", "replacement": "1"},
2425 {"kind": "replace", "paragraph": "p0", "find": "two", "replacement": "2"},
2426 ],
2427 })
2428 .to_string(),
2429 )
2430 .unwrap();
2431 let mut report = apply_plan(&docx(¶("one two")), &plan).unwrap().report;
2432 report.ok = false;
2433 report.skipped = 1;
2434 report.operations[1].status = "failed".into();
2435 report.operations[1].near = Some(anchor::NearMatches {
2436 total: 0,
2437 occurrences: Vec::new(),
2438 });
2439 report.clean_removed_comments.push(RemovedComment {
2440 id: "c3".into(),
2441 author: "Bo".into(),
2442 replies: Vec::new(),
2443 why: "anchor removed".into(),
2444 decision: None,
2445 });
2446 let out = lines(&report);
2447 let summary = out.last().unwrap();
2448 assert_eq!(summary["status"], "partial");
2449 assert_eq!(summary["ops"]["skipped"], 1);
2450 assert_eq!(summary["clean_removed_comments"][0]["id"], "c3");
2451 assert!(out.iter().any(|l| l.get("near").is_some()), "{out:?}");
2452 report.operations[0].status = "failed".into();
2454 assert_eq!(lines(&report).last().unwrap()["status"], "failed");
2455 }
2456}
2457
2458#[cfg(test)]
2459#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2460mod keep_others_branch_tests {
2461 use super::deeper_boundary_fixture::{docx, para};
2462 use super::*;
2463
2464 fn selection(json: serde_json::Value) -> ResolveRevisions {
2465 serde_json::from_value(json).unwrap()
2466 }
2467
2468 #[test]
2469 fn a_wholesale_policy_names_nameless_changes_and_passes_clean_sources() {
2470 let plain = docx(¶("Plain."));
2471 assert!(
2472 guard_keep_others(&plain, "Ed", None, Some("accept"), false, PlanSyntax::V1).is_ok()
2473 );
2474 let nameless = docx(
2475 r#"<w:p><w:r><w:t xml:space="preserve">Kept </w:t></w:r><w:ins w:id="1" w:date="2026-01-01T00:00:00Z"><w:r><w:t>added</w:t></w:r></w:ins></w:p>"#,
2476 );
2477 let e = guard_keep_others(&nameless, "Ed", None, Some("accept"), false, PlanSyntax::V1)
2478 .unwrap_err();
2479 assert_eq!(e.code, "CHANGE_NOT_YOURS");
2480 assert!(
2481 e.message
2482 .contains(r#""existing_revisions": "accept" would erase"#),
2483 "{}",
2484 e.message
2485 );
2486 }
2487
2488 #[test]
2489 fn a_visible_reject_leaves_the_reject_ids_to_the_strike() {
2490 let source = docx(
2491 r#"<w:p><w:r><w:t xml:space="preserve">Kept </w:t></w:r><w:ins w:id="1" w:author="Bo" w:date="2026-01-01T00:00:00Z"><w:r><w:t>added</w:t></w:r></w:ins></w:p>"#,
2492 );
2493 let visible = selection(serde_json::json!({"reject": {"ids": ["r1"], "visible": true}}));
2494 assert!(visible.reject_visible);
2495 assert!(
2496 guard_keep_others(&source, "Ed", Some(&visible), None, false, PlanSyntax::V1).is_ok()
2497 );
2498 let silent = selection(serde_json::json!({"reject": {"ids": ["r1"]}}));
2499 let e = guard_keep_others(&source, "Ed", Some(&silent), None, false, PlanSyntax::V1)
2500 .unwrap_err();
2501 assert_eq!(e.code, "CHANGE_NOT_YOURS");
2502 }
2503
2504 #[test]
2505 fn colon_ids_need_a_known_story_and_a_number() {
2506 let source = docx(¶("Plain."));
2507 let got = paragraph_ids(&source, &["body:p:0", "body:p:x", "nowhere:p:1"]).unwrap();
2508 assert!(
2509 got[0]
2510 .as_ref()
2511 .unwrap_err()
2512 .ends_with("the settled spelling is p0"),
2513 "{got:?}"
2514 );
2515 assert!(
2516 got[1]
2517 .as_ref()
2518 .unwrap_err()
2519 .starts_with("body:p:x: -p takes"),
2520 "{got:?}"
2521 );
2522 assert!(
2523 got[2].as_ref().unwrap_err().starts_with("unknown story"),
2524 "{got:?}"
2525 );
2526 }
2527}