-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
text-editor-registry.js
348 lines (309 loc) · 11.2 KB
/
text-editor-registry.js
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
const _ = require('underscore-plus');
const { Emitter, Disposable, CompositeDisposable } = require('event-kit');
const TextEditor = require('./text-editor');
const ScopeDescriptor = require('./scope-descriptor');
const EDITOR_PARAMS_BY_SETTING_KEY = [
['core.fileEncoding', 'encoding'],
['editor.atomicSoftTabs', 'atomicSoftTabs'],
['editor.showInvisibles', 'showInvisibles'],
['editor.tabLength', 'tabLength'],
['editor.invisibles', 'invisibles'],
['editor.showCursorOnSelection', 'showCursorOnSelection'],
['editor.showIndentGuide', 'showIndentGuide'],
['editor.showLineNumbers', 'showLineNumbers'],
['editor.softWrap', 'softWrapped'],
['editor.softWrapHangingIndent', 'softWrapHangingIndentLength'],
['editor.softWrapAtPreferredLineLength', 'softWrapAtPreferredLineLength'],
['editor.preferredLineLength', 'preferredLineLength'],
['editor.maxScreenLineLength', 'maxScreenLineLength'],
['editor.autoIndent', 'autoIndent'],
['editor.autoIndentOnPaste', 'autoIndentOnPaste'],
['editor.scrollPastEnd', 'scrollPastEnd'],
['editor.undoGroupingInterval', 'undoGroupingInterval'],
['editor.scrollSensitivity', 'scrollSensitivity']
];
// Experimental: This global registry tracks registered `TextEditors`.
//
// If you want to add functionality to a wider set of text editors than just
// those appearing within workspace panes, use `atom.textEditors.observe` to
// invoke a callback for all current and future registered text editors.
//
// If you want packages to be able to add functionality to your non-pane text
// editors (such as a search field in a custom user interface element), register
// them for observation via `atom.textEditors.add`. **Important:** When you're
// done using your editor, be sure to call `dispose` on the returned disposable
// to avoid leaking editors.
module.exports = class TextEditorRegistry {
constructor({ config, assert, packageManager }) {
this.config = config;
this.assert = assert;
this.packageManager = packageManager;
this.clear();
}
deserialize(state) {
this.editorGrammarOverrides = state.editorGrammarOverrides;
}
serialize() {
return {
editorGrammarOverrides: Object.assign({}, this.editorGrammarOverrides)
};
}
clear() {
if (this.subscriptions) {
this.subscriptions.dispose();
}
this.subscriptions = new CompositeDisposable();
this.editors = new Set();
this.emitter = new Emitter();
this.scopesWithConfigSubscriptions = new Set();
this.editorsWithMaintainedConfig = new Set();
this.editorsWithMaintainedGrammar = new Set();
this.editorGrammarOverrides = {};
this.editorGrammarScores = new WeakMap();
}
destroy() {
this.subscriptions.dispose();
this.editorsWithMaintainedConfig = null;
}
// Register a `TextEditor`.
//
// * `editor` The editor to register.
//
// Returns a {Disposable} on which `.dispose()` can be called to remove the
// added editor. To avoid any memory leaks this should be called when the
// editor is destroyed.
add(editor) {
this.editors.add(editor);
editor.registered = true;
this.emitter.emit('did-add-editor', editor);
return new Disposable(() => this.remove(editor));
}
build(params) {
params = Object.assign({ assert: this.assert }, params);
let scope = null;
if (params.buffer) {
const { grammar } = params.buffer.getLanguageMode();
if (grammar) {
scope = new ScopeDescriptor({ scopes: [grammar.scopeName] });
}
}
Object.assign(params, this.textEditorParamsForScope(scope));
return new TextEditor(params);
}
// Remove a `TextEditor`.
//
// * `editor` The editor to remove.
//
// Returns a {Boolean} indicating whether the editor was successfully removed.
remove(editor) {
const removed = this.editors.delete(editor);
editor.registered = false;
return removed;
}
// Gets the currently active text editor.
//
// Returns the currently active text editor, or `null` if there is none.
getActiveTextEditor() {
for (let ed of this.editors) {
// fast path, works as long as there's a shadow DOM inside the text editor
if (ed.getElement() === document.activeElement) {
return ed;
} else {
let editorElement = ed.getElement();
let current = document.activeElement;
while (current) {
if (current === editorElement) {
return ed;
}
current = current.parentNode;
}
}
}
return null;
}
// Invoke the given callback with all the current and future registered
// `TextEditors`.
//
// * `callback` {Function} to be called with current and future text editors.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observe(callback) {
this.editors.forEach(callback);
return this.emitter.on('did-add-editor', callback);
}
// Keep a {TextEditor}'s configuration in sync with Atom's settings.
//
// * `editor` The editor whose configuration will be maintained.
//
// Returns a {Disposable} that can be used to stop updating the editor's
// configuration.
maintainConfig(editor) {
if (this.editorsWithMaintainedConfig.has(editor)) {
return new Disposable(noop);
}
this.editorsWithMaintainedConfig.add(editor);
this.updateAndMonitorEditorSettings(editor);
const languageChangeSubscription = editor.buffer.onDidChangeLanguageMode(
(newLanguageMode, oldLanguageMode) => {
this.updateAndMonitorEditorSettings(editor, oldLanguageMode);
}
);
this.subscriptions.add(languageChangeSubscription);
const updateTabTypes = () => {
const configOptions = { scope: editor.getRootScopeDescriptor() };
editor.setSoftTabs(
shouldEditorUseSoftTabs(
editor,
this.config.get('editor.tabType', configOptions),
this.config.get('editor.softTabs', configOptions)
)
);
};
updateTabTypes();
const tokenizeSubscription = editor.onDidTokenize(updateTabTypes);
this.subscriptions.add(tokenizeSubscription);
return new Disposable(() => {
this.editorsWithMaintainedConfig.delete(editor);
tokenizeSubscription.dispose();
languageChangeSubscription.dispose();
this.subscriptions.remove(languageChangeSubscription);
this.subscriptions.remove(tokenizeSubscription);
});
}
// Deprecated: set a {TextEditor}'s grammar based on its path and content,
// and continue to update its grammar as grammars are added or updated, or
// the editor's file path changes.
//
// * `editor` The editor whose grammar will be maintained.
//
// Returns a {Disposable} that can be used to stop updating the editor's
// grammar.
maintainGrammar(editor) {
atom.grammars.maintainLanguageMode(editor.getBuffer());
}
// Deprecated: Force a {TextEditor} to use a different grammar than the
// one that would otherwise be selected for it.
//
// * `editor` The editor whose gramamr will be set.
// * `languageId` The {String} language ID for the desired {Grammar}.
setGrammarOverride(editor, languageId) {
atom.grammars.assignLanguageMode(editor.getBuffer(), languageId);
}
// Deprecated: Retrieve the grammar scope name that has been set as a
// grammar override for the given {TextEditor}.
//
// * `editor` The editor.
//
// Returns a {String} scope name, or `null` if no override has been set
// for the given editor.
getGrammarOverride(editor) {
return atom.grammars.getAssignedLanguageId(editor.getBuffer());
}
// Deprecated: Remove any grammar override that has been set for the given {TextEditor}.
//
// * `editor` The editor.
clearGrammarOverride(editor) {
atom.grammars.autoAssignLanguageMode(editor.getBuffer());
}
async updateAndMonitorEditorSettings(editor, oldLanguageMode) {
await this.packageManager.getActivatePromise();
this.updateEditorSettingsForLanguageMode(editor, oldLanguageMode);
this.subscribeToSettingsForEditorScope(editor);
}
updateEditorSettingsForLanguageMode(editor, oldLanguageMode) {
const newLanguageMode = editor.buffer.getLanguageMode();
if (oldLanguageMode) {
const newSettings = this.textEditorParamsForScope(
newLanguageMode.rootScopeDescriptor
);
const oldSettings = this.textEditorParamsForScope(
oldLanguageMode.rootScopeDescriptor
);
const updatedSettings = {};
for (const [, paramName] of EDITOR_PARAMS_BY_SETTING_KEY) {
// Update the setting only if it has changed between the two language
// modes. This prevents user-modified settings in an editor (like
// 'softWrapped') from being reset when the language mode changes.
if (!_.isEqual(newSettings[paramName], oldSettings[paramName])) {
updatedSettings[paramName] = newSettings[paramName];
}
}
if (_.size(updatedSettings) > 0) {
editor.update(updatedSettings);
}
} else {
editor.update(
this.textEditorParamsForScope(newLanguageMode.rootScopeDescriptor)
);
}
}
subscribeToSettingsForEditorScope(editor) {
if (!this.editorsWithMaintainedConfig) return;
const scopeDescriptor = editor.getRootScopeDescriptor();
const scopeChain = scopeDescriptor.getScopeChain();
if (!this.scopesWithConfigSubscriptions.has(scopeChain)) {
this.scopesWithConfigSubscriptions.add(scopeChain);
const configOptions = { scope: scopeDescriptor };
for (const [settingKey, paramName] of EDITOR_PARAMS_BY_SETTING_KEY) {
this.subscriptions.add(
this.config.onDidChange(settingKey, configOptions, ({ newValue }) => {
this.editorsWithMaintainedConfig.forEach(editor => {
if (editor.getRootScopeDescriptor().isEqual(scopeDescriptor)) {
editor.update({ [paramName]: newValue });
}
});
})
);
}
const updateTabTypes = () => {
const tabType = this.config.get('editor.tabType', configOptions);
const softTabs = this.config.get('editor.softTabs', configOptions);
this.editorsWithMaintainedConfig.forEach(editor => {
if (editor.getRootScopeDescriptor().isEqual(scopeDescriptor)) {
editor.setSoftTabs(
shouldEditorUseSoftTabs(editor, tabType, softTabs)
);
}
});
};
this.subscriptions.add(
this.config.onDidChange(
'editor.tabType',
configOptions,
updateTabTypes
),
this.config.onDidChange(
'editor.softTabs',
configOptions,
updateTabTypes
)
);
}
}
textEditorParamsForScope(scopeDescriptor) {
const result = {};
const configOptions = { scope: scopeDescriptor };
for (const [settingKey, paramName] of EDITOR_PARAMS_BY_SETTING_KEY) {
result[paramName] = this.config.get(settingKey, configOptions);
}
return result;
}
};
function shouldEditorUseSoftTabs(editor, tabType, softTabs) {
switch (tabType) {
case 'hard':
return false;
case 'soft':
return true;
case 'auto':
switch (editor.usesSoftTabs()) {
case true:
return true;
case false:
return false;
default:
return softTabs;
}
}
}
function noop() {}