Skip to main content

jubarte_cli/
cli.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Shared, platform-neutral command declarations and parsing. No runtime I/O.
6
7pub use crate::edit::flags::FlagOp;
8/// Typed edit action grammar, independent of legacy flag grouping.
9pub mod edit_actions;
10/// Desired-text template generation grammar.
11pub mod edit_template;
12use clap::{CommandFactory, FromArgMatches, Parser};
13use serde::Serialize;
14use std::path::{Path, PathBuf};
15
16pub(crate) use crate::util::datetime::parse_datetime;
17
18/// Read, edit, compare and render Word documents.
19#[derive(Parser, Debug, Serialize)]
20#[command(
21    name = "jubarte", version = env!("JUBARTE_BUILD_VERSION"),
22    help_template = "{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{all-args}{after-help}",
23    about = "Read, edit, compare and render Word documents",
24    long_about = None,
25    styles = styles(),
26    term_width = 88,
27    args_conflicts_with_subcommands = true,
28    subcommand_negates_reqs = true,
29    arg_required_else_help = true,
30    subcommand_help_heading = "Tasks",
31    after_help = "Examples:\n  jubarte compare old.docx new.docx -o redline.docx\n  jubarte contract.docx                    print the agent view (read)\n  jubarte old.docx new.docx                redline printed as the agent view (-o writes it)\n  jubarte read contract.docx --json\n  jubarte diff old.docx new.docx --format github\n  jubarte convert contract.docx -o contract.pdf\n\nRun jubarte <task> --help for task options.",
32)]
33pub struct Cli {
34    /// Subcommand (e.g. `revisions`); plain compare when omitted.
35    #[command(subcommand)]
36    pub command: Option<Command>,
37
38    /// No status on success: no `wrote` lines, SUCCESS block or edit summary.
39    /// Files are still written; a reading task
40    /// (`read`, `changes`, `compare` without -o, `diff`, `capabilities`)
41    /// still prints what it read, and warnings and errors still print.
42    /// `read`, `changes` and `comments` drop their stderr validity status
43    /// (JSON under `changes --json` and `comments --json`). `read --json`
44    /// and `read --for-edit` keep validity counts in their output, -q or not.
45    #[arg(
46        short = 'q',
47        long,
48        global = true,
49        overrides_with = "quiet",
50        help_heading = None::<&str>
51    )]
52    pub quiet: bool,
53
54    /// Inputs and settings of the shorthands: `jubarte A B` is `compare A
55    /// B`; `jubarte FILE` is `read FILE`, with `compare.read`'s options.
56    #[command(flatten)]
57    #[serde(flatten)]
58    pub compare: CompareArgs,
59}
60
61/// Options of `read`.
62#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
63#[group(id = "read_options", multiple = true)]
64pub struct ReadArgs {
65    /// Tracked changes inline (all, the default), or the text with every
66    /// change accepted or rejected (also spelled accepted, rejected); the
67    /// id lines then list what changed. --json and --tables read the
68    /// accepted text, or under reject the rejected one, every paragraph
69    /// keeping its id; the snapshot names an accept or a reject in
70    /// `track_changes`.
71    #[arg(long, value_enum, value_name = "CHOICE", help_heading = "Read options")]
72    pub track_changes: Option<TrackChanges>,
73    /// Comments inline (default) or hidden, with their ids on the id line
74    /// of the paragraph that holds them; ignored by --json, --for-edit and
75    /// the --tables grids.
76    #[arg(
77        long,
78        value_enum,
79        default_value_t = CommentsArg::Inline,
80        value_name = "MODE",
81        help_heading = "Read options"
82    )]
83    pub comments: CommentsArg,
84    /// Timestamps on the notes of an author whose changes do not all share
85    /// one (the header shows an author's single timestamp); ignored by
86    /// --json, --for-edit and the --tables grids.
87    #[arg(long, help_heading = "Read options")]
88    pub dates: bool,
89    /// Skip the layout pass; page count from Word's cached breaks, no
90    /// `<!-- page N of M -->` lines; ignored by --json, --for-edit and the
91    /// --tables grids.
92    #[arg(long, help_heading = "Read options")]
93    pub no_page_markers: bool,
94    /// Only these blocks: `p5`, `p4-p7`, `t0`, comma-separated (open-ended
95    /// `p17-` / `-p3` spellings still parse, transitionally; the 17 October
96    /// 2026 contract retires them — spell the end, `p17-p20`). With --tables,
97    /// select top-level tables (including their nested tables) by the same
98    /// tN as the view, or by a pN inside them; a pick that reaches no table
99    /// is refused. Print their grid, then a blank line and the same view as
100    /// read -p SPEC. Repeat it to add blocks: `-p p3 -p p8` reads as
101    /// `-p p3,p8`.
102    #[arg(
103        short = 'p',
104        long = "paragraphs",
105        visible_alias = "select",
106        value_name = "SPEC",
107        conflicts_with_all = ["head", "tail"],
108        action = clap::ArgAction::Append,
109        help_heading = "Read options"
110    )]
111    #[serde(serialize_with = "serialize_paragraph_spec")]
112    pub paragraphs: Vec<String>,
113    /// Only the first N blocks (a table is one block).
114    #[arg(
115        long,
116        value_name = "N",
117        conflicts_with = "tail",
118        help_heading = "Read options"
119    )]
120    pub head: Option<usize>,
121    /// Only the last N blocks.
122    #[arg(long, value_name = "N", help_heading = "Read options")]
123    pub tail: Option<usize>,
124    /// Only the blocks with a tracked change or a comment.
125    #[arg(
126        long,
127        conflicts_with_all = ["paragraphs", "head", "tail"],
128        help_heading = "Read options"
129    )]
130    pub changed: bool,
131    /// With --changed: only the blocks with this author's marks (a handle
132    /// such as AC, or the full name).
133    #[arg(
134        long,
135        value_name = "AUTHOR",
136        requires = "changed",
137        value_parser = parse_author,
138        help_heading = "Read options"
139    )]
140    pub by: Option<String>,
141    /// Print the snapshot as JSON instead of the view: `schema_version`,
142    /// `source_sha256`, `summary`, `paragraphs`, `stories`, `tables`,
143    /// `controls`, `changes` and `comments`. -p, --head, --tail, --changed
144    /// and --by keep the body paragraphs they select, and every change and
145    /// comment that starts in one of them, whoever made it; the rest of the
146    /// snapshot stays whole. --track-changes accept or reject settles the
147    /// text.
148    #[arg(long, help_heading = "Read options")]
149    pub json: bool,
150    /// Print each top-level body table as a grid: a `table N:
151    /// ROWSxCOLS header_rows=H widths=W,...` line, then one line per row of
152    /// tab-separated `ids=text` cells. Use -p t0,t2 or -p pN (a cell
153    /// paragraph) to select top-level tables and all their nested tables,
154    /// in document order, each once. tN is the view's top-level index;
155    /// nested entries follow their cell row, indented two spaces per level,
156    /// labelled `nested in t0.row2.cell0` (recursively, e.g.
157    /// `t0.row2.cell0.t0.row0.cell1`). A pN or a range selects the tables
158    /// that hold its paragraphs; one that reaches no table is refused.
159    /// With -p, follow the selected grids with a blank line and the same
160    /// view as read -p SPEC, including its YAML header. Without -p, print
161    /// only the inventory. --track-changes reject reads the rejected text.
162    #[arg(
163        long,
164        conflicts_with_all = ["json", "head", "tail", "changed", "by"],
165        help_heading = "Read options"
166    )]
167    pub tables: bool,
168    /// The working document template/apply derive, as JSON: source hash,
169    /// paired target ids, exact logical working text with `before_sha256`
170    /// and readiness per operation and range. The selection (-p/--select,
171    /// --head, --tail, --changed, --by, --find, --regex) resolves on the
172    /// original source and freezes before the decisions settle it. Given
173    /// filters narrow together: a paragraph is selected only when every
174    /// filter given matches it, and an empty result names the filters
175    /// applied in `coverage.omissions`.
176    #[arg(long, conflicts_with = "track_changes", help_heading = "Read options")]
177    pub for_edit: bool,
178    /// --for-edit: the working view after accepting this revision
179    /// (repeatable; it does not modify FILE).
180    #[arg(
181        long,
182        value_name = "ID",
183        requires = "for_edit",
184        help_heading = "Read options"
185    )]
186    pub accept_change: Vec<String>,
187    /// --for-edit: the working view after rejecting this revision
188    /// (repeatable; it does not modify FILE).
189    #[arg(
190        long,
191        value_name = "ID",
192        requires = "for_edit",
193        help_heading = "Read options"
194    )]
195    pub reject_change: Vec<String>,
196    /// --for-edit: the remaining-revision policy of the working basis
197    /// (default keep, matching new plans).
198    #[arg(
199        long,
200        value_enum,
201        value_name = "MODE",
202        requires = "for_edit",
203        help_heading = "Read options"
204    )]
205    pub existing_revisions: Option<ExistingArg>,
206    /// --for-edit: readiness for tracked (on, the default) or direct
207    /// (off) new edits.
208    #[arg(
209        long,
210        value_enum,
211        value_name = "CHOICE",
212        requires = "for_edit",
213        help_heading = "Read options"
214    )]
215    pub track: Option<TrackArg>,
216    /// Print matching body paragraphs only, with the same Markdown and id
217    /// lines as -p. Searches original final logical text, as --for-edit does;
218    /// combined filters narrow. Like -p, the view cannot select paragraphs in
219    /// headers, footers, footnotes, endnotes and comments. Use --for-edit for
220    /// header/footer/note paragraphs. No match prints nothing and reports it
221    /// on stderr.
222    #[arg(
223        long,
224        value_name = "TEXT",
225        conflicts_with = "regex",
226        help_heading = "Read options"
227    )]
228    pub find: Option<String>,
229    /// Search with a regular expression instead of literal text (view or
230    /// --for-edit). Give PATTERN here and omit --find.
231    #[arg(
232        long,
233        value_name = "PATTERN",
234        conflicts_with = "find",
235        help_heading = "Read options"
236    )]
237    pub regex: Option<String>,
238    /// Case-insensitive --find/--regex (view or --for-edit).
239    #[arg(long, help_heading = "Read options")]
240    pub ignore_case: bool,
241    /// --for-edit: this many read-only original-source neighbours around
242    /// each row.
243    #[arg(
244        long,
245        value_name = "N",
246        requires = "for_edit",
247        help_heading = "Read options"
248    )]
249    pub context: Option<usize>,
250    /// --for-edit: primary records a page returns (default 100).
251    #[arg(
252        long,
253        value_name = "N",
254        requires = "for_edit",
255        help_heading = "Read options"
256    )]
257    pub limit: Option<usize>,
258    /// --for-edit: the text budget a page shares (default 24000);
259    /// a truncated row's preview is never complete text.
260    #[arg(
261        long,
262        value_name = "N",
263        requires = "for_edit",
264        help_heading = "Read options"
265    )]
266    pub max_chars: Option<usize>,
267    /// --for-edit: continue an earlier bounded query (bound to its
268    /// source, selection, filters and working basis).
269    #[arg(
270        long,
271        value_name = "TOKEN",
272        requires = "for_edit",
273        help_heading = "Read options"
274    )]
275    pub cursor: Option<String>,
276    /// --for-edit: no presentation limits (admission limits still hold).
277    #[arg(long, requires = "for_edit", help_heading = "Read options")]
278    pub all: bool,
279}
280
281impl ReadArgs {
282    /// The `-p` selectors as one comma list: `-p p3 -p p8` reads as
283    /// `-p p3,p8` (#1690). `None` without `-p`. [`ReadArgs::paragraphs`]
284    /// holds one entry per `-p` as typed; the facade JSON carries this
285    /// joined list as one string (`null` without `-p`).
286    pub fn paragraph_spec(&self) -> Option<String> {
287        (!self.paragraphs.is_empty()).then(|| self.paragraphs.join(","))
288    }
289
290    /// The `read --for-edit` request these flags describe (V2-10): the
291    /// working basis template and apply derive — `auto` (and the absence
292    /// of the flag) keeps the remaining revisions, `on` tracks new edits.
293    /// `read --for-edit` keeps the open-ended range spellings its help
294    /// documents; the bindings build the same request through this.
295    pub fn for_edit_request(&self) -> crate::edit::for_edit::ForEditRequest {
296        crate::edit::for_edit::ForEditRequest {
297            select: self.paragraph_spec(),
298            head: self.head,
299            tail: self.tail,
300            find: self.find.clone(),
301            regex: self.regex.clone(),
302            ignore_case: self.ignore_case,
303            changed: self.changed,
304            by: self.by.clone(),
305            context: self.context.unwrap_or(0),
306            limit: self.limit,
307            max_chars: self.max_chars,
308            all: self.all,
309            cursor: self.cursor.clone(),
310            accept: self.accept_change.clone(),
311            reject: self.reject_change.clone(),
312            existing_revisions: self
313                .existing_revisions
314                .and_then(ExistingArg::plan_value)
315                .unwrap_or(crate::edit::ExistingRevisions::Keep),
316            track: self.track.unwrap_or_default() == TrackArg::On,
317            ..Default::default()
318        }
319    }
320}
321
322/// `--comments` of `read`.
323#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
324#[serde(rename_all = "kebab-case")]
325pub enum CommentsArg {
326    /// Comments inline, with their ids.
327    #[default]
328    Inline,
329    /// Comments hidden; their ids on the id lines.
330    None,
331}
332
333/// `--track` of `read --for-edit`.
334#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
335#[serde(rename_all = "kebab-case")]
336pub enum TrackArg {
337    /// The new edits are tracked.
338    #[default]
339    On,
340    /// The new edits land directly.
341    Off,
342}
343
344impl TrackArg {
345    /// `--track`'s spelling (`on`, `off`); `None` for anything else.
346    pub fn from_choice(choice: &str) -> Option<Self> {
347        match choice {
348            "on" => Some(Self::On),
349            "off" => Some(Self::Off),
350            _ => None,
351        }
352    }
353}
354
355/// Options `edit` and `add` share.
356#[derive(clap::Args, Debug, Serialize)]
357pub struct EditOptions {
358    /// Author of the changes and comments (operation flags; a plan names
359    /// its own). A write that adds markup needs it spelled here or in
360    /// JUBARTE_AUTHOR.
361    #[arg(short = 'a', long, value_name = "NAME", default_value = "Jubarte")]
362    pub author: String,
363    /// Whether `-a`/`--author` was spelled on the command line (set after
364    /// parsing). One-shot writes use this to say when the default signed
365    /// the new markup (#1891).
366    #[arg(skip)]
367    #[serde(skip)]
368    pub author_given: bool,
369    /// Revision timestamp (ISO 8601) [default: now, UTC]; pin it for
370    /// reproducible output.
371    #[arg(short = 'd', long = "datetime", value_name = "ISO8601", value_parser = parse_datetime)]
372    pub datetime: Option<String>,
373    /// The edits are tracked changes (the default): the file written is
374    /// the redline and the view shows the marks.
375    #[arg(long, conflicts_with = "editing_mode")]
376    pub suggesting_mode: bool,
377    /// The edits land directly: the file written is the result, and the
378    /// view shows it with rev tags on the id lines.
379    #[arg(long)]
380    pub editing_mode: bool,
381    /// What to do when FILE already holds tracked changes: auto keeps them
382    /// and tracks the new edits beside them; a clean file goes through the
383    /// comparer.
384    #[arg(long, value_enum, value_name = "MODE", default_value_t = ExistingArg::Auto)]
385    pub existing_revisions: ExistingArg,
386    /// Replace FILE through the same atomic write as -o. A refused edit or a
387    /// failed check leaves FILE unchanged. Not with -o or --out-dir.
388    #[arg(long, conflicts_with_all = ["output", "out_dir"])]
389    pub in_place: bool,
390    /// The edited document, a .docx (default: `<FILE's
391    /// directory>/<stem>_modified.docx`). Any other extension is written as
392    /// a .docx too; .md, .json, .pdf and .png name the task that writes them.
393    #[arg(
394        short = 'o',
395        long,
396        value_name = "FILE.docx",
397        conflicts_with = "out_dir"
398    )]
399    pub output: Option<PathBuf>,
400    /// Write the bundle instead: clean.docx, redline.docx, patch.diff and
401    /// report.jsonl (clean.docx and report.jsonl in editing mode) in DIR
402    /// (default: `<FILE's directory>/<stem>.edit`).
403    #[arg(long, value_name = "DIR", num_args = 0..=1)]
404    pub out_dir: Option<Option<PathBuf>>,
405    /// Replace an existing output (the bundle directory's files).
406    #[arg(long)]
407    pub force: bool,
408}
409
410/// What `edit` and `add` write: one document, or the bundle directory.
411#[derive(Clone, Debug, PartialEq, Eq)]
412pub enum EditTarget {
413    /// The redline (or, in editing mode, the result) as one .docx.
414    Single(PathBuf),
415    /// clean.docx, redline.docx, patch.diff and report.jsonl in a directory.
416    Bundle(PathBuf),
417}
418
419impl EditOptions {
420    /// Where `edit FILE` (or `add FILE`) writes: `--in-place` replaces
421    /// FILE, else `--out-dir [DIR]`'s bundle, else `-o`, else `<FILE's
422    /// dir>/<stem>_modified.docx`. A FILE whose stem already ends in
423    /// `_modified` keeps its name. Pure.
424    pub fn target(&self, file: &Path) -> EditTarget {
425        if self.in_place {
426            return EditTarget::Single(file.to_path_buf());
427        }
428        let beside = |name: String| match file.parent().filter(|p| !p.as_os_str().is_empty()) {
429            Some(dir) => dir.join(name),
430            None => PathBuf::from(name),
431        };
432        let stem = file.file_stem().map_or_else(
433            || "document".to_string(),
434            |s| s.to_string_lossy().into_owned(),
435        );
436        match (&self.out_dir, &self.output) {
437            (Some(Some(dir)), _) => EditTarget::Bundle(dir.clone()),
438            (Some(None), _) => EditTarget::Bundle(beside(format!("{stem}.edit"))),
439            (None, Some(output)) => EditTarget::Single(output.clone()),
440            (None, None) if stem.ends_with("_modified") => {
441                EditTarget::Single(beside(format!("{stem}.docx")))
442            }
443            (None, None) => EditTarget::Single(beside(format!("{stem}_modified.docx"))),
444        }
445    }
446}
447
448/// `--existing-revisions` of `edit` and `add`.
449#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
450#[serde(rename_all = "kebab-case")]
451pub enum ExistingArg {
452    /// `keep` when the file has tracked changes, else the comparer path.
453    #[default]
454    Auto,
455    /// Keep them; the new edits are tracked beside them.
456    Keep,
457    /// Accept them first.
458    Accept,
459    /// Reject them first.
460    Reject,
461    /// Refuse a file that has them.
462    Refuse,
463}
464
465impl ExistingArg {
466    /// `--existing-revisions`'s spelling (`auto`, `keep`, `accept`,
467    /// `reject`, `refuse`); `None` for anything else.
468    pub fn from_choice(choice: &str) -> Option<Self> {
469        match choice {
470            "auto" => Some(Self::Auto),
471            "keep" => Some(Self::Keep),
472            "accept" => Some(Self::Accept),
473            "reject" => Some(Self::Reject),
474            "refuse" => Some(Self::Refuse),
475            _ => None,
476        }
477    }
478
479    /// The plan's `existing_revisions`; `None` for `auto`.
480    pub fn plan_value(self) -> Option<crate::edit::ExistingRevisions> {
481        use crate::edit::ExistingRevisions as E;
482        match self {
483            Self::Auto => None,
484            Self::Keep => Some(E::Keep),
485            Self::Accept => Some(E::Accept),
486            Self::Reject => Some(E::Reject),
487            Self::Refuse => Some(E::Refuse),
488        }
489    }
490}
491
492/// Groups the operation flags of an `edit` or `add` invocation by their
493/// `-p`, in command-line order. `matches` is the subcommand's.
494pub fn flag_operations(matches: &clap::ArgMatches) -> Result<Vec<FlagOp>, String> {
495    if matches.contains_id("anchor") && !matches.contains_id("location") {
496        return Err("--anchor needs -p WHERE (find it with: jubarte read FILE --find TEXT)".into());
497    }
498    let mut tokens: Vec<(usize, &str, Option<String>)> = Vec::new();
499    for name in ["location", "anchor", "content", "reply", "style"] {
500        if let (Some(indices), Some(values)) =
501            (matches.indices_of(name), matches.get_many::<String>(name))
502        {
503            tokens.extend(indices.zip(values).map(|(i, v)| (i, name, Some(v.clone()))));
504        }
505    }
506    if let (Some(indices), Some(values)) = (
507        matches.indices_of("occurrence"),
508        matches.get_many::<usize>("occurrence"),
509    ) {
510        tokens.extend(
511            indices
512                .zip(values)
513                .map(|(i, v)| (i, "occurrence", Some(v.to_string()))),
514        );
515    }
516    for name in [
517        "delete", "resolve", "before", "comment", "accept", "reject", "strike", "restore",
518        "visible",
519    ] {
520        // `try_get_many` is `Err` for a flag this command does not declare
521        // (`add` has no --resolve or --accept); `indices_of` would panic on
522        // it.
523        if matches.try_get_many::<bool>(name).ok().flatten().is_none() {
524            continue;
525        }
526        if let Some(indices) = matches.indices_of(name) {
527            tokens.extend(indices.map(|i| (i, name, None)));
528        }
529    }
530    tokens.sort_by_key(|t| t.0);
531    let mut ops: Vec<FlagOp> = Vec::new();
532    for (_, name, value) in tokens {
533        if name == "location" {
534            ops.push(FlagOp {
535                at: value.unwrap_or_default(),
536                ..FlagOp::default()
537            });
538            continue;
539        }
540        let Some(op) = ops.last_mut() else {
541            return Err(format!("--{name} comes before the first -p/--location"));
542        };
543        let twice = |what: &str| Err(format!("-p {}: --{what} given twice", op.at));
544        match name {
545            "anchor" if op.anchor.is_some() => return twice("anchor"),
546            "anchor" => op.anchor = value,
547            "occurrence" if op.occurrence.is_some() => return twice("occurrence"),
548            "occurrence" if op.anchor.is_none() => {
549                return Err(format!(
550                    "-p {}: --occurrence must come after --anchor",
551                    op.at
552                ));
553            }
554            "occurrence" => {
555                op.occurrence = value.and_then(|v| v.parse().ok());
556            }
557            "content" if op.content.is_some() => return twice("content"),
558            "content" => op.content = value,
559            "reply" if op.reply.is_some() => return twice("reply"),
560            "reply" => op.reply = value,
561            "style" => op.styles.push(value.unwrap_or_default()),
562            "delete" => op.delete = true,
563            "resolve" => op.resolve = true,
564            "before" => op.before = true,
565            "comment" => op.comment = true,
566            "accept" => op.accept = true,
567            "reject" => op.reject = true,
568            "strike" => op.strike = true,
569            "restore" => op.restore = true,
570            "visible" => op.visible = true,
571            _ => {}
572        }
573    }
574    Ok(ops)
575}
576
577/// `--plan`'s parser: a path that may be empty, the value `--plan` takes
578/// when given bare (clap's `PathBuf` parser refuses an empty one). A path
579/// ending in a separator names a folder, never the plan file, so it is
580/// refused here, alike in the binary, Python and npm (#433: they
581/// once wrote `new.json`, failed the rename, or refused).
582fn plan_path() -> impl clap::builder::TypedValueParser<Value = PathBuf> {
583    use clap::builder::TypedValueParser as _;
584    clap::builder::OsStringValueParser::new().try_map(|value| {
585        let text = value.to_string_lossy();
586        if text.ends_with('/') || cfg!(windows) && text.ends_with('\\') {
587            return Err(format!(
588                "{text} ends in a separator, so it names a folder; give the plan's file, such as PLAN.json"
589            ));
590        }
591        Ok(PathBuf::from(value))
592    })
593}
594
595/// `-q`/`--quiet` before the task moves after it, so `jubarte -q validate F`
596/// reads as `jubarte validate -q F` (D6 follow-up). Only the quiet flag
597/// moves: every other option still goes after the task. Before `help` the
598/// flag is dropped, since clap's `help` takes task names only.
599fn hoist_quiet<T: AsRef<std::ffi::OsStr> + Clone>(
600    command: &clap::Command,
601    arguments: &[T],
602) -> Vec<T> {
603    let is_quiet = |a: &T| match a.as_ref().to_str() {
604        Some("--quiet") => true,
605        Some(short) => {
606            short.len() > 1 && short.starts_with('-') && short[1..].bytes().all(|b| b == b'q')
607        }
608        None => false,
609    };
610    let flags = arguments.iter().skip(1).take_while(|a| is_quiet(a)).count();
611    let task = arguments.get(1 + flags).and_then(|a| a.as_ref().to_str());
612    if flags > 0 && task == Some("help") {
613        // clap's own `help` takes task names, not -q: help is printed anyway.
614        let mut help = vec![arguments[0].clone()];
615        help.extend_from_slice(&arguments[1 + flags..]);
616        return help;
617    }
618    if flags == 0 || task.is_none_or(|name| command.find_subcommand(name).is_none()) {
619        return arguments.to_vec();
620    }
621    let mut hoisted = Vec::with_capacity(arguments.len());
622    hoisted.push(arguments[0].clone());
623    hoisted.push(arguments[1 + flags].clone());
624    hoisted.extend_from_slice(&arguments[1..1 + flags]);
625    hoisted.extend_from_slice(&arguments[2 + flags..]);
626    hoisted
627}
628
629/// `compare`'s and `diff`'s missing `-d` is now, in UTC, to the second
630/// (D17): filled once here, so the binary and every host share it.
631fn fill_date(date: &mut Option<String>) {
632    if date.is_none() {
633        *date = Some(crate::util::datetime::utc_now_iso8601());
634    }
635}
636
637/// [`fill_date`] for the task that dates its revisions.
638fn fill_task_date(task: &mut Command) {
639    match task {
640        Command::Compare(compare) => fill_date(&mut compare.datetime),
641        Command::Diff { datetime: date, .. } => fill_date(date),
642        _ => {}
643    }
644}
645
646/// A path as the CLI's agent-facing outputs spell it: `/` between the
647/// parts on every OS (#568). The paths `parse_json` resolves and the
648/// view's `source:` line are identifiers an agent reads back, so their
649/// spelling must not change with the OS; human status lines (`wrote …`)
650/// keep the native path. A `\` inside a file name is replaced too: these
651/// outputs name files the CLI itself resolved or wrote, whose names hold
652/// none.
653///
654/// Canonicalizing on Windows returns a verbatim path (`\\?\C:\…`), which
655/// this spelling would show as `//?/C:/…` — a string that is no path at
656/// all (#1222). `unverbatimed` drops that prefix from the components
657/// first, so an agent-facing canonical path spells `C:/…`.
658pub fn slash_path(path: &Path) -> String {
659    let path = unverbatimed(path).unwrap_or_else(|| path.to_path_buf());
660    path.to_string_lossy().replace('\\', "/")
661}
662
663/// `path` without the verbatim prefix `canonicalize` adds on Windows, or
664/// `None` when there is none to drop. Built on `Path::components()` so the
665/// head is the parsed prefix, never a string match: `\\?\C:\a` loses its
666/// `VerbatimDisk` head and comes back `C:\a`, and `\\?\UNC\server\share\x`
667/// comes back `\\server\share\x`, which [`slash_path`] spells
668/// `//server/share/x`. A `\\?\` path neither disk nor UNC keeps its head's
669/// text as the path's start.
670fn unverbatimed(path: &Path) -> Option<PathBuf> {
671    let mut components = path.components();
672    let (mut stripped, keeps_root) = verbatim_head(components.next())?;
673    for component in components {
674        // A disk or UNC head keeps the root: `C:` + `\` is `C:\`, while
675        // `C:` + `a` would be the drive-relative `C:a` (a bare drive takes
676        // no separator). Any other `\\?\` head is no prefix once stripped,
677        // so its root is dropped and the parts join onto the head's text.
678        if keeps_root || !matches!(component, std::path::Component::RootDir) {
679            stripped.push(component.as_os_str());
680        }
681    }
682    Some(stripped)
683}
684
685/// The path head a verbatim prefix becomes, and whether the root after it
686/// stays, or `None` for any other first component (`Prefix` is a Windows
687/// notion; off Windows this is always `None` and [`unverbatimed`] changes
688/// nothing).
689#[cfg(windows)]
690fn verbatim_head(component: Option<std::path::Component>) -> Option<(PathBuf, bool)> {
691    use std::path::{Component, Prefix};
692    match component {
693        Some(Component::Prefix(prefix)) => match prefix.kind() {
694            Prefix::VerbatimDisk(letter) => Some((
695                PathBuf::from(format!("{}:", (letter as char).to_ascii_uppercase())),
696                true,
697            )),
698            Prefix::VerbatimUNC(server, share) => {
699                let mut head = PathBuf::from(r"\\");
700                head.push(server);
701                head.push(share);
702                Some((head, true))
703            }
704            Prefix::Verbatim(rest) => Some((PathBuf::from(rest), false)),
705            _ => None,
706        },
707        _ => None,
708    }
709}
710
711/// Off Windows no component carries a prefix, so there is nothing to drop.
712#[cfg(not(windows))]
713fn verbatim_head(_component: Option<std::path::Component>) -> Option<(PathBuf, bool)> {
714    None
715}
716
717/// `--plan` without a value (D16) is `<FILE's dir>/<stem>_plan.json`.
718fn resolve_plan(task: &mut Command) {
719    let (Command::Edit {
720        file,
721        plan: Some(plan),
722        plan_default,
723        ..
724    }
725    | Command::Add {
726        file,
727        plan: Some(plan),
728        plan_default,
729        ..
730    }) = task
731    else {
732        return;
733    };
734    if !plan.as_os_str().is_empty() {
735        return;
736    }
737    let stem = file.file_stem().map_or_else(
738        || "document".to_string(),
739        |s| s.to_string_lossy().into_owned(),
740    );
741    let name = format!("{stem}_plan.json");
742    *plan = match file.parent().filter(|p| !p.as_os_str().is_empty()) {
743        Some(dir) => dir.join(name),
744        None => PathBuf::from(name),
745    };
746    *plan_default = true;
747}
748
749/// A Word document's name, by extension: what an optional value swallowed
750/// when it should have been FILE.
751fn names_word_document(path: &Path) -> bool {
752    // By name, so a bare `.docx` (no stem, no extension to Path) counts.
753    path.file_name().is_some_and(|name| {
754        let name = name.to_string_lossy().to_ascii_lowercase();
755        [".docx", ".docm", ".dotx", ".dotm", ".doc"]
756            .iter()
757            .any(|ext| name.ends_with(ext))
758    })
759}
760
761/// The message for an optional value (`--plan`, `--out-dir`) that names a
762/// Word document: FILE was read as the value.
763fn swallowed_file(flag: &str, value: &Path) -> String {
764    let instead = if flag == "--plan" { "PLAN.json" } else { "DIR" };
765    format!(
766        "{flag} {} names a Word document; put FILE before {flag}, or write {flag}={instead}",
767        value.display()
768    )
769}
770
771/// Rewrite known usage traps through clap's own error formatter. A read
772/// view conflict teaches the valid invocation; `edit --plan a.docx -p p1 …`
773/// identifies the swallowed FILE from the raw tokens. Other errors stay
774/// clap's own (including help, unknown options and invalid values).
775fn usage_error(command: &clap::Command, tokens: &[String], mut error: clap::Error) -> clap::Error {
776    if error.kind() == clap::error::ErrorKind::ArgumentConflict {
777        use clap::error::ContextKind;
778        // Use clap's identified arguments, not option-looking values in
779        // the raw tokens, so unrelated conflicts retain their diagnosis.
780        let conflicts = [ContextKind::InvalidArg, ContextKind::PriorArg]
781            .into_iter()
782            .filter_map(|kind| error.get(kind))
783            .map(ToString::to_string)
784            .collect::<Vec<_>>()
785            .join(" ");
786        let names = |flag: &&str| conflicts.split_whitespace().any(|word| word == *flag);
787        // --json and --tables take the view's options; only --for-edit,
788        // which settles through its own --accept-change, refuses one.
789        if names(&"--track-changes") && names(&"--for-edit") {
790            return read_usage_error(command, read_view_conflict("--track-changes"));
791        }
792        if names(&"--tables") {
793            error.insert(
794                ContextKind::Usage,
795                clap::error::ContextValue::StyledStr(
796                    format!("Usage: {} read [OPTIONS] <FILE>", command.get_name()).into(),
797                ),
798            );
799        }
800    }
801    if error.kind() != clap::error::ErrorKind::MissingRequiredArgument {
802        return error;
803    }
804    let Some(at) = tokens.iter().skip(1).position(|t| !t.starts_with('-')) else {
805        return error;
806    };
807    let name = tokens[at + 1].as_str();
808    let Some(sub) = command
809        .find_subcommand(name)
810        .filter(|_| matches!(name, "edit" | "add"))
811    else {
812        return error;
813    };
814    // `--plan VALUE` or `--plan=VALUE`, before `--` ends the options.
815    let options = tokens[at + 2..].iter().take_while(|t| *t != "--");
816    let mut previous: Option<&str> = None;
817    let mut found = None;
818    for token in options {
819        let pair = match token.split_once('=') {
820            Some((flag, value)) if flag.starts_with("--") => Some((flag, value)),
821            _ => previous.map(|flag| (flag, token.as_str())),
822        };
823        if let Some((flag, value)) = pair
824            && matches!(flag, "--plan" | "--out-dir")
825            && !value.starts_with('-')
826            && names_word_document(Path::new(value))
827        {
828            found = Some(swallowed_file(flag, Path::new(value)));
829            break;
830        }
831        previous = Some(token.as_str()).filter(|t| matches!(*t, "--plan" | "--out-dir"));
832    }
833    let Some(message) = found else {
834        return error;
835    };
836    let mut task = sub.clone();
837    task.set_bin_name(format!("{} {name}", command.get_name()));
838    task.error(clap::error::ErrorKind::ArgumentConflict, message)
839}
840
841/// Groups the flag operations of `edit` and `add` into their `operations`
842/// field; a grouping error is a usage error.
843fn fill_flag_operations(
844    task: &mut Command,
845    matches: &clap::ArgMatches,
846    model: &mut clap::Command,
847) -> Result<(), clap::Error> {
848    let (name, operations, options) = match task {
849        Command::Edit {
850            operations,
851            options,
852            ..
853        } => ("edit", operations, options),
854        Command::Add {
855            operations,
856            options,
857            ..
858        } => ("add", operations, options),
859        _ => return Ok(()),
860    };
861    let Some(sub) = matches.subcommand_matches(name) else {
862        return Ok(());
863    };
864    *operations = flag_operations(sub)
865        .map_err(|m| model.error(clap::error::ErrorKind::ArgumentConflict, m))?;
866    options.author_given =
867        sub.value_source("author") == Some(clap::parser::ValueSource::CommandLine);
868    env_author_fill(&mut options.author, &mut options.author_given)
869        .map_err(|m| model.error(clap::error::ErrorKind::ValueValidation, m))?;
870    Ok(())
871}
872
873/// `JUBARTE_AUTHOR`, set and non-empty, signs the way a spelled `-a` does
874/// (#1997). An invalid one is a usage error naming the variable.
875fn env_author_fill(author: &mut String, given: &mut bool) -> Result<(), String> {
876    if *given {
877        return Ok(());
878    }
879    let Some(name) = std::env::var("JUBARTE_AUTHOR")
880        .ok()
881        .filter(|name| !name.is_empty())
882    else {
883        return Ok(());
884    };
885    *author = parse_author(&name).map_err(|m| format!("JUBARTE_AUTHOR: {m}"))?;
886    *given = true;
887    Ok(())
888}
889
890/// `JUBARTE_TIMEOUT`, set and non-empty: a wall-clock bound, in seconds,
891/// on any task, as `convert --timeout` bounds `convert` (#2016). An invalid
892/// value is a usage error naming the variable.
893///
894/// # Errors
895///
896/// `JUBARTE_TIMEOUT: …` when the value is not a finite number of seconds
897/// above 0.
898pub fn env_timeout() -> Result<Option<std::time::Duration>, String> {
899    // A value that is not Unicode is refused, never read as unset: a host
900    // that set the variable expects a bound.
901    let Some(value) = std::env::var_os("JUBARTE_TIMEOUT") else {
902        return Ok(None);
903    };
904    let value = value.into_string().map_err(|raw| {
905        format!(
906            "JUBARTE_TIMEOUT: '{}' is not a number of seconds",
907            raw.to_string_lossy()
908        )
909    })?;
910    if value.is_empty() {
911        return Ok(None);
912    }
913    parse_timeout(&value)
914        .map(Some)
915        .map_err(|m| format!("JUBARTE_TIMEOUT: {m}"))
916}
917
918/// Inputs and settings shared by explicit and shorthand comparisons.
919#[derive(clap::Args, Debug, Serialize)]
920#[group(id = "compare_options", multiple = true)]
921pub struct CompareArgs {
922    /// The original / base document (.docx or Markdown).
923    #[arg(value_name = "ORIGINAL", required_unless_present = "original")]
924    pub original_pos: Option<PathBuf>,
925
926    /// The modified document (.docx or Markdown).
927    #[arg(value_name = "MODIFIED")]
928    pub modified_pos: Option<PathBuf>,
929
930    /// Original/base document (overrides the positional ORIGINAL).
931    #[arg(short = 'b', long = "original", value_name = "FILE")]
932    pub original: Option<PathBuf>,
933
934    /// Modified document (overrides the positional MODIFIED).
935    #[arg(short = 'm', long = "modified", value_name = "FILE")]
936    pub modified: Option<PathBuf>,
937
938    /// Write the redline to FILE instead of printing its agent view; the
939    /// extension picks the format: .docx (also any other), .md (the agent
940    /// view; CriticMarkup when both documents are Markdown), .pdf, .png
941    /// (one file per page) or .json (the snapshot).
942    #[arg(short = 'o', long, value_name = "FILE")]
943    pub output: Option<PathBuf>,
944
945    /// Author name recorded on the revisions.
946    #[arg(short = 'a', long, value_name = "NAME", default_value = "Jubarte")]
947    pub author: String,
948
949    /// Revision timestamp (ISO 8601) [default: now, UTC]; pin it for
950    /// reproducible output.
951    // The parser fills now when absent (D17), so every host shares it.
952    #[arg(short = 'd', long = "datetime", value_name = "ISO8601", value_parser = parse_datetime)]
953    pub datetime: Option<String>,
954
955    /// Overwrite the output file if it already exists.
956    #[arg(long)]
957    pub force: bool,
958
959    /// Word-match detail, from 0 to 1 [default: 0.02; powertools: 0.15].
960    #[arg(long, value_name = "RATIO", value_parser = parse_threshold)]
961    pub detail_threshold: Option<f64>,
962
963    /// Compare like Microsoft Word or Open-Xml-PowerTools.
964    #[arg(long, value_enum, value_name = "MODE", default_value_t = CompareMode::Word)]
965    pub mode: CompareMode,
966
967    /// Same as --mode powertools.
968    #[arg(long, hide = true)]
969    pub powertools_faithful: bool,
970
971    /// DEBUG: zero WmlComparerSettings::merge_replaced_paragraphs — the
972    /// word-visual UMBRELLA gate — which disables the WHOLE word-visual pass
973    /// family (merge, flatten, reorder, margins, …), not just the paragraph
974    /// merge (pagination experiments; hidden). Redundant with
975    /// --powertools-faithful, which sets the same preset.
976    #[arg(long, hide = true)]
977    pub no_paragraph_merge: bool,
978
979    /// Two Markdown documents written as Word take styles, page setup,
980    /// headers and footers from this .docx.
981    #[arg(long, value_name = "FILE", help_heading = "Markdown inputs")]
982    pub reference_doc: Option<PathBuf>,
983
984    /// Read CriticMarkup in the Markdown documents as tracked changes. By
985    /// default a document compared is text.
986    #[arg(long, help_heading = "Markdown inputs")]
987    pub critic: bool,
988
989    /// Where images named by the Markdown are found (default: the
990    /// original's directory when it is Markdown, else the modified's).
991    /// Only images that resolve inside that directory are read, symlinks
992    /// resolved; a URL or a path out of it is written as its alt text,
993    /// with a warning that says why.
994    #[arg(long, value_name = "DIR", help_heading = "Markdown inputs")]
995    pub resource_path: Option<PathBuf>,
996
997    /// How a .pdf or .png output is drawn.
998    #[command(flatten)]
999    #[serde(flatten)]
1000    pub render: RenderArgs,
1001
1002    /// The options of the agent view printed without -o (or written to
1003    /// FILE.md); `jubarte FILE`'s too.
1004    #[command(flatten)]
1005    #[serde(skip)]
1006    pub read: ReadArgs,
1007
1008    /// Whether the command line spells out any of `read`'s options (set
1009    /// after parsing): a `.md` of two Markdown documents is CriticMarkup,
1010    /// which they cannot shape.
1011    #[arg(skip)]
1012    pub view_given: bool,
1013}
1014
1015/// The derive model with the shorthands' options hidden: `jubarte --help`
1016/// lists the tasks; `jubarte compare --help` and `jubarte read --help` show
1017/// every option.
1018pub fn top_level_command() -> clap::Command {
1019    let hidden: std::collections::HashSet<clap::Id> =
1020        <CompareArgs as clap::Args>::augment_args(clap::Command::new("shorthand"))
1021            .get_arguments()
1022            .map(|a| a.get_id().clone())
1023            .collect();
1024    Cli::command().mut_args(move |a| {
1025        if hidden.contains(a.get_id()) {
1026            a.hide(true)
1027        } else {
1028            a
1029        }
1030    })
1031}
1032
1033impl std::ops::Deref for Cli {
1034    type Target = CompareArgs;
1035    fn deref(&self) -> &Self::Target {
1036        &self.compare
1037    }
1038}
1039
1040/// The subcommands; none given is the two-file compare.
1041#[derive(clap::Subcommand, Debug, Serialize)]
1042#[serde(rename_all = "kebab-case", tag = "command", content = "args")]
1043pub enum Command {
1044    /// Internal dispatch for the typed `edit ACTION` grammar.
1045    #[command(name = "__edit-v2", hide = true, bin_name = "jubarte edit")]
1046    #[serde(rename = "edit")]
1047    TypedEdit(edit_actions::TypedEdit),
1048    /// Generate a complete source-bound PlanV2 without applying edits.
1049    #[command(
1050        name = "__edit-template",
1051        hide = true,
1052        bin_name = "jubarte edit template"
1053    )]
1054    #[serde(rename = "edit")]
1055    EditTemplate(edit_template::TemplateDispatch),
1056    /// Compare documents: print the redline as the agent view, or write it with -o.
1057    #[command(
1058        visible_alias = "redline",
1059        after_help = "Examples:\n  jubarte compare old.docx new.docx                 the redline's agent view\n  jubarte compare old.docx new.docx -o redline.docx\n  jubarte compare old.docx new.docx -o redline.pdf --changed-pages\n  jubarte compare old.md new.md -o changes.md       CriticMarkup\n  jubarte compare -b old.docx -m new.docx --author Legal -o r.docx"
1060    )]
1061    Compare(CompareArgs),
1062    /// List tracked changes with IDs for accept, reject and edit plans.
1063    ///
1064    /// One line per logical change: the marks Word wrote for one edit are
1065    /// one change with a joined id (`r7+8+9+10`), its text followed by
1066    /// `(N elements)`. A revision inside a comment body is `comments.r9`.
1067    Changes {
1068        /// The document (.docx).
1069        #[arg(value_name = "FILE")]
1070        file: PathBuf,
1071        /// Emit one record per line on stdout (records only). The input_validity
1072        /// status is one JSON line on stderr; -q silences it.
1073        #[arg(long)]
1074        json: bool,
1075        /// Only listed changes by this author (exact match); repeat for several.
1076        #[arg(long, value_name = "NAME", action = clap::ArgAction::Append)]
1077        author: Vec<String>,
1078    },
1079    /// Accept all tracked changes, or select by ID, author or kind.
1080    ///
1081    /// Every part counts: the body, headers, footers, notes and comment
1082    /// bodies. A comment-body revision is `comments.r9`, the id `changes`
1083    /// lists, and an id, author or kind selection settles it.
1084    Accept {
1085        /// The document (.docx) whose revisions to accept.
1086        #[arg(value_name = "FILE")]
1087        file: PathBuf,
1088        /// Replace FILE through the same atomic write as -o. A refused
1089        /// resolution leaves FILE unchanged. Not with -o.
1090        #[arg(long)]
1091        in_place: bool,
1092        /// Output path; its extension picks the format: .docx (also any
1093        /// other), .md (the agent view), .pdf, .png (one file per page) or
1094        /// .json (the snapshot).
1095        #[arg(
1096            short = 'o',
1097            long,
1098            value_name = "FILE",
1099            required_unless_present = "in_place",
1100            conflicts_with = "in_place"
1101        )]
1102        output: Option<PathBuf>,
1103        /// Overwrite the output file if it already exists.
1104        #[arg(long)]
1105        force: bool,
1106        /// Keep comments and replies whose whole anchor is removed, on an empty anchor.
1107        #[arg(long)]
1108        keep_nested_comment: bool,
1109        /// Revisions to accept or reject; empty selects all.
1110        #[command(flatten)]
1111        #[serde(flatten)]
1112        selection: Selection,
1113        /// How a .pdf or .png output is drawn.
1114        #[command(flatten)]
1115        #[serde(flatten)]
1116        render: RenderArgs,
1117    },
1118    /// Reject all tracked changes, or select by ID, author or kind.
1119    ///
1120    /// Every part counts: the body, headers, footers, notes and comment
1121    /// bodies. A comment-body revision is `comments.r9`, the id `changes`
1122    /// lists, and an id, author or kind selection settles it.
1123    Reject {
1124        /// The document (.docx) whose revisions to reject.
1125        #[arg(value_name = "FILE")]
1126        file: PathBuf,
1127        /// Replace FILE through the same atomic write as -o. A refused
1128        /// resolution leaves FILE unchanged. Not with -o.
1129        #[arg(long)]
1130        in_place: bool,
1131        /// Output path; its extension picks the format: .docx (also any
1132        /// other), .md (the agent view), .pdf, .png (one file per page) or
1133        /// .json (the snapshot).
1134        #[arg(
1135            short = 'o',
1136            long,
1137            value_name = "FILE",
1138            required_unless_present = "in_place",
1139            conflicts_with = "in_place"
1140        )]
1141        output: Option<PathBuf>,
1142        /// Overwrite the output file if it already exists.
1143        #[arg(long)]
1144        force: bool,
1145        /// Keep comments and replies whose whole anchor is removed, on an empty anchor.
1146        #[arg(long)]
1147        keep_nested_comment: bool,
1148        /// Revisions to accept or reject; empty selects all.
1149        #[command(flatten)]
1150        #[serde(flatten)]
1151        selection: Selection,
1152        /// How a .pdf or .png output is drawn.
1153        #[command(flatten)]
1154        #[serde(flatten)]
1155        render: RenderArgs,
1156    },
1157    /// Convert Word or Markdown to DOCX, PDF, PNG or Markdown.
1158    #[command(after_help = "Examples:\n  \
1159        jubarte convert contract.docx                   PDF, Word-style layout\n  \
1160        jubarte convert draft.md                        draft.docx, CriticMarkup as tracked changes\n  \
1161        jubarte convert draft.md -o draft.pdf           the changes painted in a PDF\n  \
1162        jubarte convert draft.md --reference-doc house.docx -o draft.docx\n  \
1163        jubarte convert draft.md -t md --track-changes accept   the text with every change accepted\n  \
1164        jubarte convert contract.docx -t md             Markdown with <!-- page N of M --> lines\n  \
1165        jubarte convert old.doc                         old.docx (text, headings, lists, tables)\n  \
1166        jubarte convert notes.md --no-critic            {++ and the other delimiters as text")]
1167    Convert {
1168        /// The document to convert: .docx, Markdown (.md, .markdown), or a
1169        /// Word 97-2003 .doc (read into a .docx first).
1170        #[arg(value_name = "FILE")]
1171        file: PathBuf,
1172        /// Output path; its extension picks the format: .docx, .md, .pdf,
1173        /// .png (pages named `<stem>-page-NN.png` beside it) or .json (the
1174        /// snapshot of the result). Without it: `<stem>.pdf` next to a
1175        /// .docx, `<stem>.docx` next to Markdown, `<stem>.json` for
1176        /// `--to json`; Markdown output goes to stdout.
1177        #[arg(short = 'o', long, value_name = "FILE")]
1178        output: Option<PathBuf>,
1179        /// Overwrite the output file if it already exists.
1180        #[arg(long)]
1181        force: bool,
1182        /// Retired: `--to pdf` (or `-o FILE.pdf`).
1183        #[arg(long, hide = true)]
1184        pdf: bool,
1185        /// Retired: `--to png` (or `-o FILE.png`).
1186        #[arg(long, hide = true)]
1187        png: bool,
1188        /// Write a JSON page report (`{page_count, pages:[{index,text}], fonts}`).
1189        #[arg(long, value_name = "FILE")]
1190        report: Option<PathBuf>,
1191        /// Deflate the PDF's streams (`/FlateDecode`). Much smaller output;
1192        /// the trade is that the page content is no longer plain text, so it
1193        /// cannot be read with `strings` or `grep`.
1194        #[arg(long)]
1195        compress: bool,
1196        /// Write a JSON font-resolution report (`[{requested, step, physical,
1197        /// bold, italic, synthetic, substituted}, …]`) for this document
1198        /// (plan Step 2f).
1199        #[arg(long, value_name = "FILE")]
1200        font_report: Option<PathBuf>,
1201        /// Formats and Markdown reading.
1202        #[command(flatten)]
1203        #[serde(flatten)]
1204        markdown: MarkdownArgs,
1205        /// How a PDF or PNG output is rendered.
1206        #[command(flatten)]
1207        #[serde(flatten)]
1208        render: RenderArgs,
1209        /// Exit 4 when a requested font was substituted (listed on stderr
1210        /// and in --report). Every output is still written. Exit status:
1211        /// 0 ok, 1 error, 4 a requested font was substituted.
1212        #[arg(long)]
1213        fail_on_substitution: bool,
1214        /// Refresh the cached results of PAGEREF, REF, NUMPAGES, SEQ and TOC
1215        /// fields from jubarte's layout (TOCs rebuilt from the headings) in
1216        /// the .docx written, after --track-changes. Field codes stay, so
1217        /// Word can update them again; page numbers are jubarte's layout, not
1218        /// Word's (docs/WORD_DIFFERENCES.md). Prints one line per field;
1219        /// --report writes `{page_count, fields}`.
1220        #[arg(long)]
1221        update_fields: bool,
1222        /// Give up after this many seconds: exit 124 (as `timeout(1)`) with
1223        /// nothing more written. An output being written at that moment
1224        /// may be left partial.
1225        #[arg(long, value_name = "SECONDS", value_parser = parse_timeout)]
1226        #[serde(serialize_with = "serialize_timeout")]
1227        timeout: Option<std::time::Duration>,
1228    },
1229    /// Review differences as GitHub, word, normal, context or side-by-side text.
1230    #[command(after_help = "Examples:\n  \
1231        jubarte diff old.docx new.docx --format github   Git/GitHub patch on stdout\n  \
1232        jubarte diff old.md new.md                       the patch on stdout\n  \
1233        jubarte diff old.md new.md --format critic       CriticMarkup on stdout, as pandiff\n  \
1234        jubarte diff old.docx new.docx -o changes.patch  the patch in a file\n  \
1235        jubarte compare old.md new.md -o changes.docx    Word tracked changes (compare writes redlines)\n  \
1236        jubarte compare contract.docx edited.md -o redline.pdf\n      \
1237        the Markdown's edits painted on the Word document\n\n\
1238        GIT:\n  \
1239        git config --global difftool.jubarte.cmd 'jubarte diff \"$LOCAL\" \"$REMOTE\"'\n  \
1240        git difftool -t jubarte -y -- '*.md'")]
1241    Diff {
1242        /// The old document: .docx or Markdown.
1243        #[arg(value_name = "OLD")]
1244        old: PathBuf,
1245        /// The new document: .docx or Markdown.
1246        #[arg(value_name = "NEW")]
1247        new: PathBuf,
1248        /// Write the view to FILE (.md, .markdown, .txt, .patch or .diff;
1249        /// stdout otherwise).
1250        #[arg(short = 'o', long, value_name = "FILE", help_heading = "Review")]
1251        output: Option<PathBuf>,
1252        /// Choose the review view; word accepts ALL input changes first.
1253        #[arg(long, value_enum, value_name = "FORMAT", default_value_t = PatchFormat::Patch, help_heading = "Review")]
1254        format: PatchFormat,
1255        /// Wrap the patch's lines at this many columns; 0 does not wrap.
1256        #[arg(long, value_name = "N", default_value_t = crate::markdown::DEFAULT_COLUMNS, help_heading = "Paragraph patch")]
1257        columns: usize,
1258        /// Unchanged lines around GitHub or context hunks; -U0 shows changes only.
1259        #[arg(short = 'U', long, value_name = "LINES", default_value_t = 3, value_parser = parse_context, help_heading = "Review")]
1260        context: usize,
1261        /// Accept both documents' changes before comparing. Word format always does this.
1262        #[arg(long, help_heading = "Review")]
1263        accept_changes: bool,
1264        /// Show complete lines instead of a 70-character window around changes.
1265        #[arg(long, help_heading = "Review")]
1266        full_lines: bool,
1267        /// Output format: md only (the patch, CriticMarkup or a text view
1268        /// are all text).
1269        // Every format parses, so another one is refused naming compare.
1270        #[arg(
1271            short = 't',
1272            long = "to",
1273            value_enum,
1274            value_name = "FORMAT",
1275            hide_possible_values = true,
1276            help_heading = "Formats"
1277        )]
1278        to: Option<Format>,
1279        /// Input format of both documents [default: from each file].
1280        #[arg(
1281            short = 'f',
1282            long = "from",
1283            value_parser = input_format_parser(),
1284            value_name = "FORMAT",
1285            help_heading = "Formats"
1286        )]
1287        from: Option<Format>,
1288        /// Overwrite the output file if it already exists.
1289        #[arg(long, help_heading = "Review")]
1290        force: bool,
1291        /// Who made the changes: the patch's owner.
1292        #[arg(
1293            short = 'a',
1294            long,
1295            value_name = "NAME",
1296            default_value = "Jubarte",
1297            help_heading = "Paragraph patch"
1298        )]
1299        author: String,
1300        /// Revision timestamp (ISO 8601) [default: now, UTC]; pin it for
1301        /// reproducible output.
1302        #[arg(
1303            short = 'd',
1304            long = "datetime",
1305            value_name = "ISO8601",
1306            value_parser = parse_datetime,
1307            help_heading = "Paragraph patch"
1308        )]
1309        datetime: Option<String>,
1310    },
1311    /// Read the agent view: YAML header, `<!-- pN -->` id lines, changes and comments with ids
1312    ///
1313    /// A YAML header, then Markdown with an `<!-- pN -->` id line before every
1314    /// paragraph, tracked changes as CriticMarkup
1315    /// followed by their ids (`{++text++}{r12 @AC}`) and comments with
1316    /// theirs (`{>>c5 @AC: …<<}`).
1317    #[command(aliases = ["text", "inspect"])]
1318    Read {
1319        /// The document (.docx) to read.
1320        #[arg(value_name = "FILE")]
1321        file: PathBuf,
1322        /// Write the view to FILE.md, or the snapshot to FILE.json,
1323        /// instead of printing it.
1324        #[arg(short = 'o', long, value_name = "FILE")]
1325        output: Option<PathBuf>,
1326        /// Overwrite the output file if it already exists.
1327        #[arg(long)]
1328        force: bool,
1329        /// The view's options.
1330        #[command(flatten)]
1331        #[serde(flatten)]
1332        args: ReadArgs,
1333    },
1334    /// Edit a document: -p WHERE with --anchor, --content, --delete,
1335    /// --resolve, --reply, --accept, --reject, --strike, --restore or --style
1336    /// (several -p per command), or a JSON plan. Writes FILE_modified.docx
1337    /// (--in-place replaces FILE; --out-dir: the bundle), then prints SUCCESS
1338    /// and a fenced before/after diff of the full agent views (refusal: exit 3).
1339    #[command(after_help = "Examples:\n  \
1340        jubarte edit a.docx -p p12 --anchor \"thirty days\" --content \"forty-five days\" -a NAME\n  \
1341        jubarte edit a.docx -p p12 --anchor thirty --content \"thirty (30)\" -a NAME   an insertion\n  \
1342        jubarte edit a.docx -p p7 --anchor \"at its sole discretion\" --delete -p p9 --delete -a NAME\n  \
1343        jubarte edit a.docx -p p3 --content \"The parties agree as follows.\" -a NAME    rewrite\n  \
1344        jubarte edit a.docx -p p4 --anchor Fees --style bold -p p5 --style Heading2 -a NAME\n  \
1345        jubarte edit a.docx -p c5 --content \"Agreed.\" -p c7 --resolve -a NAME\n  \
1346        jubarte edit a.docx -p c5 --reply \"Agreed, will fix.\" -a NAME\n  \
1347        jubarte edit a.docx -p c5.text --content \"net 30\" -a NAME   the text c5 covers\n  \
1348        jubarte edit a.docx -p r3 --accept -p header1.r1 --reject\n  \
1349        jubarte edit a.docx -p p3 --delete -o b.docx --pdf -a NAME   b.docx and b.pdf\n  \
1350        jubarte edit a.docx --plan plan.json --out-dir review   the bundle in review/\n  \
1351        jubarte edit a.docx --plan plan.json -p p3 --content \"New.\"   record into plan.json\n  \
1352        jubarte edit a.docx --plan plan.json --consume   apply plan.json, then delete it\n\n\
1353        WHERE is an id from `jubarte read`: p12, header1, footer2.p1,\n\
1354        t0.row1.cell2, c5 (a comment), c5.text (the text it covers) or r12\n\
1355        (a revision).\n\n\
1356        A plan (--plan plan.json) is a list of operations, applied all or none;\n\
1357        `jubarte capabilities --json` lists every operation kind:\n  \
1358        {\"schema_version\": 1, \"source_sha256\": \"<sha256 from jubarte read>\", \"author\": \"Claude\",\n   \
1359        \"operations\": [\n    \
1360        {\"kind\": \"replace\", \"paragraph\": \"p1\", \"find\": \"his or her\", \"replacement\": \"their\"},\n    \
1361        {\"kind\": \"delete_paragraph\", \"paragraph\": \"p2\"}]}\n\n\
1362        Desired-text plans (PlanV2), a separate workflow:\n  \
1363        jubarte edit template FILE --select p12,p20-p25 -o edits.json   the paragraphs as they read\n  \
1364        (edit the desired text in edits.json)\n  \
1365        jubarte edit apply FILE --plan edits.json -o OUTPUT.docx        tracked changes for the difference\n\n\
1366        Typed actions: jubarte edit replace|rewrite|insert|delete FILE [OPTIONS]\n  Inline --save-plan FILE saves without applying; writes require -o or --out-dir.\n  Run jubarte edit ACTION --help for its grammar.\nRouting: valid legacy calls, including `edit replace -p p0 --content TEXT`,\n  retain v1 semantics. Use ./replace (or ./rewrite, ./insert, ./delete, ./apply)\n  to explicitly name a legacy input whose name equals an action.")]
1367    Edit {
1368        /// The source document (.docx). Left unchanged unless --in-place.
1369        #[arg(value_name = "FILE")]
1370        file: PathBuf,
1371        /// Edit plan JSON: a list of operations of any kind (see
1372        /// `jubarte capabilities --json`). Alone, it is applied to FILE; with
1373        /// operation flags, they are recorded into it (created on first use)
1374        /// and FILE is left as it is. Without a value: FILE_plan.json beside
1375        /// FILE.
1376        #[arg(long, value_name = "PLAN.json", num_args = 0..=1, default_missing_value = "", value_parser = plan_path(), required_unless_present_any = ["location", "anchor"])]
1377        plan: Option<PathBuf>,
1378        /// `--plan` was given without a value (D16): the summary says so.
1379        #[arg(skip)]
1380        plan_default: bool,
1381        /// Delete PLAN.json once it has been applied and the outputs are
1382        /// written (with --plan and no operation flags). Kept when
1383        /// --skip-failed left operations out.
1384        #[arg(long, requires = "plan")]
1385        consume: bool,
1386        /// Where: p12, header1, footer2.p1, t0.row1.cell2, c5 (a comment),
1387        /// c5.text (the text c5 covers) or r12 (a revision, with --accept,
1388        /// --reject, --strike or --restore). Each -p starts an operation; the
1389        /// flags after it belong to it.
1390        #[arg(short = 'p', long = "location", value_name = "WHERE", action = clap::ArgAction::Append)]
1391        location: Vec<String>,
1392        /// Text inside WHERE the operation applies to (must occur once,
1393        /// unless --occurrence picks a match).
1394        #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1395        anchor: Vec<String>,
1396        /// Pick the Nth anchor match (1-based), after --anchor in this -p group.
1397        #[arg(long, value_name = "N", action = clap::ArgAction::Append, value_parser = edit_actions::positive)]
1398        occurrence: Vec<usize>,
1399        /// New text: replaces the anchor; rewrites the paragraph without
1400        /// one; on c5, the comment's new text.
1401        #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1402        content: Vec<String>,
1403        /// Delete the anchor, or the whole paragraph (or comment) without one.
1404        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1405        delete: Vec<bool>,
1406        /// Resolve comment c5 (with -p c5).
1407        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1408        resolve: Vec<bool>,
1409        /// Reply to comment c5 (with -p c5), as `add -p c5 --content`.
1410        #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1411        reply: Vec<String>,
1412        /// Accepted and ignored. Deleting, resolving or rewording another
1413        /// author's comment is allowed unless --keep-others is set. Kept so
1414        /// older scripts still parse.
1415        #[arg(long, hide = true)]
1416        rewrite_others_comments: bool,
1417        /// Refuse to accept or reject another author's tracked change, and
1418        /// to delete, resolve, reopen or reword their comment. Restore,
1419        /// strike, a comment and a reply stay allowed. JUBARTE_KEEP_OTHERS=1
1420        /// sets the same guard. Another author is anyone other than
1421        /// --author (Jubarte when --author is left out).
1422        #[arg(long)]
1423        keep_others: bool,
1424        /// Accept revision r12 (with -p r12; r1+2 for several); prints the
1425        /// resolved change (`accepted r1+2 in p3: "from" > "to"`).
1426        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1427        accept: Vec<bool>,
1428        /// Reject revision r12 (with -p r12; r1+2 for several); prints the
1429        /// resolved change (`rejected r0 in p3: "from" > "to"`).
1430        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1431        reject: Vec<bool>,
1432        /// Strike another author's insertion r12 (with -p r12; r10+11 for a
1433        /// change of several marks, a replacement's insertion only): our
1434        /// tracked deletion inside it, so the decision shows. --content is
1435        /// one comment on the struck words.
1436        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1437        strike: Vec<bool>,
1438        /// Restore another author's deletion r12 (with -p r12; r10+11 for a
1439        /// change of several marks, a replacement's deletion only): their
1440        /// deletion stays and our tracked insertion of its words follows it.
1441        /// --content is one comment on the restored words.
1442        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1443        restore: Vec<bool>,
1444        /// With --reject: strike each insertion and restore each deletion
1445        /// instead of removing the change without a trace.
1446        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1447        visible: Vec<bool>,
1448        /// Formatting for the anchored text: bold, italic, underline, strike,
1449        /// caps, highlight=yellow, font=Calibri, size=11, color=FF0000; any
1450        /// other value is a paragraph style (Heading2).
1451        #[arg(long, value_name = "SPEC", action = clap::ArgAction::Append)]
1452        style: Vec<String>,
1453        /// Author, datetime, mode and output options.
1454        #[command(flatten)]
1455        #[serde(flatten)]
1456        options: EditOptions,
1457        /// Resolve and report only; write nothing. When every operation
1458        /// passes, stderr ends with the command that applies it (`next:`).
1459        #[arg(long)]
1460        dry_run: bool,
1461        /// Apply every operation that passes; leave out the ones that fail
1462        /// and every operation of their "group". Exit 0 when one landed.
1463        /// The failed ones go to PLAN.failed.json (FILE_plan.failed.json for
1464        /// operation flags): a plan to fix and run on the output.
1465        #[arg(long)]
1466        skip_failed: bool,
1467        /// Refuse when the edit would change nothing in the document
1468        /// (NO_CHANGES_REQUESTED); reports, renders and bundles do not
1469        /// count as a change.
1470        #[arg(long)]
1471        require_change: bool,
1472        /// Also write the PDF beside the document (the bundle: redline.pdf
1473        /// and clean.pdf).
1474        #[arg(long)]
1475        pdf: bool,
1476        /// Also write PNG pages beside the document, STEM-page-NN.png (the
1477        /// bundle: redline-page-NN.png and clean-page-NN.png).
1478        #[arg(long)]
1479        png: bool,
1480        /// PNG resolution in dots per inch (1-1200).
1481        #[arg(long, default_value_t = 96.0, value_name = "DPI", value_parser = parse_dpi, help_heading = "Rendering")]
1482        dpi: f32,
1483        /// How tracked changes are painted in the redline PDF/PNG.
1484        #[arg(long, value_enum, default_value_t = Revisions::Conventional, requires_if("custom", "revision_palette"), help_heading = "Revision marks")]
1485        revisions: Revisions,
1486        /// Marks for --revisions custom (see `convert --help`).
1487        #[cfg_attr(feature = "render", arg(long, value_name = "SPEC", value_parser = parse_palette, requires = "revisions", help_heading = "Revision marks"))]
1488        #[cfg_attr(
1489            not(feature = "render"),
1490            arg(
1491                long,
1492                value_name = "SPEC",
1493                requires = "revisions",
1494                help_heading = "Revision marks"
1495            )
1496        )]
1497        revision_palette: Option<String>,
1498        /// The operations the flags describe, grouped by -p (filled after
1499        /// parsing).
1500        #[arg(skip)]
1501        operations: Vec<FlagOp>,
1502    },
1503    /// Add a paragraph, a comment or a reply: -p WHERE --content TEXT
1504    /// (several -p per command). Writes FILE_modified.docx, as edit does
1505    /// (--in-place replaces FILE), and prints SUCCESS and a fenced
1506    /// before/after diff of the full agent views.
1507    #[command(after_help = "Examples:\n  \
1508        jubarte add a.docx -p p12 --content \"Time is of the essence.\" -a NAME   new paragraph after p12\n  \
1509        jubarte add a.docx -p p12 --content Recitals --before --style Heading2 -a NAME\n  \
1510        jubarte add a.docx -p p5 --anchor \"monthly fee\" --content \"Net of taxes?\" -a NAME   a comment\n  \
1511        jubarte add a.docx -p p5 --comment --content \"Whole clause needs a cap.\" -a NAME\n  \
1512        jubarte add a.docx -p c5 --content \"Agreed, will fix.\" -a NAME           a reply\n  \
1513        jubarte add a.docx -p c5 --reply \"Agreed, will fix.\" -a NAME             the same reply\n  \
1514        jubarte add a.docx --plan plan.json -p p5 --comment --content \"Cap?\"   record into plan.json")]
1515    Add {
1516        /// The source document (.docx). Left unchanged unless --in-place.
1517        #[arg(value_name = "FILE")]
1518        file: PathBuf,
1519        /// Edit plan JSON. With operation flags, they are recorded into it
1520        /// (created on first use) and FILE is left as it is; alone, it is
1521        /// applied to FILE, as `edit --plan` does. Without a value:
1522        /// FILE_plan.json beside FILE.
1523        #[arg(long, value_name = "PLAN.json", num_args = 0..=1, default_missing_value = "", value_parser = plan_path())]
1524        plan: Option<PathBuf>,
1525        /// `--plan` was given without a value (D16): the summary says so.
1526        #[arg(skip)]
1527        plan_default: bool,
1528        /// Delete PLAN.json once it has been applied and the outputs are
1529        /// written (with --plan and no operation flags).
1530        #[arg(long, requires = "plan")]
1531        consume: bool,
1532        /// Where: p12, header1, footer2.p1, t0.row1.cell2, or c5 for a reply.
1533        /// Each -p starts an operation; the flags after it belong to it.
1534        #[arg(short = 'p', long = "location", value_name = "WHERE", action = clap::ArgAction::Append, required_unless_present_any = ["plan", "anchor"])]
1535        location: Vec<String>,
1536        /// Text inside WHERE to comment on (must occur once, unless
1537        /// --occurrence picks a match).
1538        #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1539        anchor: Vec<String>,
1540        /// Pick the Nth anchor match (1-based), after --anchor in this -p group.
1541        #[arg(long, value_name = "N", action = clap::ArgAction::Append, value_parser = edit_actions::positive)]
1542        occurrence: Vec<usize>,
1543        /// The paragraph, comment or reply text.
1544        #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1545        content: Vec<String>,
1546        /// Reply to comment c5 (with -p c5); the same as --content there.
1547        #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1548        reply: Vec<String>,
1549        /// Refuse to accept or reject another author's tracked change, and
1550        /// to delete, resolve, reopen or reword their comment, when this
1551        /// command applies or records a plan. Restore, strike, a comment
1552        /// and a reply stay allowed. JUBARTE_KEEP_OTHERS=1 sets the same
1553        /// guard. Another author is anyone other than --author (Jubarte
1554        /// when --author is left out).
1555        #[arg(long)]
1556        keep_others: bool,
1557        /// A new paragraph before WHERE instead of after it.
1558        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1559        before: Vec<bool>,
1560        /// A comment on the whole paragraph (with --anchor the comment sits
1561        /// on the anchor and this flag is implied).
1562        #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1563        comment: Vec<bool>,
1564        /// Formatting for the new paragraph's text (bold, italic, underline,
1565        /// highlight=yellow) or its paragraph style (Heading2).
1566        #[arg(long, value_name = "SPEC", action = clap::ArgAction::Append)]
1567        style: Vec<String>,
1568        /// Author, datetime, mode and output options.
1569        #[command(flatten)]
1570        #[serde(flatten)]
1571        options: EditOptions,
1572        /// The operations the flags describe, grouped by -p (filled after
1573        /// parsing).
1574        #[arg(skip)]
1575        operations: Vec<FlagOp>,
1576    },
1577    /// What this binary can do, for agents choosing an operation.
1578    Capabilities {
1579        /// The manifest or focused answer as JSON instead of text.
1580        #[arg(long)]
1581        json: bool,
1582        /// Discover one edit kind, including its fields and execution conditions.
1583        #[arg(long)]
1584        operation: Option<String>,
1585        /// Discover one field, optionally within --operation.
1586        #[arg(long)]
1587        field: Option<String>,
1588        /// Publish operation × target × policy edit support.
1589        #[arg(long, conflicts_with_all = ["operation", "field"])]
1590        matrix: bool,
1591    },
1592    /// Check or install a release from GitHub.
1593    #[command(after_help = "Examples:\n  \
1594        jubarte self-update --check          installed and latest versions\n  \
1595        jubarte self-update                  ask, then install the latest release\n  \
1596        jubarte self-update --yes            install without asking\n  \
1597        jubarte self-update --version 0.9.3  install that release (also older)")]
1598    #[command(display_order = 1000)]
1599    SelfUpdate {
1600        /// Print the installed and latest versions; install nothing.
1601        #[arg(long)]
1602        check: bool,
1603        /// Install without asking (needed without a terminal).
1604        #[arg(long, short = 'y')]
1605        yes: bool,
1606        /// Install this release instead of the latest, older ones included.
1607        #[arg(long, value_name = "VERSION")]
1608        version: Option<String>,
1609    },
1610    /// Diagnose a Word package, or compare package structures.
1611    #[command(after_help = "Examples:\n  \
1612        jubarte debug out.docx                    orphans, fields, bookmarks, package, structure\n  \
1613        jubarte debug out.docx --list             the package's entries\n  \
1614        jubarte debug old.docx new.docx --list    entries that differ\n  \
1615        jubarte debug old.docx new.docx -c elements -p document.xml\n  \
1616        jubarte debug out.docx -c ids             revision/docPr ids used twice\n  \
1617        jubarte debug out.docx -c textbox -g FILENAME\n  \
1618        jubarte debug out.docx -c text            paragraphs with ins/del marks\n  \
1619        jubarte debug a.docx b.docx -c text       paragraphs that differ, per part\n  \
1620        jubarte debug a.docx b.docx -c runs       the same, with direct formatting\n  \
1621        jubarte debug out.docx -c runs -g \"Q: Can\"   one paragraph's runs, whole\n  \
1622        jubarte debug out.docx -c changes         what each pPrChange/tcPrChange/… records\n  \
1623        jubarte debug a.docx b.docx -c styledefs  style definitions that differ, paired by name\n  \
1624        jubarte debug a.docx b.docx -c numbering  list levels that differ, by numId\n  \
1625        jubarte debug a.docx b.docx -c xml -p document.xml\n  \
1626        jubarte debug diff a.docx ours.docx word.docx   element by element, three-way")]
1627    #[command(
1628        hide = true,
1629        args_conflicts_with_subcommands = true,
1630        subcommand_negates_reqs = true
1631    )]
1632    Debug {
1633        /// Optional package comparison task.
1634        #[command(subcommand)]
1635        sub: Option<DebugCommand>,
1636        /// One package, or two to compare (A then B).
1637        #[arg(value_name = "FILE", num_args = 1..=2, required = true)]
1638        files: Vec<PathBuf>,
1639        /// List the package's entries (sizes); with two files, the entries
1640        /// that differ.
1641        #[arg(short = 'l', long)]
1642        list: bool,
1643        /// Reports to run [default: orphans, fields, bookmarks, package,
1644        /// structure].
1645        #[arg(short = 'c', long = "check", value_enum, value_delimiter = ',')]
1646        checks: Vec<DebugCheck>,
1647        /// Only parts whose name contains this (e.g. document.xml).
1648        #[arg(short = 'p', long, value_name = "NAME")]
1649        part: Option<String>,
1650        /// Only what contains this: textbox stories; text/runs/xml/changes/tables/styledefs/numbering lines (a runs paragraph matched on its plain text, printed whole).
1651        #[arg(short = 'g', long, value_name = "TEXT")]
1652        grep: Option<String>,
1653        /// Examples per finding kind.
1654        #[arg(short = 'n', long, value_name = "N", default_value_t = 5)]
1655        limit: usize,
1656        /// text/xml/runs of two files: common lines shown around each change.
1657        #[arg(short = 'C', long, value_name = "N", default_value_t = 0)]
1658        context: usize,
1659        /// text/xml/runs/changes/styledefs/numbering/render: show complete
1660        /// lines instead of clipping them at 200 characters.
1661        #[arg(long)]
1662        full_lines: bool,
1663    },
1664    /// Compare rendered pages pixel by pixel (different pages: exit 5).
1665    #[command(
1666        name = "visual-diff",
1667        alias = "diff-render",
1668        after_help = "Examples:\n  \
1669        jubarte visual-diff before.docx after.docx                  changed pages on stdout\n  \
1670        jubarte visual-diff before.docx after.docx --out-dir diff   PNGs of the changed pages and diff.json\n  \
1671        jubarte visual-diff a.docx b.docx --json                    the diff.json document on stdout\n\n\
1672        With --out-dir, each page that differs is written as a-page-NN.png,\n\
1673        b-page-NN.png and diff-page-NN.png (b's page with the changed pixels\n\
1674        magenta and boxed); diff.json lists every page with its changed_ratio,\n\
1675        bbox and, for a page only one side has, only_in."
1676    )]
1677    VisualDiff {
1678        /// The document before.
1679        #[arg(value_name = "A")]
1680        a: PathBuf,
1681        /// The document after.
1682        #[arg(value_name = "B")]
1683        b: PathBuf,
1684        /// Raster resolution of both sides in dots per inch (1-1200).
1685        #[arg(long, default_value_t = 100.0, value_name = "DPI", value_parser = parse_dpi, help_heading = "Rendering")]
1686        dpi: f32,
1687        /// Write the changed pages' PNGs and diff.json here (created if
1688        /// missing).
1689        #[arg(long, value_name = "DIR")]
1690        out_dir: Option<PathBuf>,
1691        /// Print diff.json to stdout instead of one line per changed page.
1692        #[arg(long)]
1693        json: bool,
1694        /// Skip the diff-page-NN.png overlays.
1695        #[arg(long)]
1696        no_overlay: bool,
1697        /// Overwrite files already in --out-dir.
1698        #[arg(long)]
1699        force: bool,
1700    },
1701    /// List comments, threads and the text they annotate.
1702    Comments {
1703        /// The document (.docx).
1704        #[arg(value_name = "FILE")]
1705        file: PathBuf,
1706        /// Emit one record per line on stdout (records only). The input_validity
1707        /// status is one JSON line on stderr; -q silences it.
1708        #[arg(long)]
1709        json: bool,
1710        /// Only this author's comments (exact match).
1711        #[arg(long, value_name = "NAME")]
1712        author: Option<String>,
1713        /// One comment per thread: the newest.
1714        #[arg(long)]
1715        latest: bool,
1716    },
1717    /// Join documents in order, preserving images, styles, lists and notes.
1718    #[command(after_help = "Examples:\n  \
1719        jubarte append a.docx b.docx -o ab.docx\n  \
1720        jubarte append cover.docx body.docx annex.docx -o all.docx --section-break continuous\n  \
1721        jubarte append letter.docx exhibit.docx -o out.docx --keep-sections\n  \
1722        jubarte append review_a.docx review_b.docx -o both.docx --carry-comments")]
1723    Append {
1724        /// The documents (.docx), in order.
1725        #[arg(value_name = "FILE", num_args = 2.., required = true)]
1726        files: Vec<PathBuf>,
1727        /// Output path; its extension picks the format: .docx (also any
1728        /// other), .md (the agent view), .pdf, .png (one file per page) or
1729        /// .json (the snapshot).
1730        #[arg(short = 'o', long, value_name = "FILE")]
1731        output: PathBuf,
1732        /// What separates each document from the one before it.
1733        #[arg(long, value_enum, default_value_t = SectionBreakArg::NextPage)]
1734        section_break: SectionBreakArg,
1735        /// Keep each appended document's final section (page size, margins,
1736        /// headers, footers) as a section of its own.
1737        #[arg(long)]
1738        keep_sections: bool,
1739        /// Carry the comments each appended document's body and notes
1740        /// anchor, with their threads and resolution (those in headers and
1741        /// footers are still dropped). Off, comments are dropped and warned.
1742        #[arg(long)]
1743        carry_comments: bool,
1744        /// Overwrite the output file if it already exists.
1745        #[arg(long)]
1746        force: bool,
1747        /// How a .pdf or .png output is drawn.
1748        #[command(flatten)]
1749        #[serde(flatten)]
1750        render: RenderArgs,
1751    },
1752    /// Check Word validity, tracked edits, accessibility, style and
1753    /// structure; or repair Word validity.
1754    ///
1755    /// A word or edits finding fails the run (exit 2), and so does any
1756    /// error; --strict fails on warnings too. With --baseline, only the
1757    /// findings the baseline lacks count. An unreadable file exits 1.
1758    #[command(alias = "audit")]
1759    #[command(after_help = "Examples:\n  \
1760        jubarte validate contract.docx\n  \
1761        jubarte validate contract.docx --json\n  \
1762        jubarte validate contract.docx --repair fixed.docx\n  \
1763        jubarte validate review/redline.docx --original contract.docx --author Claude\n  \
1764        jubarte validate review/redline.docx --baseline contract.docx\n  \
1765        jubarte validate contract.docx --rules word,a11y,style,structure --strict\n\n\
1766        Rule sets: word (default: Word validity), edits (with --author, and \
1767        --original or --baseline), a11y, style, structure.\n\
1768        Audit codes (code, set, severity):\n  \
1769        HEADING_SKIP a11y warning, IMAGE_NO_DESCR a11y error,\n  \
1770        TABLE_NO_HEADER_ROW a11y warning, MISSING_LANG a11y warning,\n  \
1771        LITERAL_BULLET style warning, EMPTY_SPACER_PARAGRAPH style info,\n  \
1772        DIRECT_FORMATTING_OVERRIDES_STYLE style info,\n  \
1773        STALE_FIELD_CACHE structure warning, FONT_SUBSTITUTED structure info")]
1774    #[command(group(clap::ArgGroup::new("edits_against").args(["original", "baseline"]).multiple(true)))]
1775    Validate {
1776        /// The document (.docx).
1777        #[arg(value_name = "FILE")]
1778        file: PathBuf,
1779        /// JSON Lines: one object per finding, nothing when there is none.
1780        #[arg(long)]
1781        json: bool,
1782        /// Rule sets or audit codes, comma-separated [default: word; with
1783        /// --original, or --baseline and --author, word and edits].
1784        #[arg(long, value_name = "RULES", value_delimiter = ',', value_parser = parse_rule)]
1785        rules: Vec<String>,
1786        /// Also fail (exit 2) on warnings from other rule sets; word and edits
1787        /// findings fail without it.
1788        #[arg(long)]
1789        strict: bool,
1790        /// Write the repaired package here; remaining findings still fail.
1791        ///
1792        /// A structural repair: it does not check the edits' history.
1793        /// Add --original and --author for that.
1794        #[arg(long, value_name = "FILE")]
1795        repair: Option<PathBuf>,
1796        /// The document the edits started from: its findings print as
1797        /// already in the input (not yours), and only new ones fail the run.
1798        /// A finding is new by identity (code, part, place and message),
1799        /// never by count. With --author and no --original, the edits are
1800        /// checked against it too.
1801        #[arg(long, value_name = "FILE", conflicts_with = "repair")]
1802        baseline: Option<PathBuf>,
1803        /// Check tracked edits: every text change against ORIGINAL must be a
1804        /// revision by --author.
1805        #[arg(long, value_name = "FILE", requires = "author")]
1806        original: Option<PathBuf>,
1807        /// The author every change must carry (with --original or
1808        /// --baseline).
1809        #[arg(long, value_name = "NAME", requires = "edits_against")]
1810        author: Option<String>,
1811        /// Replace an existing --repair output.
1812        #[arg(long)]
1813        force: bool,
1814    },
1815    /// Check a document against a source-bound expectation contract.
1816    ///
1817    /// The only profile this build supports is `--expect`: an optional,
1818    /// separately supplied, hash-bound expectations file whose typed
1819    /// paragraph-text predicates (exact equality, containment, absence)
1820    /// are evaluated on FILE's own final projection. The other check
1821    /// profiles (integrity, quality, layout, baseline tracking) are #961;
1822    /// `jubarte validate` remains the validity audit. Passing checks and
1823    /// natural-language requirements without executable checks never claim
1824    /// the task complete.
1825    #[command(after_help = "Examples:\n  \
1826        jubarte check revised.docx --expect expectations.json\n  \
1827        jubarte check revised.docx --expect expectations.json --json\n\n\
1828        The expectations' source.sha256 must name FILE's own bytes: an\n\
1829        expectation file bound to the pre-edit source refuses as stale on\n\
1830        the edited output. Use the output-bound copy an `edit apply --expect`\n\
1831        receipt carries to re-check a published output.")]
1832    Check {
1833        /// The document (.docx) whose own digest the expectations must name.
1834        #[arg(value_name = "FILE")]
1835        file: PathBuf,
1836        /// Expectation contract (the only supported profile in this build).
1837        #[arg(long, value_name = "FILE")]
1838        expect: Option<PathBuf>,
1839        /// One result envelope, including refusals.
1840        #[arg(long)]
1841        json: bool,
1842    },
1843    /// Remove authors, editing IDs, metadata and comments before sharing.
1844    #[command(after_help = "Examples:\n  \
1845        jubarte scrub redline.docx -o out.docx                     everything, alias Author\n  \
1846        jubarte scrub redline.docx -o out.docx --author-alias Counsel --rsids\n  \
1847        jubarte scrub redline.docx -o out.docx --comments          comments only")]
1848    Scrub {
1849        /// The document (.docx) to scrub.
1850        #[arg(value_name = "FILE")]
1851        file: PathBuf,
1852        /// Output path; its extension picks the format: .docx (also any
1853        /// other), .md (the agent view), .pdf, .png (one file per page) or
1854        /// .json (the snapshot).
1855        #[arg(short = 'o', long, value_name = "FILE")]
1856        output: PathBuf,
1857        /// Overwrite the output file if it already exists.
1858        #[arg(long)]
1859        force: bool,
1860        /// Metadata and comment scrub selection.
1861        #[command(flatten)]
1862        #[serde(flatten)]
1863        scrub: ScrubSelection,
1864        /// How a .pdf or .png output is drawn.
1865        #[command(flatten)]
1866        #[serde(flatten)]
1867        render: RenderArgs,
1868    },
1869}
1870
1871/// What `jubarte scrub` removes; everything when no flag is given.
1872#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
1873pub struct ScrubSelection {
1874    /// Name every author (revisions, comments, people.xml) takes.
1875    #[arg(long, value_name = "NAME")]
1876    pub author_alias: Option<String>,
1877    /// Remove rsids, the edit-session ids that tie copies together.
1878    #[arg(long)]
1879    pub rsids: bool,
1880    /// Remove creator, last editor, revision number, dates, manager,
1881    /// company and custom properties.
1882    #[arg(long)]
1883    pub docprops: bool,
1884    /// Remove every comment.
1885    #[arg(long)]
1886    pub comments: bool,
1887}
1888
1889#[derive(clap::Subcommand, Debug, Serialize)]
1890#[serde(rename_all = "kebab-case", tag = "command", content = "args")]
1891/// Package-level diagnostic comparison tasks.
1892pub enum DebugCommand {
1893    /// What differs between two or more packages, element by element:
1894    /// styles paired by type and name, paragraphs by their text, headers
1895    /// and footers by section role. Each hunk prints the lines not every
1896    /// file holds; with three or more files each line names the files that
1897    /// hold it. rsids, paragraph ids, revision ids/authors/dates,
1898    /// relationship ids (shown as what they point to), docProps save
1899    /// stamps, attribute order, on/off values and empty property blocks
1900    /// are dropped unless --raw.
1901    #[command(after_help = "Examples:\n  \
1902        jubarte debug diff a.docx b.docx\n  \
1903        jubarte debug diff a.docx ours_rej.docx word_rej.docx -p styles\n  \
1904        jubarte debug diff a.docx ours_rej.docx word_rej.docx --style \"Body Text\" --full\n  \
1905        jubarte debug diff a.docx ours.docx --para-text \"Section 4\"")]
1906    Diff {
1907        /// Two or more packages; the first is the reference (`-` lines).
1908        #[arg(value_name = "FILE", num_args = 2.., required = true)]
1909        files: Vec<PathBuf>,
1910        /// Only parts whose name or role contains this (e.g. styles,
1911        /// document.xml, "default header").
1912        #[arg(short = 'p', long, value_name = "NAME")]
1913        part: Option<String>,
1914        /// Only the style with this name or id (case-insensitive).
1915        #[arg(long, value_name = "NAME")]
1916        style: Option<String>,
1917        /// Only paragraphs whose text contains this, in any file.
1918        #[arg(long = "para-text", value_name = "TEXT")]
1919        para_text: Option<String>,
1920        /// Keep rsids, ids, authors, dates, on/off values and empty blocks.
1921        #[arg(long)]
1922        raw: bool,
1923        /// Print each shown element's common lines too.
1924        #[arg(long)]
1925        full: bool,
1926        /// Hunks per part (0: all).
1927        #[arg(short = 'n', long, value_name = "N", default_value_t = 60)]
1928        limit: usize,
1929    },
1930}
1931
1932/// `jubarte debug --check`.
1933#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
1934#[serde(rename_all = "kebab-case")]
1935pub enum DebugCheck {
1936    /// Deleted text outside its story's w:del; live text inside one; bare runs
1937    /// in a text box whose anchor is deleted.
1938    Orphans,
1939    /// Field nesting per story; fields partly deleted.
1940    Fields,
1941    /// Duplicate/unpaired bookmarks; start and end in different sdt, cell,
1942    /// text box or revision; bookmarks in plain-text or list controls.
1943    Bookmarks,
1944    /// Content types, relationship ids and targets, dangling note/comment
1945    /// references, undeclared mc:Ignorable prefixes.
1946    Package,
1947    /// Empty field codes, cells not ending in a paragraph, rows without cells,
1948    /// nested same-kind revisions, a body sectPr that is not last.
1949    Structure,
1950    /// Revision and docPr ids used twice (not in the default triage: Word
1951    /// opens such files).
1952    Ids,
1953    /// Style links and references naming no style; two styles with one type
1954    /// and name (Word pairs styles by name).
1955    Styles,
1956    /// Where bookmark starts and ends sit (parent chains, tallied).
1957    Chains,
1958    /// Element counts.
1959    Elements,
1960    /// Text box stories as XML (see --grep).
1961    Textbox,
1962    /// Paragraph text per story part, with {+inserted+} / [-deleted-] runs
1963    /// and the mark state; with two files, the lines that differ.
1964    Text,
1965    /// Part XML one element per line, without namespace declarations,
1966    /// rsids or paraIds; with two files, the lines that differ.
1967    Xml,
1968    /// `text` with each paragraph's direct properties [..], its mark's «..»
1969    /// and each run's direct formatting «..»; with two files, the lines that
1970    /// differ.
1971    Runs,
1972    /// Property-change records (pPrChange, tcPrChange, sectPrChange, …):
1973    /// where each sits and what the live properties add (+) and drop (-)
1974    /// against the recorded ones; with two files, the lines that differ.
1975    Changes,
1976    /// Tables per story part: the grid (and a tblGridChange's old grid),
1977    /// each row's mark, gridBefore/gridAfter and trPrChange, each cell's
1978    /// mark (cellIns +, cellDel -, cellMerge ~), span, width and vMerge with
1979    /// a tcPrChange's old ones, and its paragraphs as `text` shows them;
1980    /// with two files, the lines that differ.
1981    Tables,
1982    /// Style definitions by type and name (localized ids pair): docDefaults,
1983    /// then each style's default flag and basedOn/link by name, and a line
1984    /// per pPr/rPr/tblPr/… block; with two files, the lines that differ.
1985    Styledefs,
1986    /// List levels by numId and level as paragraphs see them (abstract
1987    /// definition plus the list's overrides; abstract ids renumber, so
1988    /// they are left out); with two files, the lines that differ.
1989    Numbering,
1990    /// What each story part should put on the page (tables with style,
1991    /// float and shading; shaded, highlighted, coloured and hidden text;
1992    /// fonts; fields; ins/del order; frames; sections), and "(layout)":
1993    /// jubarte's page count and the face each font resolved to; with two
1994    /// files, the lines that differ.
1995    Render,
1996}
1997
1998impl From<DebugCheck> for crate::debug::Check {
1999    fn from(c: DebugCheck) -> Self {
2000        use crate::debug::Check;
2001        match c {
2002            DebugCheck::Orphans => Check::Orphans,
2003            DebugCheck::Fields => Check::Fields,
2004            DebugCheck::Bookmarks => Check::Bookmarks,
2005            DebugCheck::Package => Check::Package,
2006            DebugCheck::Structure => Check::Structure,
2007            DebugCheck::Ids => Check::Ids,
2008            DebugCheck::Styles => Check::Styles,
2009            DebugCheck::Chains => Check::Chains,
2010            DebugCheck::Elements => Check::Elements,
2011            DebugCheck::Textbox => Check::Textbox,
2012            DebugCheck::Text => Check::Text,
2013            DebugCheck::Xml => Check::Xml,
2014            DebugCheck::Runs => Check::Runs,
2015            DebugCheck::Changes => Check::Changes,
2016            DebugCheck::Tables => Check::Tables,
2017            DebugCheck::Styledefs => Check::StyleDefs,
2018            DebugCheck::Numbering => Check::Numbering,
2019            #[cfg(feature = "render")]
2020            DebugCheck::Render => Check::Render,
2021            #[cfg(not(feature = "render"))]
2022            DebugCheck::Render => Check::Orphans,
2023        }
2024    }
2025}
2026
2027/// `jubarte diff --format`: what goes to stdout.
2028#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2029#[serde(rename_all = "kebab-case")]
2030pub enum PatchFormat {
2031    /// The changed paragraphs, as `git diff --word-diff` with CriticMarkup
2032    /// comments and highlights.
2033    Patch,
2034    /// CriticMarkup: current document text with tracked marks.
2035    Critic,
2036    /// Git/GitHub unified text; preserves each document's tracked marks.
2037    #[value(alias = "unified", alias = "text")]
2038    Github,
2039    /// Fresh word-level CriticMarkup after accepting ALL changes in both inputs.
2040    Word,
2041    /// Normal diff with line addresses and no context (a/d/c, < and >).
2042    Normal,
2043    /// Context diff with old/new ranges and !, + and - prefixes.
2044    Context,
2045    /// Old and new lines in parallel columns, with |, < and > markers.
2046    SideBySide,
2047}
2048
2049impl PatchFormat {
2050    /// Whether this format compares document snapshots without constructing a redline.
2051    pub fn is_text_view(self) -> bool {
2052        !matches!(self, Self::Patch | Self::Critic)
2053    }
2054}
2055
2056/// `jubarte --mode` (compare).
2057#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2058#[serde(rename_all = "kebab-case")]
2059pub enum CompareMode {
2060    /// Microsoft Word Compare's layout: word-level detail, replaced paragraphs
2061    /// merged, Word's alignment passes.
2062    Word,
2063    /// Open-Xml-PowerTools: coarse paragraph fallback (threshold 0.15), no
2064    /// Word alignment passes.
2065    Powertools,
2066}
2067
2068/// A document format for `-f/--from` and `-t/--to`.
2069#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2070#[serde(rename_all = "kebab-case")]
2071pub enum Format {
2072    /// Word (.docx).
2073    Docx,
2074    /// Markdown: CommonMark with GitHub tables, task lists and footnotes,
2075    /// and CriticMarkup.
2076    #[value(alias = "markdown")]
2077    Md,
2078    /// PDF, laid out as Word does.
2079    Pdf,
2080    /// PNG pages.
2081    Png,
2082    /// The JSON snapshot (`read --json`'s object): written, never read.
2083    /// `diff` refuses it (`json_not_yet`).
2084    Json,
2085}
2086
2087/// A file name's extension: `Path::extension`, or the whole name after its
2088/// dot when the name is only an extension (`.json`, `out/.md`), which Rust
2089/// reads as a hidden file with none.
2090fn extension(path: &Path) -> Option<String> {
2091    if let Some(extension) = path.extension() {
2092        return extension.to_str().map(str::to_string);
2093    }
2094    let name = path.file_name()?.to_str()?;
2095    name.strip_prefix('.')
2096        .filter(|rest| !rest.is_empty() && !rest.contains('.'))
2097        .map(str::to_string)
2098}
2099
2100impl Format {
2101    /// The format a file name says, by extension (`.json`, a name that is
2102    /// only an extension, says json too).
2103    pub fn of_path(path: &Path) -> Option<Self> {
2104        Self::of_name(&extension(path)?)
2105    }
2106
2107    /// The format an extension names, in any case.
2108    pub fn of_name(extension: &str) -> Option<Self> {
2109        match extension.to_ascii_lowercase().as_str() {
2110            "docx" | "docm" | "dotx" | "dotm" => Some(Self::Docx),
2111            "md" | "markdown" | "mdown" | "mkd" | "mkdn" | "txt" => Some(Self::Md),
2112            "pdf" => Some(Self::Pdf),
2113            "png" => Some(Self::Png),
2114            "json" => Some(Self::Json),
2115            _ => None,
2116        }
2117    }
2118
2119    /// The name `--to` takes and messages print.
2120    pub fn name(self) -> &'static str {
2121        match self {
2122            Self::Docx => "docx",
2123            Self::Md => "md",
2124            Self::Pdf => "pdf",
2125            Self::Png => "png",
2126            Self::Json => "json",
2127        }
2128    }
2129
2130    /// An input's format: the one asked for, else its extension, else its
2131    /// bytes (a zip is Word, anything else Markdown).
2132    pub fn of_input(asked: Option<Self>, path: &Path, bytes: &[u8]) -> Self {
2133        asked
2134            .or_else(|| Format::of_path(path).filter(|f| matches!(f, Self::Docx | Self::Md)))
2135            .unwrap_or(if bytes.starts_with(b"PK\x03\x04") {
2136                Self::Docx
2137            } else {
2138                Self::Md
2139            })
2140    }
2141}
2142
2143/// A task that writes a file through `-o`.
2144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2145pub enum Task {
2146    /// `compare` (alias `redline`): the redline.
2147    Compare,
2148    /// `convert`: the document in another format.
2149    Convert,
2150    /// `read`: the agent view.
2151    Read,
2152    /// `diff`: a text diff.
2153    Diff,
2154    /// `accept`: the document with changes accepted.
2155    Accept,
2156    /// `reject`: the document with changes rejected.
2157    Reject,
2158    /// `append`: the documents joined.
2159    Append,
2160    /// `scrub`: the document with metadata removed.
2161    Scrub,
2162}
2163
2164impl Task {
2165    /// The command's name.
2166    pub fn name(self) -> &'static str {
2167        match self {
2168            Self::Compare => "compare",
2169            Self::Convert => "convert",
2170            Self::Read => "read",
2171            Self::Diff => "diff",
2172            Self::Accept => "accept",
2173            Self::Reject => "reject",
2174            Self::Append => "append",
2175            Self::Scrub => "scrub",
2176        }
2177    }
2178
2179    /// The task a command name (or its alias) runs.
2180    pub fn of_name(name: &str) -> Option<Self> {
2181        Some(match name {
2182            "compare" | "redline" => Self::Compare,
2183            "convert" => Self::Convert,
2184            "read" | "text" | "inspect" => Self::Read,
2185            "diff" => Self::Diff,
2186            "accept" => Self::Accept,
2187            "reject" => Self::Reject,
2188            "append" => Self::Append,
2189            "scrub" => Self::Scrub,
2190            _ => return None,
2191        })
2192    }
2193
2194    /// The formats its `-o` writes (`capabilities::OUTPUT_FORMATS`).
2195    fn allowed(self) -> Vec<Format> {
2196        crate::capabilities::OUTPUT_FORMATS
2197            .iter()
2198            .find(|(task, _)| *task == self.name())
2199            .map(|(_, names)| {
2200                names
2201                    .iter()
2202                    .map(|n| Format::of_name(n).expect("OUTPUT_FORMATS names a format"))
2203                    .collect()
2204            })
2205            .unwrap_or_default()
2206    }
2207
2208    /// What `-o PATH`'s extension says for this task: `diff` reads `.patch`
2209    /// and `.diff` as text too.
2210    fn known(self, path: &Path) -> Option<Format> {
2211        let patch = extension(path)
2212            .is_some_and(|e| e.eq_ignore_ascii_case("patch") || e.eq_ignore_ascii_case("diff"));
2213        if self == Self::Diff && patch {
2214            return Some(Format::Md);
2215        }
2216        Format::of_path(path)
2217    }
2218
2219    /// The refusal for a format this task cannot write; the advice names
2220    /// the file as typed (`c.EXT`/`v.EXT` when `--to` said the format).
2221    fn cannot_write(self, format: Format, typed: Option<&str>) -> String {
2222        let ext = format.name();
2223        let named = |stem: &str| typed.map_or_else(|| format!("{stem}.{ext}"), str::to_string);
2224        match (self, format) {
2225            (Self::Diff, Format::Json) => "diff does not write .json yet".to_string(),
2226            (Self::Diff, _) => format!(
2227                "diff writes text (.md, .markdown, .txt, .patch, .diff); `compare OLD NEW -o {}` writes the redline as {ext}",
2228                named("c")
2229            ),
2230            (Self::Read, _) => {
2231                format!(
2232                    "read writes .md or .json; `convert FILE -o {}` writes {ext}",
2233                    named("v")
2234                )
2235            }
2236            _ => format!("{} does not write .{ext}", self.name()),
2237        }
2238    }
2239}
2240
2241/// The format a task writes. `-o`'s extension decides; `--to` decides when
2242/// the extension is missing or unknown; a known extension that disagrees with
2243/// `--to` is an error. `-o` with neither → the task's usual format (`convert`'s
2244/// depends on its input: `None`). No `-o` and no `--to` → `None`: the task
2245/// prints, or convert picks by input. Pure.
2246pub fn output_format(
2247    task: Task,
2248    output: Option<&Path>,
2249    to: Option<Format>,
2250) -> Result<Option<Format>, String> {
2251    let said = output.and_then(|path| task.known(path));
2252    let name = output.map(|path| {
2253        path.file_name().map_or_else(
2254            || path.display().to_string(),
2255            |n| n.to_string_lossy().into_owned(),
2256        )
2257    });
2258    if let (Some(name), Some(said), Some(to)) = (&name, said, to)
2259        && said != to
2260    {
2261        return Err(format!(
2262            "-o {name} says {} and --to says {}: drop one",
2263            said.name(),
2264            to.name()
2265        ));
2266    }
2267    let format = match (output, said.or(to)) {
2268        (None, None) => return Ok(None),
2269        (_, Some(format)) => format,
2270        (Some(_), None) => match task {
2271            Task::Convert => return Ok(None),
2272            Task::Read | Task::Diff => Format::Md,
2273            _ => Format::Docx,
2274        },
2275    };
2276    if task.allowed().contains(&format) {
2277        Ok(Some(format))
2278    } else {
2279        // The typed name only when it said the format; `--to` names its own.
2280        let typed = output
2281            .filter(|_| said == Some(format))
2282            .map(|path| path.display().to_string());
2283        Err(task.cannot_write(format, typed.as_deref()))
2284    }
2285}
2286
2287/// The error line for an input no task reads, `CODE: FILE is …`: an OLE
2288/// (`.doc`, encrypted) or RTF file, or, when it must be `word`, a file that
2289/// is no ZIP package. `None` when the bytes may be read. Every host prints
2290/// this line, so a refusal reads the same on each.
2291#[must_use]
2292pub fn refused_input(path: &Path, bytes: &[u8], word: bool) -> Option<String> {
2293    let checked = if word {
2294        crate::admission::sniff_package(bytes)
2295    } else {
2296        crate::admission::sniff(bytes)
2297    };
2298    checked.err().map(|refused| {
2299        format!(
2300            "{}: {} is {}",
2301            refused.code(),
2302            path.display(),
2303            refused.message
2304        )
2305    })
2306}
2307
2308/// [`refused_input`] for a package a task reads whole (`validate
2309/// --original`): the bytes must also pass admission
2310/// ([`crate::admission::admit`]), so a ZIP that holds no Word document is
2311/// refused before anything is written. `None` when the package is
2312/// admitted.
2313#[must_use]
2314pub fn refused_package(path: &Path, bytes: &[u8]) -> Option<String> {
2315    crate::admission::admit(bytes, crate::admission::InputLimits::default())
2316        .err()
2317        .map(|refused| {
2318            format!(
2319                "{}: {} is {}",
2320                refused.code(),
2321                path.display(),
2322                refused.message
2323            )
2324        })
2325}
2326
2327/// The line a writing task prints on stderr for the file it wrote:
2328/// `wrote r.pdf (pdf, 48213 bytes, 3 pages)`; `pages` is a PDF's.
2329pub fn wrote_line(path: &Path, format: Format, bytes: usize, pages: Option<usize>) -> String {
2330    wrote_line_with(path, format, bytes, pages, None)
2331}
2332
2333/// `wrote contract.docx in place (replaced sha256 4eb2e9c3…)`, plus the
2334/// optional `; 1 change by "GiantCo"` detail (#1888, #1891).
2335#[must_use]
2336pub fn wrote_in_place_line(path: &Path, replaced_sha256: &str, detail: Option<&str>) -> String {
2337    let prefix = replaced_sha256.get(..8).unwrap_or(replaced_sha256);
2338    let extra = detail.map_or_else(String::new, |detail| format!("; {detail}"));
2339    format!(
2340        "wrote {} in place (replaced sha256 {prefix}\u{2026}){extra}",
2341        path.display()
2342    )
2343}
2344
2345/// [`wrote_line`] with an optional `; 1 change by "GiantCo"` suffix (#1891).
2346pub fn wrote_line_with(
2347    path: &Path,
2348    format: Format,
2349    bytes: usize,
2350    pages: Option<usize>,
2351    detail: Option<&str>,
2352) -> String {
2353    let pages = pages.map_or_else(String::new, |n| format!(", {}", count(n, "page")));
2354    let extra = detail.map_or_else(String::new, |s| format!("; {s}"));
2355    format!(
2356        "wrote {} ({}, {bytes} bytes{pages}{extra})",
2357        path.display(),
2358        format.name()
2359    )
2360}
2361
2362/// The `; 1 change by "GiantCo"` fragment of a one-shot edit/add `wrote`
2363/// line (#1891). `None` when the write added no markup. A markup write
2364/// without a spelled author refuses (#1997), so the name is always the
2365/// one the caller gave.
2366#[must_use]
2367pub fn wrote_markup_detail(changes: usize, comments: usize, author: &str) -> Option<String> {
2368    if changes == 0 && comments == 0 {
2369        return None;
2370    }
2371    let mut detail = String::new();
2372    if changes > 0 {
2373        detail.push_str(&count(changes, "change"));
2374    }
2375    if comments > 0 {
2376        if !detail.is_empty() {
2377            detail.push_str(", ");
2378        }
2379        detail.push_str(&count(comments, "comment"));
2380    }
2381    detail.push_str(&format!(" by \"{author}\""));
2382    Some(detail)
2383}
2384
2385/// Confirmation of the published document, comparing the two agent views.
2386pub fn success_block(before_name: &str, before: &str, after_name: &str, after: &str) -> String {
2387    let body = if before == after {
2388        "no differences\n".to_string()
2389    } else {
2390        similar::TextDiff::from_lines(before, after)
2391            .unified_diff()
2392            .context_radius(3)
2393            .header(
2394                &format!("before {before_name}"),
2395                &format!("after {after_name}"),
2396            )
2397            .to_string()
2398    };
2399    // CommonMark closes a tilde fence with up to three leading spaces, and a
2400    // context line puts one before the document's text.
2401    let longest = body
2402        .lines()
2403        .map(|line| {
2404            let indent = line.bytes().take(3).take_while(|b| *b == b' ').count();
2405            line.bytes().skip(indent).take_while(|b| *b == b'~').count()
2406        })
2407        .max()
2408        .unwrap_or(0);
2409    let fence = "~".repeat(4.max(longest + 1));
2410    format!("SUCCESS:\n{fence}diff\n{body}{fence}\n")
2411}
2412
2413#[cfg(test)]
2414mod success_tests {
2415    use super::success_block;
2416
2417    #[test]
2418    fn equal_views() {
2419        assert_eq!(
2420            success_block("in.docx", "same", "out.docx", "same"),
2421            "SUCCESS:\n~~~~diff\nno differences\n~~~~\n"
2422        );
2423    }
2424
2425    #[test]
2426    fn labels_and_known_hunk() {
2427        assert_eq!(
2428            success_block(
2429                "dir/in.docx",
2430                "one\ntwo\nthree\n",
2431                "out.docx",
2432                "one\nnew\nthree\n"
2433            ),
2434            "SUCCESS:\n~~~~diff\n--- before dir/in.docx\n+++ after out.docx\n@@ -1,3 +1,3 @@\n one\n-two\n+new\n three\n~~~~\n"
2435        );
2436    }
2437
2438    #[test]
2439    fn fence_exceeds_leading_tildes_in_diff_body() {
2440        let block = success_block("a", "a\n", "b\n~~~~~", "b\n");
2441        assert!(block.starts_with("SUCCESS:\n~~~~~~diff\n"), "{block}");
2442        assert!(block.ends_with("~~~~~~\n"), "{block}");
2443        // Tildes after a diff marker do not begin the line.
2444        assert!(success_block("a", "~~~~~~\n", "b", "x\n").starts_with("SUCCESS:\n~~~~diff\n"));
2445    }
2446
2447    /// A context line keeps the document's text after one space, and
2448    /// CommonMark lets up to three spaces precede a closing fence, so ` ~~~~`
2449    /// would close a four-tilde fence early (review gid=48).
2450    #[test]
2451    fn a_context_line_of_tildes_cannot_close_the_fence() {
2452        let block = success_block("a", "~~~~\nkeep\n", "b", "~~~~\nchanged\n");
2453        assert!(block.contains("\n ~~~~\n"), "{block}");
2454        let fence = block["SUCCESS:\n".len()..]
2455            .bytes()
2456            .take_while(|b| *b == b'~')
2457            .count();
2458        assert!(fence > 4, "{block}");
2459    }
2460
2461    #[test]
2462    fn three_context_lines_and_missing_newline() {
2463        let block = success_block(
2464            "a",
2465            "0\n1\n2\n3\n4\n5\n6\n7",
2466            "b",
2467            "0\n1\n2\n3\n4\n5\n6\nnew",
2468        );
2469        assert!(block.contains("@@ -5,4 +5,4 @@\n 4\n 5\n 6\n-7\n\\ No newline at end of file\n+new\n\\ No newline at end of file\n"), "{block}");
2470    }
2471}
2472
2473/// The line for PNG pages: `wrote out/r-page-NN.png (png, 3 pages, 96 dpi)`,
2474/// `pattern` naming them all.
2475pub fn wrote_png_line(pattern: &Path, pages: usize, dpi: f32) -> String {
2476    format!(
2477        "wrote {} (png, {}, {dpi} dpi)",
2478        pattern.display(),
2479        count(pages, "page")
2480    )
2481}
2482
2483/// `1 page`, `3 pages`.
2484fn count(n: usize, word: &str) -> String {
2485    format!("{n} {word}{}", if n == 1 { "" } else { "s" })
2486}
2487
2488/// A spelling 0.13 still accepts, with a note, and 0.14 removes.
2489#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2490pub struct Retired {
2491    /// What the command line says (`diff-render`, `--pdf`).
2492    pub old: &'static str,
2493    /// What to say instead.
2494    pub now: &'static str,
2495    /// `None`: `old` is a task name. `Some(task)`: `old` is a flag retired on
2496    /// that task only (another task may keep it).
2497    pub on: Option<&'static str>,
2498}
2499
2500/// Every retired task name and flag (D13).
2501pub const RETIRED: &[Retired] = &[
2502    Retired {
2503        old: "diff-render",
2504        now: "visual-diff",
2505        on: None,
2506    },
2507    Retired {
2508        old: "text",
2509        now: "read",
2510        on: None,
2511    },
2512    Retired {
2513        old: "inspect",
2514        now: "read",
2515        on: None,
2516    },
2517    Retired {
2518        old: "audit",
2519        now: "validate --rules a11y,style,structure",
2520        on: None,
2521    },
2522    Retired {
2523        old: "--changed-only",
2524        now: "--changed-pages",
2525        on: Some("convert"),
2526    },
2527    Retired {
2528        old: "--changed-only",
2529        now: "--changed-pages",
2530        on: Some("compare"),
2531    },
2532    Retired {
2533        old: "--changed-only",
2534        now: "--changed-pages",
2535        on: Some("accept"),
2536    },
2537    Retired {
2538        old: "--changed-only",
2539        now: "--changed-pages",
2540        on: Some("reject"),
2541    },
2542    Retired {
2543        old: "--changed-only",
2544        now: "--changed-pages",
2545        on: Some("append"),
2546    },
2547    Retired {
2548        old: "--changed-only",
2549        now: "--changed-pages",
2550        on: Some("scrub"),
2551    },
2552    Retired {
2553        old: "--pdf",
2554        now: "--to pdf",
2555        on: Some("convert"),
2556    },
2557    Retired {
2558        old: "--png",
2559        now: "--to png",
2560        on: Some("convert"),
2561    },
2562];
2563
2564/// Every task name that is gone and parses as the shorthand's first file
2565/// again (`jubarte revisions x.docx` compares a file called `revisions`):
2566/// a [`removed_task_note`] names what to say instead.
2567pub(crate) const REMOVED_TASKS: &[Retired] = &[Retired {
2568    old: "revisions",
2569    now: "changes",
2570    on: None,
2571}];
2572
2573/// Each [`REMOVED_TASKS`] name `argv` puts where the task goes, as
2574/// [`retired_spellings`] finds them.
2575pub(crate) fn removed_tasks<'a>(
2576    argv: impl IntoIterator<Item = &'a str>,
2577) -> Vec<(&'static str, &'static str)> {
2578    spellings_in(REMOVED_TASKS, argv)
2579}
2580
2581/// The note a removed task name earns: the run goes on, reading it as a
2582/// file.
2583pub(crate) fn removed_task_note(old: &str, now: &str) -> String {
2584    format!("note: {old} is no longer a task, so it reads as a file name; use {now}")
2585}
2586
2587/// Every flag that is gone: it no longer parses, and the error names what
2588/// to say instead, where clap's own tip may name a lookalike (`compare
2589/// --date` would be told `--dates`). Arthur (2026-10-14): `--date` is gone.
2590pub const REMOVED: &[Retired] = &[
2591    Retired {
2592        old: "--date",
2593        now: "--datetime",
2594        on: Some("compare"),
2595    },
2596    Retired {
2597        old: "--date",
2598        now: "--datetime",
2599        on: Some("diff"),
2600    },
2601    Retired {
2602        old: "--date",
2603        now: "--datetime",
2604        on: Some("convert"),
2605    },
2606    Retired {
2607        old: "--date",
2608        now: "--datetime",
2609        on: Some("edit"),
2610    },
2611    Retired {
2612        old: "--date",
2613        now: "--datetime",
2614        on: Some("add"),
2615    },
2616];
2617
2618/// One option as `argv` spells it: `-p`, `--location` (a long's `=value`
2619/// split off), and the index of its token. The value it takes is skipped,
2620/// not kept.
2621struct Spelled {
2622    name: String,
2623    at: usize,
2624}
2625
2626/// How many values `arg` takes after it: `None` for a flag (an option `cmd`
2627/// does not know, or one with `num_args = 0` such as `--delete`), else
2628/// `Some(optional)`, where an optional value (`num_args = 0..=1`) is taken
2629/// only when the next token is not an option, as clap does.
2630fn value_taken(arg: Option<&clap::Arg>) -> Option<bool> {
2631    let arg = arg.filter(|a| a.get_action().takes_values())?;
2632    match arg.get_num_args() {
2633        Some(range) if range.max_values() == 0 => None,
2634        Some(range) => Some(range.min_values() == 0),
2635        None => Some(false),
2636    }
2637}
2638
2639/// The argument of `cmd` spelled `--name`, by its long name or any of its
2640/// aliases, hidden ones included.
2641fn long_arg<'c>(cmd: &'c clap::Command, name: &str) -> Option<&'c clap::Arg> {
2642    cmd.get_arguments().find(|a| {
2643        a.get_long() == Some(name) || a.get_all_aliases().is_some_and(|v| v.contains(&name))
2644    })
2645}
2646
2647/// The argument of `cmd` spelled `-c`, by its short name or a short alias.
2648fn short_arg(cmd: &clap::Command, short: char) -> Option<&clap::Arg> {
2649    cmd.get_arguments().find(|a| {
2650        a.get_short() == Some(short)
2651            || a.get_all_short_aliases()
2652                .is_some_and(|v| v.contains(&short))
2653    })
2654}
2655
2656/// The options of `tokens` (read with `cmd`'s arguments: which take a value)
2657/// up to the first token that is not an option, and the index of that one.
2658/// A short cluster (`-qp t0`) is split; an option `cmd` does not know takes
2659/// no value.
2660fn spelled_options(cmd: &clap::Command, tokens: &[&str]) -> (Vec<Spelled>, usize) {
2661    // Skip the next token as a value, unless an optional value meets an
2662    // option.
2663    let skip_value = |i: &mut usize, optional: bool| {
2664        let value = tokens.get(*i).copied();
2665        if !(optional && value.is_none_or(|v| v.starts_with('-'))) {
2666            *i += 1;
2667        }
2668    };
2669    let mut found = Vec::new();
2670    let mut i = 0;
2671    while let Some(&token) = tokens.get(i) {
2672        i += 1;
2673        if let Some(long) = token.strip_prefix("--") {
2674            let (name, inline) = match long.split_once('=') {
2675                Some((name, value)) => (name, Some(value)),
2676                None => (long, None),
2677            };
2678            if inline.is_none()
2679                && let Some(optional) = value_taken(long_arg(cmd, name))
2680            {
2681                skip_value(&mut i, optional);
2682            }
2683            found.push(Spelled {
2684                name: format!("--{name}"),
2685                at: i - 1,
2686            });
2687        } else if let Some(cluster) = token.strip_prefix('-').filter(|c| !c.is_empty()) {
2688            let at = i - 1;
2689            for (offset, short) in cluster.char_indices() {
2690                let name = format!("-{short}");
2691                let Some(optional) = value_taken(short_arg(cmd, short)) else {
2692                    found.push(Spelled { name, at });
2693                    continue;
2694                };
2695                // The rest of the cluster is the value (`-pt0`, `-p=t0`),
2696                // else the next token is.
2697                if cluster[offset + short.len_utf8()..].is_empty() {
2698                    skip_value(&mut i, optional);
2699                }
2700                found.push(Spelled { name, at });
2701                break;
2702            }
2703        } else {
2704            return (found, i - 1);
2705        }
2706    }
2707    (found, i)
2708}
2709
2710/// The retired spellings in `argv` (the arguments after the program name),
2711/// each once, in the order they first appear. The task is the first token
2712/// before `--` that is neither an option nor an option's value, compare
2713/// when that is no task (the shorthand); a retired flag counts only on the
2714/// task it is retired on. Expired ids (`12`, `#12`, `t0.r1.c2`) are not
2715/// notes: the id parsers refuse them, naming the settled spelling.
2716/// Pure: no I/O.
2717pub fn retired_spellings<'a>(
2718    argv: impl IntoIterator<Item = &'a str>,
2719) -> Vec<(&'static str, &'static str)> {
2720    spellings_in(RETIRED, argv)
2721}
2722
2723/// Each [`REMOVED`] spelling `argv` uses, as [`retired_spellings`] finds
2724/// them.
2725pub fn removed_spellings<'a>(
2726    argv: impl IntoIterator<Item = &'a str>,
2727) -> Vec<(&'static str, &'static str)> {
2728    spellings_in(REMOVED, argv)
2729}
2730
2731/// The error a removed spelling ends the run with, naming what to say
2732/// instead.
2733pub fn removed_error(old: &str, now: &str) -> String {
2734    format!("error: {old} is removed; use {now}")
2735}
2736
2737fn spellings_in<'a>(
2738    table: &[Retired],
2739    argv: impl IntoIterator<Item = &'a str>,
2740) -> Vec<(&'static str, &'static str)> {
2741    let argv: Vec<&str> = argv.into_iter().take_while(|t| *t != "--").collect();
2742    let model = Cli::command();
2743    let mut found = Vec::new();
2744    let (before_task, at) = spelled_options(&model, &argv);
2745    let Some(&task) = argv.get(at) else {
2746        return found;
2747    };
2748    if let Some(retired) = table.iter().find(|r| r.on.is_none() && r.old == task) {
2749        found.push((retired.old, retired.now));
2750    }
2751    // The shorthand `jubarte A B` is compare, with the top level's options
2752    // (zcode-14 F1).
2753    let (sub, task, from) = match model.find_subcommand(task) {
2754        Some(sub) => (sub, sub.get_name(), at + 1),
2755        None => (&model, "compare", at),
2756    };
2757    let mut spot = |options: Vec<Spelled>| {
2758        for option in options {
2759            for retired in table.iter().filter(|r| r.on == Some(task)) {
2760                if option.name == retired.old {
2761                    found.push((retired.old, retired.now));
2762                }
2763            }
2764        }
2765    };
2766    // An unknown option before the task (`--date X compare …`) takes no
2767    // value, so its value reads as the shorthand's first file.
2768    spot(before_task);
2769    // Options and positionals interleave after the task.
2770    let mut rest = &argv[from..];
2771    while !rest.is_empty() {
2772        let (options, next) = spelled_options(sub, rest);
2773        spot(options);
2774        rest = rest.get(next + 1..).unwrap_or_default();
2775    }
2776    let mut seen = std::collections::HashSet::new();
2777    found.retain(|spelling| seen.insert(*spelling));
2778    found
2779}
2780
2781pub use crate::util::shell_word;
2782
2783/// What a retired spelling still means once parsed: `audit` with no
2784/// `--rules` checks `a11y,style,structure`, as the retired task did, not
2785/// `validate`'s default `word`.
2786pub(crate) fn apply_retired(task: &mut Command, retired: &[(&str, &str)]) {
2787    if let Command::Validate { rules, .. } = task
2788        && rules.is_empty()
2789        && retired.iter().any(|(old, _)| *old == "audit")
2790    {
2791        *rules = ["a11y", "style", "structure"].map(String::from).to_vec();
2792    }
2793}
2794
2795/// The stderr lines `argv` earns before its run or its usage error: each
2796/// retired spelling's note, then each removed task's.
2797pub fn notes(argv: &[String]) -> Vec<String> {
2798    let argv = || argv.iter().map(String::as_str);
2799    // `audit --rules …` runs the rules given, not audit's own sets.
2800    let rules_given = argv()
2801        .take_while(|token| *token != "--")
2802        .any(|token| token == "--rules" || token.starts_with("--rules="));
2803    retired_spellings(argv())
2804        .into_iter()
2805        .map(|(old, now)| match old {
2806            "audit" if rules_given => retired_note(old, "validate"),
2807            _ => retired_note(old, now),
2808        })
2809        .chain(
2810            removed_tasks(argv())
2811                .into_iter()
2812                .map(|(old, now)| removed_task_note(old, now)),
2813        )
2814        .collect()
2815}
2816
2817/// The stderr line a retired spelling prints once.
2818pub fn retired_note(old: &str, now: &str) -> String {
2819    format!("note: {old} is now {now}; {old} is removed in 0.14")
2820}
2821
2822/// `--track-changes`, pandoc's values.
2823#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2824#[serde(rename_all = "kebab-case")]
2825pub enum TrackChanges {
2826    /// Keep them: CriticMarkup becomes Word tracked changes and comments.
2827    All,
2828    /// Accept every change.
2829    #[value(alias = "accepted")]
2830    Accept,
2831    /// Reject every change.
2832    #[value(alias = "rejected")]
2833    Reject,
2834}
2835
2836impl From<TrackChanges> for crate::markdown::TrackChanges {
2837    fn from(choice: TrackChanges) -> Self {
2838        match choice {
2839            TrackChanges::All => Self::All,
2840            TrackChanges::Accept => Self::Accept,
2841            TrackChanges::Reject => Self::Reject,
2842        }
2843    }
2844}
2845
2846/// How `-o FILE.pdf` and `-o FILE.png` are rendered (`convert`, `diff`);
2847/// refused with any other output.
2848#[derive(clap::Args, Clone, Debug, PartialEq, Serialize)]
2849#[command(next_help_heading = "Rendering (-o FILE.pdf or FILE.png)")]
2850pub struct RenderArgs {
2851    /// How tracked changes are painted: `conventional` (deletions red
2852    /// struck through, insertions blue underlined, moves green:
2853    /// double-struck where they left, double-underlined where they landed),
2854    /// `word` (what Microsoft Word's Save as PDF paints), or `custom`
2855    /// (see --revision-palette).
2856    #[arg(long, value_enum, default_value_t = Revisions::Conventional, requires_if("custom", "revision_palette"))]
2857    pub revisions: Revisions,
2858    /// Marks for --revisions custom: `kind=#RRGGBB[:lines],...` with
2859    /// kinds deleted, inserted, moved-from, moved-to and lines strike,
2860    /// double-strike, underline, double-underline, plain. Kinds left out
2861    /// keep their conventional mark.
2862    #[cfg_attr(feature = "render", arg(long, value_name = "SPEC", value_parser = parse_palette, requires = "revisions"))]
2863    #[cfg_attr(
2864        not(feature = "render"),
2865        arg(long, value_name = "SPEC", requires = "revisions")
2866    )]
2867    pub revision_palette: Option<String>,
2868    /// PNG resolution in dots per inch (1-1200).
2869    #[arg(long, default_value_t = 96.0, value_name = "DPI", value_parser = parse_dpi)]
2870    pub dpi: f32,
2871    /// List the comments after the last page instead of in balloons beside
2872    /// the text. The commented text keeps its tint and a `[JR1]` marker,
2873    /// and the pages keep their own width.
2874    #[arg(long)]
2875    pub move_comments: bool,
2876    /// Also attach each comment as a PDF note at its anchor. Viewers paint
2877    /// a note as an icon over the text, so none is written by default and
2878    /// the flag stays out of --help: it is for the exceptional case.
2879    #[arg(long, hide = true)]
2880    pub comment_notes: bool,
2881    /// Keep only the pages a change touches: a body or note revision, a
2882    /// comment anchor, or the first page on which a revised header or
2883    /// footer paints (the first page when none does). Page numbers stay the
2884    /// document's.
2885    #[arg(long, alias = "changed-only")]
2886    pub changed_pages: bool,
2887    /// Only these pages, by the document's page numbers: `3`, `1-3,7`.
2888    /// Layout still covers the whole document; the PDF carries these pages
2889    /// and PNGs are named by them (`STEM-page-03.png`).
2890    #[arg(long, value_name = "SPEC", value_parser = validate_pages)]
2891    pub pages: Option<String>,
2892}
2893
2894impl Default for RenderArgs {
2895    fn default() -> Self {
2896        Self {
2897            revisions: Revisions::Conventional,
2898            revision_palette: None,
2899            dpi: 96.0,
2900            move_comments: false,
2901            comment_notes: false,
2902            changed_pages: false,
2903            pages: None,
2904        }
2905    }
2906}
2907
2908impl RenderArgs {
2909    /// Apply comment placement and page filtering to the renderer options.
2910    #[cfg(feature = "render")]
2911    pub fn apply(
2912        &self,
2913        options: crate::jubarte_render::convert::PdfOptions,
2914    ) -> crate::jubarte_render::convert::PdfOptions {
2915        crate::jubarte_render::convert::PdfOptions {
2916            comments: if self.move_comments {
2917                crate::jubarte_render::convert::CommentPlacement::End
2918            } else {
2919                crate::jubarte_render::convert::CommentPlacement::Margin
2920            },
2921            comment_notes: self.comment_notes,
2922            changed_only: self.changed_pages,
2923            ..options
2924        }
2925    }
2926}
2927
2928/// `convert`'s format and Markdown flags.
2929#[derive(clap::Args, Debug, Serialize)]
2930pub struct MarkdownArgs {
2931    /// Input format [default: from the file: .md and .markdown are Markdown,
2932    /// a zip is Word].
2933    #[arg(
2934        short = 'f',
2935        long = "from",
2936        value_parser = input_format_parser(),
2937        value_name = "FORMAT",
2938        help_heading = "Formats"
2939    )]
2940    pub from: Option<Format>,
2941    /// Output format [default: from --output, else pdf for Word and docx for
2942    /// Markdown].
2943    #[arg(
2944        short = 't',
2945        long = "to",
2946        value_enum,
2947        value_name = "FORMAT",
2948        help_heading = "Formats"
2949    )]
2950    pub to: Option<Format>,
2951    /// Keep tracked changes (all), or write the document with every change
2952    /// accepted or rejected (pandoc's flag): CriticMarkup in Markdown, Word's
2953    /// revisions in a .docx. With --to md, the Markdown itself is resolved.
2954    #[arg(long, value_enum, value_name = "CHOICE", default_value_t = TrackChanges::All)]
2955    pub track_changes: TrackChanges,
2956    /// Keep comments and replies whose whole anchor is removed; requires --track-changes accept or reject.
2957    #[arg(long)]
2958    pub keep_nested_comment: bool,
2959    /// Markdown: read `{++`, `{--` and the other CriticMarkup delimiters as
2960    /// text.
2961    #[arg(long)]
2962    pub no_critic: bool,
2963    /// Markdown to Word: take styles, numbering, page setup, headers and
2964    /// footers from this .docx (pandoc's --reference-doc).
2965    #[arg(long, value_name = "FILE")]
2966    pub reference_doc: Option<PathBuf>,
2967    /// Markdown to Word: where images are found [default: the Markdown
2968    /// file's directory]. Only images that resolve inside that directory
2969    /// are read, symlinks resolved; a URL or a path out of it is written
2970    /// as its alt text, with a warning that says why.
2971    #[arg(long, value_name = "DIR")]
2972    pub resource_path: Option<PathBuf>,
2973    /// Markdown to Word: author of the tracked changes and comments that
2974    /// name none [default: the front matter's `author:`, else the
2975    /// --reference-doc's creator, else Jubarte].
2976    #[arg(short = 'a', long, value_name = "NAME")]
2977    pub author: Option<String>,
2978    /// Markdown to Word: timestamp (ISO 8601) of the tracked changes and
2979    /// comments that carry none [default: the front matter's
2980    /// `last_modified:`/`modified:`/`date:`/`created:`, else the
2981    /// --reference-doc's creation time, else now]; pin it
2982    /// (`-d 1970-01-01T00:00:00Z`) for reproducible output.
2983    #[arg(
2984        short = 'd',
2985        long = "datetime",
2986        value_name = "ISO8601",
2987        value_parser = parse_datetime
2988    )]
2989    pub datetime: Option<String>,
2990    /// Markdown to Word: the page size when there is no --reference-doc
2991    /// (one-inch margins either way); a reference's page setup wins.
2992    #[arg(long, value_enum, value_name = "SIZE", default_value_t = Page::Letter)]
2993    pub page: Page,
2994    /// Markdown to Word: turn Word's Track Changes on or off in the .docx
2995    /// written, whatever the Markdown's `track_changes:` key says [default:
2996    /// the key; without one, the --reference-doc's setting, else off].
2997    #[arg(long, value_enum, value_name = "SWITCH")]
2998    pub tracking: Option<Tracking>,
2999    /// Markdown to Word: set a manuscript as LaTeX's article class does
3000    /// (Latin Modern Roman 10pt on 12pt lines, justified, bold headings)
3001    /// and number its pages from page 2, centered in the footer. The front
3002    /// matter's own `styles:` entries, headers and footers win.
3003    #[arg(long)]
3004    pub scholar: bool,
3005    /// Word to Markdown: leave out the `<!-- page N of M -->` lines, and the
3006    /// layout pass that places them.
3007    #[arg(long)]
3008    pub no_page_markers: bool,
3009    /// Word to Markdown: write plain CommonMark with CriticMarkup for
3010    /// readers outside jubarte's dialect, instead of the agent view (`jubarte
3011    /// read`'s YAML header and id lines). Fields print as their text, and
3012    /// underline, highlight and strike are left out.
3013    #[arg(long)]
3014    pub commonmark: bool,
3015}
3016
3017/// `--tracking`.
3018#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3019#[serde(rename_all = "kebab-case")]
3020pub enum Tracking {
3021    /// New edits in Word are tracked.
3022    On,
3023    /// New edits in Word are not tracked.
3024    Off,
3025}
3026
3027/// `--page`.
3028#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3029#[serde(rename_all = "kebab-case")]
3030pub enum Page {
3031    /// US Letter, 8.5 by 11 inches.
3032    Letter,
3033    /// ISO A4, 210 by 297 mm.
3034    A4,
3035}
3036
3037impl From<Page> for crate::markdown::PageSize {
3038    fn from(choice: Page) -> Self {
3039        match choice {
3040            Page::Letter => Self::Letter,
3041            Page::A4 => Self::A4,
3042        }
3043    }
3044}
3045
3046/// `jubarte convert --revisions`.
3047#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3048#[serde(rename_all = "kebab-case")]
3049pub enum Revisions {
3050    /// Red strike, blue underline, green double marks for moves.
3051    Conventional,
3052    /// Microsoft Word's own markup.
3053    Word,
3054    /// --revision-palette.
3055    Custom,
3056}
3057
3058#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
3059/// Filters selecting individual tracked changes.
3060pub struct Selection {
3061    /// Only this change: `r12` (as the view and `jubarte changes` print
3062    /// it), `header1.r1`, `comments.r9`, or `r1+2` (both). Repeatable.
3063    #[arg(long = "id", value_name = "ID")]
3064    pub ids: Vec<String>,
3065    /// Only changes by this author. Repeatable.
3066    #[arg(long = "author", value_name = "NAME")]
3067    pub authors: Vec<String>,
3068    /// Only changes of this kind. Repeatable.
3069    #[arg(long = "kind", value_enum, value_name = "KIND")]
3070    pub kinds: Vec<KindArg>,
3071}
3072
3073/// `--kind` values.
3074#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Serialize)]
3075#[serde(rename_all = "kebab-case")]
3076pub enum KindArg {
3077    /// Inserted text or structural elements.
3078    Insertion,
3079    /// Deleted text or structural elements.
3080    Deletion,
3081    /// Content moved between document locations.
3082    Move,
3083    /// Changes to text or paragraph formatting.
3084    Formatting,
3085    /// The kind `changes` prints for a deletion and the insertion that
3086    /// replaces it. It names no mark, so a filter of it is refused, with
3087    /// how to select one (by its id, or its marks by kind); hidden, it is
3088    /// no value to offer.
3089    #[value(hide = true)]
3090    Replacement,
3091}
3092
3093fn parse_timeout(value: &str) -> Result<std::time::Duration, String> {
3094    let seconds: f64 = value
3095        .parse()
3096        .map_err(|_| format!("'{value}' is not a number of seconds"))?;
3097    if !(seconds.is_finite() && seconds > 0.0) {
3098        return Err(format!(
3099            "'{value}': the timeout must be a finite number of seconds above 0"
3100        ));
3101    }
3102    std::time::Duration::try_from_secs_f64(seconds).map_err(|e| format!("'{value}': {e}"))
3103}
3104
3105/// `jubarte append --section-break`.
3106#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3107#[serde(rename_all = "kebab-case")]
3108pub enum SectionBreakArg {
3109    /// Each document starts on a new page.
3110    NextPage,
3111    /// Each document continues on the same page (a continuous section
3112    /// break with --keep-sections).
3113    Continuous,
3114    /// Nothing between the documents (continuous with --keep-sections).
3115    None,
3116}
3117
3118impl From<SectionBreakArg> for crate::append::SectionBreak {
3119    fn from(arg: SectionBreakArg) -> Self {
3120        match arg {
3121            SectionBreakArg::NextPage => Self::NextPage,
3122            SectionBreakArg::Continuous => Self::Continuous,
3123            SectionBreakArg::None => Self::None,
3124        }
3125    }
3126}
3127
3128fn styles() -> clap::builder::Styles {
3129    use clap::builder::styling::{AnsiColor, Effects};
3130    clap::builder::Styles::styled()
3131        .header(AnsiColor::Cyan.on_default() | Effects::BOLD)
3132        .usage(AnsiColor::Cyan.on_default() | Effects::BOLD)
3133        .literal(AnsiColor::Green.on_default())
3134        .placeholder(AnsiColor::Yellow.on_default())
3135}
3136
3137/// `--by`: a handle (`AC`, `@AC`) or a full name, never blank.
3138fn parse_author(value: &str) -> Result<String, String> {
3139    crate::markdown::author(value).map(str::to_string)
3140}
3141
3142fn parse_dpi(value: &str) -> Result<f32, String> {
3143    let dpi: f32 = value.parse().map_err(|_| "DPI must be a number")?;
3144    if dpi.is_finite() && dpi > 0.0 && dpi <= 1200.0 {
3145        Ok(dpi)
3146    } else {
3147        Err("DPI must be finite and above 0, up to 1200".into())
3148    }
3149}
3150
3151fn input_format_parser() -> impl clap::builder::TypedValueParser<Value = Format> {
3152    use clap::builder::TypedValueParser;
3153    clap::builder::PossibleValuesParser::new(["docx", "md", "markdown"]).map(|value| {
3154        if value == "docx" {
3155            Format::Docx
3156        } else {
3157            Format::Md
3158        }
3159    })
3160}
3161
3162fn parse_context(value: &str) -> Result<usize, String> {
3163    value
3164        .parse::<u32>()
3165        .map(|n| n as usize)
3166        .map_err(|_| "context must be an integer between 0 and 4294967295".to_string())
3167}
3168
3169fn parse_threshold(value: &str) -> Result<f64, String> {
3170    let ratio: f64 = value.parse().map_err(|_| "threshold must be a number")?;
3171    if ratio.is_finite() && (0.0..=1.0).contains(&ratio) {
3172        Ok(ratio)
3173    } else {
3174        Err("threshold must be finite and between 0 and 1".into())
3175    }
3176}
3177
3178#[cfg(feature = "render")]
3179fn parse_palette(value: &str) -> Result<String, String> {
3180    crate::jubarte_render::convert::RevisionPalette::parse(value)?;
3181    Ok(value.to_string())
3182}
3183
3184/// A `--rules` item: a [`crate::validate::RULE_SETS`] name or an audit code.
3185fn parse_rule(value: &str) -> Result<String, String> {
3186    if crate::validate::RULE_SETS.contains(&value) || crate::audit::is_rule(value) {
3187        Ok(value.to_string())
3188    } else {
3189        let codes: Vec<&str> = crate::audit::RULES.iter().map(|rule| rule.0).collect();
3190        Err(format!(
3191            "expected one of {} or an audit code ({})",
3192            crate::validate::RULE_SETS.join(", "),
3193            codes.join(", ")
3194        ))
3195    }
3196}
3197
3198// Validate without expanding ranges: parsing help or arguments never allocates
3199// a potentially enormous list of page indices.
3200fn validate_pages(value: &str) -> Result<String, String> {
3201    let page = |s: &str| {
3202        let s = s.trim();
3203        if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
3204            return Err(format!("'{s}' is not a page number"));
3205        }
3206        let n = s
3207            .parse::<usize>()
3208            .map_err(|_| format!("'{s}' is not a page number"))?;
3209        if n == 0 {
3210            Err("pages are counted from 1".to_string())
3211        } else {
3212            Ok(n)
3213        }
3214    };
3215    for item in value.split(',') {
3216        let item = item.trim();
3217        if item.is_empty() {
3218            return Err("empty item in page selection".into());
3219        }
3220        if let Some((first, last)) = item.split_once('-') {
3221            if page(first)? > page(last)? {
3222                return Err(format!("'{item}' runs backwards"));
3223            }
3224        } else {
3225            page(item)?;
3226        }
3227    }
3228    Ok(value.to_string())
3229}
3230
3231fn serialize_timeout<S: serde::Serializer>(
3232    timeout: &Option<std::time::Duration>,
3233    serializer: S,
3234) -> Result<S::Ok, S::Error> {
3235    timeout.map(|t| t.as_secs_f64()).serialize(serializer)
3236}
3237
3238/// Cross-option constraints whose meaning depends on an enum value or output
3239/// extension. These are usage errors, checked before any runtime I/O.
3240/// [`ReadArgs::paragraphs`] in the facade JSON: one comma list, as a
3241/// single `-p` spells it, or `null` without `-p`.
3242fn serialize_paragraph_spec<S: serde::Serializer>(
3243    paragraphs: &[String],
3244    serializer: S,
3245) -> Result<S::Ok, S::Error> {
3246    match paragraphs {
3247        [] => serializer.serialize_none(),
3248        _ => serializer.serialize_str(&paragraphs.join(",")),
3249    }
3250}
3251
3252/// The ids of [`ReadArgs`], as the top-level shorthand declares them.
3253const READ_OPTION_IDS: [&str; 14] = [
3254    "track_changes",
3255    "comments",
3256    "dates",
3257    "no_page_markers",
3258    "paragraphs",
3259    "head",
3260    "tail",
3261    "changed",
3262    "by",
3263    "json",
3264    "tables",
3265    "find",
3266    "regex",
3267    "ignore_case",
3268];
3269
3270/// `diff` writes no JSON snapshot: its `-o x.json` and `--to json` are
3271/// refused here, so the binary and both bindings exit 2 alike instead of
3272/// writing a patch into a `.json`.
3273fn json_not_yet(matches: &clap::ArgMatches, task: Task) -> Option<String> {
3274    let to = matches.try_get_one::<Format>("to").ok().flatten().copied();
3275    let said = matches
3276        .try_get_one::<PathBuf>("output")
3277        .ok()
3278        .flatten()
3279        .and_then(|path| task.known(path));
3280    (to == Some(Format::Json) || said == Some(Format::Json))
3281        .then(|| format!("{} does not write .json yet", task.name()))
3282}
3283
3284/// What `compare`'s `-o` writes (`None`: the view is printed), refusing
3285/// the options that do not go with it: read's `--json` and `--tables` (one
3286/// document), the view's options with a file that is not the view, and the
3287/// rendering options without a PDF or PNG.
3288fn compare_output(
3289    output: Option<&Path>,
3290    given: &dyn Fn(&str) -> bool,
3291) -> Result<Option<Format>, String> {
3292    if given("json") {
3293        return Err(
3294            "--json reads one document; `-o FILE.json` writes the redline's snapshot".to_string(),
3295        );
3296    }
3297    if given("tables") {
3298        return Err("--tables reads one document".to_string());
3299    }
3300    let kind = output_format(Task::Compare, output, None)?;
3301    if kind.is_some_and(|kind| kind != Format::Md) && READ_OPTION_IDS.into_iter().any(given) {
3302        return Err(
3303            "read options shape the view: print it (no -o) or write it (-o FILE.md)".to_string(),
3304        );
3305    }
3306    if !matches!(kind, Some(Format::Pdf | Format::Png))
3307        && let Some(flag) = RENDER_ONLY.into_iter().find(|flag| given(flag))
3308    {
3309        return Err(format!(
3310            "--{} applies to PDF or PNG output only",
3311            flag.replace('_', "-")
3312        ));
3313    }
3314    Ok(kind)
3315}
3316
3317/// The diagnosis for a view-only flag beside --for-edit.
3318fn read_view_conflict(flag: &str) -> String {
3319    format!(
3320        "{flag} shapes the Markdown view, and --for-edit prints the working document JSON, \
3321         which has no view; drop {flag}, or drop --for-edit to read the view"
3322    )
3323}
3324
3325/// As in the swallowed-FILE diagnosis, rebuild a task error through clap.
3326/// A generic usage line gives a valid invocation instead of repeating the
3327/// conflicting flags. The same model serves native and binding parsers.
3328fn read_usage_error(command: &clap::Command, message: String) -> clap::Error {
3329    let mut task = command
3330        .find_subcommand("read")
3331        .unwrap_or(command)
3332        .clone()
3333        .override_usage(format!("{} read [OPTIONS] <FILE>", command.get_name()));
3334    task.set_bin_name(format!("{} read", command.get_name()));
3335    task.error(clap::error::ErrorKind::ArgumentConflict, message)
3336}
3337
3338/// What `read -o PATH` (and the one-document shorthand's -o) writes: `.md`
3339/// the view, `.json` the snapshot. `given` says which argument ids the
3340/// command line spells out.
3341fn read_output(output: &Path, given: &dyn Fn(&str) -> bool) -> Result<Format, String> {
3342    let kind = output_format(Task::Read, Some(output), None)?.unwrap_or(Format::Md);
3343    if given("tables") && kind == Format::Json {
3344        return Err("--tables writes the grids as text: name the file FILE.md".to_string());
3345    }
3346    if given("for_edit") && kind != Format::Json {
3347        return Err("--for-edit prints JSON: name the file FILE.json or drop -o".to_string());
3348    }
3349    if kind == Format::Json && !given("for_edit") && (given("find") || given("regex")) {
3350        return Err(
3351            "--find/--regex select the Markdown view: name the file FILE.md or use --for-edit"
3352                .into(),
3353        );
3354    }
3355    if given("json") && kind != Format::Json {
3356        return Err("--json writes the snapshot: name the file FILE.json".to_string());
3357    }
3358    // A .json snapshot is --json's: --track-changes settles its text, and
3359    // the view's other options change nothing in it.
3360    Ok(kind)
3361}
3362
3363/// `--revision-palette` without `--revisions custom`, in any task that
3364/// draws revisions (convert, edit, compare, accept, reject, append, scrub):
3365/// a usage error before any document is read (#440 and #441).
3366fn palette_without_custom(args: &clap::ArgMatches) -> bool {
3367    args.try_get_one::<String>("revision_palette")
3368        .ok()
3369        .flatten()
3370        .is_some()
3371        && args.try_get_one::<Revisions>("revisions").ok().flatten() != Some(&Revisions::Custom)
3372}
3373
3374fn validate_matches(
3375    matches: &clap::ArgMatches,
3376    command: &mut clap::Command,
3377) -> Result<(), clap::Error> {
3378    use clap::{error::ErrorKind, parser::ValueSource};
3379    let read_args = match matches.subcommand() {
3380        Some(("read" | "compare", args)) => Some(args),
3381        None => Some(matches),
3382        _ => None,
3383    };
3384    if let Some(args) = read_args {
3385        let find = args.get_one::<String>("find");
3386        let regex = args.get_one::<String>("regex");
3387        if !args.get_flag("for_edit")
3388            && (find.is_some() || regex.is_some())
3389            && (args.get_flag("json") || args.get_flag("tables"))
3390        {
3391            return Err(read_usage_error(
3392                command,
3393                "--find/--regex select the Markdown view; drop --json/--tables or use --for-edit"
3394                    .into(),
3395            ));
3396        }
3397        if find.is_none()
3398            && regex.is_none()
3399            && args.get_flag("ignore_case")
3400            && !args.get_flag("for_edit")
3401        {
3402            return Err(read_usage_error(
3403                command,
3404                "--ignore-case needs --find TEXT or --regex PATTERN".into(),
3405            ));
3406        }
3407    }
3408    let Some((name, args)) = matches.subcommand() else {
3409        let given = |id: &str| {
3410            matches.try_contains_id(id).unwrap_or(false)
3411                && matches.value_source(id) == Some(ValueSource::CommandLine)
3412        };
3413        let two = given("modified_pos") || given("modified");
3414        let output = matches.get_one::<PathBuf>("output").map(PathBuf::as_path);
3415        if two {
3416            compare_output(output, &given)
3417                .map_err(|message| command.error(ErrorKind::ArgumentConflict, message))?;
3418            if palette_without_custom(matches) {
3419                return Err(command.error(
3420                    ErrorKind::ArgumentConflict,
3421                    "--revision-palette needs --revisions custom",
3422                ));
3423            }
3424        } else {
3425            // One document: `read`, whose -o writes the view or the snapshot.
3426            if let Some(output) = output {
3427                read_output(output, &given)
3428                    .map_err(|message| read_usage_error(command, message))?;
3429            }
3430            // Compare's own options and the rendering ones mean nothing to
3431            // read.
3432            if let Some(flag) = COMPARE_ONLY.into_iter().find(|id| given(id)) {
3433                return Err(command.error(
3434                    ErrorKind::ArgumentConflict,
3435                    format!(
3436                        "--{} is a compare option: name two documents",
3437                        flag.replace('_', "-")
3438                    ),
3439                ));
3440            }
3441            if let Some(flag) = RENDER_ONLY.into_iter().find(|id| given(id)) {
3442                return Err(command.error(
3443                    ErrorKind::ArgumentConflict,
3444                    format!(
3445                        "--{} draws a PDF or PNG, which read does not write: \
3446                         `convert FILE -o FILE.pdf` or `compare A B -o FILE.pdf` does",
3447                        flag.replace('_', "-")
3448                    ),
3449                ));
3450            }
3451        }
3452        // `jubarte --head 2 read a.docx`: options before a task make clap read
3453        // the task's name as ORIGINAL.
3454        if let Some(task) = matches
3455            .try_get_one::<PathBuf>("original_pos")
3456            .ok()
3457            .flatten()
3458            .and_then(|p| p.to_str())
3459            .and_then(|name| command.find_subcommand(name))
3460            .map(|task| task.get_name().to_string())
3461        {
3462            return Err(command.error(
3463                ErrorKind::ArgumentConflict,
3464                format!(
3465                    "options go after the task: `{} {task} … [OPTIONS]`",
3466                    command.get_name()
3467                ),
3468            ));
3469        }
3470        // One bare word is more likely a mistyped task than a document.
3471        let lone = |id: &str| {
3472            matches
3473                .try_get_one::<PathBuf>(id)
3474                .ok()
3475                .flatten()
3476                .filter(|_| matches.value_source(id) == Some(ValueSource::CommandLine))
3477        };
3478        if lone("modified_pos").is_none()
3479            && lone("modified").is_none()
3480            && let Some(file) = lone("original_pos")
3481            && file.extension().is_none()
3482        {
3483            return Err(command.error(
3484                ErrorKind::InvalidSubcommand,
3485                format!(
3486                    "'{}' is not a task; to read a file without an extension, use `read FILE`",
3487                    file.display()
3488                ),
3489            ));
3490        }
3491        return Ok(());
3492    };
3493    if let Some(message) = Task::of_name(name)
3494        .filter(|task| *task == Task::Diff)
3495        .and_then(|task| json_not_yet(args, task))
3496    {
3497        let mut task = command.find_subcommand(name).expect("parsed task").clone();
3498        task.set_bin_name(format!("{} {name}", command.get_name()));
3499        return Err(task.error(ErrorKind::ValueValidation, message));
3500    }
3501    if name == "validate"
3502        && args
3503            .get_many::<String>("rules")
3504            .is_some_and(|mut rules| rules.any(|rule| rule == "edits"))
3505        && !args.contains_id("author")
3506    {
3507        let mut task = command.find_subcommand(name).expect("parsed task").clone();
3508        task.set_bin_name(format!("{} {name}", command.get_name()));
3509        return Err(task.error(
3510            ErrorKind::MissingRequiredArgument,
3511            "--rules edits needs --author, and --original or --baseline",
3512        ));
3513    }
3514    if name == "compare"
3515        && !["modified", "modified_pos"]
3516            .into_iter()
3517            .any(|id| args.try_contains_id(id).unwrap_or(false))
3518    {
3519        let mut task = command.find_subcommand(name).expect("parsed task").clone();
3520        task.set_bin_name(format!("{} {name}", command.get_name()));
3521        return Err(task.error(
3522            ErrorKind::MissingRequiredArgument,
3523            "compare needs <MODIFIED> (or -m FILE)",
3524        ));
3525    }
3526    if name == "__edit-template" {
3527        return edit_template::validate(args, command);
3528    }
3529    if name == "__edit-v2" {
3530        return edit_actions::validate(args, command);
3531    }
3532    let mut task = command.find_subcommand(name).expect("parsed task").clone();
3533    task.set_bin_name(format!("{} {name}", command.get_name()));
3534    let error =
3535        |task: &mut clap::Command, message: &str| task.error(ErrorKind::ArgumentConflict, message);
3536    let given = |id: &str| {
3537        args.try_contains_id(id).unwrap_or(false)
3538            && args.value_source(id) == Some(ValueSource::CommandLine)
3539    };
3540    if name == "read"
3541        && let Some(output) = args.get_one::<PathBuf>("output")
3542    {
3543        read_output(output, &given).map_err(|message| read_usage_error(command, message))?;
3544    }
3545    if name == "compare" {
3546        compare_output(
3547            args.get_one::<PathBuf>("output").map(PathBuf::as_path),
3548            &given,
3549        )
3550        .map_err(|message| error(&mut task, &message))?;
3551    }
3552    if let Some(writer) = Task::of_name(name).filter(|task| {
3553        matches!(
3554            task,
3555            Task::Accept | Task::Reject | Task::Append | Task::Scrub
3556        )
3557    }) {
3558        let output = args.get_one::<PathBuf>("output").map(PathBuf::as_path);
3559        let kind =
3560            output_format(writer, output, None).map_err(|message| error(&mut task, &message))?;
3561        if !matches!(kind, Some(Format::Pdf | Format::Png))
3562            && let Some(flag) = RENDER_ONLY.into_iter().find(|flag| given(flag))
3563        {
3564            return Err(error(
3565                &mut task,
3566                &format!(
3567                    "--{} applies to PDF or PNG output only",
3568                    flag.replace('_', "-")
3569                ),
3570            ));
3571        }
3572    }
3573    if matches!(name, "edit" | "add")
3574        && let Some(plan) = args.get_one::<PathBuf>("plan")
3575    {
3576        // Only the flags the command line spells out: a default is no
3577        // choice the plan could contradict.
3578        let given: Vec<String> = args
3579            .ids()
3580            .filter(|id| args.value_source(id.as_str()) == Some(ValueSource::CommandLine))
3581            .map(|id| format!("--{}", id.as_str().replace('_', "-")))
3582            .collect();
3583        let given: Vec<&str> = given.iter().map(String::as_str).collect();
3584        let recording = given.contains(&"--location");
3585        if let Some(message) =
3586            crate::edit::record::plan_flag_conflict(recording, &given, &plan.display().to_string())
3587        {
3588            return Err(error(&mut task, &message));
3589        }
3590    }
3591    // --out-dir's value is optional, so `edit --out-dir a.docx -p p1`
3592    // would read the document as the directory.
3593    if matches!(name, "edit" | "add")
3594        && let Some(dir) = args.try_get_one::<PathBuf>("out_dir").ok().flatten()
3595        && names_word_document(dir)
3596    {
3597        return Err(error(&mut task, &swallowed_file("--out-dir", dir)));
3598    }
3599    // So is --plan's (D16): a plan is JSON, never a Word document.
3600    if matches!(name, "edit" | "add")
3601        && let Some(plan) = args.get_one::<PathBuf>("plan")
3602        && names_word_document(plan)
3603    {
3604        return Err(error(&mut task, &swallowed_file("--plan", plan)));
3605    }
3606    // edit and add write one Word document: a known extension that is not
3607    // .docx names the task that writes it.
3608    if matches!(name, "edit" | "add")
3609        && let Some(output) = args.get_one::<PathBuf>("output")
3610        && let Some(kind) = Format::of_path(output).filter(|kind| *kind != Format::Docx)
3611    {
3612        // As typed (`.txt`, `.markdown`), which the named task also takes.
3613        let ext = output.extension().map_or_else(
3614            || kind.name().to_string(),
3615            |e| e.to_string_lossy().to_lowercase(),
3616        );
3617        let how = match kind {
3618            Format::Md | Format::Json => format!("`jubarte read FILE_modified.docx -o v.{ext}`"),
3619            _ => format!("`jubarte convert FILE_modified.docx -o r.{ext}`"),
3620        };
3621        return Err(error(
3622            &mut task,
3623            &format!("{name} writes a .docx; {how} writes .{ext} from it"),
3624        ));
3625    }
3626    if palette_without_custom(args) {
3627        return Err(error(
3628            &mut task,
3629            "--revision-palette needs --revisions custom",
3630        ));
3631    }
3632    if name == "diff" {
3633        // Text only: Word, PDF and PNG redlines are compare's.
3634        output_format(
3635            Task::Diff,
3636            args.get_one::<PathBuf>("output").map(PathBuf::as_path),
3637            args.get_one::<Format>("to").copied(),
3638        )
3639        .map_err(|message| error(&mut task, &message))?;
3640        let format = *args
3641            .get_one::<PatchFormat>("format")
3642            .expect("default format");
3643        let (text_view, theirs) = if format.is_text_view() {
3644            (true, &["columns", "author", "datetime"][..])
3645        } else {
3646            (false, &["context", "accept_changes", "full_lines"][..])
3647        };
3648        // CriticMarkup carries no owner and is not wrapped: the patch's
3649        // flags would be dropped silently (pi-14 C3).
3650        let patch_only: &[&str] = if format == PatchFormat::Critic {
3651            &["columns", "author", "datetime"]
3652        } else {
3653            &[]
3654        };
3655        let given = |flag: &&&str| args.value_source(flag) == Some(ValueSource::CommandLine);
3656        if let Some(flag) = patch_only.iter().find(given) {
3657            return Err(error(
3658                &mut task,
3659                &format!("--{flag} applies to the paragraph patch only (--format patch)"),
3660            ));
3661        }
3662        if let Some(flag) = theirs.iter().find(given) {
3663            let flag = flag.replace('_', "-");
3664            return Err(error(
3665                &mut task,
3666                &if text_view {
3667                    format!("--{flag} does not apply to this text diff format")
3668                } else {
3669                    format!(
3670                        "--{flag} requires a text diff format (github, word, normal, context or side-by-side)"
3671                    )
3672                },
3673            ));
3674        }
3675    }
3676    if name == "convert" {
3677        if args.get_flag("keep_nested_comment")
3678            && args.get_one::<TrackChanges>("track_changes") == Some(&TrackChanges::All)
3679        {
3680            return Err(error(
3681                &mut task,
3682                "--keep-nested-comment requires --track-changes accept or reject",
3683            ));
3684        }
3685        // The retired --pdf and --png name a format, as --to does.
3686        let alias = match (args.get_flag("pdf"), args.get_flag("png")) {
3687            (true, true) => return Err(error(&mut task, "--pdf and --png name two formats")),
3688            (true, false) => Some(Format::Pdf),
3689            (false, true) => Some(Format::Png),
3690            (false, false) => None,
3691        };
3692        let given = args.get_one::<Format>("to").copied();
3693        if let (Some(to), Some(alias)) = (given, alias)
3694            && to != alias
3695        {
3696            return Err(error(
3697                &mut task,
3698                &format!(
3699                    "--to {} and --{} name two formats: drop one",
3700                    to.name(),
3701                    alias.name()
3702                ),
3703            ));
3704        }
3705        let output = args.get_one::<PathBuf>("output").map(PathBuf::as_path);
3706        let kind = output_format(Task::Convert, output, given.or(alias))
3707            .map_err(|message| error(&mut task, &message))?;
3708        let update_fields = args.get_flag("update_fields");
3709        if update_fields && kind != Some(Format::Docx) {
3710            return Err(error(
3711                &mut task,
3712                "--update-fields writes a .docx: give -o FILE.docx or --to docx",
3713            ));
3714        }
3715        if matches!(kind, Some(Format::Docx | Format::Md | Format::Json)) {
3716            let convert_only = ["compress", "report", "font_report", "fail_on_substitution"];
3717            for flag in RENDER_ONLY.into_iter().chain(convert_only) {
3718                // The fields report is the one report a .docx output has.
3719                if flag == "report" && update_fields {
3720                    continue;
3721                }
3722                if args.value_source(flag) == Some(ValueSource::CommandLine) {
3723                    return Err(error(
3724                        &mut task,
3725                        &format!(
3726                            "--{} applies to PDF or PNG output only",
3727                            flag.replace('_', "-")
3728                        ),
3729                    ));
3730                }
3731            }
3732        }
3733    }
3734    Ok(())
3735}
3736
3737/// The ids of the options only a comparison takes; `jubarte FILE` refuses
3738/// them.
3739const COMPARE_ONLY: [&str; 9] = [
3740    "author",
3741    "datetime",
3742    "detail_threshold",
3743    "mode",
3744    "powertools_faithful",
3745    "no_paragraph_merge",
3746    "reference_doc",
3747    "critic",
3748    "resource_path",
3749];
3750
3751/// The [`RenderArgs`] ids: options of a PDF or PNG output only.
3752const RENDER_ONLY: [&str; 7] = [
3753    "move_comments",
3754    "comment_notes",
3755    "changed_pages",
3756    "pages",
3757    "dpi",
3758    "revisions",
3759    "revision_palette",
3760];
3761
3762/// Normalize edit routing identically for parsing and usage-error reporting.
3763pub fn edit_arguments(
3764    command: &clap::Command,
3765    arguments: &[std::ffi::OsString],
3766) -> Vec<std::ffi::OsString> {
3767    edit_actions::route(&hoist_quiet(command, arguments), command)
3768}
3769
3770/// Requested protocol on a recognized typed edit route, respecting values and `--`:
3771/// the action name, whether the protocol is JSONL (else JSON), and the FILE
3772/// operand the tokens named when they carried one before the grammar failure
3773/// (used to keep the usage envelope's `source.path` honest).
3774pub fn typed_edit_protocol(
3775    arguments: &[std::ffi::OsString],
3776) -> Option<(String, bool, Option<String>)> {
3777    let model = top_level_command();
3778    let routed = edit_arguments(&model, arguments);
3779    if routed.get(1).is_none_or(|a| a != "__edit-v2") {
3780        return None;
3781    }
3782    let typed = model.find_subcommand("__edit-v2")?;
3783    let tokens: Vec<_> = routed
3784        .iter()
3785        .skip(2)
3786        .filter_map(|a| a.to_str())
3787        .take_while(|a| *a != "--")
3788        .collect();
3789    let (_, at) = spelled_options(typed, &tokens);
3790    let action = *tokens.get(at)?;
3791    let command = typed.find_subcommand(action)?;
3792    let mut rest = &tokens[at + 1..];
3793    let mut json = false;
3794    let mut jsonl = false;
3795    let mut file = None;
3796    while !rest.is_empty() {
3797        let (options, next) = spelled_options(command, rest);
3798        for option in options {
3799            json |= option.name == "--json";
3800            jsonl |= option.name == "--jsonl";
3801        }
3802        // The action's leading positional is its FILE operand.
3803        if file.is_none()
3804            && let Some(operand) = rest.get(next)
3805        {
3806            file = Some(operand.to_string());
3807        }
3808        rest = rest.get(next + 1..).unwrap_or_default();
3809    }
3810    (json || jsonl).then(|| (action.to_string(), jsonl, file))
3811}
3812
3813/// `argv` (the arguments after the program name) as a dry run's `next:`
3814/// command: without its `--dry-run` flag, and with `--force` before any
3815/// `--` when `force`. A `--dry-run` that is no flag stays: a FILE after
3816/// `--`, or an option's value (`--text --dry-run`). Pure: no I/O.
3817pub fn next_command(argv: &[String], force: bool) -> Vec<String> {
3818    next_command_to(argv, force, None)
3819}
3820
3821/// [`next_command`], naming `output` as `-o OUTPUT` when the dry run named
3822/// no output (#1847): the default it writes, so the command run as printed
3823/// cannot write elsewhere. It goes ahead of `--force`, before any `--`.
3824pub fn next_command_to(argv: &[String], force: bool, output: Option<&str>) -> Vec<String> {
3825    let model = top_level_command();
3826    let arguments: Vec<std::ffi::OsString> = std::iter::once("jubarte".into())
3827        .chain(argv.iter().map(Into::into))
3828        .collect();
3829    // Read as the parser reads it (the typed edit forms routed), then
3830    // matched back to `argv` by count: routing moves no `--dry-run`.
3831    let routed = edit_arguments(&model, &arguments);
3832    let tokens: Vec<&str> = routed
3833        .iter()
3834        .skip(1)
3835        .filter_map(|a| a.to_str())
3836        .take_while(|a| *a != "--")
3837        .collect();
3838    let mut flags = std::collections::BTreeSet::new();
3839    let mut command = &model;
3840    let mut start = 0;
3841    loop {
3842        let (options, next) = spelled_options(command, &tokens[start..]);
3843        flags.extend(
3844            options
3845                .iter()
3846                .filter(|option| option.name == "--dry-run")
3847                .map(|option| start + option.at),
3848        );
3849        let Some(word) = tokens.get(start + next) else {
3850            break;
3851        };
3852        if let Some(task) = command.find_subcommand(word) {
3853            command = task;
3854        }
3855        start += next + 1;
3856    }
3857    // Which of the tokens spelled `--dry-run`, in order, are the flag.
3858    let dropped: std::collections::BTreeSet<usize> = tokens
3859        .iter()
3860        .enumerate()
3861        .filter(|(_, token)| **token == "--dry-run")
3862        .enumerate()
3863        .filter(|(_, (at, _))| flags.contains(at))
3864        .map(|(nth, _)| nth)
3865        .collect();
3866    let tail = |next: &mut Vec<String>| {
3867        if let Some(output) = output {
3868            next.extend(["-o".to_string(), output.to_string()]);
3869        }
3870        if force {
3871            next.push("--force".to_string());
3872        }
3873    };
3874    let mut next = Vec::with_capacity(argv.len() + 3);
3875    let mut spelled = 0;
3876    let mut delimited = false;
3877    for arg in argv {
3878        if !delimited && arg == "--" {
3879            delimited = true;
3880            tail(&mut next);
3881        }
3882        if !delimited && arg == "--dry-run" {
3883            spelled += 1;
3884            if dropped.contains(&(spelled - 1)) {
3885                continue;
3886            }
3887        }
3888        next.push(arg.clone());
3889    }
3890    if !delimited {
3891        tail(&mut next);
3892    }
3893    next
3894}
3895
3896/// The first positional operand the tokens name for `cmd`, when they carry
3897/// one before any grammar failure: options and their values are skipped
3898/// through the command model's own spelling, so an option's value is never
3899/// mistaken for the operand. Recognized-mode usage envelopes use it to name
3900/// the file the caller supplied (proposal §11: `source` keeps the path).
3901pub fn first_positional(cmd: &clap::Command, tokens: &[&str]) -> Option<String> {
3902    let (_, at) = spelled_options(cmd, tokens);
3903    tokens.get(at).map(ToString::to_string)
3904}
3905
3906impl Cli {
3907    /// Parse native arguments with clap and validate cross-option constraints.
3908    pub fn try_parse_from<I, T>(arguments: I) -> Result<Self, clap::Error>
3909    where
3910        I: IntoIterator<Item = T>,
3911        T: Into<std::ffi::OsString> + Clone,
3912    {
3913        let mut command = top_level_command();
3914        let arguments: Vec<std::ffi::OsString> = arguments.into_iter().map(Into::into).collect();
3915        let arguments = edit_arguments(&command, &arguments);
3916        let matches = command
3917            .try_get_matches_from_mut(arguments.clone())
3918            .map_err(|e| {
3919                let tokens: Vec<String> = arguments
3920                    .iter()
3921                    .map(|a| a.to_string_lossy().into_owned())
3922                    .collect();
3923                usage_error(&command, &tokens, e)
3924            })?;
3925        validate_matches(&matches, &mut command)?;
3926        let mut cli = Self::from_arg_matches(&matches)?;
3927        if let Some(task) = cli.command.as_mut() {
3928            fill_flag_operations(task, &matches, &mut command)?;
3929            resolve_plan(task);
3930            let typed: Vec<String> = arguments
3931                .iter()
3932                .skip(1)
3933                .map(|a| a.to_string_lossy().into_owned())
3934                .collect();
3935            apply_retired(task, &retired_spellings(typed.iter().map(String::as_str)));
3936            fill_task_date(task);
3937        } else {
3938            fill_date(&mut cli.compare.datetime);
3939        }
3940        match (cli.command.as_mut(), matches.subcommand()) {
3941            (Some(Command::Compare(compare)), Some((_, args))) => {
3942                compare.view_given = view_given(args);
3943            }
3944            (Some(Command::TypedEdit(typed)), Some((_, args))) => {
3945                mark_typed_author(typed, args, &mut command)?;
3946            }
3947            (None, _) => cli.compare.view_given = view_given(&matches),
3948            _ => {}
3949        }
3950        Ok(cli)
3951    }
3952}
3953
3954/// `-a` on a typed edit is explicit only when the command line spelled it;
3955/// `JUBARTE_AUTHOR` counts the same (#1997). The default `"Jubarte"` is
3956/// not. `edit apply` has no author flag.
3957fn mark_typed_author(
3958    typed: &mut edit_actions::TypedEdit,
3959    args: &clap::ArgMatches,
3960    command: &mut clap::Command,
3961) -> Result<(), clap::Error> {
3962    let Some((_, action)) = args.subcommand() else {
3963        return Ok(());
3964    };
3965    let given = action.try_contains_id("author").unwrap_or(false)
3966        && action.value_source("author") == Some(clap::parser::ValueSource::CommandLine);
3967    let Some(inline) = typed.action.inline_mut() else {
3968        return Ok(());
3969    };
3970    inline.author_given = given;
3971    env_author_fill(&mut inline.author, &mut inline.author_given)
3972        .map_err(|m| command.error(clap::error::ErrorKind::ValueValidation, m))?;
3973    Ok(())
3974}
3975
3976/// Whether `matches` spells out any of `read`'s options.
3977fn view_given(matches: &clap::ArgMatches) -> bool {
3978    READ_OPTION_IDS.into_iter().any(|id| {
3979        matches.try_contains_id(id).unwrap_or(false)
3980            && matches.value_source(id) == Some(clap::parser::ValueSource::CommandLine)
3981    })
3982}
3983
3984fn compare_json(compare: &CompareArgs) -> serde_json::Value {
3985    let mut args = serde_json::to_value(compare).expect("UTF-8 CLI arguments");
3986    // Named inputs win, as in the native executor. Keep the raw positional
3987    // fields too, so adapters never have to reproduce precedence rules.
3988    args["original"] =
3989        serde_json::to_value(compare.original.as_ref().or(compare.original_pos.as_ref()))
3990            .expect("UTF-8 path");
3991    args["modified"] =
3992        serde_json::to_value(compare.modified.as_ref().or(compare.modified_pos.as_ref()))
3993            .expect("UTF-8 path");
3994    let input_format = |path: Option<&PathBuf>| {
3995        path.and_then(|p| Format::of_path(p))
3996            .filter(|f| matches!(f, Format::Docx | Format::Md))
3997    };
3998    args["old_format"] = serde_json::to_value(input_format(
3999        compare.original.as_ref().or(compare.original_pos.as_ref()),
4000    ))
4001    .expect("format");
4002    args["new_format"] = serde_json::to_value(input_format(
4003        compare.modified.as_ref().or(compare.modified_pos.as_ref()),
4004    ))
4005    .expect("format");
4006    // validate_matches refused a format compare cannot write.
4007    let kind = output_format(Task::Compare, compare.output.as_deref(), None)
4008        .ok()
4009        .flatten();
4010    args["output_format"] = serde_json::to_value(kind).expect("format");
4011    // The view's options, when the view may be what compare gives: printed
4012    // without -o, or written to a .md. Only the host, once it has read
4013    // both documents, knows whether a .md is CriticMarkup (both Markdown:
4014    // `view_given` must be false) or the view.
4015    if matches!(kind, None | Some(Format::Md)) {
4016        args["view"] = serde_json::to_value(&compare.read).expect("UTF-8 CLI arguments");
4017    }
4018    args
4019}
4020
4021/// Whether compare's result is surely the agent view: printed, or a .md of
4022/// documents whose names do not both say Markdown. A host without `read`
4023/// refuses it.
4024fn view_is_output(args: &serde_json::Value) -> bool {
4025    let markdown = |format: &serde_json::Value| format == "md";
4026    args["output_format"].is_null()
4027        || (args["output_format"] == "md"
4028            && !(markdown(&args["old_format"]) && markdown(&args["new_format"])))
4029}
4030
4031/// A comparison whose result is the agent view, in an adapter without
4032/// `read`: only `-o` with a file that is not the view works there.
4033fn view_not_supported(command: &mut clap::Command) -> clap::Error {
4034    command.error(
4035        clap::error::ErrorKind::InvalidSubcommand,
4036        "this adapter prints no agent view; write the redline with -o FILE.docx",
4037    )
4038}
4039
4040fn error_json(error: &clap::Error) -> String {
4041    serde_json::json!({
4042        "exit_code": error.exit_code(),
4043        "stream": if error.use_stderr() { "stderr" } else { "stdout" },
4044        "text": error.to_string(),
4045    })
4046    .to_string()
4047}
4048
4049/// Whether a command line (without the program name) asks for JSON: a
4050/// `--json` flag before any `--`. An error then prints on stdout too, as one
4051/// [`json_error`] line, for a reader that pipes stdout to a JSON parser
4052/// (#1158); stderr and the exit code stay as they are.
4053pub fn wants_json(argv: &[String]) -> bool {
4054    // Read as the typed edit protocol reads it: a `--json` where an option
4055    // takes its value (`--text --json`) is no request for JSON.
4056    let model = top_level_command();
4057    let arguments: Vec<std::ffi::OsString> = std::iter::once("jubarte".into())
4058        .chain(argv.iter().map(Into::into))
4059        .collect();
4060    let routed = edit_arguments(&model, &arguments);
4061    let tokens: Vec<&str> = routed
4062        .iter()
4063        .skip(1)
4064        .filter_map(|a| a.to_str())
4065        .take_while(|a| *a != "--")
4066        .collect();
4067    let mut command = &model;
4068    let mut rest = &tokens[..];
4069    loop {
4070        let (options, next) = spelled_options(command, rest);
4071        if options.iter().any(|option| option.name == "--json") {
4072            return true;
4073        }
4074        let Some(word) = rest.get(next) else {
4075            return false;
4076        };
4077        if let Some(task) = command.find_subcommand(word) {
4078            command = task;
4079        }
4080        rest = &rest[next + 1..];
4081    }
4082}
4083
4084/// `{"error":{"code":…,"message":…,"usage":…}}` and a newline: the line an
4085/// error prints on stdout under `--json`. `usage` only when given.
4086pub fn json_error(code: &str, message: &str, usage: Option<&str>) -> String {
4087    let mut error = serde_json::json!({ "code": code, "message": message });
4088    if let Some(usage) = usage {
4089        error["usage"] = usage.into();
4090    }
4091    format!("{}\n", serde_json::json!({ "error": error }))
4092}
4093
4094/// The [`json_error`] line of a runtime error that ends a run with `exit`,
4095/// `message` being what follows `error: ` on stderr. Its code is the
4096/// message's leading `CODE:` (`STALE_SOURCE: …`), else `USAGE` for an exit
4097/// 2 and `ERROR` for any other.
4098pub fn runtime_json_error(message: &str, exit: u8) -> String {
4099    let lead = message.split_once(": ").map_or("", |(lead, _)| lead);
4100    let coded = lead.len() >= 3
4101        && lead.starts_with(|c: char| c.is_ascii_uppercase())
4102        && lead
4103            .chars()
4104            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
4105    let code = if coded {
4106        lead
4107    } else if exit == 2 {
4108        "USAGE"
4109    } else {
4110        "ERROR"
4111    };
4112    json_error(code, message, None)
4113}
4114
4115/// The [`json_error`] line of a usage error clap reports for `argv` (no
4116/// program name) run as `program`: its message without `error: `, on one
4117/// line (a list clap names under it joined on, each tip after it), and the
4118/// task's usage (`jubarte read [OPTIONS] <FILE>`; clap's own usage, which
4119/// names the flags given, when no task is named), a line per form. `None`
4120/// for help and version, which are not errors.
4121pub fn usage_json_error(error: &clap::Error, argv: &[String], program: &str) -> Option<String> {
4122    let (message, usage) = usage_parts(error, argv, program)?;
4123    Some(json_error("USAGE", &message, usage.as_deref()))
4124}
4125
4126/// The [`json_error`] line of a removed spelling's error, `message` being
4127/// what follows `error: ` ([`removed_error`]), with the usage
4128/// [`usage_json_error`] gives clap's `error` for the same `argv`.
4129pub fn removed_json_error(
4130    error: &clap::Error,
4131    argv: &[String],
4132    program: &str,
4133    message: &str,
4134) -> String {
4135    let usage = usage_parts(error, argv, program).and_then(|(_, usage)| usage);
4136    json_error("USAGE", message, usage.as_deref())
4137}
4138
4139/// [`usage_json_error`]'s message and usage.
4140fn usage_parts(
4141    error: &clap::Error,
4142    argv: &[String],
4143    program: &str,
4144) -> Option<(String, Option<String>)> {
4145    if !error.use_stderr() {
4146        return None;
4147    }
4148    #[derive(Clone, Copy)]
4149    enum Part {
4150        Message,
4151        Tip,
4152        Usage,
4153        Other,
4154    }
4155    let text = error.render().to_string();
4156    let (mut message, mut tips, mut usage) = (String::new(), Vec::<String>::new(), Vec::new());
4157    let mut part = Part::Other;
4158    // Blank lines part clap's text: the message, its tips, the usage and
4159    // the pointer to --help; an indented line goes on with its part.
4160    for line in text.lines() {
4161        let trimmed = line.trim();
4162        if let Some(first) = line.strip_prefix("error: ") {
4163            message.push_str(first);
4164            part = Part::Message;
4165        } else if let Some(tip) = trimmed.strip_prefix("tip: ") {
4166            tips.push(tip.to_string());
4167            part = Part::Tip;
4168        } else if let Some(first) = line.strip_prefix("Usage: ") {
4169            usage.push(first.trim());
4170            part = Part::Usage;
4171        } else if trimmed.is_empty() {
4172            part = Part::Other;
4173        } else {
4174            match (part, tips.last_mut()) {
4175                (Part::Message, _) => {
4176                    message.push(' ');
4177                    message.push_str(trimmed);
4178                }
4179                (Part::Tip, Some(tip)) => {
4180                    tip.push(' ');
4181                    tip.push_str(trimmed);
4182                }
4183                (Part::Usage, _) => usage.push(trimmed),
4184                _ => {}
4185            }
4186        }
4187    }
4188    for tip in tips {
4189        message.push_str(&format!(" (tip: {tip})"));
4190    }
4191    let usage = task_usage(argv, program).or_else(|| (!usage.is_empty()).then(|| usage.join("\n")));
4192    Some((message, usage))
4193}
4194
4195/// The usage of the task `argv` names (`jubarte read [OPTIONS] <FILE>`), a
4196/// line per form, or `None` when its first word is no task.
4197fn task_usage(argv: &[String], program: &str) -> Option<String> {
4198    let mut model = Cli::command().bin_name(program.to_string());
4199    model.build();
4200    let name = argv
4201        .iter()
4202        .take_while(|a| *a != "--")
4203        .find(|a| !a.starts_with('-'))?;
4204    let usage = model.find_subcommand_mut(name)?.render_usage().to_string();
4205    let usage = usage.strip_prefix("Usage: ")?;
4206    Some(usage.lines().map(str::trim).collect::<Vec<_>>().join("\n"))
4207}
4208
4209/// The usage error for a task the host (`program`) does not have.
4210fn missing_task(command: &mut clap::Command, program: &str, task: &str) -> clap::Error {
4211    command.error(
4212        clap::error::ErrorKind::InvalidSubcommand,
4213        format!("this {program} has no {task} task; the `jubarte` binary has it"),
4214    )
4215}
4216
4217/// The `{exit_code, command, args}` value for a subcommand clap matched:
4218/// the task with its flag operations, plan, retired spellings and date
4219/// resolved, and compare's view or read routing. [`parse_json`] adds
4220/// `args.quiet` and `notes` to it.
4221fn parse_subcommand_json(
4222    command: &mut clap::Command,
4223    matches: &clap::ArgMatches,
4224    arguments: &[String],
4225    accepts: &dyn Fn(&str) -> bool,
4226) -> Result<serde_json::Value, clap::Error> {
4227    let mut task = Command::from_arg_matches(matches)?;
4228    fill_flag_operations(&mut task, matches, command)?;
4229    resolve_plan(&mut task);
4230    apply_retired(
4231        &mut task,
4232        &retired_spellings(arguments.iter().map(String::as_str)),
4233    );
4234    fill_task_date(&mut task);
4235    let mut value = serde_json::to_value(&task).expect("UTF-8 CLI arguments");
4236    if let Command::Compare(compare) = &mut task {
4237        if let Some((_, args)) = matches.subcommand() {
4238            compare.view_given = view_given(args);
4239        }
4240        value["args"] = compare_json(compare);
4241        if view_is_output(&value["args"]) && !accepts("read") {
4242            return Err(view_not_supported(command));
4243        }
4244    }
4245    if let Command::Diff {
4246        old,
4247        new,
4248        output,
4249        to,
4250        from,
4251        ..
4252    } = &task
4253    {
4254        let input_format = |path: &std::path::Path| {
4255            from.or_else(|| {
4256                Format::of_path(path).filter(|f| matches!(f, Format::Docx | Format::Md))
4257            })
4258        };
4259        value["args"]["old_format"] = serde_json::to_value(input_format(old)).expect("format");
4260        value["args"]["new_format"] = serde_json::to_value(input_format(new)).expect("format");
4261        value["args"]["output_format"] = serde_json::to_value(
4262            output_format(Task::Diff, output.as_deref(), *to)
4263                .ok()
4264                .flatten(),
4265        )
4266        .expect("format");
4267    }
4268    if let Command::Convert {
4269        output,
4270        markdown,
4271        pdf,
4272        png,
4273        ..
4274    } = &task
4275    {
4276        let alias = pdf
4277            .then_some(Format::Pdf)
4278            .or_else(|| png.then_some(Format::Png));
4279        value["args"]["output_format"] = serde_json::to_value(
4280            output_format(Task::Convert, output.as_deref(), markdown.to.or(alias))
4281                .ok()
4282                .flatten(),
4283        )
4284        .expect("format");
4285    }
4286    if let Command::Edit {
4287        file,
4288        options,
4289        plan,
4290        operations,
4291        ..
4292    }
4293    | Command::Add {
4294        file,
4295        options,
4296        plan,
4297        operations,
4298        ..
4299    } = &task
4300    {
4301        let recording = plan.is_some() && !operations.is_empty();
4302        let (output, out_dir) = match options.target(file) {
4303            _ if recording => (None, None),
4304            EditTarget::Single(path) => (Some(path), None),
4305            EditTarget::Bundle(dir) => (None, Some(dir)),
4306        };
4307        let slashed = |path: Option<&std::path::PathBuf>| {
4308            path.map(|p| serde_json::Value::String(slash_path(p)))
4309                .unwrap_or(serde_json::Value::Null)
4310        };
4311        value["args"]["plan"] = slashed(plan.as_ref());
4312        value["args"]["output"] = slashed(output.as_ref());
4313        value["args"]["out_dir"] = slashed(out_dir.as_ref());
4314        // `author_given` is skipped by serde. The Python executor needs it
4315        // for the same `#1997` AUTHOR_REQUIRED refusal the binary makes.
4316        value["args"]["author_given"] = serde_json::Value::Bool(options.author_given);
4317    }
4318    let written = match &task {
4319        Command::Accept {
4320            file,
4321            output,
4322            in_place,
4323            ..
4324        } => {
4325            if *in_place {
4326                value["args"]["output"] = serde_json::Value::String(slash_path(file));
4327            }
4328            Some((
4329                Task::Accept,
4330                if *in_place {
4331                    Some(file.as_path())
4332                } else {
4333                    output.as_deref()
4334                },
4335            ))
4336        }
4337        Command::Reject {
4338            file,
4339            output,
4340            in_place,
4341            ..
4342        } => {
4343            if *in_place {
4344                value["args"]["output"] = serde_json::Value::String(slash_path(file));
4345            }
4346            Some((
4347                Task::Reject,
4348                if *in_place {
4349                    Some(file.as_path())
4350                } else {
4351                    output.as_deref()
4352                },
4353            ))
4354        }
4355        Command::Append { output, .. } => Some((Task::Append, Some(output.as_path()))),
4356        Command::Scrub { output, .. } => Some((Task::Scrub, Some(output.as_path()))),
4357        Command::Read { output, .. } => Some((Task::Read, output.as_deref())),
4358        _ => None,
4359    };
4360    if let Some((writer, output)) = written {
4361        // `--in-place` always publishes a DOCX, even when FILE is named
4362        // `contract.json` or `notes.md`. The extension is not the format.
4363        let format = if matches!(
4364            &task,
4365            Command::Accept { in_place: true, .. } | Command::Reject { in_place: true, .. }
4366        ) {
4367            Some(Format::Docx)
4368        } else {
4369            output_format(writer, output, None).ok().flatten()
4370        };
4371        value["args"]["output_format"] = serde_json::to_value(format).expect("format");
4372    }
4373    value["exit_code"] = 0.into();
4374    Ok(value)
4375}
4376
4377fn parse_implicit_compare_json(
4378    command: &mut clap::Command,
4379    matches: &clap::ArgMatches,
4380    model: &clap::Command,
4381    program: &str,
4382    accepts: &dyn Fn(&str) -> bool,
4383) -> Result<serde_json::Value, clap::Error> {
4384    let mut compare = CompareArgs::from_arg_matches(matches)?;
4385    fill_date(&mut compare.datetime);
4386    if let Some(name) = compare
4387        .original_pos
4388        .as_ref()
4389        .and_then(|p| p.to_str())
4390        .and_then(|name| model.find_subcommand(name))
4391        .map(|task| task.get_name().to_string())
4392        .filter(|name| !accepts(name))
4393    {
4394        return Err(missing_task(command, program, &name));
4395    }
4396    if compare.modified.is_none() && compare.modified_pos.is_none() {
4397        if !accepts("read") {
4398            return Err(command.error(
4399                clap::error::ErrorKind::InvalidSubcommand,
4400                "this task is not supported by this adapter",
4401            ));
4402        }
4403        let mut args = serde_json::to_value(&compare.read).expect("UTF-8 CLI arguments");
4404        args["file"] =
4405            serde_json::to_value(compare.original.as_ref().or(compare.original_pos.as_ref()))
4406                .expect("UTF-8 path");
4407        args["output"] = serde_json::to_value(&compare.output).expect("UTF-8 path");
4408        args["force"] = compare.force.into();
4409        args["output_format"] = serde_json::to_value(
4410            output_format(Task::Read, compare.output.as_deref(), None)
4411                .ok()
4412                .flatten(),
4413        )
4414        .expect("format");
4415        return Ok(serde_json::json!({"exit_code": 0, "command": "read", "args": args}));
4416    }
4417    compare.view_given = view_given(matches);
4418    let args = compare_json(&compare);
4419    if view_is_output(&args) && !accepts("read") {
4420        return Err(view_not_supported(command));
4421    }
4422    Ok(serde_json::json!({"exit_code": 0, "command": "compare", "args": args}))
4423}
4424
4425/// Parse arguments (excluding argv0) for native-compatible adapters.
4426///
4427/// `supported` contains canonical command names; empty enables every command.
4428/// Aliases follow their canonical command. Unsupported commands are absent
4429/// from help and rejected. Success contains `{exit_code, command, args,
4430/// notes}`: `args.quiet` is the global `-q`, and `notes` holds the
4431/// [`retired_note`] of each retired spelling used. `args` has
4432/// native snake_case field names, flattened Args groups, canonical enum strings,
4433/// string paths, defaults and null optional fields. Nested subcommands use
4434/// `{command, args}`. Compare inputs include resolved named-over-positional
4435/// values; compare's output path stays null (the host picks it), while the
4436/// author is `Jubarte` (D12) and the date now (D17), as for the binary.
4437/// `edit` and `add` carry where they write, resolved: `output` for the one
4438/// document or `out_dir` for the bundle, both null while recording into a plan. Informational/error results contain
4439/// `{exit_code, stream, text}`.
4440/// This function performs no document, filesystem, network or process I/O.
4441pub fn parse_json(arguments: &[String], program: &str, supported: &[String]) -> String {
4442    let model = top_level_command();
4443    let accepts = |name: &str| supported.is_empty() || supported.iter().any(|s| s == name);
4444    // Rebuild only the outer presentation, cloning every argument/group/task
4445    // from the derive model. Clap itself parses both native and facade inputs.
4446    let mut command = clap::Command::new(program.to_string())
4447        .version(env!("JUBARTE_BUILD_VERSION"))
4448        .help_template("{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{all-args}{after-help}")
4449        .about("Read, edit, compare and render Word documents")
4450        .color(clap::ColorChoice::Never)
4451        .styles(styles())
4452        .term_width(88)
4453        .subcommand_help_heading("Tasks")
4454        .arg_required_else_help(true)
4455        .subcommands(
4456            model
4457                .get_subcommands()
4458                .filter(|s| accepts(s.get_name()) || s.get_name() == "__edit-v2" && accepts("edit"))
4459                .cloned(),
4460        );
4461    if accepts("compare") {
4462        command = command
4463            .args(model.get_arguments().cloned())
4464            .groups(model.get_groups().cloned())
4465            .args_conflicts_with_subcommands(true)
4466            .subcommand_negates_reqs(true);
4467    } else {
4468        // The global options (-q) still apply to every task.
4469        command = command
4470            .args(model.get_arguments().filter(|a| a.is_global_set()).cloned())
4471            .args_conflicts_with_subcommands(true)
4472            .subcommand_required(true);
4473    }
4474    let examples: Vec<String> = [
4475        ("compare", "compare old.docx new.docx -o redline.docx"),
4476        ("read", "contract.docx"),
4477        ("read", "read contract.docx --json"),
4478        ("diff", "diff old.docx new.docx --format github"),
4479        ("convert", "convert contract.docx -o contract.pdf"),
4480    ]
4481    .into_iter()
4482    .filter(|(name, _)| accepts(name))
4483    .map(|(_, example)| format!("  {program} {example}"))
4484    .collect();
4485    command = command.after_help(format!(
4486        "Examples:\n{}\n\nRun {program} <task> --help for task options.",
4487        examples.join("\n")
4488    ));
4489    let argv = std::iter::once(program.to_string()).chain(arguments.iter().cloned());
4490    let mut quiet = false;
4491    let result = (|| {
4492        // A task this host lacks is one error, whatever follows its name.
4493        if let Some(name) = arguments
4494            .iter()
4495            .take_while(|token| *token != "--")
4496            .find(|token| !token.starts_with('-'))
4497            .and_then(|name| model.find_subcommand(name))
4498            .map(|task| task.get_name().to_string())
4499            .filter(|name| !accepts(name))
4500        {
4501            return Err(missing_task(&mut command, program, &name));
4502        }
4503        let tokens: Vec<String> = hoist_quiet(&command, &argv.collect::<Vec<_>>());
4504        let tokens: Vec<String> = edit_actions::route(
4505            &tokens
4506                .iter()
4507                .map(std::ffi::OsString::from)
4508                .collect::<Vec<_>>(),
4509            &command,
4510        )
4511        .into_iter()
4512        .map(|s| s.to_string_lossy().into_owned())
4513        .collect();
4514        let matches = command
4515            .try_get_matches_from_mut(tokens.clone())
4516            .map_err(|e| usage_error(&command, &tokens, e))?;
4517        validate_matches(&matches, &mut command)?;
4518        quiet = matches.get_flag("quiet");
4519        if matches.subcommand().is_some() {
4520            parse_subcommand_json(&mut command, &matches, arguments, &accepts)
4521        } else {
4522            parse_implicit_compare_json(&mut command, &matches, &model, program, &accepts)
4523        }
4524    })();
4525    match result {
4526        Ok(mut value) => {
4527            value["args"]["quiet"] = quiet.into();
4528            value["notes"] = notes(arguments).into();
4529            value.to_string()
4530        }
4531        Err(error) => match removed_spellings(arguments.iter().map(String::as_str)).first() {
4532            Some((old, now)) => {
4533                let removed = removed_error(old, now);
4534                let mut value = serde_json::json!({
4535                    "exit_code": 2,
4536                    "stream": "stderr",
4537                    "text": format!("{removed}\n"),
4538                });
4539                // Under --json, the line a host prints on stdout too.
4540                if wants_json(arguments) {
4541                    let message = removed.strip_prefix("error: ").unwrap_or(&removed);
4542                    value["json"] = removed_json_error(&error, arguments, program, message).into();
4543                }
4544                value.to_string()
4545            }
4546            None => {
4547                let mut value: serde_json::Value =
4548                    serde_json::from_str(&error_json(&error)).unwrap_or_default();
4549                // Help, version and usage errors carry the notes too: the
4550                // run that fails is the one that needs the new name. Hosts
4551                // print them before `text`.
4552                value["notes"] = notes(arguments).into();
4553                if wants_json(arguments)
4554                    && let Some(line) = usage_json_error(&error, arguments, program)
4555                {
4556                    value["json"] = line.into();
4557                }
4558                value.to_string()
4559            }
4560        },
4561    }
4562}
4563
4564#[cfg(test)]
4565mod slash_path_tests {
4566    use super::{slash_path, unverbatimed};
4567    use std::path::Path;
4568
4569    #[test]
4570    fn slash_path_uses_forward_slashes() {
4571        assert_eq!(slash_path(Path::new(r"dir\sub\name.md")), "dir/sub/name.md");
4572        assert_eq!(slash_path(Path::new("plain")), "plain");
4573    }
4574
4575    /// The agent-facing contract: a canonical drive-letter path spelled
4576    /// `C:/…` regardless of the OS the test runs on (#1244).
4577    #[test]
4578    fn slash_path_canonical_drive_letter_spells_agent_facing() {
4579        let formatted = slash_path(Path::new(r"C:\Users\Alice\out.docx"));
4580        assert_eq!(formatted, "C:/Users/Alice/out.docx");
4581        assert!(!formatted.contains('\\'), "backslashes: {formatted}");
4582    }
4583
4584    #[test]
4585    fn unverbatimed_keeps_every_nonverbatim_path() {
4586        // The parsed-component contract, portable: only a Windows verbatim
4587        // prefix is ever stripped, so a drive or UNC path keeps its head.
4588        for path in ["plain", r"dir\sub", r"C:\a\b", r"\\server\share\x"] {
4589            assert_eq!(unverbatimed(Path::new(path)), None, "{path}");
4590        }
4591    }
4592
4593    #[cfg(not(windows))]
4594    #[test]
4595    fn a_verbatim_literal_is_an_ordinary_name_off_windows() {
4596        for path in [r"\\?\C:\a\b", r"\\?\UNC\s\sh\x"] {
4597            assert_eq!(unverbatimed(Path::new(path)), None, "{path}");
4598        }
4599    }
4600
4601    #[cfg(windows)]
4602    #[test]
4603    fn unverbatimed_strips_every_verbatim_prefix_kind() {
4604        for (path, stripped) in [
4605            (r"\\?\C:\a\b", "C:/a/b"),
4606            (r"\\?\c:\a", "C:/a"),
4607            (r"\\?\C:", "C:"),
4608            (r"\\?\UNC\server\share\x", "//server/share/x"),
4609            (r"\\?\GLOBALROOT\Device\Foo", "GLOBALROOT/Device/Foo"),
4610        ] {
4611            assert_eq!(slash_path(Path::new(path)), stripped, "{path}");
4612            assert!(!slash_path(Path::new(path)).contains("//?"), "{path}");
4613        }
4614    }
4615
4616    #[cfg(windows)]
4617    #[test]
4618    fn unverbatimed_returns_the_stripped_components() {
4619        assert_eq!(
4620            unverbatimed(Path::new(r"\\?\C:\a\b")).as_deref(),
4621            Some(Path::new(r"C:\a\b"))
4622        );
4623        assert_eq!(
4624            unverbatimed(Path::new(r"\\?\UNC\server\share\x")).as_deref(),
4625            Some(Path::new(r"\\server\share\x"))
4626        );
4627    }
4628}
4629
4630#[cfg(test)]
4631#[cfg_attr(all(coverage_nightly, test), coverage(off))]
4632mod parse_branch_tests {
4633    use super::*;
4634
4635    fn parse(line: &str) -> Result<(), String> {
4636        let mut argv = vec!["jubarte".to_string()];
4637        argv.extend(line.split(' ').map(str::to_string));
4638        Cli::try_parse_from(argv)
4639            .map(drop)
4640            .map_err(|e| e.to_string())
4641    }
4642
4643    /// Each command line and the start of its refusal; empty for a line the
4644    /// parser accepts.
4645    const LINES: &[(&str, &str)] = &[
4646        (
4647            "edit x.docx -p p1 --anchor a --anchor b --content c",
4648            "-p p1: --anchor given twice",
4649        ),
4650        (
4651            "edit x.docx -p p1 --content a --content b",
4652            "-p p1: --content given twice",
4653        ),
4654        (
4655            "edit x.docx -p p1 --anchor a --occurrence 2 --occurrence 3 --content c",
4656            "-p p1: --occurrence given twice",
4657        ),
4658        (
4659            "edit x.docx --anchor a -p p1 --content c",
4660            "--anchor comes before the first -p/--location",
4661        ),
4662        (
4663            "edit x.docx -p p1 --occurrence 2 --content c",
4664            "-p p1: --occurrence must come after --anchor",
4665        ),
4666        (
4667            "edit x.docx -p c1 --reply hi --reply again",
4668            "-p c1: --reply given twice",
4669        ),
4670        ("edit x.docx -p c1 --resolve", ""),
4671        (
4672            "edit --plan doc.docx",
4673            "--plan doc.docx names a Word document",
4674        ),
4675        (
4676            "edit --plan=doc.docx",
4677            "--plan doc.docx names a Word document",
4678        ),
4679        (
4680            "edit --out-dir out.docx",
4681            "--out-dir out.docx names a Word document",
4682        ),
4683        ("convert a.docx -o .md", ""),
4684        ("convert a.md --from docx -o b.docx", ""),
4685        (
4686            "convert a.docx --pdf --pages 1,x",
4687            "'x' is not a page number",
4688        ),
4689        ("convert a.docx --pdf --pages 1-3,5", ""),
4690        ("read a.docx --for-edit -o out.md", "--for-edit prints JSON"),
4691        (
4692            "read a.docx --tables -o out.json",
4693            "--tables writes the grids as text",
4694        ),
4695        (
4696            "read a.docx --ignore-case",
4697            "--ignore-case needs --find TEXT or --regex PATTERN",
4698        ),
4699        ("read a.docx --ignore-case --for-edit", ""),
4700        ("compare original", "compare needs <MODIFIED>"),
4701        ("diff a.docx b.docx --format patch --columns 80", ""),
4702        (
4703            "diff a.docx b.docx --context 3",
4704            "--context requires a text diff format",
4705        ),
4706        (
4707            "diff a.docx b.docx --full-lines",
4708            "--full-lines requires a text diff format",
4709        ),
4710        (
4711            "edit insert x.docx --kind paragraph --at p1 --text hi -o y.docx",
4712            "--kind paragraph requires --position",
4713        ),
4714        (
4715            "edit insert x.docx --kind text --at p1 --text hi -o y.docx",
4716            "--kind paragraph requires --position",
4717        ),
4718        (
4719            "edit insert x.docx --kind text --position after --at p1 --text hi -o y.docx",
4720            "--kind paragraph requires --position",
4721        ),
4722        (
4723            "edit insert x.docx --kind paragraph --position after --at p1 --text hi -o y.docx",
4724            "",
4725        ),
4726        (
4727            "edit insert x.docx --kind text --edge end --at p1 --text hi -o y.docx",
4728            "",
4729        ),
4730        ("edit -q replace x.docx --find a --text b -o y.docx", ""),
4731        (
4732            "edit replace x.docx --find a --text b",
4733            "writes require -o FILE",
4734        ),
4735        (
4736            "edit replace x.docx --find a --text b --dry-run --expect-sha256 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
4737            "",
4738        ),
4739        (
4740            "edit replace x.docx --find a --text b --dry-run --expect-sha256 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
4741            "64 lowercase hexadecimal",
4742        ),
4743        (
4744            "edit replace x.docx --find a --text b --dry-run --expect-sha256 abc",
4745            "64 lowercase hexadecimal",
4746        ),
4747    ];
4748
4749    #[test]
4750    fn command_lines_parse_or_say_why_not() {
4751        for (line, refusal) in LINES {
4752            match parse(line) {
4753                Ok(()) => assert!(refusal.is_empty(), "{line} parsed"),
4754                Err(e) => {
4755                    assert!(!refusal.is_empty(), "{line}: {e}");
4756                    assert!(e.contains(refusal), "{line}: {e}");
4757                }
4758            }
4759        }
4760    }
4761
4762    #[test]
4763    fn json_errors_take_a_leading_upper_case_code() {
4764        let code = |message: &str| -> String {
4765            let v: serde_json::Value =
4766                serde_json::from_str(&runtime_json_error(message, 1)).unwrap();
4767            v["error"]["code"].as_str().unwrap().to_string()
4768        };
4769        assert_eq!(code("STALE_SOURCE: x"), "STALE_SOURCE");
4770        assert_eq!(code("AB_1: x"), "AB_1");
4771        assert_eq!(code("ab: x"), "ERROR");
4772        assert_eq!(code("Abc1: x"), "ERROR");
4773        assert_eq!(code("AB: x"), "ERROR");
4774        assert_eq!(code("nothing"), "ERROR");
4775    }
4776}