forked from microsoft/vscode-editorconfig
-
Notifications
You must be signed in to change notification settings - Fork 117
/
DocumentWatcher.ts
225 lines (193 loc) · 5.69 KB
/
DocumentWatcher.ts
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
import * as editorconfig from 'editorconfig';
import * as compact from 'lodash.compact';
import * as get from 'lodash.get';
import * as path from 'path';
import {
window,
workspace,
Disposable,
Selection,
TextDocument,
TextEditor,
TextEditorOptions,
TextEdit,
TextDocumentSaveReason
} from 'vscode';
import languageExtensionMap from './languageExtensionMap';
import { fromEditorConfig } from './Utils';
import {
InsertFinalNewline,
PreSaveTransformation,
SetEndOfLine,
TrimTrailingWhitespace
} from './transformations';
import {
EditorConfigProvider
} from './interfaces/editorConfigProvider';
class DocumentWatcher implements EditorConfigProvider {
private docToConfigMap: { [fileName: string]: editorconfig.KnownProps };
private disposable: Disposable;
private defaults: TextEditorOptions;
private preSaveTransformations: PreSaveTransformation[] = [
new SetEndOfLine(),
new TrimTrailingWhitespace(),
new InsertFinalNewline()
];
constructor(
private outputChannel = window.createOutputChannel('EditorConfig')
) {
this.log('Initializing document watcher...');
const subscriptions: Disposable[] = [];
subscriptions.push(window.onDidChangeActiveTextEditor(editor => {
if (editor && editor.document) {
this.onDidOpenDocument(editor.document);
}
}));
subscriptions.push(workspace.onDidChangeConfiguration(
this.onConfigChanged.bind(this)
));
subscriptions.push(workspace.onDidSaveTextDocument(async doc => {
if (path.basename(doc.fileName) === '.editorconfig') {
this.log('.editorconfig file saved.');
await this.rebuildConfigMap();
}
}));
subscriptions.push(workspace.onWillSaveTextDocument(async e => {
let selections: Selection[];
const activeEditor = window.activeTextEditor;
const activeDoc = get(activeEditor, 'document');
if (activeDoc && activeDoc === e.document) {
selections = window.activeTextEditor.selections;
}
const transformations = this.calculatePreSaveTransformations(
e.document,
e.reason
);
e.waitUntil(transformations);
if (selections) {
transformations.then(() => {
activeEditor.selections = selections;
});
}
}));
this.disposable = Disposable.from.apply(this, subscriptions);
this.rebuildConfigMap();
this.onConfigChanged();
}
private log(...messages: string[]) {
this.outputChannel.appendLine(messages.join(' '));
}
public dispose() {
this.disposable.dispose();
}
public getSettingsForDocument(doc: TextDocument) {
return this.docToConfigMap[this.getFileName(doc)];
}
private getFileName(doc: TextDocument) {
if (!doc.isUntitled) {
return doc.fileName;
}
const ext = languageExtensionMap[doc.languageId] || doc.languageId;
return path.join(
...compact([
workspace.getWorkspaceFolder(doc.uri),
`${doc.fileName}.${ext}`
])
);
}
public getDefaultSettings() {
return this.defaults;
}
private async rebuildConfigMap() {
this.log('Rebuilding config map...');
this.docToConfigMap = {};
return await Promise.all(workspace.textDocuments.map(
doc => this.onDidOpenDocument(doc)
));
}
private async onDidOpenDocument(doc: TextDocument) {
if (doc.languageId === 'Log') {
return;
}
const fileName = this.getFileName(doc);
const relativePath = workspace.asRelativePath(fileName, true);
if (this.docToConfigMap[fileName]) {
this.log(`${relativePath}: Applying configuration map...`);
await this.applyEditorConfigToTextEditor(window.activeTextEditor);
return;
}
this.log(`${relativePath}: Using EditorConfig core...`);
return editorconfig.parse(fileName)
.then(async (config) => {
if (config.indent_size === 'tab') {
config.indent_size = config.tab_width;
}
this.docToConfigMap[fileName] = config;
await this.applyEditorConfigToTextEditor(window.activeTextEditor);
});
}
private async applyEditorConfigToTextEditor(
editor: TextEditor,
) {
if (!editor) {
this.log('No more open editors.');
return Promise.resolve();
}
const doc = editor.document;
const relativePath = workspace.asRelativePath(doc.fileName, true);
const editorconfigSettings = this.getSettingsForDocument(doc);
if (!editorconfigSettings) {
this.log(`${relativePath}: No configuration.`);
return Promise.resolve();
}
const newOptions = fromEditorConfig(
editorconfigSettings,
this.getDefaultSettings()
);
// tslint:disable-next-line:no-any
editor.options = newOptions as any;
this.log(`${relativePath}: ${JSON.stringify(newOptions)}`);
}
private onConfigChanged() {
const workspaceConfig = workspace.getConfiguration('editor', null);
const detectIndentation = workspaceConfig.get<boolean>('detectIndentation');
this.defaults = (detectIndentation) ? {} : {
tabSize: workspaceConfig.get<string | number>('tabSize'),
insertSpaces: workspaceConfig.get<string | boolean>('insertSpaces')
};
this.log(
'Detected change in configuration:',
JSON.stringify(this.defaults)
);
}
private async calculatePreSaveTransformations(
doc: TextDocument,
reason: TextDocumentSaveReason
): Promise<TextEdit[]> {
const editorconfigSettings = this.getSettingsForDocument(doc);
const relativePath = workspace.asRelativePath(doc.fileName);
if (!editorconfigSettings) {
this.log(`${relativePath}: No configuration found for pre-save.`);
return [];
}
return Array.prototype.concat.call([],
...this.preSaveTransformations.map(
transformer => {
const { edits, message } = transformer.transform(
editorconfigSettings,
doc,
reason
);
if (edits instanceof Error) {
this.log(`${relativePath}: ${edits.message}`);
}
if (message) {
this.log(`${relativePath}: ${message}`);
}
return edits;
}
)
);
}
}
export default DocumentWatcher;