Skip to content
Merged
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ What follows is how TuiCode implements it today.
- **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.
- **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)
Expand Down
1 change: 1 addition & 0 deletions src/TuiCode.Abstractions/CommandIds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,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";
Expand Down
1 change: 1 addition & 0 deletions src/TuiCode.Abstractions/CommandMnemonics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ private static IReadOnlyDictionary<string, string> 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
Expand Down
42 changes: 42 additions & 0 deletions src/TuiCode.Workbench/Languages/LanguageServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,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<Action> post)
{
Expand Down Expand Up @@ -104,6 +105,7 @@ 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;
lock (_gate) _renameProvider = initialized?["capabilities"]?["renameProvider"]?.DeepClone();
if (KnownLanguageServers.WithCommand(Spec.LanguageId, Spec.Command) is null
&& initialized?["serverInfo"]?["name"]?.GetValue<string>() is { Length: > 0 } name)
Title = name;
Expand Down Expand Up @@ -146,6 +148,7 @@ private JsonObject InitializeParams()
["workspace"] = new JsonObject
{
["workspaceFolders"] = true,
["workspaceEdit"] = new JsonObject { ["documentChanges"] = true },
["configuration"] = true,
["symbol"] = new JsonObject
{
Expand All @@ -160,6 +163,7 @@ private JsonObject InitializeParams()
["implementation"] = 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 } },
},
Expand Down Expand Up @@ -333,6 +337,44 @@ public async Task<IReadOnlyList<SourceLocation>> ReferencesAsync(string path, in
return LspSymbols.QualifiedName(symbols, location.Line, location.Character);
}

/// <summary>Whether the server said it can rename.</summary>
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; }
}

/// <summary>What can be renamed at <paramref name="line"/> and UTF-16 <paramref name="character"/>: the default when the server doesn't say, null when it says nothing can.</summary>
public async Task<RenameTarget?> PrepareRenameAsync(string path, int line, int character) =>
CanPrepareRename
? LspRename.ParsePrepare(await RequestAsync("textDocument/prepareRename", Position(path, line, character)).ConfigureAwait(false))
: new RenameTarget(null, null);

/// <summary>The edits that rename the symbol at <paramref name="line"/> and UTF-16 <paramref name="character"/> to <paramref name="newName"/>.</summary>
public async Task<IReadOnlyList<FileEdit>> 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));
}

/// <summary>Tells the server that files it doesn't have open changed on disk.</summary>
public void FilesChanged(IEnumerable<string> 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 })]),
});
}
}

/// <summary>The types in the folder whose names match <paramref name="query"/>, as the server matches them.</summary>
public async Task<IReadOnlyList<TypeSymbol>> TypesAsync(string query, CancellationToken cancellationToken = default) =>
LspTypes.Parse(await RequestAsync("workspace/symbol", new JsonObject { ["query"] = query }, cancellationToken).ConfigureAwait(false));
Expand Down
63 changes: 63 additions & 0 deletions src/TuiCode.Workbench/Languages/LspRename.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Text.Json.Nodes;

namespace TuiCode.Workbench.Languages;

/// <summary>A replacement of the text between two places, as LSP counts them: 0-based lines and UTF-16 columns.</summary>
public readonly record struct TextEdit(int StartLine, int StartCharacter, int EndLine, int EndCharacter, string NewText);

/// <summary>The edits a workspace edit makes to one file.</summary>
public sealed record FileEdit(string Path, IReadOnlyList<TextEdit> Edits);

/// <summary>What <c>textDocument/prepareRename</c> said: the name's range, and the name to offer when the server gives one.</summary>
public sealed record RenameTarget(TextEdit? Range, string? Placeholder);

public static class LspRename
{
/// <summary>A <c>prepareRename</c> answer, or null when the server says the place can't be renamed.</summary>
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<string>());
return answer["start"] is not null ? new RenameTarget(Range(answer), null) : null;
}

/// <summary>The text edits in a <c>WorkspaceEdit</c>, from <c>documentChanges</c> if it has them, else <c>changes</c>; file operations are left out.</summary>
public static IReadOnlyList<FileEdit> ParseWorkspaceEdit(JsonNode? result)
{
var byPath = new Dictionary<string, List<TextEdit>>(LspLocations.PathComparer);
var order = new List<string>();
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<JsonObject>())
if (edit["range"] is JsonObject range && edit["newText"]?.GetValue<string>() is { } text)
list.Add(Range(range) with { NewText = text });
}

if (result?["documentChanges"] is JsonArray documentChanges)
{
foreach (var change in documentChanges.OfType<JsonObject>())
if (change["kind"] is null)
Add(change["textDocument"]?["uri"]?.GetValue<string>(), 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<int>() ?? 0,
range["start"]?["character"]?.GetValue<int>() ?? 0,
range["end"]?["line"]?.GetValue<int>() ?? 0,
range["end"]?["character"]?.GetValue<int>() ?? 0,
"");
}
73 changes: 73 additions & 0 deletions src/TuiCode.Workbench/Languages/TextEdits.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System.Text;

namespace TuiCode.Workbench.Languages;

/// <summary>Applies a server's text edits to a file's text, keeping its line endings as they are.</summary>
public static class TextEdits
{
/// <summary>The text with every edit made, or null when one falls outside it or two overlap.</summary>
public static string? Apply(string text, IReadOnlyList<TextEdit> 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();
}

/// <summary>Where each edit's new text starts once all of them are made, in edit order.</summary>
public static IReadOnlyList<(int Line, int Character)> NewStarts(IReadOnlyList<TextEdit> 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<int> LineStarts(string text)
{
var starts = new List<int> { 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<int> 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;
}
}
4 changes: 2 additions & 2 deletions src/TuiCode.Workbench/Menus/CommandMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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,
Expand Down
61 changes: 61 additions & 0 deletions src/TuiCode.Workbench/Rename/RenameSymbolView.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using MentalDesk.Tui.Dialogs;
using MentalDesk.Tui.Fields;
using TuiCode.Abstractions;

namespace TuiCode.Workbench.Rename;

/// <summary>Rename symbol's prompt (#697): the new name, starting as the old one, all of it selected.</summary>
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<string>? Submitted;

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 };
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();

/// <summary>Marks the name with why the server refused it, keeping the dialog open.</summary>
public void ShowError(string message) => Refuse(_input, $"New name: {message}");

/// <summary>Closes the dialog once the host has the rename.</summary>
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);
}
}
Loading
Loading