mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-13 14:02:45 +00:00
Gap 19: ODT contextual spacing and LibreOffice layout settings
Contextual spacing (`style:contextual-spacing`, ODF 1.3 §20.255: no space between paragraphs of one style) is read from paragraph, custom and kind styles and written back, and the List Paragraph style is written like any other, so bulleted items keep their spacing; they were written in Standard and spread apart. LibreOffice switches many layout behaviours by `settings.xml`, and a file without them is laid out its own way. A file's own `settings.xml` is now kept through a save; a document from elsewhere gets the switches LibreOffice uses for Word files, as WordCraft lays text out as Word does. Tab stops are written from the margin either way. A Word-made document saved as ODT drew 38,652 px apart from LibreOffice's own ODT of it; now 3,302, with the same line breaks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GBVQLyDnrG8Tn1yDQcUabC
This commit is contained in:
12 files changed
+225
-18
No files matched your search
+2
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › UnderlLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (English dialects in proofing, #1281; previously trivial: triple borders draw three lines, #1740; previously trivial: progress log: double-clicking a later page's footer no longer scrolls up, #2103; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below.
|
||||
|
||||
@@ -140,6 +140,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-01: ODT: saved files carry LibreOffice's layout settings (the file's own, or Word-compatible ones), so LibreOffice lays them out as WordCraft does; list items keep their contextual spacing (gap 19). Readiness unchanged.
|
||||
- 2026-11-01: ODT: custom character styles stay styles on open and save (gap 19). Readiness unchanged.
|
||||
- 2026-11-01: ODT: custom paragraph styles (LibreOffice's Text body, your own) stay styles on open and save; their formatting used to become direct formatting (gap 19). Readiness unchanged.
|
||||
- 2026-11-01: ODT: equations are saved as LibreOffice formula objects (MathML), so they stay equations in LibreOffice; they were saved as plain text (gap 19). Readiness unchanged.
|
||||
|
||||
@@ -146,7 +146,6 @@ pub fn is_custom_style(doc: &Document, id: &str) -> bool {
|
||||
"Title",
|
||||
"Quote",
|
||||
super::types::CODE_STYLE,
|
||||
"ListParagraph",
|
||||
"FootnoteText",
|
||||
"EndnoteText",
|
||||
"Standard",
|
||||
@@ -163,7 +162,7 @@ pub fn is_custom_style(doc: &Document, id: &str) -> bool {
|
||||
fn para_extra(doc: &Document, p: &wordcraft_doc::props::ParaProps) -> Option<Box<wordcraft_doc::props::ParaProps>> {
|
||||
let tabs = p.tabs.clone().filter(|t| !t.is_empty());
|
||||
let style = p.style.clone().filter(|id| is_custom_style(doc, id));
|
||||
let x = wordcraft_doc::props::ParaProps { tabs, shading: p.shading, style, ..Default::default() };
|
||||
let x = wordcraft_doc::props::ParaProps { tabs, shading: p.shading, style, contextual_spacing: p.contextual_spacing, ..Default::default() };
|
||||
(x != wordcraft_doc::props::ParaProps::default()).then(|| Box::new(x))
|
||||
}
|
||||
|
||||
|
||||
@@ -143,6 +143,9 @@ fn para_props(p: &Para, list_num: Option<u32>) -> ParaProps {
|
||||
if let Some(st) = p.extra.as_ref().and_then(|x| x.style.clone()) {
|
||||
out.style = Some(st);
|
||||
}
|
||||
if let Some(c) = p.extra.as_ref().and_then(|x| x.contextual_spacing) {
|
||||
out.contextual_spacing = Some(c);
|
||||
}
|
||||
if let Some(bg) = p.extra.as_ref().and_then(|x| x.shading) {
|
||||
out.shading = Some(bg);
|
||||
}
|
||||
|
||||
@@ -554,6 +554,9 @@ impl Body<'_> {
|
||||
if let Some(bg) = look.shading {
|
||||
p.extra.get_or_insert_with(Default::default).shading = Some(bg);
|
||||
}
|
||||
if let Some(c) = look.contextual {
|
||||
p.extra.get_or_insert_with(Default::default).contextual_spacing = Some(c);
|
||||
}
|
||||
if let Some(mut tabs) = look.tabs {
|
||||
// LibreOffice measures tabs from the indent (its `TabsRelativeToIndent`); Word from
|
||||
// the margin.
|
||||
|
||||
@@ -245,6 +245,7 @@ fn add_custom_styles(doc: &mut Document, named: &[super::styles::NamedStyle], od
|
||||
borders: look.borders,
|
||||
shading: look.shading,
|
||||
tabs: look.tabs.clone(),
|
||||
contextual_spacing: look.contextual,
|
||||
..Default::default()
|
||||
};
|
||||
let style = wordcraft_doc::styles::Style {
|
||||
@@ -279,6 +280,9 @@ fn apply_look(doc: &mut Document, kind: model::Kind, look: &super::styles::ParaL
|
||||
(p.indent_left, p.indent_right, p.indent_first) = (sp.left, sp.right, sp.first);
|
||||
p.align = look.align;
|
||||
p.keep_next = look.keep_next.then_some(true);
|
||||
if look.contextual.is_some() {
|
||||
p.contextual_spacing = look.contextual;
|
||||
}
|
||||
}
|
||||
|
||||
/// Number the headings as the outline style `levels` does (ODF 1.3 §16.34): one list whose
|
||||
@@ -366,6 +370,8 @@ struct Parsed {
|
||||
char_styles: Vec<(String, String)>,
|
||||
/// Their names, parents and own formatting, alongside.
|
||||
char_defs: Vec<(String, Option<String>, model::Fmt)>,
|
||||
/// The file's `settings.xml`, kept for the next save.
|
||||
settings: Option<Vec<u8>>,
|
||||
/// The heading numbering (`text:outline-style`), level by level.
|
||||
outline: Option<Vec<super::styles::ListLevel>>,
|
||||
/// How the file's heading, title, quotation and preformatted styles look.
|
||||
@@ -397,7 +403,8 @@ fn parse_tracked(bytes: &[u8]) -> Result<Parsed, String> {
|
||||
pages = read_pages(s);
|
||||
}
|
||||
styles.read(&content, true);
|
||||
styles.tabs_from_indent = read_entry(&mut z, "settings.xml").map(|s| setting(&s, "TabsRelativeToIndent")).unwrap_or(None).unwrap_or(true);
|
||||
let settings = read_entry(&mut z, "settings.xml");
|
||||
styles.tabs_from_indent = settings.as_deref().and_then(|s| setting(s, "TabsRelativeToIndent")).unwrap_or(true);
|
||||
let meta = read_entry(&mut z, "meta.xml").map(|m| read_meta(&m)).unwrap_or_default();
|
||||
let mut pictures = Pictures::new(MAX_ENTRY);
|
||||
let mut fetch = |path: &str| -> Option<Vec<u8>> {
|
||||
@@ -445,6 +452,7 @@ fn parse_tracked(bytes: &[u8]) -> Result<Parsed, String> {
|
||||
named_odt,
|
||||
char_styles,
|
||||
char_defs,
|
||||
settings: settings.filter(|s| s.len() <= super::package::MAX_SETTINGS),
|
||||
outline: styles.outline.clone(),
|
||||
kern: styles.default_kern,
|
||||
default_tab: styles.default_tab,
|
||||
@@ -455,7 +463,7 @@ fn parse_tracked(bytes: &[u8]) -> Result<Parsed, String> {
|
||||
/// Parse an `.odt` package into a document.
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
model::begin_import();
|
||||
let Parsed { flow, last, track, font, spacing, looks, named, named_odt, char_styles, char_defs, outline, kern, default_tab, parts } =
|
||||
let Parsed { flow, last, track, font, spacing, looks, named, named_odt, char_styles, char_defs, settings, outline, kern, default_tab, parts } =
|
||||
parse_tracked(bytes)?;
|
||||
let mut doc = model::to_doc(&flow);
|
||||
if font.is_some() {
|
||||
@@ -471,6 +479,9 @@ pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
for (kind, look) in &looks {
|
||||
apply_look(&mut doc, *kind, look);
|
||||
}
|
||||
if let Some(s) = settings {
|
||||
doc.passthrough.insert(super::package::SETTINGS_PART.into(), std::sync::Arc::new(s));
|
||||
}
|
||||
add_custom_styles(&mut doc, &named, &named_odt);
|
||||
add_char_styles(&mut doc, &char_styles, &char_defs);
|
||||
if let Some(levels) = &outline {
|
||||
|
||||
@@ -43,6 +43,9 @@ fn kind_styles(doc: &Document) -> String {
|
||||
if pp.keep_next == Some(true) {
|
||||
para.push_str(" fo:keep-with-next=\"always\"");
|
||||
}
|
||||
if let Some(c) = pp.contextual_spacing {
|
||||
para.push_str(&format!(" style:contextual-spacing=\"{c}\""));
|
||||
}
|
||||
let outline = outline.map(|n| format!(" style:default-outline-level=\"{n}\"")).unwrap_or_default();
|
||||
s.push_str(&format!(
|
||||
"<style:style style:name=\"{name}\" style:display-name=\"{display}\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:next-style-name=\"Standard\"{outline} style:class=\"{class}\"><style:paragraph-properties{para}/><style:text-properties{}/></style:style>",
|
||||
@@ -96,6 +99,9 @@ fn custom_styles(doc: &Document, named: &std::collections::BTreeSet<String>) ->
|
||||
if pp.keep_next == Some(true) {
|
||||
attrs.push_str(" fo:keep-with-next=\"always\"");
|
||||
}
|
||||
if let Some(c) = pp.contextual_spacing {
|
||||
attrs.push_str(&format!(" style:contextual-spacing=\"{c}\""));
|
||||
}
|
||||
attrs.push_str(&super::writer::border_attrs(pp.borders));
|
||||
if let Some(bg) = pp.shading {
|
||||
attrs.push_str(&format!(" fo:background-color=\"#{}\"", bg.hex().to_ascii_lowercase()));
|
||||
@@ -331,15 +337,105 @@ fn styles_xml(
|
||||
s
|
||||
}
|
||||
|
||||
/// `settings.xml` (ODF 1.3 §3.10): tab stops are measured from the margin, as WordCraft's and
|
||||
/// Word's are (LibreOffice's own default measures them from the paragraph's indent).
|
||||
const SETTINGS: &str = concat!(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
|
||||
"<office:document-settings xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:config=\"urn:oasis:names:tc:opendocument:xmlns:config:1.0\" office:version=\"1.3\">",
|
||||
"<office:settings><config:config-item-set config:name=\"ooo:configuration-settings\">",
|
||||
"<config:config-item config:name=\"TabsRelativeToIndent\" config:type=\"boolean\">false</config:config-item>",
|
||||
"</config:config-item-set></office:settings></office:document-settings>\n"
|
||||
);
|
||||
/// `Document::passthrough` key of an ODT's own `settings.xml`, kept for the next save.
|
||||
pub(super) const SETTINGS_PART: &str = "odt/settings.xml";
|
||||
|
||||
/// Largest `settings.xml` kept, in bytes.
|
||||
pub(super) const MAX_SETTINGS: usize = 1 << 20;
|
||||
|
||||
/// LibreOffice's layout compatibility switches (`ooo:configuration-settings`) for a document
|
||||
/// laid out as Word lays it out, as LibreOffice sets them for Word files.
|
||||
const WORD_COMPAT: &[(&str, bool)] = &[
|
||||
("NoNumberingShowFollowBy", true),
|
||||
("HyphenateURLs", false),
|
||||
("FootnoteInColumnToPageEnd", true),
|
||||
("GutterAtTop", false),
|
||||
("ContinuousEndnotes", false),
|
||||
("FrameAutowidthWithMorePara", true),
|
||||
("SubtractFlysAnchoredAtFlys", false),
|
||||
("SurroundTextWrapSmall", true),
|
||||
("TreatSingleColumnBreakAsPageBreak", true),
|
||||
("TabOverSpacing", true),
|
||||
("AutoFirstLineIndentDisregardLineSpace", true),
|
||||
("TabOverMargin", false),
|
||||
("ApplyTextAttrToEmptyLineAtEndOfParagraph", true),
|
||||
("DisableOffPagePositioning", true),
|
||||
("BackgroundParaOverDrawings", true),
|
||||
("TabOverflow", true),
|
||||
("AddVerticalFrameOffsets", true),
|
||||
("AddFrameOffsets", false),
|
||||
("TableRowKeep", true),
|
||||
("ApplyParagraphMarkFormatToNumbering", true),
|
||||
("JustifyLinesWithShrinking", true),
|
||||
("CollapseEmptyCellPara", true),
|
||||
("UnbreakableNumberings", true),
|
||||
("MsWordCompTrailingBlanks", true),
|
||||
("AddParaTableSpacing", false),
|
||||
("OutlineLevelYieldsNumbering", false),
|
||||
("UseOldNumbering", false),
|
||||
("AddParaSpacingToTableCells", true),
|
||||
("PropLineSpacingShrinksFirstLine", true),
|
||||
("TabAtLeftIndentForParagraphsInList", true),
|
||||
("DoNotCaptureDrawObjsOnPage", false),
|
||||
("HeaderSpacingBelowLastPara", true),
|
||||
("ClippedPictures", true),
|
||||
("MathBaselineAlignment", true),
|
||||
("AlignTabStopPosition", true),
|
||||
("UseFormerLineSpacing", false),
|
||||
("DoNotMirrorRtlDrawObjs", true),
|
||||
("AddParaLineSpacingToTableCells", true),
|
||||
("IsKernAsianPunctuation", false),
|
||||
("DoNotJustifyLinesWithManualBreak", false),
|
||||
("UseVariableWidthNBSP", false),
|
||||
("AddParaTableSpacingAtStart", true),
|
||||
("InvertBorderSpacing", true),
|
||||
("AddExternalLeading", true),
|
||||
("UseFormerObjectPositioning", false),
|
||||
("UnxForceZeroExtLeading", false),
|
||||
("UseFormerTextWrapping", false),
|
||||
("ConsiderTextWrapOnObjPos", true),
|
||||
("StylesNoDefault", false),
|
||||
("IgnoreFirstLineIndentInNumbering", false),
|
||||
("NoGapAfterNoteNumber", true),
|
||||
("EmptyDbFieldHidesPara", false),
|
||||
("DoNotResetParaAttrsForNumFont", false),
|
||||
("IgnoreTabsAndBlanksForLineCalculation", true),
|
||||
("ClipAsCharacterAnchoredWriterFlyFrames", false),
|
||||
("DropCapPunctuation", true),
|
||||
("UseOldPrinterMetrics", false),
|
||||
("MsWordCompMinLineHeightByFly", false),
|
||||
];
|
||||
|
||||
/// `settings.xml` (ODF 1.3 §3.10) for `doc`: an ODT's own, kept from opening it, or LibreOffice's
|
||||
/// switches for Word's layout. Either way tab stops are measured from the margin, as WordCraft
|
||||
/// writes them (LibreOffice's own default measures them from the paragraph's indent).
|
||||
fn settings_xml(doc: &Document) -> String {
|
||||
const TABS: &str = "<config:config-item config:name=\"TabsRelativeToIndent\" config:type=\"boolean\">false</config:config-item>";
|
||||
if let Some(own) = doc.passthrough.get(SETTINGS_PART).filter(|b| b.len() <= MAX_SETTINGS).and_then(|b| std::str::from_utf8(b).ok()) {
|
||||
let set = "config:name=\"ooo:configuration-settings\"";
|
||||
let tabs = "config:name=\"TabsRelativeToIndent\"";
|
||||
if let Some(at) = own.find(tabs) {
|
||||
// The file's item, its value made false.
|
||||
let rest = own.get(at..).unwrap_or("");
|
||||
if let (Some(gt), Some(lt)) = (rest.find('>'), rest.find("</config:config-item>"))
|
||||
&& gt < lt
|
||||
{
|
||||
return format!("{}false{}", own.get(..at + gt + 1).unwrap_or(""), own.get(at + lt..).unwrap_or(""));
|
||||
}
|
||||
} else if let Some(at) = own.find(set).and_then(|at| own.get(at..)?.find('>').map(|gt| at + gt + 1)) {
|
||||
return format!("{}{TABS}{}", own.get(..at).unwrap_or(""), own.get(at..).unwrap_or(""));
|
||||
}
|
||||
}
|
||||
let mut s = String::from(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<office:document-settings xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:config=\"urn:oasis:names:tc:opendocument:xmlns:config:1.0\" office:version=\"1.3\"><office:settings><config:config-item-set config:name=\"ooo:configuration-settings\">",
|
||||
);
|
||||
s.push_str(TABS);
|
||||
for (name, on) in WORD_COMPAT {
|
||||
s.push_str(&format!("<config:config-item config:name=\"{name}\" config:type=\"boolean\">{on}</config:config-item>"));
|
||||
}
|
||||
s.push_str("</config:config-item-set></office:settings></office:document-settings>\n");
|
||||
s
|
||||
}
|
||||
|
||||
fn meta_xml(m: &Meta) -> String {
|
||||
let mut s =
|
||||
@@ -484,7 +580,7 @@ pub fn export(doc: &Document) -> Result<Vec<u8>, String> {
|
||||
("content.xml", content.as_bytes()),
|
||||
("styles.xml", styles.as_bytes()),
|
||||
("meta.xml", meta.as_bytes()),
|
||||
("settings.xml", SETTINGS.as_bytes()),
|
||||
("settings.xml", settings_xml(doc).as_bytes()),
|
||||
] {
|
||||
z.start_file(name, deflated).map_err(err)?;
|
||||
z.write_all(data).map_err(ioerr)?;
|
||||
|
||||
@@ -185,6 +185,8 @@ struct StyleInfo {
|
||||
family: Option<String>,
|
||||
/// Declared among automatic styles (of either file): never a custom style.
|
||||
declared_auto: bool,
|
||||
/// `style:contextual-spacing` of a paragraph style.
|
||||
contextual: Option<bool>,
|
||||
/// `fo:border*` of a paragraph style, each side's padding as its distance from the text.
|
||||
para_borders: Option<Borders>,
|
||||
/// `fo:background-color` of a paragraph style (`Some(None)`: transparent, stated).
|
||||
@@ -304,6 +306,8 @@ pub(super) struct ParaLook {
|
||||
pub(super) spacing: Spacing,
|
||||
/// Tab stops, from where the document measures them.
|
||||
pub(super) tabs: Option<Vec<TabStop>>,
|
||||
/// No spacing between paragraphs of one style (`style:contextual-spacing`).
|
||||
pub(super) contextual: Option<bool>,
|
||||
/// Borders (when a side shows) and background.
|
||||
pub(super) borders: Option<Borders>,
|
||||
pub(super) shading: Option<Rgb>,
|
||||
@@ -567,6 +571,9 @@ fn paragraph_properties(a: &Attrs, s: &mut StyleInfo) {
|
||||
if let Some(b) = border_sides(a) {
|
||||
s.para_borders = Some(b);
|
||||
}
|
||||
if let Some(c) = get(a, "style:contextual-spacing") {
|
||||
s.contextual = Some(c.trim() == "true");
|
||||
}
|
||||
if let Some(bg) = get(a, "fo:background-color") {
|
||||
s.para_shading = Some(if bg.trim() == "transparent" { None } else { model::parse_color(bg) });
|
||||
}
|
||||
@@ -962,7 +969,8 @@ impl Styles {
|
||||
}
|
||||
let align = chain.iter().find_map(|(_, s)| s.align);
|
||||
let keep_next = chain.iter().find_map(|(_, s)| s.keep_next).unwrap_or(false);
|
||||
(kind, ParaLook { kind, align, keep_next, fmt, spacing, ..Default::default() })
|
||||
let contextual = chain.iter().find_map(|(_, s)| s.contextual);
|
||||
(kind, ParaLook { kind, align, keep_next, fmt, spacing, contextual, ..Default::default() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1006,6 +1014,7 @@ impl Styles {
|
||||
tabs: s.tabs.clone(),
|
||||
borders: s.para_borders.filter(|b| b.any_visible()),
|
||||
shading: s.para_shading.flatten(),
|
||||
contextual: s.contextual,
|
||||
..Default::default()
|
||||
};
|
||||
let name = s.display.clone().unwrap_or_else(|| odt.replace("_20_", " "));
|
||||
@@ -1062,6 +1071,7 @@ impl Styles {
|
||||
let own = || chain.iter().take(kind_at).filter(|(n, s)| s.auto || *n != "Standard");
|
||||
let borders = own().find_map(|(_, s)| s.para_borders).filter(|b| b.any_visible());
|
||||
let shading = own().find_map(|(_, s)| s.para_shading).flatten();
|
||||
ParaLook { kind, align, page_break: pb, rule, keep_next, fmt: f, spacing, tabs, borders, shading, named }
|
||||
let contextual = own().find_map(|(_, s)| s.contextual);
|
||||
ParaLook { kind, align, page_break: pb, rule, keep_next, fmt: f, spacing, tabs, borders, shading, named, contextual }
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ mod named_styles;
|
||||
mod notes;
|
||||
mod outline;
|
||||
mod para_borders;
|
||||
mod settings;
|
||||
mod spacing;
|
||||
mod style_look;
|
||||
mod tables;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! `settings.xml` (ODF 1.3 §3.10): LibreOffice's layout compatibility switches. A file's own are
|
||||
//! kept through a save; a document from elsewhere gets those LibreOffice uses for Word files, as
|
||||
//! WordCraft lays text out as Word does. Tabs are always written measured from the margin.
|
||||
|
||||
use crate::odt::tests::{NS_T, package};
|
||||
use crate::odt::{export, import};
|
||||
use wordcraft_doc::Document;
|
||||
|
||||
fn settings_of(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("settings.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn item(settings: &str, name: &str) -> Option<String> {
|
||||
let at = settings.find(&format!(r#"config:name="{name}""#))?;
|
||||
let rest = &settings[at..];
|
||||
let v = rest.split_once('>')?.1;
|
||||
Some(v.split('<').next()?.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_document_gets_word_compatible_layout() {
|
||||
let s = settings_of(&export(&Document::new()).unwrap());
|
||||
assert_eq!(item(&s, "TabsRelativeToIndent").as_deref(), Some("false"));
|
||||
assert_eq!(item(&s, "AddParaSpacingToTableCells").as_deref(), Some("true"));
|
||||
assert_eq!(item(&s, "TabOverMargin").as_deref(), Some("false"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_files_own_settings_survive_a_save() {
|
||||
let settings = r#"<?xml version="1.0" encoding="UTF-8"?><office:document-settings xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0"><office:settings><config:config-item-set config:name="ooo:configuration-settings"><config:config-item config:name="AddParaTableSpacing" config:type="boolean">true</config:config-item><config:config-item config:name="TabsRelativeToIndent" config:type="boolean">true</config:config-item></config:config-item-set></office:settings></office:document-settings>"#;
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS_T}><office:body><office:text><text:p>x</text:p></office:text></office:body></office:document-content>"#
|
||||
);
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let o = zip::write::SimpleFileOptions::default();
|
||||
for (n, d) in [("mimetype", "application/vnd.oasis.opendocument.text"), ("content.xml", content.as_str()), ("settings.xml", settings)] {
|
||||
z.start_file(n, o).unwrap();
|
||||
std::io::Write::write_all(&mut z, d.as_bytes()).unwrap();
|
||||
}
|
||||
let d = import(&z.finish().unwrap().into_inner()).unwrap();
|
||||
let s = settings_of(&export(&d).unwrap());
|
||||
assert_eq!(item(&s, "AddParaTableSpacing").as_deref(), Some("true"), "{s}");
|
||||
// Not Word's switches over the file's own.
|
||||
assert_eq!(item(&s, "AddParaSpacingToTableCells"), None);
|
||||
// Tabs are written from the margin, whatever the file said.
|
||||
assert_eq!(item(&s, "TabsRelativeToIndent").as_deref(), Some("false"));
|
||||
let _ = package;
|
||||
}
|
||||
@@ -144,3 +144,31 @@ fn the_document_defaults_round_trip() {
|
||||
let o = d.styles.resolve_para(&ParaProps::default());
|
||||
assert_eq!((r.space_before, r.space_after, r.line_spacing), (o.space_before, o.space_after, o.line_spacing));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contextual_spacing_round_trips() {
|
||||
// `style:contextual-spacing` (ODF 1.3 §20.255): no space between paragraphs of one style.
|
||||
let auto = p_style("P1", "Standard", r#"fo:margin-bottom="10pt" style:contextual-spacing="true""#);
|
||||
let d = import(&package(&content(&auto, r#"<text:p text:style-name="P1">a</text:p>"#), None)).unwrap();
|
||||
assert_eq!(props(&d)[0].contextual_spacing, Some(true));
|
||||
let back = import(&export(&d).unwrap()).unwrap();
|
||||
assert_eq!(props(&back)[0].contextual_spacing, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_paragraph_style_is_written() {
|
||||
// Its spacing (and contextual spacing) was dropped: list items were written in Standard.
|
||||
let mut d = Document::new();
|
||||
let mut p = Paragraph::new();
|
||||
p.text = "item".into();
|
||||
p.runs = vec![wordcraft_doc::para::Run { len: 4, props: Default::default() }];
|
||||
p.props = ParaProps { style: Some("ListParagraph".into()), ..Default::default() };
|
||||
d.body = vec![para_block(p)];
|
||||
if let Some(st) = d.styles.get_mut("ListParagraph") {
|
||||
st.para.contextual_spacing = Some(true);
|
||||
st.para.space_after = Some(3.0);
|
||||
}
|
||||
let back = import(&export(&d).unwrap()).unwrap();
|
||||
let r = back.styles.resolve_para(&props(&back)[0]);
|
||||
assert!(r.contextual_spacing && r.space_after == 3.0, "{r:?}");
|
||||
}
|
||||
@@ -520,6 +520,9 @@ impl Writer {
|
||||
if let Some(bg) = p.extra.as_ref().and_then(|x| x.shading) {
|
||||
props.push_str(&format!(" fo:background-color=\"#{}\"", bg.hex().to_ascii_lowercase()));
|
||||
}
|
||||
if let Some(c) = p.extra.as_ref().and_then(|x| x.contextual_spacing) {
|
||||
props.push_str(&format!(" style:contextual-spacing=\"{c}\""));
|
||||
}
|
||||
let master = start.map(|(m, _)| m.clone()).unwrap_or_default();
|
||||
if props.is_empty() && master.is_empty() {
|
||||
return parent;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity with Microsoft Word
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-31 · **Change:** trivial (ODT custom character styles kept); previously trivial (ODT list level positions); previously trivial (ODT custom paragraph styles kept); previously trivial (ODT equations written as formula objects); previously trivial (ODT numbered headings written as headings); previously trivial (ODT floating pictures); previously trivial (ODT paragraph borders and background); previously trivial (ODT heading numbering); previously trivial (ODT font-face names); previously trivial (ODT table cell borders and padding); previously trivial (ODT heading, title, quote and preformatted styles keep their look); previously trivial (ODT tab stops read and written); previously trivial (ODT character formatting read and written); previously trivial (ODT lists keep their number formats, bullets and identity); previously trivial (ODT comments read and written); previously trivial (ODT footnotes and endnotes read and written); previously trivial (ODT headers, footers and text fields written; fields read); previously trivial (ODT paragraph spacing, indents and line spacing read and written); previously trivial (a paragraph naming an undefined style is formatted as Normal, as in Word, #5077); previously trivial (a hyperlinked TOC writes its page numbers as `PAGEREF _Toc… \h` fields, as Word does, #5097); previously trivial (HTML import ends the empty comments <!--> and <!---> at once, #5040); previously trivial (chart and SmartArt text the font lacks is drawn in a fallback face, so Chinese labels no longer show boxes, #4720); previously trivial (bibliography sources keep a corporate author (`b:Corporate`): read, written, cited and listed whole, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (note conversion preserves content with an ordered reference/run walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (built-in heading styles have their outline level without `w:outlineLvl`, #4696); previously trivial (DOCX comment ranges inside footnotes and endnotes are kept on read, #4548); previously trivial (RTF import and export keep Windows and Enhanced Metafile pictures (`\wmetafile`, `\emfblip`), #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (DOCX parts stored under another casing keep their embedded fonts through a save, and a private save of a kept glossary escapes the attribute values it rewrites; previously trivial: the `.doc` reader logs what its copy budget leaves out, once a kind per document; importers bound hostile expansion: font names, links, ODS repeats, LaTeX wrappers, Markdown delimiters, #3692/#3713; previously trivial: repeated DOCX style IDs: save/reopen regression; previously trivial: Markdown code spans keep line-broken text literal, #3738; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: localized TOC style ids read as the TOC styles, and a TOC in columns keeps its layout through Update Table, #3889; previously trivial: cu20we: outline caps; previously trivial: a relationship the markup names without the prefix is read as it wrote: an unqualified `id` on an element that carries a relationship names that relationship, and the writer keeps the attribute with the id the new package holds the part under; an ordinary `id` — a VML shape's, a drawing's — names no part; previously trivial: the reader takes the relationship ids the markup refers to from the relationship attributes of the main document it has already parsed, so a document with many relationships opens in the time its part takes, #3411; previously trivial: a table cell span from a `.json` file stays within 63 columns through Insert Column and Merge Cells, #3637; previously trivial: the file commands that change the document are checked on a protected document, the protection of a protected document needs an explicit stop, the session author can't change through `file.setAuthor` under protection (the CLI's `--author` uses the same protection check), and the post-check compares the settings and the metadata; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: `majorBidi`/`minorBidi` theme fonts follow the settings' theme font language, as measured in Word; previously trivial: Word signature lines are kept on save, still signable; previously trivial: Times New Roman keeps Liberation Serif under the roman-font rule; previously trivial: shape gradients and transparency, #1500; previously trivial: a folder that keeps no Unix modes, such aLine truncated
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-31 · **Change:** trivial (ODT contextual spacing and layout settings); previously trivial (ODT custom character styles kept); previously trivial (ODT list level positions); previously trivial (ODT custom paragraph styles kept); previously trivial (ODT equations written as formula objects); previously trivial (ODT numbered headings written as headings); previously trivial (ODT floating pictures); previously trivial (ODT paragraph borders and background); previously trivial (ODT heading numbering); previously trivial (ODT font-face names); previously trivial (ODT table cell borders and padding); previously trivial (ODT heading, title, quote and preformatted styles keep their look); previously trivial (ODT tab stops read and written); previously trivial (ODT character formatting read and written); previously trivial (ODT lists keep their number formats, bullets and identity); previously trivial (ODT comments read and written); previously trivial (ODT footnotes and endnotes read and written); previously trivial (ODT headers, footers and text fields written; fields read); previously trivial (ODT paragraph spacing, indents and line spacing read and written); previously trivial (a paragraph naming an undefined style is formatted as Normal, as in Word, #5077); previously trivial (a hyperlinked TOC writes its page numbers as `PAGEREF _Toc… \h` fields, as Word does, #5097); previously trivial (HTML import ends the empty comments <!--> and <!---> at once, #5040); previously trivial (chart and SmartArt text the font lacks is drawn in a fallback face, so Chinese labels no longer show boxes, #4720); previously trivial (bibliography sources keep a corporate author (`b:Corporate`): read, written, cited and listed whole, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (note conversion preserves content with an ordered reference/run walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (built-in heading styles have their outline level without `w:outlineLvl`, #4696); previously trivial (DOCX comment ranges inside footnotes and endnotes are kept on read, #4548); previously trivial (RTF import and export keep Windows and Enhanced Metafile pictures (`\wmetafile`, `\emfblip`), #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (DOCX parts stored under another casing keep their embedded fonts through a save, and a private save of a kept glossary escapes the attribute values it rewrites; previously trivial: the `.doc` reader logs what its copy budget leaves out, once a kind per document; importers bound hostile expansion: font names, links, ODS repeats, LaTeX wrappers, Markdown delimiters, #3692/#3713; previously trivial: repeated DOCX style IDs: save/reopen regression; previously trivial: Markdown code spans keep line-broken text literal, #3738; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: localized TOC style ids read as the TOC styles, and a TOC in columns keeps its layout through Update Table, #3889; previously trivial: cu20we: outline caps; previously trivial: a relationship the markup names without the prefix is read as it wrote: an unqualified `id` on an element that carries a relationship names that relationship, and the writer keeps the attribute with the id the new package holds the part under; an ordinary `id` — a VML shape's, a drawing's — names no part; previously trivial: the reader takes the relationship ids the markup refers to from the relationship attributes of the main document it has already parsed, so a document with many relationships opens in the time its part takes, #3411; previously trivial: a table cell span from a `.json` file stays within 63 columns through Insert Column and Merge Cells, #3637; previously trivial: the file commands that change the document are checked on a protected document, the protection of a protected document needs an explicit stop, the session author can't change through `file.setAuthor` under protection (the CLI's `--author` uses the same protection check), and the post-check compares the settings and the metadata; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: `majorBidi`/`minorBidi` theme fonts follow the settings' theme font language, as measured in Word; previously trivial: Word signature lines are kept on save, still signable; previously trivial: Times New Roman keeps Liberation Serif under the roman-font rule; previously trivial: shape gradients and transparency, #15Line truncated
|
||||
|
||||
Every format Word opens or saves, what WordCraft does with it, and how it's tested. Fidelity is the
|
||||
share of a typical real-world file's content and formatting that survives (read: shows correctly;
|
||||
@@ -279,6 +279,7 @@ Custom document properties retain their bookmark link targets through DOCX saves
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-01 | trivial | ODT: contextual spacing (`style:contextual-spacing`) is read and written and the List Paragraph style is written, so list items keep their spacing; a file's own `settings.xml` (LibreOffice's layout compatibility switches) is kept through a save, and a document from elsewhere gets the switches LibreOffice uses for Word files, as WordCraft lays text out as Word does (a Word-made document saved as ODT: 38,652 px apart in LibreOffice before, 3,302 now). `formats::odt::tests_more::{spacing, settings}` |
|
||||
| 2026-11-01 | trivial | ODT: custom character styles are kept: a common text style other than LibreOffice's link, note-mark and list-label styles (Emphasis, a user's own) opens as a document character style with its name, parent and own formatting, the text in it naming it; saving writes the character styles the text uses as common text styles, the spans' automatic styles based on them. `formats::odt::tests_more::char_styles` |
|
||||
| 2026-11-01 | trivial | ODT: each list level's indent, hanging and number alignment (`style:list-level-label-alignment`, `fo:text-align` of `style:list-level-properties`, ODF 1.3 §17.19–17.20) are read and written, for lists and heading numbering; every list was written 36 pt a level with left-aligned numbers. `formats::odt::tests_more::lists` |
|
||||
| 2026-11-01 | trivial | ODT: custom paragraph styles are kept: a common paragraph style other than Standard, the kinds' and the note texts' (LibreOffice's Text body, a user's own style) opens as a document style with its name, parent and own formatting, and its paragraphs stay in it instead of taking its formatting as direct formatting; saving writes the custom styles the paragraphs use, and those they are based on, as common styles. `formats::odt::tests_more::named_styles` |
|
||||
|
||||
Reference in new issue
Block a user