From b9f0ceed90a8617aec8acb802e355fdd57df69f0 Mon Sep 17 00:00:00 2001 From: "a-team-app[bot]" <334837322+a-team-app[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:16:50 +1300 Subject: [PATCH 1/3] Add Go to implementation (gi, Ctrl+G I) Go to definition stops at an interface or abstract declaration. Go to implementation asks the language server for textDocument/implementation and routes the answer as Go to definition does: one jumps, several open the picker titled "Implementations of .", decompiled library places included. A server whose initialize result lacks implementationProvider, such as Pyright, is never asked, and the status bar says it can't find them. csharp-ls answers an unimplemented member with its own declaration, so that is left out and the status bar says there are none. Quick info moves to qi / Ctrl+G Q. In the leader, Enter now runs a complete mnemonic that a longer one starts with, so q waits and q Enter quits; every other mnemonic still runs as it's typed. The resolver is handed the whole table so q waits even where qi isn't offered. Closes #699 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 +- src/TuiCode.Abstractions/CommandIds.cs | 1 + src/TuiCode.Abstractions/CommandMnemonics.cs | 8 +- .../Languages/KnownLanguageServers.cs | 5 +- .../Languages/LanguageServer.cs | 22 +- src/TuiCode.Workbench/Menus/CommandMenu.cs | 4 +- .../Mnemonics/MnemonicResolver.cs | 24 +- .../Mnemonics/MnemonicView.cs | 14 +- .../Navigation/DefinitionPickerView.cs | 6 +- src/TuiCode.Workbench/WorkbenchHost.cs | 66 +++- tests/TuiCode.Tests/CommandMnemonicsTests.cs | 26 +- .../DecompiledSourceHostTests.cs | 24 ++ tests/TuiCode.Tests/FakeLanguageServer.cs | 55 ++- .../GoToImplementationHostTests.cs | 316 ++++++++++++++++++ tests/TuiCode.Tests/LanguageServerTests.cs | 58 ++++ tests/TuiCode.Tests/MenuBarHostTests.cs | 2 +- tests/TuiCode.Tests/MnemonicResolverTests.cs | 26 ++ tests/TuiCode.Tests/MnemonicScopeHostTests.cs | 31 +- tests/TuiCode.Tests/MnemonicViewTests.cs | 39 +++ tests/TuiCode.Tests/PickerDialogsTests.cs | 2 +- tests/TuiCode.Tests/QuickInfoHostTests.cs | 13 +- 21 files changed, 684 insertions(+), 69 deletions(-) create mode 100644 tests/TuiCode.Tests/GoToImplementationHostTests.cs diff --git a/AGENTS.md b/AGENTS.md index cff91161..83c4cbc5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,10 +107,10 @@ What follows is how TuiCode implements it today. ## Mnemonics (leader key, #50) -- A leader key (`Ctrl+Space` by default, rebindable like any shortcut → `CommandIds.ShowMnemonics`) opens `MnemonicView`: a modal launcher that lists the mnemonics of the commands in scope and enabled where it opened (`WorkbenchHost.MnemonicsInScope`, captured before the modal scope is pushed) and fires the command the instant the typed prefix is unambiguous — no Enter. Esc cancels, Backspace edits. +- A leader key (`Ctrl+Space` by default, rebindable like any shortcut → `CommandIds.ShowMnemonics`) opens `MnemonicView`: a modal launcher that lists the mnemonics of the commands in scope and enabled where it opened (`WorkbenchHost.MnemonicsInScope`, captured before the modal scope is pushed) and fires the command the instant the typed prefix is unambiguous — no Enter. Enter runs a complete mnemonic that a longer one starts with (`q Enter` quits, `qi` is Quick info, #699), and the lone remaining match. Esc cancels, Backspace edits. - Mnemonics are **hard-coded design decisions, not user-configurable** — only the leader key is rebindable. The table lives in `CommandMnemonics` (Abstractions), keyed by command id, next to `CommandIds`. Commands with no entry (`ShowActions`, `ShowMnemonics` itself) simply don't appear. -- **Invariant: no complete mnemonic is a prefix of another** (guarded by `CommandMnemonicsTests.No_mnemonic_is_a_prefix_of_another`). That's what lets the auto-execute rule work without a terminating key. Mnemonics come in families under a shared first key with room to grow (`cf` close-file, `cot`/`cat` close other and all tabs, with `cs` reserved; `ts`/`tg`/`tc` toggle; `nf`/`nc`/`nt` and `pf`/`pc`/`pt` new/next and previous; `fs`/`fe`/`ft`/`fr`/`fu`/`f1`…`f9` focus; `gl`/`gs`/`gt`/`gd`/`gp`/`gn` go to, `gi` quick info and `gu` find usages, `gb` git blame, `gh` git history and `gf` go to file (*Reveal in explorer*); `cg` change grammar, `cc` create comment and `cp` copy permalink, the `c`s that aren't close; `og` open on GitHub, which skips *on* as `gl` skips *to*; `ff`/`fg` and `rf`/`rg` find/replace in the active file vs. globally — a trailing `f` means the active file, as in `sf`/`cf`). **A mnemonic is the command label's initials** — `fg` *Find globally*, `nt` *Next tab*, `rc` *Revert change*. Where the initials read badly or are taken, change the label rather than inventing letters ("Find globally", not "Search in files"); the standing exceptions are the trailing-`f` family, `q`/`?`, `tui`, `f1`…`f9`, and `ts`/`tg`/`tww`/`tc`/`tv`/`tmc`/`tmw`/`tfi`, which keep *Toggle*'s initials (#526). `mu`/`md` move and `du`/`dd` duplicate lines, `il`/`ol` indent and outdent them, and `tlc` toggles their line comment; `aa`/`ab` add a cursor above/below. `q`/`?` are the only single-key ones. `tui` (About, #107), `opr` (#184), `or` (#357), `pro` (#185), `gs` (#137), `cc` (#188, #189), `cot` and `cat` (#518) have no default keybinding. `ts` (toggle sidebar) flips visibility unconditionally, then settles focus against the *new* state — a freshly shown sidebar takes focus, a freshly hidden one that held focus hands it back to the editor. `fs` (focus sidebar) just shows-and-focuses. The split (#85) keeps `ts` honest from the palette/leader, where focus has already left the sidebar before the command runs — the old handler gated the *hide* on the sidebar being focused, so it never hid from those entry points. -- **Narrowing the list can't make a mnemonic fire early**, so there's no second, unfiltered copy of the table to keep in step (#285). `ResolveExact` fires only on a prefix that is itself a complete mnemonic, and the table is prefix-free, so a complete mnemonic has nothing under it that hiding could reveal. The guard is `MnemonicScopeHostTests.Narrowing_the_list_never_makes_a_mnemonic_fire_a_keystroke_earlier`, over the real commands; break the prefix-free invariant and it says so. A keystroke no *in-scope* mnemonic could complete is ignored by the same rejection `OnKey` always did, over the smaller set — so there's no abort path and no message, which is what makes an out-of-scope command seem not to exist. +- **A mnemonic runs as soon as it's typed unless a longer one starts with it.** `q` is the only one that does (`qi`), so it waits for Enter (#699); `CommandMnemonicsTests.Every_mnemonic_is_reachable_and_only_q_needs_Enter` guards both. Keep it that way: a new mnemonic that is a prefix of another costs every user of the shorter one an Enter. Mnemonics come in families under a shared first key with room to grow (`cf` close-file, `cot`/`cat` close other and all tabs, with `cs` reserved; `ts`/`tg`/`tc` toggle; `nf`/`nc`/`nt` and `pf`/`pc`/`pt` new/next and previous; `fs`/`fe`/`ft`/`fr`/`fu`/`f1`…`f9` focus; `gl`/`gs`/`gt`/`gd`/`gi`/`gp`/`gn` go to, `qi` quick info and `gu` find usages, `gb` git blame, `gh` git history and `gf` go to file (*Reveal in explorer*); `cg` change grammar, `cc` create comment and `cp` copy permalink, the `c`s that aren't close; `og` open on GitHub, which skips *on* as `gl` skips *to*; `ff`/`fg` and `rf`/`rg` find/replace in the active file vs. globally — a trailing `f` means the active file, as in `sf`/`cf`). **A mnemonic is the command label's initials** — `fg` *Find globally*, `nt` *Next tab*, `rc` *Revert change*. Where the initials read badly or are taken, change the label rather than inventing letters ("Find globally", not "Search in files"); the standing exceptions are the trailing-`f` family, `q`/`?`, `tui`, `f1`…`f9`, and `ts`/`tg`/`tww`/`tc`/`tv`/`tmc`/`tmw`/`tfi`, which keep *Toggle*'s initials (#526). `mu`/`md` move and `du`/`dd` duplicate lines, `il`/`ol` indent and outdent them, and `tlc` toggles their line comment; `aa`/`ab` add a cursor above/below. `q`/`?` are the only single-key ones. `tui` (About, #107), `opr` (#184), `or` (#357), `pro` (#185), `gs` (#137), `cc` (#188, #189), `cot` and `cat` (#518) have no default keybinding. `ts` (toggle sidebar) flips visibility unconditionally, then settles focus against the *new* state — a freshly shown sidebar takes focus, a freshly hidden one that held focus hands it back to the editor. `fs` (focus sidebar) just shows-and-focuses. The split (#85) keeps `ts` honest from the palette/leader, where focus has already left the sidebar before the command runs — the old handler gated the *hide* on the sidebar being focused, so it never hid from those entry points. +- **Narrowing the list can't make a mnemonic fire early** (#285). `ResolveExact` fires only on a prefix that is itself a complete mnemonic and that no mnemonic in the whole table extends, which the host hands it alongside the scope's (`every`), so `q` waits for Enter even where `qi` isn't listed. The guard is `MnemonicScopeHostTests.Narrowing_the_list_never_makes_a_mnemonic_fire_a_keystroke_earlier`, over the real commands. A keystroke no *in-scope* mnemonic could complete is ignored by the same rejection `OnKey` always did, over the smaller set — so there's no abort path and no message, which is what makes an out-of-scope command seem not to exist. - The matching logic is the pure, TG-free `MnemonicResolver` (`Matching` for the hint list, `ResolveExact` for the fire-now decision) so it's unit-tested directly. `MnemonicView` is a thin capture-scope shell over it — it reads keys via `KeyCaptureScope` rather than a focused TextField precisely so a command that disposes the view executes on the app key-dispatch path, not inside a TextChanged callback. ## Menu bar (#340) @@ -451,7 +451,7 @@ What follows is how TuiCode implements it today. ## Navigation - In-editor cursor navigation (Home/End/Ctrl+arrows + Shift selection variants) is Editor's commands on TextView's keys (`CodeEditor.TextViewKeys`), not workbench bindings. -- `Ctrl+G` is a chord family (#35): `Ctrl+G L` opens `GoToLineView` (1-based `line[:col]` input), `Ctrl+G P`/`Ctrl+G N` step back/forward through cursor history, `Ctrl+G D` goes to a definition, `Ctrl+G I` shows quick info, `Ctrl+G U` finds usages, `Ctrl+G B` blames the cursor's line (see *Git*), `Ctrl+G H` shows the file's history (see *File history*), and `Ctrl+G A` shows or hides AI assistance (`ai`). `EditorTab.MoveCursor(row, col)` writes through `CodeEditor.InsertionPoint`, which is a `Point` (Column, Row) — not an int offset. Out-of-range row/col clamp. +- `Ctrl+G` is a chord family (#35): `Ctrl+G L` opens `GoToLineView` (1-based `line[:col]` input), `Ctrl+G P`/`Ctrl+G N` step back/forward through cursor history, `Ctrl+G D` goes to a definition, `Ctrl+G I` to an implementation, `Ctrl+G Q` shows quick info, `Ctrl+G U` finds usages, `Ctrl+G B` blames the cursor's line (see *Git*), `Ctrl+G H` shows the file's history (see *File history*), and `Ctrl+G A` shows or hides AI assistance (`ai`). `EditorTab.MoveCursor(row, col)` writes through `CodeEditor.InsertionPoint`, which is a `Point` (Column, Row) — not an int offset. Out-of-range row/col clamp. - **Every explicit jump ends in `EditorTab.RevealLines`** (#200): go to line, go to symbol, Back/Forward, a Find result, `tuicode file.cs:42` and `Enter` in a diff. It scrolls so the range's first line sits `Reveal.Margin` (2) rows below the top, or below the sticky lines, or not at all when the range is already in view with that margin at both ends — so a hop to something you can see doesn't move the screen. `Reveal` (TG-free, in `TuiCode.Editor`) is the whole of the calculation and owns the margin the diff pane reads too. It runs *after* the cursor move, since TG's `ScrollToMakeCursorVisible` would otherwise have the last word, and does nothing before the first layout (height 0). Ordinary movement — arrows, PgUp/PgDn, find-next, next-occurrence — keeps TG's minimal scrolling. The gutter follows for free, off `ViewportChanged`. - **A jump never carries a selection** (#360): `EditorTab.MoveCursor` drops extra cursors and the selection before it moves, and `Select` (Find results) starts from no selection, so the match is all that's selected. - Cursor location history (#35) is `CursorLocationHistory` (`Navigation/`) — a pure, TG-free back/forward stack, unit-tested directly like `MnemonicResolver`. `WorkbenchHost` feeds it: within-file moves arrive via `EditorGroup.CursorMoved` (re-raised from `CodeEditor.CursorMoved`, in file coordinates), file switches via `ActiveTabChanged`. The history's own heuristic decides what counts as a navigable **jump** vs. **drift**: a jump is a different file, a row delta ≥ threshold (default 10), or an explicit jump (Go-to-line passes `explicitJump: true` so even a short hop records). Drift (small same-file moves) just updates the current entry so a later jump's Back target is where the user actually was — typing and single-arrow steps never fill the stack. A jump truncates the forward/redo path (browser semantics). Driving the cursor on Back/Forward/Go-to-line sets `_suppressHistory` so those programmatic moves aren't re-recorded. No key interception is needed (the event is editor-scoped), so the explorer/settings/TreeView are untouched — the two concerns #35 flagged both dissolve. @@ -469,9 +469,10 @@ What follows is how TuiCode implements it today. - **Follow link** (`fl`, no default key, `Editor` scope, #466) is enabled only while the cursor is on a link (`Links.At`, pure): `http`, `https` or `mailto`, trailing punctuation and unbalanced closing brackets trimmed, and a Markdown `[text](url)` from anywhere in it. `SystemBrowser` launches `open`/`xdg-open` with its output redirected so it can't write over the screen, or the shell on Windows. Over SSH (`IEnvironment.IsOverSsh`) it copies the link instead, through the editor's own copy, so `Ctrl+V` pastes it. Tests swap `WorkbenchHost.Browser` for a fake. - The status bar's `Ln X, Col Y` (right-aligned, #120) is polled on `IApplication.Iteration` (`Workbench.ShowCursorPosition`), not driven by `CursorMoved`: that comes from keys and the mouse only, so programmatic moves (find, Go-to-line, multi-caret, line moves) go unreported. `StatusBarPart.SetPosition` no-ops when unchanged, so polling costs a tuple compare. Col counts the model's grapheme cells, so a tab is one column. - **Go to definition** (`Ctrl+G D`, `gd`, `Editor` scope, #454) asks the file's language server (see *Language servers*). One answer jumps there the way Go to line does, recorded as an explicit jump; several (a partial class) open `DefinitionPickerView`, the shape of Go to symbol's; none is a status-bar line. Only the latest request jumps, so a slow answer to an earlier press is ignored. The command stays enabled without a ready server, so the key and the palette can say what's missing; only the menu dims it until the server is ready (`IsAvailableFrom`), the one exception to the menu following the palette (`MenuBarHostTests`). +- **Go to implementation** (`Ctrl+G I`, `gi`, `Editor` scope, #699) asks for `textDocument/implementation` and routes the answer as `gd` does, decompiled places included: one jumps, several open the same picker titled `Implementations of .` (named as Find usages names its symbol), none is `No implementations of `. TuiCode asks only a server whose initialize result has `implementationProvider`; for one that hasn't, such as Pyright, it says ` can't find implementations` (`LanguageServer.Title`: the server's `serverInfo.name`, else the name Settings knows it by) rather than reporting none. It's dimmed and says what it lacks without a ready server, like `gd`. - **Go to type** (`Ctrl+G T`, `gt`, Global, #653) asks every ready language server for `workspace/symbol` and keeps classes (records too), interfaces, structs and enums (`LspTypes`). The servers do the matching, so `TypePickerView` shows their answer as it is rather than filtering it again; TuiCode declares every LSP symbol kind, without which a server may report a struct as a class. `TypeSearch` runs one query at a time, and only the last one typed meanwhile runs next; a server that fails or takes longer than 5 s counts as finding nothing. While a server loads the picker says so and searches again on `LanguageServers.StateChanged`; with none running it says why. Enter jumps through `JumpTo`, as Go to definition does. - **Decompiled library sources** (#610): TuiCode tells every server it can show `csharp:/` locations (`experimental.csharp.metadataUris`), so csharp-ls answers a definition in a referenced assembly with `csharp:/…/decompiled/System.Console.cs`. The host asks `csharp/metadata` for each such place before jumping, and `DecompiledFiles` writes the source to `/TuiCode/decompiled//`. `LanguageServer.Alias` then sends requests about that file under its `csharp:/` URI, which csharp-ls answers (hover, `gd` within it), and never opens it as a document; a place it can't decompile is dropped. The Roslyn server writes its own files under `/MetadataAsSource`, which `DecompiledFiles.At` recognises by that folder. Either way the tab opens with `EditorTab.ReadOnly` set (Terminal.Gui.Editor's `ReadOnly`, plus every TuiCode edit route going through `CodeEditor.Refused`, which raises `EditRefused` for the status bar), titled `Console.cs [decompiled]`, resting on `Decompiled from , read-only`, and left out of the folder's saved tabs and file positions. -- **Quick info** (`Ctrl+G I`, `gi`, `Editor` scope, #591) asks the server for `textDocument/hover` and shows the answer in `QuickInfoView`, a box under the caret's line, or above it when there's more room there (`QuickInfo.Place`), at most `QuickInfo.MaxHeight` rows and never wider than the text. `LspHover` reads every shape the protocol allows: fenced code is the signature, coloured by the fence's grammar or else the file's (`CodeBlockColours`, shared with the chat), and the rest is prose, wrapped at `QuickInfo.ProseWidth` unless the code is wider, with markdown escapes, inline-code backticks and rules taken out. The box never takes focus: its keys are a `LayeredScope` over whatever had them, so `Esc` closes it, `Enter` closes it and runs Go to definition, the arrows and page keys scroll it, and any other key closes it and goes on to the editor; `F1` leaves it open and lists them (`QuickInfoKeys`). Its buttons sit on its bottom border and lose their labels, down to just the keys, when the box is too narrow for them (`FitButtons`). A click, a scroll or a resize that moves the caret's cell closes it on the next iteration, once its scope is on top again. Its rules otherwise follow `gd`'s: only the latest request shows, it's dimmed in the menu until the server is ready, and it says the same thing without one; an empty answer is `Nothing to show here`. +- **Quick info** (`Ctrl+G Q`, `qi`, `Editor` scope, #591, moved from `gi` by #699) asks the server for `textDocument/hover` and shows the answer in `QuickInfoView`, a box under the caret's line, or above it when there's more room there (`QuickInfo.Place`), at most `QuickInfo.MaxHeight` rows and never wider than the text. `LspHover` reads every shape the protocol allows: fenced code is the signature, coloured by the fence's grammar or else the file's (`CodeBlockColours`, shared with the chat), and the rest is prose, wrapped at `QuickInfo.ProseWidth` unless the code is wider, with markdown escapes, inline-code backticks and rules taken out. The box never takes focus: its keys are a `LayeredScope` over whatever had them, so `Esc` closes it, `Enter` closes it and runs Go to definition, the arrows and page keys scroll it, and any other key closes it and goes on to the editor; `F1` leaves it open and lists them (`QuickInfoKeys`). Its buttons sit on its bottom border and lose their labels, down to just the keys, when the box is too narrow for them (`FitButtons`). A click, a scroll or a resize that moves the caret's cell closes it on the next iteration, once its scope is on top again. Its rules otherwise follow `gd`'s: only the latest request shows, it's dimmed in the menu until the server is ready, and it says the same thing without one; an empty answer is `Nothing to show here`. - **Problems** (#687): `LanguageServer` reads `textDocument/publishDiagnostics` (`LspDiagnostics`, hints left out, a missing severity taken as an error) for open files only, and `LanguageServers` hands them to the tab (`EditorTab.Problems`), clearing them when the tab closes. They're kept as the server sent them, in UTF-16 columns, and drawn against the text as it is now, so they lag typing until the server answers. `CodeEditor.DrawRow` underlines them in the token theme's `editorError` / `editorWarning` / `editorInfo.foreground` (`ProblemColours`, else the `Error`, `Warning` and `Accent` schemes); TG has no separate underline colour, so the text takes the colour too. The gutter draws a line's number in its worst problem's colour, with no extra column. Quick info at a problem lists it first (`✖ CS0103 …`), then a rule, then the hover; with no hover it shows the problems alone. - **Find usages** (`Ctrl+G U`, `gu`, `Editor` scope, #455) asks the server for `textDocument/references` without the declaration, and lists them in the sidebar's **Usages** tab (`UsagesView`), grouped by file by the pure `UsageTree`: files in path order, each usage its line number and trimmed text, cut with an ellipsis as it's drawn. Its header names the symbol after its type (`Usages of LineDiff.Hunks`), from the definition's `textDocument/documentSymbol` (`LspSymbols`), falling back to the word under the caret. Only the latest request fills the tab, a Find search never touches it, and `Enter` jumps as Go to definition does. `Ctrl+Shift+U` (`fu`, Focus usages) goes back to them without asking again. It's dimmed in the menu like `gd`, and says the same thing without a server. - macOS gotcha: by default Mission Control's "Move left/right a space" eats `Ctrl+Left`/`Ctrl+Right` before iTerm2 sees them. Disable in System Settings → Keyboard → Keyboard Shortcuts → Mission Control. diff --git a/src/TuiCode.Abstractions/CommandIds.cs b/src/TuiCode.Abstractions/CommandIds.cs index 826eb56e..9a553243 100644 --- a/src/TuiCode.Abstractions/CommandIds.cs +++ b/src/TuiCode.Abstractions/CommandIds.cs @@ -91,6 +91,7 @@ public static class CommandIds public const string GoToMatchingBracket = "workbench.action.goToMatchingBracket"; public const string GoToDefinition = "workbench.action.goToDefinition"; + public const string GoToImplementation = "workbench.action.goToImplementation"; public const string QuickInfo = "workbench.action.quickInfo"; public const string QuickInfoClose = "quickInfo.action.close"; public const string QuickInfoGoToDefinition = "quickInfo.action.goToDefinition"; diff --git a/src/TuiCode.Abstractions/CommandMnemonics.cs b/src/TuiCode.Abstractions/CommandMnemonics.cs index 80f12183..77e286cb 100644 --- a/src/TuiCode.Abstractions/CommandMnemonics.cs +++ b/src/TuiCode.Abstractions/CommandMnemonics.cs @@ -9,9 +9,8 @@ namespace TuiCode.Abstractions; /// A mnemonic is the command label's initials (fg for "Find globally", nt for /// "Next tab"); a label that doesn't give usable initials is the thing to change. /// -/// Invariant: no complete mnemonic is a prefix of another. That lets the dialog -/// auto-execute the instant the typed sequence uniquely identifies a command, with no -/// terminating Enter. Mnemonics therefore come in families under a shared first key +/// The dialog runs a mnemonic the instant it's typed, unless a longer one starts with it +/// (q under qi): that one waits for Enter. Mnemonics come in families under a shared first key /// (close, open, focus, toggle, …) that have room to /// grow: cf close file leaves co/ca/cs free for future /// close-other/all/sidebar commands. q (quit) and ? (help) are the only @@ -109,7 +108,8 @@ private static IReadOnlyDictionary Build() [CommandIds.GoToType] = "gt", [CommandIds.GoToMatchingBracket] = "gm", [CommandIds.GoToDefinition] = "gd", - [CommandIds.QuickInfo] = "gi", + [CommandIds.GoToImplementation] = "gi", + [CommandIds.QuickInfo] = "qi", [CommandIds.FindUsages] = "gu", [CommandIds.AiAssistance] = "ai", [CommandIds.FocusAssistant] = "fi", diff --git a/src/TuiCode.Workbench/Languages/KnownLanguageServers.cs b/src/TuiCode.Workbench/Languages/KnownLanguageServers.cs index c78df61b..facf96ca 100644 --- a/src/TuiCode.Workbench/Languages/KnownLanguageServers.cs +++ b/src/TuiCode.Workbench/Languages/KnownLanguageServers.cs @@ -3,7 +3,8 @@ namespace TuiCode.Workbench.Languages; /// A language server TuiCode can offer by name, with what to run and how to install it. -public sealed record KnownLanguageServer(string Name, string Command, IReadOnlyList Arguments, string Install) +/// The name in a sentence, where it isn't . +public sealed record KnownLanguageServer(string Name, string Command, IReadOnlyList Arguments, string Install, string? Title = null) { public LanguageServerSetting Setting { get; } = new(Command, Arguments); } @@ -24,7 +25,7 @@ public static class KnownLanguageServers private static readonly KnownLanguageServer TypeScript = new( "typescript-language-server", "typescript-language-server", ["--stdio"], "npm install -g typescript-language-server typescript"); - private static readonly KnownLanguageServer Pyright = new("pyright", "pyright-langserver", ["--stdio"], "npm install -g pyright"); + private static readonly KnownLanguageServer Pyright = new("pyright", "pyright-langserver", ["--stdio"], "npm install -g pyright", "Pyright"); private static readonly KnownLanguageServer Pylsp = new("pylsp", "pylsp", [], "pip install python-lsp-server"); diff --git a/src/TuiCode.Workbench/Languages/LanguageServer.cs b/src/TuiCode.Workbench/Languages/LanguageServer.cs index 6f715b62..11c3fedb 100644 --- a/src/TuiCode.Workbench/Languages/LanguageServer.cs +++ b/src/TuiCode.Workbench/Languages/LanguageServer.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using System.Text.Json.Nodes; namespace TuiCode.Workbench.Languages; @@ -8,6 +9,9 @@ public sealed record LanguageServerSpec(string LanguageId, string Name, string C public static readonly LanguageServerSpec CSharp = new( "csharp", "C#", KnownLanguageServers.CSharpLs.Command, KnownLanguageServers.CSharpLs.Arguments, KnownLanguageServers.CSharpLs.Install); + /// The server's name in a sentence: Pyright for pyright-langserver. + public string Title => KnownLanguageServers.WithCommand(LanguageId, Command) is { } known ? known.Title ?? known.Name : Command; + public string Loading => $"{Command} is loading the {(LanguageId == "csharp" ? "solution" : "folder")}…"; public string NotInstalled => Install is null @@ -44,6 +48,7 @@ public LanguageServer(LanguageServerSpec spec, string root, ILanguageServerLaunc Root = root; _launcher = launcher; _post = post; + Title = spec.Title; } public LanguageServerSpec Spec { get; } @@ -59,6 +64,12 @@ public LanguageServer(LanguageServerSpec spec, string root, ILanguageServerLaunc /// How long stopping waits for the server to answer shutdown, and then to exit, before ending it. public TimeSpan StopTimeout { get; init; } = TimeSpan.FromSeconds(1); + /// Whether the server answers textDocument/implementation, as its initialize result says. + public bool FindsImplementations { get; private set; } + + /// What the server calls itself, or else what TuiCode knows it as. + public string Title { get; private set; } + public event EventHandler? StateChanged; /// The server's problems for an open file, replacing any it reported before. Raised through post. @@ -91,7 +102,9 @@ private async Task InitializeAsync(JsonRpcConnection connection) { try { - await connection.RequestAsync("initialize", InitializeParams()).ConfigureAwait(false); + var initialized = await connection.RequestAsync("initialize", InitializeParams()).ConfigureAwait(false); + FindsImplementations = initialized?["capabilities"]?["implementationProvider"]?.GetValueKind() is JsonValueKind.Object or JsonValueKind.True; + Title = initialized?["serverInfo"]?["name"]?.GetValue() is { Length: > 0 } name ? name : Spec.Title; } catch (Exception e) when (e is JsonRpcException or IOException) { @@ -142,6 +155,7 @@ private JsonObject InitializeParams() ["publishDiagnostics"] = new JsonObject(), ["synchronization"] = new JsonObject { ["didSave"] = true }, ["definition"] = new JsonObject { ["linkSupport"] = true }, + ["implementation"] = new JsonObject { ["linkSupport"] = true }, ["documentSymbol"] = new JsonObject { ["hierarchicalDocumentSymbolSupport"] = true }, ["hover"] = new JsonObject { ["contentFormat"] = new JsonArray("markdown", "plaintext") }, }, @@ -289,6 +303,12 @@ private string UriOf(string path) public async Task> DefinitionAsync(string path, int line, int character) => LspLocations.Parse(await RequestAsync("textDocument/definition", Position(path, line, character)).ConfigureAwait(false)); + /// What implements the interface, abstract member or type at and UTF-16 ; nothing from a server that can't say. + public async Task> ImplementationAsync(string path, int line, int character) => + FindsImplementations + ? LspLocations.Parse(await RequestAsync("textDocument/implementation", Position(path, line, character)).ConfigureAwait(false)) + : []; + /// What the server says the symbol at and UTF-16 is. public async Task> HoverAsync(string path, int line, int character) => LspHover.Parse(await RequestAsync("textDocument/hover", Position(path, line, character)).ConfigureAwait(false)); diff --git a/src/TuiCode.Workbench/Menus/CommandMenu.cs b/src/TuiCode.Workbench/Menus/CommandMenu.cs index cd779b25..96c1361f 100644 --- a/src/TuiCode.Workbench/Menus/CommandMenu.cs +++ b/src/TuiCode.Workbench/Menus/CommandMenu.cs @@ -58,7 +58,7 @@ .. Enumerable.Range(1, 9).Select(CommandIds.FocusEditorByIndex), [CommandIds.JoinGroups] = 'j', [CommandIds.ToggleFileHistory] = 'y', [CommandIds.RevealInExplorer] = 'x', [CommandIds.FocusAssistant] = 'a', [CommandIds.AiAssistance] = 'h', [CommandIds.ToggleToolCalls] = 'c', - [CommandIds.GoToLine] = 'g', [CommandIds.GoToSymbol] = 's', [CommandIds.GoToType] = 'y', [CommandIds.GoToMatchingBracket] = 'm', [CommandIds.GoToDefinition] = 'd', [CommandIds.QuickInfo] = 'i', + [CommandIds.GoToLine] = 'g', [CommandIds.GoToSymbol] = 's', [CommandIds.GoToType] = 'y', [CommandIds.GoToMatchingBracket] = 'm', [CommandIds.GoToDefinition] = 'd', [CommandIds.GoToImplementation] = 'i', [CommandIds.QuickInfo] = 'q', [CommandIds.FindUsages] = 'f', [CommandIds.FollowLink] = 'l', [CommandIds.NavigateBack] = 'p', [CommandIds.NavigateForward] = 'n', [CommandIds.NextEditor] = 't', [CommandIds.PreviousEditor] = 'r', @@ -128,7 +128,7 @@ public static readonly (string Title, string[] Ids)[] Layout = ]), ("_Go", [ - CommandIds.GoToLine, CommandIds.GoToSymbol, CommandIds.GoToType, CommandIds.GoToMatchingBracket, CommandIds.GoToDefinition, CommandIds.QuickInfo, CommandIds.FindUsages, CommandIds.FollowLink, + CommandIds.GoToLine, CommandIds.GoToSymbol, CommandIds.GoToType, CommandIds.GoToMatchingBracket, CommandIds.GoToDefinition, CommandIds.GoToImplementation, CommandIds.QuickInfo, CommandIds.FindUsages, CommandIds.FollowLink, Separator, CommandIds.NavigateBack, CommandIds.NavigateForward, Separator, diff --git a/src/TuiCode.Workbench/Mnemonics/MnemonicResolver.cs b/src/TuiCode.Workbench/Mnemonics/MnemonicResolver.cs index 4d6f601d..55bafda7 100644 --- a/src/TuiCode.Workbench/Mnemonics/MnemonicResolver.cs +++ b/src/TuiCode.Workbench/Mnemonics/MnemonicResolver.cs @@ -9,18 +9,20 @@ public sealed record MnemonicEntry(string CommandId, string Mnemonic, string Lab /// /// As the user types, the dialog feeds the accumulated prefix here. /// drives the filtered hint list; decides when to fire a command -/// without waiting for Enter: only when the prefix is itself a complete mnemonic and no other -/// mnemonic shares it as a prefix. Because the -/// table is prefix-free, "exactly one match and it equals the prefix" captures that precisely. +/// without waiting for Enter: only when the prefix is itself a complete mnemonic and no longer +/// mnemonic starts with it. One that does (q under qi) runs on Enter (). /// public sealed class MnemonicResolver { private readonly IReadOnlyList _entries; + private readonly IReadOnlyList _every; - public MnemonicResolver(IEnumerable entries) + /// Every mnemonic, in scope or not, so hiding a longer one never makes a shorter one fire early. + public MnemonicResolver(IEnumerable entries, IEnumerable? every = null) { ArgumentNullException.ThrowIfNull(entries); _entries = entries.OrderBy(e => e.Mnemonic, StringComparer.Ordinal).ToList(); + _every = [.. (every ?? []).Concat(_entries.Select(e => e.Mnemonic))]; } /// Every entry, ordered by mnemonic — the dialog's initial (unfiltered) list. @@ -37,10 +39,12 @@ public IReadOnlyList Matching(string prefix) => /// matches nothing, or is still an incomplete/ambiguous lead-in (e.g. c while /// only cf exists, or f with fe/ft/f1… beneath it). /// - public MnemonicEntry? ResolveExact(string prefix) - { - if (string.IsNullOrEmpty(prefix)) return null; - var matches = Matching(prefix); - return matches.Count == 1 && matches[0].Mnemonic == prefix ? matches[0] : null; - } + public MnemonicEntry? ResolveExact(string prefix) => + Complete(prefix) is { } entry && !_every.Any(m => m.Length > prefix.Length && m.StartsWith(prefix, StringComparison.Ordinal)) + ? entry + : null; + + /// The entry whose mnemonic is exactly , whether or not a longer one starts with it. + public MnemonicEntry? Complete(string prefix) => + string.IsNullOrEmpty(prefix) ? null : _entries.FirstOrDefault(e => e.Mnemonic == prefix); } diff --git a/src/TuiCode.Workbench/Mnemonics/MnemonicView.cs b/src/TuiCode.Workbench/Mnemonics/MnemonicView.cs index 3b263892..0d708215 100644 --- a/src/TuiCode.Workbench/Mnemonics/MnemonicView.cs +++ b/src/TuiCode.Workbench/Mnemonics/MnemonicView.cs @@ -10,7 +10,8 @@ namespace TuiCode.Workbench.Mnemonics; /// hands it that set, so a command out of scope isn't listed, can't be reached, and can't capture a /// keystroke (#285). As the user types, the list filters to mnemonics with the typed prefix and the /// command fires the instant the prefix is unambiguous — no Enter needed (see -/// ). Esc cancels; Backspace edits. +/// ). Enter runs a complete mnemonic a longer one starts with +/// (q under qi). Esc cancels; Backspace edits. /// /// Unlike this captures raw keystrokes via a /// rather than a focused TextField. That keeps execution on the @@ -37,12 +38,12 @@ public sealed class MnemonicView : Window /// Fired after the view wants to be removed (Esc, or after a command was dispatched). public event EventHandler? Closed; - public MnemonicView(IEnumerable entries, Action execute) + public MnemonicView(IEnumerable entries, Action execute, IEnumerable? every = null) { ArgumentNullException.ThrowIfNull(entries); ArgumentNullException.ThrowIfNull(execute); - _resolver = new MnemonicResolver(entries); + _resolver = new MnemonicResolver(entries, every); _execute = execute; _scope = new KeyCaptureScope(OnKey); @@ -95,12 +96,11 @@ private void OnKey(Key key) return; } - // Enter commits the lone remaining match. Useful for a reserved family with a single - // member today (e.g. "c" → "cf"): you needn't type the second key once it's unambiguous. + // Enter runs the complete mnemonic typed, else the lone remaining match ("c" → "cf"). if (key == Key.Enter) { - if (_visible.Count == 1) - Execute(_visible[0]); + if ((_resolver.Complete(_input.ToString()) ?? (_visible.Count == 1 ? _visible[0] : null)) is { } entry) + Execute(entry); return; } diff --git a/src/TuiCode.Workbench/Navigation/DefinitionPickerView.cs b/src/TuiCode.Workbench/Navigation/DefinitionPickerView.cs index d87eaa00..a74e64c7 100644 --- a/src/TuiCode.Workbench/Navigation/DefinitionPickerView.cs +++ b/src/TuiCode.Workbench/Navigation/DefinitionPickerView.cs @@ -15,13 +15,13 @@ public string Display(int placeWidth, int width) } } -/// Picks one of several definitions, such as a partial class's; the host does the move once it closes. +/// Picks one of several definitions or implementations, such as a partial class's; the host does the move once it closes. public sealed class DefinitionPickerView : PickerDialog { private const int DialogWidth = 66; - public DefinitionPickerView(string symbol, IReadOnlyList rows) - : base($"Definitions of {symbol}", DialogWidth, Math.Min(18, rows.Count + 4), rows, r => $"{r.Place} {r.Code}", "Go to", + public DefinitionPickerView(string title, IReadOnlyList rows) + : base(title, DialogWidth, Math.Min(18, rows.Count + 4), rows, r => $"{r.Place} {r.Code}", "Go to", r => r.Display(rows.Max(d => d.Place.Length), PickerList.Width(DialogWidth))) { Commands.Register(CancelId, "Cancel", ClearOrCancel); diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index 5f37f4d5..6bddb574 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -764,6 +764,7 @@ private void RegisterDefaultCommands() _commands.Register(CommandIds.GoToMatchingBracket, "Go to matching bracket", GoToMatchingBracket, CommandScope.Editor, FileOpen); // Enabled without a ready server, so the key can say what's missing; the menu dims it (IsAvailableFrom). _commands.Register(CommandIds.GoToDefinition, "Go to definition", GoToDefinition, CommandScope.Editor, FileOpen); + _commands.Register(CommandIds.GoToImplementation, "Go to implementation", GoToImplementation, CommandScope.Editor, FileOpen); _commands.Register(CommandIds.QuickInfo, "Quick info", ShowQuickInfo, CommandScope.Editor, FileOpen); _commands.Register(CommandIds.FindUsages, "Find usages", FindUsages, CommandScope.Editor, FileOpen); // Global and ungated, so with no agent installed it can say so (#566). @@ -1116,7 +1117,8 @@ private static void BindDefaults(IKeybindingService keybindings) keybindings.Bind("Ctrl+G A", CommandIds.AiAssistance); keybindings.Bind("Ctrl+G D", CommandIds.GoToDefinition); keybindings.Bind("Ctrl+G T", CommandIds.GoToType); - keybindings.Bind("Ctrl+G I", CommandIds.QuickInfo); + keybindings.Bind("Ctrl+G I", CommandIds.GoToImplementation); + keybindings.Bind("Ctrl+G Q", CommandIds.QuickInfo); keybindings.Bind("Ctrl+G U", CommandIds.FindUsages); keybindings.Bind("Enter", CommandIds.AssistantSend); keybindings.Bind("Ctrl+H", CommandIds.AssistantStop); @@ -1527,7 +1529,7 @@ private bool IsAvailableFrom(string id, FocusRegion region) { var scope = _commands.ScopeOf(id); return (scope == CommandScope.Global || scope == FocusService.ScopeOf(region)) && _commands.IsEnabled(id) - && (id is not (CommandIds.GoToDefinition or CommandIds.QuickInfo or CommandIds.FindUsages) || ActiveLanguageServer() is { State: LanguageServerState.Ready }); + && (id is not (CommandIds.GoToDefinition or CommandIds.GoToImplementation or CommandIds.QuickInfo or CommandIds.FindUsages) || ActiveLanguageServer() is { State: LanguageServerState.Ready }); } private LanguageServer? ActiveLanguageServer() => @@ -1553,7 +1555,7 @@ private void OpenMnemonics() var fromExplorer = _workbench.Sidebar.Explorer.HasFocus; var entries = MnemonicsInScope(_commands, FocusedScope()); - var view = new MnemonicView(entries, commandId => RunLaunched(commandId, fromExplorer)); + var view = new MnemonicView(entries, commandId => RunLaunched(commandId, fromExplorer), CommandMnemonics.All.Select(m => m.Value)); view.Closed += (_, _) => CloseMnemonics(view); _activeMnemonics = view; _workbench.Add(view); @@ -1761,11 +1763,61 @@ private void GoToDefinition() else { var (locations, sources, called) = answer.Result; - ShowDefinitions(tab, symbol, Overload(tab.File.FileSystem, Decompile(server, locations, sources), called)); + ShowLocations(tab, Overload(tab.File.FileSystem, Decompile(server, locations, sources), called), + symbol is null ? "Nothing to go to here" : $"No definition found for {symbol}", $"Definitions of {symbol ?? "symbol"}"); } }), TaskScheduler.Default); } + /// Go to implementation (gi): the code behind the interface, abstract member or type under the cursor. + private void GoToImplementation() + { + if (_workbench.Editor.Group.ActiveTab is not { } tab || ReadyLanguageServer(tab) is not { } server) return; + var status = _workbench.StatusBar; + if (!server.FindsImplementations) + { + status.ShowMessage($"{server.Title} can't find implementations"); + return; + } + var symbol = IdentifierAt(tab.Lines[tab.CursorRow], tab.CursorCharacter); + var request = ++_definitionRequest; + ImplementationsAsync(server, tab.File.FullName, tab.CursorRow, tab.CursorCharacter, symbol).ContinueWith(answer => _app.Invoke(() => + { + if (_disposed || request != _definitionRequest) return; + if (answer.Exception?.InnerException is { } error) status.ShowMessage($"Go to implementation failed: {error.Message}", Severity.Error); + else + { + var (name, locations, sources) = answer.Result; + ShowLocations(tab, Decompile(server, locations, sources), + name is null ? "Nothing to go to here" : $"No implementations of {name}", $"Implementations of {name ?? "symbol"}"); + } + }), TaskScheduler.Default); + } + + /// + /// The implementations, csharp-ls's decompiled source for each csharp:/ one, and the symbol named after its type. + /// The declaration itself is left out: csharp-ls answers with it when nothing implements it. + /// + private static async Task<(string? Name, IReadOnlyList Locations, Dictionary Sources)> ImplementationsAsync( + LanguageServer server, string path, int row, int character, string? symbol) + { + var found = await server.ImplementationAsync(path, row, character).ConfigureAwait(false); + IReadOnlyList definitions = []; + string? name = null; + try + { + definitions = await server.DefinitionAsync(path, row, character).ConfigureAwait(false); + if (symbol is not null && definitions is [var definition, ..]) + name = await server.SymbolNameAsync(definition).ConfigureAwait(false); + } + catch (Exception e) when (e is JsonRpcException or IOException) { } + var locations = found.Where(l => !definitions.Contains(l)).ToList(); + var sources = new Dictionary(StringComparer.Ordinal); + foreach (var uri in locations.Select(l => l.Path).Where(LspLocations.IsDecompiled).Distinct()) + sources[uri] = await server.DecompiledAsync(uri).ConfigureAwait(false); + return (name ?? symbol, locations, sources); + } + /// The definitions, csharp-ls's decompiled source for each csharp:/ one (#610), and which overload was called. private static async Task<(IReadOnlyList Locations, Dictionary Sources, string? Called)> DefinitionsAsync( LanguageServer server, string path, int row, int character) @@ -1958,14 +2010,14 @@ private IReadOnlyList LinesOf(IFileSystem fileSystem, string path) => ? open.Lines : [.. fileSystem.File.ReadLines(path)]; - private void ShowDefinitions(EditorTab origin, string? symbol, IReadOnlyList locations) + private void ShowLocations(EditorTab origin, IReadOnlyList locations, string none, string title) { var fileSystem = origin.File.FileSystem; locations = [.. locations.Where(l => fileSystem.File.Exists(l.Path))]; switch (locations) { case []: - _workbench.StatusBar.ShowMessage(symbol is null ? "Nothing to go to here" : $"No definition found for {symbol}"); + _workbench.StatusBar.ShowMessage(none); return; case [var only]: JumpToDefinition(origin, only); @@ -1975,7 +2027,7 @@ private void ShowDefinitions(EditorTab origin, string? symbol, IReadOnlyList new DefinitionRow(l, $"{_workbench.Decompiled?.At(l.Path)?.Place ?? DisplayPath(l.Path, root)}:{l.Line + 1}", LineAt(fileSystem, l).Trim())).ToList(); - var view = new DefinitionPickerView(symbol ?? "symbol", rows); + var view = new DefinitionPickerView(title, rows); _activeDefinitionPicker = view; HostedDialog.Show(_workbench, _scopes, view, () => { diff --git a/tests/TuiCode.Tests/CommandMnemonicsTests.cs b/tests/TuiCode.Tests/CommandMnemonicsTests.cs index 2a1c5c55..f280caf8 100644 --- a/tests/TuiCode.Tests/CommandMnemonicsTests.cs +++ b/tests/TuiCode.Tests/CommandMnemonicsTests.cs @@ -1,4 +1,5 @@ using TuiCode.Abstractions; +using TuiCode.Workbench.Mnemonics; namespace TuiCode.Tests; @@ -11,19 +12,24 @@ public void Mnemonics_are_unique() Assert.Equal(mnemonics.Count, mnemonics.Distinct().Count()); } - // The auto-execute rule (MnemonicResolver.ResolveExact) only works if no complete - // mnemonic is a prefix of another — otherwise the shorter one could never fire without Enter. [Fact] - public void No_mnemonic_is_a_prefix_of_another() + public void Every_mnemonic_is_reachable_and_only_q_needs_Enter() { - var mnemonics = CommandMnemonics.All.Select(kv => kv.Value).ToList(); - foreach (var a in mnemonics) - foreach (var b in mnemonics) + var entries = CommandMnemonics.All.Select(kv => new MnemonicEntry(kv.Key, kv.Value, kv.Key)).ToList(); + var needsEnter = new List(); + foreach (var entry in entries) + { + var ran = new List(); + using var view = new MnemonicView(entries, ran.Add); + foreach (var c in entry.Mnemonic) view.Scope.Handle(new Key(c)); + if (ran.Count == 0) { - if (ReferenceEquals(a, b) || a == b) continue; - Assert.False(b.StartsWith(a, StringComparison.Ordinal), - $"Mnemonic '{a}' is a prefix of '{b}' — one of them would be unreachable."); + needsEnter.Add(entry.Mnemonic); + view.Scope.Handle(Key.Enter); } + Assert.Equal([entry.CommandId], ran); + } + Assert.Equal(["q"], needsEnter); } [Fact] @@ -56,6 +62,8 @@ public void For_returns_the_agreed_mnemonics() Assert.Equal("rg", CommandMnemonics.For(CommandIds.ReplaceGlobally)); Assert.Equal("tui", CommandMnemonics.For(CommandIds.ShowAbout)); Assert.Equal("sts", CommandMnemonics.For(CommandIds.SuspendToShell)); + Assert.Equal("gi", CommandMnemonics.For(CommandIds.GoToImplementation)); + Assert.Equal("qi", CommandMnemonics.For(CommandIds.QuickInfo)); } [Fact] diff --git a/tests/TuiCode.Tests/DecompiledSourceHostTests.cs b/tests/TuiCode.Tests/DecompiledSourceHostTests.cs index 1fabaf05..6f36beb6 100644 --- a/tests/TuiCode.Tests/DecompiledSourceHostTests.cs +++ b/tests/TuiCode.Tests/DecompiledSourceHostTests.cs @@ -57,6 +57,30 @@ public DecompiledSourceHostTests() _server.Undecompilable.Add(SecretUri); } + [Fact] + public async Task Gi_to_an_implementation_in_a_library_opens_its_decompiled_source_read_only() + { + const string clock = "class Clock\n{\n void Go(IClock c) { c.Now(); }\n}\n"; + _fs.AddFile("/work/Clock.cs", new MockFileData(clock)); + _server.Files[_fs.Path.GetFullPath("/work/Clock.cs")] = clock; + _server.Library["csharp:/work/App.csproj/decompiled/System.SystemClock.cs"] = new DecompiledSource("System.Runtime", "System.SystemClock", + "namespace System;\n\npublic class SystemClock : IClock\n{\n public int Now() => 1;\n}\n"); + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + (string Title, int Row, int Column, bool ReadOnly) opened = default; + var resting = ""; + + await HostSteps.Run(host, + () => workbench.OpenFile(_fs.FileInfo.New("/work/Clock.cs")), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(2, 27); Execute(host, Key.I); }, + () => Tab(workbench).ReadOnly, + () => { opened = (Tab(workbench).Title, Tab(workbench).CursorRow, Tab(workbench).CursorColumn, Tab(workbench).ReadOnly); resting = workbench.StatusBar.DisplayedText; }); + + Assert.Equal(("SystemClock.cs [decompiled]", 4, 15, true), opened); + Assert.Equal("Decompiled from System.Runtime, read-only", resting); + } + [Fact] public async Task Gd_on_a_library_type_opens_its_decompiled_source_read_only_on_its_declaration_and_gp_goes_back() { diff --git a/tests/TuiCode.Tests/FakeLanguageServer.cs b/tests/TuiCode.Tests/FakeLanguageServer.cs index a158b2cc..cc8dbafd 100644 --- a/tests/TuiCode.Tests/FakeLanguageServer.cs +++ b/tests/TuiCode.Tests/FakeLanguageServer.cs @@ -9,12 +9,22 @@ namespace TuiCode.Tests; /// Launches in-process fake language servers. Each keeps the documents it's told about, and answers a definition /// with every declaration (class X, void X, ...) of the word at the position, in those documents and /// in . References are every other whole-word use of it, and document symbols the file's first class -/// with its methods. +/// with its methods. Implementations of a type are the classes naming it after their :, and of a member its +/// declarations with a body; with none, it answers with the declaration, as csharp-ls does. /// internal sealed partial class FakeLanguageServer : ILanguageServerLauncher { private readonly ConcurrentQueue<(string Method, JsonNode? Params)> _received = new(); + /// Whether initialize says it answers textDocument/implementation. + public bool FindsImplementations { get; set; } = true; + + /// The serverInfo.name initialize gives, if any. + public string? ServerName { get; set; } + + /// Answers implementations as LocationLinks rather than Locations. + public bool ImplementationLinks { get; set; } + /// Not installed: every launch fails. public bool Missing { get; set; } @@ -146,7 +156,8 @@ private void Progress(InProcessServer server, string kind) => return method switch { "initialize" when InitializeError is { } error => throw new JsonRpcException(-32603, error), - "initialize" => new JsonObject { ["capabilities"] = new JsonObject { ["definitionProvider"] = true } }, + "initialize" => Initialized(), + "textDocument/implementation" => Implementations(parameters!), "textDocument/definition" => Definitions(parameters!), "textDocument/references" => References(parameters!), "textDocument/documentSymbol" => Symbols(parameters!), @@ -182,6 +193,44 @@ private void OnNotification(InProcessServer server, string method, JsonNode? par _received.Enqueue((method, parameters?.DeepClone())); } + private JsonObject Initialized() + { + var capabilities = new JsonObject { ["definitionProvider"] = true }; + if (FindsImplementations) capabilities["implementationProvider"] = new JsonObject(); + var result = new JsonObject { ["capabilities"] = capabilities }; + if (ServerName is not null) result["serverInfo"] = new JsonObject { ["name"] = ServerName }; + return result; + } + + private JsonArray Implementations(JsonNode parameters) + { + if (WordAt(parameters) is not { } word) return []; + var name = Regex.Escape(word); + var found = new JsonArray(); + foreach (var (file, text) in Sources().OrderBy(s => s.Key, StringComparer.Ordinal)) + { + var fileLines = Lines(text); + for (var row = 0; row < fileLines.Length; row++) + { + var match = Regex.Match(fileLines[row], $@"\bclass\s+(\w+)\s*:[^{{]*\b{name}\b"); + var at = match.Success ? match.Groups[1] : null; + if (at is null && Regex.Match(fileLines[row], $@"\b(?:void|int|string)\s+({name})\s*\([^;]*(?:=>|\{{)") is { Success: true } member) + at = member.Groups[1]; + if (at is null) continue; + var location = Location(file, row, at.Index, at.Length); + found.Add(ImplementationLinks + ? new JsonObject + { + ["targetUri"] = location["uri"]!.DeepClone(), + ["targetRange"] = location["range"]!.DeepClone(), + ["targetSelectionRange"] = location["range"]!.DeepClone(), + } + : location); + } + } + return found.Count > 0 ? found : Definitions(parameters); + } + private JsonArray Definitions(JsonNode parameters) { var path = Path(parameters["textDocument"]!); @@ -297,7 +346,7 @@ private JsonArray Symbols(JsonNode parameters) var members = new JsonArray(); for (var row = 0; row < lines.Length; row++) { - if (type is null && Regex.Match(lines[row], @"\bclass\s+(\w+)") is { Success: true } declaration) + if (type is null && Regex.Match(lines[row], @"\b(?:class|interface)\s+(\w+)") is { Success: true } declaration) type = Symbol(declaration.Groups[1].Value, 5, Range(0, 0, lines.Length, 0), Range(row, declaration.Groups[1].Index, row, declaration.Groups[1].Index + declaration.Groups[1].Length)); else if (type is not null && Regex.Match(lines[row], @"\b(?:void|int|string)\s+(\w+)\(") is { Success: true } member) members.Add(Symbol($"{member.Groups[1].Value}()", 6, Range(row, 0, row + 1, 0), Range(row, member.Groups[1].Index, row, member.Groups[1].Index + member.Groups[1].Length))); diff --git a/tests/TuiCode.Tests/GoToImplementationHostTests.cs b/tests/TuiCode.Tests/GoToImplementationHostTests.cs new file mode 100644 index 00000000..acd63fb8 --- /dev/null +++ b/tests/TuiCode.Tests/GoToImplementationHostTests.cs @@ -0,0 +1,316 @@ +using TuiCode.Abstractions; +using TuiCode.Explorer; +using TuiCode.Syntax; +using TuiCode.Workbench; +using TuiCode.Workbench.Help; +using TuiCode.Workbench.Languages; +using TuiCode.Workbench.Navigation; +using TuiCode.Workbench.Parts; +using TuiCode.Workbench.Services; + +namespace TuiCode.Tests; + +// Drives `gi` / Ctrl+G I (#699) through the host against a fake language server. Boots a TG Application — serialised (#77). +public class GoToImplementationHostTests : StaticConfigurationTest +{ + private const string Caller = """ + class Caller + { + void Go(IShape shape, IClock clock, INothing nothing) + { + var area = shape.Area(); + var now = clock.Now(); + nothing.Never(); + } + } + """; + + private static readonly string Clock = "class SystemClock : IClock\n{\n" + string.Concat(Enumerable.Repeat(" // padding\n", 40)) + + " public int Now() => 0;\n" + string.Concat(Enumerable.Repeat(" // padding\n", 40)) + "}\n"; + + private static readonly SyntaxHighlighter Syntax = new(GrammarBundle.Load()); + + private readonly MockFileSystem _fs = new(); + private readonly FakeLanguageServer _server = new(); + + public GoToImplementationHostTests() + { + Add("/work/Caller.cs", Caller); + Add("/work/IShape.cs", "interface IShape\n{\n int Area();\n}\n"); + Add("/work/IClock.cs", "interface IClock\n{\n int Now();\n}\n"); + Add("/work/INothing.cs", "interface INothing\n{\n int Never();\n}\n"); + Add("/work/Shapes/Square.cs", "class Square : IShape\n{\n public int Area() => 4;\n}\n"); + Add("/work/Shapes/Circle.cs", "class Circle : IShape\n{\n public int Area() => 3;\n}\n"); + Add("/work/Time/SystemClock.cs", Clock); + _fs.AddFile("/work/README.md", new MockFileData("# Read me")); + } + + [Fact] + public async Task Ctrl_G_I_on_a_call_with_one_implementation_goes_there_below_the_sticky_lines_and_Ctrl_G_P_comes_back() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + (string File, int Row, int Column) jumped = default, back = default; + var topRow = 0; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(5, 24); Execute(host); }, + () => Tab(workbench) is { File.Name: "SystemClock.cs", StickyScan.Done: true }, + () => { jumped = Where(workbench); topRow = Tab(workbench).TopRow; host.App.InjectKey(Key.G.WithCtrl); }, + () => host.App.InjectKey(Key.P), + () => Tab(workbench).File.Name == "Caller.cs", + () => { back = Where(workbench); }); + + Assert.Equal(("SystemClock.cs", 42, 15), jumped); + Assert.Equal(42 - 1 - 2, topRow); + Assert.Equal(("Caller.cs", 5, 24), back); + Assert.Equal("Caller.cs", _server.Received("textDocument/implementation").Select(p => Path.GetFileName(p!["textDocument"]!["uri"]!.GetValue())).Single()); + } + + [Fact] + public async Task The_mnemonic_gi_does_the_same() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(5, 24); host.App.InjectKey(Key.Space.WithCtrl); }, + () => host.App.InjectKey(Key.G), + () => host.App.InjectKey(Key.I), + () => Tab(workbench).File.Name == "SystemClock.cs"); + + Assert.Equal(("SystemClock.cs", 42, 15), Where(workbench)); + } + + [Fact] + public async Task Several_implementations_open_a_picker_named_after_the_member_and_Enter_goes_to_the_one_chosen() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + IReadOnlyList rows = []; + DefinitionPickerView? picker = null; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(4, 25); Execute(host); }, + () => (picker = Picker(workbench)) is not null, + () => { rows = picker!.VisibleItems; host.App.InjectKey(Key.CursorDown); }, + () => host.App.InjectKey(Key.Enter), + () => Picker(workbench) is null && Tab(workbench).File.Name == "Square.cs"); + + Assert.Equal("Implementations of IShape.Area", picker!.Title); + Assert.Equal([Path.Combine("Shapes", "Circle.cs") + ":3", Path.Combine("Shapes", "Square.cs") + ":3"], rows); + Assert.Equal(("Square.cs", 2, 15), Where(workbench)); + } + + [Fact] + public async Task Esc_in_the_picker_leaves_the_cursor_where_it_was() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(4, 25); Execute(host); }, + () => Picker(workbench) is not null, + () => host.App.InjectKey(Key.Esc), + () => Picker(workbench) is null); + + Assert.Equal(("Caller.cs", 4, 25), Where(workbench)); + } + + [Fact] + public async Task On_an_interface_name_it_lists_the_classes_that_implement_it() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + DefinitionPickerView? picker = null; + IReadOnlyList rows = []; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(2, 14); Execute(host); }, + () => (picker = Picker(workbench)) is not null, + () => { rows = picker!.VisibleItems; host.App.InjectKey(Key.Esc); }, + () => Picker(workbench) is null); + + Assert.Equal("Implementations of IShape", picker!.Title); + Assert.Equal([Path.Combine("Shapes", "Circle.cs") + ":1", Path.Combine("Shapes", "Square.cs") + ":1"], rows); + } + + [Fact] + public async Task With_nothing_implementing_it_the_status_bar_says_so() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(6, 17); Execute(host); }, + () => workbench.StatusBar.Message == "No implementations of INothing.Never"); + + Assert.Equal(("Caller.cs", 6, 17), Where(workbench)); + } + + [Theory] + [InlineData(null, "csharp-ls can't find implementations")] + [InlineData("Pyright", "Pyright can't find implementations")] + public async Task A_server_that_cant_find_implementations_is_never_asked_and_says_so(string? name, string message) + { + _server.FindsImplementations = false; + _server.ServerName = name; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { Tab(workbench).MoveCursor(5, 24); Execute(host); }, + () => workbench.StatusBar.Message == message); + + Assert.Empty(_server.Received("textDocument/implementation")); + Assert.Equal(("Caller.cs", 5, 24), Where(workbench)); + } + + [Fact] + public async Task Without_the_server_installed_it_says_what_Ctrl_G_D_says() + { + _server.Missing = true; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + string definition = "", implementation = ""; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => workbench.StatusBar.Bar.Current is not null, + () => { workbench.StatusBar.ShowMessage("elsewhere"); host.App.InjectKey(Key.G.WithCtrl); }, + () => host.App.InjectKey(Key.D), + () => { definition = workbench.StatusBar.DisplayedText; workbench.StatusBar.ShowMessage("elsewhere"); Execute(host); }, + () => { implementation = workbench.StatusBar.DisplayedText; }); + + Assert.Equal("No C# language server. Install: dotnet tool install -g csharp-ls", definition); + Assert.Equal(definition, implementation); + } + + [Fact] + public async Task While_loading_it_says_so_and_the_menu_dims_it_as_it_dims_Go_to_definition() + { + _server.HoldLoading = true; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + var pressed = ""; + (bool Definition, bool Implementation) whileLoading = default, whenReady = default; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => workbench.StatusBar.DisplayedState.Contains("C# ◌ loading", StringComparison.Ordinal), + () => Execute(host), + () => { pressed = workbench.StatusBar.Message; host.App.InjectKey(Key.G.WithAlt); }, + () => workbench.MenuBar.IsOpen(), + () => { whileLoading = Dimmed(host); host.App.InjectKey(Key.Esc); }, + () => !workbench.MenuBar.IsOpen(), + () => _server.FinishLoading(), + () => Ready(workbench), + () => host.App.InjectKey(Key.G.WithAlt), + () => workbench.MenuBar.IsOpen(), + () => { whenReady = Dimmed(host); host.App.InjectKey(Key.Esc); }, + () => !workbench.MenuBar.IsOpen()); + + Assert.Equal("The C# language server is still loading", pressed); + Assert.Equal((true, true), whileLoading); + Assert.Equal((false, false), whenReady); + } + + [Fact] + public async Task F1_in_the_editor_lists_it() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + KeysDialog? help = null; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => host.App.InjectKey(Key.F1), + () => (help = workbench.SubViews.OfType().SingleOrDefault()) is not null, + () => host.App.InjectKey(Key.Esc)); + + var rows = help!.Sheet.Here!.Rows(); + Assert.Contains(rows, r => r.Label == "Go to implementation" && r.Keys == "Ctrl+G i"); + Assert.Contains(rows, r => r.Label == "Quick info" && r.Keys == "Ctrl+G q"); + } + + [Fact] + public void Gi_is_on_Ctrl_G_I_in_the_editor_right_after_Go_to_definition_in_the_Go_menu() + { + using var workbench = BuildWorkbench(); + var commands = new CommandService(); + var keybindings = new KeybindingService(commands); + using var host = new WorkbenchHost(workbench, commands, keybindings, new InputScopeStack(), + new InMemorySettingsService(), driverName: DriverRegistry.Names.ANSI); + + Assert.Equal("Go to implementation", commands.Registered.Single(c => c.Id == CommandIds.GoToImplementation).Label); + Assert.Equal(CommandScope.Editor, commands.ScopeOf(CommandIds.GoToImplementation)); + Assert.Equal("gi", CommandMnemonics.For(CommandIds.GoToImplementation)); + Assert.Equal("Ctrl+G i", keybindings.Bindings.Single(b => b.CommandId == CommandIds.GoToImplementation).Display); + Assert.Single(keybindings.Bindings, b => b.Display == "Ctrl+G i"); + Assert.Single(keybindings.Bindings, b => b.Display == "Ctrl+G q"); + var go = host.Menu.Items.Select(i => i.Id).ToList(); + Assert.Equal(go.IndexOf(CommandIds.GoToDefinition) + 1, go.IndexOf(CommandIds.GoToImplementation)); + Assert.Equal('i', TuiCode.Workbench.Menus.CommandMenu.Letters[CommandIds.GoToImplementation]); + } + + private void Add(string path, string content) + { + _fs.AddFile(path, new MockFileData(content)); + _server.Files[_fs.Path.GetFullPath(path)] = content; + } + + private static bool Ready(Workbench.Workbench workbench) => + workbench.StatusBar.DisplayedState.Contains("C# ● ready", StringComparison.Ordinal); + + private static void Execute(WorkbenchHost host) + { + host.App.InjectKey(Key.G.WithCtrl); + host.App.InjectKey(Key.I); + } + + private static (bool, bool) Dimmed(WorkbenchHost host) => + (host.Menu.Items.Single(i => i.Id == CommandIds.GoToDefinition).Item.Dimmed, + host.Menu.Items.Single(i => i.Id == CommandIds.GoToImplementation).Item.Dimmed); + + private static (string File, int Row, int Column) Where(Workbench.Workbench workbench) => + (Tab(workbench).File.Name, Tab(workbench).CursorRow, Tab(workbench).CursorColumn); + + private static DefinitionPickerView? Picker(Workbench.Workbench workbench) => + workbench.SubViews.OfType().SingleOrDefault(); + + private void OpenFile(Workbench.Workbench workbench, string name) => + workbench.OpenFile(_fs.FileInfo.New($"/work/{name}")); + + private static TuiCode.Editor.EditorTab Tab(Workbench.Workbench workbench) => workbench.Editor.Group.ActiveTab!; + + private Workbench.Workbench BuildWorkbench() + { + var workbench = new Workbench.Workbench(new SidebarPart(new FileExplorerView()), new EditorPart(Syntax), new StatusBarPart()); + workbench.Sidebar.Explorer.Open(_fs.DirectoryInfo.New("/work")); + return workbench; + } + + private WorkbenchHost BuildHost(Workbench.Workbench workbench) + { + var commands = new CommandService(); + var host = new WorkbenchHost(workbench, commands, new KeybindingService(commands), new InputScopeStack(), + new InMemorySettingsService(), driverName: DriverRegistry.Names.ANSI, languageServers: _server); + HostSteps.PinScreenSize(host, 80, 25); + return host; + } +} diff --git a/tests/TuiCode.Tests/LanguageServerTests.cs b/tests/TuiCode.Tests/LanguageServerTests.cs index 79aa485b..615b0dc6 100644 --- a/tests/TuiCode.Tests/LanguageServerTests.cs +++ b/tests/TuiCode.Tests/LanguageServerTests.cs @@ -124,6 +124,64 @@ public async Task Definition_asks_at_the_position_and_reads_back_the_places() Assert.Equal([new SourceLocation(Path.GetFullPath("/work/Gadget.cs"), 2, 9)], found); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Implementation_asks_at_the_position_and_reads_back_locations_or_links(bool links) + { + _fake.ImplementationLinks = links; + _fake.Files[Path.GetFullPath("/work/IGadget.cs")] = "interface IGadget\n{\n void Run();\n}"; + _fake.Files[Path.GetFullPath("/work/Gadget.cs")] = "class Gadget : IGadget\n{\n public void Run() { }\n}"; + _fake.Files[Path.GetFullPath("/work/Gizmo.cs")] = "class Gizmo : IGadget\n{\n public void Run() => Spin();\n}"; + using var server = Server(); + var ready = Reached(server, LanguageServerState.Ready); + server.Open(Widget, "class Widget { void Go(IGadget g) { g.Run(); } }"); + server.Start(); + await ready.WaitAsync(Timeout); + + var found = await server.ImplementationAsync(Widget, 0, 39); + + Assert.True(server.FindsImplementations); + Assert.Equal([new SourceLocation(Path.GetFullPath("/work/Gadget.cs"), 2, 16), new SourceLocation(Path.GetFullPath("/work/Gizmo.cs"), 2, 16)], found); + var capability = _fake.Received("initialize").Single()!["capabilities"]!["textDocument"]!["implementation"]!; + Assert.True(capability["linkSupport"]!.GetValue()); + } + + [Fact] + public async Task A_server_that_doesnt_offer_implementations_is_never_asked_for_them() + { + _fake.FindsImplementations = false; + using var server = Server(); + var ready = Reached(server, LanguageServerState.Ready); + server.Open(Widget, "class Widget { void Go(IGadget g) { g.Run(); } }"); + server.Start(); + await ready.WaitAsync(Timeout); + + var found = await server.ImplementationAsync(Widget, 0, 39); + + Assert.False(server.FindsImplementations); + Assert.Empty(found); + Assert.DoesNotContain("textDocument/implementation", _fake.Methods); + } + + [Theory] + [InlineData(null, "csharp-ls")] + [InlineData("csharp-ls 0.16", "csharp-ls 0.16")] + public async Task Its_title_is_the_name_it_gives_else_the_name_TuiCode_knows_it_by(string? given, string title) + { + _fake.ServerName = given; + using var server = Server(); + var ready = Reached(server, LanguageServerState.Ready); + server.Start(); + await ready.WaitAsync(Timeout); + + Assert.Equal(title, server.Title); + } + + [Fact] + public void Pyright_is_called_Pyright_in_a_sentence() => + Assert.Equal("Pyright", new LanguageServerSpec("python", "Python", "pyright-langserver", ["--stdio"], null).Title); + [Fact] public async Task It_tells_the_server_it_can_show_decompiled_library_sources() { diff --git a/tests/TuiCode.Tests/MenuBarHostTests.cs b/tests/TuiCode.Tests/MenuBarHostTests.cs index c611baa1..4d6958c5 100644 --- a/tests/TuiCode.Tests/MenuBarHostTests.cs +++ b/tests/TuiCode.Tests/MenuBarHostTests.cs @@ -380,7 +380,7 @@ .. Arrive(workbench, commands, context), () => !workbench.MenuBar.IsOpen()]); // The exceptions: the palette keeps the language server's commands to say why they can't run, the menu dims them until a server is ready (#454). - var offered = MenuIds().Where(id => id is not (CommandIds.GoToDefinition or CommandIds.QuickInfo or CommandIds.FindUsages) && palette.Contains(commands.Registered.Single(c => c.Id == id).Title)); + var offered = MenuIds().Where(id => id is not (CommandIds.GoToDefinition or CommandIds.GoToImplementation or CommandIds.QuickInfo or CommandIds.FindUsages) && palette.Contains(commands.Registered.Single(c => c.Id == id).Title)); Assert.Equal(offered.Order(), undimmed.Order()); if (context == "pull request") Assert.Contains(CommandIds.SubmitReview, undimmed); if (context == "diff") Assert.Contains(CommandIds.RevertChange, undimmed); diff --git a/tests/TuiCode.Tests/MnemonicResolverTests.cs b/tests/TuiCode.Tests/MnemonicResolverTests.cs index a9fb25e2..6a5befcc 100644 --- a/tests/TuiCode.Tests/MnemonicResolverTests.cs +++ b/tests/TuiCode.Tests/MnemonicResolverTests.cs @@ -98,6 +98,32 @@ public void ResolveExact_still_waits_for_the_second_key_when_filtering_left_one_ Assert.Equal("cmd.renameFile", InScope().ResolveExact("mf")?.CommandId); } + [Fact] + public void ResolveExact_waits_on_a_mnemonic_a_longer_one_starts_with_and_Complete_gives_it() + { + var resolver = new MnemonicResolver([new("cmd.quit", "q", "Quit"), new("cmd.quickInfo", "qi", "Quick info")]); + + Assert.Null(resolver.ResolveExact("q")); + Assert.Equal("cmd.quit", resolver.Complete("q")?.CommandId); + Assert.Equal("cmd.quickInfo", resolver.ResolveExact("qi")?.CommandId); + } + + [Fact] + public void ResolveExact_still_waits_when_the_longer_one_is_out_of_scope() + { + var resolver = new MnemonicResolver([new("cmd.quit", "q", "Quit")], every: ["q", "qi"]); + + Assert.Null(resolver.ResolveExact("q")); + Assert.Equal("cmd.quit", resolver.Complete("q")?.CommandId); + } + + [Fact] + public void Complete_is_null_for_an_incomplete_prefix() + { + Assert.Null(Build().Complete("f")); + Assert.Null(Build().Complete("")); + } + private static MnemonicResolver InScope() => new(new[] { new MnemonicEntry("cmd.quit", "q", "Quit"), diff --git a/tests/TuiCode.Tests/MnemonicScopeHostTests.cs b/tests/TuiCode.Tests/MnemonicScopeHostTests.cs index 08d0cb75..e9af3b71 100644 --- a/tests/TuiCode.Tests/MnemonicScopeHostTests.cs +++ b/tests/TuiCode.Tests/MnemonicScopeHostTests.cs @@ -190,11 +190,8 @@ await HostSteps.Run(host, } /// - /// The guard that lets us narrow the list without carrying a second, unfiltered copy of the table: - /// over the real commands, no scope's subset makes fire - /// on a prefix the full set wouldn't. It holds because the table is prefix-free - /// (CommandMnemonicsTests.No_mnemonic_is_a_prefix_of_another) — if that ever stops being true, - /// this fails and the second table is back on the table. + /// Over the real commands, no scope's subset makes fire + /// on a prefix the full set wouldn't, given the whole table as the host gives it (#699). /// [Fact] public async Task Narrowing_the_list_never_makes_a_mnemonic_fire_a_keystroke_earlier() @@ -217,14 +214,32 @@ await HostSteps.Run(host, () => workbench.OpenFile(_fs.FileInfo.New("/work/a.txt Assert.NotEmpty(everything); foreach (var scope in Enum.GetValues()) { - var narrowed = new MnemonicResolver(WorkbenchHost.MnemonicsInScope(commands, scope)); + var narrowed = new MnemonicResolver(WorkbenchHost.MnemonicsInScope(commands, scope), CommandMnemonics.All.Select(m => m.Value)); foreach (var prefix in prefixes) Assert.True(narrowed.ResolveExact(prefix) is null || full.ResolveExact(prefix) is not null, - $"'{prefix}' fires in {scope} but not against every command — the mnemonic table is no " - + "longer prefix-free, so filtering the leader's list can no longer be safe on its own."); + $"'{prefix}' fires in {scope} but not against every command."); } } + [Fact] + public async Task Q_waits_for_Enter_even_where_qi_isnt_offered() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench, out var commands); + IReadOnlyList listed = []; + + await HostSteps.Run(host, + () => commands.TryExecute(CommandIds.FocusSidebar), + () => workbench.StatusBar.DisplayedFocus == "Explorer", + () => host.App.InjectKey(Key.Space.WithCtrl), + () => Leader(workbench) is not null, + () => host.App.InjectKey(Key.Q), + () => { listed = Leader(workbench)?.Mnemonics ?? []; host.App.InjectKey(Key.Esc); }, + () => Leader(workbench) is null); + + Assert.Equal(["q"], listed); + } + [Theory] [InlineData(true)] [InlineData(false)] diff --git a/tests/TuiCode.Tests/MnemonicViewTests.cs b/tests/TuiCode.Tests/MnemonicViewTests.cs index 3fbb7ce6..9a81e77f 100644 --- a/tests/TuiCode.Tests/MnemonicViewTests.cs +++ b/tests/TuiCode.Tests/MnemonicViewTests.cs @@ -63,6 +63,45 @@ public void Enter_commits_the_lone_remaining_match() Assert.Equal(["cmd.renameFile"], ran); } + [Fact] + public void Q_waits_listing_q_and_qi_and_Enter_quits() + { + var ran = new List(); + using var view = new MnemonicView([new("cmd.quit", "q", "Quit"), new("cmd.quickInfo", "qi", "Quick info")], ran.Add); + + Type(view, 'q'); + Assert.Empty(ran); + Assert.Equal(["q", "qi"], view.Mnemonics); + + view.Scope.Handle(Key.Enter); + Assert.Equal(["cmd.quit"], ran); + } + + [Fact] + public void Qi_runs_quick_info_without_Enter() + { + var ran = new List(); + using var view = new MnemonicView([new("cmd.quit", "q", "Quit"), new("cmd.quickInfo", "qi", "Quick info")], ran.Add); + + Type(view, 'q'); + Type(view, 'i'); + + Assert.Equal(["cmd.quickInfo"], ran); + } + + [Fact] + public void Enter_on_an_incomplete_prefix_with_several_matches_does_nothing() + { + var ran = new List(); + using var view = new MnemonicView([new("cmd.focusEditor", "fe", "Focus editor"), new("cmd.focusTabs", "ft", "Focus tabs")], ran.Add); + + Type(view, 'f'); + view.Scope.Handle(Key.Enter); + + Assert.Empty(ran); + Assert.Equal(["fe", "ft"], view.Mnemonics); + } + [Fact] public void Backspace_re_widens_the_list() { diff --git a/tests/TuiCode.Tests/PickerDialogsTests.cs b/tests/TuiCode.Tests/PickerDialogsTests.cs index aa1b847b..06b2ab7a 100644 --- a/tests/TuiCode.Tests/PickerDialogsTests.cs +++ b/tests/TuiCode.Tests/PickerDialogsTests.cs @@ -231,7 +231,7 @@ public void F1_asks_for_a_sheet_titled_with_the_dialog_listing_its_keys(string k RecentFolderList.Row("/Users/me/code/keyboards/vault", Home), ]); - private static DefinitionPickerView DefinitionPicker() => new("Widget", + private static DefinitionPickerView DefinitionPicker() => new("Definitions of Widget", [ new DefinitionRow(new SourceLocation("/work/Widget.Draw.cs", 2, 0), "Widget.Draw.cs:3", "partial class Widget"), new DefinitionRow(new SourceLocation("/work/Widget.cs", 0, 0), "Widget.cs:1", "partial class Widget"), diff --git a/tests/TuiCode.Tests/QuickInfoHostTests.cs b/tests/TuiCode.Tests/QuickInfoHostTests.cs index e545c653..9709ef36 100644 --- a/tests/TuiCode.Tests/QuickInfoHostTests.cs +++ b/tests/TuiCode.Tests/QuickInfoHostTests.cs @@ -12,7 +12,7 @@ namespace TuiCode.Tests; -// Drives `gi` / Ctrl+G I (#591) through the host against a fake language server. Boots a TG Application — serialised (#77). +// Drives `qi` / Ctrl+G Q (#591, #699) through the host against a fake language server. Boots a TG Application — serialised (#77). public class QuickInfoHostTests : StaticConfigurationTest { private const string Caller = """ @@ -390,7 +390,7 @@ await HostSteps.Run(host, } [Fact] - public void Gi_is_on_Ctrl_G_I_in_the_editor_right_after_Go_to_definition_in_the_Go_menu() + public void Qi_is_on_Ctrl_G_Q_in_the_editor_right_after_Go_to_implementation_in_the_Go_menu_with_hotkey_Q() { using var workbench = BuildWorkbench(); var commands = new CommandService(); @@ -400,10 +400,11 @@ public void Gi_is_on_Ctrl_G_I_in_the_editor_right_after_Go_to_definition_in_the_ Assert.Equal("Quick info", commands.Registered.Single(c => c.Id == CommandIds.QuickInfo).Label); Assert.Equal(CommandScope.Editor, commands.ScopeOf(CommandIds.QuickInfo)); - Assert.Equal("gi", CommandMnemonics.For(CommandIds.QuickInfo)); - Assert.Equal("Ctrl+G i", keybindings.Bindings.Single(b => b.CommandId == CommandIds.QuickInfo).Display); + Assert.Equal("qi", CommandMnemonics.For(CommandIds.QuickInfo)); + Assert.Equal("Ctrl+G q", keybindings.Bindings.Single(b => b.CommandId == CommandIds.QuickInfo).Display); var go = host.Menu.Items.Select(i => i.Id).ToList(); - Assert.Equal(go.IndexOf(CommandIds.GoToDefinition) + 1, go.IndexOf(CommandIds.QuickInfo)); + Assert.Equal(go.IndexOf(CommandIds.GoToImplementation) + 1, go.IndexOf(CommandIds.QuickInfo)); + Assert.Equal('q', TuiCode.Workbench.Menus.CommandMenu.Letters[CommandIds.QuickInfo]); } private void Add(string path, string content) @@ -418,7 +419,7 @@ private static bool Ready(Workbench.Workbench workbench) => private static void Execute(WorkbenchHost host) { host.App.InjectKey(Key.G.WithCtrl); - host.App.InjectKey(Key.I); + host.App.InjectKey(Key.Q); } private static QuickInfoView? Box(Workbench.Workbench workbench) => workbench.SubViews.OfType().SingleOrDefault(); From 30f3776c68ebdf4182819300245f4cf48a44e386 Mon Sep 17 00:00:00 2001 From: "a-team-app[bot]" <334837322+a-team-app[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:33:19 +1300 Subject: [PATCH 2/3] Treat csharp-ls's lone self-answer as no implementations Asked for the implementations of an interface member nothing implements, csharp-ls 0.28 answers with the member's own declaration, so gi jumped back to the interface instead of saying there are none. A single answer that is the definition the name comes from now counts as none. The fake server answers the same way, so the "nothing implements it" test covers it. Closes #699 Co-Authored-By: Claude Opus 5.5 --- src/TuiCode.Workbench/WorkbenchHost.cs | 4 ++-- tests/TuiCode.Tests/DecompiledSourceHostTests.cs | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index 6bddb574..fecc6d7b 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -1796,7 +1796,7 @@ private void GoToImplementation() /// /// The implementations, csharp-ls's decompiled source for each csharp:/ one, and the symbol named after its type. - /// The declaration itself is left out: csharp-ls answers with it when nothing implements it. + /// A lone answer that is the declaration itself counts as none: csharp-ls gives it when nothing implements it. /// private static async Task<(string? Name, IReadOnlyList Locations, Dictionary Sources)> ImplementationsAsync( LanguageServer server, string path, int row, int character, string? symbol) @@ -1811,7 +1811,7 @@ private void GoToImplementation() name = await server.SymbolNameAsync(definition).ConfigureAwait(false); } catch (Exception e) when (e is JsonRpcException or IOException) { } - var locations = found.Where(l => !definitions.Contains(l)).ToList(); + IReadOnlyList locations = found is [var only] && definitions is [var declared, ..] && only == declared ? [] : found; var sources = new Dictionary(StringComparer.Ordinal); foreach (var uri in locations.Select(l => l.Path).Where(LspLocations.IsDecompiled).Distinct()) sources[uri] = await server.DecompiledAsync(uri).ConfigureAwait(false); diff --git a/tests/TuiCode.Tests/DecompiledSourceHostTests.cs b/tests/TuiCode.Tests/DecompiledSourceHostTests.cs index 6f36beb6..9634bfc2 100644 --- a/tests/TuiCode.Tests/DecompiledSourceHostTests.cs +++ b/tests/TuiCode.Tests/DecompiledSourceHostTests.cs @@ -63,6 +63,7 @@ public async Task Gi_to_an_implementation_in_a_library_opens_its_decompiled_sour const string clock = "class Clock\n{\n void Go(IClock c) { c.Now(); }\n}\n"; _fs.AddFile("/work/Clock.cs", new MockFileData(clock)); _server.Files[_fs.Path.GetFullPath("/work/Clock.cs")] = clock; + _server.Files[_fs.Path.GetFullPath("/work/IClock.cs")] = "interface IClock\n{\n int Now();\n}\n"; _server.Library["csharp:/work/App.csproj/decompiled/System.SystemClock.cs"] = new DecompiledSource("System.Runtime", "System.SystemClock", "namespace System;\n\npublic class SystemClock : IClock\n{\n public int Now() => 1;\n}\n"); using var workbench = BuildWorkbench(); From 259bc6b0062190b352cc723b4305fdca9cdbc0c9 Mon Sep 17 00:00:00 2001 From: James Crosswell Date: Fri, 20 Nov 2026 13:25:30 +1300 Subject: [PATCH 3/3] Name known servers TuiCode's way, and ask for the definition alongside implementations The status bar uses KnownLanguageServers' title for a server TuiCode knows, and serverInfo.name only for one it doesn't, so "Pyright can't find implementations" no longer depends on what Pyright calls itself. gi now sends textDocument/definition alongside textDocument/implementation instead of after it, and skips documentSymbol when the answer is a single jump that never shows the name. Closes #699 Co-Authored-By: Claude Opus 5.5 --- .../Languages/LanguageServer.cs | 6 +++-- src/TuiCode.Workbench/WorkbenchHost.cs | 16 ++++++++------ tests/TuiCode.Tests/FakeLanguageServer.cs | 11 ++++++++++ .../GoToImplementationHostTests.cs | 22 ++++++++++++++++++- tests/TuiCode.Tests/LanguageServerTests.cs | 14 ++++++++---- 5 files changed, 55 insertions(+), 14 deletions(-) diff --git a/src/TuiCode.Workbench/Languages/LanguageServer.cs b/src/TuiCode.Workbench/Languages/LanguageServer.cs index 11c3fedb..66e4b608 100644 --- a/src/TuiCode.Workbench/Languages/LanguageServer.cs +++ b/src/TuiCode.Workbench/Languages/LanguageServer.cs @@ -67,7 +67,7 @@ public LanguageServer(LanguageServerSpec spec, string root, ILanguageServerLaunc /// Whether the server answers textDocument/implementation, as its initialize result says. public bool FindsImplementations { get; private set; } - /// What the server calls itself, or else what TuiCode knows it as. + /// What TuiCode knows the server as, or else what it calls itself. public string Title { get; private set; } public event EventHandler? StateChanged; @@ -104,7 +104,9 @@ private async Task InitializeAsync(JsonRpcConnection connection) { var initialized = await connection.RequestAsync("initialize", InitializeParams()).ConfigureAwait(false); FindsImplementations = initialized?["capabilities"]?["implementationProvider"]?.GetValueKind() is JsonValueKind.Object or JsonValueKind.True; - Title = initialized?["serverInfo"]?["name"]?.GetValue() is { Length: > 0 } name ? name : Spec.Title; + if (KnownLanguageServers.WithCommand(Spec.LanguageId, Spec.Command) is null + && initialized?["serverInfo"]?["name"]?.GetValue() is { Length: > 0 } name) + Title = name; } catch (Exception e) when (e is JsonRpcException or IOException) { diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index fecc6d7b..2814b5a2 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -1801,17 +1801,19 @@ private void GoToImplementation() private static async Task<(string? Name, IReadOnlyList Locations, Dictionary Sources)> ImplementationsAsync( LanguageServer server, string path, int row, int character, string? symbol) { - var found = await server.ImplementationAsync(path, row, character).ConfigureAwait(false); + var asked = server.ImplementationAsync(path, row, character); + var declaration = server.DefinitionAsync(path, row, character); + var found = await asked.ConfigureAwait(false); IReadOnlyList definitions = []; + try { definitions = await declaration.ConfigureAwait(false); } + catch (Exception e) when (e is JsonRpcException or IOException) { } + IReadOnlyList locations = found is [var only] && definitions is [var declared, ..] && only == declared ? [] : found; string? name = null; - try + if (locations is not [_] && symbol is not null && definitions is [var definition, ..]) { - definitions = await server.DefinitionAsync(path, row, character).ConfigureAwait(false); - if (symbol is not null && definitions is [var definition, ..]) - name = await server.SymbolNameAsync(definition).ConfigureAwait(false); + try { name = await server.SymbolNameAsync(definition).ConfigureAwait(false); } + catch (Exception e) when (e is JsonRpcException or IOException) { } } - catch (Exception e) when (e is JsonRpcException or IOException) { } - IReadOnlyList locations = found is [var only] && definitions is [var declared, ..] && only == declared ? [] : found; var sources = new Dictionary(StringComparer.Ordinal); foreach (var uri in locations.Select(l => l.Path).Where(LspLocations.IsDecompiled).Distinct()) sources[uri] = await server.DecompiledAsync(uri).ConfigureAwait(false); diff --git a/tests/TuiCode.Tests/FakeLanguageServer.cs b/tests/TuiCode.Tests/FakeLanguageServer.cs index cc8dbafd..c4eecfe3 100644 --- a/tests/TuiCode.Tests/FakeLanguageServer.cs +++ b/tests/TuiCode.Tests/FakeLanguageServer.cs @@ -51,6 +51,9 @@ internal sealed partial class FakeLanguageServer : ILanguageServerLauncher public string? HoldHoverOf { get; set; } + /// Holds every implementation request until it's set, while answering the rest. + public ManualResetEventSlim? HoldImplementation { get; set; } + /// Answers workspace/symbol as WorkspaceSymbol[] rather than SymbolInformation[]. public bool WorkspaceSymbols { get; set; } @@ -108,6 +111,14 @@ internal sealed partial class FakeLanguageServer : ILanguageServerLauncher return Answer(server, method, parameters); }) : Task.FromResult(Answer(server, method, parameters)); + if (HoldImplementation is { } holdImplementation) + server.Connection.AsyncRequestHandler = (method, parameters) => method == "textDocument/implementation" + ? Task.Run(() => + { + holdImplementation.Wait(TimeSpan.FromSeconds(30)); + return Answer(server, method, parameters); + }) + : Task.FromResult(Answer(server, method, parameters)); if (HoldWorkspaceSymbol is { } held) server.Connection.AsyncRequestHandler = (method, parameters) => method == "workspace/symbol" ? Task.Run(() => diff --git a/tests/TuiCode.Tests/GoToImplementationHostTests.cs b/tests/TuiCode.Tests/GoToImplementationHostTests.cs index acd63fb8..3e2270a0 100644 --- a/tests/TuiCode.Tests/GoToImplementationHostTests.cs +++ b/tests/TuiCode.Tests/GoToImplementationHostTests.cs @@ -69,6 +69,26 @@ await HostSteps.Run(host, Assert.Equal("Caller.cs", _server.Received("textDocument/implementation").Select(p => Path.GetFileName(p!["textDocument"]!["uri"]!.GetValue())).Single()); } + [Fact] + public async Task It_asks_for_the_definition_without_waiting_for_the_implementations_and_a_single_jump_skips_the_name() + { + using var release = new ManualResetEventSlim(); + _server.HoldImplementation = release; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + var symbolsBefore = 0; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Caller.cs"), + () => Ready(workbench), + () => { symbolsBefore = _server.Received("textDocument/documentSymbol").Count(); Tab(workbench).MoveCursor(5, 24); Execute(host); }, + () => _server.Received("textDocument/definition").Any(), + () => release.Set(), + () => Tab(workbench).File.Name == "SystemClock.cs"); + + Assert.Equal(symbolsBefore, _server.Received("textDocument/documentSymbol").Count()); + } + [Fact] public async Task The_mnemonic_gi_does_the_same() { @@ -162,7 +182,7 @@ await HostSteps.Run(host, [Theory] [InlineData(null, "csharp-ls can't find implementations")] - [InlineData("Pyright", "Pyright can't find implementations")] + [InlineData("csharp-ls 0.16", "csharp-ls can't find implementations")] public async Task A_server_that_cant_find_implementations_is_never_asked_and_says_so(string? name, string message) { _server.FindsImplementations = false; diff --git a/tests/TuiCode.Tests/LanguageServerTests.cs b/tests/TuiCode.Tests/LanguageServerTests.cs index 615b0dc6..791b7c05 100644 --- a/tests/TuiCode.Tests/LanguageServerTests.cs +++ b/tests/TuiCode.Tests/LanguageServerTests.cs @@ -165,12 +165,18 @@ public async Task A_server_that_doesnt_offer_implementations_is_never_asked_for_ } [Theory] - [InlineData(null, "csharp-ls")] - [InlineData("csharp-ls 0.16", "csharp-ls 0.16")] - public async Task Its_title_is_the_name_it_gives_else_the_name_TuiCode_knows_it_by(string? given, string title) + [InlineData("csharp-ls", null, "csharp-ls")] + [InlineData("csharp-ls", "csharp-ls 0.16", "csharp-ls")] + [InlineData("my-lsp", null, "my-lsp")] + [InlineData("my-lsp", "My LSP", "My LSP")] + public async Task Its_title_is_the_name_TuiCode_knows_it_by_else_the_name_it_gives(string command, string? given, string title) { _fake.ServerName = given; - using var server = Server(); + using var server = new LanguageServer(LanguageServerSpec.CSharp with { Command = command }, Root, _fake, action => action()) + { + QuietLoad = TimeSpan.FromMinutes(1), + StopTimeout = Timeout, + }; var ready = Reached(server, LanguageServerState.Ready); server.Start(); await ready.WaitAsync(Timeout);