-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquick_settings.py
1179 lines (831 loc) · 39.3 KB
/
quick_settings.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
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import os
import re
import sys
import pprint
import sublime
import sublime_plugin
import ast
import json
from collections import OrderedDict
# # Import the debugger
from debug_tools import getLogger
from debug_tools.third_part import load_data_file
from debug_tools.third_part import write_data_file
from debug_tools.utilities import pop_dict_last_item
# Enable debug messages: (bitwise)
#
# 0 - Disabled debugging
# 1 - Error logging messages
# 2 - Settings loading notices
# 4 - Settings loading file contents
# 8 - Quick panel selection.
#
# 127 - All debugging levels at the same time.
log = getLogger( 127, __name__ )
#log.setup( "DebugLog.txt" )
#log.clear()
# log( 2, "Debugging" )
# log( 2, "..." )
# log( 2, "..." )
this_view_file = 'Current/This View'
current_syntax_file = 'Current Syntax'
current_project_file = 'Current Project'
distraction_free_file = 'Distraction Free'
default_preferences_file = 'Preferences'
# This must be the snake case name of the main class
command_name = "quick_settings_edit_preferences"
standard_settings_types = ('default', 'default_'+sublime.platform(), 'user')
standard_settings_names = ( distraction_free_file, current_syntax_file, current_project_file, this_view_file )
CURRENT_PACKAGE_FILE = os.path.dirname( os.path.realpath( __file__ ) )
PACKAGE_ROOT_DIRECTORY = CURRENT_PACKAGE_FILE.replace( ".sublime-package", "" )
CURRENT_PACKAGE_NAME = os.path.basename( PACKAGE_ROOT_DIRECTORY )
g_settings = {}
main_function_key = 'main_function'
last_quick_settings_input = 'last_quick_settings_input'
MAXIMUM_WORSPACES_ENTRIES = 100
def plugin_loaded():
load_settings()
def load_settings():
global g_settings
global g_package_settings_path
g_package_settings_path = os.path.join( sublime.packages_path(), "User", CURRENT_PACKAGE_NAME + ".inputs" )
try:
# Returns an OrderedDict
g_settings = load_data_file( g_package_settings_path, exceptions=True )
except Exception as error:
log.exception( "Could not load the settings file" )
write_data_file( g_package_settings_path, g_settings, debug=0 )
def save_index(key, index):
g_settings[key] = index
window = sublime.active_window()
project_file_name = window.project_file_name()
window_settings = window.settings()
window_settings.set(last_quick_settings_input, g_settings)
if project_file_name:
workspaces = g_settings.setdefault( 'workspaces_' + last_quick_settings_input, OrderedDict() )
# https://docs.python.org/3/library/collections.html#collections.OrderedDict.move_to_end
# https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python
workspacesetting = workspaces.setdefault(project_file_name, {key: index})
workspacesetting[key] = index
workspaces.move_to_end( project_file_name, last=False )
while len( workspaces ) > MAXIMUM_WORSPACES_ENTRIES:
pop_dict_last_item( workspaces )
write_data_file( g_package_settings_path, g_settings, debug=0 )
def get_index(key):
indexdict = _get_index(key)
index = indexdict.get( key, 0 )
return index
def has_index(key):
return key in _get_index(key)
def _get_index(key):
window = sublime.active_window()
window_settings = window.settings()
project_file_name = window.project_file_name()
workspaces = g_settings.get( 'workspaces_' + last_quick_settings_input, {} )
indexdict = window_settings.get(
last_quick_settings_input,
workspaces.get(project_file_name, g_settings )
)
return indexdict
def show_quick_panel(view, options, done, highlighted=None, last=-1):
"""
Allow to add a default text to the quick panel API self.window.show_quick_panel
https://github.com/SublimeTextIssues/Core/issues/1896
"""
# How can I test whether a variable holds a lambda?
# https://stackoverflow.com/questions/3655842/how-can-i-test-whether-a-variable-holds-a-lambda
if callable( last ):
last = last()
sublime.set_timeout(lambda: view.window().show_quick_panel(options, done, sublime.KEEP_OPEN_ON_FOCUS_LOST, last, highlighted), 10)
def get_preference_name(file):
return os.path.basename(file).rsplit('.', 1)[0]
def json_list(x):
d = sublime.decode_value(x)
#sys.stderr.write("d: %s\n" % d)
if not isinstance(d, list):
raise ValueError("Expected a JSON list")
return d
def json_dict(x):
d = sublime.decode_value(x)
#sys.stderr.write("d: %s\n" % d)
if not isinstance(d, dict):
raise ValueError("Expected a JSON dictionary")
return d
def show_input(view, caption, initial, on_done=None, on_change=None, on_cancel=None, on_load=None):
window = view.window()
def do_input():
_initial = initial
if not isinstance(_initial, str):
_initial = json.dumps(_initial)
input_view = window.show_input_panel(caption, _initial, on_done=on_done, on_change=on_change, on_cancel=on_cancel)
if on_load:
on_load(input_view)
sublime.set_timeout(do_input, 10)
def get_descriptions(data):
r"""get descriptions from preferences string
extract descriptions from passed ``data``.
:param data:
string containing json preferences file.
This is only a rough parser and will fetch also keys from
sub-dictionaries. Calling function is responsible to
select correct data.
"""
COMMENT_RE = re.compile(r"(?s)\s*//\s?(.*)")
COMMENT_RE2 = re.compile(r'''(?xs)
(?:
"(?:[^"\\]|\\.)*"
| (?:(?!//)[^"])
)+
(//.*)
''')
COMMENT_START = re.compile(r"^\s*/\*(.*)")
COMMENT_END = re.compile(r"(.*)\*/")
KEY_RE = re.compile(r'\s*"([^"]+)"\s*:')
INDENT_RE = re.compile(r'^\s*')
description = {}
comment = ""
is_comment = False
for line in data.splitlines(1):
if is_comment:
m = COMMENT_END.search(line)
if m:
comment += m.group(1).rstrip()+"\n"
is_comment = False
else:
comment += line
continue
m = COMMENT_START.match(line)
if m:
is_comment = True
comment += m.group(1).rstrip()+"\n"
continue
m = COMMENT_RE.match(line)
if m:
s = m.group(1)
if not s: s = "\n"
comment += s
continue
m = COMMENT_RE2.match(line)
if m:
#sys.stderr.write("line1: %s\n" % (repr(line)))
line = line[:m.start(1)].rstrip()+"\n"
#sys.stderr.write("line2: %s\n" % (repr(line)))
if not line.strip(): # empty line resets current comment
comment = ""
continue
m = KEY_RE.match(line)
if m:
while comment.startswith('\n'):
comment = comment[1:]
indent = INDENT_RE.match(comment).group(0)
if indent:
comment = ''.join([ l.startswith(indent) and l[len(indent):] or l for l in comment.splitlines(1) ])
description[m.group(1)] = {"description": comment.replace("\r", "") or "No help available"}
comment = ""
return description
# resolution order of settings
# Packages/Default/Preferences.sublime-settings
# Packages/Default/Preferences (<platform>).sublime-settings
# Packages/User/Preferences.sublime-settings
# <Project Settings>
# Packages/<syntax>/<syntax>.sublime-settings
# Packages/User/<syntax>.sublime-settings
# <Buffer Specific Settings>
def get_current_syntax(view, syntax=None):
current_syntax = None
settings = view.settings()
if syntax:
current_syntax = syntax
elif settings.has('syntax'):
current_syntax = get_preference_name(settings.get('syntax'))
return current_syntax
def save_preference(view, setting_file, setting_name, value):
# log( 2, "save__preference" )
# log( 2, "save__preference, setting_file: " + str( setting_file ) )
# log( 2, "save__preference, setting_name: " + str( setting_name ) )
# log( 2, "save__preference, value: " + str( value ) )
if setting_file == this_view_file:
settings = view.settings()
settings.set(setting_name, value)
return
if setting_file == current_project_file:
data = view.window().project_data()
if 'settings' not in data:
data['settings'] = {}
data['settings'][setting_name] = value
view.window().set_project_data(data)
return
setting_file = os.path.basename(setting_file)
# log( 2, "save__preference, setting_file: " + setting_file )
settings = sublime.load_settings(setting_file+'.sublime-settings')
settings.set(setting_name, value)
sublime.save_settings(setting_file+'.sublime-settings')
def load_preferences():
# log( 2, "load__preferences" )
preferences = {}
preferences_files = sublime.find_resources("*.sublime-settings")
for preference_file in preferences_files:
# log( 2, "load__preferences, preference_file: {0}".format( preference_file ) )
preference_name = get_preference_name(preference_file)
# log( 2, "load__preferences, preference_name: {0}".format( preference_name ) )
platform = "any"
if preference_name[-5:].lower() == "(osx)":
preference_name = preference_name[:-6]
platform = "osx"
elif preference_name[-9:].lower() == "(windows)":
preference_name = preference_name[:-10]
platform = "windows"
elif preference_name[-7:].lower() == "(linux)":
preference_name = preference_name[:-8]
platform = "linux"
# log( 2, "load__preferences, preference_name: {0}".format( preference_name ) )
if preference_name == "Base File":
preference_name = default_preferences_file
if preference_name == "Global":
preference_name = default_preferences_file
if "/User/" in preference_file:
setting_type = "user"
else:
setting_type = "default"
if platform != "any":
setting_type = setting_type+"_"+platform
if preference_name not in preferences:
preferences[preference_name] = {}
if setting_type not in preferences[preference_name]:
preferences[preference_name][setting_type] = {}
#sys.stderr.write("preference_name: %s, setting_type: %s\n" % (preference_name, setting_type))
preference = preferences[preference_name][setting_type]
# log( 2, "preference: " + str( preference ) )
preference_data = sublime.load_resource(preference_file)
if preference_data:
preference_settings = {}
try:
#import spdb ; spdb.start()
description = get_descriptions(preference_data)
#sys.stderr.write("preference_data: %s\n" % preference_)
preference_data = sublime.decode_value(preference_data)
for setting_name, setting_value in preference_data.items():
if setting_name not in description:
preference_settings[setting_name] = {"description": "No help available"}
else:
preference_settings[setting_name] = description[setting_name]
preference_settings[setting_name]['value'] = setting_value
except:
log( 1, "load_preferences: Error reading %s (preference_data is %s)", preference_file, preference_data )
preference.update(preference_settings)
# for item in preferences:
# print( "isinstance(" + str( item ) + ", str): " + str( isinstance(item, str) ) )
# print( "isinstance(" + str( item ) + ", dict): " + str( isinstance(item, dict) ) )
# print( "item: " + json.dumps( preferences[item] ) )
return preferences
def load_syntax_names():
syntax_names = []
syntax_types = [ "*.tmLanguage", "*.sublime-syntax" ]
for syntax_type in syntax_types:
syntaxes = sublime.find_resources(syntax_type)
for syntax in syntaxes:
syntax_names.append(os.path.basename(syntax).rsplit('.', 1)[0])
return syntax_names
class HelperView():
def __init__(self, window, help_view_name, is_enabled=True):
self.window = window
self.is_enabled = is_enabled
self.help_view = self.window.create_output_panel(help_view_name)
self.help_view_name = help_view_name
self.help_view.settings().set('auto_indent', False)
def disable_panel():
self.is_enabled = False
def enable_panel():
self.is_enabled = True
def run_command(self, command, args={}):
if self.is_enabled:
self.help_view.run_command(command, args)
def show_panel(self):
if self.is_enabled:
self.window.run_command("show_panel", {"panel": "output."+self.help_view_name})
def hide_panel(self):
if self.is_enabled:
self.window.run_command("hide_panel", {"panel": "output."+self.help_view_name})
def focus_begining(self):
if self.is_enabled:
self.help_view.show(0)
# commands are
#
# Edit Preferences --> User
# Edit Syntax Preferences --> User
#
class QuickSettingsEditPreferencesCommand(sublime_plugin.WindowCommand):
# meta.<setting_name>: {
# "widget": "select"
# "value": [ "", [caption, value] ]
# "validate": "Package Name.module.function"
# "tip": "text" in status bar
# "help": "Packages/..." or "text"
# }
#
def set_setting_value(self, setting_file, setting_name, value):
# log( 2, "set__setting_value, setting_file: " + str( setting_file ) )
# log( 2, "set__setting_value, setting_name: " + str( setting_name ) )
# log( 2, "set__setting_value, json.dumps(value): " + json.dumps(value) )
if setting_file == current_syntax_file:
setting_file = self.current_syntax
save_preference(self.view, setting_file, setting_name, value)
self.options_names[self.index][1] = json.dumps(value)
def make_pref_rec(self, setting_file, setting_type, setting_name, value):
return "%s/%s/%s" % (setting_file, setting_type, setting_name), value
def getUserValueAndDescription(self, setting_file, setting_name):
"""
@setting_name the name of the setting
@setting_file the name of the setting's file on self.setting_files[setting_file]
@return dictionary with the setting value and description
dict: {'value': True, 'description': 'No help available'}
"""
_setting = {'value': None, 'description': 'No help available'}
platform = sublime.platform()
settings = [ self.setting_files[setting_file], self.get_default_setting_names(setting_file) ]
setting_types = \
[
"user_%s" % platform,
"user",
"default_%s" % platform,
"default",
]
for setting in settings:
for setting_type in setting_types:
if setting_type in setting:
if setting_name in setting[setting_type]:
_setting = setting[setting_type][setting_name]
if setting_file == this_view_file:
_setting['value'] = self.view.settings().get(setting_name)
elif setting_file == current_project_file:
data = self.view.window().project_data()
if 'settings' in data and setting_name in data['settings']:
_setting['value'] = data['settings'].get(setting_name)
return _setting
return _setting
def get_default_setting_names(self, setting_name):
pref_default = None
if self.is_preferences(setting_name):
pref_default = self.setting_files[default_preferences_file]
else:
pref_default = {'default': {}, 'default_'+sublime.platform(): {}}
return pref_default
def get_setting_names(self, setting_name):
setting = self.setting_files[setting_name]
# log( 2, "get__setting_names, setting: " + str( setting ) )
# log( 2, "get__setting_names, setting type: " + str( type( setting ) ) )
if self.is_preferences(setting_name):
pref_default = self.setting_files[default_preferences_file]
else:
pref_default = {'default': {}, 'default_'+sublime.platform(): {}}
return set \
(
[ x
for y in standard_settings_types
for x in setting.get(y, {}).keys()
] +
[ x
for y in standard_settings_types
for x in pref_default.get(y, {}).keys()
]
)
def is_preferences(self, setting_file):
return setting_file in self.syntax_names or setting_file in standard_settings_names
def getDefaultValueAndDescription(self, setting_file, setting_name, is_metadata=False):
"""
@setting_file the name of the setting file name on self.setting_files
@setting_name the name of the setting
setting_file: Preferences
setting_name: word_wrap
setting_file: Default
setting_name: adaptive_dividers
@return a dictionary with the keys `value` and `description` for the given setting file and setting name.
{'value': 0, 'description': 'Set to a value other than 0 to force wrapping at that column rather than the\nwindow width\n'}
{'value': './\\()"\'-:,.;<>~!@#$%^&*|+=[]{}`~?', 'description': 'Characters that are considered to separate words\n'}
"""
setting = self.setting_files[setting_file]
for item in standard_settings_types:
if setting_name in setting.get(item, {}):
return setting[item][setting_name]
if self.is_preferences(setting_file):
return self.getDefaultValueAndDescription(default_preferences_file, setting_name, is_metadata)
if is_metadata:
return None
return {'value': 0, 'description': 'No Description available'}
def getSettingMetadata(self, setting_file, setting_name, defaultValueAndDescription):
"""
@setting_file the name of the setting file name on self.setting_files
@setting_name the name of the setting
@defaultValueAndDescription a dictionary with the keys `value` and `description` for
the given setting file and setting setting_file.
{'value': 0, 'description': 'Set to a value other than 0 to force wrapping'}
@return
"""
settingMetadata = self.getDefaultValueAndDescription(setting_file, "meta."+setting_name, True)
# log( 8, "get_SettingMetadata, settingMetadata: " + str( settingMetadata ) )
#sys.stderr.write("settingMetadata: %s\n" % settingMetadata)
if settingMetadata:
return settingMetadata.get('value')
setting_value = defaultValueAndDescription.get('value')
if isinstance(setting_value, bool):
return \
{
'widget': 'select_bool'
}
if isinstance(setting_value, float):
return \
{
'widget': 'input',
'validate': 'float',
}
if isinstance(setting_value, int):
return \
{
'widget': 'input',
'validate': 'int',
}
if isinstance(setting_value, list):
return \
{
'widget': 'input',
'validate': 'json_list'
}
if isinstance(setting_value, dict):
return \
{
'widget': 'input',
'validate': 'json_dict'
}
return \
{
'widget': 'input'
}
def widget_select_bool(self, option, value=None, validate=None):
# log( 8, "widget__select_bool, option: %s" % str(option) )
view = self.window.active_view()
options = ["BACK (Open the Last Menu)", "true", "false"]
setting_file = option[0]
setting_name = option[1]
settings = view.settings()
default = settings.get(setting_name, "")
def done(index):
# log( 8, "widget__select_bool, done, index: " + str( index ) )
view.erase_status("preferences_editor")
if index < 1:
settings.set( setting_name, default )
if index < 0:
return self.shutdown()
elif index == 1:
self.set_setting_value(setting_file, setting_name, True)
sublime.status_message("Set %s to %s" % (setting_file + '/' + setting_name, 'True'))
else:
self.set_setting_value(setting_file, setting_name, False)
sublime.status_message("Set %s to %s" % (setting_file + '/' + setting_name, 'False'))
self.preferences_selector()
def highlight(index):
if index < 1:
settings.set(setting_name, default)
elif index == 1:
settings.set(setting_name, True)
elif index == 2:
settings.set(setting_name, False)
# for op in options: log( 2, "op: {0}".format( op ) )
view.set_status("preferences_editor", "Set %s" % (setting_file + '/' + setting_name))
show_quick_panel(view, options, done, highlight)
def widget_select(self, option, value=None, validate=None, values=[]):
# log( 8, "widget__select, option: %s" % str(option) )
view = self.window.active_view()
setting_file = option[0]
setting_name = option[1]
settings = view.settings()
default = settings.get(setting_name, "")
# values.append({})
options = []
commands = []
args = []
types = []
_values = []
if len( values ) > 0 and isinstance(values[0], dict):
values.insert( 0, {"value": default, "caption": "Cancel Changes"} )
for data in values:
args.append( data.get('args', {}) )
types.append( data.get('type', 'window') )
_values.append( data.get('value') )
options.append( data['caption'] )
commands.append( data.get('command') )
else:
values.insert( 0, default )
_values = values
options = [ str(x) for x in values ]
options.remove( default )
options.insert( 0, [ "Cancel Changes" ] )
def done(index):
# log( 8, "widget__select, done, index: %s" % str(index) )
view.erase_status("preferences_editor")
if index < 1:
settings.set( setting_name, default )
if index == 0:
return self.preferences_selector()
else:
return self.shutdown()
# if command is set, let the command handle this preference
if commands:
if commands[index]:
context = view
if types[index] == "window":
context = view.window()
sublime.set_timeout(lambda: context.run_command(commands[index], args[index]), 10)
return
self.set_setting_value(setting_file, setting_name, _values[index])
sublime.status_message("Set %s to %s" % (setting_file + '/' + setting_name, str(_values[index])))
self.preferences_selector()
def highlight(index):
# log( 8, "widget__select, highlight: setting %s to %s" % (setting_name, _values[index]) )
settings.set(setting_name, _values[index])
view.set_status("preferences_editor", "Set %s" % (setting_file + '/' + setting_name))
show_quick_panel(view, options, done, highlight)
def widget_multiselect(self, option, value=None, validate=None, values=None):
# log( 8, "widget__multiselect, option: %s" % str(option) )
view = self.window.active_view()
setting_file = option[0]
setting_name = option[1]
settings = view.settings()
default = settings.get(setting_name, "")
if len( values ) > 0 and isinstance( values[0], str ):
_values = [ dict(caption=_value, value=_value) for _value in values ]
other = []
def do_add_option():
options = \
[
_value.get('caption', str(_value.get('value')))
for _value in _values if _value['value'] not in value
]
def done(index):
if index < 0:
settings.set( setting_name, default )
return self.shutdown()
value.append(other[index])
settings.set(setting_name, value)
do_show_panel()
show_quick_panel(view, options, done)
def do_remove_option():
options = \
[
_value.get('caption', str(_value.get('value')))
for _value in _values if _value['value'] in value
]
def done(index):
if index < 0:
settings.set( setting_name, default )
return self.shutdown()
value.remove(value[index])
settings.set(setting_name, value)
do_show_panel()
show_quick_panel(view, options, done)
def do_show_panel():
other[:] = [ _value['value'] for _value in _values if _value['value'] not in value ]
options = \
[
["Save Changes", json.dumps(value)],
["Add Option", "From: "+json.dumps(other)],
["Remove Option", "From:"+json.dumps(value)]
]
def done(index):
view.erase_status("preferences_editor")
if index < 0:
settings.set( setting_name, default )
return self.shutdown()
if index == 0:
self.set_setting_value(setting_file, setting_name, value)
sublime.status_message("Set %s to %s" % (setting_file + '/' + setting_name, str( value )))
self.preferences_selector()
if index == 1:
if len( other ) > 0:
do_add_option()
else:
sublime.status_message("No options available to add.")
do_show_panel()
if index == 2:
if len( value ) > 0:
do_remove_option()
else:
sublime.status_message("No options available to remove.")
do_show_panel()
view.set_status("preferences_editor", "Set %s" % (setting_file + '/' + setting_name))
show_quick_panel(view, options, done)
do_show_panel()
def widget_select_resource(self, option, value=None, validate=None, find_resources=""):
# log( 8, "widget__select_resource, option: %s" % str(option) )
resources = sorted(sublime.find_resources(find_resources))
setting_file = option[0]
setting_name = option[1]
view = self.window.active_view()
settings = self.view.settings()
options = []
default = settings.get(setting_name, "")
for resource in resources:
options.append( [ os.path.basename(resource), os.path.dirname(resource).replace("Packages/", "") ] )
options.insert( 0, ["Cancel Selection", "Go back to the settings menu"] )
resources.insert( 0, default )
def done(index):
view.erase_status("preferences_editor")
if index < 1:
settings.set( setting_name, default )
if index == 0:
self.preferences_selector()
else:
return self.shutdown()
self.set_setting_value(setting_file, setting_name, resources[index])
sublime.status_message("Set %s to %s" % (setting_file + '/' + setting_name, str( resources[index] )))
self.preferences_selector()
def highlight(index):
# log( 8, "widget__select_resource, highlight: setting %s to %s" % (setting_file, resources[index]) )
settings.set(setting_name, resources[index])
view.set_status("preferences_editor", "Set %s" % (setting_file + '/' + setting_name))
show_quick_panel(view, options, done, highlight)
def widget_input(self, option, value=None, validate=None):
setting_file = option[0]
setting_name = option[1]
view = self.view
view.set_status("preferences_editor", "Set %s" % (setting_file + '/' + setting_name))
settings = view.settings()
default = settings.get(setting_name, "")
def done(value):
view.erase_status("preferences_editor")
try:
value = validate(value)
self.set_setting_value(setting_file, setting_name, value)
sublime.status_message("Set %s to %s" % (setting_file + '/' + setting_name, str( value )))
except ValueError as e:
settings.set( setting_name, default )
sublime.error_message("Invalid Value: %s" % e)
self.preferences_selector()
def change(value):
try:
value = validate(value)
settings.set(setting_name, value)
# log( 8, "widget__input, change: set %s to %s" % (setting_name, value) )
except ValueError as e:
settings.set( setting_name, default )
sublime.status_message("Invalid Value: %s" % e)
def cancel():
settings.set( setting_name, default )
view.erase_status("preferences_editor")
self.preferences_selector()
view.set_status("preferences_editor", "Set %s" % (setting_file + '/' + setting_name))
show_input(self.view, setting_name, value, done, change, cancel)
def run_widget(self, option):
# log( 8, "run__widget, option: " + str( option ) )
setting_file = option[0]
setting_name = option[1]
# log( 8, "run__widget, setting_file: " + str( setting_file ) )
# log( 8, "run__widget, setting_name: " + str( setting_name ) )
defaultValueAndDescription = self.getDefaultValueAndDescription(setting_file, setting_name)
# log( 8, "run__widget, defaultValueAndDescription: " + str( defaultValueAndDescription ) )
settingMetadata = self.getSettingMetadata(setting_file, setting_name, defaultValueAndDescription)
# log( 8, "run__widget, settingMetadata: " + str( settingMetadata ) )
widget = settingMetadata.get('widget', 'input')
validate = settingMetadata.get('validate', 'str')
args = settingMetadata.get('args', {})
# log( 8, "run__widget, widget: " + str( widget ) )
# log( 8, "run__widget, validate: " + str( validate ) )
# log( 8, "run__widget, args: " + str( args ) )
userValueAndDescription = self.getUserValueAndDescription(setting_file, setting_name)
# log( 8, "run__widget, userValueAndDescription: " + str( userValueAndDescription ) )
if isinstance(validate, list):
validate_in_list = validate
def _validate_element(x):
if x in validate_in_list:
return x
else:
raise ValueError("Value must be one of %s" % validate_in_list)
validate = _validate_element
elif '.' not in validate:
validate = eval(validate)