Action

Clean MD lines

Posted by RoyRogers, Last update about 5 years ago

Normalizes/prettifying Markdown lines, adding and deleting blank lines as needed.

For example in imported text with single line breaks or excess blank lines.

Note: Creates new draft, keeping tags and moves original to trash.
Note: Will mess up code blocks!

Steps

  • script

    // Uses regex to clean up MD text lines etc.
    
    var text = draft.content;
    text = text.replace(/\n+/g, '\n\n')
    text = text.replace(/(\n)+([ \t]*[>*\-+][ \t]+)/g, '$1$2')
    text = text.replace(/(\n)+([ \t]*\d+\.[ \t]+)/g, '$1$2')
    // heading level 3 - 6 get no blank line before para,
    // modify by changing number of #s in regex below:
    text = text.replace(/(\n###+ .+?)(\n)+/g, '$1$2')
    
    var lines = text.split('\n');
    let newlines = [];
    
    let list = false;
    for (let line of lines) {
      if (line.trim() == '') {
        newlines.push('');
        list = false;
      } 
      //else if (line.startsWith('> ')) {
      else if (/^[ \t]*[>\-+*] |^[ \t]*\d+\. /.test(line)) {
        if (list == false) {
          newlines.push('');
        };
        newlines.push(line);
        list = true;
      else {
        newlines.push(line);
        list = false;
      };
    };
    
    // create a new draft, assign content and save it
    let d = Draft.create();
    for (let tag of draft.tags) {
      d.addTag(tag);
    };
    d.content = newlines.join('\n');
    d.update();
    
    // load new draft
    editor.load(d);
    editor.activate();
    
    

Options

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