Select nearest word

Script key: Select nearest word

Posted by @onetapless

Install

Details

Label
Voice Over Select nearest word
Script
// Script keys run short Javascripts
// For documentation and examples, visit:
// http://help.agiletortoise.com

var selRange = getSelectedRange();
var text = getText();
var selRangeLength = selRange[0] + selRange[1];
var regex = /\s/gi;

var beforeMatch = function(str) {
  var i = str.length - 1;
  var result;
  do {
    if (!str.charAt(i).match(regex)) {
      result = str.lastIndexOf(str.charAt(i));
    }
    i--;
  } while (result == undefined);
  return result;
};

var afterMatch = function(str) {
  var i = 0;
  var result;
  do {
    if (!str.charAt(i).match(regex)) {
      result = str.indexOf(str.charAt(i));
    }
    i++;
  } while (result == undefined);
  return result;
}

if (selRange[1] === 0) {
  var beforeText = text.substring(0, selRange[0]);
  var afterText = text.substring(selRangeLength);
  var charsAfter = afterMatch(afterText);
  var charsBefore = selRange[0] - beforeMatch(beforeText);
  var selection, selectionStart, selectionEnd;
  
  if (charsAfter === 0 && charsBefore === 1) {
    // Cursor is within the word.
    selectionStart = beforeText.lastIndexOf(" ") + 1;
    selectionEnd = afterText.indexOf(" ") + (selRange[0] - selectionStart);
    setSelectedRange(selectionStart, selectionEnd);
  } else if (charsBefore <= charsAfter) {
    // Nearest word on the left.
    selectionEnd = selRange[0] - (charsBefore - 1);
    selection = text.substring(0, selectionEnd);
    selectionStart = selection.lastIndexOf(" ") + 1;
    setSelectedRange(selectionStart, selectionEnd - selectionStart);
  } else {
    // Nearest word on the right.
    selectionStart = selRangeLength + charsAfter;
    selection = text.substring(selectionStart);
    selectionEnd = selection.indexOf(" ");
    setSelectedRange(selectionStart, selectionEnd);
  }
}

Advanced

Keyboard shortcut None
Hide key Yes

Discussion

comments powered by Disqus