Drafts Action Directory

Jump To Header

Posted by @StefanoRausch, Last updated: 2018-07-04 04:27:44 UTC

Jump to the start, headers ( lines starting with 1 – 6 #s ) or end of a Markdown-formatted draft.

Install

Steps

  • script

    /*
     * Original Script 'Find and Navigate to Headers' by Tim Nahumck.
     *
     * Enhanced by Stefano F. Rausch:
     *
     * - Applied the modular pattern.
     * - Using the strict programming conventions.
     * 
     * - Better ( real ) header recognition.
     * - Empty headers will not appear in the list of jump points.
     * - Jump to the start or end of a draft even if headers are missing.
     * - Simplified the conditional statements user response-wise.
     */
    
    ( () => {
      'use strict';
      
      let d = draft.content;
      
      // find lines that start with hashes
      
      let headers = d.match( /^#+?[ \t]+\S.*$/mgi );
      
      // display prompt
      
      let p = Prompt.create();
      
      p.title = "Jump To";
      
      p.addButton( "Start of Draft" );
      
      if ( headers ) {
        for ( let i = 0; i < headers.length; i++ ) {
        	p.addButton( headers[i] );
        }
      }
      
      p.addButton( "End of Draft" );
      
      let jump = p.show();
      
      // process user response
      
      if ( jump ) {
        if ( p.buttonPressed == "Start of Draft" ) {
          editor.setSelectedRange( 0, 0 );
        }
        
        else if ( p.buttonPressed == "End of Draft" ) {
            editor.setSelectedRange( d.length, 0 );
        }
        
        else {
          let header = p.buttonPressed;
          let position = d.search( header );
          
          editor.setSelectedRange( position + header.length, 0 )
       }
        
        editor.focus();
      }
      
      else {
        context.cancel();
      }
      
      return;
    } )();

Comments

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