Action

Sort Lines...

Posted by agiletortoise, Last update almost 5 years ago

Sort lines in alpha order, with options for case-sensitivity and destination for sorted text.

Steps

  • script

    // sort methods
    
    function alphaSort(vals, caseSensitive, ascending) {
    	let result = vals.sort(function(a, b) {
    		if (!caseSensitive) {
    			a = a.toLowerCase();
    			b = b.toLowerCase();
    		}
    		return a.localeCompare(b);
    	});
    	if (!ascending) {
    		result = result.reverse();
    	}
    	return result;
    }
    
    
    
  • script

    // prompt for sort options and run
    let f = () => {
    	let p = Prompt.create();
    	
    	p.title = "Sort Lines";
    	p.message = "Sort lines in the text selection";
    	
    	p.addSwitch("cs", "Case sensitive", true);
    	p.addSwitch("asc", "Sort ascending", true);
    	
    	p.addSelect("output", "Output", ["Replace selection", "Clipboard", "New draft"], ["Replace selection"], false);
    	
    	p.addButton("Sort Lines");
    	
    	if (!p.show()) {
    		return false;
    	}
    	
    	const cs = p.fieldValues["cs"];
    	const asc = p.fieldValues["asc"];
    
    	const [st, len] = editor.getSelectedLineRange();
    	const ln = editor.getTextInRange(st, len);
    
    	const lines = ln.split('\n');
    	const sortedLines = alphaSort(lines, cs, asc);
    	const result = sortedLines.join("\n");
    	
    	const output = p.fieldValues["output"][0];
    	
    	switch(output) {
    		case "Replace selection":
    			editor.setTextInRange(st, len, result);
    			break;
    		case "Clipboard":
    			app.setClipboard(result);
    			break;
    		case "New draft":
    			let d = Draft.create();
    			d.content = result;
    			d.update();
    			editor.load(d);
    			break;
    	}
    
    	return true;
    }
    
    if (!f()) {
    	context.cancel();
    }
    

Options

  • After Success Default
    Notification Error
    Log Level Error
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.