Skip to content

feat(charts): native chart support — chartN locator + docx:chart hint, charts list/extract, set-data (caches + embedded xlsx), charts add #43

Open

Description

@kklimuk

Problem

Native Word charts (word/charts/chartN.xml, usually backed by an embedded workbook in word/embeddings/*.xlsx) can't be seen, addressed, read, updated or created. A drawing that contains c:chart turns into an anonymous ChartRun { type: "chart", kind: "chart" } (classifyDrawing in src/core/ast/read.ts), and read prints `[chart]` with no id, type, title or data (src/cli/read/markdown.ts). So an agent asked to "update the chart with Q4's numbers" or "add a bar chart of this table" has two options: give up, or render a PNG and use images add. That leaves a picture where the user expected a chart they can edit in Word.

Repro (main @ e176d62), using an open-source fixture: an appendix from a US Treasury (TIGTA) Annual Audit Plan, committed to LibreOffice's test corpus:

curl -sSfLO https://raw.githubusercontent.com/LibreOffice/core/a05ad6dd36f73647cdf0839d2c18dbc1d399c792/chart2/qa/extras/data/docx/PieChartDataLabels.docx
docx read PieChartDataLabels.docx           # `[chart]` <!-- docx:p p2 align="center" -->  (no id, no title, no data)
docx find PieChartDataLabels.docx "Audit Focus"   # no matches: the chart title is invisible
docx wc PieChartDataLabels.docx             # 43 words; the 12 slice labels and the title aren't counted
docx images list PieChartDataLabels.docx    # []
docx raw part get PieChartDataLabels.docx --name word/charts/chart1.xml   # the only way to see the data
What Today
Visibility `[chart]` with no locator, type, title, series or size
Data only via raw part get, as cached c:strCache/c:numCache values. The source of truth for Word's Edit Data is the embedded workbook, which no verb can reach
Edit the paragraph around it works: chart part, part rels and xlsx come through byte-identical (verified)
delete --at p2 drawing removed; chart1.xml, its rels, the 58 KB xlsx and the document rel stay behind as a harmless orphan (verified)
Update the data none. raw part edit on the cache "works", but the workbook goes stale: both Word and LibreOffice render the cache and ignore the workbook (verified, below), so the doc looks right until someone clicks Edit Data
Create a chart none. The raw pipeline can't even do it by hand: raw part add refuses word/charts/_rels/chart1.xml.rels ("Relationship parts aren't created directly"), so a chart can't be wired to its workbook
Validation docx validate checks WML-root parts only; chart XML is never schema-checked (raw part edit inserting <c:bogus/> into a chart passes every gate), even though dml-chart.xsd is already bundled

Proposal: a charts noun, in four phases

Images are the precedent (images add/list/extract/replace/delete, imgN). Each phase ships on its own and keeps the write-read loop closed.

Phase 1: visibility (chartN locator, docx:chart hint, AST)

  • chartN is a positional id, in document order, for kind: "chart" only. SmartArt, shapes and other drawings keep their current placeholder; they aren't charts. Like imgN/eqN/tbxN, the numbering covers every story a chart can live in: body, table cells, text boxes and headers/footers (LibreOffice's chart-in-footer.docx has one).

  • The ChartRun AST gains:

    • id
    • chartTypes: string[] (a list: one plot area can hold several, e.g. testSeriesIdxOrder.docx is barChart + lineChart on a secondary axis)
    • title?
    • series: { name, categories, values, nameRef?, categoriesRef?, valuesRef?, formatCode? }[], from the caches
    • dataSource: "embedded" | "external" | "none"
    • widthEmu/heightEmu
    • trackedChange?, same as ImageRun

    By the "everything we parse is in the AST" rule, the parsed data belongs here.

  • read keeps the placeholder token and adds a metadata hint, following the docx:image shape. The locator rides as a bare leading token, per the naming rule:

    `[chart]` <!-- docx:chart chart0 type="pie3D" title="Audit Focus Areas" series="1" points="12" size="6x3.6in" -->
    `[chart]` <!-- docx:chart chart1 type="bar+line" series="2" points="13" -->
    

    chart0, type and the series/points counts always show: they're what an agent decides on. title shows when there is one. Everything else is deviation-only: data="external" / data="none" (embedded is the norm), readonly for chartex (below), float/wrap like images, and possibly stale="yes" when the cache disagrees with the workbook. The importer drops the hint like every other docx: comment. (The separate in-progress fix that makes `[chart]` safe to copy back through edit is out of scope here.)

  • wc keeps counting what read shows; open question 1 covers whether chart text should count.

Phase 2: charts list / charts extract

docx charts list FILE                                   # JSON array; id is the --at handle
docx charts extract FILE --at chart0 [--csv | --json] [-o PATH]
  • list items: { id, at: "p2", type, title, series: [names], points, data: "embedded"|"external"|"none", workbook?: "word/embeddings/Microsoft_Excel_Worksheet1.xlsx" }.
  • extract --csv writes one header row (category,<series 1>,<series 2>…) and one row per category, from the caches. The caches are what the reader sees on the page, and they're the only data a data="none" or external chart has. --json gives the full series objects, including refs and formatCode. extract's CSV is exactly what set-data takes in, so extract → edit the CSV → set-data is the loop.

Phase 3: charts set-data --at chartN --csv PATH|-

docx charts set-data FILE --at chart0 --csv q4.csv [--title "Revenue by Quarter"] [--dry-run] [-o PATH]
docx charts set-data FILE --batch updates.jsonl    # {"at":"chart0","csv":"…"}: all ids as read

This rewrites both the chart caches and the embedded workbook, in place, through XmlNode refs. It never regenerates either: the TIGTA workbook has 8 sheets, a chartsheet, external links and print areas, and all of that has to survive.

  1. Resolve chart0 → <c:chart r:id> → chart part → its part rels → c:externalData r:id → package rel → embedded xlsx (or an oleObject external link, or nothing).
  2. Parse the CSV (RFC 4180). The header row holds the series names and the first column the categories. An empty cell is a gap, written as a missing c:pt, not as 0.
  3. Caches. Per series: rewrite tx/strCache, cat (keep the existing cache kind: a date axis is a numRef with a date formatCode; POI's radar and stock charts use Excel serials such as 37261), val/numCache, and every ptCount. Prune per-point overrides (c:dPt, c:dLbl) whose idx falls past the new count. Adding a series clones the last c:ser with fresh idx/order and strips its spPr/dPt so the palette colors it by index. Removing one drops the trailing c:ser.
  4. Refs. Recompute each c:f from the existing top-left anchor and orientation (series in columns or rows, detected from the existing ranges). Keep the sheet name, quoted the way Excel quotes it ('Summary-Staff Day Alloc'!$D$5:$D$16).
  5. Workbook (jszip + our XML parser; see "xlsx" below):
    • Resolve the sheet by name through xl/workbook.xml → xl/_rels/workbook.xml.rels. Never guess sheetN.xml: in the TIGTA workbook, "Summary-Staff Day Alloc" is rId6 → worksheets/sheet5.xml.
    • Write cells and keep each existing cell's s style. Strings go into sharedStrings.xml when it exists, as inline strings otherwise.
    • Keep <row>/<c> sorted, and update <dimension>.
    • When an xl/tables/tableN.xml covers the range (Word's default chart workbook always has Table1), update its ref, and its tableColumn/@name values to the new header text. A mismatch makes Excel "repair" the file.
    • On shrink, clear the cells that fell out of the old range.
  6. Refuse (UNSUPPORTED + hint, nothing written) when:
    • A target cell holds a formula. In the TIGTA workbook every value is a shared formula (D5 = H5/$H$18, ref="D5:D16"). We can't recalculate, and overwriting would silently break the author's model. See open question 2.
    • The data is an external link. LibreOffice's TableOnPage3.docx points at file:///C:\Users\…\Graph for pipeline 13 Feb.xlsx with TargetMode="External". See open question 3.
    • It's a chartex chart (box & whisker, sunburst, waterfall, histogram, funnel, treemap). Its mc:Fallback is a PNG we can't regenerate, the same staleness problem the text-box Fallback had, but with no way to mirror it. These are read-only in v1.
    • The CSV equals the current data. A no-op is an error (MATCH_NOT_FOUND-style), per the output contract.
  7. Tracking. We don't yet know whether Word tracks chart-data edits; find out with the scripts/word-redlines.sh oracle before shipping. Until then follow the images/raw precedent: untracked; under document-level tracking, apply untracked plus a [docx-cli] audit comment; reject --track.
  8. Output. respondAck prints charts.set-data chart0 (2 series × 4 points), and read immediately shows the new counts and title.

--title TEXT rewrites the c:title rich text in place, keeping the first run's a:rPr. It creates a title when there isn't one and sets autoTitleDeleted val="0".

Phase 4: charts add (authoring) and charts delete

docx charts add FILE (--after LOC | --before LOC | --at-end) --type column|bar|line|pie --csv PATH|- \
    [--title T] [--width IN] [--height IN] [--legend right|bottom|none] [--grouping clustered|stacked|percent]
docx charts delete FILE --at chart0
  • add prints the minted chartN (respondMinted). It writes:
    • word/charts/chartN.xml with content-type Override application/vnd.openxmlformats-officedocument.drawingml.chart+xml
    • word/charts/_rels/chartN.xml.rels with a package rel
    • word/embeddings/Microsoft_Excel_WorksheetN.xlsx with a Default or Override for application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    • a document chart relationship
    • an inline <w:drawing> run whose docPr id comes from nextDrawingId
  • Types, first wave: column (barChart + barDir=col, the type people mean by "bar chart" in Word), bar (horizontal), line, pie. Second wave: doughnut, area, scatter, plus stacked/percent grouping. 3-D variants and chartex types aren't authored.
  • Write every default explicitly. We verified that both Word and LibreOffice smooth a line series when c:smooth is absent, and that Word draws a rounded chart frame when c:roundedCorners is absent. So the emitter writes c:roundedCorners val="0", c:smooth val="0", c:date1904 val="0", c:varyColors, c:marker and c:legendPos, rather than trusting the spec defaults.
  • The chartStyle/chartColorStyle parts are optional. Our probe had neither, and Word (Mac) and LibreOffice both rendered it with theme-accent series colors (verified). Leave them out of v1.
  • Emitters are JSX components (<ChartSpace>, <BarChart>, <Series>, <ChartDrawing>) in a new src/core/chart/, which also holds the read model and the Charts lens (new Charts(document).list() / extract() / setData() / add() / delete()). Like Fonts with the theme, the workbook isn't a view: the lens reads, mutates and stages word/embeddings/*.xlsx through document.pkg only when a chart verb runs, so unrelated saves never re-zip it.
  • delete removes the drawing run (an untracked removal of the last run keeps the paragraph, or not, the same way images delete does). It then prunes the document rel only when isRelationshipReferenced says it's unreferenced, and the chart/xlsx parts only when nothing else targets them. When in doubt, leave the orphan.

xlsx: no new dependency

package.json has no xlsx library; jszip and fast-xml-parser are already there.

  • SheetJS (xlsx): Apache-2.0, but the npm package is frozen at 0.18.5 with open advisories (prototype pollution, ReDoS), and newer builds ship only from their own CDN. Large.
  • ExcelJS (MIT): heavy, and it writes back from its own model. Anything it doesn't model is dropped (chartsheets, external links, printer settings, the TIGTA workbook's structure), which breaks the "mutate in place, don't round-trip" invariant one package down.

Both directions are small enough to own:

  • Patching (phase 3): locate the sheet → set cells → maintain sharedStrings, dimension and table. A few hundred lines over our own XmlNode, in the same in-place style as the rest of the codebase.
  • Writing (phase 4): verified minimal workbook of 5 parts, about 2 KB: [Content_Types].xml, _rels/.rels, xl/workbook.xml, xl/_rels/workbook.xml.rels, xl/worksheets/sheet1.xml with inline strings. LibreOffice opens it (soffice --convert-to csv gives back the exact grid), and Word renders a document that embeds it. Not yet verified: whether Word's Edit Data is happy with it, or wants Word's own default shape (styles.xml, sharedStrings.xml, theme1.xml, tables/table1.xml with ref + tableColumn names, as in every Word-made workbook in the corpora). Test that once, by hand, before choosing. Mimicking Word's shape costs about 4 KB and no code risk.

Smaller fixes this work needs (each also useful on its own)

  1. Schema-validate chart parts. Validate c:chartSpace-rooted parts against the already-bundled dml-chart.xsd, in docx validate and in the raw part gates (WML_ROOT_TAGS in src/core/raw/validate.ts decides what gets checked today).
  2. Part-level relationships in raw. Let raw address them (e.g. raw insert --part word/charts/chart1.xml --xml '<Relationship …/>'), so the escape hatch can wire a chart to its workbook. Today the hand-built path dead-ends there.
  3. chartex reading. classifyDrawing should also recognize cx:chart (graphicData …/drawing/2014/chartex), so chartex charts get a chartN and a readonly hint instead of falling through to kind: "drawing".

Empirical findings (probed by hand through docx raw, rendered in both engines)

  • Minimal charts render in both engines. A bar, line and pie chart, each a bare c:chartSpace with caches only (no workbook, no style/colors parts, no c:lang/c:date1904), wired through raw part add + raw insert <Relationship> + raw insert <w:p><w:drawing>…<c:chart r:id/>, renders in Word for Mac and in LibreOffice, with no repair prompt.
  • The same chart with an embedded workbook renders too. c:externalData r:id + c:autoUpdate val="0" + a package rel to the 2 KB workbook renders in both engines. The part rels had to be injected outside docx-cli; see smaller fix 2.
  • Both engines render the cache. With the cache changed (120 → 30) and the workbook left alone, Word and LibreOffice both draw 30. A cache-only edit therefore looks correct, and Edit Data then shows (and may restore) the old number. That's why set-data must write both.
  • Spec defaults are unsafe (see Phase 4): an absent c:smooth gives a smoothed line in both engines, and an absent c:roundedCorners gives Word a rounded frame.
  • POI's chartex.docx doesn't use Word's chartex markup. It wraps its chartex charts in mc:AlternateContent Requires="cx" with a PNG mc:Fallback, and LibreOffice renders the fallback. But inside the chartex graphicData it uses c:chart and the plain chart relationship type. Word-native chartex is cx:chart + the …/2014/relationships/chartEx rel (from the spec; we didn't check against a Word-made file). Test against both shapes.

Tests and coverage

  • Third-party fixtures go in tests/fixtures/, unmodified, each recorded with source URL, commit, license and sha256 in a fixtures NOTICE (MPL-2.0 is file-level copyleft: committing the files unmodified next to MIT code is fine, and we keep the notice):

    • PieChartDataLabels.docx, the primary realistic fixture. LibreOffice core, MPL-2.0, chart2/qa/extras/data/docx/ @ a05ad6dd36. 120 KB, sha256 52c3ddfc…2374. The content is a TIGTA Annual Audit Plan appendix (a US federal work, so the content is public domain as well). One pie3DChart titled "Audit Focus Areas" with 12 categories, a 0.0% formatCode, a rich-text title and a themeOverride part. Its 58 KB, 8-sheet embedded workbook has a chartsheet, external links, a quoted sheet name, and values that are shared formulas, which makes it the refuse-formulas test case. It also has three sections with headers/footers and prose around the chart.
      https://github.com/LibreOffice/core/blob/master/chart2/qa/extras/data/docx/PieChartDataLabels.docx
    • testSeriesIdxOrder.docx, the combo-chart fixture. LibreOffice core, MPL-2.0, @ 9ca4fa05eb. 26 KB, sha256 1ef1d7ce…ef93. Real data (wine grape production in kt vs price in $/t, 2000-01 … 2012-13f): barChart + lineChart with a secondary axis, an accounting formatCode, and series refs that start at different rows ($A$4 vs $A$2). Exercises type="bar+line".
      https://github.com/LibreOffice/core/blob/master/chart2/qa/extras/data/docx/testSeriesIdxOrder.docx
    • chartex.docx, the breadth fixture. Apache POI, Apache-2.0, test-data/document/ @ 528591ba11. 133 KB, sha256 5d7f0ca9…0b57. Six charts: bar, line, radar (date categories), stock, and two chartex (box & whisker, sunburst) with PNG fallbacks. Each has an embedded workbook plus style/colors parts. The data is placeholder, so it's for type coverage, not realism.
      https://github.com/apache/poi/blob/trunk/test-data/document/chartex.docx
    • Optional edge cases, all LibreOffice MPL-2.0: sw/qa/extras/ooxmlexport/data/chart-in-footer.docx (chart in a footer), chart2/qa/extras/data/docx/TableOnPage3.docx (externally linked workbook, anonymized text), chart2/qa/extras/data/docx/testMultipleChart.docx (three charts).
    • Already in the repo: tests/fixtures/strict-profile.docx, a placeholder bar chart in the Strict profile namespace. Make sure the chart reader handles Strict too.
  • A dogfooding builder, tests/fixtures/setup/charts.ts in CORE_FIXTURES: create a short quarterly report, then charts add a column, line and pie chart, charts set-data one of them to add a series and a category, and --title another. It round-trips through LibreOffice, and its read joins the eval:read snapshots. The hint is a read-output change, so review the snapshot diff for length and signalRatio.

  • Unit tests:

    • the reader on every fixture: types, titles, series, refs, date and multi-level categories, literal (numLit/strLit) data
    • set-data keeps caches and workbook consistent: re-open the xlsx and compare cells to caches, including shape changes in both directions, table1.xml ref/columns and sharedStrings
    • every refusal path (formula, external link, chartex, no-op) exits nonzero and writes nothing
    • --batch resolves all ids against the document as read
    • delete never dangles a rel
    • chart parts pass dml-chart.xsd
  • Word check (one-time, manual): open a charts add result and a set-data result in Word, click Edit Data, and confirm the grid matches and that nothing gets repaired. That settles the minimal-vs-Word-shaped workbook question.

  • Weak-agent scenario: a new quarterly-report scenario whose fixture is built by charts add. task.md, as a human would phrase it:

    Our Q4 numbers came in (below). Please update the revenue chart in the report so it includes Q4, change its title to "Revenue by Quarter, FY2026", and add a pie chart right after the summary paragraph showing each region's share of full-year revenue. They need to stay real charts I can click into and edit in Word, not pictures.

    criteria.md (judge only) checks:

    • chart0's caches and its embedded workbook both contain Q4
    • the new title is in place
    • a second c:chart exists with a pieChart and its own workbook
    • no images add PNG stands in for a chart (today's failure mode)
    • the render shows both charts

    (Folding into invoice would also work, e.g. "the invoice has a spend-by-category chart; update it", but a report is where charts naturally live.)

  • Docs: REFERENCE.md (the charts noun, the chartN locator, the docx:chart hint), a top-level docx --help one-liner (that's how weak agents find features), src/cli/CLAUDE.md, a new src/core/chart/CLAUDE.md, and the skill's workflows section (the extract → edit CSV → set-data loop).

Open questions

  1. Chart text in find/replace/wc. The title, series names and category labels are text a human reads first, and issue Text in text boxes is invisible to read/find/replace — mc:AlternateContent is never unwrapped #4 (text boxes) set the precedent that replace --all mustn't exit 0 while "Acme" sits somewhere visible. Proposal: find reports matches as chart0. replace either updates cache + workbook, or counts the chart hits and fails loudly. wc counts what read shows: the title, and labels only if the hint prints them.
  2. Formula-backed data (the TIGTA case): refuse (proposed), offer --overwrite-formulas (it replaces formulas with constants and says so), or refuse with a hint naming the precedent cells? We can't recalculate, so writing to the precedents won't update the cached <v>.
  3. External workbooks: refuse, or --cache-only with a warning that Word will refresh from the link (c:autoUpdate)? Updating a linked chart's cache is really a "this document lies until refresh" operation.
  4. Does Word track chart edits? Check with the oracle (step 7 of phase 3). If Word doesn't, untracked plus an audit comment is the honest equivalent.
  5. The CSV dialect: do number formats in the CSV (12%, $1,200, 2026-01-31) set the formatCode, or must values be bare, with --format separate? Proposal: bare numbers, plus an optional --number-format that writes both the cache formatCode and the cell style.
  6. Markdown authoring: should insert/create --from accept a fenced ```chart block (type/title + a GFM table)? Not in v1: verbs are discoverable and the hint isn't parse-back. But it would make create a full report builder later.
  7. The verb surface: a combined charts set --at chart0 [--csv] [--title] (like headers set), or keep set-data + --title? charts replace (swap a chart for a new type) is a later want.

🤖 Generated with Claude Code

Activity

  1. kklimuk commented on Nov 6, 2026

    @kklimuk
    OwnerAuthor

    🤖 docx-cli triage

    I opened #51 as the first slice of this issue: Phase 1 visibility and Phase 2 charts list / charts extract, both read-only.

    • What it adds: the chartN locator, the docx:chart read hint, the cached series in the AST, a new charts.docx fixture, and the docs.
    • What it leaves out: Phase 3 set-data, Phase 4 add/delete, chartex, charts in headers/footers, and chart text in find/wc.

    The PR description lists the decisions that are yours to make.

    Action needed: approve/merge — review #51, which is a first slice so it references #43 rather than closing it, and tick the decisions checklist in the PR.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementtriage:pr-open

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions