f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! Tab stops.

use f_office_units::Length;

use crate::props::{TabKind, TabStop};

/// The tab stops of one paragraph, measured from the left edge of the text column (or from
/// `origin` when a left floating wrap shifts custom and default tab stops before mode 15).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Tabs {
    stops: Vec<TabStop>,
    default: Length,
    hanging: Option<Length>,
    origin: Length,
    indent_after_custom: bool,
    truncates_negative_default: bool,
}

impl Tabs {
    /// Makes the stops of a paragraph from its custom stops, the default distance and, for a
    /// hanging indent, the left indent, which acts as one more stop.
    #[must_use]
    pub fn new(
        stops: impl IntoIterator<Item = TabStop>,
        default: Length,
        hanging: Option<Length>,
    ) -> Self {
        Self {
            stops: stops.into_iter().collect(),
            default,
            hanging,
            origin: Length::ZERO,
            indent_after_custom: false,
            truncates_negative_default: false,
        }
    }

    /// Whether `stop` is one of the paragraph's custom stops, and not its hanging indent or a
    /// default stop.
    #[must_use]
    pub fn is_custom(&self, stop: TabStop) -> bool {
        self.stops.iter().any(|&s| self.placed_custom(s) == stop)
    }

    /// Returns the stop that a tab starting at `from` moves to: the nearest custom stop or
    /// hanging indent after it, or else the next default stop.
    #[must_use]
    pub fn next(&self, from: Length) -> TabStop {
        self.next_stop(from).0
    }

    /// The stop that a tab at `from` moves to, as [`Tabs::next`] gives it, and whether that
    /// stop is a default stop.
    #[must_use]
    pub fn next_stop(&self, from: Length) -> (TabStop, bool) {
        let custom = self
            .stops
            .iter()
            .map(|&s| self.placed_custom(s))
            .find(|s| s.position > from);
        let hanging = self.hanging.filter(|h| *h > from).map(|position| TabStop {
            position,
            kind: TabKind::Left,
            leader: None,
        });
        let default = self.default_after(from);
        let nearest = match (custom, hanging) {
            (Some(c), Some(_)) if self.indent_after_custom => Some(c),
            (None, Some(h)) if self.indent_after_custom && default.position < h.position => None,
            (Some(c), Some(h)) => Some(if h.position < c.position { h } else { c }),
            (c, h) => c.or(h),
        };
        nearest.map_or((default, true), |stop| (stop, false))
    }

    /// Puts the hanging indent after the custom stops: a tab then moves to the next custom
    /// stop when there is one, also one beyond the indent, and else to the nearer of the
    /// indent and the next default stop. This is the tab after a list label in a document
    /// with `w:doNotUseIndentAsNumberingTabStop`.
    #[must_use]
    pub const fn with_indent_after_custom_stops(mut self) -> Self {
        self.indent_after_custom = true;
        self
    }

    /// Truncates `from / step` toward zero without adding 1 when `from < 0` (mode 15+), so
    /// exact negative multiples of the default tab step yield zero advance.
    #[must_use]
    pub(crate) const fn with_truncated_negative_default_tabs(mut self) -> Self {
        self.truncates_negative_default = true;
        self
    }

    /// Measures custom and default tab stops from `origin` (leaving the column-relative hanging
    /// indent stop unshifted) when a left floating wrap narrows a line before compatibility mode
    /// 15.
    pub(crate) const fn shift_origin(&mut self, origin: Length) {
        self.origin = origin;
    }

    fn placed_custom(&self, stop: TabStop) -> TabStop {
        TabStop {
            position: stop.position + self.origin,
            ..stop
        }
    }

