2

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!

2

This is a tricky problem. I found "TransposeTwoCharacters.jsx" by Keith Gilbert (here) and took some logic from him.
This should work for you.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.