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"
25 client *powernap.Client
28 // File types this LSP server handles (e.g., .go, .rs, .py)
31 // Configuration for this LSP client
32 config config.LSPConfig
34 // Diagnostic change callback
35 onDiagnosticsChanged func(name string, count int)
38 diagnostics *csync.VersionedMap[protocol.DocumentURI, []protocol.Diagnostic]
40 // Files are currently opened by the LSP
41 openFiles *csync.Map[string, *OpenFileInfo]
44 serverState atomic.Value
47// New creates a new LSP client using the powernap implementation.
48func New(ctx context.Context, name string, config config.LSPConfig, resolver config.VariableResolver) (*Client, error) {
49 // Convert working directory to file URI
50 workDir, err := os.Getwd()
52 return nil, fmt.Errorf("failed to get working directory: %w", err)
55 rootURI := string(protocol.URIFromPath(workDir))
57 command, err := resolver.ResolveValue(config.Command)
59 return nil, fmt.Errorf("invalid lsp command: %w", err)
62 // Create powernap client config
63 clientConfig := powernap.ClientConfig{
64 Command: home.Long(command),
67 Environment: func() map[string]string {
68 env := make(map[string]string)
69 maps.Copy(env, config.Env)
72 Settings: config.Options,
73 InitOptions: config.InitOptions,
74 WorkspaceFolders: []protocol.WorkspaceFolder{
77 Name: filepath.Base(workDir),
82 // Create the powernap client
83 powernapClient, err := powernap.NewClient(clientConfig)
85 return nil, fmt.Errorf("failed to create lsp client: %w", err)
89 client: powernapClient,
91 fileTypes: config.FileTypes,
92 diagnostics: csync.NewVersionedMap[protocol.DocumentURI, []protocol.Diagnostic](),
93 openFiles: csync.NewMap[string, *OpenFileInfo](),
97 // Initialize server state
98 client.serverState.Store(StateStarting)
103// Initialize initializes the LSP client and returns the server capabilities.
104func (c *Client) Initialize(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
105 if err := c.client.Initialize(ctx, false); err != nil {
106 return nil, fmt.Errorf("failed to initialize the lsp client: %w", err)
109 // Convert powernap capabilities to protocol capabilities
110 caps := c.client.GetCapabilities()
111 protocolCaps := protocol.ServerCapabilities{
112 TextDocumentSync: caps.TextDocumentSync,
113 CompletionProvider: func() *protocol.CompletionOptions {
114 if caps.CompletionProvider != nil {
115 return &protocol.CompletionOptions{
116 TriggerCharacters: caps.CompletionProvider.TriggerCharacters,
117 AllCommitCharacters: caps.CompletionProvider.AllCommitCharacters,
118 ResolveProvider: caps.CompletionProvider.ResolveProvider,
125 result := &protocol.InitializeResult{
126 Capabilities: protocolCaps,
129 c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
130 c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
131 c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
132 c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
133 c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(_ context.Context, _ string, params json.RawMessage) {
134 HandleDiagnostics(c, params)
140// Close closes the LSP client.
141func (c *Client) Close(ctx context.Context) error {
142 // Try to close all open files first
143 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
148 // Shutdown and exit the client
149 if err := c.client.Shutdown(ctx); err != nil {
150 slog.Warn("Failed to shutdown LSP client", "error", err)
153 return c.client.Exit()
156// ServerState represents the state of an LSP server
160 StateStarting ServerState = iota
166// GetServerState returns the current state of the LSP server
167func (c *Client) GetServerState() ServerState {
168 if val := c.serverState.Load(); val != nil {
169 return val.(ServerState)
174// SetServerState sets the current state of the LSP server
175func (c *Client) SetServerState(state ServerState) {
176 c.serverState.Store(state)
179// GetName returns the name of the LSP client
180func (c *Client) GetName() string {
184// SetDiagnosticsCallback sets the callback function for diagnostic changes
185func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
186 c.onDiagnosticsChanged = callback
189// WaitForServerReady waits for the server to be ready
190func (c *Client) WaitForServerReady(ctx context.Context) error {
194 c.SetServerState(StateStarting)
196 // Create a context with timeout
197 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
200 // Try to ping the server with a simple request
201 ticker := time.NewTicker(500 * time.Millisecond)
204 if cfg != nil && cfg.Options.DebugLSP {
205 slog.Debug("Waiting for LSP server to be ready...")
208 c.openKeyConfigFiles(ctx)
213 c.SetServerState(StateError)
214 return fmt.Errorf("timeout waiting for LSP server to be ready")
216 // Check if client is running
217 if !c.client.IsRunning() {
218 if cfg != nil && cfg.Options.DebugLSP {
219 slog.Debug("LSP server not ready yet", "server", c.name)
225 c.SetServerState(StateReady)
226 if cfg != nil && cfg.Options.DebugLSP {
227 slog.Debug("LSP server is ready")
234// OpenFileInfo contains information about an open file
235type OpenFileInfo struct {
237 URI protocol.DocumentURI
240// HandlesFile checks if this LSP client handles the given file based on its extension.
241func (c *Client) HandlesFile(path string) bool {
242 // If no file types are specified, handle all files (backward compatibility)
243 if len(c.fileTypes) == 0 {
247 name := strings.ToLower(filepath.Base(path))
248 for _, filetype := range c.fileTypes {
249 suffix := strings.ToLower(filetype)
250 if !strings.HasPrefix(suffix, ".") {
251 suffix = "." + suffix
253 if strings.HasSuffix(name, suffix) {
254 slog.Debug("handles file", "name", c.name, "file", name, "filetype", filetype)
258 slog.Debug("doesn't handle file", "name", c.name, "file", name)
262// OpenFile opens a file in the LSP server.
263func (c *Client) OpenFile(ctx context.Context, filepath string) error {
264 if !c.HandlesFile(filepath) {
268 uri := string(protocol.URIFromPath(filepath))
270 if _, exists := c.openFiles.Get(uri); exists {
271 return nil // Already open
274 // Skip files that do not exist or cannot be read
275 content, err := os.ReadFile(filepath)
277 return fmt.Errorf("error reading file: %w", err)
280 // Notify the server about the opened document
281 if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(DetectLanguageID(uri)), 1, string(content)); err != nil {
285 c.openFiles.Set(uri, &OpenFileInfo{
287 URI: protocol.DocumentURI(uri),
293// NotifyChange notifies the server about a file change.
294func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
295 uri := string(protocol.URIFromPath(filepath))
297 content, err := os.ReadFile(filepath)
299 return fmt.Errorf("error reading file: %w", err)
302 fileInfo, isOpen := c.openFiles.Get(uri)
304 return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
310 // Create change event
311 changes := []protocol.TextDocumentContentChangeEvent{
313 Value: protocol.TextDocumentContentChangeWholeDocument{
314 Text: string(content),
319 return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
322// IsFileOpen checks if a file is currently open.
323func (c *Client) IsFileOpen(filepath string) bool {
324 uri := string(protocol.URIFromPath(filepath))
325 _, exists := c.openFiles.Get(uri)
329// CloseAllFiles closes all currently open files.
330func (c *Client) CloseAllFiles(ctx context.Context) {
332 debugLSP := cfg != nil && cfg.Options.DebugLSP
333 for uri := range c.openFiles.Seq2() {
335 slog.Debug("Closing file", "file", uri)
337 if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
338 slog.Warn("Error closing rile", "uri", uri, "error", err)
345// GetFileDiagnostics returns diagnostics for a specific file.
346func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
347 diags, _ := c.diagnostics.Get(uri)
351// GetDiagnostics returns all diagnostics for all files.
352func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
353 return maps.Collect(c.diagnostics.Seq2())
356// OpenFileOnDemand opens a file only if it's not already open.
357func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
358 // Check if the file is already open
359 if c.IsFileOpen(filepath) {
364 return c.OpenFile(ctx, filepath)
367// GetDiagnosticsForFile ensures a file is open and returns its diagnostics.
368func (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {
369 documentURI := protocol.URIFromPath(filepath)
371 // Make sure the file is open
372 if !c.IsFileOpen(filepath) {
373 if err := c.OpenFile(ctx, filepath); err != nil {
374 return nil, fmt.Errorf("failed to open file for diagnostics: %w", err)
377 // Give the LSP server a moment to process the file
378 time.Sleep(100 * time.Millisecond)
382 diagnostics, _ := c.diagnostics.Get(documentURI)
384 return diagnostics, nil
387// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache.
388func (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentURI) {
389 c.diagnostics.Del(uri)
392// RegisterNotificationHandler registers a notification handler.
393func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
394 c.client.RegisterNotificationHandler(method, handler)
397// RegisterServerRequestHandler handles server requests.
398func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
399 c.client.RegisterHandler(method, handler)
402// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the server.
403func (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {
404 return c.client.NotifyDidChangeWatchedFiles(ctx, params.Changes)
407// openKeyConfigFiles opens important configuration files that help initialize the server.
408func (c *Client) openKeyConfigFiles(ctx context.Context) {
409 wd, err := os.Getwd()
414 // Try to open each file, ignoring errors if they don't exist
415 for _, file := range c.config.RootMarkers {
416 file = filepath.Join(wd, file)
417 if _, err := os.Stat(file); err == nil {
418 // File exists, try to open it
419 if err := c.OpenFile(ctx, file); err != nil {
420 slog.Error("Failed to open key config file", "file", file, "error", err)
422 slog.Debug("Opened key config file for initialization", "file", file)
428// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
429func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
430 ticker := time.NewTicker(200 * time.Millisecond)
432 timeout := time.After(d)
433 pv := c.diagnostics.Version()
441 if pv != c.diagnostics.Version() {
448// FindReferences finds all references to the symbol at the given position.
449func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
450 if err := c.OpenFileOnDemand(ctx, filepath); err != nil {
453 // NOTE: line and character should be 0-based.
454 // See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
455 return c.client.FindReferences(ctx, filepath, line-1, character-1, includeDeclaration)
458// HasRootMarkers checks if any of the specified root marker patterns exist in the given directory.
459// Uses glob patterns to match files, allowing for more flexible matching.
460func HasRootMarkers(dir string, rootMarkers []string) bool {
461 if len(rootMarkers) == 0 {
464 for _, pattern := range rootMarkers {
465 // Use fsext.GlobWithDoubleStar to find matches
466 matches, _, err := fsext.GlobWithDoubleStar(pattern, dir, 1)
467 if err == nil && len(matches) > 0 {
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list