turtlefranklin
turtlefranklin

Reputation: 529

How can I retrieve the sentence where the cursor currently resides in a Google Doc?

I want to be able to get the string for the sentence which the user is currently editing. This should be the sentence containing the cursor. Right now, I know that I can get the cursor's surrounding element with the following:

var cursor = DocumentApp.getActiveDocument().getCursor();
var surroundingTextStr = cursor.getSurroundingText().getText();

And then search it using the following regular expression to isolate by sentence.

var pattern = /([A-Z][^\.!?]*[\.!?])/ig;
var match;
while ((match = pattern.exec(surroundingTextStr)) != null){
    // How can I check that this sentence currently holds the cursor?
}

How can I go about checking each sentence to see if it contains the cursor? I know by searching the surrounding text as a string removes a lot of the positional information, but could I perhaps then search the document for that string and check the positions of the RangeElement and the Cursor? I"m really not sure.

Thanks

Upvotes: 1

Views: 231

Answers (1)

turtlefranklin
turtlefranklin

Reputation: 529

So before I mark this as the answer, I would much prefer to see an implementation that works with the Google Apps Scripts API. This is merely a sneaky workaround (read: cheat).

Here is my working implementation below.

var cursor = DocumentApp.getActiveDocument().getCursor();
var surroundings = cursor.getSurroundingText();
var marker = '\u200B';  // A zero-wdith space character - i.e. a hidden marker.
cursor.insertText(marker);
var surroundingTextStr = surroundings.getText();  // Copy to string
surroundings.replaceText(marker, '');  // Remove the marker from the document.

// Build sentence pattern, allowing for marker.
var pattern = /([A-Z\u200B][^\.!?]*[\.!?])/ig;  
var match;
while ((match = pattern.exec(surroundingTextStr)[0]) != null){
  Logger.log(match);
  if (/\u200B/.test(match)){
    match = match.replace(marker, '');
    Logger.log("We found the sentence containing the cursor!");
    Logger.log(match);
  }
}

Because the API has no easy way to recognize the location of the cursor within its paragraph, I've instead placed what should be a zero-width Unicode character by the cursor.

This Unicode character, \u200B serves as a marker. I copy the surrounding text for separation into sentences and then find the sentence containing this marker. When I find that, I know that I've found the sentence where the cursor was positioned! Just be sure to clear the document of the marker.

On another note, I would love it if the Position class implemented some kind of indexing or way to compare positions.

Upvotes: 2

Related Questions