Move cursor programmatically forward or backward (easy) in Google Doc
Whenever I insert an image into my document with the following code,
var cursor = DocumentApp.getActiveDocument().getCursor();
var image = cursor.insertInlineImage(resp.getBlob());
the cursor is positioned in front of the image. It seems like it makes sense to have a cursor after what has been inserted, as if it were inserted.
I found Document.newPosition
, but it seems very difficult to use.
Here's what I put together:
- get the current cursor
- get the element contained in
- parse its type (like a paragraph) and process the logic with newPosition based on the numbers of children if the cursor is at the end of the paragraph, etc.
I started trying to do this but figured I was doing something wrong because it is so difficult. Isn't there a simple function to move the cursor forward or backward a certain number of items, for example using the arrow keys?
Edit: I found a simple solution to insert an image. There is always an image after the cursor, so this works:
var position = doc.newPosition(cursor.getElement(), cursor.getOffset()+1);
doc.setCursor(position);
However, if the cursor moves arbitrarily forward, you need to consider cases where it cursor.getOffset()+1
exceeds ContainerElement
.
source to share
For images:
var cursor = DocumentApp.getActiveDocument().getCursor();
var image = cursor.insertInlineImage(resp.getBlob());
var position = doc.newPosition(image, 1); // image was just inserted, you want to go one cursor position past that.
doc.setCursor(position);
Text:
var cursor = DocumentApp.getActiveDocument().getCursor();
var sometext = cursor.insertText("Hokey Pokey");
var position = doc.newPosition(sometext, 11); // Move 11 characters into new text. You can't move past the end of the text you just inserted.
doc.setCursor(position);
source to share