-
Notifications
You must be signed in to change notification settings - Fork 6
/
ColorPick.py
47 lines (42 loc) · 1.43 KB
/
ColorPick.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
import sublime, sublime_plugin
import subprocess
from os import path
def is_valid_hex_color(s):
if len(s) not in (3, 6):
return False
try:
return 0 <= int(s, 16) <= 0xffffff
except ValueError:
return False
class ColorPickCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
sel = view.sel()
start_color = None
# get the currently selected color - if any
if len(sel) > 0:
selected = view.substr(view.word(sel[0])).strip()
if selected.startswith('#'): selected = selected[1:]
if is_valid_hex_color(selected):
start_color = selected
# get new color from picker
args = [path.join(sublime.packages_path(), 'ColorPick', 'bin', 'colorpick')]
if start_color:
args.append('-startColor')
args.append(start_color)
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
color = proc.communicate()[0]
if color:
# replace all regions with color
for region in sel:
word = view.word(region)
# if the selected word is a valid color, replace it
if is_valid_hex_color(view.substr(word)):
# include '#' if present
if view.substr(word.a - 1) == '#':
word = sublime.Region(word.a - 1, word.b)
# replace
self.view.replace(edit, word, '#' + color)
# otherwise just replace the selected region
else:
self.view.replace(edit, region, '#' + color)