Action

open URL in current line

Posted by @FlohGro, Last update about 1 year ago

created by @FlohGro / more on my Blog

open URL in current line

opens the url in the current line, if several urls are in the current line it will prompt you to select one.
if no url is found nothing happens

Its great to use this with a keyboard shortcut (e.g. cmd+shift+o) on a device with a keyboard attached.


If you find this useful and want to support me you can donate or buy me a coffe

Buy Me A Coffee

Steps

  • script

    // John Grubers regex: http://daringfireball.net/2010/07/improved_regex_for_matching_urls
    const regex = /((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))/gi;
    
    const curLineRange = editor.getSelectedLineRange()
    
    const str = editor.getTextInRange(curLineRange[0], curLineRange[1])
    
    
    let foundUrls = []
    let m;
    while ((m = regex.exec(str)) !== null) {
    
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
    
        }
    
        // The result can be accessed through the `m`-variable.
        foundUrls.push(m[0])
        /*m.forEach((match, groupIndex) => {
        foundUrls.push(match)
        });*/
    }
    let urlToOpen = undefined
    if(foundUrls.length == 0) {
        app.displayInfoMessage("no url found in current line")
    }
    
    if(foundUrls.length == 1) {
        urlToOpen = foundUrls[0]
    } 
    if(foundUrls.length > 1) {
        let p = new Prompt()
        p.title = "select url to open"
        for (url of foundUrls) {
            p.addButton(url)
        }
        if (p.show()) {
        	urlToOpen = p.buttonPressed
        } else {
            app.displayInfoMessage("no url selected")
        }
    }
    //alert(foundUrls)
    if(urlToOpen){
    
    	let result = app.openURL(urlToOpen)
    	console.log("open url " + urlToOpen + " result: " + result)
    	if(result){
    		//app.displaySuccessMessage("url opened")
    	} else {
    		app.displayErrorMessage("failed to open url")
    		context.fail()
    	}
    }
    

Options

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