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