Action

Run Script

Posted by @edgauthier, Last update over 6 years ago

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.

Steps

  • includeAction

    name
    Import Script
  • script

    // Scripting - 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);
          draft = saveInfoPrompt("Error",
            `Error: ${e.message}\n` + 
            `line: ${e.line} column: ${e.column}`) || orig_draft;
          editor.load(draft);
          return;
        }
      
        if (output) {
          draft = saveInfoPrompt("Output", output) || orig_draft;
        } 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") {
          return saveOutput(s);
        }
      };
      
      // Content -> new draft in editor
      const saveOutput = s => {
        draft = Draft.create();
        draft.content = s;
        draft.languageGrammar = "JavaScript";
        draft.addTag("script");
        draft.update();
        return draft;
      };
    
      main();
    
    })();

Options

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