Action

Number Lines

Posted by drdrang, Last update almost 4 years ago

Add line numbers (followed by a colon and two spaces) to either the selected text or, if there’s no selection, the entire draft.

Steps

  • script

    // Number the selected lines (or all lines) with colon and
    // two spaces after each line number.
    
    // Define the text that's going to be numbered.
    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")) { // trailing LF doesn't count
    	lnText = lnText.slice(0, -1);
    	len -= 1;
    }
    
    // Break the text into lines and number them.
    // Right-justify the numbers and put a colon and
    // two spaces after the line number.
    var lines = lnText.split('\n');
    var numLines = lines.length;
    var width = Math.floor(Math.log(numLines)*Math.LOG10E) + 1;
    var numbered = [];
    var lNum;
    for (var i=0; i<numLines; i++) {
      lNum = i + 1;
      numbered.push(lNum.toString().padStart(width) + ':  ' + lines[i]);
    }
    
    // Replace the original text with the line-numbered text.
    let rep = numbered.join('\n')
    editor.setTextInRange(st, len, rep);
    editor.setSelectedRange(st, rep.length);
    

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.