Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

refactor(doc): split attrs.rs into attrs/

aiongg2dd87273a224
diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs
index 0227b9f80..26ff6036f 100644
--- a/crates/doc/src/attrs.rs
+++ b/crates/doc/src/attrs.rs
@@ -113,6 +113,26 @@ macro_rules! attr_set {
};
}
+mod enums;
+mod language;
+mod rules_lists;
+mod tabs;
+
+pub use enums::{
+ Align, Capitalization, ChangeMark, Composer, Digits, GrepStyle, GridAlign, Kerning, Leading, NestedLineStyle, NestedStyle, NestedUntil, Position,
+ SpanColumns, StartParagraph, TextDirection,
+};
+pub use language::{capitalizes, language_subtag, language_tag};
+use tabs::sanitized_tabs;
+use rules_lists::list_level_index;
+pub use rules_lists::{
+ BoxBottom, BoxTop, BoxWidth, LIST_LEVELS, ListAlign, ListCounter, ListType, NumberStyle, Rule, TEXT_COLOR, expand_list_levels, expand_list_text,
+};
+pub use tabs::{
+ MAX_MEASURE, MAX_TAB_LEADER, MAX_TAB_POSITION, MAX_TAB_STOPS, MAX_TYPE_SIZE, MIN_TYPE_SIZE, SAME_TAB_POSITION, TabAlign, TabStop,
+ imported_measure, imported_type_size,
+};
+
fn attr_key(snake: &'static str) -> &'static str {
snake
}
@@ -168,868 +188,6 @@ fn unknown_attribute(key: &str, fields: &[&str]) -> String {
}
}
-// ---------- value types ----------
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", tag = "kind", content = "value")]
-pub enum Leading {
- /// Auto leading (percentage of the largest size on the line, Justification → Auto Leading).
- #[default]
- Auto,
- Points(f64),
-}
-
-/// Paragraph direction.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum TextDirection {
- #[default]
- LeftToRight,
- RightToLeft,
-}
-
-/// Digits (World-Ready): the figures 0–9 are drawn as these.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum Digits {
- /// Contextual digits; composition selects the preceding strong script/language.
- #[default]
- Default,
- /// European (0123).
- Arabic,
- /// Arabic-Indic (٠١٢٣).
- Hindi,
- /// Extended Arabic-Indic, as used for Persian and Urdu (۰۱۲۳).
- Farsi,
- /// Those of the text's language (Thai, Devanagari, Bengali, Arabic, Persian…); else as typed.
- Native,
-}
-
-impl Digits {
- /// The digit `c` (0–9) is drawn as, for text in `language`.
- pub fn map(self, c: char, language: &str) -> char {
- let d = match c {
- '0'..='9' => c as u32 - '0' as u32,
- '\u{0660}'..='\u{0669}' => c as u32 - 0x0660,
- '\u{06F0}'..='\u{06F9}' => c as u32 - 0x06F0,
- _ => return c,
- };
- let zero = match self {
- Digits::Default => return c,
- Digits::Arabic => 0x0030,
- Digits::Hindi => 0x0660,
- Digits::Farsi => 0x06F0,
- Digits::Native => {
- let l = language.to_ascii_lowercase();
- match () {
- _ if l.starts_with("arabic") || l == "ar" || l.starts_with("ar-") => 0x0660,
- _ if l.starts_with("persian")
- || l.starts_with("farsi")
- || l.starts_with("urdu")
- || l == "fa"
- || l.starts_with("fa-")
- || l == "ur"
- || l.starts_with("ur-") =>
- {
- 0x06F0
- }
- _ if l.starts_with("hindi") || l.starts_with("marathi") || l.starts_with("nepali") || l.starts_with("sanskrit") => 0x0966,
- _ if l.starts_with("bengali") => 0x09E6,
- _ if l.starts_with("gujarati") => 0x0AE6,
- _ if l.starts_with("punjabi") => 0x0A66,
- _ if l.starts_with("tamil") => 0x0BE6,
- _ if l.starts_with("telugu") => 0x0C66,
- _ if l.starts_with("kannada") => 0x0CE6,
- _ if l.starts_with("malayalam") => 0x0D66,
- _ if l.starts_with("thai") => 0x0E50,
- _ if l.starts_with("lao") => 0x0ED0,
- _ if l.starts_with("tibetan") => 0x0F20,
- _ if l.starts_with("burmese") => 0x1040,
- _ if l.starts_with("khmer") => 0x17E0,
- _ => return c,
- }
- }
- };
- char::from_u32(zero + d).unwrap_or(c)
- }
-}
-
-/// Does `c` belong to a script that capitalizes the first letter of sentences, words and headings?
-/// Georgian doesn't: Unicode maps Mkhedruli to Mtavruli capitals, but those are only for all-caps
-/// text, never for a sentence's, a title's or an index heading's first letter.
-pub fn capitalizes(c: char) -> bool {
- !matches!(c, '\u{10A0}'..='\u{10FF}' | '\u{1C90}'..='\u{1CBF}' | '\u{2D00}'..='\u{2D2F}')
-}
-
-/// The BCP 47 tag of a language name as InDesign and IDML write it ("English: USA", "Chinese:
-/// Simplified", or a locale code such as "de_DE_2006"), for the shaper's localized forms (`locl`)
-/// and everything that depends on the language (quotes, hyphenation and spelling, line breaking,
-/// fallback fonts). A variant we don't know falls back to its language ("English: Australian" →
-/// `en`); an unknown language (or "[No Language]") has none. Case, punctuation and IDML's `$ID/`
-/// don't matter. Locale codes (`ll`, `ll_CC`, `ll-CC`, with a reform year after them as in
-/// `de_DE_2006`) are their tag (`de-DE`), and Chinese also goes by its other common spellings
-/// ("Simplified Chinese", "Chinese (Traditional)", "zh_CN", "zh-Hant").
-pub fn language_tag(language: &str) -> Option<&'static str> {
- let language = language.trim();
- let language = language.strip_prefix("$ID/").unwrap_or(language);
- let l = language.to_lowercase();
- let words: Vec<&str> = l.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect();
- let first = words.first().copied().unwrap_or("");
- let has = |any: &[&str]| words.iter().any(|w| any.contains(w));
- if first == "zh" || has(&["chinese"]) {
- // The script decides; then the name; then the region.
- return Some(if has(&["hans"]) {
- "zh-Hans"
- } else if has(&["hant"]) {
- "zh-Hant"
- } else if has(&["simplified", "cn", "sg"]) {
- "zh-Hans"
- } else if has(&["traditional", "tw", "hk", "mo"]) {
- "zh-Hant"
- } else {
- "zh"
- });
- }
- if let Some(tag) = locale_code(&words) {
- return intern_tag(tag);
- }
- let variant = match words.join(" ").as_str() {
- "english usa" => Some("en-US"),
- "english uk" => Some("en-GB"),
- "english canadian" => Some("en-CA"),
- "german swiss 2006 reform" | "german swiss" => Some("de-CH"),
- "french swiss" => Some("fr-CH"),
- "italian swiss" => Some("it-CH"),
- "spanish castilian" => Some("es-ES"),
- "french canadian" => Some("fr-CA"),
- "portuguese brazilian" => Some("pt-BR"),
- "norwegian bokmål" | "norwegian bokmal" => Some("nb"),
- "norwegian nynorsk" => Some("nn"),
- _ => None,
- };
- if variant.is_some() {
- return variant;
- }
- Some(match first {
- "english" => "en",
- "german" => "de",
- "french" => "fr",
- "spanish" => "es",
- "catalan" => "ca",
- "italian" => "it",
- "portuguese" => "pt",
- "dutch" => "nl",
- "danish" => "da",
- "swedish" => "sv",
- "norwegian" => "no",
- "finnish" => "fi",
- "polish" => "pl",
- "czech" => "cs",
- "slovak" => "sk",
- "hungarian" => "hu",
- "romanian" => "ro",
- "croatian" => "hr",
- "lithuanian" => "lt",
- "greek" => "el",
- "russian" => "ru",
- "ukrainian" => "uk",
- "bulgarian" => "bg",
- "serbian" => "sr",
- "macedonian" => "mk",
- "turkish" => "tr",
- "japanese" => "ja",
- "korean" => "ko",
- "arabic" => "ar",
- "persian" | "farsi" => "fa",
- "urdu" => "ur",
- "hebrew" => "he",
- "georgian" => "ka",
- _ => return None,
- })
-}
-
-/// The tag of a locale code split into lowercase `words`: a language (2 or 3 letters), then
-/// optionally a region (2 letters or 3 digits) and a reform year (4 digits) → `ll` or `ll-CC`.
-fn locale_code(words: &[&str]) -> Option<String> {
- let letters = |w: &str, n: std::ops::RangeInclusive<usize>| n.contains(&w.len()) && w.bytes().all(|b| b.is_ascii_lowercase());
- let digits = |w: &str, n: usize| w.len() == n && w.bytes().all(|b| b.is_ascii_digit());
- match *words {
- [lang] if letters(lang, 2..=3) => Some(lang.to_string()),
- [lang, region] | [lang, region, _] if letters(lang, 2..=3) && (letters(region, 2..=2) || digits(region, 3)) => {
- if let [_, _, year] = *words
- && !digits(year, 4)
- {
- return None;
- }
- Some(format!("{lang}-{}", region.to_ascii_uppercase()))
- }
- _ => None,
- }
-}
-
-/// `tag` as a `&'static str`: each distinct tag is kept once for the process. Language names come
-/// from documents, so at most [`MAX_TAGS`] are kept; past that a new tag is unknown (`None`).
-fn intern_tag(tag: String) -> Option<&'static str> {
- const MAX_TAGS: usize = 512;
- static TAGS: std::sync::Mutex<Vec<&str>> = std::sync::Mutex::new(Vec::new());
- let mut tags = TAGS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
- if let Some(t) = tags.iter().find(|t| **t == tag) {
- return Some(t);
- }
- if tags.len() >= MAX_TAGS {
- return None;
- }
- let t: &'static str = Box::leak(tag.into_boxed_str());
- tags.push(t);
- Some(t)
-}
-
-/// The language subtag of a BCP 47 tag (`de-DE` → `de`, `zh-Hant` → `zh`).
-pub fn language_subtag(tag: &str) -> &str {
- tag.split('-').next().unwrap_or(tag)
-}
-
-/// A tracked change on text.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum ChangeMark {
- #[default]
- None,
- Inserted,
- Deleted,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", tag = "kind", content = "value")]
-pub enum Kerning {
- #[default]
- Metrics,
- Optical,
- /// Zero ("0" in the kerning menu).
- None,
- /// Manual pair kerning in 1/1000 em (applies after this character).
- Manual(f64),
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum Capitalization {
- #[default]
- Normal,
- AllCaps,
- SmallCaps,
- OpenTypeAllSmallCaps,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum Position {
- #[default]
- Normal,
- Superscript,
- Subscript,
- OtSuperscript,
- OtSubscript,
- OtNumerator,
- OtDenominator,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum Align {
- #[default]
- Left,
- Center,
- Right,
- LeftJustified,
- CenterJustified,
- RightJustified,
- FullyJustified,
- TowardsSpine,
- AwayFromSpine,
-}
-
-impl Align {
- pub fn is_justified(self) -> bool {
- matches!(self, Align::LeftJustified | Align::CenterJustified | Align::RightJustified | Align::FullyJustified)
- }
- pub const ALL: [Align; 9] = [
- Align::Left,
- Align::Center,
- Align::Right,
- Align::LeftJustified,
- Align::CenterJustified,
- Align::RightJustified,
- Align::FullyJustified,
- Align::TowardsSpine,
- Align::AwayFromSpine,
- ];
- pub fn label(self) -> &'static str {
- match self {
- Align::Left => "Align left",
- Align::Center => "Align center",
- Align::Right => "Align right",
- Align::LeftJustified => "Justify with last line aligned left",
- Align::CenterJustified => "Justify with last line aligned center",
- Align::RightJustified => "Justify with last line aligned right",
- Align::FullyJustified => "Justify all lines",
- Align::TowardsSpine => "Align towards spine",
- Align::AwayFromSpine => "Align away from spine",
- }
- }
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum Composer {
- /// Total-fit (Knuth–Plass) over the whole paragraph.
- #[default]
- Paragraph,
- /// Greedy, line by line.
- SingleLine,
- /// The Japanese paragraph composer: total fit, with the CJK leading model and character
- /// alignment.
- Japanese,
- /// The Japanese single-line composer.
- JapaneseSingleLine,
-}
-
-impl Composer {
- /// Breaks lines greedily, one at a time.
- pub fn single_line(self) -> bool {
- matches!(self, Composer::SingleLine | Composer::JapaneseSingleLine)
- }
-
- /// A Japanese composer: lines follow the leading model ([`crate::cjk::LeadingModel`]) and
- /// characters their [`crate::cjk::CharacterAlignment`]. The others set lines baseline to
- /// baseline with every character on the Roman baseline.
- pub fn japanese(self) -> bool {
- matches!(self, Composer::Japanese | Composer::JapaneseSingleLine)
- }
-}
-
-/// What a nested style runs to (Drop Caps and Nested Styles).
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", tag = "kind", content = "chars")]
-pub enum NestedUntil {
- Sentences,
- #[default]
- Words,
- Characters,
- Letters,
- Digits,
- Tab,
- ForcedLineBreak,
- EmSpace,
- EnSpace,
- /// The paragraph's drop cap characters.
- Dropcap,
- /// Any of these characters.
- Chars(String),
-}
-
-/// A character style applied from the start of the paragraph through (or up to) the `count`-th
-/// delimiter; nested styles follow each other.
-/// A nested line style: `style` for the next `lines` lines.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", default)]
-pub struct NestedLineStyle {
- pub style: String,
- pub lines: u32,
-}
-
-impl Default for NestedLineStyle {
- fn default() -> Self {
- NestedLineStyle { style: String::new(), lines: 1 }
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", default)]
-pub struct NestedStyle {
- pub style: String,
- /// Through (include the delimiter) or up to (stop before it).
- pub through: bool,
- pub count: u32,
- pub until: NestedUntil,
-}
-
-impl Default for NestedStyle {
- fn default() -> Self {
- NestedStyle { style: String::new(), through: true, count: 1, until: NestedUntil::Words }
- }
-}
-
-impl NestedStyle {
- /// The drop cap's character style as a nested style: `style` through 1 drop cap.
- pub fn drop_cap(style: &str) -> Self {
- NestedStyle { style: style.into(), through: true, count: 1, until: NestedUntil::Dropcap }
- }
-
- /// Is this the form a drop cap's character style takes at the start of a nested style list?
- pub fn is_drop_cap(&self) -> bool {
- self.until == NestedUntil::Dropcap && self.through && self.count == 1
- }
-}
-
-/// A character style applied to every match of a regular expression in the paragraph.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", default)]
-pub struct GrepStyle {
- pub style: String,
- pub pattern: String,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum GridAlign {
- #[default]
- None,
- AllLines,
- FirstLineOnly,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum StartParagraph {
- #[default]
- Anywhere,
- NextColumn,
- NextFrame,
- NextPage,
- NextOddPage,
- NextEvenPage,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", tag = "kind", content = "columns")]
-pub enum SpanColumns {
- #[default]
- Single,
- /// Span `n` columns (0 = all).
- Span(u32),
- /// Split into `n` sub-columns.
- Split(u32),
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum TabAlign {
- #[default]
- Left,
- Center,
- Right,
- /// Align on a character (default `.`).
- Char,
-}
-
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TabStop {
- /// A file that held a non-finite position (written as `null`) reads it back as NaN, which
- /// [`TabStop::sanitized_list`] drops.
- #[serde(deserialize_with = "position_or_nan")]
- pub position: f64,
- #[serde(default)]
- pub align: TabAlign,
- #[serde(default, skip_serializing_if = "String::is_empty")]
- pub leader: String,
- #[serde(default, skip_serializing_if = "String::is_empty")]
- pub align_on: String,
-}
-
-/// The colour of a paragraph rule that follows the paragraph's text colour.
-pub const TEXT_COLOR: &str = "Text Color";
-
-/// Most stops a paragraph holds.
-pub const MAX_TAB_STOPS: usize = 100;
-/// Furthest stop position: 216 in, the largest page.
-pub const MAX_TAB_POSITION: f64 = 15_552.0;
-/// Longest leader, in characters.
-pub const MAX_TAB_LEADER: usize = 8;
-/// Stops closer than this share a position.
-pub const SAME_TAB_POSITION: f64 = 0.01;
-
-/// Smallest type size the engine accepts, in points.
-pub const MIN_TYPE_SIZE: f64 = 0.1;
-/// Largest type size the engine accepts, in points, as InDesign's own field allows.
-pub const MAX_TYPE_SIZE: f64 = 1296.0;
-/// Largest measure an imported indent, spacing or offset can carry, in points: the furthest tab
-/// stop, which is the widest page.
-pub const MAX_MEASURE: f64 = MAX_TAB_POSITION;
-
-/// A type size read from a file, or `None` when it is not a size the engine can mean.
-///
-/// A file can hold any number, including `NaN`, `inf`, `0`, a negative or `1e300`. Every importer
-/// had its own spelling of this test, or only checked that the value was finite -- so tagged text
-/// took `<cSize:1e300>` and set a 1e300 pt size on the text (#1593). A size outside the range is
-/// dropped rather than clamped, so the text keeps the size its style gives it.
-pub fn imported_type_size(pt: f64) -> Option<f64> {
- (pt.is_finite() && (MIN_TYPE_SIZE..=MAX_TYPE_SIZE).contains(&pt)).then_some(pt)
-}
-
-/// An indent, spacing or offset read from a file, clamped to ±[`MAX_MEASURE`]; `None` when the
-/// value is not finite.
-///
-/// Unlike a type size this is clamped rather than dropped: a file that says "indent everything"
-/// still indents to the widest page the engine has, where dropping the value would quietly
-/// restore the style's own indent and hide what the file asked for (#1593).
-pub fn imported_measure(pt: f64) -> Option<f64> {
- pt.is_finite().then(|| pt.clamp(-MAX_MEASURE, MAX_MEASURE))
-}
-
-impl TabStop {
- /// A finite position clamped to `0..=MAX_TAB_POSITION`.
- pub fn clamp_position(v: f64) -> Result<f64, String> {
- if v.is_finite() { Ok(v.clamp(0.0, MAX_TAB_POSITION)) } else { Err("position must be a finite number".into()) }
- }
-
- /// A leader: up to [`MAX_TAB_LEADER`] characters, no control characters.
- pub fn check_leader(v: &str) -> Result<(), String> {
- if v.chars().count() > MAX_TAB_LEADER || v.chars().any(char::is_control) {
- return Err(format!("`leader`: at most {MAX_TAB_LEADER} printable characters"));
- }
- Ok(())
- }
-
- /// An align-on character: one printable character or none (a decimal point).
- pub fn check_align_on(v: &str) -> Result<(), String> {
- if v.chars().count() > 1 || v.chars().any(char::is_control) {
- return Err("`alignOn`: one printable character".into());
- }
- Ok(())
- }
-
- /// A tab-stop list as the Tabs commands keep it: at most [`MAX_TAB_STOPS`] stops, positions
- /// clamped, leaders and align-on characters checked, a char stop aligning on `.` unless it
- /// names a character, sorted by position, and one stop per position (the later one wins).
- pub fn checked_list(mut tabs: Vec<TabStop>) -> Result<Vec<TabStop>, String> {
- if tabs.len() > MAX_TAB_STOPS {
- return Err(format!("a paragraph holds at most {MAX_TAB_STOPS} tab stops"));
- }
- for t in &mut tabs {
- t.position = Self::clamp_position(t.position)?;
- Self::check_leader(&t.leader)?;
- Self::check_align_on(&t.align_on)?;
- }
- Ok(Self::normalized(tabs))
- }
-
- /// A tab-stop list read from a file, repaired to what [`checked_list`](Self::checked_list)
- /// accepts: stops with a non-finite position dropped, positions clamped, control characters
- /// removed from leaders and align-on characters and both cut to their limits, sorted, one stop
- /// per position (the later one wins), and the first [`MAX_TAB_STOPS`] by position kept.
- pub fn sanitized_list(tabs: Vec<TabStop>) -> Vec<TabStop> {
- let tabs = tabs
- .into_iter()
- .filter_map(|mut t| {
- t.position = Self::clamp_position(t.position).ok()?;
- if Self::check_leader(&t.leader).is_err() {
- t.leader = t.leader.chars().filter(|c| !c.is_control()).take(MAX_TAB_LEADER).collect();
- }
- if Self::check_align_on(&t.align_on).is_err() {
- t.align_on = t.align_on.chars().filter(|c| !c.is_control()).take(1).collect();
- }
- Some(t)
- })
- .collect();
- let mut out = Self::normalized(tabs);
- out.truncate(MAX_TAB_STOPS);
- out
- }
-
- /// Finite, clamped stops sorted by position, one per position: of stops closer than
- /// [`SAME_TAB_POSITION`], the later one in `tabs` wins. A char stop with no character aligns
- /// on `.`.
- fn normalized(tabs: Vec<TabStop>) -> Vec<TabStop> {
- let mut stops: Vec<(usize, TabStop)> = tabs.into_iter().enumerate().collect();
- stops.sort_by(|a, b| a.1.position.total_cmp(&b.1.position));
- let mut out: Vec<(usize, TabStop)> = Vec::with_capacity(stops.len());
- for (i, mut t) in stops {
- if t.align == TabAlign::Char && t.align_on.is_empty() {
- t.align_on = ".".into();
- }
- match out.last_mut() {
- Some(last) if t.position - last.1.position < SAME_TAB_POSITION => {
- if i > last.0 {
- *last = (i, t);
- }
- }
- _ => out.push((i, t)),
- }
- }
- out.into_iter().map(|(_, t)| t).collect()
- }
-}
-
-/// A stop's position; `null` (how JSON writes a non-finite number) reads as NaN.
-fn position_or_nan<'de, D: serde::Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
- Ok(Option::<f64>::deserialize(d)?.unwrap_or(f64::NAN))
-}
-
-/// A paragraph's tab-stop list in either attribute form, as read from a file.
-trait FileTabs: Sized {
- fn sanitized(self) -> Self;
-}
-
-impl FileTabs for Vec<TabStop> {
- fn sanitized(self) -> Self {
- TabStop::sanitized_list(self)
- }
-}
-
-impl FileTabs for Option<Vec<TabStop>> {
- fn sanitized(self) -> Self {
- self.map(TabStop::sanitized_list)
- }
-}
-
-/// Deserializes a `tabs` field through [`TabStop::sanitized_list`]: a saved document's tab lists
-/// get the limits the Tabs commands keep.
-fn sanitized_tabs<'de, D: serde::Deserializer<'de>, T: Deserialize<'de> + FileTabs>(d: D) -> Result<T, D::Error> {
- T::deserialize(d).map(FileTabs::sanitized)
-}
-
-/// A paragraph rule (Rule Above / Rule Below).
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(default, rename_all = "camelCase")]
-pub struct Rule {
- pub on: bool,
- pub weight: f64,
- /// A swatch, or [`TEXT_COLOR`].
- pub color: String,
- pub tint: f32,
- /// Width: column (true) or text (false).
- pub column_width: bool,
- pub offset: f64,
- pub left_indent: f64,
- pub right_indent: f64,
-}
-
-impl Default for Rule {
- fn default() -> Self {
- Rule { on: false, weight: 1.0, color: TEXT_COLOR.into(), tint: 1.0, column_width: true, offset: 0.0, left_indent: 0.0, right_indent: 0.0 }
- }
-}
-
-/// How wide a paragraph border or shading box is: the column, or the text's longest line.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum BoxWidth {
- #[default]
- Column,
- Text,
-}
-
-/// Where a paragraph border or shading box starts above the first line (before its top offset).
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum BoxTop {
- /// The tallest ascent on the line.
- #[default]
- Ascent,
- Baseline,
- /// The top of the em box.
- EmBox,
- /// The top of the line's leading.
- Leading,
-}
-
-/// Where a paragraph border or shading box ends below the last line (before its bottom offset).
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum BoxBottom {
- /// The deepest descent on the line.
- #[default]
- Descent,
- Baseline,
- /// The bottom of the em box.
- EmBox,
-}
-
-/// Where a bullet or number sits against the first line's start (the left and first-line
-/// indents): it starts there, is centred on it, or ends there.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum ListAlign {
- #[default]
- Left,
- Center,
- Right,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum ListType {
- #[default]
- None,
- Bullets,
- Numbers,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum NumberStyle {
- #[default]
- Arabic,
- UpperRoman,
- LowerRoman,
- UpperLetters,
- LowerLetters,
- /// 01, 02, …
- ArabicLeadingZero,
- /// 001, 002, …
- ArabicThreeDigits,
- /// 0001, 0002, …
- ArabicFourDigits,
- /// *, †, ‡, §, ¶, ‖, then doubled (**, ††, …): footnotes.
- Symbols,
- /// 一, 二, 三, …: Chinese numerals written digit by digit, so 10 is 一〇 and 38 is 三八.
- Kanji,
-}
-
-/// Numbers past this are written in Arabic digits by the styles that repeat characters (roman
-/// numerals, letters, symbols), so a hostile start number can't build a huge label.
-const MAX_REPEATED_FORM: u32 = 3999;
-
-impl NumberStyle {
- pub fn format(self, n: u32) -> String {
- if n > MAX_REPEATED_FORM
- && matches!(
- self,
- NumberStyle::UpperRoman | NumberStyle::LowerRoman | NumberStyle::UpperLetters | NumberStyle::LowerLetters | NumberStyle::Symbols
- )
- {
- return n.to_string();
- }
- match self {
- NumberStyle::Arabic => n.to_string(),
- NumberStyle::ArabicLeadingZero => format!("{n:02}"),
- NumberStyle::ArabicThreeDigits => format!("{n:03}"),
- NumberStyle::ArabicFourDigits => format!("{n:04}"),
- NumberStyle::UpperRoman => roman(n),
- NumberStyle::LowerRoman => roman(n).to_lowercase(),
- NumberStyle::UpperLetters => letters(n),
- NumberStyle::LowerLetters => letters(n).to_lowercase(),
- NumberStyle::Symbols => {
- const SYM: [char; 6] = ['*', '†', '‡', '§', '¶', '‖'];
- let n = n.max(1) as usize - 1;
- std::iter::repeat_n(SYM[n % SYM.len()], n / SYM.len() + 1).collect()
- }
- NumberStyle::Kanji => kanji_digits(n),
- }
- }
-}
-
-/// Expand the metacharacters of a list's label text (`^t` tab, `^>` en space, `^^` caret, …),
-/// putting `number` in for `^#`. Level placeholders (`^1`…`^9`) and metacharacters with no
-/// meaning in a label are dropped; a label never holds a paragraph break.
-pub fn expand_list_text(s: &str, number: &str) -> String {
- expand_list_levels(s, number, &[])
-}
-
-/// [`expand_list_text`] with `levels[k]` in for `^1`…`^9` (level k + 1's current number; a level
-/// past the end is dropped).
-pub fn expand_list_levels(s: &str, number: &str, levels: &[String]) -> String {
- let mut out = String::with_capacity(s.len() + number.len());
- let mut it = s.chars();
- while let Some(c) = it.next() {
- if c != '^' {
- if c != '\n' && c != '\r' {
- out.push(c);
- }
- continue;
- }
- let Some(m) = it.next() else {
- out.push('^');
- break;
- };
- let r = match m {
- '#' => {
- out.push_str(number);
- continue;
- }
- d @ '1'..='9' => {
- let k = d as usize - '1' as usize;
- if let Some(l) = levels.get(k) {
- out.push_str(l);
- }
- continue;
- }
- '^' => '^',
- 't' => '\t',
- 'y' => crate::story::RIGHT_INDENT_TAB,
- 'i' => crate::story::INDENT_HERE,
- 'n' => crate::story::FORCED_LINE_BREAK,
- 'm' => '\u{2003}',
- '>' => '\u{2002}',
- 'f' => '\u{2001}',
- '|' => '\u{200A}',
- '<' => '\u{2009}',
- '/' => '\u{2007}',
- '.' => '\u{2008}',
- 's' => '\u{A0}',
- 'S' => '\u{202F}',
- '_' => '\u{2014}',
- '=' => '\u{2013}',
- '~' => '\u{2011}',
- '{' => '\u{201C}',
- '}' => '\u{201D}',
- '[' => '\u{2018}',
- ']' => '\u{2019}',
- '"' => '"',
- '\'' => '\'',
- _ => continue,
- };
- out.push(r);
- }
- out
-}
-
-fn kanji_digits(n: u32) -> String {
- const DIGITS: [char; 10] = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
- n.to_string().chars().map(|c| c.to_digit(10).and_then(|d| DIGITS.get(d as usize)).copied().unwrap_or(c)).collect()
-}
-
-fn roman(mut n: u32) -> String {
- if n == 0 {
- return "0".into();
- }
- let t = [
- (1000, "M"),
- (900, "CM"),
- (500, "D"),
- (400, "CD"),
- (100, "C"),
- (90, "XC"),
- (50, "L"),
- (40, "XL"),
- (10, "X"),
- (9, "IX"),
- (5, "V"),
- (4, "IV"),
- (1, "I"),
- ];
- let mut s = String::new();
- for (v, r) in t {
- while n >= v {
- s.push_str(r);
- n -= v;
- }
- }
- s
-}
-
-/// A, B, …, Z, AA, BB, … (InDesign's letter numbering repeats the letter).
-fn letters(n: u32) -> String {
- if n == 0 {
- return String::new();
- }
- let i = (n - 1) % 26;
- let reps = (n - 1) / 26 + 1;
- std::iter::repeat_n(char::from(b'A' + i as u8), reps as usize).collect()
-}
-
attr_set! {
/// Character attributes (Character panel / character styles / the character part of paragraph styles).
CharAttrs / CharProps {
@@ -1453,46 +611,5 @@ impl ParaProps {
}
}
-/// Levels a list can have.
-pub const LIST_LEVELS: usize = 9;
-
-/// Index (0-based) of list level `level` (1-based, clamped to 1–[`LIST_LEVELS`]).
-fn list_level_index(level: u32) -> usize {
- (level.clamp(1, LIST_LEVELS as u32) - 1) as usize
-}
-
-/// The numbering of one list as it goes: each level's last number and its text, and when each
-/// level last numbered a paragraph (for Restart Numbers at This Level After).
-#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
-pub struct ListCounter {
- numbers: [u32; LIST_LEVELS],
- labels: [String; LIST_LEVELS],
- seen: [u64; LIST_LEVELS],
- tick: u64,
-}
-
-impl ListCounter {
- /// Number the next paragraph of `pp` (a numbered paragraph with text) and return its number.
- pub fn advance(&mut self, pp: &ParaProps) -> u32 {
- let l = list_level_index(pp.list_level);
- self.tick = self.tick.saturating_add(1);
- let since = self.seen[l];
- let restart = pp.restart_numbers
- && match pp.restart_after_level {
- 0 => self.seen[..l].iter().any(|&t| t > since),
- m => (m as usize) <= l && self.seen.get(m as usize - 1).is_some_and(|&t| t > since),
- };
- let n = match pp.start_at {
- Some(s) => s.max(1),
- None if restart => 1,
- None => self.numbers[l].saturating_add(1),
- };
- self.numbers[l] = n;
- self.labels[l] = pp.number_style.format(n);
- self.seen[l] = self.tick;
- n
- }
-}
-
#[cfg(test)]
mod tests;
diff --git a/crates/doc/src/attrs/enums.rs b/crates/doc/src/attrs/enums.rs
new file mode 100644
index 000000000..947deb66a
--- /dev/null
+++ b/crates/doc/src/attrs/enums.rs
@@ -0,0 +1,310 @@
+use super::*;
+
+// ---------- value types ----------
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "kind", content = "value")]
+pub enum Leading {
+ /// Auto leading (percentage of the largest size on the line, Justification → Auto Leading).
+ #[default]
+ Auto,
+ Points(f64),
+}
+
+/// Paragraph direction.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum TextDirection {
+ #[default]
+ LeftToRight,
+ RightToLeft,
+}
+
+/// Digits (World-Ready): the figures 0–9 are drawn as these.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Digits {
+ /// Contextual digits; composition selects the preceding strong script/language.
+ #[default]
+ Default,
+ /// European (0123).
+ Arabic,
+ /// Arabic-Indic (٠١٢٣).
+ Hindi,
+ /// Extended Arabic-Indic, as used for Persian and Urdu (۰۱۲۳).
+ Farsi,
+ /// Those of the text's language (Thai, Devanagari, Bengali, Arabic, Persian…); else as typed.
+ Native,
+}
+
+impl Digits {
+ /// The digit `c` (0–9) is drawn as, for text in `language`.
+ pub fn map(self, c: char, language: &str) -> char {
+ let d = match c {
+ '0'..='9' => c as u32 - '0' as u32,
+ '\u{0660}'..='\u{0669}' => c as u32 - 0x0660,
+ '\u{06F0}'..='\u{06F9}' => c as u32 - 0x06F0,
+ _ => return c,
+ };
+ let zero = match self {
+ Digits::Default => return c,
+ Digits::Arabic => 0x0030,
+ Digits::Hindi => 0x0660,
+ Digits::Farsi => 0x06F0,
+ Digits::Native => {
+ let l = language.to_ascii_lowercase();
+ match () {
+ _ if l.starts_with("arabic") || l == "ar" || l.starts_with("ar-") => 0x0660,
+ _ if l.starts_with("persian")
+ || l.starts_with("farsi")
+ || l.starts_with("urdu")
+ || l == "fa"
+ || l.starts_with("fa-")
+ || l == "ur"
+ || l.starts_with("ur-") =>
+ {
+ 0x06F0
+ }
+ _ if l.starts_with("hindi") || l.starts_with("marathi") || l.starts_with("nepali") || l.starts_with("sanskrit") => 0x0966,
+ _ if l.starts_with("bengali") => 0x09E6,
+ _ if l.starts_with("gujarati") => 0x0AE6,
+ _ if l.starts_with("punjabi") => 0x0A66,
+ _ if l.starts_with("tamil") => 0x0BE6,
+ _ if l.starts_with("telugu") => 0x0C66,
+ _ if l.starts_with("kannada") => 0x0CE6,
+ _ if l.starts_with("malayalam") => 0x0D66,
+ _ if l.starts_with("thai") => 0x0E50,
+ _ if l.starts_with("lao") => 0x0ED0,
+ _ if l.starts_with("tibetan") => 0x0F20,
+ _ if l.starts_with("burmese") => 0x1040,
+ _ if l.starts_with("khmer") => 0x17E0,
+ _ => return c,
+ }
+ }
+ };
+ char::from_u32(zero + d).unwrap_or(c)
+ }
+}
+
+/// A tracked change on text.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ChangeMark {
+ #[default]
+ None,
+ Inserted,
+ Deleted,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "kind", content = "value")]
+pub enum Kerning {
+ #[default]
+ Metrics,
+ Optical,
+ /// Zero ("0" in the kerning menu).
+ None,
+ /// Manual pair kerning in 1/1000 em (applies after this character).
+ Manual(f64),
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Capitalization {
+ #[default]
+ Normal,
+ AllCaps,
+ SmallCaps,
+ OpenTypeAllSmallCaps,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Position {
+ #[default]
+ Normal,
+ Superscript,
+ Subscript,
+ OtSuperscript,
+ OtSubscript,
+ OtNumerator,
+ OtDenominator,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Align {
+ #[default]
+ Left,
+ Center,
+ Right,
+ LeftJustified,
+ CenterJustified,
+ RightJustified,
+ FullyJustified,
+ TowardsSpine,
+ AwayFromSpine,
+}
+
+impl Align {
+ pub fn is_justified(self) -> bool {
+ matches!(self, Align::LeftJustified | Align::CenterJustified | Align::RightJustified | Align::FullyJustified)
+ }
+ pub const ALL: [Align; 9] = [
+ Align::Left,
+ Align::Center,
+ Align::Right,
+ Align::LeftJustified,
+ Align::CenterJustified,
+ Align::RightJustified,
+ Align::FullyJustified,
+ Align::TowardsSpine,
+ Align::AwayFromSpine,
+ ];
+ pub fn label(self) -> &'static str {
+ match self {
+ Align::Left => "Align left",
+ Align::Center => "Align center",
+ Align::Right => "Align right",
+ Align::LeftJustified => "Justify with last line aligned left",
+ Align::CenterJustified => "Justify with last line aligned center",
+ Align::RightJustified => "Justify with last line aligned right",
+ Align::FullyJustified => "Justify all lines",
+ Align::TowardsSpine => "Align towards spine",
+ Align::AwayFromSpine => "Align away from spine",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Composer {
+ /// Total-fit (Knuth–Plass) over the whole paragraph.
+ #[default]
+ Paragraph,
+ /// Greedy, line by line.
+ SingleLine,
+ /// The Japanese paragraph composer: total fit, with the CJK leading model and character
+ /// alignment.
+ Japanese,
+ /// The Japanese single-line composer.
+ JapaneseSingleLine,
+}
+
+impl Composer {
+ /// Breaks lines greedily, one at a time.
+ pub fn single_line(self) -> bool {
+ matches!(self, Composer::SingleLine | Composer::JapaneseSingleLine)
+ }
+
+ /// A Japanese composer: lines follow the leading model ([`crate::cjk::LeadingModel`]) and
+ /// characters their [`crate::cjk::CharacterAlignment`]. The others set lines baseline to
+ /// baseline with every character on the Roman baseline.
+ pub fn japanese(self) -> bool {
+ matches!(self, Composer::Japanese | Composer::JapaneseSingleLine)
+ }
+}
+
+/// What a nested style runs to (Drop Caps and Nested Styles).
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "kind", content = "chars")]
+pub enum NestedUntil {
+ Sentences,
+ #[default]
+ Words,
+ Characters,
+ Letters,
+ Digits,
+ Tab,
+ ForcedLineBreak,
+ EmSpace,
+ EnSpace,
+ /// The paragraph's drop cap characters.
+ Dropcap,
+ /// Any of these characters.
+ Chars(String),
+}
+
+/// A character style applied from the start of the paragraph through (or up to) the `count`-th
+/// delimiter; nested styles follow each other.
+/// A nested line style: `style` for the next `lines` lines.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct NestedLineStyle {
+ pub style: String,
+ pub lines: u32,
+}
+
+impl Default for NestedLineStyle {
+ fn default() -> Self {
+ NestedLineStyle { style: String::new(), lines: 1 }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct NestedStyle {
+ pub style: String,
+ /// Through (include the delimiter) or up to (stop before it).
+ pub through: bool,
+ pub count: u32,
+ pub until: NestedUntil,
+}
+
+impl Default for NestedStyle {
+ fn default() -> Self {
+ NestedStyle { style: String::new(), through: true, count: 1, until: NestedUntil::Words }
+ }
+}
+
+impl NestedStyle {
+ /// The drop cap's character style as a nested style: `style` through 1 drop cap.
+ pub fn drop_cap(style: &str) -> Self {
+ NestedStyle { style: style.into(), through: true, count: 1, until: NestedUntil::Dropcap }
+ }
+
+ /// Is this the form a drop cap's character style takes at the start of a nested style list?
+ pub fn is_drop_cap(&self) -> bool {
+ self.until == NestedUntil::Dropcap && self.through && self.count == 1
+ }
+}
+
+/// A character style applied to every match of a regular expression in the paragraph.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct GrepStyle {
+ pub style: String,
+ pub pattern: String,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum GridAlign {
+ #[default]
+ None,
+ AllLines,
+ FirstLineOnly,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum StartParagraph {
+ #[default]
+ Anywhere,
+ NextColumn,
+ NextFrame,
+ NextPage,
+ NextOddPage,
+ NextEvenPage,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "kind", content = "columns")]
+pub enum SpanColumns {
+ #[default]
+ Single,
+ /// Span `n` columns (0 = all).
+ Span(u32),
+ /// Split into `n` sub-columns.
+ Split(u32),
+}
diff --git a/crates/doc/src/attrs/language.rs b/crates/doc/src/attrs/language.rs
new file mode 100644
index 000000000..35ac044a1
--- /dev/null
+++ b/crates/doc/src/attrs/language.rs
@@ -0,0 +1,134 @@
+/// Does `c` belong to a script that capitalizes the first letter of sentences, words and headings?
+/// Georgian doesn't: Unicode maps Mkhedruli to Mtavruli capitals, but those are only for all-caps
+/// text, never for a sentence's, a title's or an index heading's first letter.
+pub fn capitalizes(c: char) -> bool {
+ !matches!(c, '\u{10A0}'..='\u{10FF}' | '\u{1C90}'..='\u{1CBF}' | '\u{2D00}'..='\u{2D2F}')
+}
+
+/// The BCP 47 tag of a language name as InDesign and IDML write it ("English: USA", "Chinese:
+/// Simplified", or a locale code such as "de_DE_2006"), for the shaper's localized forms (`locl`)
+/// and everything that depends on the language (quotes, hyphenation and spelling, line breaking,
+/// fallback fonts). A variant we don't know falls back to its language ("English: Australian" →
+/// `en`); an unknown language (or "[No Language]") has none. Case, punctuation and IDML's `$ID/`
+/// don't matter. Locale codes (`ll`, `ll_CC`, `ll-CC`, with a reform year after them as in
+/// `de_DE_2006`) are their tag (`de-DE`), and Chinese also goes by its other common spellings
+/// ("Simplified Chinese", "Chinese (Traditional)", "zh_CN", "zh-Hant").
+pub fn language_tag(language: &str) -> Option<&'static str> {
+ let language = language.trim();
+ let language = language.strip_prefix("$ID/").unwrap_or(language);
+ let l = language.to_lowercase();
+ let words: Vec<&str> = l.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect();
+ let first = words.first().copied().unwrap_or("");
+ let has = |any: &[&str]| words.iter().any(|w| any.contains(w));
+ if first == "zh" || has(&["chinese"]) {
+ // The script decides; then the name; then the region.
+ return Some(if has(&["hans"]) {
+ "zh-Hans"
+ } else if has(&["hant"]) {
+ "zh-Hant"
+ } else if has(&["simplified", "cn", "sg"]) {
+ "zh-Hans"
+ } else if has(&["traditional", "tw", "hk", "mo"]) {
+ "zh-Hant"
+ } else {
+ "zh"
+ });
+ }
+ if let Some(tag) = locale_code(&words) {
+ return intern_tag(tag);
+ }
+ let variant = match words.join(" ").as_str() {
+ "english usa" => Some("en-US"),
+ "english uk" => Some("en-GB"),
+ "english canadian" => Some("en-CA"),
+ "german swiss 2006 reform" | "german swiss" => Some("de-CH"),
+ "french swiss" => Some("fr-CH"),
+ "italian swiss" => Some("it-CH"),
+ "spanish castilian" => Some("es-ES"),
+ "french canadian" => Some("fr-CA"),
+ "portuguese brazilian" => Some("pt-BR"),
+ "norwegian bokmål" | "norwegian bokmal" => Some("nb"),
+ "norwegian nynorsk" => Some("nn"),
+ _ => None,
+ };
+ if variant.is_some() {
+ return variant;
+ }
+ Some(match first {
+ "english" => "en",
+ "german" => "de",
+ "french" => "fr",
+ "spanish" => "es",
+ "catalan" => "ca",
+ "italian" => "it",
+ "portuguese" => "pt",
+ "dutch" => "nl",
+ "danish" => "da",
+ "swedish" => "sv",
+ "norwegian" => "no",
+ "finnish" => "fi",
+ "polish" => "pl",
+ "czech" => "cs",
+ "slovak" => "sk",
+ "hungarian" => "hu",
+ "romanian" => "ro",
+ "croatian" => "hr",
+ "lithuanian" => "lt",
+ "greek" => "el",
+ "russian" => "ru",
+ "ukrainian" => "uk",
+ "bulgarian" => "bg",
+ "serbian" => "sr",
+ "macedonian" => "mk",
+ "turkish" => "tr",
+ "japanese" => "ja",
+ "korean" => "ko",
+ "arabic" => "ar",
+ "persian" | "farsi" => "fa",
+ "urdu" => "ur",
+ "hebrew" => "he",
+ "georgian" => "ka",
+ _ => return None,
+ })
+}
+
+/// The tag of a locale code split into lowercase `words`: a language (2 or 3 letters), then
+/// optionally a region (2 letters or 3 digits) and a reform year (4 digits) → `ll` or `ll-CC`.
+fn locale_code(words: &[&str]) -> Option<String> {
+ let letters = |w: &str, n: std::ops::RangeInclusive<usize>| n.contains(&w.len()) && w.bytes().all(|b| b.is_ascii_lowercase());
+ let digits = |w: &str, n: usize| w.len() == n && w.bytes().all(|b| b.is_ascii_digit());
+ match *words {
+ [lang] if letters(lang, 2..=3) => Some(lang.to_string()),
+ [lang, region] | [lang, region, _] if letters(lang, 2..=3) && (letters(region, 2..=2) || digits(region, 3)) => {
+ if let [_, _, year] = *words
+ && !digits(year, 4)
+ {
+ return None;
+ }
+ Some(format!("{lang}-{}", region.to_ascii_uppercase()))
+ }
+ _ => None,
+ }
+}
+
+/// `tag` as a `&'static str`: each distinct tag is kept once for the process. Language names come
+/// from documents, so at most [`MAX_TAGS`] are kept; past that a new tag is unknown (`None`).
+fn intern_tag(tag: String) -> Option<&'static str> {
+ const MAX_TAGS: usize = 512;
+ static TAGS: std::sync::Mutex<Vec<&str>> = std::sync::Mutex::new(Vec::new());
+ let mut tags = TAGS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ if let Some(t) = tags.iter().find(|t| **t == tag) {
+ return Some(t);
+ }
+ if tags.len() >= MAX_TAGS {
+ return None;
+ }
+ let t: &'static str = Box::leak(tag.into_boxed_str());
+ tags.push(t);
+ Some(t)
+}
+
+/// The language subtag of a BCP 47 tag (`de-DE` → `de`, `zh-Hant` → `zh`).
+pub fn language_subtag(tag: &str) -> &str {
+ tag.split('-').next().unwrap_or(tag)
+}
diff --git a/crates/doc/src/attrs/rules_lists.rs b/crates/doc/src/attrs/rules_lists.rs
new file mode 100644
index 000000000..dde764302
--- /dev/null
+++ b/crates/doc/src/attrs/rules_lists.rs
@@ -0,0 +1,285 @@
+use super::*;
+
+/// The colour of a paragraph rule that follows the paragraph's text colour.
+pub const TEXT_COLOR: &str = "Text Color";
+
+/// A paragraph rule (Rule Above / Rule Below).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Rule {
+ pub on: bool,
+ pub weight: f64,
+ /// A swatch, or [`TEXT_COLOR`].
+ pub color: String,
+ pub tint: f32,
+ /// Width: column (true) or text (false).
+ pub column_width: bool,
+ pub offset: f64,
+ pub left_indent: f64,
+ pub right_indent: f64,
+}
+
+impl Default for Rule {
+ fn default() -> Self {
+ Rule { on: false, weight: 1.0, color: TEXT_COLOR.into(), tint: 1.0, column_width: true, offset: 0.0, left_indent: 0.0, right_indent: 0.0 }
+ }
+}
+
+/// How wide a paragraph border or shading box is: the column, or the text's longest line.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum BoxWidth {
+ #[default]
+ Column,
+ Text,
+}
+
+/// Where a paragraph border or shading box starts above the first line (before its top offset).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum BoxTop {
+ /// The tallest ascent on the line.
+ #[default]
+ Ascent,
+ Baseline,
+ /// The top of the em box.
+ EmBox,
+ /// The top of the line's leading.
+ Leading,
+}
+
+/// Where a paragraph border or shading box ends below the last line (before its bottom offset).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum BoxBottom {
+ /// The deepest descent on the line.
+ #[default]
+ Descent,
+ Baseline,
+ /// The bottom of the em box.
+ EmBox,
+}
+
+/// Where a bullet or number sits against the first line's start (the left and first-line
+/// indents): it starts there, is centred on it, or ends there.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ListAlign {
+ #[default]
+ Left,
+ Center,
+ Right,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ListType {
+ #[default]
+ None,
+ Bullets,
+ Numbers,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum NumberStyle {
+ #[default]
+ Arabic,
+ UpperRoman,
+ LowerRoman,
+ UpperLetters,
+ LowerLetters,
+ /// 01, 02, …
+ ArabicLeadingZero,
+ /// 001, 002, …
+ ArabicThreeDigits,
+ /// 0001, 0002, …
+ ArabicFourDigits,
+ /// *, †, ‡, §, ¶, ‖, then doubled (**, ††, …): footnotes.
+ Symbols,
+ /// 一, 二, 三, …: Chinese numerals written digit by digit, so 10 is 一〇 and 38 is 三八.
+ Kanji,
+}
+
+/// Numbers past this are written in Arabic digits by the styles that repeat characters (roman
+/// numerals, letters, symbols), so a hostile start number can't build a huge label.
+const MAX_REPEATED_FORM: u32 = 3999;
+
+impl NumberStyle {
+ pub fn format(self, n: u32) -> String {
+ if n > MAX_REPEATED_FORM
+ && matches!(
+ self,
+ NumberStyle::UpperRoman | NumberStyle::LowerRoman | NumberStyle::UpperLetters | NumberStyle::LowerLetters | NumberStyle::Symbols
+ )
+ {
+ return n.to_string();
+ }
+ match self {
+ NumberStyle::Arabic => n.to_string(),
+ NumberStyle::ArabicLeadingZero => format!("{n:02}"),
+ NumberStyle::ArabicThreeDigits => format!("{n:03}"),
+ NumberStyle::ArabicFourDigits => format!("{n:04}"),
+ NumberStyle::UpperRoman => roman(n),
+ NumberStyle::LowerRoman => roman(n).to_lowercase(),
+ NumberStyle::UpperLetters => letters(n),
+ NumberStyle::LowerLetters => letters(n).to_lowercase(),
+ NumberStyle::Symbols => {
+ const SYM: [char; 6] = ['*', '†', '‡', '§', '¶', '‖'];
+ let n = n.max(1) as usize - 1;
+ std::iter::repeat_n(SYM[n % SYM.len()], n / SYM.len() + 1).collect()
+ }
+ NumberStyle::Kanji => kanji_digits(n),
+ }
+ }
+}
+
+/// Expand the metacharacters of a list's label text (`^t` tab, `^>` en space, `^^` caret, …),
+/// putting `number` in for `^#`. Level placeholders (`^1`…`^9`) and metacharacters with no
+/// meaning in a label are dropped; a label never holds a paragraph break.
+pub fn expand_list_text(s: &str, number: &str) -> String {
+ expand_list_levels(s, number, &[])
+}
+
+/// [`expand_list_text`] with `levels[k]` in for `^1`…`^9` (level k + 1's current number; a level
+/// past the end is dropped).
+pub fn expand_list_levels(s: &str, number: &str, levels: &[String]) -> String {
+ let mut out = String::with_capacity(s.len() + number.len());
+ let mut it = s.chars();
+ while let Some(c) = it.next() {
+ if c != '^' {
+ if c != '\n' && c != '\r' {
+ out.push(c);
+ }
+ continue;
+ }
+ let Some(m) = it.next() else {
+ out.push('^');
+ break;
+ };
+ let r = match m {
+ '#' => {
+ out.push_str(number);
+ continue;
+ }
+ d @ '1'..='9' => {
+ let k = d as usize - '1' as usize;
+ if let Some(l) = levels.get(k) {
+ out.push_str(l);
+ }
+ continue;
+ }
+ '^' => '^',
+ 't' => '\t',
+ 'y' => crate::story::RIGHT_INDENT_TAB,
+ 'i' => crate::story::INDENT_HERE,
+ 'n' => crate::story::FORCED_LINE_BREAK,
+ 'm' => '\u{2003}',
+ '>' => '\u{2002}',
+ 'f' => '\u{2001}',
+ '|' => '\u{200A}',
+ '<' => '\u{2009}',
+ '/' => '\u{2007}',
+ '.' => '\u{2008}',
+ 's' => '\u{A0}',
+ 'S' => '\u{202F}',
+ '_' => '\u{2014}',
+ '=' => '\u{2013}',
+ '~' => '\u{2011}',
+ '{' => '\u{201C}',
+ '}' => '\u{201D}',
+ '[' => '\u{2018}',
+ ']' => '\u{2019}',
+ '"' => '"',
+ '\'' => '\'',
+ _ => continue,
+ };
+ out.push(r);
+ }
+ out
+}
+
+fn kanji_digits(n: u32) -> String {
+ const DIGITS: [char; 10] = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
+ n.to_string().chars().map(|c| c.to_digit(10).and_then(|d| DIGITS.get(d as usize)).copied().unwrap_or(c)).collect()
+}
+
+fn roman(mut n: u32) -> String {
+ if n == 0 {
+ return "0".into();
+ }
+ let t = [
+ (1000, "M"),
+ (900, "CM"),
+ (500, "D"),
+ (400, "CD"),
+ (100, "C"),
+ (90, "XC"),
+ (50, "L"),
+ (40, "XL"),
+ (10, "X"),
+ (9, "IX"),
+ (5, "V"),
+ (4, "IV"),
+ (1, "I"),
+ ];
+ let mut s = String::new();
+ for (v, r) in t {
+ while n >= v {
+ s.push_str(r);
+ n -= v;
+ }
+ }
+ s
+}
+
+/// A, B, …, Z, AA, BB, … (InDesign's letter numbering repeats the letter).
+fn letters(n: u32) -> String {
+ if n == 0 {
+ return String::new();
+ }
+ let i = (n - 1) % 26;
+ let reps = (n - 1) / 26 + 1;
+ std::iter::repeat_n(char::from(b'A' + i as u8), reps as usize).collect()
+}
+
+/// Levels a list can have.
+pub const LIST_LEVELS: usize = 9;
+
+/// Index (0-based) of list level `level` (1-based, clamped to 1–[`LIST_LEVELS`]).
+pub(super) fn list_level_index(level: u32) -> usize {
+ (level.clamp(1, LIST_LEVELS as u32) - 1) as usize
+}
+
+/// The numbering of one list as it goes: each level's last number and its text, and when each
+/// level last numbered a paragraph (for Restart Numbers at This Level After).
+#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
+pub struct ListCounter {
+ numbers: [u32; LIST_LEVELS],
+ pub(super) labels: [String; LIST_LEVELS],
+ seen: [u64; LIST_LEVELS],
+ tick: u64,
+}
+
+impl ListCounter {
+ /// Number the next paragraph of `pp` (a numbered paragraph with text) and return its number.
+ pub fn advance(&mut self, pp: &ParaProps) -> u32 {
+ let l = list_level_index(pp.list_level);
+ self.tick = self.tick.saturating_add(1);
+ let since = self.seen[l];
+ let restart = pp.restart_numbers
+ && match pp.restart_after_level {
+ 0 => self.seen[..l].iter().any(|&t| t > since),
+ m => (m as usize) <= l && self.seen.get(m as usize - 1).is_some_and(|&t| t > since),
+ };
+ let n = match pp.start_at {
+ Some(s) => s.max(1),
+ None if restart => 1,
+ None => self.numbers[l].saturating_add(1),
+ };
+ self.numbers[l] = n;
+ self.labels[l] = pp.number_style.format(n);
+ self.seen[l] = self.tick;
+ n
+ }
+}
diff --git a/crates/doc/src/attrs/tabs.rs b/crates/doc/src/attrs/tabs.rs
new file mode 100644
index 000000000..6962bcc73
--- /dev/null
+++ b/crates/doc/src/attrs/tabs.rs
@@ -0,0 +1,181 @@
+use super::*;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum TabAlign {
+ #[default]
+ Left,
+ Center,
+ Right,
+ /// Align on a character (default `.`).
+ Char,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TabStop {
+ /// A file that held a non-finite position (written as `null`) reads it back as NaN, which
+ /// [`TabStop::sanitized_list`] drops.
+ #[serde(deserialize_with = "position_or_nan")]
+ pub position: f64,
+ #[serde(default)]
+ pub align: TabAlign,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub leader: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub align_on: String,
+}
+
+/// Most stops a paragraph holds.
+pub const MAX_TAB_STOPS: usize = 100;
+
+/// Furthest stop position: 216 in, the largest page.
+pub const MAX_TAB_POSITION: f64 = 15_552.0;
+
+/// Longest leader, in characters.
+pub const MAX_TAB_LEADER: usize = 8;
+
+/// Stops closer than this share a position.
+pub const SAME_TAB_POSITION: f64 = 0.01;
+
+/// Smallest type size the engine accepts, in points.
+pub const MIN_TYPE_SIZE: f64 = 0.1;
+
+/// Largest type size the engine accepts, in points, as InDesign's own field allows.
+pub const MAX_TYPE_SIZE: f64 = 1296.0;
+
+/// Largest measure an imported indent, spacing or offset can carry, in points: the furthest tab
+/// stop, which is the widest page.
+pub const MAX_MEASURE: f64 = MAX_TAB_POSITION;
+
+/// A type size read from a file, or `None` when it is not a size the engine can mean.
+///
+/// A file can hold any number, including `NaN`, `inf`, `0`, a negative or `1e300`. Every importer
+/// had its own spelling of this test, or only checked that the value was finite -- so tagged text
+/// took `<cSize:1e300>` and set a 1e300 pt size on the text (#1593). A size outside the range is
+/// dropped rather than clamped, so the text keeps the size its style gives it.
+pub fn imported_type_size(pt: f64) -> Option<f64> {
+ (pt.is_finite() && (MIN_TYPE_SIZE..=MAX_TYPE_SIZE).contains(&pt)).then_some(pt)
+}
+
+/// An indent, spacing or offset read from a file, clamped to ±[`MAX_MEASURE`]; `None` when the
+/// value is not finite.
+///
+/// Unlike a type size this is clamped rather than dropped: a file that says "indent everything"
+/// still indents to the widest page the engine has, where dropping the value would quietly
+/// restore the style's own indent and hide what the file asked for (#1593).
+pub fn imported_measure(pt: f64) -> Option<f64> {
+ pt.is_finite().then(|| pt.clamp(-MAX_MEASURE, MAX_MEASURE))
+}
+
+impl TabStop {
+ /// A finite position clamped to `0..=MAX_TAB_POSITION`.
+ pub fn clamp_position(v: f64) -> Result<f64, String> {
+ if v.is_finite() { Ok(v.clamp(0.0, MAX_TAB_POSITION)) } else { Err("position must be a finite number".into()) }
+ }
+
+ /// A leader: up to [`MAX_TAB_LEADER`] characters, no control characters.
+ pub fn check_leader(v: &str) -> Result<(), String> {
+ if v.chars().count() > MAX_TAB_LEADER || v.chars().any(char::is_control) {
+ return Err(format!("`leader`: at most {MAX_TAB_LEADER} printable characters"));
+ }
+ Ok(())
+ }
+
+ /// An align-on character: one printable character or none (a decimal point).
+ pub fn check_align_on(v: &str) -> Result<(), String> {
+ if v.chars().count() > 1 || v.chars().any(char::is_control) {
+ return Err("`alignOn`: one printable character".into());
+ }
+ Ok(())
+ }
+
+ /// A tab-stop list as the Tabs commands keep it: at most [`MAX_TAB_STOPS`] stops, positions
+ /// clamped, leaders and align-on characters checked, a char stop aligning on `.` unless it
+ /// names a character, sorted by position, and one stop per position (the later one wins).
+ pub fn checked_list(mut tabs: Vec<TabStop>) -> Result<Vec<TabStop>, String> {
+ if tabs.len() > MAX_TAB_STOPS {
+ return Err(format!("a paragraph holds at most {MAX_TAB_STOPS} tab stops"));
+ }
+ for t in &mut tabs {
+ t.position = Self::clamp_position(t.position)?;
+ Self::check_leader(&t.leader)?;
+ Self::check_align_on(&t.align_on)?;
+ }
+ Ok(Self::normalized(tabs))
+ }
+
+ /// A tab-stop list read from a file, repaired to what [`checked_list`](Self::checked_list)
+ /// accepts: stops with a non-finite position dropped, positions clamped, control characters
+ /// removed from leaders and align-on characters and both cut to their limits, sorted, one stop
+ /// per position (the later one wins), and the first [`MAX_TAB_STOPS`] by position kept.
+ pub fn sanitized_list(tabs: Vec<TabStop>) -> Vec<TabStop> {
+ let tabs = tabs
+ .into_iter()
+ .filter_map(|mut t| {
+ t.position = Self::clamp_position(t.position).ok()?;
+ if Self::check_leader(&t.leader).is_err() {
+ t.leader = t.leader.chars().filter(|c| !c.is_control()).take(MAX_TAB_LEADER).collect();
+ }
+ if Self::check_align_on(&t.align_on).is_err() {
+ t.align_on = t.align_on.chars().filter(|c| !c.is_control()).take(1).collect();
+ }
+ Some(t)
+ })
+ .collect();
+ let mut out = Self::normalized(tabs);
+ out.truncate(MAX_TAB_STOPS);
+ out
+ }
+
+ /// Finite, clamped stops sorted by position, one per position: of stops closer than
+ /// [`SAME_TAB_POSITION`], the later one in `tabs` wins. A char stop with no character aligns
+ /// on `.`.
+ fn normalized(tabs: Vec<TabStop>) -> Vec<TabStop> {
+ let mut stops: Vec<(usize, TabStop)> = tabs.into_iter().enumerate().collect();
+ stops.sort_by(|a, b| a.1.position.total_cmp(&b.1.position));
+ let mut out: Vec<(usize, TabStop)> = Vec::with_capacity(stops.len());
+ for (i, mut t) in stops {
+ if t.align == TabAlign::Char && t.align_on.is_empty() {
+ t.align_on = ".".into();
+ }
+ match out.last_mut() {
+ Some(last) if t.position - last.1.position < SAME_TAB_POSITION => {
+ if i > last.0 {
+ *last = (i, t);
+ }
+ }
+ _ => out.push((i, t)),
+ }
+ }
+ out.into_iter().map(|(_, t)| t).collect()
+ }
+}
+
+/// A stop's position; `null` (how JSON writes a non-finite number) reads as NaN.
+fn position_or_nan<'de, D: serde::Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
+ Ok(Option::<f64>::deserialize(d)?.unwrap_or(f64::NAN))
+}
+
+/// A paragraph's tab-stop list in either attribute form, as read from a file.
+pub(super) trait FileTabs: Sized {
+ fn sanitized(self) -> Self;
+}
+
+impl FileTabs for Vec<TabStop> {
+ fn sanitized(self) -> Self {
+ TabStop::sanitized_list(self)
+ }
+}
+
+impl FileTabs for Option<Vec<TabStop>> {
+ fn sanitized(self) -> Self {
+ self.map(TabStop::sanitized_list)
+ }
+}
+
+/// Deserializes a `tabs` field through [`TabStop::sanitized_list`]: a saved document's tab lists
+/// get the limits the Tabs commands keep.
+pub(super) fn sanitized_tabs<'de, D: serde::Deserializer<'de>, T: Deserialize<'de> + FileTabs>(d: D) -> Result<T, D::Error> {
+ T::deserialize(d).map(FileTabs::sanitized)
+}