Build an `additional_text_edits` entry that inserts a `use function` statement for the given fully-qualified function name at the alphabetically correct position in the file's existing use block. The sort key is prefixed with `"function "` so that function imports naturally group after class imports and among other function imports. When this is the first `use function` being added and there are
(
fqn: &str,
use_block: &UseBlockInfo,
)
| 401 | /// Global functions never need importing. Returns `None` when no import |
| 402 | /// is required. |
| 403 | pub(crate) fn build_use_function_edit( |
| 404 | fqn: &str, |
| 405 | use_block: &UseBlockInfo, |
| 406 | ) -> Option<Vec<TextEdit>> { |
| 407 | // Global functions (no namespace separator) never need importing. |
| 408 | if !fqn.contains('\\') { |
| 409 | return None; |
| 410 | } |
| 411 | |
| 412 | // Use a prefixed sort key so function imports sort after class |
| 413 | // imports and sit among other function imports. |
| 414 | let sort_key = format!("function {}", fqn.to_lowercase()); |
| 415 | |
| 416 | // Skip if this exact function is already imported. |
| 417 | if use_block.existing.iter().any(|(_, k)| k == &sort_key) { |
| 418 | return None; |
| 419 | } |
| 420 | let insert_pos = use_block.insert_position_for_key(&sort_key); |
| 421 | |
| 422 | // Prepend a blank line when: |
| 423 | // - There are no existing imports at all and the file has a |
| 424 | // namespace (separate namespace from the use block), or |
| 425 | // - This is the first function import and there are already class |
| 426 | // imports (group separator). |
| 427 | let separator = if (use_block.existing.is_empty() && use_block.has_namespace) |
| 428 | || (!use_block.has_function_imports() && use_block.has_class_imports()) |
| 429 | { |
| 430 | "\n" |
| 431 | } else { |
| 432 | "" |
| 433 | }; |
| 434 | |
| 435 | Some(vec![TextEdit { |
| 436 | range: Range { |
| 437 | start: insert_pos, |
| 438 | end: insert_pos, |
| 439 | }, |
| 440 | new_text: format!("{}use function {};\n", separator, fqn), |
| 441 | }]) |
| 442 | } |
| 443 | |
| 444 | #[cfg(test)] |
| 445 | #[path = "use_edit_tests.rs"] |