Google Docs API text indexes use UTF-16 code units. A programming language’s ordinary string length may count something else, so calculating offsets from visible characters can target the wrong text.
Use the document’s structural indexes
Read the current document and inspect the startIndex and endIndex on the relevant structural elements. Identify the correct tab and segment before calculating a range.
For example, an emoji represented by a UTF-16 surrogate pair consumes two code units even though a reader sees one symbol. A sequence of several displayed characters can also have more complex Unicode boundaries.
Account for edits that shift positions
- Calculate offsets against a specific current document state.
- Count inserted text using UTF-16 units.
- Adjust later indexes after earlier insertions or deletions.
- Consider processing independent edits from higher indexes to lower indexes.
Writing backward can simplify index management, but it does not remove the need to understand tabs, segments, or structural constraints. A valid numeric offset in the wrong tab is still the wrong target.
Validate Unicode and structure
Test with ordinary ASCII text, an emoji, and representative non-English text. Check the exact before-and-after passage, not just the response status.
Google forbids deletions that split a surrogate pair or create an invalid document structure. Respect final-newline and table boundaries as well. Use a revision guard when applying a plan based on a prior read, and reread after a conflict rather than replaying stale offsets. Correct indexing is a prerequisite for safe document edits, not a guarantee that the intended editorial change itself is appropriate.
References
- Structure of a Google Docs document | Google for Developers
- Insert, delete, and move text | Google Docs | Google for Developers
- Structural edit rules and behavior | Google Docs | Google for Developers
Reviewed against the linked official product guidance on November 3, 2026. Features, limits, screen labels, and access can vary by account, platform, region, and organization policy.