Sublime Forum

Open URL doesn't work well

#1

Description & the fix: github.com/SublimeTextIssues/Core/issues/654

0 Likes

#2

I personally cooked up something more like this to also catch those links without the http://. I guess you could add more than www. support without http://, but I think that is probably all I care about.

[pre=#232628]import sublime_plugin
import webbrowser
import re

RE_LINK = r’’’(?x)(?i)
(
(
http(s?)://((a-zA-Z0-9-.]+(.a-zA-Z0-9-.]+)+)|localhost)| # http://
(?Pw{3})(.a-zA-Z0-9-.]+(.a-zA-Z0-9-.]+)+) # www.
)
(/?)(a-zA-Z0-9-.?,’/+&%$#])(\d\w./%±=&?:"’,|~;])
A-Za-z\d-
~:/?#@!$*+=]
)
‘’’

class OpenContextUrlCommand(sublime_plugin.TextCommand):
def run(self, edit, event):
url = self.find_url(event)
webbrowser.open_new_tab(url)

def is_visible(self, event):
    return self.find_url(event) is not None

def find_url(self, event):
    pt = self.view.window_to_text((event"x"], event"y"]))
    line = self.view.line(pt)

    line.a = max(line.a, pt - 1024)
    line.b = min(line.b, pt + 1024)

    text = self.view.substr(line)

    it = re.finditer(RE_LINK, text)

    for match in it:
        if match.start() <= (pt - line.a) and match.end() >= (pt - line.a):
            url = textmatch.start():match.end()]
            if match.group('www') is not None:
                url = 'http://' + url
            return url

    return None

def description(self, event):
    url = self.find_url(event)
    if len(url) > 64:
        url = url0:64] + "..."
    return "Open " + url

def want_event(self):
    return True[/pre]
0 Likes