This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
index.js
494 lines (416 loc) · 13.4 KB
/
index.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
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
'use strict';
const {CompositeDisposable, Disposable} = require('atom');
// Lazy-loaded modules
let checklist;
let editorconfig;
let fixFile;
let generateConfig;
let showState;
let statusTile;
let wrapGuideInterceptor;
let lint;
lint = require('./lib/lint.js');
function provideLinter() { // eslint-disable-line no-unused-vars
// Auto-magically called by the package linter, see package.json -> "providedServices.linter"
if (!lint) {
lint = require('./lib/lint.js');
}
return lint.provideLinter();
}
// Sets the state of the embedded editorconfig
// This includes the severity (info, warning..) as well as the notification-messages for users
function setState(ecfg) {
if (!checklist) {
checklist = require('./lib/checklist.js');
}
checklist(ecfg);
if (!statusTile) {
statusTile = require('./lib/statustile-view.js');
}
statusTile.updateIcon(ecfg.state);
}
// Initializes the (into the TextBuffer-instance) embedded editorconfig-object
function initializeTextBuffer(buffer) {
if ('editorconfig' in buffer === false) {
buffer.editorconfig = {
buffer, // Preserving a reference to the parent `TextBuffer`
disposables: new CompositeDisposable(),
lastEncoding: buffer.getEncoding(),
originallyCRLF: buffer.lineEndingForRow(0) === '\r\n',
state: 'subtle',
settings: {
trim_trailing_whitespace: 'unset',
insert_final_newline: 'unset',
max_line_length: 'unset',
end_of_line: 'unset',
indent_style: 'unset',
tab_width: 'unset',
charset: 'unset'
},
// Get the current Editor for this.buffer
getCurrentEditor() {
return atom.workspace.getTextEditors().reduce((previous, current) => {
return (current.getBuffer() === this.buffer && current) || previous;
}, undefined);
},
// Applies the settings to the buffer and the corresponding editor
applySettings() {
const editor = this.getCurrentEditor();
if (!editor) {
return;
}
const configOptions = {scope: editor.getRootScopeDescriptor()};
const {settings} = this;
if (editor && editor.getBuffer() === buffer) {
if (settings.indent_style === 'unset') {
const usesSoftTabs = editor.usesSoftTabs();
if (usesSoftTabs === undefined) {
editor.setSoftTabs(atom.config.get('editor.softTabs', configOptions));
} else {
editor.setSoftTabs(usesSoftTabs);
}
} else {
editor.setSoftTabs(settings.indent_style === 'space');
}
if (settings.tab_width === 'unset') {
editor.setTabLength(atom.config.get('editor.tabLength', configOptions));
} else {
editor.setTabLength(settings.tab_width);
}
if (settings.charset === 'unset') {
buffer.setEncoding(atom.config.get('core.fileEncoding', configOptions));
} else if (settings.charset === 'utf8bom') {
buffer.setEncoding('utf8');
} else {
buffer.setEncoding(settings.charset);
}
// Max_line_length-settings
const editorParameters = {};
if (settings.max_line_length === 'unset') {
editorParameters.preferredLineLength =
atom.config.get('editor.preferredLineLength', configOptions);
} else {
editorParameters.preferredLineLength = settings.max_line_length;
}
// Update the editor-properties
editor.update(editorParameters);
// Ensure the wrap-guide is being intercepted
const bufferDom = atom.views.getView(editor);
const wrapGuide = bufferDom.querySelector('.wrap-guide');
if (wrapGuide !== null) {
if (wrapGuide.editorconfig === undefined) {
if (!wrapGuideInterceptor) {
wrapGuideInterceptor = require('./lib/wrapguide-interceptor.js');
}
wrapGuide.editorconfig = this;
wrapGuide.getNativeGuideColumn = wrapGuide.getGuideColumn;
wrapGuide.getGuideColumn = wrapGuideInterceptor.getGuideColumn.bind(wrapGuide);
wrapGuide.getNativeGuidesColumns = wrapGuide.getGuidesColumns;
wrapGuide.getGuidesColumns = wrapGuideInterceptor.getGuidesColumns.bind(wrapGuide);
}
if (typeof wrapGuide.updateGuide === 'function') {
wrapGuide.updateGuide();
} else {
// NB: This won't work with multiple wrap-guides
const columnWidth = bufferDom.getDefaultCharacterWidth() * editorParameters.preferredLineLength;
if (columnWidth > 0) {
wrapGuide.style.left = Math.round(columnWidth) + 'px';
wrapGuide.style.display = 'block';
} else {
wrapGuide.style.display = 'none';
}
}
}
if (settings.end_of_line !== 'unset') {
buffer.setPreferredLineEnding(settings.end_of_line);
}
}
setState(this);
},
// Inserts or removes a leading byte-order mark
setBOM(enabled) {
const hasBOM = buffer.getText().codePointAt(0) === 0xFEFF;
if (enabled && !hasBOM) {
buffer.setTextInRange([[0, 0], [0, 0]], '\uFEFF');
} else if (!enabled && hasBOM) {
buffer.delete([[0, 0], [0, 1]]);
}
},
// Add or remove byte-order mark depending on UTF-8 type
updateBOM() {
const {settings} = this;
if (settings.charset === 'utf8bom') {
this.setBOM(true);
} else if (settings.charset === 'utf8') {
this.setBOM(false);
}
},
// `onDidChangeEncoding` event handler
// Used to insert/strip byte-order marks in UTF-8 encoded files
onDidChangeEncoding(encoding) {
if (encoding === 'utf8') {
this.updateBOM();
} else if (this.lastEncoding === 'utf8') {
this.setBOM(false);
}
this.lastEncoding = encoding;
},
// `onWillSave` event handler
// Trims whitespaces and inserts/strips final newline before saving
onWillSave() {
const {settings} = this;
if (buffer.getEncoding() === 'utf8') {
this.updateBOM();
}
if (settings.end_of_line === '\r') {
let text = buffer.getText();
if (this.originallyCRLF) {
text = text.replace(/\r\n/g, '\r');
}
text = text.replace(/\n/g, '\r');
// NB: Atom doesn't handle CR endings well when scanning/counting lines.
// So we handle whitespace trimming the messier and less efficient way.
if (settings.trim_trailing_whitespace === true) {
text = text.replace(/[ \t]+$/gm, '');
}
if (settings.insert_final_newline !== 'unset') {
text = text.replace(/(?:\r[ \t]*)+$/, '');
if (settings.insert_final_newline === true) {
text += '\r';
}
}
buffer.setText(text);
} else {
if (settings.end_of_line === '\r\n') {
buffer.backwardsScan(/([^\r]|^)\n|\r(?!\n)/g, parameters => {
const {match} = parameters;
if (match && match[0].length > 0) {
parameters.replace((match[1] || '') + '\r\n');
}
});
} else if (settings.end_of_line === '\n') {
buffer.backwardsScan(/\r\n|\r([^\n]|$)/g, parameters => {
const {match} = parameters;
if (match && match[0].length > 0) {
parameters.replace('\n' + ([match[1]] || ''));
}
});
}
if (settings.trim_trailing_whitespace === true) {
buffer.backwardsScan(/[ \t]+$/gm, parameters => {
if (parameters.match[0].length > 0) {
parameters.replace('');
}
});
}
if (settings.insert_final_newline !== 'unset' && !buffer.isEmpty()) {
const lastRow = buffer.getLineCount() - 1;
if (buffer.isRowBlank(lastRow)) {
let stripStart = buffer.previousNonBlankRow(lastRow);
if (settings.insert_final_newline === true) {
stripStart += 1;
}
// Strip empty lines from the end
if (stripStart < lastRow) {
buffer.deleteRows(stripStart + 1, lastRow);
}
} else if (settings.insert_final_newline === true) {
buffer.append('\n');
}
}
}
}
};
buffer.editorconfig.disposables.add(
buffer.onWillSave(buffer.editorconfig.onWillSave.bind(buffer.editorconfig)),
buffer.onDidChangeEncoding(buffer.editorconfig.onDidChangeEncoding.bind(buffer.editorconfig)),
buffer.onDidDestroy(() => buffer.editorconfig.disposables.dispose()),
new Disposable(() => delete buffer.editorconfig)
);
if (buffer.getUri() && buffer.getUri().match(/[\\|/]\.editorconfig$/g) !== null) {
buffer.editorconfig.disposables.add(
buffer.onDidSave(reapplyEditorconfig)
);
}
}
}
// Reveal and apply the editorconfig for the given TextEditor-instance
function observeTextEditor(editor) {
if (!editor) {
return;
}
initializeTextBuffer(editor.getBuffer());
const file = editor.getURI();
if (!file) {
editor.onDidSave(() => {
observeTextEditor(editor);
});
return;
}
if (!editorconfig) {
editorconfig = require('editorconfig');
}
editorconfig.parse(file).then(config => {
if (Object.keys(config).length === 0) {
return;
}
const ecfg = editor.getBuffer().editorconfig;
const {settings} = ecfg;
const lineEndings = {
crlf: '\r\n',
cr: '\r',
lf: '\n'
};
// Preserve evaluated Editorconfig
ecfg.config = config;
// Carefully normalize and initialize config-settings
settings.trim_trailing_whitespace = ('trim_trailing_whitespace' in config) &&
typeof config.trim_trailing_whitespace === 'boolean' ?
config.trim_trailing_whitespace === true :
'unset';
settings.insert_final_newline = ('insert_final_newline' in config) &&
typeof config.insert_final_newline === 'boolean' ?
config.insert_final_newline === true :
'unset';
settings.indent_style = (('indent_style' in config) &&
config.indent_style.search(/^(space|tab)$/) > -1) ?
config.indent_style :
'unset';
settings.end_of_line = lineEndings[config.end_of_line] || 'unset';
settings.tab_width = parseInt(config.indent_size || config.tab_width, 10);
if (isNaN(settings.tab_width) || settings.tab_width <= 0) {
settings.tab_width = 'unset';
}
settings.max_line_length = parseInt(config.max_line_length, 10);
if (isNaN(settings.max_line_length) || settings.max_line_length <= 0) {
settings.max_line_length = 'unset';
}
settings.charset = ('charset' in config) ?
config.charset.replace(/-|_/g, '').toLowerCase() :
'unset';
switch (String(settings.charset).toLowerCase().replace(/\W/g, '')) {
case 'latin1': {
// #227: Allow `latin1` as an alias of ISO 8859-1.
settings.charset = 'iso88591';
break;
}
case 'sjis': {
settings.charset = 'shiftjis';
break;
}
default:
}
ecfg.applySettings();
}).catch(error => {
console.warn(`atom-editorconfig: ${error}`);
});
}
// Reapplies the whole editorconfig to **all** open TextEditor-instances
function reapplyEditorconfig() {
const textEditors = atom.workspace.getTextEditors();
textEditors.forEach(editor => {
observeTextEditor(editor);
});
}
// Reapplies the settings immediately after changing the focus to a new pane
function observeActivePaneItem(editor) {
if (editor && editor.constructor.name === 'TextEditor') {
if (editor.buffer && editor.buffer.editorconfig) {
editor.buffer.editorconfig.applySettings();
}
} else {
if (!statusTile) {
statusTile = require('./lib/statustile-view.js');
}
statusTile.removeIcon();
}
}
module.exports = {
disposables: null,
// Activate package and register commands and event listeners
activate() {
if (Disposable.isDisposable(this.disposables)) {
this.disposables.dispose();
}
this.disposables = new CompositeDisposable(
atom.commands.add('atom-workspace', {
'EditorConfig:fix-file': () => {
if (!fixFile) {
fixFile = require('./commands/fix-file.js');
}
return fixFile();
},
'EditorConfig:fix-file-quietly': () => {
if (!fixFile) {
fixFile = require('./commands/fix-file.js');
}
return fixFile(false);
},
'EditorConfig:generate-config': () => {
if (!generateConfig) {
generateConfig = require('./commands/generate-config.js');
}
return generateConfig();
},
'EditorConfig:show-state': () => {
if (!showState) {
showState = require('./commands/show-state.js');
}
return showState();
}
}),
atom.workspace.observeTextEditors(observeTextEditor),
atom.workspace.observeActivePaneItem(observeActivePaneItem),
new Disposable(() => {
// Remove all embedded editorconfig-objects
const textEditors = atom.workspace.getTextEditors();
textEditors.forEach(ed => ed.getBuffer().editorconfig.disposables.dispose());
if (!statusTile) {
statusTile = require('./lib/statustile-view.js');
}
// Clean the status-bar up
statusTile.removeIcon();
})
);
reapplyEditorconfig();
// #220: Fix spurious "thrashing" in open editors at startup
if (!atom.packages.hasActivatedInitialPackages()) {
const disposables = new CompositeDisposable();
disposables.add(
atom.packages.onDidActivatePackage(currentPackage => {
if (currentPackage.name === 'whitespace' || currentPackage.name === 'wrap-guide') {
reapplyEditorconfig();
}
}),
atom.packages.onDidActivateInitialPackages(() => {
disposables.dispose();
reapplyEditorconfig();
})
);
}
},
deactivate() {
if (Disposable.isDisposable(this.disposables)) {
this.disposables.dispose();
this.disposables = null;
}
},
provideLinter() {
if (!lint) {
lint = require('./lib/lint.js');
}
return lint.provideLinter();
},
// Apply the statusbar icon-container. The icon will be applied if needed
consumeStatusBar(statusBar) {
if (!statusTile) {
statusTile = require('./lib/statustile-view.js');
}
if (statusTile.containerExists() === false) {
statusBar.addRightTile({
item: statusTile.createContainer(),
priority: 999
});
}
}
};