    fn default_after(&self, from: Length) -> TabStop {
        let rel = from - self.origin;
        let step = self.default.max(Length::from_units(1));
        let steps = if self.truncates_negative_default && rel < Length::ZERO {
            rel.units() / step.units()
        } else {
            rel.units().div_euclid(step.units()) + 1
        };
        TabStop {
            position: self.origin + step * steps,
            kind: TabKind::Left,
            leader: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Tabs;
    use crate::props::{TabKind, TabStop};
    use f_office_units::Length;

    fn stop(position: i64, kind: TabKind) -> TabStop {
        TabStop {
            position: Length::from_units(position),
            kind,
            leader: None,
        }
    }

    #[test]
    fn custom_stops_come_before_defaults() {
        let tabs = Tabs::new([stop(250, TabKind::Right)], Length::from_units(100), None);
        assert_eq!(tabs.next(Length::from_units(10)).position.units(), 250);
        assert_eq!(tabs.next(Length::from_units(10)).kind, TabKind::Right);
        assert_eq!(tabs.next(Length::from_units(250)).position.units(), 300);
        assert_eq!(tabs.next(Length::from_units(-5)).position.units(), 250);
    }

    #[test]
    fn a_hanging_indent_is_a_stop() {
        let tabs = Tabs::new(
            [stop(500, TabKind::Left)],
            Length::from_units(100),
            Some(Length::from_units(300)),
        );
        assert_eq!(tabs.next(Length::from_units(120)).position.units(), 300);
        assert_eq!(tabs.next(Length::from_units(320)).position.units(), 500);
        let early = Tabs::new(
            [stop(200, TabKind::Left)],
            Length::from_units(100),
            Some(Length::from_units(300)),
        );
        assert_eq!(early.next(Length::from_units(120)).position.units(), 200);
        let none = Tabs::new([], Length::from_units(100), Some(Length::from_units(300)));
        assert_eq!(none.next(Length::from_units(350)).position.units(), 400);
    }

    #[test]
    fn a_hanging_indent_after_the_custom_stops_competes_with_the_default_stops() {
        let tabs = |stops: &[TabStop], default: i64| {
            Tabs::new(
                stops.iter().copied(),
                Length::from_units(default),
                Some(Length::from_units(300)),
            )
            .with_indent_after_custom_stops()
        };
        let next = |tabs: &Tabs, from: i64| tabs.next_stop(Length::from_units(from));
        // A custom stop beyond the indent wins over the indent.
        let custom = tabs(&[stop(500, TabKind::Left)], 100);
        assert_eq!(next(&custom, 220).0.position.units(), 500);
        // Without one, the nearer of the indent and the next default stop wins.
        let (stop_at, is_default) = next(&tabs(&[], 250), 220);
        assert_eq!((stop_at.position.units(), is_default), (250, true));
        let (stop_at, is_default) = next(&tabs(&[], 400), 220);
        assert_eq!((stop_at.position.units(), is_default), (300, false));
    }

    #[test]
    fn mode_15_truncates_negative_default_tab_steps_toward_zero() {
        let legacy = Tabs::new([], Length::from_units(720), None);
        let modern = legacy.clone().with_truncated_negative_default_tabs();
        // Exact negative multiples advance by one step before mode 15 and by zero in mode 15+.
        for (from, want_legacy, want_modern) in [
            (-1440, -720, -1440),
            (-1280, -720, -720),
            (-720, 0, -720),
            (-667, 0, 0),
            (0, 720, 720),
            (720, 1440, 1440),
        ] {
            let from = Length::from_units(from);
            assert_eq!(
                (
                    legacy.next(from).position.units(),
                    modern.next(from).position.units(),
                ),
                (want_legacy, want_modern),
            );
        }
    }

    #[test]
    fn shifted_origin_moves_custom_and_default_stops_but_not_hanging_indent() {
        let mut tabs = Tabs::new(
            [stop(720, TabKind::Left), stop(3000, TabKind::Right)],
            Length::from_units(708),
            Some(Length::from_units(2500)),
        );
        tabs.shift_origin(Length::from_units(1763));
        // Custom stops are measured from the shifted origin (1763 + 720 = 2483, 1763 + 3000 = 4763).
        let first = tabs.next(Length::from_units(1800));
        assert_eq!(first.position.units(), 2483);
        assert!(tabs.is_custom(first));
        // Column-relative hanging indent (2500) is NOT shifted and wins between 2483 and 4763.
        let hang = tabs.next(Length::from_units(2483));
        assert_eq!(hang.position.units(), 2500);
        assert!(!tabs.is_custom(hang));
        // Without custom stops, default stops step from origin (1763 + 708 = 2471, + 1416 = 3179).
        let mut plain = Tabs::new([], Length::from_units(708), Some(Length::from_units(714)));
        plain.shift_origin(Length::from_units(1763));
        assert_eq!(plain.next(Length::from_units(2120)).position.units(), 2471);
        assert_eq!(plain.next(Length::from_units(2483)).position.units(), 3179);
    }
}