Action

Code Block With Syntax (```bash)

Posted by @scottaw, Last update over 3 years ago

UPDATES

over 3 years ago

Separated language syntax list array into separate script step.

Apply Markdown fenced code block (“`) around selection, or insert empty block if no selection. This version has you choose your code block syntax (html, javascript, css, bash, zsh, and so on) from a list.

Result is blocks with the code block syntax in the top code block delimiter, which will change the highlighting appropriately for that language or syntax.

Based on and still mostly Greg Pierce’s Code Block Action at https://actions.getdrafts.com/a/1Ux

Steps

  • script

    // Modification of Code Block action by Greg Pierce at https://actions.getdrafts.com/a/1Ux
    // Set language options
    let languages = ["actionscript","apache","apacheconf","bash","sh","zsh","basic","csharp","cs","c","h","css","bat","golang","html","xml","rss","svg","http","https","javascript","less","markdown","php","python","ruby","swift","typescript","vim","yaml"];
    
  • script

    // Modification of Code Block action by Greg Pierce at https://actions.getdrafts.com/a/1Ux
    // Language options are set in the previous script in an array called "languages"
    var p = Prompt.create();
    p.title = "Code Syntax";
    p.addPicker("Syntaxes", "", [languages], [languages.indexOf("bash")]); //default selection is bash
    p.addButton("Code Block It!!");
    p.show();
    
    let syndex = p.fieldValues["Syntaxes"]; 
    
    // Apply Markdown code block to selection, or empty code block if no selection
    let markupStart = "```" + languages[syndex];
    let markupEnd = "```";
    
    let sel = editor.getSelectedText();
    let [st, len] = editor.getSelectedRange();
    let [lnSt, lnLen] = editor.getSelectedLineRange();
    
    if (!sel || sel.length == 0) { // no selected text
    	if (st != lnSt) {
    		// not beginning of line, make block
    		editor.setSelectedText(markupStart+"\n\n"+markupEnd+"\n");
    		editor.setSelectedRange(st+markupStart.length+3,0);
      	}
      	else {
      		// beginning of line
    		editor.setSelectedText(markupStart+"\n\n"+markupEnd+"\n");
    		editor.setSelectedRange(st+markupStart.length+1,0);
    	}
    }
    else {
      editor.setSelectedText(markupStart+"\n"+sel+"\n"+markupEnd+"\n");
      editor.setSelectedRange(st+len+(markupStart.length*2)+6,0);
    }

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.