diff --git a/lapce-app/src/doc.rs b/lapce-app/src/doc.rs index 22da4a56..85bc76c7 100644 --- a/lapce-app/src/doc.rs +++ b/lapce-app/src/doc.rs @@ -67,7 +67,7 @@ }; use lsp_types::{ CodeActionOrCommand, CodeLens, Diagnostic, DiagnosticSeverity, - DocumentSymbolResponse, InlayHint, InlayHintLabel, + DocumentSymbolResponse, InlayHint, InlayHintLabel, TextEdit, }; use serde::{Deserialize, Serialize}; 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::>(); + edits + }); + self.do_raw_edit(&edits, EditType::Completion); + } + fn check_auto_save(&self) { let config = self.common.config.get_untracked(); 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; }; let rev = self.rev(); let doc = self.clone(); + let scope = self.scope; + let proxy = self.common.proxy.clone(); + let format = config.editor.format_on_save; exec_after( Duration::from_millis(config.editor.autosave_interval), move |_| { @@ -701,7 +723,26 @@ fn check_auto_save(&self) { 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(|| {}); + } }, ); }