| 1 |
use std::collections::btree_map::Entry; |
| 2 |
use std::collections::HashSet; |
| 3 |
use std::fmt::Display; |
| 4 |
|
| 5 |
use crate::editor::Action; |
| 6 |
use crate::events::{ |
| 7 |
DiagnosticsDidChange, DocumentDidChange, DocumentDidClose, LanguageServerInitialized, |
| 8 |
}; |
| 9 |
use crate::{DocumentId, Editor, ViewId}; |
| 10 |
use helix_core::diagnostic::DiagnosticProvider; |
| 11 |
use helix_core::Uri; |
| 12 |
use helix_event::register_hook; |
| 13 |
use helix_lsp::util::generate_transaction_from_edits; |
| 14 |
use helix_lsp::{lsp, LanguageServerId, OffsetEncoding}; |
| 15 |
|
| 16 |
use super::Handlers; |
| 17 |
|
| 18 |
pub struct DocumentColorsEvent(pub DocumentId); |
| 19 |
pub struct DocumentLinksEvent(pub DocumentId); |
| 20 |
|
| 21 |
#[derive(Debug, PartialEq, Eq, Clone, Copy)] |
| 22 |
pub enum SignatureHelpInvoked { |
| 23 |
Automatic, |
| 24 |
Manual, |
| 25 |
} |
| 26 |
|
| 27 |
pub enum SignatureHelpEvent { |
| 28 |
Invoked, |
| 29 |
Trigger, |
| 30 |
ReTrigger, |
| 31 |
Cancel, |
| 32 |
RequestComplete { open: bool }, |
| 33 |
} |
| 34 |
|
| 35 |
pub struct PullDiagnosticsEvent { |
| 36 |
pub document_id: DocumentId, |
| 37 |
} |
| 38 |
|
| 39 |
pub struct PullAllDocumentsDiagnosticsEvent { |
| 40 |
pub language_servers: HashSet<LanguageServerId>, |
| 41 |
} |
| 42 |
|
| 43 |
pub struct CodeActionHintEvent { |
| 44 |
pub document_id: DocumentId, |
| 45 |
pub view_id: ViewId, |
| 46 |
} |
| 47 |
|
| 48 |
#[derive(Debug)] |
| 49 |
pub struct ApplyEditError { |
| 50 |
pub kind: ApplyEditErrorKind, |
| 51 |
pub failed_change_idx: usize, |
| 52 |
} |
| 53 |
|
| 54 |
#[derive(Debug)] |
| 55 |
pub enum ApplyEditErrorKind { |
| 56 |
DocumentChanged, |
| 57 |
FileNotFound, |
| 58 |
InvalidUrl(helix_core::uri::UrlConversionError), |
| 59 |
IoError(std::io::Error), |
| 60 |
|
| 61 |
|
| 62 |
} |
| 63 |
|
| 64 |
impl From<std::io::Error> for ApplyEditErrorKind { |
| 65 |
fn from(err: std::io::Error) -> Self { |
| 66 |
ApplyEditErrorKind::IoError(err) |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
impl From<helix_core::uri::UrlConversionError> for ApplyEditErrorKind { |
| 71 |
fn from(err: helix_core::uri::UrlConversionError) -> Self { |
| 72 |
ApplyEditErrorKind::InvalidUrl(err) |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
impl Display for ApplyEditErrorKind { |
| 77 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 78 |
match self { |
| 79 |
ApplyEditErrorKind::DocumentChanged => f.write_str("document has changed"), |
| 80 |
ApplyEditErrorKind::FileNotFound => f.write_str("file not found"), |
| 81 |
ApplyEditErrorKind::InvalidUrl(err) => f.write_str(&format!("{err}")), |
| 82 |
ApplyEditErrorKind::IoError(err) => f.write_str(&format!("{err}")), |
| 83 |
} |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
impl Editor { |
| 88 |
fn apply_text_edits( |
| 89 |
&mut self, |
| 90 |
url: &helix_lsp::Url, |
| 91 |
version: Option<i32>, |
| 92 |
text_edits: Vec<lsp::TextEdit>, |
| 93 |
offset_encoding: OffsetEncoding, |
| 94 |
) -> Result<(), ApplyEditErrorKind> { |
| 95 |
let uri = match Uri::try_from(url) { |
| 96 |
Ok(uri) => uri, |
| 97 |
Err(err) => { |
| 98 |
log::error!("{err}"); |
| 99 |
return Err(err.into()); |
| 100 |
} |
| 101 |
}; |
| 102 |
let path = uri.as_path().expect("URIs are valid paths"); |
| 103 |
|
| 104 |
let doc_id = match self.open(path, Action::Load) { |
| 105 |
Ok(doc_id) => doc_id, |
| 106 |
Err(err) => { |
| 107 |
let err = format!( |
| 108 |
"failed to open document: {}: {}", |
| 109 |
path.to_string_lossy(), |
| 110 |
err |
| 111 |
); |
| 112 |
log::error!("{}", err); |
| 113 |
self.set_error(err); |
| 114 |
return Err(ApplyEditErrorKind::FileNotFound); |
| 115 |
} |
| 116 |
}; |
| 117 |
|
| 118 |
let doc = doc_mut!(self, &doc_id); |
| 119 |
if let Some(version) = version { |
| 120 |
if version != doc.version() { |
| 121 |
let err = format!("outdated workspace edit for {path:?}"); |
| 122 |
log::error!("{err}, expected {} but got {version}", doc.version()); |
| 123 |
self.set_error(err); |
| 124 |
return Err(ApplyEditErrorKind::DocumentChanged); |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
|
| 129 |
let view_id = self.get_synced_view_id(doc_id); |
| 130 |
let doc = doc_mut!(self, &doc_id); |
| 131 |
|
| 132 |
let transaction = generate_transaction_from_edits(doc.text(), text_edits, offset_encoding); |
| 133 |
let view = view_mut!(self, view_id); |
| 134 |
doc.apply(&transaction, view.id); |
| 135 |
doc.append_changes_to_history(view); |
| 136 |
Ok(()) |
| 137 |
} |
| 138 |
|
| 139 |
|
| 140 |
pub fn apply_workspace_edit( |
| 141 |
&mut self, |
| 142 |
offset_encoding: OffsetEncoding, |
| 143 |
workspace_edit: &lsp::WorkspaceEdit, |
| 144 |
) -> Result<(), ApplyEditError> { |
| 145 |
if let Some(ref document_changes) = workspace_edit.document_changes { |
| 146 |
match document_changes { |
| 147 |
lsp::DocumentChanges::Edits(document_edits) => { |
| 148 |
for (i, document_edit) in document_edits.iter().enumerate() { |
| 149 |
let edits = document_edit |
| 150 |
.edits |
| 151 |
.iter() |
| 152 |
.map(|edit| match edit { |
| 153 |
lsp::OneOf::Left(text_edit) => text_edit, |
| 154 |
lsp::OneOf::Right(annotated_text_edit) => { |
| 155 |
&annotated_text_edit.text_edit |
| 156 |
} |
| 157 |
}) |
| 158 |
.cloned() |
| 159 |
.collect(); |
| 160 |
self.apply_text_edits( |
| 161 |
&document_edit.text_document.uri, |
| 162 |
document_edit.text_document.version, |
| 163 |
edits, |
| 164 |
offset_encoding, |
| 165 |
) |
| 166 |
.map_err(|kind| ApplyEditError { |
| 167 |
kind, |
| 168 |
failed_change_idx: i, |
| 169 |
})?; |
| 170 |
} |
| 171 |
} |
| 172 |
lsp::DocumentChanges::Operations(operations) => { |
| 173 |
log::debug!("document changes - operations: {:?}", operations); |
| 174 |
for (i, operation) in operations.iter().enumerate() { |
| 175 |
match operation { |
| 176 |
lsp::DocumentChangeOperation::Op(op) => { |
| 177 |
self.apply_document_resource_op(op).map_err(|err| { |
| 178 |
ApplyEditError { |
| 179 |
kind: err, |
| 180 |
failed_change_idx: i, |
| 181 |
} |
| 182 |
})?; |
| 183 |
} |
| 184 |
|
| 185 |
lsp::DocumentChangeOperation::Edit(document_edit) => { |
| 186 |
let edits = document_edit |
| 187 |
.edits |
| 188 |
.iter() |
| 189 |
.map(|edit| match edit { |
| 190 |
lsp::OneOf::Left(text_edit) => text_edit, |
| 191 |
lsp::OneOf::Right(annotated_text_edit) => { |
| 192 |
&annotated_text_edit.text_edit |
| 193 |
} |
| 194 |
}) |
| 195 |
.cloned() |
| 196 |
.collect(); |
| 197 |
self.apply_text_edits( |
| 198 |
&document_edit.text_document.uri, |
| 199 |
document_edit.text_document.version, |
| 200 |
edits, |
| 201 |
offset_encoding, |
| 202 |
) |
| 203 |
.map_err(|kind| { |
| 204 |
ApplyEditError { |
| 205 |
kind, |
| 206 |
failed_change_idx: i, |
| 207 |
} |
| 208 |
})?; |
| 209 |
} |
| 210 |
} |
| 211 |
} |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
return Ok(()); |
| 216 |
} |
| 217 |
|
| 218 |
if let Some(ref changes) = workspace_edit.changes { |
| 219 |
log::debug!("workspace changes: {:?}", changes); |
| 220 |
for (i, (uri, text_edits)) in changes.iter().enumerate() { |
| 221 |
let text_edits = text_edits.to_vec(); |
| 222 |
self.apply_text_edits(uri, None, text_edits, offset_encoding) |
| 223 |
.map_err(|kind| ApplyEditError { |
| 224 |
kind, |
| 225 |
failed_change_idx: i, |
| 226 |
})?; |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
Ok(()) |
| 231 |
} |
| 232 |
|
| 233 |
fn apply_document_resource_op( |
| 234 |
&mut self, |
| 235 |
op: &lsp::ResourceOp, |
| 236 |
) -> Result<(), ApplyEditErrorKind> { |
| 237 |
use lsp::ResourceOp; |
| 238 |
|
| 239 |
|
| 240 |
match op { |
| 241 |
ResourceOp::Create(op) => { |
| 242 |
let uri = Uri::try_from(&op.uri)?; |
| 243 |
let path = uri.as_path().expect("URIs are valid paths"); |
| 244 |
let ignore_if_exists = op.options.as_ref().is_some_and(|options| { |
| 245 |
!options.overwrite.unwrap_or(false) && options.ignore_if_exists.unwrap_or(false) |
| 246 |
}); |
| 247 |
if !ignore_if_exists || !path.exists() { |
| 248 |
self.create_path(path, false)?; |
| 249 |
} |
| 250 |
} |
| 251 |
ResourceOp::Delete(op) => { |
| 252 |
let uri = Uri::try_from(&op.uri)?; |
| 253 |
let path = uri.as_path().expect("URIs are valid paths"); |
| 254 |
let ignore_if_not_exists = op |
| 255 |
.options |
| 256 |
.as_ref() |
| 257 |
.is_some_and(|options| options.ignore_if_not_exists.unwrap_or(false)); |
| 258 |
if ignore_if_not_exists && !path.exists() { |
| 259 |
return Ok(()); |
| 260 |
} |
| 261 |
let recursive = op |
| 262 |
.options |
| 263 |
.as_ref() |
| 264 |
.and_then(|options| options.recursive) |
| 265 |
.unwrap_or(false); |
| 266 |
self.delete_path(path, recursive)?; |
| 267 |
} |
| 268 |
ResourceOp::Rename(op) => { |
| 269 |
let from_uri = Uri::try_from(&op.old_uri)?; |
| 270 |
let from = from_uri.as_path().expect("URIs are valid paths"); |
| 271 |
let to_uri = Uri::try_from(&op.new_uri)?; |
| 272 |
let to = to_uri.as_path().expect("URIs are valid paths"); |
| 273 |
let ignore_if_exists = op.options.as_ref().is_some_and(|options| { |
| 274 |
!options.overwrite.unwrap_or(false) && options.ignore_if_exists.unwrap_or(false) |
| 275 |
}); |
| 276 |
if !ignore_if_exists || !to.exists() { |
| 277 |
self.move_path(from, to)?; |
| 278 |
} |
| 279 |
} |
| 280 |
} |
| 281 |
Ok(()) |
| 282 |
} |
| 283 |
|
| 284 |
pub fn handle_lsp_diagnostics( |
| 285 |
&mut self, |
| 286 |
provider: &DiagnosticProvider, |
| 287 |
uri: Uri, |
| 288 |
version: Option<i32>, |
| 289 |
mut diagnostics: Vec<lsp::Diagnostic>, |
| 290 |
) { |
| 291 |
let doc = self |
| 292 |
.documents |
| 293 |
.values_mut() |
| 294 |
.find(|doc| doc.uri().is_some_and(|u| u == uri)); |
| 295 |
|
| 296 |
if let Some((version, doc)) = version.zip(doc.as_ref()) { |
| 297 |
if version != doc.version() { |
| 298 |
log::info!("Version ({version}) is out of date for {uri:?} (expected ({})), dropping PublishDiagnostic notification", doc.version()); |
| 299 |
return; |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
let mut unchanged_diag_sources = Vec::new(); |
| 304 |
if let Some((lang_conf, old_diagnostics)) = doc |
| 305 |
.as_ref() |
| 306 |
.and_then(|doc| Some((doc.language_config()?, self.diagnostics.get(&uri)?))) |
| 307 |
{ |
| 308 |
if !lang_conf.persistent_diagnostic_sources.is_empty() { |
| 309 |
|
| 310 |
|
| 311 |
diagnostics.sort_by_key(|d| (d.severity, d.range.start)); |
| 312 |
} |
| 313 |
for source in &lang_conf.persistent_diagnostic_sources { |
| 314 |
let new_diagnostics = diagnostics |
| 315 |
.iter() |
| 316 |
.filter(|d| d.source.as_ref() == Some(source)); |
| 317 |
let old_diagnostics = old_diagnostics |
| 318 |
.iter() |
| 319 |
.filter(|(d, d_provider)| { |
| 320 |
d_provider == provider && d.source.as_ref() == Some(source) |
| 321 |
}) |
| 322 |
.map(|(d, _)| d); |
| 323 |
if new_diagnostics.eq(old_diagnostics) { |
| 324 |
unchanged_diag_sources.push(source.clone()) |
| 325 |
} |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
let diagnostics = diagnostics.into_iter().map(|d| (d, provider.clone())); |
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
let diagnostics = match self.diagnostics.entry(uri) { |
| 335 |
Entry::Occupied(o) => { |
| 336 |
let current_diagnostics = o.into_mut(); |
| 337 |
|
| 338 |
current_diagnostics.retain(|(_, d_provider)| d_provider != provider); |
| 339 |
current_diagnostics.extend(diagnostics); |
| 340 |
current_diagnostics |
| 341 |
|
| 342 |
} |
| 343 |
Entry::Vacant(v) => v.insert(diagnostics.collect()), |
| 344 |
}; |
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
diagnostics.sort_by_key(|(d, provider)| (d.severity, d.range.start, provider.clone())); |
| 349 |
|
| 350 |
if let Some(doc) = doc { |
| 351 |
let diagnostic_of_language_server_and_not_in_unchanged_sources = |
| 352 |
|diagnostic: &lsp::Diagnostic, d_provider: &DiagnosticProvider| { |
| 353 |
d_provider == provider |
| 354 |
&& diagnostic |
| 355 |
.source |
| 356 |
.as_ref() |
| 357 |
.is_none_or(|source| !unchanged_diag_sources.contains(source)) |
| 358 |
}; |
| 359 |
let diagnostics = Self::doc_diagnostics_with_filter( |
| 360 |
&self.language_servers, |
| 361 |
&self.diagnostics, |
| 362 |
doc, |
| 363 |
diagnostic_of_language_server_and_not_in_unchanged_sources, |
| 364 |
); |
| 365 |
doc.replace_diagnostics(diagnostics, &unchanged_diag_sources, Some(provider)); |
| 366 |
|
| 367 |
let doc = doc.id(); |
| 368 |
helix_event::dispatch(DiagnosticsDidChange { editor: self, doc }); |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
pub fn execute_lsp_command(&mut self, command: lsp::Command, server_id: LanguageServerId) { |
| 373 |
|
| 374 |
|
| 375 |
let Some(future) = self |
| 376 |
.language_server_by_id(server_id) |
| 377 |
.and_then(|server| server.command(command)) |
| 378 |
else { |
| 379 |
self.set_error("Language server does not support executing commands"); |
| 380 |
return; |
| 381 |
}; |
| 382 |
|
| 383 |
tokio::spawn(async move { |
| 384 |
if let Err(err) = future.await { |
| 385 |
log::error!("Error executing LSP command: {err}"); |
| 386 |
} |
| 387 |
}); |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
pub fn register_hooks(_handlers: &Handlers) { |
| 392 |
register_hook!(move |event: &mut LanguageServerInitialized<'_>| { |
| 393 |
let language_server = event.editor.language_server_by_id(event.server_id).unwrap(); |
| 394 |
|
| 395 |
for doc in event |
| 396 |
.editor |
| 397 |
.documents() |
| 398 |
.filter(|doc| doc.supports_language_server(event.server_id)) |
| 399 |
{ |
| 400 |
let Some(url) = doc.url() else { |
| 401 |
continue; |
| 402 |
}; |
| 403 |
|
| 404 |
let language_id = doc.language_id().map(ToOwned::to_owned).unwrap_or_default(); |
| 405 |
|
| 406 |
language_server.text_document_did_open(url, doc.version(), doc.text(), language_id); |
| 407 |
} |
| 408 |
|
| 409 |
Ok(()) |
| 410 |
}); |
| 411 |
|
| 412 |
register_hook!(move |event: &mut DocumentDidChange<'_>| { |
| 413 |
|
| 414 |
if !event.ghost_transaction { |
| 415 |
for language_server in event.doc.language_servers() { |
| 416 |
language_server.text_document_did_change( |
| 417 |
event.doc.versioned_identifier(), |
| 418 |
event.old_text, |
| 419 |
event.doc.text(), |
| 420 |
event.changes, |
| 421 |
); |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
Ok(()) |
| 426 |
}); |
| 427 |
|
| 428 |
register_hook!(move |event: &mut DocumentDidClose<'_>| { |
| 429 |
|
| 430 |
for language_server in event.doc.language_servers() { |
| 431 |
language_server.text_document_did_close(event.doc.identifier()); |
| 432 |
} |
| 433 |
|
| 434 |
Ok(()) |
| 435 |
}); |
| 436 |
} |