-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings_editor.py
More file actions
1854 lines (1677 loc) · 78.5 KB
/
Copy pathsettings_editor.py
File metadata and controls
1854 lines (1677 loc) · 78.5 KB
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
"""Sublime Settings editor (v2) — Eclipse Property Sheet style.
Left pane: a directory-style tree of categories -> settings (folded by
default, expand on click). Right pane: an Eclipse-style Property|Value sheet
for the ONE selected setting, showing every dimension (name, type, enum,
default, effective [from the active view], owner, the full override chain
Default -> Platform -> Distraction Free -> User with the winner marked) and
every consequence (which keybindings/menus/plugin code read it, what breaks if
it changes). The editable Value row hosts a typed cell editor; a Write-to
dropdown picks the destination settings file (default = current source); a
Restore Default action reverts; the description/help area sits right under
Type/Default (moved up from the Eclipse-convention bottom placement: it's
often the only place a setting's valid-values vocabulary is documented, e.g.
font_options' "no_bold"/"gray_antialias"/... list, and burying it below seven
other panels meant it went unnoticed); and edit-time consequence warnings
surface inline and in a confirm dialog before the write. A Stop button kills
the server.
Architecture (see config/EDITOR_DESIGN.md):
- In-ST Python HTTP server + browser UI (port 57323).
- Defaults from Default/Preferences.sublime-settings + platform variant.
- Descriptions parsed from the // comment blocks in Default/Preferences.
- Effective value from the active view's merged settings (all layers).
- Override chain + owner from find_resources/decode_value.
- Reads from .sublime-keymap/.sublime-menu contexts + a loose-Packages .py grep.
- Writes byte-faithful via vendored json5 (ModelLoader positions) + position
surgery so comments, trailing commas, spacing and line endings on UNEDITED
lines are preserved. Writes generalize to any User/*.sublime-settings target.
"""
import os
import re
import sys
import json
import threading
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
# --- vendor json5 (pure-Python, bundled at config/lib/json5) -----------------
_HERE = os.path.dirname(os.path.abspath(__file__))
_LIB = os.path.join(_HERE, "lib")
if _LIB not in sys.path:
sys.path.insert(0, _LIB)
import json5 # noqa: E402
from json5.loader import loads as _j5loads, ModelLoader as _ModelLoader # noqa: E402
import sublime
import sublime_plugin # noqa: E402
_PORT = 57323 # was 57323; bumped to escape a zombie server left by an earlier
# reload (reload_plugin doesn't kill the old server thread, and the
# orphan held the port). Revert to 57323 after a clean ST restart.
_SERVER = [None]
_gen = [0]
_MISSING = object()
# --- known enum settings (curated; others get free-text) ---------------------
_ENUMS = {
"word_wrap": ["auto", "true", "false"],
"draw_white_space": ["none", "selection", "all"],
"draw_minimap_border": ["auto", "true", "false"],
"trim_trailing_white_space_on_save": ["none", "all", "modified"],
"ensure_newline_at_eof_on_save": ["auto", "true", "false"],
"default_line_ending": ["system", "unix", "windows"],
"caret_style": ["solid", "blink", "smooth", "phase", "wide"],
"fold_style": ["auto", "classic", "indent"],
"control_character_style": ["hex", "none", "name"],
"wrap_width_style": ["constant", "variable"],
"auto_complete_preserve_order": ["some", "none", "always"],
"show_definitions": ["auto", "true", "false"],
"highlight_line": ["none", "gutter", "line", "all"],
"tab_completion": ["true", "false", "insert"],
"shift_tab_unindent": ["auto", "true", "false"],
"drag_text": ["true", "false", "single"],
}
# Short curated descriptions used to fill gaps the comment parser misses.
_DESC_OVERLAY = {
"ignored_packages": "Packages disabled at startup (e.g. Vintage). Changing this needs a restart.",
"installed_packages": "Packages Package Control should keep installed.",
"folder_exclude_patterns": "Glob patterns of folders hidden from the sidebar and excluded from indexing.",
"file_exclude_patterns": "Glob patterns of files hidden from the sidebar and excluded from indexing.",
}
# --- categories --------------------------------------------------------------
_CATEGORY_ORDER = [
"Appearance & Theme", "Font", "Tabs & Indentation", "Wrapping & Lines",
"Whitespace", "Gutter & Rulers", "Sidebar & Minimap", "Tabs Bar & Menu",
"Find & Replace", "Auto-complete & Snippets", "Spell Check", "File & Save",
"Indexing & Goto", "Application Behavior", "Packages", "Behavior & Selection",
"Other",
]
_RULES = [
("Appearance & Theme", ["color_scheme", "theme", "mini_diff", "overlay_scroll_bars", "highlight_line", "line_numbers", "match_brackets"]),
("Font", ["font", "glyph_size"]),
("Tabs & Indentation", ["tab_size", "translate_tabs_to_spaces", "use_tab_stops", "detect_indentation", "auto_indent", "smart_indent", "indent_to_bracket", "trim_automatic_white_space", "indent_guide_options", "shift_tab_unindent", "use_nested_indent"]),
("Wrapping & Lines", ["word_wrap", "wrap_width", "line_padding", "default_line_ending", "ensure_newline_at_eof", "line_numbers"]),
("Whitespace", ["draw_white_space", "draw_white_space_selection", "trailing_white_space", "fade_fold_buttons", "draw_indent_guides", "draw_unloaded_tabs"]),
("Gutter & Rulers", ["gutter", "margin", "ruler", "fold_"]),
("Sidebar & Minimap", ["sidebar", "minimap", "tree_animation", "always_show_minimap_viewport", "show_open_files"]),
("Tabs Bar & Menu", ["show_tab_bar", "tab_bar", "hide_menu", "show_sidebar", "show_status_bar", "auto_hide_menu", "auto_hide_tabs", "remember_tab_switch"]),
("Find & Replace", ["find", "replace", "incremental", "auto_hide_find", "highlight_find_results"]),
("Auto-complete & Snippets", ["auto_complete", "snippet", "completion", "auto_close", "auto_match", "tab_completion"]),
("Spell Check", ["spell"]),
("File & Save", ["file", "save", "reload", "prompt_delete", "create_file", "open_files", "close_windows", "remember_open_files", "always_prompt_for_file_reload"]),
("Indexing & Goto", ["index", "goto", "preview_file", "reveal", "show_definitions", "gpu_indexing"]),
("Application Behavior", ["hot_exit", "remember_full_screen", "animation", "scroll_past", "gpu", "hardware_accel", "close_windows_when_empty"]),
("Packages", ["ignored_packages", "installed_packages", "package"]),
("Behavior & Selection", ["caret", "selection", "bracket", "match", "draw_minimap", "scroll", "mouse", "drag", "copy", "paste", "drag_text"]),
]
def _categorize(name):
nl = name.lower()
for cat, kws in _RULES:
for kw in kws:
if kw in nl:
return cat
return "Other"
# --- paths -------------------------------------------------------------------
def _user_dir():
return os.path.join(sublime.packages_path(), "User")
def _settings_path(rel):
return os.path.join(_user_dir(), rel.replace("/", os.sep))
def _platform_name():
p = sublime.platform()
return "Windows" if p == "windows" else ("OSX" if p == "osx" else "Linux")
def _line_ending(text):
if "\r\n" in text:
return "\r\n"
if "\n" in text:
return "\n"
return "\r\n" if sublime.platform() == "windows" else "\n"
# --- active view / syntax ----------------------------------------------------
def _active_view():
w = sublime.active_window()
return w.active_view() if w else None
def _active_syntax_name():
v = _active_view()
if not v:
return None
try:
syn = v.syntax()
return syn.name if syn else None
except Exception:
return None
# --- resource decode cache ---------------------------------------------------
_RES_CACHE = {}
def _res_decode(res):
if res not in _RES_CACHE:
try:
_RES_CACHE[res] = sublime.decode_value(sublime.load_resource(res))
except Exception:
_RES_CACHE[res] = None
return _RES_CACHE[res]
def _default_res(filename):
for r in sublime.find_resources(filename):
if r.startswith("Packages/Default/"):
return r
return None
def _load_defaults():
merged = {}
plat = _platform_name()
for fn in ("Preferences.sublime-settings", "Preferences (%s).sublime-settings" % plat):
r = _default_res(fn)
if r:
d = _res_decode(r)
if isinstance(d, dict):
merged.update(d)
return merged
_DESCRIPTIONS = None
def _parse_default_descriptions():
"""Parse // comment blocks in Default/Preferences.sublime-settings.
Each blank-line-delimited block: trailing 'key': value line owns the
preceding // comment lines as its description."""
global _DESCRIPTIONS
if _DESCRIPTIONS is not None:
return _DESCRIPTIONS
out = {}
r = _default_res("Preferences.sublime-settings")
if r:
try:
text = sublime.load_resource(r)
except Exception:
text = ""
for block in re.split(r"\n\s*\n", text):
comments = []
key = None
for ln in block.splitlines():
s = ln.strip()
if s.startswith("//"):
comments.append(s.lstrip("/").strip())
elif key is None and s and not s.startswith("/*") and not s.startswith("*"):
m = re.match(r'"([^"]+)"\s*:', s)
if m:
key = m.group(1)
if key:
txt = " ".join([c for c in comments if c]).strip()
if txt:
out[key] = txt
_DESCRIPTIONS = out
return out
def _desc_for(name):
d = _parse_default_descriptions().get(name)
if d:
return d
return _DESC_OVERLAY.get(name, "")
# --- user file values (User/Preferences) -------------------------------------
def _read_file(p):
if os.path.exists(p):
try:
with open(p, "r", encoding="utf-8", newline="") as f:
return f.read()
except Exception:
return "{}"
return "{}"
def _write_file(p, text):
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w", encoding="utf-8", newline="") as f:
f.write(text)
_gen[0] += 1
def _user_prefs_path():
return _settings_path("Preferences.sublime-settings")
def _user_values():
try:
d = json5.loads(_read_file(_user_prefs_path()))
return d if isinstance(d, dict) else {}
except Exception:
return {}
def _target_values(rel):
try:
d = json5.loads(_read_file(_settings_path(rel)))
return d if isinstance(d, dict) else {}
except Exception:
return {}
# --- types / effective -------------------------------------------------------
def _infer_type(name, value):
if name in _ENUMS and _ENUMS[name] is not None:
return "enum"
if isinstance(value, bool):
return "bool"
if isinstance(value, int):
return "int"
if isinstance(value, float):
return "float"
if isinstance(value, str):
return "string"
if isinstance(value, list):
return "array"
if isinstance(value, dict):
return "object"
return "string"
def _same_json(a, b):
try:
return json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True)
except Exception:
return a == b
# --- owner index -------------------------------------------------------------
_OWNER = None
def _owner_index():
global _OWNER
if _OWNER is not None:
return _OWNER
idx = {}
for res in sublime.find_resources("*.sublime-settings"):
try:
d = sublime.decode_value(sublime.load_resource(res))
except Exception:
d = None
if not isinstance(d, dict):
continue
parts = res.split("/")
pkg = parts[1] if len(parts) > 2 else "?"
for k in d.keys():
idx.setdefault(k, []).append({"res": res, "pkg": pkg})
_OWNER = idx
return idx
def _owner_for(name):
entries = _owner_index().get(name, [])
if not entries:
return "core (no resource declares it)"
pkgs = sorted(set(e["pkg"] for e in entries))
if pkgs == ["Default"]:
return "core"
nondefault = [p for p in pkgs if p != "Default"]
if nondefault:
return "package: " + ", ".join(nondefault)
return "core"
# --- override chain ----------------------------------------------------------
def _override_chain(name):
plat = _platform_name()
chain = []
layers = [
("Default", "Preferences.sublime-settings"),
("Platform (%s)" % plat, "Preferences (%s).sublime-settings" % plat),
("Distraction Free", "Preferences (Distraction Free).sublime-settings"),
]
for label, fn in layers:
r = _default_res(fn)
if r:
d = _res_decode(r)
if isinstance(d, dict) and name in d:
chain.append({"layer": label, "value": d[name], "source": "Default/" + fn})
uv = _user_values().get(name, _MISSING)
if uv is not _MISSING:
chain.append({"layer": "User", "value": uv, "source": "User/Preferences.sublime-settings"})
# mark winner (last wins)
for i, e in enumerate(chain):
e["wins"] = (i == len(chain) - 1)
return chain
# --- reads: keymap / menu / plugin code --------------------------------------
_KEYMAP_IDX = None
def _keymap_index():
global _KEYMAP_IDX
if _KEYMAP_IDX is not None:
return _KEYMAP_IDX
idx = {}
for res in sublime.find_resources("*.sublime-keymap"):
try:
d = sublime.decode_value(sublime.load_resource(res))
except Exception:
continue
if not isinstance(d, list):
continue
for entry in d:
if not isinstance(entry, dict):
continue
ctx = entry.get("context")
if not isinstance(ctx, list):
continue
for c in ctx:
if not isinstance(c, dict):
continue
k = c.get("key")
if isinstance(k, str) and k.startswith("setting."):
nm = k[len("setting."):]
idx.setdefault(nm, []).append({
"keys": entry.get("keys"),
"command": entry.get("command"),
"file": res,
"operator": c.get("operator"),
"operand": c.get("operand"),
})
_KEYMAP_IDX = idx
return idx
def _menu_reads(name):
hits = []
for res in sublime.find_resources("*.sublime-menu"):
try:
d = sublime.decode_value(sublime.load_resource(res))
except Exception:
continue
stack = [d]
while stack:
node = stack.pop()
if isinstance(node, list):
stack.extend(node)
elif isinstance(node, dict):
ctx = node.get("context")
if isinstance(ctx, list):
for c in ctx:
if isinstance(c, dict) and c.get("key") == "setting." + name:
hits.append({
"caption": node.get("caption"),
"command": node.get("command"),
"file": res,
"operator": c.get("operator"),
"operand": c.get("operand"),
})
for v in node.values():
if isinstance(v, (list, dict)):
stack.append(v)
return hits
_PY_CACHE = None
def _py_cache():
global _PY_CACHE
if _PY_CACHE is not None:
return _PY_CACHE
cache = {}
root = sublime.packages_path()
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if not d.startswith(".") and d != "__pycache__"]
for fn in filenames:
if not fn.endswith(".py"):
continue
p = os.path.join(dirpath, fn)
try:
sz = os.path.getsize(p)
except Exception:
continue
if sz > 200_000:
continue
try:
with open(p, "r", encoding="utf-8", errors="replace") as f:
cache[p] = f.read()
except Exception:
pass
_PY_CACHE = cache
return cache
def _py_reads(name):
cache = _py_cache()
pats = [
re.compile(r'\.get\(\s*["\']' + re.escape(name) + r'["\']'),
re.compile(r'\[\s*["\']' + re.escape(name) + r'["\']\s*\]'),
]
hits = []
for p, txt in cache.items():
for ln, line in enumerate(txt.splitlines(), 1):
for pat in pats:
if pat.search(line):
rel = os.path.relpath(p, sublime.packages_path()).replace("\\", "/")
hits.append({"file": rel, "line": ln, "snippet": line.strip()[:140]})
break
if len(hits) >= 60:
break
return hits
# --- consequence warnings ----------------------------------------------------
_SAVE_EFFECT = {
"trim_trailing_white_space_on_save": "files are rewritten on save (trailing whitespace stripped)",
"ensure_newline_at_eof_on_save": "files are rewritten on save (final newline added/ensured)",
"default_line_ending": "files are rewritten on save (line endings converted)",
}
def _warnings(name, new_value, usage):
w = []
kb = usage.get("keybindings") or []
if kb:
cmds = sorted(set((h.get("command") or "?") for h in kb))
w.append("Tested by %d keybinding(s); changing it may stop them matching: %s" % (len(kb), ", ".join(cmds[:8])))
if name == "ignored_packages" and isinstance(new_value, list):
w.append("Packages added/removed here are enabled/disabled at startup (needs restart); their commands/keybindings/menus change.")
if name in _SAVE_EFFECT and new_value and new_value != "none":
w.append("With this value, %s." % _SAVE_EFFECT[name])
if name == "index_files" and not new_value:
w.append("Disabling indexing degrades auto-complete, Goto Definition, and project-wide search.")
if name in _ENUMS and new_value not in _ENUMS[name]:
w.append("Value %r is not a recognized option (allowed: %s)." % (new_value, ", ".join(_ENUMS[name])))
return w
# --- comment-preserving write path (position-based text surgery) ------------
def _pos(text, lineno, col):
s = 0
for _ in range(lineno - 1):
s = text.index("\n", s) + 1
return s + col
def _kvp_map(text):
try:
m = _j5loads(text, loader=_ModelLoader())
if m and m.value and hasattr(m.value, "key_value_pairs"):
return {k.key.characters: k for k in m.value.key_value_pairs}
except Exception:
pass
return {}
def _indent_of(text):
kvps = _kvp_map(text)
if not kvps:
return " "
m = _j5loads(text, loader=_ModelLoader())
k0 = m.value.key_value_pairs[0]
ls = _pos(text, k0.key.lineno, 0)
return text[ls:_pos(text, k0.key.lineno, k0.key.col_offset)]
def _set_existing(text, name, value):
k = _kvp_map(text)[name].value
s = _pos(text, k.lineno, k.col_offset)
e = _pos(text, k.end_lineno, k.end_col_offset)
return text[:s] + json.dumps(value) + text[e:]
def _delete(text, name):
k = _kvp_map(text)[name]
line_start = _pos(text, k.key.lineno, 0)
val_end = _pos(text, k.value.end_lineno, k.value.end_col_offset)
ci = text.find(",", val_end)
nl_after = text.find("\n", val_end)
if ci != -1 and (nl_after == -1 or ci < nl_after):
# a trailing comma follows the value on the same line: drop through its
# newline so the whole key line disappears.
end_nl = text.find("\n", ci)
end = (end_nl + 1) if end_nl != -1 else (ci + 1)
else:
# last entry (no trailing comma): drop this whole line + its newline.
end = (nl_after + 1) if nl_after != -1 else len(text)
return text[:line_start] + text[end:]
def _add(text, name, value):
nl = _line_ending(text)
kvps = _kvp_map(text)
if not kvps:
return "{" + nl + _indent_of(text) + json.dumps(name) + ": " + json.dumps(value) + nl + "}"
m = _j5loads(text, loader=_ModelLoader())
last = m.value.key_value_pairs[-1].value
s = _pos(text, last.end_lineno, last.end_col_offset)
indent = _indent_of(text)
return text[:s] + "," + nl + indent + json.dumps(name) + ": " + json.dumps(value) + text[s:]
def _apply_set(name, value, target_rel):
p = _settings_path(target_rel)
text = _read_file(p)
if name in _kvp_map(text):
text = _set_existing(text, name, value)
else:
text = _add(text, name, value)
_write_file(p, text)
def _apply_delete(name, target_rel):
p = _settings_path(target_rel)
text = _read_file(p)
if name in _kvp_map(text):
text = _delete(text, name)
_write_file(p, text)
# --- scopes (multi-file browsing; QuickSettings-style) ----------------------
def _syntax_settings_rel():
syn = _active_syntax_name()
return (syn + ".sublime-settings") if syn else None
def _scope_list():
"""Browable settings files: global, Distraction Free, the active view's
syntax, and every per-package User/*.sublime-settings. Each carries its
User write target + the default-resource chain that supplies its baseline."""
out = []
plat = _platform_name()
out.append({
"id": "global", "label": "Preferences (global)",
"user_rel": "Preferences.sublime-settings",
"default_rels": [r for r in (
_default_res("Preferences.sublime-settings"),
_default_res("Preferences (%s).sublime-settings" % plat),
) if r],
})
df = _default_res("Preferences (Distraction Free).sublime-settings")
out.append({
"id": "df", "label": "Distraction Free",
"user_rel": "Preferences (Distraction Free).sublime-settings",
"default_rels": [df] if df else [],
})
syn_rel = _syntax_settings_rel()
if syn_rel:
def_rels = [r for r in sublime.find_resources(syn_rel)
if not r.startswith("Packages/User/")]
out.append({
"id": "syntax", "label": _active_syntax_name() + " (syntax)",
"user_rel": syn_rel, "default_rels": def_rels,
})
covered = {s["user_rel"] for s in out}
try:
for fn in sorted(os.listdir(_user_dir())):
if not fn.endswith(".sublime-settings") or fn in covered:
continue
pkg = fn[:-len(".sublime-settings")]
def_rels = [r for r in sublime.find_resources(fn)
if not r.startswith("Packages/User/")]
out.append({
"id": "pkg:" + pkg, "label": pkg,
"user_rel": fn, "default_rels": def_rels,
})
except Exception:
pass
for s in out:
s["exists"] = os.path.exists(_settings_path(s["user_rel"]))
return out
def _resolve_scope(scope_id):
scopes = _scope_list()
for s in scopes:
if s["id"] == scope_id:
return s
for s in scopes:
if s["id"] == "global":
return s
return scopes[0]
def _scope_defaults(scope):
if scope["id"] == "global":
return _load_defaults()
merged = {}
for r in scope["default_rels"]:
d = _res_decode(r)
if isinstance(d, dict):
merged.update(d)
return merged
def _scope_user_values(scope):
if scope["id"] == "global":
return _user_values()
try:
d = json5.loads(_read_file(_settings_path(scope["user_rel"])))
return d if isinstance(d, dict) else {}
except Exception:
return {}
def _effective_for(name, default_val, scope, user):
# Global + syntax settings are merged into the active view's settings, so
# the view is authoritative there. Per-package settings are not view-merged
# — fall back to the scope's user file, then the scope's default baseline.
if scope["id"] in ("global", "syntax"):
v = _active_view()
if v:
try:
val = v.settings().get(name, _MISSING)
if val is not _MISSING:
return val
except Exception:
pass
uv = user.get(name, _MISSING)
if uv is not _MISSING:
return uv
return default_val
def _override_chain_for(name, scope, user):
if scope["id"] == "global":
return _override_chain(name)
chain = []
for r in scope["default_rels"]:
d = _res_decode(r)
if isinstance(d, dict) and name in d:
chain.append({"layer": r.split("/")[-1], "value": d[name], "source": r})
uv = user.get(name, _MISSING)
if uv is not _MISSING:
chain.append({"layer": "User", "value": uv, "source": "User/" + scope["user_rel"]})
for i, e in enumerate(chain):
e["wins"] = (i == len(chain) - 1)
return chain
def _scope_write_targets(scope):
rels = [scope["user_rel"]]
# For global/DF/syntax scopes, Preferences and DF remain useful alternate
# write destinations. Per-package scopes write only to that package's file.
if scope["id"] in ("global", "df", "syntax"):
for r in ("Preferences.sublime-settings", "Preferences (Distraction Free).sublime-settings"):
if r not in rels:
rels.append(r)
return [{"rel": r, "label": r, "exists": os.path.exists(_settings_path(r))} for r in rels]
# --- catalog + detail --------------------------------------------------------
def _build_catalog(scope_id=None):
scope = _resolve_scope(scope_id)
defaults = _scope_defaults(scope)
user = _scope_user_values(scope)
kidx = _keymap_index()
names = sorted(set(defaults) | set(user))
out = []
for name in names:
dv = defaults.get(name, None)
eff = _effective_for(name, dv, scope, user)
overridden = not _same_json(eff, dv)
out.append({
"name": name,
"category": _categorize(name),
"type": _infer_type(name, eff),
"default": dv,
"effective": eff,
"overridden": overridden,
"enum": _ENUMS.get(name),
"has_usage": name in kidx,
})
cats = [c for c in _CATEGORY_ORDER if any(s["category"] == c for s in out)]
cats += sorted(set(s["category"] for s in out) - set(cats))
wt = _scope_write_targets(scope)
return {
"scope": scope["id"],
"scope_label": scope["label"],
"settings": out,
"categories": cats,
"write_targets": wt,
"current_source": scope["user_rel"],
"gen": _gen[0],
}
def _detail(name, scope_id=None):
scope = _resolve_scope(scope_id)
defaults = _scope_defaults(scope)
user = _scope_user_values(scope)
dv = defaults.get(name, None)
eff = _effective_for(name, dv, scope, user)
kidx = _keymap_index()
kb = kidx.get(name, [])
usage = {
"keybindings": kb,
"menus": _menu_reads(name),
"plugins": _py_reads(name),
}
wt = _scope_write_targets(scope)
return {
"name": name,
"category": _categorize(name),
"type": _infer_type(name, eff),
"default": dv,
"effective": eff,
"owner": _owner_for(name),
"override_chain": _override_chain_for(name, scope, user),
"enum": _ENUMS.get(name),
"desc": _desc_for(name),
"usage": usage,
"overridden": not _same_json(eff, dv),
"write_targets": wt,
"current_source": scope["user_rel"],
"gen": _gen[0],
}
# --- keybindings: runtime command registry -----------------------------------
_CMD = None
def _runtime_commands():
global _CMD
if _CMD is not None:
return _CMD
out = {}
for lst in (sublime_plugin.application_command_classes,
sublime_plugin.window_command_classes,
sublime_plugin.text_command_classes):
for c in lst or []:
try:
n = c.__new__(c).name()
except Exception:
continue
if isinstance(n, str) and n:
out[n] = (c.__module__ or "?") + "." + c.__name__
_CMD = out
return out
# Known commands = Python runtime classes + everything Default package binds
# (Default only references real commands, so this captures the C++ builtins
# that Python introspection cannot see — exit, new_window, copy, save, ...).
_DEFAULT_CMD = None
def _default_resource_commands():
global _DEFAULT_CMD
if _DEFAULT_CMD is not None:
return _DEFAULT_CMD
out = set()
res = (sublime.find_resources("*.sublime-keymap")
+ sublime.find_resources("*.sublime-menu")
+ sublime.find_resources("*.sublime-commands"))
for r in res:
if not r.startswith("Packages/Default/"):
continue
try:
d = sublime.decode_value(sublime.load_resource(r))
except Exception:
continue
stack = [d]
while stack:
n = stack.pop()
if isinstance(n, list):
stack.extend(n)
elif isinstance(n, dict):
c = n.get("command")
if isinstance(c, str):
out.add(c)
for v in n.values():
if isinstance(v, (list, dict)):
stack.append(v)
_DEFAULT_CMD = out
return out
def _known_commands():
return set(_runtime_commands().keys()) | _default_resource_commands()
# --- keybindings: catalog (merged Default + platform + User) ------------------
_KM = None
_KM_GEN = -1
def _km_real_path(res):
"""Packages/User/Foo.sublime-keymap -> fs path; package files -> None (RO)."""
parts = res.split("/")
if len(parts) >= 2 and parts[1] == "User":
return os.path.join(sublime.packages_path(), "User", *parts[2:])
return None
def _km_chord(keys):
if isinstance(keys, list):
return " ".join(str(k) for k in keys)
return str(keys) if keys else ""
def _keymap_catalog():
global _KM, _KM_GEN
if _KM is not None and _KM_GEN == _gen[0]:
return _KM
known = _known_commands()
recs = []
chord_idx = {}
for res in sublime.find_resources("*.sublime-keymap"):
try:
d = sublime.decode_value(sublime.load_resource(res))
except Exception:
continue
if not isinstance(d, list):
continue
is_user = res.startswith("Packages/User/")
pkg = res.split("/")[1] if len(res.split("/")) > 2 else "?"
for li, entry in enumerate(d):
if not isinstance(entry, dict):
continue
keys = entry.get("keys")
cmd = entry.get("command")
chord = _km_chord(keys)
rec = {
"idx": len(recs),
"local_index": li,
"source": res,
"pkg": pkg,
"is_user": is_user,
"writable": is_user,
"keys": keys,
"chord": chord,
"command": cmd,
"args": entry.get("args"),
"context": entry.get("context"),
"dead": isinstance(cmd, str) and cmd not in known,
}
recs.append(rec)
chord_idx.setdefault(chord, []).append(rec["idx"])
for r in recs:
group = chord_idx.get(r["chord"], [])
r["conflict_count"] = max(0, len(group) - 1)
_KM = {"bindings": recs, "write_targets": _km_write_targets(), "gen": _gen[0]}
_KM_GEN = _gen[0]
return _KM
def _keymap_binding(idx):
cat = _keymap_catalog()
recs = cat["bindings"]
if idx < 0 or idx >= len(recs):
return {"error": "no such binding"}
r = recs[idx]
cmds = _runtime_commands()
conflicts = []
for other in recs:
if other["idx"] == idx or other["chord"] != r["chord"] or not r["chord"]:
continue
conflicts.append({
"idx": other["idx"],
"keys": other["keys"],
"command": other["command"],
"context": other["context"],
"source": other["source"],
"is_user": other["is_user"],
})
return {
"idx": idx,
"keys": r["keys"],
"chord": r["chord"],
"command": r["command"],
"args": r["args"],
"context": r["context"],
"source": r["source"],
"is_user": r["is_user"],
"writable": r["writable"],
"dead": r["dead"],
"command_source": cmds.get(r["command"]) if isinstance(r["command"], str) else None,
"conflicts": conflicts,
"write_targets": _km_write_targets(),
"gen": _gen[0],
}
# --- keybindings: comment-preserving writes (array-of-objects) ---------------
def _km_model(text):
return _j5loads(text, loader=_ModelLoader())
def _km_entry_text(text, local_index):
m = _km_model(text)
el = m.value.values[local_index]
s = _pos(text, el.lineno, el.col_offset)
e = _pos(text, el.end_lineno, el.end_col_offset)
return el, m, s, e
def _km_indent_for(text, m):
vals = m.value.values
if not vals:
return "\t"
e0 = vals[0] # the element object; its col_offset is the '{' position
ls = _pos(text, e0.lineno, 0)
return text[ls:_pos(text, e0.lineno, e0.col_offset)]
def _km_set_entry(res, local_index, entry, expect_cmd):
p = _km_real_path(res)
if not p:
raise Exception("source is inside a package zip — not writable; add an override in User")
text = _read_file(p)
el, m, s, e = _km_entry_text(text, local_index)
kvp = {kp.key.characters: kp for kp in el.key_value_pairs}
if expect_cmd is not None:
cur = kvp.get("command")
cur_chars = cur.value.characters if cur and hasattr(cur.value, "characters") else None
if cur_chars != expect_cmd:
raise Exception("file changed since load — refresh and retry")
text = text[:s] + json.dumps(entry) + text[e:]
_write_file(p, text)
def _km_delete_entry(res, local_index, expect_cmd):
p = _km_real_path(res)
if not p:
raise Exception("source is inside a package zip — not writable")
text = _read_file(p)
el, m, s_line, _ = _km_entry_text(text, local_index)
kvp = {kp.key.characters: kp for kp in el.key_value_pairs}
if expect_cmd is not None:
cur = kvp.get("command")
cur_chars = cur.value.characters if cur and hasattr(cur.value, "characters") else None
if cur_chars != expect_cmd:
raise Exception("file changed since load — refresh and retry")
line_start = _pos(text, el.lineno, 0)