Skip to content

Commit

Permalink
redetect indent and line endings after language server replaces document
Browse files Browse the repository at this point in the history
  • Loading branch information
farwyler committed Jun 20, 2022
1 parent ad15e7b commit 764d14f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
29 changes: 29 additions & 0 deletions helix-lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,35 @@ pub mod util {
generate_transaction_from_edits(&fmt.doc, fmt.edits, fmt.offset_encoding)
}
}

impl LspFormatting {
pub fn replaces_document(&self, old: &Rope) -> Option<&String> {
match &self.edits[..] {
[lsp::TextEdit {
range:
lsp::Range {
start:
lsp::Position {
line: 0,
character: 0,
},
end:
lsp::Position {
line: last_line, ..
},
},
new_text,
}] => {
if *last_line as usize >= old.len_lines() - 1 {
Some(new_text)
} else {
None
}
}
_ => None,
}
}
}
}

#[derive(Debug, PartialEq, Clone)]
Expand Down
15 changes: 11 additions & 4 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2326,10 +2326,17 @@ async fn make_format_callback(
let view_id = view!(editor).id;
if let Some(doc) = editor.document_mut(doc_id) {
if doc.version() == doc_version {
doc.apply(&Transaction::from(format), view_id);
doc.append_changes_to_history(view_id);
if let Modified::SetUnmodified = modified {
doc.reset_modified();
if let Some(text) = format.replaces_document(doc.text()) {
// the language server wants to replace the whole document. perform same behaviour as if reloading document from disk.
log::info!("formatting changes replace the whole document");
let rope = Rope::from_str(text);
doc.replace_content(view_id, &rope).unwrap();
} else {
doc.apply(&Transaction::from(format), view_id);
doc.append_changes_to_history(view_id);
if let Modified::SetUnmodified = modified {
doc.reset_modified();
}
}
} else {
log::info!("discarded formatting changes because the document changed");
Expand Down
7 changes: 6 additions & 1 deletion helix-view/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -549,10 +549,15 @@ impl Document {
let mut file = std::fs::File::open(path.unwrap())?;
let (rope, ..) = from_reader(&mut file, Some(encoding))?;

self.replace_content(view_id, &rope)
}

/// Replace the whole text.
pub fn replace_content(&mut self, view_id: ViewId, rope: &Rope) -> Result<(), Error> {
// Calculate the difference between the buffer and source text, and apply it.
// This is not considered a modification of the contents of the file regardless
// of the encoding.
let transaction = helix_core::diff::compare_ropes(self.text(), &rope);
let transaction = helix_core::diff::compare_ropes(self.text(), rope);
self.apply(&transaction, view_id);
self.append_changes_to_history(view_id);
self.reset_modified();
Expand Down

0 comments on commit 764d14f

Please sign in to comment.