Get child index of findtext in google API script - google-apps-script

My goal is to replace a piece of text in a Google Drive document with the contents of another document.
I have been able to insert the document at a certain position in the other document, but I'm having trouble determining the child index of the piece of text I want to replace. Here is what I have so far:
function replace(docId, requirementsId) {
var body = DocumentApp.openById(docId).getActiveSection();
var searchResult = body.findText("<<requirementsBody>>");
var pos = searchResult.?? // Here I would need to determine the position of the searchResult, to use it in the insertParagraph function below
var otherBody = DocumentApp.openById(requirementsId).getActiveSection();
var totalElements = otherBody.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var element = otherBody.getChild(j).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ) {
body.insertParagraph(pos,element);
} else if( type == DocumentApp.ElementType.TABLE ) {
body.insertTable(pos,element);
} else if( type == DocumentApp.ElementType.LIST_ITEM ) {
body.insertListItem(pos,element);
} else {
throw new Error("According to the doc this type couldn't appear in the body: "+type);
}
}
};
Any assistance would be greatly appreciated.

findText()
returns a RangeElement.
You can use
var r = rangeElement.getElement()
to get the element containing the found text.
To get its childIndex you can use
r.getParent().getChildIndex(r)

Thanks to bruce's answer I was able to figure out a solution to this problem, however if I was inserting Elements from another document I needed to actually find the index of the parent of the found text, as the found text was just a Text element inside of a Paragraph Element. So, I needed to find the index of the Paragraph Element, and then insert the new elements in relation to that Paragraph.
The code looks like this:
var foundTag = body.findText(searchPattern);
if (foundTag != null) {
var tagElement = foundTag.getElement();
var parent = tagElement.getParent();
var insertPoint = parent.getParent().getChildIndex(parent);
var otherBody = DocumentApp.openById(requirementsId).getActiveSection();
var totalElements = otherBody.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
... then same insertCode from the question above ...
insertPoint++;
}

Related

Google Apps Script. Get all links from document

Hi all) I need to get all links from google document. I found that general approach:
function getAllLinks(element) {
var links = [];
element = element || DocumentApp.getActiveDocument().getBody();
if (element.getType() === DocumentApp.ElementType.TEXT) {
var textObj = element.editAsText();
var text = element.getText();
Logger.log("text " + text);
var inUrl = false;
for (var ch=0; ch < text.length; ch++) {
var url = textObj.getLinkUrl(ch);
if (url != null) {
if (!inUrl) {
// We are now!
inUrl = true;
var curUrl = {};
curUrl.element = element;
curUrl.url = String( url ); // grab a copy
curUrl.startOffset = ch;
}
else {
curUrl.endOffsetInclusive = ch;
}
}
else {
if (inUrl) {
// Not any more, we're not.
inUrl = false;
links.push(curUrl); // add to links
curUrl = {};
}
}
}
}
else {
var numChildren = element.getNumChildren();
for (var i=0; i<numChildren; i++) {
links = links.concat(getAllLinks(element.getChild(i)));
}
}
Logger.log(links);
}
It works perfectly fine if i, for example, type url in text, but if add link via menu ("Insert" -> "Link") it doesn't work, function getLinkUrl() returns null. Documentation contains info about Link class, i thought all links represented by it, but don't understand why i can't get link inserted via menu.
I thought maybe i can use some regular expression on text of document element, but if i add link via menu item i can specify custom label for link, which may not contain url in it.
Have anyone faced this scenario? What i missed?

How to copy images in google docs paragraphs rigth?

Due the answer on this topic I can copy content form template doc to another saving all formatting.
But when I add some pictures to couple of paragraphs the result document shows pictures as picture logo
The question is how to copy images right on this way?
You need to adapt your insert method to every different element type...
an example could be like this :
function copyElementsByType() {
var sourceDoc = DocumentApp.openById('yyyy');
var targetDoc = DocumentApp.openById('xxxx');;
var bodyS = sourceDoc.getBody();
var otherBody = targetDoc.getBody()();
var elements = bodyS.getNumChildren()
for( var e=0;e<elements;e++) {
var element = otherBody.getChild(e).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ){
body.insertParagraph(e,element)}
else if( type == DocumentApp.ElementType.TABLE ){
body.insertTable(e,element)}
else if( type == DocumentApp.ElementType.LIST_ITEM ){
body.insertListItem(e,element)}
else if( type == DocumentApp.ElementType.INLINE_IMAGE ){
body.insertImage(e,element)
} else {
throw new Error("check what to do with this type of element : "+type);
}
}
}

How I can get the textwrap image in google doc

