| 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 |
|
| 60 |
Utf8, |
| 61 |
|
| 62 |
Utf32, |
| 63 |
|
| 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 |
|
| 76 |
|
| 77 |
|
| 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 |
|
| 132 |
|
| 133 |
|
| 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 |
|
| 142 |
|
| 143 |
|
| 144 |
log::warn!("LSP position {pos:?} out of range assuming EOF"); |
| 145 |
return Some(doc.len_chars()); |
| 146 |
} |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
er agnostic. |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 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 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 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 |
|
| 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 |
|
| 209 |
|
| 210 |
|
| 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 |
|
| 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 |
|
| 259 |
|
| 260 |
|
| 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 |
|
| 276 |
|
| 277 |
|
| 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 |
|
| 318 |
|
| 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 |
|
| 361 |
|
| 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 |
|
| 392 |
|
| 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 |
|
| 405 |
|
| 406 |
edits.sort_by_key(|edit| edit.range.start); |
| 407 |
|
| 408 |
|
| 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 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
|
| 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 |
|
| 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 |
|
| 526 |
Initialized, |
| 527 |
|
| 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 |
|
| 640 |
|
| 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 |
|
| 681 |
|
| 682 |
|
| 683 |
|
| 684 |
|
| 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 |
|
| 704 |
|
| 705 |
|
| 706 |
|
| 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 |
|
| 767 |
|
| 768 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 878 |
|
| 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 |
|
| 901 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 951 |
_client.notify::<lsp::notification::Initialized>(lsp::InitializedParams {}); |
| 952 |
|
| 953 |
initialize_notify.notify_one(); |
| 954 |
}); |
| 955 |
|
| 956 |
Ok(NewClient(client, incoming)) |
| 957 |
} |
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
|
| 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 |
|
| 1008 |
|
| 1009 |
return Some(top_marker.unwrap_or(workspace).to_owned()); |
| 1010 |
} |
| 1011 |
if ancestor == workspace { |
| 1012 |
|
| 1013 |
|
| 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 |
|
| 1097 |
|
| 1098 |
|
| 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 |
|
| 1110 |
|
| 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 |
|
| 1116 |
|
| 1117 |
assert!(transaction.apply(&mut source)); |
| 1118 |
assert_eq!(source, "XdZf"); |
| 1119 |
} |
| 1120 |
|
| 1121 |
#[test] |
| 1122 |
fn unsorted_edits_are_applied() { |
| 1123 |
|
| 1124 |
|
| 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 |
} |