Text Edits That Survive Real PowerPoint Files
go-pptx Tech Blog · Part 4: Object Model, Cross-Run Text Replacement, and Handle Lifecycle
Series: go-pptx Tech Blog (10 parts)
Baseline: v2.4.4
Keywords: TextFrame / Paragraph / Run, cross-Run replacement, grapheme cluster,cNvPr@id, STALE-GUARD, monotonic ID allocation
1. Object Model: Strictly Aligned with the DrawingML Hierarchy
go-pptx's public object model is not "designed off the top of one's head"; it aligns with the OOXML PresentationML / DrawingML hierarchy:
Presentation (Root)
└── Slide 1..N
└── Shape
├── GroupShape / AutoShape (including the TextShape alias) / OpaqueShape
├── PictureShape / TableShape / ChartShape
├── AudioShape / VideoShape
└── TextFrame
└── Paragraph 1..N
└── TextRun 1..N
The benefit of this hierarchy is that the object relationships callers see correspond almost one-to-one with the structure in the XML. You do not need to first learn a "library-specific document model" and then guess how it maps to OOXML.
But once an object model introduces "handles", it must answer a question that every long-running editor faces: when do handles become stale?
2. Handle Identity: Reusing Stable IDs That Already Exist in OOXML
go-pptx does not maintain a separate "object ID table". It reuses the stable identities that already exist in OOXML:
| Handle layer | Stable identity |
|---|---|
Shape |
cNvPr@id (DrawingML requires it to be globally unique within an spTree) |
TextFrame / Paragraph / TextRun
|
shapeHint = the cNvPr@id of the owning shape |
Cell (table) |
shapeHint = the cNvPr@id of the graphicFrame of the owning table |
NodePath serves only as a parent-container hint for "which spTree / grpSp to search under", not as identity. The resolution flow is:
- resolve the parent container by path;
- search among child elements by
cNvPr@id; - compare the
cNvPr@idof the nearest ancestor with the hint recorded in the handle; - not found or mismatched →
ErrStaleHandle.
This has one fewer source of truth than "building your own ID table", and it avoids the classic bug of "the XML changed but the ID table was not synced".
2.1 Which Operations Invalidate a Handle?
| Operation | Handle state |
|---|---|
MoveShape |
Still valid (cNvPr@id unchanged) |
| Adding a shape at a sibling position | Still valid |
| Text editing | Still valid |
RemoveShape |
The target cNvPr@id disappears → ErrStaleHandle
|
| Child shapes after grouping | Old handle is invalidated (grouping changes the hierarchy path; re-fetch required) |
Close |
Business methods return ErrClosed; handle reads may return ErrStaleHandle
|
2.2 Monotonic ID Allocator: Avoiding the ABA Trap
Here is an easily overlooked bug:
If the allocator takes "the current
max(id)+1within the spTree", then after deleting the shape with the largest id, a newly added shape will reuse the same id. When an old handle locates by id lazily, it will "resurrect" from the first matching element and return the geometry/text of the wrong shape instead ofErrStaleHandle.
Since v2.0.2, the allocator has been changed to be monotonically increasing and never reusing:
const maxShapeIDValue = 4294967295
func (p *Presentation) allocShapeID() (int64, error) {
if p.maxShapeID >= maxShapeIDValue {
return 0, ErrOutOfRange
}
p.maxShapeID++
return p.maxShapeID, nil
}
In addition, after New / Open / OpenReader, it scans the spTree of every slide in the whole document and takes the global maximum of the existing cNvPr@id as the initial upper bound (seedShapeIDAlloc). This way:
- appending across sessions does not fall back;
- deleting a shape does not make the allocator regress;
- locating an old handle fails with
ErrStaleHandle, and does not silently point to a new shape because the id was reused.
OOXML allows cNvPr@id to skip within its range; monotonic allocation does not violate the spec.
3. Cross-Run Text Replacement: Why Not Just strings.Replace
PPT text is not one big string; it is:
TextFrame
└── Paragraph
├── Run 1: "Q3 revenue"
├── Run 2: "year-over-year"
└── Run 3: "12%"
Each Run can have its own font, color, size, and hyperlink. What the user sees as "Q3 revenue year-over-year 12%" is the logical concatenation of these Runs.
If you apply strings.Replace directly to the <a:t> of some Run, you will run into:
- the target string crossing Runs: it cannot be found within a single Run;
- formatting lost after replacement: the new text inherits the wrong Run's formatting;
- splitting grapheme clusters: cutting an emoji or combining character in half;
- breaking field/line-break/hyperlink boundaries: a match crossing
a:br,a:fld, or Runs with different links.
The rules of pptx.TextFrame.ReplaceText / Paragraph.ReplaceText are explicit:
- case-sensitive, literal matching, left to right, non-overlapping, based on an initial text snapshot, replacement results not processed recursively;
-
an empty old returns
ErrInvalidArgument; -
matches do not cross
a:br/a:fld; - matches do not cross adjacent Runs with "different hyperlinks/actions";
- match boundaries must not split combining characters or ZWJ sequences; violating hits are skipped and recorded as diagnostics;
- replacement containing a line break (U+000A) is rejected in the first version (express it with the paragraph API).
3.1 Three Formatting Strategies
type ReplaceMode int
const (
// default: replacement inherits the explicit formatting of the Run containing the first matched character
ReplaceFirstCharacter ReplaceMode = iota
// old and replacement must have the same number of runes; each Run keeps its own formatting
ReplaceEqualLengthPerRune
// the caller provides formatting via WithReplacementStyle
ReplaceExplicitStyle
)
Example:
tf, _ := box.TextFrame()
res, err := tf.ReplaceText("Q3", "Q4")
if err != nil {
return err
}
fmt.Printf("matches=%d replaced=%d skipped=%d\n",
res.Matches, res.Replaced, res.Skipped)
ReplaceResult does not just tell you "success/failure"; it also gives:
-
Matches: the total number of matches on the initial snapshot; -
Replaced: the number actually completed; -
Skipped: the number skipped due to boundary/safety rules; -
Hits: the range of each hit, whether it was replaced, and the skip reason.
Skip reasons are stable strings, for example:
-
grapheme-cluster-boundary: the match splits a combining character/ZWJ; -
unsafe-link-or-extension-run: a Run within the covered range contains semantic child elements such as hyperlinks/extensions; -
adjacent-match-run-conflict: adjacent hits share a Run and cannot be expressed independently.
This is more honest than "all replacements succeeded": some positions simply cannot be replaced safely, and the library tells you why.
3.2 Minimal Patch Planning Across Runs
The internal implementation (internal/textmap) does three things:
- rune mapping: index Run text by rune rather than by byte;
-
span location: map
[start,end)of the logical text to the first/last Run and its internal offset; - grapheme safety: check whether a match boundary falls inside a combining character or ZWJ sequence.
Then the replacement plan is greedily scheduled by "occupied Run interval":
- multiple in-place text changes in the same Run are merged into a single
<a:t>content replacement; - for hits that need Run splitting, the formatting strategy decides the
rProf the new Run; - all patches are validated as a whole first, then applied in one pass via
ApplyPatches+SinglePartPatch.
The result: the preceding and following content and formatting of non-hits are fully preserved; a hit's replacement changes only the necessary interval.
3.3 Paragraphs/Fields/Plain Text
Besides ReplaceText, there are:
-
SetPlainText: for template batch-replacement scenarios, bypassing the rich-text structure; -
Paragraph.AppendField/InsertField/Fields/Remove/SetText: support theslidenum/datetimewhitelisted fields; -
Paragraph.Text(): concatenates ordinary Run text with field cached text, as a logical text view.
Fields and line breaks are hard boundaries, and this must be consistent in match planning; otherwise "the text you see" and "the range you can replace" will not line up.
4. A Complete Text Editing Example
p, _ := pptx.Open("template.pptx")
defer p.Close()
slides, _ := p.Slides()
shapes, _ := slides[0].Shapes()
tf, _ := shapes[0].TextFrame()
res, err := tf.ReplaceText("{{customer}}", "East China Region Customer",
pptx.WithReplaceMode(pptx.ReplaceFirstCharacter))
if err != nil {
return err
}
if res.Skipped > 0 {
for _, h := range res.Hits {
if !h.Replaced {
log.Printf("skip [%d,%d): %s", h.StartRune, h.EndRune, h.Reason)
}
}
}
// field: page number
para, _ := tf.AddParagraph(pptx.ParagraphSpec{})
para.AppendField(pptx.FieldSpec{Kind: pptx.FieldSlideNumber, Text: "1"})
if _, err := p.Save(ctx, "out.pptx", pptx.WithSaveOverwrite(true)); err != nil {
return err
}
5. Observability of Handle Invalidation
go-pptx's error model is "explicit failure", not "return a zero value and let you guess":
- after a shape is deleted, the old
Shape.Bounds()returnsErrStaleHandle; - after a slide is deleted,
SpeakerNotesText()on the oldSlidehandle returnsErrStaleHandle; - after
Close, business methods returnErrClosed; -
Close()itself is idempotent: repeated calls returnnil, compatible withdefer p.Close().
This looks "verbose", but it is very important for long-running services: you can see in the logs that "a handle that has already been deleted is used here", rather than getting a coordinate that looks normal but actually belongs to another shape.
6. Design Trade-offs
| Question | Choice | Cost |
|---|---|---|
| Handle identity | Reuse cNvPr@id
|
Depends on OOXML's "unique within spTree" premise; malformed files may have duplicate IDs, and Validate reports DRAWING_ID_DUPLICATE
|
| ID after deletion | Monotonically increasing, no reuse | IDs grow larger, but ABA is avoided; nearing the uint32 limit returns ErrOutOfRange
|
| Replacement range | Does not cross br/fld/links | Some text that "looks continuous" cannot be replaced at once and needs segmented handling |
| Grapheme safety | Skip anything that splits | A few boundary scenarios require the caller to express it differently |
| Line breaks | First version rejects a replacement containing \n
|
Express it explicitly with the paragraph API, avoiding implicit structural changes |
| Formatting strategy | Three fixed modes | No arbitrary "map formatting by character" scripting capability |
7. Summary
The core of the object model layer is two things:
- Text editing must be faithful: cross-Run matching, minimal patching, grapheme safety, explicable boundaries.
-
Handles must fail safely: reuse OOXML identity, monotonic IDs, explicit
ErrStaleHandle.
The next part moves into the chart subsystem: a chart is not just drawing a bar; it simultaneously involves chart XML, embedded workbooks, cached data, and client compatibility.
Series navigation: ← Part 3: OPC and Transactions · Part 5: Chart Subsystem →
Top comments (0)