-
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathVscodeOpenLink.ts
More file actions
88 lines (80 loc) · 2.26 KB
/
Copy pathVscodeOpenLink.ts
File metadata and controls
88 lines (80 loc) · 2.26 KB
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
import * as vscode from "vscode";
import type { OpenLinkOptions, Range } from "@cursorless/lib-common";
import { Selection } from "@cursorless/lib-common";
import { toVscodePositionOrRange } from "@cursorless/lib-vscode-common";
import type { VscodeTextEditor } from "./VscodeTextEditor";
export async function vscodeOpenLink(
editor: VscodeTextEditor,
range: Range,
{ openAside }: OpenLinkOptions,
): Promise<void> {
const rawEditor = editor.vscodeEditor;
const links = await getLinksForEditor(rawEditor);
const vscodeRange = toVscodePositionOrRange(range);
const filteredLinks = links.filter((link) =>
link.range.contains(vscodeRange),
);
if (filteredLinks.length > 1) {
throw new Error("Multiple links found at location");
}
if (filteredLinks.length === 0) {
await runCommandAtRange(
editor,
openAside
? "editor.action.revealDefinitionAside"
: "editor.action.revealDefinition",
range,
);
return;
}
try {
await openLink(filteredLinks[0], openAside);
} catch {
// Fallback to moving cursor and running open link command
await runCommandAtRange(editor, "editor.action.openLink", range);
}
}
async function runCommandAtRange(
editor: VscodeTextEditor,
command: string,
range: Range,
) {
await editor.setSelections([Selection.fromRange(range)], {
focusEditor: true,
});
await vscode.commands.executeCommand(command);
}
async function getLinksForEditor(
editor: vscode.TextEditor,
): Promise<vscode.DocumentLink[]> {
return await vscode.commands.executeCommand(
"vscode.executeLinkProvider",
editor.document.uri,
);
}
function openLink(link: vscode.DocumentLink, openAside: boolean) {
if (link.target == null) {
throw new Error("Document link is missing uri");
}
return openUri(link.target, openAside);
}
async function openUri(uri: vscode.Uri, openAside: boolean) {
switch (uri.scheme) {
case "http":
case "https":
await vscode.env.openExternal(uri);
break;
case "file":
await vscode.window.showTextDocument(
uri,
openAside
? {
viewColumn: vscode.ViewColumn.Beside,
}
: undefined,
);
break;
default:
throw new Error(`Unknown uri scheme '${uri.scheme}'`);
}
}