Action

Jump to MD Heading

Posted by derick, Last update over 6 years ago

Pick a Markdown heading in the text and jump to it. There’s an existing “Navigate Draft” action that does nearly the same thing - this was an experiment in converting a 1Writer script for use with Drafts.

Steps

  • script

    // See online documentation for examples
    // http://getdrafts.com/scripting
    
    // script adapted from http://1writerapp.com/action/072ca
    
    var content,
        lines,
        headings,
        lengths,
        ranges,
        linesLength,
        i;
    
    content = editor.getText();
    lines = content.split('\n');
    linesLength = lines.length;
    lengths = 0;
    headings = Array();
    ranges = Array();
    
    for(i = 0; i < linesLength; i++) {
        if(lines[i].match(/^#+\s?.*/)) {
            headings.push(lines[i]);
            ranges.push(lengths);
        }
        lengths += lines[i].length + 1; // +1 because the line breaks count;
    }
    
    var p = Prompt.create();
    
    if (headings.length > 0) {
    	p.addSelect("headings","Jump to Section",headings,[],false);
    	p.addButton("Go");
    } else {
       p.title = "No headings";
    }
    
    p.show();
    
    if (p.buttonPressed = "Go") {
    	var h = p.fieldValues["headings"][0];
    	if (h == undefined) {
    		alert ("No heading selected"); 
    		} else {
    		var r = ranges[headings.findIndex(sel => sel == h)];
    		editor.setSelectedRange(r);
          }
    };
    
    

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.