Skip to content

Select words at insertionPoint

fabiantheblind edited this page Jun 1, 2016 · 1 revision

This was a tricky question at graphicdesign.stackexchange.com.

Consider the following text:

She sells sea shells.

Say my insertion point is currently at a blank space between two words, i.e.

app.selection[0].characters.length < 1 I need to select or return the two words flanking the insertion point on either sides. So, if the insertion point is between sells and sea, I need the selection to be sells sea, if it's between sea and shells, I need the selection to be sea shells, and so on. I tried using the parent property but it's not giving me any option to return the specific words I need. Any help will be precious!

I found a script by Keith Gilbert called "TransposeTwoCharacters.jsx". That did most of the trick. I took some of the logic to make this happen.

// based on
// TransposeTwoCharacters.jsx
// by
// Keith Gilbert
// www.gilbertconsulting.com
// blog.gilbertconsulting.com
//
// http://www.gilbertconsulting.com/resources-scripts.html


// check for a doc
if (app.documents.length > 0) {
  // check for selection
  if (app.selection.length > 0) {
    // if it is a insertinpoint
    if (app.selection[0].constructor.name == "InsertionPoint") {

      $.writeln("got it IP");

      var ip = app.selection[0]; // isolate insertionPoint

      var story = app.selection[0].parentStory; // isolate story
      // get two characters before and after
      // we need two because there is a whitespace
      var twoCharactersBefore = story.characters[(ip.index - 2)];
      var twoCharactersAfter = story.characters[(ip.index + 2)];
      // catch the error that occurs if we are at the end
      try {

        $.writeln(twoCharactersBefore.words[0].contents); // this might throw an error
        // if not select the word
        app.select(twoCharactersBefore.words[0], SelectionOptions.REPLACE_WITH);
      } catch (e) {
        $.writeln("The insertion point is at the end of the text");
      }
      // catch the error that occurs if we are at the start
      try {
        $.writeln(twoCharactersAfter.words[0].contents); //this might throw an error
        // if not select the word
        app.select(twoCharactersAfter.words[0], SelectionOptions.ADD_TO);

      } catch (e) {
        $.writeln("The insertion point is at the start of the text");
      }
    } // ip check
  } // selection check
} // doc check

Home

Clone this wiki locally