Debian Codegraph @

helix-lsp/src/lib.rs

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