diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 5c0bf800b..f90f4f3df 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -947,6 +947,25 @@ mod tests { assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs); } + /// #1446: File › Open honours Excel's `sep=` first line; saved again, the file opens in the same + /// columns. A `.txt` file is read with tabs, so its `sep=` line stays data. + #[test] + fn csv_open_honours_a_sep_line_and_saves_a_file_that_reopens_in_columns() { + let (wb, _) = open_bytes("parts.csv", b"sep=|\r\nPart|Note\r\n1|a,b\r\n").unwrap(); + let sh = wb.sheet(0).unwrap(); + let text = |a: &str| sh.value(CellRef::parse(a).unwrap()).as_text().map(str::to_string); + assert_eq!((text("A1"), text("B1"), text("B2")), (Some("Part".into()), Some("Note".into()), Some("a,b".into()))); + let saved = save_bytes(&wb, "parts.csv").unwrap(); + assert_eq!(String::from_utf8(saved.clone()).unwrap(), "Part,Note\r\n1,\"a,b\"\r\n"); + let (again, _) = open_bytes("parts.csv", &saved).unwrap(); + assert_eq!(again.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()).as_text(), Some("a,b")); + // `sep=;` keeps its semicolons, as a semicolon file does. + let (semi, _) = open_bytes("semi.csv", b"sep=;\r\na;b\r\n").unwrap(); + assert_eq!(save_bytes(&semi, "semi.csv").unwrap(), b"a;b\r\n"); + let (txt, _) = open_bytes("list.txt", b"sep=|\r\na\tb\r\n").unwrap(); + assert_eq!(txt.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=|")); + } + #[test] fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() { let mut wb = Workbook::new(); diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index dfc694ea6..b4e58b49b 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -193,9 +193,34 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { best.0 } +/// Excel's `sep=` line: a first line `sep=` plus one character names the delimiter and isn't data. +/// Returns the delimiter it names (`None`: the line names none, so nothing is split) and the bytes +/// to skip, line end included. Observed in Excel 16.0 (build 17932, Windows): spaces anywhere in the +/// line are ignored, `SEP=` is the same, the line may be quoted as a whole field, and `sep=` with +/// nothing after it (or a non-ASCII character) is dropped and splits nothing. Two characters after +/// `=` (a tab counts: `sep=|`), or the line anywhere but first, is data. +pub(crate) fn sep_line(text: &str, quote: char) -> Option<(Option, usize)> { + let end = text.find(['\r', '\n']).unwrap_or(text.len()); + let skip = match text.get(end..end + 2) { + Some("\r\n") => end + 2, + _ if end < text.len() => end + 1, + _ => end, + }; + let line: String = text.get(..end)?.chars().filter(|&c| c != ' ').collect(); + let line = line.strip_prefix(quote).and_then(|l| l.strip_suffix(quote)).unwrap_or(&line); + let rest = line.get(..4).filter(|p| p.eq_ignore_ascii_case("sep=")).and_then(|_| line.get(4..))?; + let mut chars = rest.chars(); + match (chars.next(), chars.next()) { + (None, _) => Some((None, skip)), + (Some(c), None) => Some((Some(c).filter(char::is_ascii), skip)), + _ => None, + } +} + /// Splits CSV text into records of fields. A record keeps at most [`MAX_COLS`] fields; the rest are /// dropped as they are read, so a row of endless delimiters cannot allocate a string per field. -pub(crate) fn parse_records(text: &str, delim: char, quote: char, mut on_record: impl FnMut(Vec) -> bool) { +/// Without a delimiter each line is one field; without a quote character nothing is quoted. +pub(crate) fn parse_records(text: &str, delim: Option, quote: Option, mut on_record: impl FnMut(Vec) -> bool) { let mut field = String::new(); let mut record: Vec = vec![]; let mut in_q = false; @@ -203,9 +228,9 @@ pub(crate) fn parse_records(text: &str, delim: char, quote: char, mut on_record: let mut field_started_quoted = false; while let Some(c) = chars.next() { if in_q { - if c == quote { - if chars.peek() == Some("e) { - field.push(quote); + if Some(c) == quote { + if chars.peek() == quote.as_ref() { + field.push(c); chars.next(); } else { in_q = false; @@ -215,10 +240,10 @@ pub(crate) fn parse_records(text: &str, delim: char, quote: char, mut on_record: } continue; } - if c == quote && field.is_empty() && !field_started_quoted { + if Some(c) == quote && field.is_empty() && !field_started_quoted { in_q = true; field_started_quoted = true; - } else if c == delim { + } else if Some(c) == delim { let f = std::mem::take(&mut field); if record.len() < MAX_COLS as usize { record.push(f); @@ -251,18 +276,32 @@ pub(crate) fn parse_records(text: &str, delim: char, quote: char, mut on_record: pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { let text = decode_text(bytes); let quote = if opts.quote == 0 { '"' } else { opts.quote as char }; - let delim = if opts.delimiter == 0 { sniff_delimiter(&text, quote) } else { opts.delimiter } as char; - if delim == quote { - return Err(IoError::Format("the delimiter and quote character must differ".into())); - } let mut wb = Workbook::new(); wb.date_system = opts.date_system; - wb.csv_delimiter = u8::try_from(delim).ok(); + // A detected delimiter: a `sep=` line names it (and isn't data), else the text shows it. + let sep = if opts.delimiter == 0 { sep_line(&text, quote) } else { None }; + let (body, delim, quote) = match sep { + Some((d, skip)) => { + // Saved again with it only when it would be detected without the line (Excel saves + // with its list separator and drops the line); else with the CSV default, comma. + wb.csv_delimiter = d.filter(|d| [',', ';', '\t'].contains(d)).and_then(|d| u8::try_from(d).ok()); + // `sep="`: Excel splits at the quotes, so nothing is quoted. + (text.get(skip..).unwrap_or_default(), d, Some(quote).filter(|q| d != Some(*q))) + } + None => { + let delim = if opts.delimiter == 0 { sniff_delimiter(&text, quote) } else { opts.delimiter } as char; + if delim == quote { + return Err(IoError::Format("the delimiter and quote character must differ".into())); + } + wb.csv_delimiter = u8::try_from(delim).ok(); + (text.as_str(), Some(delim), Some(quote)) + } + }; let mut sheet = Sheet::new("Sheet1"); let mut styles = std::mem::take(&mut wb.styles); let mut fmt_cache: Vec<(&'static str, StyleId)> = vec![]; let mut row: u32 = 0; - parse_records(&text, delim, quote, |rec| { + parse_records(body, delim, quote, |rec| { if row >= MAX_ROWS { return false; } diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 066f507e0..4a2f70db9 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -313,16 +313,57 @@ fn parser_stops_collecting_fields_at_max_cols() { let mut text = ",".repeat((MAX_COLS + extra) as usize - 1); text.push_str("end\nx,y\n"); let mut lens = vec![]; - parse_records(&text, ',', '"', |rec| { + parse_records(&text, Some(','), Some('"'), |rec| { lens.push(rec.len()); true }); assert_eq!(lens, vec![MAX_COLS as usize, 2]); // An unterminated last row is capped the same way. let mut lens = vec![]; - parse_records(&",".repeat(MAX_COLS as usize + extra as usize), ',', '"', |rec| { + parse_records(&",".repeat(MAX_COLS as usize + extra as usize), Some(','), Some('"'), |rec| { lens.push(rec.len()); true }); assert_eq!(lens, vec![MAX_COLS as usize]); } + +/// #1446: a first line `sep=` plus one character names the delimiter and isn't data, as Excel 16.0 +/// reads it when it opens a CSV file. Each case: file → first two rows. +#[test] +fn sep_line_names_the_delimiter() { + let read = |src: &str| -> Vec { + let wb = read_csv(src.as_bytes(), &CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }).unwrap(); + let sh = wb.sheet(0).unwrap(); + let cell = |r, c| sh.value(CellRef::new(r, c)).as_text().map(|t| t.to_string()).unwrap_or_default(); + (0..2).map(|r| (0..3).map(|c| cell(r, c)).collect::>().join("|").trim_end_matches('|').to_string()).collect() + }; + // Named delimiters, whatever the text would suggest. + assert_eq!(read("sep=|\r\nA|B\r\n1|2\r\n"), ["A|B", "1|2"]); + assert_eq!(read("sep=;\nA;B,C\n"), ["A|B,C", ""]); + assert_eq!(read("sep=,\r\n1,5;2\r\n"), ["1|5;2", ""]); + assert_eq!(read("sep=\t\r\nA\tB\r\n"), ["A|B", ""]); + assert_eq!(read("sep=x\r\nAxB\r\n"), ["A|B", ""]); + // Spaces anywhere, upper case, the line quoted as a field, a BOM before it. + for src in ["sep= |\r\nA|B", "sep =|\r\nA|B", " sep=| \r\nA|B", "SEP=|\r\nA|B", "\"sep=|\"\r\nA|B", "\u{feff}sep=|\r\nA|B"] { + assert_eq!(read(src), ["A|B", ""], "{src:?}"); + } + // `sep=` naming nothing (or a space) is dropped and splits nothing. + assert_eq!(read("sep=\r\nA;B\tC,D\r\n"), ["A;B\tC,D", ""]); + assert_eq!(read("sep= \r\nA,B\r\n"), ["A,B", ""]); + assert_eq!(read("sep=|"), ["", ""], "only the line: an empty sheet"); + // `sep="`: split at the quotes. + assert_eq!(read("sep=\"\r\nA\"B\r\n"), ["A|B", ""]); + // Data: two characters after `=` (a tab counts), the line anywhere but first, an unclosed quote. + assert_eq!(read("sep=ab\r\nAaB\r\n"), ["sep=ab", "AaB"]); + assert_eq!(read("sep=|\t\r\nA|B\r\n"), ["sep=|\t", "A|B"]); + assert!(read("sep=;,\r\nA;B,C\r\n")[0].starts_with("sep=;"), "data, split as the text suggests"); + assert_eq!(read("A,B\r\nsep=,\r\n"), ["A|B", "sep="], "a data row, split at its comma"); + // A delimiter that was given wins, and the line stays data. + let wb = read_csv(b"sep=|\r\nA|B\r\n", &CsvOptions { delimiter: b',', ..Default::default() }).unwrap(); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(0, 0)), Value::text("sep=|")); + // Saved again with the named delimiter only when it would be detected without the line. + let delim = |src: &str| read_csv(src.as_bytes(), &CsvOptions { delimiter: 0, ..Default::default() }).unwrap().csv_delimiter; + assert_eq!(delim("sep=;\r\nA;B"), Some(b';')); + assert_eq!(delim("sep=\t\r\nA\tB"), Some(b'\t')); + assert_eq!(delim("sep=|\r\nA|B"), None, "| isn't detected: saved with commas so it reopens in columns"); +} diff --git a/docs/decisions.md b/docs/decisions.md index 2aa18069f..95f151ce0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -79,4 +79,23 @@ to 115% or 100%. That's a large relative step at low zoom and a small one near 4 relative steps keep each notch feeling the same, and the doublings land on 25, 50, 100, 200 and 400%. The status bar's Zoom In / Zoom Out buttons and Ctrl+Alt+= / Ctrl+Alt+- keep their 10% steps, so the wheel and the buttons now step differently. Whether they should share one ladder -(this one, Excel's, or another) is left to the maintainers. \ No newline at end of file +(this one, Excel's, or another) is left to the maintainers. +## CSV: Excel's `sep=` first line (#1446) + +A CSV file whose first line is `sep=` plus one character is split at that character when File › +Open detects the delimiter, and the line isn't data. Observed in Excel 16.0 (build 17932, Windows) +opening synthetic files: spaces anywhere in the line are ignored (`sep= |`, ` sep=| `), case +doesn't matter, the line may be quoted as a whole field, and a BOM before it is fine. `sep=` with +nothing after it (or only spaces) is dropped and nothing is split; a non-ASCII character is dropped +the same way. Two characters after `=` (a tab counts, `sep=|`), or the line anywhere but first, +is data. `sep="` splits at the quotes, so nothing is quoted. (#1446 measured `sep=` alone as data in +Excel for Microsoft 365, de-DE; this build drops it.) + +A delimiter given by the caller wins and the line stays data, so a `.tsv`/`.txt` file (read with +tabs) keeps it. Saving: Excel writes its list separator and drops the line. GridCraft saves a CSV +with the separator it was read with, so it does that for `,` `;` and tab, which it detects again +when the file is reopened; any other named delimiter (`|`) is saved as commas, because without the +line the file would reopen as one column. + +From Text/CSV still guesses its own delimiter; making it detect like File › Open (and so honour +`sep=`) is another part of #1446. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cf567f8bd..ebc3a7bfc 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (.xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-22 · **Change:** minor (CSV: an Excel `sep=` first line names the delimiter and isn't read as data, #1446; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -66,9 +66,9 @@ values) is still dropped. | Format | Excel | GridCraft read | GridCraft write | Notes | |---|---|---|---|---| -| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, likely Windows-1256 Arabic detection, otherwise Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Excel writes the **displayed** values; we write raw values. No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | +| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, likely Windows-1256 Arabic detection, otherwise Windows-1252 fallback; delimiter detection, or the one an Excel `sep=` first line names, #1446) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Excel writes the **displayed** values; we write raw values. No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | | `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`; likely Windows-1256 Arabic detection for invalid UTF-8) | yes | Text Import Wizard options partly via Text to Columns | -| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, likely Windows-1256 Arabic detection, otherwise Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF) | Writes the **displayed** values like Excel (number formats applied, formula results, never column-width `#####`). No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | +| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, likely Windows-1256 Arabic detection, otherwise Windows-1252 fallback; delimiter detection, or the one an Excel `sep=` first line names, #1446) | yes (UTF-8 without BOM, CRLF) | Writes the **displayed** values like Excel (number formats applied, formula results, never column-width `#####`). No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | | `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`; likely Windows-1256 Arabic detection for invalid UTF-8) | yes (displayed values) | Text Import Wizard options partly via Text to Columns | | `.prn` formatted text (space-delimited) | R/W | no | no | | | `.dif`, `.slk` (SYLK) | R/W | no | no | Small, legacy | @@ -110,6 +110,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | CSV File › Open: a first line `sep=` plus one character names the delimiter and isn't data, as in Excel 16.0 (spaces ignored, any case, the line may be quoted; `sep=` alone splits nothing; two characters, or the line anywhere but first, is data). Saved again with that delimiter only when it's one GridCraft detects (`,` `;` tab), else with commas, so the file opens in the same columns (#1446) | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters |