| 1 |
use futures_util::{stream::FuturesUnordered, FutureExt}; |
| 2 |
use helix_lsp::{ |
| 3 |
block_on, |
| 4 |
lsp::{ |
| 5 |
self, CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionTriggerKind, |
| 6 |
DiagnosticSeverity, NumberOrString, |
| 7 |
}, |
| 8 |
util::{diagnostic_to_lsp_diagnostic, lsp_range_to_range, range_to_lsp_range}, |
| 9 |
Client, LanguageServerId, OffsetEncoding, |
| 10 |
}; |
| 11 |
use tokio_stream::StreamExt; |
| 12 |
use tui::{text::Span, widgets::Row}; |
| 13 |
|
| 14 |
use super::{align_view, push_jump, Align, Context, Editor}; |
| 15 |
|
| 16 |
use helix_core::{ |
| 17 |
diagnostic::DiagnosticProvider, syntax::config::LanguageServerFeature, |
| 18 |
text_annotations::InlineAnnotation, Selection, Uri, |
| 19 |
}; |
| 20 |
use helix_stdx::path; |
| 21 |
use helix_view::{ |
| 22 |
action::Action as CodeActionItem, |
| 23 |
document::{DocumentInlayHints, DocumentInlayHintsId}, |
| 24 |
editor::Action, |
| 25 |
handlers::lsp::SignatureHelpInvoked, |
| 26 |
theme::Style, |
| 27 |
Document, DocumentId, View, |
| 28 |
}; |
| 29 |
|
| 30 |
use crate::{ |
| 31 |
compositor::{self, Compositor}, |
| 32 |
job::{Callback, Job}, |
| 33 |
ui::{self, overlay::overlaid, FileLocation, Picker, Popup, PromptEvent}, |
| 34 |
}; |
| 35 |
|
| 36 |
use std::{ |
| 37 |
collections::{HashSet, VecDeque}, |
| 38 |
fmt::Display, |
| 39 |
future::Future, |
| 40 |
path::Path, |
| 41 |
}; |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
#[macro_export] |
| 49 |
macro_rules! language_server_with_feature { |
| 50 |
($editor:expr, $doc:expr, $feature:expr) => {{ |
| 51 |
let language_server = $doc.language_servers_with_feature($feature).next(); |
| 52 |
match language_server { |
| 53 |
Some(language_server) => language_server, |
| 54 |
None => { |
| 55 |
$editor.set_error(format!( |
| 56 |
"No configured language server supports {}", |
| 57 |
$feature |
| 58 |
)); |
| 59 |
return; |
| 60 |
} |
| 61 |
} |
| 62 |
}}; |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 68 |
struct Location { |
| 69 |
uri: Uri, |
| 70 |
range: lsp::Range, |
| 71 |
offset_encoding: OffsetEncoding, |
| 72 |
} |
| 73 |
|
| 74 |
fn lsp_location_to_location( |
| 75 |
location: lsp::Location, |
| 76 |
offset_encoding: OffsetEncoding, |
| 77 |
) -> Option<Location> { |
| 78 |
let uri = match location.uri.try_into() { |
| 79 |
Ok(uri) => uri, |
| 80 |
Err(err) => { |
| 81 |
log::warn!("discarding invalid or unsupported URI: {err}"); |
| 82 |
return None; |
| 83 |
} |
| 84 |
}; |
| 85 |
Some(Location { |
| 86 |
uri, |
| 87 |
range: location.range, |
| 88 |
offset_encoding, |
| 89 |
}) |
| 90 |
} |
| 91 |
|
| 92 |
struct SymbolInformationItem { |
| 93 |
location: Location, |
| 94 |
symbol: lsp::SymbolInformation, |
| 95 |
} |
| 96 |
|
| 97 |
struct DiagnosticStyles { |
| 98 |
hint: Style, |
| 99 |
info: Style, |
| 100 |
warning: Style, |
| 101 |
error: Style, |
| 102 |
} |
| 103 |
|
| 104 |
struct PickerDiagnostic { |
| 105 |
location: Location, |
| 106 |
diag: lsp::Diagnostic, |
| 107 |
} |
| 108 |
|
| 109 |
fn location_to_file_location(location: &Location) -> Option<FileLocation<'_>> { |
| 110 |
let path = location.uri.as_path()?; |
| 111 |
let line = Some(( |
| 112 |
location.range.start.line as usize, |
| 113 |
location.range.end.line as usize, |
| 114 |
)); |
| 115 |
Some((path.into(), line)) |
| 116 |
} |
| 117 |
|
| 118 |
fn jump_to_location(editor: &mut Editor, location: &Location, action: Action) { |
| 119 |
let (view, doc) = current!(editor); |
| 120 |
push_jump(view, doc); |
| 121 |
|
| 122 |
let Some(path) = location.uri.as_path() else { |
| 123 |
let err = format!("unable to convert URI to filepath: {:?}", location.uri); |
| 124 |
editor.set_error(err); |
| 125 |
return; |
| 126 |
}; |
| 127 |
jump_to_position( |
| 128 |
editor, |
| 129 |
path, |
| 130 |
location.range, |
| 131 |
location.offset_encoding, |
| 132 |
action, |
| 133 |
); |
| 134 |
} |
| 135 |
|
| 136 |
fn jump_to_position( |
| 137 |
editor: &mut Editor, |
| 138 |
path: &Path, |
| 139 |
range: lsp::Range, |
| 140 |
offset_encoding: OffsetEncoding, |
| 141 |
action: Action, |
| 142 |
) { |
| 143 |
let doc = match editor.open(path, action) { |
| 144 |
Ok(id) => doc_mut!(editor, &id), |
| 145 |
Err(err) => { |
| 146 |
let err = format!("failed to open path: {:?}: {:?}", path, err); |
| 147 |
editor.set_error(err); |
| 148 |
return; |
| 149 |
} |
| 150 |
}; |
| 151 |
let view = view_mut!(editor); |
| 152 |
|
| 153 |
let new_range = if let Some(new_range) = lsp_range_to_range(doc.text(), range, offset_encoding) |
| 154 |
{ |
| 155 |
new_range |
| 156 |
} else { |
| 157 |
log::warn!("lsp position out of bounds - {:?}", range); |
| 158 |
return; |
| 159 |
}; |
| 160 |
|
| 161 |
|
| 162 |
doc.set_selection(view.id, Selection::single(new_range.head, new_range.anchor)); |
| 163 |
if action.align_view(view, doc.id()) { |
| 164 |
align_view(doc, view, Align::Center); |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
fn display_symbol_kind(kind: lsp::SymbolKind) -> &'static str { |
| 169 |
match kind { |
| 170 |
lsp::SymbolKind::FILE => "file", |
| 171 |
lsp::SymbolKind::MODULE => "module", |
| 172 |
lsp::SymbolKind::NAMESPACE => "namespace", |
| 173 |
lsp::SymbolKind::PACKAGE => "package", |
| 174 |
lsp::SymbolKind::CLASS => "class", |
| 175 |
lsp::SymbolKind::METHOD => "method", |
| 176 |
lsp::SymbolKind::PROPERTY => "property", |
| 177 |
lsp::SymbolKind::FIELD => "field", |
| 178 |
lsp::SymbolKind::CONSTRUCTOR => "construct", |
| 179 |
lsp::SymbolKind::ENUM => "enum", |
| 180 |
lsp::SymbolKind::INTERFACE => "interface", |
| 181 |
lsp::SymbolKind::FUNCTION => "function", |
| 182 |
lsp::SymbolKind::VARIABLE => "variable", |
| 183 |
lsp::SymbolKind::CONSTANT => "constant", |
| 184 |
lsp::SymbolKind::STRING => "string", |
| 185 |
lsp::SymbolKind::NUMBER => "number", |
| 186 |
lsp::SymbolKind::BOOLEAN => "boolean", |
| 187 |
lsp::SymbolKind::ARRAY => "array", |
| 188 |
lsp::SymbolKind::OBJECT => "object", |
| 189 |
lsp::SymbolKind::KEY => "key", |
| 190 |
lsp::SymbolKind::NULL => "null", |
| 191 |
lsp::SymbolKind::ENUM_MEMBER => "enummem", |
| 192 |
lsp::SymbolKind::STRUCT => "struct", |
| 193 |
lsp::SymbolKind::EVENT => "event", |
| 194 |
lsp::SymbolKind::OPERATOR => "operator", |
| 195 |
lsp::SymbolKind::TYPE_PARAMETER => "typeparam", |
| 196 |
_ => { |
| 197 |
log::warn!("Unknown symbol kind: {:?}", kind); |
| 198 |
"" |
| 199 |
} |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
#[derive(Copy, Clone, PartialEq)] |
| 204 |
enum DiagnosticsFormat { |
| 205 |
ShowSourcePath, |
| 206 |
HideSourcePath, |
| 207 |
} |
| 208 |
|
| 209 |
type DiagnosticsPicker = Picker<PickerDiagnostic, DiagnosticStyles>; |
| 210 |
|
| 211 |
fn diag_picker( |
| 212 |
cx: &Context, |
| 213 |
diagnostics: impl IntoIterator<Item = (Uri, Vec<(lsp::Diagnostic, DiagnosticProvider)>)>, |
| 214 |
format: DiagnosticsFormat, |
| 215 |
) -> DiagnosticsPicker { |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
let mut flat_diag = Vec::new(); |
| 220 |
for (uri, diags) in diagnostics { |
| 221 |
flat_diag.reserve(diags.len()); |
| 222 |
|
| 223 |
for (diag, provider) in diags { |
| 224 |
if let Some(ls) = provider |
| 225 |
.language_server_id() |
| 226 |
.and_then(|id| cx.editor.language_server_by_id(id)) |
| 227 |
{ |
| 228 |
flat_diag.push(PickerDiagnostic { |
| 229 |
location: Location { |
| 230 |
uri: uri.clone(), |
| 231 |
range: diag.range, |
| 232 |
offset_encoding: ls.offset_encoding(), |
| 233 |
}, |
| 234 |
diag, |
| 235 |
}); |
| 236 |
} |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
flat_diag.sort_by(|a, b| { |
| 241 |
a.diag |
| 242 |
.severity |
| 243 |
.unwrap_or(lsp::DiagnosticSeverity::HINT) |
| 244 |
.cmp(&b.diag.severity.unwrap_or(lsp::DiagnosticSeverity::HINT)) |
| 245 |
}); |
| 246 |
|
| 247 |
let styles = DiagnosticStyles { |
| 248 |
hint: cx.editor.theme.get("hint"), |
| 249 |
info: cx.editor.theme.get("info"), |
| 250 |
warning: cx.editor.theme.get("warning"), |
| 251 |
error: cx.editor.theme.get("error"), |
| 252 |
}; |
| 253 |
|
| 254 |
let mut columns = vec![ |
| 255 |
ui::PickerColumn::new( |
| 256 |
"severity", |
| 257 |
|item: &PickerDiagnostic, styles: &DiagnosticStyles| { |
| 258 |
match item.diag.severity { |
| 259 |
Some(DiagnosticSeverity::HINT) => Span::styled("HINT", styles.hint), |
| 260 |
Some(DiagnosticSeverity::INFORMATION) => Span::styled("INFO", styles.info), |
| 261 |
Some(DiagnosticSeverity::WARNING) => Span::styled("WARN", styles.warning), |
| 262 |
Some(DiagnosticSeverity::ERROR) => Span::styled("ERROR", styles.error), |
| 263 |
_ => Span::raw(""), |
| 264 |
} |
| 265 |
.into() |
| 266 |
}, |
| 267 |
), |
| 268 |
ui::PickerColumn::new("source", |item: &PickerDiagnostic, _| { |
| 269 |
item.diag.source.as_deref().unwrap_or("").into() |
| 270 |
}), |
| 271 |
ui::PickerColumn::new("code", |item: &PickerDiagnostic, _| { |
| 272 |
match item.diag.code.as_ref() { |
| 273 |
Some(NumberOrString::Number(n)) => n.to_string().into(), |
| 274 |
Some(NumberOrString::String(s)) => s.as_str().into(), |
| 275 |
None => "".into(), |
| 276 |
} |
| 277 |
}), |
| 278 |
ui::PickerColumn::new("message", |item: &PickerDiagnostic, _| { |
| 279 |
item.diag.message.as_str().into() |
| 280 |
}), |
| 281 |
]; |
| 282 |
let mut primary_column = 3; |
| 283 |
|
| 284 |
if format == DiagnosticsFormat::ShowSourcePath { |
| 285 |
columns.insert( |
| 286 |
|
| 287 |
3, |
| 288 |
ui::PickerColumn::new("path", |item: &PickerDiagnostic, _| { |
| 289 |
if let Some(path) = item.location.uri.as_path() { |
| 290 |
path::get_truncated_path(path) |
| 291 |
.to_string_lossy() |
| 292 |
.to_string() |
| 293 |
.into() |
| 294 |
} else { |
| 295 |
Default::default() |
| 296 |
} |
| 297 |
}), |
| 298 |
); |
| 299 |
primary_column += 1; |
| 300 |
} |
| 301 |
|
| 302 |
Picker::new( |
| 303 |
columns, |
| 304 |
primary_column, |
| 305 |
flat_diag, |
| 306 |
styles, |
| 307 |
move |cx, diag, action| { |
| 308 |
jump_to_location(cx.editor, &diag.location, action); |
| 309 |
let (view, doc) = current!(cx.editor); |
| 310 |
view.diagnostics_handler |
| 311 |
.immediately_show_diagnostic(doc, view.id); |
| 312 |
}, |
| 313 |
) |
| 314 |
.with_preview(move |_editor, diag| location_to_file_location(&diag.location)) |
| 315 |
.truncate_start(false) |
| 316 |
} |
| 317 |
|
| 318 |
pub fn symbol_picker(cx: &mut Context) { |
| 319 |
fn nested_to_flat( |
| 320 |
list: &mut Vec<SymbolInformationItem>, |
| 321 |
file: &lsp::TextDocumentIdentifier, |
| 322 |
uri: &Uri, |
| 323 |
symbol: lsp::DocumentSymbol, |
| 324 |
offset_encoding: OffsetEncoding, |
| 325 |
) { |
| 326 |
#[allow(deprecated)] |
| 327 |
list.push(SymbolInformationItem { |
| 328 |
symbol: lsp::SymbolInformation { |
| 329 |
name: symbol.name, |
| 330 |
kind: symbol.kind, |
| 331 |
tags: symbol.tags, |
| 332 |
deprecated: symbol.deprecated, |
| 333 |
location: lsp::Location::new(file.uri.clone(), symbol.selection_range), |
| 334 |
container_name: None, |
| 335 |
}, |
| 336 |
location: Location { |
| 337 |
uri: uri.clone(), |
| 338 |
range: symbol.selection_range, |
| 339 |
offset_encoding, |
| 340 |
}, |
| 341 |
}); |
| 342 |
for child in symbol.children.into_iter().flatten() { |
| 343 |
nested_to_flat(list, file, uri, child, offset_encoding); |
| 344 |
} |
| 345 |
} |
| 346 |
let doc = doc!(cx.editor); |
| 347 |
|
| 348 |
let mut seen_language_servers = HashSet::new(); |
| 349 |
|
| 350 |
let mut futures: FuturesUnordered<_> = doc |
| 351 |
.language_servers_with_feature(LanguageServerFeature::DocumentSymbols) |
| 352 |
.filter(|ls| seen_language_servers.insert(ls.id())) |
| 353 |
.map(|language_server| { |
| 354 |
let request = language_server.document_symbols(doc.identifier()).unwrap(); |
| 355 |
let offset_encoding = language_server.offset_encoding(); |
| 356 |
let doc_id = doc.identifier(); |
| 357 |
let doc_uri = doc |
| 358 |
.uri() |
| 359 |
.expect("docs with active language servers must be backed by paths"); |
| 360 |
|
| 361 |
async move { |
| 362 |
let symbols = match request.await? { |
| 363 |
Some(symbols) => symbols, |
| 364 |
None => return anyhow::Ok(vec![]), |
| 365 |
}; |
| 366 |
|
| 367 |
|
| 368 |
let symbols = match symbols { |
| 369 |
lsp::DocumentSymbolResponse::Flat(symbols) => symbols |
| 370 |
.into_iter() |
| 371 |
.map(|symbol| SymbolInformationItem { |
| 372 |
location: Location { |
| 373 |
uri: doc_uri.clone(), |
| 374 |
range: symbol.location.range, |
| 375 |
offset_encoding, |
| 376 |
}, |
| 377 |
symbol, |
| 378 |
}) |
| 379 |
.collect(), |
| 380 |
lsp::DocumentSymbolResponse::Nested(symbols) => { |
| 381 |
let mut flat_symbols = Vec::new(); |
| 382 |
for symbol in symbols { |
| 383 |
nested_to_flat( |
| 384 |
&mut flat_symbols, |
| 385 |
&doc_id, |
| 386 |
&doc_uri, |
| 387 |
symbol, |
| 388 |
offset_encoding, |
| 389 |
) |
| 390 |
} |
| 391 |
flat_symbols |
| 392 |
} |
| 393 |
}; |
| 394 |
Ok(symbols) |
| 395 |
} |
| 396 |
}) |
| 397 |
.collect(); |
| 398 |
|
| 399 |
if futures.is_empty() { |
| 400 |
cx.editor |
| 401 |
.set_error("No configured language server supports document symbols"); |
| 402 |
return; |
| 403 |
} |
| 404 |
|
| 405 |
cx.jobs.callback(async move { |
| 406 |
let mut symbols = Vec::new(); |
| 407 |
while let Some(response) = futures.next().await { |
| 408 |
match response { |
| 409 |
Ok(mut items) => symbols.append(&mut items), |
| 410 |
Err(err) => log::error!("Error requesting document symbols: {err}"), |
| 411 |
} |
| 412 |
} |
| 413 |
let call = move |_editor: &mut Editor, compositor: &mut Compositor| { |
| 414 |
let columns = [ |
| 415 |
ui::PickerColumn::new("kind", |item: &SymbolInformationItem, _| { |
| 416 |
display_symbol_kind(item.symbol.kind).into() |
| 417 |
}), |
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
ui::PickerColumn::new("name", |item: &SymbolInformationItem, _| { |
| 422 |
item.symbol.name.as_str().into() |
| 423 |
}), |
| 424 |
ui::PickerColumn::new("container", |item: &SymbolInformationItem, _| { |
| 425 |
item.symbol |
| 426 |
.container_name |
| 427 |
.as_deref() |
| 428 |
.unwrap_or_default() |
| 429 |
.into() |
| 430 |
}), |
| 431 |
]; |
| 432 |
|
| 433 |
let picker = Picker::new( |
| 434 |
columns, |
| 435 |
1, |
| 436 |
symbols, |
| 437 |
(), |
| 438 |
move |cx, item, action| { |
| 439 |
jump_to_location(cx.editor, &item.location, action); |
| 440 |
}, |
| 441 |
) |
| 442 |
.with_preview(move |_editor, item| location_to_file_location(&item.location)) |
| 443 |
.truncate_start(false); |
| 444 |
|
| 445 |
compositor.push(Box::new(overlaid(picker))) |
| 446 |
}; |
| 447 |
|
| 448 |
Ok(Callback::EditorCompositor(Box::new(call))) |
| 449 |
}); |
| 450 |
} |
| 451 |
|
| 452 |
pub fn workspace_symbol_picker(cx: &mut Context) { |
| 453 |
use crate::ui::picker::Injector; |
| 454 |
|
| 455 |
let doc = doc!(cx.editor); |
| 456 |
if doc |
| 457 |
.language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols) |
| 458 |
.count() |
| 459 |
== 0 |
| 460 |
{ |
| 461 |
cx.editor |
| 462 |
.set_error("No configured language server supports workspace symbols"); |
| 463 |
return; |
| 464 |
} |
| 465 |
|
| 466 |
let get_symbols = |pattern: &str, editor: &mut Editor, _data, injector: &Injector<_, _>| { |
| 467 |
let doc = doc!(editor); |
| 468 |
let mut seen_language_servers = HashSet::new(); |
| 469 |
let mut futures: FuturesUnordered<_> = doc |
| 470 |
.language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols) |
| 471 |
.filter(|ls| seen_language_servers.insert(ls.id())) |
| 472 |
.map(|language_server| { |
| 473 |
let request = language_server |
| 474 |
.workspace_symbols(pattern.to_string()) |
| 475 |
.unwrap(); |
| 476 |
let offset_encoding = language_server.offset_encoding(); |
| 477 |
async move { |
| 478 |
let symbols = request |
| 479 |
.await? |
| 480 |
.and_then(|resp| match resp { |
| 481 |
lsp::WorkspaceSymbolResponse::Flat(symbols) => Some(symbols), |
| 482 |
lsp::WorkspaceSymbolResponse::Nested(_) => None, |
| 483 |
}) |
| 484 |
.unwrap_or_default(); |
| 485 |
|
| 486 |
let response: Vec<_> = symbols |
| 487 |
.into_iter() |
| 488 |
.filter_map(|symbol| { |
| 489 |
let uri = match Uri::try_from(&symbol.location.uri) { |
| 490 |
Ok(uri) => uri, |
| 491 |
Err(err) => { |
| 492 |
log::warn!("discarding symbol with invalid URI: {err}"); |
| 493 |
return None; |
| 494 |
} |
| 495 |
}; |
| 496 |
Some(SymbolInformationItem { |
| 497 |
location: Location { |
| 498 |
uri, |
| 499 |
range: symbol.location.range, |
| 500 |
offset_encoding, |
| 501 |
}, |
| 502 |
symbol, |
| 503 |
}) |
| 504 |
}) |
| 505 |
.collect(); |
| 506 |
|
| 507 |
anyhow::Ok(response) |
| 508 |
} |
| 509 |
}) |
| 510 |
.collect(); |
| 511 |
|
| 512 |
if futures.is_empty() { |
| 513 |
editor.set_error("No configured language server supports workspace symbols"); |
| 514 |
} |
| 515 |
|
| 516 |
let injector = injector.clone(); |
| 517 |
async move { |
| 518 |
while let Some(response) = futures.next().await { |
| 519 |
match response { |
| 520 |
Ok(items) => { |
| 521 |
for item in items { |
| 522 |
injector.push(item)?; |
| 523 |
} |
| 524 |
} |
| 525 |
Err(err) => log::error!("Error requesting workspace symbols: {err}"), |
| 526 |
} |
| 527 |
} |
| 528 |
Ok(()) |
| 529 |
} |
| 530 |
.boxed() |
| 531 |
}; |
| 532 |
let columns = [ |
| 533 |
ui::PickerColumn::new("kind", |item: &SymbolInformationItem, _| { |
| 534 |
display_symbol_kind(item.symbol.kind).into() |
| 535 |
}), |
| 536 |
ui::PickerColumn::new("name", |item: &SymbolInformationItem, _| { |
| 537 |
item.symbol.name.as_str().into() |
| 538 |
}) |
| 539 |
.without_filtering(), |
| 540 |
ui::PickerColumn::new("container", |item: &SymbolInformationItem, _| { |
| 541 |
item.symbol |
| 542 |
.container_name |
| 543 |
.as_deref() |
| 544 |
.unwrap_or_default() |
| 545 |
.into() |
| 546 |
}), |
| 547 |
ui::PickerColumn::new("path", |item: &SymbolInformationItem, _| { |
| 548 |
if let Some(path) = item.location.uri.as_path() { |
| 549 |
path::get_relative_path(path) |
| 550 |
.to_string_lossy() |
| 551 |
.to_string() |
| 552 |
.into() |
| 553 |
} else { |
| 554 |
item.symbol.location.uri.to_string().into() |
| 555 |
} |
| 556 |
}), |
| 557 |
]; |
| 558 |
|
| 559 |
let picker = Picker::new( |
| 560 |
columns, |
| 561 |
1, |
| 562 |
[], |
| 563 |
(), |
| 564 |
move |cx, item, action| { |
| 565 |
jump_to_location(cx.editor, &item.location, action); |
| 566 |
}, |
| 567 |
) |
| 568 |
.with_preview(|_editor, item| location_to_file_location(&item.location)) |
| 569 |
.with_dynamic_query(get_symbols, None) |
| 570 |
.truncate_start(false); |
| 571 |
|
| 572 |
cx.push_layer(Box::new(overlaid(picker))); |
| 573 |
} |
| 574 |
|
| 575 |
pub fn diagnostics_picker(cx: &mut Context) { |
| 576 |
let doc = doc!(cx.editor); |
| 577 |
if let Some(uri) = doc.uri() { |
| 578 |
let diagnostics = cx.editor.diagnostics.get(&uri).cloned().unwrap_or_default(); |
| 579 |
let picker = diag_picker(cx, [(uri, diagnostics)], DiagnosticsFormat::HideSourcePath); |
| 580 |
cx.push_layer(Box::new(overlaid(picker))); |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
pub fn workspace_diagnostics_picker(cx: &mut Context) { |
| 585 |
|
| 586 |
let diagnostics = cx.editor.diagnostics.clone(); |
| 587 |
let picker = diag_picker(cx, diagnostics, DiagnosticsFormat::ShowSourcePath); |
| 588 |
cx.push_layer(Box::new(overlaid(picker))); |
| 589 |
} |
| 590 |
|
| 591 |
impl ui::menu::Item for CodeActionItem { |
| 592 |
type Data = (); |
| 593 |
fn format(&self, _data: &Self::Data) -> Row<'_> { |
| 594 |
self.title().into() |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
pub fn code_action(cx: &mut Context) { |
| 599 |
let (view, doc) = current!(cx.editor); |
| 600 |
|
| 601 |
let selection_range = doc.selection(view.id).primary(); |
| 602 |
|
| 603 |
let mut futures: FuturesUnordered<_> = |
| 604 |
code_actions_for_range(doc, selection_range, None, CodeActionTriggerKind::INVOKED) |
| 605 |
.into_iter() |
| 606 |
.map(|(request, ls_id)| async move { |
| 607 |
let Some(mut actions) = request.await? else { |
| 608 |
return anyhow::Ok(Vec::new()); |
| 609 |
}; |
| 610 |
|
| 611 |
|
| 612 |
actions.retain(|action| { |
| 613 |
matches!( |
| 614 |
action, |
| 615 |
CodeActionOrCommand::Command(_) |
| 616 |
| CodeActionOrCommand::CodeAction(CodeAction { disabled: None, .. }) |
| 617 |
) |
| 618 |
}); |
| 619 |
|
| 620 |
Ok(actions |
| 621 |
.into_iter() |
| 622 |
.map(|lsp_item| CodeActionItem::lsp(ls_id, lsp_item)) |
| 623 |
.collect()) |
| 624 |
}) |
| 625 |
.collect(); |
| 626 |
|
| 627 |
if futures.is_empty() { |
| 628 |
cx.editor |
| 629 |
.set_error("No configured language server supports code actions"); |
| 630 |
return; |
| 631 |
} |
| 632 |
|
| 633 |
cx.jobs.callback(async move { |
| 634 |
let mut actions = Vec::new(); |
| 635 |
|
| 636 |
while let Some(output) = futures.next().await { |
| 637 |
match output { |
| 638 |
Ok(mut items) => actions.append(&mut items), |
| 639 |
Err(err) => log::error!("while gathering code actions: {err}"), |
| 640 |
} |
| 641 |
} |
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
actions.sort_by_key(|action| std::cmp::Reverse(action.priority)); |
| 646 |
|
| 647 |
let call = move |editor: &mut Editor, compositor: &mut Compositor| { |
| 648 |
if actions.is_empty() { |
| 649 |
editor.set_error("No code actions available"); |
| 650 |
return; |
| 651 |
} |
| 652 |
let mut picker = ui::Menu::new(actions, (), move |editor, action, event| { |
| 653 |
if event != PromptEvent::Validate { |
| 654 |
return; |
| 655 |
} |
| 656 |
|
| 657 |
action.unwrap().execute(editor); |
| 658 |
}); |
| 659 |
picker.move_down(); |
| 660 |
|
| 661 |
let popup = Popup::new("code-action", picker) |
| 662 |
.with_scrollbar(false) |
| 663 |
.auto_close(true); |
| 664 |
|
| 665 |
compositor.replace_or_push("code-action", popup); |
| 666 |
}; |
| 667 |
|
| 668 |
Ok(Callback::EditorCompositor(Box::new(call))) |
| 669 |
}); |
| 670 |
} |
| 671 |
|
| 672 |
|
| 673 |
#[allow(clippy::type_complexity)] |
| 674 |
pub(crate) fn code_actions_for_range( |
| 675 |
doc: &Document, |
| 676 |
range: helix_core::Range, |
| 677 |
only: Option<Vec<CodeActionKind>>, |
| 678 |
trigger_kind: CodeActionTriggerKind, |
| 679 |
) -> Vec<( |
| 680 |
impl Future<Output = Result<Option<Vec<CodeActionOrCommand>>, helix_lsp::Error>>, |
| 681 |
LanguageServerId, |
| 682 |
)> { |
| 683 |
let mut seen_language_servers = HashSet::new(); |
| 684 |
|
| 685 |
doc.language_servers_with_feature(LanguageServerFeature::CodeAction) |
| 686 |
.filter(|ls| seen_language_servers.insert(ls.id())) |
| 687 |
|
| 688 |
.filter_map(|language_server| { |
| 689 |
let offset_encoding = language_server.offset_encoding(); |
| 690 |
let language_server_id = language_server.id(); |
| 691 |
let lsp_range = range_to_lsp_range(doc.text(), range, offset_encoding); |
| 692 |
|
| 693 |
let code_action_context = lsp::CodeActionContext { |
| 694 |
diagnostics: doc |
| 695 |
.diagnostics() |
| 696 |
.iter() |
| 697 |
.filter(|&diag| { |
| 698 |
range.overlaps(&helix_core::Range::new(diag.range.start, diag.range.end)) |
| 699 |
}) |
| 700 |
.map(|diag| diagnostic_to_lsp_diagnostic(doc.text(), diag, offset_encoding)) |
| 701 |
.collect(), |
| 702 |
only: only.clone(), |
| 703 |
trigger_kind: Some(trigger_kind), |
| 704 |
}; |
| 705 |
let code_action_request = |
| 706 |
language_server.code_actions(doc.identifier(), lsp_range, code_action_context)?; |
| 707 |
Some((code_action_request, language_server_id)) |
| 708 |
}) |
| 709 |
.collect::<Vec<_>>() |
| 710 |
} |
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
pub fn code_actions_on_save( |
| 717 |
cx: &compositor::Context, |
| 718 |
doc_id: DocumentId, |
| 719 |
tail: Option<Job>, |
| 720 |
) -> Option<Job> { |
| 721 |
let kinds = doc!(cx.editor, &doc_id) |
| 722 |
.language_config() |
| 723 |
.and_then(|config| config.code_actions_on_save.clone()); |
| 724 |
let Some(kinds) = kinds else { |
| 725 |
return tail; |
| 726 |
}; |
| 727 |
let kinds: VecDeque<CodeActionKind> = kinds.into_iter().map(CodeActionKind::from).collect(); |
| 728 |
code_action_on_save_step(doc_id, kinds, tail) |
| 729 |
} |
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
fn code_action_on_save_step( |
| 736 |
doc_id: DocumentId, |
| 737 |
mut kinds: VecDeque<CodeActionKind>, |
| 738 |
tail: Option<Job>, |
| 739 |
) -> Option<Job> { |
| 740 |
let Some(kind) = kinds.pop_front() else { |
| 741 |
|
| 742 |
return tail; |
| 743 |
}; |
| 744 |
|
| 745 |
let build_request = move |editor: &mut Editor| -> Option<Job> { |
| 746 |
|
| 747 |
if !editor.documents.contains_key(&doc_id) { |
| 748 |
return None; |
| 749 |
} |
| 750 |
let doc = doc!(editor, &doc_id); |
| 751 |
let version = doc.version(); |
| 752 |
let full_range = helix_core::Range::new(0, doc.text().len_chars()); |
| 753 |
let Some((request, ls_id)) = code_actions_for_range( |
| 754 |
doc, |
| 755 |
full_range, |
| 756 |
Some(vec![kind.clone()]), |
| 757 |
CodeActionTriggerKind::INVOKED, |
| 758 |
) |
| 759 |
.into_iter() |
| 760 |
.next() else { |
| 761 |
|
| 762 |
return code_action_on_save_step(doc_id, kinds, tail); |
| 763 |
}; |
| 764 |
|
| 765 |
let future = async move { |
| 766 |
let actions = request.await?; |
| 767 |
let resolve = move |editor: &mut Editor| -> Option<Job> { |
| 768 |
resolve_and_apply_code_actions_of_kind( |
| 769 |
editor, doc_id, version, ls_id, kind, kinds, tail, actions, |
| 770 |
) |
| 771 |
}; |
| 772 |
Ok(Callback::Followup(Box::new(resolve))) |
| 773 |
}; |
| 774 |
Some(Job::with_callback(future).wait_before_exiting()) |
| 775 |
}; |
| 776 |
|
| 777 |
Some( |
| 778 |
Job::with_callback(async move { Ok(Callback::Followup(Box::new(build_request))) }) |
| 779 |
.wait_before_exiting(), |
| 780 |
) |
| 781 |
} |
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
fn code_action_kind_matches(action: &CodeAction, requested: &CodeActionKind) -> bool { |
| 788 |
action.kind.as_ref().is_some_and(|kind| { |
| 789 |
let (kind, requested) = (kind.as_str(), requested.as_str()); |
| 790 |
kind == requested |
| 791 |
|| (kind.starts_with(requested) && kind[requested.len()..].starts_with('.')) |
| 792 |
}) |
| 793 |
} |
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
type ResolveFuture = |
| 801 |
std::pin::Pin<Box<dyn Future<Output = Result<lsp::CodeAction, helix_lsp::Error>> + Send>>; |
| 802 |
enum ResolveStep { |
| 803 |
Ready(lsp::WorkspaceEdit), |
| 804 |
Resolve(ResolveFuture), |
| 805 |
} |
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
#[allow(clippy::too_many_arguments)] |
| 810 |
fn resolve_and_apply_code_actions_of_kind( |
| 811 |
editor: &mut Editor, |
| 812 |
doc_id: DocumentId, |
| 813 |
version: i32, |
| 814 |
ls_id: LanguageServerId, |
| 815 |
kind: CodeActionKind, |
| 816 |
kinds: VecDeque<CodeActionKind>, |
| 817 |
tail: Option<Job>, |
| 818 |
actions: Option<Vec<CodeActionOrCommand>>, |
| 819 |
) -> Option<Job> { |
| 820 |
|
| 821 |
|
| 822 |
let prepared = (|| -> Option<(OffsetEncoding, Vec<ResolveStep>)> { |
| 823 |
let actions = actions?; |
| 824 |
if editor.documents.get(&doc_id)?.version() != version { |
| 825 |
log::debug!("code-actions-on-save: document changed, skipping {kind:?}"); |
| 826 |
return None; |
| 827 |
} |
| 828 |
let ls = editor.language_server_by_id(ls_id)?; |
| 829 |
let steps = actions |
| 830 |
.iter() |
| 831 |
.filter_map(|action| match action { |
| 832 |
CodeActionOrCommand::CodeAction(ca) if ca.disabled.is_none() => Some(ca), |
| 833 |
_ => None, |
| 834 |
}) |
| 835 |
.filter(|ca| code_action_kind_matches(ca, &kind)) |
| 836 |
.filter_map(|ca| { |
| 837 |
|
| 838 |
if ca.edit.is_none() || ca.command.is_none() { |
| 839 |
if let Some(future) = ls.resolve_code_action(ca) { |
| 840 |
return Some(ResolveStep::Resolve(Box::pin(future))); |
| 841 |
} |
| 842 |
} |
| 843 |
ca.edit.clone().map(ResolveStep::Ready) |
| 844 |
}) |
| 845 |
.collect(); |
| 846 |
Some((ls.offset_encoding(), steps)) |
| 847 |
})(); |
| 848 |
let Some((offset_encoding, steps)) = prepared else { |
| 849 |
return code_action_on_save_step(doc_id, kinds, tail); |
| 850 |
}; |
| 851 |
|
| 852 |
let future = async move { |
| 853 |
let mut edits = Vec::new(); |
| 854 |
for step in steps { |
| 855 |
match step { |
| 856 |
ResolveStep::Ready(edit) => edits.push(edit), |
| 857 |
ResolveStep::Resolve(future) => match future.await { |
| 858 |
Ok(resolved) => edits.extend(resolved.edit), |
| 859 |
Err(err) => log::error!("code-actions-on-save: resolve failed: {err:?}"), |
| 860 |
}, |
| 861 |
} |
| 862 |
} |
| 863 |
let apply = move |editor: &mut Editor| -> Option<Job> { |
| 864 |
|
| 865 |
|
| 866 |
|
| 867 |
if editor |
| 868 |
.documents |
| 869 |
.get(&doc_id) |
| 870 |
.is_some_and(|doc| doc.version() == version) |
| 871 |
{ |
| 872 |
for edit in &edits { |
| 873 |
if let Err(err) = editor.apply_workspace_edit(offset_encoding, edit) { |
| 874 |
log::error!("code-actions-on-save: failed to apply edit: {err:?}"); |
| 875 |
} |
| 876 |
} |
| 877 |
} else { |
| 878 |
log::debug!("code-actions-on-save: document changed, skipping {kind:?}"); |
| 879 |
} |
| 880 |
code_action_on_save_step(doc_id, kinds, tail) |
| 881 |
}; |
| 882 |
Ok(Callback::Followup(Box::new(apply))) |
| 883 |
}; |
| 884 |
Some(Job::with_callback(future).wait_before_exiting()) |
| 885 |
} |
| 886 |
|
| 887 |
#[derive(Debug)] |
| 888 |
pub struct ApplyEditError { |
| 889 |
pub kind: ApplyEditErrorKind, |
| 890 |
pub failed_change_idx: usize, |
| 891 |
} |
| 892 |
|
| 893 |
#[derive(Debug)] |
| 894 |
pub enum ApplyEditErrorKind { |
| 895 |
DocumentChanged, |
| 896 |
FileNotFound, |
| 897 |
UnknownURISchema, |
| 898 |
IoError(std::io::Error), |
| 899 |
|
| 900 |
|
| 901 |
} |
| 902 |
|
| 903 |
impl Display for ApplyEditErrorKind { |
| 904 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 905 |
match self { |
| 906 |
ApplyEditErrorKind::DocumentChanged => f.write_str("document has changed"), |
| 907 |
ApplyEditErrorKind::FileNotFound => f.write_str("file not found"), |
| 908 |
ApplyEditErrorKind::UnknownURISchema => f.write_str("URI schema not supported"), |
| 909 |
ApplyEditErrorKind::IoError(err) => f.write_str(&format!("{err}")), |
| 910 |
} |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
|
| 915 |
fn goto_impl(editor: &mut Editor, compositor: &mut Compositor, locations: Vec<Location>) { |
| 916 |
let cwdir = helix_stdx::env::current_working_dir(); |
| 917 |
|
| 918 |
match locations.as_slice() { |
| 919 |
[location] => { |
| 920 |
jump_to_location(editor, location, Action::Replace); |
| 921 |
} |
| 922 |
[] => unreachable!("`locations` should be non-empty for `goto_impl`"), |
| 923 |
_locations => { |
| 924 |
let columns = [ui::PickerColumn::new( |
| 925 |
"location", |
| 926 |
|item: &Location, cwdir: &std::path::PathBuf| { |
| 927 |
let path = if let Some(path) = item.uri.as_path() { |
| 928 |
path.strip_prefix(cwdir).unwrap_or(path).to_string_lossy() |
| 929 |
} else { |
| 930 |
item.uri.to_string().into() |
| 931 |
}; |
| 932 |
|
| 933 |
format!("{path}:{}", item.range.start.line + 1).into() |
| 934 |
}, |
| 935 |
)]; |
| 936 |
|
| 937 |
let picker = Picker::new(columns, 0, locations, cwdir, |cx, location, action| { |
| 938 |
jump_to_location(cx.editor, location, action) |
| 939 |
}) |
| 940 |
.with_preview(|_editor, location| location_to_file_location(location)); |
| 941 |
compositor.push(Box::new(overlaid(picker))); |
| 942 |
} |
| 943 |
} |
| 944 |
} |
| 945 |
|
| 946 |
fn goto_single_impl<P, F>(cx: &mut Context, feature: LanguageServerFeature, request_provider: P) |
| 947 |
where |
| 948 |
P: Fn(&Client, lsp::Position, lsp::TextDocumentIdentifier) -> Option<F>, |
| 949 |
F: Future<Output = helix_lsp::Result<Option<lsp::GotoDefinitionResponse>>> + 'static + Send, |
| 950 |
{ |
| 951 |
let (view, doc) = current_ref!(cx.editor); |
| 952 |
let mut futures: FuturesUnordered<_> = doc |
| 953 |
.language_servers_with_feature(feature) |
| 954 |
.map(|language_server| { |
| 955 |
let offset_encoding = language_server.offset_encoding(); |
| 956 |
let pos = doc.position(view.id, offset_encoding); |
| 957 |
let future = request_provider(language_server, pos, doc.identifier()).unwrap(); |
| 958 |
async move { anyhow::Ok((future.await?, offset_encoding)) } |
| 959 |
}) |
| 960 |
.collect(); |
| 961 |
|
| 962 |
cx.jobs.callback(async move { |
| 963 |
let mut locations = Vec::new(); |
| 964 |
while let Some(response) = futures.next().await { |
| 965 |
match response { |
| 966 |
Ok((response, offset_encoding)) => match response { |
| 967 |
Some(lsp::GotoDefinitionResponse::Scalar(lsp_location)) => { |
| 968 |
locations.extend(lsp_location_to_location(lsp_location, offset_encoding)); |
| 969 |
} |
| 970 |
Some(lsp::GotoDefinitionResponse::Array(lsp_locations)) => { |
| 971 |
locations.extend(lsp_locations.into_iter().flat_map(|location| { |
| 972 |
lsp_location_to_location(location, offset_encoding) |
| 973 |
})); |
| 974 |
} |
| 975 |
Some(lsp::GotoDefinitionResponse::Link(lsp_locations)) => { |
| 976 |
locations.extend( |
| 977 |
lsp_locations |
| 978 |
.into_iter() |
| 979 |
.map(|location_link| { |
| 980 |
lsp::Location::new( |
| 981 |
location_link.target_uri, |
| 982 |
location_link.target_range, |
| 983 |
) |
| 984 |
}) |
| 985 |
.flat_map(|location| { |
| 986 |
lsp_location_to_location(location, offset_encoding) |
| 987 |
}), |
| 988 |
); |
| 989 |
} |
| 990 |
None => (), |
| 991 |
}, |
| 992 |
Err(err) => log::error!("Error requesting locations: {err}"), |
| 993 |
} |
| 994 |
} |
| 995 |
let call = move |editor: &mut Editor, compositor: &mut Compositor| { |
| 996 |
if locations.is_empty() { |
| 997 |
editor.set_error(match feature { |
| 998 |
LanguageServerFeature::GotoDeclaration => "No declaration found.", |
| 999 |
LanguageServerFeature::GotoDefinition => "No definition found.", |
| 1000 |
LanguageServerFeature::GotoTypeDefinition => "No type definition found.", |
| 1001 |
LanguageServerFeature::GotoImplementation => "No implementation found.", |
| 1002 |
_ => "No location found.", |
| 1003 |
}); |
| 1004 |
} else { |
| 1005 |
goto_impl(editor, compositor, locations); |
| 1006 |
} |
| 1007 |
}; |
| 1008 |
Ok(Callback::EditorCompositor(Box::new(call))) |
| 1009 |
}); |
| 1010 |
} |
| 1011 |
|
| 1012 |
pub fn goto_declaration(cx: &mut Context) { |
| 1013 |
goto_single_impl( |
| 1014 |
cx, |
| 1015 |
LanguageServerFeature::GotoDeclaration, |
| 1016 |
|ls, pos, doc_id| ls.goto_declaration(doc_id, pos, None), |
| 1017 |
); |
| 1018 |
} |
| 1019 |
|
| 1020 |
pub fn goto_definition(cx: &mut Context) { |
| 1021 |
goto_single_impl( |
| 1022 |
cx, |
| 1023 |
LanguageServerFeature::GotoDefinition, |
| 1024 |
|ls, pos, doc_id| ls.goto_definition(doc_id, pos, None), |
| 1025 |
); |
| 1026 |
} |
| 1027 |
|
| 1028 |
pub fn goto_type_definition(cx: &mut Context) { |
| 1029 |
goto_single_impl( |
| 1030 |
cx, |
| 1031 |
LanguageServerFeature::GotoTypeDefinition, |
| 1032 |
|ls, pos, doc_id| ls.goto_type_definition(doc_id, pos, None), |
| 1033 |
); |
| 1034 |
} |
| 1035 |
|
| 1036 |
pub fn goto_implementation(cx: &mut Context) { |
| 1037 |
goto_single_impl( |
| 1038 |
cx, |
| 1039 |
LanguageServerFeature::GotoImplementation, |
| 1040 |
|ls, pos, doc_id| ls.goto_implementation(doc_id, pos, None), |
| 1041 |
); |
| 1042 |
} |
| 1043 |
|
| 1044 |
pub fn goto_reference(cx: &mut Context) { |
| 1045 |
let config = cx.editor.config(); |
| 1046 |
let (view, doc) = current_ref!(cx.editor); |
| 1047 |
|
| 1048 |
let mut futures: FuturesUnordered<_> = doc |
| 1049 |
.language_servers_with_feature(LanguageServerFeature::GotoReference) |
| 1050 |
.map(|language_server| { |
| 1051 |
let offset_encoding = language_server.offset_encoding(); |
| 1052 |
let pos = doc.position(view.id, offset_encoding); |
| 1053 |
let future = language_server |
| 1054 |
.goto_reference( |
| 1055 |
doc.identifier(), |
| 1056 |
pos, |
| 1057 |
config.lsp.goto_reference_include_declaration, |
| 1058 |
None, |
| 1059 |
) |
| 1060 |
.unwrap(); |
| 1061 |
async move { anyhow::Ok((future.await?, offset_encoding)) } |
| 1062 |
}) |
| 1063 |
.collect(); |
| 1064 |
|
| 1065 |
cx.jobs.callback(async move { |
| 1066 |
let mut locations = Vec::new(); |
| 1067 |
while let Some(response) = futures.next().await { |
| 1068 |
match response { |
| 1069 |
Ok((lsp_locations, offset_encoding)) => locations.extend( |
| 1070 |
lsp_locations |
| 1071 |
.into_iter() |
| 1072 |
.flatten() |
| 1073 |
.flat_map(|location| lsp_location_to_location(location, offset_encoding)), |
| 1074 |
), |
| 1075 |
Err(err) => log::error!("Error requesting references: {err}"), |
| 1076 |
} |
| 1077 |
} |
| 1078 |
let call = move |editor: &mut Editor, compositor: &mut Compositor| { |
| 1079 |
if locations.is_empty() { |
| 1080 |
editor.set_error("No references found."); |
| 1081 |
} else { |
| 1082 |
goto_impl(editor, compositor, locations); |
| 1083 |
} |
| 1084 |
}; |
| 1085 |
Ok(Callback::EditorCompositor(Box::new(call))) |
| 1086 |
}); |
| 1087 |
} |
| 1088 |
|
| 1089 |
pub fn signature_help(cx: &mut Context) { |
| 1090 |
cx.editor |
| 1091 |
.handlers |
| 1092 |
.trigger_signature_help(SignatureHelpInvoked::Manual, cx.editor) |
| 1093 |
} |
| 1094 |
|
| 1095 |
pub fn hover(cx: &mut Context) { |
| 1096 |
use ui::lsp::hover::Hover; |
| 1097 |
|
| 1098 |
let (view, doc) = current!(cx.editor); |
| 1099 |
if doc |
| 1100 |
.language_servers_with_feature(LanguageServerFeature::Hover) |
| 1101 |
.count() |
| 1102 |
== 0 |
| 1103 |
{ |
| 1104 |
cx.editor |
| 1105 |
.set_error("No configured language server supports hover"); |
| 1106 |
return; |
| 1107 |
} |
| 1108 |
|
| 1109 |
let mut seen_language_servers = HashSet::new(); |
| 1110 |
let mut futures: FuturesUnordered<_> = doc |
| 1111 |
.language_servers_with_feature(LanguageServerFeature::Hover) |
| 1112 |
.filter(|ls| seen_language_servers.insert(ls.id())) |
| 1113 |
.map(|language_server| { |
| 1114 |
let server_name = language_server.name().to_string(); |
| 1115 |
|
| 1116 |
let pos = doc.position(view.id, language_server.offset_encoding()); |
| 1117 |
let request = language_server |
| 1118 |
.text_document_hover(doc.identifier(), pos, None) |
| 1119 |
.unwrap(); |
| 1120 |
|
| 1121 |
async move { anyhow::Ok((server_name, request.await?)) } |
| 1122 |
}) |
| 1123 |
.collect(); |
| 1124 |
|
| 1125 |
cx.jobs.callback(async move { |
| 1126 |
let mut hovers: Vec<(String, lsp::Hover)> = Vec::new(); |
| 1127 |
|
| 1128 |
while let Some(response) = futures.next().await { |
| 1129 |
match response { |
| 1130 |
Ok((server_name, Some(hover))) => hovers.push((server_name, hover)), |
| 1131 |
Ok(_) => (), |
| 1132 |
Err(err) => log::error!("Error requesting hover: {err}"), |
| 1133 |
} |
| 1134 |
} |
| 1135 |
|
| 1136 |
let call = move |editor: &mut Editor, compositor: &mut Compositor| { |
| 1137 |
if hovers.is_empty() { |
| 1138 |
editor.set_status("No hover results available."); |
| 1139 |
return; |
| 1140 |
} |
| 1141 |
|
| 1142 |
|
| 1143 |
let contents = Hover::new(hovers, editor.syn_loader.clone()); |
| 1144 |
let popup = Popup::new(Hover::ID, contents).auto_close(true); |
| 1145 |
compositor.replace_or_push(Hover::ID, popup); |
| 1146 |
}; |
| 1147 |
Ok(Callback::EditorCompositor(Box::new(call))) |
| 1148 |
}); |
| 1149 |
} |
| 1150 |
|
| 1151 |
pub fn rename_symbol(cx: &mut Context) { |
| 1152 |
fn get_prefill_from_word_boundary(editor: &Editor) -> String { |
| 1153 |
let (view, doc) = current_ref!(editor); |
| 1154 |
let text = doc.text().slice(..); |
| 1155 |
let primary_selection = doc.selection(view.id).primary(); |
| 1156 |
if primary_selection.len() > 1 { |
| 1157 |
primary_selection |
| 1158 |
} else { |
| 1159 |
use helix_core::textobject::{textobject_word, TextObject}; |
| 1160 |
textobject_word(text, primary_selection, TextObject::Inside, 1, false) |
| 1161 |
} |
| 1162 |
.fragment(text) |
| 1163 |
.into() |
| 1164 |
} |
| 1165 |
|
| 1166 |
fn get_prefill_from_lsp_response( |
| 1167 |
editor: &Editor, |
| 1168 |
offset_encoding: OffsetEncoding, |
| 1169 |
response: Option<lsp::PrepareRenameResponse>, |
| 1170 |
) -> Result<String, &'static str> { |
| 1171 |
match response { |
| 1172 |
Some(lsp::PrepareRenameResponse::Range(range)) => { |
| 1173 |
let text = doc!(editor).text(); |
| 1174 |
|
| 1175 |
Ok(lsp_range_to_range(text, range, offset_encoding) |
| 1176 |
.ok_or("lsp sent invalid selection range for rename")? |
| 1177 |
.fragment(text.slice(..)) |
| 1178 |
.into()) |
| 1179 |
} |
| 1180 |
Some(lsp::PrepareRenameResponse::RangeWithPlaceholder { placeholder, .. }) => { |
| 1181 |
Ok(placeholder) |
| 1182 |
} |
| 1183 |
Some(lsp::PrepareRenameResponse::DefaultBehavior { .. }) => { |
| 1184 |
Ok(get_prefill_from_word_boundary(editor)) |
| 1185 |
} |
| 1186 |
None => Err("lsp did not respond to prepare rename request"), |
| 1187 |
} |
| 1188 |
} |
| 1189 |
|
| 1190 |
fn create_rename_prompt( |
| 1191 |
editor: &Editor, |
| 1192 |
prefill: String, |
| 1193 |
history_register: Option<char>, |
| 1194 |
language_server_id: Option<LanguageServerId>, |
| 1195 |
) -> Box<ui::Prompt> { |
| 1196 |
let prompt = ui::Prompt::new( |
| 1197 |
"rename-to:".into(), |
| 1198 |
history_register, |
| 1199 |
ui::completers::none, |
| 1200 |
move |cx: &mut compositor::Context, input: &str, event: PromptEvent| { |
| 1201 |
if event != PromptEvent::Validate { |
| 1202 |
return; |
| 1203 |
} |
| 1204 |
let (view, doc) = current!(cx.editor); |
| 1205 |
|
| 1206 |
let Some(language_server) = doc |
| 1207 |
.language_servers_with_feature(LanguageServerFeature::RenameSymbol) |
| 1208 |
.find(|ls| language_server_id.is_none_or(|id| id == ls.id())) |
| 1209 |
else { |
| 1210 |
cx.editor |
| 1211 |
.set_error("No configured language server supports symbol renaming"); |
| 1212 |
return; |
| 1213 |
}; |
| 1214 |
|
| 1215 |
let offset_encoding = language_server.offset_encoding(); |
| 1216 |
let pos = doc.position(view.id, offset_encoding); |
| 1217 |
let future = language_server |
| 1218 |
.rename_symbol(doc.identifier(), pos, input.to_string()) |
| 1219 |
.unwrap(); |
| 1220 |
|
| 1221 |
match block_on(future) { |
| 1222 |
Ok(edits) => { |
| 1223 |
let _ = cx |
| 1224 |
.editor |
| 1225 |
.apply_workspace_edit(offset_encoding, &edits.unwrap_or_default()); |
| 1226 |
} |
| 1227 |
Err(err) => cx.editor.set_error(err.to_string()), |
| 1228 |
} |
| 1229 |
}, |
| 1230 |
) |
| 1231 |
.with_line(prefill, editor); |
| 1232 |
|
| 1233 |
Box::new(prompt) |
| 1234 |
} |
| 1235 |
|
| 1236 |
let (view, doc) = current_ref!(cx.editor); |
| 1237 |
let history_register = cx.register; |
| 1238 |
|
| 1239 |
if doc |
| 1240 |
.language_servers_with_feature(LanguageServerFeature::RenameSymbol) |
| 1241 |
.next() |
| 1242 |
.is_none() |
| 1243 |
{ |
| 1244 |
cx.editor |
| 1245 |
.set_error("No configured language server supports symbol renaming"); |
| 1246 |
return; |
| 1247 |
} |
| 1248 |
|
| 1249 |
let language_server_with_prepare_rename_support = doc |
| 1250 |
.language_servers_with_feature(LanguageServerFeature::RenameSymbol) |
| 1251 |
.find(|ls| { |
| 1252 |
matches!( |
| 1253 |
ls.capabilities().rename_provider, |
| 1254 |
Some(lsp::OneOf::Right(lsp::RenameOptions { |
| 1255 |
prepare_provider: Some(true), |
| 1256 |
.. |
| 1257 |
})) |
| 1258 |
) |
| 1259 |
}); |
| 1260 |
|
| 1261 |
if let Some(language_server) = language_server_with_prepare_rename_support { |
| 1262 |
let ls_id = language_server.id(); |
| 1263 |
let offset_encoding = language_server.offset_encoding(); |
| 1264 |
let pos = doc.position(view.id, offset_encoding); |
| 1265 |
let future = language_server |
| 1266 |
.prepare_rename(doc.identifier(), pos) |
| 1267 |
.unwrap(); |
| 1268 |
cx.callback( |
| 1269 |
future, |
| 1270 |
move |editor, compositor, response: Option<lsp::PrepareRenameResponse>| { |
| 1271 |
let prefill = match get_prefill_from_lsp_response(editor, offset_encoding, response) |
| 1272 |
{ |
| 1273 |
Ok(p) => p, |
| 1274 |
Err(e) => { |
| 1275 |
editor.set_error(e); |
| 1276 |
return; |
| 1277 |
} |
| 1278 |
}; |
| 1279 |
|
| 1280 |
let prompt = create_rename_prompt(editor, prefill, history_register, Some(ls_id)); |
| 1281 |
|
| 1282 |
compositor.push(prompt); |
| 1283 |
}, |
| 1284 |
); |
| 1285 |
} else { |
| 1286 |
let prefill = get_prefill_from_word_boundary(cx.editor); |
| 1287 |
let prompt = create_rename_prompt(cx.editor, prefill, history_register, None); |
| 1288 |
cx.push_layer(prompt); |
| 1289 |
} |
| 1290 |
} |
| 1291 |
|
| 1292 |
pub fn select_references_to_symbol_under_cursor(cx: &mut Context) { |
| 1293 |
let (view, doc) = current!(cx.editor); |
| 1294 |
let language_server = |
| 1295 |
language_server_with_feature!(cx.editor, doc, LanguageServerFeature::DocumentHighlight); |
| 1296 |
let offset_encoding = language_server.offset_encoding(); |
| 1297 |
let pos = doc.position(view.id, offset_encoding); |
| 1298 |
let future = language_server |
| 1299 |
.text_document_document_highlight(doc.identifier(), pos, None) |
| 1300 |
.unwrap(); |
| 1301 |
|
| 1302 |
cx.callback( |
| 1303 |
future, |
| 1304 |
move |editor, _compositor, response: Option<Vec<lsp::DocumentHighlight>>| { |
| 1305 |
let document_highlights = match response { |
| 1306 |
Some(highlights) if !highlights.is_empty() => highlights, |
| 1307 |
_ => return, |
| 1308 |
}; |
| 1309 |
let (view, doc) = current!(editor); |
| 1310 |
let text = doc.text(); |
| 1311 |
let pos = doc.selection(view.id).primary().cursor(text.slice(..)); |
| 1312 |
|
| 1313 |
|
| 1314 |
let mut primary_index = 0; |
| 1315 |
let ranges = document_highlights |
| 1316 |
.iter() |
| 1317 |
.filter_map(|highlight| lsp_range_to_range(text, highlight.range, offset_encoding)) |
| 1318 |
.enumerate() |
| 1319 |
.map(|(i, range)| { |
| 1320 |
if range.contains(pos) { |
| 1321 |
primary_index = i; |
| 1322 |
} |
| 1323 |
range |
| 1324 |
}) |
| 1325 |
.collect(); |
| 1326 |
let selection = Selection::new(ranges, primary_index); |
| 1327 |
doc.set_selection(view.id, selection); |
| 1328 |
}, |
| 1329 |
); |
| 1330 |
} |
| 1331 |
|
| 1332 |
pub fn compute_inlay_hints_for_all_views(editor: &mut Editor, jobs: &mut crate::job::Jobs) { |
| 1333 |
if !editor.config().lsp.display_inlay_hints { |
| 1334 |
return; |
| 1335 |
} |
| 1336 |
|
| 1337 |
for (view, _) in editor.tree.views() { |
| 1338 |
let doc = match editor.documents.get(&view.doc) { |
| 1339 |
Some(doc) => doc, |
| 1340 |
None => continue, |
| 1341 |
}; |
| 1342 |
if let Some(callback) = compute_inlay_hints_for_view(view, doc) { |
| 1343 |
jobs.callback(callback); |
| 1344 |
} |
| 1345 |
} |
| 1346 |
} |
| 1347 |
|
| 1348 |
fn compute_inlay_hints_for_view( |
| 1349 |
view: &View, |
| 1350 |
doc: &Document, |
| 1351 |
) -> Option<std::pin::Pin<Box<impl Future<Output = Result<crate::job::Callback, anyhow::Error>>>>> { |
| 1352 |
let view_id = view.id; |
| 1353 |
let doc_id = view.doc; |
| 1354 |
|
| 1355 |
let language_server = doc |
| 1356 |
.language_servers_with_feature(LanguageServerFeature::InlayHints) |
| 1357 |
.next()?; |
| 1358 |
|
| 1359 |
let doc_text = doc.text(); |
| 1360 |
let len_lines = doc_text.len_lines(); |
| 1361 |
|
| 1362 |
|
| 1363 |
|
| 1364 |
|
| 1365 |
|
| 1366 |
let view_height = view.inner_height(); |
| 1367 |
let first_visible_line = |
| 1368 |
doc_text.char_to_line(doc.view_offset(view_id).anchor.min(doc_text.len_chars())); |
| 1369 |
let first_line = first_visible_line.saturating_sub(view_height); |
| 1370 |
let last_line = first_visible_line |
| 1371 |
.saturating_add(view_height.saturating_mul(2)) |
| 1372 |
.min(len_lines); |
| 1373 |
|
| 1374 |
let new_doc_inlay_hints_id = DocumentInlayHintsId { |
| 1375 |
first_line, |
| 1376 |
last_line, |
| 1377 |
}; |
| 1378 |
|
| 1379 |
if !doc.inlay_hints_oudated |
| 1380 |
&& doc |
| 1381 |
.inlay_hints(view_id) |
| 1382 |
.is_some_and(|dih| dih.id == new_doc_inlay_hints_id) |
| 1383 |
{ |
| 1384 |
return None; |
| 1385 |
} |
| 1386 |
|
| 1387 |
let doc_slice = doc_text.slice(..); |
| 1388 |
let first_char_in_range = doc_slice.line_to_char(first_line); |
| 1389 |
let last_char_in_range = doc_slice.line_to_char(last_line); |
| 1390 |
|
| 1391 |
let range = helix_lsp::util::range_to_lsp_range( |
| 1392 |
doc_text, |
| 1393 |
helix_core::Range::new(first_char_in_range, last_char_in_range), |
| 1394 |
language_server.offset_encoding(), |
| 1395 |
); |
| 1396 |
|
| 1397 |
let offset_encoding = language_server.offset_encoding(); |
| 1398 |
|
| 1399 |
let callback = super::make_job_callback( |
| 1400 |
language_server.text_document_range_inlay_hints(doc.identifier(), range, None)?, |
| 1401 |
move |editor, _compositor, response: Option<Vec<lsp::InlayHint>>| { |
| 1402 |
|
| 1403 |
if !editor.config().lsp.display_inlay_hints || editor.tree.try_get(view_id).is_none() { |
| 1404 |
return; |
| 1405 |
} |
| 1406 |
|
| 1407 |
|
| 1408 |
let doc = match editor.documents.get_mut(&doc_id) { |
| 1409 |
Some(doc) => doc, |
| 1410 |
None => return, |
| 1411 |
}; |
| 1412 |
|
| 1413 |
|
| 1414 |
let mut hints = match response { |
| 1415 |
Some(hints) if !hints.is_empty() => hints, |
| 1416 |
_ => { |
| 1417 |
doc.set_inlay_hints( |
| 1418 |
view_id, |
| 1419 |
DocumentInlayHints::empty_with_id(new_doc_inlay_hints_id), |
| 1420 |
); |
| 1421 |
doc.inlay_hints_oudated = false; |
| 1422 |
return; |
| 1423 |
} |
| 1424 |
}; |
| 1425 |
|
| 1426 |
|
| 1427 |
|
| 1428 |
hints.sort_by_key(|inlay_hint| inlay_hint.position); |
| 1429 |
|
| 1430 |
let mut padding_before_inlay_hints = Vec::new(); |
| 1431 |
let mut type_inlay_hints = Vec::new(); |
| 1432 |
let mut parameter_inlay_hints = Vec::new(); |
| 1433 |
let mut other_inlay_hints = Vec::new(); |
| 1434 |
let mut padding_after_inlay_hints = Vec::new(); |
| 1435 |
|
| 1436 |
let doc_text = doc.text(); |
| 1437 |
let inlay_hints_length_limit = doc.config.load().lsp.inlay_hints_length_limit; |
| 1438 |
|
| 1439 |
for hint in hints { |
| 1440 |
let char_idx = |
| 1441 |
match helix_lsp::util::lsp_pos_to_pos(doc_text, hint.position, offset_encoding) |
| 1442 |
{ |
| 1443 |
Some(pos) => pos, |
| 1444 |
|
| 1445 |
None => continue, |
| 1446 |
}; |
| 1447 |
|
| 1448 |
let mut label = match hint.label { |
| 1449 |
lsp::InlayHintLabel::String(s) => s, |
| 1450 |
lsp::InlayHintLabel::LabelParts(parts) => parts |
| 1451 |
.into_iter() |
| 1452 |
.map(|p| p.value) |
| 1453 |
.collect::<Vec<_>>() |
| 1454 |
.join(""), |
| 1455 |
}; |
| 1456 |
|
| 1457 |
if let Some(limit) = inlay_hints_length_limit { |
| 1458 |
|
| 1459 |
use helix_core::unicode::{ |
| 1460 |
segmentation::UnicodeSegmentation, width::UnicodeWidthStr, |
| 1461 |
}; |
| 1462 |
|
| 1463 |
let width = label.width(); |
| 1464 |
let limit = limit.get().into(); |
| 1465 |
if width > limit { |
| 1466 |
let mut floor_boundary = 0; |
| 1467 |
let mut acc = 0; |
| 1468 |
for (i, grapheme_cluster) in label.grapheme_indices(true) { |
| 1469 |
acc += grapheme_cluster.width(); |
| 1470 |
|
| 1471 |
if acc > limit { |
| 1472 |
floor_boundary = i; |
| 1473 |
break; |
| 1474 |
} |
| 1475 |
} |
| 1476 |
|
| 1477 |
label.truncate(floor_boundary); |
| 1478 |
label.push('…'); |
| 1479 |
} |
| 1480 |
} |
| 1481 |
|
| 1482 |
let inlay_hints_vec = match hint.kind { |
| 1483 |
Some(lsp::InlayHintKind::TYPE) => &mut type_inlay_hints, |
| 1484 |
Some(lsp::InlayHintKind::PARAMETER) => &mut parameter_inlay_hints, |
| 1485 |
|
| 1486 |
|
| 1487 |
_ => &mut other_inlay_hints, |
| 1488 |
}; |
| 1489 |
|
| 1490 |
if let Some(true) = hint.padding_left { |
| 1491 |
padding_before_inlay_hints.push(InlineAnnotation::new(char_idx, " ")); |
| 1492 |
} |
| 1493 |
|
| 1494 |
inlay_hints_vec.push(InlineAnnotation::new(char_idx, label)); |
| 1495 |
|
| 1496 |
if let Some(true) = hint.padding_right { |
| 1497 |
padding_after_inlay_hints.push(InlineAnnotation::new(char_idx, " ")); |
| 1498 |
} |
| 1499 |
} |
| 1500 |
|
| 1501 |
doc.set_inlay_hints( |
| 1502 |
view_id, |
| 1503 |
DocumentInlayHints { |
| 1504 |
id: new_doc_inlay_hints_id, |
| 1505 |
type_inlay_hints, |
| 1506 |
parameter_inlay_hints, |
| 1507 |
other_inlay_hints, |
| 1508 |
padding_before_inlay_hints, |
| 1509 |
padding_after_inlay_hints, |
| 1510 |
}, |
| 1511 |
); |
| 1512 |
doc.inlay_hints_oudated = false; |
| 1513 |
}, |
| 1514 |
); |
| 1515 |
|
| 1516 |
Some(callback) |
| 1517 |
} |