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