on master help sign in
Make Document's format API a little nicer.
2902a10Joe Neeman
helix-term/src/commands.rs+9−14
@@ -1160,20 +1160,12 @@ mod cmd {
1160 if doc.path().is_none() {
1160 if doc.path().is_none() {
1161 return Err(anyhow!("cannot write a buffer without a filename"));
1161 return Err(anyhow!("cannot write a buffer without a filename"));
1162 }
1162 }
1163− let autofmt = doc
1164− .language_config()
1165− .map(|config| config.auto_format)
1163+ let fmt = doc.auto_format().map(|fmt| {
1166− .unwrap_or_default();
1167− let fmt = if autofmt {
1168− doc.format().map(|fmt| {
1169− let shared = fmt.shared();
1164+ let shared = fmt.shared();
1170− let callback = make_format_callback(doc.id(), doc.version(), true, shared.clone());
1165+ let callback = make_format_callback(doc.id(), doc.version(), true, shared.clone());
1171− jobs.callback(callback);
1166+ jobs.callback(callback);
1172− shared
1167+ shared
1173− })
1174− } else {
1175− None
1176− };
1168+ });
1177 Ok(tokio::spawn(doc.format_and_save(fmt)))
1169 Ok(tokio::spawn(doc.format_and_save(fmt)))
1178 }
1170 }
1179
1171
@@ -1917,6 +1909,9 @@ fn append_to_line(cx: &mut Context) {
1917
1909
1918// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
1910// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
1919// it applies them, but only if the doc hasn't changed.
1911// 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
1920async fn make_format_callback(
1915async fn make_format_callback(
1921 doc_id: DocumentId,
1916 doc_id: DocumentId,
1922 doc_version: i32,
1917 doc_version: i32,
helix-view/src/document.rs+12
@@ -473,6 +473,18 @@ impl Document {
473 Ok(doc)
473 Ok(doc)
474 }
474 }
475
475
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.
476 pub fn format(&self) -> Option<impl Future<Output = LspFormatting> + 'static> {
488 pub fn format(&self) -> Option<impl Future<Output = LspFormatting> + 'static> {
477 if let Some(language_server) = self.language_server.clone() {
489 if let Some(language_server) = self.language_server.clone() {
478 let text = self.text.clone();
490 let text = self.text.clone();