Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

24 changes: 24 additions & 0 deletions src/crates/execution/office-documents/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ pub struct Run {
pub size_pt: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font: Option<String>,
/// BCP 47 text language; omitted legacy runs keep automatic language selection.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lang: Option<String>,
/// External hyperlink target (http, https, or mailto).
#[serde(default, skip_serializing_if = "Option::is_none", alias = "url")]
pub link: Option<String>,
Expand All @@ -198,6 +201,9 @@ impl Run {
}

pub fn validate(&self, path: &str) -> OfficeResult<()> {
if let Some(lang) = &self.lang {
validate_language(lang).map_err(|err| prefix(err, path, "lang"))?;
}
if let Some(color) = &self.color {
parse_color(color).map_err(|err| prefix(err, path, "color"))?;
}
Expand All @@ -218,6 +224,24 @@ impl Run {
}
}

/// A syntax check, not a locale allowlist: Office language tags are independent
/// of the product UI's supported locales.
pub(crate) fn validate_language(lang: &str) -> OfficeResult<()> {
let mut parts = lang.split('-');
let primary = parts.next().unwrap_or_default();
if (!(2..=8).contains(&primary.len()) && !matches!(primary, "x" | "X" | "i" | "I"))
|| !primary.bytes().all(|c| c.is_ascii_alphabetic())
|| parts.any(|part| {
part.is_empty() || part.len() > 8 || !part.bytes().all(|c| c.is_ascii_alphanumeric())
})
{
return Err(OfficeError::invalid(
"use a BCP 47 language tag, such as en-US, zh-CN, zh-TW, ja-JP, or ko-KR",
));
}
Ok(())
}

impl UnknownFields for Run {
fn unknown_fields(&self, path: &str, out: &mut Vec<String>) {
report_extra(&self.extra, path, out);
Expand Down
6 changes: 6 additions & 0 deletions src/crates/execution/office-documents/src/docx/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,12 @@ impl Writer<'_> {
} else if run.subscript == Some(true) {
rpr.push_str("<w:vertAlign w:val=\"subscript\"/>");
}
if let Some(lang) = &run.lang {
let lang = esc(lang);
rpr.push_str(&format!(
"<w:lang w:val=\"{lang}\" w:eastAsia=\"{lang}\" w:bidi=\"{lang}\"/>"
));
}
let mut out = String::from("<w:r>");
if !rpr.is_empty() {
out.push_str(&format!("<w:rPr>{rpr}</w:rPr>"));
Expand Down
8 changes: 6 additions & 2 deletions src/crates/execution/office-documents/src/guides/docx.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

A Word document is an ordered list of **blocks** (0-based indexes) plus document settings. Build it over several `edit` calls: write the skeleton first, then insert sections one or a few at a time. `read` pages over blocks with `offset`/`limit` and returns the heading outline, so you can find where to insert next.

Pass ordinary Unicode text; do not manually transcode or pre-escape XML. The tool writes UTF-8. Choose fonts installed in the intended viewer; fonts are not embedded. File generation does not require an Office installation, and `read` is a model inspection, not a rendered page preview.

## Blocks

Every block is an object with `type`. Text fields take either `text` (plain string) or `runs` (formatted spans). Inside text, `\n` is a line break.
Expand All @@ -19,7 +21,7 @@ Every block is an object with `type`. Text fields take either `text` (plain stri
| `horizontal_rule` | — |
| `toc` | `title`, `levels` (default 3). Lists the headings; Word refreshes page numbers on open |

**Run** fields: `text`, `bold`, `italic`, `underline`, `strike`, `code`, `superscript`, `subscript`, `color` (`#RRGGBB`), `highlight` (`#RRGGBB`), `size_pt`, `font`, `link` (http/https/mailto URL).
**Run** fields: `text`, `bold`, `italic`, `underline`, `strike`, `code`, `superscript`, `subscript`, `color` (`#RRGGBB`), `highlight` (`#RRGGBB`), `size_pt`, `font`, `lang` (optional BCP 47 language, e.g. `zh-CN`), `link` (http/https/mailto URL).

### Markdown

Expand All @@ -41,9 +43,11 @@ Every block is an object with `type`. Text fields take either `text` (plain stri

Indexes inside one batch are live: after inserting two blocks at index 3, the old block 3 is block 5 for the next operation in the same batch. A batch is atomic — if any operation fails, nothing is written and the error names the operation.

Prefer `replace_blocks` for content corrections instead of insert/delete/move sequences. After failure, correct the named field/index; read the current target if uncertain. Do not repeat unchanged failed input or replay successful batches.

## Settings at create

`settings` may carry `page`, `styles`, `header`, `footer`, `properties` (same fields as above). For Chinese documents set `styles.east_asia_font` (for example `Microsoft YaHei`, `SimSun`, `PingFang SC`).
`settings` may carry `page`, `styles`, `header`, `footer`, `properties` (same fields as above). Use the style defaults unless document requirements call for specific fonts; `styles.east_asia_font` sets the East Asian font. Font availability and substitution depend on the viewing environment, which may differ from the generation environment.

## Example

Expand Down
35 changes: 30 additions & 5 deletions src/crates/execution/office-documents/src/guides/pptx.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,26 @@

A deck is a list of **slides** (0-based). Each slide is a fixed canvas — **1280 × 720 px** for `16:9` (default) or 960 × 720 for `4:3` — with absolutely positioned elements: origin top-left, `x` `y` `w` `h` in px, painted in array order (first = bottom). Build one slide (or a few) per `edit` call; `read` pages over slides, and `detail: "full"` returns a slide's elements with their indexes for targeted edits.

## Editing workflow

- Append new pages with `insert_slides`. To rewrite a page, use `replace_slide` with **both `index` and `slide`**; no insert/delete/move sequence is needed.
- For a small correction, `read` the target with `detail: "full"`, then `update_slide` with its slide index and element patches. Each patch is `{index, ...changed fields}`, with **no nested `op`**. `text` replaces the old paragraphs; use `paragraphs` instead to retain rich run formatting. Do not supply both.
- Indexes are live within a batch: inserting or deleting slides shifts subsequent indexes. Recalculate later selectors against the resulting order. `move_slides.to` is measured after removing the moved pages.
- Failure leaves the whole batch unapplied. Correct the named field/index; if uncertain, read the current document and retry a smaller edit. Do not resend unchanged failed input or replay successful calls.

## Text and fonts

Pass ordinary Unicode text; do not manually transcode or pre-escape XML. The tool writes UTF-8. Set deck defaults at create with `settings.theme`, or later with `set_theme`: `{font, east_asia_font, text_color, lang}`. Use the theme defaults unless document requirements call for specific fonts. Fonts are not embedded; availability and substitution depend on the viewing environment, which may differ from the generation environment.

`lang` is an optional BCP 47 override on the theme, text/shape element, paragraph, or run (most specific wins). Omit it for automatic selection: kana → `ja-JP`, Hangul → `ko-KR`, Han → `zh-CN`, otherwise `en-US`. Set the intended language explicitly when script alone is ambiguous, such as Traditional Chinese or Han-only Japanese/Korean. `font` on an element/run overrides its font; `theme.east_asia_font` supplies the theme's East Asian font.

## Slide

`{ "title", "layout", "background": "#RRGGBB", "notes": "speaker notes", "elements": [ … ] }`. `title` and `layout` are planning labels shown by `read` (not drawn).

## Elements

Colors are `#RRGGBB` or `#RRGGBBAA` (alpha). Text-bearing elements accept `text` (string, `\n` = new paragraph) or `paragraphs`, plus element-level run defaults `size_pt`, `bold`, `italic`, `color`, `font`, `align` that apply wherever a run or paragraph does not set its own.
Colors are `#RRGGBB` or `#RRGGBBAA` (alpha). Text-bearing elements accept `text` (string, `\n` = new paragraph) or `paragraphs`, plus element-level defaults `size_pt`, `bold`, `italic`, `color`, `font`, `lang`, `align`. Defaults apply only where a run/paragraph does not set its own value; changing element size/color/font does not override explicit values inside runs.

**text** — `{type: "text", x, y, w, h, text | paragraphs, valign (top|middle|bottom, default top), rotation, …defaults}`. Zero inner padding; the box wraps at `w` and does not grow, so size it for its content.

Expand All @@ -18,9 +31,9 @@ Colors are `#RRGGBB` or `#RRGGBBAA` (alpha). Text-bearing elements accept `text`

**table** — `{type: "table", x, y, w, h, rows, header (default true), column_widths (px, scaled to w), font_size_pt (default 14), font, header_fill, header_color, fill, band_fill ("" disables banding), border_color, text_color}`. Cells are strings/numbers or `{text/runs, bold, color, fill, align}`. Rows share `h` equally. At most 60 rows × 30 columns.

**Paragraph** — a string, or `{text | runs, align (left|center|right|justify), line_spacing_pct, space_before_pt, space_after_pt, bullet, numbered, level, size_pt, bold, italic, color, font}`.
**Paragraph** — a string, or `{text | runs, align (left|center|right|justify), line_spacing_pct, space_before_pt, space_after_pt, bullet, numbered, level, size_pt, bold, italic, color, font, lang}`.

**Run** — `{text, size_pt, bold, italic, underline, strike, superscript, subscript, color, highlight, font, link}`.
**Run** — `{text, size_pt, bold, italic, underline, strike, superscript, subscript, color, highlight, font, lang, link}`.

GenOffice spec spellings are accepted as aliases: `sizePt`, `lineSpacingPct`, `spaceBeforePt`, `spaceAfterPt`, `widthPt`, `flipH`, `flipV`, `url`.

Expand All @@ -34,10 +47,22 @@ GenOffice spec spellings are accepted as aliases: `sizePt`, `lineSpacingPct`, `s
| `delete_slides` | `index`, `count` (default 1) | |
| `move_slides` | `index`, `count`, `to` | `to` is the position after the moved slides are removed |
| `duplicate_slide` | `index`, `to` (default right after) | |
| `set_theme` | `font`, `east_asia_font`, `text_color` | deck-wide defaults |
| `set_theme` | `font`, `east_asia_font`, `text_color`, `lang` (null clears an override) | deck-wide defaults |
| `set_properties` | `title`, `subject`, `author`, `keywords`, `description`, `category` | |

After a batch the tool audits the touched slides and reports elements outside the canvas and text that likely overflows its box; fix those with `update_slide`.
After a batch the tool audits the touched slides and reports elements outside the canvas and text that likely overflows its box; fix relevant findings with `update_slide`. These are estimates, not rendered images. Visual verification is a separate step using an available viewer/renderer; report the environment actually checked. File generation does not require an installed Office application or renderer.

### In-place edit examples

```json
{"action":"edit","file_path":"/abs/deck.pptx","operations":[
{"op":"replace_slide","index":2,"slide":{"title":"Summary","elements":[
{"type":"text","x":80,"y":80,"w":1000,"h":100,"size_pt":32,"text":"Updated result"}
]}}
]}
```

Then change only that text with `{"op":"update_slide","index":2,"update_elements":[{"index":0,"text":"Final result"}]}`. Slide index 2 and element index 0 are different selectors; get both from `read`.

## Design rules (from GenOffice's deck pipeline)

Expand Down
4 changes: 4 additions & 0 deletions src/crates/execution/office-documents/src/guides/xlsx.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ A workbook is a list of **sheets**; each sheet holds sparse cells addressed A1-s

Range reads also honor `offset`/`limit` (at most 500 rows per call); pass the same range and the returned `next_offset` to continue. `detail: "full"` preserves complete cell text; outline reads shorten long text.

Pass ordinary Unicode text; do not manually transcode or pre-escape XML. The tool writes UTF-8. Use `style.font_name` for a font available in the target viewer; fonts are not embedded. File generation does not require an Office installation, and `read` is not a rendered workbook preview.

## Cell values

Rows are arrays of cell values:
Expand Down Expand Up @@ -46,6 +48,8 @@ Formula results are computed and cached for arithmetic, comparisons, `&`, cell a

Operations run in order and each sees the previous result: after `insert_rows`, later operations in the same batch address the shifted grid. A batch is atomic.

Prefer `set_cells`/`format_range` for corrections instead of deleting/recreating sheets or rows. After failure, correct the named field/range; read the current sheet if uncertain. Do not repeat unchanged failed input or replay successful batches.

## Example

```json
Expand Down
5 changes: 5 additions & 0 deletions src/crates/execution/office-documents/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@ pub mod docx;
mod error;
mod guide;
pub mod image;
mod operation_contract;
mod package;
pub mod pptx;
pub mod xlsx;
mod xml;

pub use error::{OfficeError, OfficeErrorKind, OfficeResult};
pub use guide::guide;
pub use operation_contract::{
operation_recovery_hint, operation_schema, validate_operation_headers,
};

use common::{merge_patch, operation_name, UnknownFields};
use docx::DocxDocument;
Expand Down Expand Up @@ -349,6 +353,7 @@ impl OfficeDocument {
"a batch is limited to {MAX_OPERATIONS_PER_BATCH} operations; split it across calls"
)));
}
validate_operation_headers(self.format(), operations)?;
let mut model = self.model.clone();
let mut assets = self.assets.clone();
let mut ctx = ApplyContext {
Expand Down
Loading
Loading