Skip to content

Commit

Permalink
Make Document's format API a little nicer.
Browse files Browse the repository at this point in the history
  • Loading branch information
jneem authored and archseer committed Jun 30, 2021
1 parent ffa2f25 commit 2902a10
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
23 changes: 9 additions & 14 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1160,20 +1160,12 @@ mod cmd {
if doc.path().is_none() {
return Err(anyhow!("cannot write a buffer without a filename"));
}
let autofmt = doc
.language_config()
.map(|config| config.auto_format)
.unwrap_or_default();
let fmt = if autofmt {
doc.format().map(|fmt| {
let shared = fmt.shared();
let callback = make_format_callback(doc.id(), doc.version(), true, shared.clone());
jobs.callback(callback);
shared
})
} else {
None
};
let fmt = doc.auto_format().map(|fmt| {
let shared = fmt.shared();
let callback = make_format_callback(doc.id(), doc.version(), true, shared.clone());
jobs.callback(callback);
shared
});
Ok(tokio::spawn(doc.format_and_save(fmt)))
}

Expand Down Expand Up @@ -1917,6 +1909,9 @@ fn append_to_line(cx: &mut Context) {

// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
// it applies them, but only if the doc hasn't changed.
//
// TODO: provide some way to cancel this, probably as part of a more general job cancellation
// scheme
async fn make_format_callback(
doc_id: DocumentId,
doc_version: i32,
Expand Down
12 changes: 12 additions & 0 deletions helix-view/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,18 @@ impl Document {
Ok(doc)
}

/// The same as [`format`], but only returns formatting changes if auto-formatting
/// is configured.
pub fn auto_format(&self) -> Option<impl Future<Output = LspFormatting> + 'static> {
if self.language_config().map(|c| c.auto_format) == Some(true) {
self.format()
} else {
None
}
}

/// If supported, returns the changes that should be applied to this document in order
/// to format it nicely.
pub fn format(&self) -> Option<impl Future<Output = LspFormatting> + 'static> {
if let Some(language_server) = self.language_server.clone() {
let text = self.text.clone();
Expand Down

0 comments on commit 2902a10

Please sign in to comment.