@@ -23,17 +23,17 @@ use helix_core::{
2323 regex::{self, Regex, RegexBuilder},
2424 search::{self, CharMatcher},
2525 selection, shellwords, surround,
26+ syntax::LanguageServerFeature,
2627 text_annotations::TextAnnotations,
2728 textobject,
2829 tree_sitter::Node,
2930 unicode::width::UnicodeWidthChar,
30− visual_offset_from_block, LineEnding, Position, Range, Rope, RopeGraphemes, RopeSlice,
31− Selection, SmallVec, Tendril, Transaction,
31+ visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes,
32+ RopeReader, RopeSlice, Selection, SmallVec, Tendril, Transaction,
3233};
3334use helix_view::{
34− clipboard::ClipboardType,
3535 document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
36− editor::{Action, CompleteAction, Motion},
36+ editor::{Action, CompleteAction},
3737 info::Info,
3838 input::KeyEvent,
3939 keyboard::KeyCode,
@@ -43,7 +43,6 @@ use helix_view::{
4343};
4444
4545use anyhow::{anyhow, bail, ensure, Context as _};
46−use fuzzy_matcher::FuzzyMatcher;
4746use insert::*;
4847use movement::Movement;
4948
@@ -54,15 +53,20 @@ use crate::{
5453 job::Callback,
5554 keymap::ReverseKeymap,
5655 ui::{
57− self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, FilePicker, Picker,
56+ self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem, Picker,
5857 Popup, Prompt, PromptEvent,
5958 },
6059};
6160
6261use crate::job::{self, Jobs};
63−use futures_util::StreamExt;
64−use std::{collections::HashMap, fmt, future::Future};
65−use std::{collections::HashSet, num::NonZeroUsize};
62+use futures_util::{stream::FuturesUnordered, TryStreamExt};
63+use std::{
64+ collections::{HashMap, HashSet},
65+ fmt,
66+ future::Future,
67+ io::Read,
68+ num::NonZeroUsize,
69+};
6670
6771use std::{
6872 borrow::Cow,
@@ -71,11 +75,11 @@ use std::{
7175
7276use once_cell::sync::Lazy;
7377use serde::de::{self, Deserialize, Deserializer};
78+use url::Url;
7479
7580use grep_regex::RegexMatcherBuilder;
7681use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
7782use ignore::{DirEntry, WalkBuilder, WalkState};
78−use tokio_stream::wrappers::UnboundedReceiverStream;
7983
8084pub type OnKeyCallback = Box<dyn FnOnce(&mut Context, KeyEvent)>;
8185
@@ -246,6 +250,9 @@ impl MappableCommand {
246250 move_next_long_word_start, "Move to start of next long word",
247251 move_prev_long_word_start, "Move to start of previous long word",
248252 move_next_long_word_end, "Move to end of next long word",
253+ move_prev_long_word_end, "Move to end of previous long word",
254+ move_parent_node_end, "Move to end of the parent node",
255+ move_parent_node_start, "Move to beginning of the parent node",
249256 extend_next_word_start, "Extend to start of next word",
250257 extend_prev_word_start, "Extend to start of previous word",
251258 extend_next_word_end, "Extend to end of next word",
@@ -253,6 +260,9 @@ impl MappableCommand {
253260 extend_next_long_word_start, "Extend to start of next long word",
254261 extend_prev_long_word_start, "Extend to start of previous long word",
255262 extend_next_long_word_end, "Extend to end of next long word",
263+ extend_prev_long_word_end, "Extend to end of prev long word",
264+ extend_parent_node_end, "Extend to end of the parent node",
265+ extend_parent_node_start, "Extend to beginning of the parent node",
256266 find_till_char, "Move till next occurrence of char",
257267 find_next_char, "Move to next occurrence of char",
258268 extend_till_char, "Extend till next occurrence of char",
@@ -274,6 +284,7 @@ impl MappableCommand {
274284 select_regex, "Select all regex matches inside selections",
275285 split_selection, "Split selections on regex matches",
276286 split_selection_on_newline, "Split selection on newlines",
287+ merge_selections, "Merge selections",
277288 merge_consecutive_selections, "Merge consecutive selections",
278289 search, "Search for regex pattern",
279290 rsearch, "Reverse search for regex pattern",
@@ -326,7 +337,7 @@ impl MappableCommand {
326337 goto_implementation, "Goto implementation",
327338 goto_file_start, "Goto line number <n> else file start",
328339 goto_file_end, "Goto file end",
329− goto_file, "Goto files in selection",
340+ goto_file, "Goto files/URLs in selection",
330341 goto_file_hsplit, "Goto files in selection (hsplit)",
331342 goto_file_vsplit, "Goto files in selection (vsplit)",
332343 goto_reference, "Goto references",
@@ -358,6 +369,7 @@ impl MappableCommand {
358369 extend_to_line_end, "Extend to line end",
359370 extend_to_line_end_newline, "Extend to line end",
360371 signature_help, "Show signature help",
372+ smart_tab, "Insert tab if all cursors have all whitespace to their left; otherwise, run a separate command.",
361373 insert_tab, "Insert tab char",
362374 insert_newline, "Insert newline char",
363375 delete_char_backward, "Delete previous char",
@@ -372,6 +384,9 @@ impl MappableCommand {
372384 later, "Move forward in history",
373385 commit_undo_checkpoint, "Commit changes to new checkpoint",
374386 yank, "Yank selection",
387+ yank_to_clipboard, "Yank selections to clipboard",
388+ yank_to_primary_clipboard, "Yank selections to primary clipboard",
389+ yank_joined, "Join and yank selections",
375390 yank_joined_to_clipboard, "Join and yank selections to clipboard",
376391 yank_main_selection_to_clipboard, "Yank main selection to clipboard",
377392 yank_joined_to_primary_clipboard, "Join and yank selections to primary clipboard",
@@ -402,6 +417,7 @@ impl MappableCommand {
402417 rotate_selections_backward, "Rotate selections backward",
403418 rotate_selection_contents_forward, "Rotate selection contents forward",
404419 rotate_selection_contents_backward, "Rotate selections contents backward",
420+ reverse_selection_contents, "Reverse selections contents",
405421 expand_selection, "Expand selection to parent syntax node",
406422 shrink_selection, "Shrink selection to previously expanded syntax node",
407423 select_next_sibling, "Select next sibling in syntax tree",
@@ -795,54 +811,50 @@ fn extend_to_line_start(cx: &mut Context) {
795811}
796812
797813fn kill_to_line_start(cx: &mut Context) {
798− let (view, doc) = current!(cx.editor);
799− let text = doc.text().slice(..);
800−
801− let selection = doc.selection(view.id).clone().transform(|range| {
802− let line = range.cursor_line(text);
803− let first_char = text.line_to_char(line);
804− let anchor = range.cursor(text);
805− let head = if anchor == first_char && line != 0 {
806− // select until previous line
807− line_end_char_index(&text, line - 1)
808− } else if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
809− if first_char + pos < anchor {
810− // select until first non-blank in line if cursor is after it
811− first_char + pos
814+ delete_by_selection_insert_mode(
815+ cx,
816+ move |text, range| {
817+ let line = range.cursor_line(text);
818+ let first_char = text.line_to_char(line);
819+ let anchor = range.cursor(text);
820+ let head = if anchor == first_char && line != 0 {
821+ // select until previous line
822+ line_end_char_index(&text, line - 1)
823+ } else if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
824+ if first_char + pos < anchor {
825+ // select until first non-blank in line if cursor is after it
826+ first_char + pos
827+ } else {
828+ // select until start of line
829+ first_char
830+ }
812831 } else {
813832 // select until start of line
814833 first_char
815− }
816− } else {
817− // select until start of line
818− first_char
819− };
820− Range::new(head, anchor)
821− });
822− delete_selection_insert_mode(doc, view, &selection);
823−
824− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
834+ };
835+ (head, anchor)
836+ },
837+ Direction::Backward,
838+ );
825839}
826840
827841fn kill_to_line_end(cx: &mut Context) {
828− let (view, doc) = current!(cx.editor);
829− let text = doc.text().slice(..);
830−
831− let selection = doc.selection(view.id).clone().transform(|range| {
832− let line = range.cursor_line(text);
833− let line_end_pos = line_end_char_index(&text, line);
834− let pos = range.cursor(text);
835−
836− let mut new_range = range.put_cursor(text, line_end_pos, true);
837− // don't want to remove the line separator itself if the cursor doesn't reach the end of line.
838− if pos != line_end_pos {
839− new_range.head = line_end_pos;
840− }
841− new_range
842− });
843− delete_selection_insert_mode(doc, view, &selection);
842+ delete_by_selection_insert_mode(
843+ cx,
844+ |text, range| {
845+ let line = range.cursor_line(text);
846+ let line_end_pos = line_end_char_index(&text, line);
847+ let pos = range.cursor(text);
844848
845− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
849+ // if the cursor is on the newline char delete that
850+ if pos == line_end_pos {
851+ (pos, text.line_to_char(line + 1))
852+ } else {
853+ (pos, line_end_pos)
854+ }
855+ },
856+ Direction::Forward,
857+ );
846858}
847859
848860fn goto_first_nonwhitespace(cx: &mut Context) {
@@ -978,6 +990,7 @@ fn align_selections(cx: &mut Context) {
978990
979991 let transaction = Transaction::change(doc.text(), changes.into_iter());
980992 doc.apply(&transaction, view.id);
993+ exit_select_mode(cx);
981994}
982995
983996fn goto_window(cx: &mut Context, align: Align) {
@@ -1069,6 +1082,10 @@ fn move_prev_long_word_start(cx: &mut Context) {
10691082 move_word_impl(cx, movement::move_prev_long_word_start)
10701083}
10711084
1085+fn move_prev_long_word_end(cx: &mut Context) {
1086+ move_word_impl(cx, movement::move_prev_long_word_end)
1087+}
1088+
10721089fn move_next_long_word_end(cx: &mut Context) {
10731090 move_word_impl(cx, movement::move_next_long_word_end)
10741091}
@@ -1093,8 +1110,7 @@ where
10931110 .transform(|range| move_fn(text, range, count, behavior));
10941111 doc.set_selection(view.id, selection);
10951112 };
1096− motion(cx.editor);
1097− cx.editor.last_motion = Some(Motion(Box::new(motion)));
1113+ cx.editor.apply_motion(motion)
10981114}
10991115
11001116fn goto_prev_paragraph(cx: &mut Context) {
@@ -1149,6 +1165,10 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11491165 let (view, doc) = current_ref!(cx.editor);
11501166 let text = doc.text();
11511167 let selections = doc.selection(view.id);
1168+ let rel_path = doc
1169+ .relative_path()
1170+ .map(|path| path.parent().unwrap().to_path_buf())
1171+ .unwrap_or_default();
11521172 let mut paths: Vec<_> = selections
11531173 .iter()
11541174 .map(|r| text.slice(r.from()..r.to()).to_string())
@@ -1176,16 +1196,80 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11761196 .to_string(),
11771197 );
11781198 }
1199+
11791200 for sel in paths {
11801201 let p = sel.trim();
1181− if !p.is_empty() {
1182− if let Err(e) = cx.editor.open(&PathBuf::from(p), action) {
1202+ if p.is_empty() {
1203+ continue;
1204+ }
1205+
1206+ if let Ok(url) = Url::parse(p) {
1207+ return open_url(cx, url, action);
1208+ }
1209+
1210+ let path = &rel_path.join(p);
1211+ if path.is_dir() {
1212+ let picker = ui::file_picker(path.into(), &cx.editor.config());
1213+ cx.push_layer(Box::new(overlaid(picker)));
1214+ } else if let Err(e) = cx.editor.open(path, action) {
1215+ cx.editor.set_error(format!("Open file failed: {:?}", e));
1216+ }
1217+ }
1218+}
1219+
1220+/// Opens the given url. If the URL points to a valid textual file it is open in helix.
1221+// Otherwise, the file is open using external program.
1222+fn open_url(cx: &mut Context, url: Url, action: Action) {
1223+ let doc = doc!(cx.editor);
1224+ let rel_path = doc
1225+ .relative_path()
1226+ .map(|path| path.parent().unwrap().to_path_buf())
1227+ .unwrap_or_default();
1228+
1229+ if url.scheme() != "file" {
1230+ return open_external_url(cx, url);
1231+ }
1232+
1233+ let content_type = std::fs::File::open(url.path()).and_then(|file| {
1234+ // Read up to 1kb to detect the content type
1235+ let mut read_buffer = Vec::new();
1236+ let n = file.take(1024).read_to_end(&mut read_buffer)?;
1237+ Ok(content_inspector::inspect(&read_buffer[..n]))
1238+ });
1239+
1240+ // we attempt to open binary files - files that can't be open in helix - using external
1241+ // program as well, e.g. pdf files or images
1242+ match content_type {
1243+ Ok(content_inspector::ContentType::BINARY) => open_external_url(cx, url),
1244+ Ok(_) | Err(_) => {
1245+ let path = &rel_path.join(url.path());
1246+ if path.is_dir() {
1247+ let picker = ui::file_picker(path.into(), &cx.editor.config());
1248+ cx.push_layer(Box::new(overlaid(picker)));
1249+ } else if let Err(e) = cx.editor.open(path, action) {
11831250 cx.editor.set_error(format!("Open file failed: {:?}", e));
11841251 }
11851252 }
11861253 }
11871254}
11881255
1256+/// Opens URL in external program.
1257+fn open_external_url(cx: &mut Context, url: Url) {
1258+ let commands = open::commands(url.as_str());
1259+ cx.jobs.callback(async {
1260+ for cmd in commands {
1261+ let mut command = tokio::process::Command::new(cmd.get_program());
1262+ command.args(cmd.get_args());
1263+ if command.output().await.is_ok() {
1264+ return Ok(job::Callback::Editor(Box::new(|_| {})));
1265+ }
1266+ }
1267+ Ok(job::Callback::Editor(Box::new(move |editor| {
1268+ editor.set_error("Opening URL in external program failed")
1269+ })))
1270+ });
1271+}
1272+
11891273fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
11901274where
11911275 F: Fn(RopeSlice, Range, usize) -> Range,
@@ -1226,14 +1310,74 @@ fn extend_prev_long_word_start(cx: &mut Context) {
12261310 extend_word_impl(cx, movement::move_prev_long_word_start)
12271311}
12281312
1313+fn extend_prev_long_word_end(cx: &mut Context) {
1314+ extend_word_impl(cx, movement::move_prev_long_word_end)
1315+}
1316+
12291317fn extend_next_long_word_end(cx: &mut Context) {
12301318 extend_word_impl(cx, movement::move_next_long_word_end)
12311319}
12321320
1233−fn will_find_char<F>(cx: &mut Context, search_fn: F, inclusive: bool, extend: bool)
1234−where
1235− F: Fn(RopeSlice, char, usize, usize, bool) -> Option<usize> + 'static,
1236−{
1321+/// Separate branch to find_char designed only for `<ret>` char.
1322+//
1323+// This is necessary because the one document can have different line endings inside. And we
1324+// cannot predict what character to find when <ret> is pressed. On the current line it can be `lf`
1325+// but on the next line it can be `crlf`. That's why [`find_char_impl`] cannot be applied here.
1326+fn find_char_line_ending(
1327+ cx: &mut Context,
1328+ count: usize,
1329+ direction: Direction,
1330+ inclusive: bool,
1331+ extend: bool,
1332+) {
1333+ let (view, doc) = current!(cx.editor);
1334+ let text = doc.text().slice(..);
1335+
1336+ let selection = doc.selection(view.id).clone().transform(|range| {
1337+ let cursor = range.cursor(text);
1338+ let cursor_line = range.cursor_line(text);
1339+
1340+ // Finding the line where we're going to find <ret>. Depends mostly on
1341+ // `count`, but also takes into account edge cases where we're already at the end
1342+ // of a line or the beginning of a line
1343+ let find_on_line = match direction {
1344+ Direction::Forward => {
1345+ let on_edge = line_end_char_index(&text, cursor_line) == cursor;
1346+ let line = cursor_line + count - 1 + (on_edge as usize);
1347+ if line >= text.len_lines() - 1 {
1348+ return range;
1349+ } else {
1350+ line
1351+ }
1352+ }
1353+ Direction::Backward => {
1354+ let on_edge = text.line_to_char(cursor_line) == cursor && !inclusive;
1355+ let line = cursor_line as isize - (count as isize - 1 + on_edge as isize);
1356+ if line <= 0 {
1357+ return range;
1358+ } else {
1359+ line as usize
1360+ }
1361+ }
1362+ };
1363+
1364+ let pos = match (direction, inclusive) {
1365+ (Direction::Forward, true) => line_end_char_index(&text, find_on_line),
1366+ (Direction::Forward, false) => line_end_char_index(&text, find_on_line) - 1,
1367+ (Direction::Backward, true) => line_end_char_index(&text, find_on_line - 1),
1368+ (Direction::Backward, false) => text.line_to_char(find_on_line),
1369+ };
1370+
1371+ if extend {
1372+ range.put_cursor(text, pos, true)
1373+ } else {
1374+ Range::point(range.cursor(text)).put_cursor(text, pos, true)
1375+ }
1376+ });
1377+ doc.set_selection(view.id, selection);
1378+}
1379+
1380+fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bool) {
12371381 // TODO: count is reset to 1 before next key so we move it into the closure here.
12381382 // Would be nice to carry over.
12391383 let count = cx.count();
@@ -1246,13 +1390,9 @@ where
12461390 KeyEvent {
12471391 code: KeyCode::Enter,
12481392 ..
1249− } =>
1250− // TODO: this isn't quite correct when CRLF is involved.
1251− // This hack will work in most cases, since documents don't
1252− // usually mix line endings. But we should fix it eventually
1253− // anyway.
1254− {
1255− doc!(cx.editor).line_ending.as_str().chars().next().unwrap()
1393+ } => {
1394+ find_char_line_ending(cx, count, direction, inclusive, extend);
1395+ return;
12561396 }
12571397
12581398 KeyEvent {
@@ -1265,11 +1405,18 @@ where
12651405 } => ch,
12661406 _ => return,
12671407 };
1408+ let motion = move |editor: &mut Editor| {
1409+ match direction {
1410+ Direction::Forward => {
1411+ find_char_impl(editor, &find_next_char_impl, inclusive, extend, ch, count)
1412+ }
1413+ Direction::Backward => {
1414+ find_char_impl(editor, &find_prev_char_impl, inclusive, extend, ch, count)
1415+ }
1416+ };
1417+ };
12681418
1269− find_char_impl(cx.editor, &search_fn, inclusive, extend, ch, count);
1270− cx.editor.last_motion = Some(Motion(Box::new(move |editor: &mut Editor| {
1271− find_char_impl(editor, &search_fn, inclusive, true, ch, 1);
1272− })));
1419+ cx.editor.apply_motion(motion);
12731420 })
12741421}
12751422
@@ -1348,46 +1495,39 @@ fn find_prev_char_impl(
13481495}
13491496
13501497fn find_till_char(cx: &mut Context) {
1351− will_find_char(cx, find_next_char_impl, false, false)
1498+ find_char(cx, Direction::Forward, false, false);
13521499}
13531500
13541501fn find_next_char(cx: &mut Context) {
1355− will_find_char(cx, find_next_char_impl, true, false)
1502+ find_char(cx, Direction::Forward, true, false)
13561503}
13571504
13581505fn extend_till_char(cx: &mut Context) {
1359− will_find_char(cx, find_next_char_impl, false, true)
1506+ find_char(cx, Direction::Forward, false, true)
13601507}
13611508
13621509fn extend_next_char(cx: &mut Context) {
1363− will_find_char(cx, find_next_char_impl, true, true)
1510+ find_char(cx, Direction::Forward, true, true)
13641511}
13651512
13661513fn till_prev_char(cx: &mut Context) {
1367− will_find_char(cx, find_prev_char_impl, false, false)
1514+ find_char(cx, Direction::Backward, false, false)
13681515}
13691516
13701517fn find_prev_char(cx: &mut Context) {
1371− will_find_char(cx, find_prev_char_impl, true, false)
1518+ find_char(cx, Direction::Backward, true, false)
13721519}
13731520
13741521fn extend_till_prev_char(cx: &mut Context) {
1375− will_find_char(cx, find_prev_char_impl, false, true)
1522+ find_char(cx, Direction::Backward, false, true)
13761523}
13771524
13781525fn extend_prev_char(cx: &mut Context) {
1379− will_find_char(cx, find_prev_char_impl, true, true)
1526+ find_char(cx, Direction::Backward, true, true)
13801527}
13811528
13821529fn repeat_last_motion(cx: &mut Context) {
1383− let count = cx.count();
1384− let last_motion = cx.editor.last_motion.take();
1385− if let Some(m) = &last_motion {
1386− for _ in 0..count {
1387− m.run(cx.editor);
1388− }
1389− cx.editor.last_motion = last_motion;
1390− }
1530+ cx.editor.repeat_last_motion(cx.count())
13911531}
13921532
13931533fn replace(cx: &mut Context) {
@@ -1454,6 +1594,7 @@ where
14541594 });
14551595
14561596 doc.apply(&transaction, view.id);
1597+ exit_select_mode(cx);
14571598}
14581599
14591600fn switch_case(cx: &mut Context) {
@@ -1695,8 +1836,8 @@ fn select_regex(cx: &mut Context) {
16951836 "select:".into(),
16961837 Some(reg),
16971838 ui::completers::none,
1698− move |editor, regex, event| {
1699− let (view, doc) = current!(editor);
1839+ move |cx, regex, event| {
1840+ let (view, doc) = current!(cx.editor);
17001841 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
17011842 return;
17021843 }
@@ -1717,8 +1858,8 @@ fn split_selection(cx: &mut Context) {
17171858 "split:".into(),
17181859 Some(reg),
17191860 ui::completers::none,
1720− move |editor, regex, event| {
1721− let (view, doc) = current!(editor);
1861+ move |cx, regex, event| {
1862+ let (view, doc) = current!(cx.editor);
17221863 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
17231864 return;
17241865 }
@@ -1740,6 +1881,12 @@ fn split_selection_on_newline(cx: &mut Context) {
17401881 doc.set_selection(view.id, selection);
17411882}
17421883
1884+fn merge_selections(cx: &mut Context) {
1885+ let (view, doc) = current!(cx.editor);
1886+ let selection = doc.selection(view.id).clone().merge_ranges();
1887+ doc.set_selection(view.id, selection);
1888+}
1889+
17431890fn merge_consecutive_selections(cx: &mut Context) {
17441891 let (view, doc) = current!(cx.editor);
17451892 let selection = doc.selection(view.id).clone().merge_consecutive_ranges();
@@ -1835,11 +1982,11 @@ fn search_impl(
18351982
18361983fn search_completions(cx: &mut Context, reg: Option<char>) -> Vec<String> {
18371984 let mut items = reg
1838− .and_then(|reg| cx.editor.registers.get(reg))
1839− .map_or(Vec::new(), |reg| reg.read().iter().take(200).collect());
1985+ .and_then(|reg| cx.editor.registers.read(reg, cx.editor))
1986+ .map_or(Vec::new(), |reg| reg.take(200).collect());
18401987 items.sort_unstable();
18411988 items.dedup();
1842− items.into_iter().cloned().collect()
1989+ items.into_iter().map(|value| value.to_string()).collect()
18431990}
18441991
18451992fn search(cx: &mut Context) {
@@ -1876,12 +2023,14 @@ fn searcher(cx: &mut Context, direction: Direction) {
18762023 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
18772024 .collect()
18782025 },
1879− move |editor, regex, event| {
1880− if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
2026+ move |cx, regex, event| {
2027+ if event == PromptEvent::Validate {
2028+ cx.editor.registers.last_search_register = reg;
2029+ } else if event != PromptEvent::Update {
18812030 return;
18822031 }
18832032 search_impl(
1884− editor,
2033+ cx.editor,
18852034 &contents,
18862035 ®ex,
18872036 Movement::Move,
@@ -1896,11 +2045,13 @@ fn searcher(cx: &mut Context, direction: Direction) {
18962045
18972046fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Direction) {
18982047 let count = cx.count();
2048+ let register = cx
2049+ .register
2050+ .unwrap_or(cx.editor.registers.last_search_register);
18992051 let config = cx.editor.config();
19002052 let scrolloff = config.scrolloff;
1901− let (_, doc) = current!(cx.editor);
1902− let registers = &cx.editor.registers;
1903− if let Some(query) = registers.read('/').and_then(|query| query.last()) {
2053+ if let Some(query) = cx.editor.registers.first(register, cx.editor) {
2054+ let doc = doc!(cx.editor);
19042055 let contents = doc.text().slice(..).to_string();
19052056 let search_config = &config.search;
19062057 let case_insensitive = if search_config.smart_case {
@@ -1909,7 +2060,7 @@ fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Dir
19092060 false
19102061 };
19112062 let wrap_around = search_config.wrap_around;
1912− if let Ok(regex) = RegexBuilder::new(query)
2063+ if let Ok(regex) = RegexBuilder::new(&query)
19132064 .case_insensitive(case_insensitive)
19142065 .multi_line(true)
19152066 .build()
@@ -1949,6 +2100,7 @@ fn extend_search_prev(cx: &mut Context) {
19492100}
19502101
19512102fn search_selection(cx: &mut Context) {
2103+ let register = cx.register.unwrap_or('/');
19522104 let (view, doc) = current!(cx.editor);
19532105 let contents = doc.text().slice(..);
19542106
@@ -1961,13 +2113,24 @@ fn search_selection(cx: &mut Context) {
19612113 .collect::<Vec<_>>()
19622114 .join("|");
19632115
1964− let msg = format!("register '{}' set to '{}'", '/', ®ex);
1965− cx.editor.registers.push('/', regex);
1966− cx.editor.set_status(msg);
2116+ let msg = format!("register '{}' set to '{}'", register, ®ex);
2117+ match cx.editor.registers.push(register, regex) {
2118+ Ok(_) => {
2119+ cx.editor.registers.last_search_register = register;
2120+ cx.editor.set_status(msg)
2121+ }
2122+ Err(err) => cx.editor.set_error(err.to_string()),
2123+ }
19672124}
19682125
19692126fn make_search_word_bounded(cx: &mut Context) {
1970− let regex = match cx.editor.registers.last('/') {
2127+ // Defaults to the active search register instead `/` to be more ergonomic assuming most people
2128+ // would use this command following `search_selection`. This avoids selecting the register
2129+ // twice.
2130+ let register = cx
2131+ .register
2132+ .unwrap_or(cx.editor.registers.last_search_register);
2133+ let regex = match cx.editor.registers.first(register, cx.editor) {
19712134 Some(regex) => regex,
19722135 None => return,
19732136 };
@@ -1985,14 +2148,19 @@ fn make_search_word_bounded(cx: &mut Context) {
19852148 if !start_anchored {
19862149 new_regex.push_str("\\b");
19872150 }
1988− new_regex.push_str(regex);
2151+ new_regex.push_str(®ex);
19892152 if !end_anchored {
19902153 new_regex.push_str("\\b");
19912154 }
19922155
1993− let msg = format!("register '{}' set to '{}'", '/', &new_regex);
1994− cx.editor.registers.push('/', new_regex);
1995− cx.editor.set_status(msg);
2156+ let msg = format!("register '{}' set to '{}'", register, &new_regex);
2157+ match cx.editor.registers.push(register, new_regex) {
2158+ Ok(_) => {
2159+ cx.editor.registers.last_search_register = register;
2160+ cx.editor.set_status(msg)
2161+ }
2162+ Err(err) => cx.editor.set_error(err.to_string()),
2163+ }
19962164}
19972165
19982166fn global_search(cx: &mut Context) {
@@ -2031,13 +2199,11 @@ fn global_search(cx: &mut Context) {
20312199 }
20322200 }
20332201
2034− let (all_matches_sx, all_matches_rx) = tokio::sync::mpsc::unbounded_channel::<FileResult>();
20352202 let config = cx.editor.config();
20362203 let smart_case = config.search.smart_case;
20372204 let file_picker_config = config.file_picker.clone();
20382205
20392206 let reg = cx.register.unwrap_or('/');
2040−
20412207 let completions = search_completions(cx, Some(reg));
20422208 ui::regex_prompt(
20432209 cx,
@@ -2050,43 +2216,67 @@ fn global_search(cx: &mut Context) {
20502216 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
20512217 .collect()
20522218 },
2053− move |_editor, regex, event| {
2219+ move |cx, regex, event| {
20542220 if event != PromptEvent::Validate {
20552221 return;
20562222 }
2223+ cx.editor.registers.last_search_register = reg;
2224+
2225+ let current_path = doc_mut!(cx.editor).path().cloned();
2226+ let documents: Vec<_> = cx
2227+ .editor
2228+ .documents()
2229+ .map(|doc| (doc.path().cloned(), doc.text().to_owned()))
2230+ .collect();
20572231
20582232 if let Ok(matcher) = RegexMatcherBuilder::new()
20592233 .case_smart(smart_case)
20602234 .build(regex.as_str())
20612235 {
2062− let searcher = SearcherBuilder::new()
2063− .binary_detection(BinaryDetection::quit(b'\x00'))
2064− .build();
2236+ let search_root = helix_loader::current_working_dir();
2237+ if !search_root.exists() {
2238+ cx.editor
2239+ .set_error("Current working directory does not exist");
2240+ return;
2241+ }
2242+
2243+ let (picker, injector) = Picker::stream(current_path);
20652244
2066− let search_root = std::env::current_dir()
2067− .expect("Global search error: Failed to get current dir");
20682245 let dedup_symlinks = file_picker_config.deduplicate_links;
20692246 let absolute_root = search_root
20702247 .canonicalize()
20712248 .unwrap_or_else(|_| search_root.clone());
2072−
2073− WalkBuilder::new(search_root)
2074− .hidden(file_picker_config.hidden)
2075− .parents(file_picker_config.parents)
2076− .ignore(file_picker_config.ignore)
2077− .follow_links(file_picker_config.follow_symlinks)
2078− .git_ignore(file_picker_config.git_ignore)
2079− .git_global(file_picker_config.git_global)
2080− .git_exclude(file_picker_config.git_exclude)
2081− .max_depth(file_picker_config.max_depth)
2082− .filter_entry(move |entry| {
2083− filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2084− })
2085− .build_parallel()
2086− .run(|| {
2249+ let injector_ = injector.clone();
2250+
2251+ std::thread::spawn(move || {
2252+ let searcher = SearcherBuilder::new()
2253+ .binary_detection(BinaryDetection::quit(b'\x00'))
2254+ .build();
2255+
2256+ let mut walk_builder = WalkBuilder::new(search_root);
2257+
2258+ walk_builder
2259+ .hidden(file_picker_config.hidden)
2260+ .parents(file_picker_config.parents)
2261+ .ignore(file_picker_config.ignore)
2262+ .follow_links(file_picker_config.follow_symlinks)
2263+ .git_ignore(file_picker_config.git_ignore)
2264+ .git_global(file_picker_config.git_global)
2265+ .git_exclude(file_picker_config.git_exclude)
2266+ .max_depth(file_picker_config.max_depth)
2267+ .filter_entry(move |entry| {
2268+ filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2269+ });
2270+
2271+ walk_builder
2272+ .add_custom_ignore_filename(helix_loader::config_dir().join("ignore"));
2273+ walk_builder.add_custom_ignore_filename(".helix/ignore");
2274+
2275+ walk_builder.build_parallel().run(|| {
20872276 let mut searcher = searcher.clone();
20882277 let matcher = matcher.clone();
2089− let all_matches_sx = all_matches_sx.clone();
2278+ let injector = injector_.clone();
2279+ let documents = &documents;
20902280 Box::new(move |entry: Result<DirEntry, ignore::Error>| -> WalkState {
20912281 let entry = match entry {
20922282 Ok(entry) => entry,
@@ -2099,17 +2289,39 @@ fn global_search(cx: &mut Context) {
20992289 _ => return WalkState::Continue,
21002290 };
21012291
2102− let result = searcher.search_path(
2103− &matcher,
2104− entry.path(),
2105− sinks::UTF8(|line_num, _| {
2106− all_matches_sx
2107− .send(FileResult::new(entry.path(), line_num as usize - 1))
2108− .unwrap();
2109−
2110− Ok(true)
2111− }),
2112− );
2292+ let mut stop = false;
2293+ let sink = sinks::UTF8(|line_num, _| {
2294+ stop = injector
2295+ .push(FileResult::new(entry.path(), line_num as usize - 1))
2296+ .is_err();
2297+
2298+ Ok(!stop)
2299+ });
2300+ let doc = documents.iter().find(|&(doc_path, _)| {
2301+ doc_path
2302+ .as_ref()
2303+ .map_or(false, |doc_path| doc_path == entry.path())
2304+ });
2305+
2306+ let result = if let Some((_, doc)) = doc {
2307+ // there is already a buffer for this file
2308+ // search the buffer instead of the file because it's faster
2309+ // and captures new edits without requiring a save
2310+ if searcher.multi_line_with_matcher(&matcher) {
2311+ // in this case a continous buffer is required
2312+ // convert the rope to a string
2313+ let text = doc.to_string();
2314+ searcher.search_slice(&matcher, text.as_bytes(), sink)
2315+ } else {
2316+ searcher.search_reader(
2317+ &matcher,
2318+ RopeReader::new(doc.slice(..)),
2319+ sink,
2320+ )
2321+ }
2322+ } else {
2323+ searcher.search_path(&matcher, entry.path(), sink)
2324+ };
21132325
21142326 if let Err(err) = result {
21152327 log::error!(
@@ -2118,67 +2330,66 @@ fn global_search(cx: &mut Context) {
21182330 err
21192331 );
21202332 }
2121− WalkState::Continue
2333+ if stop {
2334+ WalkState::Quit
2335+ } else {
2336+ WalkState::Continue
2337+ }
21222338 })
21232339 });
2340+ });
2341+
2342+ cx.jobs.callback(async move {
2343+ let call = move |_: &mut Editor, compositor: &mut Compositor| {
2344+ let picker = Picker::with_stream(
2345+ picker,
2346+ injector,
2347+ move |cx, FileResult { path, line_num }, action| {
2348+ let doc = match cx.editor.open(path, action) {
2349+ Ok(id) => doc_mut!(cx.editor, &id),
2350+ Err(e) => {
2351+ cx.editor.set_error(format!(
2352+ "Failed to open file '{}': {}",
2353+ path.display(),
2354+ e
2355+ ));
2356+ return;
2357+ }
2358+ };
2359+
2360+ let line_num = *line_num;
2361+ let view = view_mut!(cx.editor);
2362+ let text = doc.text();
2363+ if line_num >= text.len_lines() {
2364+ cx.editor.set_error(
2365+ "The line you jumped to does not exist anymore because the file has changed.",
2366+ );
2367+ return;
2368+ }
2369+ let start = text.line_to_char(line_num);
2370+ let end = text.line_to_char((line_num + 1).min(text.len_lines()));
2371+
2372+ doc.set_selection(view.id, Selection::single(start, end));
2373+ if action.align_view(view, doc.id()) {
2374+ align_view(doc, view, Align::Center);
2375+ }
2376+ },
2377+ )
2378+ .with_preview(
2379+ |_editor, FileResult { path, line_num }| {
2380+ Some((path.clone().into(), Some((*line_num, *line_num))))
2381+ },
2382+ );
2383+ compositor.push(Box::new(overlaid(picker)))
2384+ };
2385+ Ok(Callback::EditorCompositor(Box::new(call)))
2386+ })
21242387 } else {
21252388 // Otherwise do nothing
21262389 // log::warn!("Global Search Invalid Pattern")
21272390 }
21282391 },
21292392 );
2130−
2131− let current_path = doc_mut!(cx.editor).path().cloned();
2132−
2133− let show_picker = async move {
2134− let all_matches: Vec<FileResult> =
2135− UnboundedReceiverStream::new(all_matches_rx).collect().await;
2136− let call: job::Callback = Callback::EditorCompositor(Box::new(
2137− move |editor: &mut Editor, compositor: &mut Compositor| {
2138− if all_matches.is_empty() {
2139− editor.set_status("No matches found");
2140− return;
2141− }
2142−
2143− let picker = FilePicker::new(
2144− all_matches,
2145− current_path,
2146− move |cx, FileResult { path, line_num }, action| {
2147− match cx.editor.open(path, action) {
2148− Ok(_) => {}
2149− Err(e) => {
2150− cx.editor.set_error(format!(
2151− "Failed to open file '{}': {}",
2152− path.display(),
2153− e
2154− ));
2155− return;
2156− }
2157− }
2158−
2159− let line_num = *line_num;
2160− let (view, doc) = current!(cx.editor);
2161− let text = doc.text();
2162− if line_num >= text.len_lines() {
2163− cx.editor.set_error("The line you jumped to does not exist anymore because the file has changed.");
2164− return;
2165− }
2166− let start = text.line_to_char(line_num);
2167− let end = text.line_to_char((line_num + 1).min(text.len_lines()));
2168−
2169− doc.set_selection(view.id, Selection::single(start, end));
2170− align_view(doc, view, Align::Center);
2171− },
2172− |_editor, FileResult { path, line_num }| {
2173− Some((path.clone().into(), Some((*line_num, *line_num))))
2174− },
2175− );
2176− compositor.push(Box::new(overlaid(picker)));
2177− },
2178− ));
2179− Ok(call)
2180− };
2181− cx.jobs.callback(show_picker);
21822393}
21832394
21842395enum Extend {
@@ -2301,23 +2512,40 @@ enum Operation {
23012512 Change,
23022513}
23032514
2515+fn selection_is_linewise(selection: &Selection, text: &Rope) -> bool {
2516+ selection.ranges().iter().all(|range| {
2517+ let text = text.slice(..);
2518+ if range.slice(text).len_lines() < 2 {
2519+ return false;
2520+ }
2521+ // If the start of the selection is at the start of a line and the end at the end of a line.
2522+ let (start_line, end_line) = range.line_range(text);
2523+ let start = text.line_to_char(start_line);
2524+ let end = text.line_to_char((end_line + 1).min(text.len_lines()));
2525+ start == range.from() && end == range.to()
2526+ })
2527+}
2528+
23042529fn delete_selection_impl(cx: &mut Context, op: Operation) {
23052530 let (view, doc) = current!(cx.editor);
23062531
23072532 let selection = doc.selection(view.id);
2533+ let only_whole_lines = selection_is_linewise(selection, doc.text());
23082534
23092535 if cx.register != Some('_') {
23102536 // first yank the selection
23112537 let text = doc.text().slice(..);
23122538 let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect();
23132539 let reg_name = cx.register.unwrap_or('"');
2314− cx.editor.registers.write(reg_name, values);
2540+ if let Err(err) = cx.editor.registers.write(reg_name, values) {
2541+ cx.editor.set_error(err.to_string());
2542+ return;
2543+ }
23152544 };
23162545
23172546 // then delete
2318− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
2319− (range.from(), range.to(), None)
2320− });
2547+ let transaction =
2548+ Transaction::delete_by_selection(doc.text(), selection, |range| (range.from(), range.to()));
23212549 doc.apply(&transaction, view.id);
23222550
23232551 match op {
@@ -2326,17 +2554,59 @@ fn delete_selection_impl(cx: &mut Context, op: Operation) {
23262554 exit_select_mode(cx);
23272555 }
23282556 Operation::Change => {
2329− enter_insert_mode(cx);
2557+ if only_whole_lines {
2558+ open_above(cx);
2559+ } else {
2560+ enter_insert_mode(cx);
2561+ }
23302562 }
23312563 }
23322564}
23332565
23342566#[inline]
2335−fn delete_selection_insert_mode(doc: &mut Document, view: &mut View, selection: &Selection) {
2336− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
2337− (range.from(), range.to(), None)
2338− });
2567+fn delete_by_selection_insert_mode(
2568+ cx: &mut Context,
2569+ mut f: impl FnMut(RopeSlice, &Range) -> Deletion,
2570+ direction: Direction,
2571+) {
2572+ let (view, doc) = current!(cx.editor);
2573+ let text = doc.text().slice(..);
2574+ let mut selection = SmallVec::new();
2575+ let mut insert_newline = false;
2576+ let text_len = text.len_chars();
2577+ let mut transaction =
2578+ Transaction::delete_by_selection(doc.text(), doc.selection(view.id), |range| {
2579+ let (start, end) = f(text, range);
2580+ if direction == Direction::Forward {
2581+ let mut range = *range;
2582+ if range.head > range.anchor {
2583+ insert_newline |= end == text_len;
2584+ // move the cursor to the right so that the selection
2585+ // doesn't shrink when deleting forward (so the text appears to
2586+ // move to left)
2587+ // += 1 is enough here as the range is normalized to grapheme boundaries
2588+ // later anyway
2589+ range.head += 1;
2590+ }
2591+ selection.push(range);
2592+ }
2593+ (start, end)
2594+ });
2595+
2596+ // in case we delete the last character and the cursor would be moved to the EOF char
2597+ // insert a newline, just like when entering append mode
2598+ if insert_newline {
2599+ transaction = transaction.insert_at_eof(doc.line_ending.as_str().into());
2600+ }
2601+
2602+ if direction == Direction::Forward {
2603+ doc.set_selection(
2604+ view.id,
2605+ Selection::new(selection, doc.selection(view.id).primary_index()),
2606+ );
2607+ }
23392608 doc.apply(&transaction, view.id);
2609+ lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
23402610}
23412611
23422612fn delete_selection(cx: &mut Context) {
@@ -2410,6 +2680,10 @@ fn insert_mode(cx: &mut Context) {
24102680 .transform(|range| Range::new(range.to(), range.from()));
24112681
24122682 doc.set_selection(view.id, selection);
2683+
2684+ // [TODO] temporary workaround until we're not using the idle timer to
2685+ // trigger auto completions any more
2686+ cx.editor.clear_idle_timer();
24132687}
24142688
24152689// inserts at the end of each selection
@@ -2446,6 +2720,10 @@ fn append_mode(cx: &mut Context) {
24462720
24472721fn file_picker(cx: &mut Context) {
24482722 let root = find_workspace().0;
2723+ if !root.exists() {
2724+ cx.editor.set_error("Workspace directory does not exist");
2725+ return;
2726+ }
24492727 let picker = ui::file_picker(root, &cx.editor.config());
24502728 cx.push_layer(Box::new(overlaid(picker)));
24512729}
@@ -2466,8 +2744,14 @@ fn file_picker_in_current_buffer_directory(cx: &mut Context) {
24662744 let picker = ui::file_picker(path, &cx.editor.config());
24672745 cx.push_layer(Box::new(overlaid(picker)));
24682746}
2747+
24692748fn file_picker_in_current_directory(cx: &mut Context) {
2470− let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("./"));
2749+ let cwd = helix_loader::current_working_dir();
2750+ if !cwd.exists() {
2751+ cx.editor
2752+ .set_error("Current working directory does not exist");
2753+ return;
2754+ }
24712755 let picker = ui::file_picker(cwd, &cx.editor.config());
24722756 cx.push_layer(Box::new(overlaid(picker)));
24732757}
@@ -2526,22 +2810,18 @@ fn buffer_picker(cx: &mut Context) {
25262810 // mru
25272811 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
25282812
2529− let picker = FilePicker::new(
2530− items,
2531− (),
2532− |cx, meta, action| {
2533− cx.editor.switch(meta.id, action);
2534− },
2535− |editor, meta| {
2536− let doc = &editor.documents.get(&meta.id)?;
2537− let &view_id = doc.selections().keys().next()?;
2538− let line = doc
2539− .selection(view_id)
2540− .primary()
2541− .cursor_line(doc.text().slice(..));
2542− Some((meta.id.into(), Some((line, line))))
2543− },
2544− );
2813+ let picker = Picker::new(items, (), |cx, meta, action| {
2814+ cx.editor.switch(meta.id, action);
2815+ })
2816+ .with_preview(|editor, meta| {
2817+ let doc = &editor.documents.get(&meta.id)?;
2818+ let &view_id = doc.selections().keys().next()?;
2819+ let line = doc
2820+ .selection(view_id)
2821+ .primary()
2822+ .cursor_line(doc.text().slice(..));
2823+ Some((meta.id.into(), Some((line, line))))
2824+ });
25452825 cx.push_layer(Box::new(overlaid(picker)));
25462826}
25472827
@@ -2607,7 +2887,7 @@ fn jumplist_picker(cx: &mut Context) {
26072887 }
26082888 };
26092889
2610− let picker = FilePicker::new(
2890+ let picker = Picker::new(
26112891 cx.editor
26122892 .tree
26132893 .views()
@@ -2621,16 +2901,18 @@ fn jumplist_picker(cx: &mut Context) {
26212901 |cx, meta, action| {
26222902 cx.editor.switch(meta.id, action);
26232903 let config = cx.editor.config();
2624− let (view, doc) = current!(cx.editor);
2904+ let (view, doc) = (view_mut!(cx.editor), doc_mut!(cx.editor, &meta.id));
26252905 doc.set_selection(view.id, meta.selection.clone());
2626− view.ensure_cursor_in_view_center(doc, config.scrolloff);
2627− },
2628− |editor, meta| {
2629− let doc = &editor.documents.get(&meta.id)?;
2630− let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2631− Some((meta.path.clone()?.into(), Some((line, line))))
2906+ if action.align_view(view, doc.id()) {
2907+ view.ensure_cursor_in_view_center(doc, config.scrolloff);
2908+ }
26322909 },
2633− );
2910+ )
2911+ .with_preview(|editor, meta| {
2912+ let doc = &editor.documents.get(&meta.id)?;
2913+ let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2914+ Some((meta.id.into(), Some((line, line))))
2915+ });
26342916 cx.push_layer(Box::new(overlaid(picker)));
26352917}
26362918
@@ -2664,6 +2946,9 @@ impl ui::menu::Item for MappableCommand {
26642946}
26652947
26662948pub fn command_palette(cx: &mut Context) {
2949+ let register = cx.register;
2950+ let count = cx.count;
2951+
26672952 cx.callback = Some(Box::new(
26682953 move |compositor: &mut Compositor, cx: &mut compositor::Context| {
26692954 let keymap = compositor.find::<ui::EditorView>().unwrap().keymaps.map()
@@ -2681,8 +2966,8 @@ pub fn command_palette(cx: &mut Context) {
26812966
26822967 let picker = Picker::new(commands, keymap, move |cx, command, _action| {
26832968 let mut ctx = Context {
2684− register: None,
2685− count: std::num::NonZeroUsize::new(1),
2969+ register,
2970+ count,
26862971 editor: cx.editor,
26872972 callback: None,
26882973 on_next_key_callback: None,
@@ -2721,24 +3006,88 @@ fn last_picker(cx: &mut Context) {
27213006 }));
27223007}
27233008
2724−// I inserts at the first nonwhitespace character of each line with a selection
3009+/// Fallback position to use for [`insert_with_indent`].
3010+enum IndentFallbackPos {
3011+ LineStart,
3012+ LineEnd,
3013+}
3014+
3015+// `I` inserts at the first nonwhitespace character of each line with a selection.
3016+// If the line is empty, automatically indent.
27253017fn insert_at_line_start(cx: &mut Context) {
2726− goto_first_nonwhitespace(cx);
2727− enter_insert_mode(cx);
3018+ insert_with_indent(cx, IndentFallbackPos::LineStart);
27283019}
27293020
2730−// A inserts at the end of each line with a selection
3021+// `A` inserts at the end of each line with a selection.
3022+// If the line is empty, automatically indent.
27313023fn insert_at_line_end(cx: &mut Context) {
3024+ insert_with_indent(cx, IndentFallbackPos::LineEnd);
3025+}
3026+
3027+// Enter insert mode and auto-indent the current line if it is empty.
3028+// If the line is not empty, move the cursor to the specified fallback position.
3029+fn insert_with_indent(cx: &mut Context, cursor_fallback: IndentFallbackPos) {
27323030 enter_insert_mode(cx);
3031+
27333032 let (view, doc) = current!(cx.editor);
27343033
2735− let selection = doc.selection(view.id).clone().transform(|range| {
2736− let text = doc.text().slice(..);
2737− let line = range.cursor_line(text);
2738− let pos = line_end_char_index(&text, line);
2739− Range::new(pos, pos)
3034+ let text = doc.text().slice(..);
3035+ let contents = doc.text();
3036+ let selection = doc.selection(view.id);
3037+
3038+ let language_config = doc.language_config();
3039+ let syntax = doc.syntax();
3040+ let tab_width = doc.tab_width();
3041+
3042+ let mut ranges = SmallVec::with_capacity(selection.len());
3043+ let mut offs = 0;
3044+
3045+ let mut transaction = Transaction::change_by_selection(contents, selection, |range| {
3046+ let cursor_line = range.cursor_line(text);
3047+ let cursor_line_start = text.line_to_char(cursor_line);
3048+
3049+ if line_end_char_index(&text, cursor_line) == cursor_line_start {
3050+ // line is empty => auto indent
3051+ let line_end_index = cursor_line_start;
3052+
3053+ let indent = indent::indent_for_newline(
3054+ language_config,
3055+ syntax,
3056+ &doc.config.load().indent_heuristic,
3057+ &doc.indent_style,
3058+ tab_width,
3059+ text,
3060+ cursor_line,
3061+ line_end_index,
3062+ cursor_line,
3063+ );
3064+
3065+ // calculate new selection ranges
3066+ let pos = offs + cursor_line_start;
3067+ let indent_width = indent.chars().count();
3068+ ranges.push(Range::point(pos + indent_width));
3069+ offs += indent_width;
3070+
3071+ (line_end_index, line_end_index, Some(indent.into()))
3072+ } else {
3073+ // move cursor to the fallback position
3074+ let pos = match cursor_fallback {
3075+ IndentFallbackPos::LineStart => {
3076+ find_first_non_whitespace_char(text.line(cursor_line))
3077+ .map(|ws_offset| ws_offset + cursor_line_start)
3078+ .unwrap_or(cursor_line_start)
3079+ }
3080+ IndentFallbackPos::LineEnd => line_end_char_index(&text, cursor_line),
3081+ };
3082+
3083+ ranges.push(range.put_cursor(text, pos + offs, cx.editor.mode == Mode::Select));
3084+
3085+ (cursor_line_start, cursor_line_start, None)
3086+ }
27403087 });
2741− doc.set_selection(view.id, selection);
3088+
3089+ transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3090+ doc.apply(&transaction, view.id);
27423091}
27433092
27443093// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
@@ -2809,6 +3158,7 @@ fn open(cx: &mut Context, open: Open) {
28093158 Open::Below => graphemes::prev_grapheme_boundary(text, range.to()),
28103159 Open::Above => range.from(),
28113160 });
3161+
28123162 let new_line = match open {
28133163 // adjust position to the end of the line (next line - 1)
28143164 Open::Below => cursor_line + 1,
@@ -2816,13 +3166,15 @@ fn open(cx: &mut Context, open: Open) {
28163166 Open::Above => cursor_line,
28173167 };
28183168
3169+ let line_num = new_line.saturating_sub(1);
3170+
28193171 // Index to insert newlines after, as well as the char width
28203172 // to use to compensate for those inserted newlines.
28213173 let (line_end_index, line_end_offset_width) = if new_line == 0 {
28223174 (0, 0)
28233175 } else {
28243176 (
2825− line_end_char_index(&doc.text().slice(..), new_line.saturating_sub(1)),
3177+ line_end_char_index(&text, line_num),
28263178 doc.line_ending.len_chars(),
28273179 )
28283180 };
@@ -2830,13 +3182,15 @@ fn open(cx: &mut Context, open: Open) {
28303182 let indent = indent::indent_for_newline(
28313183 doc.language_config(),
28323184 doc.syntax(),
3185+ &doc.config.load().indent_heuristic,
28333186 &doc.indent_style,
28343187 doc.tab_width(),
28353188 text,
2836− new_line.saturating_sub(1),
3189+ line_num,
28373190 line_end_index,
28383191 cursor_line,
28393192 );
3193+
28403194 let indent_len = indent.len();
28413195 let mut text = String::with_capacity(1 + indent_len);
28423196 text.push_str(doc.line_ending.as_str());
@@ -2996,7 +3350,7 @@ fn exit_select_mode(cx: &mut Context) {
29963350
29973351fn goto_first_diag(cx: &mut Context) {
29983352 let (view, doc) = current!(cx.editor);
2999− let selection = match doc.diagnostics().first() {
3353+ let selection = match doc.shown_diagnostics().next() {
30003354 Some(diag) => Selection::single(diag.range.start, diag.range.end),
30013355 None => return,
30023356 };
@@ -3005,7 +3359,7 @@ fn goto_first_diag(cx: &mut Context) {
30053359
30063360fn goto_last_diag(cx: &mut Context) {
30073361 let (view, doc) = current!(cx.editor);
3008− let selection = match doc.diagnostics().last() {
3362+ let selection = match doc.shown_diagnostics().last() {
30093363 Some(diag) => Selection::single(diag.range.start, diag.range.end),
30103364 None => return,
30113365 };
@@ -3021,10 +3375,9 @@ fn goto_next_diag(cx: &mut Context) {
30213375 .cursor(doc.text().slice(..));
30223376
30233377 let diag = doc
3024− .diagnostics()
3025− .iter()
3378+ .shown_diagnostics()
30263379 .find(|diag| diag.range.start > cursor_pos)
3027− .or_else(|| doc.diagnostics().first());
3380+ .or_else(|| doc.shown_diagnostics().next());
30283381
30293382 let selection = match diag {
30303383 Some(diag) => Selection::single(diag.range.start, diag.range.end),
@@ -3042,11 +3395,10 @@ fn goto_prev_diag(cx: &mut Context) {
30423395 .cursor(doc.text().slice(..));
30433396
30443397 let diag = doc
3045− .diagnostics()
3046− .iter()
3398+ .shown_diagnostics()
30473399 .rev()
30483400 .find(|diag| diag.range.start < cursor_pos)
3049− .or_else(|| doc.diagnostics().last());
3401+ .or_else(|| doc.shown_diagnostics().last());
30503402
30513403 let selection = match diag {
30523404 // NOTE: the selection is reversed because we're jumping to the
@@ -3137,8 +3489,7 @@ fn goto_next_change_impl(cx: &mut Context, direction: Direction) {
31373489
31383490 doc.set_selection(view.id, selection)
31393491 };
3140− motion(cx.editor);
3141− cx.editor.last_motion = Some(Motion(Box::new(motion)));
3492+ cx.editor.apply_motion(motion);
31423493}
31433494
31443495/// Returns the [Range] for a [Hunk] in the given text.
@@ -3201,23 +3552,19 @@ pub mod insert {
32013552 use helix_lsp::lsp;
32023553 // if ch matches completion char, trigger completion
32033554 let doc = doc_mut!(cx.editor);
3204− let language_server = match doc.language_server() {
3205− Some(language_server) => language_server,
3206− None => return,
3207− };
3208−
3209− let capabilities = language_server.capabilities();
3555+ let trigger_completion = doc
3556+ .language_servers_with_feature(LanguageServerFeature::Completion)
3557+ .any(|ls| {
3558+ // TODO: what if trigger is multiple chars long
3559+ matches!(&ls.capabilities().completion_provider, Some(lsp::CompletionOptions {
3560+ trigger_characters: Some(triggers),
3561+ ..
3562+ }) if triggers.iter().any(|trigger| trigger.contains(ch)))
3563+ });
32103564
3211− if let Some(lsp::CompletionOptions {
3212− trigger_characters: Some(triggers),
3213− ..
3214− }) = &capabilities.completion_provider
3215− {
3216− // TODO: what if trigger is multiple chars long
3217− if triggers.iter().any(|trigger| trigger.contains(ch)) {
3218− cx.editor.clear_idle_timer();
3219− super::completion(cx);
3220− }
3565+ if trigger_completion {
3566+ cx.editor.clear_idle_timer();
3567+ super::completion(cx);
32213568 }
32223569 }
32233570
@@ -3225,12 +3572,12 @@ pub mod insert {
32253572 use helix_lsp::lsp;
32263573 // if ch matches signature_help char, trigger
32273574 let doc = doc_mut!(cx.editor);
3228− // The language_server!() macro is not used here since it will
3229− // print an "LSP not active for current buffer" message on
3230− // every keypress.
3231− let language_server = match doc.language_server() {
3232− Some(language_server) => language_server,
3233− None => return,
3575+ // TODO support multiple language servers (not just the first that is found), likely by merging UI somehow
3576+ let Some(language_server) = doc
3577+ .language_servers_with_feature(LanguageServerFeature::SignatureHelp)
3578+ .next()
3579+ else {
3580+ return;
32343581 };
32353582
32363583 let capabilities = language_server.capabilities();
@@ -3269,6 +3616,7 @@ pub mod insert {
32693616 }
32703617
32713618 use helix_core::auto_pairs;
3619+ use helix_view::editor::SmartTabConfig;
32723620
32733621 pub fn insert_char(cx: &mut Context, c: char) {
32743622 let (view, doc) = current_ref!(cx.editor);
@@ -3294,7 +3642,32 @@ pub mod insert {
32943642 }
32953643 }
32963644
3297− pub fn insert_tab(cx: &mut Context) {
3645+ pub fn smart_tab(cx: &mut Context) {
3646+ let (view, doc) = current_ref!(cx.editor);
3647+ let view_id = view.id;
3648+
3649+ if matches!(
3650+ cx.editor.config().smart_tab,
3651+ Some(SmartTabConfig { enable: true, .. })
3652+ ) {
3653+ let cursors_after_whitespace = doc.selection(view_id).ranges().iter().all(|range| {
3654+ let cursor = range.cursor(doc.text().slice(..));
3655+ let current_line_num = doc.text().char_to_line(cursor);
3656+ let current_line_start = doc.text().line_to_char(current_line_num);
3657+ let left = doc.text().slice(current_line_start..cursor);
3658+ left.chars().all(|c| c.is_whitespace())
3659+ });
3660+
3661+ if !cursors_after_whitespace {
3662+ move_parent_node_end(cx);
3663+ return;
3664+ }
3665+ }
3666+
3667+ insert_tab(cx);
3668+ }
3669+
3670+ pub fn insert_tab(cx: &mut Context) {
32983671 let (view, doc) = current!(cx.editor);
32993672 // TODO: round out to nearest indentation level (for example a line with 3 spaces should
33003673 // indent by one to reach 4 spaces).
@@ -3349,6 +3722,7 @@ pub mod insert {
33493722 let indent = indent::indent_for_newline(
33503723 doc.language_config(),
33513724 doc.syntax(),
3725+ &doc.config.load().indent_heuristic,
33523726 &doc.indent_style,
33533727 doc.tab_width(),
33543728 text,
@@ -3422,10 +3796,10 @@ pub mod insert {
34223796 let auto_pairs = doc.auto_pairs(cx.editor);
34233797
34243798 let transaction =
3425− Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
3799+ Transaction::delete_by_selection(doc.text(), doc.selection(view.id), |range| {
34263800 let pos = range.cursor(text);
34273801 if pos == 0 {
3428− return (pos, pos, None);
3802+ return (pos, pos);
34293803 }
34303804 let line_start_pos = text.line_to_char(range.cursor_line(text));
34313805 // consider to delete by indent level if all characters before `pos` are indent units.
@@ -3433,11 +3807,7 @@ pub mod insert {
34333807 if !fragment.is_empty() && fragment.chars().all(|ch| ch == ' ' || ch == '\t') {
34343808 if text.get_char(pos.saturating_sub(1)) == Some('\t') {
34353809 // fast path, delete one char
3436− (
3437− graphemes::nth_prev_grapheme_boundary(text, pos, 1),
3438− pos,
3439− None,
3440− )
3810+ (graphemes::nth_prev_grapheme_boundary(text, pos, 1), pos)
34413811 } else {
34423812 let width: usize = fragment
34433813 .chars()
@@ -3464,7 +3834,7 @@ pub mod insert {
34643834 _ => break,
34653835 }
34663836 }
3467− (start, pos, None) // delete!
3837+ (start, pos) // delete!
34683838 }
34693839 } else {
34703840 match (
@@ -3482,17 +3852,12 @@ pub mod insert {
34823852 (
34833853 graphemes::nth_prev_grapheme_boundary(text, pos, count),
34843854 graphemes::nth_next_grapheme_boundary(text, pos, count),
3485− None,
34863855 )
34873856 }
34883857 _ =>
34893858 // delete 1 char
34903859 {
3491− (
3492− graphemes::nth_prev_grapheme_boundary(text, pos, count),
3493− pos,
3494− None,
3495− )
3860+ (graphemes::nth_prev_grapheme_boundary(text, pos, count), pos)
34963861 }
34973862 }
34983863 }
@@ -3505,50 +3870,40 @@ pub mod insert {
35053870
35063871 pub fn delete_char_forward(cx: &mut Context) {
35073872 let count = cx.count();
3508− let (view, doc) = current!(cx.editor);
3509− let text = doc.text().slice(..);
3510− let transaction =
3511− Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
3873+ delete_by_selection_insert_mode(
3874+ cx,
3875+ |text, range| {
35123876 let pos = range.cursor(text);
3513− (
3514− pos,
3515− graphemes::nth_next_grapheme_boundary(text, pos, count),
3516− None,
3517− )
3518− });
3519− doc.apply(&transaction, view.id);
3520−
3521− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
3877+ (pos, graphemes::nth_next_grapheme_boundary(text, pos, count))
3878+ },
3879+ Direction::Forward,
3880+ )
35223881 }
35233882
35243883 pub fn delete_word_backward(cx: &mut Context) {
35253884 let count = cx.count();
3526− let (view, doc) = current!(cx.editor);
3527− let text = doc.text().slice(..);
3528−
3529− let selection = doc.selection(view.id).clone().transform(|range| {
3530− let anchor = movement::move_prev_word_start(text, range, count).from();
3531− let next = Range::new(anchor, range.cursor(text));
3532− exclude_cursor(text, next, range)
3533− });
3534− delete_selection_insert_mode(doc, view, &selection);
3535−
3536− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
3885+ delete_by_selection_insert_mode(
3886+ cx,
3887+ |text, range| {
3888+ let anchor = movement::move_prev_word_start(text, *range, count).from();
3889+ let next = Range::new(anchor, range.cursor(text));
3890+ let range = exclude_cursor(text, next, *range);
3891+ (range.from(), range.to())
3892+ },
3893+ Direction::Backward,
3894+ );
35373895 }
35383896
35393897 pub fn delete_word_forward(cx: &mut Context) {
35403898 let count = cx.count();
3541− let (view, doc) = current!(cx.editor);
3542− let text = doc.text().slice(..);
3543−
3544− let selection = doc.selection(view.id).clone().transform(|range| {
3545− let head = movement::move_next_word_end(text, range, count).to();
3546− Range::new(range.cursor(text), head)
3547− });
3548−
3549− delete_selection_insert_mode(doc, view, &selection);
3550−
3551− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
3899+ delete_by_selection_insert_mode(
3900+ cx,
3901+ |text, range| {
3902+ let head = movement::move_next_word_end(text, *range, count).to();
3903+ (range.cursor(text), head)
3904+ },
3905+ Direction::Forward,
3906+ );
35523907 }
35533908}
35543909
@@ -3608,34 +3963,21 @@ fn commit_undo_checkpoint(cx: &mut Context) {
36083963// Yank / Paste
36093964
36103965fn yank(cx: &mut Context) {
3611− let (view, doc) = current!(cx.editor);
3612− let text = doc.text().slice(..);
3613−
3614− let values: Vec<String> = doc
3615− .selection(view.id)
3616− .fragments(text)
3617− .map(Cow::into_owned)
3618− .collect();
3619−
3620− let msg = format!(
3621− "yanked {} selection(s) to register {}",
3622− values.len(),
3623− cx.register.unwrap_or('"')
3624− );
3966+ yank_impl(cx.editor, cx.register.unwrap_or('"'));
3967+ exit_select_mode(cx);
3968+}
36253969
3626− cx.editor
3627− .registers
3628− .write(cx.register.unwrap_or('"'), values);
3970+fn yank_to_clipboard(cx: &mut Context) {
3971+ yank_impl(cx.editor, '+');
3972+ exit_select_mode(cx);
3973+}
36293974
3630− cx.editor.set_status(msg);
3975+fn yank_to_primary_clipboard(cx: &mut Context) {
3976+ yank_impl(cx.editor, '*');
36313977 exit_select_mode(cx);
36323978}
36333979
3634−fn yank_joined_to_clipboard_impl(
3635− editor: &mut Editor,
3636− separator: &str,
3637− clipboard_type: ClipboardType,
3638−) -> anyhow::Result<()> {
3980+fn yank_impl(editor: &mut Editor, register: char) {
36393981 let (view, doc) = current!(editor);
36403982 let text = doc.text().slice(..);
36413983
@@ -3644,74 +3986,79 @@ fn yank_joined_to_clipboard_impl(
36443986 .fragments(text)
36453987 .map(Cow::into_owned)
36463988 .collect();
3989+ let selections = values.len();
36473990
3648− let clipboard_text = match clipboard_type {
3649− ClipboardType::Clipboard => "system clipboard",
3650− ClipboardType::Selection => "primary clipboard",
3651− };
3652−
3653− let msg = format!(
3654− "joined and yanked {} selection(s) to {}",
3655− values.len(),
3656− clipboard_text,
3657− );
3991+ match editor.registers.write(register, values) {
3992+ Ok(_) => editor.set_status(format!(
3993+ "yanked {selections} selection{} to register {register}",
3994+ if selections == 1 { "" } else { "s" }
3995+ )),
3996+ Err(err) => editor.set_error(err.to_string()),
3997+ }
3998+}
36583999
3659− let joined = values.join(separator);
4000+fn yank_joined_impl(editor: &mut Editor, separator: &str, register: char) {
4001+ let (view, doc) = current!(editor);
4002+ let text = doc.text().slice(..);
36604003
3661− editor
3662− .clipboard_provider
3663− .set_contents(joined, clipboard_type)
3664− .context("Couldn't set system clipboard content")?;
4004+ let selection = doc.selection(view.id);
4005+ let selections = selection.len();
4006+ let joined = selection
4007+ .fragments(text)
4008+ .fold(String::new(), |mut acc, fragment| {
4009+ if !acc.is_empty() {
4010+ acc.push_str(separator);
4011+ }
4012+ acc.push_str(&fragment);
4013+ acc
4014+ });
36654015
3666− editor.set_status(msg);
4016+ match editor.registers.write(register, vec![joined]) {
4017+ Ok(_) => editor.set_status(format!(
4018+ "joined and yanked {selections} selection{} to register {register}",
4019+ if selections == 1 { "" } else { "s" }
4020+ )),
4021+ Err(err) => editor.set_error(err.to_string()),
4022+ }
4023+}
36674024
3668− Ok(())
4025+fn yank_joined(cx: &mut Context) {
4026+ let separator = doc!(cx.editor).line_ending.as_str();
4027+ yank_joined_impl(cx.editor, separator, cx.register.unwrap_or('"'));
4028+ exit_select_mode(cx);
36694029}
36704030
36714031fn yank_joined_to_clipboard(cx: &mut Context) {
36724032 let line_ending = doc!(cx.editor).line_ending;
3673− let _ =
3674− yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Clipboard);
4033+ yank_joined_impl(cx.editor, line_ending.as_str(), '+');
36754034 exit_select_mode(cx);
36764035}
36774036
3678−fn yank_main_selection_to_clipboard_impl(
3679− editor: &mut Editor,
3680− clipboard_type: ClipboardType,
3681−) -> anyhow::Result<()> {
4037+fn yank_joined_to_primary_clipboard(cx: &mut Context) {
4038+ let line_ending = doc!(cx.editor).line_ending;
4039+ yank_joined_impl(cx.editor, line_ending.as_str(), '*');
4040+ exit_select_mode(cx);
4041+}
4042+
4043+fn yank_primary_selection_impl(editor: &mut Editor, register: char) {
36824044 let (view, doc) = current!(editor);
36834045 let text = doc.text().slice(..);
36844046
3685− let message_text = match clipboard_type {
3686− ClipboardType::Clipboard => "yanked main selection to system clipboard",
3687− ClipboardType::Selection => "yanked main selection to primary clipboard",
3688− };
3689−
3690− let value = doc.selection(view.id).primary().fragment(text);
4047+ let selection = doc.selection(view.id).primary().fragment(text).to_string();
36914048
3692− if let Err(e) = editor
3693− .clipboard_provider
3694− .set_contents(value.into_owned(), clipboard_type)
3695− {
3696− bail!("Couldn't set system clipboard content: {}", e);
4049+ match editor.registers.write(register, vec![selection]) {
4050+ Ok(_) => editor.set_status(format!("yanked primary selection to register {register}",)),
4051+ Err(err) => editor.set_error(err.to_string()),
36974052 }
3698−
3699− editor.set_status(message_text);
3700− Ok(())
37014053}
37024054
37034055fn yank_main_selection_to_clipboard(cx: &mut Context) {
3704− let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Clipboard);
3705−}
3706−
3707−fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3708− let line_ending = doc!(cx.editor).line_ending;
3709− let _ =
3710− yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Selection);
4056+ yank_primary_selection_impl(cx.editor, '+');
4057+ exit_select_mode(cx);
37114058}
37124059
37134060fn yank_main_selection_to_primary_clipboard(cx: &mut Context) {
3714− let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Selection);
4061+ yank_primary_selection_impl(cx.editor, '*');
37154062 exit_select_mode(cx);
37164063}
37174064
@@ -3809,146 +4156,99 @@ pub(crate) fn paste_bracketed_value(cx: &mut Context, contents: String) {
38094156 };
38104157 let (view, doc) = current!(cx.editor);
38114158 paste_impl(&[contents], doc, view, paste, count, cx.editor.mode);
3812−}
3813−
3814−fn paste_clipboard_impl(
3815− editor: &mut Editor,
3816− action: Paste,
3817− clipboard_type: ClipboardType,
3818− count: usize,
3819−) -> anyhow::Result<()> {
3820− let (view, doc) = current!(editor);
3821− match editor.clipboard_provider.get_contents(clipboard_type) {
3822− Ok(contents) => {
3823− paste_impl(&[contents], doc, view, action, count, editor.mode);
3824− Ok(())
3825− }
3826− Err(e) => Err(e.context("Couldn't get system clipboard contents")),
3827− }
4159+ exit_select_mode(cx);
38284160}
38294161
38304162fn paste_clipboard_after(cx: &mut Context) {
3831− let _ = paste_clipboard_impl(
3832− cx.editor,
3833− Paste::After,
3834− ClipboardType::Clipboard,
3835− cx.count(),
3836− );
4163+ paste(cx.editor, '+', Paste::After, cx.count());
4164+ exit_select_mode(cx);
38374165}
38384166
38394167fn paste_clipboard_before(cx: &mut Context) {
3840− let _ = paste_clipboard_impl(
3841− cx.editor,
3842− Paste::Before,
3843− ClipboardType::Clipboard,
3844− cx.count(),
3845− );
4168+ paste(cx.editor, '+', Paste::Before, cx.count());
4169+ exit_select_mode(cx);
38464170}
38474171
38484172fn paste_primary_clipboard_after(cx: &mut Context) {
3849− let _ = paste_clipboard_impl(
3850− cx.editor,
3851− Paste::After,
3852− ClipboardType::Selection,
3853− cx.count(),
3854− );
4173+ paste(cx.editor, '*', Paste::After, cx.count());
4174+ exit_select_mode(cx);
38554175}
38564176
38574177fn paste_primary_clipboard_before(cx: &mut Context) {
3858− let _ = paste_clipboard_impl(
3859− cx.editor,
3860− Paste::Before,
3861− ClipboardType::Selection,
3862− cx.count(),
3863− );
4178+ paste(cx.editor, '*', Paste::Before, cx.count());
4179+ exit_select_mode(cx);
38644180}
38654181
38664182fn replace_with_yanked(cx: &mut Context) {
3867− let count = cx.count();
3868− let reg_name = cx.register.unwrap_or('"');
3869− let (view, doc) = current!(cx.editor);
3870− let registers = &mut cx.editor.registers;
3871−
3872− if let Some(values) = registers.read(reg_name) {
3873− if !values.is_empty() {
3874− let repeat = std::iter::repeat(
3875− values
3876− .last()
3877− .map(|value| Tendril::from(&value.repeat(count)))
3878− .unwrap(),
3879− );
3880− let mut values = values
3881− .iter()
3882− .map(|value| Tendril::from(&value.repeat(count)))
3883− .chain(repeat);
3884− let selection = doc.selection(view.id);
3885− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3886− if !range.is_empty() {
3887− (range.from(), range.to(), Some(values.next().unwrap()))
3888− } else {
3889− (range.from(), range.to(), None)
3890− }
3891− });
3892−
3893− doc.apply(&transaction, view.id);
3894− exit_select_mode(cx);
3895− }
3896− }
4183+ replace_with_yanked_impl(cx.editor, cx.register.unwrap_or('"'), cx.count());
4184+ exit_select_mode(cx);
38974185}
38984186
3899−fn replace_selections_with_clipboard_impl(
3900− cx: &mut Context,
3901− clipboard_type: ClipboardType,
3902−) -> anyhow::Result<()> {
3903− let count = cx.count();
3904− let (view, doc) = current!(cx.editor);
3905−
3906− match cx.editor.clipboard_provider.get_contents(clipboard_type) {
3907− Ok(contents) => {
3908− let selection = doc.selection(view.id);
3909− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3910− (
3911− range.from(),
3912− range.to(),
3913− Some(contents.repeat(count).as_str().into()),
3914− )
3915− });
4187+fn replace_with_yanked_impl(editor: &mut Editor, register: char, count: usize) {
4188+ let Some(values) = editor.registers
4189+ .read(register, editor)
4190+ .filter(|values| values.len() > 0) else { return };
4191+ let values: Vec<_> = values.map(|value| value.to_string()).collect();
39164192
3917− doc.apply(&transaction, view.id);
3918− doc.append_changes_to_history(view);
4193+ let (view, doc) = current!(editor);
4194+ let repeat = std::iter::repeat(
4195+ values
4196+ .last()
4197+ .map(|value| Tendril::from(&value.repeat(count)))
4198+ .unwrap(),
4199+ );
4200+ let mut values = values
4201+ .iter()
4202+ .map(|value| Tendril::from(&value.repeat(count)))
4203+ .chain(repeat);
4204+ let selection = doc.selection(view.id);
4205+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
4206+ if !range.is_empty() {
4207+ (range.from(), range.to(), Some(values.next().unwrap()))
4208+ } else {
4209+ (range.from(), range.to(), None)
39194210 }
3920− Err(e) => return Err(e.context("Couldn't get system clipboard contents")),
3921− }
4211+ });
39224212
3923− exit_select_mode(cx);
3924− Ok(())
4213+ doc.apply(&transaction, view.id);
39254214}
39264215
39274216fn replace_selections_with_clipboard(cx: &mut Context) {
3928− let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Clipboard);
4217+ replace_with_yanked_impl(cx.editor, '+', cx.count());
4218+ exit_select_mode(cx);
39294219}
39304220
39314221fn replace_selections_with_primary_clipboard(cx: &mut Context) {
3932− let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Selection);
4222+ replace_with_yanked_impl(cx.editor, '*', cx.count());
4223+ exit_select_mode(cx);
39334224}
39344225
3935−fn paste(cx: &mut Context, pos: Paste) {
3936− let count = cx.count();
3937− let reg_name = cx.register.unwrap_or('"');
3938− let (view, doc) = current!(cx.editor);
3939− let registers = &mut cx.editor.registers;
4226+fn paste(editor: &mut Editor, register: char, pos: Paste, count: usize) {
4227+ let Some(values) = editor.registers.read(register, editor) else { return };
4228+ let values: Vec<_> = values.map(|value| value.to_string()).collect();
39404229
3941− if let Some(values) = registers.read(reg_name) {
3942− paste_impl(values, doc, view, pos, count, cx.editor.mode);
3943− }
4230+ let (view, doc) = current!(editor);
4231+ paste_impl(&values, doc, view, pos, count, editor.mode);
39444232}
39454233
39464234fn paste_after(cx: &mut Context) {
3947− paste(cx, Paste::After)
4235+ paste(
4236+ cx.editor,
4237+ cx.register.unwrap_or('"'),
4238+ Paste::After,
4239+ cx.count(),
4240+ );
4241+ exit_select_mode(cx);
39484242}
39494243
39504244fn paste_before(cx: &mut Context) {
3951− paste(cx, Paste::Before)
4245+ paste(
4246+ cx.editor,
4247+ cx.register.unwrap_or('"'),
4248+ Paste::Before,
4249+ cx.count(),
4250+ );
4251+ exit_select_mode(cx);
39524252}
39534253
39544254fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
@@ -3987,6 +4287,7 @@ fn indent(cx: &mut Context) {
39874287 }),
39884288 );
39894289 doc.apply(&transaction, view.id);
4290+ exit_select_mode(cx);
39904291}
39914292
39924293fn unindent(cx: &mut Context) {
@@ -4026,71 +4327,76 @@ fn unindent(cx: &mut Context) {
40264327 let transaction = Transaction::change(doc.text(), changes.into_iter());
40274328
40284329 doc.apply(&transaction, view.id);
4330+ exit_select_mode(cx);
40294331}
40304332
40314333fn format_selections(cx: &mut Context) {
40324334 use helix_lsp::{lsp, util::range_to_lsp_range};
40334335
40344336 let (view, doc) = current!(cx.editor);
4337+ let view_id = view.id;
40354338
40364339 // via lsp if available
40374340 // TODO: else via tree-sitter indentation calculations
40384341
4039− let language_server = match doc.language_server() {
4040− Some(language_server) => language_server,
4041− None => return,
4342+ if doc.selection(view_id).len() != 1 {
4343+ cx.editor
4344+ .set_error("format_selections only supports a single selection for now");
4345+ return;
4346+ }
4347+
4348+ // TODO extra LanguageServerFeature::FormatSelections?
4349+ // maybe such that LanguageServerFeature::Format contains it as well
4350+ let Some(language_server) = doc
4351+ .language_servers_with_feature(LanguageServerFeature::Format)
4352+ .find(|ls| {
4353+ matches!(
4354+ ls.capabilities().document_range_formatting_provider,
4355+ Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_))
4356+ )
4357+ })
4358+ else {
4359+ cx.editor
4360+ .set_error("No configured language server supports range formatting");
4361+ return;
40424362 };
40434363
4364+ let offset_encoding = language_server.offset_encoding();
40444365 let ranges: Vec<lsp::Range> = doc
4045− .selection(view.id)
4366+ .selection(view_id)
40464367 .iter()
4047− .map(|range| range_to_lsp_range(doc.text(), *range, language_server.offset_encoding()))
4368+ .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
40484369 .collect();
40494370
4050− if ranges.len() != 1 {
4051− cx.editor
4052− .set_error("format_selections only supports a single selection for now");
4053− return;
4054− }
4055−
40564371 // TODO: handle fails
40574372 // TODO: concurrent map over all ranges
40584373
40594374 let range = ranges[0];
40604375
4061− let request = match language_server.text_document_range_formatting(
4062− doc.identifier(),
4063− range,
4064− lsp::FormattingOptions::default(),
4065− None,
4066− ) {
4067− Some(future) => future,
4068− None => {
4069− cx.editor
4070− .set_error("Language server does not support range formatting");
4071− return;
4072− }
4073− };
4376+ let future = language_server
4377+ .text_document_range_formatting(
4378+ doc.identifier(),
4379+ range,
4380+ lsp::FormattingOptions::default(),
4381+ None,
4382+ )
4383+ .unwrap();
40744384
4075− let edits = tokio::task::block_in_place(|| helix_lsp::block_on(request)).unwrap_or_default();
4385+ let edits = tokio::task::block_in_place(|| helix_lsp::block_on(future)).unwrap_or_default();
40764386
4077− let transaction = helix_lsp::util::generate_transaction_from_edits(
4078− doc.text(),
4079− edits,
4080− language_server.offset_encoding(),
4081− );
4387+ let transaction =
4388+ helix_lsp::util::generate_transaction_from_edits(doc.text(), edits, offset_encoding);
40824389
4083− doc.apply(&transaction, view.id);
4390+ doc.apply(&transaction, view_id);
40844391}
40854392
40864393fn join_selections_impl(cx: &mut Context, select_space: bool) {
40874394 use movement::skip_while;
40884395 let (view, doc) = current!(cx.editor);
40894396 let text = doc.text();
4090− let slice = doc.text().slice(..);
4397+ let slice = text.slice(..);
40914398
40924399 let mut changes = Vec::new();
4093− let fragment = Tendril::from(" ");
40944400
40954401 for selection in doc.selection(view.id) {
40964402 let (start, mut end) = selection.line_range(slice);
@@ -4106,9 +4412,13 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
41064412 let mut end = text.line_to_char(line + 1);
41074413 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
41084414
4109− // need to skip from start, not end
4110− let change = (start, end, Some(fragment.clone()));
4111− changes.push(change);
4415+ let separator = if end == line_end_char_index(&slice, line + 1) {
4416+ // the joining line contains only space-characters => don't include a whitespace when joining
4417+ None
4418+ } else {
4419+ Some(Tendril::from(" "))
4420+ };
4421+ changes.push((start, end, separator));
41124422 }
41134423 }
41144424
@@ -4120,9 +4430,6 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
41204430 changes.sort_unstable_by_key(|(from, _to, _text)| *from);
41214431 changes.dedup();
41224432
4123− // TODO: joining multiple empty lines should be replaced by a single space.
4124− // need to merge change ranges that touch
4125−
41264433 // select inserted spaces
41274434 let transaction = if select_space {
41284435 let ranges: SmallVec<_> = changes
@@ -4134,9 +4441,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
41344441 })
41354442 .collect();
41364443 let selection = Selection::new(ranges, 0);
4137− Transaction::change(doc.text(), changes.into_iter()).with_selection(selection)
4444+ Transaction::change(text, changes.into_iter()).with_selection(selection)
41384445 } else {
4139− Transaction::change(doc.text(), changes.into_iter())
4446+ Transaction::change(text, changes.into_iter())
41404447 };
41414448
41424449 doc.apply(&transaction, view.id);
@@ -4150,8 +4457,8 @@ fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) {
41504457 if remove { "remove:" } else { "keep:" }.into(),
41514458 Some(reg),
41524459 ui::completers::none,
4153− move |editor, regex, event| {
4154− let (view, doc) = current!(editor);
4460+ move |cx, regex, event| {
4461+ let (view, doc) = current!(cx.editor);
41554462 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
41564463 return;
41574464 }
@@ -4210,21 +4517,53 @@ pub fn completion(cx: &mut Context) {
42104517
42114518 let (view, doc) = current!(cx.editor);
42124519
4213− let language_server = match doc.language_server() {
4214− Some(language_server) => language_server,
4215− None => return,
4520+ let savepoint = if let Some(CompleteAction::Selected { savepoint }) = &cx.editor.last_completion
4521+ {
4522+ savepoint.clone()
4523+ } else {
4524+ doc.savepoint(view)
42164525 };
42174526
4218− let offset_encoding = language_server.offset_encoding();
4219− let text = doc.text().slice(..);
4220− let cursor = doc.selection(view.id).primary().cursor(text);
4221−
4222− let pos = pos_to_lsp_pos(doc.text(), cursor, offset_encoding);
4527+ let text = savepoint.text.clone();
4528+ let cursor = savepoint.cursor();
4529+
4530+ let mut seen_language_servers = HashSet::new();
4531+
4532+ let mut futures: FuturesUnordered<_> = doc
4533+ .language_servers_with_feature(LanguageServerFeature::Completion)
4534+ .filter(|ls| seen_language_servers.insert(ls.id()))
4535+ .map(|language_server| {
4536+ let language_server_id = language_server.id();
4537+ let offset_encoding = language_server.offset_encoding();
4538+ let pos = pos_to_lsp_pos(&text, cursor, offset_encoding);
4539+ let doc_id = doc.identifier();
4540+ let completion_request = language_server.completion(doc_id, pos, None).unwrap();
4541+
4542+ async move {
4543+ let json = completion_request.await?;
4544+ let response: Option<lsp::CompletionResponse> = serde_json::from_value(json)?;
4545+
4546+ let items = match response {
4547+ Some(lsp::CompletionResponse::Array(items)) => items,
4548+ // TODO: do something with is_incomplete
4549+ Some(lsp::CompletionResponse::List(lsp::CompletionList {
4550+ is_incomplete: _is_incomplete,
4551+ items,
4552+ })) => items,
4553+ None => Vec::new(),
4554+ }
4555+ .into_iter()
4556+ .map(|item| CompletionItem {
4557+ item,
4558+ language_server_id,
4559+ resolved: false,
4560+ })
4561+ .collect();
42234562
4224− let future = match language_server.completion(doc.identifier(), pos, None) {
4225− Some(future) => future,
4226− None => return,
4227− };
4563+ anyhow::Ok(items)
4564+ }
4565+ })
4566+ .collect();
42284567
42294568 // setup a channel that allows the request to be canceled
42304569 let (tx, rx) = oneshot::channel();
@@ -4233,12 +4572,20 @@ pub fn completion(cx: &mut Context) {
42334572 // and the associated request is automatically dropped
42344573 cx.editor.completion_request_handle = Some(tx);
42354574 let future = async move {
4575+ let items_future = async move {
4576+ let mut items = Vec::new();
4577+ // TODO if one completion request errors, all other completion requests are discarded (even if they're valid)
4578+ while let Some(mut lsp_items) = futures.try_next().await? {
4579+ items.append(&mut lsp_items);
4580+ }
4581+ anyhow::Ok(items)
4582+ };
42364583 tokio::select! {
42374584 biased;
42384585 _ = rx => {
4239− Ok(serde_json::Value::Null)
4586+ Ok(Vec::new())
42404587 }
4241− res = future => {
4588+ res = items_future => {
42424589 res
42434590 }
42444591 }
@@ -4254,12 +4601,6 @@ pub fn completion(cx: &mut Context) {
42544601 iter.reverse();
42554602 let offset = iter.take_while(|ch| chars::char_is_word(*ch)).count();
42564603 let start_offset = cursor.saturating_sub(offset);
4257− let savepoint = if let Some(CompleteAction::Selected { savepoint }) = &cx.editor.last_completion
4258− {
4259− savepoint.clone()
4260− } else {
4261− doc.savepoint(view)
4262− };
42634604
42644605 let trigger_doc = doc.id();
42654606 let trigger_view = view.id;
@@ -4278,9 +4619,9 @@ pub fn completion(cx: &mut Context) {
42784619 },
42794620 ));
42804621
4281− cx.callback(
4282− future,
4283− move |editor, compositor, response: Option<lsp::CompletionResponse>| {
4622+ cx.jobs.callback(async move {
4623+ let items = future.await?;
4624+ let call = move |editor: &mut Editor, compositor: &mut Compositor| {
42844625 let (view, doc) = current_ref!(editor);
42854626 // check if the completion request is stale.
42864627 //
@@ -4291,16 +4632,6 @@ pub fn completion(cx: &mut Context) {
42914632 return;
42924633 }
42934634
4294− let items = match response {
4295− Some(lsp::CompletionResponse::Array(items)) => items,
4296− // TODO: do something with is_incomplete
4297− Some(lsp::CompletionResponse::List(lsp::CompletionList {
4298− is_incomplete: _is_incomplete,
4299− items,
4300− })) => items,
4301− None => Vec::new(),
4302− };
4303−
43044635 if items.is_empty() {
43054636 // editor.set_error("No completion available");
43064637 return;
@@ -4311,7 +4642,6 @@ pub fn completion(cx: &mut Context) {
43114642 editor,
43124643 savepoint,
43134644 items,
4314− offset_encoding,
43154645 start_offset,
43164646 trigger_offset,
43174647 size,
@@ -4325,8 +4655,9 @@ pub fn completion(cx: &mut Context) {
43254655 {
43264656 compositor.remove(SignatureHelp::ID);
43274657 }
4328− },
4329− );
4658+ };
4659+ Ok(Callback::EditorCompositor(Box::new(call)))
4660+ });
43304661}
43314662
43324663// comments
@@ -4361,7 +4692,13 @@ fn rotate_selections_backward(cx: &mut Context) {
43614692 rotate_selections(cx, Direction::Backward)
43624693}
43634694
4364−fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
4695+enum ReorderStrategy {
4696+ RotateForward,
4697+ RotateBackward,
4698+ Reverse,
4699+}
4700+
4701+fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
43654702 let count = cx.count;
43664703 let (view, doc) = current!(cx.editor);
43674704 let text = doc.text().slice(..);
@@ -4379,9 +4716,10 @@ fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
43794716
43804717 for chunk in fragments.chunks_mut(group) {
43814718 // TODO: also modify main index
4382− match direction {
4383− Direction::Forward => chunk.rotate_right(1),
4384− Direction::Backward => chunk.rotate_left(1),
4719+ match strategy {
4720+ ReorderStrategy::RotateForward => chunk.rotate_right(1),
4721+ ReorderStrategy::RotateBackward => chunk.rotate_left(1),
4722+ ReorderStrategy::Reverse => chunk.reverse(),
43854723 };
43864724 }
43874725
@@ -4398,10 +4736,13 @@ fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
43984736}
43994737
44004738fn rotate_selection_contents_forward(cx: &mut Context) {
4401− rotate_selection_contents(cx, Direction::Forward)
4739+ reorder_selection_contents(cx, ReorderStrategy::RotateForward)
44024740}
44034741fn rotate_selection_contents_backward(cx: &mut Context) {
4404− rotate_selection_contents(cx, Direction::Backward)
4742+ reorder_selection_contents(cx, ReorderStrategy::RotateBackward)
4743+}
4744+fn reverse_selection_contents(cx: &mut Context) {
4745+ reorder_selection_contents(cx, ReorderStrategy::Reverse)
44054746}
44064747
44074748// tree sitter node selection
@@ -4425,8 +4766,7 @@ fn expand_selection(cx: &mut Context) {
44254766 }
44264767 }
44274768 };
4428− motion(cx.editor);
4429− cx.editor.last_motion = Some(Motion(Box::new(motion)));
4769+ cx.editor.apply_motion(motion);
44304770}
44314771
44324772fn shrink_selection(cx: &mut Context) {
@@ -4450,8 +4790,7 @@ fn shrink_selection(cx: &mut Context) {
44504790 doc.set_selection(view.id, selection);
44514791 }
44524792 };
4453− motion(cx.editor);
4454− cx.editor.last_motion = Some(Motion(Box::new(motion)));
4793+ cx.editor.apply_motion(motion);
44554794}
44564795
44574796fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: &'static F)
@@ -4469,8 +4808,7 @@ where
44694808 doc.set_selection(view.id, selection);
44704809 }
44714810 };
4472− motion(cx.editor);
4473− cx.editor.last_motion = Some(Motion(Box::new(motion)));
4811+ cx.editor.apply_motion(motion);
44744812}
44754813
44764814fn select_next_sibling(cx: &mut Context) {
@@ -4481,22 +4819,68 @@ fn select_prev_sibling(cx: &mut Context) {
44814819 select_sibling_impl(cx, &|node| Node::prev_sibling(&node))
44824820}
44834821
4822+fn move_node_bound_impl(cx: &mut Context, dir: Direction, movement: Movement) {
4823+ let motion = move |editor: &mut Editor| {
4824+ let (view, doc) = current!(editor);
4825+
4826+ if let Some(syntax) = doc.syntax() {
4827+ let text = doc.text().slice(..);
4828+ let current_selection = doc.selection(view.id);
4829+
4830+ let selection = movement::move_parent_node_end(
4831+ syntax,
4832+ text,
4833+ current_selection.clone(),
4834+ dir,
4835+ movement,
4836+ );
4837+
4838+ doc.set_selection(view.id, selection);
4839+
4840+ // [TODO] temporary workaround until we're not using the idle timer to
4841+ // trigger auto completions any more
4842+ editor.clear_idle_timer();
4843+ }
4844+ };
4845+
4846+ cx.editor.apply_motion(motion);
4847+}
4848+
4849+pub fn move_parent_node_end(cx: &mut Context) {
4850+ move_node_bound_impl(cx, Direction::Forward, Movement::Move)
4851+}
4852+
4853+pub fn move_parent_node_start(cx: &mut Context) {
4854+ move_node_bound_impl(cx, Direction::Backward, Movement::Move)
4855+}
4856+
4857+pub fn extend_parent_node_end(cx: &mut Context) {
4858+ move_node_bound_impl(cx, Direction::Forward, Movement::Extend)
4859+}
4860+
4861+pub fn extend_parent_node_start(cx: &mut Context) {
4862+ move_node_bound_impl(cx, Direction::Backward, Movement::Extend)
4863+}
4864+
44844865fn match_brackets(cx: &mut Context) {
44854866 let (view, doc) = current!(cx.editor);
4867+ let is_select = cx.editor.mode == Mode::Select;
4868+ let text = doc.text();
4869+ let text_slice = text.slice(..);
44864870
4487− if let Some(syntax) = doc.syntax() {
4488− let text = doc.text().slice(..);
4489− let selection = doc.selection(view.id).clone().transform(|range| {
4490− if let Some(pos) =
4491− match_brackets::find_matching_bracket_fuzzy(syntax, doc.text(), range.cursor(text))
4492− {
4493− range.put_cursor(text, pos, cx.editor.mode == Mode::Select)
4494− } else {
4495− range
4496− }
4497− });
4498− doc.set_selection(view.id, selection);
4499− }
4871+ let selection = doc.selection(view.id).clone().transform(|range| {
4872+ let pos = range.cursor(text_slice);
4873+ if let Some(matched_pos) = doc.syntax().map_or_else(
4874+ || match_brackets::find_matching_bracket_plaintext(text.slice(..), pos),
4875+ |syntax| match_brackets::find_matching_bracket_fuzzy(syntax, text.slice(..), pos),
4876+ ) {
4877+ range.put_cursor(text_slice, matched_pos, is_select)
4878+ } else {
4879+ range
4880+ }
4881+ });
4882+
4883+ doc.set_selection(view.id, selection);
45004884}
45014885
45024886//
@@ -4591,17 +4975,19 @@ fn transpose_view(cx: &mut Context) {
45914975 cx.editor.transpose_view()
45924976}
45934977
4594−// split helper, clear it later
4595−fn split(cx: &mut Context, action: Action) {
4596− let (view, doc) = current!(cx.editor);
4978+/// Open a new split in the given direction specified by the action.
4979+///
4980+/// Maintain the current view (both the cursor's position and view in document).
4981+fn split(editor: &mut Editor, action: Action) {
4982+ let (view, doc) = current!(editor);
45974983 let id = doc.id();
45984984 let selection = doc.selection(view.id).clone();
45994985 let offset = view.offset;
46004986
4601− cx.editor.switch(id, action);
4987+ editor.switch(id, action);
46024988
46034989 // match the selection in the previous view
4604− let (view, doc) = current!(cx.editor);
4990+ let (view, doc) = current!(editor);
46054991 doc.set_selection(view.id, selection);
46064992 // match the view scroll offset (switch doesn't handle this fully
46074993 // since the selection is only matched after the split)
@@ -4609,7 +4995,7 @@ fn split(cx: &mut Context, action: Action) {
46094995}
46104996
46114997fn hsplit(cx: &mut Context) {
4612− split(cx, Action::HorizontalSplit);
4998+ split(cx.editor, Action::HorizontalSplit);
46134999}
46145000
46155001fn hsplit_new(cx: &mut Context) {
@@ -4617,7 +5003,7 @@ fn hsplit_new(cx: &mut Context) {
46175003}
46185004
46195005fn vsplit(cx: &mut Context) {
4620− split(cx, Action::VerticalSplit);
5006+ split(cx.editor, Action::VerticalSplit);
46215007}
46225008
46235009fn vsplit_new(cx: &mut Context) {
@@ -4666,7 +5052,12 @@ fn insert_register(cx: &mut Context) {
46665052 if let Some(ch) = event.char() {
46675053 cx.editor.autoinfo = None;
46685054 cx.register = Some(ch);
4669− paste(cx, Paste::Cursor);
5055+ paste(
5056+ cx.editor,
5057+ cx.register.unwrap_or('"'),
5058+ Paste::Cursor,
5059+ cx.count(),
5060+ );
46705061 }
46715062 })
46725063}
@@ -4750,8 +5141,7 @@ fn goto_ts_object_impl(cx: &mut Context, object: &'static str, direction: Direct
47505141 editor.set_status("Syntax-tree is not available in current buffer");
47515142 }
47525143 };
4753− motion(cx.editor);
4754− cx.editor.last_motion = Some(Motion(Box::new(motion)));
5144+ cx.editor.apply_motion(motion);
47555145}
47565146
47575147fn goto_next_function(cx: &mut Context) {
@@ -4872,8 +5262,7 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
48725262 });
48735263 doc.set_selection(view.id, selection);
48745264 };
4875− textobject(cx.editor);
4876− cx.editor.last_motion = Some(Motion(Box::new(textobject)));
5265+ cx.editor.apply_motion(textobject);
48775266 }
48785267 });
48795268
@@ -4963,11 +5352,18 @@ fn surround_replace(cx: &mut Context) {
49635352 }
49645353 };
49655354
5355+ let selection = selection.clone();
5356+ let ranges: SmallVec<[Range; 1]> = change_pos.iter().map(|&p| Range::point(p)).collect();
5357+ doc.set_selection(
5358+ view.id,
5359+ Selection::new(ranges, selection.primary_index() * 2),
5360+ );
5361+
49665362 cx.on_next_key(move |cx, event| {
49675363 let (view, doc) = current!(cx.editor);
49685364 let to = match event.char() {
49695365 Some(to) => to,
4970− None => return,
5366+ None => return doc.set_selection(view.id, selection),
49715367 };
49725368 let (open, close) = surround::get_pair(to);
49735369 let transaction = Transaction::change(
@@ -4978,6 +5374,7 @@ fn surround_replace(cx: &mut Context) {
49785374 (pos, pos + 1, Some(t))
49795375 }),
49805376 );
5377+ doc.set_selection(view.id, selection);
49815378 doc.apply(&transaction, view.id);
49825379 exit_select_mode(cx);
49835380 });
@@ -5126,7 +5523,7 @@ async fn shell_impl_async(
51265523 helix_view::document::to_writer(&mut stdin, (encoding::UTF_8, false), &input)
51275524 .await?;
51285525 }
5129− Ok::<_, anyhow::Error>(())
5526+ anyhow::Ok(())
51305527 });
51315528 let (output, _) = tokio::join! {
51325529 process.wait_with_output(),
@@ -5212,12 +5609,18 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
52125609 };
52135610
52145611 // These `usize`s cannot underflow because selection ranges cannot overlap.
5215− // Once the MSRV is 1.66.0 (mixed_integer_ops is stabilized), we can use checked
5216− // arithmetic to assert this.
5217− let anchor = (to as isize + offset - deleted_len as isize) as usize;
5612+ let anchor = to
5613+ .checked_add_signed(offset)
5614+ .expect("Selection ranges cannot overlap")
5615+ .checked_sub(deleted_len)
5616+ .expect("Selection ranges cannot overlap");
52185617 let new_range = Range::new(anchor, anchor + output_len).with_direction(range.direction());
52195618 ranges.push(new_range);
5220− offset = offset + output_len as isize - deleted_len as isize;
5619+ offset = offset
5620+ .checked_add_unsigned(output_len)
5621+ .expect("Selection ranges cannot overlap")
5622+ .checked_sub_unsigned(deleted_len)
5623+ .expect("Selection ranges cannot overlap");
52215624
52225625 changes.push((from, to, Some(output)));
52235626 }
@@ -5239,7 +5642,7 @@ fn shell_prompt(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBeha
52395642 cx,
52405643 prompt,
52415644 Some('|'),
5242− ui::completers::none,
5645+ ui::completers::filename,
52435646 move |cx, input: &str, event: PromptEvent| {
52445647 if event != PromptEvent::Validate {
52455648 return;
@@ -5356,6 +5759,7 @@ fn increment_impl(cx: &mut Context, increment_direction: IncrementDirection) {
53565759 let transaction = Transaction::change(doc.text(), changes.into_iter());
53575760 let transaction = transaction.with_selection(new_selection);
53585761 doc.apply(&transaction, view.id);
5762+ exit_select_mode(cx);
53595763 }
53605764}
53615765
@@ -5374,9 +5778,12 @@ fn record_macro(cx: &mut Context) {
53745778 }
53755779 })
53765780 .collect::<String>();
5377− cx.editor.registers.write(reg, vec![s]);
5378− cx.editor
5379− .set_status(format!("Recorded to register [{}]", reg));
5781+ match cx.editor.registers.write(reg, vec![s]) {
5782+ Ok(_) => cx
5783+ .editor
5784+ .set_status(format!("Recorded to register [{}]", reg)),
5785+ Err(err) => cx.editor.set_error(err.to_string()),
5786+ }
53805787 } else {
53815788 let reg = cx.register.take().unwrap_or('@');
53825789 cx.editor.macro_recording = Some((reg, Vec::new()));
@@ -5396,8 +5803,14 @@ fn replay_macro(cx: &mut Context) {
53965803 return;
53975804 }
53985805
5399− let keys: Vec<KeyEvent> = if let Some([keys_str]) = cx.editor.registers.read(reg) {
5400− match helix_view::input::parse_macro(keys_str) {
5806+ let keys: Vec<KeyEvent> = if let Some(keys) = cx
5807+ .editor
5808+ .registers
5809+ .read(reg, cx.editor)
5810+ .filter(|values| values.len() == 1)
5811+ .map(|mut values| values.next().unwrap())
5812+ {
5813+ match helix_view::input::parse_macro(&keys) {
54015814 Ok(keys) => keys,
54025815 Err(err) => {
54035816 cx.editor.set_error(format!("Invalid macro: {}", err));