forked from jdavisclark/CaseConversion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcase_conversion.py
61 lines (43 loc) · 1.51 KB
/
case_conversion.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
import sublime_plugin
import re
def to_snake_case(text):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def strip_wrapping_underscores(text):
return re.sub("^(_*)(.*?)(_*)$", r'\2', text)
def get_indexes(text, char):
indexlist = []
last = 0
while last != -1:
pos = text.find(char, last)
if pos == -1:
break
else:
indexlist.append(pos)
last = pos + 1
return indexlist
def to_pascal_case(text):
if "_" in text:
callback = lambda pat: pat.group(1).lower() + pat.group(2).upper()
text = re.sub("(\w)_(\w)", callback, text)
if text[0].islower():
text = text[0].upper() + text[1:]
return text
return text[0].upper() + text[1:]
def to_camel_case(text):
text = to_pascal_case(text)
return text[0].lower() + text[1:]
def run_on_selections(view, edit, func):
for s in view.sel():
region = view.word(s)
text = strip_wrapping_underscores(view.substr(region))
view.replace(edit, region, func(text))
class ConvertToSnakeCommand(sublime_plugin.TextCommand):
def run(self, edit):
run_on_selections(self.view, edit, to_snake_case)
class ConvertToCamel(sublime_plugin.TextCommand):
def run(self, edit):
run_on_selections(self.view, edit, to_camel_case)
class ConvertToPascal(sublime_plugin.TextCommand):
def run(self, edit):
run_on_selections(self.view, edit, to_pascal_case)