Action

Prepend/Append

Posted by drdrang, Last update about 4 years ago - Unlisted

Steps

  • script

    // Append or prepend the selected lines (or all lines) with
    // text supplied by the user.
    
    // Prepare the prompt
    var p = Prompt.create();
    p.title = "Append/Prepend"
    p.message = "Text to add to start or end of lines."
    p.addTextField("text", "", "", {placeholder: "Added text", wantsFocus: true});
    p.addButton("Prepend");
    p.addButton("Append");
    
    // Define the text that's going to be edited
    // If there's no selection, use the whole draft
    let st, len;
    if (editor.getSelectedRange()[1] > 0) { // use selected lines
    	[st, len] = editor.getSelectedLineRange();
    }
    else { // use full text
    	[st, len] = [0, editor.getText().length];
    }
    let lnText = editor.getTextInRange(st, len);
    if (lnText.endsWith("\n")) {
    	lnText = lnText.slice(0, -1);
    	len -= 1;
    }
    
    // Get the text to be added from the user
    var didSelect = p.show();
    
    if (didSelect) {
    	// Edit a copy of the chosen text
    	var addText = p.fieldValues["text"];
    	var lines = lnText.split('\n');
    	var edited = [];
    	
    	if (p.buttonPressed == "Prepend") {
    		lines.forEach(line => edited.push(addText + line));
    	}
    	else {
    		lines.forEach(line => edited.push(line + addText));
    	}
    	
    	// Replace the text in the editor
    	editor.setTextInRange(st, len, edited.join('\n'));
    }
    

Options

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