Skip to content

Instantly share code, notes, and snippets.

@erickoledadevrel
Last active August 29, 2015 13:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erickoledadevrel/c0968c31f1d63cc3a874 to your computer and use it in GitHub Desktop.
Save erickoledadevrel/c0968c31f1d63cc3a874 to your computer and use it in GitHub Desktop.
Google Apps Script: How to determine if a range within a Google Doc contains a given position.
/**
* Determines if a range within a Google Doc contains a given position.
* @param {DocumentApp.Range} range A range within the document.
* @param {DocumentApp.Position} psoition A position within the document.
* @return {boolean} True if the position falls within the range, false otherwise.
*/
function rangeContainsPosition(range, position) {
var positionElement = position.getElement();
var positionOffest = position.getOffset();
// If the the position is a container element, get the actual element it points to.
if (positionElement.getNumChildren && positionElement.getNumChildren() > 0) {
// If the position is at the end of a container, get the last element.
if (positionElement.getNumChildren() <= positionOffest) {
positionOffest = positionElement.getNumChildren() - 1;
}
positionElement = positionElement.getChild(positionOffest);
positionOffest = 0;
}
var positionElementPath = getElementPath(positionElement);
// Look through all the elements in the range.
var rangeElements = range.getRangeElements();
for (var i = 0; i < rangeElements.length; i++) {
var rangeElement = rangeElements[i];
var rangeElementPath = getElementPath(rangeElement.getElement());
// Are they the same element?
if (rangeElementPath == positionElementPath) {
if (rangeElement.isPartial()) {
return positionOffest >= rangeElement.getStartOffset() &&
positionOffest <= rangeElement.getEndOffsetInclusive();
} else {
return true;
}
// Is position element contained within range element?
} else if (positionElementPath.indexOf(rangeElementPath) == 0) {
return true;
}
}
return false;
}
/**
* Gets the path of an element within the document.
* @param {DocumentApp.Element} element The element to evaluate.
* @return {string} The path of an element within the document.
*/
function getElementPath(element) {
var parts = [];
while (element.getParent()) {
var parent = element.getParent();
var pathSegment = Utilities.formatString('%s[%d]', element.getType(), parent.getChildIndex(element));
parts.unshift(pathSegment);
element = parent;
}
return parts.join('.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment