-
Notifications
You must be signed in to change notification settings - Fork 3
/
extension.ts
76 lines (60 loc) · 1.86 KB
/
extension.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
'use strict';
import {
window,
workspace,
Disposable,
Position,
WorkspaceConfiguration,
ExtensionContext,
TextDocumentWillSaveEvent,
TextEdit,
Selection
} from 'vscode';
import {EOL} from 'os';
export function activate(context: ExtensionContext) {
const config = workspace.getConfiguration('files');
const controller = new FinalNewLineController(config);
context.subscriptions.push(controller);
}
class FinalNewLineController {
private _disposable: Disposable;
private _config: WorkspaceConfiguration;
private _selections: Selection[];
constructor(config) {
this._config = config;
const subscriptions: Disposable[] = [];
workspace.onWillSaveTextDocument(this._onWillDocumentSave, this, subscriptions);
workspace.onDidSaveTextDocument(this._onDidDocumentSave, this, subscriptions);
workspace.onDidChangeConfiguration(this._onConfigChanged, this, subscriptions);
this._disposable = Disposable.from(...subscriptions);
}
dispose() {
this._disposable.dispose();
}
private _onWillDocumentSave(e: TextDocumentWillSaveEvent) {
if (this._config.get('insertFinalNewline', false) === true) {
if (window.activeTextEditor) {
// Keep track of the current pre-save selections in case the cursor is at the last position
this._selections = window.activeTextEditor.selections;
}
const doc = e.document;
const lastLine = doc.lineAt(doc.lineCount - 1);
if (lastLine.isEmptyOrWhitespace === false) {
const edit = TextEdit.insert(new Position(doc.lineCount - 1, lastLine.text.length), EOL);
e.waitUntil(Promise.resolve([
edit
]));
}
}
}
private _onDidDocumentSave() {
if (this._selections) {
// Put back the selection before the save
window.activeTextEditor.selections = this._selections;
this._selections = undefined;
}
}
private _onConfigChanged() {
this._config = workspace.getConfiguration('files');
}
}