forked from evandroforks/SublimePackageDefault
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsettings.py
388 lines (306 loc) · 14.5 KB
/
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
import os.path
import tempfile
import sublime
import sublime_plugin
def status(message, *formatting):
print("Default Settings:", message, " ".join( str( item ) for item in formatting ) )
sublime.status_message(message)
class ResetViewSyntaxCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
window = view.window() or sublime.active_window()
if view.settings().get("is_widget"):
status("Cannot run 'reset_view_syntax' command on widgets!")
return
file_path = view.file_name()
if not file_path:
status("Cannot run 'reset_view_syntax' command on files without names!")
return
syntax = get_file_extension_syntax(window, file_path)
view.set_syntax_file(syntax)
class EditSettingsCommand(sublime_plugin.ApplicationCommand):
def run(self, base_file, user_file=None, default=None):
"""
:param base_file:
A unicode string of the path to the base settings file. Typically
this will be in the form: "${packages}/PackageName/Package.sublime-settings"
:param user_file:
An optional file path to the user's editable version of the settings
file. If not provided, the filename from base_file will be appended
to "${packages}/User/".
:param default:
An optional unicode string of the default contents if the user
version of the settings file does not yet exist. Use "$0" to place
the cursor.
"""
if base_file is None:
raise ValueError('No base_file argument was passed to edit_settings')
platform_name = {
'osx': 'OSX',
'windows': 'Windows',
'linux': 'Linux',
}[sublime.platform()]
variables = {
'packages': '${packages}',
'platform': platform_name,
}
base_file = sublime.expand_variables(base_file.replace('\\', '\\\\'), variables)
if user_file is not None:
user_file = sublime.expand_variables(user_file.replace('\\', '\\\\'), variables)
base_path = base_file.replace('${packages}', 'res://Packages')
is_resource = base_path.startswith('res://')
file_name = os.path.basename(base_file)
resource_exists = is_resource and base_path[6:] in sublime.find_resources(file_name)
filesystem_exists = (not is_resource) and os.path.exists(base_path)
if not resource_exists and not filesystem_exists:
sublime.error_message('The settings file "' + base_path + '" could not be opened')
return
if user_file is None:
user_package_path = os.path.join(sublime.packages_path(), 'User')
user_file = os.path.join(user_package_path, file_name)
# If the user path does not exist, and it is a supported
# platform-variant file path, then try and non-platform-variant
# file path.
if not os.path.exists(os.path.join(user_package_path, file_name)):
for suffix in {'.sublime-keymap', '.sublime-mousemap', '.sublime-menu'}:
platform_suffix = ' (%s)%s' % (platform_name, suffix)
if not file_name.endswith(platform_suffix):
continue
non_platform_file_name = file_name[:-len(platform_suffix)] + suffix
non_platform_path = os.path.join(user_package_path, non_platform_file_name)
if os.path.exists(non_platform_path):
user_file = non_platform_path
break
# If the user has previously opened the settings from the menu, locate and bring to front the respective window
windows = sublime.windows()
previous_settings_index = -1
view_to_focus = None
for window in windows:
user_view = window.find_open_file(user_file)
base_view = window.find_open_file(base_file.replace("${packages}", sublime.packages_path()))
if (window.num_groups() == 2 and
window.get_view_index(user_view) == (1, 0) and
window.get_view_index(base_view) == (0, 0)):
previous_settings_index = windows.index(window)
view_to_focus = user_view
break
if previous_settings_index > -1:
settings_window = windows[previous_settings_index]
settings_window.bring_to_front()
settings_window.focus_view(view_to_focus)
else:
sublime.run_command('new_window')
new_window = sublime.active_window()
self.window = new_window
# print('base_file ', base_file)
# print('base_file fixed', fix_base_file(base_file))
base_file = fix_base_file(base_file)
new_window.run_command(
'set_layout',
{
'cols': [0.0, 0.5, 1.0],
'rows': [0.0, 1.0],
'cells': [[0, 0, 1, 1], [1, 0, 2, 1]]
})
new_window.focus_group(0)
new_window.run_command('open_file', {'file': base_file})
new_window.focus_group(1)
new_window.run_command('open_file', {'file': user_file, 'contents': default})
new_window.set_tabs_visible(True)
new_window.set_sidebar_visible(False)
base_view = new_window.active_view_in_group(0)
user_view = new_window.active_view_in_group(1)
base_settings = base_view.settings()
base_settings.set('edit_settings_view', 'base')
base_settings.set('edit_settings_other_view_id', user_view.id())
user_settings = user_view.settings()
user_settings.set('edit_settings_view', 'user')
user_settings.set('edit_settings_other_view_id', base_view.id())
if not os.path.exists(user_file):
user_view.set_scratch(True)
user_settings.set('edit_settings_default', default.replace('$0', ''))
if base_file.endswith('.hide'):
syntax = get_file_extension_syntax(self.window, base_file.replace('.hide', ''))
base_view.set_syntax_file(syntax)
# https://forum.sublimetext.com/t/get-syntax-associated-with-file-extension/26348
# https://gist.github.com/mattst/71488757f2a2ca573c2d5e73af636d4c#file-getfileextensionsyntax-py
#
# Retrieve the path of the syntax that a user has
# associated with any file extension in Sublime Text.
#
# 1) Create a temp file with the file extension of the desired syntax.
# 2) Open the temp file in ST with the API `open_file()` method; use a
# sublime.TRANSIENT buffer so that no tab is shown on the tab bar.
# 3) Retrieve the syntax ST has assigned to the view's settings.
# 4) Close the temp file's ST buffer.
# 5) Delete the temp file.
#
# ST command of demo: get_file_extension_syntax
def get_file_extension_syntax(window, base_file):
filename, file_extension = os.path.splitext(base_file)
try:
tmp_base = "GetFileExtensionSyntaxTempFile"
tmp_file = tempfile.NamedTemporaryFile(prefix = tmp_base,
suffix = file_extension,
delete = False)
tmp_path = tmp_file.name
except Exception:
return None
finally:
tmp_file.close()
active_buffer = window.active_view()
# Using TRANSIENT prevents the creation of a tab bar tab.
tmp_buffer = window.open_file(tmp_path, sublime.TRANSIENT)
# Even if is_loading() is true the view's settings can be
# retrieved; settings assigned before open_file() returns.
syntax = tmp_buffer.settings().get("syntax", None)
window.run_command("close")
if active_buffer:
window.focus_view(active_buffer)
try:
os.remove(tmp_path)
# In the unlikely event of remove() failing: on Linux/OSX
# the OS will delete the contents of /tmp on boot or daily
# by default, on Windows the file will remain in the user
# temporary directory (amazingly never cleaned by default).
except Exception:
pass
return syntax
def fix_base_file(base_file):
base_file = os.path.normpath(base_file)
# print('base_file', base_file)
settings_files = \
[
"Default (Linux).sublime-mousemap",
"Default (Linux).sublime-keymap",
"Default (OSX).sublime-keymap",
"Default (OSX).sublime-mousemap",
"Default (Windows).sublime-mousemap",
"Default (Windows).sublime-keymap",
"Preferences (Linux).sublime-settings",
"Preferences (OSX).sublime-settings",
"Preferences (Windows).sublime-settings",
"Preferences.sublime-settings",
]
for file in settings_files:
base_path = os.path.join( 'Default', file )
base_path = os.path.normpath( base_path )
# print('base_path', base_path)
if base_path in base_file:
base_file = base_file.replace('.sublime-keymap', '.sublime-keymap.hide')
base_file = base_file.replace('.sublime-mousemap', '.sublime-mousemap.hide')
base_file = base_file.replace('.sublime-settings', '.sublime-settings.hide')
break
# Using os.path.join("Packages", __package__, "resource.name") on Windows causes OSError: resource not found
# https://github.com/SublimeTextIssues/Core/issues/2586
return base_file.replace('\\', '/')
class InsertSelectionMatchCommand(sublime_plugin.TextCommand):
def run(self, edit, start, end):
# import time; print( time.time(), 'start', start, 'end', end)
view = self.view
selections = view.sel()
for selection in selections:
first_char = sublime.Region( selection.begin() - 1, selection.begin())
first_char = view.substr(first_char)
last_char = sublime.Region( selection.end() + 1, selection.end())
last_char = view.substr(last_char)
# import time; print( time.time(), 'first_char', first_char, 'last_char', last_char )
if first_char == start and last_char == end:
view.insert( edit, selection.begin(), start )
view.insert( edit, selection.end() + 1, end )
elif first_char != start and last_char != end:
view.insert( edit, selection.begin(), start )
view.insert( edit, selection.end() + 1, end )
elif first_char != start:
view.insert( edit, selection.begin(), start )
else:
view.insert( edit, selection.end(), end )
class EditSyntaxSettingsCommand(sublime_plugin.WindowCommand):
"""
Opens the syntax-specific settings file for the currently active view
"""
def run(self):
view = self.window.active_view()
syntax, _ = os.path.splitext(os.path.basename(view.settings().get('syntax')))
self.window.run_command(
'edit_settings',
{
'base_file': '${packages}/Default/Preferences.sublime-settings',
'user_file': os.path.join(sublime.packages_path(), 'User', syntax + '.sublime-settings'),
'default': (
'// These settings override both User and Default settings '
'for the %s syntax\n{\n\t$0\n}\n') % syntax
})
def is_enabled(self):
return self.window.active_view() is not None
class EditSettingsListener(sublime_plugin.ViewEventListener):
"""
Closes the base and user settings files together, and then closes the
window if no other views are opened
"""
@classmethod
def is_applicable(cls, settings):
return settings.get('edit_settings_view') is not None
def on_modified(self):
"""
Prevents users from editing the base file
"""
view_settings = self.view.settings()
# If any edits are made to the user version, we unmark it as a
# scratch view so that the user is prompted to save any changes
if view_settings.get('edit_settings_view') == 'user' and self.view.is_scratch():
file_region = sublime.Region(0, self.view.size())
if view_settings.get('edit_settings_default') != self.view.substr(file_region):
self.view.set_scratch(False)
def on_pre_close(self):
"""
Grabs the window id before the view is actually removed
"""
if self.view.window() is None:
return
self.view.settings().set('window_id', self.view.window().id())
def on_close(self):
"""
Closes the other settings view when one of the two is closed
"""
view_settings = self.view.settings()
window_id = view_settings.get('window_id')
window = None
for win in sublime.windows():
if win.id() == window_id:
window = win
break
if not window:
return
other_view_id = view_settings.get('edit_settings_other_view_id')
views = window.views()
views_left = len(views)
for other in views:
if other.id() == other_view_id:
window.focus_view(other)
# Prevent the handler from running on the other view
other.settings().erase('edit_settings_view')
# Run after timeout so the UI doesn't block with the view half closed
sublime.set_timeout(lambda: window.run_command("close"), 50)
# Don't close the window if the user opens another view in the window
# or adds a folder, since they likely didn't realize this is a settings
# window
if views_left == 1 and len(window.folders()) < 1:
# If the user closes the window containing the settings views, and
# this is not delayed, the close_window command will be run on any
# other window that is open.
def close_window():
if window.id() == sublime.active_window().id():
window.run_command("close_window")
sublime.set_timeout(close_window, 50)
class OpenFileSettingsCommand(sublime_plugin.WindowCommand):
"""
Old syntax-specific settings command - preserved for backwards compatibility
"""
def run(self):
view = self.window.active_view()
settings_name, _ = os.path.splitext(os.path.basename(view.settings().get('syntax')))
dir_name = os.path.join(sublime.packages_path(), 'User')
self.window.open_file(os.path.join(dir_name, settings_name + '.sublime-settings'))
def is_enabled(self):
return self.window.active_view() is not None