[ ]
Smart Bracket

Use this key to insert “smart brackets”. The key will do the following:

  • If a text selection is present, wrap the text in square brackets.
  • If no text is present, look for the last occurrence of a bracket in the text, and if the last bracket was an open bracket, insert a close bracket. Otherwise, insert an open one.

See also: Smart Parentheses.

Posted by agiletortoise

Install

Details

Label [ ]
Voice Over Smart Bracket
Script
// Smart bracket key
//
// If a selection is present, wrap the text in brackets
//
// If no selection, scan text for last bracket and
// close it if last one was an open bracket, or
// insert open bracket if not.

var open = "[";
var close = "]";

var range = getSelectedRange();
var priorText = getTextInRange(0, range[0]);

if (range[1] > 0) { 
 //text selected, wrap it!
 setSelectedText(open + getSelectedText() + close);
 setSelectedRange(range[0] + range[1] + open.length + close.length, 0);
}
else {
 // no selection, find last 
 var lastOpen = priorText.lastIndexOf(open);
 var lastClose = priorText.lastIndexOf(close);
 
 if	(lastOpen == -1 || lastClose > lastOpen) { // no close, use open
   setSelectedText(open);
   setSelectedRange(range[0]+open.length, 0);
 }
 else { // close last open
   setSelectedText(close);
   setSelectedRange(range[0]+close.length, 0);
 }
}

Advanced

Keyboard shortcut None
Hide key Yes

Discussion

comments powered by Disqus