5

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.

Rubén
  • 34,714
  • 9
  • 70
  • 166
Fuhrmanator
  • 11,459
  • 6
  • 62
  • 111

1 Answers1

5

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);

For 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);
Alex B
  • 24,678
  • 14
  • 64
  • 87