Drafts Action Directory

Sort

Posted by dchar, Last update 5 months ago

Sort lines of a draft or selection.

A prompt allows for ascending or descending order and to filter only unique lines.

Install

Steps

  • script

    const  p = Prompt.create();
    p.title = 'Sort options';
    p.addSelect('order', '', ['ascending', 'descending'], ['ascending'], false);
    p.addSelect('unique', '', ['unique'], [], true);
    p.addButton('Ok');
    
    if (!p.show()) {
      context.fail();
    }
    
    const desc = p.fieldValues['order'] == 'descending';
    const unique = p.fieldValues['unique'] == 'unique';
    
  • script

    // sort
    
    (() => {
    
        const hasSelection = () => editor.getSelectedRange()[1] > 0;
      
        const getText = () => {
          const e = editor;
          return hasSelection() ? 
            e.getTextInRange(...e.getSelectedLineRange()) :
            e.getText();
        };
      
        const setText = (t) => {
          const e = editor;
          if (hasSelection()) {
            const sel = e.getSelectedLineRange();
            e.setTextInRange(...sel, t);
            e.setSelectedRange(sel[0], t.length);
          } else {
            e.setText(t);
          }
        };
      
        let l = getText().split('\n');
    
        // remove blank lines
        l = l.filter(l => l.trim());
    
        if (unique) {
            l = l.filter((v,i,a) => a.indexOf(v) === i);
        }
    
        l.sort();
        if (desc) {
            l.reverse();
        }
    
        setText(l.join('\n') + '\n');
      
      })();

Options

  • After Success Default
    Notification Info
    Log Level Info

Comments

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