From 4e85a1fd21a302594599ef6bcad9e8fc6d395ef6 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:36:18 +0200 Subject: [PATCH 1/6] CSV: an Excel `sep=` first line names the delimiter (#1446) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open read a `sep=|` first line as data and split the file by the detected delimiter, so a `|` file stayed one column. When the delimiter is detected, a first line `sep=` plus one character now names it and isn't data, as observed in Excel 16.0: spaces ignored, any case, the line may be quoted; `sep=` alone (or a non-ASCII character) splits nothing; two characters or the line anywhere but first is data; `sep="` splits at the quotes. A given delimiter wins. Saved again, the file keeps `,` `;` or tab; any other named delimiter is written as commas, so it reopens in the same columns. parse_records takes an optional delimiter and quote character for the two cases that split or quote nothing. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/io.rs | 19 +++++++++ crates/xlsx/src/csv.rs | 63 ++++++++++++++++++++++++------ crates/xlsx/src/tests/csv_tests.rs | 45 ++++++++++++++++++++- docs/decisions.md | 21 +++++++++- docs/file-format-parity.md | 7 ++-- 5 files changed, 137 insertions(+), 18 deletions(-) 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 | From 60c758af662bb47f3992b3f8addaa9299c33191b Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:35:53 +0200 Subject: [PATCH 2/6] CSV: keep a sep= delimiter only if it would be detected again; a first row like a sep= line stays data (#1446) Review of #2270. A delimiter a sep= line named was kept for saving whenever it was , ; or tab, but the saved file has no sep= line, so sep=; over a;b,c reopened split at the commas. It's kept now only when detection would pick it again; otherwise the file is saved with commas. A sheet whose first row reads as a sep= line (a lone sep=; in A1) was saved bare and that row was dropped on reopening; it's now written behind a sep= line naming the delimiter. Excel writes such a row bare and reopens the file garbled (observed: Excel 16.0). Co-Authored-By: Claude Opus 5.5 --- crates/xlsx/src/csv.rs | 14 ++++++++-- crates/xlsx/src/tests/csv_tests.rs | 45 ++++++++++++++++++++++++++++++ docs/decisions.md | 8 ++++-- 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index b4e58b49b..5310487b7 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -282,9 +282,12 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { 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()); + // Saved again with it only when the text would be read with it again without the line + // (Excel saves with its list separator and drops the line); else with the CSV default, + // comma. `sep=;` over `a;b,c` keeps commas: detection would pick them. + let body = text.get(skip..).unwrap_or_default(); + wb.csv_delimiter = + d.filter(|d| [',', ';', '\t'].contains(d) && sniff_delimiter(body, quote) as char == *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))) } @@ -401,5 +404,10 @@ pub fn write_csv_limited(sheet: &Sheet, delimiter: u8, limit: usize, mut cell_te return Err(too_large(format!("more than {} MiB (stopped at row {})", limit >> 20, row + 1))); } } + // A first row that would read as Excel's `sep=` line (a lone `sep=;` cell) stays data behind a + // `sep=` line of its own naming the delimiter, which GridCraft and Excel both drop on opening. + if out.split(['\r', '\n']).next().is_some_and(|first| sep_line(first, '"').is_some()) { + out.insert_str(0, &format!("sep={delim}\r\n")); + } Ok(out.into_bytes()) } diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 4a2f70db9..b35ff81f5 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -367,3 +367,48 @@ fn sep_line_names_the_delimiter() { 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"); } + +/// Review of #2270: the delimiter a `sep=` line names is kept for saving only if the text would be +/// read with it again. +#[test] +fn a_named_delimiter_is_kept_only_if_it_would_be_detected_again() { + let opts = CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }; + let texts = |wb: &Workbook| -> Vec { + let sh = wb.sheet(0).unwrap(); + (0..2).flat_map(|r| (0..2).map(move |c| CellRef::new(r, c))).map(|c| sh.value(c).as_text().unwrap_or("").to_string()).collect() + }; + let save = |wb: &Workbook| { + let sh = wb.sheet(0).unwrap(); + write_csv(sh, wb.csv_delimiter.unwrap_or(b','), |c| sh.value(c).as_text().unwrap_or("").to_string()).unwrap() + }; + // `;` named, but `a;b,c` would be detected as commas: saved with commas, it reopens the same. + let wb = read_csv(b"sep=;\na;b,c\n1;2,3\n", &opts).unwrap(); + assert_eq!(texts(&wb), ["a", "b,c", "1", "2,3"]); + assert_eq!(wb.csv_delimiter, None); + let saved = save(&wb); + assert_eq!(saved, b"a,\"b,c\"\r\n1,\"2,3\"\r\n"); + assert_eq!(texts(&read_csv(&saved, &opts).unwrap()), ["a", "b,c", "1", "2,3"]); + // `;` named and detected again: kept. + assert_eq!(read_csv(b"sep=;\na;b\n1;2\n", &opts).unwrap().csv_delimiter, Some(b';')); +} + +/// Review of #2270: a first row that looks like a `sep=` line (a lone `sep=;` in A1) is data. Saved +/// behind a `sep=,` line it opens as it was; Excel writes it bare and reads it back garbled. +#[test] +fn a_first_row_like_a_sep_line_survives_a_save() { + let opts = CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }; + let texts = |wb: &Workbook| -> Vec { + let sh = wb.sheet(0).unwrap(); + (0..2).flat_map(|r| (0..2).map(move |c| CellRef::new(r, c))).map(|c| sh.value(c).as_text().unwrap_or("").to_string()).collect() + }; + let mut sheet = Sheet::new("Sheet1"); + sheet.set_value(CellRef::new(0, 0), Value::text("sep=;")); + sheet.set_value(CellRef::new(1, 0), Value::text("value")); + let saved = write_csv(&sheet, b',', |c| sheet.value(c).as_text().unwrap_or("").to_string()).unwrap(); + assert_eq!(saved, b"sep=,\r\nsep=;\r\nvalue\r\n"); + assert_eq!(texts(&read_csv(&saved, &opts).unwrap()), ["sep=;", "", "value", ""]); + // Other first rows are written as before. + let mut plain = Sheet::new("Sheet1"); + plain.set_value(CellRef::new(0, 0), Value::text("separator")); + assert_eq!(write_csv(&plain, b',', |c| plain.value(c).as_text().unwrap_or("").to_string()).unwrap(), b"separator\r\n"); +} diff --git a/docs/decisions.md b/docs/decisions.md index 95f151ce0..81d02a8c1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -93,9 +93,11 @@ 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. +with the separator it was read with, so it keeps a named `,` `;` or tab only when detection picks +it again on reopening; otherwise (`|`, or `sep=;` over text with as many commas) it saves commas, +which reopen in the same columns. A first row that would itself read as a `sep=` line (a lone +`sep=;` cell) is written behind a `sep=` line naming the delimiter, so it stays data. Excel writes +such a row bare (`"sep=;";`) and reopens the file garbled (observed: A1 `sep=;;`, row 2 in one cell). From Text/CSV still guesses its own delimiter; making it detect like File › Open (and so honour `sep=`) is another part of #1446. From f90c2c0fe245ecc1f5b26c0e58f6922f4432de19 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:47:48 +0100 Subject: [PATCH 3/6] CSV: a .tsv save writes no sep= line (#1446) The guard that puts a sep= line before a first row reading like one is for CSV, which is read by detection. A .tsv or .txt file is read with tabs given, so the line came back as an extra row and moved every row down (CodeRabbit). write_tsv writes without it; Save as .tsv uses it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/io.rs | 15 ++++++++++----- crates/engine/src/io/tests.rs | 20 ++++++++++++++++++++ crates/xlsx/src/csv.rs | 22 ++++++++++++++++++++-- crates/xlsx/src/lib.rs | 2 +- docs/decisions.md | 3 ++- 5 files changed, 53 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 6cd39f839..3abbaaa77 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -514,8 +514,8 @@ pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result wb.sheet(sheet).map(|sh| csv(wb, sh, wb.csv_delimiter.unwrap_or(b','))).transpose().map(Option::unwrap_or_default), - FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, b'\t')).transpose().map(Option::unwrap_or_default), + FileKind::Csv => wb.sheet(sheet).map(|sh| csv(wb, sh, Some(wb.csv_delimiter.unwrap_or(b',')))).transpose().map(Option::unwrap_or_default), + FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, None)).transpose().map(Option::unwrap_or_default), FileKind::Json => crate::macros::json_bytes(wb), FileKind::Html => to_html(wb, sheet).map(String::into_bytes), } @@ -544,8 +544,9 @@ pub fn source_path(path: &str) -> Option { /// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all /// characters in each cell" (Microsoft Support, *Excel formatting and features that are not /// transferred to other file formats*): number formats applied, never column-width `#####`. -fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result> { - gridcraft_xlsx::write_csv(sh, delimiter, |c| { +/// `delimiter` `None` writes a tab-separated file (`.tsv`, `.txt`). +fn csv(wb: &Workbook, sh: &Sheet, delimiter: Option) -> Result> { + let text = |c: CellRef| { // General's grid-width formatting rounds large identifiers to scientific notation. // Delimited files have no column width, so preserve the whole numeric value instead. if wb.styles.get(sh.style_id(c)).num_fmt.as_str().eq_ignore_ascii_case("General") @@ -556,7 +557,11 @@ fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result> { } else { crate::display::value_text(wb, sh, c) } - }) + }; + match delimiter { + Some(d) => gridcraft_xlsx::write_csv(sh, d, text), + None => gridcraft_xlsx::write_tsv(sh, text), + } .map_err(|e| EngineError::Other(e.to_string())) } diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index 00ce6588a..626640b52 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -415,6 +415,26 @@ fn csv_open_honours_a_sep_line_and_saves_a_file_that_reopens_in_columns() { assert_eq!(txt.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=|")); } +/// A first cell that reads like a `sep=` line needs one of its own only in a CSV. A `.tsv` is read +/// with tabs given, so a `sep=` line there would come back as an extra row above the data. +#[test] +fn tsv_save_writes_no_sep_line_and_reopens_in_place() { + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("sep=;")); + sh.set_value(CellRef::new(1, 0), gridcraft_core::Value::text("x")); + let saved = save_bytes(&wb, "list.tsv").unwrap(); + assert_eq!(saved, b"sep=;\r\nx\r\n"); + let (again, _) = open_bytes("list.tsv", &saved).unwrap(); + let text = |r: u32| again.sheet(0).unwrap().value(CellRef::new(r, 0)).as_text().map(str::to_string); + assert_eq!((text(0), text(1)), (Some("sep=;".into()), Some("x".into()))); + // Saved as CSV, the same sheet keeps its protective line, which reading drops again. + let csv = save_bytes(&wb, "list.csv").unwrap(); + assert_eq!(csv, b"sep=,\r\nsep=;\r\nx\r\n"); + let (again, _) = open_bytes("list.csv", &csv).unwrap(); + assert_eq!(again.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 058e34620..c02c881b1 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -594,7 +594,25 @@ pub fn write_csv(sheet: &Sheet, delimiter: u8, cell_text: impl FnMut(CellRef) -> } /// [`write_csv`] with the output cap `limit` (bytes) given. -pub fn write_csv_limited(sheet: &Sheet, delimiter: u8, limit: usize, mut cell_text: impl FnMut(CellRef) -> String) -> Result, IoError> { +pub fn write_csv_limited(sheet: &Sheet, delimiter: u8, limit: usize, cell_text: impl FnMut(CellRef) -> String) -> Result, IoError> { + write_delimited(sheet, delimiter, limit, true, cell_text) +} + +/// The sheet as tab-separated text (`.tsv`, `.txt`), like [`write_csv`] with tabs. Such a file is +/// read with tabs given, never by detection, so a first cell like `sep=;` stays data without the +/// `sep=` line a CSV needs: that line would come back as an extra row. +pub fn write_tsv(sheet: &Sheet, cell_text: impl FnMut(CellRef) -> String) -> Result, IoError> { + write_delimited(sheet, b'\t', MAX_CSV_BYTES, false, cell_text) +} + +/// [`write_csv_limited`], and with `sep_guard` a first row that reads as a `sep=` line gets one. +fn write_delimited( + sheet: &Sheet, + delimiter: u8, + limit: usize, + sep_guard: bool, + mut cell_text: impl FnMut(CellRef) -> String, +) -> Result, IoError> { let delim = if delimiter == 0 { ',' } else { delimiter as char }; let mut out = String::new(); let Some(r) = sheet.used_range() else { return Ok(Vec::new()) }; @@ -641,7 +659,7 @@ pub fn write_csv_limited(sheet: &Sheet, delimiter: u8, limit: usize, mut cell_te } // A first row that would read as Excel's `sep=` line (a lone `sep=;` cell) stays data behind a // `sep=` line of its own naming the delimiter, which GridCraft and Excel both drop on opening. - if out.split(['\r', '\n']).next().is_some_and(|first| sep_line(first, '"').is_some()) { + if sep_guard && out.split(['\r', '\n']).next().is_some_and(|first| sep_line(first, '"').is_some()) { out.insert_str(0, &format!("sep={delim}\r\n")); } Ok(out.into_bytes()) diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index 4d5038012..5b3ade63a 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -48,7 +48,7 @@ use gridcraft_core::DateSystem; use gridcraft_model::Workbook; pub use crypto::{DecryptError, check_encryption, decrypt}; -pub use csv::{MAX_CSV_BYTES, decode_text, read_csv, read_csv_with_report, write_csv, write_csv_limited}; +pub use csv::{MAX_CSV_BYTES, decode_text, read_csv, read_csv_with_report, write_csv, write_csv_limited, write_tsv}; pub use ods::read_ods; pub use package::MAX_PART; pub use passthrough::rebase_links; diff --git a/docs/decisions.md b/docs/decisions.md index c51d5ae52..a208fdd96 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -141,7 +141,8 @@ tabs) keeps it. Saving: Excel writes its list separator and drops the line. Grid with the separator it was read with, so it keeps a named `,` `;` or tab only when detection picks it again on reopening; otherwise (`|`, or `sep=;` over text with as many commas) it saves commas, which reopen in the same columns. A first row that would itself read as a `sep=` line (a lone -`sep=;` cell) is written behind a `sep=` line naming the delimiter, so it stays data. Excel writes +`sep=;` cell) is written behind a `sep=` line naming the delimiter, so it stays data; a `.tsv` +or `.txt` file is read with tabs given, so it gets no such line. Excel writes such a row bare (`"sep=;";`) and reopens the file garbled (observed: A1 `sep=;;`, row 2 in one cell). From Text/CSV still guesses its own delimiter; making it detect like File › Open (and so honour From 3316bac277e4cf99396b3bbcfeeb9582663f8271 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:16:13 +0100 Subject: [PATCH 4/6] CSV: a save that would reopen with another delimiter names its own (#1446) Saving drops quotes a field no longer needs, so `"a,b";x` read with `;` was written `a,b;x`, a tie that detection gives to comma, and `a;b;c|d;e;f` saved with commas read back as `;`. The `sep=` line the first-row guard already writes now also goes first whenever detection on the written text would pick another delimiter. Test: csv_save_names_its_delimiter_when_reopening_would_pick_another (fails without the fix). decisions.md no longer promises more than this. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/io/tests.rs | 19 +++++++++++++++++++ crates/xlsx/src/csv.rs | 9 ++++++--- docs/decisions.md | 11 +++++++---- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index 626640b52..c1166b4cc 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -417,6 +417,25 @@ fn csv_open_honours_a_sep_line_and_saves_a_file_that_reopens_in_columns() { /// A first cell that reads like a `sep=` line needs one of its own only in a CSV. A `.tsv` is read /// with tabs given, so a `sep=` line there would come back as an extra row above the data. +#[test] +fn csv_save_names_its_delimiter_when_reopening_would_pick_another() { + let cells = |wb: &Workbook| { + let sh = wb.sheet(0).unwrap(); + (0..2).map(|c| sh.value(CellRef::new(0, c)).as_text().map(str::to_string)).collect::>() + }; + // Read with `;`; saved, `a,b` loses its quotes and the line has one comma and one semicolon, + // which detection alone would read as comma-separated. + let (wb, _) = open_bytes("tie.csv", b"sep=;\r\n\"a,b\";x\r\n").unwrap(); + let saved = save_bytes(&wb, "tie.csv").unwrap(); + assert_eq!(saved, b"sep=;\r\na,b;x\r\n"); + assert_eq!(cells(&open_bytes("tie.csv", &saved).unwrap().0), [Some("a,b".into()), Some("x".into())]); + // `|` is saved as commas; semicolons in the values would make detection pick `;`. + let (wb, _) = open_bytes("pipe.csv", b"sep=|\r\na;b;c|d;e;f\r\n").unwrap(); + let saved = save_bytes(&wb, "pipe.csv").unwrap(); + assert_eq!(saved, b"sep=,\r\na;b;c,d;e;f\r\n"); + assert_eq!(cells(&open_bytes("pipe.csv", &saved).unwrap().0), [Some("a;b;c".into()), Some("d;e;f".into())]); +} + #[test] fn tsv_save_writes_no_sep_line_and_reopens_in_place() { let mut wb = Workbook::new(); diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index c02c881b1..01120e29f 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -657,9 +657,12 @@ fn write_delimited( return Err(too_large(format!("more than {} MiB (stopped at row {})", limit >> 20, row + 1))); } } - // A first row that would read as Excel's `sep=` line (a lone `sep=;` cell) stays data behind a - // `sep=` line of its own naming the delimiter, which GridCraft and Excel both drop on opening. - if sep_guard && out.split(['\r', '\n']).next().is_some_and(|first| sep_line(first, '"').is_some()) { + // A `sep=` line naming the delimiter, which GridCraft and Excel both drop on opening, goes first + // when the file wouldn't reopen in the same columns without it: a first row that would read as + // Excel's `sep=` line (a lone `sep=;` cell) stays data, and output that detection would read + // with another delimiter (`a,b;x` once `"a,b"` lost its quotes) keeps its own. + let first_is_sep = out.split(['\r', '\n']).next().is_some_and(|first| sep_line(first, '"').is_some()); + if sep_guard && (first_is_sep || sniff_delimiter(&out, '"') != delim as u8) { out.insert_str(0, &format!("sep={delim}\r\n")); } Ok(out.into_bytes()) diff --git a/docs/decisions.md b/docs/decisions.md index 01a288c0a..e96b121c1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -142,10 +142,13 @@ 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 keeps a named `,` `;` or tab only when detection picks -it again on reopening; otherwise (`|`, or `sep=;` over text with as many commas) it saves commas, -which reopen in the same columns. A first row that would itself read as a `sep=` line (a lone -`sep=;` cell) is written behind a `sep=` line naming the delimiter, so it stays data; a `.tsv` -or `.txt` file is read with tabs given, so it gets no such line. Excel writes +it again on reopening; otherwise (`|`, or `sep=;` over text with as many commas) it saves commas. +Saving drops quotes a field no longer needs, so the written text can still read differently +(`"a,b";x` saved with `;` is `a,b;x`, a tie that detection gives to comma; `a;b;c|d;e;f` saved with +commas is `a;b;c,d;e;f`, which detection reads as `;`). Whenever detection on the written text would +pick another delimiter, or a first row would itself read as a `sep=` line (a lone `sep=;` cell), the +file starts with a `sep=` line naming its delimiter, so it reopens in the same columns. A `.tsv` or +`.txt` file is read with tabs given, so it gets no such line. Excel writes such a row bare (`"sep=;";`) and reopens the file garbled (observed: A1 `sep=;;`, row 2 in one cell). From Text/CSV still guesses its own delimiter; making it detect like File › Open (and so honour From a7ae5a86680d23e47d7d21dc4cc9dff2c5150e13 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:14:13 +0100 Subject: [PATCH 5/6] CSV: the sep= line counts against the output limit (#1446) A save that puts a sep= line first checks the limit with the line included, so a file at the cap is refused instead of growing past it. The CSV row in file-format-parity.md now says when a sep= line is written. Co-Authored-By: Claude Opus 5.5 --- crates/xlsx/src/csv.rs | 7 ++++++- crates/xlsx/src/tests/csv_tests.rs | 10 ++++++++++ docs/file-format-parity.md | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index cbda4523b..474eff091 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -459,7 +459,12 @@ fn write_delimited( // with another delimiter (`a,b;x` once `"a,b"` lost its quotes) keeps its own. let first_is_sep = out.split(['\r', '\n']).next().is_some_and(|first| sep_line(first, '"').is_some()); if sep_guard && (first_is_sep || sniff_delimiter(&out, '"') != delim as u8) { - out.insert_str(0, &format!("sep={delim}\r\n")); + let line = format!("sep={delim}\r\n"); + // The line counts against the cap like the rows. + if out.len().saturating_add(line.len()) > limit { + return Err(too_large(format!("more than {} MiB with its sep= line", limit >> 20))); + } + out.insert_str(0, &line); } Ok(out.into_bytes()) } diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 730eac922..73f3e34af 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -446,6 +446,16 @@ fn a_named_delimiter_is_kept_only_if_it_would_be_detected_again() { assert_eq!(read_csv(b"sep=;\na;b\n1;2\n", &opts).unwrap().csv_delimiter, Some(b';')); } +#[test] +fn sep_line_counts_against_the_output_limit() { + let mut sheet = Sheet::new("Sheet1"); + sheet.set_value(CellRef::new(0, 0), Value::text("sep=;")); + let text = |c: CellRef| sheet.value(c).as_text().unwrap_or("").to_string(); + // The row is 7 bytes and fits; with the `sep=,` line it needs 14. + assert!(matches!(write_csv_limited(&sheet, b',', 7, text), Err(IoError::TooLarge(_)))); + assert_eq!(write_csv_limited(&sheet, b',', 14, text).unwrap(), b"sep=,\r\nsep=;\r\n"); +} + /// Review of #2270: a first row that looks like a `sep=` line (a lone `sep=;` in A1) is data. Saved /// behind a `sep=,` line it opens as it was; Excel writes it bare and reads it back garbled. #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cfcf5d622..dc7b0a261 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -104,7 +104,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real | 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, or the one an Excel `sep=` first line names, #1446; per-column day/month date-order detection for `/` and `-` dates) | 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, and so do we; `file.exportCsv {values: true}` writes raw values (full precision, ISO 8601 dates) for automation. 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; per-column day/month date-order detection for `/` and `-` dates) | 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 `,`, also for a `sep=` delimiter that detection wouldn't pick again; a `sep=` line goes first when detection would read the saved text with another delimiter, #1446) | Excel writes the **displayed** values, and so do we; `file.exportCsv {values: true}` writes raw values (full precision, ISO 8601 dates) for automation. 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; per-column day/month date-order detection for `/` and `-` dates) | 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, or the one an Excel `sep=` first line names, #1446; per-column day/month date-order detection for `/` and `-` dates) | yes (UTF-8 without BOM, CRLF) | Writes the **displayed** values like Excel (number formats applied, formula results, never column-width `#####`); `file.exportCsv {values: true}` writes raw values instead. 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; per-column day/month date-order detection for `/` and `-` dates) | yes (displayed values) | Text Import Wizard options partly via Text to Columns | From bdf7d657a4711bd8b6daa6f22b45d0a7e184ea9d Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:48:14 +0100 Subject: [PATCH 6/6] CSV: a sep= stand-in is never a character the file holds (#1446) The stand-in delimiter for a sep= line that names none is now chosen once over the whole body: a free noncharacter, else any free character. A text that holds every character is refused instead of being split at U+FDD0. Co-Authored-By: Claude Opus 5.5 --- crates/xlsx/src/csv.rs | 48 ++++++++++++++++++++---------- crates/xlsx/src/tests/csv_tests.rs | 22 +++++++++++--- 2 files changed, 50 insertions(+), 20 deletions(-) diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index 474eff091..5e5f86865 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -40,23 +40,28 @@ pub(crate) fn sep_line(text: &str, quote: char) -> Option<(Option, usize)> } } -/// [`craft_csv::parse_records`] with a record kept to the grid's [`MAX_COLS`] fields. Without a -/// delimiter each line is one field; without a quote character nothing is quoted. -fn parse_records(text: &str, delim: Option, quote: Option, on_record: impl FnMut(Vec) -> bool) { - // craft-csv always splits and unquotes, so a character the text doesn't hold stands in. - let (delim, quote) = match (delim, quote) { - (Some(d), Some(q)) => (d, q), - _ => { - let [d, q] = unused_chars(text); - (delim.unwrap_or(d), quote.unwrap_or(q)) - } - }; +/// [`craft_csv::parse_records`] with a record kept to the grid's [`MAX_COLS`] fields. +fn parse_records(text: &str, delim: char, quote: char, on_record: impl FnMut(Vec) -> bool) { craft_csv::parse_records(text, delim, quote, MAX_COLS as usize, on_record); } -/// Two Unicode noncharacters (U+FDD0 to U+FDEF, which exchanged text doesn't use) that `text` -/// doesn't hold. A text that holds them all is hostile: it gets the first two, and is split there. -fn unused_chars(text: &str) -> [char; 2] { +/// The delimiter and quote character to read `text` with. craft-csv always splits and unquotes, so +/// for a `sep=` line that names no delimiter (each line is one field) or names the quote (nothing is +/// quoted), a character `text` doesn't hold stands in: a Unicode noncharacter (U+FDD0 to U+FDEF, +/// which exchanged text doesn't use), else any other. A text that holds every character leaves +/// none, and is refused rather than split at one of its own. +fn stand_ins(text: &str, delim: Option, quote: Option) -> Result<(char, char), IoError> { + if let (Some(d), Some(q)) = (delim, quote) { + return Ok((d, q)); + } + let [d, q] = unused_chars(text) + .ok_or_else(|| IoError::Format("the file holds every character, so its fields can't be read without a delimiter".into()))?; + Ok((delim.unwrap_or(d), quote.unwrap_or(q))) +} + +/// Two characters `text` doesn't hold: noncharacters when it leaves two of them free, else the +/// first two free scalar values (a 136 KiB bitset, only for a text holding all 32 noncharacters). +fn unused_chars(text: &str) -> Option<[char; 2]> { const FIRST: u32 = 0xFDD0; let mut used = 0u32; for c in text.chars() { @@ -65,7 +70,17 @@ fn unused_chars(text: &str) -> [char; 2] { } } let mut free = (0..32).filter(|i| used & (1 << i) == 0).filter_map(|i| char::from_u32(FIRST + i)); - [free.next().unwrap_or('\u{FDD0}'), free.next().unwrap_or('\u{FDD1}')] + if let (Some(d), Some(q)) = (free.next(), free.next()) { + return Some([d, q]); + } + let mut all = vec![0u64; 0x11_0000 / 64]; + for c in text.chars() { + if let Some(w) = all.get_mut(c as usize / 64) { + *w |= 1 << (c as u32 % 64); + } + } + let mut free = (0..0x11_0000u32).filter(|&u| all.get(u as usize / 64).is_some_and(|w| w & (1 << (u % 64)) == 0)).filter_map(char::from_u32); + Some([free.next()?, free.next()?]) } /// How many rows and bytes of a text file are read to decide each column's date order. @@ -215,7 +230,7 @@ fn valid_date(sys: DateSystem, year: i64, month: i64, day: i64) -> Option { } /// The first records of the file, bounded by rows and bytes, for date-order inference. -fn sample_records(text: &str, delim: Option, quote: Option) -> Vec> { +fn sample_records(text: &str, delim: char, quote: char) -> Vec> { let mut cut = text.len().min(DATE_SAMPLE_BYTES); while !text.is_char_boundary(cut) { cut -= 1; @@ -325,6 +340,7 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook (text.as_str(), Some(delim), Some(quote)) } }; + let (delim, quote) = stand_ins(body, delim, quote)?; let date_columns = if opts.parse_values { infer_date_rules(&sample_records(body, delim, quote), opts.date_system) } else { vec![] }; let mut report = ReadReport::default(); date_warnings(&date_columns, &mut report); diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 73f3e34af..5642c9971 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -493,11 +493,25 @@ fn csv_used_range_limit_is_enforced_while_reading() { } /// `sep=` naming nothing reads through craft-csv with a stand-in delimiter the text doesn't hold -/// (`sep_line_names_the_delimiter` has the usual cases). A text holding every stand-in still opens. +/// (`sep_line_names_the_delimiter` has the usual cases). A text holding every noncharacter still +/// opens whole: another character stands in. Review of #2270: it was split at U+FDD0. #[test] fn sep_line_stand_in_survives_a_text_holding_every_stand_in() { let all: String = (0xFDD0..=0xFDEF).filter_map(char::from_u32).collect(); - let text = format!("sep=\r\nx{all}y\r\n"); - let wb = read_csv(text.as_bytes(), &CsvOptions { delimiter: 0, ..Default::default() }).unwrap(); - assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(0, 0)), Value::text("x"), "split at the first stand-in"); + let text = format!("sep=\r\nx{all}y\r\n\0z\r\n"); + let wb = read_csv(text.as_bytes(), &CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }).unwrap(); + let sh = wb.sheet(0).unwrap(); + assert_eq!(sh.value(CellRef::new(0, 0)), Value::text(format!("x{all}y")), "the whole line is one field"); + assert_eq!(sh.value(CellRef::new(0, 1)), Value::Empty); + assert_eq!(sh.value(CellRef::new(1, 0)), Value::text("\0z")); +} + +/// A text that holds every character leaves nothing to stand in for the missing delimiter: it's +/// refused, not split at one of its own characters. +#[test] +fn sep_line_without_a_free_stand_in_is_refused() { + let all: String = (0..=0x10_FFFF).filter_map(char::from_u32).filter(|c| !matches!(c, '\r' | '\n')).collect(); + let text = format!("sep=\r\n{all}\r\n"); + let opts = CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }; + assert!(matches!(read_csv(text.as_bytes(), &opts), Err(IoError::Format(_)))); }