1use anyhow::{anyhow, bail, Context, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_trait::async_trait;
4use futures::{io::BufReader, StreamExt};
5use gpui::AsyncAppContext;
6pub use language::*;
7use lazy_static::lazy_static;
8use lsp::LanguageServerBinary;
9use project::project_settings::ProjectSettings;
10use regex::Regex;
11use settings::Settings;
12use smol::fs::{self, File};
13use std::{
14 any::Any,
15 borrow::Cow,
16 env::consts,
17 path::{Path, PathBuf},
18 sync::Arc,
19};
20use task::{
21 static_source::{Definition, TaskDefinitions},
22 TaskVariables, VariableName,
23};
24use util::{
25 fs::remove_matching,
26 github::{latest_github_release, GitHubLspBinaryVersion},
27 maybe, ResultExt,
28};
29
30pub struct RustLspAdapter;
31
32impl RustLspAdapter {
33 const SERVER_NAME: &'static str = "rust-analyzer";
34}
35
36#[async_trait(?Send)]
37impl LspAdapter for RustLspAdapter {
38 fn name(&self) -> LanguageServerName {
39 LanguageServerName(Self::SERVER_NAME.into())
40 }
41
42 async fn check_if_user_installed(
43 &self,
44 _delegate: &dyn LspAdapterDelegate,
45 cx: &AsyncAppContext,
46 ) -> Option<LanguageServerBinary> {
47 let binary = cx
48 .update(|cx| {
49 ProjectSettings::get_global(cx)
50 .lsp
51 .get(Self::SERVER_NAME)
52 .and_then(|s| s.binary.clone())
53 })
54 .ok()??;
55
56 let path = binary.path?;
57 Some(LanguageServerBinary {
58 path: path.into(),
59 arguments: binary
60 .arguments
61 .unwrap_or_default()
62 .iter()
63 .map(|arg| arg.into())
64 .collect(),
65 env: None,
66 })
67 }
68
69 async fn fetch_latest_server_version(
70 &self,
71 delegate: &dyn LspAdapterDelegate,
72 ) -> Result<Box<dyn 'static + Send + Any>> {
73 let release = latest_github_release(
74 "rust-lang/rust-analyzer",
75 true,
76 false,
77 delegate.http_client(),
78 )
79 .await?;
80 let os = match consts::OS {
81 "macos" => "apple-darwin",
82 "linux" => "unknown-linux-gnu",
83 "windows" => "pc-windows-msvc",
84 other => bail!("Running on unsupported os: {other}"),
85 };
86 let asset_name = format!("rust-analyzer-{}-{os}.gz", consts::ARCH);
87 let asset = release
88 .assets
89 .iter()
90 .find(|asset| asset.name == asset_name)
91 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
92 Ok(Box::new(GitHubLspBinaryVersion {
93 name: release.tag_name,
94 url: asset.browser_download_url.clone(),
95 }))
96 }
97
98 async fn fetch_server_binary(
99 &self,
100 version: Box<dyn 'static + Send + Any>,
101 container_dir: PathBuf,
102 delegate: &dyn LspAdapterDelegate,
103 ) -> Result<LanguageServerBinary> {
104 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
105 let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
106
107 if fs::metadata(&destination_path).await.is_err() {
108 let mut response = delegate
109 .http_client()
110 .get(&version.url, Default::default(), true)
111 .await
112 .map_err(|err| anyhow!("error downloading release: {}", err))?;
113 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
114 let mut file = File::create(&destination_path).await?;
115 futures::io::copy(decompressed_bytes, &mut file).await?;
116 // todo("windows")
117 #[cfg(not(windows))]
118 {
119 fs::set_permissions(
120 &destination_path,
121 <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
122 )
123 .await?;
124 }
125
126 remove_matching(&container_dir, |entry| entry != destination_path).await;
127 }
128
129 Ok(LanguageServerBinary {
130 path: destination_path,
131 env: None,
132 arguments: Default::default(),
133 })
134 }
135
136 async fn cached_server_binary(
137 &self,
138 container_dir: PathBuf,
139 _: &dyn LspAdapterDelegate,
140 ) -> Option<LanguageServerBinary> {
141 get_cached_server_binary(container_dir).await
142 }
143
144 async fn installation_test_binary(
145 &self,
146 container_dir: PathBuf,
147 ) -> Option<LanguageServerBinary> {
148 get_cached_server_binary(container_dir)
149 .await
150 .map(|mut binary| {
151 binary.arguments = vec!["--help".into()];
152 binary
153 })
154 }
155
156 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
157 vec!["rustc".into()]
158 }
159
160 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
161 Some("rust-analyzer/flycheck".into())
162 }
163
164 fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
165 lazy_static! {
166 static ref REGEX: Regex = Regex::new("(?m)`([^`]+)\n`$").unwrap();
167 }
168
169 for diagnostic in &mut params.diagnostics {
170 for message in diagnostic
171 .related_information
172 .iter_mut()
173 .flatten()
174 .map(|info| &mut info.message)
175 .chain([&mut diagnostic.message])
176 {
177 if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
178 *message = sanitized;
179 }
180 }
181 }
182 }
183
184 async fn label_for_completion(
185 &self,
186 completion: &lsp::CompletionItem,
187 language: &Arc<Language>,
188 ) -> Option<CodeLabel> {
189 match completion.kind {
190 Some(lsp::CompletionItemKind::FIELD) if completion.detail.is_some() => {
191 let detail = completion.detail.as_ref().unwrap();
192 let name = &completion.label;
193 let text = format!("{}: {}", name, detail);
194 let source = Rope::from(format!("struct S {{ {} }}", text).as_str());
195 let runs = language.highlight_text(&source, 11..11 + text.len());
196 return Some(CodeLabel {
197 text,
198 runs,
199 filter_range: 0..name.len(),
200 });
201 }
202 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE)
203 if completion.detail.is_some()
204 && completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) =>
205 {
206 let detail = completion.detail.as_ref().unwrap();
207 let name = &completion.label;
208 let text = format!("{}: {}", name, detail);
209 let source = Rope::from(format!("let {} = ();", text).as_str());
210 let runs = language.highlight_text(&source, 4..4 + text.len());
211 return Some(CodeLabel {
212 text,
213 runs,
214 filter_range: 0..name.len(),
215 });
216 }
217 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD)
218 if completion.detail.is_some() =>
219 {
220 lazy_static! {
221 static ref REGEX: Regex = Regex::new("\\(…?\\)").unwrap();
222 }
223 let detail = completion.detail.as_ref().unwrap();
224 const FUNCTION_PREFIXES: [&'static str; 2] = ["async fn", "fn"];
225 let prefix = FUNCTION_PREFIXES
226 .iter()
227 .find_map(|prefix| detail.strip_prefix(*prefix).map(|suffix| (prefix, suffix)));
228 // fn keyword should be followed by opening parenthesis.
229 if let Some((prefix, suffix)) = prefix {
230 if suffix.starts_with('(') {
231 let text = REGEX.replace(&completion.label, suffix).to_string();
232 let source = Rope::from(format!("{prefix} {} {{}}", text).as_str());
233 let run_start = prefix.len() + 1;
234 let runs =
235 language.highlight_text(&source, run_start..run_start + text.len());
236 return Some(CodeLabel {
237 filter_range: 0..completion.label.find('(').unwrap_or(text.len()),
238 text,
239 runs,
240 });
241 }
242 }
243 }
244 Some(kind) => {
245 let highlight_name = match kind {
246 lsp::CompletionItemKind::STRUCT
247 | lsp::CompletionItemKind::INTERFACE
248 | lsp::CompletionItemKind::ENUM => Some("type"),
249 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
250 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
251 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
252 Some("constant")
253 }
254 _ => None,
255 };
256 let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name?)?;
257 let mut label = CodeLabel::plain(completion.label.clone(), None);
258 label.runs.push((
259 0..label.text.rfind('(').unwrap_or(label.text.len()),
260 highlight_id,
261 ));
262 return Some(label);
263 }
264 _ => {}
265 }
266 None
267 }
268
269 async fn label_for_symbol(
270 &self,
271 name: &str,
272 kind: lsp::SymbolKind,
273 language: &Arc<Language>,
274 ) -> Option<CodeLabel> {
275 let (text, filter_range, display_range) = match kind {
276 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
277 let text = format!("fn {} () {{}}", name);
278 let filter_range = 3..3 + name.len();
279 let display_range = 0..filter_range.end;
280 (text, filter_range, display_range)
281 }
282 lsp::SymbolKind::STRUCT => {
283 let text = format!("struct {} {{}}", name);
284 let filter_range = 7..7 + name.len();
285 let display_range = 0..filter_range.end;
286 (text, filter_range, display_range)
287 }
288 lsp::SymbolKind::ENUM => {
289 let text = format!("enum {} {{}}", name);
290 let filter_range = 5..5 + name.len();
291 let display_range = 0..filter_range.end;
292 (text, filter_range, display_range)
293 }
294 lsp::SymbolKind::INTERFACE => {
295 let text = format!("trait {} {{}}", name);
296 let filter_range = 6..6 + name.len();
297 let display_range = 0..filter_range.end;
298 (text, filter_range, display_range)
299 }
300 lsp::SymbolKind::CONSTANT => {
301 let text = format!("const {}: () = ();", name);
302 let filter_range = 6..6 + name.len();
303 let display_range = 0..filter_range.end;
304 (text, filter_range, display_range)
305 }
306 lsp::SymbolKind::MODULE => {
307 let text = format!("mod {} {{}}", name);
308 let filter_range = 4..4 + name.len();
309 let display_range = 0..filter_range.end;
310 (text, filter_range, display_range)
311 }
312 lsp::SymbolKind::TYPE_PARAMETER => {
313 let text = format!("type {} {{}}", name);
314 let filter_range = 5..5 + name.len();
315 let display_range = 0..filter_range.end;
316 (text, filter_range, display_range)
317 }
318 _ => return None,
319 };
320
321 Some(CodeLabel {
322 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
323 text: text[display_range].to_string(),
324 filter_range,
325 })
326 }
327}
328
329pub(crate) struct RustContextProvider;
330
331const RUST_PACKAGE_TASK_VARIABLE: VariableName =
332 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
333
334impl ContextProvider for RustContextProvider {
335 fn build_context(
336 &self,
337 location: Location,
338 cx: &mut gpui::AppContext,
339 ) -> Result<TaskVariables> {
340 let mut context = SymbolContextProvider.build_context(location.clone(), cx)?;
341
342 let local_abs_path = location
343 .buffer
344 .read(cx)
345 .file()
346 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
347 if let Some(package_name) = local_abs_path
348 .as_deref()
349 .and_then(|local_abs_path| local_abs_path.parent())
350 .and_then(human_readable_package_name)
351 {
352 context.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
353 }
354
355 Ok(context)
356 }
357
358 fn associated_tasks(&self) -> Option<TaskDefinitions> {
359 Some(TaskDefinitions(vec![
360 Definition {
361 label: "Rust: Test current crate".to_owned(),
362 command: "cargo".into(),
363 args: vec![
364 "test".into(),
365 "-p".into(),
366 RUST_PACKAGE_TASK_VARIABLE.template_value(),
367 ],
368 ..Definition::default()
369 },
370 Definition {
371 label: "Rust: Test current function".to_owned(),
372 command: "cargo".into(),
373 args: vec![
374 "test".into(),
375 "-p".into(),
376 RUST_PACKAGE_TASK_VARIABLE.template_value(),
377 VariableName::Symbol.template_value(),
378 "--".into(),
379 "--nocapture".into(),
380 ],
381 ..Definition::default()
382 },
383 Definition {
384 label: "Rust: cargo run".into(),
385 command: "cargo".into(),
386 args: vec!["run".into()],
387 ..Definition::default()
388 },
389 Definition {
390 label: "Rust: cargo check current crate".into(),
391 command: "cargo".into(),
392 args: vec![
393 "check".into(),
394 "-p".into(),
395 RUST_PACKAGE_TASK_VARIABLE.template_value(),
396 ],
397 ..Definition::default()
398 },
399 Definition {
400 label: "Rust: cargo check workspace".into(),
401 command: "cargo".into(),
402 args: vec!["check".into(), "--workspace".into()],
403 ..Definition::default()
404 },
405 ]))
406 }
407}
408
409fn human_readable_package_name(package_directory: &Path) -> Option<String> {
410 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
411 match input.rsplit_once(suffix_start) {
412 Some((without_suffix, _)) => without_suffix,
413 None => input,
414 }
415 }
416
417 let pkgid = String::from_utf8(
418 std::process::Command::new("cargo")
419 .current_dir(package_directory)
420 .arg("pkgid")
421 .output()
422 .log_err()?
423 .stdout,
424 )
425 .ok()?;
426 // For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
427 // Output example in the root of Zed project:
428 // ```bash
429 // ❯ cargo pkgid zed
430 // path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
431 // ```
432 // Extrarct the package name from the output according to the spec:
433 // https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
434 let mut package_name = pkgid.trim();
435 package_name = split_off_suffix(package_name, '#');
436 package_name = split_off_suffix(package_name, '?');
437 let (_, package_name) = package_name.rsplit_once('/')?;
438 Some(package_name.to_string())
439}
440
441async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
442 maybe!(async {
443 let mut last = None;
444 let mut entries = fs::read_dir(&container_dir).await?;
445 while let Some(entry) = entries.next().await {
446 last = Some(entry?.path());
447 }
448
449 anyhow::Ok(LanguageServerBinary {
450 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
451 env: None,
452 arguments: Default::default(),
453 })
454 })
455 .await
456 .log_err()
457}
458
459#[cfg(test)]
460mod tests {
461 use std::num::NonZeroU32;
462
463 use super::*;
464 use crate::language;
465 use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
466 use language::language_settings::AllLanguageSettings;
467 use settings::SettingsStore;
468 use theme::SyntaxTheme;
469
470 #[gpui::test]
471 async fn test_process_rust_diagnostics() {
472 let mut params = lsp::PublishDiagnosticsParams {
473 uri: lsp::Url::from_file_path("/a").unwrap(),
474 version: None,
475 diagnostics: vec![
476 // no newlines
477 lsp::Diagnostic {
478 message: "use of moved value `a`".to_string(),
479 ..Default::default()
480 },
481 // newline at the end of a code span
482 lsp::Diagnostic {
483 message: "consider importing this struct: `use b::c;\n`".to_string(),
484 ..Default::default()
485 },
486 // code span starting right after a newline
487 lsp::Diagnostic {
488 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
489 .to_string(),
490 ..Default::default()
491 },
492 ],
493 };
494 RustLspAdapter.process_diagnostics(&mut params);
495
496 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
497
498 // remove trailing newline from code span
499 assert_eq!(
500 params.diagnostics[1].message,
501 "consider importing this struct: `use b::c;`"
502 );
503
504 // do not remove newline before the start of code span
505 assert_eq!(
506 params.diagnostics[2].message,
507 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
508 );
509 }
510
511 #[gpui::test]
512 async fn test_rust_label_for_completion() {
513 let adapter = Arc::new(RustLspAdapter);
514 let language = language("rust", tree_sitter_rust::language());
515 let grammar = language.grammar().unwrap();
516 let theme = SyntaxTheme::new_test([
517 ("type", Hsla::default()),
518 ("keyword", Hsla::default()),
519 ("function", Hsla::default()),
520 ("property", Hsla::default()),
521 ]);
522
523 language.set_theme(&theme);
524
525 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
526 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
527 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
528 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
529
530 assert_eq!(
531 adapter
532 .label_for_completion(
533 &lsp::CompletionItem {
534 kind: Some(lsp::CompletionItemKind::FUNCTION),
535 label: "hello(…)".to_string(),
536 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
537 ..Default::default()
538 },
539 &language
540 )
541 .await,
542 Some(CodeLabel {
543 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
544 filter_range: 0..5,
545 runs: vec![
546 (0..5, highlight_function),
547 (7..10, highlight_keyword),
548 (11..17, highlight_type),
549 (18..19, highlight_type),
550 (25..28, highlight_type),
551 (29..30, highlight_type),
552 ],
553 })
554 );
555 assert_eq!(
556 adapter
557 .label_for_completion(
558 &lsp::CompletionItem {
559 kind: Some(lsp::CompletionItemKind::FUNCTION),
560 label: "hello(…)".to_string(),
561 detail: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
562 ..Default::default()
563 },
564 &language
565 )
566 .await,
567 Some(CodeLabel {
568 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
569 filter_range: 0..5,
570 runs: vec![
571 (0..5, highlight_function),
572 (7..10, highlight_keyword),
573 (11..17, highlight_type),
574 (18..19, highlight_type),
575 (25..28, highlight_type),
576 (29..30, highlight_type),
577 ],
578 })
579 );
580 assert_eq!(
581 adapter
582 .label_for_completion(
583 &lsp::CompletionItem {
584 kind: Some(lsp::CompletionItemKind::FIELD),
585 label: "len".to_string(),
586 detail: Some("usize".to_string()),
587 ..Default::default()
588 },
589 &language
590 )
591 .await,
592 Some(CodeLabel {
593 text: "len: usize".to_string(),
594 filter_range: 0..3,
595 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
596 })
597 );
598
599 assert_eq!(
600 adapter
601 .label_for_completion(
602 &lsp::CompletionItem {
603 kind: Some(lsp::CompletionItemKind::FUNCTION),
604 label: "hello(…)".to_string(),
605 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
606 ..Default::default()
607 },
608 &language
609 )
610 .await,
611 Some(CodeLabel {
612 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
613 filter_range: 0..5,
614 runs: vec![
615 (0..5, highlight_function),
616 (7..10, highlight_keyword),
617 (11..17, highlight_type),
618 (18..19, highlight_type),
619 (25..28, highlight_type),
620 (29..30, highlight_type),
621 ],
622 })
623 );
624 }
625
626 #[gpui::test]
627 async fn test_rust_label_for_symbol() {
628 let adapter = Arc::new(RustLspAdapter);
629 let language = language("rust", tree_sitter_rust::language());
630 let grammar = language.grammar().unwrap();
631 let theme = SyntaxTheme::new_test([
632 ("type", Hsla::default()),
633 ("keyword", Hsla::default()),
634 ("function", Hsla::default()),
635 ("property", Hsla::default()),
636 ]);
637
638 language.set_theme(&theme);
639
640 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
641 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
642 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
643
644 assert_eq!(
645 adapter
646 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
647 .await,
648 Some(CodeLabel {
649 text: "fn hello".to_string(),
650 filter_range: 3..8,
651 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
652 })
653 );
654
655 assert_eq!(
656 adapter
657 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
658 .await,
659 Some(CodeLabel {
660 text: "type World".to_string(),
661 filter_range: 5..10,
662 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
663 })
664 );
665 }
666
667 #[gpui::test]
668 async fn test_rust_autoindent(cx: &mut TestAppContext) {
669 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
670 cx.update(|cx| {
671 let test_settings = SettingsStore::test(cx);
672 cx.set_global(test_settings);
673 language::init(cx);
674 cx.update_global::<SettingsStore, _>(|store, cx| {
675 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
676 s.defaults.tab_size = NonZeroU32::new(2);
677 });
678 });
679 });
680
681 let language = crate::language("rust", tree_sitter_rust::language());
682
683 cx.new_model(|cx| {
684 let mut buffer = Buffer::local("", cx).with_language(language, cx);
685
686 // indent between braces
687 buffer.set_text("fn a() {}", cx);
688 let ix = buffer.len() - 1;
689 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
690 assert_eq!(buffer.text(), "fn a() {\n \n}");
691
692 // indent between braces, even after empty lines
693 buffer.set_text("fn a() {\n\n\n}", cx);
694 let ix = buffer.len() - 2;
695 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
696 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
697
698 // indent a line that continues a field expression
699 buffer.set_text("fn a() {\n \n}", cx);
700 let ix = buffer.len() - 2;
701 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
702 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
703
704 // indent further lines that continue the field expression, even after empty lines
705 let ix = buffer.len() - 2;
706 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
707 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
708
709 // dedent the line after the field expression
710 let ix = buffer.len() - 2;
711 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
712 assert_eq!(
713 buffer.text(),
714 "fn a() {\n b\n .c\n \n .d;\n e\n}"
715 );
716
717 // indent inside a struct within a call
718 buffer.set_text("const a: B = c(D {});", cx);
719 let ix = buffer.len() - 3;
720 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
721 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
722
723 // indent further inside a nested call
724 let ix = buffer.len() - 4;
725 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
726 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
727
728 // keep that indent after an empty line
729 let ix = buffer.len() - 8;
730 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
731 assert_eq!(
732 buffer.text(),
733 "const a: B = c(D {\n e: f(\n \n \n )\n});"
734 );
735
736 buffer
737 });
738 }
739}