-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsublime_plus.py
1469 lines (1135 loc) · 49.5 KB
/
sublime_plus.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sublime
import sublime_plugin
import re
import functools
import os
import zlib
import subprocess
import webbrowser
import difflib
import time
import sys
import Default.send2trash as send2trash
from operator import itemgetter
from itertools import groupby
# ------------------------------------------------------
# - Plugin Setup -
# ------------------------------------------------------
# global settings object that is used in almost all commands, initialized on plugin load
settings = sublime.Settings(9999)
def plugin_loaded():
global settings
settings = sublime.load_settings("Sublime Plus.sublime-settings")
for window in sublime.windows():
for view in window.views():
view.run_command("auto_fold_code_restore")
def open_path(path):
system = sys.platform
if system == "Darwin": # macOS
subprocess.Popen(("open", path))
elif system == "Windows" or system == "win32" or system == "win": # Windows
os.startfile(path)
else: # Linux and other Unix-like systems
# If it is an executable run it, otherwise
if os.access(path, os.X_OK):
subprocess.Popen(path)
else:
subprocess.Popen(("xdg-open", path))
# ------------------------------------------------------
# - Commands -
# ------------------------------------------------------
# Git Gui statusbar button override
class GgcOpenCommand(sublime_plugin.WindowCommand):
def run(self):
open_path(settings.get("git_gui_path"))
class OpenGithubRepoCommand(sublime_plugin.WindowCommand):
def run(self):
path = self.window.active_view().file_name()
if not path:
return
dirname = os.path.dirname(path)
gitdir = os.path.join(dirname, ".git")
# Check if there is a .git folder
if not os.path.isdir(gitdir):
return
# Check if repo is a github repo
git_file_to_check = os.path.join(gitdir, "config")
with open(git_file_to_check, "r") as file:
data = file.read()
if "github" not in data:
return
self.window.run_command(
"exec",
{"cmd": ["gh", "browse"], "quiet": True},
)
self.window.destroy_output_panel("exec")
class CommandEventListener(sublime_plugin.EventListener):
def on_window_command(self, view, command_name, args):
# Clicking on the repo button in the status bar will open a custom git gui instead of sublime merge
if command_name == "sublime_merge_open_repo":
path = settings.get("git_gui_path")
if path != "none":
return "ggc_open"
else:
return None
# Notepad
class ToggleUiCommand(sublime_plugin.ApplicationCommand):
def __init__(self):
self.notepad_toggle = False
def run(self):
window = sublime.active_window()
view = window.active_view()
if not self.notepad_toggle:
if window.is_menu_visible() is True:
window.set_menu_visible(False)
window.set_sidebar_visible(False)
window.set_tabs_visible(False)
window.set_status_bar_visible(False)
window.set_minimap_visible(False)
view.settings().set("gutter", False)
self.notepad_toggle = True
else:
window.set_tabs_visible(True)
window.set_sidebar_visible(True)
window.set_status_bar_visible(True)
window.set_minimap_visible(True)
view.settings().set("gutter", True)
window.set_menu_visible(True)
self.notepad_toggle = False
class ToggleNotePadCommand(sublime_plugin.ApplicationCommand):
def __init__(self):
self.notepad_toggle = False
self.old_scheme = None
self.original_centered_setting = None
def run(self):
window = sublime.active_window()
view = window.active_view()
print("HIDING GUTTER...")
if not self.notepad_toggle:
# Make notepad
if window.is_menu_visible() is True:
window.set_menu_visible(False)
window.set_sidebar_visible(False)
if not settings.get("show_tabs_in_notepad"):
window.set_tabs_visible(False)
if not settings.get("show_status_bar_in_notepad"):
window.set_status_bar_visible(False)
if not settings.get("show_minimap_in_notepad"):
window.set_minimap_visible(False)
if not settings.get("show_gutter_in_notepad"):
window.settings().set("gutter", False)
view.settings().set("toggle_status_bar", False)
window.run_command("hide_panel")
self.old_scheme = view.settings().get("color_scheme")
self.original_centered_setting = view.settings().get("draw_centered")
if settings.get("notepad_color_scheme_mode") == "Light":
view.settings().set("color_scheme", "NotepadLight.hidden-color-scheme")
elif settings.get("notepad_color_scheme_mode") == "Dark":
view.settings().set("color_scheme", "Notepad.hidden-color-scheme")
if settings.get("draw_centered_notepad"):
view.settings().set("draw_centered", True)
self.notepad_toggle = True
else:
# Revert to default state
window.set_tabs_visible(True)
window.set_status_bar_visible(True)
window.set_minimap_visible(True)
window.settings().set("gutter", True)
view.settings().set("toggle_status_bar", True)
if settings.get("notepad_color_scheme_mode") != "Default":
view.settings().set("color_scheme", self.old_scheme)
if settings.get("draw_centered_notepad"):
# If draw_centered was already on, turn it back on. Else turn it off
if self.original_centered_setting:
view.settings().set("draw_centered", True)
else:
view.settings().set("draw_centered", False)
self.notepad_toggle = False
class OutputPanelNotePadCommand(sublime_plugin.ApplicationCommand):
def __init__(self):
self.shown = False
def panel_creation(self, window, view):
window.focus_view(view)
if settings.get("temp_notepad_color_scheme_mode") == "Light":
view.settings().set("color_scheme", "NotepadLight.hidden-color-scheme")
elif settings.get("temp_notepad_color_scheme_mode") == "Dark":
view.settings().set("color_scheme", "Notepad.hidden-color-scheme")
# view.assign_syntax("scope:text.notes")
view.settings().set("font_size", settings.get("temp_notepad_font_size"))
if not settings.get("show_gutter_in_notepad"):
view.settings().set("gutter", False)
if settings.get("draw_centered_temp_notepad"):
view.settings().set("draw_centered", True)
self.shown = True
# def save_output_panel_contents(self):
# window = sublime.active_window()
# if window.find_output_panel("NotePad") == None:
# return 1
# view = window.find_output_panel("NotePad")
# region = sublime.Region(0, len(self.view))
# string = view.substr(region)
# print(string)
def run(self):
window = sublime.active_window()
if window.find_output_panel("NotePad") is None:
panel = window.create_output_panel("NotePad")
window.run_command("show_panel", {"panel": "output.NotePad"})
self.panel_creation(window, panel)
else:
window.run_command("show_panel", {"panel": "output.NotePad"})
view = window.find_output_panel("NotePad")
self.panel_creation(window, view)
# Selection and movement commands
class ToggleFoldSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
selection = view.sel()
def is_folded(region):
return self.view.unfold(region)
for region in selection:
if not is_folded(region):
self.view.fold(region)
else:
self.view.unfold(region)
str_buffer = view.substr(region)
if len(str_buffer) == 0:
sublime.set_timeout(lambda: sublime.status_message("There is no text selected!"), 0)
class SplitSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit, separator=None):
self.savedSelection = [r for r in self.view.sel()]
selectionSize = sum(map(lambda region: region.size(), self.savedSelection))
if selectionSize == 0:
# nothing to do
sublime.status_message("Cannot split an empty selection.")
return
if separator is not None:
self.splitSelection(separator)
else:
onConfirm, onChange = self.getHandlers()
inputView = sublime.active_window().show_input_panel(
"Separating character(s) for splitting the selection",
" ",
onConfirm,
onChange,
self.restoreSelection,
)
inputView.run_command("select_all")
def getHandlers(self):
live_split_selection = settings.get("live_split_selection")
if live_split_selection:
onConfirm = None
onChange = self.splitSelection
else:
onConfirm = self.splitSelection
onChange = None
return (onConfirm, onChange)
def restoreSelection(self):
selection = self.view.sel()
selection.clear()
for region in self.savedSelection:
selection.add(region)
def splitSelection(self, separator):
view = self.view
newRegions = []
for region in self.savedSelection:
currentPosition = region.begin()
regionString = view.substr(region)
if separator:
subRegions = regionString.split(separator)
else:
# take each character separately
subRegions = list(regionString)
for subRegion in subRegions:
newRegion = sublime.Region(currentPosition, currentPosition + len(subRegion))
newRegions.append(newRegion)
currentPosition += len(subRegion) + len(separator)
selection = view.sel()
selection.clear()
for region in newRegions:
selection.add(region)
window = sublime.active_window()
window.run_command("move", {"by": "characters", "forward": True})
window.run_command("move", {"by": "characters", "forward": False})
class SelectionToSnippetCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
selection = view.sel()
str_out = ""
for region in selection:
str_buffer = view.substr(region)
if len(str_buffer) == 0:
sublime.set_timeout(lambda: sublime.status_message("There is no text selected!"), 0)
else:
str_out = str_out + "\n" + str_buffer
window = sublime.active_window()
window.run_command("new_file")
snippet_view = window.active_view()
snippet_view.set_name("snippet.sublime-snippet")
snippet_view.run_command("insert_snippet_contents", {"string": str_out})
class InsertSnippetContentsCommand(sublime_plugin.TextCommand):
def run(self, edit, string):
snippet_head = "<snippet>\n\t<content><![CDATA["
snippet_foot = "\n\t]]></content>\n\t<!-- ${1:Selection Field 1}.${2:Selection Field 2} -->\n\t<tabTrigger>add_centralization</tabTrigger>\n\t<scope>source.python</scope>\n\t<description>Description</description>\n</snippet>"
string = snippet_head + string + snippet_foot
self.view.insert(edit, len(self.view), string)
class CycleThroughRegionsCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
visibleRegion = view.visible_region()
selectedRegions = view.sel()
nextRegion = None
for region in selectedRegions:
str_buffer = view.substr(region)
if len(str_buffer) == 0:
sublime.set_timeout(lambda: sublime.status_message("There is no text selected!"), 0)
if region.end() > visibleRegion.b:
nextRegion = region
break
if nextRegion is None:
nextRegion = selectedRegions[0]
view.show(nextRegion, False)
class MoveToTopOfFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.sel().clear()
selection = sublime.Region(0, 0)
self.view.sel().add(selection)
self.view.show(selection)
class MoveToBottomOfFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.sel().clear()
eof = len(self.view)
selection = sublime.Region(eof, eof)
self.view.sel().add(selection)
self.view.show(selection)
class FastMoveCommand(sublime_plugin.TextCommand):
def run(self, edit, direction, extend=False):
window = sublime.active_window()
if direction == "up":
for i in range(settings.get("fast_move_vertical_move_amount")):
window.run_command("move", {"by": "lines", "forward": False, "extend": extend})
if direction == "down":
for i in range(settings.get("fast_move_vertical_move_amount")):
window.run_command("move", {"by": "lines", "forward": True, "extend": extend})
if direction == "left":
for i in range(settings.get("fast_move_horizontal_character_amount")):
window.run_command("move", {"by": "characters", "forward": False, "extend": extend})
if direction == "right":
for i in range(settings.get("fast_move_horizontal_character_amount")):
window.run_command("move", {"by": "characters", "forward": True, "extend": extend})
class RemoveOrSelectAllCommentsCommand(sublime_plugin.TextCommand):
def run(self, edit, select=False):
comments = self.view.find_by_selector("comment")
if select:
self.view.selection.clear()
for region in reversed(comments):
if select:
self.view.selection.add(region)
else:
self.view.erase(edit, region)
# Tab Context commands
class RenameFileInTabCommand(sublime_plugin.TextCommand):
def run(self, edit, args=None, index=-1, group=-1, **kwargs):
w = self.view.window()
views = w.views_in_group(group)
view = views[index]
full_path = view.file_name()
if full_path is None:
return
directory, fn = os.path.split(full_path)
v = w.show_input_panel(
"New file name:",
fn,
functools.partial(self.on_done, full_path, directory),
None,
None,
)
name, ext = os.path.splitext(fn)
v.sel().clear()
v.sel().add(sublime.Region(0, len(name)))
def on_done(self, old, directory, fn):
new = os.path.join(directory, fn)
if new == old:
return
try:
if os.path.isfile(new):
if old.lower() != new.lower() or os.stat(old).st_ino != os.stat(new).st_ino:
# not the same file (for case-insensitive OSes)
raise OSError("File already exists")
os.rename(old, new)
v = self.view.window().find_open_file(old)
if v:
v.retarget(new)
except OSError as e:
sublime.error_message("Unable to rename: " + str(e))
except Exception as e:
sublime.error_message("Unable to rename: " + str(e))
class CopyFilePath(sublime_plugin.TextCommand):
def run(self, edit, args=None, index=-1, group=-1, **kwargs):
w = self.view.window()
views = w.views_in_group(group)
view = views[index]
file_name = view.file_name()
if file_name is None:
return
sublime.set_clipboard(file_name)
class TabContextTerminalCommand(sublime_plugin.TextCommand):
def run(self, edit, args=None, index=-1, group=-1, **kwargs):
window = self.view.window()
views = window.views_in_group(group)
view = views[index]
file_name = view.file_name()
if file_name:
env = os.environ.copy()
res_str = file_name[file_name.rfind("\\") : len(file_name)]
file_name = file_name.replace(res_str, "")
subprocess.Popen("cmd.exe", env=env, cwd=file_name)
else:
sublime.set_timeout(
lambda: sublime.status_message("Selected file cannot be opened in Terminal."),
0,
)
def is_enabled(self):
if sublime.platform() == "windows":
return True
else:
return False
def is_visible(self):
if sublime.platform() == "windows":
return True
else:
return False
class TabContextDeleteCommand(sublime_plugin.TextCommand):
def run(self, edit, args=None, index=-1, group=-1, **kwargs):
window = self.view.window()
views = window.views_in_group(group)
view = views[index]
file_name = view.file_name()
if file_name:
if sublime.ok_cancel_dialog(f"Are you sure you want to delete\n{file_name}?", "Delete"):
try:
send2trash.send2trash(file_name)
view.close()
except:
window.status_message("Unable to delete")
else:
sublime.set_timeout(lambda: sublime.status_message("Selected file cannot be deleted."), 0)
class ToggleReadonlyCommand(sublime_plugin.TextCommand):
def run(self, edit, args=None, index=-1, group=-1, **kwargs):
window = self.view.window()
views = window.views_in_group(group)
view = views[index]
if view.is_read_only():
view.set_read_only(False)
view.set_status("toggle_readonly", "Read only off")
sublime.set_timeout(lambda: ToggleReadonlyCommand.clear_status(view), 1250)
else:
view.set_read_only(True)
view.set_status(
"toggle_readonly", "Read only"
) # BUG: Sometimes this gets set when the view isn't actually read only somehow
@staticmethod
def clear_status(view):
view.set_status("toggle_readonly", "")
class TabContextEventListener(sublime_plugin.EventListener):
def check_readonly(self, view):
if view.is_read_only():
view.set_status("toggle_readonly", "Readonly")
else:
view.set_status("toggle_readonly", "")
def on_activated(self, view):
self.check_readonly(view)
class SortTabs(object):
sorting_indexes = (1,)
def __init__(self, *args, **kwargs):
super(SortTabs, self).__init__(*args, **kwargs)
def run(self, sort=True, close=False, current_grp_only=None):
# store the last command if sort is True
# so not if it's a close only call
# save active view to restore it latter
self.current_view = self.window.active_view()
self.current_grp_only = current_grp_only
if current_grp_only is None:
self.current_grp_only = settings.get("current_group_only", False)
list_views = []
# init, fill and sort list_views
self.init_file_views(list_views)
self.fill_list_views(list_views)
self.sort_list_views(list_views)
message = ""
if sort:
self.sort_views(list_views)
message = "%s" % (self.description(),)
if close is not False:
closed_view = self.close_views(list_views, close)
message = "Closed %i view(s) using %s" % (closed_view, self.description())
if message:
sublime.status_message(message)
# restore active view
self.window.focus_view(self.current_view)
def init_file_views(self, list_views):
if self.current_grp_only:
current_grp, _ = self.window.get_view_index(self.current_view)
for view in self.window.views():
group, _ = self.window.get_view_index(view)
if not self.current_grp_only or (group == current_grp):
list_views.append([view, group])
def fill_list_views(self, list_views):
pass
def sort_list_views(self, list_views):
# sort list_views using sorting_indexes
list_views.sort(key=itemgetter(*self.sorting_indexes))
def sort_views(self, list_views):
# sort views according to list_views
for group, groupviews in groupby(list_views, itemgetter(1)):
for index, view in enumerate(v[0] for v in groupviews):
# remove flag for auto sorting
view.settings().erase("sorttabs_tosort")
if self.window.get_view_index(view) != (group, index):
self.window.set_view_index(view, group, index)
def close_views(self, list_views, close):
if close < 0:
# close is a percent of opened views
close = int(len(list_views) / 100.0 * abs(close))
close = close if close else 1
closed = 0
for view in (v[0] for v in list_views[-close:]):
if view.id() != self.current_view.id() and not view.is_dirty() and not view.is_scratch():
self.window.focus_view(view)
self.window.run_command("close_file")
closed += 1
return closed
def description(self, *args):
# use class __doc__ for description
return self.__doc__
class SortTabsByNameCommand(SortTabs, sublime_plugin.WindowCommand):
"""Sort Tabs by file name"""
sorting_indexes = (1, 2)
def fill_list_views(self, list_views):
super(SortTabsByNameCommand, self).fill_list_views(list_views)
for item in list_views:
filename = os.path.basename(item[0].file_name() if item[0].file_name() else "")
item.append(filename.lower())
class SortTabsByFilePathCommand(SortTabsByNameCommand, sublime_plugin.WindowCommand):
"""Sort Tabs by file path"""
sorting_indexes = (1, 3, 2)
def fill_list_views(self, list_views):
super(SortTabsByFilePathCommand, self).fill_list_views(list_views)
for item in list_views:
dirname = os.path.dirname(item[0].file_name() if item[0].file_name() else "")
item.append(dirname.lower())
class SortTabsByTypeCommand(SortTabsByNameCommand):
"""Sort Tabs by file type"""
sorting_indexes = (1, 3, 2)
def fill_list_views(self, list_views):
super(SortTabsByTypeCommand, self).fill_list_views(list_views)
# add syntax to each element of list_views
for item in list_views:
item.append(item[0].settings().get("syntax", ""))
class SortTabsByDateCommand(SortTabsByNameCommand):
"""Sort Tabs by modification date"""
sorting_indexes = (1, 3, 4, 2)
def fill_list_views(self, list_views):
super(SortTabsByDateCommand, self).fill_list_views(list_views)
# add modifcation date and dirty flag to each element of list_views
for item in list_views:
modified = 0
dirty = item[0].is_dirty()
if not dirty:
dirty = True
filepath = item[0].file_name()
if filepath is not None:
try:
modified = os.path.getmtime(filepath)
dirty = False
except WindowsError:
pass
item.extend([not dirty, -modified])
class SortTabsByLastActivationCommand(SortTabsByNameCommand):
"""Sort Tabs by last activation"""
sorting_indexes = (1, 3, 2)
def fill_list_views(self, list_views):
super(SortTabsByLastActivationCommand, self).fill_list_views(list_views)
# add syntax to each element of list_views
for item in list_views:
item.append(-item[0].settings().get("sorttabs_lastactivated", 0))
# Workspace
class WorkspaceListInputHandler(sublime_plugin.ListInputHandler):
def __init__(self):
self.project_directories = settings.get("sublime_workspace_directories_list")
def find_workspaces(self):
s_workspace_file = re.compile("^.*?\.sublime-workspace$")
results = []
for directory in self.project_directories:
for name in os.listdir(directory):
if s_workspace_file.match(name):
results.append(name)
return results
def name(self):
return "workspace"
def list_items(self):
list_items = []
for workspace in self.find_workspaces():
workspace = workspace.replace(".sublime-workspace", "")
list_items.append(workspace)
return list_items
class CloseWindowListInputHandler(sublime_plugin.ListInputHandler):
def name(self):
return "close"
def list_items(self):
return [("Close Current Workspace", True), ("Keep Current Workspace", False)]
class OpenWorkspaceFromListCommand(sublime_plugin.WindowCommand):
def input_description(self):
return "Select Workspace"
def input(self, args):
if "workspace" not in args:
return WorkspaceListInputHandler()
if "close" not in args:
return CloseWindowListInputHandler()
def run(self, workspace, close):
if workspace is not None:
workspace = workspace + ".sublime-workspace"
project_directories = settings.get("sublime_workspace_directories_list")
if len(project_directories) > 0:
# space_path = os.path.abspath(workspace)
s_workspace_file = re.compile("^.*?\.sublime-workspace$")
results = []
for directory in project_directories:
for name in os.listdir(directory):
if s_workspace_file.match(workspace):
if name == workspace:
workspace = directory + "\\" + name
window = sublime.active_window()
if close:
window.run_command("close_workspace")
window.run_command("close_pane")
open_path(workspace)
else:
open_path(workspace)
else:
sublime.set_timeout(
lambda: sublime.status_message(
"No directories have been added to the workspace directories list. See Sublime Plus.sublime-setting for more info."
),
0,
)
# Sidebar navigation commands
class TreeViewGoToParentNode(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("move_to", {"to": "bol", "extend": False})
class TreeViewGoToRootNode(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("move", {"by": "characters", "forward": False})
class TreeViewGoToChildNode(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("move_to", {"to": "eol", "extend": False})
class TreeViewMoveDown(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("move", {"by": "lines", "forward": True})
class TreeViewMoveLeft(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("move", {"by": "characters", "forward": False})
class TreeViewMoveRight(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("move", {"by": "characters", "forward": True})
class TreeViewMoveUp(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("move", {"by": "lines", "forward": False})
# Layout commands
class PolyfillSetLayoutCommand(sublime_plugin.WindowCommand):
def run(self, cols, rows, cells):
num_groups_before = self.window.num_groups()
active_group_before = self.window.active_group()
self.window.run_command("set_layout", {"cols": cols, "rows": rows, "cells": cells})
if num_groups_before == self.window.num_groups():
self.window.focus_group(active_group_before)
return
if len(self.window.views_in_group(active_group_before)) < 2:
return
view = self.window.active_view_in_group(active_group_before)
self.window.set_view_index(view, self.window.active_group(), 0)
# Autofold
class AutoFoldCommandBase:
"""
Base class for common methods for auto fold commands
"""
def __init__(self):
self.__storage_file__ = "AutoFoldCode.sublime-settings"
self.CURRENT_STORAGE_VERSION = 1
self.MAX_BUFFER_SIZE_DEFAULT = 1000000
def _save_view_data(self, view, clean_existing_versions):
"""
Save the folded regions of the view to disk.
"""
file_name = view.file_name()
if file_name is None:
return
# Skip saving data if the file size is larger than `max_buffer_size`.
settings = self._load_storage_settings(save_on_reset=False)
if view.size() > settings.get("max_buffer_size", self.MAX_BUFFER_SIZE_DEFAULT):
return
def _save_region_data(data_key, regions):
all_data = settings.get(data_key)
if regions:
if clean_existing_versions or file_name not in all_data:
all_data[file_name] = {}
view_data = all_data.get(file_name)
view_data[view_content_checksum] = regions
else:
all_data.pop(file_name, None)
settings.set(data_key, all_data)
view_content_checksum = self._compute_view_content_checksum(view)
# Save folds
fold_regions = [(r.a, r.b) for r in view.folded_regions()]
_save_region_data("folds", fold_regions)
# Save selections if set
if settings.get("save_selections") is True:
selection_regions = [(r.a, r.b) for r in view.selection]
_save_region_data("selections", selection_regions)
# Save settings
sublime.save_settings(self.__storage_file__)
def _clear_cache(self, name):
"""
Clears the cache. If name is '*', it will clear the whole cache.
Otherwise, pass in the file_name of the view to clear the view's cache.
"""
settings = self._load_storage_settings(save_on_reset=False)
def _clear_cache_section(data_key):
all_data = settings.get(data_key)
file_names_to_delete = [file_name for file_name in all_data if name == "*" or file_name == name]
for file_name in file_names_to_delete:
all_data.pop(file_name)
settings.set(data_key, all_data)
_clear_cache_section("folds")
_clear_cache_section("selections")
sublime.save_settings(self.__storage_file__)
def _load_storage_settings(self, save_on_reset):
"""
Loads the settings, resetting the storage file, if the version is old (or broken).
Returns the settings instance
"""
try:
settings = sublime.load_settings(self.__storage_file__)
except Exception as e:
print("[AutoFoldCode.] Error loading settings file (file will be reset): ", e)
save_on_reset = True
if self._is_old_storage_version(settings):
settings.set("max_buffer_size", self.MAX_BUFFER_SIZE_DEFAULT)
settings.set("version", self.CURRENT_STORAGE_VERSION)
settings.set("folds", {})
settings.set("selections", {})
if save_on_reset:
sublime.save_settings(self.__storage_file__)
return settings
def _is_old_storage_version(self, settings):
settings_version = settings.get("version", 0)
# Consider the edge case of a file named "version".
return not isinstance(settings_version, int) or settings_version < self.CURRENT_STORAGE_VERSION
def _compute_view_content_checksum(self, view):
"""
Returns the checksum in Python hex string format.
The view content returned is always the latest version, even when closing without saving.
"""
view_content = view.substr(sublime.Region(0, view.size()))
int_crc32 = zlib.crc32(view_content.encode("utf-8"))
return hex(int_crc32 % (1 << 32))
class AutoFoldCodeListener(sublime_plugin.EventListener, AutoFoldCommandBase):
"""
Listen to changes in views to automatically save code folds.
"""
def on_load_async(self, view):
view.run_command("auto_fold_code_restore")
def on_post_save_async(self, view):
# Keep only the latest version, since it's guaranteed that on open, the
# saved version of the file is opened.
if settings.get("save_folds_on_save"):
AutoFoldCommandBase.__init__(self)
self._save_view_data(view, True)
# Listening on close events is required to handle hot exit, for whom there is
# no available listener.
def on_close(self, view):
# In this case, we don't clear the previous versions view data, so that on
# open, depending on the previous close being a hot exit or a regular window
# close, the corresponding view data is retrieved.
#
# If a user performs multiple modifications and hot exits, the view data for
# each version is stored. This is acceptable, since the first user initiated
# save will purge the versions and store only the latest.
self._save_view_data(view, False)
def on_text_command(self, view, command_name, args):
if command_name == "unfold_all" and view.file_name() is not None:
self._clear_cache(view.file_name())
class AutoFoldCodeClearAllCommand(sublime_plugin.WindowCommand, AutoFoldCommandBase):
"""
Clears all the saved code folds and unfolds all the currently open windows.
"""
def run(self):
AutoFoldCommandBase.__init__(self)
self._clear_cache("*")
self.window.run_command("auto_fold_code_unfold_all")
class AutoFoldCodeClearCurrentCommand(sublime_plugin.WindowCommand, AutoFoldCommandBase):
"""
Clears the cache for the current view, and unfolds all its regions.
"""
def run(self):
AutoFoldCommandBase.__init__(self)
view = self.window.active_view()
if view and view.file_name():
view.unfold(sublime.Region(0, view.size()))
self._clear_cache(view.file_name())
def is_enabled(self):
view = self.window.active_view()
return view is not None and view.file_name() is not None