Due to this answer now I can make copy of elements with images right, but I spotted one more thing - if image inserted as 'in text' - then copying is done well. But when I make it 'text wrap', I can't find this element at all!
Here is the code of test:
function test_show_all_structure_of_doc() {
var final = 'final';
var doc = get_doc(working_directory, final);
var body = doc.getBody();
var elements = body.getNumChildren();
for( var i=0;i<elements;i++) {
var element = body.getChild(i).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ){
Logger.log('paragraph' + i);
var children = element.getNumChildren();
if (children >0) {
for (var j=0;j<children;j++) {
var subelement = element.getChild(j).copy();
var subtype = subelement.getType();
Logger.log('subelement ' + j + ":" + subtype);
if (subtype == DocumentApp.ElementType.TEXT) Logger.log(subelement.getText());
}
}
}
else if( type == DocumentApp.ElementType.TABLE ){
Logger.log('table');}
else if( type == DocumentApp.ElementType.LIST_ITEM ){
Logger.log('list item');}
else if( type == DocumentApp.ElementType.INLINE_IMAGE ){
Logger.log('inline image');}
else {
throw new Error("check what to do with this type of element : "+ type);
}
}
}
so where I can find textwrap image? Or it is impossible for now?
This is not possible using Google Apps Script (for now) and is the object of an enhancement request for more than 2 years now.
In the mean time, only inline image is supported.

GAS is it possible to replace getActiveDocument().getSelection() at once?

My User has the following selection in his Gdoc.
Now from the sidebar he wants to to replace the selection he made on the document. The GAS question is if it is possible to do that at once, something like:
var selection = DocumentApp.getActiveDocument().getSelection()
selection.replace("newtext")
Or do I have to loop through selection.getRangeElements() in order to delete them (or replace them) and than in someway place the new text in that position?
Not, that's not possible (well, if it is, it's not documented).
You have to loop through the selected elements, mainly because the selection may take part of paragraphs, forcing you to manage that. i.e. deleting just the selected part. And for completed selected elements, you can just remove them entirely (like images).
Here's an implementation on how to do this (part of the Kaylan's Translate script modified by me to properly replace images and partially selected paragraphs.
function replaceSelection(newText) {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
var replace = true;
for (var i = 0; i < elements.length; i++) {
if (elements[i].isPartial()) {
var element = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
var text = element.getText().substring(startIndex, endIndex + 1);
element.deleteText(startIndex, endIndex);
if( replace ) {
element.insertText(startIndex, newText);
replace = false;
}
} else {
var element = elements[i].getElement();
if( replace && element.editAsText ) {
element.clear().asText().setText(newText);
replace = false;
} else {
if( replace && i === elements.length -1 ) {
var parent = element.getParent();
parent[parent.insertText ? 'insertText' : 'insertParagraph'](parent.getChildIndex(element), newText);
replace = false; //not really necessary since it's the last one
}
element.removeFromParent();
}
}
}
} else
throw "Hey, select something so I can replace!";
}

How to insert a paragraph object in listItem preserving the formating of each word of the paragraph?

Following the documentation sample, I'm trying to create a function that search for a numerated list in a google document and, if it finds it, adds a new item to the list. My code works well (thanks to #Serge insas for previous help) with strings, but not with paragraphs objects. I know I could get the paragraph text and add it to listItem, but then I lose the formating. Is there a way to insert a paragraph preserving all it's formating? (I know I could use var newElement = child.getParent().insertListItem(childIndex, elementContent.getText()) do insert text without words formating)
Here the code:
function test() {
var targetDocId = "1A02VhxOWLUIdl8LTV1tt2S1yASDbOq77VbsUpxPa6vk";
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
var elementContent = targetDoc.getChild(2); // a paragraph with its formating
var childIndex = 0;
for (var p= 0; p< targetDoc.getNumChildren(); p++) {
var child = targetDoc.getChild(p);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
while(child.getType() == DocumentApp.ElementType.LIST_ITEM){
child = targetDoc.getChild(p)
Logger.log("child = " + child.getText())
childIndex = body.getChildIndex(child);
Logger.log(childIndex)
p++
}
child = targetDoc.getChild(p-2);
var listId = child.getListId();
if (child.getText() == '') {
childIndex = childIndex -1;
}
Logger.log(childIndex)
var newElement = child.getParent().insertListItem(childIndex, elementContent);
newElement.setListId(child);
var lastEmptyItem = targetDoc.getChild(childIndex +1).removeFromParent();
break;
}
Here a screen shot of my targetDoc (note the second item, Paragraph):
I know this question is old, but I've come up with a solution and will leave here for anyone that may need it. It is not complete, as I have yet to find a way to copy any Inline Drawing and Equation to a new element...
Anyways, here is my code, it will work well if the paragraph you want to convert to a list item only has text and Inline Images.
function parToList() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
//gets the paragraph at index 1 on body -> can be changed to what you want
var par = body.getChild(1);
var childs = [];
for (var i = 0; i<par.getNumChildren(); i++) {
var child = par.getChild(0);
childs.push(child);
child.removeFromParent();
};
par.removeFromParent();
//puts the list item on index 1 of body -> can be changed to the wanted position
var li = body.insertListItem(1, "");
childs.reverse();
for (var j in childs) {
var liChild = childs[j];
var childType = liChild.getType();
if (childType == DocumentApp.ElementType.EQUATION) {
//still need to find a way to append an equation
} else if (childType == DocumentApp.ElementType.INLINE_DRAWING) {
//still need to find a way to append an inlineDrawing
} else if (childType == DocumentApp.ElementType.INLINE_IMAGE) {
li.appendInlineImage(liChild);
} else if (childType == DocumentApp.ElementType.TEXT) {
li.appendText(liChild);
};
};
};
Cheers