on master help sign in
Show surround delete and replace errors in editor (#1709)
c15996aGokul Soumya
helix-core/src/surround.rs+73−38
@@ -1,3 +1,5 @@
1+use std::fmt::Display;
2+
1use crate::{search, Range, Selection};
3use crate::{search, Range, Selection};
2use ropey::RopeSlice;
4use ropey::RopeSlice;
3
5
@@ -11,6 +13,27 @@ pub const PAIRS: &[(char, char)] = &[
11 ('(', ')'),
13 ('(', ')'),
12];
14];
13
15
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+
14/// Given any char in [PAIRS], return the open and closing chars. If not found in
37/// Given any char in [PAIRS], return the open and closing chars. If not found in
15/// [PAIRS] return (ch, ch).
38/// [PAIRS] return (ch, ch).
16///
39///
@@ -37,31 +60,36 @@ pub fn find_nth_pairs_pos(
37 ch: char,
60 ch: char,
38 range: Range,
61 range: Range,
39 n: usize,
62 n: usize,
40−) -> Option<(usize, usize)> {
63+) -> Result<(usize, usize)> {
64+ if text.len_chars() < 2 {
65+ return Err(Error::PairNotFound);
66+ }
41− if text.len_chars() < 2 || range.to() >= text.len_chars() {
67+ if range.to() >= text.len_chars() {
42− return None;
68+ return Err(Error::RangeExceedsText);
43 }
69 }
44
70
45 let (open, close) = get_pair(ch);
71 let (open, close) = get_pair(ch);
46 let pos = range.cursor(text);
72 let pos = range.cursor(text);
47
73
48− if open == close {
74+ let (open, close) = if open == close {
49 if Some(open) == text.get_char(pos) {
75 if Some(open) == text.get_char(pos) {
50 // Cursor is directly on match char. We return no match
76 // Cursor is directly on match char. We return no match
51 // because there's no way to know which side of the char
77 // because there's no way to know which side of the char
52 // we should be searching on.
78 // we should be searching on.
53− return None;
79+ return Err(Error::CursorOnAmbiguousPair);
54 }
80 }
55− Some((
81+ (
56− search::find_nth_prev(text, open, pos, n)?,
82+ search::find_nth_prev(text, open, pos, n),
57− search::find_nth_next(text, close, pos, n)?,
83+ search::find_nth_next(text, close, pos, n),
58− ))
84+ )
59 } else {
85 } else {
60− Some((
86+ (
61− find_nth_open_pair(text, open, close, pos, n)?,
87+ find_nth_open_pair(text, open, close, pos, n),
62− find_nth_close_pair(text, open, close, pos, n)?,
88+ find_nth_close_pair(text, open, close, pos, n),
63− ))
89+ )
64− }
90+ };
91+
92+ Option::zip(open, close).ok_or(Error::PairNotFound)
65}
93}
66
94
67fn find_nth_open_pair(
95fn find_nth_open_pair(
@@ -151,17 +179,17 @@ pub fn get_surround_pos(
151 selection: &Selection,
179 selection: &Selection,
152 ch: char,
180 ch: char,
153 skip: usize,
181 skip: usize,
154−) -> Option<Vec<usize>> {
182+) -> Result<Vec<usize>> {
155 let mut change_pos = Vec::new();
183 let mut change_pos = Vec::new();
156
184
157 for &range in selection {
185 for &range in selection {
158 let (open_pos, close_pos) = find_nth_pairs_pos(text, ch, range, skip)?;
186 let (open_pos, close_pos) = find_nth_pairs_pos(text, ch, range, skip)?;
159 if change_pos.contains(&open_pos) || change_pos.contains(&close_pos) {
187 if change_pos.contains(&open_pos) || change_pos.contains(&close_pos) {
160− return None;
188+ return Err(Error::CursorOverlap);
161 }
189 }
162 change_pos.extend_from_slice(&[open_pos, close_pos]);
190 change_pos.extend_from_slice(&[open_pos, close_pos]);
163 }
191 }
164− Some(change_pos)
192+ Ok(change_pos)
165}
193}
166
194
167#[cfg(test)]
195#[cfg(test)]
@@ -175,7 +203,7 @@ mod test {
175 #[allow(clippy::type_complexity)]
203 #[allow(clippy::type_complexity)]
176 fn check_find_nth_pair_pos(
204 fn check_find_nth_pair_pos(
177 text: &str,
205 text: &str,
178− cases: Vec<(usize, char, usize, Option<(usize, usize)>)>,
206+ cases: Vec<(usize, char, usize, Result<(usize, usize)>)>,
179 ) {
207 ) {
180 let doc = Rope::from(text);
208 let doc = Rope::from(text);
181 let slice = doc.slice(..);
209 let slice = doc.slice(..);
@@ -196,13 +224,13 @@ mod test {
196 "some (text) here",
224 "some (text) here",
197 vec![
225 vec![
198 // cursor on [t]ext
226 // cursor on [t]ext
199− (6, '(', 1, Some((5, 10))),
227+ (6, '(', 1, Ok((5, 10))),
200− (6, ')', 1, Some((5, 10))),
228+ (6, ')', 1, Ok((5, 10))),
201 // cursor on so[m]e
229 // cursor on so[m]e
202− (2, '(', 1, None),
230+ (2, '(', 1, Err(Error::PairNotFound)),
203 // cursor on bracket itself
231 // cursor on bracket itself
204− (5, '(', 1, Some((5, 10))),
232+ (5, '(', 1, Ok((5, 10))),
205− (10, '(', 1, Some((5, 10))),
233+ (10, '(', 1, Ok((5, 10))),
206 ],
234 ],
207 );
235 );
208 }
236 }
@@ -213,9 +241,9 @@ mod test {
213 "(so (many (good) text) here)",
241 "(so (many (good) text) here)",
214 vec![
242 vec![
215 // cursor on go[o]d
243 // cursor on go[o]d
216− (13, '(', 1, Some((10, 15))),
244+ (13, '(', 1, Ok((10, 15))),
217− (13, '(', 2, Some((4, 21))),
245+ (13, '(', 2, Ok((4, 21))),
218− (13, '(', 3, Some((0, 27))),
246+ (13, '(', 3, Ok((0, 27))),
219 ],
247 ],
220 );
248 );
221 }
249 }
@@ -226,11 +254,11 @@ mod test {
226 "'so 'many 'good' text' here'",
254 "'so 'many 'good' text' here'",
227 vec![
255 vec![
228 // cursor on go[o]d
256 // cursor on go[o]d
229− (13, '\'', 1, Some((10, 15))),
257+ (13, '\'', 1, Ok((10, 15))),
230− (13, '\'', 2, Some((4, 21))),
258+ (13, '\'', 2, Ok((4, 21))),
231− (13, '\'', 3, Some((0, 27))),
259+ (13, '\'', 3, Ok((0, 27))),
232 // cursor on the quotes
260 // cursor on the quotes
233− (10, '\'', 1, None),
261+ (10, '\'', 1, Err(Error::CursorOnAmbiguousPair)),
234 ],
262 ],
235 )
263 )
236 }
264 }
@@ -241,8 +269,8 @@ mod test {
241 "((so)((many) good (text))(here))",
269 "((so)((many) good (text))(here))",
242 vec![
270 vec![
243 // cursor on go[o]d
271 // cursor on go[o]d
244− (15, '(', 1, Some((5, 24))),
272+ (15, '(', 1, Ok((5, 24))),
245− (15, '(', 2, Some((0, 31))),
273+ (15, '(', 2, Ok((0, 31))),
246 ],
274 ],
247 )
275 )
248 }
276 }
@@ -253,9 +281,9 @@ mod test {
253 "(so [many {good} text] here)",
281 "(so [many {good} text] here)",
254 vec![
282 vec![
255 // cursor on go[o]d
283 // cursor on go[o]d
256− (13, '{', 1, Some((10, 15))),
284+ (13, '{', 1, Ok((10, 15))),
257− (13, '[', 1, Some((4, 21))),
285+ (13, '[', 1, Ok((4, 21))),
258− (13, '(', 1, Some((0, 27))),
286+ (13, '(', 1, Ok((0, 27))),
259 ],
287 ],
260 )
288 )
261 }
289 }
@@ -285,11 +313,10 @@ mod test {
285
313
286 let selection =
314 let selection =
287 Selection::new(SmallVec::from_slice(&[Range::point(2), Range::point(9)]), 0);
315 Selection::new(SmallVec::from_slice(&[Range::point(2), Range::point(9)]), 0);
288−
289 // cursor on s[o]me, c[h]ars
316 // cursor on s[o]me, c[h]ars
290 assert_eq!(
317 assert_eq!(
291 get_surround_pos(slice, &selection, '(', 1),
318 get_surround_pos(slice, &selection, '(', 1),
292− None // different surround chars
319+ Err(Error::PairNotFound) // different surround chars
293 );
320 );
294
321
295 let selection = Selection::new(
322 let selection = Selection::new(
@@ -299,7 +326,15 @@ mod test {
299 // cursor on [x]x, newli[n]e
326 // cursor on [x]x, newli[n]e
300 assert_eq!(
327 assert_eq!(
301 get_surround_pos(slice, &selection, '(', 1),
328 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)
303 );
338 );
304 }
339 }
305}
340}
helix-term/src/commands.rs+68−54
@@ -5407,76 +5407,90 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
5407
5407
5408fn surround_add(cx: &mut Context) {
5408fn surround_add(cx: &mut Context) {
5409 cx.on_next_key(move |cx, event| {
5409 cx.on_next_key(move |cx, event| {
5410− if let Some(ch) = event.char() {
5410+ let ch = match event.char() {
5411+ Some(ch) => ch,
5412+ None => return,
5413+ };
5411− let (view, doc) = current!(cx.editor);
5414+ let (view, doc) = current!(cx.editor);
5412− let selection = doc.selection(view.id);
5415+ let selection = doc.selection(view.id);
5413− let (open, close) = surround::get_pair(ch);
5416+ let (open, close) = surround::get_pair(ch);
5414−
5417+
5415− let mut changes = Vec::with_capacity(selection.len() * 2);
5418+ let mut changes = Vec::with_capacity(selection.len() * 2);
5416− for range in selection.iter() {
5419+ for range in selection.iter() {
5417− let mut o = Tendril::new();
5420+ let mut o = Tendril::new();
5418− o.push(open);
5421+ o.push(open);
5419− let mut c = Tendril::new();
5422+ let mut c = Tendril::new();
5420− c.push(close);
5423+ c.push(close);
5421− changes.push((range.from(), range.from(), Some(o)));
5424+ changes.push((range.from(), range.from(), Some(o)));
5422− changes.push((range.to(), range.to(), Some(c)));
5425+ 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);
5427 }
5426 }
5427+
5428+ let transaction = Transaction::change(doc.text(), changes.into_iter());
5429+ doc.apply(&transaction, view.id);
5428 })
5430 })
5429}
5431}
5430
5432
5431fn surround_replace(cx: &mut Context) {
5433fn surround_replace(cx: &mut Context) {
5432 let count = cx.count();
5434 let count = cx.count();
5433 cx.on_next_key(move |cx, event| {
5435 cx.on_next_key(move |cx, event| {
5434− if let Some(from) = event.char() {
5436+ let from = match event.char() {
5435− cx.on_next_key(move |cx, event| {
5437+ Some(from) => from,
5436− if let Some(to) = event.char() {
5438+ None => return,
5439+ };
5437− let (view, doc) = current!(cx.editor);
5440+ let (view, doc) = current!(cx.editor);
5438− let text = doc.text().slice(..);
5441+ let text = doc.text().slice(..);
5439− let selection = doc.selection(view.id);
5442+ 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− };
5446
5443
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+ };
5447− let (open, close) = surround::get_pair(to);
5458+ let (open, close) = surround::get_pair(to);
5448− let transaction = Transaction::change(
5459+ let transaction = Transaction::change(
5449− doc.text(),
5460+ doc.text(),
5450− change_pos.iter().enumerate().map(|(i, &pos)| {
5461+ change_pos.iter().enumerate().map(|(i, &pos)| {
5451− let mut t = Tendril::new();
5462+ let mut t = Tendril::new();
5452− t.push(if i % 2 == 0 { open } else { close });
5463+ t.push(if i % 2 == 0 { open } else { close });
5453− (pos, pos + 1, Some(t))
5464+ (pos, pos + 1, Some(t))
5454− }),
5465+ }),
5455− );
5466+ );
5456− doc.apply(&transaction, view.id);
5467+ doc.apply(&transaction, view.id);
5457− }
5458− });
5468+ });
5459− }
5460 })
5469 })
5461}
5470}
5462
5471
5463fn surround_delete(cx: &mut Context) {
5472fn surround_delete(cx: &mut Context) {
5464 let count = cx.count();
5473 let count = cx.count();
5465 cx.on_next_key(move |cx, event| {
5474 cx.on_next_key(move |cx, event| {
5466− if let Some(ch) = event.char() {
5475+ let ch = match event.char() {
5476+ Some(ch) => ch,
5477+ None => return,
5478+ };
5467− let (view, doc) = current!(cx.editor);
5479+ let (view, doc) = current!(cx.editor);
5468− let text = doc.text().slice(..);
5480+ let text = doc.text().slice(..);
5469− let selection = doc.selection(view.id);
5481+ let selection = doc.selection(view.id);
5470
5482
5471− let change_pos = match surround::get_surround_pos(text, selection, ch, count) {
5483+ let change_pos = match surround::get_surround_pos(text, selection, ch, count) {
5472− Some(c) => c,
5484+ Ok(c) => c,
5485+ Err(err) => {
5486+ cx.editor.set_error(err.to_string());
5473− None => return,
5487+ return;
5474− };
5488+ }
5489+ };
5475
5490
5476− let transaction =
5491+ let transaction =
5477− Transaction::change(doc.text(), change_pos.into_iter().map(|p| (p, p + 1, None)));
5492+ Transaction::change(doc.text(), change_pos.into_iter().map(|p| (p, p + 1, None)));
5478− doc.apply(&transaction, view.id);
5493+ doc.apply(&transaction, view.id);
5479− }
5480 })
5494 })
5481}
5495}
5482
5496