Axtru
Axtru

Reputation: 191

GAS - Google Docs API - getActiveDocument().getCursor().getOffset() returns unexpected '1' for cursor at end of line

I use CLASP therefore my dummy code is displayed as TypeScript.

If I write "test" into my google document and let the cursor be at what I would expect index 4 of the string, the Apps Script API returns 1 when calling:

const activeDocument = DocumentApp.getActiveDocument();
const cursor = activeDocument.getCursor();
const cursorOffset = cursor.getOffset();

This is a true headage for me because when I rest the cursor at index 1 for the string "test", then the same code returns the expected index 1.

How should anyone know that the cursor is at end of line or at the actual index 1 of the SurroundingText for the cursor Position when the offset is the same?

Upvotes: 2

Views: 496

Answers (1)

Axtru
Axtru

Reputation: 191

Solved this by using the getSurroundingTextOffset() instead of getOffset().

const activeDocument = DocumentApp.getActiveDocument();
const cursor = activeDocument.getCursor();
const cursorOffset = cursor.getSurroundingTextOffset();

NOTE: This makes sense in case of using the getSurroundingText().

read more at the docs: https://developers.google.com/apps-script/reference/document/position#getSurroundingTextOffset()

Upvotes: 0

Related Questions