Drafts Action Directory

Smart Parentheses

Posted by agiletortoise, Last update 5 months ago

If a selection is present, wrap the text in parentheses. If no selection, scan text for last parenthesis and close it if last one was an open parenthesis, or insert open parenthesis if not.

Install

Steps

  • script

    // Smart parentheses key
    //
    // If a selection is present, wrap the text in parentheses
    //
    // If no selection, scan text for last parenthesis and
    // close it if last one was an open parenthesis, or
    // insert open parenthesis if not.
    
    var open = "(";
    var close = ")";
    
    var range = editor.getSelectedRange();
    var priorText = editor.getTextInRange(0, range[0]);
    
    if (range[1] > 0) { 
     //text selected, wrap it!
     editor.setSelectedText(open + editor.getSelectedText() + close);
     editor.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
       editor.setSelectedText(open);
       editor.setSelectedRange(range[0]+open.length, 0);
     }
     else { // close last open
       editor.setSelectedText(close);
       editor.setSelectedRange(range[0]+close.length, 0);
     }
    }
    

Options

  • After Success Nothing
    Notification Error
    Log Level Error

Comments

Actions available in the Action Directory are uploaded by community members. Use appropriate caution reviewing downloaded actions before use.