-
Notifications
You must be signed in to change notification settings - Fork 0
/
codemarks.py
333 lines (173 loc) · 6.14 KB
/
codemarks.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import sublime, sublime_plugin, os
import collections
import json
# add our codemarks cache folder if !exists
def plugin_loaded():
directory = '{:s}/User/codemarks'.format( sublime.packages_path() )
if not os.path.exists(directory):
os.makedirs(directory)
def Log( message ):
if Settings().get( 'verbose', False ):
print('[codemarks] ' + message)
def Settings():
return sublime.load_settings( 'codemarks.sublime-settings' )
def Variable( var, window=None):
window = window if window else sublime.active_window()
return sublime.expand_variables(var, window.extract_variables())
# convert marks-as-tuples back into sublime.Regions
def UnhashMarks( marks ):
newMarks = []
for mark in marks:
newMarks.append(sublime.Region(mark[0], mark[1]))
return newMarks
# convert sublime.Region into mark-as-tuple
def HashMarks( marks ):
newMarks = []
for mark in marks:
newMarks.append((mark.a, mark.b))
return newMarks
# convert sublime.Region into string
class RegionJSONCoder( json.JSONEncoder ):
def default( self, obj ):
if isinstance( obj, sublime.Region ):
return {
'__type__': 'sublime.Region',
'a': obj.a,
'b': obj.b,
}
return json.JSONEncoder.default(self, obj)
@staticmethod
def dict_to_object( d ):
if '__type__' not in d:
return d
type = d.pop('__type__')
if type == 'sublime.Region':
return sublime.Region(d.pop('a'), d.pop('b'))
else:
d['__type__'] = type
return d
class CodemarksCommand(sublime_plugin.TextCommand):
def __init__( self, edit ):
sublime_plugin.TextCommand.__init__( self, edit )
self.filename = Variable( '${file_name}' )
self.layers = collections.deque( Settings().get( 'layer_icons' ) )
self.layer = Settings().get( 'default_layer' )
while not self.layers[0] == self.layer:
self.layers.rotate(1)
self.marks = {}
for layer in Settings().get( 'layer_icons' ):
self.marks[layer] = []
def _is_empty( self ):
for layer in self.layers:
if self.marks[layer]:
return False
return True
# path to cache file
def _marks(self):
return '{:s}/User/codemarks/{:s}.cm_cache'.format( sublime.packages_path(), self.filename.replace( '.', '-' ) )
# render current layer marks
def _render( self ):
marks = UnhashMarks(self.marks[self.layer])
icon = Settings().get( 'layer_icons' )[self.layer]['icon']
scope = Settings().get( 'layer_icons' )[self.layer]['scope']
self.view.add_regions( 'bookmarks', marks, scope, icon, sublime.PERSISTENT | sublime.HIDDEN )
# add list of marks to existing list
def _add_marks( self, newMarks, layer=None ):
layer = layer if layer else self.layer
marks = []
if newMarks:
if not layer in self.marks:
self.marks[layer] = []
marks = self.marks[layer]
for mark in newMarks:
if mark in marks:
marks.remove(mark)
else:
marks.append(mark)
self.marks[layer] = marks
if layer == self.layer:
self._render()
# jump to selected layer
def _change_to_layer( self, layer ):
self.layer = layer
status_name = 'code_layer_status'
status = Settings().get( 'layer_status_location', ['permanent'] )
if 'temporary' in status:
sublime.status_message( self.layer )
if 'permanent' in status:
self.view.set_status( status_name, 'codemark layer: {:s}'.format( self.layer ) )
else:
self.view.erase_status( status_name )
if 'popup' in status:
if self.view.is_popup_visible():
self.view.update_popup( self.layer )
else:
self.view.show_popup( self.layer , 0, -1, 1000, 1000, None, None)
self._render()
def _save_marks( self ):
if not self._is_empty():
Log( 'Saving BBFile for ' + self.filename )
with open( self._marks(), 'w') as fp:
json.dump( self.marks, fp, cls=RegionJSONCoder )
def run( self, edit, **args ):
view = self.view
subcommand = args['subcommand']
if subcommand == 'mark_line':
selection = view.sel()
if Settings().get( 'mark_whole_line', False):
selection = view.lines( selection[0] )
line = args['line'] if 'line' in args else HashMarks( selection )
layer = args['layer'] if 'layer' in args else self.layer
self._add_marks( line, layer )
elif subcommand == 'clear_marks':
layer = args['layer'] if 'layer' in args else self.layer
self._add_marks([], layer)
elif subcommand == 'clear_all':
for layer in self.layers:
self._add_marks([], layer)
elif subcommand == 'layer_swap':
direction = args.get( 'direction' )
if direction == 'prev':
self.layers.rotate(-1)
elif direction == 'next':
self.layers.rotate(1)
else:
sublime.error_message( 'invalid layer swap' )
self._change_to_layer(self.layers[0])
elif subcommand == 'on_load':
Log( 'Loading BBFile for ' + self.filename )
try:
with open( self._marks(), 'r' ) as fp:
marks = json.load(fp, object_hook=RegionJSONCoder.dict_to_object)
for layer, regions in marks.items():
self.marks[layer] = regions
except Exception as e:
pass
self._change_to_layer( Settings().get( 'default_layer' ) )
elif subcommand == 'on_save':
self._save_marks()
elif subcommand == 'on_close':
if Settings().get( 'cache_marks_on_close', False ):
self._save_marks()
if self._is_empty():
Log( 'Removing BBFile for ' + self.filename )
try:
os.remove( self._marks() )
except FileNotFoundError as e:
pass
class CodemarksEventListener(sublime_plugin.EventListener):
def __init__(self):
sublime_plugin.EventListener.__init__(self)
def _contact(self, view, subcommand):
view.run_command( 'codemarks_fx', {
'subcommand': subcommand
})
def on_load_async(self, view):
if Settings().get('uncache_marks_on_load'):
self._contact(view, 'on_load')
def on_pre_save(self, view):
if Settings().get('cache_marks_on_save'):
self._contact(view, 'on_save')
def on_close(self, view):
if view.file_name() and Settings().get('cleanup_empty_cache_on_close'):
self._contact(view, 'on_close')