on master help sign in
Format document on save
commit2c48d65b1565cf68a3efb5c9e91e9011526f43e7 authorBlaž Hrastnik <blaz@mxxn.io> dateSun 30 May 2021, 00:00 (5 years ago) parentd5466ed
2 files changed+28−22
helix-term/src/commands.rs+5−22 helix-view/src/document.rs+23
helix-term/src/commands.rs+5−22
@@ -890,12 +890,12 @@ mod cmd {
890890 }
891891
892892 fn write(editor: &mut Editor, args: &[&str], event: PromptEvent) {
893− let id = editor.view().doc;
894− let doc = &mut editor.documents[id];
893+ let (view, doc) = editor.current();
895894 if doc.path().is_none() {
896895 editor.set_error("cannot write a buffer without a filename".to_string());
897896 return;
898897 }
898+ doc.format(view.id); // TODO: merge into save
899899 tokio::spawn(doc.save());
900900 }
901901
@@ -906,25 +906,7 @@ mod cmd {
906906 fn format(editor: &mut Editor, args: &[&str], event: PromptEvent) {
907907 let (view, doc) = editor.current();
908908
909− if let Some(language_server) = doc.language_server() {
910− // TODO: await, no blocking
911− let transaction = helix_lsp::block_on(
912− language_server
913− .text_document_formatting(doc.identifier(), lsp::FormattingOptions::default()),
914− )
915− .map(|edits| {
916− helix_lsp::util::generate_transaction_from_edits(
917− doc.text(),
918− edits,
919− language_server.offset_encoding(),
920− )
921− });
922−
923− if let Ok(transaction) = transaction {
924− doc.apply(&transaction, view.id);
925− doc.append_changes_to_history(view.id);
926− }
927− }
909+ doc.format(view.id)
928910 }
929911
930912 pub const COMMAND_LIST: &[Command] = &[
@@ -2277,7 +2259,8 @@ pub fn space_mode(cx: &mut Context) {
22772259 'v' => vsplit(cx),
22782260 'w' => {
22792261 // save current buffer
2280− let doc = cx.doc();
2262+ let (view, doc) = cx.current();
2263+ doc.format(view.id); // TODO: merge into save
22812264 tokio::spawn(doc.save());
22822265 }
22832266 'c' => {
helix-view/src/document.rs+23
@@ -116,6 +116,29 @@ impl Document {
116116 Ok(doc)
117117 }
118118
119+ // TODO: remove view_id dependency here
120+ pub fn format(&mut self, view_id: ViewId) {
121+ if let Some(language_server) = self.language_server() {
122+ // TODO: await, no blocking
123+ let transaction = helix_lsp::block_on(
124+ language_server
125+ .text_document_formatting(self.identifier(), lsp::FormattingOptions::default()),
126+ )
127+ .map(|edits| {
128+ helix_lsp::util::generate_transaction_from_edits(
129+ self.text(),
130+ edits,
131+ language_server.offset_encoding(),
132+ )
133+ });
134+
135+ if let Ok(transaction) = transaction {
136+ self.apply(&transaction, view_id);
137+ self.append_changes_to_history(view_id);
138+ }
139+ }
140+ }
141+
119142 // TODO: do we need some way of ensuring two save operations on the same doc can't run at once?
120143 // or is that handled by the OS/async layer
121144 pub fn save(&mut self) -> impl Future<Output = Result<(), anyhow::Error>> {