TL DR: use the code snippet below.
It seems that what Google Docs does when choosing Insert> Table is to split the current paragraph into two paragraphs and then insert a new table between them.
The hard part is to split the paragraph into two. I tried to achieve this in several ways. I could not find the API request from the Google Apps Script documentation that does this (the Spreadsheet API has a moveTo() method for the Range object, but that cannot help us here). I was hoping that I could copy the elements from this position in the paragraph further to another paragraph and delete the originals. However, since the Document Service does not allow the explicit insertion of several types of elements , but can only be managed locally, for example, Equation elements, copying these one by one is not possible.
Fortunately, Paragraph has a copy() method that performs a deep copy. Therefore, I take care to copy the entire paragraph, delete everything from the cursor position forward in the original paragraph, and delete everything to where the cursor was in the copy of the paragraph. This way you split the paragraph in the middle and you can insert the table in the desired position. It works the same for ListItem .
Here is the code for the splitParagraphAt() function that returns the newly created paragraph (or list item, which is the next native original). I did a few extra checks in the code to make sure that it does what you think it does. After that, I added a short code excerpt on how this can be used to insert a table at the current cursor position. You can use splitParagraphAt() same way as inserting any element at the cursor position. I have not tested this completely, so any input is welcome.
function splitParagraphAt(pos) { var el = pos.getElement(), offset = pos.getOffset(); var inParagraph = (el.getType() == DocumentApp.ElementType.PARAGRAPH || el.getType() == DocumentApp.ElementType.LIST_ITEM); if (!inParagraph && (el.getType() != DocumentApp.ElementType.TEXT)) { throw new Error("Position must be inside text or paragraph."); } var par; if (inParagraph) {
Here is the code excerpt for inserting the table at the cursor position and setting the cursor position in the first cell of the table:
var doc = DocumentApp.getActiveDocument(); var cursor = doc.getCursor(); var el = (cursor.getOffset() == 0? cursor.getElement() : splitParagraphAt(cursor)); var parentEl = el.getParent(); var table = parentEl.insertTable(parentEl.getChildIndex(el), [['ಠ‿ಠ']]); doc.setCursor(doc.newPosition(table.getCell(0, 0), 0));
Please note that additional checks are still needed to see if there is a choice or not, etc. In particular, this accepted cursor will not be null .