diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 6863960230..a07afd0843 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -32,8 +32,8 @@ pub use para_style::{ pub use runs::PATH_LEAD_MAX; pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias}; pub use tabs_lists::{ - Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, - TabStop, + Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, + TabAlign, TabStop, }; pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5bd31f7699..5a6cff4b56 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -284,17 +284,40 @@ impl TextObject { /// Update the paragraph styles for replacing bytes `start..end` of the current plain text by /// `insert` (call before changing the runs). The paragraph the range starts in keeps its /// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that - /// style too (Return continues the paragraph it splits); later paragraphs keep theirs. + /// style too (Return continues the paragraph it splits), without the number its list gives it + /// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new + /// paragraphs is made at the start of a paragraph and some of that paragraph's text stays + /// after it, that number moves with the text to the last paragraph the insertion starts. pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) { - if self.paras.is_empty() { + let added = insert.bytes().filter(|&b| b == b'\n').count(); + let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some()); + // With one style for every paragraph, the new paragraphs take it as it is unless its list + // gives the paragraph a number. + if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) { return; } let r = self.paragraphs_in(start, end); let v = self.paragraph_styles(); - let Some(keep) = v.get(r.start).cloned() else { return }; - let added = insert.bytes().filter(|&b| b == b'\n').count(); + let Some(mut keep) = v.get(r.start).cloned() else { return }; + let given = keep.list.and_then(|l| l.start); + if let Some(l) = keep.list.as_mut() { + l.start = None; + } let mut out: Vec = v.iter().take(r.start + 1).cloned().collect(); out.extend(std::iter::repeat_n(keep, added)); + let text = self.plain_text(); + let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len())); + let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n')); + // The paragraph's text after the replaced bytes, which the last new paragraph then holds. + let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n'); + if given.is_some() && added > 0 && at_para_start && text_kept { + if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) { + l.start = None; + } + if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) { + l.start = given; + } + } out.extend(v.iter().skip(r.end).cloned()); self.paras = out; if let Some(first) = self.paras.first() { diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 26622fa115..2d62eb2f0d 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -206,15 +206,41 @@ pub struct ParaList { /// ([`Self::depth`]). The file saves it only when it is not 1. #[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")] pub level: u8, + /// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs + /// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the + /// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made + /// with Return in a paragraph that has one does not take it, and a paragraph style does not + /// keep it. A saved number outside the range is read as the nearest one. The file saves it + /// only when it is set. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")] + pub start: Option, } impl Default for ParaList { - /// A bulleted list with a dot, its marker aligned left, at level 1. + /// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the + /// paragraph before. fn default() -> Self { - Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 } + Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None } } } +/// The largest number a numbered paragraph can be given ([`ParaList::start`]). +pub const MAX_LIST_START: u32 = 999_999_999; + +/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`], +/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else +/// is an error. +fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let start = match serde_json::Value::deserialize(d)? { + serde_json::Value::Null => return Ok(None), + serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => { + n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START))) + } + _ => return Err(serde::de::Error::custom("a list start must be a whole number")), + }; + Ok(u32::try_from(start).ok()) +} + /// Is `level` the first list level, which the file does not save? fn is_first_level(level: &u8) -> bool { *level == 1 @@ -307,6 +333,12 @@ impl ParaList { Self { level, ..self } } + /// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the + /// paragraph before). + pub fn starting_at(self, start: Option) -> Self { + Self { start, ..self } + } + /// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken /// as the nearest level. pub fn depth(&self) -> usize { @@ -334,8 +366,9 @@ impl ParaList { /// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts /// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1 /// again; a bulleted one has its bullet and leaves the count of its level as it is, and a - /// numbered one adds one to the count of its level and is numbered with it. A paragraph back - /// at a shallower level then goes on with that level's count. + /// numbered one adds one to the count of its level and is numbered with it, or with the number + /// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a + /// shallower level then goes on with that level's count. pub fn next_marker(list: Option, empty: bool, counts: &mut ListCounts) -> Option { let Some(list) = list else { *counts = ListCounts::default(); @@ -350,7 +383,7 @@ impl ParaList { } let count = &mut counts.0[level]; if list.number.is_some() { - *count = count.saturating_add(1); + *count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START)); } Some(list.marker(*count)) } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index a5230d5d86..53419ecb53 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() { assert_eq!(opened.list_level_counts, (1..=8).collect::>(), "a file keeps only the counts of levels 2 to 9"); } +/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level +/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does +/// not use the number, and a paragraph in no list still starts the count again. The file saves the +/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one. +#[test] +fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() { + let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start)); + let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7))); + let mut counts = ListCounts::default(); + let markers: Vec> = [ + (num(1, None), false), + (num(1, Some(5)), false), + (num(1, None), false), + (num(2, None), false), + (num(2, Some(1)), false), + (num(2, None), false), + (num(1, None), false), + (num(1, Some(9)), true), + (num(1, None), false), + (dot, false), + (num(1, Some(1)), false), + (None, false), + (num(1, None), false), + ] + .iter() + .map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts)) + .collect(); + let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."]; + assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::>(), want); + let mut counts = ListCounts::default(); + let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START))); + assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999.")); + let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0))); + assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1"); + assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"})); + assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5})); + let read = |v: serde_json::Value| serde_json::from_value::(v).unwrap().start; + assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5)); + assert_eq!(read(serde_json::json!({"number": "arabic"})), None); + assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None); + let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)]; + assert_eq!( + starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))), + [Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)], + "a saved number outside 1 to 999999999 reads as the nearest one" + ); + for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] { + assert!(serde_json::from_value::(serde_json::json!({ "start": bad })).is_err(), "{bad}"); + } +} + +/// Return in a paragraph that its list gives a number makes paragraphs without it, also while +/// every paragraph shares one style; Return at the start of its text moves the number with the +/// text, and Return elsewhere leaves it where it was. +#[test] +fn return_does_not_copy_a_paragraphs_number() { + let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() }; + let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::>(); + // One style for the whole text: Return after "one" splits it. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(five); + t.splice_paras(3, 3, "\n"); + t.runs[0].text.insert(3, '\n'); + t.normalize_paras(); + assert_eq!(starts(&t), [Some(5), None]); + assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list"); + // Return at the start of "two" (a paragraph with a number of its own): the number moves on + // with the text, and the empty paragraph left before it has none. + t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8)))); + t.splice_paras(4, 4, "\n\n"); + t.runs[0].text.insert_str(4, "\n\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, Some(8)]); + // A whole paragraph pasted at the start of "two": the number stays with "two". + t.splice_paras(6, 6, "Pasted\n"); + t.runs[0].text.insert_str(6, "Pasted\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]); + // "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it. + t.splice_paras(13, 16, "A\nB"); + t.runs[0].text.replace_range(13..16, "A\nB"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]); + // Text without a number keeps one style for every paragraph. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() }); + t.splice_paras(3, 3, "\n"); + assert!(t.paras.is_empty()); +} + /// In a threaded frame whose first paragraph continues from the frame before, the text at the /// frame's start is not the start of a paragraph, so typing a list's start there starts nothing. /// The paragraphs after it still start lists. diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index a155245fbc..7db343afc3 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids`, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -482,6 +482,52 @@ fn list_level_param(p: &Value, cmd: &str) -> Result> { } } +/// The number a numbered paragraph is given, from `startNumber` (a whole number from 1 to +/// [`vectorcraft_doc::text::MAX_LIST_START`]) or `restartNumbering` (true: 1): `Some(Some(n))`, +/// or `Some(None)` for `restartNumbering` false, which numbers paragraphs on from the one before. +/// None without either; giving both is an error. +fn list_start_param(p: &Value, cmd: &str) -> Result>> { + let (key, other) = ("startNumber", "restartNumbering"); + let start = p.get(key).filter(|v| !v.is_null()); + let restart = p.get(other).filter(|v| !v.is_null()); + if start.is_some() && restart.is_some() { + return Err(bad(cmd, format!("give `{key}` or `{other}`, not both"))); + } + if let Some(v) = start { + let (min, max) = (1, vectorcraft_doc::text::MAX_LIST_START); + return match v.as_f64() { + Some(x) if x.fract() == 0.0 && (f64::from(min)..=f64::from(max)).contains(&x) => Ok(Some(Some(x as u32))), + Some(x) => Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))), + None => Err(bad(cmd, format!("`{key}` must be a whole number"))), + }; + } + // `check_switches` has already refused a value that is not true or false. + Ok(restart.and_then(Value::as_bool).map(|on| on.then_some(1))) +} + +/// Take the number its list gives a paragraph away from paragraphs `paras` of `t` (indices; +/// None: every paragraph), so they count on from the paragraph before. +fn clear_list_start(t: &mut vectorcraft_doc::text::TextObject, paras: Option>) { + let paras = paras.unwrap_or(0..t.paragraph_count()); + t.edit_paras(Some(paras), |p| { + if let Some(l) = p.list.as_mut() { + l.start = None; + } + }); +} + +/// Among paragraphs `paras` of `t` (indices; None: every paragraph), the first numbered paragraph +/// that holds text and the first numbered paragraph: where a number from [`list_start_param`] can go. +fn list_start_candidates(t: &vectorcraft_doc::text::TextObject, paras: Option>) -> (Option, Option) { + let paras = paras.unwrap_or(0..t.paragraph_count()); + let text = t.plain_text(); + let pieces: Vec<&str> = text.split('\n').collect(); + let mut numbered = paras.filter(|&i| t.para_at(i).list.is_some_and(|l| l.number.is_some())).peekable(); + let first = numbered.peek().copied(); + let with_text = numbered.find(|&i| pieces.get(i).is_some_and(|s| !s.is_empty())); + (with_text, first) +} + /// Set the Warichu and Warichu Settings of `st` that are given: Warichu on or off, Lines, Line Gap /// (in the type's own units), Scale and Alignment. fn set_warichu( @@ -523,6 +569,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "koreanLineBreakAnywhere", "bunriKinshi", "kurikaeshiMojiShori", + "restartNumbering", ], C, )?; @@ -582,6 +629,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "number", "listAlign", "listLevel", + "startNumber", + "restartNumbering", "hyphenate", "wordsLongerThan", "afterFirst", @@ -762,6 +811,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { .map(|a| if a == "right" { vectorcraft_doc::text::ListAlign::Right } else { vectorcraft_doc::text::ListAlign::Left }); // …and `listLevel` the level of every list paragraph, 1 to 9. let list_level = list_level_param(p, C)?; + // …and `startNumber` or `restartNumbering` the number of the first numbered paragraph. + let list_start = list_start_param(p, C)?; let indents_given = num("leftIndent").is_some() || num("firstLineIndent").is_some(); let spacing = |k: &str| spacing_param(p, k, C); let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?); @@ -885,9 +936,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result { // A numbered list for list "number", or without `list` for a number style. let numbered = list == Some("number") || (list.is_none() && number.is_some()); // The list's other settings (the marker's alignment) stay as they were. + // A paragraph made bulleted keeps no number of its own. para.list = on.then(|| vectorcraft_doc::text::ParaList { bullet: bullet.flatten().or(had.map(|l| l.bullet)).unwrap_or_default(), number: numbered.then(|| number.flatten().or(had.and_then(|l| l.number)).unwrap_or_default()), + start: had.and_then(|l| l.start).filter(|_| numbered), ..had.unwrap_or_default() }); // A paragraph that joins a list with no left or first-line indent gets a @@ -912,6 +965,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let d = &mut doc; // The paragraph change, for the graph labels to keep. let mut para_change = None; + // Where the number `startNumber` or `restartNumbering` gives goes: the first numbered + // paragraph with text the call touches, through every target, else the first numbered one. + let (mut start_with_text, mut start_first) = (None, None); let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")); for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; @@ -1021,14 +1077,36 @@ fn set_format(s: &mut Session, p: &Value) -> Result { para.composer = v; } }; - t.edit_paras(span, |para| paras(para, &mut out_of_order)); + t.edit_paras(span.clone(), |para| paras(para, &mut out_of_order)); if let Some(name) = out_of_order { return Err(out_of_order_error(name)); } + match list_start { + Some(None) => clear_list_start(t, span), + Some(Some(_)) if start_with_text.is_none() => { + let (with_text, first) = list_start_candidates(t, span); + start_with_text = with_text.map(|i| (*id, i)); + start_first = start_first.or(first.map(|i| (*id, i))); + } + _ => {} + } super::typecmd::refresh_bounds(t); changed |= *t != before; para_change = Some(paras); } + if let Some(Some(n)) = list_start + && let Some((id, i)) = start_with_text.or(start_first) + && let Some(NodeKind::Text(t)) = d.node_mut(id).map(|node| &mut node.kind) + { + let before = t.clone(); + t.edit_paras(Some(i..i + 1), |p| { + if let Some(l) = p.list.as_mut() { + l.start = Some(n); + } + }); + super::typecmd::refresh_bounds(t); + changed |= *t != before; + } // Graph labels keep a change made to all of their text through the graph being drawn again. if range.is_none() { let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0)); diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index e560c831cd..d544697c5c 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -488,8 +488,14 @@ fn selection_attrs(s: &Session, p: &Value, kind: Kind, verb: &str) -> Result para_attrs(t.para_at(t.paragraphs_in(at, at).start)), + // The paragraph at `start`, without the number its list gives that paragraph alone. + Kind::Para => { + let mut para = t.para_at(t.paragraphs_in(at, at).start).clone(); + if let Some(l) = para.list.as_mut() { + l.start = None; + } + para_attrs(¶) + } })) } @@ -639,6 +645,11 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } Kind::Para => { let mut st = with_attrs(&ParaStyle::default(), m, &c)?; + // A list's number belongs to one paragraph, not to a style. + if st.list.is_some_and(|l| l.start.is_some()) { + let k = "list.start"; + return Err(bad(&c, format!("unknown attribute `{k}`"))); + } para_ranges(&st, m, kept, &c)?; sort_tabs(&mut st, m, kept); para_attrs(&st) diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index aa6b75032d..682ec5439e 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -736,6 +736,156 @@ fn numbered_lists_are_set_per_paragraph_saved_and_styled() { assert_eq!((list(&s, 0), list(&s, 1), list(&s, 2)), (None, None, None)); } +/// `text.setFormat {startNumber}` gives the first numbered paragraph it touches a number, and the +/// paragraphs after it count on from it; `restartNumbering` true gives it 1 and false takes the +/// numbers away. Each change is one undo step, a call that changes nothing records none, and a +/// bad value or both keys change nothing. The file keeps the number, Return and paragraph styles +/// do not take it, a bulleted paragraph keeps none, and Convert to Text writes the numbers shown. +#[test] +fn a_numbered_paragraph_starts_at_a_given_number_or_restarts() { + use vectorcraft_doc::text::{Bullet, ParaList}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s + .execute("text.create", &json!({"x": 10, "y": 10, "text": "Intro\nOne\nTwo\nThree\nFour", "area": {"width": 300, "height": 200}})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + let starts = |s: &Session| text(s).paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::>(); + let numbers = |s: &Session| { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s)).markers.iter().map(|m| m.text.clone()).collect::>() + }; + let undo = |s: &Session| s.active().unwrap().history.undo.len(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // A call over all the text gives the number to the first paragraph the same call numbers. + s.execute("text.setFormat", &json!({"start": 6, "end": 24, "number": "arabic", "startNumber": 5})).unwrap(); + assert_eq!(starts(&s), [None, Some(5), None, None, None]); + assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."]); + // On "Three": `restartNumbering` gives it 1, and "Four" counts on from it. + let steps = undo(&s); + s.execute("text.setFormat", &json!({"start": 14, "end": 14, "restartNumbering": true})).unwrap(); + assert_eq!((numbers(&s), undo(&s)), (vec!["5.".to_string(), "6.".into(), "1.".into(), "2.".into()], steps + 1)); + // The same number again, or a call on a paragraph in no list, changes nothing. + s.execute("text.setFormat", &json!({"start": 14, "end": 14, "startNumber": 1.0})).unwrap(); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 3})).unwrap(); + assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1)); + // Bad values and both keys at once are errors and change nothing. + for bad in [ + json!({"startNumber": 0}), + json!({"startNumber": -2}), + json!({"startNumber": 2.5}), + json!({"startNumber": 1_000_000_000}), + json!({"startNumber": "5"}), + json!({"restartNumbering": "yes"}), + json!({"startNumber": 3, "restartNumbering": true}), + ] { + assert!(s.execute("text.setFormat", &bad).is_err(), "{bad}"); + } + assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."], "one Undo takes the restart back"); + s.execute("edit.redo", &json!({})).unwrap(); + // The file keeps the numbers. + assert_eq!(serde_json::to_value(text(&s).para_at(1)).unwrap()["list"], json!({"bullet": "dot", "number": "arabic", "start": 5})); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert_eq!(back.paragraph_styles(), text(&s).paragraph_styles()); + // Return at the end of "One" makes an item that counts on, without a number of its own. + s.execute("text.editRange", &json!({"id": id, "start": 9, "end": 9, "insert": "\nOne and a half"})).unwrap(); + assert_eq!(numbers(&s), ["5.", "6.", "7.", "1.", "2."]); + assert_eq!(starts(&s), [None, Some(5), None, None, Some(1), None]); + // A paragraph style made from the paragraph does not keep its number, and a style's list + // with a number is an error. + s.execute("paraStyle.new", &json!({"name": "Item", "id": id, "start": 6, "end": 6})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Item", "id": id})).unwrap(); + assert_eq!(starts(&s), [None; 6]); + assert_eq!(numbers(&s), ["1.", "2.", "3.", "4.", "5.", "6."]); + let given = json!({"name": "Given", "attrs": {"list": {"number": "arabic", "start": 4}}}); + assert!(s.execute("paraStyle.new", &given).is_err()); + // `restartNumbering` false takes every number the call touches away; a paragraph made bulleted + // keeps none. + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap(); + s.execute("text.setFormat", &json!({"start": 6, "end": 6, "startNumber": 3})).unwrap(); + assert_eq!(starts(&s)[..2], [Some(7), Some(3)]); + s.execute("text.setFormat", &json!({"restartNumbering": false})).unwrap(); + assert_eq!(starts(&s), [None; 6]); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap(); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "bullet": "dot"})).unwrap(); + assert_eq!(text(&s).para_at(0).list, Some(ParaList::bulleted(Bullet::Dot))); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "upperRoman"})).unwrap(); + assert_eq!(text(&s).para_at(0).list.and_then(|l| l.start), None, "numbered again, it counts on"); + // Convert to Text writes the numbers the paragraphs showed. + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "arabic", "startNumber": 10})).unwrap(); + s.execute("text.setFormat", &json!({"start": 30, "end": 30, "restartNumbering": true})).unwrap(); + let shown = numbers(&s); + assert_eq!(shown, ["10.", "11.", "12.", "13.", "1.", "2."]); + s.execute("text.convertListToText", &json!({})).unwrap(); + let written: Vec = text(&s).plain_text().split('\n').map(|p| p.split('\t').next().unwrap_or("").to_string()).collect(); + assert_eq!(written, shown); + assert_eq!(starts(&s), [None; 6]); + assert!(text(&s).paragraph_styles().iter().all(|p| p.list.is_none())); +} + +/// In threaded type, a paragraph given a number in the first frame carries its count on through +/// the later frames, and a paragraph given 1 in a later frame starts the count again there. +#[test] +fn a_given_number_carries_through_threaded_frames() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let numbers = |s: &Session, id: u64| { + let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::>() + }; + let story = (1..=10).map(|i| format!("Item {i}")).collect::>().join("\n"); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap(); + let first = numbers(&s, a).len(); + assert!((2..10).contains(&first), "both frames hold items: {first}"); + s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 20})).unwrap(); + let want: Vec = (20..30).map(|n| format!("{n}.")).collect(); + assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want); + // The first paragraph of the second frame given 1: the second frame counts from 1. + s.execute("text.setFormat", &json!({"ids": [b], "start": 0, "end": 0, "restartNumbering": true})).unwrap(); + let want: Vec = (20..20 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect(); + assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want); + // Editing the first frame's number moves every later number on with it. + s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 2})).unwrap(); + let want: Vec = (2..2 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect(); + assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want); +} + +/// `startNumber` over several type objects goes to the first numbered paragraph with text among +/// all of them, past an empty numbered object listed first; with no text anywhere it goes to the +/// first numbered paragraph. +#[test] +fn a_given_number_goes_to_the_first_numbered_text_across_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let make = + |s: &mut Session, y: u32, text: &str| s.execute("text.create", &json!({"x": 10, "y": y, "text": text})).unwrap()["id"].as_u64().unwrap(); + let empty = make(&mut s, 10, ""); + let full = make(&mut s, 60, "One\nTwo"); + let start = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).list.and_then(|l| l.start), + _ => panic!("text"), + }; + s.execute("text.setFormat", &json!({"ids": [empty, full], "number": "arabic"})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [empty, full], "startNumber": 4})).unwrap(); + assert_eq!((start(&s, empty), start(&s, full)), (None, Some(4))); + let other = make(&mut s, 120, ""); + s.execute("text.setFormat", &json!({"ids": [other, empty], "number": "arabic"})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [other, empty], "startNumber": 6})).unwrap(); + assert_eq!((start(&s, other), start(&s, empty)), (Some(6), None)); +} + /// Bullets and Numbering… › Alignment: `text.setFormat {listAlign}` sets where the marker /// stands in the list paragraphs it touches, in one undo step, and refuses unknown values; /// a paragraph in no list gets no list from it. A list keeps its alignment when it changes diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0e3d6df203..2b2d9a0c0b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -260,7 +260,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.bulletsAndNumbering", "Bullets and Numbering…", "", - "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", + "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt), startAt (bool: the Numbers tab's Start at box, on when the paragraphs have the same number of their own, blank when those differ; on sends startNumber, off sends restartNumbering false), startNumber (1..999999999: its number, 1 until one is typed)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", ), ( "type.convertListToText", diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 43f15edbb8..93c20339e7 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -12,14 +12,20 @@ //! preset picked), `bullet` (`dot`, `dash`, `circle` or `square`), `number` (`arabic`, //! `upperLetters`, `lowerLetters`, `upperRoman`, `lowerRoman`, `twoDigits` or `threeDigits`), //! `listAlign` (`left` or `right`), `listLevel` (1 to 9; 1 for paragraphs in no list), -//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, with `__initial` (the -//! values it opened with) and `__targets` (the type and range it acts on). +//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, `startAt` (the Numbers +//! tab's Start At box) and `startNumber` (its number, 1 to 999999999), with `__initial` (the values +//! it opened with) and `__targets` (the type and range it acts on). +//! +//! Start At is VectorCraft's own: on, OK gives the first numbered paragraph the number in the +//! field (`text.setFormat` `startNumber`), and the numbered paragraphs after it count on from it; +//! off, the paragraphs count on from the paragraph before (`restartNumbering` false). The box is on +//! when the paragraphs have a number of their own, off when none has, and blank when they differ. //! //! Behavior reference (public documentation): //! . use serde_json::{Map, Value, json}; -use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, NumberStyle, ParaList}; +use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; use super::swatch_options::label; use super::{DialogSpec, form}; @@ -52,7 +58,7 @@ const ARROWS: egui::EventFilter = egui::EventFilter { tab: false, horizontal_arr /// The fields `ui.dialog.set` can set while the dialog does not hold them: the dialog leaves a /// field out where the paragraphs differ, and holds no `bullet` or `number` for paragraphs in no /// list or in another kind of list. -const INPUTS: [&str; 7] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent"]; +const INPUTS: [&str; 9] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent", "startAt", "startNumber"]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Bullets and Numbering").into(), @@ -114,6 +120,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if let Some(v) = shared_para_field(app, |p| p.first_line_indent) { values.insert("firstLineIndent".into(), json!(v)); } + // …and Start At: on with the number when the paragraphs share one, off when none has one. + if let Some(start) = shared_para(app, |p| p.list.and_then(|l| l.start)) { + values.insert("startAt".into(), json!(start.is_some())); + if let Some(n) = start { + values.insert("startNumber".into(), json!(n)); + } + } let tab = tab.unwrap_or(if list == Some("number") { "numbers" } else { "bullets" }); let mut fields = Value::Object(values.clone()); fields[INITIAL] = Value::Object(values); @@ -210,6 +223,29 @@ fn number_tab(ui: &mut egui::Ui, d: &mut Dialog) { } None => {} } + ui.add_space(8.0); + start_at(ui, d); +} + +/// The Start At box and its number, 1 to [`MAX_LIST_START`]: the box shows a dash while the +/// paragraphs' numbers differ, and a click then turns it on; the number field is dimmed unless the +/// box is on, and shows 1 until a number is typed. +fn start_at(ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + let on = d.fields.get("startAt").and_then(Value::as_bool); + if widgets::check3(ui, tl!("Start at:"), on, true) { + d.fields.insert("startAt".into(), json!(on != Some(true))); + } + let value = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + ui.add_enabled_ui(on == Some(true), |ui| { + let name = Some(tl!("Start at:")); + if let Some(v) = + widgets::range_field_named(ui, ("bullets-numbering", "startNumber"), name, value, 1.0..=f64::from(MAX_LIST_START), "", 0, 90.0) + { + d.fields.insert("startNumber".into(), json!(v)); + } + }); + }); } /// A row of preset buttons named `names`, `current` selected, each drawn by `paint` (painter, @@ -367,6 +403,20 @@ fn params(d: &Dialog) -> Map { { p.insert("listLevel".into(), json!(l)); } + // …and Start At, unless the paragraphs are made bulleted or taken out of their list: on, the + // number shown; off, the paragraphs count on from the one before. + if let Some(on) = d.fields.get("startAt").and_then(Value::as_bool) + && !matches!(field("list"), Some("none" | "bullet")) + { + let n = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + let was_on = initial.and_then(|m| m.get("startAt")).and_then(Value::as_bool); + let was_n = initial.and_then(|m| m.get("startNumber")).and_then(Value::as_f64); + if on && (was_on != Some(true) || was_n != Some(n)) { + p.insert("startNumber".into(), json!(n)); + } else if !on && was_on != Some(false) { + p.insert("restartNumbering".into(), json!(false)); + } + } // For paragraphs in a list and paragraphs in none, an indent left as it was is not sent: // `text.setFormat` then gives each paragraph that joins the list its hanging indent. let mixed = initial.is_some_and(|m| !m.contains_key("list")); @@ -690,7 +740,8 @@ mod tests { app.run("text.setFormat", json!({"ids": [id], "listAlign": "right", "listLevel": 2, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); let held = app.ui.dialog.as_ref().unwrap().fields.clone(); - for key in INPUTS { + // Neither paragraph has a number of its own, so Start at is off, not blank. + for key in INPUTS.into_iter().filter(|k| !["startAt", "startNumber"].contains(k)) { assert!(!held.contains_key(key), "{key} is blank"); } let fields = json!([ @@ -737,6 +788,67 @@ mod tests { assert_eq!((first(&app, id).0.map(|l| l.level), paras(&app, id).1.list.map(|l| l.level)), (Some(2), Some(2))); } + /// Start at: the box opens off for paragraphs without a number of their own and on with the + /// number for one that has it; a change shows on the type at once, OK keeps it as one undo + /// step, Cancel puts the type back, and turning the box off sends `restartNumbering` false. + #[test] + fn start_at_gives_the_first_numbered_paragraph_its_number() { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.fields.get("startNumber")), (Some(&json!(false)), None)); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + frame(&mut app); + let starts = |app: &VectorcraftApp| { + let (one, two) = paras(app, id); + (one.list.and_then(|l| l.start), two.list.and_then(|l| l.start)) + }; + assert_eq!(starts(&app), (Some(4), None), "previewed on the type"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the preview adds no undo step"); + super::super::cancel(&mut app); + assert_eq!(starts(&app), (None, None), "Cancel puts it back"); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((starts(&app), app.session.active().unwrap().history.undo.len()), ((Some(4), None), undo + 1)); + // One paragraph with a number and one without: the box is blank, and OK sends nothing for it. + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert!(!d.fields.contains_key("startAt") && !changes(¶ms(&d))); + // The blank box shows a dash, not an empty box. + use egui::accesskit::{Role, Toggled}; + let mut shown = d.clone(); + let tree = crate::widgets::accessibility_tests::tree(|ui| start_at(ui, &mut shown)); + let check = tree.iter().find(|n| n.label() == Some("Start at:") && n.role() == Role::CheckBox).map(|n| n.toggled()); + assert_eq!(check, Some(Some(Toggled::Mixed))); + // A preset that makes the paragraphs bulleted sends no number. + set(&mut app, "startAt", json!(true)); + pick_preset(&mut app, "bullet", Some("dot")); + let p = params(app.ui.dialog.as_ref().unwrap()); + assert!(!p.contains_key("startNumber") && !p.contains_key("restartNumbering")); + super::super::cancel(&mut app); + // A paragraph with a number opens the box on with it, and off sends it back to counting on. + let solo = app.run("text.create", json!({"x": 10, "y": 200, "text": "Solo"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [solo]})).unwrap(); + app.run("text.setFormat", json!({"number": "arabic", "startNumber": 9})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.f64("startNumber", 0.0)), (Some(&json!(true)), 9.0)); + assert!(!changes(¶ms(&d)), "nothing changed yet"); + set(&mut app, "startAt", json!(false)); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()).get("restartNumbering"), Some(&json!(false))); + super::super::confirm(&mut app).unwrap(); + let start = match &app.session.active().unwrap().doc.node(NodeId(solo)).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).list.map(|l| l.start), + _ => panic!("not text"), + }; + assert_eq!(start, Some(None), "still numbered, with no number of its own"); + } + /// `text.setFormat` sets `listLevel` only on paragraphs in a list, so a Level change alone on /// paragraphs in no list sends nothing and adds no undo step; with a preset it applies. #[test] diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..aeed1b43a9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3766,6 +3766,7 @@ Start Normally સામાન્ય રીતે શરૂ કરો Start Tile શરૂઆતની ટાઇલ Start arrowhead શરૂઆતનું એરોહેડ + Start at: આનાથી શરૂ કરો: Start from VectorCraft Defaults VectorCraft ડિફૉલ્ટથી શરૂ કરો Start in Safe Mode સેફ મોડમાં શરૂ કરો Start: શરૂ: diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..fef6416e39 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10222,6 +10222,24 @@ after Remove Threading or Release Selection, in a frame converted to point type, duplicated, copied in the Layers panel, or taken out of a symbol or a placed file). A symbol made of a thread keeps the numbers in the symbol's art. +`text.setFormat {startNumber: 1..999999999}` gives a numbered paragraph a number of its own, and +`text.setFormat {restartNumbering: true}` gives it 1. Both are VectorCraft's own. The number goes to the first numbered +paragraph the call touches: the first that holds text, or the first when none does, taking the type objects in the +order of `ids`. That paragraph shows the number, and the numbered paragraphs after it at its level count on from it, +through the frames of threaded type. Deeper levels count from 1 after it, as after any list paragraph, and a paragraph in +no list still starts the count again. `restartNumbering: false` takes the number away from every paragraph the call +touches, and they count on from the paragraph before. `startNumber` is a whole number (`5` or `5.0`); 0, a negative +number, a fraction, a number past 999999999 and any other type are errors, and giving both keys is an error. A call +that touches no numbered paragraph, or that gives the number the paragraph already has, changes nothing and records no +undo step. A call that also puts paragraphs in a numbered list gives the number after the list is set. Return in a +paragraph with a number of its own does not give the number to the new paragraph; Return, or pasted text that starts +new paragraphs, at the start of its text moves the number with the text. Making the paragraph bulleted or taking it out of its list removes the number, and Convert to +Text writes the numbers the paragraphs showed. The list saves the number (`"start": 5`) only when it is set; a file's +number below 1 or past 999999999 opens as the nearest of them. A paragraph style made from the paragraph does not keep +the number, and a paragraph style's `list` with a `start` is an error (`unknown attribute`). A graph keeps one paragraph +style for every label of a kind, so a graph label loses its number when the graph is drawn again. The canvas and the formats +that write the marker (below) write the number the paragraph shows. + The canvas, EPS, PDF and Type › Create Outlines draw the marker. PDF writes the marker as text of its own, where the canvas draws it, and a PDF viewer selects, copies and finds its characters. Each of its glyphs stands for the marker character that the glyph's font maps to that glyph in its character map. Glyphs that an OpenType feature such as @@ -10242,11 +10260,14 @@ More Options at the end of the Paragraph panel's Bullets and Numbered List prese dialog (`bulletsAndNumbering`) on the paragraphs the Paragraph panel acts on, on that tab; without `tab` it opens on Numbers when the paragraphs are a numbered list and on Bullets otherwise. On both tabs the Level field, above the presets, holds the paragraphs' list level (1 to 9; 1 for paragraphs in no list). The Bullets tab has the five bullet -presets and the Numbers tab has None and the seven number styles. The Position group has Alignment (Left or Right), +presets and the Numbers tab has None and the seven number styles, then Start at, a box with a number from 1 to +999999999 (1 until one is typed). The box is on when the paragraphs have the same number of their own, off when none +has one, and blank when they differ; on, OK sends `startNumber` with the number, and off, it sends +`restartNumbering: false`, unless a preset makes the paragraphs bulleted or takes them out of their list. The Position group has Alignment (Left or Right), Left Indent and First Line Indent. The dialog opens with the values the Paragraph panel shows; where the paragraphs differ, no preset is picked and the field is blank. Its fields are `tab`, `list` (`none`, `bullet` or `number`: the kind of the preset picked), `bullet`, `number`, `listAlign`, `listLevel`, `leftIndent` and `firstLineIndent` (points), -and `ui.dialog.set` sets them, including those the dialog opened blank or without. The type shows the dialog's values while it is open. A preset picked for paragraphs that are in no list and have +`startAt` (true or false) and `startNumber`, and `ui.dialog.set` sets them, including those the dialog opened blank or without. The type shows the dialog's values while it is open. A preset picked for paragraphs that are in no list and have no indents fills in 18 pt and -18 pt, and None takes them out again while they are unchanged. OK runs `text.setFormat` with the values that changed, as one undo step, and Cancel puts the type back as it was. When a preset puts the paragraphs in a list, OK also sends the indents the dialog shows, and the paragraphs take them, 0 included. OK does not @@ -10307,6 +10328,8 @@ the paragraph's text now starts; when the text before `at` starts no list, nothi {"name":"run_command","arguments":{"command":"text.setFormat","params":{"number":"upperRoman"}}} {"name":"run_command","arguments":{"command":"text.setFormat","params":{"listAlign":"right"}}} {"name":"run_command","arguments":{"command":"text.setFormat","params":{"listLevel":2,"start":4,"end":4}}} +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"startNumber":5,"start":4,"end":4}}} +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"restartNumbering":true,"start":12,"end":12}}} {"name":"invoke_menu","arguments":{"command":"ui.bulletsAndNumbering","params":{"tab":"numbers"}}} {"name":"run_command","arguments":{"command":"text.convertListToText","params":{}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af7974b880..c716502c14 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1517,6 +1517,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. More Options in the Bullets and Numbered List presets (`ui.bulletsAndNumbering`) opens the Bullets and Numbering dialog ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): a Bullets tab and a Numbers tab with the presets, and the Position group's Alignment, Left Indent and First Line Indent, shown on the type while the dialog is open; OK applies them with `text.setFormat` (Alignment is its `listAlign`) as one undo step, and Cancel puts the type back. Alignment Left starts the marker at the first line's start, and Right ends it where the text starts. The cited page does not say where the marker sits for each choice, so these meanings are VectorCraft's own rule. Paragraph styles and the native file keep the alignment. Tab and Shift+Tab with the caret at the start of a list paragraph (`text.setFormat {listLevel}`), and the Bullets and Numbering dialog's Level field (OK sends it as `listLevel`), move the paragraph down and up the list's nine levels ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html)): each level past the first sets the paragraph 18 pt further in, each level counts its own numbers from 1, and a paragraph back at a shallower level goes on with that level's count, through threaded frames too. Elsewhere Tab inserts a tab as before; one Undo takes a level change back, and paragraph styles and the native file keep the level. Convert to Text writes each level's numbers and keeps a deeper paragraph's indent. + VectorCraft's own (the help pages above show no such control; requested in #2473): the Bullets and Numbering dialog's Start at box (`text.setFormat {startNumber}`, and `restartNumbering` for 1) gives a numbered paragraph a number from 1 to 999999999, and the numbered paragraphs after it at its level count on from it, through threaded frames too; off, the paragraphs count on from the one before. One Undo takes it back, the native file keeps it, a paragraph made with Return and a paragraph style do not take it, and Convert to Text and the exports write the numbers shown. Type › Bullets and Numbering › Convert to Text (`type.convertListToText`, `text.convertListToText`) makes the bullets and numbers of the list paragraphs editable characters of their text ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [December 2022 release notes](https://web.archive.org/web/20260203094741/https://helpx.adobe.com/illustrator/using/whats-new/2023-1.html)): each marker becomes its characters and a tab at the start of its paragraph, in the marker's font, size and color, the list is turned off, and a left tab stop at the left indent keeps the text after the tab where it started; threaded type keeps the numbers its story counted. While no type is being edited, a press with Shift held makes new type with the horizontal or vertical counterpart of the Type, Area Type or Type on a Path tool chosen, and a press with Alt (Option) held makes it with Type on a Path in place of Area Type or the reverse, in the chosen tool's writing direction; with both keys held, both switch ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). The pointer shows the tool the press acts as, and the tool chosen stays selected. The Type tool starts a list from the characters [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html) names (`text.startList`): a space typed on its own after `1.`, `1)`, `A.` or `A)` at the start of a paragraph in no list makes the paragraph a numbered list in 1, 2, 3 or A, B, C, and a space typed after `*`, `+`, `#` or `>` makes it a bulleted list with the filled dot, the hollow circle, the filled square or the dash (a VectorCraft choice: the page does not say which bullet each character gives). The typed characters are removed, and one Undo puts them back as text with no list. The same characters later in a paragraph, and pasted list characters, start nothing.