-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathextension.js
538 lines (459 loc) · 14.2 KB
/
extension.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
let assert = require("node:assert");
let path = require("node:path");
let { homedir } = require("node:os");
let { window, workspace, commands, Uri, EventEmitter, FileType, Selection, languages, Range, Diagnostic, DiagnosticRelatedInformation, Location, ViewColumn } = require("vscode");
/**
* The scheme is used to associate vsnetrw documents with the text content provider
* that renders the directory listing.
*/
const scheme = "vsnetrw";
/**
* The editorLanguageId used to identify vsnetrw buffers.
*/
const languageId = "vsnetrw";
/**
* The path to the file that was open before the current explorer.
*/
let previousFilePath = "";
/**
* Creates a vsnetrw document uri for a given path.
*
* @param {string} dirName The directory to open
* @returns {Uri} The path as a Uri
*/
function createUri(dirName) {
return Uri.from({ scheme, path: dirName });
}
/**
* Get the current directory from the current document's Uri.
* @returns The path to the directory that is open in the current vsnetrw document.
*/
function getCurrentDir() {
let editor = window.activeTextEditor;
assert(editor && editor.document.uri.scheme === scheme, "Not a vsnetrw editor");
return editor.document.uri.path;
}
/**
* Event emitter used to trigger updates for the text document content provider.
*/
let uriChangeEmitter = new EventEmitter();
/**
* Refresh the current vsnetrw document.
*/
function refresh() {
let dir = getCurrentDir();
let uri = createUri(dir);
uriChangeEmitter.fire(uri);
refreshDiagnostics();
}
/**
* @param {string} prompt
* @returns {Promise<boolean>}
*/
function confirm(prompt) {
return new Promise(resolve => {
let inputBox = window.createInputBox();
let resolveOnHide = true;
inputBox.validationMessage = `${prompt} (y or n)`;
let onChange = inputBox.onDidChangeValue(text => {
let ch = text[0].toLowerCase();
if (ch === "y") {
resolve(true);
resolveOnHide = false;
inputBox.hide();
} else if (ch === "n" || "q") {
inputBox.hide();
}
});
let onHide = inputBox.onDidHide(() => {
inputBox.dispose();
onChange.dispose();
onHide.dispose();
if (resolveOnHide) {
resolve(false);
}
});
inputBox.show();
});
}
function moveCursorToPreviousFile() {
let editor = window.activeTextEditor;
if (!editor) return;
let dir = getCurrentDir();
let files = editor.document.getText().split("\n");
let index = files.findIndex(file => (
path.join(dir, file) === previousFilePath ||
path.join(dir, file) === `${previousFilePath}/`
));
if (index >= 0) {
editor.selections = [new Selection(index, 0, index, 0)];
}
}
/**
* Open a new vsnetrw document for a given directory.
* @param {string} dirName
*/
async function openExplorer(dirName) {
let editor = window.activeTextEditor;
if (editor) {
previousFilePath = editor.document.uri.fsPath;
}
let uri = createUri(dirName);
let doc = await workspace.openTextDocument(uri);
await languages.setTextDocumentLanguage(doc, languageId);
await window.showTextDocument(doc, { preview: true });
moveCursorToPreviousFile();
}
/**
* Checks whether a file exists.
* @param {string} file
* @returns {Promise<boolean>}
*/
async function doesFileExist(file) {
try {
let uri = Uri.file(file);
await workspace.fs.stat(uri);
return true;
} catch (err) {
return false;
}
}
/**
* Checks whether a file exists.
* @param {string} file
* @returns {Promise<FileType | undefined>}
*/
async function getFileType(file) {
let uri = Uri.file(file);
try {
let stat = await workspace.fs.stat(uri);
return stat.type;
} catch (err) {
return undefined;
}
}
/**
* Returns the name of the file under the cursor in the current vsnetrw
* document.
* @returns {string}
*/
function getLineUnderCursor() {
let editor = window.activeTextEditor;
assert(editor, "No active editor");
let line = editor.document.lineAt(editor.selection.active);
return line.text;
}
/**
* Returns all lines in the active selection.
* @returns {string[]}
*/
function getLinesUnderCursor() {
let editor = window.activeTextEditor;
assert(editor, "No active editor");
let lines = [];
for (let i = editor.selection.start.line; i <= editor.selection.end.line; i++) {
let line = editor.document.lineAt(i);
lines.push(line.text);
}
return lines;
}
/**
* Opens a file in a vscode editor.
* @param {string} fileName
* @param {ViewColumn} [viewColumn]
*/
async function openFileInVscodeEditor(fileName, viewColumn) {
let uri = Uri.file(fileName);
await closeExplorer();
if (viewColumn) {
await commands.executeCommand("vscode.open", uri, viewColumn);
} else {
await commands.executeCommand("vscode.open", uri);
}
}
/**
* Close the vsnetrw explorer if it is the active editor.
*/
async function closeExplorer() {
let editor = window.activeTextEditor;
if (editor?.document.uri.scheme === scheme) {
await commands.executeCommand("workbench.action.closeActiveEditor");
}
}
/**
* Prompts the user to rename the file that is currently under their cursor in
* a vsnetrw document.
*
* If the name includes a path that does not exist, then it will be created.
*/
async function renameFileUnderCursor() {
let file = getLineUnderCursor();
let base = getCurrentDir();
let newName = await window.showInputBox({
title: "Rename",
value: file,
placeHolder: "Enter a new filename",
});
if (!newName) return;
let srcPath = path.join(base, file);
let dstPath = path.join(base, newName);
let dstFileType = await getFileType(dstPath);
// Treat renames like "a.txt -> ../" as "a.txt -> ../a.txt"
if (dstFileType === FileType.Directory) {
dstPath = path.join(dstPath, file);
dstFileType = await getFileType(dstPath);
}
if (dstFileType === FileType.Directory) {
window.showErrorMessage(`Can't replace directory: ${dstPath}`);
return;
}
if (dstFileType != undefined) {
let ok = await confirm("Overwrite existing file?");
if (!ok) return;
}
let srcUri = Uri.file(srcPath);
let dstUri = Uri.file(dstPath);
await workspace.fs.rename(srcUri, dstUri, { overwrite: true });
refresh();
}
/**
* Attempt to delete the file that is under the cursor in a vsnetrw document.
*/
async function deleteFileUnderCursor() {
let files = getLinesUnderCursor();
let base = getCurrentDir();
// Never allow the user to accidentally delete the parent dir
files = files.filter(file => file !== "../");
let ok = await confirm(
files.length === 1
? `Confirm deletion of ${files[0]}`
: `Confirm deletion of ${files.length} files`
);
if (!ok) return;
for (let file of files) {
let pathToFile = path.join(base, file);
let uri = Uri.file(pathToFile);
await workspace.fs.delete(uri, { recursive: true, useTrash: true });
}
refresh();
}
/**
* Prompt the user to create a new file. If the name of the new file ends with a slash,
* a directory will be created instead.
*
* If the file includes a path that does not exist, then the path will be created.
*/
async function createFile() {
let base = getCurrentDir();
let newFileName = await window.showInputBox({
title: "Create New File / Directory",
placeHolder: "Enter a name for the new file",
});
if (newFileName == null) return;
let pathToFile = path.join(base, newFileName);
let uri = Uri.file(pathToFile);
// Ignore if the file already exists
if (await doesFileExist(pathToFile)) return;
if (newFileName.endsWith("/")) {
await workspace.fs.createDirectory(uri)
refresh();
} else {
await workspace.fs.writeFile(uri, new Uint8Array());
await openFileInVscodeEditor(uri.fsPath);
}
}
/**
* Prompt the user to create a new directory. Intermediate directories that
* don't exist will be created too.
*/
async function createDir() {
let base = getCurrentDir();
let newFileName = await window.showInputBox({
title: "Create New Directory",
placeHolder: "Enter a name for the new directory",
});
if (newFileName == null) return;
let pathToDir = path.join(base, newFileName);
let uri = Uri.file(pathToDir);
await workspace.fs.createDirectory(uri);
refresh();
}
/**
* @returns {string}
*/
function getInitialDir() {
let editor = window.activeTextEditor;
if (editor && !editor.document.isUntitled) {
return path.dirname(editor.document.uri.fsPath);
} else if (workspace.workspaceFolders) {
let folder = workspace.workspaceFolders[0];
return folder.uri.fsPath;
} else {
return homedir();
}
}
/**
* Opens a new explorer editor.
*/
async function openNewExplorer(dir = getInitialDir()) {
// For some reason vim.normalModeKeyBindings pass an empty array
if (Array.isArray(dir)) dir = getInitialDir();
await openExplorer(dir);
}
/**
* Attempt to open the file that is currently under the cursor.
*
* If there is a file under the cursor, it will open in a vscode text
* editor. If there is a directory under the cursor, then it will open in a
* new vsnetrw document.
* @param {ViewColumn} [viewColumn]
*/
async function openFileUnderCursor(viewColumn) {
let relativePath = getLineUnderCursor();
let basePath = getCurrentDir();
let newPath = path.resolve(basePath, relativePath);
let uri = Uri.file(newPath);
let stat = await workspace.fs.stat(uri);
if (stat.type & FileType.Directory) {
await openExplorer(newPath);
} else {
await openFileInVscodeEditor(newPath, viewColumn);
}
}
async function openFileUnderCursorInHorizontalSplit() {
await openFileUnderCursor(ViewColumn.Beside);
}
async function openFileUnderCursorInVerticalSplit() {
await openFileUnderCursor(ViewColumn.Beside);
// saving the reference
// toggling the editor layout (vertical split) will make the editor lose focus
const lastActiveEditor = window.activeTextEditor;
await commands.executeCommand("workbench.action.toggleEditorGroupLayout");
if (lastActiveEditor) {
// focus the editor again
await window.showTextDocument(lastActiveEditor.document);
}
}
/**
* Opens the parent directory in a vsnetrw document.
*/
async function openParentDirectory() {
let editor = window.activeTextEditor;
assert(editor, "No active editor");
let pathName = editor.document.uri.path;
let parentPath = path.dirname(pathName);
openExplorer(parentPath);
}
/**
* Opens the home directory in a vsnetrw document. If there's an active workspace folder
* it will be used, otherwise the user's home directory is used.
*/
async function openHomeDirectory() {
let folder = homedir();
let editor = window.activeTextEditor;
if (editor) {
let workspaceFolder = (
workspace.getWorkspaceFolder(editor.document.uri) ||
workspace.workspaceFolders?.[0]
);
if (workspaceFolder) {
folder = workspaceFolder.uri.fsPath;
}
}
openExplorer(folder);
}
/**
* Renders the text content for the current vsnetrw document.
* @param {Uri} documentUri
* @returns {Promise<string>}
*/
async function provideTextDocumentContent(documentUri) {
let pathName = documentUri.path;
let pathUri = Uri.file(pathName);
let results = await workspace.fs.readDirectory(pathUri);
results.sort(([aName, aType], [bName, bType]) => {
return aType & FileType.Directory ?
bType & FileType.Directory ? 0 : -1 :
aName < bName ? -1 : 1;
});
let listings = results.map(([name, type]) => {
return type & FileType.Directory ? `${name}/` : name;
});
let hasParent = path.dirname(pathName) !== pathName;
if (hasParent) listings.unshift("../");
return listings.join("\n");
}
/**
* @type {import("vscode").TextDocumentContentProvider}
*/
let contentProvider = {
onDidChange: uriChangeEmitter.event,
provideTextDocumentContent,
};
let diagnostics = languages.createDiagnosticCollection("vsnetrw");
/**
* Propagate diagnostics in files up to the explorer.
*/
function refreshDiagnostics() {
assert(window.activeTextEditor);
let document = window.activeTextEditor.document;
let base = getCurrentDir();
let uris = document.getText().split("\n").map(name => {
let pathToFile = path.join(base, name);
return Uri.file(pathToFile);
})
let ownDiagnostics = uris.flatMap((uri, line) => {
let childDiagnostics = languages.getDiagnostics(uri);
if (childDiagnostics.length === 0) return [];
let severities = childDiagnostics.map(diagnostic => diagnostic.severity);
let severity = Math.min(...severities);
let name = path.basename(uri.fsPath);
let range = new Range(line, 0, line, name.length);
let diagnostic = new Diagnostic(
range, `${childDiagnostics.length} problems in this file`,
severity
);
diagnostic.relatedInformation = childDiagnostics.map(childDiagnostic => {
return new DiagnosticRelatedInformation(
new Location(uri, childDiagnostic.range),
childDiagnostic.message
);
});
return diagnostic;
});
diagnostics.set(document.uri, ownDiagnostics);
}
/**
* @param {import("vscode").TextEditor | undefined} editor
*/
function onChangeActiveTextEditor(editor) {
if (editor?.document.uri.scheme === scheme) {
refresh();
}
}
/**
* @param {import("vscode").ExtensionContext} context
*/
function activate(context) {
context.subscriptions.push(
workspace.registerTextDocumentContentProvider(scheme, contentProvider),
);
context.subscriptions.push(
window.onDidChangeActiveTextEditor(onChangeActiveTextEditor)
);
context.subscriptions.push(
commands.registerCommand("vsnetrw.open", openNewExplorer),
commands.registerCommand("vsnetrw.openAtCursor", openFileUnderCursor),
commands.registerCommand("vsnetrw.openAtCursorInHorizontalSplit", openFileUnderCursorInHorizontalSplit),
commands.registerCommand("vsnetrw.openAtCursorInVerticalSplit", openFileUnderCursorInVerticalSplit),
commands.registerCommand("vsnetrw.openParent", openParentDirectory),
commands.registerCommand("vsnetrw.openHome", openHomeDirectory),
commands.registerCommand("vsnetrw.rename", renameFileUnderCursor),
commands.registerCommand("vsnetrw.delete", deleteFileUnderCursor),
commands.registerCommand("vsnetrw.create", createFile),
commands.registerCommand("vsnetrw.createDir", createDir),
commands.registerCommand("vsnetrw.refresh", refresh),
commands.registerCommand("vsnetrw.close", closeExplorer),
);
}
module.exports = { activate };