-
Notifications
You must be signed in to change notification settings - Fork 348
/
cssrem.py
executable file
·86 lines (69 loc) · 3.07 KB
/
cssrem.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
78
79
80
81
82
83
84
85
86
import sublime
import sublime_plugin
import re
import time
import os
SETTINGS = {}
lastCompletion = {"needFix": False, "value": None, "region": None}
def plugin_loaded():
init_settings()
def init_settings():
get_settings()
sublime.load_settings('cssrem.sublime-settings').add_on_change('get_settings', get_settings)
def get_settings():
settings = sublime.load_settings('cssrem.sublime-settings')
SETTINGS['px_to_rem'] = settings.get('px_to_rem', 40)
SETTINGS['max_rem_fraction_length'] = settings.get('max_rem_fraction_length', 6)
SETTINGS['available_file_types'] = settings.get('available_file_types', ['.css', '.less', '.sass'])
def get_setting(view, key):
return view.settings().get(key, SETTINGS[key]);
class CssRemCommand(sublime_plugin.EventListener):
def on_text_command(self, view, name, args):
if name == 'commit_completion':
view.run_command('replace_rem')
return None
def on_query_completions(self, view, prefix, locations):
# print('cssrem start {0}, {1}'.format(prefix, locations))
# only works on specific file types
fileName, fileExtension = os.path.splitext(view.file_name())
if not fileExtension.lower() in get_setting(view, 'available_file_types'):
return []
# reset completion match
lastCompletion["needFix"] = False
location = locations[0]
snippets = []
# get rem match
match = re.compile("([\d.]+)p(x)?").match(prefix)
if match:
lineLocation = view.line(location)
line = view.substr(sublime.Region(lineLocation.a, location))
value = match.group(1)
# fix: values like `0.5px`
segmentStart = line.rfind(" ", 0, location)
if segmentStart == -1:
segmentStart = 0
segmentStr = line[segmentStart:location]
segment = re.compile("([\d.])+" + value).search(segmentStr)
if segment:
value = segment.group(0)
start = lineLocation.a + segmentStart + 0 + segment.start(0)
lastCompletion["needFix"] = True
else:
start = location
remValue = round(float(value) / get_setting(view, 'px_to_rem'), get_setting(view, 'max_rem_fraction_length'))
# save them for replace fix
lastCompletion["value"] = str(remValue) + 'rem'
lastCompletion["region"] = sublime.Region(start, location)
# set completion snippet
snippets += [(value + 'px ->rem(' + str(get_setting(view, 'px_to_rem')) + ')', str(remValue) + 'rem')]
# print("cssrem: {0}".format(snippets))
return snippets
class ReplaceRemCommand(sublime_plugin.TextCommand):
def run(self, edit):
needFix = lastCompletion["needFix"]
if needFix == True:
value = lastCompletion["value"]
region = lastCompletion["region"]
# print('replace: {0}, {1}'.format(value, region))
self.view.replace(edit, region, value)
self.view.end_edit(edit)