rust-analyzer/crates/ra_text_edit/src/text_edit.rs

82 lines
2.4 KiB
Rust
Raw Normal View History

use crate::AtomTextEdit;
use text_unit::{TextRange, TextUnit};
2018-08-12 15:50:16 +00:00
2018-08-12 23:38:34 +00:00
#[derive(Debug, Clone)]
pub struct TextEdit {
atoms: Vec<AtomTextEdit>,
2018-08-12 15:50:16 +00:00
}
2019-01-03 15:59:17 +00:00
#[derive(Debug, Default)]
pub struct TextEditBuilder {
atoms: Vec<AtomTextEdit>,
2018-08-12 15:50:16 +00:00
}
impl TextEditBuilder {
2018-08-25 09:44:26 +00:00
pub fn replace(&mut self, range: TextRange, replace_with: String) {
self.atoms.push(AtomTextEdit::replace(range, replace_with))
2018-08-12 15:50:16 +00:00
}
pub fn delete(&mut self, range: TextRange) {
self.atoms.push(AtomTextEdit::delete(range))
2018-08-12 15:50:16 +00:00
}
pub fn insert(&mut self, offset: TextUnit, text: String) {
self.atoms.push(AtomTextEdit::insert(offset, text))
2018-08-12 15:50:16 +00:00
}
pub fn finish(self) -> TextEdit {
2018-12-24 16:01:25 +00:00
TextEdit::from_atoms(self.atoms)
2018-08-12 15:50:16 +00:00
}
2018-08-29 15:35:28 +00:00
pub fn invalidates_offset(&self, offset: TextUnit) -> bool {
2019-02-08 11:49:43 +00:00
self.atoms.iter().any(|atom| atom.delete.contains_inclusive(offset))
2018-08-29 15:35:28 +00:00
}
2018-08-12 15:50:16 +00:00
}
impl TextEdit {
2018-12-24 16:01:25 +00:00
pub(crate) fn from_atoms(mut atoms: Vec<AtomTextEdit>) -> TextEdit {
atoms.sort_by_key(|a| (a.delete.start(), a.delete.end()));
for (a1, a2) in atoms.iter().zip(atoms.iter().skip(1)) {
assert!(a1.delete.end() <= a2.delete.start())
}
TextEdit { atoms }
}
2018-12-21 08:24:16 +00:00
pub fn as_atoms(&self) -> &[AtomTextEdit] {
&self.atoms
2018-08-12 23:38:34 +00:00
}
2018-08-12 15:50:16 +00:00
pub fn apply(&self, text: &str) -> String {
2018-08-12 23:38:34 +00:00
let mut total_len = text.len();
2018-08-12 15:50:16 +00:00
for atom in self.atoms.iter() {
2018-08-12 23:38:34 +00:00
total_len += atom.insert.len();
2018-08-25 09:44:26 +00:00
total_len -= u32::from(atom.delete.end() - atom.delete.start()) as usize;
2018-08-12 15:50:16 +00:00
}
2018-08-12 23:38:34 +00:00
let mut buf = String::with_capacity(total_len);
let mut prev = 0;
for atom in self.atoms.iter() {
2018-08-25 09:44:26 +00:00
let start = u32::from(atom.delete.start()) as usize;
let end = u32::from(atom.delete.end()) as usize;
if start > prev {
buf.push_str(&text[prev..start]);
2018-08-12 23:38:34 +00:00
}
buf.push_str(&atom.insert);
2018-08-25 09:44:26 +00:00
prev = end;
2018-08-12 23:38:34 +00:00
}
buf.push_str(&text[prev..text.len()]);
assert_eq!(buf.len(), total_len);
buf
2018-08-12 15:50:16 +00:00
}
2018-08-15 20:24:20 +00:00
pub fn apply_to_offset(&self, offset: TextUnit) -> Option<TextUnit> {
let mut res = offset;
for atom in self.atoms.iter() {
if atom.delete.start() >= offset {
break;
}
if offset < atom.delete.end() {
return None;
2018-08-15 20:24:20 +00:00
}
res += TextUnit::of_str(&atom.insert);
res -= atom.delete.len();
}
Some(res)
}
2018-08-12 15:50:16 +00:00
}