Action

Smart Brackets

Last update over 4 years ago

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

Steps

  • script

    // If a selection is present, wrap the text.
    //
    // If no selection, scan text for last open or close and
    // close it if last one was an open, or
    // insert open if not.
    
    const open = "[";
    const close = "]";
    
    const range = editor.getSelectedRange();
    const 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 
     const lastOpen = priorText.lastIndexOf(open);
     const 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 Ask
    Notification Error
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.