mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
feat(lsp): follow doc.rust-lang.org and docs.rs links inside the documentation popup (#3960)
rust-analyzer renders intra-doc links as rustdoc URLs (doc.rust-lang.org for the standard library, docs.rs for other crates, the project's own included). Such a link now resolves by crate, module path, name and member (#method.x, #variant.X) through workspace/symbol and opens as the next history step when exactly one declaration fits (re-exports don't count); otherwise it opens in the browser. Web link rules live per language in src/editor/lsp/docLinks/. typescript-language-server's #L20%2C3 source links keep their column. Refs #3874 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
co-authored by
wildcatDownstairs
parent
04ab9e8999
commit
e34e925b8f
@@ -8,15 +8,10 @@
|
||||
*/
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { call, commands, nextRequestId, type LibraryGroup, type WorkspaceSymbol } from "@/platform/ipc";
|
||||
import { symbols, unique, type DocTarget } from "./symbols";
|
||||
import { dirname } from "@/platform/project";
|
||||
import { readFileLines } from "../files";
|
||||
|
||||
export interface GoTarget {
|
||||
path: string;
|
||||
line: number;
|
||||
col: number;
|
||||
}
|
||||
|
||||
/** A name in a Go signature: `pkg.Name` (`qualifier` = `pkg`) or `Name`. */
|
||||
export interface GoRef {
|
||||
qualifier: string | null;
|
||||
@@ -33,17 +28,17 @@ const IDENT = "[A-Za-z_][A-Za-z0-9_]*";
|
||||
|
||||
/** `https://pkg.go.dev/<import path>[@version]#<Name>` or `#<Type>.<Method>`; null for other links. */
|
||||
export function pkgGoDevLink(href: string): { importPath: string; name: string } | null {
|
||||
let url: URL;
|
||||
// Malformed URLs and escapes are no links.
|
||||
try {
|
||||
url = new URL(href);
|
||||
const url = new URL(href);
|
||||
if (url.hostname !== "pkg.go.dev") return null;
|
||||
const name = decodeURIComponent(url.hash.slice(1));
|
||||
const importPath = decodeURIComponent(url.pathname.slice(1)).replace(/@[^/]*/, "");
|
||||
if (!importPath || !new RegExp(`^${IDENT}(\\.${IDENT})?$`).test(name)) return null;
|
||||
return { importPath, name };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (url.hostname !== "pkg.go.dev") return null;
|
||||
const name = decodeURIComponent(url.hash.slice(1));
|
||||
const importPath = decodeURIComponent(url.pathname.slice(1)).replace(/@[^/]*/, "");
|
||||
if (!importPath || !new RegExp(`^${IDENT}(\\.${IDENT})?$`).test(name)) return null;
|
||||
return { importPath, name };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,23 +88,8 @@ function named(s: WorkspaceSymbol, qualifier: string, name: string): boolean {
|
||||
return s.name === name || s.name === `${qualifier}.${name}`;
|
||||
}
|
||||
|
||||
async function symbols(query: string): Promise<WorkspaceSymbol[]> {
|
||||
return call(commands.lspWorkspaceSymbols(nextRequestId(), query)).catch(() => []);
|
||||
}
|
||||
|
||||
/** The one symbol `hits` hold (the same place listed twice counts once); null when none or several. */
|
||||
function unique(hits: WorkspaceSymbol[]): GoTarget | null {
|
||||
const places = new Map(
|
||||
hits.map((s) => {
|
||||
const { path, range } = s.location;
|
||||
return [`${path}:${range.start.line}:${range.start.col}`, { path, ...range.start }] as const;
|
||||
}),
|
||||
);
|
||||
return places.size === 1 ? [...places.values()][0]! : null;
|
||||
}
|
||||
|
||||
/** `name` (`Name` or `Type.Method`) declared in the package at `importPath`. */
|
||||
export async function findInPackage(importPath: string, name: string): Promise<GoTarget | null> {
|
||||
export async function findInPackage(importPath: string, name: string): Promise<DocTarget | null> {
|
||||
const pkg = goPackageName(importPath);
|
||||
const inPackage = (list: WorkspaceSymbol[]) => list.filter((s) => s.container === importPath && named(s, pkg, name));
|
||||
const hits = inPackage(await symbols(`${pkg}.${name}`));
|
||||
@@ -129,7 +109,7 @@ async function goSourceRoot(): Promise<string | null> {
|
||||
}
|
||||
|
||||
/** A predeclared name's declaration in `$GOROOT/src/builtin/builtin.go`. */
|
||||
async function builtin(name: string): Promise<GoTarget | null> {
|
||||
async function builtin(name: string): Promise<DocTarget | null> {
|
||||
const src = await goSourceRoot();
|
||||
if (!src) return null;
|
||||
const path = `${src}/builtin/builtin.go`;
|
||||
@@ -143,7 +123,7 @@ async function builtin(name: string): Promise<GoTarget | null> {
|
||||
}
|
||||
|
||||
/** Where a name in a Go signature is declared; null when it isn't found exactly once. */
|
||||
export async function resolveGoRef(ref: GoRef, ctx: GoRefContext): Promise<GoTarget | null> {
|
||||
export async function resolveGoRef(ref: GoRef, ctx: GoRefContext): Promise<DocTarget | null> {
|
||||
const { qualifier, name } = ref;
|
||||
if (!qualifier) {
|
||||
if (PREDECLARED.has(name)) return builtin(name);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/** Web documentation links a language server's convention lets us resolve to a declaration. */
|
||||
import { findInPackage, pkgGoDevLink } from "./go";
|
||||
import { findRustItem, rustDocLink } from "./rust";
|
||||
import type { DocTarget } from "./symbols";
|
||||
|
||||
/** Looks up the declaration `href` documents; null when no language's rule reads the link. */
|
||||
export function docUrlResolver(href: string): (() => Promise<DocTarget | null>) | null {
|
||||
const go = pkgGoDevLink(href);
|
||||
if (go) return () => findInPackage(go.importPath, go.name);
|
||||
const rust = rustDocLink(href);
|
||||
if (rust) return () => findRustItem(rust);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { WorkspaceSymbol } from "@/bindings";
|
||||
|
||||
const LIB = "/rust/lib/rustlib/src/rust/library";
|
||||
const REG = "/home/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f";
|
||||
const files: Record<string, string> = {
|
||||
[`${LIB}/std/src/ffi/mod.rs`]: "\n\npub use self::os_str::{OsStr, OsString};\n",
|
||||
};
|
||||
|
||||
const sym = (name: string, path: string, container: string | null = null, line = 3): WorkspaceSymbol => ({
|
||||
name,
|
||||
kind: "struct",
|
||||
container,
|
||||
location: { path, range: { start: { line, col: 11 }, end: { line, col: 14 } } },
|
||||
});
|
||||
|
||||
// What rust-analyzer answers per query (`*` = the dependencies instead of the workspace, `#` = every kind).
|
||||
const index: Record<string, WorkspaceSymbol[]> = {
|
||||
"ExitCode*": [
|
||||
sym("ExitCode", `${LIB}/std/src/process.rs`),
|
||||
sym("ExitCode", `${LIB}/std/src/sys/process/mod.rs`),
|
||||
sym("ExitCode", `${LIB}/std/src/sys/process/unix/common.rs`),
|
||||
],
|
||||
"HashMap*": [
|
||||
sym("HashMap", `${LIB}/vendor/hashbrown-0.17.1/src/map.rs`),
|
||||
sym("HashMap", `${LIB}/std/src/collections/mod.rs`),
|
||||
sym("HashMap", `${LIB}/std/src/collections/hash/map.rs`),
|
||||
],
|
||||
"OsString*": [sym("OsString", `${LIB}/std/src/ffi/os_str.rs`), sym("OsString", `${LIB}/std/src/ffi/mod.rs`, null, 2)],
|
||||
"From*": [sym("From", `${LIB}/core/src/convert/mod.rs`)],
|
||||
"push*#": [
|
||||
sym("push", `${LIB}/alloc/src/vec/mod.rs`, "Vec<T, A>"),
|
||||
sym("push", `${LIB}/alloc/src/string.rs`, "String"),
|
||||
],
|
||||
"None*#": [sym("None", `${LIB}/core/src/option.rs`, "Option")],
|
||||
"exit*#": [sym("exit", `${LIB}/std/src/process.rs`), sym("exit", `${REG}/libc-0.2.170/src/unix/mod.rs`)],
|
||||
Sku: [sym("Sku", "/work/rust-app/src/lib.rs")],
|
||||
"Sku*": [sym("Sku", `${REG}/other-1.0.0/src/lib.rs`)],
|
||||
"parse#": [sym("parse", "/work/rust-app/src/parser.rs"), sym("parse", "/work/rust-app/src/lib.rs", "Sku")],
|
||||
"Value*": [sym("Value", `${REG}/serde_json-1.0.140/src/value/mod.rs`)],
|
||||
Twice: [sym("Twice", "/work/a/src/lib.rs"), sym("Twice", "/work/b/src/lib.rs")],
|
||||
};
|
||||
|
||||
vi.mock("@/platform/ipc", async (orig) => ({
|
||||
...(await orig<typeof import("@/platform/ipc")>()),
|
||||
commands: { lspWorkspaceSymbols: async (_id: number, q: string) => ({ status: "ok", data: index[q] ?? [] }) },
|
||||
}));
|
||||
vi.mock("../files", () => ({ readFileLines: async (p: string) => files[p]?.split("\n") ?? [] }));
|
||||
|
||||
const { rustDocLink, findRustItem } = await import("./rust");
|
||||
const { docUrlResolver } = await import("./index");
|
||||
|
||||
describe("rustdoc links", () => {
|
||||
it.each([
|
||||
[
|
||||
"https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html",
|
||||
{ crate: "std", modules: ["process"], kind: "struct", name: "ExitCode", member: null },
|
||||
],
|
||||
[
|
||||
"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html#method.push",
|
||||
{ crate: "alloc", modules: ["vec"], kind: "struct", name: "Vec", member: "push" },
|
||||
],
|
||||
[
|
||||
"https://doc.rust-lang.org/stable/alloc/vec/struct.Vec.html#capacity-and-reallocation",
|
||||
{ crate: "alloc", modules: ["vec"], kind: "struct", name: "Vec", member: null },
|
||||
],
|
||||
[
|
||||
"https://docs.rs/inventory/0.1.0/inventory/struct.Sku.html",
|
||||
{ crate: "inventory", modules: [], kind: "struct", name: "Sku", member: null },
|
||||
],
|
||||
[
|
||||
"https://docs.rs/serde-json/latest/serde_json/value/enum.Value.html",
|
||||
{ crate: "serde_json", modules: ["value"], kind: "enum", name: "Value", member: null },
|
||||
],
|
||||
["https://doc.rust-lang.org/stable/alloc/fmt/index.html", null],
|
||||
["https://doc.rust-lang.org/nightly/core/primitive.char.html", null],
|
||||
["https://doc.rust-lang.org/stable/core/iter/book/ch03-05-control-flow.html", null],
|
||||
["https://docs.rs/serde", null],
|
||||
["https://crates.io/keywords/hasher", null],
|
||||
["https://docs.rs/x/1/x/struct.%E0%A4%A.html", null],
|
||||
])("%s", (href, want) => expect(rustDocLink(href)).toEqual(want));
|
||||
|
||||
const at = (path: string, line = 3) => ({ path, line, col: 11 });
|
||||
it.each([
|
||||
[
|
||||
"std struct, among private copies",
|
||||
"https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html",
|
||||
at(`${LIB}/std/src/process.rs`),
|
||||
],
|
||||
[
|
||||
"module path into a private submodule's file",
|
||||
"https://doc.rust-lang.org/stable/std/collections/hash/map/struct.HashMap.html",
|
||||
at(`${LIB}/std/src/collections/hash/map.rs`),
|
||||
],
|
||||
[
|
||||
"re-export left out",
|
||||
"https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html",
|
||||
at(`${LIB}/std/src/ffi/os_str.rs`),
|
||||
],
|
||||
["trait", "https://doc.rust-lang.org/stable/core/convert/trait.From.html", at(`${LIB}/core/src/convert/mod.rs`)],
|
||||
[
|
||||
"method of its type only",
|
||||
"https://doc.rust-lang.org/stable/alloc/vec/struct.Vec.html#method.push",
|
||||
at(`${LIB}/alloc/src/vec/mod.rs`),
|
||||
],
|
||||
[
|
||||
"enum variant",
|
||||
"https://doc.rust-lang.org/stable/core/option/enum.Option.html#variant.None",
|
||||
at(`${LIB}/core/src/option.rs`),
|
||||
],
|
||||
[
|
||||
"function, other crate's same name left out",
|
||||
"https://doc.rust-lang.org/stable/std/process/fn.exit.html",
|
||||
at(`${LIB}/std/src/process.rs`),
|
||||
],
|
||||
[
|
||||
"the project's own crate (docs.rs)",
|
||||
"https://docs.rs/inventory/0.1.0/inventory/struct.Sku.html",
|
||||
at("/work/rust-app/src/lib.rs"),
|
||||
],
|
||||
[
|
||||
"own module function, not a method",
|
||||
"https://docs.rs/inventory/0.1.0/inventory/parser/fn.parse.html",
|
||||
at("/work/rust-app/src/parser.rs"),
|
||||
],
|
||||
[
|
||||
"registry crate",
|
||||
"https://docs.rs/serde_json/1.0.140/serde_json/value/enum.Value.html",
|
||||
at(`${REG}/serde_json-1.0.140/src/value/mod.rs`),
|
||||
],
|
||||
["registry crate of another version name", "https://docs.rs/serde_json/1.0.140/other/value/enum.Value.html", null],
|
||||
["two local crates: ambiguous", "https://docs.rs/a/0.1.0/a/struct.Twice.html", null],
|
||||
["not found", "https://doc.rust-lang.org/stable/std/process/struct.Missing.html", null],
|
||||
["member not found", "https://doc.rust-lang.org/stable/alloc/string/struct.String.html#method.push_front", null],
|
||||
])("%s", async (_, href, want) => {
|
||||
expect(await findRustItem(rustDocLink(href)!)).toEqual(want);
|
||||
});
|
||||
|
||||
it("is one of the languages documentation links resolve for", async () => {
|
||||
expect(docUrlResolver("https://example.com/x")).toBeNull();
|
||||
expect(await docUrlResolver("https://doc.rust-lang.org/stable/core/convert/trait.From.html")!()).toEqual(
|
||||
at(`${LIB}/core/src/convert/mod.rs`),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Rust documentation links (rust-analyzer): intra-doc links come as rustdoc URLs —
|
||||
* `https://doc.rust-lang.org/<channel>/<crate>/<module…>/<kind>.<Name>.html[#method.<m>]`
|
||||
* for the standard library, `https://docs.rs/<package>/<version>/<crate>/…` for other crates,
|
||||
* the project's own included. They resolve through `workspace/symbol` by name, the crate and
|
||||
* module the URL names and, for a member, its type; only a unique match counts.
|
||||
*/
|
||||
import type { WorkspaceSymbol } from "@/platform/ipc";
|
||||
import { readFileLines } from "../files";
|
||||
import { symbols, unique, type DocTarget } from "./symbols";
|
||||
|
||||
export interface RustDocLink {
|
||||
crate: string;
|
||||
/** Module path inside the crate (`["collections", "hash", "map"]`). */
|
||||
modules: string[];
|
||||
/** Item kind as rustdoc names its page (`struct`, `fn`, `trait`…). */
|
||||
kind: string;
|
||||
name: string;
|
||||
/** `#method.push`, `#variant.None`…: that member of the item. */
|
||||
member: string | null;
|
||||
}
|
||||
|
||||
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
const MEMBER = /^(?:method|tymethod|variant|structfield|associatedconstant|associatedtype)\.([A-Za-z_][A-Za-z0-9_]*)$/;
|
||||
/** Pages of items `workspace/symbol` lists (not modules, primitives or keywords). */
|
||||
const ITEM_KINDS = new Set(["struct", "enum", "trait", "union", "type", "fn", "macro", "constant", "static"]);
|
||||
const TYPE_KINDS = new Set(["struct", "enum", "trait", "union", "type"]);
|
||||
|
||||
/** A rustdoc item URL on doc.rust-lang.org or docs.rs; null for other links. */
|
||||
export function rustDocLink(href: string): RustDocLink | null {
|
||||
// Malformed URLs and escapes are no links.
|
||||
try {
|
||||
const url = new URL(href);
|
||||
const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
||||
// doc.rust-lang.org/<channel>/<crate>/…; docs.rs/<package>/<version>/<crate>/…
|
||||
const skip = url.hostname === "doc.rust-lang.org" ? 1 : url.hostname === "docs.rs" ? 2 : -1;
|
||||
if (skip < 0 || parts.length < skip + 2) return null;
|
||||
const [crate, ...rest] = parts.slice(skip);
|
||||
const page = /^(\w+)\.(\w+)\.html$/.exec(rest.pop()!);
|
||||
if (!page || !ITEM_KINDS.has(page[1]!) || ![crate, ...rest].every((p) => IDENT.test(p!))) return null;
|
||||
const member = MEMBER.exec(decodeURIComponent(url.hash.slice(1)))?.[1] ?? null;
|
||||
return { crate: crate!, modules: rest, kind: page[1]!, name: page[2]!, member };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `path` can be `link`'s module of its crate: the module's file or a file under its
|
||||
* directory. Files of the standard library and of downloaded crates also have to be that crate;
|
||||
* the project's own crates can't be told apart by path.
|
||||
*/
|
||||
export function inModule(path: string, link: Pick<RustDocLink, "crate" | "modules">): boolean {
|
||||
const m = /^(.*\/)?([^/]+)\/src\/(.*)$/.exec(path);
|
||||
if (!m) return false;
|
||||
const [, parent = "", dir, file] = m;
|
||||
const crateDir = link.crate.replace(/_/g, "[-_]");
|
||||
const packaged = /\/(?:registry\/src\/[^/]+|library\/vendor)\/$/.test(parent);
|
||||
if (/\/library\/$/.test(parent) ? dir !== link.crate : packaged && !new RegExp(`^${crateDir}-\\d`).test(dir!))
|
||||
return false;
|
||||
if (!link.modules.length) return true;
|
||||
const mod = link.modules.join("/");
|
||||
return file === `${mod}.rs` || file!.startsWith(`${mod}/`);
|
||||
}
|
||||
|
||||
/** The type a member's symbol belongs to, as rust-analyzer names its container (`Vec<T, A>` → `Vec`). */
|
||||
function ownerName(s: WorkspaceSymbol): string {
|
||||
return (s.container ?? "").replace(/<.*$/, "").trim();
|
||||
}
|
||||
|
||||
/** A `use` line: rust-analyzer lists re-exports too, but the declaration is what's meant. */
|
||||
async function isReexport(s: WorkspaceSymbol): Promise<boolean> {
|
||||
const line = (await readFileLines(s.location.path).catch(() => null))?.[s.location.range.start.line] ?? "";
|
||||
return /^\s*(?:pub(?:\([^)]*\))?\s+)?use\b/.test(line);
|
||||
}
|
||||
|
||||
/** Where `link` is declared, when exactly one symbol fits it. */
|
||||
export async function findRustItem(link: RustDocLink): Promise<DocTarget | null> {
|
||||
const name = link.member ?? link.name;
|
||||
// rust-analyzer's query markers: `*` searches the dependencies (instead of the workspace),
|
||||
// `#` every kind of symbol (not only types).
|
||||
// A common name (`Vec::new`) can be past rust-analyzer's 128 results; such links open in the browser.
|
||||
const all = link.member || !TYPE_KINDS.has(link.kind) ? "#" : "";
|
||||
const found = await Promise.all([symbols(`${name}${all}`), symbols(`${name}*${all}`)]);
|
||||
const hits = found
|
||||
.flat()
|
||||
.filter((s) => s.name === name && (!link.member || ownerName(s) === link.name) && inModule(s.location.path, link));
|
||||
const declared = await Promise.all(hits.map(async (s) => !(await isReexport(s))));
|
||||
return unique(hits.filter((_, i) => declared[i]));
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/** `workspace/symbol` lookups shared by the per-language documentation link rules. */
|
||||
import { call, commands, nextRequestId, type WorkspaceSymbol } from "@/platform/ipc";
|
||||
|
||||
export interface DocTarget {
|
||||
path: string;
|
||||
line: number;
|
||||
col: number;
|
||||
}
|
||||
|
||||
export async function symbols(query: string): Promise<WorkspaceSymbol[]> {
|
||||
return call(commands.lspWorkspaceSymbols(nextRequestId(), query)).catch(() => []);
|
||||
}
|
||||
|
||||
/** The one place `hits` name (the same place listed twice counts once); null when none or several. */
|
||||
export function unique(hits: WorkspaceSymbol[]): DocTarget | null {
|
||||
const places = new Map(
|
||||
hits.map((s) => {
|
||||
const { path, range } = s.location;
|
||||
return [`${path}:${range.start.line}:${range.start.col}`, { path, ...range.start }] as const;
|
||||
}),
|
||||
);
|
||||
return places.size === 1 ? [...places.values()][0]! : null;
|
||||
}
|
||||
@@ -12,7 +12,9 @@ import { hasPrimaryModifier } from "@/platform/keymap";
|
||||
import { editorService, maybeEditorService, toolWindowService } from "@/workbench/contributions";
|
||||
import { closePopup, updatePopup, useLspPopup, type DocEntry } from "./popupStore";
|
||||
import { isEmptyMarkup, languageForPath, openDocLink, sourceLink, type DocLinkHandler } from "./markdown";
|
||||
import { findInPackage, pkgGoDevLink, resolveGoRef, signatureRef } from "./docLinks/go";
|
||||
import { resolveGoRef, signatureRef } from "./docLinks/go";
|
||||
import { docUrlResolver } from "./docLinks";
|
||||
import type { DocTarget } from "./docLinks/symbols";
|
||||
import { lspRequest } from "./lsp";
|
||||
import { readFileLines, withDocument } from "./files";
|
||||
|
||||
@@ -190,8 +192,6 @@ async function docAt(target: { path: string; line: number; col: number }): Promi
|
||||
});
|
||||
}
|
||||
|
||||
type DocTarget = { path: string; line: number; col: number };
|
||||
|
||||
/** Shows `target`'s documentation as the next history step; without any, opens its source. */
|
||||
async function followTo(host: DocHost, target: DocTarget) {
|
||||
const entry = await docAt(target).catch(() => null);
|
||||
@@ -210,18 +210,18 @@ async function followTo(host: DocHost, target: DocTarget) {
|
||||
/**
|
||||
* Link clicks in a documentation view: a source link shows that symbol's
|
||||
* documentation in the same view (⌘-click opens the source instead); so does
|
||||
* a pkg.go.dev link whose symbol is found, others open in the browser.
|
||||
* a web link a language's rule (`docLinks/`) finds the symbol of, others open in the browser.
|
||||
*/
|
||||
export function docLinkHandler(host: DocHost): DocLinkHandler {
|
||||
return (href, e) => {
|
||||
const target = sourceLink(href);
|
||||
const web = target ? null : pkgGoDevLink(href);
|
||||
const web = target ? null : docUrlResolver(href);
|
||||
if ((!target && !web) || hasPrimaryModifier(e)) {
|
||||
if (target) closeHost(host);
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
const found = target ?? (web && (await findInPackage(web.importPath, web.name).catch(() => null)));
|
||||
const found = target ?? (web && (await web().catch(() => null)));
|
||||
if (found) await followTo(host, found);
|
||||
else openDocLink(href);
|
||||
})();
|
||||
|
||||
@@ -68,6 +68,7 @@ describe("sourceLink", () => {
|
||||
it("reads the file and position a documentation link names", () => {
|
||||
project("C:/repo");
|
||||
expect(sourceLink("file:///C:/repo/src/a.py#L12,5")).toEqual({ path: "/C:/repo/src/a.py", line: 11, col: 4 });
|
||||
expect(sourceLink("file:///p/src/cart.ts#L20%2C3")).toEqual({ path: "/p/src/cart.ts", line: 19, col: 2 });
|
||||
expect(sourceLink("https://example.com/a.py")).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -208,7 +208,8 @@ export function sourceLink(href: string): { path: string; line: number; col: num
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
// Documentation is text someone else wrote.
|
||||
if (onOtherShare(path, useProject.getState().project?.root ?? "")) return null;
|
||||
const m = /^#?L?(\d+)(?:[,:](\d+))?/.exec(url.hash.slice(1));
|
||||
// typescript-language-server encodes the comma (`#L20%2C3`).
|
||||
const m = /^#?L?(\d+)(?:[,:](\d+))?/.exec(url.hash.slice(1).replace(/%2C/gi, ","));
|
||||
return {
|
||||
path,
|
||||
line: m ? Math.max(0, Number(m[1]) - 1) : 0,
|
||||
|
||||
Reference in New Issue
Block a user