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.Map[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.NewMap[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.
317func (c *Client) CloseFile(ctx context.Context, filepath string) error {
318 cfg := config.Get()
319 uri := string(protocol.URIFromPath(filepath))
320
321 if _, exists := c.openFiles.Get(uri); !exists {
322 return nil // Already closed
323 }
324
325 if cfg.Options.DebugLSP {
326 slog.Debug("Closing file", "file", filepath)
327 }
328
329 if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
330 return err
331 }
332
333 c.openFiles.Del(uri)
334
335 return nil
336}
337
338// IsFileOpen checks if a file is currently open.
339func (c *Client) IsFileOpen(filepath string) bool {
340 uri := string(protocol.URIFromPath(filepath))
341 _, exists := c.openFiles.Get(uri)
342 return exists
343}
344
345// CloseAllFiles closes all currently open files.
346func (c *Client) CloseAllFiles(ctx context.Context) {
347 cfg := config.Get()
348 filesToClose := make([]string, 0, c.openFiles.Len())
349
350 // First collect all URIs that need to be closed
351 for uri := range c.openFiles.Seq2() {
352 // Convert URI back to file path using proper URI handling
353 filePath, err := protocol.DocumentURI(uri).Path()
354 if err != nil {
355 slog.Error("Failed to convert URI to path for file closing", "uri", uri, "error", err)
356 continue
357 }
358 filesToClose = append(filesToClose, filePath)
359 }
360
361 // Then close them all
362 for _, filePath := range filesToClose {
363 err := c.CloseFile(ctx, filePath)
364 if err != nil && cfg != nil && cfg.Options.DebugLSP {
365 slog.Warn("Error closing file", "file", filePath, "error", err)
366 }
367 }
368
369 if cfg != nil && cfg.Options.DebugLSP {
370 slog.Debug("Closed all files", "files", filesToClose)
371 }
372}
373
374// GetFileDiagnostics returns diagnostics for a specific file.
375func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
376 diags, _ := c.diagnostics.Get(uri)
377 return diags
378}
379
380// GetDiagnostics returns all diagnostics for all files.
381func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
382 return maps.Collect(c.diagnostics.Seq2())
383}
384
385// OpenFileOnDemand opens a file only if it's not already open.
386func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
387 // Check if the file is already open
388 if c.IsFileOpen(filepath) {
389 return nil
390 }
391
392 // Open the file
393 return c.OpenFile(ctx, filepath)
394}
395
396// GetDiagnosticsForFile ensures a file is open and returns its diagnostics.
397func (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {
398 documentURI := protocol.URIFromPath(filepath)
399
400 // Make sure the file is open
401 if !c.IsFileOpen(filepath) {
402 if err := c.OpenFile(ctx, filepath); err != nil {
403 return nil, fmt.Errorf("failed to open file for diagnostics: %w", err)
404 }
405
406 // Give the LSP server a moment to process the file
407 time.Sleep(100 * time.Millisecond)
408 }
409
410 // Get diagnostics
411 diagnostics, _ := c.diagnostics.Get(documentURI)
412
413 return diagnostics, nil
414}
415
416// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache.
417func (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentURI) {
418 c.diagnostics.Del(uri)
419}
420
421// RegisterNotificationHandler registers a notification handler.
422func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
423 c.client.RegisterNotificationHandler(method, handler)
424}
425
426// RegisterServerRequestHandler handles server requests.
427func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
428 c.client.RegisterHandler(method, handler)
429}
430
431// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the server.
432func (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {
433 return c.client.NotifyDidChangeWatchedFiles(ctx, params.Changes)
434}
435
436// openKeyConfigFiles opens important configuration files that help initialize the server.
437func (c *Client) openKeyConfigFiles(ctx context.Context) {
438 wd, err := os.Getwd()
439 if err != nil {
440 return
441 }
442
443 // Try to open each file, ignoring errors if they don't exist
444 for _, file := range c.config.RootMarkers {
445 file = filepath.Join(wd, file)
446 if _, err := os.Stat(file); err == nil {
447 // File exists, try to open it
448 if err := c.OpenFile(ctx, file); err != nil {
449 slog.Debug("Failed to open key config file", "file", file, "error", err)
450 } else {
451 slog.Debug("Opened key config file for initialization", "file", file)
452 }
453 }
454 }
455}
456
457// HasRootMarkers checks if any of the specified root marker patterns exist in the given directory.
458// Uses glob patterns to match files, allowing for more flexible matching.
459func HasRootMarkers(dir string, rootMarkers []string) bool {
460 if len(rootMarkers) == 0 {
461 return true
462 }
463 for _, pattern := range rootMarkers {
464 // Use fsext.GlobWithDoubleStar to find matches
465 matches, _, err := fsext.GlobWithDoubleStar(pattern, dir, 1)
466 if err == nil && len(matches) > 0 {
467 return true
468 }
469 }
470 return false
471}