-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.ts
65 lines (54 loc) · 2.13 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
import * as vscode from 'vscode';
let isAutoCenterEnabled = false;
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.toggleAutoCenter', () => {
isAutoCenterEnabled = !isAutoCenterEnabled;
vscode.window.showInformationMessage(`Auto code centering feature is now ${isAutoCenterEnabled ? 'enabled' : 'disabled'}.`);
});
context.subscriptions.push(disposable);
let centerDisposable = vscode.commands.registerCommand('extension.centerText', () => {
centerText();
});
context.subscriptions.push(centerDisposable);
vscode.workspace.onDidSaveTextDocument((_) => {
if (isAutoCenterEnabled) {
centerText();
}
});
}
export function deactivate() {}
function centerText() {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return vscode.window.showErrorMessage('No active text editor.');
}
const document = editor.document;
const maxLength = findLongestLineLength(document);
if (maxLength <= 0) {
return vscode.window.showInformationMessage('No text found to center.');
}
editor.edit((editBuilder) => {
for (let i = 0; i < document.lineCount; i++) {
const currentLine = document.lineAt(i);
if (currentLine.isEmptyOrWhitespace) {
continue;
}
const line = currentLine.text.trim();
let padding = Math.max(0, Math.round((maxLength - line.length) / 2));
const leadingSpaces = currentLine.firstNonWhitespaceCharacterIndex;
if (leadingSpaces + padding > 0) {
padding = Math.max(0, padding - leadingSpaces);
}
const padText = ' '.repeat(padding);
editBuilder.insert(currentLine.range.start, padText);
}
});
}
function findLongestLineLength(document: vscode.TextDocument): number {
let maxLength = 0;
for (let i = 0; i < document.lineCount; i++) {
const trimmedLine = document.lineAt(i).text.trim();
maxLength = Math.max(maxLength, trimmedLine.length);
}
return maxLength;
}