From 5ab17ebc5ba4c0a3b5cceb13d6ecf64378a31b8b Mon Sep 17 00:00:00 2001 From: "a-team-app[bot]" <334837322+a-team-app[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:02:23 +1300 Subject: [PATCH 1/6] Add Rename symbol (rs): rename across the workspace through the language server Asks textDocument/prepareRename where the server advertises prepareProvider, then opens a prompt on the name it gives. Ctrl+Enter sends textDocument/rename and reads the WorkspaceEdit from documentChanges or changes, text edits only. Open tabs take their part as one ReplaceLines each, so one undo step, left unsaved; files that aren't open are written after a confirm, keeping their BOM and line endings, and the server is told they changed. A tab edited or a file changed on disk since the server was asked is skipped and named on the status bar. The Usages tab lists one row per changed line afterwards. Closes #697 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + src/TuiCode.Abstractions/CommandIds.cs | 1 + src/TuiCode.Abstractions/CommandMnemonics.cs | 1 + .../Languages/LanguageServer.cs | 44 +- src/TuiCode.Workbench/Languages/LspRename.cs | 63 +++ src/TuiCode.Workbench/Languages/TextEdits.cs | 73 ++++ src/TuiCode.Workbench/Menus/CommandMenu.cs | 4 +- .../Rename/RenameSymbolView.cs | 60 +++ .../Rename/WorkspaceRename.cs | 112 +++++ src/TuiCode.Workbench/Usages/UsagesView.cs | 10 +- src/TuiCode.Workbench/WorkbenchHost.cs | 117 +++++- tests/TuiCode.Tests/FakeLanguageServer.cs | 81 +++- tests/TuiCode.Tests/LanguageServerTests.cs | 98 +++++ tests/TuiCode.Tests/LspRenameTests.cs | 79 ++++ tests/TuiCode.Tests/MenuBarHostTests.cs | 2 +- tests/TuiCode.Tests/RenameSymbolHostTests.cs | 385 ++++++++++++++++++ tests/TuiCode.Tests/TextEditsTests.cs | 57 +++ tests/TuiCode.Tests/WorkspaceRenameTests.cs | 121 ++++++ 18 files changed, 1301 insertions(+), 8 deletions(-) create mode 100644 src/TuiCode.Workbench/Languages/LspRename.cs create mode 100644 src/TuiCode.Workbench/Languages/TextEdits.cs create mode 100644 src/TuiCode.Workbench/Rename/RenameSymbolView.cs create mode 100644 src/TuiCode.Workbench/Rename/WorkspaceRename.cs create mode 100644 tests/TuiCode.Tests/LspRenameTests.cs create mode 100644 tests/TuiCode.Tests/RenameSymbolHostTests.cs create mode 100644 tests/TuiCode.Tests/TextEditsTests.cs create mode 100644 tests/TuiCode.Tests/WorkspaceRenameTests.cs diff --git a/AGENTS.md b/AGENTS.md index cff91161..81068d00 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -474,6 +474,7 @@ What follows is how TuiCode implements it today. - **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`. - **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. +- **Rename symbol** (`rs`, no default key, `Editor` scope, in the Edit menu, #697) asks the server for `textDocument/prepareRename` where it advertises `prepareProvider`, and opens `RenameSymbolView` on the name it gives; a `null` answer, an error, or a server with no `renameProvider` is a status-bar line instead. `Ctrl+Enter` sends `textDocument/rename`, whose `WorkspaceEdit` `LspRename` reads from `documentChanges` or `changes`, text edits only. `WorkspaceRename` splits it: open tabs get one `ReplaceLines` each (one undo step, left unsaved), and files that aren't open are written as UTF-8 with their BOM and line endings kept, after a confirm. A tab edited, or a file changed on disk, since the server was asked is left alone and named on the status bar. The Usages tab then lists one row per changed line under `Renamed A → B · n in m files`. It's dimmed in the menu like `gd`. F1 doesn't list it while it has no key, like every unbound command. - 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. ## Language servers (#454) diff --git a/src/TuiCode.Abstractions/CommandIds.cs b/src/TuiCode.Abstractions/CommandIds.cs index 826eb56e..e694fc28 100644 --- a/src/TuiCode.Abstractions/CommandIds.cs +++ b/src/TuiCode.Abstractions/CommandIds.cs @@ -99,6 +99,7 @@ public static class CommandIds public const string QuickInfoPageUp = "quickInfo.action.pageUp"; public const string QuickInfoPageDown = "quickInfo.action.pageDown"; public const string FindUsages = "workbench.action.findUsages"; + public const string RenameSymbol = "workbench.action.renameSymbol"; public const string AiAssistance = "workbench.action.aiAssistance"; public const string FocusAssistant = "workbench.action.focusAssistant"; public const string AssistantSend = "assistant.action.send"; diff --git a/src/TuiCode.Abstractions/CommandMnemonics.cs b/src/TuiCode.Abstractions/CommandMnemonics.cs index 80f12183..7daa3b57 100644 --- a/src/TuiCode.Abstractions/CommandMnemonics.cs +++ b/src/TuiCode.Abstractions/CommandMnemonics.cs @@ -140,6 +140,7 @@ private static IReadOnlyDictionary Build() [CommandIds.ReplaceInFile] = "rf", [CommandIds.FindGlobally] = "fg", [CommandIds.ReplaceGlobally] = "rg", + [CommandIds.RenameSymbol] = "rs", }; // f1..f9 mirror the Ctrl+D1..Ctrl+D9 "focus editor tab N" bindings. Digits don't diff --git a/src/TuiCode.Workbench/Languages/LanguageServer.cs b/src/TuiCode.Workbench/Languages/LanguageServer.cs index 6f715b62..830d8e52 100644 --- a/src/TuiCode.Workbench/Languages/LanguageServer.cs +++ b/src/TuiCode.Workbench/Languages/LanguageServer.cs @@ -37,6 +37,7 @@ public sealed class LanguageServer : IDisposable private bool _initialized; private bool _loaded; private bool _stopping; + private JsonNode? _renameProvider; public LanguageServer(LanguageServerSpec spec, string root, ILanguageServerLauncher launcher, Action post) { @@ -91,7 +92,8 @@ private async Task InitializeAsync(JsonRpcConnection connection) { try { - await connection.RequestAsync("initialize", InitializeParams()).ConfigureAwait(false); + var answer = await connection.RequestAsync("initialize", InitializeParams()).ConfigureAwait(false); + lock (_gate) _renameProvider = answer?["capabilities"]?["renameProvider"]?.DeepClone(); } catch (Exception e) when (e is JsonRpcException or IOException) { @@ -131,6 +133,7 @@ private JsonObject InitializeParams() ["workspace"] = new JsonObject { ["workspaceFolders"] = true, + ["workspaceEdit"] = new JsonObject { ["documentChanges"] = true }, ["configuration"] = true, ["symbol"] = new JsonObject { @@ -144,6 +147,7 @@ private JsonObject InitializeParams() ["definition"] = new JsonObject { ["linkSupport"] = true }, ["documentSymbol"] = new JsonObject { ["hierarchicalDocumentSymbolSupport"] = true }, ["hover"] = new JsonObject { ["contentFormat"] = new JsonArray("markdown", "plaintext") }, + ["rename"] = new JsonObject { ["prepareSupport"] = true }, }, ["experimental"] = new JsonObject { ["csharp"] = new JsonObject { ["metadataUris"] = true } }, }, @@ -311,6 +315,44 @@ public async Task> ReferencesAsync(string path, in return LspSymbols.QualifiedName(symbols, location.Line, location.Character); } + /// Whether the server said it can rename. + public bool CanRename + { + get { lock (_gate) return _renameProvider is JsonObject || _renameProvider?.GetValueKind() == System.Text.Json.JsonValueKind.True; } + } + + private bool CanPrepareRename + { + get { lock (_gate) return (_renameProvider as JsonObject)?["prepareProvider"]?.GetValueKind() == System.Text.Json.JsonValueKind.True; } + } + + /// What can be renamed at and UTF-16 : the default when the server doesn't say, null when it says nothing can. + public async Task PrepareRenameAsync(string path, int line, int character) => + CanPrepareRename + ? LspRename.ParsePrepare(await RequestAsync("textDocument/prepareRename", Position(path, line, character)).ConfigureAwait(false)) + : new RenameTarget(null, null); + + /// The edits that rename the symbol at and UTF-16 to . + public async Task> RenameAsync(string path, int line, int character, string newName) + { + var parameters = Position(path, line, character); + parameters["newName"] = newName; + return LspRename.ParseWorkspaceEdit(await RequestAsync("textDocument/rename", parameters).ConfigureAwait(false)); + } + + /// Tells the server that files it doesn't have open changed on disk. + public void FilesChanged(IEnumerable paths) + { + lock (_gate) + { + if (!_initialized) return; + _connection?.Notify("workspace/didChangeWatchedFiles", new JsonObject + { + ["changes"] = new JsonArray([.. paths.Select(p => (JsonNode)new JsonObject { ["uri"] = LspLocations.ToUri(p), ["type"] = 2 })]), + }); + } + } + /// The types in the folder whose names match , as the server matches them. public async Task> TypesAsync(string query, CancellationToken cancellationToken = default) => LspTypes.Parse(await RequestAsync("workspace/symbol", new JsonObject { ["query"] = query }, cancellationToken).ConfigureAwait(false)); diff --git a/src/TuiCode.Workbench/Languages/LspRename.cs b/src/TuiCode.Workbench/Languages/LspRename.cs new file mode 100644 index 00000000..97bf19f3 --- /dev/null +++ b/src/TuiCode.Workbench/Languages/LspRename.cs @@ -0,0 +1,63 @@ +using System.Text.Json.Nodes; + +namespace TuiCode.Workbench.Languages; + +/// A replacement of the text between two places, as LSP counts them: 0-based lines and UTF-16 columns. +public readonly record struct TextEdit(int StartLine, int StartCharacter, int EndLine, int EndCharacter, string NewText); + +/// The edits a workspace edit makes to one file. +public sealed record FileEdit(string Path, IReadOnlyList Edits); + +/// What textDocument/prepareRename said: the name's range, and the name to offer when the server gives one. +public sealed record RenameTarget(TextEdit? Range, string? Placeholder); + +public static class LspRename +{ + /// A prepareRename answer, or null when the server says the place can't be renamed. + public static RenameTarget? ParsePrepare(JsonNode? result) + { + if (result is not JsonObject answer) return null; + if (answer["defaultBehavior"] is not null) return new RenameTarget(null, null); + if (answer["range"] is JsonObject range) return new RenameTarget(Range(range), answer["placeholder"]?.GetValue()); + return answer["start"] is not null ? new RenameTarget(Range(answer), null) : null; + } + + /// The text edits in a WorkspaceEdit, from documentChanges if it has them, else changes; file operations are left out. + public static IReadOnlyList ParseWorkspaceEdit(JsonNode? result) + { + var byPath = new Dictionary>(LspLocations.PathComparer); + var order = new List(); + void Add(string? uri, JsonNode? edits) + { + if (uri is null || LspLocations.ToPath(uri) is not { } path || edits is not JsonArray array) return; + if (!byPath.TryGetValue(path, out var list)) + { + byPath[path] = list = []; + order.Add(path); + } + foreach (var edit in array.OfType()) + if (edit["range"] is JsonObject range && edit["newText"]?.GetValue() is { } text) + list.Add(Range(range) with { NewText = text }); + } + + if (result?["documentChanges"] is JsonArray documentChanges) + { + foreach (var change in documentChanges.OfType()) + if (change["kind"] is null) + Add(change["textDocument"]?["uri"]?.GetValue(), change["edits"]); + } + else if (result?["changes"] is JsonObject changes) + { + foreach (var (uri, edits) in changes) + Add(uri, edits); + } + return [.. order.Where(p => byPath[p].Count > 0).Select(p => new FileEdit(p, byPath[p]))]; + } + + private static TextEdit Range(JsonObject range) => new( + range["start"]?["line"]?.GetValue() ?? 0, + range["start"]?["character"]?.GetValue() ?? 0, + range["end"]?["line"]?.GetValue() ?? 0, + range["end"]?["character"]?.GetValue() ?? 0, + ""); +} diff --git a/src/TuiCode.Workbench/Languages/TextEdits.cs b/src/TuiCode.Workbench/Languages/TextEdits.cs new file mode 100644 index 00000000..9f4f9472 --- /dev/null +++ b/src/TuiCode.Workbench/Languages/TextEdits.cs @@ -0,0 +1,73 @@ +using System.Text; + +namespace TuiCode.Workbench.Languages; + +/// Applies a server's text edits to a file's text, keeping its line endings as they are. +public static class TextEdits +{ + /// The text with every edit made, or null when one falls outside it or two overlap. + public static string? Apply(string text, IReadOnlyList edits) + { + var starts = LineStarts(text); + var spans = new List<(int Start, int End, string NewText)>(); + foreach (var edit in edits) + { + if (Offset(text, starts, edit.StartLine, edit.StartCharacter) is not { } start + || Offset(text, starts, edit.EndLine, edit.EndCharacter) is not { } end + || end < start) + return null; + spans.Add((start, end, edit.NewText)); + } + spans.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.End.CompareTo(b.End)); + for (var i = 1; i < spans.Count; i++) + if (spans[i].Start < spans[i - 1].End) return null; + + var result = new StringBuilder(text); + // Back to front, so the offsets still to come stay where they were. + for (var i = spans.Count - 1; i >= 0; i--) + result.Remove(spans[i].Start, spans[i].End - spans[i].Start).Insert(spans[i].Start, spans[i].NewText); + return result.ToString(); + } + + /// Where each edit's new text starts once all of them are made, in edit order. + public static IReadOnlyList<(int Line, int Character)> NewStarts(IReadOnlyList edits) + { + var sorted = edits.Select((e, i) => (Edit: e, Index: i)) + .OrderBy(e => e.Edit.StartLine).ThenBy(e => e.Edit.StartCharacter).ToList(); + var places = new (int Line, int Character)[edits.Count]; + var lineShift = 0; + var (shiftedLine, characterShift) = (-1, 0); + foreach (var (edit, index) in sorted) + { + var line = edit.StartLine + lineShift; + var character = edit.StartCharacter + (edit.StartLine == shiftedLine ? characterShift : 0); + places[index] = (line, character); + + var newLines = edit.NewText.Split('\n'); + var endCharacter = newLines.Length == 1 ? character + edit.NewText.Length : newLines[^1].Length; + lineShift += newLines.Length - 1 - (edit.EndLine - edit.StartLine); + (shiftedLine, characterShift) = (edit.EndLine, endCharacter - edit.EndCharacter); + } + return places; + } + + private static List LineStarts(string text) + { + var starts = new List { 0 }; + for (var i = 0; i < text.Length; i++) + { + if (text[i] == '\r' && i + 1 < text.Length && text[i + 1] == '\n') i++; + if (text[i] is '\n' or '\r') starts.Add(i + 1); + } + return starts; + } + + private static int? Offset(string text, List starts, int line, int character) + { + if (line < 0 || line >= starts.Count || character < 0) return null; + var start = starts[line]; + var end = line + 1 < starts.Count ? starts[line + 1] : text.Length; + while (end > start && text[end - 1] is '\n' or '\r') end--; + return start + character <= end ? start + character : null; + } +} diff --git a/src/TuiCode.Workbench/Menus/CommandMenu.cs b/src/TuiCode.Workbench/Menus/CommandMenu.cs index cd779b25..8add66af 100644 --- a/src/TuiCode.Workbench/Menus/CommandMenu.cs +++ b/src/TuiCode.Workbench/Menus/CommandMenu.cs @@ -41,7 +41,7 @@ .. Enumerable.Range(1, 9).Select(CommandIds.FocusEditorByIndex), [CommandIds.MoveLinesUp] = 'm', [CommandIds.MoveLinesDown] = 'd', [CommandIds.DuplicateLinesUp] = 'u', [CommandIds.DuplicateLinesDown] = 'l', [CommandIds.IndentLines] = 'i', [CommandIds.OutdentLines] = 'o', [CommandIds.ToggleLineComment] = 't', [CommandIds.FindInFile] = 'f', [CommandIds.ReplaceInFile] = 'r', - [CommandIds.ReplaceGlobally] = 'g', [CommandIds.ToggleMatchCase] = 's', [CommandIds.ToggleWholeWord] = 'w', + [CommandIds.ReplaceGlobally] = 'g', [CommandIds.RenameSymbol] = 'a', [CommandIds.ToggleMatchCase] = 's', [CommandIds.ToggleWholeWord] = 'w', [CommandIds.ToggleIgnoredFiles] = 'n', [CommandIds.ChangeGrammar] = 'c', [CommandIds.KeepCurrentChange] = 'k', [CommandIds.KeepIncomingChange] = 'e', [CommandIds.KeepBothChanges] = 'b', [CommandIds.NextMergeConflict] = 'x', [CommandIds.PreviousMergeConflict] = 'p', @@ -95,7 +95,7 @@ public static readonly (string Title, string[] Ids)[] Layout = CommandIds.KeepCurrentChange, CommandIds.KeepIncomingChange, CommandIds.KeepBothChanges, CommandIds.NextMergeConflict, CommandIds.PreviousMergeConflict, Separator, - CommandIds.FindInFile, CommandIds.ReplaceInFile, CommandIds.ReplaceGlobally, + CommandIds.FindInFile, CommandIds.ReplaceInFile, CommandIds.ReplaceGlobally, CommandIds.RenameSymbol, CommandIds.ToggleMatchCase, CommandIds.ToggleWholeWord, CommandIds.ToggleIgnoredFiles, Separator, CommandIds.ChangeGrammar, diff --git a/src/TuiCode.Workbench/Rename/RenameSymbolView.cs b/src/TuiCode.Workbench/Rename/RenameSymbolView.cs new file mode 100644 index 00000000..e05848b3 --- /dev/null +++ b/src/TuiCode.Workbench/Rename/RenameSymbolView.cs @@ -0,0 +1,60 @@ +using MentalDesk.Tui.Dialogs; +using MentalDesk.Tui.Fields; +using TuiCode.Abstractions; + +namespace TuiCode.Workbench.Rename; + +/// Rename symbol's prompt (#697): the new name, starting as the old one, all of it selected. +public sealed class RenameSymbolView : AppDialog +{ + private const string RenameId = "renameSymbol.rename"; + private const int ContentRows = 4; + + private readonly TextField _input; + private readonly VerbatimLabel _label; + + public event EventHandler? Submitted; + + public RenameSymbolView(string name) + : base($"Rename {name}", 60, ContentRows) + { + OldName = name; + _label = new VerbatimLabel { X = 1, Y = 0, Width = Dim.Fill(1), Text = "New name:" }; + _input = new PlaceholderField { X = 1, Y = 1, Width = Dim.Fill(1), Text = name }; + Add(_label, _input); + Check(_input, _label, Refusal); + + Commands.Register(RenameId, "Rename", OnConfirm); + Keys.Bind("Ctrl+Enter", RenameId); + var rename = CommandButton(ButtonKind.Primary, RenameId); + rename.IsDefault = false; + AddButtonRow(ContentRows - 1, rename, CommandButton(ButtonKind.Secondary, CancelId)); + } + + public string OldName { get; } + + public string NewName => _input.Text?.Trim() ?? ""; + + internal VerbatimLabel FieldLabel => _label; + + internal string SelectedText => _input.SelectedText ?? ""; + + public bool FocusInput() => _input.SetFocus(); + + /// Marks the name with why the server refused it, keeping the dialog open. + public void ShowError(string message) => Refuse(_input, $"New name: {message}"); + + /// Closes the dialog once the host has the rename. + public void Finish() => Accept(); + + private string? Refusal() + { + if (NewName.Length == 0) return "New name is needed"; + return NewName == OldName ? $"New name is still {OldName}" : null; + } + + private void OnConfirm() + { + if (Checked()) Submitted?.Invoke(this, NewName); + } +} diff --git a/src/TuiCode.Workbench/Rename/WorkspaceRename.cs b/src/TuiCode.Workbench/Rename/WorkspaceRename.cs new file mode 100644 index 00000000..af53791c --- /dev/null +++ b/src/TuiCode.Workbench/Rename/WorkspaceRename.cs @@ -0,0 +1,112 @@ +using System.Text; +using TuiCode.Editor; +using TuiCode.Workbench.Languages; + +namespace TuiCode.Workbench.Rename; + +/// A server's rename, split between the files open in tabs and the files only on disk. +public sealed class WorkspaceRename +{ + private static readonly byte[] Utf8Bom = [0xEF, 0xBB, 0xBF]; + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + private readonly IReadOnlyDictionary _openText; + private readonly Dictionary _closedBytes; + + private WorkspaceRename(IReadOnlyList open, IReadOnlyList closed, + IReadOnlyDictionary openText, Dictionary closedBytes) + { + Open = open; + Closed = closed; + _openText = openText; + _closedBytes = closedBytes; + } + + public IReadOnlyList Open { get; } + public IReadOnlyList Closed { get; } + public int Changes => Open.Concat(Closed).Sum(f => f.Edits.Count); + public int Files => Open.Count + Closed.Count; + + /// Each open tab's lines joined with \n, as they were when the server was asked. + public static WorkspaceRename Plan(IReadOnlyList files, IReadOnlyDictionary openText, IFileSystem fileSystem) + { + List open = [], closed = []; + var bytes = new Dictionary(LspLocations.PathComparer); + foreach (var file in files) + { + if (openText.ContainsKey(file.Path)) + open.Add(file); + else if (fileSystem.File.Exists(file.Path)) + { + closed.Add(file); + bytes[file.Path] = fileSystem.File.ReadAllBytes(file.Path); + } + } + return new WorkspaceRename(open, closed, openText, bytes); + } + + /// Makes the edits: each open tab's as one undo step, left unsaved, and each closed file's written with its BOM and line endings. + public RenameResult Apply(IEnumerable tabs, IFileSystem fileSystem) + { + List applied = []; + List skipped = []; + var byPath = tabs.GroupBy(t => t.File.FullName, LspLocations.PathComparer).ToDictionary(g => g.Key, g => g.First(), LspLocations.PathComparer); + foreach (var file in Open) + { + if (byPath.TryGetValue(file.Path, out var tab) && ApplyTo(tab, file)) applied.Add(file); + else skipped.Add(file.Path); + } + foreach (var file in Closed) + { + if (byPath.ContainsKey(file.Path) || !ApplyTo(fileSystem, file)) skipped.Add(file.Path); + else applied.Add(file); + } + return new RenameResult(applied, skipped); + } + + private bool ApplyTo(EditorTab tab, FileEdit file) + { + var old = string.Join('\n', tab.Lines); + if (tab.ReadOnly || old != _openText[file.Path] || TextEdits.Apply(old, file.Edits) is not { } renamed) return false; + var before = old.Split('\n'); + var after = renamed.Split('\n'); + var prefix = 0; + while (prefix < before.Length && prefix < after.Length && before[prefix] == after[prefix]) prefix++; + var suffix = 0; + while (suffix < before.Length - prefix && suffix < after.Length - prefix && before[^(suffix + 1)] == after[^(suffix + 1)]) suffix++; + tab.ReplaceLines(prefix, before.Length - prefix - suffix, after[prefix..^suffix]); + return true; + } + + // A file that changed since the server answered, or isn't UTF-8, is left as it is. + private bool ApplyTo(IFileSystem fileSystem, FileEdit file) + { + try + { + var bytes = fileSystem.File.ReadAllBytes(file.Path); + if (!bytes.AsSpan().SequenceEqual(_closedBytes[file.Path])) return false; + var hasBom = bytes.AsSpan().StartsWith(Utf8Bom); + var text = StrictUtf8.GetString(bytes, hasBom ? Utf8Bom.Length : 0, bytes.Length - (hasBom ? Utf8Bom.Length : 0)); + if (TextEdits.Apply(text, file.Edits) is not { } renamed) return false; + var written = StrictUtf8.GetBytes(renamed); + fileSystem.File.WriteAllBytes(file.Path, hasBom ? [.. Utf8Bom, .. written] : written); + return true; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or DecoderFallbackException or EncoderFallbackException) + { + return false; + } + } +} + +/// The files a rename changed, and those it left alone because they'd changed or couldn't be written. +public sealed record RenameResult(IReadOnlyList Applied, IReadOnlyList Skipped) +{ + public int Changes => Applied.Sum(f => f.Edits.Count); + + /// One place per changed line, where its first change now starts. + public IEnumerable ChangedLines() => + Applied.SelectMany(f => TextEdits.NewStarts(f.Edits) + .GroupBy(p => p.Line).Select(g => g.MinBy(p => p.Character)) + .Select(p => new SourceLocation(f.Path, p.Line, p.Character))); +} diff --git a/src/TuiCode.Workbench/Usages/UsagesView.cs b/src/TuiCode.Workbench/Usages/UsagesView.cs index c6a923e9..534d0809 100644 --- a/src/TuiCode.Workbench/Usages/UsagesView.cs +++ b/src/TuiCode.Workbench/Usages/UsagesView.cs @@ -16,10 +16,11 @@ public sealed class UsagesView : View private readonly TreeView _tree; private string _title = "Find usages of a symbol to list them here"; private string? _counted; + private string _separator = " "; public event EventHandler? UsageActivated; - public string HeaderText => _counted is null ? _title : $"{_title} {_counted}"; + public string HeaderText => _counted is null ? _title : $"{_title}{_separator}{_counted}"; public IReadOnlyList Files { get; private set; } = []; public bool ResultsHaveFocus => _tree.HasFocus; @@ -69,6 +70,10 @@ public void ShowUsages(string symbol, IReadOnlyList files) else Show($"Usages of {symbol}", UsageTree.Count(files), files); } + /// What a rename changed: edits on the lines in . + public void ShowRenamed(string oldName, string newName, int changes, IReadOnlyList files) => + Show($"Renamed {oldName} → {newName}", $"{changes} in {files.Count} {Plural.Of(files.Count, "file")}", files, " · "); + /// The first usage, or the tab itself while there are none. public bool FocusResults() { @@ -77,8 +82,9 @@ public bool FocusResults() return _tree.SetFocus(); } - private void Show(string title, string? counted, IReadOnlyList files) + private void Show(string title, string? counted, IReadOnlyList files, string separator = " ") { + _separator = separator; var hadFocus = _tree.HasFocus; Files = files; _title = title; diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index 5f37f4d5..6c104c24 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -38,6 +38,7 @@ using TuiCode.Workbench.Mnemonics; using TuiCode.Workbench.Navigation; using TuiCode.Workbench.Parts; +using TuiCode.Workbench.Rename; using TuiCode.Workbench.Usages; using TuiCode.Workbench.Review; using TuiCode.Workbench.Services; @@ -120,6 +121,8 @@ public sealed class WorkbenchHost : IDisposable private (EditorTab Tab, System.Drawing.Point? Caret, System.Drawing.Rectangle Text) _quickInfoAt; private int _quickInfoRequest; private IFileSystem? _usagesFileSystem; + private int _renameRequest; + private RenameSymbolView? _activeRename; private GrammarPickerView? _activeGrammarPicker; private DiagnosticsView? _activeDiagnostics; private string? _cursorColour; @@ -766,6 +769,7 @@ private void RegisterDefaultCommands() _commands.Register(CommandIds.GoToDefinition, "Go to definition", GoToDefinition, CommandScope.Editor, FileOpen); _commands.Register(CommandIds.QuickInfo, "Quick info", ShowQuickInfo, CommandScope.Editor, FileOpen); _commands.Register(CommandIds.FindUsages, "Find usages", FindUsages, CommandScope.Editor, FileOpen); + _commands.Register(CommandIds.RenameSymbol, "Rename symbol", RenameSymbol, CommandScope.Editor, FileOpen); // Global and ungated, so with no agent installed it can say so (#566). _commands.Register(CommandIds.AiAssistance, "AI assistance", AskAssistant, CommandScope.Global, null, () => _workbench.IsAssistantShowing ? "Hide AI assistance" : "Show AI assistance"); @@ -1527,7 +1531,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.QuickInfo or CommandIds.FindUsages or CommandIds.RenameSymbol) || ActiveLanguageServer() is { State: LanguageServerState.Ready }); } private LanguageServer? ActiveLanguageServer() => @@ -1953,6 +1957,117 @@ private void FindUsages() return (name ?? symbol, await usages.ConfigureAwait(false)); } + /// Rename symbol (rs, #697): asks for the new name, then makes the server's rename across the folder. + private void RenameSymbol() + { + if (_activeRename is not null) return; + if (_workbench.Editor.Group.ActiveTab is not { } tab || ReadyLanguageServer(tab) is not { } server) return; + var status = _workbench.StatusBar; + if (!server.CanRename) + { + status.ShowMessage($"Can't rename this: the {server.Spec.Name} language server doesn't rename"); + return; + } + var (path, row, character) = (tab.File.FullName, tab.CursorRow, tab.CursorCharacter); + var word = IdentifierAt(tab.Lines[row], character); + var request = ++_renameRequest; + server.PrepareRenameAsync(path, row, character).ContinueWith(answer => _app.Invoke(() => + { + if (_disposed || request != _renameRequest || _activeRename is not null || _workbench.Editor.Group.ActiveTab != tab) return; + if (answer.Exception?.InnerException is { } error) + { + status.ShowMessage($"Can't rename this: {error.Message}"); + return; + } + if (answer.Result is not { } target) + { + status.ShowMessage("Can't rename this"); + return; + } + if ((target.Placeholder ?? TextIn(tab, target.Range) ?? word) is not { Length: > 0 } name) + { + status.ShowMessage("Nothing to rename here"); + return; + } + OpenRenameSymbol(tab, server, (path, row, character), name); + }), TaskScheduler.Default); + } + + private static string? TextIn(EditorTab tab, TextEdit? range) + { + if (range is not { } r || r.StartLine != r.EndLine || r.StartLine >= tab.Lines.Count) return null; + var line = tab.Lines[r.StartLine]; + return r.StartCharacter <= r.EndCharacter && r.EndCharacter <= line.Length ? line[r.StartCharacter..r.EndCharacter] : null; + } + + private void OpenRenameSymbol(EditorTab tab, LanguageServer server, (string Path, int Row, int Character) at, string name) + { + var view = new RenameSymbolView(name); + var fileSystem = tab.File.FileSystem; + var asking = false; + _activeRename = view; + view.Submitted += (_, newName) => + { + if (asking) return; + asking = true; + _workbench.Languages!.Flush(); + var openText = _workbench.Editor.Groups.Tabs + .GroupBy(t => t.File.FullName, LspLocations.PathComparer) + .ToDictionary(g => g.Key, g => string.Join('\n', g.First().Lines), LspLocations.PathComparer); + server.RenameAsync(at.Path, at.Row, at.Character, newName).ContinueWith(answer => _app.Invoke(() => + { + asking = false; + if (_disposed || !ReferenceEquals(_activeRename, view)) return; + if (answer.Exception?.InnerException is { } error) + { + view.ShowError(error.Message); + return; + } + var rename = WorkspaceRename.Plan(answer.Result, openText, fileSystem); + if (rename.Files == 0) + { + view.ShowError($"the {server.Spec.Name} language server found nothing to rename"); + return; + } + view.Finish(); + if (rename.Closed.Count == 0) + { + ApplyRename(server, rename, name, newName, fileSystem); + return; + } + var closed = rename.Closed.Count; + Confirm("Rename symbol", + $"Rename {name} to {newName}?\n{rename.Changes} {Plural.Of(rename.Changes, "change")} in {rename.Files} {Plural.Of(rename.Files, "file")}. " + + (closed == 1 ? "1 file isn't open and is saved straight away." : $"{closed} files aren't open and are saved straight away."), + [Main("Rename", ButtonKind.Primary, () => ApplyRename(server, rename, name, newName, fileSystem))]); + }), TaskScheduler.Default); + }; + HostedDialog.Show(_workbench, _scopes, view, () => + { + _activeRename = null; + FocusCallingRegion(); + }); + view.FocusInput(); + } + + private void ApplyRename(LanguageServer server, WorkspaceRename rename, string oldName, string newName, IFileSystem fileSystem) + { + var result = rename.Apply(_workbench.Editor.Groups.Tabs, fileSystem); + var written = result.Applied.Select(f => f.Path).Where(p => rename.Closed.Any(c => LspLocations.PathComparer.Equals(c.Path, p))).ToList(); + if (written.Count > 0) server.FilesChanged(written); + + var files = UsageTree.Build(result.ChangedLines(), p => LinesOf(fileSystem, p), _workbench.Sidebar.Explorer.Root?.FullName); + _usagesFileSystem = fileSystem; + _workbench.Sidebar.Usages.ShowRenamed(oldName, newName, result.Changes, files); + ShowSidebarTab(SidebarTab.Usages); + if (result.Skipped.Count > 0) + _workbench.StatusBar.ShowMessage( + $"Renamed {oldName} to {newName}, except in {string.Join(", ", result.Skipped.Select(Path.GetFileName))}, which changed while renaming", + Severity.Error); + else + _workbench.StatusBar.ShowMessage($"Renamed {oldName} to {newName}"); + } + private IReadOnlyList LinesOf(IFileSystem fileSystem, string path) => _workbench.Editor.Group.Tabs.FirstOrDefault(t => t.File.FullName == path) is { } open ? open.Lines diff --git a/tests/TuiCode.Tests/FakeLanguageServer.cs b/tests/TuiCode.Tests/FakeLanguageServer.cs index a158b2cc..015adb52 100644 --- a/tests/TuiCode.Tests/FakeLanguageServer.cs +++ b/tests/TuiCode.Tests/FakeLanguageServer.cs @@ -53,6 +53,21 @@ internal sealed partial class FakeLanguageServer : ILanguageServerLauncher /// Answers workspace/symbol with an error. public bool FailWorkspaceSymbol { get; set; } + /// The renameProvider capability it answers initialize with; null leaves it out. + public JsonNode? RenameProvider { get; set; } = new JsonObject { ["prepareProvider"] = true }; + + /// Answers rename with documentChanges, a file creation among them, rather than changes. + public bool RenamesAsDocumentChanges { get; set; } + + /// Answers prepareRename with this error. + public string? PrepareRenameError { get; set; } + + /// Answers rename with this error. + public string? RenameError { get; set; } + + /// Runs as rename is answered, after the edits are worked out. + public Action? Renaming { get; set; } + /// Every workspace/symbol query asked, in order. public ConcurrentQueue SymbolQueries { get; } = new(); @@ -146,7 +161,11 @@ 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" => new JsonObject { ["capabilities"] = Capabilities() }, + "textDocument/prepareRename" when PrepareRenameError is { } error => throw new JsonRpcException(-32603, error), + "textDocument/prepareRename" => PrepareRename(parameters!), + "textDocument/rename" when RenameError is { } error => throw new JsonRpcException(-32603, error), + "textDocument/rename" => Rename(parameters!), "textDocument/definition" => Definitions(parameters!), "textDocument/references" => References(parameters!), "textDocument/documentSymbol" => Symbols(parameters!), @@ -156,6 +175,66 @@ private void Progress(InProcessServer server, string kind) => }; } + private JsonObject Capabilities() + { + var capabilities = new JsonObject { ["definitionProvider"] = true }; + if (RenameProvider is { } rename) capabilities["renameProvider"] = rename.DeepClone(); + return capabilities; + } + + private JsonObject? PrepareRename(JsonNode parameters) + { + if (WordAt(parameters) is not { } word) return null; + var line = parameters["position"]!["line"]!.GetValue(); + var character = parameters["position"]!["character"]!.GetValue(); + var text = Lines(Sources()[Path(parameters["textDocument"]!)])[line]; + var match = WordPattern().Matches(text).First(m => m.Index <= character && character <= m.Index + m.Length); + return new JsonObject { ["range"] = Range(line, match.Index, line, match.Index + word.Length), ["placeholder"] = word }; + } + + // Every whole-word use outside comments and strings, in every file it knows. + private JsonObject? Rename(JsonNode parameters) + { + if (WordAt(parameters) is not { } word) return null; + var newName = parameters["newName"]!.GetValue(); + var byFile = new List<(string File, JsonArray Edits)>(); + foreach (var (file, text) in Sources().Where(s => !LspLocations.IsDecompiled(s.Key)).OrderBy(s => s.Key, StringComparer.Ordinal)) + { + var edits = new JsonArray(); + var fileLines = Lines(text); + for (var row = 0; row < fileLines.Length; row++) + { + var code = CodeOnly(fileLines[row]); + foreach (Match match in Regex.Matches(code, $@"\b{Regex.Escape(word)}\b")) + edits.Add(new JsonObject { ["range"] = Range(row, match.Index, row, match.Index + word.Length), ["newText"] = newName }); + } + if (edits.Count > 0) byFile.Add((file, edits)); + } + Renaming?.Invoke(); + if (!RenamesAsDocumentChanges) + { + var changes = new JsonObject(); + foreach (var (file, edits) in byFile) changes[LspLocations.ToUri(file)] = edits; + return new JsonObject { ["changes"] = changes }; + } + var documentChanges = new JsonArray(new JsonObject { ["kind"] = "create", ["uri"] = LspLocations.ToUri("/work/New.cs") }); + foreach (var (file, edits) in byFile) + documentChanges.Add(new JsonObject + { + ["textDocument"] = new JsonObject { ["uri"] = LspLocations.ToUri(file), ["version"] = null }, + ["edits"] = edits, + }); + return new JsonObject { ["documentChanges"] = documentChanges }; + } + + // The line with its comment and the insides of its strings blanked out, keeping every column where it was. + private static string CodeOnly(string line) + { + var comment = line.IndexOf("//", StringComparison.Ordinal); + var code = comment < 0 ? line : line[..comment] + new string(' ', line.Length - comment); + return Regex.Replace(code, "\"[^\"]*\"", m => new string(' ', m.Length)); + } + private void OnNotification(InProcessServer server, string method, JsonNode? parameters) { var document = parameters?["textDocument"]; diff --git a/tests/TuiCode.Tests/LanguageServerTests.cs b/tests/TuiCode.Tests/LanguageServerTests.cs index 79aa485b..73f272bb 100644 --- a/tests/TuiCode.Tests/LanguageServerTests.cs +++ b/tests/TuiCode.Tests/LanguageServerTests.cs @@ -124,6 +124,94 @@ 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); } + [Fact] + public async Task It_tells_the_server_it_can_rename_with_prepareRename_and_document_changes() + { + using var server = Server(); + var ready = Reached(server, LanguageServerState.Ready); + server.Start(); + await ready.WaitAsync(Timeout); + + var capabilities = _fake.Received("initialize").Single()!["capabilities"]!; + + Assert.True(capabilities["textDocument"]!["rename"]!["prepareSupport"]!.GetValue()); + Assert.True(capabilities["workspace"]!["workspaceEdit"]!["documentChanges"]!.GetValue()); + Assert.Null(capabilities["workspace"]!["workspaceEdit"]!["resourceOperations"]); + } + + [Fact] + public async Task Rename_asks_prepareRename_first_where_the_server_offers_it_then_reads_back_the_edits() + { + _fake.Files[Path.GetFullPath("/work/Gadget.cs")] = "class Gadget\n{\n void Run() { }\n}"; + using var server = await Started("class Widget { void Go() { Run(); } }"); + + var target = await server.PrepareRenameAsync(Widget, 0, 28); + var edits = await server.RenameAsync(Widget, 0, 28, "Start"); + + Assert.True(server.CanRename); + Assert.Equal(new RenameTarget(new TextEdit(0, 27, 0, 30, ""), "Run"), target); + Assert.Equal( + [(Path.GetFullPath("/work/Gadget.cs"), new TextEdit(2, 9, 2, 12, "Start")), (Widget, new TextEdit(0, 27, 0, 30, "Start"))], + edits.SelectMany(f => f.Edits.Select(e => (f.Path, e)))); + var rename = _fake.Received("textDocument/rename").Single()!; + Assert.Equal("Start", rename["newName"]!.GetValue()); + Assert.Equal(28, rename["position"]!["character"]!.GetValue()); + } + + [Fact] + public async Task Without_prepareProvider_it_doesnt_ask_prepareRename() + { + _fake.RenameProvider = true; + using var server = await Started("class Widget { void Go() { Run(); } }"); + + var target = await server.PrepareRenameAsync(Widget, 0, 28); + + Assert.True(server.CanRename); + Assert.Equal(new RenameTarget(null, null), target); + Assert.Empty(_fake.Received("textDocument/prepareRename")); + } + + [Fact] + public async Task A_server_without_renameProvider_cant_rename() + { + _fake.RenameProvider = null; + using var server = await Started("class Widget { }"); + + Assert.False(server.CanRename); + } + + [Fact] + public async Task Rename_reads_documentChanges_and_leaves_out_the_file_operations() + { + _fake.RenamesAsDocumentChanges = true; + using var server = await Started("class Widget { void Run() { Run(); } }"); + + var edits = await server.RenameAsync(Widget, 0, 21, "Start"); + + var file = Assert.Single(edits); + Assert.Equal(Widget, file.Path); + Assert.Equal([new TextEdit(0, 20, 0, 23, "Start"), new TextEdit(0, 28, 0, 31, "Start")], file.Edits); + } + + [Fact] + public async Task A_rename_the_server_refuses_throws_in_its_words() + { + _fake.RenameError = "Start is already defined"; + using var server = await Started("class Widget { void Run() { } }"); + + var refused = await Assert.ThrowsAsync(() => server.RenameAsync(Widget, 0, 21, "Start")); + + Assert.Equal("Start is already defined", refused.Message); + } + + [Fact] + public async Task A_place_prepareRename_says_no_to_has_no_target() + { + using var server = await Started("class Widget { void Run() { } }"); + + Assert.Null(await server.PrepareRenameAsync(Widget, 0, 16)); + } + [Fact] public async Task It_tells_the_server_it_can_show_decompiled_library_sources() { @@ -260,6 +348,16 @@ public async Task It_tells_the_server_it_takes_problems() ["message"] = "nam", }; + private async Task Started(string widget) + { + var server = Server(); + var ready = Reached(server, LanguageServerState.Ready); + server.Open(Widget, widget); + server.Start(); + await ready.WaitAsync(Timeout); + return server; + } + private LanguageServer Server(TimeSpan? quietLoad = null) => new(LanguageServerSpec.CSharp, Root, _fake, action => action()) { QuietLoad = quietLoad ?? TimeSpan.FromMinutes(1), StopTimeout = Timeout }; diff --git a/tests/TuiCode.Tests/LspRenameTests.cs b/tests/TuiCode.Tests/LspRenameTests.cs new file mode 100644 index 00000000..f384071e --- /dev/null +++ b/tests/TuiCode.Tests/LspRenameTests.cs @@ -0,0 +1,79 @@ +using System.Text.Json.Nodes; +using TuiCode.Workbench.Languages; + +namespace TuiCode.Tests; + +public class LspRenameTests +{ + private static readonly string A = Path.GetFullPath("/work/A.cs"); + private static readonly string B = Path.GetFullPath("/work/B.cs"); + + [Fact] + public void ParseWorkspaceEdit_reads_changes_by_file() + { + var edits = LspRename.ParseWorkspaceEdit(new JsonObject + { + ["changes"] = new JsonObject + { + [LspLocations.ToUri(A)] = new JsonArray(Edit(1, 4, 1, 9, "Total"), Edit(3, 0, 3, 5, "Total")), + [LspLocations.ToUri(B)] = new JsonArray(Edit(0, 2, 0, 7, "Total")), + }, + }); + + Assert.Equal( + [ + (A, new TextEdit[] { new(1, 4, 1, 9, "Total"), new(3, 0, 3, 5, "Total") }), + (B, new TextEdit[] { new(0, 2, 0, 7, "Total") }), + ], edits.Select(f => (f.Path, f.Edits.ToArray()))); + } + + [Fact] + public void ParseWorkspaceEdit_prefers_documentChanges_and_leaves_out_file_operations() + { + var edits = LspRename.ParseWorkspaceEdit(new JsonObject + { + ["changes"] = new JsonObject { [LspLocations.ToUri(B)] = new JsonArray(Edit(0, 0, 0, 1, "x")) }, + ["documentChanges"] = new JsonArray( + new JsonObject { ["kind"] = "rename", ["oldUri"] = LspLocations.ToUri(A), ["newUri"] = LspLocations.ToUri(B) }, + new JsonObject + { + ["textDocument"] = new JsonObject { ["uri"] = LspLocations.ToUri(A), ["version"] = 3 }, + ["edits"] = new JsonArray(Edit(2, 1, 2, 4, "Sum")), + }, + new JsonObject + { + ["textDocument"] = new JsonObject { ["uri"] = LspLocations.ToUri(A), ["version"] = 3 }, + ["edits"] = new JsonArray(Edit(5, 1, 5, 4, "Sum")), + }, + new JsonObject { ["kind"] = "delete", ["uri"] = LspLocations.ToUri(B) }), + }); + + var file = Assert.Single(edits); + Assert.Equal(A, file.Path); + Assert.Equal([new TextEdit(2, 1, 2, 4, "Sum"), new TextEdit(5, 1, 5, 4, "Sum")], file.Edits); + } + + [Fact] + public void ParseWorkspaceEdit_of_null_is_no_edits() => Assert.Empty(LspRename.ParseWorkspaceEdit(null)); + + [Fact] + public void ParsePrepare_reads_a_range_with_or_without_a_placeholder_and_the_default_behaviour() + { + Assert.Equal(new RenameTarget(new TextEdit(1, 2, 1, 6, ""), null), LspRename.ParsePrepare(Range(1, 2, 1, 6))); + Assert.Equal(new RenameTarget(new TextEdit(1, 2, 1, 6, ""), "Hunk"), + LspRename.ParsePrepare(new JsonObject { ["range"] = Range(1, 2, 1, 6), ["placeholder"] = "Hunk" })); + Assert.Equal(new RenameTarget(null, null), LspRename.ParsePrepare(new JsonObject { ["defaultBehavior"] = true })); + } + + [Fact] + public void ParsePrepare_of_null_means_nothing_here_can_be_renamed() => Assert.Null(LspRename.ParsePrepare(null)); + + private static JsonObject Edit(int startLine, int startCharacter, int endLine, int endCharacter, string text) => + new() { ["range"] = Range(startLine, startCharacter, endLine, endCharacter), ["newText"] = text }; + + private static JsonObject Range(int startLine, int startCharacter, int endLine, int endCharacter) => new() + { + ["start"] = new JsonObject { ["line"] = startLine, ["character"] = startCharacter }, + ["end"] = new JsonObject { ["line"] = endLine, ["character"] = endCharacter }, + }; +} diff --git a/tests/TuiCode.Tests/MenuBarHostTests.cs b/tests/TuiCode.Tests/MenuBarHostTests.cs index c611baa1..5d295881 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.QuickInfo or CommandIds.FindUsages or CommandIds.RenameSymbol) && 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/RenameSymbolHostTests.cs b/tests/TuiCode.Tests/RenameSymbolHostTests.cs new file mode 100644 index 00000000..73f75ebf --- /dev/null +++ b/tests/TuiCode.Tests/RenameSymbolHostTests.cs @@ -0,0 +1,385 @@ +using MentalDesk.Tui.Dialogs; +using MentalDesk.Tui.Theming; +using Terminal.Gui.Views; +using TuiCode.Abstractions; +using TuiCode.Explorer; +using TuiCode.Syntax; +using TuiCode.Workbench; +using TuiCode.Workbench.Parts; +using TuiCode.Workbench.Rename; +using TuiCode.Workbench.Services; + +namespace TuiCode.Tests; + +// Drives `rs` (#697) through the host against a fake language server. Boots a TG Application — serialised (#77). +public class RenameSymbolHostTests : StaticConfigurationTest +{ + private const string Diff = "class Diff\n{\n int Hunks() => 0;\n // Hunks are counted here\n int Twice() => Hunks() * 2;\n string Name = \"Hunks\";\n}\n"; + + private const string Report = "class Report\r\n{\r\n void Print()\r\n {\r\n Diff.Hunks();\r\n }\r\n}\r\n"; + + private static readonly SyntaxHighlighter Syntax = new(GrammarBundle.Load()); + + private static readonly string[] Renamed = + ["class Diff", "{", " int Count() => 0;", " // Hunks are counted here", " int Twice() => Count() * 2;", " string Name = \"Hunks\";", "}", ""]; + + private readonly MockFileSystem _fs = new(); + private readonly FakeLanguageServer _server = new(); + + public RenameSymbolHostTests() + { + Add("/work/Diff.cs", Diff); + Add("/work/Report.cs", Report); + } + + [Fact] + public async Task Rs_on_a_method_opens_Rename_with_the_name_all_selected() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + RenameSymbolView? view = null; + string selected = "", label = ""; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { workbench.Editor.Group.ActiveTab!.MoveCursor(2, 10); Rs(host); }, + () => (view = Dialog(workbench)) is not null, + () => { selected = view!.SelectedText; label = view.FieldLabel.Text; host.App.InjectKey(Key.Esc); }, + () => Dialog(workbench) is null); + + Assert.Equal("Rename Hunks", view!.Title); + Assert.Equal("New name:", label); + Assert.Equal("Hunks", view.NewName); + Assert.Equal("Hunks", selected); + Assert.Single(_server.Received("textDocument/prepareRename")); + } + + [Fact] + public async Task With_every_file_open_Ctrl_Enter_renames_in_the_tabs_unsaved_and_Ctrl_Z_takes_a_tab_back() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + ConfirmDialog? confirm = null; + string[] renamed = [], undone = []; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Report.cs"), + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => Submit(host, workbench, "Count"), + () => Dialog(workbench) is null && workbench.Sidebar.Usages.HeaderText.StartsWith("Renamed", StringComparison.Ordinal), + () => { confirm = ConfirmDialogs.Of(workbench); renamed = [.. Tab(workbench, "Diff.cs").Lines]; }, + () => host.App.InjectKey(Key.Esc), + () => workbench.StatusBar.DisplayedFocus == "Editor", + () => host.App.InjectKey(Key.Z.WithCtrl), + () => { undone = [.. Tab(workbench, "Diff.cs").Lines]; }); + + Assert.Null(confirm); + Assert.Equal(Renamed, renamed); + Assert.Equal(Diff.Split('\n'), undone); + Assert.Equal(["class Report", "{", " void Print()", " {", " Diff.Count();", " }", "}", ""], Tab(workbench, "Report.cs").Lines); + Assert.True(Tab(workbench, "Report.cs").IsDirty); + Assert.Equal(Report, _fs.File.ReadAllText("/work/Report.cs")); + Assert.Equal(Diff, _fs.File.ReadAllText("/work/Diff.cs")); + Assert.Equal("Renamed Hunks → Count · 3 in 2 files", workbench.Sidebar.Usages.HeaderText); + } + + [Fact] + public async Task With_a_file_not_open_a_confirm_says_so_first_and_Cancel_changes_nothing() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + ConfirmDialog? confirm = null; + string[] buttons = []; + string? focused = null; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => Submit(host, workbench, "Count"), + () => (confirm = ConfirmDialogs.Of(workbench)) is not null, + () => { buttons = confirm!.Buttons(); focused = confirm.FocusedButton(); host.App.InjectKey(Key.Esc); }, + () => ConfirmDialogs.Of(workbench) is null); + + Assert.Equal("Rename symbol", confirm!.Title); + Assert.Equal("Rename Hunks to Count?\n3 changes in 2 files. 1 file isn't open and is saved straight away.", confirm.Message()); + Assert.Equal(["Ctrl+Enter Rename", "Esc Cancel"], buttons); + Assert.Equal("Esc Cancel", focused); + Assert.Equal(Diff.Split('\n'), Tab(workbench, "Diff.cs").Lines); + Assert.False(Tab(workbench, "Diff.cs").IsDirty); + Assert.Equal(Report, _fs.File.ReadAllText("/work/Report.cs")); + Assert.DoesNotContain("Renamed", workbench.Sidebar.Usages.HeaderText, StringComparison.Ordinal); + } + + [Fact] + public async Task Rename_in_the_confirm_writes_the_closed_file_and_lists_the_changed_lines_in_Usages() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + var pane = workbench.Sidebar.Usages; + (string File, int Row, int Column) jumped = default; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => Submit(host, workbench, "Count"), + () => ConfirmDialogs.Of(workbench) is not null, + ConfirmDialogs.Choose(host, workbench, "Rename"), + () => pane.Files.Count > 0 && pane.ResultsHaveFocus, + () => { for (var i = 0; i < 3; i++) host.App.InjectKey(Key.CursorDown); }, + () => host.App.InjectKey(Key.Enter), + () => workbench.Editor.Group.ActiveTab!.File.Name == "Report.cs", + () => + { + var tab = workbench.Editor.Group.ActiveTab!; + jumped = (tab.File.Name, tab.CursorRow, tab.CursorColumn); + }); + + Assert.Equal("class Report\r\n{\r\n void Print()\r\n {\r\n Diff.Count();\r\n }\r\n}\r\n", _fs.File.ReadAllText("/work/Report.cs")); + Assert.Equal(Renamed, Tab(workbench, "Diff.cs").Lines); + Assert.True(Tab(workbench, "Diff.cs").IsDirty); + Assert.Equal(Diff, _fs.File.ReadAllText("/work/Diff.cs")); + Assert.Equal("Renamed Hunks → Count · 3 in 2 files", pane.HeaderText); + Assert.Equal([("Diff.cs", 2), ("Report.cs", 1)], pane.Files.Select(f => (f.Name, f.Count))); + Assert.Equal(["3 int Count() => 0;", "5 int Twice() => Count() * 2;", "5 Diff.Count();"], + pane.Files.SelectMany(f => f.Children).Select(u => u.ToString())); + Assert.Equal(("Report.cs", 4, 13), jumped); + Assert.Contains(_server.Received("workspace/didChangeWatchedFiles"), + p => p!["changes"]![0]!["uri"]!.GetValue() == TuiCode.Workbench.Languages.LspLocations.ToUri(_fs.Path.GetFullPath("/work/Report.cs"))); + } + + [Fact] + public async Task Esc_closes_the_dialog_and_changes_nothing() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => { Field(workbench).Text = "Count"; host.App.InjectKey(Key.Esc); }, + () => Dialog(workbench) is null); + + Assert.Equal(Diff.Split('\n'), Tab(workbench, "Diff.cs").Lines); + Assert.Empty(_server.Received("textDocument/rename")); + } + + [Theory] + [InlineData("", "New name is needed")] + [InlineData("Hunks", "New name is still Hunks")] + public async Task An_empty_or_unchanged_name_keeps_the_dialog_open_and_says_why(string typed, string why) + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + string said = ""; + string? marked = null; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => Submit(host, workbench, typed), + () => Dialog(workbench)!.Alert.Lines > 0, + () => { said = Dialog(workbench)!.Alert.Message; marked = Dialog(workbench)!.FieldLabel.SchemeName; host.App.InjectKey(Key.Esc); }, + () => Dialog(workbench) is null); + + Assert.Equal(why, said); + Assert.Equal(SchemeNames.Error, marked); + Assert.Empty(_server.Received("textDocument/rename")); + } + + [Fact] + public async Task A_name_the_server_refuses_keeps_the_dialog_open_and_says_why_in_its_words() + { + _server.RenameError = "Twice is already defined in Diff"; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + string said = ""; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => Submit(host, workbench, "Twice"), + () => Dialog(workbench)!.Alert.Lines > 0, + () => { said = Dialog(workbench)!.Alert.Message; host.App.InjectKey(Key.Esc); }, + () => Dialog(workbench) is null); + + Assert.Equal("New name: Twice is already defined in Diff", said); + Assert.Equal(Diff.Split('\n'), Tab(workbench, "Diff.cs").Lines); + } + + [Fact] + public async Task On_a_keyword_the_dialog_doesnt_open_and_the_status_bar_says_why() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + var said = ""; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 5); Rs(host); }, + () => _server.Received("textDocument/prepareRename").Any() && workbench.StatusBar.Message == "Can't rename this", + () => { said = workbench.StatusBar.Message; }); + + Assert.Equal("Can't rename this", said); + Assert.Null(Dialog(workbench)); + } + + [Fact] + public async Task Where_prepareRename_refuses_the_status_bar_says_why_in_the_servers_words() + { + _server.PrepareRenameError = "it's defined in a library"; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => workbench.StatusBar.Message.StartsWith("Can't rename", StringComparison.Ordinal)); + + Assert.Equal("Can't rename this: it's defined in a library", workbench.StatusBar.Message); + Assert.Null(Dialog(workbench)); + } + + [Fact] + public async Task With_a_server_that_doesnt_rename_the_status_bar_says_so() + { + _server.RenameProvider = null; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => workbench.StatusBar.Message.StartsWith("Can't rename", StringComparison.Ordinal)); + + Assert.Equal("Can't rename this: the C# language server doesn't rename", workbench.StatusBar.Message); + Assert.Null(Dialog(workbench)); + Assert.Empty(_server.Received("textDocument/prepareRename")); + } + + [Fact] + public async Task Without_the_server_installed_rs_says_how_to_install_it() + { + _server.Missing = true; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => { workbench.StatusBar.ShowMessage("elsewhere"); Rs(host); }, + () => workbench.StatusBar.Message != "elsewhere"); + + Assert.Equal("No C# language server. Install: dotnet tool install -g csharp-ls", workbench.StatusBar.Message); + Assert.Null(Dialog(workbench)); + } + + [Fact] + public async Task While_the_server_loads_the_Edit_menu_dims_Rename_symbol() + { + _server.HoldLoading = true; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + bool dimmedWhileLoading = false, dimmedWhenReady = true; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => workbench.StatusBar.DisplayedState.Contains("C# ◌ loading", StringComparison.Ordinal), + () => host.App.InjectKey(Key.E.WithAlt), + () => workbench.MenuBar.IsOpen(), + () => { dimmedWhileLoading = Item(host).Dimmed; host.App.InjectKey(Key.Esc); }, + () => !workbench.MenuBar.IsOpen(), + () => { _server.FinishLoading(); }, + () => Ready(workbench), + () => host.App.InjectKey(Key.E.WithAlt), + () => workbench.MenuBar.IsOpen(), + () => { dimmedWhenReady = Item(host).Dimmed; host.App.InjectKey(Key.Esc); }, + () => !workbench.MenuBar.IsOpen()); + + Assert.True(dimmedWhileLoading); + Assert.False(dimmedWhenReady); + } + + [Fact] + public void Rs_has_no_key_and_a_place_in_the_Edit_menu_after_Replace_globally() + { + 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("Rename symbol", commands.Registered.Single(c => c.Id == CommandIds.RenameSymbol).Label); + Assert.Equal(CommandScope.Editor, commands.ScopeOf(CommandIds.RenameSymbol)); + Assert.Equal("rs", CommandMnemonics.For(CommandIds.RenameSymbol)); + Assert.DoesNotContain(keybindings.Bindings, b => b.CommandId == CommandIds.RenameSymbol); + var items = host.Menu.Items.Select(i => i.Id).ToList(); + Assert.Equal(items.IndexOf(CommandIds.ReplaceGlobally) + 1, items.IndexOf(CommandIds.RenameSymbol)); + } + + 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 Rs(WorkbenchHost host) + { + host.App.InjectKey(Key.Space.WithCtrl); + host.App.InjectKey(Key.R); + host.App.InjectKey(Key.S); + } + + private static void Submit(WorkbenchHost host, Workbench.Workbench workbench, string name) + { + Field(workbench).Text = name; + host.App.InjectKey(Key.Enter.WithCtrl); + } + + private static RenameSymbolView? Dialog(Workbench.Workbench workbench) => workbench.SubViews.OfType().SingleOrDefault(); + + private static TextField Field(Workbench.Workbench workbench) => Dialog(workbench)!.SubViews.OfType().Single(); + + private static TuiCode.Workbench.Menus.CommandMenuItem Item(WorkbenchHost host) => + host.Menu.Items.Single(i => i.Id == CommandIds.RenameSymbol).Item; + + private void OpenFile(Workbench.Workbench workbench, string name) => + workbench.OpenFile(_fs.FileInfo.New($"/work/{name}")); + + private static TuiCode.Editor.EditorTab Tab(Workbench.Workbench workbench, string name) => + workbench.Editor.Groups.Tabs.Single(t => t.File.Name == name); + + 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, 100, 30); + return host; + } +} diff --git a/tests/TuiCode.Tests/TextEditsTests.cs b/tests/TuiCode.Tests/TextEditsTests.cs new file mode 100644 index 00000000..dcd96486 --- /dev/null +++ b/tests/TuiCode.Tests/TextEditsTests.cs @@ -0,0 +1,57 @@ +using TuiCode.Workbench.Languages; + +namespace TuiCode.Tests; + +public class TextEditsTests +{ + [Fact] + public void Apply_makes_several_edits_on_one_line_whatever_order_they_come_in() + { + var renamed = TextEdits.Apply("a = Sum(Sum(1));\n", [new(0, 8, 0, 11, "Total"), new(0, 4, 0, 7, "Total")]); + + Assert.Equal("a = Total(Total(1));\n", renamed); + } + + [Fact] + public void Apply_keeps_each_line_ending_as_it_was() + { + var renamed = TextEdits.Apply("int Sum;\r\nSum();\nreturn Sum;\r", [new(0, 4, 0, 7, "Total"), new(1, 0, 1, 3, "Total"), new(2, 7, 2, 10, "Total")]); + + Assert.Equal("int Total;\r\nTotal();\nreturn Total;\r", renamed); + } + + [Fact] + public void Apply_counts_columns_in_UTF16_chars() + { + var renamed = TextEdits.Apply("var 😀 = Sum;", [new(0, 9, 0, 12, "Total")]); + + Assert.Equal("var 😀 = Total;", renamed); + } + + [Fact] + public void Apply_can_span_lines() + { + Assert.Equal("one\nfour", TextEdits.Apply("one\ntwo\nthree\nfour", [new(1, 0, 3, 0, "")])); + } + + [Fact] + public void Apply_refuses_an_edit_past_the_end_of_its_line_or_the_file() + { + Assert.Null(TextEdits.Apply("int Sum;\n", [new(0, 4, 0, 12, "Total")])); + Assert.Null(TextEdits.Apply("int Sum;\n", [new(4, 0, 4, 3, "Total")])); + } + + [Fact] + public void Apply_refuses_overlapping_edits() + { + Assert.Null(TextEdits.Apply("int Sum;", [new(0, 4, 0, 7, "Total"), new(0, 5, 0, 6, "x")])); + } + + [Fact] + public void NewStarts_follows_each_edit_past_the_ones_before_it() + { + var places = TextEdits.NewStarts([new(0, 8, 0, 11, "Total"), new(0, 4, 0, 7, "Total"), new(1, 0, 2, 0, "a\nb\nc\n"), new(3, 2, 3, 5, "Total")]); + + Assert.Equal([(0, 10), (0, 4), (1, 0), (5, 2)], places); + } +} diff --git a/tests/TuiCode.Tests/WorkspaceRenameTests.cs b/tests/TuiCode.Tests/WorkspaceRenameTests.cs new file mode 100644 index 00000000..65b625c2 --- /dev/null +++ b/tests/TuiCode.Tests/WorkspaceRenameTests.cs @@ -0,0 +1,121 @@ +using System.Text; +using TuiCode.Editor; +using TuiCode.Workbench.Languages; +using TuiCode.Workbench.Rename; + +namespace TuiCode.Tests; + +public class WorkspaceRenameTests +{ + private readonly MockFileSystem _fs = new(); + + private string Full(string path) => _fs.Path.GetFullPath(path); + + [Fact] + public void Plan_splits_the_files_into_open_and_closed_and_counts_the_changes() + { + _fs.AddFile("/work/A.cs", new MockFileData("int Sum;")); + _fs.AddFile("/work/B.cs", new MockFileData("Sum(); Sum();")); + _fs.AddFile("/work/C.cs", new MockFileData("Sum();")); + + var rename = WorkspaceRename.Plan( + [ + new FileEdit(Full("/work/A.cs"), [new(0, 4, 0, 7, "Total")]), + new FileEdit(Full("/work/B.cs"), [new(0, 0, 0, 3, "Total"), new(0, 7, 0, 10, "Total")]), + new FileEdit(Full("/work/C.cs"), [new(0, 0, 0, 3, "Total")]), + new FileEdit(Full("/work/Gone.cs"), [new(0, 0, 0, 3, "Total")]), + ], new Dictionary { [Full("/work/A.cs")] = "int Sum;" }, _fs); + + Assert.Equal([Full("/work/A.cs")], rename.Open.Select(f => f.Path)); + Assert.Equal([Full("/work/B.cs"), Full("/work/C.cs")], rename.Closed.Select(f => f.Path)); + Assert.Equal(4, rename.Changes); + Assert.Equal(3, rename.Files); + } + + [Fact] + public void Apply_edits_an_open_tab_as_one_undo_step_and_leaves_it_unsaved() + { + _fs.AddFile("/work/A.cs", new MockFileData("class A\n{\n int Sum() => 1;\n int Twice() => Sum() + Sum();\n}\n")); + using var tab = new EditorTab(_fs.FileInfo.New("/work/A.cs")); + var rename = Plan(tab, [new(2, 8, 2, 11, "Total"), new(3, 19, 3, 22, "Total"), new(3, 27, 3, 30, "Total")]); + + var result = rename.Apply([tab], _fs); + + Assert.Equal(["class A", "{", " int Total() => 1;", " int Twice() => Total() + Total();", "}", ""], tab.Lines); + Assert.True(tab.IsDirty); + Assert.Equal("class A\n{\n int Sum() => 1;\n int Twice() => Sum() + Sum();\n}\n", _fs.File.ReadAllText("/work/A.cs")); + Assert.Equal(3, result.Changes); + Assert.Empty(result.Skipped); + + tab.SubViews.OfType().Single().Undo(); + + Assert.Equal(["class A", "{", " int Sum() => 1;", " int Twice() => Sum() + Sum();", "}", ""], tab.Lines); + } + + [Fact] + public void Apply_leaves_a_tab_edited_since_the_server_was_asked_alone() + { + _fs.AddFile("/work/A.cs", new MockFileData("int Sum;")); + using var tab = new EditorTab(_fs.FileInfo.New("/work/A.cs")); + var rename = Plan(tab, [new(0, 4, 0, 7, "Total")]); + tab.ReplaceLines(0, 1, ["int Sum;"]); + + var result = rename.Apply([tab], _fs); + + Assert.Equal(["int Sum;"], tab.Lines); + Assert.Equal([Full("/work/A.cs")], result.Skipped); + Assert.Empty(result.Applied); + } + + [Fact] + public void Apply_writes_a_closed_file_keeping_its_BOM_and_line_endings() + { + byte[] bom = [0xEF, 0xBB, 0xBF]; + _fs.AddFile("/work/B.cs", new MockFileData([.. bom, .. Encoding.UTF8.GetBytes("int Sum;\r\nSum();\r\n")])); + var rename = WorkspaceRename.Plan([new FileEdit(Full("/work/B.cs"), [new(0, 4, 0, 7, "Total"), new(1, 0, 1, 3, "Total")])], + new Dictionary(), _fs); + + var result = rename.Apply([], _fs); + + Assert.Equal([.. bom, .. Encoding.UTF8.GetBytes("int Total;\r\nTotal();\r\n")], _fs.File.ReadAllBytes("/work/B.cs")); + Assert.Equal(2, result.Changes); + } + + [Fact] + public void Apply_leaves_a_closed_file_that_changed_on_disk_since_the_server_answered_as_it_is() + { + _fs.AddFile("/work/B.cs", new MockFileData("int Sum;")); + var rename = WorkspaceRename.Plan([new FileEdit(Full("/work/B.cs"), [new(0, 4, 0, 7, "Total")])], new Dictionary(), _fs); + _fs.File.WriteAllText("/work/B.cs", "// moved\nint Sum;"); + + var result = rename.Apply([], _fs); + + Assert.Equal("// moved\nint Sum;", _fs.File.ReadAllText("/work/B.cs")); + Assert.Equal([Full("/work/B.cs")], result.Skipped); + } + + [Fact] + public void Apply_leaves_a_closed_file_whose_edit_falls_outside_it_as_it_is() + { + _fs.AddFile("/work/B.cs", new MockFileData("int Sum;")); + var rename = WorkspaceRename.Plan([new FileEdit(Full("/work/B.cs"), [new(3, 0, 3, 3, "Total")])], new Dictionary(), _fs); + + var result = rename.Apply([], _fs); + + Assert.Equal("int Sum;", _fs.File.ReadAllText("/work/B.cs")); + Assert.Equal([Full("/work/B.cs")], result.Skipped); + } + + [Fact] + public void ChangedLines_has_one_place_per_changed_line() + { + var result = new RenameResult([new FileEdit("/work/A.cs", [new(3, 19, 3, 22, "Total"), new(3, 27, 3, 30, "Total"), new(2, 8, 2, 11, "Total")])], []); + + Assert.Equal([new SourceLocation("/work/A.cs", 3, 19), new SourceLocation("/work/A.cs", 2, 8)], result.ChangedLines()); + Assert.Equal(3, result.Changes); + } + + private WorkspaceRename Plan(EditorTab tab, IReadOnlyList edits) => + WorkspaceRename.Plan([new FileEdit(tab.File.FullName, edits)], + new Dictionary { [tab.File.FullName] = string.Join('\n', tab.Lines) }, _fs); +} From 3d1d4c5c0970b2d217b80658d30cd39ff6a792c8 Mon Sep 17 00:00:00 2001 From: "a-team-app[bot]" <334837322+a-team-app[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:38:05 +1300 Subject: [PATCH 2/6] Give the fake server's created file a full path, so the test doesn't hang on Windows new Uri("/work/New.cs") throws on Windows, so the fake never answered textDocument/rename and Rename_reads_documentChanges_and_leaves_out_the_file_operations waited until CI's 30-minute timeout. Closes #697 Co-Authored-By: Claude Opus 5.5 --- tests/TuiCode.Tests/FakeLanguageServer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/TuiCode.Tests/FakeLanguageServer.cs b/tests/TuiCode.Tests/FakeLanguageServer.cs index 015adb52..8f0bbd84 100644 --- a/tests/TuiCode.Tests/FakeLanguageServer.cs +++ b/tests/TuiCode.Tests/FakeLanguageServer.cs @@ -217,7 +217,7 @@ private JsonObject Capabilities() foreach (var (file, edits) in byFile) changes[LspLocations.ToUri(file)] = edits; return new JsonObject { ["changes"] = changes }; } - var documentChanges = new JsonArray(new JsonObject { ["kind"] = "create", ["uri"] = LspLocations.ToUri("/work/New.cs") }); + var documentChanges = new JsonArray(new JsonObject { ["kind"] = "create", ["uri"] = LspLocations.ToUri(System.IO.Path.GetFullPath("/work/New.cs")) }); foreach (var (file, edits) in byFile) documentChanges.Add(new JsonObject { From 6c4b8458eeaf449dd6daf83eec9a6a88f116f0bf Mon Sep 17 00:00:00 2001 From: "a-team-app[bot]" <334837322+a-team-app[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:30:58 +1300 Subject: [PATCH 3/6] Read Usages rows from tabs in either group, and say a skipped file was left unchanged After a rename, a changed file open in the other editor group had its Usages rows read from disk, showing the old name. Rows now come from whichever group holds the tab. The status bar said every skipped file "changed while renaming", but a file is also skipped when it isn't UTF-8, can't be written, or is read-only. It now says the file was left unchanged. Closes #697 Co-Authored-By: Claude Opus 5.5 --- src/TuiCode.Workbench/WorkbenchHost.cs | 4 +- tests/TuiCode.Tests/RenameSymbolHostTests.cs | 50 +++++++++++++++++++- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index 6c104c24..7cd24876 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -2062,14 +2062,14 @@ private void ApplyRename(LanguageServer server, WorkspaceRename rename, string o ShowSidebarTab(SidebarTab.Usages); if (result.Skipped.Count > 0) _workbench.StatusBar.ShowMessage( - $"Renamed {oldName} to {newName}, except in {string.Join(", ", result.Skipped.Select(Path.GetFileName))}, which changed while renaming", + $"Renamed {oldName} to {newName}, but left {string.Join(", ", result.Skipped.Select(Path.GetFileName))} unchanged", Severity.Error); else _workbench.StatusBar.ShowMessage($"Renamed {oldName} to {newName}"); } private IReadOnlyList LinesOf(IFileSystem fileSystem, string path) => - _workbench.Editor.Group.Tabs.FirstOrDefault(t => t.File.FullName == path) is { } open + _workbench.Editor.Groups.Tabs.FirstOrDefault(t => t.File.FullName == path) is { } open ? open.Lines : [.. fileSystem.File.ReadLines(path)]; diff --git a/tests/TuiCode.Tests/RenameSymbolHostTests.cs b/tests/TuiCode.Tests/RenameSymbolHostTests.cs index 73f75ebf..3fcae6b7 100644 --- a/tests/TuiCode.Tests/RenameSymbolHostTests.cs +++ b/tests/TuiCode.Tests/RenameSymbolHostTests.cs @@ -25,6 +25,7 @@ public class RenameSymbolHostTests : StaticConfigurationTest private readonly MockFileSystem _fs = new(); private readonly FakeLanguageServer _server = new(); + private readonly CommandService _commands = new(); public RenameSymbolHostTests() { @@ -155,6 +156,52 @@ await HostSteps.Run(host, p => p!["changes"]![0]!["uri"]!.GetValue() == TuiCode.Workbench.Languages.LspLocations.ToUri(_fs.Path.GetFullPath("/work/Report.cs"))); } + [Fact] + public async Task With_the_editor_split_Usages_shows_the_renamed_lines_of_a_tab_in_the_other_group() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + var pane = workbench.Sidebar.Usages; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Report.cs"), + () => OpenFile(workbench, "Diff.cs"), + () => _commands.TryExecute(CommandIds.MoveToOtherGroup), + () => workbench.Editor.Groups.IsSplit && Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => Submit(host, workbench, "Count"), + () => pane.Files.Count > 0); + + Assert.DoesNotContain(Tab(workbench, "Report.cs"), workbench.Editor.Group.Tabs); + Assert.Equal(["3 int Count() => 0;", "5 int Twice() => Count() * 2;", "5 Diff.Count();"], + pane.Files.SelectMany(f => f.Children).Select(u => u.ToString())); + } + + [Fact] + public async Task A_file_the_rename_cant_write_is_named_in_the_status_bar_as_left_unchanged() + { + const string latin1 = "// caf\u00e9\r\n" + Report; + _fs.AddFile("/work/Report.cs", new MockFileData(System.Text.Encoding.Latin1.GetBytes(latin1))); + _server.Files[_fs.Path.GetFullPath("/work/Report.cs")] = latin1; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => Dialog(workbench) is not null, + () => Submit(host, workbench, "Count"), + () => ConfirmDialogs.Of(workbench) is not null, + ConfirmDialogs.Choose(host, workbench, "Rename"), + () => workbench.StatusBar.Message.StartsWith("Renamed", StringComparison.Ordinal)); + + Assert.Equal("Renamed Hunks to Count, but left Report.cs unchanged", workbench.StatusBar.Message); + Assert.Equal(Renamed, Tab(workbench, "Diff.cs").Lines); + Assert.Equal(System.Text.Encoding.Latin1.GetBytes(latin1), _fs.File.ReadAllBytes("/work/Report.cs")); + } + [Fact] public async Task Esc_closes_the_dialog_and_changes_nothing() { @@ -376,8 +423,7 @@ private Workbench.Workbench BuildWorkbench() private WorkbenchHost BuildHost(Workbench.Workbench workbench) { - var commands = new CommandService(); - var host = new WorkbenchHost(workbench, commands, new KeybindingService(commands), new InputScopeStack(), + var host = new WorkbenchHost(workbench, _commands, new KeybindingService(_commands), new InputScopeStack(), new InMemorySettingsService(), driverName: DriverRegistry.Names.ANSI, languageServers: _server); HostSteps.PinScreenSize(host, 100, 30); return host; From 662760de081214b5e11a65db1b1479d0f12f86f2 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:22:00 +1300 Subject: [PATCH 4/6] Rename the name just before the cursor, and keep a leading _ in the dialog's title csharp-ls answers prepareRename with null when the cursor is just past a name (before a `;` say), so `rs` there said "Can't rename this". Ask about the start of the identifier at or just before the cursor instead, as the word fallback already did. And `_` in the dialog's title was taken as a hotkey marker, so "Rename _bar" showed as "Rename bar". Closes #697 Co-Authored-By: Claude Opus 5.5 --- .../Rename/RenameSymbolView.cs | 1 + src/TuiCode.Workbench/WorkbenchHost.cs | 26 ++++++++----- tests/TuiCode.Tests/FakeLanguageServer.cs | 2 + tests/TuiCode.Tests/RenameSymbolHostTests.cs | 39 +++++++++++++++++++ 4 files changed, 59 insertions(+), 9 deletions(-) diff --git a/src/TuiCode.Workbench/Rename/RenameSymbolView.cs b/src/TuiCode.Workbench/Rename/RenameSymbolView.cs index e05848b3..306c7207 100644 --- a/src/TuiCode.Workbench/Rename/RenameSymbolView.cs +++ b/src/TuiCode.Workbench/Rename/RenameSymbolView.cs @@ -18,6 +18,7 @@ public sealed class RenameSymbolView : AppDialog public RenameSymbolView(string name) : base($"Rename {name}", 60, ContentRows) { + HotKeySpecifier = VerbatimLabel.NoHotKey; OldName = name; _label = new VerbatimLabel { X = 1, Y = 0, Width = Dim.Fill(1), Text = "New name:" }; _input = new PlaceholderField { X = 1, Y = 1, Width = Dim.Fill(1), Text = name }; diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index 7cd24876..e162b79b 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -1968,7 +1968,8 @@ private void RenameSymbol() status.ShowMessage($"Can't rename this: the {server.Spec.Name} language server doesn't rename"); return; } - var (path, row, character) = (tab.File.FullName, tab.CursorRow, tab.CursorCharacter); + var (path, row) = (tab.File.FullName, tab.CursorRow); + var character = IdentifierStart(tab.Lines[row], tab.CursorCharacter) ?? tab.CursorCharacter; var word = IdentifierAt(tab.Lines[row], character); var request = ++_renameRequest; server.PrepareRenameAsync(path, row, character).ContinueWith(answer => _app.Invoke(() => @@ -2135,16 +2136,23 @@ private void JumpTo(IFileSystem fileSystem, EditorTab? origin, SourceLocation lo } /// The identifier is in or just after, or null on whitespace and punctuation. - internal static string? IdentifierAt(string line, int index) + private static bool IdentifierPart(char c) => char.IsLetterOrDigit(c) || c == '_'; + + /// Where the identifier under , or just before it, starts; null when there's none. + internal static int? IdentifierStart(string line, int index) { - static bool Part(char c) => char.IsLetterOrDigit(c) || c == '_'; index = Math.Min(index, line.Length); - if (index == line.Length || !Part(line[index])) index--; - if (index < 0 || !Part(line[index])) return null; - var start = index; - while (start > 0 && Part(line[start - 1])) start--; - var end = index; - while (end + 1 < line.Length && Part(line[end + 1])) end++; + if (index == line.Length || !IdentifierPart(line[index])) index--; + if (index < 0 || !IdentifierPart(line[index])) return null; + while (index > 0 && IdentifierPart(line[index - 1])) index--; + return index; + } + + internal static string? IdentifierAt(string line, int index) + { + if (IdentifierStart(line, index) is not { } start) return null; + var end = start; + while (end + 1 < line.Length && IdentifierPart(line[end + 1])) end++; return line[start..(end + 1)]; } diff --git a/tests/TuiCode.Tests/FakeLanguageServer.cs b/tests/TuiCode.Tests/FakeLanguageServer.cs index 8f0bbd84..d07a692d 100644 --- a/tests/TuiCode.Tests/FakeLanguageServer.cs +++ b/tests/TuiCode.Tests/FakeLanguageServer.cs @@ -182,6 +182,7 @@ private JsonObject Capabilities() return capabilities; } + // Like csharp-ls, which says a place just past a name can't be renamed. private JsonObject? PrepareRename(JsonNode parameters) { if (WordAt(parameters) is not { } word) return null; @@ -189,6 +190,7 @@ private JsonObject Capabilities() var character = parameters["position"]!["character"]!.GetValue(); var text = Lines(Sources()[Path(parameters["textDocument"]!)])[line]; var match = WordPattern().Matches(text).First(m => m.Index <= character && character <= m.Index + m.Length); + if (character == match.Index + match.Length) return null; return new JsonObject { ["range"] = Range(line, match.Index, line, match.Index + word.Length), ["placeholder"] = word }; } diff --git a/tests/TuiCode.Tests/RenameSymbolHostTests.cs b/tests/TuiCode.Tests/RenameSymbolHostTests.cs index 3fcae6b7..31bcb341 100644 --- a/tests/TuiCode.Tests/RenameSymbolHostTests.cs +++ b/tests/TuiCode.Tests/RenameSymbolHostTests.cs @@ -56,6 +56,45 @@ await HostSteps.Run(host, Assert.Single(_server.Received("textDocument/prepareRename")); } + [Fact] + public async Task Rs_just_past_a_name_renames_that_name() + { + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + RenameSymbolView? view = null; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { workbench.Editor.Group.ActiveTab!.MoveCursor(2, 13); Rs(host); }, + () => (view = Dialog(workbench)) is not null, + () => host.App.InjectKey(Key.Esc), + () => Dialog(workbench) is null); + + Assert.Equal("Hunks", view!.NewName); + Assert.Equal(8, _server.Received("textDocument/prepareRename").Single()!["position"]!["character"]!.GetValue()); + } + + [Fact] + public async Task A_name_starting_with_an_underscore_keeps_it_in_the_title() + { + Add("/work/Foo.cs", "class Foo\n{\n private int _bar;\n}\n"); + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + RenameSymbolView? view = null; + + await HostSteps.Run(host, + () => OpenFile(workbench, "Foo.cs"), + () => Ready(workbench), + () => { workbench.Editor.Group.ActiveTab!.MoveCursor(2, 20); Rs(host); }, + () => (view = Dialog(workbench)) is not null, + () => host.App.InjectKey(Key.Esc), + () => Dialog(workbench) is null); + + Assert.Equal("_bar", view!.NewName); + Assert.Equal(Key.Empty, view.HotKey); + } + [Fact] public async Task With_every_file_open_Ctrl_Enter_renames_in_the_tabs_unsaved_and_Ctrl_Z_takes_a_tab_back() { From b1607f1e8c53461c69a7fc23f1f1bddbfd19e175 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:22:16 +1300 Subject: [PATCH 5/6] Keep IdentifierAt's summary on it Closes #697 Co-Authored-By: Claude Opus 5.5 --- src/TuiCode.Workbench/WorkbenchHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index e162b79b..e660b5ce 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -2135,7 +2135,6 @@ private void JumpTo(IFileSystem fileSystem, EditorTab? origin, SourceLocation lo _history.Visit(new CursorLocation(tab.File.FullName, tab.CursorRow, tab.CursorColumn), explicitJump: true); } - /// The identifier is in or just after, or null on whitespace and punctuation. private static bool IdentifierPart(char c) => char.IsLetterOrDigit(c) || c == '_'; /// Where the identifier under , or just before it, starts; null when there's none. @@ -2148,6 +2147,7 @@ private void JumpTo(IFileSystem fileSystem, EditorTab? origin, SourceLocation lo return index; } + /// The identifier is in or just after, or null on whitespace and punctuation. internal static string? IdentifierAt(string line, int index) { if (IdentifierStart(line, index) is not { } start) return null; From 62f6b0ff5881e13dc2c0c9e7eb71de8994c92367 Mon Sep 17 00:00:00 2001 From: "a-team-app[bot]" <334837322+a-team-app[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:07:59 +1300 Subject: [PATCH 6/6] Say when Rename symbol can't rename because the file is in no C# project csharp-ls only knows files inside a project it loaded, and answers prepareRename with null for any other, so a loose test.cs at a repo root got a bare "Can't rename this". When no folder from the file's up to the server's root holds a .csproj, the status bar now says so. Closes #697 Co-Authored-By: Claude Opus 5.5 --- src/TuiCode.Workbench/WorkbenchHost.cs | 17 ++++++++++++++++- tests/TuiCode.Tests/FakeLanguageServer.cs | 5 ++++- tests/TuiCode.Tests/RenameSymbolHostTests.cs | 20 ++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/TuiCode.Workbench/WorkbenchHost.cs b/src/TuiCode.Workbench/WorkbenchHost.cs index 39ddcbcb..8330874e 100644 --- a/src/TuiCode.Workbench/WorkbenchHost.cs +++ b/src/TuiCode.Workbench/WorkbenchHost.cs @@ -2036,7 +2036,9 @@ private void RenameSymbol() } if (answer.Result is not { } target) { - status.ShowMessage("Can't rename this"); + status.ShowMessage(OutsideEveryProject(tab, server) + ? $"Can't rename this: {tab.File.Name} isn't in any C# project" + : "Can't rename this"); return; } if ((target.Placeholder ?? TextIn(tab, target.Range) ?? word) is not { Length: > 0 } name) @@ -2048,6 +2050,19 @@ private void RenameSymbol() }), TaskScheduler.Default); } + /// Whether no folder from the file's up to the server's root holds a .csproj, which C# servers need to know a file. + private static bool OutsideEveryProject(EditorTab tab, LanguageServer server) + { + if (server.Spec.LanguageId != "csharp") return false; + var fileSystem = tab.File.FileSystem; + for (var folder = tab.File.Directory; folder is not null; folder = folder.Parent) + { + if (fileSystem.Directory.Exists(folder.FullName) && fileSystem.Directory.EnumerateFiles(folder.FullName, "*.csproj").Any()) return false; + if (LspLocations.PathComparer.Equals(folder.FullName.TrimEnd('/', '\\'), server.Root.TrimEnd('/', '\\'))) break; + } + return true; + } + private static string? TextIn(EditorTab tab, TextEdit? range) { if (range is not { } r || r.StartLine != r.EndLine || r.StartLine >= tab.Lines.Count) return null; diff --git a/tests/TuiCode.Tests/FakeLanguageServer.cs b/tests/TuiCode.Tests/FakeLanguageServer.cs index e7e63491..2c891289 100644 --- a/tests/TuiCode.Tests/FakeLanguageServer.cs +++ b/tests/TuiCode.Tests/FakeLanguageServer.cs @@ -75,6 +75,9 @@ internal sealed partial class FakeLanguageServer : ILanguageServerLauncher /// Answers prepareRename with this error. public string? PrepareRenameError { get; set; } + /// Answers every prepareRename with null, as csharp-ls does for a file outside its projects. + public bool PrepareRenameRefuses { get; set; } + /// Answers rename with this error. public string? RenameError { get; set; } @@ -185,7 +188,7 @@ private void Progress(InProcessServer server, string kind) => "initialize" => Initialized(), "textDocument/implementation" => Implementations(parameters!), "textDocument/prepareRename" when PrepareRenameError is { } error => throw new JsonRpcException(-32603, error), - "textDocument/prepareRename" => PrepareRename(parameters!), + "textDocument/prepareRename" => PrepareRenameRefuses ? null : PrepareRename(parameters!), "textDocument/rename" when RenameError is { } error => throw new JsonRpcException(-32603, error), "textDocument/rename" => Rename(parameters!), "textDocument/definition" => Definitions(parameters!), diff --git a/tests/TuiCode.Tests/RenameSymbolHostTests.cs b/tests/TuiCode.Tests/RenameSymbolHostTests.cs index 31bcb341..9a09da1c 100644 --- a/tests/TuiCode.Tests/RenameSymbolHostTests.cs +++ b/tests/TuiCode.Tests/RenameSymbolHostTests.cs @@ -31,6 +31,7 @@ public RenameSymbolHostTests() { Add("/work/Diff.cs", Diff); Add("/work/Report.cs", Report); + _fs.AddFile("/work/Work.csproj", new MockFileData("")); } [Fact] @@ -324,6 +325,25 @@ await HostSteps.Run(host, Assert.Null(Dialog(workbench)); } + [Fact] + public async Task In_a_file_outside_every_project_the_status_bar_says_so() + { + _fs.RemoveFile("/work/Work.csproj"); + _fs.AddFile("/work/src/Lib/Lib.csproj", new MockFileData("")); + _server.PrepareRenameRefuses = true; + using var workbench = BuildWorkbench(); + using var host = BuildHost(workbench); + + await HostSteps.Run(host, + () => OpenFile(workbench, "Diff.cs"), + () => Ready(workbench), + () => { Tab(workbench, "Diff.cs").MoveCursor(2, 10); Rs(host); }, + () => workbench.StatusBar.Message.StartsWith("Can't rename", StringComparison.Ordinal)); + + Assert.Equal("Can't rename this: Diff.cs isn't in any C# project", workbench.StatusBar.Message); + Assert.Null(Dialog(workbench)); + } + [Fact] public async Task Where_prepareRename_refuses_the_status_bar_says_why_in_the_servers_words() {