Debian Codegraph @

helix-lsp/src/lib.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 mod client;
2 pub mod file_event;
3 mod file_operations;
4 pub mod jsonrpc;
5 mod transport;
6
7 use arc_swap::ArcSwap;
8 pub use client::Client;
9 pub use futures_executor::block_on;
10 pub use helix_lsp_types as lsp;
11 pub use jsonrpc::Call;
12 use log::warn;
13 pub use lsp::{Position, Url};
14
15 use futures_util::stream::select_all::SelectAll;
16 use helix_core::syntax::config::{
17 LanguageConfiguration, LanguageServerConfiguration, LanguageServerFeatures, RootMarkers,
18 };
19 use helix_stdx::path;
20 use slotmap::SlotMap;
21 use tokio::sync::mpsc::UnboundedReceiver;
22
23 use std::{
24 collections::HashMap,
25 fs,
26 path::{Path, PathBuf},
27 sync::Arc,
28 };
29
30 use thiserror::Error;
31 use tokio_stream::wrappers::UnboundedReceiverStream;
32
33 pub type Result<T, E = Error> = core::result::Result<T, E>;
34 pub type LanguageServerName = String;
35 pub use helix_core::diagnostic::LanguageServerId;
36
37 #[derive(Error, Debug)]
38 pub enum Error {
39 #[error("protocol error: {0}")]
40 Rpc(#[from] jsonrpc::Error),
41 #[error("failed to parse: {0}")]
42 Parse(Box<dyn std::error::Error + Send + Sync>),
43 #[error("IO Error: {0}")]
44 IO(#[from] std::io::Error),
45 #[error("request {0} timed out")]
46 Timeout(jsonrpc::Id),
47 #[error("server closed the stream")]
48 StreamClosed,
49 #[error("Unhandled")]
50 Unhandled,
51 #[error(transparent)]
52 ExecutableNotFound(#[from] helix_stdx::env::ExecutableNotFoundError),
53 #[error(transparent)]
54 Other(#[from] anyhow::Error),
55 }
56
57 impl From<serde_json::Error> for Error {
58 fn from(value: serde_json::Error) -> Self {
59 Self::Parse(Box::new(value))
60 }
61 }
62
63 impl From<sonic_rs::Error> for Error {
64 fn from(value: sonic_rs::Error) -> Self {
65 Self::Parse(Box::new(value))
66 }
67 }
68
69 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70 pub enum OffsetEncoding {
71 /// UTF-8 code units aka bytes
72 Utf8,
73 /// UTF-32 code units aka chars
74 Utf32,
75 /// UTF-16 code units
76 #[default]
77 Utf16,
78 }
79
80 pub mod util {
81 use super::*;
82 use helix_core::line_ending::{line_end_byte_index, line_end_char_index};
83 use helix_core::snippets::{RenderedSnippet, Snippet, SnippetRenderCtx};
84 use helix_core::{chars, RopeSlice};
85 use helix_core::{diagnostic::NumberOrString, Range, Rope, Selection, Tendril, Transaction};
86
87 /// Converts a diagnostic in the document to [`lsp::Diagnostic`].
88 ///
89 /// Panics when [`pos_to_lsp_pos`] would for an invalid range on the diagnostic.
90 pub fn diagnostic_to_lsp_diagnostic(
91 doc: &Rope,
92 diag: &helix_core::diagnostic::Diagnostic,
93 offset_encoding: OffsetEncoding,
94 ) -> lsp::Diagnostic {
95 use helix_core::diagnostic::Severity::*;
96
97 let range = Range::new(diag.range.start, diag.range.end);
98 let severity = diag.severity.map(|s| match s {
99 Hint => lsp::DiagnosticSeverity::HINT,
100 Info => lsp::DiagnosticSeverity::INFORMATION,
101 Warning => lsp::DiagnosticSeverity::WARNING,
102 Error => lsp::DiagnosticSeverity::ERROR,
103 });
104
105 let code = match diag.code.clone() {
106 Some(x) => match x {
107 NumberOrString::Number(x) => Some(lsp::NumberOrString::Number(x)),
108 NumberOrString::String(x) => Some(lsp::NumberOrString::String(x)),
109 },
110 None => None,
111 };
112
113 let new_tags: Vec<_> = diag
114 .tags
115 .iter()
116 .map(|tag| match tag {
117 helix_core::diagnostic::DiagnosticTag::Unnecessary => {
118 lsp::DiagnosticTag::UNNECESSARY
119 }
120 helix_core::diagnostic::DiagnosticTag::Deprecated => lsp::DiagnosticTag::DEPRECATED,
121 })
122 .collect();
123
124 let tags = if !new_tags.is_empty() {
125 Some(new_tags)
126 } else {
127 None
128 };
129
130 lsp::Diagnostic {
131 range: range_to_lsp_range(doc, range, offset_encoding),
132 severity,
133 code,
134 source: diag.source.clone(),
135 message: diag.message.to_owned(),
136 related_information: None,
137 tags,
138 data: diag.data.to_owned(),
139 ..Default::default()
140 }
141 }
142
143 /// Converts [`lsp::Position`] to a position in the document.
144 ///
145 /// Returns `None` if position.line is out of bounds or an overflow occurs
146 pub fn lsp_pos_to_pos(
147 doc: &Rope,
148 pos: lsp::Position,
149 offset_encoding: OffsetEncoding,
150 ) -> Option<usize> {
151 let pos_line = pos.line as usize;
152 if pos_line > doc.len_lines() - 1 {
153 // If it extends past the end, truncate it to the end. This is because the
154 // way the LSP describes the range including the last newline is by
155 // specifying a line number after what we would call the last line.
156 log::warn!("LSP position {pos:?} out of range assuming EOF");
157 return Some(doc.len_chars());
158 }
159
160 // We need to be careful here to fully comply ith the LSP spec.
161 // Two relevant quotes from the spec:
162 //
163 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
164 // > If the character value is greater than the line length it defaults back
165 // > to the line length.
166 //
167 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocuments
168 // > To ensure that both client and server split the string into the same
169 // > line representation the protocol specifies the following end-of-line sequences:
170 // > ‘\n’, ‘\r\n’ and ‘\r’. Positions are line end character agnostic.
171 // > So you can not specify a position that denotes \r|\n or \n| where | represents the character offset.
172 //
173 // This means that while the line must be in bounds the `character`
174 // must be capped to the end of the line.
175 // Note that the end of the line here is **before** the line terminator
176 // so we must use `line_end_char_index` instead of `doc.line_to_char(pos_line + 1)`
177 //
178 // FIXME: Helix does not fully comply with the LSP spec for line terminators.
179 // The LSP standard requires that line terminators are ['\n', '\r\n', '\r'].
180 // Without the unicode-linebreak feature disabled, the `\r` terminator is not handled by helix.
181 // With the unicode-linebreak feature, helix recognizes multiple extra line break chars
182 // which means that positions will be decoded/encoded incorrectly in their presence
183
184 let line = match offset_encoding {
185 OffsetEncoding::Utf8 => {
186 let line_start = doc.line_to_byte(pos_line);
187 let line_end = line_end_byte_index(&doc.slice(..), pos_line);
188 line_start..line_end
189 }
190 OffsetEncoding::Utf16 => {
191 // TODO directly translate line index to char-idx
192 // ropey can do this just as easily as utf-8 byte translation
193 // but the functions are just missing.
194 // Translate to char first and then utf-16 as a workaround
195 let line_start = doc.line_to_char(pos_line);
196 let line_end = line_end_char_index(&doc.slice(..), pos_line);
197 doc.char_to_utf16_cu(line_start)..doc.char_to_utf16_cu(line_end)
198 }
199 OffsetEncoding::Utf32 => {
200 let line_start = doc.line_to_char(pos_line);
201 let line_end = line_end_char_index(&doc.slice(..), pos_line);
202 line_start..line_end
203 }
204 };
205
206 // The LSP spec demands that the offset is capped to the end of the line
207 let pos = line
208 .start
209 .checked_add(pos.character as usize)
210 .unwrap_or(line.end)
211 .min(line.end);
212
213 match offset_encoding {
214 OffsetEncoding::Utf8 => doc.try_byte_to_char(pos).ok(),
215 OffsetEncoding::Utf16 => doc.try_utf16_cu_to_char(pos).ok(),
216 OffsetEncoding::Utf32 => Some(pos),
217 }
218 }
219
220 /// Converts position in the document to [`lsp::Position`].
221 ///
222 /// Panics when `pos` is out of `doc` bounds or operation overflows.
223 pub fn pos_to_lsp_pos(
224 doc: &Rope,
225 pos: usize,
226 offset_encoding: OffsetEncoding,
227 ) -> lsp::Position {
228 match offset_encoding {
229 OffsetEncoding::Utf8 => {
230 let line = doc.char_to_line(pos);
231 let line_start = doc.line_to_byte(line);
232 let col = doc.char_to_byte(pos) - line_start;
233
234 lsp::Position::new(line as u32, col as u32)
235 }
236 OffsetEncoding::Utf16 => {
237 let line = doc.char_to_line(pos);
238 let line_start = doc.char_to_utf16_cu(doc.line_to_char(line));
239 let col = doc.char_to_utf16_cu(pos) - line_start;
240
241 lsp::Position::new(line as u32, col as u32)
242 }
243 OffsetEncoding::Utf32 => {
244 let line = doc.char_to_line(pos);
245 let line_start = doc.line_to_char(line);
246 let col = pos - line_start;
247
248 lsp::Position::new(line as u32, col as u32)
249 }
250 }
251 }
252
253 /// Converts a range in the document to [`lsp::Range`].
254 pub fn range_to_lsp_range(
255 doc: &Rope,
256 range: Range,
257 offset_encoding: OffsetEncoding,
258 ) -> lsp::Range {
259 let start = pos_to_lsp_pos(doc, range.from(), offset_encoding);
260 let end = pos_to_lsp_pos(doc, range.to(), offset_encoding);
261
262 lsp::Range::new(start, end)
263 }
264
265 pub fn lsp_range_to_range(
266 doc: &Rope,
267 mut range: lsp::Range,
268 offset_encoding: OffsetEncoding,
269 ) -> Option<Range> {
270 // This is sort of an edgecase. It's not clear from the spec how to deal with
271 // ranges where end < start. They don't make much sense but vscode simply caps start to end
272 // and because it's not specified quite a few LS rely on this as a result (for example the TS server)
273 if range.start > range.end {
274 log::error!(
275 "Invalid LSP range start {:?} > end {:?}, using an empty range at the end instead",
276 range.start,
277 range.end
278 );
279 range.start = range.end;
280 }
281 let start = lsp_pos_to_pos(doc, range.start, offset_encoding)?;
282 let end = lsp_pos_to_pos(doc, range.end, offset_encoding)?;
283
284 Some(Range::new(start, end))
285 }
286
287 /// If the LS did not provide a range for the completion or the range of the
288 /// primary cursor can not be used for the secondary cursor, this function
289 /// can be used to find the completion range for a cursor
290 fn find_completion_range(text: RopeSlice, replace_mode: bool, cursor: usize) -> (usize, usize) {
291 let start = cursor
292 - text
293 .chars_at(cursor)
294 .reversed()
295 .take_while(|ch| chars::char_is_word(*ch))
296 .count();
297 let mut end = cursor;
298 if replace_mode {
299 end += text
300 .chars_at(cursor)
301 .take_while(|ch| chars::char_is_word(*ch))
302 .count();
303 }
304 (start, end)
305 }
306 fn completion_range(
307 text: RopeSlice,
308 edit_offset: Option<(i128, i128)>,
309 replace_mode: bool,
310 cursor: usize,
311 ) -> Option<(usize, usize)> {
312 let res = match edit_offset {
313 Some((start_offset, end_offset)) => {
314 let start_offset = cursor as i128 + start_offset;
315 if start_offset < 0 {
316 return None;
317 }
318 let end_offset = cursor as i128 + end_offset;
319 if end_offset > text.len_chars() as i128 {
320 return None;
321 }
322 (start_offset as usize, end_offset as usize)
323 }
324 None => find_completion_range(text, replace_mode, cursor),
325 };
326 Some(res)
327 }
328
329 /// Creates a [Transaction] from the [lsp::TextEdit] in a completion response.
330 /// The transaction applies the edit to all cursors.
331 pub fn generate_transaction_from_completion_edit(
332 doc: &Rope,
333 selection: &Selection,
334 edit_offset: Option<(i128, i128)>,
335 replace_mode: bool,
336 new_text: String,
337 ) -> Transaction {
338 let replacement: Option<Tendril> = if new_text.is_empty() {
339 None
340 } else {
341 Some(new_text.into())
342 };
343
344 let text = doc.slice(..);
345 let (removed_start, removed_end) = completion_range(
346 text,
347 edit_offset,
348 replace_mode,
349 selection.primary().cursor(text),
350 )
351 .expect("transaction must be valid for primary selection");
352 let removed_text = text.slice(removed_start..removed_end);
353
354 let (transaction, mut selection) = Transaction::change_by_selection_ignore_overlapping(
355 doc,
356 selection,
357 |range| {
358 let cursor = range.cursor(text);
359 completion_range(text, edit_offset, replace_mode, cursor)
360 .filter(|(start, end)| text.slice(start..end) == removed_text)
361 .unwrap_or_else(|| find_completion_range(text, replace_mode, cursor))
362 },
363 |_, _| replacement.clone(),
364 );
365 if transaction.changes().is_empty() {
366 return transaction;
367 }
368 selection = selection.map(transaction.changes());
369 transaction.with_selection(selection)
370 }
371
372 /// Creates a [Transaction] from the [Snippet] in a completion response.
373 /// The transaction applies the edit to all cursors.
374 pub fn generate_transaction_from_snippet(
375 doc: &Rope,
376 selection: &Selection,
377 edit_offset: Option<(i128, i128)>,
378 replace_mode: bool,
379 snippet: Snippet,
380 cx: &mut SnippetRenderCtx,
381 ) -> (Transaction, RenderedSnippet) {
382 let text = doc.slice(..);
383 let (removed_start, removed_end) = completion_range(
384 text,
385 edit_offset,
386 replace_mode,
387 selection.primary().cursor(text),
388 )
389 .expect("transaction must be valid for primary selection");
390 let removed_text = text.slice(removed_start..removed_end);
391 let (transaction, mapped_selection, snippet) = snippet.render(
392 doc,
393 selection,
394 |range| {
395 let cursor = range.cursor(text);
396 completion_range(text, edit_offset, replace_mode, cursor)
397 .filter(|(start, end)| text.slice(start..end) == removed_text)
398 .unwrap_or_else(|| find_completion_range(text, replace_mode, cursor))
399 },
400 cx,
401 );
402 let transaction = transaction.with_selection(snippet.first_selection(
403 // we keep the direction of the old primary selection in case it changed during mapping
404 // but use the primary idx from the mapped selection in case ranges had to be merged
405 selection.primary().direction(),
406 mapped_selection.primary_index(),
407 ));
408 (transaction, snippet)
409 }
410
411 pub fn generate_transaction_from_edits(
412 doc: &Rope,
413 mut edits: Vec<lsp::TextEdit>,
414 offset_encoding: OffsetEncoding,
415 ) -> Transaction {
416 // Sort edits by start range, since some LSPs (Omnisharp) send them
417 // in reverse order.
418 edits.sort_by_key(|edit| edit.range.start);
419
420 // Generate a diff if the edit is a full document replacement.
421 #[allow(clippy::collapsible_if)]
422 if edits.len() == 1 {
423 let is_document_replacement = edits.first().and_then(|edit| {
424 let start = lsp_pos_to_pos(doc, edit.range.start, offset_encoding)?;
425 let end = lsp_pos_to_pos(doc, edit.range.end, offset_encoding)?;
426 Some(start..end)
427 }) == Some(0..doc.len_chars());
428 if is_document_replacement {
429 let new_text = Rope::from(edits.pop().unwrap().new_text);
430 return helix_core::diff::compare_ropes(doc, &new_text);
431 }
432 }
433
434 // `ChangeSet::from_changes` requires its changes to be sorted and
435 // non-overlapping (it does `retain(from - last)`, which underflows when
436 // `from < last`). The sort above handles ordering, but the LSP spec
437 // already forbids overlapping edits and some servers violate that. So
438 // resolve the edits here and drop any that overlap an earlier one (or
439 // fail to map), instead of feeding an overlap into `from_changes` and
440 // panicking. This matches the overlap policy of `Transaction::delete`.
441 // See issue #15514 / AUDIT-044/045.
442 let mut last_end = 0;
443 let mut changes: Vec<(usize, usize, Option<helix_core::Tendril>)> =
444 Vec::with_capacity(edits.len());
445 for edit in edits {
446 let Some(start) = lsp_pos_to_pos(doc, edit.range.start, offset_encoding) else {
447 continue;
448 };
449 let Some(end) = lsp_pos_to_pos(doc, edit.range.end, offset_encoding) else {
450 continue;
451 };
452
453 if start > end {
454 log::error!("Invalid LSP text edit start {start:?} > end {end:?}, discarding");
455 continue;
456 }
457
458 if start < last_end {
459 log::error!(
460 "Overlapping LSP text edit {start}..{end} (after {last_end}), discarding"
461 );
462 continue;
463 }
464 last_end = end;
465
466 // simplify "" into None for cleaner changesets
467 let replacement = if edit.new_text.is_empty() {
468 None
469 } else {
470 Some(edit.new_text.into())
471 };
472
473 changes.push((start, end, replacement));
474 }
475
476 Transaction::change(doc, changes.into_iter())
477 }
478 }
479
480 #[derive(Debug, PartialEq, Clone)]
481 pub enum MethodCall {
482 WorkDoneProgressCreate(lsp::WorkDoneProgressCreateParams),
483 ApplyWorkspaceEdit(lsp::ApplyWorkspaceEditParams),
484 WorkspaceFolders,
485 WorkspaceConfiguration(lsp::ConfigurationParams),
486 RegisterCapability(lsp::RegistrationParams),
487 UnregisterCapability(lsp::UnregistrationParams),
488 ShowDocument(lsp::ShowDocumentParams),
489 WorkspaceDiagnosticRefresh,
490 ShowMessageRequest(lsp::ShowMessageRequestParams),
491 }
492
493 impl MethodCall {
494 pub fn parse(method: &str, params: jsonrpc::Params) -> Result<MethodCall> {
495 use lsp::request::Request;
496 let request = match method {
497 lsp::request::WorkDoneProgressCreate::METHOD => {
498 let params: lsp::WorkDoneProgressCreateParams = params.parse()?;
499 Self::WorkDoneProgressCreate(params)
500 }
501 lsp::request::ApplyWorkspaceEdit::METHOD => {
502 let params: lsp::ApplyWorkspaceEditParams = params.parse()?;
503 Self::ApplyWorkspaceEdit(params)
504 }
505 lsp::request::WorkspaceFoldersRequest::METHOD => Self::WorkspaceFolders,
506 lsp::request::WorkspaceConfiguration::METHOD => {
507 let params: lsp::ConfigurationParams = params.parse()?;
508 Self::WorkspaceConfiguration(params)
509 }
510 lsp::request::RegisterCapability::METHOD => {
511 let params: lsp::RegistrationParams = params.parse()?;
512 Self::RegisterCapability(params)
513 }
514 lsp::request::UnregisterCapability::METHOD => {
515 let params: lsp::UnregistrationParams = params.parse()?;
516 Self::UnregisterCapability(params)
517 }
518 lsp::request::ShowDocument::METHOD => {
519 let params: lsp::ShowDocumentParams = params.parse()?;
520 Self::ShowDocument(params)
521 }
522 lsp::request::WorkspaceDiagnosticRefresh::METHOD => Self::WorkspaceDiagnosticRefresh,
523 lsp::request::ShowMessageRequest::METHOD => {
524 let params: lsp::ShowMessageRequestParams = params.parse()?;
525 Self::ShowMessageRequest(params)
526 }
527 _ => {
528 return Err(Error::Unhandled);
529 }
530 };
531 Ok(request)
532 }
533 }
534
535 #[derive(Debug, PartialEq, Clone)]
536 pub enum Notification {
537 // we inject this notification to signal the LSP is ready
538 Initialized,
539 // and this notification to signal that the LSP exited
540 Exit,
541 PublishDiagnostics(lsp::PublishDiagnosticsParams),
542 ShowMessage(lsp::ShowMessageParams),
543 LogMessage(lsp::LogMessageParams),
544 ProgressMessage(lsp::ProgressParams),
545 }
546
547 impl Notification {
548 pub fn parse(method: &str, params: jsonrpc::Params) -> Result<Notification> {
549 use lsp::notification::Notification as _;
550
551 let notification = match method {
552 lsp::notification::Initialized::METHOD => Self::Initialized,
553 lsp::notification::Exit::METHOD => Self::Exit,
554 lsp::notification::PublishDiagnostics::METHOD => {
555 let params: lsp::PublishDiagnosticsParams = params.parse()?;
556 Self::PublishDiagnostics(params)
557 }
558
559 lsp::notification::ShowMessage::METHOD => {
560 let params: lsp::ShowMessageParams = params.parse()?;
561 Self::ShowMessage(params)
562 }
563 lsp::notification::LogMessage::METHOD => {
564 let params: lsp::LogMessageParams = params.parse()?;
565 Self::LogMessage(params)
566 }
567 lsp::notification::Progress::METHOD => {
568 let params: lsp::ProgressParams = params.parse()?;
569 Self::ProgressMessage(params)
570 }
571 _ => {
572 return Err(Error::Unhandled);
573 }
574 };
575
576 Ok(notification)
577 }
578 }
579
580 #[derive(Debug)]
581 pub struct Registry {
582 inner: SlotMap<LanguageServerId, Arc<Client>>,
583 inner_by_name: HashMap<LanguageServerName, Vec<Arc<Client>>>,
584 syn_loader: Arc<ArcSwap<helix_core::syntax::Loader>>,
585 pub incoming: SelectAll<UnboundedReceiverStream<(LanguageServerId, Call)>>,
586 pub file_event_handler: file_event::Handler,
587 }
588
589 impl Registry {
590 pub fn new(syn_loader: Arc<ArcSwap<helix_core::syntax::Loader>>) -> Self {
591 Self {
592 inner: SlotMap::with_key(),
593 inner_by_name: HashMap::new(),
594 syn_loader,
595 incoming: SelectAll::new(),
596 file_event_handler: file_event::Handler::new(),
597 }
598 }
599
600 pub fn get_by_id(&self, id: LanguageServerId) -> Option<&Arc<Client>> {
601 self.inner.get(id)
602 }
603
604 pub fn remove_by_id(&mut self, id: LanguageServerId) {
605 let Some(client) = self.inner.remove(id) else {
606 log::debug!("client was already removed");
607 return;
608 };
609 self.file_event_handler.remove_client(id);
610 let instances = self
611 .inner_by_name
612 .get_mut(client.name())
613 .expect("inner and inner_by_name must be synced");
614 instances.retain(|ls| id != ls.id());
615 if instances.is_empty() {
616 self.inner_by_name.remove(client.name());
617 }
618 }
619
620 fn start_client(
621 &mut self,
622 name: String,
623 ls_config: &LanguageConfiguration,
624 doc_path: Option<&std::path::Path>,
625 root_dirs: &[PathBuf],
626 enable_snippets: bool,
627 ) -> Result<Arc<Client>, StartupError> {
628 let syn_loader = self.syn_loader.load();
629 let config = syn_loader
630 .language_server_configs()
631 .get(&name)
632 .ok_or_else(|| anyhow::anyhow!("Language server '{name}' not defined"))?;
633 let id = self.inner.try_insert_with_key(|id| {
634 start_client(
635 id,
636 name,
637 ls_config,
638 config,
639 doc_path,
640 root_dirs,
641 enable_snippets,
642 )
643 .map(|client| {
644 self.incoming.push(UnboundedReceiverStream::new(client.1));
645 client.0
646 })
647 })?;
648 Ok(self.inner[id].clone())
649 }
650
651 /// If this method is called, all documents that have a reference to the language server have to refresh their language servers,
652 /// See helix_view::editor::Editor::refresh_language_servers
653 pub fn restart_server(
654 &mut self,
655 name: &str,
656 language_config: &LanguageConfiguration,
657 doc_path: Option<&std::path::Path>,
658 root_dirs: &[PathBuf],
659 enable_snippets: bool,
660 ) -> Option<Result<Arc<Client>>> {
661 if let Some(old_clients) = self.inner_by_name.remove(name) {
662 if old_clients.is_empty() {
663 log::info!("restarting client for '{name}' which was manually stopped");
664 } else {
665 log::info!("stopping existing clients for '{name}'");
666 }
667 for old_client in old_clients {
668 self.file_event_handler.remove_client(old_client.id());
669 self.inner.remove(old_client.id());
670 old_client.force_shutdown();
671 }
672 }
673 let client = match self.start_client(
674 name.to_string(),
675 language_config,
676 doc_path,
677 root_dirs,
678 enable_snippets,
679 ) {
680 Ok(client) => client,
681 Err(StartupError::NoRequiredRootFound) => return None,
682 Err(StartupError::Error(err)) => return Some(Err(err)),
683 };
684 self.inner_by_name
685 .insert(name.to_owned(), vec![client.clone()]);
686
687 Some(Ok(client))
688 }
689
690 pub fn stop(&mut self, name: &str) {
691 if let Some(clients) = self.inner_by_name.get_mut(name) {
692 // Drain the clients vec so that the entry in `inner_by_name` remains
693 // empty. We use the empty vec as a "tombstone" to mean that a server
694 // has been manually stopped with :lsp-stop and shouldn't be automatically
695 // restarted by `get`. :lsp-restart can be used to restart the server
696 // manually.
697 for client in clients.drain(..) {
698 self.file_event_handler.remove_client(client.id());
699 self.inner.remove(client.id());
700 client.force_shutdown();
701 }
702 }
703 }
704
705 pub fn get<'a>(
706 &'a mut self,
707 language_config: &'a LanguageConfiguration,
708 doc_path: Option<&'a std::path::Path>,
709 root_dirs: &'a [PathBuf],
710 enable_snippets: bool,
711 ) -> impl Iterator<Item = (LanguageServerName, Result<Arc<Client>>)> + 'a {
712 language_config.language_servers.iter().filter_map(
713 move |LanguageServerFeatures { name, .. }| {
714 if let Some(clients) = self.inner_by_name.get(name) {
715 // If the clients vec is empty, do not automatically start a client
716 // for this server. The empty vec is a tombstone left to mean that a
717 // server has been manually stopped and shouldn't be started automatically.
718 // See `stop`.
719 if clients.is_empty() {
720 return None;
721 }
722
723 if let Some((_, client)) = clients.iter().enumerate().find(|(i, client)| {
724 let manual_roots = language_config
725 .workspace_lsp_roots
726 .as_deref()
727 .unwrap_or(root_dirs);
728 client.try_add_doc(&language_config.roots, manual_roots, doc_path, *i == 0)
729 }) {
730 return Some((name.to_owned(), Ok(client.clone())));
731 }
732 }
733 match self.start_client(
734 name.clone(),
735 language_config,
736 doc_path,
737 root_dirs,
738 enable_snippets,
739 ) {
740 Ok(client) => {
741 self.inner_by_name
742 .entry(name.to_owned())
743 .or_default()
744 .push(client.clone());
745 Some((name.clone(), Ok(client)))
746 }
747 Err(StartupError::NoRequiredRootFound) => None,
748 Err(StartupError::Error(err)) => Some((name.to_owned(), Err(err))),
749 }
750 },
751 )
752 }
753
754 pub fn iter_clients(&self) -> impl Iterator<Item = &Arc<Client>> {
755 self.inner.values()
756 }
757 }
758
759 #[derive(Debug)]
760 pub enum ProgressStatus {
761 Created,
762 Started {
763 title: String,
764 progress: lsp::WorkDoneProgress,
765 },
766 }
767
768 impl ProgressStatus {
769 pub fn progress(&self) -> Option<&lsp::WorkDoneProgress> {
770 match &self {
771 ProgressStatus::Created => None,
772 ProgressStatus::Started { title: _, progress } => Some(progress),
773 }
774 }
775 }
776
777 #[derive(Default, Debug)]
778 /// Acts as a container for progress reported by language servers. Each server
779 /// has a unique id assigned at creation through [`Registry`]. This id is then used
780 /// to store the progress in this map.
781 pub struct LspProgressMap(HashMap<LanguageServerId, HashMap<lsp::ProgressToken, ProgressStatus>>);
782
783 impl LspProgressMap {
784 pub fn new() -> Self {
785 Self::default()
786 }
787
788 /// Returns a map of all tokens corresponding to the language server with `id`.
789 pub fn progress_map(
790 &self,
791 id: LanguageServerId,
792 ) -> Option<&HashMap<lsp::ProgressToken, ProgressStatus>> {
793 self.0.get(&id)
794 }
795
796 pub fn is_progressing(&self, id: LanguageServerId) -> bool {
797 self.0.get(&id).map(|it| !it.is_empty()).unwrap_or_default()
798 }
799
800 /// Returns last progress status for a given server with `id` and `token`.
801 pub fn progress(
802 &self,
803 id: LanguageServerId,
804 token: &lsp::ProgressToken,
805 ) -> Option<&ProgressStatus> {
806 self.0.get(&id).and_then(|values| values.get(token))
807 }
808
809 pub fn title(&self, id: LanguageServerId, token: &lsp::ProgressToken) -> Option<&String> {
810 self.progress(id, token).and_then(|p| match p {
811 ProgressStatus::Created => None,
812 ProgressStatus::Started { title, .. } => Some(title),
813 })
814 }
815
816 /// Checks if progress `token` for server with `id` is created.
817 pub fn is_created(&mut self, id: LanguageServerId, token: &lsp::ProgressToken) -> bool {
818 self.0
819 .get(&id)
820 .map(|values| values.get(token).is_some())
821 .unwrap_or_default()
822 }
823
824 pub fn create(&mut self, id: LanguageServerId, token: lsp::ProgressToken) {
825 self.0
826 .entry(id)
827 .or_default()
828 .insert(token, ProgressStatus::Created);
829 }
830
831 /// Ends the progress by removing the `token` from server with `id`, if removed returns the value.
832 pub fn end_progress(
833 &mut self,
834 id: LanguageServerId,
835 token: &lsp::ProgressToken,
836 ) -> Option<ProgressStatus> {
837 self.0.get_mut(&id).and_then(|vals| vals.remove(token))
838 }
839
840 /// Updates the progress of `token` for server with `id` to begin state `status`
841 pub fn begin(
842 &mut self,
843 id: LanguageServerId,
844 token: lsp::ProgressToken,
845 status: lsp::WorkDoneProgressBegin,
846 ) {
847 self.0.entry(id).or_default().insert(
848 token,
849 ProgressStatus::Started {
850 title: status.title.clone(),
851 progress: lsp::WorkDoneProgress::Begin(status),
852 },
853 );
854 }
855
856 /// Updates the progress of `token` for server with `id` to report state `status`.
857 pub fn update(
858 &mut self,
859 id: LanguageServerId,
860 token: lsp::ProgressToken,
861 status: lsp::WorkDoneProgressReport,
862 ) {
863 self.0
864 .entry(id)
865 .or_default()
866 .entry(token)
867 .and_modify(|e| match e {
868 ProgressStatus::Created => (),
869 ProgressStatus::Started { progress, .. } => {
870 *progress = lsp::WorkDoneProgress::Report(status)
871 }
872 });
873 }
874 }
875
876 struct NewClient(Arc<Client>, UnboundedReceiver<(LanguageServerId, Call)>);
877
878 enum StartupError {
879 NoRequiredRootFound,
880 Error(Error),
881 }
882
883 impl<T: Into<Error>> From<T> for StartupError {
884 fn from(value: T) -> Self {
885 StartupError::Error(value.into())
886 }
887 }
888
889 /// start_client takes both a LanguageConfiguration and a LanguageServerConfiguration to ensure that
890 /// it is only called when it makes sense.
891 fn start_client(
892 id: LanguageServerId,
893 name: String,
894 config: &LanguageConfiguration,
895 ls_config: &LanguageServerConfiguration,
896 doc_path: Option<&std::path::Path>,
897 root_dirs: &[PathBuf],
898 enable_snippets: bool,
899 ) -> Result<NewClient, StartupError> {
900 let (workspace, workspace_is_cwd) = helix_loader::find_workspace();
901 let workspace = path::normalize(workspace);
902 let root = find_lsp_workspace(
903 doc_path
904 .and_then(|x| x.parent().and_then(|x| x.to_str()))
905 .unwrap_or("."),
906 &config.roots,
907 config.workspace_lsp_roots.as_deref().unwrap_or(root_dirs),
908 &workspace,
909 workspace_is_cwd,
910 );
911
912 // `root_uri` and `workspace_folder` can be empty in case there is no workspace
913 // `root_url` can not, use `workspace` as a fallback
914 let root_path = root.clone().unwrap_or_else(|| workspace.clone());
915 let root_uri = root.and_then(|root| lsp::Url::from_file_path(root).ok());
916
917 if let Some(globset) = &ls_config.required_root_patterns {
918 if !root_path
919 .read_dir()?
920 .flatten()
921 .map(|entry| entry.file_name())
922 .any(|entry| globset.is_match(entry))
923 {
924 // TODO: also show the globset that should be matched: https://github.com/BurntSushi/ripgrep/issues/3274
925 warn!("The lsp {name:?} tried to start at {root_path:?} but failed to match it's 'required_root_patterns'");
926 return Err(StartupError::NoRequiredRootFound);
927 }
928 }
929
930 let (client, incoming, initialize_notify) = Client::start(
931 &ls_config.command,
932 &ls_config.args,
933 ls_config.config.clone(),
934 &ls_config.environment,
935 root_path,
936 root_uri,
937 id,
938 name,
939 ls_config.timeout,
940 )?;
941
942 let client = Arc::new(client);
943
944 // Initialize the client asynchronously
945 let _client = client.clone();
946 tokio::spawn(async move {
947 use futures_util::TryFutureExt;
948 let value = _client
949 .capabilities
950 .get_or_try_init(|| {
951 _client
952 .initialize(enable_snippets)
953 .map_ok(|response| response.capabilities)
954 })
955 .await;
956
957 if let Err(e) = value {
958 log::error!("failed to initialize language server: {}", e);
959 return;
960 }
961
962 // next up, notify<initialized>
963 _client.notify::<lsp::notification::Initialized>(lsp::InitializedParams {});
964
965 initialize_notify.notify_one();
966 });
967
968 Ok(NewClient(client, incoming))
969 }
970
971 /// Find an LSP workspace of a file using the following mechanism:
972 /// * if the file is outside `workspace` return `None`
973 /// * start at `file` and search the file tree upward
974 /// * stop the search at the first `root_dirs` entry that contains `file`
975 /// * if no `root_dirs` matches `file` stop at workspace
976 /// * Returns the top most directory that contains a `root_marker`
977 /// * If no root marker and we stopped at a `root_dirs` entry, return the directory we stopped at
978 /// * If we stopped at `workspace` instead and `workspace_is_cwd == false` return `None`
979 /// * If we stopped at `workspace` instead and `workspace_is_cwd == true` return `workspace`
980 pub fn find_lsp_workspace(
981 file: &str,
982 root_markers: &RootMarkers,
983 root_dirs: &[PathBuf],
984 workspace: &Path,
985 workspace_is_cwd: bool,
986 ) -> Option<PathBuf> {
987 let file = std::path::Path::new(file);
988 let mut file = if file.is_absolute() {
989 file.to_path_buf()
990 } else {
991 let current_dir = helix_stdx::env::current_working_dir();
992 current_dir.join(file)
993 };
994 file = path::normalize(&file);
995
996 if !file.starts_with(workspace) {
997 return None;
998 }
999
1000 let mut top_marker = None;
1001 for ancestor in file.ancestors() {
1002 let Ok(mut dir) = fs::read_dir(ancestor) else {
1003 continue;
1004 };
1005
1006 if dir.any(|entry| {
1007 if let Ok(entry) = entry {
1008 return root_markers.is_match(entry.file_name());
1009 }
1010 false
1011 }) {
1012 top_marker = Some(ancestor);
1013 }
1014
1015 if root_dirs
1016 .iter()
1017 .any(|root_dir| path::normalize(workspace.join(root_dir)) == ancestor)
1018 {
1019 // if the worskapce is the cwd do not search any higher for workspaces
1020 // but specify
1021 return Some(top_marker.unwrap_or(workspace).to_owned());
1022 }
1023 if ancestor == workspace {
1024 // if the workspace is the CWD, let the LSP decide what the workspace
1025 // is
1026 return top_marker
1027 .or_else(|| (!workspace_is_cwd).then_some(workspace))
1028 .map(Path::to_owned);
1029 }
1030 }
1031
1032 debug_assert!(false, "workspace must be an ancestor of <file>");
1033 None
1034 }
1035
1036 #[cfg(test)]
1037 mod tests {
1038 use super::{lsp, util::*, OffsetEncoding};
1039 use helix_core::Rope;
1040
1041 #[test]
1042 fn converts_lsp_pos_to_pos() {
1043 macro_rules! test_case {
1044 ($doc:expr, ($x:expr, $y:expr) => $want:expr) => {
1045 let doc = Rope::from($doc);
1046 let pos = lsp::Position::new($x, $y);
1047 assert_eq!($want, lsp_pos_to_pos(&doc, pos, OffsetEncoding::Utf16));
1048 assert_eq!($want, lsp_pos_to_pos(&doc, pos, OffsetEncoding::Utf8))
1049 };
1050 }
1051
1052 test_case!("", (0, 0) => Some(0));
1053 test_case!("", (0, 1) => Some(0));
1054 test_case!("", (1, 0) => Some(0));
1055 test_case!("\n\n", (0, 0) => Some(0));
1056 test_case!("\n\n", (1, 0) => Some(1));
1057 test_case!("\n\n", (1, 1) => Some(1));
1058 test_case!("\n\n", (2, 0) => Some(2));
1059 test_case!("\n\n", (3, 0) => Some(2));
1060 test_case!("test\n\n\n\ncase", (4, 3) => Some(11));
1061 test_case!("test\n\n\n\ncase", (4, 4) => Some(12));
1062 test_case!("test\n\n\n\ncase", (4, 5) => Some(12));
1063 test_case!("", (u32::MAX, u32::MAX) => Some(0));
1064 }
1065
1066 #[test]
1067 fn emoji_format_gh_4791() {
1068 use lsp::{Position, Range, TextEdit};
1069
1070 let edits = vec![
1071 TextEdit {
1072 range: Range {
1073 start: Position {
1074 line: 0,
1075 character: 1,
1076 },
1077 end: Position {
1078 line: 1,
1079 character: 0,
1080 },
1081 },
1082 new_text: "\n ".to_string(),
1083 },
1084 TextEdit {
1085 range: Range {
1086 start: Position {
1087 line: 1,
1088 character: 7,
1089 },
1090 end: Position {
1091 line: 2,
1092 character: 0,
1093 },
1094 },
1095 new_text: "\n ".to_string(),
1096 },
1097 ];
1098
1099 let mut source = Rope::from_str("[\n\"🇺🇸\",\n\"🎄\",\n]");
1100
1101 let transaction = generate_transaction_from_edits(&source, edits, OffsetEncoding::Utf16);
1102 assert!(transaction.apply(&mut source));
1103 assert_eq!(source, "[\n \"🇺🇸\",\n \"🎄\",\n]");
1104 }
1105
1106 #[test]
1107 fn overlapping_edits_are_dropped() {
1108 // Regression for issue #15514: a language server may send overlapping text edits.
1109 // Feeding overlapping ranges to `ChangeSet::from_changes` violates its sorted/non-overlapping
1110 // precondition and underflows `retain(from - last)`. The overlapping edit must be discarded here
1111 use lsp::{Position, Range, TextEdit};
1112
1113 let edit = |sc, ec, text: &str| TextEdit {
1114 range: Range {
1115 start: Position::new(0, sc),
1116 end: Position::new(0, ec),
1117 },
1118 new_text: text.to_string(),
1119 };
1120
1121 // Edits are given out of order and the second overlaps the first
1122 // (0..3 vs 2..4); after sorting, 2..4 starts before 0..3 ends.
1123 let edits = vec![edit(4, 5, "Z"), edit(0, 3, "X"), edit(2, 4, "Y")];
1124
1125 let mut source = Rope::from_str("abcdef");
1126 let transaction = generate_transaction_from_edits(&source, edits, OffsetEncoding::Utf16);
1127 // Must not panic. The overlapping 2..4 edit is dropped; 0..3 -> "X",
1128 // retain "d" (idx 3), 4..5 -> "Z", retain "f": "abcdef" -> "XdZf".
1129 assert!(transaction.apply(&mut source));
1130 assert_eq!(source, "XdZf");
1131 }
1132
1133 #[test]
1134 fn unsorted_edits_are_applied() {
1135 // Out-of-order (but non-overlapping) edits must all land; the sort keeps
1136 // every edit rather than dropping the earlier-positioned one.
1137 use lsp::{Position, Range, TextEdit};
1138
1139 let edit = |sc, ec, text: &str| TextEdit {
1140 range: Range {
1141 start: Position::new(0, sc),
1142 end: Position::new(0, ec),
1143 },
1144 new_text: text.to_string(),
1145 };
1146
1147 let edits = vec![edit(4, 5, "Y"), edit(0, 1, "X")];
1148
1149 let mut source = Rope::from_str("abcdef");
1150 let transaction = generate_transaction_from_edits(&source, edits, OffsetEncoding::Utf16);
1151 assert!(transaction.apply(&mut source));
1152 assert_eq!(source, "XbcdYf");
1153 }
1154 }