on master help sign in
Show surround delete and replace errors in editor (#1709)

* Refactor surround commands to use early returns * Show surround delete and replace errors in editor

commitc15996aff597aa8cb63850c6080bc69470bb84a5 authorGokul Soumya <gokulps15@gmail.com> dateMon 28 Feb 2022, 14:26 (5 years ago) parentf9ad1ca
2 files changed+141−92
helix-core/src/surround.rs+73−38 helix-term/src/commands.rs+68−54
helix-core/src/surround.rs+73−38
@@ -1,3 +1,5 @@
1+use std::fmt::Display;
2+
13use crate::{search, Range, Selection};
24use ropey::RopeSlice;
35
@@ -11,6 +13,27 @@ pub const PAIRS: &[(char, char)] = &[
1113 ('(', ')'),
1214];
1315
16+#[derive(Debug, PartialEq)]
17+pub enum Error {
18+ PairNotFound,
19+ CursorOverlap,
20+ RangeExceedsText,
21+ CursorOnAmbiguousPair,
22+}
23+
24+impl Display for Error {
25+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26+ f.write_str(match *self {
27+ Error::PairNotFound => "Surround pair not found around all cursors",
28+ Error::CursorOverlap => "Cursors overlap for a single surround pair range",
29+ Error::RangeExceedsText => "Cursor range exceeds text length",
30+ Error::CursorOnAmbiguousPair => "Cursor on ambiguous surround pair",
31+ })
32+ }
33+}
34+
35+type Result<T> = std::result::Result<T, Error>;
36+
1437/// Given any char in [PAIRS], return the open and closing chars. If not found in
1538/// [PAIRS] return (ch, ch).
1639///
@@ -37,31 +60,36 @@ pub fn find_nth_pairs_pos(
3760 ch: char,
3861 range: Range,
3962 n: usize,
40−) -> Option<(usize, usize)> {
41− if text.len_chars() < 2 || range.to() >= text.len_chars() {
42− return None;
63+) -> Result<(usize, usize)> {
64+ if text.len_chars() < 2 {
65+ return Err(Error::PairNotFound);
66+ }
67+ if range.to() >= text.len_chars() {
68+ return Err(Error::RangeExceedsText);
4369 }
4470
4571 let (open, close) = get_pair(ch);
4672 let pos = range.cursor(text);
4773
48− if open == close {
74+ let (open, close) = if open == close {
4975 if Some(open) == text.get_char(pos) {
5076 // Cursor is directly on match char. We return no match
5177 // because there's no way to know which side of the char
5278 // we should be searching on.
53− return None;
79+ return Err(Error::CursorOnAmbiguousPair);
5480 }
55− Some((
56− search::find_nth_prev(text, open, pos, n)?,
57− search::find_nth_next(text, close, pos, n)?,
58− ))
81+ (
82+ search::find_nth_prev(text, open, pos, n),
83+ search::find_nth_next(text, close, pos, n),
84+ )
5985 } else {
60− Some((
61− find_nth_open_pair(text, open, close, pos, n)?,
62− find_nth_close_pair(text, open, close, pos, n)?,
63− ))
64− }
86+ (
87+ find_nth_open_pair(text, open, close, pos, n),
88+ find_nth_close_pair(text, open, close, pos, n),
89+ )
90+ };
91+
92+ Option::zip(open, close).ok_or(Error::PairNotFound)
6593}
6694
6795fn find_nth_open_pair(
@@ -151,17 +179,17 @@ pub fn get_surround_pos(
151179 selection: &Selection,
152180 ch: char,
153181 skip: usize,
154−) -> Option<Vec<usize>> {
182+) -> Result<Vec<usize>> {
155183 let mut change_pos = Vec::new();
156184
157185 for &range in selection {
158186 let (open_pos, close_pos) = find_nth_pairs_pos(text, ch, range, skip)?;
159187 if change_pos.contains(&open_pos) || change_pos.contains(&close_pos) {
160− return None;
188+ return Err(Error::CursorOverlap);
161189 }
162190 change_pos.extend_from_slice(&[open_pos, close_pos]);
163191 }
164− Some(change_pos)
192+ Ok(change_pos)
165193}
166194
167195#[cfg(test)]
@@ -175,7 +203,7 @@ mod test {
175203 #[allow(clippy::type_complexity)]
176204 fn check_find_nth_pair_pos(
177205 text: &str,
178− cases: Vec<(usize, char, usize, Option<(usize, usize)>)>,
206+ cases: Vec<(usize, char, usize, Result<(usize, usize)>)>,
179207 ) {
180208 let doc = Rope::from(text);
181209 let slice = doc.slice(..);
@@ -196,13 +224,13 @@ mod test {
196224 "some (text) here",
197225 vec![
198226 // cursor on [t]ext
199− (6, '(', 1, Some((5, 10))),
200− (6, ')', 1, Some((5, 10))),
227+ (6, '(', 1, Ok((5, 10))),
228+ (6, ')', 1, Ok((5, 10))),
201229 // cursor on so[m]e
202− (2, '(', 1, None),
230+ (2, '(', 1, Err(Error::PairNotFound)),
203231 // cursor on bracket itself
204− (5, '(', 1, Some((5, 10))),
205− (10, '(', 1, Some((5, 10))),
232+ (5, '(', 1, Ok((5, 10))),
233+ (10, '(', 1, Ok((5, 10))),
206234 ],
207235 );
208236 }
@@ -213,9 +241,9 @@ mod test {
213241 "(so (many (good) text) here)",
214242 vec![
215243 // cursor on go[o]d
216− (13, '(', 1, Some((10, 15))),
217− (13, '(', 2, Some((4, 21))),
218− (13, '(', 3, Some((0, 27))),
244+ (13, '(', 1, Ok((10, 15))),
245+ (13, '(', 2, Ok((4, 21))),
246+ (13, '(', 3, Ok((0, 27))),
219247 ],
220248 );
221249 }
@@ -226,11 +254,11 @@ mod test {
226254 "'so 'many 'good' text' here'",
227255 vec![
228256 // cursor on go[o]d
229− (13, '\'', 1, Some((10, 15))),
230− (13, '\'', 2, Some((4, 21))),
231− (13, '\'', 3, Some((0, 27))),
257+ (13, '\'', 1, Ok((10, 15))),
258+ (13, '\'', 2, Ok((4, 21))),
259+ (13, '\'', 3, Ok((0, 27))),
232260 // cursor on the quotes
233− (10, '\'', 1, None),
261+ (10, '\'', 1, Err(Error::CursorOnAmbiguousPair)),
234262 ],
235263 )
236264 }
@@ -241,8 +269,8 @@ mod test {
241269 "((so)((many) good (text))(here))",
242270 vec![
243271 // cursor on go[o]d
244− (15, '(', 1, Some((5, 24))),
245− (15, '(', 2, Some((0, 31))),
272+ (15, '(', 1, Ok((5, 24))),
273+ (15, '(', 2, Ok((0, 31))),
246274 ],
247275 )
248276 }
@@ -253,9 +281,9 @@ mod test {
253281 "(so [many {good} text] here)",
254282 vec![
255283 // cursor on go[o]d
256− (13, '{', 1, Some((10, 15))),
257− (13, '[', 1, Some((4, 21))),
258− (13, '(', 1, Some((0, 27))),
284+ (13, '{', 1, Ok((10, 15))),
285+ (13, '[', 1, Ok((4, 21))),
286+ (13, '(', 1, Ok((0, 27))),
259287 ],
260288 )
261289 }
@@ -285,11 +313,10 @@ mod test {
285313
286314 let selection =
287315 Selection::new(SmallVec::from_slice(&[Range::point(2), Range::point(9)]), 0);
288−
289316 // cursor on s[o]me, c[h]ars
290317 assert_eq!(
291318 get_surround_pos(slice, &selection, '(', 1),
292− None // different surround chars
319+ Err(Error::PairNotFound) // different surround chars
293320 );
294321
295322 let selection = Selection::new(
@@ -299,7 +326,15 @@ mod test {
299326 // cursor on [x]x, newli[n]e
300327 assert_eq!(
301328 get_surround_pos(slice, &selection, '(', 1),
302− None // overlapping surround chars
329+ Err(Error::PairNotFound) // overlapping surround chars
330+ );
331+
332+ let selection =
333+ Selection::new(SmallVec::from_slice(&[Range::point(2), Range::point(3)]), 0);
334+ // cursor on s[o][m]e
335+ assert_eq!(
336+ get_surround_pos(slice, &selection, '[', 1),
337+ Err(Error::CursorOverlap)
303338 );
304339 }
305340}
helix-term/src/commands.rs+68−54
@@ -5407,76 +5407,90 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
54075407
54085408fn surround_add(cx: &mut Context) {
54095409 cx.on_next_key(move |cx, event| {
5410− if let Some(ch) = event.char() {
5411− let (view, doc) = current!(cx.editor);
5412− let selection = doc.selection(view.id);
5413− let (open, close) = surround::get_pair(ch);
5414−
5415− let mut changes = Vec::with_capacity(selection.len() * 2);
5416− for range in selection.iter() {
5417− let mut o = Tendril::new();
5418− o.push(open);
5419− let mut c = Tendril::new();
5420− c.push(close);
5421− changes.push((range.from(), range.from(), Some(o)));
5422− changes.push((range.to(), range.to(), Some(c)));
5423− }
5424−
5425− let transaction = Transaction::change(doc.text(), changes.into_iter());
5426− doc.apply(&transaction, view.id);
5410+ let ch = match event.char() {
5411+ Some(ch) => ch,
5412+ None => return,
5413+ };
5414+ let (view, doc) = current!(cx.editor);
5415+ let selection = doc.selection(view.id);
5416+ let (open, close) = surround::get_pair(ch);
5417+
5418+ let mut changes = Vec::with_capacity(selection.len() * 2);
5419+ for range in selection.iter() {
5420+ let mut o = Tendril::new();
5421+ o.push(open);
5422+ let mut c = Tendril::new();
5423+ c.push(close);
5424+ changes.push((range.from(), range.from(), Some(o)));
5425+ changes.push((range.to(), range.to(), Some(c)));
54275426 }
5427+
5428+ let transaction = Transaction::change(doc.text(), changes.into_iter());
5429+ doc.apply(&transaction, view.id);
54285430 })
54295431}
54305432
54315433fn surround_replace(cx: &mut Context) {
54325434 let count = cx.count();
54335435 cx.on_next_key(move |cx, event| {
5434− if let Some(from) = event.char() {
5435− cx.on_next_key(move |cx, event| {
5436− if let Some(to) = event.char() {
5437− let (view, doc) = current!(cx.editor);
5438− let text = doc.text().slice(..);
5439− let selection = doc.selection(view.id);
5440−
5441− let change_pos = match surround::get_surround_pos(text, selection, from, count)
5442− {
5443− Some(c) => c,
5444− None => return,
5445− };
5436+ let from = match event.char() {
5437+ Some(from) => from,
5438+ None => return,
5439+ };
5440+ let (view, doc) = current!(cx.editor);
5441+ let text = doc.text().slice(..);
5442+ let selection = doc.selection(view.id);
54465443
5447− let (open, close) = surround::get_pair(to);
5448− let transaction = Transaction::change(
5449− doc.text(),
5450− change_pos.iter().enumerate().map(|(i, &pos)| {
5451− let mut t = Tendril::new();
5452− t.push(if i % 2 == 0 { open } else { close });
5453− (pos, pos + 1, Some(t))
5454− }),
5455− );
5456− doc.apply(&transaction, view.id);
5457− }
5458− });
5459− }
5444+ let change_pos = match surround::get_surround_pos(text, selection, from, count) {
5445+ Ok(c) => c,
5446+ Err(err) => {
5447+ cx.editor.set_error(err.to_string());
5448+ return;
5449+ }
5450+ };
5451+
5452+ cx.on_next_key(move |cx, event| {
5453+ let (view, doc) = current!(cx.editor);
5454+ let to = match event.char() {
5455+ Some(to) => to,
5456+ None => return,
5457+ };
5458+ let (open, close) = surround::get_pair(to);
5459+ let transaction = Transaction::change(
5460+ doc.text(),
5461+ change_pos.iter().enumerate().map(|(i, &pos)| {
5462+ let mut t = Tendril::new();
5463+ t.push(if i % 2 == 0 { open } else { close });
5464+ (pos, pos + 1, Some(t))
5465+ }),
5466+ );
5467+ doc.apply(&transaction, view.id);
5468+ });
54605469 })
54615470}
54625471
54635472fn surround_delete(cx: &mut Context) {
54645473 let count = cx.count();
54655474 cx.on_next_key(move |cx, event| {
5466− if let Some(ch) = event.char() {
5467− let (view, doc) = current!(cx.editor);
5468− let text = doc.text().slice(..);
5469− let selection = doc.selection(view.id);
5475+ let ch = match event.char() {
5476+ Some(ch) => ch,
5477+ None => return,
5478+ };
5479+ let (view, doc) = current!(cx.editor);
5480+ let text = doc.text().slice(..);
5481+ let selection = doc.selection(view.id);
54705482
5471− let change_pos = match surround::get_surround_pos(text, selection, ch, count) {
5472− Some(c) => c,
5473− None => return,
5474− };
5483+ let change_pos = match surround::get_surround_pos(text, selection, ch, count) {
5484+ Ok(c) => c,
5485+ Err(err) => {
5486+ cx.editor.set_error(err.to_string());
5487+ return;
5488+ }
5489+ };
54755490
5476− let transaction =
5477− Transaction::change(doc.text(), change_pos.into_iter().map(|p| (p, p + 1, None)));
5478− doc.apply(&transaction, view.id);
5479− }
5491+ let transaction =
5492+ Transaction::change(doc.text(), change_pos.into_iter().map(|p| (p, p + 1, None)));
5493+ doc.apply(&transaction, view.id);
54805494 })
54815495}
54825496