diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 31c183663..e7efd6c84 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -532,8 +532,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), } @@ -567,8 +567,14 @@ pub fn source_path(path: &str) -> Option { /// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as /// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers /// that `&` writes in scientific notation as their 15 digits in full. -fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result> { - gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string())) +/// `delimiter` `None` writes a tab-separated file (`.tsv`, `.txt`). +fn csv(wb: &Workbook, sh: &Sheet, delimiter: Option) -> Result> { + let text = |c| 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())) } /// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index 4a775bd56..61f1376fd 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -518,6 +518,64 @@ fn csv_save_keeps_the_separator_it_was_opened_with() { 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=|")); +} + +/// 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(); + 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 87955432f..d406c9a8f 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -16,11 +16,73 @@ pub const MAX_CSV_BYTES: usize = 512 << 20; pub use craft_csv::{decode_text, sniff_delimiter}; +/// 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, + } +} + /// [`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); } +/// 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() { + if let Some(i) = (c as u32).checked_sub(FIRST).filter(|&i| i < 32) { + used |= 1 << i; + } + } + let mut free = (0..32).filter(|i| used & (1 << i) == 0).filter_map(|i| char::from_u32(FIRST + i)); + 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. const DATE_SAMPLE_ROWS: usize = 200; const DATE_SAMPLE_BYTES: usize = 1 << 20; @@ -254,16 +316,34 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook, ReadReport), IoError> { 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 date_columns = if opts.parse_values { infer_date_rules(&sample_records(&text, delim, quote), opts.date_system) } else { vec![] }; - let mut report = ReadReport::default(); - date_warnings(&date_columns, &mut report); 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 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. + (body, 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 (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); let mut sheet = Sheet::new("Sheet1"); let mut styles = std::mem::take(&mut wb.styles); let mut fmt_cache: Vec<(&'static str, StyleId)> = vec![]; @@ -271,7 +351,7 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook // The bounding box of the non-empty cells, which is the sheet's used range. let mut used: Option<(u32, u32, u32, u32)> = None; let mut too_many = false; - parse_records(&text, delim, quote, |rec| { + parse_records(body, delim, quote, |rec| { if row >= MAX_ROWS { return false; } @@ -339,7 +419,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()) }; @@ -371,5 +469,18 @@ 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 `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) { + 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/lib.rs b/crates/xlsx/src/lib.rs index 29071cff2..a1537533d 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/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index da537c104..7e0b21062 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -418,6 +418,102 @@ fn parser_stops_collecting_fields_at_max_cols() { 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"); +} + +/// 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';')); +} + +#[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] +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"); +} + #[test] fn a_field_over_32767_characters_is_cut() { let src = format!("{},{},'{}", "x".repeat(40_000), "y".repeat(32_768), "z".repeat(40_000)); @@ -445,3 +541,27 @@ fn csv_used_range_limit_is_enforced_while_reading() { // No limit by default. assert!(read_csv(dense, &CsvOptions::default()).is_ok()); } + +/// `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 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\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(_)))); +} diff --git a/docs/decisions.md b/docs/decisions.md index 2440e3416..e88863c2f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -159,3 +159,29 @@ errs on the wide side; a UI test checks that the real font then draws the number Excel doesn't widen when a value is entered into a cell that already has the format (observed through the `Value` property: the cell shows `####`), and neither does GridCraft. Typing into such a cell wasn't observed. + +## 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 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. +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 +`sep=`) is another part of #1446. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 57c66fd8f..70889f906 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-23 · **Change:** minor (an unedited embedded chart keeps its original XML on save (#1668); .xls data validation is read; earlier: form controls: buttons, scroll bars and spin buttons read and written; web pages open their first table as a sheet; external-source PivotTables and the Data Model are kept on save when their connections are kept; earlier: one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)` and prints at 176×250 mm instead of the old Letter fallback, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .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; earlier: `file.exportCsv {values: true}` writes raw values for automation; .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; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-23 · **Change:** minor (CSV: an Excel `sep=` first line names the delimiter and isn't read as data, #1446; earlier: an unedited embedded chart keeps its original XML on save (#1668); .xls data validation is read; earlier: form controls: buttons, scroll bars and spin buttons read and written; web pages open their first table as a sheet; external-source PivotTables and the Data Model are kept on save when their connections are kept; earlier: one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)` and prints at 176×250 mm instead of the old Letter fallback, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .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; earlier: `file.exportCsv {values: true}` writes raw values for automation; .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; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **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** @@ -107,7 +107,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; 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 `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`); `file.exportCsv {values: true}` writes raw values (full precision, ISO 8601 dates) for automation. **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it with the 15 significant digits `&` gives (`0.333333333333333`, `0.3`, not `0.30000000000000004`) but never with an exponent, since reopening the file would give the cell a scientific format that rounds it on the next save: a number of 1E+15 or more is written as the shortest digits that read back as the same value (every integer below 1e16 exactly, so 16-digit card and order numbers survive: `9007199254740993` is stored and written as `9007199254740992`, `12345678901234567` as `12345678901234568`), a small one as its 15 digits in full (`0.00000128233995888454`). A CSV GridCraft wrote, opened and saved again, is unchanged. A CSV from elsewhere can change on its first save: a decimal with 16 or 17 significant digits is cut to 15, as in Excel (`3.141592653589793` → `3.14159265358979`), and a number typed in scientific notation gets the `0.00E+00` format on open and is saved rounded to it (`1.23456789012346E-10` → `1.23E-10`, unchanged from before). The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. 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) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`); `file.exportCsv {values: true}` writes raw values (full precision, ISO 8601 dates) for automation. **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it with the 15 significant digits `&` gives (`0.333333333333333`, `0.3`, not `0.30000000000000004`) but never with an exponent, since reopening the file would give the cell a scientific format that rounds it on the next save: a number of 1E+15 or more is written as the shortest digits that read back as the same value (every integer below 1e16 exactly, so 16-digit card and order numbers survive: `9007199254740993` is stored and written as `9007199254740992`, `12345678901234567` as `12345678901234568`), a small one as its 15 digits in full (`0.00000128233995888454`). A CSV GridCraft wrote, opened and saved again, is unchanged. A CSV from elsewhere can change on its first save: a decimal with 16 or 17 significant digits is cut to 15, as in Excel (`3.141592653589793` → `3.14159265358979`), and a number typed in scientific notation gets the `0.00E+00` format on open and is saved rounded to it (`1.23456789012346E-10` → `1.23E-10`, unchanged from before). The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. 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, with General numbers as for `.csv`) | Text Import Wizard options partly via Text to Columns | | `.prn` formatted text (space-delimited) | R/W | no | no | | | `.slk` SYLK | R/W | **yes, partial** (#1481) | no (Save As `.xlsx`) | Values (numbers, text, booleans, errors), formulas converted from R1C1 to A1 as Excel does (relative and absolute references, ranges, whole rows and columns, shared formulas) with their cached results, number formats (`P`/`F;P`), column widths (`F;W`); the sheet is named after the file. Not read: fonts and cell styles, row heights, names, comments. Non-UTF-8 files are read as Latin-1 | engine `io/tests.rs` (`sylk_*`) | @@ -198,6 +198,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-26 | minor | Arabic PDF export embeds licensed glyph outlines, joins letters and marks, preserves logical text and reports unsupported glyphs before writing; Arabic runs take the embedded faces ahead of the CJK CID font, and CJK inside Arabic text is set in the CID font instead of failing the export | | 2026-10-26 | minor | Alignment readingOrder 0/1/2 survives cell, named-style and differential-style round-trips; Format Cells exposes reading direction and CF priority preserves unspecified inheritance | | 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921); a read-only open refuses Save to its own file; SHA-1 modify hashes verify; an encrypted and reserved file asks for the modify password after its decryption password | +| 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-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet as set by hand (the shared craft-xls reader does not report fBestFit) (#1077) | | 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`) |