This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
urlencode.py
77 lines (53 loc) · 1.99 KB
/
urlencode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import sublime
import sublime_plugin
import urllib
def get_current_encoding(view, default='utf8'):
"""Get the encoding of view, else return default
"""
view_encoding = view.encoding()
if view_encoding == 'Undefined':
view_encoding = view.settings().get('default_encoding', default)
br1 = view_encoding.find('(')
br2 = view_encoding.find(')')
if br2 > br1:
view_encoding = view_encoding[br1+1:br2].replace(' ', '-')
return view_encoding
def updateSelection(self, edit, command):
view = self.view
selection = view.sel()
for region in selection:
if region.empty():
continue
s = view.substr(region)
view.replace(edit, region, command(view, s))
# update coords so next regions get shifted and still refer the correct buffer positions
region.b = region.a + len(s)
ST3 = sublime.version() == '' or int(sublime.version()) > 3000
if ST3:
def quote(view, s):
return urllib.parse.quote(s, safe='')
def unquote(view, s):
return urllib.parse.unquote(s)
else:
# py26 urllib does not quote unicode, so encode first
def quote(view, s):
enc = get_current_encoding(view)
return urllib.quote(s.encode(enc), safe='')
def unquote(view, s):
settings = sublime.load_settings('URLEncode.sublime-settings')
fallback_encodings = settings.get('fallback_encodings', [])
fallback_encodings.insert(0, get_current_encoding(view))
s = urllib.unquote(s.encode('utf8'))
## Now decode (to unicode) using best guess encoding
for enc in fallback_encodings:
try:
return s.decode(enc)
except UnicodeDecodeError:
continue
return s
class UrlencodeCommand(sublime_plugin.TextCommand):
def run(self, edit):
updateSelection(self, edit, quote)
class UrldecodeCommand(sublime_plugin.TextCommand):
def run(self, edit):
updateSelection(self, edit, unquote)