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