Whenever I insert an image in my document with the following code,
var cursor = DocumentApp.getActiveDocument().getCursor();
var image = cursor.insertInlineImage(resp.getBlob());
the cursor is positioned before the image. It seems that it makes more sense to have the cursor be after what was inserted, as if it had been pasted.
I found Document.newPosition
to achieve this, but it seems very complicated to use.
Here's what I gathered:
- get the current cursor
- get the element it is contained in
- parse its type (e.g., paragraph), and handle the logic with newPosition based on numbers of children, in case the cursor's at the end of the paragraph, etc.
I started trying to do this, but figured I'm doing something wrong because it's so complicated. Isn't there a simple function to move the cursor forward or back some number of elements, like with the arrow keys?
Edit: I found a simple solution for the image insertion. There's always an image after the cursor, so this works:
var position = doc.newPosition(cursor.getElement(), cursor.getOffset()+1);
doc.setCursor(position);
However, if moving the cursor arbitrarily forward, one must consider cases where cursor.getOffset()+1
exceeds the ContainerElement
.