Drafts Action Directory

Go to Line

Posted by @edgauthier, Last updated: 2018-07-05 18:51:27 UTC

Prompts for a line number and then jumps to the beginning of that line. Can be helpful when editing long scripts or other drafts where you know a specific line that you want to jump to.

Install

Steps

  • script

    /**************************
     * Prompt utility methods *
     **************************
     */
    
    // Creates a new prompt with a title and message
    const newPrompt = (t = "", m = "") => 
      Object.assign(Prompt.create(),
        {"title": t, "message": m});
    
    const addButton = (p, b) => {
      p.addButton(b);
      return p;
    };
    
    // Takes a title and list of button names
    // Returns a prompt with title and list of buttons
    const buttonPrompt = (t, buttons) =>
      buttons.reduce(addButton, newPrompt(t));
    
    // p = Prompt
    // c = ["funcName", [arguments]]
    const addControl = (p, c) => {
      const func = c[0], args = c[1];
      p[func](...args);
      return p;
    };
    
    // Define a prompt in a object
    // {
    //   "title": "",
    //   "message": "",
    //   "controls": [
    //     ["funcName", [arguments]],
    //     ["funcName", [arguments]]
    //   ]
    // }
    const customPrompt = p => 
      p.controls.reduce(addControl,
        newPrompt(p.title, p.message));
    
    /***************************
     * General Utility Methods *
     ***************************
     */
    
    const splitLines = s => s.split(/[\r\n]/);
    const joinLines = xs => xs.join("\n");
    
    // clamp a number between a min and max (inclusive)
    const clamp = (n, min, max) => 
      Math.min(Math.max(n, min), max);
  • script

    // Editor - Go to Line
    
    (() => {
    
      const p = customPrompt({
        title: "Go to Line",
        controls: [
          ["addTextField", 
            ["ln", "Line Number:", "", 
            {"keyboard":"numberPad",
            "wantsFocus": true}]],
          ["addButton", ["Go"]]
        ]});
      
      if (p.show()){
        const 
          lines = splitLines(draft.content),
          lineCount = lines.length,
          inputNum = parseInt(p.fieldValues["ln"]),
          lineNum = clamp(inputNum, 1, lineCount),
          pos = (lineNum > 1)
            ? joinLines(lines.slice(0,lineNum-1)).length + 1
            : 0;
        editor.setSelectedRange(pos,0);
        editor.activate();
      }
    
    })();

Comments

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