Action

Global Find and Replace

Posted by jsamlarose, Last update about 3 years ago

Quick and dirty solution adapted from Derek Van’s “retitle” script (https://forums.getdrafts.com/t/drafts-used-for-a-zettelkasten/7966/12)

Steps

  • script

    //This scripts prompts for a new title and then replaces the old title with it.// 
    //The script also searches the current workspace to locate links based on the old title, and updates them.//
    // https://forums.getdrafts.com/t/drafts-used-for-a-zettelkasten/7966/12?u=jsamlarose
    
    
    // prompt for new title.// 
    let p = Prompt.create();
    p.title = "Search for";
    p.message = "careful; CMD-Z will not save you from your mistakes here... ";
    
    p.addTextField("searchFor", "Search For", editor.getSelectedText(), {
        "placeholder": " ",
        "autocorrect": false,
        "autocapitalization": "none",
        "wantsFocus": true
    });
    
    p.addTextField("replaceWith", "Replace With", "", {
        "placeholder": " ",
        "autocorrect": false,
        "autocapitalization": "none",
        "wantsFocus": true
    });
    
    // could also add a "search" button here that would pull up an MGCL style list of all instances, then you could also select the ones you want to replace...
    
    
    p.addButton("Replace");
    
    if (p.show()) {
        //Establish variables for the search and replacement
        let searchFor = p.fieldValues["searchFor"];
        let replaceWith = p.fieldValues["replaceWith"];
    
        //Search the current workspace looking for instances based on the query and update them.
        let count = 0
        let cCount = 0
        // let workspace = new Workspace() // JSLR: added this to search all not just current workspace and so avoid missing some drafts if a workspace is filtered
        var drafts = app.currentWorkspace.query("all"); // swap next line for this and remove the line above to focus on the current workspace only
        // var drafts = workspace.query("all");
    
        for (let d of drafts) {
            		if (d.content.includes(searchFor)){ 
                 // let regex =  new RegExp(searchFor,'g'); 
                 // d.content = d.content.replace(regex,replaceWith); 
                	d.content = d.content.replaceAll(searchFor, replaceWith);
                	d.update();
                	cCount++
                }
               count++
               
        }
    
        editor.setText(editor.getText().replace(searchFor, replaceWith))
        alert(cCount + " changed in " + count + " drafts evaluated.");
        draft.update()
    }

Options

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