fabianmoronzirfas
2/19/2015 - 7:21 AM

select-words-at-ip.jsx

// 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