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 _: Option<&Path>,
338 location: &Location,
339 cx: &mut gpui::AppContext,
340 ) -> Result<TaskVariables> {
341 let local_abs_path = location
342 .buffer
343 .read(cx)
344 .file()
345 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
346 Ok(
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 TaskVariables::from_iter(Some((RUST_PACKAGE_TASK_VARIABLE.clone(), package_name)))
353 } else {
354 TaskVariables::default()
355 },
356 )
357 }
358
359 fn associated_tasks(&self) -> Option<TaskDefinitions> {
360 Some(TaskDefinitions(vec![
361 Definition {
362 label: "Rust: Test current crate".to_owned(),
363 command: "cargo".into(),
364 args: vec![
365 "test".into(),
366 "-p".into(),
367 RUST_PACKAGE_TASK_VARIABLE.template_value(),
368 ],
369 ..Definition::default()
370 },
371 Definition {
372 label: "Rust: Test current function".to_owned(),
373 command: "cargo".into(),
374 args: vec![
375 "test".into(),
376 "-p".into(),
377 RUST_PACKAGE_TASK_VARIABLE.template_value(),
378 VariableName::Symbol.template_value(),
379 "--".into(),
380 "--nocapture".into(),
381 ],
382 ..Definition::default()
383 },
384 Definition {
385 label: "Rust: cargo run".into(),
386 command: "cargo".into(),
387 args: vec!["run".into()],
388 ..Definition::default()
389 },
390 Definition {
391 label: "Rust: cargo check current crate".into(),
392 command: "cargo".into(),
393 args: vec![
394 "check".into(),
395 "-p".into(),
396 RUST_PACKAGE_TASK_VARIABLE.template_value(),
397 ],
398 ..Definition::default()
399 },
400 Definition {
401 label: "Rust: cargo check workspace".into(),
402 command: "cargo".into(),
403 args: vec!["check".into(), "--workspace".into()],
404 ..Definition::default()
405 },
406 ]))
407 }
408}
409
410fn human_readable_package_name(package_directory: &Path) -> Option<String> {
411 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
412 match input.rsplit_once(suffix_start) {
413 Some((without_suffix, _)) => without_suffix,
414 None => input,
415 }
416 }
417
418 let pkgid = String::from_utf8(
419 std::process::Command::new("cargo")
420 .current_dir(package_directory)
421 .arg("pkgid")
422 .output()
423 .log_err()?
424 .stdout,
425 )
426 .ok()?;
427 // For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
428 // Output example in the root of Zed project:
429 // ```bash
430 // ❯ cargo pkgid zed
431 // path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
432 // ```
433 // Extrarct the package name from the output according to the spec:
434 // https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
435 let mut package_name = pkgid.trim();
436 package_name = split_off_suffix(package_name, '#');
437 package_name = split_off_suffix(package_name, '?');
438 let (_, package_name) = package_name.rsplit_once('/')?;
439 Some(package_name.to_string())
440}
441
442async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
443 maybe!(async {
444 let mut last = None;
445 let mut entries = fs::read_dir(&container_dir).await?;
446 while let Some(entry) = entries.next().await {
447 last = Some(entry?.path());
448 }
449
450 anyhow::Ok(LanguageServerBinary {
451 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
452 env: None,
453 arguments: Default::default(),
454 })
455 })
456 .await
457 .log_err()
458}
459
460#[cfg(test)]
461mod tests {
462 use std::num::NonZeroU32;
463
464 use super::*;
465 use crate::language;
466 use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
467 use language::language_settings::AllLanguageSettings;
468 use settings::SettingsStore;
469 use theme::SyntaxTheme;
470
471 #[gpui::test]
472 async fn test_process_rust_diagnostics() {
473 let mut params = lsp::PublishDiagnosticsParams {
474 uri: lsp::Url::from_file_path("/a").unwrap(),
475 version: None,
476 diagnostics: vec![
477 // no newlines
478 lsp::Diagnostic {
479 message: "use of moved value `a`".to_string(),
480 ..Default::default()
481 },
482 // newline at the end of a code span
483 lsp::Diagnostic {
484 message: "consider importing this struct: `use b::c;\n`".to_string(),
485 ..Default::default()
486 },
487 // code span starting right after a newline
488 lsp::Diagnostic {
489 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
490 .to_string(),
491 ..Default::default()
492 },
493 ],
494 };
495 RustLspAdapter.process_diagnostics(&mut params);
496
497 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
498
499 // remove trailing newline from code span
500 assert_eq!(
501 params.diagnostics[1].message,
502 "consider importing this struct: `use b::c;`"
503 );
504
505 // do not remove newline before the start of code span
506 assert_eq!(
507 params.diagnostics[2].message,
508 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
509 );
510 }
511
512 #[gpui::test]
513 async fn test_rust_label_for_completion() {
514 let adapter = Arc::new(RustLspAdapter);
515 let language = language("rust", tree_sitter_rust::language());
516 let grammar = language.grammar().unwrap();
517 let theme = SyntaxTheme::new_test([
518 ("type", Hsla::default()),
519 ("keyword", Hsla::default()),
520 ("function", Hsla::default()),
521 ("property", Hsla::default()),
522 ]);
523
524 language.set_theme(&theme);
525
526 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
527 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
528 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
529 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
530
531 assert_eq!(
532 adapter
533 .label_for_completion(
534 &lsp::CompletionItem {
535 kind: Some(lsp::CompletionItemKind::FUNCTION),
536 label: "hello(…)".to_string(),
537 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
538 ..Default::default()
539 },
540 &language
541 )
542 .await,
543 Some(CodeLabel {
544 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
545 filter_range: 0..5,
546 runs: vec![
547 (0..5, highlight_function),
548 (7..10, highlight_keyword),
549 (11..17, highlight_type),
550 (18..19, highlight_type),
551 (25..28, highlight_type),
552 (29..30, highlight_type),
553 ],
554 })
555 );
556 assert_eq!(
557 adapter
558 .label_for_completion(
559 &lsp::CompletionItem {
560 kind: Some(lsp::CompletionItemKind::FUNCTION),
561 label: "hello(…)".to_string(),
562 detail: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
563 ..Default::default()
564 },
565 &language
566 )
567 .await,
568 Some(CodeLabel {
569 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
570 filter_range: 0..5,
571 runs: vec![
572 (0..5, highlight_function),
573 (7..10, highlight_keyword),
574 (11..17, highlight_type),
575 (18..19, highlight_type),
576 (25..28, highlight_type),
577 (29..30, highlight_type),
578 ],
579 })
580 );
581 assert_eq!(
582 adapter
583 .label_for_completion(
584 &lsp::CompletionItem {
585 kind: Some(lsp::CompletionItemKind::FIELD),
586 label: "len".to_string(),
587 detail: Some("usize".to_string()),
588 ..Default::default()
589 },
590 &language
591 )
592 .await,
593 Some(CodeLabel {
594 text: "len: usize".to_string(),
595 filter_range: 0..3,
596 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
597 })
598 );
599
600 assert_eq!(
601 adapter
602 .label_for_completion(
603 &lsp::CompletionItem {
604 kind: Some(lsp::CompletionItemKind::FUNCTION),
605 label: "hello(…)".to_string(),
606 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
607 ..Default::default()
608 },
609 &language
610 )
611 .await,
612 Some(CodeLabel {
613 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
614 filter_range: 0..5,
615 runs: vec![
616 (0..5, highlight_function),
617 (7..10, highlight_keyword),
618 (11..17, highlight_type),
619 (18..19, highlight_type),
620 (25..28, highlight_type),
621 (29..30, highlight_type),
622 ],
623 })
624 );
625 }
626
627 #[gpui::test]
628 async fn test_rust_label_for_symbol() {
629 let adapter = Arc::new(RustLspAdapter);
630 let language = language("rust", tree_sitter_rust::language());
631 let grammar = language.grammar().unwrap();
632 let theme = SyntaxTheme::new_test([
633 ("type", Hsla::default()),
634 ("keyword", Hsla::default()),
635 ("function", Hsla::default()),
636 ("property", Hsla::default()),
637 ]);
638
639 language.set_theme(&theme);
640
641 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
642 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
643 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
644
645 assert_eq!(
646 adapter
647 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
648 .await,
649 Some(CodeLabel {
650 text: "fn hello".to_string(),
651 filter_range: 3..8,
652 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
653 })
654 );
655
656 assert_eq!(
657 adapter
658 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
659 .await,
660 Some(CodeLabel {
661 text: "type World".to_string(),
662 filter_range: 5..10,
663 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
664 })
665 );
666 }
667
668 #[gpui::test]
669 async fn test_rust_autoindent(cx: &mut TestAppContext) {
670 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
671 cx.update(|cx| {
672 let test_settings = SettingsStore::test(cx);
673 cx.set_global(test_settings);
674 language::init(cx);
675 cx.update_global::<SettingsStore, _>(|store, cx| {
676 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
677 s.defaults.tab_size = NonZeroU32::new(2);
678 });
679 });
680 });
681
682 let language = crate::language("rust", tree_sitter_rust::language());
683
684 cx.new_model(|cx| {
685 let mut buffer = Buffer::local("", cx).with_language(language, cx);
686
687 // indent between braces
688 buffer.set_text("fn a() {}", cx);
689 let ix = buffer.len() - 1;
690 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
691 assert_eq!(buffer.text(), "fn a() {\n \n}");
692
693 // indent between braces, even after empty lines
694 buffer.set_text("fn a() {\n\n\n}", cx);
695 let ix = buffer.len() - 2;
696 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
697 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
698
699 // indent a line that continues a field expression
700 buffer.set_text("fn a() {\n \n}", cx);
701 let ix = buffer.len() - 2;
702 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
703 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
704
705 // indent further lines that continue the field expression, even after empty lines
706 let ix = buffer.len() - 2;
707 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
708 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
709
710 // dedent the line after the field expression
711 let ix = buffer.len() - 2;
712 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
713 assert_eq!(
714 buffer.text(),
715 "fn a() {\n b\n .c\n \n .d;\n e\n}"
716 );
717
718 // indent inside a struct within a call
719 buffer.set_text("const a: B = c(D {});", cx);
720 let ix = buffer.len() - 3;
721 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
722 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
723
724 // indent further inside a nested call
725 let ix = buffer.len() - 4;
726 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
727 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
728
729 // keep that indent after an empty line
730 let ix = buffer.len() - 8;
731 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
732 assert_eq!(
733 buffer.text(),
734 "const a: B = c(D {\n e: f(\n \n \n )\n});"
735 );
736
737 buffer
738 });
739 }
740}