1package lsp
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log/slog"
8 "maps"
9 "os"
10 "path/filepath"
11 "strings"
12 "sync/atomic"
13 "time"
14
15 "github.com/charmbracelet/crush/internal/config"
16 "github.com/charmbracelet/crush/internal/csync"
17 "github.com/charmbracelet/crush/internal/fsext"
18 "github.com/charmbracelet/crush/internal/home"
19 powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
20 "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
21 "github.com/charmbracelet/x/powernap/pkg/transport"
22)
23
24// DiagnosticCounts holds the count of diagnostics by severity.
25type DiagnosticCounts struct {
26 Error int
27 Warning int
28 Information int
29 Hint int
30}
31
32type Client struct {
33 client *powernap.Client
34 name string
35
36 // File types this LSP server handles (e.g., .go, .rs, .py)
37 fileTypes []string
38
39 // Configuration for this LSP client
40 config config.LSPConfig
41
42 // Diagnostic change callback
43 onDiagnosticsChanged func(name string, count int)
44
45 // Diagnostic cache
46 diagnostics *csync.VersionedMap[protocol.DocumentURI, []protocol.Diagnostic]
47
48 // Cached diagnostic counts to avoid map copy on every UI render.
49 diagCountsCache DiagnosticCounts
50 diagCountsVersion uint64
51
52 // Files are currently opened by the LSP
53 openFiles *csync.Map[string, *OpenFileInfo]
54
55 // Server state
56 serverState atomic.Value
57}
58
59// New creates a new LSP client using the powernap implementation.
60func New(ctx context.Context, name string, config config.LSPConfig, resolver config.VariableResolver) (*Client, error) {
61 // Convert working directory to file URI
62 workDir, err := os.Getwd()
63 if err != nil {
64 return nil, fmt.Errorf("failed to get working directory: %w", err)
65 }
66
67 rootURI := string(protocol.URIFromPath(workDir))
68
69 command, err := resolver.ResolveValue(config.Command)
70 if err != nil {
71 return nil, fmt.Errorf("invalid lsp command: %w", err)
72 }
73
74 // Create powernap client config
75 clientConfig := powernap.ClientConfig{
76 Command: home.Long(command),
77 Args: config.Args,
78 RootURI: rootURI,
79 Environment: func() map[string]string {
80 env := make(map[string]string)
81 maps.Copy(env, config.Env)
82 return env
83 }(),
84 Settings: config.Options,
85 InitOptions: config.InitOptions,
86 WorkspaceFolders: []protocol.WorkspaceFolder{
87 {
88 URI: rootURI,
89 Name: filepath.Base(workDir),
90 },
91 },
92 }
93
94 // Create the powernap client
95 powernapClient, err := powernap.NewClient(clientConfig)
96 if err != nil {
97 return nil, fmt.Errorf("failed to create lsp client: %w", err)
98 }
99
100 client := &Client{
101 client: powernapClient,
102 name: name,
103 fileTypes: config.FileTypes,
104 diagnostics: csync.NewVersionedMap[protocol.DocumentURI, []protocol.Diagnostic](),
105 openFiles: csync.NewMap[string, *OpenFileInfo](),
106 config: config,
107 }
108
109 // Initialize server state
110 client.serverState.Store(StateStarting)
111
112 return client, nil
113}
114
115// Initialize initializes the LSP client and returns the server capabilities.
116func (c *Client) Initialize(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
117 if err := c.client.Initialize(ctx, false); err != nil {
118 return nil, fmt.Errorf("failed to initialize the lsp client: %w", err)
119 }
120
121 // Convert powernap capabilities to protocol capabilities
122 caps := c.client.GetCapabilities()
123 protocolCaps := protocol.ServerCapabilities{
124 TextDocumentSync: caps.TextDocumentSync,
125 CompletionProvider: func() *protocol.CompletionOptions {
126 if caps.CompletionProvider != nil {
127 return &protocol.CompletionOptions{
128 TriggerCharacters: caps.CompletionProvider.TriggerCharacters,
129 AllCommitCharacters: caps.CompletionProvider.AllCommitCharacters,
130 ResolveProvider: caps.CompletionProvider.ResolveProvider,
131 }
132 }
133 return nil
134 }(),
135 }
136
137 result := &protocol.InitializeResult{
138 Capabilities: protocolCaps,
139 }
140
141 c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
142 c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
143 c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
144 c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
145 c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(_ context.Context, _ string, params json.RawMessage) {
146 HandleDiagnostics(c, params)
147 })
148
149 return result, nil
150}
151
152// Close closes the LSP client.
153func (c *Client) Close(ctx context.Context) error {
154 // Try to close all open files first
155 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
156 defer cancel()
157
158 c.CloseAllFiles(ctx)
159
160 // Shutdown and exit the client
161 if err := c.client.Shutdown(ctx); err != nil {
162 slog.Warn("Failed to shutdown LSP client", "error", err)
163 }
164
165 return c.client.Exit()
166}
167
168// ServerState represents the state of an LSP server
169type ServerState int
170
171const (
172 StateStarting ServerState = iota
173 StateReady
174 StateError
175 StateDisabled
176)
177
178// GetServerState returns the current state of the LSP server
179func (c *Client) GetServerState() ServerState {
180 if val := c.serverState.Load(); val != nil {
181 return val.(ServerState)
182 }
183 return StateStarting
184}
185
186// SetServerState sets the current state of the LSP server
187func (c *Client) SetServerState(state ServerState) {
188 c.serverState.Store(state)
189}
190
191// GetName returns the name of the LSP client
192func (c *Client) GetName() string {
193 return c.name
194}
195
196// SetDiagnosticsCallback sets the callback function for diagnostic changes
197func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
198 c.onDiagnosticsChanged = callback
199}
200
201// WaitForServerReady waits for the server to be ready
202func (c *Client) WaitForServerReady(ctx context.Context) error {
203 cfg := config.Get()
204
205 // Set initial state
206 c.SetServerState(StateStarting)
207
208 // Create a context with timeout
209 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
210 defer cancel()
211
212 // Try to ping the server with a simple request
213 ticker := time.NewTicker(500 * time.Millisecond)
214 defer ticker.Stop()
215
216 if cfg != nil && cfg.Options.DebugLSP {
217 slog.Debug("Waiting for LSP server to be ready...")
218 }
219
220 c.openKeyConfigFiles(ctx)
221
222 for {
223 select {
224 case <-ctx.Done():
225 c.SetServerState(StateError)
226 return fmt.Errorf("timeout waiting for LSP server to be ready")
227 case <-ticker.C:
228 // Check if client is running
229 if !c.client.IsRunning() {
230 if cfg != nil && cfg.Options.DebugLSP {
231 slog.Debug("LSP server not ready yet", "server", c.name)
232 }
233 continue
234 }
235
236 // Server is ready
237 c.SetServerState(StateReady)
238 if cfg != nil && cfg.Options.DebugLSP {
239 slog.Debug("LSP server is ready")
240 }
241 return nil
242 }
243 }
244}
245
246// OpenFileInfo contains information about an open file
247type OpenFileInfo struct {
248 Version int32
249 URI protocol.DocumentURI
250}
251
252// HandlesFile checks if this LSP client handles the given file based on its extension.
253func (c *Client) HandlesFile(path string) bool {
254 // If no file types are specified, handle all files (backward compatibility)
255 if len(c.fileTypes) == 0 {
256 return true
257 }
258
259 name := strings.ToLower(filepath.Base(path))
260 for _, filetype := range c.fileTypes {
261 suffix := strings.ToLower(filetype)
262 if !strings.HasPrefix(suffix, ".") {
263 suffix = "." + suffix
264 }
265 if strings.HasSuffix(name, suffix) {
266 slog.Debug("handles file", "name", c.name, "file", name, "filetype", filetype)
267 return true
268 }
269 }
270 slog.Debug("doesn't handle file", "name", c.name, "file", name)
271 return false
272}
273
274// OpenFile opens a file in the LSP server.
275func (c *Client) OpenFile(ctx context.Context, filepath string) error {
276 if !c.HandlesFile(filepath) {
277 return nil
278 }
279
280 uri := string(protocol.URIFromPath(filepath))
281
282 if _, exists := c.openFiles.Get(uri); exists {
283 return nil // Already open
284 }
285
286 // Skip files that do not exist or cannot be read
287 content, err := os.ReadFile(filepath)
288 if err != nil {
289 return fmt.Errorf("error reading file: %w", err)
290 }
291
292 // Notify the server about the opened document
293 if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(DetectLanguageID(uri)), 1, string(content)); err != nil {
294 return err
295 }
296
297 c.openFiles.Set(uri, &OpenFileInfo{
298 Version: 1,
299 URI: protocol.DocumentURI(uri),
300 })
301
302 return nil
303}
304
305// NotifyChange notifies the server about a file change.
306func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
307 uri := string(protocol.URIFromPath(filepath))
308
309 content, err := os.ReadFile(filepath)
310 if err != nil {
311 return fmt.Errorf("error reading file: %w", err)
312 }
313
314 fileInfo, isOpen := c.openFiles.Get(uri)
315 if !isOpen {
316 return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
317 }
318
319 // Increment version
320 fileInfo.Version++
321
322 // Create change event
323 changes := []protocol.TextDocumentContentChangeEvent{
324 {
325 Value: protocol.TextDocumentContentChangeWholeDocument{
326 Text: string(content),
327 },
328 },
329 }
330
331 return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
332}
333
334// IsFileOpen checks if a file is currently open.
335func (c *Client) IsFileOpen(filepath string) bool {
336 uri := string(protocol.URIFromPath(filepath))
337 _, exists := c.openFiles.Get(uri)
338 return exists
339}
340
341// CloseAllFiles closes all currently open files.
342func (c *Client) CloseAllFiles(ctx context.Context) {
343 cfg := config.Get()
344 debugLSP := cfg != nil && cfg.Options.DebugLSP
345 for uri := range c.openFiles.Seq2() {
346 if debugLSP {
347 slog.Debug("Closing file", "file", uri)
348 }
349 if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
350 slog.Warn("Error closing rile", "uri", uri, "error", err)
351 continue
352 }
353 c.openFiles.Del(uri)
354 }
355}
356
357// GetFileDiagnostics returns diagnostics for a specific file.
358func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
359 diags, _ := c.diagnostics.Get(uri)
360 return diags
361}
362
363// GetDiagnostics returns all diagnostics for all files.
364func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
365 return c.diagnostics.Copy()
366}
367
368// GetDiagnosticCounts returns cached diagnostic counts by severity.
369// Uses the VersionedMap version to avoid recomputing on every call.
370func (c *Client) GetDiagnosticCounts() DiagnosticCounts {
371 currentVersion := c.diagnostics.Version()
372 if currentVersion == c.diagCountsVersion {
373 return c.diagCountsCache
374 }
375
376 // Recompute counts.
377 counts := DiagnosticCounts{}
378 for _, diags := range c.diagnostics.Seq2() {
379 for _, diag := range diags {
380 switch diag.Severity {
381 case protocol.SeverityError:
382 counts.Error++
383 case protocol.SeverityWarning:
384 counts.Warning++
385 case protocol.SeverityInformation:
386 counts.Information++
387 case protocol.SeverityHint:
388 counts.Hint++
389 }
390 }
391 }
392
393 c.diagCountsCache = counts
394 c.diagCountsVersion = currentVersion
395 return counts
396}
397
398// OpenFileOnDemand opens a file only if it's not already open.
399func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
400 // Check if the file is already open
401 if c.IsFileOpen(filepath) {
402 return nil
403 }
404
405 // Open the file
406 return c.OpenFile(ctx, filepath)
407}
408
409// GetDiagnosticsForFile ensures a file is open and returns its diagnostics.
410func (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {
411 documentURI := protocol.URIFromPath(filepath)
412
413 // Make sure the file is open
414 if !c.IsFileOpen(filepath) {
415 if err := c.OpenFile(ctx, filepath); err != nil {
416 return nil, fmt.Errorf("failed to open file for diagnostics: %w", err)
417 }
418
419 // Give the LSP server a moment to process the file
420 time.Sleep(100 * time.Millisecond)
421 }
422
423 // Get diagnostics
424 diagnostics, _ := c.diagnostics.Get(documentURI)
425
426 return diagnostics, nil
427}
428
429// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache.
430func (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentURI) {
431 c.diagnostics.Del(uri)
432}
433
434// RegisterNotificationHandler registers a notification handler.
435func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
436 c.client.RegisterNotificationHandler(method, handler)
437}
438
439// RegisterServerRequestHandler handles server requests.
440func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
441 c.client.RegisterHandler(method, handler)
442}
443
444// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the server.
445func (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {
446 return c.client.NotifyDidChangeWatchedFiles(ctx, params.Changes)
447}
448
449// openKeyConfigFiles opens important configuration files that help initialize the server.
450func (c *Client) openKeyConfigFiles(ctx context.Context) {
451 wd, err := os.Getwd()
452 if err != nil {
453 return
454 }
455
456 // Try to open each file, ignoring errors if they don't exist
457 for _, file := range c.config.RootMarkers {
458 file = filepath.Join(wd, file)
459 if _, err := os.Stat(file); err == nil {
460 // File exists, try to open it
461 if err := c.OpenFile(ctx, file); err != nil {
462 slog.Error("Failed to open key config file", "file", file, "error", err)
463 } else {
464 slog.Debug("Opened key config file for initialization", "file", file)
465 }
466 }
467 }
468}
469
470// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
471func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
472 ticker := time.NewTicker(200 * time.Millisecond)
473 defer ticker.Stop()
474 timeout := time.After(d)
475 pv := c.diagnostics.Version()
476 for {
477 select {
478 case <-ctx.Done():
479 return
480 case <-timeout:
481 return
482 case <-ticker.C:
483 if pv != c.diagnostics.Version() {
484 return
485 }
486 }
487 }
488}
489
490// FindReferences finds all references to the symbol at the given position.
491func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
492 if err := c.OpenFileOnDemand(ctx, filepath); err != nil {
493 return nil, err
494 }
495 // NOTE: line and character should be 0-based.
496 // See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
497 return c.client.FindReferences(ctx, filepath, line-1, character-1, includeDeclaration)
498}
499
500// HasRootMarkers checks if any of the specified root marker patterns exist in the given directory.
501// Uses glob patterns to match files, allowing for more flexible matching.
502func HasRootMarkers(dir string, rootMarkers []string) bool {
503 if len(rootMarkers) == 0 {
504 return true
505 }
506 for _, pattern := range rootMarkers {
507 // Use fsext.GlobWithDoubleStar to find matches
508 matches, _, err := fsext.GlobWithDoubleStar(pattern, dir, 1)
509 if err == nil && len(matches) > 0 {
510 return true
511 }
512 }
513 return false
514}