Action

Renumber nested lists

Posted by RoyRogers, Last update over 5 years ago

(Re)number selected Markdown lists.
Works with nested lists and changes bullets to numbers. Max 4 levels.

HTML display automatically corrects numeric disorder in MD etc lists, but this action aims to fix disordered numbering in the plain text document too.

Steps

  • script

    /*
    (Re)number selected Markdown lists.
    Works with nested lists and changes bullets to numbers. Max 4 levels.
    */
    
    text = draft.processTemplate('[[selection_only]]');
    
    if (text == '') {
       var lines = [];
       //return;
    } else {
       var lines = text.split('\n');
    };
    
    var i = 0;
    var i2 = 0;
    var i3 = 0;
    var i4 = 0;
    var cleanlines = [];
    var newlines = [];
    const indent = /    /g
    const tab = '\t'
    const new_indent = tab
    
    for (line of lines) {
      // Clean current list with regEx
      cleaned = line.replace(/([\t ]*)\d\. /,"$1") // Clean old numbers
      cleaned = cleaned.replace(/([\t ]*)[\*\-\+] /,"$1") // Clean old bullets
      cleanlines.push(cleaned);
    }
    
    for (line of cleanlines) {
      line = line.replace(indent, tab); // Change space indent(s) to tab(s)
      if (line.startsWith(tab.repeat(3))) {
        i4 += 1;
        newlines.push(new_indent.repeat(3) + i4 + '. ' + line.slice(3));
      } else if (line.startsWith(tab.repeat(2))) {
        i3 += 1;
        newlines.push(new_indent.repeat(2) + i3 + '. ' + line.slice(2));
      } else if (line.startsWith(tab)) {
        i2 += 1;
        i3 = 0;
        newlines.push(new_indent + i2 + '. ' + line.slice(1));
      } else {
        i += 1;
        i2 = 0;
        i3 = 0;
        newlines.push(i + '. ' + line);
      }};
    
    new_text = newlines.join('\n')
    
    // console.log(new_text);
    draft.setTemplateTag('new_text', new_text);
    
  • insertText

    template
    [[new_text]]

Options

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