Drafts Action Directory

Run Script

Posted by @edgauthier, Last updated: 2018-06-22 20:56:04 UTC

Runs eval on the selected code (or entire draft if there’s no selection).

Optionally select an alternative input draft, as well as capture any errors and/or output as a new draft.

This action includes the Import Script action to allow importing other scripts for reuse.

Install

Steps

  • includeAction

    No preview available.

  • script

    // Run Script
    
    (() => {
    
      const main = () => {
    
        let output = null;
        const
          orig_draft = draft,
          r = editor.getSelectedRange(),
          code = r[1] > 0 
            ? editor.getSelectedText()
            : draft.content,
          opts = ["Yes", "No", "Abort"],
          title = "Alternate Input Draft",
          p = buttonPrompt(title, opts);
          p.isCancellable = false;
        
        p.show();
    
        switch (p.buttonPressed) {
          case "Yes":
            draft = app.selectDraft();
            editor.load(draft);
            break;
          case "Abort":
            context.cancel("Abort");
            return;
        }
    
        try {
          // Execute the script
          output = eval(code);
        }
        catch(e) {
          context.fail(e);
          saveInfoPrompt("Error",
            `Error: ${e.message}\n` + 
            `line: ${e.line - 32} column: ${e.column}`);
        }
      
        if (output) {
          saveInfoPrompt("Output", output)
        } else {
          draft = orig_draft;
          editor.load(draft);
        }
      }
    
      // Title, Buttons -> Prompt
      const buttonPrompt = (t, bs) =>
        bs.reduce((p, b) => {p.addButton(b);return p;},
          Object.assign(Prompt.create(), {title: t}));
    
      const saveInfoPrompt = (t, s) => {
        const opts = ["Save", "Discard"];
        const p = buttonPrompt(t, opts);
        p.isCancellable = false;
        p.addTextView("s", "", s);
        p.show();
        if (p.buttonPressed === "Save") {
          saveOutput(s);
        }
      };
      
      // Content -> new draft in editor
      const saveOutput = s => {
        draft = Draft.create();
        draft.content = s;
        draft.languageGrammar = "JavaScript";
        draft.addTag("script");
        draft.update();
        editor.load(draft);
        return draft;
      };
    
      main();
    
    })();

Comments

Actions available in the Action Directory are uploaded by community members. Use appropriate caution reviewing downloaded actions before use.