Action

Find Selection

Posted by suderman, Last update almost 5 years ago

Search the current draft for the selection. Prompts for query if there is no selected text. Trigger this action multiple times to search the draft for each next occurance.

Steps

  • script

    // Get search input, from selection or prompt
    let input = function(){
    
      // First attempt to get input from selection
      let find = editor.getSelectedText(),
          start = draft.selectionStart,
          length = draft.selectionLength,
          end = start + length;
    
      // If there is none, try the prompt
      if (!find) {
    
        // Create prompt UI
        let p = Prompt.create();
        p.title = "Find Selection";
        p.isCancellable = false;
        p.addTextField("find", "", "", { 
          wantsFocus: true
        });
        p.addButton("Find");
    
        // Set values from prompt
        if (p.show()) {
          find = p.fieldValues["find"],
          start = editor.getSelectedRange()[0],
          length = find.length,
          end = start + length;
        }
      }
      
      // Return values as array
      return [ find, start, length, end ];
    }
    
    // Search draft for selection
    let search = function(){
    
      // Get search input, from selection or prompt
      let [ find, start, length, end ] = input();
      
      // Ensure the keyboard is active for selection
      editor.activate()
    
      // Find next occurence
      start = draft.content.indexOf( find, end );  
      
      // If none, try again from beginning
      if ( start < 0 ) {
        start = draft.content.indexOf( find, 0 );
      }
      
      // Update the selection to the next occurence
      if ( start > 0 ) {
        editor.setSelectedRange( start, length );
      }
    
    }
    
    search();

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.