on master help sign in
Make formatting happen asynchronously.
commitc9be480bf86489fbf659b45b107be0d26a076b50 authorJoe Neeman <joeneeman@gmail.com> dateWed 23 Jun 2021, 13:35 (5 years ago) parent3007478
4 files changed+128−40
helix-lsp/src/lib.rs+16 helix-term/src/commands.rs+52−14 helix-view/src/document.rs+56−26 helix-view/src/editor.rs+4
helix-lsp/src/lib.rs+16
@@ -182,6 +182,22 @@ pub mod util {
182182 }),
183183 )
184184 }
185+
186+ /// The result of asking the language server to format the document. This can be turned into a
187+ /// `Transaction`, but the advantage of not doing that straight away is that this one is
188+ /// `Send` and `Sync`.
189+ #[derive(Clone, Debug)]
190+ pub struct LspFormatting {
191+ pub doc: Rope,
192+ pub edits: Vec<lsp::TextEdit>,
193+ pub offset_encoding: OffsetEncoding,
194+ }
195+
196+ impl From<LspFormatting> for Transaction {
197+ fn from(fmt: LspFormatting) -> Transaction {
198+ generate_transaction_from_edits(&fmt.doc, fmt.edits, fmt.offset_encoding)
199+ }
200+ }
185201}
186202
187203#[derive(Debug, PartialEq, Clone)]
helix-term/src/commands.rs+52−14
@@ -35,7 +35,7 @@ use crate::{
3535 ui::{self, Completion, Picker, Popup, Prompt, PromptEvent},
3636};
3737
38−use crate::application::{LspCallbackWrapper, LspCallbacks};
38+use crate::application::{LspCallback, LspCallbackWrapper, LspCallbacks};
3939use futures_util::FutureExt;
4040use std::{fmt, future::Future, path::Display, str::FromStr};
4141
@@ -1145,11 +1145,12 @@ mod cmd {
11451145 }
11461146
11471147 fn write_impl<P: AsRef<Path>>(
1148− view: &View,
1149− doc: &mut Document,
1148+ cx: &mut compositor::Context,
11501149 path: Option<P>,
11511150 ) -> Result<tokio::task::JoinHandle<Result<(), anyhow::Error>>, anyhow::Error> {
11521151 use anyhow::anyhow;
1152+ let callbacks = &mut cx.callbacks;
1153+ let (view, doc) = current!(cx.editor);
11531154
11541155 if let Some(path) = path {
11551156 if let Err(err) = doc.set_path(path.as_ref()) {
@@ -1163,15 +1164,21 @@ mod cmd {
11631164 .language_config()
11641165 .map(|config| config.auto_format)
11651166 .unwrap_or_default();
1166− if autofmt {
1167− doc.format(view.id); // TODO: merge into save
1168− }
1169− Ok(tokio::spawn(doc.save()))
1167+ let fmt = if autofmt {
1168+ doc.format().map(|fmt| {
1169+ let shared = fmt.shared();
1170+ let callback = make_format_callback(doc.id(), doc.version(), true, shared.clone());
1171+ callbacks.push(callback);
1172+ shared
1173+ })
1174+ } else {
1175+ None
1176+ };
1177+ Ok(tokio::spawn(doc.format_and_save(fmt)))
11701178 }
11711179
11721180 fn write(cx: &mut compositor::Context, args: &[&str], event: PromptEvent) {
1173− let (view, doc) = current!(cx.editor);
1174− if let Err(e) = write_impl(view, doc, args.first()) {
1181+ if let Err(e) = write_impl(cx, args.first()) {
11751182 cx.editor.set_error(e.to_string());
11761183 };
11771184 }
@@ -1181,9 +1188,12 @@ mod cmd {
11811188 }
11821189
11831190 fn format(cx: &mut compositor::Context, args: &[&str], event: PromptEvent) {
1184− let (view, doc) = current!(cx.editor);
1191+ let (_, doc) = current!(cx.editor);
11851192
1186− doc.format(view.id)
1193+ if let Some(format) = doc.format() {
1194+ let callback = make_format_callback(doc.id(), doc.version(), false, format);
1195+ cx.callbacks.push(callback);
1196+ }
11871197 }
11881198
11891199 fn set_indent_style(cx: &mut compositor::Context, args: &[&str], event: PromptEvent) {
@@ -1288,8 +1298,7 @@ mod cmd {
12881298 }
12891299
12901300 fn write_quit(cx: &mut compositor::Context, args: &[&str], event: PromptEvent) {
1291− let (view, doc) = current!(cx.editor);
1292− match write_impl(view, doc, args.first()) {
1301+ match write_impl(cx, args.first()) {
12931302 Ok(handle) => {
12941303 if let Err(e) = helix_lsp::block_on(handle) {
12951304 cx.editor.set_error(e.to_string());
@@ -1305,7 +1314,7 @@ mod cmd {
13051314
13061315 fn force_write_quit(cx: &mut compositor::Context, args: &[&str], event: PromptEvent) {
13071316 let (view, doc) = current!(cx.editor);
1308− match write_impl(view, doc, args.first()) {
1317+ match write_impl(cx, args.first()) {
13091318 Ok(handle) => {
13101319 if let Err(e) = helix_lsp::block_on(handle) {
13111320 cx.editor.set_error(e.to_string());
@@ -1902,6 +1911,35 @@ fn append_to_line(cx: &mut Context) {
19021911 doc.set_selection(view.id, selection);
19031912}
19041913
1914+// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
1915+// it applies them, but only if the doc hasn't changed.
1916+fn make_format_callback(
1917+ doc_id: DocumentId,
1918+ doc_version: i32,
1919+ set_unmodified: bool,
1920+ format: impl Future<Output = helix_lsp::util::LspFormatting> + Send + 'static,
1921+) -> LspCallback {
1922+ Box::pin(async move {
1923+ let format = format.await;
1924+ let call: LspCallbackWrapper =
1925+ Box::new(move |editor: &mut Editor, compositor: &mut Compositor| {
1926+ let view_id = view!(editor).id;
1927+ if let Some(doc) = editor.document_mut(doc_id) {
1928+ if doc.version() == doc_version {
1929+ doc.apply(&Transaction::from(format), view_id);
1930+ doc.append_changes_to_history(view_id);
1931+ if set_unmodified {
1932+ doc.reset_modified();
1933+ }
1934+ } else {
1935+ log::info!("discarded formatting changes because the document changed");
1936+ }
1937+ }
1938+ });
1939+ Ok(call)
1940+ })
1941+}
1942+
19051943enum Open {
19061944 Below,
19071945 Above,
helix-view/src/document.rs+56−26
@@ -16,6 +16,7 @@ use helix_core::{
1616 ChangeSet, Diagnostic, LineEnding, Rope, RopeBuilder, Selection, State, Syntax, Transaction,
1717 DEFAULT_LINE_ENDING,
1818};
19+use helix_lsp::util::LspFormatting;
1920
2021use crate::{DocumentId, Theme, ViewId};
2122
@@ -472,39 +473,55 @@ impl Document {
472473 Ok(doc)
473474 }
474475
475− // TODO: remove view_id dependency here
476− pub fn format(&mut self, view_id: ViewId) {
477− if let Some(language_server) = self.language_server() {
478− // TODO: await, no blocking
479− let transaction = helix_lsp::block_on(language_server.text_document_formatting(
480− self.identifier(),
481− lsp::FormattingOptions::default(),
482− None,
483− ))
484− .map(|edits| {
485− helix_lsp::util::generate_transaction_from_edits(
486− self.text(),
476+ pub fn format(&self) -> Option<impl Future<Output = LspFormatting> + 'static> {
477+ if let Some(language_server) = self.language_server.clone() {
478+ let text = self.text.clone();
479+ let id = self.identifier();
480+ let fut = async move {
481+ let edits = language_server
482+ .text_document_formatting(id, lsp::FormattingOptions::default(), None)
483+ .await
484+ .unwrap_or_else(|e| {
485+ log::warn!("LSP formatting failed: {}", e);
486+ Default::default()
487+ });
488+ LspFormatting {
489+ doc: text,
487490 edits,
488− language_server.offset_encoding(),
489− )
490− });
491−
492− if let Ok(transaction) = transaction {
493− self.apply(&transaction, view_id);
494− self.append_changes_to_history(view_id);
495− }
491+ offset_encoding: language_server.offset_encoding(),
492+ }
493+ };
494+ Some(fut)
495+ } else {
496+ None
496497 }
497498 }
498499
500+ pub fn save(&mut self) -> impl Future<Output = Result<(), anyhow::Error>> {
501+ self.save_impl::<futures_util::future::Ready<_>>(None)
502+ }
503+
504+ pub fn format_and_save(
505+ &mut self,
506+ formatting: Option<impl Future<Output = LspFormatting>>,
507+ ) -> impl Future<Output = anyhow::Result<()>> {
508+ self.save_impl(formatting)
509+ }
510+
499511 // TODO: do we need some way of ensuring two save operations on the same doc can't run at once?
500512 // or is that handled by the OS/async layer
501513 /// The `Document`'s text is encoded according to its encoding and written to the file located
502514 /// at its `path()`.
503− pub fn save(&mut self) -> impl Future<Output = Result<(), anyhow::Error>> {
515+ ///
516+ /// If `formatting` is present, it supplies some changes that we apply to the text before saving.
517+ fn save_impl<F: Future<Output = LspFormatting>>(
518+ &mut self,
519+ formatting: Option<F>,
520+ ) -> impl Future<Output = Result<(), anyhow::Error>> {
504521 // we clone and move text + path into the future so that we asynchronously save the current
505522 // state without blocking any further edits.
506523
507− let text = self.text().clone();
524+ let mut text = self.text().clone();
508525 let path = self.path.clone().expect("Can't save with no path set!"); // TODO: handle no path
509526 let identifier = self.identifier();
510527
@@ -512,10 +529,7 @@ impl Document {
512529
513530 let language_server = self.language_server.clone();
514531
515− // reset the modified flag
516− let history = self.history.take();
517− self.last_saved_revision = history.current_revision();
518− self.history.set(history);
532+ self.reset_modified();
519533
520534 let encoding = self.encoding;
521535
@@ -531,6 +545,15 @@ impl Document {
531545 }
532546 }
533547
548+ if let Some(fmt) = formatting {
549+ let success = Transaction::from(fmt.await).changes().apply(&mut text);
550+ if !success {
551+ // This shouldn't happen, because the transaction changes were generated
552+ // from the same text we're saving.
553+ log::error!("failed to apply format changes before saving");
554+ }
555+ }
556+
534557 let mut file = File::create(path).await?;
535558 to_writer(&mut file, encoding, &text).await?;
536559
@@ -877,6 +900,13 @@ impl Document {
877900 current_revision != self.last_saved_revision || !self.changes.is_empty()
878901 }
879902
903+ pub fn reset_modified(&mut self) {
904+ let history = self.history.take();
905+ let current_revision = history.current_revision();
906+ self.history.set(history);
907+ self.last_saved_revision = current_revision;
908+ }
909+
880910 pub fn mode(&self) -> Mode {
881911 self.mode
882912 }
helix-view/src/editor.rs+4
@@ -270,6 +270,10 @@ impl Editor {
270270 self.documents.get(id)
271271 }
272272
273+ pub fn document_mut(&mut self, id: DocumentId) -> Option<&mut Document> {
274+ self.documents.get_mut(id)
275+ }
276+
273277 pub fn documents(&self) -> impl Iterator<Item = &Document> {
274278 self.documents.iter().map(|(_id, doc)| doc)
275279 }