@@ -23,17 +23,17 @@ use helix_core::{
2323 regex::{self, Regex, RegexBuilder},
2424 search::{self, CharMatcher},
2525 selection, shellwords, surround,
26− syntax::LanguageServerFeature,
2726 text_annotations::TextAnnotations,
2827 textobject,
2928 tree_sitter::Node,
3029 unicode::width::UnicodeWidthChar,
31− visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes,
32− RopeReader, RopeSlice, Selection, SmallVec, Tendril, Transaction,
30+ visual_offset_from_block, LineEnding, Position, Range, Rope, RopeGraphemes, RopeSlice,
31+ Selection, SmallVec, Tendril, Transaction,
3332};
3433use helix_view::{
34+ clipboard::ClipboardType,
3535 document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
36− editor::{Action, CompleteAction},
36+ editor::{Action, Motion},
3737 info::Info,
3838 input::KeyEvent,
3939 keyboard::KeyCode,
@@ -43,6 +43,7 @@ use helix_view::{
4343};
4444
4545use anyhow::{anyhow, bail, ensure, Context as _};
46+use fuzzy_matcher::FuzzyMatcher;
4647use insert::*;
4748use movement::Movement;
4849
@@ -53,20 +54,15 @@ use crate::{
5354 job::Callback,
5455 keymap::ReverseKeymap,
5556 ui::{
56− self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem, Picker,
57+ self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, FilePicker, Picker,
5758 Popup, Prompt, PromptEvent,
5859 },
5960};
6061
6162use crate::job::{self, Jobs};
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−};
63+use futures_util::StreamExt;
64+use std::{collections::HashMap, fmt, future::Future};
65+use std::{collections::HashSet, num::NonZeroUsize};
7066
7167use std::{
7268 borrow::Cow,
@@ -75,11 +71,11 @@ use std::{
7571
7672use once_cell::sync::Lazy;
7773use serde::de::{self, Deserialize, Deserializer};
78−use url::Url;
7974
8075use grep_regex::RegexMatcherBuilder;
8176use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
8277use ignore::{DirEntry, WalkBuilder, WalkState};
78+use tokio_stream::wrappers::UnboundedReceiverStream;
8379
8480pub type OnKeyCallback = Box<dyn FnOnce(&mut Context, KeyEvent)>;
8581
@@ -101,13 +97,6 @@ impl<'a> Context<'a> {
10197 }));
10298 }
10399
104− /// Call `replace_or_push` on the Compositor
105− pub fn replace_or_push_layer<T: Component>(&mut self, id: &'static str, component: T) {
106− self.callback = Some(Box::new(move |compositor: &mut Compositor, _| {
107− compositor.replace_or_push(id, component);
108− }));
109− }
110−
111100 #[inline]
112101 pub fn on_next_key(
113102 &mut self,
@@ -250,9 +239,6 @@ impl MappableCommand {
250239 move_next_long_word_start, "Move to start of next long word",
251240 move_prev_long_word_start, "Move to start of previous long word",
252241 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",
256242 extend_next_word_start, "Extend to start of next word",
257243 extend_prev_word_start, "Extend to start of previous word",
258244 extend_next_word_end, "Extend to end of next word",
@@ -260,9 +246,6 @@ impl MappableCommand {
260246 extend_next_long_word_start, "Extend to start of next long word",
261247 extend_prev_long_word_start, "Extend to start of previous long word",
262248 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",
266249 find_till_char, "Move till next occurrence of char",
267250 find_next_char, "Move to next occurrence of char",
268251 extend_till_char, "Extend till next occurrence of char",
@@ -284,7 +267,6 @@ impl MappableCommand {
284267 select_regex, "Select all regex matches inside selections",
285268 split_selection, "Split selections on regex matches",
286269 split_selection_on_newline, "Split selection on newlines",
287− merge_selections, "Merge selections",
288270 merge_consecutive_selections, "Merge consecutive selections",
289271 search, "Search for regex pattern",
290272 rsearch, "Reverse search for regex pattern",
@@ -337,7 +319,7 @@ impl MappableCommand {
337319 goto_implementation, "Goto implementation",
338320 goto_file_start, "Goto line number <n> else file start",
339321 goto_file_end, "Goto file end",
340− goto_file, "Goto files/URLs in selection",
322+ goto_file, "Goto files in selection",
341323 goto_file_hsplit, "Goto files in selection (hsplit)",
342324 goto_file_vsplit, "Goto files in selection (vsplit)",
343325 goto_reference, "Goto references",
@@ -369,7 +351,6 @@ impl MappableCommand {
369351 extend_to_line_end, "Extend to line end",
370352 extend_to_line_end_newline, "Extend to line end",
371353 signature_help, "Show signature help",
372− smart_tab, "Insert tab if all cursors have all whitespace to their left; otherwise, run a separate command.",
373354 insert_tab, "Insert tab char",
374355 insert_newline, "Insert newline char",
375356 delete_char_backward, "Delete previous char",
@@ -384,9 +365,6 @@ impl MappableCommand {
384365 later, "Move forward in history",
385366 commit_undo_checkpoint, "Commit changes to new checkpoint",
386367 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",
390368 yank_joined_to_clipboard, "Join and yank selections to clipboard",
391369 yank_main_selection_to_clipboard, "Yank main selection to clipboard",
392370 yank_joined_to_primary_clipboard, "Join and yank selections to primary clipboard",
@@ -417,7 +395,6 @@ impl MappableCommand {
417395 rotate_selections_backward, "Rotate selections backward",
418396 rotate_selection_contents_forward, "Rotate selection contents forward",
419397 rotate_selection_contents_backward, "Rotate selections contents backward",
420− reverse_selection_contents, "Reverse selections contents",
421398 expand_selection, "Expand selection to parent syntax node",
422399 shrink_selection, "Shrink selection to previously expanded syntax node",
423400 select_next_sibling, "Select next sibling in syntax tree",
@@ -811,50 +788,54 @@ fn extend_to_line_start(cx: &mut Context) {
811788}
812789
813790fn kill_to_line_start(cx: &mut Context) {
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− }
791+ let (view, doc) = current!(cx.editor);
792+ let text = doc.text().slice(..);
793+
794+ let selection = doc.selection(view.id).clone().transform(|range| {
795+ let line = range.cursor_line(text);
796+ let first_char = text.line_to_char(line);
797+ let anchor = range.cursor(text);
798+ let head = if anchor == first_char && line != 0 {
799+ // select until previous line
800+ line_end_char_index(&text, line - 1)
801+ } else if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
802+ if first_char + pos < anchor {
803+ // select until first non-blank in line if cursor is after it
804+ first_char + pos
831805 } else {
832806 // select until start of line
833807 first_char
834− };
835− (head, anchor)
836− },
837− Direction::Backward,
838− );
808+ }
809+ } else {
810+ // select until start of line
811+ first_char
812+ };
813+ Range::new(head, anchor)
814+ });
815+ delete_selection_insert_mode(doc, view, &selection);
816+
817+ lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
839818}
840819
841820fn kill_to_line_end(cx: &mut Context) {
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);
821+ let (view, doc) = current!(cx.editor);
822+ let text = doc.text().slice(..);
848823
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− );
824+ let selection = doc.selection(view.id).clone().transform(|range| {
825+ let line = range.cursor_line(text);
826+ let line_end_pos = line_end_char_index(&text, line);
827+ let pos = range.cursor(text);
828+
829+ let mut new_range = range.put_cursor(text, line_end_pos, true);
830+ // don't want to remove the line separator itself if the cursor doesn't reach the end of line.
831+ if pos != line_end_pos {
832+ new_range.head = line_end_pos;
833+ }
834+ new_range
835+ });
836+ delete_selection_insert_mode(doc, view, &selection);
837+
838+ lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
858839}
859840
860841fn goto_first_nonwhitespace(cx: &mut Context) {
@@ -990,7 +971,6 @@ fn align_selections(cx: &mut Context) {
990971
991972 let transaction = Transaction::change(doc.text(), changes.into_iter());
992973 doc.apply(&transaction, view.id);
993− exit_select_mode(cx);
994974}
995975
996976fn goto_window(cx: &mut Context, align: Align) {
@@ -1082,10 +1062,6 @@ fn move_prev_long_word_start(cx: &mut Context) {
10821062 move_word_impl(cx, movement::move_prev_long_word_start)
10831063}
10841064
1085−fn move_prev_long_word_end(cx: &mut Context) {
1086− move_word_impl(cx, movement::move_prev_long_word_end)
1087−}
1088−
10891065fn move_next_long_word_end(cx: &mut Context) {
10901066 move_word_impl(cx, movement::move_next_long_word_end)
10911067}
@@ -1110,7 +1086,8 @@ where
11101086 .transform(|range| move_fn(text, range, count, behavior));
11111087 doc.set_selection(view.id, selection);
11121088 };
1113− cx.editor.apply_motion(motion)
1089+ motion(cx.editor);
1090+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
11141091}
11151092
11161093fn goto_prev_paragraph(cx: &mut Context) {
@@ -1165,10 +1142,6 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11651142 let (view, doc) = current_ref!(cx.editor);
11661143 let text = doc.text();
11671144 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();
11721145 let mut paths: Vec<_> = selections
11731146 .iter()
11741147 .map(|r| text.slice(r.from()..r.to()).to_string())
@@ -1196,80 +1169,16 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11961169 .to_string(),
11971170 );
11981171 }
1199−
12001172 for sel in paths {
12011173 let p = sel.trim();
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) {
1174+ if !p.is_empty() {
1175+ if let Err(e) = cx.editor.open(&PathBuf::from(p), action) {
12501176 cx.editor.set_error(format!("Open file failed: {:?}", e));
12511177 }
12521178 }
12531179 }
12541180}
12551181
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−
12731182fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
12741183where
12751184 F: Fn(RopeSlice, Range, usize) -> Range,
@@ -1310,74 +1219,14 @@ fn extend_prev_long_word_start(cx: &mut Context) {
13101219 extend_word_impl(cx, movement::move_prev_long_word_start)
13111220}
13121221
1313−fn extend_prev_long_word_end(cx: &mut Context) {
1314− extend_word_impl(cx, movement::move_prev_long_word_end)
1315−}
1316−
13171222fn extend_next_long_word_end(cx: &mut Context) {
13181223 extend_word_impl(cx, movement::move_next_long_word_end)
13191224}
13201225
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) {
1226+fn will_find_char<F>(cx: &mut Context, search_fn: F, inclusive: bool, extend: bool)
1227+where
1228+ F: Fn(RopeSlice, char, usize, usize, bool) -> Option<usize> + 'static,
1229+{
13811230 // TODO: count is reset to 1 before next key so we move it into the closure here.
13821231 // Would be nice to carry over.
13831232 let count = cx.count();
@@ -1390,9 +1239,13 @@ fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bo
13901239 KeyEvent {
13911240 code: KeyCode::Enter,
13921241 ..
1393− } => {
1394− find_char_line_ending(cx, count, direction, inclusive, extend);
1395− return;
1242+ } =>
1243+ // TODO: this isn't quite correct when CRLF is involved.
1244+ // This hack will work in most cases, since documents don't
1245+ // usually mix line endings. But we should fix it eventually
1246+ // anyway.
1247+ {
1248+ doc!(cx.editor).line_ending.as_str().chars().next().unwrap()
13961249 }
13971250
13981251 KeyEvent {
@@ -1405,18 +1258,11 @@ fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bo
14051258 } => ch,
14061259 _ => return,
14071260 };
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− };
14181261
1419− cx.editor.apply_motion(motion);
1262+ find_char_impl(cx.editor, &search_fn, inclusive, extend, ch, count);
1263+ cx.editor.last_motion = Some(Motion(Box::new(move |editor: &mut Editor| {
1264+ find_char_impl(editor, &search_fn, inclusive, true, ch, 1);
1265+ })));
14201266 })
14211267}
14221268
@@ -1495,39 +1341,46 @@ fn find_prev_char_impl(
14951341}
14961342
14971343fn find_till_char(cx: &mut Context) {
1498− find_char(cx, Direction::Forward, false, false);
1344+ will_find_char(cx, find_next_char_impl, false, false)
14991345}
15001346
15011347fn find_next_char(cx: &mut Context) {
1502− find_char(cx, Direction::Forward, true, false)
1348+ will_find_char(cx, find_next_char_impl, true, false)
15031349}
15041350
15051351fn extend_till_char(cx: &mut Context) {
1506− find_char(cx, Direction::Forward, false, true)
1352+ will_find_char(cx, find_next_char_impl, false, true)
15071353}
15081354
15091355fn extend_next_char(cx: &mut Context) {
1510− find_char(cx, Direction::Forward, true, true)
1356+ will_find_char(cx, find_next_char_impl, true, true)
15111357}
15121358
15131359fn till_prev_char(cx: &mut Context) {
1514− find_char(cx, Direction::Backward, false, false)
1360+ will_find_char(cx, find_prev_char_impl, false, false)
15151361}
15161362
15171363fn find_prev_char(cx: &mut Context) {
1518− find_char(cx, Direction::Backward, true, false)
1364+ will_find_char(cx, find_prev_char_impl, true, false)
15191365}
15201366
15211367fn extend_till_prev_char(cx: &mut Context) {
1522− find_char(cx, Direction::Backward, false, true)
1368+ will_find_char(cx, find_prev_char_impl, false, true)
15231369}
15241370
15251371fn extend_prev_char(cx: &mut Context) {
1526− find_char(cx, Direction::Backward, true, true)
1372+ will_find_char(cx, find_prev_char_impl, true, true)
15271373}
15281374
15291375fn repeat_last_motion(cx: &mut Context) {
1530− cx.editor.repeat_last_motion(cx.count())
1376+ let count = cx.count();
1377+ let last_motion = cx.editor.last_motion.take();
1378+ if let Some(m) = &last_motion {
1379+ for _ in 0..count {
1380+ m.run(cx.editor);
1381+ }
1382+ cx.editor.last_motion = last_motion;
1383+ }
15311384}
15321385
15331386fn replace(cx: &mut Context) {
@@ -1594,7 +1447,6 @@ where
15941447 });
15951448
15961449 doc.apply(&transaction, view.id);
1597− exit_select_mode(cx);
15981450}
15991451
16001452fn switch_case(cx: &mut Context) {
@@ -1836,8 +1688,8 @@ fn select_regex(cx: &mut Context) {
18361688 "select:".into(),
18371689 Some(reg),
18381690 ui::completers::none,
1839− move |cx, regex, event| {
1840− let (view, doc) = current!(cx.editor);
1691+ move |editor, regex, event| {
1692+ let (view, doc) = current!(editor);
18411693 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
18421694 return;
18431695 }
@@ -1858,8 +1710,8 @@ fn split_selection(cx: &mut Context) {
18581710 "split:".into(),
18591711 Some(reg),
18601712 ui::completers::none,
1861− move |cx, regex, event| {
1862− let (view, doc) = current!(cx.editor);
1713+ move |editor, regex, event| {
1714+ let (view, doc) = current!(editor);
18631715 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
18641716 return;
18651717 }
@@ -1881,12 +1733,6 @@ fn split_selection_on_newline(cx: &mut Context) {
18811733 doc.set_selection(view.id, selection);
18821734}
18831735
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−
18901736fn merge_consecutive_selections(cx: &mut Context) {
18911737 let (view, doc) = current!(cx.editor);
18921738 let selection = doc.selection(view.id).clone().merge_consecutive_ranges();
@@ -1982,11 +1828,11 @@ fn search_impl(
19821828
19831829fn search_completions(cx: &mut Context, reg: Option<char>) -> Vec<String> {
19841830 let mut items = reg
1985− .and_then(|reg| cx.editor.registers.read(reg, cx.editor))
1986− .map_or(Vec::new(), |reg| reg.take(200).collect());
1831+ .and_then(|reg| cx.editor.registers.get(reg))
1832+ .map_or(Vec::new(), |reg| reg.read().iter().take(200).collect());
19871833 items.sort_unstable();
19881834 items.dedup();
1989− items.into_iter().map(|value| value.to_string()).collect()
1835+ items.into_iter().cloned().collect()
19901836}
19911837
19921838fn search(cx: &mut Context) {
@@ -2023,14 +1869,12 @@ fn searcher(cx: &mut Context, direction: Direction) {
20231869 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
20241870 .collect()
20251871 },
2026− move |cx, regex, event| {
2027− if event == PromptEvent::Validate {
2028− cx.editor.registers.last_search_register = reg;
2029− } else if event != PromptEvent::Update {
1872+ move |editor, regex, event| {
1873+ if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
20301874 return;
20311875 }
20321876 search_impl(
2033− cx.editor,
1877+ editor,
20341878 &contents,
20351879 ®ex,
20361880 Movement::Move,
@@ -2045,13 +1889,11 @@ fn searcher(cx: &mut Context, direction: Direction) {
20451889
20461890fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Direction) {
20471891 let count = cx.count();
2048− let register = cx
2049− .register
2050− .unwrap_or(cx.editor.registers.last_search_register);
20511892 let config = cx.editor.config();
20521893 let scrolloff = config.scrolloff;
2053− if let Some(query) = cx.editor.registers.first(register, cx.editor) {
2054− let doc = doc!(cx.editor);
1894+ let (_, doc) = current!(cx.editor);
1895+ let registers = &cx.editor.registers;
1896+ if let Some(query) = registers.read('/').and_then(|query| query.last()) {
20551897 let contents = doc.text().slice(..).to_string();
20561898 let search_config = &config.search;
20571899 let case_insensitive = if search_config.smart_case {
@@ -2060,7 +1902,7 @@ fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Dir
20601902 false
20611903 };
20621904 let wrap_around = search_config.wrap_around;
2063− if let Ok(regex) = RegexBuilder::new(&query)
1905+ if let Ok(regex) = RegexBuilder::new(query)
20641906 .case_insensitive(case_insensitive)
20651907 .multi_line(true)
20661908 .build()
@@ -2100,7 +1942,6 @@ fn extend_search_prev(cx: &mut Context) {
21001942}
21011943
21021944fn search_selection(cx: &mut Context) {
2103− let register = cx.register.unwrap_or('/');
21041945 let (view, doc) = current!(cx.editor);
21051946 let contents = doc.text().slice(..);
21061947
@@ -2113,24 +1954,13 @@ fn search_selection(cx: &mut Context) {
21131954 .collect::<Vec<_>>()
21141955 .join("|");
21151956
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− }
1957+ let msg = format!("register '{}' set to '{}'", '/', ®ex);
1958+ cx.editor.registers.push('/', regex);
1959+ cx.editor.set_status(msg);
21241960}
21251961
21261962fn make_search_word_bounded(cx: &mut Context) {
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) {
1963+ let regex = match cx.editor.registers.last('/') {
21341964 Some(regex) => regex,
21351965 None => return,
21361966 };
@@ -2148,19 +1978,14 @@ fn make_search_word_bounded(cx: &mut Context) {
21481978 if !start_anchored {
21491979 new_regex.push_str("\\b");
21501980 }
2151− new_regex.push_str(®ex);
1981+ new_regex.push_str(regex);
21521982 if !end_anchored {
21531983 new_regex.push_str("\\b");
21541984 }
21551985
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− }
1986+ let msg = format!("register '{}' set to '{}'", '/', &new_regex);
1987+ cx.editor.registers.push('/', new_regex);
1988+ cx.editor.set_status(msg);
21641989}
21651990
21661991fn global_search(cx: &mut Context) {
@@ -2199,11 +2024,13 @@ fn global_search(cx: &mut Context) {
21992024 }
22002025 }
22012026
2027+ let (all_matches_sx, all_matches_rx) = tokio::sync::mpsc::unbounded_channel::<FileResult>();
22022028 let config = cx.editor.config();
22032029 let smart_case = config.search.smart_case;
22042030 let file_picker_config = config.file_picker.clone();
22052031
22062032 let reg = cx.register.unwrap_or('/');
2033+
22072034 let completions = search_completions(cx, Some(reg));
22082035 ui::regex_prompt(
22092036 cx,
@@ -2216,67 +2043,43 @@ fn global_search(cx: &mut Context) {
22162043 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
22172044 .collect()
22182045 },
2219− move |cx, regex, event| {
2046+ move |_editor, regex, event| {
22202047 if event != PromptEvent::Validate {
22212048 return;
22222049 }
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();
22312050
22322051 if let Ok(matcher) = RegexMatcherBuilder::new()
22332052 .case_smart(smart_case)
22342053 .build(regex.as_str())
22352054 {
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);
2055+ let searcher = SearcherBuilder::new()
2056+ .binary_detection(BinaryDetection::quit(b'\x00'))
2057+ .build();
22442058
2059+ let search_root = std::env::current_dir()
2060+ .expect("Global search error: Failed to get current dir");
22452061 let dedup_symlinks = file_picker_config.deduplicate_links;
22462062 let absolute_root = search_root
22472063 .canonicalize()
22482064 .unwrap_or_else(|_| search_root.clone());
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(|| {
2065+
2066+ WalkBuilder::new(search_root)
2067+ .hidden(file_picker_config.hidden)
2068+ .parents(file_picker_config.parents)
2069+ .ignore(file_picker_config.ignore)
2070+ .follow_links(file_picker_config.follow_symlinks)
2071+ .git_ignore(file_picker_config.git_ignore)
2072+ .git_global(file_picker_config.git_global)
2073+ .git_exclude(file_picker_config.git_exclude)
2074+ .max_depth(file_picker_config.max_depth)
2075+ .filter_entry(move |entry| {
2076+ filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2077+ })
2078+ .build_parallel()
2079+ .run(|| {
22762080 let mut searcher = searcher.clone();
22772081 let matcher = matcher.clone();
2278− let injector = injector_.clone();
2279− let documents = &documents;
2082+ let all_matches_sx = all_matches_sx.clone();
22802083 Box::new(move |entry: Result<DirEntry, ignore::Error>| -> WalkState {
22812084 let entry = match entry {
22822085 Ok(entry) => entry,
@@ -2289,39 +2092,17 @@ fn global_search(cx: &mut Context) {
22892092 _ => return WalkState::Continue,
22902093 };
22912094
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− };
2095+ let result = searcher.search_path(
2096+ &matcher,
2097+ entry.path(),
2098+ sinks::UTF8(|line_num, _| {
2099+ all_matches_sx
2100+ .send(FileResult::new(entry.path(), line_num as usize - 1))
2101+ .unwrap();
2102+
2103+ Ok(true)
2104+ }),
2105+ );
23252106
23262107 if let Err(err) = result {
23272108 log::error!(
@@ -2330,66 +2111,67 @@ fn global_search(cx: &mut Context) {
23302111 err
23312112 );
23322113 }
2333− if stop {
2334− WalkState::Quit
2335− } else {
2336− WalkState::Continue
2337− }
2114+ WalkState::Continue
23382115 })
23392116 });
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− })
23872117 } else {
23882118 // Otherwise do nothing
23892119 // log::warn!("Global Search Invalid Pattern")
23902120 }
23912121 },
23922122 );
2123+
2124+ let current_path = doc_mut!(cx.editor).path().cloned();
2125+
2126+ let show_picker = async move {
2127+ let all_matches: Vec<FileResult> =
2128+ UnboundedReceiverStream::new(all_matches_rx).collect().await;
2129+ let call: job::Callback = Callback::EditorCompositor(Box::new(
2130+ move |editor: &mut Editor, compositor: &mut Compositor| {
2131+ if all_matches.is_empty() {
2132+ editor.set_status("No matches found");
2133+ return;
2134+ }
2135+
2136+ let picker = FilePicker::new(
2137+ all_matches,
2138+ current_path,
2139+ move |cx, FileResult { path, line_num }, action| {
2140+ match cx.editor.open(path, action) {
2141+ Ok(_) => {}
2142+ Err(e) => {
2143+ cx.editor.set_error(format!(
2144+ "Failed to open file '{}': {}",
2145+ path.display(),
2146+ e
2147+ ));
2148+ return;
2149+ }
2150+ }
2151+
2152+ let line_num = *line_num;
2153+ let (view, doc) = current!(cx.editor);
2154+ let text = doc.text();
2155+ if line_num >= text.len_lines() {
2156+ cx.editor.set_error("The line you jumped to does not exist anymore because the file has changed.");
2157+ return;
2158+ }
2159+ let start = text.line_to_char(line_num);
2160+ let end = text.line_to_char((line_num + 1).min(text.len_lines()));
2161+
2162+ doc.set_selection(view.id, Selection::single(start, end));
2163+ align_view(doc, view, Align::Center);
2164+ },
2165+ |_editor, FileResult { path, line_num }| {
2166+ Some((path.clone().into(), Some((*line_num, *line_num))))
2167+ },
2168+ );
2169+ compositor.push(Box::new(overlaid(picker)));
2170+ },
2171+ ));
2172+ Ok(call)
2173+ };
2174+ cx.jobs.callback(show_picker);
23932175}
23942176
23952177enum Extend {
@@ -2512,40 +2294,23 @@ enum Operation {
25122294 Change,
25132295}
25142296
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−
25292297fn delete_selection_impl(cx: &mut Context, op: Operation) {
25302298 let (view, doc) = current!(cx.editor);
25312299
25322300 let selection = doc.selection(view.id);
2533− let only_whole_lines = selection_is_linewise(selection, doc.text());
25342301
25352302 if cx.register != Some('_') {
25362303 // first yank the selection
25372304 let text = doc.text().slice(..);
25382305 let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect();
25392306 let reg_name = cx.register.unwrap_or('"');
2540− if let Err(err) = cx.editor.registers.write(reg_name, values) {
2541− cx.editor.set_error(err.to_string());
2542− return;
2543− }
2307+ cx.editor.registers.write(reg_name, values);
25442308 };
25452309
25462310 // then delete
2547− let transaction =
2548− Transaction::delete_by_selection(doc.text(), selection, |range| (range.from(), range.to()));
2311+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
2312+ (range.from(), range.to(), None)
2313+ });
25492314 doc.apply(&transaction, view.id);
25502315
25512316 match op {
@@ -2554,59 +2319,17 @@ fn delete_selection_impl(cx: &mut Context, op: Operation) {
25542319 exit_select_mode(cx);
25552320 }
25562321 Operation::Change => {
2557− if only_whole_lines {
2558− open_above(cx);
2559− } else {
2560− enter_insert_mode(cx);
2561− }
2322+ enter_insert_mode(cx);
25622323 }
25632324 }
25642325}
25652326
25662327#[inline]
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− }
2328+fn delete_selection_insert_mode(doc: &mut Document, view: &mut View, selection: &Selection) {
2329+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
2330+ (range.from(), range.to(), None)
2331+ });
26082332 doc.apply(&transaction, view.id);
2609− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
26102333}
26112334
26122335fn delete_selection(cx: &mut Context) {
@@ -2680,10 +2403,6 @@ fn insert_mode(cx: &mut Context) {
26802403 .transform(|range| Range::new(range.to(), range.from()));
26812404
26822405 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();
26872406}
26882407
26892408// inserts at the end of each selection
@@ -2720,10 +2439,6 @@ fn append_mode(cx: &mut Context) {
27202439
27212440fn file_picker(cx: &mut Context) {
27222441 let root = find_workspace().0;
2723− if !root.exists() {
2724− cx.editor.set_error("Workspace directory does not exist");
2725− return;
2726− }
27272442 let picker = ui::file_picker(root, &cx.editor.config());
27282443 cx.push_layer(Box::new(overlaid(picker)));
27292444}
@@ -2744,14 +2459,8 @@ fn file_picker_in_current_buffer_directory(cx: &mut Context) {
27442459 let picker = ui::file_picker(path, &cx.editor.config());
27452460 cx.push_layer(Box::new(overlaid(picker)));
27462461}
2747−
27482462fn file_picker_in_current_directory(cx: &mut Context) {
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− }
2463+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("./"));
27552464 let picker = ui::file_picker(cwd, &cx.editor.config());
27562465 cx.push_layer(Box::new(overlaid(picker)));
27572466}
@@ -2810,18 +2519,22 @@ fn buffer_picker(cx: &mut Context) {
28102519 // mru
28112520 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
28122521
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− });
2522+ let picker = FilePicker::new(
2523+ items,
2524+ (),
2525+ |cx, meta, action| {
2526+ cx.editor.switch(meta.id, action);
2527+ },
2528+ |editor, meta| {
2529+ let doc = &editor.documents.get(&meta.id)?;
2530+ let &view_id = doc.selections().keys().next()?;
2531+ let line = doc
2532+ .selection(view_id)
2533+ .primary()
2534+ .cursor_line(doc.text().slice(..));
2535+ Some((meta.id.into(), Some((line, line))))
2536+ },
2537+ );
28252538 cx.push_layer(Box::new(overlaid(picker)));
28262539}
28272540
@@ -2887,7 +2600,7 @@ fn jumplist_picker(cx: &mut Context) {
28872600 }
28882601 };
28892602
2890− let picker = Picker::new(
2603+ let picker = FilePicker::new(
28912604 cx.editor
28922605 .tree
28932606 .views()
@@ -2901,18 +2614,16 @@ fn jumplist_picker(cx: &mut Context) {
29012614 |cx, meta, action| {
29022615 cx.editor.switch(meta.id, action);
29032616 let config = cx.editor.config();
2904− let (view, doc) = (view_mut!(cx.editor), doc_mut!(cx.editor, &meta.id));
2617+ let (view, doc) = current!(cx.editor);
29052618 doc.set_selection(view.id, meta.selection.clone());
2906− if action.align_view(view, doc.id()) {
2907− view.ensure_cursor_in_view_center(doc, config.scrolloff);
2908− }
2619+ view.ensure_cursor_in_view_center(doc, config.scrolloff);
29092620 },
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− });
2621+ |editor, meta| {
2622+ let doc = &editor.documents.get(&meta.id)?;
2623+ let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2624+ Some((meta.path.clone()?.into(), Some((line, line))))
2625+ },
2626+ );
29162627 cx.push_layer(Box::new(overlaid(picker)));
29172628}
29182629
@@ -2946,9 +2657,6 @@ impl ui::menu::Item for MappableCommand {
29462657}
29472658
29482659pub fn command_palette(cx: &mut Context) {
2949− let register = cx.register;
2950− let count = cx.count;
2951−
29522660 cx.callback = Some(Box::new(
29532661 move |compositor: &mut Compositor, cx: &mut compositor::Context| {
29542662 let keymap = compositor.find::<ui::EditorView>().unwrap().keymaps.map()
@@ -2966,8 +2674,8 @@ pub fn command_palette(cx: &mut Context) {
29662674
29672675 let picker = Picker::new(commands, keymap, move |cx, command, _action| {
29682676 let mut ctx = Context {
2969− register,
2970− count,
2677+ register: None,
2678+ count: std::num::NonZeroUsize::new(1),
29712679 editor: cx.editor,
29722680 callback: None,
29732681 on_next_key_callback: None,
@@ -3006,88 +2714,24 @@ fn last_picker(cx: &mut Context) {
30062714 }));
30072715}
30082716
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.
2717+// I inserts at the first nonwhitespace character of each line with a selection
30172718fn insert_at_line_start(cx: &mut Context) {
3018− insert_with_indent(cx, IndentFallbackPos::LineStart);
2719+ goto_first_nonwhitespace(cx);
2720+ enter_insert_mode(cx);
30192721}
30202722
3021−// `A` inserts at the end of each line with a selection.
3022−// If the line is empty, automatically indent.
2723+// A inserts at the end of each line with a selection
30232724fn 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) {
30302725 enter_insert_mode(cx);
3031−
30322726 let (view, doc) = current!(cx.editor);
30332727
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− }
2728+ let selection = doc.selection(view.id).clone().transform(|range| {
2729+ let text = doc.text().slice(..);
2730+ let line = range.cursor_line(text);
2731+ let pos = line_end_char_index(&text, line);
2732+ Range::new(pos, pos)
30872733 });
3088−
3089− transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3090− doc.apply(&transaction, view.id);
2734+ doc.set_selection(view.id, selection);
30912735}
30922736
30932737// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
@@ -3158,7 +2802,6 @@ fn open(cx: &mut Context, open: Open) {
31582802 Open::Below => graphemes::prev_grapheme_boundary(text, range.to()),
31592803 Open::Above => range.from(),
31602804 });
3161−
31622805 let new_line = match open {
31632806 // adjust position to the end of the line (next line - 1)
31642807 Open::Below => cursor_line + 1,
@@ -3166,15 +2809,13 @@ fn open(cx: &mut Context, open: Open) {
31662809 Open::Above => cursor_line,
31672810 };
31682811
3169− let line_num = new_line.saturating_sub(1);
3170−
31712812 // Index to insert newlines after, as well as the char width
31722813 // to use to compensate for those inserted newlines.
31732814 let (line_end_index, line_end_offset_width) = if new_line == 0 {
31742815 (0, 0)
31752816 } else {
31762817 (
3177− line_end_char_index(&text, line_num),
2818+ line_end_char_index(&doc.text().slice(..), new_line.saturating_sub(1)),
31782819 doc.line_ending.len_chars(),
31792820 )
31802821 };
@@ -3182,15 +2823,13 @@ fn open(cx: &mut Context, open: Open) {
31822823 let indent = indent::indent_for_newline(
31832824 doc.language_config(),
31842825 doc.syntax(),
3185− &doc.config.load().indent_heuristic,
31862826 &doc.indent_style,
31872827 doc.tab_width(),
31882828 text,
3189− line_num,
2829+ new_line.saturating_sub(1),
31902830 line_end_index,
31912831 cursor_line,
31922832 );
3193−
31942833 let indent_len = indent.len();
31952834 let mut text = String::with_capacity(1 + indent_len);
31962835 text.push_str(doc.line_ending.as_str());
@@ -3350,7 +2989,7 @@ fn exit_select_mode(cx: &mut Context) {
33502989
33512990fn goto_first_diag(cx: &mut Context) {
33522991 let (view, doc) = current!(cx.editor);
3353− let selection = match doc.shown_diagnostics().next() {
2992+ let selection = match doc.diagnostics().first() {
33542993 Some(diag) => Selection::single(diag.range.start, diag.range.end),
33552994 None => return,
33562995 };
@@ -3359,7 +2998,7 @@ fn goto_first_diag(cx: &mut Context) {
33592998
33602999fn goto_last_diag(cx: &mut Context) {
33613000 let (view, doc) = current!(cx.editor);
3362− let selection = match doc.shown_diagnostics().last() {
3001+ let selection = match doc.diagnostics().last() {
33633002 Some(diag) => Selection::single(diag.range.start, diag.range.end),
33643003 None => return,
33653004 };
@@ -3375,9 +3014,10 @@ fn goto_next_diag(cx: &mut Context) {
33753014 .cursor(doc.text().slice(..));
33763015
33773016 let diag = doc
3378− .shown_diagnostics()
3017+ .diagnostics()
3018+ .iter()
33793019 .find(|diag| diag.range.start > cursor_pos)
3380− .or_else(|| doc.shown_diagnostics().next());
3020+ .or_else(|| doc.diagnostics().first());
33813021
33823022 let selection = match diag {
33833023 Some(diag) => Selection::single(diag.range.start, diag.range.end),
@@ -3395,10 +3035,11 @@ fn goto_prev_diag(cx: &mut Context) {
33953035 .cursor(doc.text().slice(..));
33963036
33973037 let diag = doc
3398− .shown_diagnostics()
3038+ .diagnostics()
3039+ .iter()
33993040 .rev()
34003041 .find(|diag| diag.range.start < cursor_pos)
3401− .or_else(|| doc.shown_diagnostics().last());
3042+ .or_else(|| doc.diagnostics().last());
34023043
34033044 let selection = match diag {
34043045 // NOTE: the selection is reversed because we're jumping to the
@@ -3489,7 +3130,8 @@ fn goto_next_change_impl(cx: &mut Context, direction: Direction) {
34893130
34903131 doc.set_selection(view.id, selection)
34913132 };
3492− cx.editor.apply_motion(motion);
3133+ motion(cx.editor);
3134+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
34933135}
34943136
34953137/// Returns the [Range] for a [Hunk] in the given text.
@@ -3552,19 +3194,23 @@ pub mod insert {
35523194 use helix_lsp::lsp;
35533195 // if ch matches completion char, trigger completion
35543196 let doc = doc_mut!(cx.editor);
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− });
3197+ let language_server = match doc.language_server() {
3198+ Some(language_server) => language_server,
3199+ None => return,
3200+ };
3201+
3202+ let capabilities = language_server.capabilities();
35643203
3565− if trigger_completion {
3566− cx.editor.clear_idle_timer();
3567− super::completion(cx);
3204+ if let Some(lsp::CompletionOptions {
3205+ trigger_characters: Some(triggers),
3206+ ..
3207+ }) = &capabilities.completion_provider
3208+ {
3209+ // TODO: what if trigger is multiple chars long
3210+ if triggers.iter().any(|trigger| trigger.contains(ch)) {
3211+ cx.editor.clear_idle_timer();
3212+ super::completion(cx);
3213+ }
35683214 }
35693215 }
35703216
@@ -3572,12 +3218,12 @@ pub mod insert {
35723218 use helix_lsp::lsp;
35733219 // if ch matches signature_help char, trigger
35743220 let doc = doc_mut!(cx.editor);
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;
3221+ // The language_server!() macro is not used here since it will
3222+ // print an "LSP not active for current buffer" message on
3223+ // every keypress.
3224+ let language_server = match doc.language_server() {
3225+ Some(language_server) => language_server,
3226+ None => return,
35813227 };
35823228
35833229 let capabilities = language_server.capabilities();
@@ -3616,7 +3262,6 @@ pub mod insert {
36163262 }
36173263
36183264 use helix_core::auto_pairs;
3619− use helix_view::editor::SmartTabConfig;
36203265
36213266 pub fn insert_char(cx: &mut Context, c: char) {
36223267 let (view, doc) = current_ref!(cx.editor);
@@ -3642,31 +3287,6 @@ pub mod insert {
36423287 }
36433288 }
36443289
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−
36703290 pub fn insert_tab(cx: &mut Context) {
36713291 let (view, doc) = current!(cx.editor);
36723292 // TODO: round out to nearest indentation level (for example a line with 3 spaces should
@@ -3722,7 +3342,6 @@ pub mod insert {
37223342 let indent = indent::indent_for_newline(
37233343 doc.language_config(),
37243344 doc.syntax(),
3725− &doc.config.load().indent_heuristic,
37263345 &doc.indent_style,
37273346 doc.tab_width(),
37283347 text,
@@ -3796,10 +3415,10 @@ pub mod insert {
37963415 let auto_pairs = doc.auto_pairs(cx.editor);
37973416
37983417 let transaction =
3799− Transaction::delete_by_selection(doc.text(), doc.selection(view.id), |range| {
3418+ Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
38003419 let pos = range.cursor(text);
38013420 if pos == 0 {
3802− return (pos, pos);
3421+ return (pos, pos, None);
38033422 }
38043423 let line_start_pos = text.line_to_char(range.cursor_line(text));
38053424 // consider to delete by indent level if all characters before `pos` are indent units.
@@ -3807,7 +3426,11 @@ pub mod insert {
38073426 if !fragment.is_empty() && fragment.chars().all(|ch| ch == ' ' || ch == '\t') {
38083427 if text.get_char(pos.saturating_sub(1)) == Some('\t') {
38093428 // fast path, delete one char
3810− (graphemes::nth_prev_grapheme_boundary(text, pos, 1), pos)
3429+ (
3430+ graphemes::nth_prev_grapheme_boundary(text, pos, 1),
3431+ pos,
3432+ None,
3433+ )
38113434 } else {
38123435 let width: usize = fragment
38133436 .chars()
@@ -3834,7 +3457,7 @@ pub mod insert {
38343457 _ => break,
38353458 }
38363459 }
3837− (start, pos) // delete!
3460+ (start, pos, None) // delete!
38383461 }
38393462 } else {
38403463 match (
@@ -3852,12 +3475,17 @@ pub mod insert {
38523475 (
38533476 graphemes::nth_prev_grapheme_boundary(text, pos, count),
38543477 graphemes::nth_next_grapheme_boundary(text, pos, count),
3478+ None,
38553479 )
38563480 }
38573481 _ =>
38583482 // delete 1 char
38593483 {
3860− (graphemes::nth_prev_grapheme_boundary(text, pos, count), pos)
3484+ (
3485+ graphemes::nth_prev_grapheme_boundary(text, pos, count),
3486+ pos,
3487+ None,
3488+ )
38613489 }
38623490 }
38633491 }
@@ -3870,40 +3498,50 @@ pub mod insert {
38703498
38713499 pub fn delete_char_forward(cx: &mut Context) {
38723500 let count = cx.count();
3873− delete_by_selection_insert_mode(
3874− cx,
3875− |text, range| {
3501+ let (view, doc) = current!(cx.editor);
3502+ let text = doc.text().slice(..);
3503+ let transaction =
3504+ Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
38763505 let pos = range.cursor(text);
3877− (pos, graphemes::nth_next_grapheme_boundary(text, pos, count))
3878− },
3879− Direction::Forward,
3880− )
3506+ (
3507+ pos,
3508+ graphemes::nth_next_grapheme_boundary(text, pos, count),
3509+ None,
3510+ )
3511+ });
3512+ doc.apply(&transaction, view.id);
3513+
3514+ lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
38813515 }
38823516
38833517 pub fn delete_word_backward(cx: &mut Context) {
38843518 let count = cx.count();
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− );
3519+ let (view, doc) = current!(cx.editor);
3520+ let text = doc.text().slice(..);
3521+
3522+ let selection = doc.selection(view.id).clone().transform(|range| {
3523+ let anchor = movement::move_prev_word_start(text, range, count).from();
3524+ let next = Range::new(anchor, range.cursor(text));
3525+ exclude_cursor(text, next, range)
3526+ });
3527+ delete_selection_insert_mode(doc, view, &selection);
3528+
3529+ lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
38953530 }
38963531
38973532 pub fn delete_word_forward(cx: &mut Context) {
38983533 let count = cx.count();
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− );
3534+ let (view, doc) = current!(cx.editor);
3535+ let text = doc.text().slice(..);
3536+
3537+ let selection = doc.selection(view.id).clone().transform(|range| {
3538+ let head = movement::move_next_word_end(text, range, count).to();
3539+ Range::new(range.cursor(text), head)
3540+ });
3541+
3542+ delete_selection_insert_mode(doc, view, &selection);
3543+
3544+ lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
39073545 }
39083546}
39093547
@@ -3963,21 +3601,34 @@ fn commit_undo_checkpoint(cx: &mut Context) {
39633601// Yank / Paste
39643602
39653603fn yank(cx: &mut Context) {
3966− yank_impl(cx.editor, cx.register.unwrap_or('"'));
3967− exit_select_mode(cx);
3968−}
3604+ let (view, doc) = current!(cx.editor);
3605+ let text = doc.text().slice(..);
39693606
3970−fn yank_to_clipboard(cx: &mut Context) {
3971− yank_impl(cx.editor, '+');
3972− exit_select_mode(cx);
3973−}
3607+ let values: Vec<String> = doc
3608+ .selection(view.id)
3609+ .fragments(text)
3610+ .map(Cow::into_owned)
3611+ .collect();
39743612
3975−fn yank_to_primary_clipboard(cx: &mut Context) {
3976− yank_impl(cx.editor, '*');
3613+ let msg = format!(
3614+ "yanked {} selection(s) to register {}",
3615+ values.len(),
3616+ cx.register.unwrap_or('"')
3617+ );
3618+
3619+ cx.editor
3620+ .registers
3621+ .write(cx.register.unwrap_or('"'), values);
3622+
3623+ cx.editor.set_status(msg);
39773624 exit_select_mode(cx);
39783625}
39793626
3980−fn yank_impl(editor: &mut Editor, register: char) {
3627+fn yank_joined_to_clipboard_impl(
3628+ editor: &mut Editor,
3629+ separator: &str,
3630+ clipboard_type: ClipboardType,
3631+) -> anyhow::Result<()> {
39813632 let (view, doc) = current!(editor);
39823633 let text = doc.text().slice(..);
39833634
@@ -3986,79 +3637,74 @@ fn yank_impl(editor: &mut Editor, register: char) {
39863637 .fragments(text)
39873638 .map(Cow::into_owned)
39883639 .collect();
3989− let selections = values.len();
39903640
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−}
3641+ let clipboard_text = match clipboard_type {
3642+ ClipboardType::Clipboard => "system clipboard",
3643+ ClipboardType::Selection => "primary clipboard",
3644+ };
39993645
4000−fn yank_joined_impl(editor: &mut Editor, separator: &str, register: char) {
4001− let (view, doc) = current!(editor);
4002− let text = doc.text().slice(..);
3646+ let msg = format!(
3647+ "joined and yanked {} selection(s) to {}",
3648+ values.len(),
3649+ clipboard_text,
3650+ );
40033651
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− });
3652+ let joined = values.join(separator);
40153653
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−}
3654+ editor
3655+ .clipboard_provider
3656+ .set_contents(joined, clipboard_type)
3657+ .context("Couldn't set system clipboard content")?;
40243658
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);
4029−}
3659+ editor.set_status(msg);
40303660
4031−fn yank_joined_to_clipboard(cx: &mut Context) {
4032− let line_ending = doc!(cx.editor).line_ending;
4033− yank_joined_impl(cx.editor, line_ending.as_str(), '+');
4034− exit_select_mode(cx);
3661+ Ok(())
40353662}
40363663
4037−fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3664+fn yank_joined_to_clipboard(cx: &mut Context) {
40383665 let line_ending = doc!(cx.editor).line_ending;
4039− yank_joined_impl(cx.editor, line_ending.as_str(), '*');
3666+ let _ =
3667+ yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Clipboard);
40403668 exit_select_mode(cx);
40413669}
40423670
4043−fn yank_primary_selection_impl(editor: &mut Editor, register: char) {
3671+fn yank_main_selection_to_clipboard_impl(
3672+ editor: &mut Editor,
3673+ clipboard_type: ClipboardType,
3674+) -> anyhow::Result<()> {
40443675 let (view, doc) = current!(editor);
40453676 let text = doc.text().slice(..);
40463677
4047− let selection = doc.selection(view.id).primary().fragment(text).to_string();
3678+ let message_text = match clipboard_type {
3679+ ClipboardType::Clipboard => "yanked main selection to system clipboard",
3680+ ClipboardType::Selection => "yanked main selection to primary clipboard",
3681+ };
40483682
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()),
3683+ let value = doc.selection(view.id).primary().fragment(text);
3684+
3685+ if let Err(e) = editor
3686+ .clipboard_provider
3687+ .set_contents(value.into_owned(), clipboard_type)
3688+ {
3689+ bail!("Couldn't set system clipboard content: {}", e);
40523690 }
3691+
3692+ editor.set_status(message_text);
3693+ Ok(())
40533694}
40543695
40553696fn yank_main_selection_to_clipboard(cx: &mut Context) {
4056− yank_primary_selection_impl(cx.editor, '+');
4057− exit_select_mode(cx);
3697+ let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Clipboard);
3698+}
3699+
3700+fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3701+ let line_ending = doc!(cx.editor).line_ending;
3702+ let _ =
3703+ yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Selection);
40583704}
40593705
40603706fn yank_main_selection_to_primary_clipboard(cx: &mut Context) {
4061− yank_primary_selection_impl(cx.editor, '*');
3707+ let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Selection);
40623708 exit_select_mode(cx);
40633709}
40643710
@@ -4156,99 +3802,146 @@ pub(crate) fn paste_bracketed_value(cx: &mut Context, contents: String) {
41563802 };
41573803 let (view, doc) = current!(cx.editor);
41583804 paste_impl(&[contents], doc, view, paste, count, cx.editor.mode);
4159− exit_select_mode(cx);
3805+}
3806+
3807+fn paste_clipboard_impl(
3808+ editor: &mut Editor,
3809+ action: Paste,
3810+ clipboard_type: ClipboardType,
3811+ count: usize,
3812+) -> anyhow::Result<()> {
3813+ let (view, doc) = current!(editor);
3814+ match editor.clipboard_provider.get_contents(clipboard_type) {
3815+ Ok(contents) => {
3816+ paste_impl(&[contents], doc, view, action, count, editor.mode);
3817+ Ok(())
3818+ }
3819+ Err(e) => Err(e.context("Couldn't get system clipboard contents")),
3820+ }
41603821}
41613822
41623823fn paste_clipboard_after(cx: &mut Context) {
4163− paste(cx.editor, '+', Paste::After, cx.count());
4164− exit_select_mode(cx);
3824+ let _ = paste_clipboard_impl(
3825+ cx.editor,
3826+ Paste::After,
3827+ ClipboardType::Clipboard,
3828+ cx.count(),
3829+ );
41653830}
41663831
41673832fn paste_clipboard_before(cx: &mut Context) {
4168− paste(cx.editor, '+', Paste::Before, cx.count());
4169− exit_select_mode(cx);
3833+ let _ = paste_clipboard_impl(
3834+ cx.editor,
3835+ Paste::Before,
3836+ ClipboardType::Clipboard,
3837+ cx.count(),
3838+ );
41703839}
41713840
41723841fn paste_primary_clipboard_after(cx: &mut Context) {
4173− paste(cx.editor, '*', Paste::After, cx.count());
4174− exit_select_mode(cx);
3842+ let _ = paste_clipboard_impl(
3843+ cx.editor,
3844+ Paste::After,
3845+ ClipboardType::Selection,
3846+ cx.count(),
3847+ );
41753848}
41763849
41773850fn paste_primary_clipboard_before(cx: &mut Context) {
4178− paste(cx.editor, '*', Paste::Before, cx.count());
4179− exit_select_mode(cx);
3851+ let _ = paste_clipboard_impl(
3852+ cx.editor,
3853+ Paste::Before,
3854+ ClipboardType::Selection,
3855+ cx.count(),
3856+ );
41803857}
41813858
41823859fn replace_with_yanked(cx: &mut Context) {
4183− replace_with_yanked_impl(cx.editor, cx.register.unwrap_or('"'), cx.count());
4184− exit_select_mode(cx);
3860+ let count = cx.count();
3861+ let reg_name = cx.register.unwrap_or('"');
3862+ let (view, doc) = current!(cx.editor);
3863+ let registers = &mut cx.editor.registers;
3864+
3865+ if let Some(values) = registers.read(reg_name) {
3866+ if !values.is_empty() {
3867+ let repeat = std::iter::repeat(
3868+ values
3869+ .last()
3870+ .map(|value| Tendril::from(&value.repeat(count)))
3871+ .unwrap(),
3872+ );
3873+ let mut values = values
3874+ .iter()
3875+ .map(|value| Tendril::from(&value.repeat(count)))
3876+ .chain(repeat);
3877+ let selection = doc.selection(view.id);
3878+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3879+ if !range.is_empty() {
3880+ (range.from(), range.to(), Some(values.next().unwrap()))
3881+ } else {
3882+ (range.from(), range.to(), None)
3883+ }
3884+ });
3885+
3886+ doc.apply(&transaction, view.id);
3887+ exit_select_mode(cx);
3888+ }
3889+ }
41853890}
41863891
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();
3892+fn replace_selections_with_clipboard_impl(
3893+ cx: &mut Context,
3894+ clipboard_type: ClipboardType,
3895+) -> anyhow::Result<()> {
3896+ let count = cx.count();
3897+ let (view, doc) = current!(cx.editor);
41923898
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)
3899+ match cx.editor.clipboard_provider.get_contents(clipboard_type) {
3900+ Ok(contents) => {
3901+ let selection = doc.selection(view.id);
3902+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3903+ (
3904+ range.from(),
3905+ range.to(),
3906+ Some(contents.repeat(count).as_str().into()),
3907+ )
3908+ });
3909+
3910+ doc.apply(&transaction, view.id);
3911+ doc.append_changes_to_history(view);
42103912 }
4211− });
3913+ Err(e) => return Err(e.context("Couldn't get system clipboard contents")),
3914+ }
42123915
4213− doc.apply(&transaction, view.id);
3916+ exit_select_mode(cx);
3917+ Ok(())
42143918}
42153919
42163920fn replace_selections_with_clipboard(cx: &mut Context) {
4217− replace_with_yanked_impl(cx.editor, '+', cx.count());
4218− exit_select_mode(cx);
3921+ let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Clipboard);
42193922}
42203923
42213924fn replace_selections_with_primary_clipboard(cx: &mut Context) {
4222− replace_with_yanked_impl(cx.editor, '*', cx.count());
4223− exit_select_mode(cx);
3925+ let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Selection);
42243926}
42253927
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();
3928+fn paste(cx: &mut Context, pos: Paste) {
3929+ let count = cx.count();
3930+ let reg_name = cx.register.unwrap_or('"');
3931+ let (view, doc) = current!(cx.editor);
3932+ let registers = &mut cx.editor.registers;
42293933
4230− let (view, doc) = current!(editor);
4231− paste_impl(&values, doc, view, pos, count, editor.mode);
3934+ if let Some(values) = registers.read(reg_name) {
3935+ paste_impl(values, doc, view, pos, count, cx.editor.mode);
3936+ }
42323937}
42333938
42343939fn paste_after(cx: &mut Context) {
4235− paste(
4236− cx.editor,
4237− cx.register.unwrap_or('"'),
4238− Paste::After,
4239− cx.count(),
4240− );
4241− exit_select_mode(cx);
3940+ paste(cx, Paste::After)
42423941}
42433942
42443943fn paste_before(cx: &mut Context) {
4245− paste(
4246− cx.editor,
4247− cx.register.unwrap_or('"'),
4248− Paste::Before,
4249− cx.count(),
4250− );
4251− exit_select_mode(cx);
3944+ paste(cx, Paste::Before)
42523945}
42533946
42543947fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
@@ -4287,7 +3980,6 @@ fn indent(cx: &mut Context) {
42873980 }),
42883981 );
42893982 doc.apply(&transaction, view.id);
4290− exit_select_mode(cx);
42913983}
42923984
42933985fn unindent(cx: &mut Context) {
@@ -4327,76 +4019,71 @@ fn unindent(cx: &mut Context) {
43274019 let transaction = Transaction::change(doc.text(), changes.into_iter());
43284020
43294021 doc.apply(&transaction, view.id);
4330− exit_select_mode(cx);
43314022}
43324023
43334024fn format_selections(cx: &mut Context) {
43344025 use helix_lsp::{lsp, util::range_to_lsp_range};
43354026
43364027 let (view, doc) = current!(cx.editor);
4337− let view_id = view.id;
43384028
43394029 // via lsp if available
43404030 // TODO: else via tree-sitter indentation calculations
43414031
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;
4032+ let language_server = match doc.language_server() {
4033+ Some(language_server) => language_server,
4034+ None => return,
43624035 };
43634036
4364− let offset_encoding = language_server.offset_encoding();
43654037 let ranges: Vec<lsp::Range> = doc
4366− .selection(view_id)
4038+ .selection(view.id)
43674039 .iter()
4368− .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
4040+ .map(|range| range_to_lsp_range(doc.text(), *range, language_server.offset_encoding()))
43694041 .collect();
43704042
4043+ if ranges.len() != 1 {
4044+ cx.editor
4045+ .set_error("format_selections only supports a single selection for now");
4046+ return;
4047+ }
4048+
43714049 // TODO: handle fails
43724050 // TODO: concurrent map over all ranges
43734051
43744052 let range = ranges[0];
43754053
4376− let future = language_server
4377− .text_document_range_formatting(
4378− doc.identifier(),
4379− range,
4380− lsp::FormattingOptions::default(),
4381− None,
4382− )
4383− .unwrap();
4054+ let request = match language_server.text_document_range_formatting(
4055+ doc.identifier(),
4056+ range,
4057+ lsp::FormattingOptions::default(),
4058+ None,
4059+ ) {
4060+ Some(future) => future,
4061+ None => {
4062+ cx.editor
4063+ .set_error("Language server does not support range formatting");
4064+ return;
4065+ }
4066+ };
43844067
4385− let edits = tokio::task::block_in_place(|| helix_lsp::block_on(future)).unwrap_or_default();
4068+ let edits = tokio::task::block_in_place(|| helix_lsp::block_on(request)).unwrap_or_default();
43864069
4387− let transaction =
4388− helix_lsp::util::generate_transaction_from_edits(doc.text(), edits, offset_encoding);
4070+ let transaction = helix_lsp::util::generate_transaction_from_edits(
4071+ doc.text(),
4072+ edits,
4073+ language_server.offset_encoding(),
4074+ );
43894075
4390− doc.apply(&transaction, view_id);
4076+ doc.apply(&transaction, view.id);
43914077}
43924078
43934079fn join_selections_impl(cx: &mut Context, select_space: bool) {
43944080 use movement::skip_while;
43954081 let (view, doc) = current!(cx.editor);
43964082 let text = doc.text();
4397− let slice = text.slice(..);
4083+ let slice = doc.text().slice(..);
43984084
43994085 let mut changes = Vec::new();
4086+ let fragment = Tendril::from(" ");
44004087
44014088 for selection in doc.selection(view.id) {
44024089 let (start, mut end) = selection.line_range(slice);
@@ -4412,13 +4099,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44124099 let mut end = text.line_to_char(line + 1);
44134100 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
44144101
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));
4102+ // need to skip from start, not end
4103+ let change = (start, end, Some(fragment.clone()));
4104+ changes.push(change);
44224105 }
44234106 }
44244107
@@ -4430,6 +4113,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44304113 changes.sort_unstable_by_key(|(from, _to, _text)| *from);
44314114 changes.dedup();
44324115
4116+ // TODO: joining multiple empty lines should be replaced by a single space.
4117+ // need to merge change ranges that touch
4118+
44334119 // select inserted spaces
44344120 let transaction = if select_space {
44354121 let ranges: SmallVec<_> = changes
@@ -4441,9 +4127,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44414127 })
44424128 .collect();
44434129 let selection = Selection::new(ranges, 0);
4444− Transaction::change(text, changes.into_iter()).with_selection(selection)
4130+ Transaction::change(doc.text(), changes.into_iter()).with_selection(selection)
44454131 } else {
4446− Transaction::change(text, changes.into_iter())
4132+ Transaction::change(doc.text(), changes.into_iter())
44474133 };
44484134
44494135 doc.apply(&transaction, view.id);
@@ -4457,8 +4143,8 @@ fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) {
44574143 if remove { "remove:" } else { "keep:" }.into(),
44584144 Some(reg),
44594145 ui::completers::none,
4460− move |cx, regex, event| {
4461− let (view, doc) = current!(cx.editor);
4146+ move |editor, regex, event| {
4147+ let (view, doc) = current!(editor);
44624148 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
44634149 return;
44644150 }
@@ -4517,53 +4203,21 @@ pub fn completion(cx: &mut Context) {
45174203
45184204 let (view, doc) = current!(cx.editor);
45194205
4520− let savepoint = if let Some(CompleteAction::Selected { savepoint }) = &cx.editor.last_completion
4521− {
4522− savepoint.clone()
4523− } else {
4524− doc.savepoint(view)
4206+ let language_server = match doc.language_server() {
4207+ Some(language_server) => language_server,
4208+ None => return,
45254209 };
45264210
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();
4211+ let offset_encoding = language_server.offset_encoding();
4212+ let text = doc.text().slice(..);
4213+ let cursor = doc.selection(view.id).primary().cursor(text);
45624214
4563− anyhow::Ok(items)
4564− }
4565− })
4566− .collect();
4215+ let pos = pos_to_lsp_pos(doc.text(), cursor, offset_encoding);
4216+
4217+ let future = match language_server.completion(doc.identifier(), pos, None) {
4218+ Some(future) => future,
4219+ None => return,
4220+ };
45674221
45684222 // setup a channel that allows the request to be canceled
45694223 let (tx, rx) = oneshot::channel();
@@ -4572,20 +4226,12 @@ pub fn completion(cx: &mut Context) {
45724226 // and the associated request is automatically dropped
45734227 cx.editor.completion_request_handle = Some(tx);
45744228 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− };
45834229 tokio::select! {
45844230 biased;
45854231 _ = rx => {
4586− Ok(Vec::new())
4232+ Ok(serde_json::Value::Null)
45874233 }
4588− res = items_future => {
4234+ res = future => {
45894235 res
45904236 }
45914237 }
@@ -4601,6 +4247,7 @@ pub fn completion(cx: &mut Context) {
46014247 iter.reverse();
46024248 let offset = iter.take_while(|ch| chars::char_is_word(*ch)).count();
46034249 let start_offset = cursor.saturating_sub(offset);
4250+ let savepoint = doc.savepoint(view);
46044251
46054252 let trigger_doc = doc.id();
46064253 let trigger_view = view.id;
@@ -4619,9 +4266,9 @@ pub fn completion(cx: &mut Context) {
46194266 },
46204267 ));
46214268
4622− cx.jobs.callback(async move {
4623− let items = future.await?;
4624− let call = move |editor: &mut Editor, compositor: &mut Compositor| {
4269+ cx.callback(
4270+ future,
4271+ move |editor, compositor, response: Option<lsp::CompletionResponse>| {
46254272 let (view, doc) = current_ref!(editor);
46264273 // check if the completion request is stale.
46274274 //
@@ -4632,6 +4279,16 @@ pub fn completion(cx: &mut Context) {
46324279 return;
46334280 }
46344281
4282+ let items = match response {
4283+ Some(lsp::CompletionResponse::Array(items)) => items,
4284+ // TODO: do something with is_incomplete
4285+ Some(lsp::CompletionResponse::List(lsp::CompletionList {
4286+ is_incomplete: _is_incomplete,
4287+ items,
4288+ })) => items,
4289+ None => Vec::new(),
4290+ };
4291+
46354292 if items.is_empty() {
46364293 // editor.set_error("No completion available");
46374294 return;
@@ -4642,6 +4299,7 @@ pub fn completion(cx: &mut Context) {
46424299 editor,
46434300 savepoint,
46444301 items,
4302+ offset_encoding,
46454303 start_offset,
46464304 trigger_offset,
46474305 size,
@@ -4655,9 +4313,8 @@ pub fn completion(cx: &mut Context) {
46554313 {
46564314 compositor.remove(SignatureHelp::ID);
46574315 }
4658− };
4659− Ok(Callback::EditorCompositor(Box::new(call)))
4660− });
4316+ },
4317+ );
46614318}
46624319
46634320// comments
@@ -4692,13 +4349,7 @@ fn rotate_selections_backward(cx: &mut Context) {
46924349 rotate_selections(cx, Direction::Backward)
46934350}
46944351
4695−enum ReorderStrategy {
4696− RotateForward,
4697− RotateBackward,
4698− Reverse,
4699−}
4700−
4701−fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
4352+fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
47024353 let count = cx.count;
47034354 let (view, doc) = current!(cx.editor);
47044355 let text = doc.text().slice(..);
@@ -4716,10 +4367,9 @@ fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
47164367
47174368 for chunk in fragments.chunks_mut(group) {
47184369 // TODO: also modify main index
4719− match strategy {
4720− ReorderStrategy::RotateForward => chunk.rotate_right(1),
4721− ReorderStrategy::RotateBackward => chunk.rotate_left(1),
4722− ReorderStrategy::Reverse => chunk.reverse(),
4370+ match direction {
4371+ Direction::Forward => chunk.rotate_right(1),
4372+ Direction::Backward => chunk.rotate_left(1),
47234373 };
47244374 }
47254375
@@ -4736,13 +4386,10 @@ fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
47364386}
47374387
47384388fn rotate_selection_contents_forward(cx: &mut Context) {
4739− reorder_selection_contents(cx, ReorderStrategy::RotateForward)
4389+ rotate_selection_contents(cx, Direction::Forward)
47404390}
47414391fn rotate_selection_contents_backward(cx: &mut Context) {
4742− reorder_selection_contents(cx, ReorderStrategy::RotateBackward)
4743−}
4744−fn reverse_selection_contents(cx: &mut Context) {
4745− reorder_selection_contents(cx, ReorderStrategy::Reverse)
4392+ rotate_selection_contents(cx, Direction::Backward)
47464393}
47474394
47484395// tree sitter node selection
@@ -4766,7 +4413,8 @@ fn expand_selection(cx: &mut Context) {
47664413 }
47674414 }
47684415 };
4769− cx.editor.apply_motion(motion);
4416+ motion(cx.editor);
4417+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
47704418}
47714419
47724420fn shrink_selection(cx: &mut Context) {
@@ -4790,7 +4438,8 @@ fn shrink_selection(cx: &mut Context) {
47904438 doc.set_selection(view.id, selection);
47914439 }
47924440 };
4793− cx.editor.apply_motion(motion);
4441+ motion(cx.editor);
4442+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
47944443}
47954444
47964445fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: &'static F)
@@ -4808,7 +4457,8 @@ where
48084457 doc.set_selection(view.id, selection);
48094458 }
48104459 };
4811− cx.editor.apply_motion(motion);
4460+ motion(cx.editor);
4461+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
48124462}
48134463
48144464fn select_next_sibling(cx: &mut Context) {
@@ -4819,68 +4469,22 @@ fn select_prev_sibling(cx: &mut Context) {
48194469 select_sibling_impl(cx, &|node| Node::prev_sibling(&node))
48204470}
48214471
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−
48654472fn match_brackets(cx: &mut Context) {
48664473 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(..);
4870−
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− });
48824474
4883− doc.set_selection(view.id, selection);
4475+ if let Some(syntax) = doc.syntax() {
4476+ let text = doc.text().slice(..);
4477+ let selection = doc.selection(view.id).clone().transform(|range| {
4478+ if let Some(pos) =
4479+ match_brackets::find_matching_bracket_fuzzy(syntax, doc.text(), range.cursor(text))
4480+ {
4481+ range.put_cursor(text, pos, cx.editor.mode == Mode::Select)
4482+ } else {
4483+ range
4484+ }
4485+ });
4486+ doc.set_selection(view.id, selection);
4487+ }
48844488}
48854489
48864490//
@@ -4975,19 +4579,17 @@ fn transpose_view(cx: &mut Context) {
49754579 cx.editor.transpose_view()
49764580}
49774581
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);
4582+// split helper, clear it later
4583+fn split(cx: &mut Context, action: Action) {
4584+ let (view, doc) = current!(cx.editor);
49834585 let id = doc.id();
49844586 let selection = doc.selection(view.id).clone();
49854587 let offset = view.offset;
49864588
4987− editor.switch(id, action);
4589+ cx.editor.switch(id, action);
49884590
49894591 // match the selection in the previous view
4990− let (view, doc) = current!(editor);
4592+ let (view, doc) = current!(cx.editor);
49914593 doc.set_selection(view.id, selection);
49924594 // match the view scroll offset (switch doesn't handle this fully
49934595 // since the selection is only matched after the split)
@@ -4995,7 +4597,7 @@ fn split(editor: &mut Editor, action: Action) {
49954597}
49964598
49974599fn hsplit(cx: &mut Context) {
4998− split(cx.editor, Action::HorizontalSplit);
4600+ split(cx, Action::HorizontalSplit);
49994601}
50004602
50014603fn hsplit_new(cx: &mut Context) {
@@ -5003,7 +4605,7 @@ fn hsplit_new(cx: &mut Context) {
50034605}
50044606
50054607fn vsplit(cx: &mut Context) {
5006− split(cx.editor, Action::VerticalSplit);
4608+ split(cx, Action::VerticalSplit);
50074609}
50084610
50094611fn vsplit_new(cx: &mut Context) {
@@ -5052,12 +4654,7 @@ fn insert_register(cx: &mut Context) {
50524654 if let Some(ch) = event.char() {
50534655 cx.editor.autoinfo = None;
50544656 cx.register = Some(ch);
5055− paste(
5056− cx.editor,
5057− cx.register.unwrap_or('"'),
5058− Paste::Cursor,
5059− cx.count(),
5060− );
4657+ paste(cx, Paste::Cursor);
50614658 }
50624659 })
50634660}
@@ -5141,7 +4738,8 @@ fn goto_ts_object_impl(cx: &mut Context, object: &'static str, direction: Direct
51414738 editor.set_status("Syntax-tree is not available in current buffer");
51424739 }
51434740 };
5144− cx.editor.apply_motion(motion);
4741+ motion(cx.editor);
4742+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
51454743}
51464744
51474745fn goto_next_function(cx: &mut Context) {
@@ -5262,7 +4860,8 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
52624860 });
52634861 doc.set_selection(view.id, selection);
52644862 };
5265− cx.editor.apply_motion(textobject);
4863+ textobject(cx.editor);
4864+ cx.editor.last_motion = Some(Motion(Box::new(textobject)));
52664865 }
52674866 });
52684867
@@ -5352,18 +4951,11 @@ fn surround_replace(cx: &mut Context) {
53524951 }
53534952 };
53544953
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−
53624954 cx.on_next_key(move |cx, event| {
53634955 let (view, doc) = current!(cx.editor);
53644956 let to = match event.char() {
53654957 Some(to) => to,
5366− None => return doc.set_selection(view.id, selection),
4958+ None => return,
53674959 };
53684960 let (open, close) = surround::get_pair(to);
53694961 let transaction = Transaction::change(
@@ -5374,7 +4966,6 @@ fn surround_replace(cx: &mut Context) {
53744966 (pos, pos + 1, Some(t))
53754967 }),
53764968 );
5377− doc.set_selection(view.id, selection);
53784969 doc.apply(&transaction, view.id);
53794970 exit_select_mode(cx);
53804971 });
@@ -5523,7 +5114,7 @@ async fn shell_impl_async(
55235114 helix_view::document::to_writer(&mut stdin, (encoding::UTF_8, false), &input)
55245115 .await?;
55255116 }
5526− anyhow::Ok(())
5117+ Ok::<_, anyhow::Error>(())
55275118 });
55285119 let (output, _) = tokio::join! {
55295120 process.wait_with_output(),
@@ -5609,18 +5200,12 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
56095200 };
56105201
56115202 // These `usize`s cannot underflow because selection ranges cannot overlap.
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");
5203+ // Once the MSRV is 1.66.0 (mixed_integer_ops is stabilized), we can use checked
5204+ // arithmetic to assert this.
5205+ let anchor = (to as isize + offset - deleted_len as isize) as usize;
56175206 let new_range = Range::new(anchor, anchor + output_len).with_direction(range.direction());
56185207 ranges.push(new_range);
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");
5208+ offset = offset + output_len as isize - deleted_len as isize;
56245209
56255210 changes.push((from, to, Some(output)));
56265211 }
@@ -5642,7 +5227,7 @@ fn shell_prompt(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBeha
56425227 cx,
56435228 prompt,
56445229 Some('|'),
5645− ui::completers::filename,
5230+ ui::completers::none,
56465231 move |cx, input: &str, event: PromptEvent| {
56475232 if event != PromptEvent::Validate {
56485233 return;
@@ -5759,7 +5344,6 @@ fn increment_impl(cx: &mut Context, increment_direction: IncrementDirection) {
57595344 let transaction = Transaction::change(doc.text(), changes.into_iter());
57605345 let transaction = transaction.with_selection(new_selection);
57615346 doc.apply(&transaction, view.id);
5762− exit_select_mode(cx);
57635347 }
57645348}
57655349
@@ -5778,12 +5362,9 @@ fn record_macro(cx: &mut Context) {
57785362 }
57795363 })
57805364 .collect::<String>();
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− }
5365+ cx.editor.registers.write(reg, vec![s]);
5366+ cx.editor
5367+ .set_status(format!("Recorded to register [{}]", reg));
57875368 } else {
57885369 let reg = cx.register.take().unwrap_or('@');
57895370 cx.editor.macro_recording = Some((reg, Vec::new()));
@@ -5803,14 +5384,8 @@ fn replay_macro(cx: &mut Context) {
58035384 return;
58045385 }
58055386
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) {
5387+ let keys: Vec<KeyEvent> = if let Some([keys_str]) = cx.editor.registers.read(reg) {
5388+ match helix_view::input::parse_macro(keys_str) {
58145389 Ok(keys) => keys,
58155390 Err(err) => {
58165391 cx.editor.set_error(format!("Invalid macro: {}", err));