code
Smart Code

Script key: Smart Code

Posted by @nahumck

Install

Details

Label code
Voice Over Smart Code
Script
// Smart <code> key
// Based on tbe smart parentheses key by AgileTortoise
//
// If a selection is present, wrap the text in <code> </code>
//
// If no selection, scan text for last <code> and
// close it with </code> if last one was a <code>, or
// insert <code> if not.

var open = "<code>";
var close = "</code>";

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