From db2fffa9be7be607e46549c7fe08d21087651010 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 17:19:15 +0200 Subject: [PATCH 01/25] Print: Print Selection in File > Print > Settings, several selected areas print one after the other (fixes #2351) --- ROADMAP.md | 3 +- crates/engine/src/cmd/print.rs | 58 +++++++++++++----- crates/ui-egui/src/backstage.rs | 52 +++++++++++++---- crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/el.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 7 ++- crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/nl.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt.rs | 1 + crates/ui-egui/src/i18n/ro.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/sr.rs | 1 + crates/ui-egui/src/i18n/tr.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + crates/ui-egui/src/i18n/vi.rs | 1 + crates/ui-egui/src/i18n/zh.rs | 1 + crates/ui-egui/tests/print_selection.rs | 78 +++++++++++++++++++++++++ docs/gaps.md | 5 +- docs/ui-parity.md | 5 +- 24 files changed, 192 insertions(+), 33 deletions(-) create mode 100644 crates/ui-egui/tests/print_selection.rs diff --git a/ROADMAP.md b/ROADMAP.md index 1faf680ca3..873b1ee095 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-22 · **Change:** trivial (progress log: formula hardening, #2163/#2162; previously minor: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (File › Print › Settings: Print Selection; previously: progress log: formula hardening, #2163/#2162; previously minor: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel | | 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) | | 2026-10-21 | Page Setup paper sizes match Japanese Excel: `B4`/`B5`/`B6` are the JIS sizes (ISO B4/B5/B6 stay reachable by name), so a Japanese B5 worksheet prints at 182×257 mm; Japanese Postcard (100×148 mm), Double Postcard (148×200 mm), Envelope #3/#4 (120×235/90×205 mm), Kaku #2/#3 (240×332/216×277 mm) and A6 are added, both sizes reach the PDF page (`file.exportPdf`/`file.print` MediaBox) and the size survives an XLSX round-trip; the Page Layout Size menu lists them. `B4`/`B5` used to be the ISO sizes, which is changed here | | 2026-10-20 | Japanese interface catalog covers every key the Brazilian Portuguese catalog translates: the 398-label shared core plus 545 dialog, message, Backstage and menu strings (943 total, ~43% of ~2,200). A test parses `pt.rs`'s source, so the two catalogs stay in step | diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 4c80f2fa90..a871937949 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Export as PDF", ["File", "Export"], None, - "{path?, sheets?: active|all, range?: \"A1:F40\" (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.", + "{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.", has_doc, export_pdf ), @@ -145,7 +145,8 @@ impl SheetLayout { #[derive(Clone, Debug, Default)] pub struct PrintOptions { pub all_sheets: bool, - pub range: Option, + /// Areas of the active sheet to print instead of its print area, in order (Print Selection). + pub ranges: Vec, pub fit_to_page: Option, } @@ -156,11 +157,13 @@ impl PrintOptions { Some("all") | Some("workbook") => true, Some(other) => return Err(bad(cmd, format!("`sheets` must be active or all, not `{other}`"))), }; - let range = match str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { - Some(r) => Some(RangeRef::parse(split_sheet(r).1).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?), - None => None, - }; - Ok(PrintOptions { all_sheets, range, fit_to_page: bool_param(p, "fitToPage") }) + let mut ranges = Vec::new(); + if let Some(r) = str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { + for part in split_sheet(r).1.split(',') { + ranges.push(RangeRef::parse(part.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?); + } + } + Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") }) } } @@ -376,14 +379,20 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec { if pages >= MAX_PAGES { break; } - let ovr = if si == wb.active_sheet { opts.range } else { None }; - if opts.all_sheets && ovr.is_none() && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) { + let areas: Vec> = + if si == wb.active_sheet && !opts.ranges.is_empty() { opts.ranges.iter().copied().map(Some).collect() } else { vec![None] }; + if opts.all_sheets && areas == [None] && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) { continue; } - if let Some(mut l) = layout_sheet(wb, si, opts, ovr) { - l.pages.truncate(MAX_PAGES - pages); - pages += l.pages.len(); - out.push(l); + for ovr in areas { + if pages >= MAX_PAGES { + break; + } + if let Some(mut l) = layout_sheet(wb, si, opts, ovr) { + l.pages.truncate(MAX_PAGES - pages); + pages += l.pages.len(); + out.push(l); + } } } if out.is_empty() && opts.all_sheets { @@ -1859,6 +1868,29 @@ mod tests { assert!(!cropped.contains("/Dest [")); } + fn preview_ranges(s: &mut Session, p: Json) -> Vec { + let r = s.execute("file.printPreview", p).unwrap(); + r["pageList"].as_array().unwrap().iter().map(|pg| pg["range"].as_str().unwrap().to_string()).collect() + } + + #[test] + fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("cell.set", json!({"cell": "H20", "input": "y"})).unwrap(); + s.execute("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap(); + assert_eq!(preview_ranges(&mut s, json!({})), ["F10:H20"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]); + // Several areas, like a multi-area selection: one run of pages each, in the order given. + assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]); + let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"})); + assert_eq!(pages, 2); + for bad in ["A1:B2,", "A1:B2,nope", ","] { + assert!(s.execute("file.printPreview", json!({"range": bad})).is_err(), "{bad}"); + } + } + #[test] fn header_sections_split_join_and_field_names() { let spec = "&L&\"Arial,Bold\"Sales &&Co&CPage &P of &N&R&D"; diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index c2acf025bf..a2b68b360c 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -102,20 +102,41 @@ const PROPERTIES: [(&str, &str); 6] = [ ("description", "Description"), ]; +/// What File › Print › Settings prints. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PrintScope { + ActiveSheets, + EntireWorkbook, + /// The selected cells of the active sheet. + Selection, +} + +impl PrintScope { + const ALL: [PrintScope; 3] = [PrintScope::ActiveSheets, PrintScope::EntireWorkbook, PrintScope::Selection]; + + fn label(self) -> &'static str { + match self { + PrintScope::ActiveSheets => "Print Active Sheets", + PrintScope::EntireWorkbook => "Print Entire Workbook", + PrintScope::Selection => "Print Selection", + } + } +} + /// The open Backstage view. #[derive(Clone, Debug)] pub struct Backstage { pub page: Page, /// Info: property drafts while a field is being edited (committed when it loses focus). props: [String; 6], - /// Print: the whole workbook rather than the active sheet. - pub print_all: bool, + /// Print: what to print (the Settings menu's first choice). + pub print_scope: PrintScope, /// Print: fit each sheet on one page. pub fit_to_page: bool, /// Print: the previewed page (0-based). preview_page: usize, - /// Print: the preview for (document, revision, whole workbook, fit to page). - preview: Option<((u64, u64, bool, bool), Json)>, + /// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page). + preview: Option<((u64, u64, PrintScope, String, bool), Json)>, /// Save As: the chosen file type (an extension from [`SAVE_TYPES`]). pub save_format: &'static str, /// Home and Open: when the recent workbooks were last changed. @@ -132,7 +153,7 @@ impl Backstage { Backstage { page, props: Default::default(), - print_all: false, + print_scope: PrintScope::ActiveSheets, fit_to_page: false, preview_page: 0, preview: None, @@ -703,11 +724,19 @@ fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) dim(ui, lang.tr("No workbook is open.")); return; }; - let mut params = json!({"sheets": if bs.print_all { "all" } else { "active" }}); + let mut params = json!({"sheets": if bs.print_scope == PrintScope::EntireWorkbook { "all" } else { "active" }}); + // The selection is not part of the document revision, so it goes in the preview's key. + let mut selection = String::new(); + if bs.print_scope == PrintScope::Selection + && let Some(d) = app.session.active() + { + selection = d.selection.a1(); + params["range"] = json!(selection); + } if bs.fit_to_page { params["fitToPage"] = json!(true); } - let key = (uid, revision, bs.print_all, bs.fit_to_page); + let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page); if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) { let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null); bs.preview = Some((key, preview)); @@ -727,11 +756,10 @@ fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) out.close = app.services.print_native.is_none(); } ui.add_space(16.0); - let scope = if bs.print_all { "Print Entire Workbook" } else { "Print Active Sheets" }; - egui::ComboBox::from_id_salt("backstage_print_scope").width(230.0).selected_text(lang.tr(scope)).show_ui(ui, |ui| { - for (all, label) in [(false, "Print Active Sheets"), (true, "Print Entire Workbook")] { - if ui.selectable_label(bs.print_all == all, lang.tr(label)).clicked() { - bs.print_all = all; + egui::ComboBox::from_id_salt("backstage_print_scope").width(230.0).selected_text(lang.tr(bs.print_scope.label())).show_ui(ui, |ui| { + for scope in PrintScope::ALL { + if ui.selectable_label(bs.print_scope == scope, lang.tr(scope.label())).clicked() { + bs.print_scope = scope; bs.preview_page = 0; } } diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index fc9181feb1..db89a29e6f 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -308,6 +308,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Uloží sešit pod jiným názvem nebo do jiné složky.", "Print Active Sheets" => "Vytisknout aktivní listy", "Print Entire Workbook" => "Vytisknout celý sešit", + "Print Selection" => "Vytisknout výběr", "Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku", "Page Setup…" => "Vzhled stránky…", "Page {page} of {pages}" => "Stránka {page} z {pages}", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 61c2292f49..cc31a117e4 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -313,6 +313,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { } "Print Active Sheets" => "Aktive Blätter drucken", "Print Entire Workbook" => "Gesamte Arbeitsmappe drucken", + "Print Selection" => "Auswahl drucken", "Fit Sheet on One Page" => "Blatt auf einer Seite darstellen", "Page Setup…" => "Seite einrichten…", "Page {page} of {pages}" => "Seite {page} von {pages}", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index e54416a6fd..287072b55b 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -284,6 +284,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Αποθηκεύστε το βιβλίο εργασίας με άλλο όνομα ή σε άλλον φάκελο.", "Print Active Sheets" => "Εκτύπωση ενεργών φύλλων", "Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας", + "Print Selection" => "Εκτύπωση επιλογής", "Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα", "Page Setup…" => "Διαμόρφωση σελίδας…", "Page {page} of {pages}" => "Σελίδα {page} από {pages}", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 36898c0985..e19a1ab16c 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -310,6 +310,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Guarda el libro con otro nombre o en otra carpeta.", "Print Active Sheets" => "Imprimir hojas activas", "Print Entire Workbook" => "Imprimir todo el libro", + "Print Selection" => "Imprimir selección", "Fit Sheet on One Page" => "Ajustar hoja en una página", "Page Setup…" => "Configurar página…", "Page {page} of {pages}" => "Página {page} de {pages}", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 317647c2f5..595b58bd52 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -395,6 +395,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Enregistrer le classeur sous un autre nom ou dans un autre dossier.", "Print Active Sheets" => "Imprimer les feuilles actives", "Print Entire Workbook" => "Imprimer tout le classeur", + "Print Selection" => "Imprimer la sélection", "Fit Sheet on One Page" => "Ajuster la feuille sur une page", "Page Setup…" => "Mise en page…", "Page {page} of {pages}" => "Page {page} sur {pages}", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 65f356669e..e6f3a3120f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -384,6 +384,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salva la cartella di lavoro con un altro nome o in un'altra cartella.", "Print Active Sheets" => "Stampa fogli attivi", "Print Entire Workbook" => "Stampa intera cartella di lavoro", + "Print Selection" => "Stampa selezione", "Fit Sheet on One Page" => "Adatta foglio a una pagina", "Page Setup…" => "Imposta pagina…", "Page {page} of {pages}" => "Pagina {page} di {pages}", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 482852d8d7..a75093de9c 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -391,6 +391,7 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Save the workbook under another name or in another folder.", "ブックを別の名前または別のフォルダーに保存します。"), ("Print Active Sheets", "作業中のシートを印刷"), ("Print Entire Workbook", "ブック全体を印刷"), + ("Print Selection", "選択した部分を印刷"), ("Fit Sheet on One Page", "シートを 1 ページに印刷"), ("Page Setup…", "ページ設定…"), ("Page {page} of {pages}", "{page} / {pages} ページ"), @@ -1236,9 +1237,9 @@ mod tests { assert!(seen.insert(*english), "duplicate key across CORE and DIALOGS: {english:?}"); } assert_eq!(seen.len(), catalog_keys().count()); - assert_eq!(CORE.len(), 392, "the shared reference set every catalog covers"); + assert_eq!(CORE.len(), 393, "the shared reference set every catalog covers"); assert_eq!(DIALOGS.len(), 562, "the dialog, message and menu strings beyond it"); - assert_eq!(catalog_keys().count(), 954); + assert_eq!(catalog_keys().count(), 955); } #[test] @@ -1256,7 +1257,7 @@ mod tests { #[test] fn covers_every_key_the_portuguese_catalog_translates() { let portuguese = portuguese_keys(); - assert_eq!(portuguese.len(), 954, "pt.rs's arms changed: add the new keys here and update the count"); + assert_eq!(portuguese.len(), 955, "pt.rs's arms changed: add the new keys here and update the count"); let japanese: HashSet<&str> = catalog_keys().collect(); for key in &portuguese { assert!(japanese.contains(key.as_str()), "the Portuguese catalog translates {key:?}, the Japanese one does not"); diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d3c440cf30..31f73b7d66 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -397,6 +397,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "통합 문서를 다른 이름 또는 다른 폴더에 저장합니다.", "Print Active Sheets" => "활성 시트 인쇄", "Print Entire Workbook" => "전체 통합 문서 인쇄", + "Print Selection" => "선택 영역 인쇄", "Fit Sheet on One Page" => "한 페이지에 시트 맞추기", "Page Setup…" => "페이지 설정…", "Page {page} of {pages}" => "{page}/{pages} 페이지", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index c1f952357f..8e568fc871 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -383,6 +383,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "De werkmap onder een andere naam of in een andere map opslaan.", "Print Active Sheets" => "Actieve bladen afdrukken", "Print Entire Workbook" => "Hele werkmap afdrukken", + "Print Selection" => "Selectie afdrukken", "Fit Sheet on One Page" => "Blad op één pagina passen", "Page Setup…" => "Pagina-instelling…", "Page {page} of {pages}" => "Pagina {page} van {pages}", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index e3185d55ae..231424cc0b 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -378,6 +378,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Zapisz skoroszyt pod inną nazwą lub w innym folderze.", "Print Active Sheets" => "Drukuj aktywne arkusze", "Print Entire Workbook" => "Drukuj cały skoroszyt", + "Print Selection" => "Drukuj zaznaczenie", "Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony", "Page Setup…" => "Ustawienia strony…", "Page {page} of {pages}" => "Strona {page} z {pages}", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 1b56ff5046..c984853f01 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -390,6 +390,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salve a pasta de trabalho com outro nome ou em outra pasta.", "Print Active Sheets" => "Imprimir planilhas ativas", "Print Entire Workbook" => "Imprimir toda a pasta de trabalho", + "Print Selection" => "Imprimir seleção", "Fit Sheet on One Page" => "Ajustar planilha em uma página", "Page Setup…" => "Configurar página…", "Page {page} of {pages}" => "Página {page} de {pages}", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 9e0d92516f..4fca840ed6 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -385,6 +385,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salvează registrul cu alt nume sau în alt folder.", "Print Active Sheets" => "Imprimare foi active", "Print Entire Workbook" => "Imprimare tot registrul", + "Print Selection" => "Imprimare selecție", "Fit Sheet on One Page" => "Încadrare foaie pe o pagină", "Page Setup…" => "Configurare pagină…", "Page {page} of {pages}" => "Pagina {page} din {pages}", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index ce675701ea..776292b413 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -397,6 +397,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Сохранить книгу под другим именем или в другой папке.", "Print Active Sheets" => "Напечатать активные листы", "Print Entire Workbook" => "Напечатать всю книгу", + "Print Selection" => "Напечатать выделенный диапазон", "Fit Sheet on One Page" => "Вписать лист на одну страницу", "Page Setup…" => "Параметры страницы…", "Page {page} of {pages}" => "Страница {page} из {pages}", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index c71ce53a87..0aa3311a2b 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -389,6 +389,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Sačuvaj radnu svesku pod drugim imenom ili u drugoj fascikli.", "Print Active Sheets" => "Štampaj aktivne listove", "Print Entire Workbook" => "Štampaj celu radnu svesku", + "Print Selection" => "Štampaj izbor", "Fit Sheet on One Page" => "Uklopi list na jednu stranicu", "Page Setup…" => "Podešavanje stranice…", "Page {page} of {pages}" => "Stranica {page} od {pages}", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index ce2bc8e1ec..0cdc8347ee 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -299,6 +299,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Çalışma kitabını başka bir adla veya başka bir klasöre kaydedin.", "Print Active Sheets" => "Etkin Sayfaları Yazdır", "Print Entire Workbook" => "Tüm Çalışma Kitabını Yazdır", + "Print Selection" => "Seçimi Yazdır", "Fit Sheet on One Page" => "Sayfayı Bir Sayfaya Sığdır", "Page Setup…" => "Sayfa Yapısı…", "Page {page} of {pages}" => "Sayfa {page} / {pages}", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 97659cc121..22ab200cc1 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -383,6 +383,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Зберегти книгу під іншим іменем або в іншій теці.", "Print Active Sheets" => "Надрукувати активні аркуші", "Print Entire Workbook" => "Надрукувати всю книгу", + "Print Selection" => "Надрукувати виділений діапазон", "Fit Sheet on One Page" => "Вмістити аркуш на одну сторінку", "Page Setup…" => "Параметри сторінки…", "Page {page} of {pages}" => "Сторінка {page} з {pages}", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 94c32b3a54..4b83941871 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -388,6 +388,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Lưu sổ làm việc với tên khác hoặc vào thư mục khác.", "Print Active Sheets" => "In các trang tính hiện hoạt", "Print Entire Workbook" => "In toàn bộ sổ làm việc", + "Print Selection" => "In vùng chọn", "Fit Sheet on One Page" => "Vừa trang tính trên một trang", "Page Setup…" => "Thiết lập trang…", "Page {page} of {pages}" => "Trang {page} / {pages}", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index c9d3ecb7d3..f4016724c9 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -389,6 +389,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "以其他名称或在其他文件夹中保存工作簿。", "Print Active Sheets" => "打印活动工作表", "Print Entire Workbook" => "打印整个工作簿", + "Print Selection" => "打印选定区域", "Fit Sheet on One Page" => "将工作表调整为一页", "Page Setup…" => "页面设置…", "Page {page} of {pages}" => "第 {page} 页,共 {pages} 页", diff --git a/crates/ui-egui/tests/print_selection.rs b/crates/ui-egui/tests/print_selection.rs new file mode 100644 index 0000000000..f715ea043f --- /dev/null +++ b/crates/ui-egui/tests/print_selection.rs @@ -0,0 +1,78 @@ +//! File › Print › Settings offers "Print Selection": only the selected cells are previewed and sent. +use std::{cell::RefCell, rc::Rc}; + +use egui_kittest::kittest::Queryable as _; +use gridcraft_engine::Session; +use gridcraft_ui_egui::{Services, SheetApp}; +use serde_json::json; + +fn contains(hay: &[u8], needle: &str) -> bool { + hay.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +/// A sheet whose print area (F10:H20, "Outside") is not where the selection (A1:B2, "Inside") is, +/// so printing the selection and printing the sheet give different pages. +fn harness(jobs: Rc>>>) -> egui_kittest::Harness<'static, SheetApp> { + let mut session = Session::new(); + session.new_workbook(); + let mut app = SheetApp::new(session, Services::default()); + app.run("cell.set", json!({"cell": "A1", "input": "Inside"})).unwrap(); + app.run("cell.set", json!({"cell": "D4", "input": "Second area"})).unwrap(); + app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap(); + app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap(); + app.run("selection.set", json!({"range": "A1:B2"})).unwrap(); + app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec()))); + app.run("ui.backstage", json!({"page": "print"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn choose_selection(h: &mut egui_kittest::Harness<'static, SheetApp>) { + h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("print scope combo").click(); + h.run_steps(3); + h.get_by_label("Print Selection").click(); + h.run_steps(4); +} + +#[test] +fn print_selection_previews_and_prints_only_the_selected_cells() { + let jobs = Rc::new(RefCell::new(Vec::new())); + let mut h = harness(jobs.clone()); + assert!(h.query_by_label("Sheet1 · F10:H20").is_some(), "the sheet prints its print area by default"); + choose_selection(&mut h); + assert!(h.query_by_label("Sheet1 · A1:B2").is_some(), "the preview shows the selection"); + assert!(h.query_by_label("Sheet1 · F10:H20").is_none()); + + h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click(); + h.run_steps(3); + let jobs = jobs.borrow(); + assert_eq!(jobs.len(), 1); + assert!(contains(&jobs[0], "(Inside) Tj"), "the selected cell is printed"); + assert!(!contains(&jobs[0], "(Outside) Tj"), "the print area is not"); +} + +#[test] +fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() { + let jobs = Rc::new(RefCell::new(Vec::new())); + let mut h = harness(jobs.clone()); + choose_selection(&mut h); + assert!(h.query_by_label("Sheet1 · A1:B2").is_some()); + + // Same document revision, other selection: the cached preview must not be reused. + h.state_mut().run("selection.set", json!({"range": "D4:E5"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label("Sheet1 · D4:E5").is_some(), "the preview is rebuilt for the new selection"); + assert!(h.query_by_label("Sheet1 · A1:B2").is_none()); + + // Two selected areas: Excel prints each area on its own page. + h.state_mut().run("selection.set", json!({"range": "A1:B2,D4:E5"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages"); +} diff --git a/docs/gaps.md b/docs/gaps.md index 7e2e40dc06..7a58a64f2e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (the Japanese catalog covers the dialogs, messages and menus) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (File › Print › Settings: Print Selection; previously: the Japanese catalog covers the dialogs, messages and menus) · **Target:** Microsoft Excel (Microsoft 365) Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open @@ -127,7 +127,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- ### 14. Page Layout view and print polish (U, F) - Page Layout view landed (#329): paper view with rulers and in-place header/footer editing. - Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print ranges and driver tray/options UI remain. **Estimate:** 5–10 h. + Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Driver tray/options UI remains. **Estimate:** 5–10 h. ### 15. Remaining functions and an oracle suite (F) - 18 missing, 9 stubs; no Excel-computed oracle corpus; #137, #138. **Estimate:** 16–26 h. @@ -178,6 +178,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | §14: Print Selection landed in File › Print › Settings (several selected areas print one after the other); "print ranges" removed from the remainder | | 2026-10-20 | minor | §11: the Japanese catalog covers the dialogs, messages and menus — 943 keys (~43%), matching the pt-BR coverage; a test keeps the two catalogs in step | | 2026-10-17 | minor | §6: the five reports it tracked are closed and their PRs merged (#57, #133, #139, #140, #134; PRs #148, #155, #156, #157); the entry stays open for §15's oracle suite | | 2026-10-15 | minor | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c7cbc349ee..c88ec82930 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (File › Print › Settings: Print Selection; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -30,7 +30,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Task panes (Format Chart, Comments, Watch, Selection, PivotTable fields) | yes | yes; PivotTable source-field list scrollbar sits at the right edge of its pane | element-level Format pane for shapes and pictures missing | | Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | partial | Options dialog and template gallery missing | | Dark mode, system appearance | yes | yes | done (10-09); follows the system on first run, title-bar switch and File › Display theme (#194, #239) | -| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet or workbook, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has | +| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet, workbook or selection, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has | | Dark mode, system appearance | yes | yes | done (10-09) | | Page Layout view (paper view with rulers and header editing) | yes | yes (#329, 10-11): per-sheet view saved in XLSX, pages with margins and gaps on the print pagination, "Click to add data" pages, rulers (inches or centimetres), headers and footers drawn and edited in place with a Header & Footer tab | margins drag on the rulers (#792, with header and footer margins); header/footer pictures, Different First Page / Odd & Even missing (1–3 h) | | Multiple windows per workbook | yes | no (#162) | see [hardware-parity.md](hardware-parity.md) | @@ -175,6 +175,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook: the preview and the printed PDF cover the selected cells, and a selection of several areas prints each area on its own pages, as in Excel (`file.print`, `file.exportPdf` and `file.printPreview` accept `range: "A1:B5,D1:E5"`). A single selected cell prints that cell | | 2026-10-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | | 2026-10-22 | minor | Show Outline Symbols (`view.showOutlineSymbols`, Ctrl+8): a sheet can hide the outline's level buttons and brackets while keeping its outline, as Excel saves with `showOutlineSymbols="0"` (read and written); the grid then gives the bands no room | From df2b24dbfdc52ef8d18c793590b8a423ae43c920 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 19:12:21 +0200 Subject: [PATCH 02/25] Print Selection: split a multi-area range at its commas before dropping each Sheet! qualifier, so earlier unqualified areas are kept --- crates/engine/src/cmd/print.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index a871937949..a315e1f8c9 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -159,14 +159,33 @@ impl PrintOptions { }; let mut ranges = Vec::new(); if let Some(r) = str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { - for part in split_sheet(r).1.split(',') { - ranges.push(RangeRef::parse(part.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?); + for part in split_areas(r) { + ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?); } } Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") }) } } +/// Splits a multi-area reference at the commas outside quoted sheet names, so each area keeps +/// its own optional `Sheet!` prefix. +fn split_areas(r: &str) -> Vec<&str> { + let mut parts = Vec::new(); + let (mut start, mut quoted) = (0, false); + for (i, c) in r.char_indices() { + match c { + '\'' => quoted = !quoted, + ',' if !quoted => { + parts.push(&r[start..i]); + start = i + 1; + } + _ => {} + } + } + parts.push(&r[start..]); + parts +} + /// The range a sheet prints: its print area, else the used range grown to cover drawing /// objects. `None` when there is nothing to print. pub fn print_range(sh: &Sheet) -> Option { @@ -1891,6 +1910,15 @@ mod tests { } } + #[test] + fn a_sheet_qualifier_on_a_later_area_does_not_swallow_the_earlier_ones() { + let mut s = s(); + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]); + // A comma inside a quoted sheet name is not an area separator. + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,'a,b'!D4:E5"})), ["A1:B2", "D4:E5"]); + } + #[test] fn header_sections_split_join_and_field_names() { let spec = "&L&\"Arial,Bold\"Sales &&Co&CPage &P of &N&R&D"; From 15661dc97305b0acc265c74f915c3a336a3dca6e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:13:15 -0500 Subject: [PATCH 03/25] Cap text at 32,767 characters like Excel: & and CONCATENATE cut, CONCAT and TEXTJOIN give #CALC!, cell.set and CSV fields cut (#2635) --- ROADMAP.md | 1 + crates/calc/src/eval.rs | 8 +------ crates/calc/src/tests.rs | 10 ++++++++ crates/core/src/lib.rs | 2 +- crates/core/src/value.rs | 13 ++++++++++ crates/engine/src/cmd/edit.rs | 19 +++++++++++++++ crates/functions/src/text.rs | 38 ++++++++++++++++++++++-------- crates/xlsx/src/csv.rs | 4 ++-- crates/xlsx/src/tests/csv_tests.rs | 10 ++++++++ 9 files changed, 85 insertions(+), 20 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6b9b0fce78..faf1bf55a7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-26 | Text past 32,767 characters behaves like Excel (#2635): `&` and CONCATENATE cut their result there, CONCAT and TEXTJOIN give `#CALC!`, and a typed or CSV-read cell is cut, so GridCraft never writes a cell Excel refuses to open | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 4bdb3a30d4..4ba0bf515e 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -1872,13 +1872,7 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste } }), BinOp::Concat => match (a.to_text(), b.to_text()) { - (Ok(x), Ok(y)) => { - if x.len() + y.len() > 32767 * 4 { - Value::Error(CellError::Value) - } else { - Value::text(x + &y) - } - } + (Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)), (Err(e), _) | (_, Err(e)) => Value::Error(e), }, BinOp::Eq => Value::Bool(compare(a, b) == Equal), diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e900854..f2a2490567 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2274,3 +2274,13 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +#[test] +fn concat_operator_cuts_at_the_cell_limit() { + // Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767. + let mut t = T::new(); + t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))"); + t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")"); + t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))"); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3")), (32767.0, 32767.0, 32767.0)); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 96f485cd93..574f78243c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,4 +14,4 @@ pub use addr::{ split_sheet, unquote_sheet, }; pub use date::DateSystem; -pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare}; +pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, compare, compare_numbers, compare_text, number_to_text, sort_compare}; diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index c531de4dc1..b5b820562d 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -462,3 +462,16 @@ mod tests { assert_eq!(row.get_broadcast(5, 1), Value::Number(2.0)); } } + +/// Longest text a cell can hold, in characters. +pub const MAX_TEXT_CHARS: usize = 32_767; + +/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. +pub fn cap_text(mut s: String) -> String { + if s.len() > MAX_TEXT_CHARS + && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) + { + s.truncate(i); + } + s +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 28ce338d6c..c7fa94dcf8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -123,6 +123,13 @@ pub fn specs() -> Vec { /// format, before parsing. Errors when the formula can't be parsed. pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result> { let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); + let capped; + let mut input = input; + if input.len() > gridcraft_core::MAX_TEXT_CHARS && !input.starts_with('=') { + // Excel cuts typed text to 32,767 characters. + capped = gridcraft_core::cap_text(input.to_string()); + input = &capped; + } if input.is_empty() { let c = Cell { value: Value::Empty, formula: None, style }; return Ok(if c.is_blank() { None } else { Some(c) }); @@ -2039,6 +2046,18 @@ mod tests { assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}"); } + #[test] + fn cell_set_cuts_text_to_32767_characters() { + // Excel cuts a 40,000-character entry to 32,767; a formula is left alone. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone(); + assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767)); + assert_eq!(get(&mut s, "A2"), json!(32767.0)); + } + #[test] fn cell_set_takes_numbers_for_input_and_value() { // #697: a JSON number for `input` used to clear the cell instead of entering it. diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index df125f022f..82b2654ca7 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -27,30 +27,41 @@ fn check_len(s: String) -> R { } /// Pushes `piece` onto `out`, failing once the result exceeds the cell limit. -fn push_capped(out: &mut String, piece: &str) -> R<()> { +fn push_capped(out: &mut String, piece: &str, over: CellError) -> R<()> { out.push_str(piece); if out.len() > MAX_TEXT * 4 { - return Err(CellError::Value); + return Err(over); } Ok(()) } +/// CONCATENATE cuts at the cell limit like `&`; CONCAT and TEXTJOIN give `#CALC!` past it. fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { - push_capped(&mut out, &scalar(x).to_text()?)?; + out.push_str(&scalar(x).to_text()?); + if out.len() > MAX_TEXT * 4 { + break; + } } - check_len(out) + text_val(gridcraft_core::cap_text(out)) +} + +fn check_calc(s: String) -> R { + if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT { + return Err(CellError::Calc); + } + text_val(s) } fn concat(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { for v in as_array(&x.value).iter() { - push_capped(&mut out, &v.to_text()?)?; + push_capped(&mut out, &v.to_text()?, CellError::Calc)?; } } - check_len(out) + check_calc(out) } fn textjoin(a: &[Arg], _c: &mut dyn Ctx) -> R { @@ -69,11 +80,11 @@ fn textjoin(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for (i, s) in items.iter().enumerate() { if i > 0 && !delims.is_empty() { - push_capped(&mut out, &delims[(i - 1) % delims.len()])?; + push_capped(&mut out, &delims[(i - 1) % delims.len()], CellError::Calc)?; } - push_capped(&mut out, s)?; + push_capped(&mut out, s, CellError::Calc)?; } - check_len(out) + check_calc(out) } fn count_arg(a: &[Arg], i: usize, default: f64) -> R { @@ -680,7 +691,7 @@ fn arraytotext(a: &[Arg], _c: &mut dyn Ctx) -> R { } else if c > 0 { out.push_str(if strict { "," } else { ", " }); } - push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict))?; + push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict), CellError::Value)?; } } if strict { @@ -1094,6 +1105,13 @@ mod tests { is_text(ev("TEXTJOIN", vec![t("-"), b(false), av(arr(vec![vec![tv("a"), tv(""), tv("b")]]))]), "a--b"); is_text(ev("TEXTJOIN", vec![av(row_t(&[",", ";"])), b(true), t("a"), t("b"), t("c")]), "a,b;c"); is_err(ev("CONCAT", vec![t("a"), e(CellError::NA)]), CellError::NA); + // Past 32,767 characters: CONCAT and TEXTJOIN are #CALC!, CONCATENATE cuts like `&` + // (checked in Excel: LEN(...) is #CALC!, #CALC! and 32767). + let x = || t(&"x".repeat(20_000)); + is_err(ev("CONCAT", vec![x(), x()]), CellError::Calc); + is_err(ev("TEXTJOIN", vec![t(","), b(false), x(), x()]), CellError::Calc); + assert_eq!(ev("CONCATENATE", vec![x(), x()]), Value::text("x".repeat(32_767))); + assert_eq!(ev("CONCAT", vec![x()]), Value::text("x".repeat(20_000))); // Lifting: CONCATENATE over an array. assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]); } diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index dfc694ea61..10d48024d1 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -276,7 +276,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { } let pos = CellRef::new(row, col as u32); let cell = if opts.parse_values { - let p = parse_input(&f, opts.date_system); + let p = parse_input(&gridcraft_core::cap_text(f), opts.date_system); let style = match p.format { Some(code) => match fmt_cache.iter().find(|(c, _)| *c == code) { Some((_, id)) => *id, @@ -290,7 +290,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { }; Cell { value: p.value, formula: None, style } } else { - Cell::value(Value::Text(Arc::from(f))) + Cell::value(Value::Text(Arc::from(gridcraft_core::cap_text(f)))) }; sheet.cells.set(pos, cell); } diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 066f507e07..2a1974588b 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -326,3 +326,13 @@ fn parser_stops_collecting_fields_at_max_cols() { }); assert_eq!(lens, vec![MAX_COLS as usize]); } + +#[test] +fn a_field_over_32767_characters_is_cut() { + let src = format!("{},{}", "x".repeat(40_000), "y".repeat(32_768)); + for parse_values in [true, false] { + let wb = read_csv(src.as_bytes(), &CsvOptions { parse_values, ..Default::default() }).unwrap(); + assert_eq!(v(&wb, 0, 0), Value::text("x".repeat(32_767))); + assert_eq!(v(&wb, 0, 1), Value::text("y".repeat(32_767))); + } +} From 0ddd8684efaeae2142f28e875d6b3342bfa370d1 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:24:42 -0500 Subject: [PATCH 04/25] Move cap_text above the test module --- crates/core/src/value.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index b5b820562d..66db292096 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -389,6 +389,19 @@ pub fn sci_text(n: f64, sig: usize) -> String { format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) } +/// Longest text a cell can hold, in characters. +pub const MAX_TEXT_CHARS: usize = 32_767; + +/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. +pub fn cap_text(mut s: String) -> String { + if s.len() > MAX_TEXT_CHARS + && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) + { + s.truncate(i); + } + s +} + #[cfg(test)] mod tests { use super::*; @@ -462,16 +475,3 @@ mod tests { assert_eq!(row.get_broadcast(5, 1), Value::Number(2.0)); } } - -/// Longest text a cell can hold, in characters. -pub const MAX_TEXT_CHARS: usize = 32_767; - -/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. -pub fn cap_text(mut s: String) -> String { - if s.len() > MAX_TEXT_CHARS - && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) - { - s.truncate(i); - } - s -} From 571bdf68adb16366b183338b0bc461f2fb2044ef Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:30:59 -0500 Subject: [PATCH 05/25] Keep the clipboard budget test within the cell limit --- crates/engine/src/tests.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13fbb9b3a4..077c787f4d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -675,11 +675,13 @@ fn rich_clipboard_omits_html_for_large_ranges_without_truncating_text() { #[test] fn rich_clipboard_omits_html_when_escaping_exceeds_byte_budget() { let mut s = s(); - let text = "&".repeat(1_000_000); - s.execute("range.setValues", json!({"range": "A1", "values": [[text]]})).unwrap(); - let copied = s.execute("edit.copy", json!({"range": "A1", "html": true})).unwrap(); + // Cells hold at most 32,767 characters, so 30 full cells of `&` (5 bytes each once escaped) + // pass the 4 MiB HTML budget while the plain text stays far below it. + let cell = "&".repeat(32_767); + s.execute("range.setValues", json!({"range": "A1", "values": [vec![cell; 30]]})).unwrap(); + let copied = s.execute("edit.copy", json!({"range": "A1:AD1", "html": true})).unwrap(); assert!(copied.get("html").is_none(), "an oversized escaped value must not produce partial HTML"); - assert_eq!(copied["text"].as_str().unwrap().len(), 1_000_001); + assert_eq!(copied["text"].as_str().unwrap().len(), 30 * 32_767 + 30); assert!(copied["text"].as_str().unwrap().ends_with("&\n")); } From 7155ced916be2860361fb6cad498c6ac2518c509 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:42:21 -0500 Subject: [PATCH 06/25] Cap text after parsing the apostrophe prefix and in text-formatted cells; keep CONCATENATE errors past the cap --- crates/core/src/lib.rs | 2 +- crates/core/src/value.rs | 8 ++++++++ crates/engine/src/cmd/edit.rs | 18 ++++++++++-------- crates/functions/src/text.rs | 10 +++++++--- crates/xlsx/src/csv.rs | 4 ++-- crates/xlsx/src/tests/csv_tests.rs | 5 ++++- 6 files changed, 32 insertions(+), 15 deletions(-) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 574f78243c..bf5d3fd3f5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,4 +14,4 @@ pub use addr::{ split_sheet, unquote_sheet, }; pub use date::DateSystem; -pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, compare, compare_numbers, compare_text, number_to_text, sort_compare}; +pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare}; diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index 66db292096..634b577468 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -402,6 +402,14 @@ pub fn cap_text(mut s: String) -> String { s } +/// `v` with text cut to [`MAX_TEXT_CHARS`] characters; other values pass through. +pub fn cap_value(v: Value) -> Value { + match v { + Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())), + v => v, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c7fa94dcf8..7ae7ab494a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -123,20 +123,13 @@ pub fn specs() -> Vec { /// format, before parsing. Errors when the formula can't be parsed. pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result> { let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); - let capped; - let mut input = input; - if input.len() > gridcraft_core::MAX_TEXT_CHARS && !input.starts_with('=') { - // Excel cuts typed text to 32,767 characters. - capped = gridcraft_core::cap_text(input.to_string()); - input = &capped; - } if input.is_empty() { let c = Cell { value: Value::Empty, formula: None, style }; return Ok(if c.is_blank() { None } else { Some(c) }); } let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@"; if fmt_is_text { - return Ok(Some(Cell { value: Value::text(input), formula: None, style })); + return Ok(Some(Cell { value: gridcraft_core::cap_value(Value::text(input)), formula: None, style })); } let is_formula = input.starts_with('=') || (input.len() > 1 @@ -173,6 +166,8 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri return Ok(Some(cell)); } let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system); + // Excel cuts typed text to 32,767 characters (after any leading apostrophe is dropped). + parsed.value = gridcraft_core::cap_value(parsed.value); // Like Excel's automatic percent entry: a bare number of 1 or more typed into a cell already // formatted as a percentage is a percent (3 -> 3%); smaller numbers are taken as fractions. if parsed.format.is_none() @@ -2053,7 +2048,14 @@ mod tests { s.new_workbook(); s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap(); s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap(); + // An apostrophe prefix isn't text, and a text-formatted cell takes `=` as text. + s.execute("cell.set", json!({"cell": "B1", "input": format!("'{}", "x".repeat(40_000))})).unwrap(); + s.execute("home.numberFormat", json!({"range": "C1", "code": "@"})).unwrap(); + s.execute("cell.set", json!({"cell": "C1", "input": format!("={}", "x".repeat(40_000))})).unwrap(); let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone(); + for at in ["B1", "C1"] { + assert_eq!(get(&mut s, at).as_str().map(|t| t.chars().count()), Some(32_767), "{at}"); + } assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767)); assert_eq!(get(&mut s, "A2"), json!(32767.0)); } diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index 82b2654ca7..38a760db90 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -39,9 +39,10 @@ fn push_capped(out: &mut String, piece: &str, over: CellError) -> R<()> { fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { - out.push_str(&scalar(x).to_text()?); - if out.len() > MAX_TEXT * 4 { - break; + // Past the budget, later arguments are still converted so their errors propagate. + let piece = scalar(x).to_text()?; + if out.len() <= MAX_TEXT * 4 { + out.push_str(&piece); } } text_val(gridcraft_core::cap_text(out)) @@ -1112,6 +1113,9 @@ mod tests { is_err(ev("TEXTJOIN", vec![t(","), b(false), x(), x()]), CellError::Calc); assert_eq!(ev("CONCATENATE", vec![x(), x()]), Value::text("x".repeat(32_767))); assert_eq!(ev("CONCAT", vec![x()]), Value::text("x".repeat(20_000))); + // An error after the cut still propagates. + let big = || t(&"x".repeat(32_767)); + is_err(ev("CONCATENATE", vec![big(), big(), big(), big(), big(), e(CellError::NA)]), CellError::NA); // Lifting: CONCATENATE over an array. assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]); } diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index 10d48024d1..f7ce010ca8 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -276,7 +276,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { } let pos = CellRef::new(row, col as u32); let cell = if opts.parse_values { - let p = parse_input(&gridcraft_core::cap_text(f), opts.date_system); + let p = parse_input(&f, opts.date_system); let style = match p.format { Some(code) => match fmt_cache.iter().find(|(c, _)| *c == code) { Some((_, id)) => *id, @@ -288,7 +288,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { }, None => StyleId::DEFAULT, }; - Cell { value: p.value, formula: None, style } + Cell { value: gridcraft_core::cap_value(p.value), formula: None, style } } else { Cell::value(Value::Text(Arc::from(gridcraft_core::cap_text(f)))) }; diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 2a1974588b..b840322087 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -329,10 +329,13 @@ fn parser_stops_collecting_fields_at_max_cols() { #[test] fn a_field_over_32767_characters_is_cut() { - let src = format!("{},{}", "x".repeat(40_000), "y".repeat(32_768)); + let src = format!("{},{},'{}", "x".repeat(40_000), "y".repeat(32_768), "z".repeat(40_000)); for parse_values in [true, false] { let wb = read_csv(src.as_bytes(), &CsvOptions { parse_values, ..Default::default() }).unwrap(); assert_eq!(v(&wb, 0, 0), Value::text("x".repeat(32_767))); assert_eq!(v(&wb, 0, 1), Value::text("y".repeat(32_767))); } + // The apostrophe is dropped before the cut when values are parsed. + let wb = read_csv(src.as_bytes(), &CsvOptions::default()).unwrap(); + assert_eq!(v(&wb, 0, 2), Value::text("z".repeat(32_767))); } From 2fbe96820c326d2a5fbd8eec7c97372a02d00420 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:07:19 -0500 Subject: [PATCH 07/25] Cap range.setValues text when parse is false --- crates/engine/src/cmd/edit.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 7ae7ab494a..32a154a7b4 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -342,7 +342,7 @@ fn range_set_values(s: &mut Session, p: &Json) -> Result { if text.contains('\n') && !cx.wb.styles.get(style).align.wrap { style = cx.wb.styles.derive(style, |s| s.align.wrap = true); } - Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style }) + Some(Cell { value: gridcraft_core::cap_value(Value::Text(text.as_str().into())), formula: None, style }) } _ => input_to_cell(&input, sheet, at, &mut cx.wb)?, }; @@ -2120,6 +2120,11 @@ mod tests { assert!(s.execute("range.setValues", json!({"range": "A8", "parse": 0, "values": [["x"]]})).is_err()); // A line break still turns on Wrap Text. s.execute("range.setValues", json!({"range": "A9", "parse": false, "values": [["one\ntwo"]]})).unwrap(); + // Text stored as given still stops at Excel's 32,767-character cell limit. + let long = "x".repeat(40_000); + s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap(); + let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count())); + assert_eq!(len.flatten(), Some(32_767)); assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo")); let d = s.doc().unwrap(); let sh = d.wb.active().unwrap(); From 1f3c7a3390c6b9cd05ab20f1f38e9562edac4aef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=E1=BB=91ng=20Huy=20S=C6=A1n?= Date: Mon, 2 Nov 2026 14:01:29 +0700 Subject: [PATCH 08/25] i18n(vi): expand Vietnamese catalog to full 1,170-entry parity --- crates/ui-egui/src/i18n/vi.rs | 993 ++++++++++++++++++++++++++++++---- docs/localization-parity.md | 4 +- 2 files changed, 880 insertions(+), 117 deletions(-) diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 6ab6a71c40..21c999b507 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -1,5 +1,6 @@ -//! Vietnamese translations for the interface strings in i18n.rs. Labels follow the wording -//! Vietnamese spreadsheet users know; anything absent falls back to English. +//! Vietnamese translations for the interface strings in i18n.rs. +//! Clean-room translations written from the plain meaning of the English labels in natural +//! Vietnamese spreadsheet and computing terminology; anything absent falls back to English. /// Returns the Vietnamese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { @@ -15,26 +16,27 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Insert Copied Cells…" => "Chèn ô đã sao chép…", "Insert Cut Cells" => "Chèn ô đã cắt", "Insert Paste" => "Chèn và dán", - "Cut" => "Cắt", - "Copy" => "Sao chép", - "Format Painter (double-click to keep it on)" => "Sao định dạng (bấm đúp để giữ)", - "Bold" => "Đậm", - "Italic" => "Nghiêng", + "Cut (⌘X)" => "Cắt (⌘X)", + "Copy (⌘C)" => "Sao chép (⌘C)", + "Format Painter (double-click to keep it on)" => "Sao chép định dạng (nhấp đúp để giữ bật)", + "Bold (⌘B)" => "In đậm (⌘B)", + "Italic (⌘I)" => "In nghiêng (⌘I)", + "Underline (⌘U)" => "Gạch chân (⌘U)", "Double Underline" => "Gạch chân đôi", "Strikethrough" => "Gạch ngang", "Underline" => "Gạch chân", "Increase Font Size" => "Tăng cỡ chữ", "Decrease Font Size" => "Giảm cỡ chữ", - "Wrap Text" => "Xuống dòng tự động", - "Merge & Center" => "Hợp nhất và căn giữa", - "Merge Cells" => "Hợp nhất ô", - "Merge Across" => "Hợp nhất theo hàng", - "Unmerge Cells" => "Bỏ hợp nhất ô", + "Wrap Text" => "Ngắt dòng tự động", + "Merge & Center" => "Gộp & Căn giữa", + "Merge Cells" => "Gộp ô", + "Merge Across" => "Gộp theo hàng", + "Unmerge Cells" => "Tách ô", "Fill Color" => "Màu tô", "Font Color" => "Màu chữ", - "Borders" => "Viền", + "Borders" => "Đường viền", "Top\nAlign" => "Căn\ntrên", - "Middle\nAlign" => "Căn\ngiữa dọc", + "Middle\nAlign" => "Căn\ngiữa", "Bottom\nAlign" => "Căn\ndưới", "Left" => "Trái", "Right" => "Phải", @@ -44,23 +46,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Decrease Indent" => "Giảm thụt lề", "Increase Indent" => "Tăng thụt lề", "Orientation" => "Hướng chữ", - "Page Layout|Orientation" => "Hướng giấy", + "Page Layout|Orientation" => "Hướng trang", "Angle Counterclockwise" => "Xoay ngược chiều kim đồng hồ", - "Angle Clockwise" => "Xoay theo chiều kim đồng hồ", - "Rotate Text Up" => "Xoay chữ lên", - "Rotate Text Down" => "Xoay chữ xuống", + "Angle Clockwise" => "Xoay xuôi chiều kim đồng hồ", + "Rotate Text Up" => "Xoay chữ hướng lên", + "Rotate Text Down" => "Xoay chữ hướng xuống", "Accounting Number Format" => "Định dạng số kế toán", "Percent Style" => "Kiểu phần trăm", - "Comma Style" => "Kiểu dấu phân cách", - "Increase Decimal" => "Tăng số thập phân", - "Decrease Decimal" => "Giảm số thập phân", - "More Accounting Formats…" => "Định dạng kế toán khác…", + "Comma Style" => "Kiểu dấu phân cách hàng nghìn", + "Increase Decimal" => "Tăng chữ số thập phân", + "Decrease Decimal" => "Giảm chữ số thập phân", + "More Accounting Formats…" => "Thêm định dạng kế toán…", "Conditional\nFormatting" => "Định dạng\ncó điều kiện", "Conditional Formatting" => "Định dạng có điều kiện", "Format\nas Table" => "Định dạng\nthành bảng", "Cell\nStyles" => "Kiểu\nô", "Format Cells…" => "Định dạng ô…", - "Format Cell Alignment…" => "Căn chỉnh ô…", + "Format Cell Alignment…" => "Định dạng căn chỉnh ô…", "Format\nPane" => "Ngăn\nđịnh dạng", "Format" => "Định dạng", "Insert" => "Chèn", @@ -72,22 +74,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Delete Sheet Rows" => "Xóa hàng trang tính", "Delete Sheet Columns" => "Xóa cột trang tính", "Row Height…" => "Chiều cao hàng…", - "AutoFit Row Height" => "Tự động khớp chiều cao hàng", + "AutoFit Row Height" => "Tự khớp chiều cao hàng", "Column Width…" => "Độ rộng cột…", - "AutoFit Column Width" => "Tự động khớp độ rộng cột", + "AutoFit Column Width" => "Tự khớp độ rộng cột", "Default Width…" => "Độ rộng mặc định…", "Hide Rows" => "Ẩn hàng", - "Unhide Rows" => "Bỏ ẩn hàng", + "Unhide Rows" => "Hiện hàng", "Hide Columns" => "Ẩn cột", - "Unhide Columns" => "Bỏ ẩn cột", + "Unhide Columns" => "Hiện cột", "Lock Cell" => "Khóa ô", "Clear" => "Xóa", "Clear All" => "Xóa tất cả", "Clear Formats" => "Xóa định dạng", "Clear Contents" => "Xóa nội dung", - "Clear Comments and Notes" => "Xóa chú thích và ghi chú", + "Clear Comments and Notes" => "Xóa nhận xét và ghi chú", "Clear Hyperlinks" => "Xóa siêu liên kết", - "AutoSum" => "Tự động tính tổng", + "AutoSum" => "Tổng tự động", + "AutoSum (⌘⇧T)" => "Tổng tự động (⌘⇧T)", "Flash\nFill" => "Điền\nnhanh", "Flash Fill" => "Điền nhanh", "Fill" => "Điền", @@ -97,19 +100,19 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Replace…" => "Thay thế…", "Go To…" => "Đi tới…", "Go To Special…" => "Đi tới đặc biệt…", - "PivotTable" => "PivotTable", + "PivotTable" => "Bảng tổng hợp", "Recommended\nCharts" => "Biểu đồ\nđề xuất", "Table" => "Bảng", - "Pictures" => "Ảnh", - "Shapes" => "Hình", + "Pictures" => "Hình ảnh", + "Shapes" => "Hình dạng", "Icons" => "Biểu tượng", "Text\nBox" => "Hộp\nvăn bản", - "Comment" => "Chú thích", - "New\nComment" => "Chú thích\nmới", + "Comment" => "Nhận xét", + "New\nComment" => "Nhận xét\nmới", "New Note" => "Ghi chú mới", - "Show/Hide Note" => "Hiện/ẩn ghi chú", + "Show/Hide Note" => "Hiện/Ẩn ghi chú", "Header &\nFooter" => "Đầu trang &\nChân trang", - "Text to\nColumns" => "Tách\ncột", + "Text to\nColumns" => "Văn bản\nthành cột", "Link" => "Liên kết", "Symbol" => "Ký hiệu", "Sparklines" => "Biểu đồ thu nhỏ", @@ -128,30 +131,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Bottom Margin" => "Lề dưới", "Header Margin" => "Lề đầu trang", "Footer Margin" => "Lề chân trang", - "Size" => "Khổ giấy", + "Size" => "Kích cỡ", "Print\nArea" => "Vùng\nin", "Set Print Area" => "Đặt vùng in", "Breaks" => "Ngắt trang", "Insert Page Break" => "Chèn ngắt trang", "Remove Page Break" => "Bỏ ngắt trang", "Reset All Page Breaks" => "Đặt lại tất cả ngắt trang", - "Print\nTitles" => "In\ntiêu đề", + "Print\nTitles" => "Tiêu đề\nin", "Sheet\nRight-to-Left" => "Trang tính\nphải sang trái", "Sheet Right-to-Left" => "Trang tính phải sang trái", "Narrow" => "Hẹp", "Wide" => "Rộng", - "Normal" => "Bình thường", + "Normal" => "Thường", "Portrait" => "Dọc", "Landscape" => "Ngang", "Custom Margins…" => "Lề tùy chỉnh…", "Insert\nFunction" => "Chèn\nhàm", "Name\nManager" => "Trình quản lý\ntên", - "Define Name" => "Xác định tên", + "Define Name" => "Đặt tên", "Use in Formula" => "Dùng trong công thức", "Create from Selection" => "Tạo từ vùng chọn", - "Trace Precedents" => "Truy tìm ô tham chiếu", + "Trace Precedents" => "Truy tìm ô tiền nhiệm", "Trace Dependents" => "Truy tìm ô phụ thuộc", - "Remove Arrows" => "Bỏ mũi tên", + "Remove Arrows" => "Xóa mũi tên", "Show Formulas" => "Hiện công thức", "Error Checking" => "Kiểm tra lỗi", "Trace Error" => "Truy tìm lỗi", @@ -159,24 +162,24 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Evaluate Formula" => "Đánh giá công thức", "Watch Window" => "Cửa sổ theo dõi", "Calculation\nOptions" => "Tùy chọn\ntính toán", - "Calculate Now" => "Tính ngay", - "Calculate Sheet" => "Tính trang tính", + "Calculate Now" => "Tính toán ngay", + "Calculate Sheet" => "Tính toán trang tính", "Automatic" => "Tự động", "Automatic Except for Data Tables" => "Tự động trừ bảng dữ liệu", "Manual" => "Thủ công", "Sort &\nFilter" => "Sắp xếp &\nLọc", "Sort" => "Sắp xếp", - "Sort A to Z" => "Sắp xếp từ A đến Z", - "Sort Z to A" => "Sắp xếp từ Z đến A", + "Sort A to Z" => "Sắp xếp A đến Z", + "Sort Z to A" => "Sắp xếp Z đến A", "Custom Sort…" => "Sắp xếp tùy chỉnh…", - "Filter" => "Lọc", + "Filter" => "Bộ lọc", "Reapply" => "Áp dụng lại", "Get Data\n(Text/CSV)" => "Lấy dữ liệu\n(Văn bản/CSV)", - "Remove\nDuplicates" => "Loại bỏ\ntrùng lặp", + "Remove\nDuplicates" => "Xóa\ntrùng lặp", "Data\nValidation" => "Xác thực\ndữ liệu", "Data Validation" => "Xác thực dữ liệu", "Data Validation…" => "Xác thực dữ liệu…", - "Circle Invalid Data" => "Khoanh dữ liệu không hợp lệ", + "Circle Invalid Data" => "Khoanh tròn dữ liệu không hợp lệ", "Clear Validation" => "Xóa xác thực", "Group" => "Nhóm", "Ungroup" => "Bỏ nhóm", @@ -185,61 +188,59 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Subtotal" => "Tổng phụ", "Data\nAnalysis" => "Phân tích\ndữ liệu", "Data Analysis" => "Phân tích dữ liệu", - "Solver" => "Solver", - "What-If\nAnalysis" => "Phân tích\nWhat-If", + "Solver" => "Bộ giải Solver", + "What-If\nAnalysis" => "Phân tích\ngiả định", "Data Table…" => "Bảng dữ liệu…", "Scenario Manager…" => "Trình quản lý kịch bản…", "Goal Seek…" => "Tìm mục tiêu…", "Forecast\nSheet" => "Trang tính\ndự báo", "Spelling" => "Chính tả", - "Check\nAccessibility" => "Kiểm tra\ntrợ năng", - "Threaded Comments" => "Chú thích dạng chuỗi", - "Show\nComments" => "Hiện\nchú thích", + "Check\nAccessibility" => "Kiểm tra\nkhả năng tiếp cận", + "Threaded Comments" => "Nhận xét theo luồng", + "Show\nComments" => "Hiện\nnhận xét", "Previous" => "Trước", "Next" => "Tiếp", - "Previous Comment" => "Chú thích trước", - "Next Comment" => "Chú thích tiếp theo", + "Previous Comment" => "Nhận xét trước", + "Next Comment" => "Nhận xét tiếp", "Show All Notes" => "Hiện tất cả ghi chú", - "Convert to Comments" => "Chuyển thành chú thích", + "Convert to Comments" => "Chuyển thành nhận xét", "Protect\nWorkbook" => "Bảo vệ\nsổ làm việc", - "Allow Edit\nRanges" => "Cho phép sửa\nphạm vi", - "Allow Edit Ranges" => "Cho phép sửa phạm vi", + "Allow Edit\nRanges" => "Cho phép sửa\nvùng", + "Allow Edit Ranges" => "Cho phép sửa vùng", "Unprotect\nSheet" => "Bỏ bảo vệ\ntrang tính", "Protect Sheet…" => "Bảo vệ trang tính…", - "Comments" => "Chú thích", + "Comments" => "Nhận xét", "Notes" => "Ghi chú", "Page Break\nPreview" => "Xem trước\nngắt trang", - "Page\nLayout" => "Bố trí\ntrang", + "Page\nLayout" => "Bố cục\ntrang", "Formula Bar" => "Thanh công thức", "Name Box" => "Hộp tên", "Cell Editor" => "Trình soạn thảo ô", "Font Size" => "Cỡ chữ", "Gridlines" => "Đường lưới", - "Headings" => "Tiêu đề hàng/cột", + "Headings" => "Tiêu đề hàng cột", "Zoom" => "Thu phóng", "100%" => "100%", - "Zoom to\nSelection" => "Phóng to\nvùng chọn", - "Freeze\nPanes" => "Cố định\nngăn", - "Freeze Panes" => "Cố định ngăn", - "Freeze Top Row" => "Cố định hàng trên cùng", - "Freeze First Column" => "Cố định cột đầu tiên", - "Unfreeze Panes" => "Bỏ cố định ngăn", + "Zoom to\nSelection" => "Thu phóng đến\nvùng chọn", + "Freeze\nPanes" => "Cố định\nkhung", + "Freeze Panes" => "Cố định khung", + "Freeze Top Row" => "Cố định hàng đầu", + "Freeze First Column" => "Cố định cột đầu", + "Unfreeze Panes" => "Bỏ cố định khung", "Dark Mode" => "Chế độ tối", - "Display theme" => "Chủ đề hiển thị", - "Animations" => "Hiệu ứng động", - "Glide the selection outline to the cell you move to instead of jumping there" => { - "Trượt khung vùng chọn tới ô bạn di chuyển đến thay vì nhảy ngay tới đó" - } + "Display theme" => "Giao diện hiển thị", + "Animations" => "Hiệu ứng chuyển động", + "Glide the selection outline to the cell you move to instead of jumping there" => "Trượt mượt khung chọn tới ô đích thay vì nhảy tức thì", "System" => "Hệ thống", "Light" => "Sáng", "Dark" => "Tối", "Interface language" => "Ngôn ngữ giao diện", - "Interface size" => "Kích thước giao diện", + "Interface size" => "Kích cỡ giao diện", "Auto" => "Tự động", "Drag to freeze columns" => "Kéo để cố định cột", "Drag to freeze rows" => "Kéo để cố định hàng", "Command\nPalette" => "Bảng\nlệnh", - "Agent\nControl" => "Điều khiển\nagent", + "Agent\nControl" => "Điều khiển\ntác tử", "Action\nJournal" => "Nhật ký\nthao tác", "About\nGridCraft" => "Giới thiệu\nGridCraft", "Share" => "Chia sẻ", @@ -257,12 +258,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Gridlines: Show" => "Đường lưới: Hiện", "Chart\nTitle" => "Tiêu đề\nbiểu đồ", "Delete\nChart" => "Xóa\nbiểu đồ", - "Convert\nto Range" => "Chuyển thành\nphạm vi", + "Convert\nto Range" => "Chuyển\nthành vùng", "Table\nStyles" => "Kiểu\nbảng", - "Top 10 Items" => "10 mục đầu", - "Top 10%" => "10% đầu", - "Bottom 10 Items" => "10 mục cuối", - "Bottom 10%" => "10% cuối", + "Top 10 Items" => "10 mục cao nhất", + "Top 10%" => "10% cao nhất", + "Bottom 10 Items" => "10 mục thấp nhất", + "Bottom 10%" => "10% thấp nhất", "Above Average" => "Trên trung bình", "Below Average" => "Dưới trung bình", "Clear Rules from Entire Sheet" => "Xóa quy tắc khỏi toàn bộ trang tính", @@ -271,9 +272,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Data Bars" => "Thanh dữ liệu", "Color Scales" => "Thang màu", "Icon Sets" => "Bộ biểu tượng", - "Home" => "Trang đầu", + "Home" => "Trang chủ", "Draw" => "Vẽ", - "Page Layout" => "Bố trí trang", + "Page Layout" => "Bố cục trang", "Formulas" => "Công thức", "Data" => "Dữ liệu", "Review" => "Xem lại", @@ -292,34 +293,32 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Currency" => "Tiền tệ", "Accounting" => "Kế toán", "Date" => "Ngày", - "Time" => "Giờ", + "Time" => "Thời gian", "Percentage" => "Phần trăm", "Fraction" => "Phân số", "Scientific" => "Khoa học", "Text" => "Văn bản", "Special" => "Đặc biệt", "Custom" => "Tùy chỉnh", - "Short Date" => "Ngày dạng ngắn", - "Long Date" => "Ngày dạng dài", - "More Number Formats…" => "Định dạng số khác…", + "Short Date" => "Ngày ngắn", + "Long Date" => "Ngày dài", + "More Number Formats…" => "Thêm định dạng số…", "Financial" => "Tài chính", + "Recently Used" => "Dùng gần đây", "Logical" => "Logic", - "Date & Time" => "Ngày & Giờ", - "Lookup & Reference" => "Tra cứu & Tham chiếu", - "Math & Trig" => "Toán & Lượng giác", - "More Functions" => "Hàm khác", - "Sheet Options|View" => "Xem", + "More Functions" => "Thêm hàm", + "Sheet Options|View" => "Hiển thị", "Print" => "In", "Print What" => "Nội dung in", // Page Layout view and the Header & Footer tab. - "Click to add data" => "Bấm để thêm dữ liệu", + "Click to add data" => "Nhấp để thêm dữ liệu", "Add header" => "Thêm đầu trang", "Add footer" => "Thêm chân trang", "(none)" => "(không có)", "Header" => "Đầu trang", "Footer" => "Chân trang", "Page\nNumber" => "Số\ntrang", - "Number\nof Pages" => "Tổng\nsố trang", + "Number\nof Pages" => "Tổng số\ntrang", "Current\nDate" => "Ngày\nhiện tại", "Current\nTime" => "Giờ\nhiện tại", "File\nPath" => "Đường dẫn\ntệp", @@ -335,8 +334,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "File Name" => "Tên tệp", "Sheet Name" => "Tên trang tính", "Go to Header" => "Đi tới đầu trang", - "Different First Page" => "Trang đầu khác", - "Different Odd & Even Pages" => "Trang chẵn lẻ khác nhau", + "Different First Page" => "Trang đầu khác biệt", + "Different Odd & Even Pages" => "Trang chẵn & lẻ khác nhau", "Scale with Document" => "Co giãn theo tài liệu", "Align with Page Margins" => "Căn theo lề trang", "Go to Footer" => "Đi tới chân trang", @@ -355,7 +354,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Blank workbook" => "Sổ làm việc trống", "Recent" => "Gần đây", "No recent workbooks yet." => "Chưa có sổ làm việc gần đây.", - "More workbooks" => "Sổ làm việc khác", + "More workbooks" => "Thêm sổ làm việc", "Modified" => "Đã sửa đổi", "Not available" => "Không khả dụng", "Just now" => "Vừa xong", @@ -372,10 +371,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Sheets" => "Trang tính", "Protect Workbook" => "Bảo vệ sổ làm việc", "Sheet structure is locked: sheets can't be added, moved, renamed or deleted." => { - "Cấu trúc trang tính đã bị khóa: không thể thêm, di chuyển, đổi tên hoặc xóa trang tính." + "Cấu trúc trang tính đã khóa: không thể thêm, di chuyển, đổi tên hoặc xóa trang tính." } "Lock the sheet structure so sheets can't be added, moved, renamed or deleted." => { - "Khóa cấu trúc trang tính để không thể thêm, di chuyển, đổi tên hoặc xóa trang tính." + "Khóa cấu trúc trang tính để ngăn thêm, di chuyển, đổi tên hoặc xóa trang tính." } "Properties" => "Thuộc tính", "Title" => "Tiêu đề", @@ -387,47 +386,811 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "No workbook is open." => "Chưa mở sổ làm việc nào.", "Save as type" => "Lưu dưới dạng", "Excel Workbook (*.xlsx)" => "Sổ làm việc Excel (*.xlsx)", - "CSV UTF-8 (Comma delimited) (*.csv)" => "CSV UTF-8 (phân cách bằng dấu phẩy) (*.csv)", + "CSV UTF-8 (Comma delimited) (*.csv)" => "CSV UTF-8 (Phân cách bằng dấu phẩy) (*.csv)", "Web Page (*.html)" => "Trang web (*.html)", "PDF (*.pdf)" => "PDF (*.pdf)", "Download" => "Tải xuống", "A CSV file, web page or PDF is a copy: the workbook keeps its own file." => { - "Tệp CSV, trang web hoặc PDF chỉ là bản sao: sổ làm việc vẫn giữ tệp gốc." + "Tệp CSV, trang web hoặc PDF là bản sao: sổ làm việc vẫn giữ tệp gốc của nó." } "Save the workbook under another name or in another folder." => "Lưu sổ làm việc với tên khác hoặc vào thư mục khác.", - "Print Active Sheets" => "In các trang tính hiện hoạt", + "Print Active Sheets" => "In các trang tính đang chọn", "Print Entire Workbook" => "In toàn bộ sổ làm việc", - "Fit Sheet on One Page" => "Vừa trang tính trên một trang", + "Fit Sheet on One Page" => "Vừa trang tính trên một trang in", "Page Setup…" => "Thiết lập trang…", - "Page {page} of {pages}" => "Trang {page} / {pages}", - "Nothing to print." => "Không có gì để in.", + "Page {page} of {pages}" => "Trang {page} trên {pages}", + "Nothing to print." => "Không có nội dung để in.", "Previous page" => "Trang trước", - "Next page" => "Trang sau", + "Next page" => "Trang tiếp theo", "Create PDF" => "Tạo PDF", - "Save the sheet as a PDF document that keeps its page layout." => "Lưu trang tính thành tài liệu PDF, giữ nguyên bố trí trang.", - "Change File Type" => "Đổi kiểu tệp", - "CSV (Comma delimited)" => "CSV (phân cách bằng dấu phẩy)", - "Save the active sheet as comma-separated text." => "Lưu trang tính hiện hoạt thành văn bản phân cách bằng dấu phẩy.", + "Save the sheet as a PDF document that keeps its page layout." => "Lưu trang tính thành tài liệu PDF giữ nguyên bố cục trang.", + "Change File Type" => "Đổi loại tệp", + "CSV (Comma delimited)" => "CSV (Phân cách bằng dấu phẩy)", + "Save the active sheet as comma-separated text." => "Lưu trang tính hiện hành thành văn bản phân cách bằng dấu phẩy.", "Web Page (.html)" => "Trang web (.html)", "Save the workbook as a web page." => "Lưu sổ làm việc thành trang web.", "Options|General" => "Chung", "Options|Save" => "Lưu", "Show formula bar" => "Hiện thanh công thức", - "Enable AutoComplete for cell values" => "Bật tự động hoàn thành giá trị ô", + "Enable AutoComplete for cell values" => "Bật Tự động hoàn tất cho giá trị ô", "Save .xlsx workbooks automatically after every change" => "Tự động lưu sổ làm việc .xlsx sau mỗi thay đổi", "Workbook calculation" => "Tính toán sổ làm việc", "Enable iterative calculation" => "Bật tính toán lặp", - "Calculation settings are saved with the workbook." => "Thiết lập tính toán được lưu cùng sổ làm việc.", + "Maximum Iterations:" => "Số lần lặp tối đa:", + "Maximum Change:" => "Mức thay đổi tối đa:", + "Maximum Iterations must be a whole number from 1 to 32767." => "Số lần lặp tối đa phải là số nguyên từ 1 đến 32767.", + "Maximum Change must be a number of 0 or more." => "Mức thay đổi tối đa phải là một số lớn hơn hoặc bằng 0.", + "Calculation settings are saved with the workbook." => "Thiết lập tính toán được lưu cùng với sổ làm việc.", + // Dialogs, menus, context menus and tooltips. + "OK" => "OK", + "Cancel" => "Hủy", + "Don't Save" => "Không lưu", + "Open…" => "Mở…", + "Show password" => "Hiện mật khẩu", + "Start a new workbook" => "Bắt đầu sổ làm việc mới", + "Household Budget" => "Ngân sách gia đình", + "Quarterly Sales Dashboard" => "Bảng điều khiển doanh số quý", + "Gradebook" => "Sổ điểm", + "this workbook" => "sổ làm việc này", + "This workbook" => "Sổ làm việc này", + "Do you want to save the changes you made to {title}?" => "Bạn có muốn lưu các thay đổi đã thực hiện cho {title} không?", + "Save a copy as .{format}" => "Lưu bản sao dưới dạng .{format}", + "Select a chart first." => "Hãy chọn một biểu đồ trước.", "Text Box" => "Hộp văn bản", + "Select Data" => "Chọn dữ liệu", + "Row Height" => "Chiều cao hàng", + "Column Width" => "Độ rộng cột", + "Standard Width" => "Độ rộng tiêu chuẩn", + "Rename Sheet" => "Đổi tên trang tính", + "Move or Copy" => "Di chuyển hoặc sao chép", + "Protect Sheet" => "Bảo vệ trang tính", + "Protect Structure and Windows" => "Bảo vệ cấu trúc và cửa sổ", + "Unprotect Workbook" => "Bỏ bảo vệ sổ làm việc", + "Unprotect Sheet" => "Bỏ bảo vệ trang tính", + "Password" => "Mật khẩu", + "Unhide" => "Hiện", + "Paste Special" => "Dán đặc biệt", + "Series" => "Chuỗi", + "New Comment" => "Nhận xét mới", + "Insert Hyperlink" => "Chèn siêu liên kết", + "Create Sparklines" => "Tạo biểu đồ thu nhỏ", + "Page Setup" => "Thiết lập trang", + "Convert Text to Columns" => "Chuyển văn bản thành cột", + "Remove Duplicates" => "Xóa trùng lặp", + "Goal Seek" => "Tìm mục tiêu", + "Create Forecast Worksheet" => "Tạo trang tính dự báo", + "Solver Parameters" => "Tham số Solver", + "Solver Results" => "Kết quả Solver", + "Edit Name" => "Sửa tên", + "New Name" => "Tên mới", + "Format Cells" => "Định dạng ô", + "Find and Replace" => "Tìm và Thay thế", + "Go To" => "Đi tới", + "Insert Calculated Field" => "Chèn trường tính toán", + "Go To Special" => "Đi tới đặc biệt", + "Name Manager" => "Trình quản lý tên", + "Conditional Formatting Rules Manager" => "Trình quản lý quy tắc định dạng có điều kiện", + "Search Commands" => "Tìm lệnh", + "Agent Control" => "Điều khiển tác tử", + "About GridCraft" => "Giới thiệu về GridCraft", + "Insert Chart" => "Chèn biểu đồ", + "Select Data Source" => "Chọn nguồn dữ liệu", + "Action Journal" => "Nhật ký thao tác", "Macros" => "Macro", + "Workbook Statistics" => "Thống kê sổ làm việc", + "Accessibility" => "Khả năng tiếp cận", + "Chart Title" => "Tiêu đề biểu đồ", + "Place Picture in Cell" => "Đặt ảnh trong ô", + "Place Picture over Cells" => "Đặt ảnh đè lên các ô", + "Pick From List" => "Chọn từ danh sách", + "Save a Copy" => "Lưu bản sao", + "Save Changes?" => "Lưu thay đổi?", + "Shift cells right" => "Dịch các ô sang phải", + "Shift cells down" => "Dịch các ô xuống dưới", + "Shift cells left" => "Dịch các ô sang trái", + "Shift cells up" => "Dịch các ô lên trên", + "Entire row" => "Toàn bộ hàng", + "Entire column" => "Toàn bộ cột", + "Row height (pixels):" => "Chiều cao hàng (pixel):", + "Column width (characters):" => "Độ rộng cột (ký tự):", + "Standard column width (pixels):" => "Độ rộng cột tiêu chuẩn (pixel):", + "Name:" => "Tên:", + "Before sheet (position, 0 = first):" => "Trước trang tính (vị trí, 0 = đầu tiên):", + "Create a copy" => "Tạo một bản sao", + "Sheets: {sheets}" => "Trang tính: {sheets}", + "Password (optional):" => "Mật khẩu (tùy chọn):", + "Password:" => "Mật khẩu:", + "Allow all users of this sheet to:" => "Cho phép mọi người dùng trang tính này:", + "Format cells" => "Định dạng ô", + "Format columns" => "Định dạng cột", + "Format rows" => "Định dạng hàng", + "Insert rows" => "Chèn hàng", + "Delete rows" => "Xóa hàng", + "Use AutoFilter" => "Dùng Tự động lọc", + " (password, unlocked)" => " (có mật khẩu, đã mở khóa)", + " (password)" => " (có mật khẩu)", + "No ranges yet." => "Chưa có vùng nào.", + "Ranges that stay editable when the sheet is protected:" => "Các vùng vẫn cho phép chỉnh sửa khi trang tính được bảo vệ:", + "Action" => "Thao tác", + "Modify" => "Sửa đổi", + "Unlock with password" => "Mở khóa bằng mật khẩu", + "Title:" => "Tiêu đề:", + "Refers to cells:" => "Tham chiếu tới các ô:", + "Range password:" => "Mật khẩu vùng:", + "New title (Modify):" => "Tiêu đề mới (Sửa đổi):", + "Remove the password (Modify)" => "Gỡ mật khẩu (Sửa đổi)", + "'{file}' is protected." => "'{file}' được bảo vệ.", + "Unhide sheet:" => "Hiện trang tính:", + "Hidden: {sheets}" => "Đã ẩn: {sheets}", + "All" => "Tất cả", + "Formulas (F)" => "Công thức (F)", + "Values (V)" => "Giá trị (V)", + "Formats (T)" => "Định dạng (T)", + "Comments and notes (C)" => "Nhận xét và ghi chú (C)", + "Validation" => "Xác thực", + "All except borders" => "Tất cả trừ đường viền", + "Column widths" => "Độ rộng cột", + "Formulas and number formats" => "Công thức và định dạng số", + "Values and number formats" => "Giá trị và định dạng số", + "Operation" => "Phép tính", + "Add" => "Cộng", + "Subtract" => "Trừ", + "Multiply" => "Nhân", + "Divide" => "Chia", + "Skip blanks" => "Bỏ qua ô trống", + "Transpose (E)" => "Chuyển vị (E)", + "Series in" => "Chuỗi theo", + "Columns" => "Cột", + "Rows" => "Hàng", + "Type" => "Loại", + "Linear" => "Tuyến tính", + "Growth" => "Tăng trưởng", + "Date unit" => "Đơn vị ngày", + "Day" => "Ngày", + "Weekday" => "Ngày làm việc", + "Month" => "Tháng", + "Year" => "Năm", + "Step value:" => "Bước nhảy:", + "Stop value:" => "Giá trị dừng:", + "Start a conversation:" => "Bắt đầu cuộc trò chuyện:", + "Note:" => "Ghi chú:", + "Display:" => "Hiển thị:", + "Link to (web address, e-mail or Sheet!A1):" => "Liên kết tới (địa chỉ web, email hoặc Sheet!A1):", + "ScreenTip:" => "Chú giải màn hình:", + "Data Range:" => "Vùng dữ liệu:", + "Location Range:" => "Vùng vị trí:", + "Markers" => "Điểm đánh dấu", + "Footer:" => "Chân trang:", + "Left margin (in):" => "Lề trái (in):", + "Right margin (in):" => "Lề phải (in):", + "Top margin (in):" => "Lề trên (in):", + "Bottom margin (in):" => "Lề dưới (in):", + "Header (in):" => "Đầu trang (in):", + "Footer (in):" => "Chân trang (in):", + "Page order" => "Thứ tự trang", + "Down, then over" => "Xuống dưới, rồi sang phải", + "Over, then down" => "Sang phải, rồi xuống dưới", + "Tab" => "Tab", + "Semicolon" => "Dấu chấm phẩy", + "Comma" => "Dấu phẩy", + "Space" => "Dấu cách", + "Other:" => "Khác:", + "Treat consecutive delimiters as one" => "Gộp các dấu phân cách liên tiếp thành một", + "Destination:" => "Đích đến:", + "My data has headers" => "Dữ liệu của tôi có tiêu đề", + "Columns (blank = all, e.g. A,C):" => "Cột (để trống = tất cả, VD: A,C):", + "Timeline range (blank: first column of the selection):" => "Vùng mốc thời gian (để trống: cột đầu tiên của vùng chọn):", + "Values range (blank: second column of the selection):" => "Vùng giá trị (để trống: cột thứ hai của vùng chọn):", + "Confidence interval" => "Khoảng tin cậy", + "Confidence level (%):" => "Mức tin cậy (%):", + "Seasonality (auto, 0 for none, or a season length):" => "Tính mùa vụ (tự động, 0 là không có, hoặc độ dài chu kỳ):", + "Fill missing points using" => "Điền các điểm thiếu bằng", + "Interpolation" => "Nội suy", + "Zeros" => "Số 0", + "Aggregate duplicates using" => "Gộp các giá trị trùng bằng", + "Average" => "Trung bình", + "Count" => "Đếm", + "CountA" => "Đếm không trống (CountA)", + "Max" => "Lớn nhất", + "Median" => "Trung vị", + "Min" => "Nhỏ nhất", + "Sum" => "Tổng", + "Product" => "Tích", + "Include forecast statistics" => "Bao gồm thống kê dự báo", + "Chart" => "Biểu đồ", + "Line chart" => "Biểu đồ đường", + "Column chart" => "Biểu đồ cột", + "At each change in (column letter):" => "Tại mỗi thay đổi trong (chữ cái cột):", + "Use function" => "Sử dụng hàm", + "Add subtotal to (columns, e.g. C,D):" => "Thêm tổng phụ vào (các cột, VD: C,D):", + "Magnification" => "Độ phóng đại", + "Custom (%):" => "Tùy chỉnh (%):", + "Scope (Workbook or sheet name):" => "Phạm vi (Sổ làm việc hoặc tên trang tính):", + "Comment:" => "Nhận xét:", + "Refers to:" => "Tham chiếu tới:", + "Allow" => "Cho phép", + "Any value" => "Giá trị bất kỳ", + "Whole number" => "Số nguyên", + "Decimal" => "Số thập phân", + "List" => "Danh sách", + "Text length" => "Độ dài văn bản", + "between" => "nằm giữa", + "not between" => "không nằm giữa", + "equal to" => "bằng", + "not equal to" => "không bằng", + "greater than" => "lớn hơn", + "less than" => "nhỏ hơn", + "greater than or equal to" => "lớn hơn hoặc bằng", + "less than or equal to" => "nhỏ hơn hoặc bằng", + "Minimum / Source / Formula:" => "Tối thiểu / Nguồn / Công thức:", + "Maximum:" => "Tối đa:", + "Ignore blank" => "Bỏ qua ô trống", + "In-cell dropdown" => "Danh sách thả xuống trong ô", + "Input message:" => "Thông báo nhập:", + "Error style" => "Kiểu báo lỗi", + "Stop" => "Dừng", + "Warning" => "Cảnh báo", + "Information" => "Thông tin", + "Error message:" => "Thông báo lỗi:", + "Format cells that are (value):" => "Định dạng các ô có giá trị:", + "and:" => "và:", + "Format cells that contain the text:" => "Định dạng các ô chứa văn bản:", + "Format cells that contain a date occurring:" => "Định dạng các ô chứa ngày:", + "Today" => "Hôm nay", + "Tomorrow" => "Ngày mai", + "In the last 7 days" => "Trong 7 ngày qua", + "Last week" => "Tuần trước", + "This week" => "Tuần này", + "Next week" => "Tuần sau", + "Last month" => "Tháng trước", + "This month" => "Tháng này", + "Next month" => "Tháng sau", + "Format values where this formula is true:" => "Định dạng các giá trị khi công thức này đúng:", + "with" => "với", + "Light Red Fill with Dark Red Text" => "Tô đỏ nhạt với chữ đỏ đậm", + "Yellow Fill with Dark Yellow Text" => "Tô vàng với chữ vàng đậm", + "Green Fill with Dark Green Text" => "Tô xanh lục với chữ xanh lục đậm", + "Light Red Fill" => "Tô đỏ nhạt", + "Red Text" => "Chữ đỏ", + "Red Border" => "Viền đỏ", + "Formula:" => "Công thức:", + "Select" => "Chọn", + "Blanks" => "Ô trống", + "Errors" => "Lỗi", + "Numbers" => "Số", + "Current region" => "Vùng hiện tại", + "Last cell" => "Ô cuối cùng", + "Visible cells only" => "Chỉ các ô hiển thị", + "Conditional formats" => "Định dạng có điều kiện", + "Data validation" => "Xác thực dữ liệu", + "Horizontal axis title:" => "Tiêu đề trục ngang:", + "Vertical axis title:" => "Tiêu đề trục dọc:", + "No picture selected" => "Chưa chọn hình ảnh", + "Picture file path (PNG or JPEG):" => "Đường dẫn tệp ảnh (PNG hoặc JPEG):", + "Description (optional):" => "Mô tả (tùy chọn):", + "Fits inside the selected cell and moves with its content." => "Vừa khít trong ô đã chọn và di chuyển theo nội dung ô.", + "Choose a PNG or JPEG no larger than 16 MB." => "Chọn tệp PNG hoặc JPEG không quá 16 MB.", + "About" => "Giới thiệu", + "Contributors" => "Người đóng góp", + "Models" => "Mô hình", + "Version {version}" => "Phiên bản {version}", + "Join the ArtCraft Discord" => "Tham gia Discord của ArtCraft", + "This workbook has no scripts or macros." => "Sổ làm việc này không có tập lệnh hay macro nào.", + "(unnamed)" => "(chưa đặt tên)", + "— VBA project (preserved, not run)" => "— Dự án VBA (được bảo toàn, không chạy)", + "— 1 step" => "— 1 bước", + "— {steps} steps" => "— {steps} bước", + "Alignment" => "Căn chỉnh", + "Font" => "Phông chữ", + "Border" => "Đường viền", + "Format Cells|Fill" => "Tô nền", + "Protection" => "Bảo vệ", + "Category:" => "Danh mục:", + "Sample" => "Mẫu", + "Type (custom format code):" => "Loại (mã định dạng tùy chỉnh):", + "Vertical" => "Dọc", + "Justify" => "Căn đều", + "Center Across Selection" => "Căn giữa qua vùng chọn", + "Distributed" => "Căn đều phân tán", + "Top" => "Trên", + "Bottom" => "Dưới", + "Indent" => "Thụt lề", + "Orientation (degrees)" => "Góc xoay (độ)", + "Wrap text" => "Ngắt dòng tự động", + "Shrink to fit" => "Thu nhỏ vừa ô", + "Bold" => "In đậm", + "Italic" => "In nghiêng", + "None" => "Không có", + "Single" => "Đơn", + "Double" => "Đôi", + "Single Accounting" => "Kế toán đơn", + "Double Accounting" => "Kế toán đôi", + "Superscript" => "Chỉ số trên", + "Subscript" => "Chỉ số dưới", + "Color:" => "Màu:", + "Outline" => "Viền ngoài", + "Diagonal ↘" => "Chéo ↘", + "Diagonal ↗" => "Chéo ↗", + "none" => "không có", + "thin" => "mảnh", + "medium" => "vừa", + "thick" => "dày", + "dashed" => "nét đứt", + "dotted" => "nét chấm", + "double" => "nét đôi", + "Background Color:" => "Màu nền:", + "Locked" => "Đã khóa", + "Hidden" => "Ẩn", + "Search:" => "Tìm kiếm:", + "e.g. lookup, average, date" => "VD: tra cứu, trung bình, ngày", + "Date & Time" => "Ngày & Giờ", + "Lookup & Reference" => "Tra cứu & Tham chiếu", + "Math & Trig" => "Toán & Lượng giác", + "Statistical" => "Thống kê", + "Engineering" => "Kỹ thuật", + "Database" => "Cơ sở dữ liệu", + "Compatibility" => "Tương thích", + "Web" => "Web", + "Cube" => "Khối dữ liệu (Cube)", + "Add-in and Automation" => "Tiện ích bổ sung và Tự động hóa", + "Find" => "Tìm", + "Replace" => "Thay thế", + "Find what:" => "Tìm gì:", + "Replace with:" => "Thay bằng:", + "Match case" => "Khớp chữ hoa/thường", + "Match entire cell contents" => "Khớp toàn bộ nội dung ô", + "Within workbook" => "Trong toàn sổ làm việc", + "Replace All" => "Thay thế tất cả", + "Find All" => "Tìm tất cả", + "Find Next" => "Tìm tiếp", + "All done. We made {count} replacements." => "Hoàn tất. Đã thực hiện {count} lần thay thế.", + "{count} cell(s) found" => "Tìm thấy {count} ô", + "Reference:" => "Tham chiếu:", + "Special…" => "Đặc biệt…", + "My list has headers" => "Danh sách của tôi có tiêu đề", + "Sort by" => "Sắp xếp theo", + "Then by" => "Sau đó theo", + "Cell Values" => "Giá trị ô", + "Cell Color" => "Màu ô", + "A to Z" => "A đến Z", + "Z to A" => "Z đến A", + "+ Add Level" => "+ Thêm cấp", + "New…" => "Tạo mới…", + "Edit…" => "Sửa…", + "Name" => "Tên", + "Value" => "Giá trị", + "Refers To" => "Tham chiếu tới", + "Scope" => "Phạm vi", + "Workbook" => "Sổ làm việc", + "No names defined" => "Chưa định nghĩa tên nào", + "Recommended Charts" => "Biểu đồ đề xuất", + "All Charts" => "Tất cả biểu đồ", + "Clustered Column" => "Cột cụm", + "Stacked Column" => "Cột chồng", + "100% Stacked Column" => "Cột chồng 100%", + "Clustered Bar" => "Thanh cụm", + "Stacked Bar" => "Thanh chồng", + "100% Stacked Bar" => "Thanh chồng 100%", + "Line" => "Đường", + "Line with Markers" => "Đường có điểm đánh dấu", + "Stacked Line" => "Đường chồng", + "Pie" => "Tròn", + "Doughnut" => "Vành khuyên", + "Area" => "Miền", + "Stacked Area" => "Miền chồng", + "100% Stacked Area" => "Miền chồng 100%", + "Scatter" => "Phân tán", + "Scatter with Lines" => "Phân tán có đường nối", + "Radar" => "Radar", + "Histogram" => "Biểu đồ tần suất", + "Waterfall" => "Thác nước", + "Funnel" => "Phễu", + "Combo" => "Kết hợp", + "Chart data range:" => "Vùng dữ liệu biểu đồ:", + "Legend Entries (Series)" => "Mục chú giải (Chuỗi)", + "Series{n}" => "Chuỗi{n}", + "Keep" => "Giữ", + "Remove" => "Gỡ bỏ", + "Horizontal (Category) Axis Labels:" => "Nhãn trục ngang (Danh mục):", + "There are no conditional formatting rules on this sheet." => "Không có quy tắc định dạng có điều kiện nào trên trang tính này.", + "applies to" => "áp dụng cho", + "Type a command, e.g. freeze, chart, bold…" => "Nhập lệnh, VD: cố định, biểu đồ, in đậm…", + "Set cell:" => "Đặt ô:", + "To value:" => "Thành giá trị:", + "By changing cell:" => "Bằng cách thay đổi ô:", + "Goal Seeking found a solution: {value}" => "Tìm mục tiêu đã tìm thấy nghiệm: {value}", + "Analysis Tools" => "Công cụ phân tích", + "Anova: Single Factor" => "Anova: Một yếu tố", + "Correlation" => "Tương quan", + "Covariance" => "Hiệp phương sai", + "Descriptive Statistics" => "Thống kê mô tả", + "Exponential Smoothing" => "Làm mượt hàm mũ", + "F-Test Two-Sample for Variances" => "Kiểm định F hai mẫu cho phương sai", + "Moving Average" => "Trung bình trượt", + "Rank and Percentile" => "Thứ hạng và Bách phân vị", + "Regression" => "Hồi quy", + "t-Test: Paired Two Sample for Means" => "Kiểm định t: Hai mẫu ghép cặp cho trung bình", + "t-Test: Two-Sample Assuming Equal Variances" => "Kiểm định t: Hai mẫu giả định phương sai bằng nhau", + "t-Test: Two-Sample Assuming Unequal Variances" => "Kiểm định t: Hai mẫu giả định phương sai khác nhau", + "Output options" => "Tùy chọn đầu ra", + "Output Range:" => "Vùng đầu ra:", + "New Worksheet Ply:" => "Trang tính mới:", + "Grouped By:" => "Nhóm theo:", + "Labels in first row" => "Nhãn ở hàng đầu tiên", + "Input Range:" => "Vùng đầu vào:", + "Variable 1 Range:" => "Vùng biến 1:", + "Variable 2 Range:" => "Vùng biến 2:", + "Summary statistics" => "Thống kê tóm tắt", + "Confidence Level for Mean (%), blank for none:" => "Mức tin cậy cho trung bình (%), để trống nếu không dùng:", + "Kth Largest (blank for none):" => "Lớn thứ K (để trống nếu không dùng):", + "Kth Smallest (blank for none):" => "Nhỏ thứ K (để trống nếu không dùng):", + "Bin Range (blank for automatic bins):" => "Vùng chia lớp (để trống để chia tự động):", + "Pareto (sorted histogram)" => "Pareto (biểu đồ tần suất sắp xếp)", + "Cumulative Percentage" => "Phần trăm tích lũy", + "Alpha:" => "Alpha:", + "Input Y Range:" => "Vùng Y đầu vào:", + "Input X Range:" => "Vùng X đầu vào:", + "Constant is Zero" => "Hằng số bằng 0", + "Confidence Level (%):" => "Mức tin cậy (%):", + "Residuals" => "Phần dư", + "Standardized Residuals" => "Phần dư chuẩn hóa", + "Normal Probability" => "Xác suất chuẩn", + "Interval:" => "Khoảng:", + "Standard Errors" => "Sai số chuẩn", + "Damping factor:" => "Hệ số làm mượt:", + "Hypothesized Mean Difference:" => "Hiệu số trung bình giả thuyết:", + "Set Objective:" => "Đặt mục tiêu:", + "To:" => "Thành:", + "Value Of:" => "Giá trị bằng:", + "By Changing Variable Cells:" => "Bằng cách thay đổi các ô biến số:", + "Subject to the Constraints:" => "Tuân theo các ràng buộc:", + "Make Unconstrained Variables Non-Negative" => "Đặt các biến không ràng buộc là số không âm", + "Select a Solving Method:" => "Chọn phương pháp giải:", + "GRG Nonlinear" => "GRG Phi tuyến", + "Solve" => "Giải", + "Keep Solver Solution" => "Giữ nghiệm Solver", + "Restore Original Values" => "Khôi phục giá trị ban đầu", + "The spelling check is complete for the entire sheet." => "Đã hoàn tất kiểm tra chính tả cho toàn bộ trang tính.", + "Not in Dictionary ({cell}):" => "Không có trong từ điển ({cell}):", + "Suggestions:" => "Gợi ý:", + "(No suggestions)" => "(Không có gợi ý)", + "Ignore Once" => "Bỏ qua một lần", + "Add to Dictionary" => "Thêm vào từ điển", + "Change" => "Đổi", + "Change All" => "Đổi tất cả", + "$ English (United States)" => "$ Tiếng Anh (Hoa Kỳ)", + "Add Chart Element" => "Thêm thành phần biểu đồ", + "Align Left" => "Căn trái", + "Align Right" => "Căn phải", + "Bottom Align" => "Căn dưới", + "Calculate Now (F9)" => "Tính toán ngay (F9)", + "Calculate Sheet (⇧F9)" => "Tính toán trang tính (⇧F9)", + "Calculation Options" => "Tùy chọn tính toán", + "Cell Styles" => "Kiểu ô", + "Change Chart Type" => "Đổi kiểu biểu đồ", + "Check Accessibility" => "Kiểm tra khả năng tiếp cận", + "Clear Filter" => "Xóa bộ lọc", + "Column or Bar" => "Cột hoặc Thanh", + "Comments pane" => "Ngăn nhận xét", + "Convert the last ink stroke to a shape" => "Chuyển nét mực cuối thành hình dạng", + "Convert to Range" => "Chuyển thành vùng", + "Copy" => "Sao chép", + "Custom Sort" => "Sắp xếp tùy chỉnh", + "Cut" => "Cắt", + "Define Name…" => "Đặt tên…", + "Delete Comment" => "Xóa nhận xét", + "Delete Sheet" => "Xóa trang tính", + "Delete chart" => "Xóa biểu đồ", + "Delete…" => "Xóa…", + "Dismiss" => "Đóng", + "Down" => "Xuống", + "Edit chart title" => "Sửa tiêu đề biểu đồ", + "Erase ink strokes" => "Tẩy nét mực", + "Every command run in this session (replayable)" => "Mọi lệnh đã chạy trong phiên này (có thể phát lại)", + "Expand formula bar" => "Mở rộng thanh công thức", + "Filter (⌘⇧F)" => "Bộ lọc (⌘⇧F)", + "Filter by Selected Cell's Value" => "Lọc theo giá trị của ô đã chọn", + "Find & Select" => "Tìm & Chọn", + "Flash Fill (⌘E)" => "Điền nhanh (⌘E)", + "Forecast Sheet" => "Trang tính dự báo", + "Forecast end (date or number; blank: a third of the history):" => "Kết thúc dự báo (ngày hoặc số; để trống: một phần ba lịch sử):", + "Format Chart pane" => "Ngăn Định dạng biểu đồ", + "Format as Table" => "Định dạng thành bảng", + "Hide" => "Ẩn", + "Hide Sheet" => "Ẩn trang tính", + "Hierarchy & more" => "Phân cấp & khác", + "Highlighter" => "Bút tô sáng", + "How agents drive GridCraft (MCP / control channel)" => "Cách tác tử điều khiển GridCraft (MCP / kênh điều khiển)", + "Import a text or CSV file" => "Nhập tệp văn bản hoặc CSV", + "Insert Function" => "Chèn hàm", + "Insert Function (⇧F3)" => "Chèn hàm (⇧F3)", + "Insert Link (⌘K)" => "Chèn liên kết (⌘K)", + "Insert Sheet" => "Chèn trang tính", + "Insert Slicer" => "Chèn bộ cắt lát", + "Insert a picture" => "Chèn hình ảnh", + "Insert a slicer to filter a table" => "Chèn bộ cắt lát để lọc bảng", + "Insert an icon" => "Chèn biểu tượng", + "Insert…" => "Chèn…", + "Line or Area" => "Đường hoặc Miền", + "Link…" => "Liên kết…", + "Macros and scripts in this workbook (Alt+F8)" => "Macro và tập lệnh trong sổ làm việc này (Alt+F8)", + "Middle Align" => "Căn giữa theo chiều dọc", + "More commands" => "Thêm lệnh", + "Move or Copy Sheet…" => "Di chuyển hoặc sao chép trang tính…", + "New sheet (⇧F11)" => "Trang tính mới (⇧F11)", + "Next sheet" => "Trang tính tiếp theo", + "Page Breaks" => "Ngắt trang", + "Paper Size" => "Khổ giấy", + "Paste (⌘V)" => "Dán (⌘V)", + "Pick From Drop-down List…" => "Chọn từ danh sách thả xuống…", + "Pie or Doughnut" => "Tròn hoặc Vành khuyên", + "Previous sheet" => "Trang tính trước", + "Print Area" => "Vùng in", + "Print Titles" => "Tiêu đề in", + "Protect Workbook structure" => "Bảo vệ cấu trúc sổ làm việc", + "Redo (⌘Y)" => "Làm lại (⌘Y)", + "Save (⌘S)" => "Lưu (⌘S)", + "Scatter or Bubble" => "Phân tán hoặc Bong bóng", + "Search and run any command" => "Tìm và chạy bất kỳ lệnh nào", + "Search commands (⌘⇧Space)" => "Tìm lệnh (⌘⇧Space)", + "Select and move ink and shapes" => "Chọn và di chuyển nét mực và hình dạng", + "Series…" => "Chuỗi…", + "Share: export or save a copy" => "Chia sẻ: xuất hoặc lưu bản sao", + "Show Formulas (⌃`)" => "Hiện công thức (⌃`)", + "Slicer" => "Bộ cắt lát", + "Sort & Filter" => "Sắp xếp & Lọc", + "Spelling (F7)" => "Chính tả (F7)", + "Statistic" => "Thống kê", + "Switch Row/Column" => "Đổi hàng/cột", + "Table (⌘T)" => "Bảng (⌘T)", + "Table Styles" => "Kiểu bảng", + "Text to Columns" => "Văn bản thành cột", + "The output range already holds data. Replace it with the report?" => "Vùng đầu ra đã có dữ liệu. Thay thế bằng báo cáo?", + "Top Align" => "Căn trên", + "Undo (⌘Z)" => "Hoàn tác (⌘Z)", + "Undo list" => "Danh sách hoàn tác", + "Unhide Sheet…" => "Hiện trang tính…", + "Up" => "Lên", + "Version, contributors and the AI models that helped" => "Phiên bản, người đóng góp và các mô hình AI đã hỗ trợ", + "What-If Analysis" => "Phân tích giả định", + "Zoom In" => "Phóng to", + "Zoom Out" => "Thu nhỏ", + "Zoom to 100%" => "Thu phóng về 100%", + "Zoom to Selection" => "Thu phóng đến vùng chọn", + "Zoom…" => "Thu phóng…", + "£ English (United Kingdom)" => "£ Tiếng Anh (Vương quốc Anh)", + "¥ Japanese" => "¥ Tiếng Nhật", + "€ Euro" => "€ Euro", + "Tab|Insert" => "Chèn", + "AutoSave" => "Tự động lưu", + "Insert\nSlicer" => "Chèn bộ\ncắt lát", + "Pen\nBlack" => "Bút\nđen", + "Pen\nBlue" => "Bút\nxanh lam", + "Pen\nRed" => "Bút\nđỏ", + "Protect\nSheet" => "Bảo vệ\ntrang tính", + "Watch\nWindow" => "Cửa sổ\ntheo dõi", + "Workbook\nStatistics" => "Thống kê\nsổ làm việc", + // PivotTable Fields pane. + "PivotTable Fields" => "Các trường Bảng tổng hợp", + "Choose fields to add to report:" => "Chọn trường để thêm vào báo cáo:", + "Use a field's menu to move it between areas:" => "Dùng menu của trường để chuyển giữa các vùng:", + "Filters" => "Bộ lọc", + "Values" => "Giá trị", + "Move to Row Labels" => "Chuyển tới Nhãn hàng", + "Move to Column Labels" => "Chuyển tới Nhãn cột", + "Move to Report Filter" => "Chuyển tới Bộ lọc báo cáo", + "Move to Values" => "Chuyển tới Giá trị", + "Summarize by Sum" => "Tổng hợp theo Tổng", + "Summarize by Count" => "Tổng hợp theo Đếm", + "Summarize by Average" => "Tổng hợp theo Trung bình", + "Summarize by Max" => "Tổng hợp theo Lớn nhất", + "Summarize by Min" => "Tổng hợp theo Nhỏ nhất", + "Show as No Calculation" => "Hiển thị không tính toán", + "Show as % of Grand Total" => "Hiển thị theo % tổng chung", + "Show as Running Total" => "Hiển thị theo tổng lũy kế", + "Show as Rank" => "Hiển thị theo thứ hạng", + "Group by Years" => "Nhóm theo năm", + "Group by Quarters" => "Nhóm theo quý", + "Group by Months" => "Nhóm theo tháng", + "Remove Field" => "Gỡ trường", + "Refresh" => "Làm mới", + "Calculated Field…" => "Trường tính toán…", + "Report Layout" => "Bố cục báo cáo", + "Compact" => "Thu gọn", + "Tabular" => "Dạng bảng", + // Print settings, cell styles, conditional formatting, chart types, sheet tab menu & account. + "20% - Accent1" => "20% - Nhấn 1", + "20% - Accent2" => "20% - Nhấn 2", + "20% - Accent3" => "20% - Nhấn 3", + "20% - Accent4" => "20% - Nhấn 4", + "20% - Accent5" => "20% - Nhấn 5", + "20% - Accent6" => "20% - Nhấn 6", + "3 Arrows" => "3 mũi tên", + "3 Symbols" => "3 ký hiệu", + "3 Traffic Lights" => "3 đèn giao thông", + "4 Ratings" => "4 mức xếp hạng", + "40% - Accent1" => "40% - Nhấn 1", + "40% - Accent2" => "40% - Nhấn 2", + "40% - Accent3" => "40% - Nhấn 3", + "40% - Accent4" => "40% - Nhấn 4", + "40% - Accent5" => "40% - Nhấn 5", + "40% - Accent6" => "40% - Nhấn 6", + "5 Arrows" => "5 mũi tên", + "5 Quarters" => "5 phần tư", + "60% - Accent1" => "60% - Nhấn 1", + "60% - Accent2" => "60% - Nhấn 2", + "60% - Accent3" => "60% - Nhấn 3", + "60% - Accent4" => "60% - Nhấn 4", + "60% - Accent5" => "60% - Nhấn 5", + "60% - Accent6" => "60% - Nhấn 6", + "A Date Occurring…" => "Ngày xảy ra…", + "Accent1" => "Nhấn 1", + "Accent2" => "Nhấn 2", + "Accent3" => "Nhấn 3", + "Accent4" => "Nhấn 4", + "Accent5" => "Nhấn 5", + "Accent6" => "Nhấn 6", + "Account" => "Tài khoản", + "All Borders" => "Tất cả viền", + "All sheets" => "Tất cả trang tính", + "Apply" => "Áp dụng", + "Arrow" => "Mũi tên", + "AutoSave: save after every change (workbooks saved to a file)" => "Tự động lưu: lưu sau mỗi thay đổi (sổ làm việc đã lưu vào tệp)", + "Bad" => "Kém", + "Bar" => "Thanh ngang", + "Between…" => "Nằm giữa…", + "Blue" => "Xanh dương", + "Blue - White - Red" => "Xanh dương - Trắng - Đỏ", + "Bottom Border" => "Viền dưới", + "Bottom Double Border" => "Viền đôi dưới", + "Box & Whisker" => "Biểu đồ hộp và râu", + "Bubble" => "Bong bóng", + "Calculation" => "Tính toán", + "Check Cell" => "Ô kiểm tra", + "Clear Rules" => "Xóa quy tắc", + "Column" => "Cột", + "Comma [0]" => "Dấu phẩy [0]", + "Convert to Number" => "Chuyển đổi thành số", + "Copies" => "Số bản sao", + "Currency [0]" => "Tiền tệ [0]", + "Data and Model" => "Dữ liệu và mô hình", + "Drag to fill cells. Drag from inside a cell to select a range." => "Kéo để điền các ô. Kéo từ bên trong ô để chọn một vùng.", + "Duplicate" => "Nhân bản", + "Duplicate Values…" => "Giá trị trùng lặp…", + "End date:" => "Ngày kết thúc:", + "Equal To…" => "Bằng…", + "Error checking options" => "Tùy chọn kiểm tra lỗi", + "Explanatory Text" => "Văn bản giải thích", + "Export as CSV…" => "Xuất thành CSV…", + "Export as PDF…" => "Xuất thành PDF…", + "Export as Web Page (.html)…" => "Xuất thành Trang web (.html)…", + "Finding printers…" => "Đang tìm máy in…", + "Fit selection" => "Vừa với vùng chọn", + "Forecast start (a date or number in the history; blank: after the last point):" => { + "Bắt đầu dự báo (ngày hoặc số trong lịch sử; để trống: sau điểm cuối):" + } + "Format Chart Area…" => "Định dạng vùng biểu đồ…", + "Good" => "Tốt", + "Good, Bad and Neutral" => "Tốt, kém và trung tính", + "Grayscale" => "Thang độ xám", + "Greater Than…" => "Lớn hơn…", + "Green" => "Xanh lá", + "Green - White - Red" => "Xanh lá - Trắng - Đỏ", + "Green - Yellow - Red" => "Xanh lá - Vàng - Đỏ", + "Header (&L left, &C center, &R right; &P page, &N pages, &D date, &A sheet):" => { + "Đầu trang (&L trái, &C giữa, &R phải; &P trang, &N tổng trang, &D ngày, &A trang tính):" + } + "Heading 1" => "Tiêu đề 1", + "Heading 2" => "Tiêu đề 2", + "Heading 3" => "Tiêu đề 3", + "Heading 4" => "Tiêu đề 4", + "Hex" => "Thập lục phân", + "Highlight Cells Rules" => "Quy tắc tô sáng ô", + "Input" => "Đầu vào", + "Insert Link" => "Chèn liên kết", + "Inside Borders" => "Viền trong", + "Left Border" => "Viền trái", + "Less Than…" => "Nhỏ hơn…", + "Licence" => "Giấy phép", + "Light Blue" => "Xanh lam nhạt", + "Linked Cell" => "Ô liên kết", + "Manage Rules…" => "Quản lý quy tắc…", + "More Borders…" => "Thêm đường viền…", + "More Colors…" => "Thêm màu…", + "More Functions…" => "Thêm hàm…", + "Move or Copy…" => "Di chuyển hoặc sao chép…", + "Neutral" => "Trung tính", + "New Rule…" => "Quy tắc mới…", + "New Workbook" => "Sổ làm việc mới", + "No Border" => "Không viền", + "No Color" => "Không màu", + "No Fill" => "Không tô", + "No printers found. Configure a system printer or export a PDF." => "Không tìm thấy máy in. Hãy cấu hình máy in hệ thống hoặc xuất tệp PDF.", + "Note" => "Ghi chú", + "Number Format" => "Định dạng số", + "Number Stored as Text" => "Số được lưu dưới dạng văn bản", + "One-sided" => "In một mặt", + "Options|Editing" => "Chỉnh sửa", + "Orange" => "Cam", + "Output" => "Đầu ra", + "Outside Borders" => "Viền ngoài", + "Oval" => "Hình bầu dục", + "Page Break Preview" => "Xem trước ngắt trang", + "Paste formulas that refer to the copied cells" => "Dán công thức tham chiếu đến các ô đã sao chép", + "Percent" => "Phần trăm", + "Place in Cell" => "Đặt trong ô", + "Place over Cells" => "Đặt đè lên các ô", + "Platform" => "Nền tảng", + "Print failed: the printing worker stopped." => "In thất bại: tiến trình in đã dừng.", + "Print failed: {error}" => "In thất bại: {error}", + "Print job submitted." => "Đã gửi lệnh in.", + "Print job submitted: {receipt}" => "Đã gửi lệnh in: {receipt}", + "Printer" => "Máy in", + "Printer default" => "Mặc định của máy in", + "Printer discovery failed." => "Không thể tìm kiếm máy in.", + "Print…" => "In…", + "Product Information" => "Thông tin sản phẩm", + "Protect workbook for: Structure (sheets can't be added, moved, renamed, hidden or deleted)." => { + "Bảo vệ sổ làm việc cho: Cấu trúc (không thể thêm, di chuyển, đổi tên, ẩn hoặc xóa trang tính)." + } + "Purple" => "Tím", + "Recent Colors" => "Màu dùng gần đây", + "Rectangle" => "Hình chữ nhật", + "Red" => "Đỏ", + "Red - Yellow - Green" => "Đỏ - Vàng - Xanh lá", + "Redo" => "Làm lại", + "Refresh printers" => "Làm mới danh sách máy in", + "Rename" => "Đổi tên", + "Right Border" => "Viền phải", + "Rounded Rectangle" => "Hình chữ nhật bo góc", + "Save As…" => "Lưu thành…", + "Save a Copy as Excel Workbook (.xlsx)…" => "Lưu bản sao dưới dạng Sổ làm việc Excel (.xlsx)…", + "Search" => "Tìm kiếm", + "Search commands" => "Tìm lệnh", + "Select All Sheets" => "Chọn tất cả trang tính", + "Select Data…" => "Chọn dữ liệu…", + "Select a printer" => "Chọn máy in", + "Sort Ascending" => "Sắp xếp tăng dần", + "Sort Descending" => "Sắp xếp giảm dần", + "Source:" => "Nguồn:", + "Standard Colors" => "Màu chuẩn", + "Stock" => "Chứng khoán", + "Submitting print job…" => "Đang gửi lệnh in…", + "Sunburst" => "Biểu đồ vòng đồng tâm", + "Tab Color" => "Màu thẻ trang tính", + "Text that Contains…" => "Văn bản có chứa…", + "Theme Colors" => "Màu chủ đề", + "Themed Cell Styles" => "Kiểu ô theo chủ đề", + "Thick Bottom Border" => "Viền dưới dày", + "Thick Outside Borders" => "Viền ngoài dày", + "Titles and Headings" => "Tiêu đề và đề mục", + "Top Border" => "Viền trên", + "Top and Bottom Border" => "Viền trên và dưới", + "Top and Double Bottom Border" => "Viền trên và viền đôi dưới", + "Top and Thick Bottom Border" => "Viền trên và viền dưới dày", + "Top/Bottom Rules" => "Quy tắc trên/dưới cùng", + "Total" => "Tổng cộng", + "Treemap" => "Biểu đồ bản đồ cây", + "Triangle" => "Hình tam giác", + "Two-sided printing" => "In hai mặt", + "Two-sided: long edge" => "Hai mặt: lật theo cạnh dài", + "Two-sided: short edge" => "Hai mặt: lật theo cạnh ngắn", + "Type to filter…" => "Nhập để lọc…", + "Undo" => "Hoàn tác", + "Unhide…" => "Hiện…", + "Unprotect Sheet…" => "Bỏ bảo vệ trang tính…", + "Version" => "Phiên bản", + "Warning Text" => "Văn bản cảnh báo", + "White - Green" => "Trắng - Xanh lá", + "White - Red" => "Trắng - Đỏ", + "Win/Loss" => "Thắng/Thua", "Record Macro" => "Ghi Macro", - "Stop Recording" => "Dừng Ghi", - "Use Relative References" => "Dùng Tham chiếu Tương đối", + "Stop Recording" => "Dừng ghi", + "Use Relative References" => "Dùng tham chiếu tương đối", "Run\nMacro" => "Chạy Macro", "Macros…" => "Macro…", "Recording" => "Đang ghi", - "Stop" => "Dừng", - "New Macro" => "Macro Mới", + "New Macro" => "Macro mới", "Show" => "Hiện", _ => return None, }) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 39a9b3f91e..4834776038 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -82,11 +82,10 @@ separators, number/date formats, machine translation with agent review, and scri | German | de | 266 (~12%) | no | Latin: yes | no | menus only | 4–8 h | | Italian | it | 971 (~44%) | dialogs, tooltips, pivot pane | Latin: yes | no | menus, File view, dialogs, pivot pane | 3–5 h | | Korean | ko | 266 (~12%) | no | Hangul via the CJK fallback; IME unverified | no | menus only | 6–10 h | -| Vietnamese | vi | 0 (0%) | no | Latin with stacked diacritics: unverified | no | none | 6–10 h | +| Vietnamese | vi | 1,170 (~53%) | dialogs, PivotTable pane and tooltips | Latin with stacked diacritics: unverified | no | menus, File view, dialogs, pivot pane | 2–4 h | | Turkish | tr | 382 (~17%) | no | Latin: yes | yes | menus only | 4–8 h | Other shipped languages: Russian (ru), German (de), Czech (cs), French (fr) and Turkish (tr), menus only. -| Vietnamese | vi | 398 (~18%) | no | Latin with stacked diacritics: unverified | no | menus, File view | 5–9 h | Other shipped languages: Russian (ru) and German (de), 266 labels each (~12%), menus only; Dutch (nl), 518 labels (~24%): ribbon, context menus, File view, dialog titles and the Options page. **Total:** catalog work 10–20 h + languages 92–144 h ≈ **100–165 h**. Parallelizes almost fully @@ -110,6 +109,7 @@ language (none so far) and of localized function names. | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Vietnamese catalog (`i18n/vi.rs`) expanded to 1,170 entries (~53%), covering every key across all catalogs (dialogs, File backstage, PivotTable pane, print settings, cell styles, conditional formatting, chart types, macros, context menus and tooltips; 0 missing in `cargo xtask i18n-report`) | | 2026-10-23 | minor | Missing translations are reported, never a failure: `cargo xtask i18n-report` prints, per language, the strings other catalogs translate and it lacks (plus Spanish function help rows keyed by English the function catalog no longer has) and always passes; `cargo xtask ci` runs it first. Coverage and per-language parity tests and tests of one language's exact wording are gone; UI tests take the expected text from the catalog. Duplicate-key, placeholder, context-prefix and line-shape checks stay | | 2026-10-21 | minor | Romanian interface (`ro`, Română): 970 labels covering every key of the other catalogs (`crates/ui-egui/src/i18n/ro.rs`), `ro-*` system locales, the View-tab switcher and `app.language.set`; context keys show no prefix (File › Options test). English formulas and formats; AI-assisted draft pending native-speaker review | | 2026-10-20 | minor | Japanese: furigana (`rPh` phonetic runs and `` in `xl/sharedStrings.xml`) is no longer deleted by an open + save; it is kept on the workbook and written back (a `` without runs is kept too, while duplicate texts with different readings keep only the first, reported on open). Display of the readings is still missing (`crates/xlsx/src/tests/phonetic_tests.rs`) | From 5f4f5ce4c55cde30b63c17386288905e587b8218 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:43:58 -0600 Subject: [PATCH 09/25] Count Excel text limits in UTF-16 units --- crates/calc/src/tests.rs | 5 ++++- crates/core/src/value.rs | 28 +++++++++++++++++++++------- crates/engine/src/cmd/edit/tests.rs | 6 ++++++ crates/functions/src/text.rs | 12 +++++++++--- crates/functions/src/util.rs | 6 +++--- 5 files changed, 43 insertions(+), 14 deletions(-) diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 136f91e9e7..0149609545 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2320,7 +2320,10 @@ fn concat_operator_cuts_at_the_cell_limit() { t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))"); t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")"); t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))"); - assert_eq!((t.num("A1"), t.num("A2"), t.num("A3")), (32767.0, 32767.0, 32767.0)); + t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")"); + t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))"); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16383.0)); + assert_eq!(t.get("A5"), Value::Error(CellError::Value)); } /// Makes `at` a Python cell showing `cached` (its value before this calculation), with `result` diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index 994d8f0c6a..7c045a749a 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -412,20 +412,24 @@ pub fn sci_text(n: f64, sig: usize) -> String { format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) } -/// Longest text a cell can hold, in characters. +/// Longest text a cell can hold, in UTF-16 code units. pub const MAX_TEXT_CHARS: usize = 32_767; -/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. +/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value. pub fn cap_text(mut s: String) -> String { - if s.len() > MAX_TEXT_CHARS - && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) - { - s.truncate(i); + if s.len() > MAX_TEXT_CHARS { + let mut units = 0; + if let Some((i, _)) = s.char_indices().find(|(_, c)| { + units += c.len_utf16(); + units > MAX_TEXT_CHARS + }) { + s.truncate(i); + } } s } -/// `v` with text cut to [`MAX_TEXT_CHARS`] characters; other values pass through. +/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through. pub fn cap_value(v: Value) -> Value { match v { Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())), @@ -478,6 +482,16 @@ mod tests { assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater); } + #[test] + fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() { + let face = "😀"; + assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS)); + assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS)); + assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)); + assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1)); + assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383)); + } + #[test] fn errors() { for e in CellError::ALL { diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 2e9457cb12..57eb5a121b 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -143,6 +143,8 @@ fn cell_set_cuts_text_to_32767_characters() { } assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767)); assert_eq!(get(&mut s, "A2"), json!(32767.0)); + s.execute("cell.set", json!({"cell": "D1", "input": "😀".repeat(16_384)})).unwrap(); + assert_eq!(get(&mut s, "D1").as_str().map(|t| t.encode_utf16().count()), Some(32_766)); } #[test] @@ -210,6 +212,10 @@ fn set_values_can_store_strings_as_the_text_they_are() { s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap(); let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count())); assert_eq!(len.flatten(), Some(32_767)); + s.execute("range.setValues", json!({"range": "B10", "parse": false, "values": [["😀".repeat(16_384)]]})).unwrap(); + let emoji_len = + s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("B10").unwrap()).map(|c| c.value.as_text().map(|t| t.encode_utf16().count())); + assert_eq!(emoji_len.flatten(), Some(32_766)); assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo")); let d = s.doc().unwrap(); let sh = d.wb.active().unwrap(); diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index efd4cd310a..227124efb1 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -20,7 +20,7 @@ fn chars(s: &str) -> Vec { } fn check_len(s: String) -> R { - if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT { + if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT { return Err(CellError::Value); } text_val(s) @@ -49,7 +49,7 @@ fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { } fn check_calc(s: String) -> R { - if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT { + if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT { return Err(CellError::Calc); } text_val(s) @@ -234,7 +234,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R { return Err(CellError::Value); } let n = n.trunc(); - let total = s.chars().count() as f64 * n; + let total = s.encode_utf16().count() as f64 * n; if total > MAX_TEXT as f64 { return Err(CellError::Value); } @@ -1149,6 +1149,12 @@ mod tests { // An error after the cut still propagates. let big = || t(&"x".repeat(32_767)); is_err(ev("CONCATENATE", vec![big(), big(), big(), big(), big(), e(CellError::NA)]), CellError::NA); + let emoji = "😀"; + is_err(ev("CONCAT", vec![t(&emoji.repeat(16_384))]), CellError::Calc); + is_err(ev("TEXTJOIN", vec![t(""), b(false), t(&emoji.repeat(16_384))]), CellError::Calc); + assert_eq!(ev("CONCATENATE", vec![t(&emoji.repeat(16_384))]), Value::text(emoji.repeat(16_383))); + is_err(ev("REPT", vec![t(emoji), n(16_384.0)]), CellError::Value); + assert_eq!(ev("REPT", vec![t(emoji), n(16_383.0)]), Value::text(emoji.repeat(16_383))); // Lifting: CONCATENATE over an array. assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]); } diff --git a/crates/functions/src/util.rs b/crates/functions/src/util.rs index 14c6279370..4db1c94320 100644 --- a/crates/functions/src/util.rs +++ b/crates/functions/src/util.rs @@ -11,7 +11,7 @@ pub(crate) type R = Result; /// Largest array a function may build. pub(crate) const MAX_CELLS: usize = 10_000_000; -/// Longest text a cell can hold. +/// Longest text a cell can hold, in UTF-16 code units. pub(crate) const MAX_TEXT: usize = 32_767; /// Scalar-position lifting tables. @@ -20,11 +20,11 @@ pub(crate) const S: &[bool] = &[true]; pub(crate) const A: &[bool] = &[false]; /// Turns an implementation result into a cell value: errors become error values, non-finite -/// numbers become `#NUM!`, text longer than 32,767 characters becomes `#VALUE!`. +/// numbers become `#NUM!`, text longer than 32,767 UTF-16 code units becomes `#VALUE!`. pub(crate) fn finish(r: R) -> Value { match r { Ok(Value::Number(n)) => Value::number(n), - Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.chars().count() > MAX_TEXT => Value::Error(CellError::Value), + Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.encode_utf16().count() > MAX_TEXT => Value::Error(CellError::Value), Ok(v) => v, Err(e) => Value::Error(e), } From 1ac75eb85810f3649385439de60600c9b1edb974 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:59:43 -0600 Subject: [PATCH 10/25] Correct Unicode concat boundary expectation --- crates/calc/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 0149609545..ed4176759d 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2322,7 +2322,7 @@ fn concat_operator_cuts_at_the_cell_limit() { t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))"); t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")"); t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))"); - assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16383.0)); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0)); assert_eq!(t.get("A5"), Value::Error(CellError::Value)); } From 30f24fd2399b32ce3180cbd52e5e50ce840c3f54 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:05:00 -0600 Subject: [PATCH 11/25] Pass series index to chart table lookup --- crates/chart/src/render/table.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index f0839dcfef..4f641afd25 100644 --- a/crates/chart/src/render/table.rs +++ b/crates/chart/src/render/table.rs @@ -70,7 +70,7 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay let y = top + (layout.headers as f32 + i as f32 + 0.5) * layout.row_height; let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; if settings.show_keys { - let swatch = match plot_kind(chart, series) { + let swatch = match plot_kind(chart, series, i) { ChartKind::Line | ChartKind::LineStacked => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, _ => Swatch::Box, From 28086016fe2743e1f42db5634d40cd67d84e7944 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:21:43 -0500 Subject: [PATCH 12/25] i18n: Paste Special's Add and Text to Columns' Comma get their own keys "Add" is both a Paste Special operation and the Solver's Add button, and "Comma" both the Text to Columns delimiter and the Comma cell style. One translation can't fit both (Spanish Excel: Sumar vs Agregar, Coma vs Millares), and open PRs are about to translate the Solver button and the cell-style gallery. The two dialog options now use `Paste Special|Add` and `Text to Columns|Comma`; English shows the same labels and every catalog carries its current translation onto the new key, so nothing visible changes. A test checks both. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 10 ++++++++-- crates/ui-egui/src/i18n.rs | 17 +++++++++++++++++ crates/ui-egui/src/i18n/el.rs | 2 ++ crates/ui-egui/src/i18n/it.rs | 2 ++ crates/ui-egui/src/i18n/ja.rs | 2 ++ crates/ui-egui/src/i18n/pl.rs | 2 ++ crates/ui-egui/src/i18n/pt.rs | 2 ++ crates/ui-egui/src/i18n/ro.rs | 2 ++ crates/ui-egui/src/i18n/uk.rs | 2 ++ docs/localization-parity.md | 3 ++- 10 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 47b215302e..2513c1e112 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -506,7 +506,13 @@ impl Dialog { Choice { key: "operation", label: "Operation", - options: vec![("none", "None"), ("add", "Add"), ("subtract", "Subtract"), ("multiply", "Multiply"), ("divide", "Divide")], + options: vec![ + ("none", "None"), + ("add", "Paste Special|Add"), + ("subtract", "Subtract"), + ("multiply", "Multiply"), + ("divide", "Divide"), + ], }, Check { key: "skipBlanks", label: "Skip blanks" }, Check { key: "transpose", label: "Transpose (E)" }, @@ -648,7 +654,7 @@ impl Dialog { vec![ Check { key: "tab", label: "Tab" }, Check { key: "semicolon", label: "Semicolon" }, - Check { key: "comma", label: "Comma" }, + Check { key: "comma", label: "Text to Columns|Comma" }, Check { key: "space", label: "Space" }, Text { key: "other", label: "Other:" }, Check { key: "treatConsecutive", label: "Treat consecutive delimiters as one" }, diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 0ffd0ad09c..6e4b7c052b 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -418,6 +418,23 @@ mod tests { } } + #[test] + fn paste_special_add_and_text_to_columns_comma_have_their_own_keys() { + // "Add" is also the Solver button and "Comma" also the cell style (Spanish Excel: Sumar + // vs Agregar, Coma vs Millares), so the two dialog options are keyed by context. English + // shows the plain label, and every catalog shows what it showed before the split. + for (keyed, plain) in [("Paste Special|Add", "Add"), ("Text to Columns|Comma", "Comma")] { + assert_eq!(Language::En.tr(keyed), plain); + for language in Language::ALL { + let shown = language.tr(keyed); + assert!(!shown.contains('|'), "{} shows a context prefix for {keyed}: {shown}", language.code()); + if language.tr(plain) != plain { + assert_eq!(shown, language.tr(plain), "{}: {keyed}", language.code()); + } + } + } + } + #[test] fn translations_never_show_the_context_prefix() { // `tr` returns a found translation as it is, so a catalog that keeps `context|` in its diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 2a7449fd66..d30bd20e09 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -667,6 +667,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Values and number formats" => "Τιμές και μορφές αριθμών", "Operation" => "Πράξη", "Add" => "Πρόσθεση", + "Paste Special|Add" => "Πρόσθεση", "Subtract" => "Αφαίρεση", "Multiply" => "Πολλαπλασιασμός", "Divide" => "Διαίρεση", @@ -704,6 +705,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Tab" => "Στηλοθέτης", "Semicolon" => "Ερωτηματικό (;)", "Comma" => "Κόμμα", + "Text to Columns|Comma" => "Κόμμα", "Space" => "Διάστημα", "Other:" => "Άλλο:", "Treat consecutive delimiters as one" => "Αντιμετώπιση διαδοχικών διαχωριστικών ως ενός", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 24fa45c959..631c7cf070 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -549,6 +549,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Values and number formats" => "Valori e formati numero", "Operation" => "Operazione", "Add" => "Aggiungi", + "Paste Special|Add" => "Aggiungi", "Subtract" => "Sottrai", "Multiply" => "Moltiplica", "Divide" => "Dividi", @@ -588,6 +589,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Tab" => "Tabulazione", "Semicolon" => "Punto e virgola", "Comma" => "Virgola", + "Text to Columns|Comma" => "Virgola", "Space" => "Spazio", "Other:" => "Altro:", "Treat consecutive delimiters as one" => "Considera delimitatori consecutivi come uno solo", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index a659da7442..d6fb4352db 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -566,6 +566,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Values and number formats", "値と数値の書式"), ("Operation", "演算"), ("Add", "加算"), + ("Paste Special|Add", "加算"), ("Subtract", "減算"), ("Multiply", "乗算"), ("Divide", "除算"), @@ -605,6 +606,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Tab", "タブ"), ("Semicolon", "セミコロン"), ("Comma", "コンマ"), + ("Text to Columns|Comma", "コンマ"), ("Space", "スペース"), ("Other:", "その他:"), ("Treat consecutive delimiters as one", "連続した区切り文字は 1 文字として扱う"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index d232a6e0de..279bb1e576 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -540,6 +540,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Values and number formats" => "Wartości i formaty liczb", "Operation" => "Operacja", "Add" => "Dodaj", + "Paste Special|Add" => "Dodaj", "Subtract" => "Odejmij", "Multiply" => "Pomnóż", "Divide" => "Podziel", @@ -579,6 +580,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Tab" => "Tabulator", "Semicolon" => "Średnik", "Comma" => "Przecinek", + "Text to Columns|Comma" => "Przecinek", "Space" => "Spacja", "Other:" => "Inny:", "Treat consecutive delimiters as one" => "Traktuj kolejne ograniczniki jako jeden", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index d930543099..4f6c0f4f77 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -574,6 +574,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Values and number formats" => "Valores e formatos de número", "Operation" => "Operação", "Add" => "Adicionar", + "Paste Special|Add" => "Adicionar", "Subtract" => "Subtrair", "Multiply" => "Multiplicar", "Divide" => "Dividir", @@ -613,6 +614,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Tab" => "Tabulação", "Semicolon" => "Ponto e vírgula", "Comma" => "Vírgula", + "Text to Columns|Comma" => "Vírgula", "Space" => "Espaço", "Other:" => "Outros:", "Treat consecutive delimiters as one" => "Considerar delimitadores consecutivos como um só", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 0876ac50f5..f2c7395cba 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -546,6 +546,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Values and number formats" => "Valori și formate de număr", "Operation" => "Operație", "Add" => "Adăugare", + "Paste Special|Add" => "Adăugare", "Subtract" => "Scădere", "Multiply" => "Înmulțire", "Divide" => "Împărțire", @@ -585,6 +586,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Tab" => "Tab", "Semicolon" => "Punct și virgulă", "Comma" => "Virgulă", + "Text to Columns|Comma" => "Virgulă", "Space" => "Spațiu", "Other:" => "Altele:", "Treat consecutive delimiters as one" => "Delimitatorii consecutivi se tratează ca unul singur", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 4374cc1359..53cd57f76c 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -544,6 +544,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Values and number formats" => "Values and number formats", "Operation" => "Operation", "Add" => "Add", + "Paste Special|Add" => "Add", "Subtract" => "Subtract", "Multiply" => "Multiply", "Divide" => "Divide", @@ -583,6 +584,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Tab" => "Tab", "Semicolon" => "Semicolon", "Comma" => "Comma", + "Text to Columns|Comma" => "Comma", "Space" => "Space", "Other:" => "Other:", "Treat consecutive delimiters as one" => "Treat consecutive delimiters as one", diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 1de2927ac6..eef37d88af 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (Paste Special's Add and Text to Columns' Comma get their own keys); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Per-language status against Excel, which ships its UI in dozens of languages (Windows language packs cover 100+), with localized function names, argument separators, number and date formats, @@ -140,6 +140,7 @@ language (none so far) and of localized function names. | 2026-10-26 | minor | Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work | | 2026-10-27 | minor | Number formats honour the `B1`/`B2` calendar prefixes: never shown; `B2` renders year, month, day and Arabic month and weekday names in the tabular Hijri calendar (1 Jan 2001 = 6 Shawwal 1421; leap years 2, 5, 7, 10, 13, 15, 18, 21, 24, 26 and 29 of the 30-year cycle, which is what Excel shows). Checked against Excel 16.0 (build 20527, en-US) on every serial and about 1,700 format/value pairs: a locale or currency tag before `B2` keeps the date Gregorian, a misplaced `B` and digit or a prefix before a number format is rejected, serial 60 has no Hijri date, serial 0 shows as serial 1, two-word month names use a no-break space. Not matched: Excel's weekday/month-name mix-ups in one `B2` section and its weekday-only quirks | | 2026-10-27 | minor | AutoFit column width, wrapped-row height and PivotTable column fit estimate Arabic letters at ~0.48 em (measured 0.36–0.53 em shaped, Noto Sans/Naskh Arabic and DejaVu Sans) instead of 1 em, Arabic-Indic digits as wide as ASCII digits, and give vowel marks and direction marks no width; vowelled Arabic no longer fits ~3.5× too wide | +| 2026-10-26 | minor | Paste Special's Add operation and Text to Columns' Comma delimiter are keyed `Paste Special|Add` and `Text to Columns|Comma`, so they can be translated apart from the Solver's Add button and the Comma cell style (Spanish: Sumar vs Agregar, Coma vs Millares); every catalog keeps the text it showed | | 2026-10-23 | minor | Missing translations are reported, never a failure: `cargo xtask i18n-report` prints, per language, the strings other catalogs translate and it lacks (plus Spanish function help rows keyed by English the function catalog no longer has) and always passes; `cargo xtask ci` runs it first. Coverage and per-language parity tests and tests of one language's exact wording are gone; UI tests take the expected text from the catalog. Duplicate-key, placeholder, context-prefix and line-shape checks stay | | 2026-10-21 | minor | Romanian interface (`ro`, Română): 970 labels covering every key of the other catalogs (`crates/ui-egui/src/i18n/ro.rs`), `ro-*` system locales, the View-tab switcher and `app.language.set`; context keys show no prefix (File › Options test). English formulas and formats; AI-assisted draft pending native-speaker review | | 2026-10-20 | minor | Japanese: furigana (`rPh` phonetic runs and `` in `xl/sharedStrings.xml`) is no longer deleted by an open + save; it is kept on the workbook and written back (a `` without runs is kept too, while duplicate texts with different readings keep only the first, reported on open). Display of the readings is still missing (`crates/xlsx/src/tests/phonetic_tests.rs`) | From ad7ec8d775166adb622ccd36879ab56123c06d65 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:23:49 -0500 Subject: [PATCH 13/25] i18n: the key-split test lets a catalog translate the two uses differently The test required `Paste Special|Add` and `Text to Columns|Comma` to show the same text as the plain keys, which forbids the very split it guards (Spanish: Sumar vs Agregar). It now checks that a catalog translating the plain label also translates the keyed one. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n.rs | 5 +++-- docs/localization-parity.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 6e4b7c052b..4453a14465 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -422,14 +422,15 @@ mod tests { fn paste_special_add_and_text_to_columns_comma_have_their_own_keys() { // "Add" is also the Solver button and "Comma" also the cell style (Spanish Excel: Sumar // vs Agregar, Coma vs Millares), so the two dialog options are keyed by context. English - // shows the plain label, and every catalog shows what it showed before the split. + // shows the plain label, and a catalog that translates the plain label translates the + // keyed one too, so the dialog option doesn't fall back to English. for (keyed, plain) in [("Paste Special|Add", "Add"), ("Text to Columns|Comma", "Comma")] { assert_eq!(Language::En.tr(keyed), plain); for language in Language::ALL { let shown = language.tr(keyed); assert!(!shown.contains('|'), "{} shows a context prefix for {keyed}: {shown}", language.code()); if language.tr(plain) != plain { - assert_eq!(shown, language.tr(plain), "{}: {keyed}", language.code()); + assert_ne!(shown, plain, "{} translates {plain:?} but not {keyed:?}", language.code()); } } } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index eef37d88af..759c813e1c 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -140,7 +140,7 @@ language (none so far) and of localized function names. | 2026-10-26 | minor | Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work | | 2026-10-27 | minor | Number formats honour the `B1`/`B2` calendar prefixes: never shown; `B2` renders year, month, day and Arabic month and weekday names in the tabular Hijri calendar (1 Jan 2001 = 6 Shawwal 1421; leap years 2, 5, 7, 10, 13, 15, 18, 21, 24, 26 and 29 of the 30-year cycle, which is what Excel shows). Checked against Excel 16.0 (build 20527, en-US) on every serial and about 1,700 format/value pairs: a locale or currency tag before `B2` keeps the date Gregorian, a misplaced `B` and digit or a prefix before a number format is rejected, serial 60 has no Hijri date, serial 0 shows as serial 1, two-word month names use a no-break space. Not matched: Excel's weekday/month-name mix-ups in one `B2` section and its weekday-only quirks | | 2026-10-27 | minor | AutoFit column width, wrapped-row height and PivotTable column fit estimate Arabic letters at ~0.48 em (measured 0.36–0.53 em shaped, Noto Sans/Naskh Arabic and DejaVu Sans) instead of 1 em, Arabic-Indic digits as wide as ASCII digits, and give vowel marks and direction marks no width; vowelled Arabic no longer fits ~3.5× too wide | -| 2026-10-26 | minor | Paste Special's Add operation and Text to Columns' Comma delimiter are keyed `Paste Special|Add` and `Text to Columns|Comma`, so they can be translated apart from the Solver's Add button and the Comma cell style (Spanish: Sumar vs Agregar, Coma vs Millares); every catalog keeps the text it showed | +| 2026-10-26 | minor | Paste Special's Add operation and Text to Columns' Comma delimiter are keyed `Paste Special\|Add` and `Text to Columns\|Comma`, so they can be translated apart from the Solver's Add button and the Comma cell style (Spanish: Sumar vs Agregar, Coma vs Millares); every catalog keeps the text it showed | | 2026-10-23 | minor | Missing translations are reported, never a failure: `cargo xtask i18n-report` prints, per language, the strings other catalogs translate and it lacks (plus Spanish function help rows keyed by English the function catalog no longer has) and always passes; `cargo xtask ci` runs it first. Coverage and per-language parity tests and tests of one language's exact wording are gone; UI tests take the expected text from the catalog. Duplicate-key, placeholder, context-prefix and line-shape checks stay | | 2026-10-21 | minor | Romanian interface (`ro`, Română): 970 labels covering every key of the other catalogs (`crates/ui-egui/src/i18n/ro.rs`), `ro-*` system locales, the View-tab switcher and `app.language.set`; context keys show no prefix (File › Options test). English formulas and formats; AI-assisted draft pending native-speaker review | | 2026-10-20 | minor | Japanese: furigana (`rPh` phonetic runs and `` in `xl/sharedStrings.xml`) is no longer deleted by an open + save; it is kept on the workbook and written back (a `` without runs is kept too, while duplicate texts with different readings keep only the first, reported on open). Display of the readings is still missing (`crates/xlsx/src/tests/phonetic_tests.rs`) | From b98a7c43de25b452568daeab39e20fb640217fa9 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:29:36 -0500 Subject: [PATCH 14/25] cargo xtask bench: calculation benchmarks on fixed in-code workbooks Ten scenarios (crates/engine/examples/bench.rs, replacing the ad-hoc perf example) build their workbooks in code, warm up, and time edits, formula entry, Calculate Now, sort and XLSX save/open through Session::execute, checking each result so a scenario that stops recalculating fails instead of getting fast. A failed scenario is reported and the rest still run. `cargo xtask bench` runs them in release, writes /bench/latest.json and compares with a baseline saved by --save. Baseline (M2 Pro, 100k rows): a 100k-dependent edit recalculates in 90-106 ms; 100 whole-column SUMIFS take ~0.5 s per edit. xlsx.open fails on main: the #2413 element cap drops the last ~9,000 rows of the 100k-row model on reopen (fixed by #2527). Parity docs, gaps and roadmap carry the measured numbers. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/engine/examples/bench.rs | 327 ++++++++++++++++++++++++++++++++ crates/engine/examples/perf.rs | 60 ------ docs/egui-037-migration-plan.md | 4 +- docs/gaps.md | 11 +- docs/roadmap.md | 6 +- docs/target-app-parity.md | 20 +- xtask/Cargo.toml | 2 +- xtask/src/bench.rs | 103 ++++++++++ xtask/src/main.rs | 5 + 10 files changed, 468 insertions(+), 74 deletions(-) create mode 100644 crates/engine/examples/bench.rs delete mode 100644 crates/engine/examples/perf.rs create mode 100644 xtask/src/bench.rs diff --git a/ROADMAP.md b/ROADMAP.md index fd27ee9eb6..4605110467 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (`cargo xtask bench`: measured recalc baselines; earlier: CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -151,6 +151,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged | | 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority | | 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks | +| 2026-10-26 | `cargo xtask bench`: ten fixed in-code workbooks (100k rows) time edits, formula entry, Calculate Now, sort and XLSX save/open, check their results and compare with a saved baseline. On an M2 Pro a 100k-dependent edit recalculates in 90–106 ms and 300k formulas in 395–455 ms | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | @@ -288,6 +289,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles | | 2026-10-26 | minor | Progress log: Arabic bidi display and editing | | 2026-10-26 | minor | Progress log: Arabic font fallback | +| 2026-10-26 | minor | Progress log: `cargo xtask bench` | | 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column | | 2026-10-24 | minor | Macro interface on the Automate tab; progress log row | | 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row | diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs new file mode 100644 index 0000000000..c07872ea9c --- /dev/null +++ b/crates/engine/examples/bench.rs @@ -0,0 +1,327 @@ +//! Calculation benchmarks on fixed workbooks built in code (release build). Run through +//! `cargo xtask bench`, which builds this in release and compares against a saved baseline, or +//! directly: `cargo run --release -p gridcraft-engine --example bench -- [--quick] [--rows N] +//! [--reps N] [--filter NAME] [--json PATH]`. +//! +//! Every scenario builds its workbook untimed, runs one warm-up, then times `reps` runs of one +//! operation through `Session::execute` (so a timing includes what an edit costs the user: undo +//! history, graph update and recalculation). Results are checked so a scenario that silently +//! stopped recalculating fails instead of getting fast. + +#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it + +use std::time::{Duration, Instant}; + +use gridcraft_core::{CellRef, Value}; +use gridcraft_engine::Session; +use serde_json::{Value as Json, json}; + +struct Cfg { + rows: usize, + reps: usize, + filter: Option, +} + +struct Outcome { + name: &'static str, + what: String, + times: Vec, + cells: usize, +} + +type R = Result; + +fn main() -> std::process::ExitCode { + match run() { + Ok(()) => std::process::ExitCode::SUCCESS, + Err(e) => { + eprintln!("bench: {e}"); + std::process::ExitCode::FAILURE + } + } +} + +fn run() -> R<()> { + let args: Vec = std::env::args().skip(1).collect(); + let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned(); + let quick = args.iter().any(|a| a == "--quick"); + let cfg = Cfg { + rows: flag("--rows").and_then(|s| s.parse().ok()).unwrap_or(if quick { 10_000 } else { 100_000 }).max(200), + reps: flag("--reps").and_then(|s| s.parse().ok()).unwrap_or(if quick { 3 } else { 7 }).max(1), + filter: flag("--filter"), + }; + let scenarios: [(&'static str, fn(&Cfg) -> R); 10] = [ + ("edit.chain", edit_chain), + ("edit.fanout", edit_fanout), + ("edit.sliding", edit_sliding), + ("edit.sumifs", edit_sumifs), + ("edit.lookup", edit_lookup), + ("enter.formulas", enter_formulas), + ("recalc.full", recalc_full), + ("data.sort", data_sort), + ("xlsx.save", xlsx_save), + ("xlsx.open", xlsx_open), + ]; + println!("GridCraft calc bench: {} rows, {} reps (median / min)\n", cfg.rows, cfg.reps); + println!("{:<16} {:>10} {:>10} {:>9} workload", "scenario", "median", "min", "cells"); + let mut results = Vec::new(); + // A failed scenario is reported and the others still run, so one regression doesn't hide + // the numbers for everything else. + let mut failed = Vec::new(); + for (name, f) in scenarios { + if cfg.filter.as_deref().is_some_and(|p| !name.contains(p)) { + continue; + } + let o = match f(&cfg) { + Ok(o) => o, + Err(e) => { + println!("{name:<16} {:>10} {e}", "FAILED"); + failed.push(name); + continue; + } + }; + let (med, min) = stats(&o.times); + let cells = if o.cells == 0 { "-".to_string() } else { o.cells.to_string() }; + println!("{:<16} {:>10} {:>10} {:>9} {}", o.name, ms(med), ms(min), cells, o.what); + results.push(json!({"name": o.name, "what": o.what, "median_ms": med, "min_ms": min, "cells": o.cells})); + } + if let Some(path) = flag("--json") { + let out = json!({"rows": cfg.rows, "reps": cfg.reps, "results": results, "failed": failed}); + let text = serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?; + std::fs::write(&path, text).map_err(|e| format!("{path}: {e}"))?; + } + if failed.is_empty() { Ok(()) } else { Err(format!("{} scenario(s) failed: {}", failed.len(), failed.join(", "))) } +} + +fn stats(times: &[Duration]) -> (f64, f64) { + let mut v: Vec = times.iter().map(|d| d.as_secs_f64() * 1000.0).collect(); + v.sort_by(f64::total_cmp); + let med = v.get(v.len() / 2).copied().unwrap_or(0.0); + (med, v.first().copied().unwrap_or(0.0)) +} + +fn ms(v: f64) -> String { + if v >= 100.0 { format!("{v:.0} ms") } else { format!("{v:.2} ms") } +} + +fn exec(s: &mut Session, cmd: &str, p: Json) -> R { + s.execute(cmd, p).map_err(|e| format!("{cmd}: {e}")) +} + +fn session() -> R { + let mut s = Session::new(); + s.new_workbook(); + Ok(s) +} + +/// Writes `rows` rows starting at `col` row 1, `make(i)` giving row i (0-based), in chunks. +fn fill(s: &mut Session, col: &str, rows: usize, make: impl Fn(usize) -> Json) -> R<()> { + let chunk = 10_000; + let mut r = 0; + while r < rows { + let n = chunk.min(rows - r); + let vals: Vec = (r..r + n).map(&make).collect(); + exec(s, "range.setValues", json!({"range": format!("{col}{}", r + 1), "values": vals}))?; + r += n; + } + Ok(()) +} + +fn num(s: &Session, at: &str) -> R { + let c = CellRef::parse(at).ok_or_else(|| format!("bad ref {at}"))?; + let d = s.doc().map_err(|e| e.to_string())?; + match d.wb.sheet(0).map(|sh| sh.value(c)) { + Some(Value::Number(n)) => Ok(n), + other => Err(format!("{at} = {other:?}, expected a number")), + } +} + +fn expect(s: &Session, at: &str, want: f64) -> R<()> { + let got = num(s, at)?; + if (got - want).abs() <= 1e-6 * want.abs().max(1.0) { Ok(()) } else { Err(format!("{at} = {got}, expected {want}")) } +} + +fn recalc_cells(s: &Session) -> usize { + s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0) +} + +/// Runs a warm-up then `reps` timed calls of `op(rep)`, then `check(rep)` (untimed) after each. +fn time( + cfg: &Cfg, + s: &mut Session, + mut op: impl FnMut(&mut Session, usize) -> R<()>, + check: impl Fn(&Session, usize) -> R<()>, +) -> R<(Vec, usize)> { + let mut times = Vec::with_capacity(cfg.reps); + let mut cells = 0; + for rep in 0..=cfg.reps { + let t = Instant::now(); + op(s, rep)?; + let dt = t.elapsed(); + check(s, rep)?; + cells = recalc_cells(s); + if rep > 0 { + times.push(dt); + } + } + Ok((times, cells)) +} + +/// Value typed into A1 on rep `r`: alternates so every rep changes something. +fn a1(r: usize) -> f64 { + (r % 2 + 2) as f64 +} + +/// A running sum `B[n] = B[n-1] + A[n]`: one edit at the top recalculates a dependency chain +/// `rows` deep. +fn edit_chain(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = session()?; + fill(&mut s, "A", n, |_| json!([1]))?; + fill(&mut s, "B", n, |i| json!([if i == 0 { "=A1".to_string() } else { format!("=B{i}+A{}", i + 1) }]))?; + let (times, cells) = time( + cfg, + &mut s, + |s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop), + |s, r| expect(s, &format!("B{n}"), (n - 1) as f64 + a1(r)), + )?; + Ok(Outcome { name: "edit.chain", what: format!("edit A1 under a {n}-deep running sum"), times, cells }) +} + +/// `rows` formulas that each read `$A$1`: one edit, a wide and shallow dirty set. +fn edit_fanout(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = session()?; + exec(&mut s, "cell.set", json!({"cell": "A1", "input": "1"}))?; + fill(&mut s, "B", n, |i| json!([format!("=$A$1*{}", i + 1)]))?; + let (times, cells) = time( + cfg, + &mut s, + |s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop), + |s, r| expect(s, &format!("B{n}"), a1(r) * n as f64), + )?; + Ok(Outcome { name: "edit.fanout", what: format!("edit $A$1 read by {n} formulas"), times, cells }) +} + +/// `rows` overlapping 100-row window sums; an edit in the middle dirties ~100 of them, so this +/// measures the range index lookup, not evaluation. +fn edit_sliding(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = session()?; + fill(&mut s, "A", n + 99, |_| json!([1]))?; + fill(&mut s, "B", n, |i| json!([format!("=SUM(A{}:A{})", i + 1, i + 100)]))?; + let mid = n / 2; + let (times, cells) = time( + cfg, + &mut s, + |s, r| exec(s, "cell.set", json!({"cell": format!("A{mid}"), "input": a1(r).to_string()})).map(drop), + |s, r| expect(s, &format!("B{mid}"), 99.0 + a1(r)), + )?; + Ok(Outcome { name: "edit.sliding", what: format!("edit one cell under {n} 100-row SUM windows"), times, cells }) +} + +/// 100 whole-column SUMIFS over `rows` rows of data, all dirtied by one data edit. +fn edit_sumifs(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = session()?; + fill(&mut s, "A", n, |i| json!([1, (i % 100) as f64]))?; + fill(&mut s, "D", 100, |k| json!([format!("=SUMIFS(A:A,B:B,{k})")]))?; + let per = (n / 100) as f64; + let (times, cells) = time( + cfg, + &mut s, + |s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop), + |s, r| expect(s, "D1", per - 1.0 + a1(r)), + )?; + Ok(Outcome { name: "edit.sumifs", what: format!("edit data under 100 SUMIFS(A:A,B:B,k) over {n} rows"), times, cells }) +} + +/// 100 exact-match XLOOKUPs over whole columns of `rows` keys, all dirtied by one key edit. +fn edit_lookup(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = session()?; + fill(&mut s, "A", n, |i| json!([(i + 1) as f64, (2 * (i + 1)) as f64]))?; + let step = n / 100; + fill(&mut s, "D", 100, |k| json!([format!("=XLOOKUP({},A:A,B:B)", (k + 1) * step)]))?; + let (times, cells) = time( + cfg, + &mut s, + // A1's key alternates between 1 and -1, so A:A changes but the lookups' answers don't. + |s, r| exec(s, "cell.set", json!({"cell": "A1", "input": if r % 2 == 0 { "-1" } else { "1" }})).map(drop), + |s, _| expect(s, "D100", (2 * n) as f64), + )?; + Ok(Outcome { name: "edit.lookup", what: format!("edit a key under 100 XLOOKUPs over {n} rows"), times, cells }) +} + +/// Entering `rows` formulas in one command: parse, graph insertion and first evaluation. +fn enter_formulas(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = session()?; + fill(&mut s, "A", n, |i| json!([(i % 97) as f64]))?; + let vals: Vec = (0..n).map(|i| json!([format!("=A{}*2+1", i + 1)])).collect(); + let (times, cells) = time( + cfg, + &mut s, + |s, _| exec(s, "range.setValues", json!({"range": "B1", "values": vals})).map(drop), + |s, _| expect(s, &format!("B{n}"), ((n - 1) % 97) as f64 * 2.0 + 1.0), + )?; + Ok(Outcome { name: "enter.formulas", what: format!("enter {n} formulas =An*2+1 in one paste"), times, cells }) +} + +/// A model with 3 formulas per row (arithmetic and a row SUM), recalculated in full. +fn model(n: usize) -> R { + let mut s = session()?; + fill(&mut s, "A", n, |i| json!([(i % 97) as f64, format!("=A{}*2", i + 1), format!("=B{0}+A{0}", i + 1), format!("=SUM(A{0}:C{0})", i + 1)]))?; + Ok(s) +} + +fn recalc_full(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = model(n)?; + let last = ((n - 1) % 97) as f64 * 6.0; + let (times, cells) = time(cfg, &mut s, |s, _| exec(s, "formulas.calculateNow", json!({})).map(drop), |s, _| expect(s, &format!("D{n}"), last))?; + Ok(Outcome { name: "recalc.full", what: format!("Calculate Now, {} formulas (3 per row)", 3 * n), times, cells }) +} + +fn data_sort(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = session()?; + fill(&mut s, "A", n, |i| json!([format!("Item {i}"), (i % 97) as f64, ((i * 7919) % 1000) as f64]))?; + let (times, _) = time( + cfg, + &mut s, + |s, r| { + let cmd = if r % 2 == 0 { "data.sortDescending" } else { "data.sortAscending" }; + exec(s, cmd, json!({"range": format!("A1:C{n}"), "column": "B"})).map(drop) + }, + |s, r| expect(s, "B1", if r % 2 == 0 { 96.0 } else { 0.0 }), + )?; + // A sort with no formulas recalculates nothing; 0 shows as "-". + Ok(Outcome { name: "data.sort", what: format!("sort {n} rows x 3 columns by a numeric key"), times, cells: 0 }) +} + +fn save_bytes(s: &mut Session) -> R { + let r = exec(s, "file.saveBytes", json!({"format": "xlsx"}))?; + r.get("base64").and_then(Json::as_str).map(str::to_string).ok_or_else(|| "file.saveBytes: no base64".to_string()) +} + +fn xlsx_save(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = model(n)?; + let (times, _) = time(cfg, &mut s, |s, _| save_bytes(s).map(drop), |_, _| Ok(()))?; + Ok(Outcome { name: "xlsx.save", what: format!("save the {n}-row model as XLSX"), times, cells: 0 }) +} + +fn xlsx_open(cfg: &Cfg) -> R { + let n = cfg.rows; + let mut s = model(n)?; + let b64 = save_bytes(&mut s)?; + let last = ((n - 1) % 97) as f64 * 6.0; + let (times, cells) = time( + cfg, + &mut s, + |s, _| exec(s, "file.open", json!({"name": "bench.xlsx", "base64": b64})).map(drop), + |s, _| expect(s, &format!("D{n}"), last), + )?; + Ok(Outcome { name: "xlsx.open", what: format!("open the {n}-row model from XLSX (with full recalc)"), times, cells }) +} diff --git a/crates/engine/examples/perf.rs b/crates/engine/examples/perf.rs deleted file mode 100644 index 61ecf56269..0000000000 --- a/crates/engine/examples/perf.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Performance scenarios on large workbooks (release build): -//! `cargo run --release -p gridcraft-engine --example perf -- [rows]` - -#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it - -use std::time::Instant; - -use gridcraft_engine::Session; -use serde_json::json; - -fn main() { - let rows: usize = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(100_000); - let mut s = Session::new(); - s.new_workbook(); - // Data: rows × 6 numeric columns, built through range.setValues in chunks. - let t = Instant::now(); - let chunk = 10_000; - let mut r = 0; - while r < rows { - let n = chunk.min(rows - r); - let vals: Vec = (0..n) - .map(|i| json!([format!("Item {}", r + i), (r + i) as f64, ((r + i) % 97) as f64, ((r + i) % 13) as f64 * 1.5, 1.0, 2.0])) - .collect(); - s.execute("range.setValues", json!({"range": format!("A{}", r + 1), "values": vals})).expect("set"); - r += n; - } - println!("fill {rows}x6 values: {:?}", t.elapsed()); - // Formulas: G = B*C+D, H = running sum of G (chain). - let t = Instant::now(); - s.execute("cell.set", json!({"cell": "G1", "input": "=B1*C1+D1"})).expect("g1"); - s.execute("edit.autoFill", json!({"source": "G1", "target": format!("G1:G{rows}")})).expect("fill g"); - println!("fill {rows} formulas G=B*C+D: {:?}", t.elapsed()); - let t = Instant::now(); - s.execute("cell.set", json!({"cell": "H1", "input": "=G1"})).expect("h1"); - s.execute("cell.set", json!({"cell": "H2", "input": "=H1+G2"})).expect("h2"); - s.execute("edit.autoFill", json!({"source": "H2", "target": format!("H2:H{rows}")})).expect("fill h"); - println!("fill {rows} chained running-sum formulas: {:?}", t.elapsed()); - let t = Instant::now(); - s.execute("cell.set", json!({"cell": "J1", "input": format!("=SUM(G1:G{rows})")})).expect("sum"); - s.execute("cell.set", json!({"cell": "J2", "input": "=SUMIFS(B:B,C:C,\">50\")"})).expect("sumifs"); - s.execute("cell.set", json!({"cell": "J3", "input": "=XLOOKUP(\"Item 77777\",A:A,B:B)"})).expect("xlookup"); - println!("aggregate formulas: {:?}", t.elapsed()); - // Edit at the top: everything below recalculates. - let t = Instant::now(); - s.execute("cell.set", json!({"cell": "B1", "input": "5"})).expect("edit"); - println!("edit B1 → recalc {} cells: {:?}", s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0), t.elapsed()); - let t = Instant::now(); - s.execute("data.sortDescending", json!({"range": format!("A1:F{rows}"), "column": "C"})).expect("sort"); - println!("sort {rows} rows: {:?}", t.elapsed()); - let t = Instant::now(); - let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).expect("save"); - let b64 = r["base64"].as_str().unwrap_or("").to_string(); - println!("save xlsx ({} bytes): {:?}", r["bytes"], t.elapsed()); - let t = Instant::now(); - s.execute("file.open", json!({"name": "big.xlsx", "base64": b64})).expect("open"); - println!("open xlsx + full recalc: {:?}", t.elapsed()); - let t = Instant::now(); - s.execute("edit.undo", json!({})).ok(); - println!("undo: {:?}", t.elapsed()); -} diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md index 2f59c863f5..12199a1cc6 100644 --- a/docs/egui-037-migration-plan.md +++ b/docs/egui-037-migration-plan.md @@ -1013,8 +1013,8 @@ Fixtures are built in code and never committed as large binaries: - `Session::new()` + `file.new {sample: "sales"|"budget"|"grades"}` for the three samples. - A 100,000-row × 6-column workbook built through `range.setValues` in 10,000-row chunks, plus - formulas `G=B*C+D`, a chained running sum, `SUM`/`SUMIFS`/`XLOOKUP` and a sort, mirroring - `crates/engine/examples/perf.rs`. + formulas `G=B*C+D`, a chained running sum, `SUM`/`SUMIFS`/`XLOOKUP` and a sort, like the + workloads in `crates/engine/examples/bench.rs` (`cargo xtask bench`). - A two-sheet workbook with a formula being pointed across sheets, a right-to-left sheet, frozen panes, merged cells, a table, a chart, comments/notes, validation and a cell picture. - Password-protected and corrupt-font fixtures through `gridcraft-xlsx`'s `test-support` feature diff --git a/docs/gaps.md b/docs/gaps.md index d2c89d86af..842136e369 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-02 · **Change:** minor (§17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** minor (`cargo xtask bench`: measured recalc baselines; earlier: §17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365) Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open @@ -26,9 +26,11 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- - **Estimate:** 15–25 h, plus owner time in Excel. [file-format-parity.md](file-format-parity.md) ### 2. Large workbooks don't open; recalc is single-threaded (P, H) -- **Missing:** streaming read for ~100 MB XLSX; multi-threaded recalc; 100k-dependent edit under - 100 ms (was ~0.4 s); whole-sheet operations bounded. -- **Evidence:** #175; no threading in `crates/calc`; PR #152 (whole-sheet Fill/Remove Duplicates +- **Missing:** streaming read for ~100 MB XLSX; multi-threaded recalc; faster whole-column + SUMIFS and lookups (100 of either over 100k rows take 0.16–0.59 s per edit); whole-sheet + operations bounded. A 100k-dependent edit measures 90–106 ms, around the 100 ms target + (`cargo xtask bench`). +- **Evidence:** #175; `cargo xtask bench`; no threading in `crates/calc`; PR #152 (whole-sheet Fill/Remove Duplicates out of memory), PR #151 (current region past 10,000 rows). - **Impact:** finance and data users routinely have big workbooks. - **Estimate:** 25–40 h. [target-app-parity.md](target-app-parity.md#performance), [hardware-parity.md](hardware-parity.md) @@ -202,6 +204,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | 2026-10-31 | minor | §13: Solver Load/Save Model (`data.solverSaveModel`, `data.solverLoadModel`) and Reset All (`data.solverReset`), with buttons in the Solver Parameters dialog | | 2026-10-26 | minor | Arabic shared bidi display/editing and persisted cell reading direction; other script and PDF work remain separate | | 2026-10-26 | minor | §5: Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work | +| 2026-10-26 | minor | #2: measured with `cargo xtask bench`; 100k-dependent edit around 100 ms, whole-column SUMIFS/XLOOKUP added | | 2026-10-24 | minor | §8: PivotTable Enable show details: `pivot.options` `enableShowDetails` turns Show Details off for a PivotTable, read and written in XLSX as `enableDrill` | | 2026-10-23 | minor | §8: PivotTable Show Details: double-clicking a value cell lists its source records on a new sheet (#2364) | | 2026-10-22 | minor | §20: a native window per workbook window, New Window on the same workbook and Arrange All on the desktop; left: Arrange All across monitors, the web's one window, pen pressure (estimate 10–14 h → 5–8 h) | diff --git a/docs/roadmap.md b/docs/roadmap.md index 458af936af..8c0d279dbb 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap detail -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (test command) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (`cargo xtask bench`: measured recalc baselines) · **Target:** Microsoft Excel (Microsoft 365) Forward-looking plan. The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); numbers and method are in @@ -107,12 +107,14 @@ to check our files, and Windows machines with the reported GPU drivers. - Function coverage: the script method in [function-parity.md](function-parity.md). A `cargo xtask functions` that diffs the registry against a checked-in Excel name list would make it a CI number (1–2 h). -- No `cargo xtask scorecard` or `bench` yet. +- `cargo xtask bench`: recalc, entry, sort and XLSX timings on fixed in-code workbooks, compared + with a local baseline (`--save`). No `cargo xtask scorecard` yet. ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Measuring: `cargo xtask bench` | | 2026-10-23 | minor | Measuring: tests run through `cargo xtask test` | | 2026-10-11 | minor | PivotTable calculated fields landed | | 2026-10-10 | minor | Current focus and M15 updated for the 10-10 merges | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a2243bc92b..2fe7226942 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: GridCraft vs Microsoft Excel -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-02 · **Change:** minor (form controls; catalog 281 / 296; earlier: insert objects: equations; earlier: what-if and analysis: Solver Sensitivity report; no score change; earlier: chart resizing no longer listed as missing; no score change; earlier: what-if and analysis: Analysis ToolPak has all 19 tools; earlier: page layout and print: Page Setup's page order; no score change; earlier: charts: data tables with XLSX round-trip and print/PDF; no score change; earlier: what-if and analysis: Solver Options; the Insert Function dialog is named as in Excel; no score change; earlier: Solver Load/Save Model and Reset All; automation: macro interface; catalog count 276 / 292, as `cargo xtask parity` measures; automation: typed macros in the engine; several windows: a native window per workbook window, New Window on the same workbook, Arrange All; no score change) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** minor (`cargo xtask bench`: measured recalc baselines; earlier: form controls; catalog 281 / 296; earlier: insert objects: equations; earlier: what-if and analysis: Solver Sensitivity report; no score change; earlier: chart resizing no longer listed as missing; no score change; earlier: what-if and analysis: Analysis ToolPak has all 19 tools; earlier: page layout and print: Page Setup's page order; no score change; earlier: charts: data tables with XLSX round-trip and print/PDF; no score change; earlier: what-if and analysis: Solver Options; the Insert Function dialog is named as in Excel; no score change; earlier: Solver Load/Save Model and Reset All; automation: macro interface; catalog count 276 / 292, as `cargo xtask parity` measures; automation: typed macros in the engine; several windows: a native window per workbook window, New Window on the same workbook, Arrange All; no score change) · **Target:** Microsoft Excel (Microsoft 365) This is the authoritative parity assessment. [`ROADMAP.md`](../ROADMAP.md) summarizes it, [`gaps.md`](gaps.md) lists every shortfall, and the area checklists hold the detail: @@ -203,14 +203,26 @@ Excel recalculates on every core (multi-threaded recalculation), streams large f |---|---|---|---| | Sheet size limits | 1,048,576 × 16,384 | same | measured (`crates/core/src/addr.rs`) | | Recalc threads | 1 | all cores | measured (no threading in `crates/calc`) | -| Edit → recalc, 100k dependents | ~0.4 s (2026-10-07), target < 100 ms | tens of ms | measured on the owner's machine; #66 since made range-formula recalc linear, not re-timed | +| Edit → recalc, 100k-deep chain | 90–106 ms (target < 100 ms) | tens of ms | measured (`cargo xtask bench`, `edit.chain`) | +| Edit → recalc, 100k formulas reading one cell | 71–87 ms | tens of ms | measured (`edit.fanout`) | +| Edit → 100 whole-column SUMIFS / XLOOKUP over 100k rows | 420–590 ms / 160–250 ms | not measured | measured (`edit.sumifs`, `edit.lookup`) | +| Calculate Now, 300k formulas | 395–455 ms | not measured | measured (`recalc.full`) | +| Save the 100k-row model (300k formulas) as XLSX | ~530 ms | not measured | measured (`xlsx.save`) | +| Reopen that file | drops the last ~9,000 rows (element cap from #2413; fix in PR #2527, then ~1.3 s with full recalc) | opens | measured (`xlsx.open`) | | Grid scrolling | virtualised, O(log n) geometry with custom row heights | smooth | measured in code | | Open a ~100 MB XLSX | fails (#175) | opens | user report | | Whole-sheet operations | Fill and Remove Duplicates on a whole-sheet selection run out of memory or time (fix in PR #152) | fine | open PR | Work: streaming XLSX reader with shared-string and style dedup, multi-threaded recalc of independent chains (native only; WASM stays single-threaded), whole-column reference -clamping, a `cargo xtask bench` with fixed workbooks so the numbers become measured. +clamping, and faster whole-column SUMIFS and lookups (each formula rescans the column on every +edit). + +Benchmarks: `cargo xtask bench` builds ten fixed workbooks in code, times each operation through +`Session::execute` (median of 7 after a warm-up, results checked) and compares with a baseline +saved by `--save`. The numbers above are ranges over several runs on an Apple M2 Pro, release +build, 100,000 rows, 2026-10-26; recalculation is single-threaded, so core count doesn't change +them. ## Platforms @@ -327,7 +339,6 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land - Pixel comparison against Excel screenshots (planned; screenshots stay in `plan/excel/`). - Function results against Excel-computed oracles (a corpus repo is the planned home). -- Recalc and open-time benchmarks on fixed workbooks (no `cargo xtask bench` yet). - Whether Excel opens our XLSX output without repair, across features. ## Revision history @@ -344,6 +355,7 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land | 2026-10-31 | minor | The Insert Function dialog is named as in Excel (it was called Formula Builder); no score change | | 2026-10-31 | minor | What-if and analysis: Solver Options (no score change) | | 2026-10-31 | minor | What-if and analysis: Solver Load/Save Model and Reset All; Forecast Sheet moved from Missing to the list of tools, as gaps.md §13 records (no score change) | +| 2026-10-26 | minor | Performance: `cargo xtask bench` measures recalc, entry, sort and XLSX save/open on fixed in-code workbooks; the 100k-dependent edit is 90–106 ms (was ~0.4 s, an old timing), around the 100 ms target for simple formulas; a 100k-row model doesn't reopen whole until PR #2527 lands (no score change) | | 2026-10-25 | minor | Automation: macro interface (Automate › Macros, the Macros and Record Macro dialogs, the step editor, shortcuts) (no score change) | | 2026-10-25 | trivial | Catalog count 276 / 292 in the summary table and the method, as `cargo xtask parity` measures (no score change) | | 2026-10-22 | minor | Several windows on the desktop: a native window per workbook window, New Window on the same workbook, Switch Windows and Arrange All; "one window" removed from UI/UX fidelity, Hardware and the interaction-fidelity discount; no score change | diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index c40c976973..7e62711d9d 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true license.workspace = true publish = false -description = "GridCraft workspace tooling: cargo xtask ci | layers | assets | wasm | parity | i18n-report | version | stats | ico" +description = "GridCraft workspace tooling: cargo xtask ci | layers | assets | wasm | parity | i18n-report | bench | version | stats | ico" [lints] workspace = true diff --git a/xtask/src/bench.rs b/xtask/src/bench.rs new file mode 100644 index 0000000000..42f2d54397 --- /dev/null +++ b/xtask/src/bench.rs @@ -0,0 +1,103 @@ +//! `cargo xtask bench`: runs the calculation benchmarks (`crates/engine/examples/bench.rs`) in a +//! release build, writes the results to `/bench/latest.json` and compares them with a +//! baseline (`/bench/baseline.json` unless `--baseline PATH`). `--save` makes this run +//! the baseline. Timings are machine-specific, so baselines stay in the target directory; the +//! reference numbers in docs/target-app-parity.md name the machine they came from. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +/// Flags passed through to the bench binary (the others are xtask's own). +const PASS: [&str; 3] = ["--rows", "--reps", "--filter"]; + +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let target = std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from).unwrap_or_else(|| root.join("target")); + let dir = target.join("bench"); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let latest = dir.join("latest.json"); + let mut baseline = dir.join("baseline.json"); + let mut save = false; + let mut pass: Vec = Vec::new(); + let mut it = args.iter(); + while let Some(&a) = it.next() { + match a { + "--save" => save = true, + "--quick" => pass.push(a.into()), + "--baseline" => baseline = it.next().map(PathBuf::from).ok_or("--baseline needs a path")?, + _ if PASS.contains(&a) => { + let v = it.next().ok_or_else(|| format!("{a} needs a value"))?; + pass.extend([a.to_string(), v.to_string()]); + } + other => return Err(format!("bench: unknown flag `{other}`")), + } + } + let mut cmd = crate::cargo(); + cmd.args(["run", "--release", "--quiet", "-p", "gridcraft-engine", "--example", "bench", "--"]).args(&pass).arg("--json").arg(&latest); + // A stale file from an earlier run must not pass for this one's results. + let _ = std::fs::remove_file(&latest); + // The bench exits non-zero when a scenario fails but still writes the others' results: + // compare those, then report the failure. + let status = crate::run(cmd, "cargo run --release -p gridcraft-engine --example bench"); + let now = match read(&latest) { + Ok(v) => v, + Err(e) => return status.and(Err(e)), + }; + if save && status.is_err() { + return status.map_err(|e| format!("{e}\nnot saved as the baseline: a scenario failed")); + } + if save { + std::fs::copy(&latest, &baseline).map_err(|e| format!("{}: {e}", baseline.display()))?; + println!("\nSaved as the baseline: {}", baseline.display()); + return Ok(()); + } + match read(&baseline) { + Ok(base) => compare(&base, &now), + Err(_) => println!("\nNo baseline at {} (run `cargo xtask bench --save` to make one).", baseline.display()), + } + status +} + +fn read(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) +} + +fn results(v: &Value) -> Vec<(String, f64)> { + v.get("results") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|r| Some((r.get("name")?.as_str()?.to_string(), r.get("median_ms")?.as_f64()?))).collect()) + .unwrap_or_default() +} + +/// Prints the median change per scenario; a different row count makes the numbers incomparable. +fn compare(base: &Value, now: &Value) { + if base.get("rows") != now.get("rows") { + println!("\nBaseline was run with {} rows, this run with {}: not compared.", base["rows"], now["rows"]); + return; + } + let old = results(base); + println!("\nAgainst the baseline (median):"); + for (name, ms) in results(now) { + match old.iter().find(|(n, _)| *n == name) { + Some((_, was)) if *was > 0.0 => { + let pct = (ms - was) / was * 100.0; + println!(" {name:<16} {was:>10.2} ms -> {ms:>10.2} ms {pct:+6.1}%"); + } + _ => println!(" {name:<16} {:>13} -> {ms:>10.2} ms", "new"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn reads_results() { + let v = json!({"rows": 10, "results": [{"name": "edit.chain", "median_ms": 1.5}, {"name": "bad"}]}); + assert_eq!(results(&v), vec![("edit.chain".to_string(), 1.5)]); + assert!(results(&json!({})).is_empty()); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fe54b0f4e8..26e3a77708 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -6,6 +6,7 @@ #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] mod assets; +mod bench; mod i18n_report; mod ico; mod keytips; @@ -36,6 +37,9 @@ commands: regenerate crates/ui-egui/src/keytips/generated.rs from keytips.json (--check: fail if stale) version [set X.Y.Z[-pre]] print or set the workspace version ([workspace.package] in Cargo.toml) + bench [--quick] [--rows N] [--reps N] [--filter NAME] [--save] [--baseline PATH] + release-build calculation benchmarks on fixed in-code workbooks; compares + with /bench/baseline.json (--save: make this run the baseline) stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) ico ... pack square PNGs (<= 256 px) into a Windows .ico (see packaging/icons.sh) @@ -51,6 +55,7 @@ fn main() -> ExitCode { Some("wasm") => cmd_wasm(), Some("test") => cmd_test().and_then(|()| cmd_doctest()), Some("ci") => cmd_ci(), + Some("bench") => bench::run(&root(), &rest), Some("stats") => stats::run(&root(), rest.contains(&"--exact")), Some("parity") => parity::run(&root(), &rest), Some("keytips") => keytips::run(&root(), &rest), From 815627264fbfd20fcae4d7a048c491237d51a436 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:06:29 -0500 Subject: [PATCH 15/25] bench: address review (empty filter, row-count-exact checks, fresh formula entry) - A --filter that selects no scenario is an error, so --save can't write an empty baseline. - edit.sumifs and edit.lookup derive their expected values from the rows actually generated, so any --rows passes. - edit.lookup edits the key of a checked lookup (XLOOKUP falls back to 0 when it is gone), so a lookup that stops recalculating fails the check. - enter.formulas clears B1:Bn untimed before each run, so it times entry into empty cells, not an overwrite of the previous run's formulas. - xtask: a relative CARGO_TARGET_DIR resolves against the workspace root, as cargo does for the bench; an existing baseline that doesn't parse is an error instead of "no baseline". Co-Authored-By: Claude Opus 5.5 --- crates/engine/examples/bench.rs | 45 +++++++++++++++++++++++++-------- xtask/src/bench.rs | 12 ++++++--- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index c07872ea9c..731d5c6830 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -68,10 +68,12 @@ fn run() -> R<()> { // A failed scenario is reported and the others still run, so one regression doesn't hide // the numbers for everything else. let mut failed = Vec::new(); - for (name, f) in scenarios { - if cfg.filter.as_deref().is_some_and(|p| !name.contains(p)) { - continue; - } + let selected: Vec<_> = scenarios.into_iter().filter(|(name, _)| cfg.filter.as_deref().is_none_or(|p| name.contains(p))).collect(); + if selected.is_empty() { + // An empty run would otherwise save as a baseline with nothing in it. + return Err(format!("--filter {} matches no scenario", cfg.filter.as_deref().unwrap_or(""))); + } + for (name, f) in selected { let o = match f(&cfg) { Ok(o) => o, Err(e) => { @@ -149,12 +151,24 @@ fn recalc_cells(s: &Session) -> usize { fn time( cfg: &Cfg, s: &mut Session, + op: impl FnMut(&mut Session, usize) -> R<()>, + check: impl Fn(&Session, usize) -> R<()>, +) -> R<(Vec, usize)> { + time_prepared(cfg, s, |_| Ok(()), op, check) +} + +/// [`time`] with `prep` run (untimed) before each call, to put back the state `op` starts from. +fn time_prepared( + cfg: &Cfg, + s: &mut Session, + mut prep: impl FnMut(&mut Session) -> R<()>, mut op: impl FnMut(&mut Session, usize) -> R<()>, check: impl Fn(&Session, usize) -> R<()>, ) -> R<(Vec, usize)> { let mut times = Vec::with_capacity(cfg.reps); let mut cells = 0; for rep in 0..=cfg.reps { + prep(s)?; let t = Instant::now(); op(s, rep)?; let dt = t.elapsed(); @@ -226,7 +240,8 @@ fn edit_sumifs(cfg: &Cfg) -> R { let mut s = session()?; fill(&mut s, "A", n, |i| json!([1, (i % 100) as f64]))?; fill(&mut s, "D", 100, |k| json!([format!("=SUMIFS(A:A,B:B,{k})")]))?; - let per = (n / 100) as f64; + // Rows whose category is 0 (i % 100 == 0), A1 among them. + let per = n.div_ceil(100) as f64; let (times, cells) = time( cfg, &mut s, @@ -242,13 +257,21 @@ fn edit_lookup(cfg: &Cfg) -> R { let mut s = session()?; fill(&mut s, "A", n, |i| json!([(i + 1) as f64, (2 * (i + 1)) as f64]))?; let step = n / 100; - fill(&mut s, "D", 100, |k| json!([format!("=XLOOKUP({},A:A,B:B)", (k + 1) * step)]))?; + fill(&mut s, "D", 100, |k| json!([format!("=XLOOKUP({},A:A,B:B,0)", (k + 1) * step)]))?; + let last = (2 * 100 * step) as f64; let (times, cells) = time( cfg, &mut s, - // A1's key alternates between 1 and -1, so A:A changes but the lookups' answers don't. - |s, r| exec(s, "cell.set", json!({"cell": "A1", "input": if r % 2 == 0 { "-1" } else { "1" }})).map(drop), - |s, _| expect(s, "D100", (2 * n) as f64), + // D1 looks up the key in A{step}: removing it (-step) makes D1 fall back to 0, putting it + // back finds it again. Every lookup reads A:A, so all 100 recalculate either way. + |s, r| { + let key = if r % 2 == 0 { format!("-{step}") } else { step.to_string() }; + exec(s, "cell.set", json!({"cell": format!("A{step}"), "input": key})).map(drop) + }, + |s, r| { + expect(s, "D1", if r % 2 == 0 { 0.0 } else { (2 * step) as f64 })?; + expect(s, "D100", last) + }, )?; Ok(Outcome { name: "edit.lookup", what: format!("edit a key under 100 XLOOKUPs over {n} rows"), times, cells }) } @@ -259,9 +282,11 @@ fn enter_formulas(cfg: &Cfg) -> R { let mut s = session()?; fill(&mut s, "A", n, |i| json!([(i % 97) as f64]))?; let vals: Vec = (0..n).map(|i| json!([format!("=A{}*2+1", i + 1)])).collect(); - let (times, cells) = time( + let (times, cells) = time_prepared( cfg, &mut s, + // Each run enters the formulas into empty cells, not over the previous run's. + |s| exec(s, "edit.clearAll", json!({"range": format!("B1:B{n}")})).map(drop), |s, _| exec(s, "range.setValues", json!({"range": "B1", "values": vals})).map(drop), |s, _| expect(s, &format!("B{n}"), ((n - 1) % 97) as f64 * 2.0 + 1.0), )?; diff --git a/xtask/src/bench.rs b/xtask/src/bench.rs index 42f2d54397..4030f8e19f 100644 --- a/xtask/src/bench.rs +++ b/xtask/src/bench.rs @@ -12,7 +12,9 @@ use serde_json::Value; const PASS: [&str; 3] = ["--rows", "--reps", "--filter"]; pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { - let target = std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from).unwrap_or_else(|| root.join("target")); + // Cargo resolves a relative CARGO_TARGET_DIR against the directory it runs in, which for the + // bench is the workspace root; resolve it the same way here. + let target = std::env::var_os("CARGO_TARGET_DIR").map(|d| root.join(d)).unwrap_or_else(|| root.join("target")); let dir = target.join("bench"); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; let latest = dir.join("latest.json"); @@ -51,9 +53,11 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { println!("\nSaved as the baseline: {}", baseline.display()); return Ok(()); } - match read(&baseline) { - Ok(base) => compare(&base, &now), - Err(_) => println!("\nNo baseline at {} (run `cargo xtask bench --save` to make one).", baseline.display()), + if baseline.exists() { + // A baseline that is there but unreadable is an error, not a missing one. + compare(&read(&baseline)?, &now); + } else { + println!("\nNo baseline at {} (run `cargo xtask bench --save` to make one).", baseline.display()); } status } From a4aee78391ad310b66ba539931198c9276bf2c00 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:39:25 -0500 Subject: [PATCH 16/25] M-perf: bench: Scenario type alias (clippy type_complexity) Co-Authored-By: Claude Opus 5.5 --- crates/engine/examples/bench.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 731d5c6830..2011f1ce1a 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -30,6 +30,8 @@ struct Outcome { } type R = Result; +/// A scenario: its name and the function that runs it. +type Scenario = (&'static str, fn(&Cfg) -> R); fn main() -> std::process::ExitCode { match run() { @@ -50,7 +52,7 @@ fn run() -> R<()> { reps: flag("--reps").and_then(|s| s.parse().ok()).unwrap_or(if quick { 3 } else { 7 }).max(1), filter: flag("--filter"), }; - let scenarios: [(&'static str, fn(&Cfg) -> R); 10] = [ + let scenarios: [Scenario; 10] = [ ("edit.chain", edit_chain), ("edit.fanout", edit_fanout), ("edit.sliding", edit_sliding), From f17f730887c21e3c45e93cb2778f4eb0410f1fb4 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:51:26 -0500 Subject: [PATCH 17/25] M-perf: bench: median of an even count averages the middle two Co-Authored-By: Claude Opus 5.5 --- crates/engine/examples/bench.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 2011f1ce1a..9c8f96aabb 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -100,7 +100,13 @@ fn run() -> R<()> { fn stats(times: &[Duration]) -> (f64, f64) { let mut v: Vec = times.iter().map(|d| d.as_secs_f64() * 1000.0).collect(); v.sort_by(f64::total_cmp); - let med = v.get(v.len() / 2).copied().unwrap_or(0.0); + // An even count averages the two middle samples. + let mid = v.len() / 2; + let med = match (v.len() % 2, v.get(mid.wrapping_sub(1)), v.get(mid)) { + (0, Some(a), Some(b)) => (a + b) / 2.0, + (_, _, Some(m)) => *m, + _ => 0.0, + }; (med, v.first().copied().unwrap_or(0.0)) } From d56e3638fdd41289e56573c2384cfcb617834de4 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:05:22 -0500 Subject: [PATCH 18/25] M-perf: bench: recalc.full recalculates a stale result; malformed --rows/--reps is an error Co-Authored-By: Claude Opus 5.5 --- crates/engine/examples/bench.rs | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 9c8f96aabb..e17d949752 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -48,8 +48,8 @@ fn run() -> R<()> { let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned(); let quick = args.iter().any(|a| a == "--quick"); let cfg = Cfg { - rows: flag("--rows").and_then(|s| s.parse().ok()).unwrap_or(if quick { 10_000 } else { 100_000 }).max(200), - reps: flag("--reps").and_then(|s| s.parse().ok()).unwrap_or(if quick { 3 } else { 7 }).max(1), + rows: count(flag("--rows"), "--rows")?.unwrap_or(if quick { 10_000 } else { 100_000 }).max(200), + reps: count(flag("--reps"), "--reps")?.unwrap_or(if quick { 3 } else { 7 }).max(1), filter: flag("--filter"), }; let scenarios: [Scenario; 10] = [ @@ -118,6 +118,11 @@ fn exec(s: &mut Session, cmd: &str, p: Json) -> R { s.execute(cmd, p).map_err(|e| format!("{cmd}: {e}")) } +/// A count flag's value; one that isn't a number is an error, not the default. +fn count(v: Option, name: &str) -> R> { + v.map(|s| s.parse().map_err(|_| format!("{name}: `{s}` is not a count"))).transpose() +} + fn session() -> R { let mut s = Session::new(); s.new_workbook(); @@ -311,8 +316,20 @@ fn model(n: usize) -> R { fn recalc_full(cfg: &Cfg) -> R { let n = cfg.rows; let mut s = model(n)?; - let last = ((n - 1) % 97) as f64 * 6.0; - let (times, cells) = time(cfg, &mut s, |s, _| exec(s, "formulas.calculateNow", json!({})).map(drop), |s, _| expect(s, &format!("D{n}"), last))?; + // Manual calculation, and A[n] changed (untimed) before each run, so D[n] is stale until + // Calculate Now recalculates: a Calculate Now that did nothing fails the check. + exec(&mut s, "formulas.calculationOptions", json!({"mode": "manual"}))?; + let mut rep = 0; + let (times, cells) = time_prepared( + cfg, + &mut s, + |s| { + rep += 1; + exec(s, "cell.set", json!({"cell": format!("A{n}"), "input": (100 + rep).to_string()})).map(drop) + }, + |s, _| exec(s, "formulas.calculateNow", json!({})).map(drop), + |s, r| expect(s, &format!("D{n}"), (101 + r) as f64 * 6.0), + )?; Ok(Outcome { name: "recalc.full", what: format!("Calculate Now, {} formulas (3 per row)", 3 * n), times, cells }) } From 35996c6e2ea6e0c0ebe25e1784b32ef6247a492b Mon Sep 17 00:00:00 2001 From: David Ardila Date: Mon, 9 Nov 2026 21:44:01 -0600 Subject: [PATCH 19/25] M-perf: bench: the egui 0.37 plan's Recalc scene points at cargo xtask bench, not the removed perf example Co-Authored-By: Claude Opus 5.5 --- docs/egui-037-migration-plan.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md index 12199a1cc6..39a76f3550 100644 --- a/docs/egui-037-migration-plan.md +++ b/docs/egui-037-migration-plan.md @@ -1111,7 +1111,7 @@ Never report compile duration as UI performance. | Startup | fresh process → first painted frame / control channel ready | wall time, split font setup, wgpu renderer creation, first frame | | Grid scroll | `sales`/100k-row synthetic workbook, 1,000 frames of vertical/horizontal scroll | frame distribution, `grid_ms`, tessellation time, vertices/indices, uploads | | Cell edit | type/commit 1,000 cells via control channel | command latency, frame CPU, undo memory | -| Recalc | `crates/engine/examples/perf` on the same workbook | engine-only latency, recalc cell count (not a UI number) | +| Recalc | `cargo xtask bench` (`crates/engine/examples/bench.rs`, fixed in-code workbooks; `recalc.full` and the edit scenarios) | engine-only latency, recalc cell count (not a UI number) | | Dialog/ribbon | open/close Format Cells, switch tabs, type filter | CPU frame time, paint counts | | Text tessellation | fixed 120-ASCII-label scene + mixed color-glyph row | per-tessellate time/instructions; reproduce #8731 | | Fonts | 20 cold starts with the same font set | discovery/build/set_fonts time, peak RSS | From f32fefddcf6961da5bc101090dfac4154542e006 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:34:22 -0600 Subject: [PATCH 20/25] Tables never hold merged cells, which Excel removes the table for on open A table with a merged cell in it opened in Excel with the repair prompt, and Excel removed the table and its AutoFilter ("Removed Feature: Table from /xl/tables/table1.xml"). GridCraft let merged cells into a table four ways; each now does what Excel does: - Merge Cells, Merge & Center and Merge Across refuse a range that touches a table ("You can't merge cells in a table."). Unmerging is still allowed, so a file that has one can be fixed. - Insert Table / Format as Table and Resize Table unmerge the merged cells the table covers (observed: Excel creates the table and A2:B2 is no longer merged). - Paste brings merged areas along, except into a table, where the cells arrive unmerged. The command-sequence fuzzer checks the invariant (it found the paste case, seed 230). --- crates/engine/src/cmd/edit/paste_special.rs | 5 ++ crates/engine/src/cmd/extra/data.rs | 2 + crates/engine/src/cmd/format.rs | 5 ++ crates/engine/src/cmd/insert.rs | 7 +++ crates/engine/src/tests.rs | 60 +++++++++++++++++++ .../engine/tests/it/command_sequence_fuzz.rs | 6 +- crates/engine/tests/it/sheet_copy_spill.rs | 2 +- 7 files changed, 85 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index c90dd9ec80..0c2f17a3dc 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -361,6 +361,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { if let (Some(a), Some(b)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) { let nm = RangeRef::new(a, b); let sh = cx.sheet_mut(dest_sheet)?; + // A table can't hold merged cells (Excel removes the table on open): the + // cells are pasted there unmerged. + if sh.tables.iter().any(|t| t.range.intersects(&nm)) { + continue; + } sh.merges.retain(|x| !x.intersects(&nm)); sh.merges.push(nm); } diff --git a/crates/engine/src/cmd/extra/data.rs b/crates/engine/src/cmd/extra/data.rs index 5af7df0a86..9940ffc459 100644 --- a/crates/engine/src/cmd/extra/data.rs +++ b/crates/engine/src/cmd/extra/data.rs @@ -37,6 +37,8 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result { } t.columns = cols; t.range = r; + // A table can't hold merged cells: those it now covers are unmerged, as by Insert Table. + sheet.merges.retain(|m| !m.intersects(&r)); cx.structural = true; Ok(Json::Null) }) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 90213a5e1c..d512b7a0cb 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -637,6 +637,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let ranges = target_ranges(s, p)?; let how = if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how }; + // Excel has no merged cells in a table (a file with one loses the table when Excel opens it): + // merging there is refused, unmerging is still allowed. + if how != "unmerge" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| ranges.iter().any(|r| t.range.intersects(r)))) { + return Err(EngineError::Other("You can't merge cells in a table.".into())); + } edit(s, |cx| { let mut touched = Vec::new(); // Areas whose merging changes: a merged cell blocks a dynamic array's spill. diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 4bd564db37..f88c6040fa 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -334,6 +334,13 @@ fn insert_table(s: &mut Session, p: &Json) -> Result { RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col)) }; let sh = cx.sheet_mut(sheet)?; + // As in Excel, the table unmerges the merged cells it covers: a table can't hold them. + let merged = sh.merges.len(); + sh.merges.retain(|m| !m.intersects(&r)); + if sh.merges.len() != merged { + cx.structural = true; + } + let sh = cx.sheet_mut(sheet)?; let mut names: Vec = Vec::new(); // Lower-case names taken, and the next suffix for each header, so that thousands of equal // headers don't take cubic time. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f000eb9fe1..5cc071d5a3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6728,3 +6728,63 @@ fn history_charges_the_storage_of_empty_comment_replies() { // 500 replies of no text are still 500 elements. assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>()); } + +#[test] +fn tables_never_hold_merged_cells() { + // Excel removes a table that contains a merged cell when it opens the file. Merging in a + // table is refused; making or resizing a table over merged cells unmerges them; pasting into + // a table skips the merges. + let base = || { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:D4", "values": [["A", "B", "C", "D"], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]})) + .unwrap(); + s + }; + let merges = |s: &Session| s.doc().unwrap().wb.active().unwrap().merges.clone(); + + let mut s = base(); + s.execute("insert.table", json!({"range": "A1:C4"})).unwrap(); + for id in ["home.mergeCells", "home.mergeCenter", "home.mergeAcross"] { + for range in ["A2:B2", "A1:B1", "C3:D3"] { + let e = s.execute(id, json!({"range": range})).unwrap_err().to_string(); + assert!(e.contains("can't merge cells in a table"), "{id} {range}: {e}"); + } + } + assert!(merges(&s).is_empty()); + s.execute("home.mergeCells", json!({"range": "E2:F2"})).unwrap(); + assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F2").unwrap()]); + + // A table over merged cells unmerges them; undo brings them back. + let mut s = base(); + s.execute("home.mergeCells", json!({"range": "A2:B2"})).unwrap(); + s.execute("home.mergeCells", json!({"range": "C3:D4"})).unwrap(); + s.execute("home.mergeCells", json!({"range": "F1:G1"})).unwrap(); + s.execute("insert.table", json!({"range": "A1:C4"})).unwrap(); + assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("F1:G1").unwrap()]); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(merges(&s).len(), 3); + s.execute("edit.redo", json!({})).unwrap(); + + // Resizing a table over merged cells unmerges them too. + let mut s = base(); + s.execute("insert.table", json!({"range": "A1:B4", "name": "T"})).unwrap(); + s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap(); + s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap(); + assert!(merges(&s).is_empty()); + + // Merged cells pasted into a table arrive unmerged; elsewhere they stay merged. + s.execute("home.mergeCells", json!({"range": "E2:F3"})).unwrap(); + s.execute("edit.copy", json!({"range": "E2:F3"})).unwrap(); + s.execute("edit.paste", json!({"at": "A2"})).unwrap(); + s.execute("edit.paste", json!({"at": "H2"})).unwrap(); + assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F3").unwrap(), gridcraft_core::RangeRef::parse("H2:I3").unwrap()]); + + // The saved file has no merge inside the table. + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + let bytes = crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap(); + let (back, _) = crate::io::open_bytes("t.xlsx", &bytes).unwrap(); + let sh = back.active().unwrap(); + assert_eq!(sh.tables.len(), 1); + assert_eq!(sh.tables[0].range, gridcraft_core::RangeRef::parse("A1:C4").unwrap()); + assert!(sh.merges.iter().all(|m| sh.tables.iter().all(|t| !t.range.intersects(m)))); +} diff --git a/crates/engine/tests/it/command_sequence_fuzz.rs b/crates/engine/tests/it/command_sequence_fuzz.rs index 89b3e91865..949f637539 100644 --- a/crates/engine/tests/it/command_sequence_fuzz.rs +++ b/crates/engine/tests/it/command_sequence_fuzz.rs @@ -12,7 +12,7 @@ //! and saving, reloading or recalculating never panics either; //! - a non-undoable command never changes cell content (it would be lost to undo); //! - the structure stays valid: active sheet in range, sheet and table names valid and unique, -//! merges and tables on the sheet and not overlapping, legacy arrays anchored at their +//! merges and tables on the sheet and not overlapping (nor a merge inside a table), legacy arrays anchored at their //! top-left cell, the selection on the sheet; //! - a full recalculation from scratch gives the values the incremental recalculation left //! (catches stale dependency graphs); @@ -408,6 +408,10 @@ fn structure_problem(wb: &Workbook, sel: &gridcraft_engine::Selection) -> Option if let Some(o) = sh.tables.iter().skip(k + 1).find(|o| overlaps(&t.range, &o.range)) { return Some(format!("{}: tables `{}` ({}) and `{}` ({}) overlap", sh.name, t.name, t.range, o.name, o.range)); } + // Excel removes a table that holds a merged cell when it opens the file. + if let Some(m) = sh.merges.iter().find(|m| overlaps(&t.range, m)) { + return Some(format!("{}: table `{}` ({}) holds merged cells {m}", sh.name, t.name, t.range)); + } } } if sel.ranges.is_empty() || !sel.active.is_valid() || sel.ranges.iter().any(|r| !r.start.is_valid() || !r.end.is_valid()) { diff --git a/crates/engine/tests/it/sheet_copy_spill.rs b/crates/engine/tests/it/sheet_copy_spill.rs index aed68baf97..481f9889ee 100644 --- a/crates/engine/tests/it/sheet_copy_spill.rs +++ b/crates/engine/tests/it/sheet_copy_spill.rs @@ -17,7 +17,7 @@ fn value(s: &Session, sheet: &str, cell: &str) -> Value { fn copied_sheet_keeps_spill_values_through_full_recalc() { let mut s = Session::new(); run(&mut s, "file.new", json!({"sample": "grades"})); - run(&mut s, "home.mergeCells", json!({"range": "F:H"})); + run(&mut s, "home.mergeCells", json!({"range": "F15:H20"})); run(&mut s, "cell.set", json!({"cell": "J54", "input": "=SEQUENCE(5)*C6"})); run(&mut s, "selection.set", json!({"range": "15:15"})); run(&mut s, "sheet.move", json!({"copy": true, "sheet": 0, "to": 1})); From 595a2ee0a86eb35a970f07c5274591c8b63f36ed Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:15:32 +0700 Subject: [PATCH 21/25] vi: drop 13 entries that repeat keys translated earlier in the catalog main added Sort-dialog, status-bar and Goal Seek strings to vi.rs after this branch had translated them. The merge kept both copies, and clippy rejects the later ones as unreachable match arms. The earlier entries are the ones in use, so nothing shown changes. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/i18n/vi.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 32068cb417..bd84fcb994 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -1214,13 +1214,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Hiện", "Collapse dialog" => "Thu gọn hộp thoại", "Expand dialog" => "Mở rộng hộp thoại", - "My list has headers" => "Dữ liệu của tôi có tiêu đề", - "Sort by" => "Sắp xếp theo", - "Then by" => "Sau đó theo", - "Cell Values" => "Giá trị ô", - "Cell Color" => "Màu ô", - "A to Z" => "A đến Z", - "Z to A" => "Z đến A", "Add Level" => "Thêm cấp", "Delete Level" => "Xóa cấp", "Copy Level" => "Sao chép cấp", @@ -1260,12 +1253,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Macro “{name}” stopped: {message}" => "Macro “{name}” đã dừng: {message}", "Ran macro “{name}” ({steps} step)" => "Đã chạy macro “{name}” ({steps} bước)", "Ran macro “{name}” ({steps} steps)" => "Đã chạy macro “{name}” ({steps} bước)", - "Average" => "Trung bình", - "Count" => "Số đếm", - "Sum" => "Tổng", - "Goal Seeking found a solution: {value}" => "Tìm mục tiêu đã tìm thấy nghiệm: {value}", - "Sheets: {sheets}" => "Trang tính: {sheets}", - "Hidden: {sheets}" => "Đang ẩn: {sheets}", "Double superscript" => "Chỉ số trên bị lặp", "Double subscript" => "Chỉ số dưới bị lặp", "Extra }" => "Thừa }", From 637e7809f0644a7c62ab6fd23eb8a0e4a2a8b6ba Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:39:40 +0200 Subject: [PATCH 22/25] Make HYPERLINK formula cells behave as clickable links Fixes #2230 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/lib.rs | 2 +- crates/engine/src/cmd/insert/links.rs | 4 +-- crates/engine/src/cmd/inspect.rs | 2 +- crates/engine/src/links.rs | 39 ++++++++++++++++++++++++++- crates/engine/src/tests.rs | 15 +++++++++++ crates/ui-egui/src/grid/interact.rs | 4 +-- crates/ui-egui/src/grid/show.rs | 2 +- 7 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/calc/src/lib.rs b/crates/calc/src/lib.rs index 794a3f97f1..92aa9526cd 100644 --- a/crates/calc/src/lib.rs +++ b/crates/calc/src/lib.rs @@ -12,7 +12,7 @@ mod trimrange; pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function}; pub use precision::DisplayedPrecision; -pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial}; +pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, evaluate_expr, now_serial}; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/insert/links.rs b/crates/engine/src/cmd/insert/links.rs index c90fc946ad..b0b4892955 100644 --- a/crates/engine/src/cmd/insert/links.rs +++ b/crates/engine/src/cmd/insert/links.rs @@ -56,10 +56,10 @@ pub(super) fn open_link(s: &mut Session, p: &Json) -> Result { None => { let sheet = target_sheet(s, p)?; let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active); - let Some(h) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.hyperlinks.get(&at)) else { + let Some(h) = crate::links::cell_link(&s.doc()?.wb, sheet, at) else { return Err(EngineError::Other("There's no hyperlink in this cell.".into())); }; - h.target.clone() + h.target } }; match crate::links::classify(&target) { diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index e91a269fb3..d6646743db 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -136,7 +136,7 @@ fn cell_get(s: &mut Session, p: &Json) -> Result { "style": style, "merge": sh.merge_at(c).map(|m| m.a1()), "comment": sh.comments.get(&c), - "hyperlink": sh.hyperlinks.get(&c), + "hyperlink": crate::links::cell_link(&d.wb, sheet, c), "python": cell.and_then(|x| x.py.as_deref()).map(|py| json!({ "code": py.code, "output": if py.object { "object" } else { "value" }, diff --git a/crates/engine/src/links.rs b/crates/engine/src/links.rs index 4c2318f07f..9497de4ef2 100644 --- a/crates/engine/src/links.rs +++ b/crates/engine/src/links.rs @@ -9,7 +9,9 @@ //! external addresses; only the host, after showing the address and getting OK from the user, //! opens one through [`crate::Session::open_confirmed_link`], which no command reaches. -use gridcraft_core::RangeRef; +use gridcraft_core::{CellRef, RangeRef}; +use gridcraft_formula::Expr; +use gridcraft_model::{Hyperlink, Workbook}; use serde_json::{Value as Json, json}; use crate::{EngineError, Result, Session, UiRequest}; @@ -86,6 +88,41 @@ pub fn classify(target: &str) -> LinkKind { } } +/// The link of a cell: the one stored with it, or, for a cell whose formula is `HYPERLINK(target, …)`, +/// the target that formula currently evaluates to. A scheme-less web address (`google.com`) is +/// opened over `https`, as Excel does. +pub fn cell_link(wb: &Workbook, sheet: usize, at: CellRef) -> Option { + let sh = wb.sheet(sheet)?; + if let Some(h) = sh.hyperlinks.get(&at) { + return Some(h.clone()); + } + let expr = sh.cell(at)?.formula.as_ref()?.expr()?; + let Expr::Call(name, args) = &expr else { return None }; + if name != "HYPERLINK" { + return None; + } + let value = gridcraft_calc::evaluate_expr(wb, sheet, at, args.first()?); + let target = value.display().trim().to_string(); + if target.is_empty() || matches!(value, gridcraft_core::Value::Error(_)) { + return None; + } + let target = if looks_like_web_address(&target) && wb.name(&target, sheet).is_none() { format!("https://{target}") } else { target }; + let external = !matches!(classify(&target), LinkKind::Internal(_)); + Some(Hyperlink { target, tooltip: None, external }) +} + +fn looks_like_web_address(t: &str) -> bool { + if t.contains(|c: char| c.is_whitespace() || matches!(c, '\\' | '!' | '#' | ':')) { + return false; + } + let host = t.split('/').next().unwrap_or(t); + let Some((_, tld)) = host.rsplit_once('.') else { return false }; + tld.len() >= 2 + && tld.chars().all(|c| c.is_ascii_alphabetic()) + && !["xlsx", "xlsm", "xlsb", "xls", "csv", "txt", "pdf", "doc", "docx"].contains(&tld.to_ascii_lowercase().as_str()) + && RangeRef::parse(t).is_none() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 785e68f6b9..7b25f7af6d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7657,3 +7657,18 @@ fn history_charges_the_storage_of_empty_comment_replies() { // 500 replies of no text are still 500 elements. assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>()); } + +#[test] +fn hyperlink_function_makes_a_cell_link() { + let mut s = s(); + s.link_policy = crate::links::LinkPolicy::Allow; + s.execute("cell.set", json!({"cell": "A1", "input": "https://example.com/x"})).unwrap(); + s.execute("cell.set", json!({"cell": "B2", "input": "=HYPERLINK(A1,\"Go\")"})).unwrap(); + s.execute("cell.set", json!({"cell": "C3", "input": "=HYPERLINK(\"google.com\")"})).unwrap(); + s.take_ui_requests(); + s.execute("link.open", json!({"cell": "B2"})).unwrap(); + assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://example.com/x".into())]); + s.execute("link.open", json!({"cell": "C3"})).unwrap(); + assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://google.com".into())]); + assert!(s.execute("link.open", json!({"cell": "A1"})).is_err()); +} diff --git a/crates/ui-egui/src/grid/interact.rs b/crates/ui-egui/src/grid/interact.rs index f0ab7bc8ea..e5fe41f539 100644 --- a/crates/ui-egui/src/grid/interact.rs +++ b/crates/ui-egui/src/grid/interact.rs @@ -528,7 +528,7 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) { } } else if mods.command { // Ctrl+click (without Alt) on a hyperlink's text follows it instead of adding the cell to the selection. - if let Some(h) = sh.hyperlinks.get(&c).cloned() + if let Some(h) = gridcraft_engine::links::cell_link(wb, wb.active_sheet(), c) && acts && !mods.alt && p.x < geo.cell_rect(sh, c).left() + geo.cell_rect(sh, c).width() * 0.8 @@ -545,7 +545,7 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) { let _ = app.run("cell.toggleCheckbox", json!({"cell": c.a1()})); } // A click on a hyperlink's text follows it (like Excel); elsewhere in the cell selects. - if let Some(h) = sh.hyperlinks.get(&c).cloned() + if let Some(h) = gridcraft_engine::links::cell_link(wb, wb.active_sheet(), c) && acts && !mods.any() { diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 713c2d51c7..13839f1b8e 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -770,7 +770,7 @@ pub(crate) fn paint_overlays(input: OverlayInput<'_>) { ); } // Hyperlink tooltip. - if let Some(h) = hover.and_then(|c| sh.hyperlinks.get(&c)) + if let Some(h) = hover.and_then(|c| gridcraft_engine::links::cell_link(wb, si, c)) && app.editor.is_none() { let tip = h.tooltip.clone().unwrap_or_else(|| format!("{}\nClick once to follow. Click and hold to select this cell.", h.target)); From def333fe4287bac6bdf7f84a0a56738ab201c920 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:56:52 +0700 Subject: [PATCH 23/25] #2230: HYPERLINK targets with a query, fragment or port open over https; a table name stays internal; a click resolves the link after committing an edit --- crates/engine/src/links.rs | 15 ++++++++++++--- crates/engine/src/tests.rs | 16 ++++++++++++++++ crates/ui-egui/src/grid/interact.rs | 11 +++++++++-- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/links.rs b/crates/engine/src/links.rs index 9497de4ef2..2b26c925bf 100644 --- a/crates/engine/src/links.rs +++ b/crates/engine/src/links.rs @@ -106,16 +106,25 @@ pub fn cell_link(wb: &Workbook, sheet: usize, at: CellRef) -> Option if target.is_empty() || matches!(value, gridcraft_core::Value::Error(_)) { return None; } - let target = if looks_like_web_address(&target) && wb.name(&target, sheet).is_none() { format!("https://{target}") } else { target }; + // a defined name or a table of that spelling (`sales.data`) stays an internal target + let internal_name = wb.name(&target, sheet).is_some() || wb.table(&target).is_some(); + let target = if looks_like_web_address(&target) && !internal_name { format!("https://{target}") } else { target }; let external = !matches!(classify(&target), LinkKind::Internal(_)); Some(Hyperlink { target, tooltip: None, external }) } fn looks_like_web_address(t: &str) -> bool { - if t.contains(|c: char| c.is_whitespace() || matches!(c, '\\' | '!' | '#' | ':')) { + if t.contains(|c: char| c.is_whitespace() || matches!(c, '\\' | '!')) { return false; } - let host = t.split('/').next().unwrap_or(t); + // the host ends at the path, query or fragment (`google.com/x`, `google.com?q=1`, `google.com#top`) + let host = t.split(['/', '?', '#']).next().unwrap_or(t); + // with an optional port (`example.com:8443`); any other colon is a scheme or a sheet reference + let host = match host.split_once(':') { + Some((h, port)) if !port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit()) => h, + Some(_) => return false, + None => host, + }; let Some((_, tld)) = host.rsplit_once('.') else { return false }; tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8a05634179..41ce6c2a90 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7943,6 +7943,22 @@ fn hyperlink_function_makes_a_cell_link() { s.execute("link.open", json!({"cell": "C3"})).unwrap(); assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://google.com".into())]); assert!(s.execute("link.open", json!({"cell": "A1"})).is_err()); + // a scheme-less address with a query, fragment or port opens over https too + for (cell, input, url) in [ + ("D1", "=HYPERLINK(\"google.com?q=rust\")", "https://google.com?q=rust"), + ("D2", "=HYPERLINK(\"google.com#results\")", "https://google.com#results"), + ("D3", "=HYPERLINK(\"example.com:8443/x\")", "https://example.com:8443/x"), + ] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + s.execute("link.open", json!({"cell": cell})).unwrap(); + assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl(url.into())], "{input}"); + } + // a table named like an address stays an internal target + s.execute("range.setValues", json!({"range": "F1:G2", "values": [["a", "b"], [1, 2]]})).unwrap(); + s.execute("insert.table", json!({"range": "F1:G2", "name": "sales.data"})).unwrap(); + s.execute("cell.set", json!({"cell": "D4", "input": "=HYPERLINK(\"sales.data\")"})).unwrap(); + let link = crate::links::cell_link(&s.doc().unwrap().wb, 0, gridcraft_core::CellRef::parse("D4").unwrap()).unwrap(); + assert_eq!(link.target, "sales.data"); } /// #1348: the selection a workbook opens with, and the one a sheet gets on its first visit, take diff --git a/crates/ui-egui/src/grid/interact.rs b/crates/ui-egui/src/grid/interact.rs index 257231a29f..09564ec9e5 100644 --- a/crates/ui-egui/src/grid/interact.rs +++ b/crates/ui-egui/src/grid/interact.rs @@ -400,6 +400,13 @@ fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: } } +/// The link of cell `c` on the active sheet as the session holds it now: a click may have just +/// committed an edit the frame's workbook snapshot predates (a `HYPERLINK` target cell). +fn current_cell_link(app: &SheetApp, c: CellRef) -> Option { + let d = app.session.active()?; + gridcraft_engine::links::cell_link(&d.wb, d.wb.active_sheet(), c) +} + fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) { let (geo, sh, wb, resp) = (input.geo, input.sheet, input.workbook, input.response); let (pos, mods, sel) = (input.position, input.modifiers, &input.selection); @@ -528,7 +535,7 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) { } } else if mods.command { // Ctrl+click (without Alt) on a hyperlink's text follows it instead of adding the cell to the selection. - if let Some(h) = gridcraft_engine::links::cell_link(wb, wb.active_sheet(), c) + if let Some(h) = current_cell_link(app, c) && acts && !mods.alt && p.x < geo.cell_rect(sh, c).left() + geo.cell_rect(sh, c).width() * 0.8 @@ -545,7 +552,7 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) { let _ = app.run("cell.toggleCheckbox", json!({"cell": c.a1()})); } // A click on a hyperlink's text follows it (like Excel); elsewhere in the cell selects. - if let Some(h) = gridcraft_engine::links::cell_link(wb, wb.active_sheet(), c) + if let Some(h) = current_cell_link(app, c) && acts && !mods.any() { From 91f9b870704600eaf6e2ccafb0d58c33192e549d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:15:09 +0100 Subject: [PATCH 24/25] Resize Table keeps main's refusal over merged cells (Excel's behaviour); test follows --- crates/engine/src/cmd/extra/data.rs | 2 -- crates/engine/src/tests.rs | 6 ++++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/extra/data.rs b/crates/engine/src/cmd/extra/data.rs index 37f383642d..cc4490e7f9 100644 --- a/crates/engine/src/cmd/extra/data.rs +++ b/crates/engine/src/cmd/extra/data.rs @@ -93,8 +93,6 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result { let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?; t.columns = cols; t.range = r; - // A table can't hold merged cells: those it now covers are unmerged, as by Insert Table. - sheet.merges.retain(|m| !m.intersects(&r)); cx.structural = true; Ok(Json::Null) }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 829b153684..c1668a0034 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8208,12 +8208,14 @@ fn tables_never_hold_merged_cells() { assert_eq!(merges(&s).len(), 3); s.execute("edit.redo", json!({})).unwrap(); - // Resizing a table over merged cells unmerges them too. + // Resizing a table over merged cells is refused, as in Excel; the merge stays. let mut s = base(); s.execute("insert.table", json!({"range": "A1:B4", "name": "T"})).unwrap(); s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap(); + let e = s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap_err().to_string(); + assert!(e.contains("can't overlap merged cells"), "{e}"); + s.execute("home.unmergeCells", json!({"range": "C2:D2"})).unwrap(); s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap(); - assert!(merges(&s).is_empty()); // Merged cells pasted into a table arrive unmerged; elsewhere they stay merged. s.execute("home.mergeCells", json!({"range": "E2:F3"})).unwrap(); From 604cdf03f0b29101b63975cb96090553b19db0a1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:04:37 +0100 Subject: [PATCH 25/25] vi: translate the context-keyed Paste Special|Add and Text to Columns|Comma, as main's catalogs do --- crates/ui-egui/src/i18n/vi.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 35dee524f3..a870ca9fe9 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -558,6 +558,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Values and number formats" => "Giá trị và định dạng số", "Operation" => "Phép tính", "Add" => "Cộng", + "Paste Special|Add" => "Cộng", "Subtract" => "Trừ", "Multiply" => "Nhân", "Divide" => "Chia", @@ -597,6 +598,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Tab" => "Tab", "Semicolon" => "Dấu chấm phẩy", "Comma" => "Dấu phẩy", + "Text to Columns|Comma" => "Dấu phẩy", "Space" => "Dấu cách", "Other:" => "Khác:", "Treat consecutive delimiters as one" => "Gộp các dấu phân cách liên tiếp thành một",