on master help sign in
Make Document's format API a little nicer.
commit2902a10a3eb07af7df9f04184000ad75c6b38532 authorJoe Neeman <joeneeman@gmail.com> dateTue 29 Jun 2021, 22:36 (5 years ago) parentffa2f25
2 files changed+21−14
helix-term/src/commands.rs+9−14 helix-view/src/document.rs+12
helix-term/src/commands.rs+9−14
@@ -1160,20 +1160,12 @@ mod cmd {
11601160 if doc.path().is_none() {
11611161 return Err(anyhow!("cannot write a buffer without a filename"));
11621162 }
1163− let autofmt = doc
1164− .language_config()
1165− .map(|config| config.auto_format)
1166− .unwrap_or_default();
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− jobs.callback(callback);
1172− shared
1173− })
1174− } else {
1175− None
1176− };
1163+ let fmt = doc.auto_format().map(|fmt| {
1164+ let shared = fmt.shared();
1165+ let callback = make_format_callback(doc.id(), doc.version(), true, shared.clone());
1166+ jobs.callback(callback);
1167+ shared
1168+ });
11771169 Ok(tokio::spawn(doc.format_and_save(fmt)))
11781170 }
11791171
@@ -1917,6 +1909,9 @@ fn append_to_line(cx: &mut Context) {
19171909
19181910// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
19191911// it applies them, but only if the doc hasn't changed.
1912+//
1913+// TODO: provide some way to cancel this, probably as part of a more general job cancellation
1914+// scheme
19201915async fn make_format_callback(
19211916 doc_id: DocumentId,
19221917 doc_version: i32,
helix-view/src/document.rs+12
@@ -473,6 +473,18 @@ impl Document {
473473 Ok(doc)
474474 }
475475
476+ /// The same as [`format`], but only returns formatting changes if auto-formatting
477+ /// is configured.
478+ pub fn auto_format(&self) -> Option<impl Future<Output = LspFormatting> + 'static> {
479+ if self.language_config().map(|c| c.auto_format) == Some(true) {
480+ self.format()
481+ } else {
482+ None
483+ }
484+ }
485+
486+ /// If supported, returns the changes that should be applied to this document in order
487+ /// to format it nicely.
476488 pub fn format(&self) -> Option<impl Future<Output = LspFormatting> + 'static> {
477489 if let Some(language_server) = self.language_server.clone() {
478490 let text = self.text.clone();