From e7d005f95aa7e755bf6143278a5c5d9bbce5c038 Mon Sep 17 00:00:00 2001 From: Nayeem Rahman Date: Tue, 16 Apr 2024 00:07:32 +0100 Subject: [PATCH] fix(lsp): slice strings by byte index in code actions (#23387) Fixes #23361. --- cli/lsp/analysis.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/cli/lsp/analysis.rs b/cli/lsp/analysis.rs index ce5d0c7f4d..9da3fcad7d 100644 --- a/cli/lsp/analysis.rs +++ b/cli/lsp/analysis.rs @@ -1126,9 +1126,11 @@ impl CodeActionCollection { /// Prepend the whitespace characters found at the start of line_content to content. fn prepend_whitespace(content: String, line_content: Option) -> String { if let Some(line) = line_content { - let whitespaces = - line.chars().position(|c| !c.is_whitespace()).unwrap_or(0); - let whitespace = &line[0..whitespaces]; + let whitespace_end = line + .char_indices() + .find_map(|(i, c)| (!c.is_whitespace()).then_some(i)) + .unwrap_or(0); + let whitespace = &line[0..whitespace_end]; format!("{}{}", &whitespace, content) } else { content @@ -1271,4 +1273,13 @@ mod tests { "utils/sub_utils" ); } + + #[test] + fn test_prepend_whitespace() { + // Regression test for https://github.com/denoland/deno/issues/23361. + assert_eq!( + &prepend_whitespace("foo".to_string(), Some("\u{a0}bar".to_string())), + "\u{a0}foo" + ); + } }