-
Notifications
You must be signed in to change notification settings - Fork 0
/
name_converter.py
75 lines (55 loc) · 2.15 KB
/
name_converter.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
import sublime
import sublime_plugin
class NameConverter(sublime_plugin.TextCommand):
def run(self, edit, converter):
assert self.view.substr(self.view.sel()[0]), sublime.error_message(
'expected at least one valid selection')
selections = [sel for sel in self.view.sel()]
old_strs = [self.view.substr(sel) for sel in selections]
new_strs = [converter(s) for s in old_strs]
for region, new_str in zip(selections, new_strs):
self.view.replace(edit, region, new_str)
class CamelcaseToSnakecaseCommand(NameConverter):
"""Convert variable names with camelCase to snake_case.
"""
def run(self, edit):
super(CamelcaseToSnakecaseCommand, self).run(edit,
self.camelcase2snakecase)
@staticmethod
def camelcase2snakecase(name):
new_name = []
continous_caps = []
for char in name:
if char.isupper():
continous_caps.append(char)
else:
if len(continous_caps) > 0:
continous_caps.insert(-1, '_')
new_name.append(''.join(continous_caps).lower())
continous_caps = []
new_name.append(char)
if continous_caps:
if new_name:
new_name.append('_')
new_name.append(''.join(continous_caps).lower())
return ''.join(new_name)
class SnakecaseToCamelcaseCommand(NameConverter):
"""Convert variable names with snake_case to camelCase.
"""
def run(self, edit):
super(SnakecaseToCamelcaseCommand, self).run(edit,
self.snakecase2camelcase)
@staticmethod
def snakecase2camelcase(name):
new_name = []
need_convert = False
for char in name:
if char == '_':
need_convert = True
continue
if need_convert and char != '_':
new_name.append(char.upper())
need_convert = False
else:
new_name.append(char)
return ''.join(new_name)