Format the document before auto-saving. (#3527)

* Format the document before auto-saving.

* check format_on_save

* 1. Verify rev-matching
This commit is contained in:
ifengqi 2024-09-24 17:33:00 +08:00 committed by GitHub
parent ea9b7a9c9c
commit a99ce3e626
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 44 additions and 3 deletions

View File

@ -67,7 +67,7 @@
}; };
use lsp_types::{ use lsp_types::{
CodeActionOrCommand, CodeLens, Diagnostic, DiagnosticSeverity, CodeActionOrCommand, CodeLens, Diagnostic, DiagnosticSeverity,
DocumentSymbolResponse, InlayHint, InlayHintLabel, DocumentSymbolResponse, InlayHint, InlayHintLabel, TextEdit,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use smallvec::SmallVec; use smallvec::SmallVec;
@ -678,14 +678,36 @@ fn do_bracket_colorization(&self) {
} }
} }
pub fn do_text_edit(&self, edits: &[TextEdit]) {
let edits = self.buffer.with_untracked(|buffer| {
let edits = edits
.iter()
.map(|edit| {
let selection = lapce_core::selection::Selection::region(
buffer.offset_of_position(&edit.range.start),
buffer.offset_of_position(&edit.range.end),
);
(selection, edit.new_text.as_str())
})
.collect::<Vec<_>>();
edits
});
self.do_raw_edit(&edits, EditType::Completion);
}
fn check_auto_save(&self) { fn check_auto_save(&self) {
let config = self.common.config.get_untracked(); let config = self.common.config.get_untracked();
if config.editor.autosave_interval > 0 { if config.editor.autosave_interval > 0 {
if !self.content.with_untracked(|c| c.is_file()) { let Some(path) =
self.content.with_untracked(|c| c.path().map(|x| x.clone()))
else {
return; return;
}; };
let rev = self.rev(); let rev = self.rev();
let doc = self.clone(); let doc = self.clone();
let scope = self.scope;
let proxy = self.common.proxy.clone();
let format = config.editor.format_on_save;
exec_after( exec_after(
Duration::from_millis(config.editor.autosave_interval), Duration::from_millis(config.editor.autosave_interval),
move |_| { move |_| {
@ -701,7 +723,26 @@ fn check_auto_save(&self) {
return; return;
} }
doc.save(|| {}); if format {
let send = create_ext_action(scope, move |result| {
let current_rev = doc.rev();
if current_rev != rev {
return;
}
if let Ok(ProxyResponse::GetDocumentFormatting {
edits,
}) = result
{
doc.do_text_edit(&edits);
}
doc.save(|| {});
});
proxy.get_document_formatting(path, move |result| {
send(result);
});
} else {
doc.save(|| {});
}
}, },
); );
} }