@@ -29,11 +29,12 @@ use helix_core::{
2929 tree_sitter::Node,
3030 unicode::width::UnicodeWidthChar,
3131 visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes,
32− RopeReader, RopeSlice, Selection, SmallVec, Tendril, Transaction,
32+ RopeSlice, Selection, SmallVec, Tendril, Transaction,
3333};
3434use helix_view::{
35+ clipboard::ClipboardType,
3536 document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
36− editor::{Action, CompleteAction},
37+ editor::{Action, CompleteAction, Motion},
3738 info::Info,
3839 input::KeyEvent,
3940 keyboard::KeyCode,
@@ -43,6 +44,7 @@ use helix_view::{
4344};
4445
4546use anyhow::{anyhow, bail, ensure, Context as _};
47+use fuzzy_matcher::FuzzyMatcher;
4648use insert::*;
4749use movement::Movement;
4850
@@ -53,20 +55,15 @@ use crate::{
5355 job::Callback,
5456 keymap::ReverseKeymap,
5557 ui::{
56− self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem, Picker,
57− Popup, Prompt, PromptEvent,
58+ self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem,
59+ FilePicker, Picker, Popup, Prompt, PromptEvent,
5860 },
5961};
6062
6163use 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−};
64+use futures_util::{stream::FuturesUnordered, StreamExt, TryStreamExt};
65+use std::{collections::HashMap, fmt, future::Future};
66+use std::{collections::HashSet, num::NonZeroUsize};
7067
7168use std::{
7269 borrow::Cow,
@@ -75,11 +72,11 @@ use std::{
7572
7673use once_cell::sync::Lazy;
7774use serde::de::{self, Deserialize, Deserializer};
78−use url::Url;
7975
8076use grep_regex::RegexMatcherBuilder;
8177use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
8278use ignore::{DirEntry, WalkBuilder, WalkState};
79+use tokio_stream::wrappers::UnboundedReceiverStream;
8380
8481pub type OnKeyCallback = Box<dyn FnOnce(&mut Context, KeyEvent)>;
8582
@@ -250,9 +247,6 @@ impl MappableCommand {
250247 move_next_long_word_start, "Move to start of next long word",
251248 move_prev_long_word_start, "Move to start of previous long word",
252249 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",
256250 extend_next_word_start, "Extend to start of next word",
257251 extend_prev_word_start, "Extend to start of previous word",
258252 extend_next_word_end, "Extend to end of next word",
@@ -260,9 +254,6 @@ impl MappableCommand {
260254 extend_next_long_word_start, "Extend to start of next long word",
261255 extend_prev_long_word_start, "Extend to start of previous long word",
262256 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",
266257 find_till_char, "Move till next occurrence of char",
267258 find_next_char, "Move to next occurrence of char",
268259 extend_till_char, "Extend till next occurrence of char",
@@ -284,7 +275,6 @@ impl MappableCommand {
284275 select_regex, "Select all regex matches inside selections",
285276 split_selection, "Split selections on regex matches",
286277 split_selection_on_newline, "Split selection on newlines",
287− merge_selections, "Merge selections",
288278 merge_consecutive_selections, "Merge consecutive selections",
289279 search, "Search for regex pattern",
290280 rsearch, "Reverse search for regex pattern",
@@ -337,7 +327,7 @@ impl MappableCommand {
337327 goto_implementation, "Goto implementation",
338328 goto_file_start, "Goto line number <n> else file start",
339329 goto_file_end, "Goto file end",
340− goto_file, "Goto files/URLs in selection",
330+ goto_file, "Goto files in selection",
341331 goto_file_hsplit, "Goto files in selection (hsplit)",
342332 goto_file_vsplit, "Goto files in selection (vsplit)",
343333 goto_reference, "Goto references",
@@ -369,7 +359,6 @@ impl MappableCommand {
369359 extend_to_line_end, "Extend to line end",
370360 extend_to_line_end_newline, "Extend to line end",
371361 signature_help, "Show signature help",
372− smart_tab, "Insert tab if all cursors have all whitespace to their left; otherwise, run a separate command.",
373362 insert_tab, "Insert tab char",
374363 insert_newline, "Insert newline char",
375364 delete_char_backward, "Delete previous char",
@@ -384,9 +373,6 @@ impl MappableCommand {
384373 later, "Move forward in history",
385374 commit_undo_checkpoint, "Commit changes to new checkpoint",
386375 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",
390376 yank_joined_to_clipboard, "Join and yank selections to clipboard",
391377 yank_main_selection_to_clipboard, "Yank main selection to clipboard",
392378 yank_joined_to_primary_clipboard, "Join and yank selections to primary clipboard",
@@ -417,7 +403,6 @@ impl MappableCommand {
417403 rotate_selections_backward, "Rotate selections backward",
418404 rotate_selection_contents_forward, "Rotate selection contents forward",
419405 rotate_selection_contents_backward, "Rotate selections contents backward",
420− reverse_selection_contents, "Reverse selections contents",
421406 expand_selection, "Expand selection to parent syntax node",
422407 shrink_selection, "Shrink selection to previously expanded syntax node",
423408 select_next_sibling, "Select next sibling in syntax tree",
@@ -990,7 +975,6 @@ fn align_selections(cx: &mut Context) {
990975
991976 let transaction = Transaction::change(doc.text(), changes.into_iter());
992977 doc.apply(&transaction, view.id);
993− exit_select_mode(cx);
994978}
995979
996980fn goto_window(cx: &mut Context, align: Align) {
@@ -1082,10 +1066,6 @@ fn move_prev_long_word_start(cx: &mut Context) {
10821066 move_word_impl(cx, movement::move_prev_long_word_start)
10831067}
10841068
1085−fn move_prev_long_word_end(cx: &mut Context) {
1086− move_word_impl(cx, movement::move_prev_long_word_end)
1087−}
1088−
10891069fn move_next_long_word_end(cx: &mut Context) {
10901070 move_word_impl(cx, movement::move_next_long_word_end)
10911071}
@@ -1110,7 +1090,8 @@ where
11101090 .transform(|range| move_fn(text, range, count, behavior));
11111091 doc.set_selection(view.id, selection);
11121092 };
1113− cx.editor.apply_motion(motion)
1093+ motion(cx.editor);
1094+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
11141095}
11151096
11161097fn goto_prev_paragraph(cx: &mut Context) {
@@ -1165,10 +1146,6 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11651146 let (view, doc) = current_ref!(cx.editor);
11661147 let text = doc.text();
11671148 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();
11721149 let mut paths: Vec<_> = selections
11731150 .iter()
11741151 .map(|r| text.slice(r.from()..r.to()).to_string())
@@ -1196,80 +1173,16 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11961173 .to_string(),
11971174 );
11981175 }
1199−
12001176 for sel in paths {
12011177 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) {
1178+ if !p.is_empty() {
1179+ if let Err(e) = cx.editor.open(&PathBuf::from(p), action) {
12501180 cx.editor.set_error(format!("Open file failed: {:?}", e));
12511181 }
12521182 }
12531183 }
12541184}
12551185
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−
12731186fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
12741187where
12751188 F: Fn(RopeSlice, Range, usize) -> Range,
@@ -1310,74 +1223,14 @@ fn extend_prev_long_word_start(cx: &mut Context) {
13101223 extend_word_impl(cx, movement::move_prev_long_word_start)
13111224}
13121225
1313−fn extend_prev_long_word_end(cx: &mut Context) {
1314− extend_word_impl(cx, movement::move_prev_long_word_end)
1315−}
1316−
13171226fn extend_next_long_word_end(cx: &mut Context) {
13181227 extend_word_impl(cx, movement::move_next_long_word_end)
13191228}
13201229
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) {
1230+fn will_find_char<F>(cx: &mut Context, search_fn: F, inclusive: bool, extend: bool)
1231+where
1232+ F: Fn(RopeSlice, char, usize, usize, bool) -> Option<usize> + 'static,
1233+{
13811234 // TODO: count is reset to 1 before next key so we move it into the closure here.
13821235 // Would be nice to carry over.
13831236 let count = cx.count();
@@ -1390,9 +1243,13 @@ fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bo
13901243 KeyEvent {
13911244 code: KeyCode::Enter,
13921245 ..
1393− } => {
1394− find_char_line_ending(cx, count, direction, inclusive, extend);
1395− return;
1246+ } =>
1247+ // TODO: this isn't quite correct when CRLF is involved.
1248+ // This hack will work in most cases, since documents don't
1249+ // usually mix line endings. But we should fix it eventually
1250+ // anyway.
1251+ {
1252+ doc!(cx.editor).line_ending.as_str().chars().next().unwrap()
13961253 }
13971254
13981255 KeyEvent {
@@ -1405,18 +1262,11 @@ fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bo
14051262 } => ch,
14061263 _ => return,
14071264 };
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− };
14181265
1419− cx.editor.apply_motion(motion);
1266+ find_char_impl(cx.editor, &search_fn, inclusive, extend, ch, count);
1267+ cx.editor.last_motion = Some(Motion(Box::new(move |editor: &mut Editor| {
1268+ find_char_impl(editor, &search_fn, inclusive, true, ch, 1);
1269+ })));
14201270 })
14211271}
14221272
@@ -1495,39 +1345,46 @@ fn find_prev_char_impl(
14951345}
14961346
14971347fn find_till_char(cx: &mut Context) {
1498− find_char(cx, Direction::Forward, false, false);
1348+ will_find_char(cx, find_next_char_impl, false, false)
14991349}
15001350
15011351fn find_next_char(cx: &mut Context) {
1502− find_char(cx, Direction::Forward, true, false)
1352+ will_find_char(cx, find_next_char_impl, true, false)
15031353}
15041354
15051355fn extend_till_char(cx: &mut Context) {
1506− find_char(cx, Direction::Forward, false, true)
1356+ will_find_char(cx, find_next_char_impl, false, true)
15071357}
15081358
15091359fn extend_next_char(cx: &mut Context) {
1510− find_char(cx, Direction::Forward, true, true)
1360+ will_find_char(cx, find_next_char_impl, true, true)
15111361}
15121362
15131363fn till_prev_char(cx: &mut Context) {
1514− find_char(cx, Direction::Backward, false, false)
1364+ will_find_char(cx, find_prev_char_impl, false, false)
15151365}
15161366
15171367fn find_prev_char(cx: &mut Context) {
1518− find_char(cx, Direction::Backward, true, false)
1368+ will_find_char(cx, find_prev_char_impl, true, false)
15191369}
15201370
15211371fn extend_till_prev_char(cx: &mut Context) {
1522− find_char(cx, Direction::Backward, false, true)
1372+ will_find_char(cx, find_prev_char_impl, false, true)
15231373}
15241374
15251375fn extend_prev_char(cx: &mut Context) {
1526− find_char(cx, Direction::Backward, true, true)
1376+ will_find_char(cx, find_prev_char_impl, true, true)
15271377}
15281378
15291379fn repeat_last_motion(cx: &mut Context) {
1530− cx.editor.repeat_last_motion(cx.count())
1380+ let count = cx.count();
1381+ let last_motion = cx.editor.last_motion.take();
1382+ if let Some(m) = &last_motion {
1383+ for _ in 0..count {
1384+ m.run(cx.editor);
1385+ }
1386+ cx.editor.last_motion = last_motion;
1387+ }
15311388}
15321389
15331390fn replace(cx: &mut Context) {
@@ -1594,7 +1451,6 @@ where
15941451 });
15951452
15961453 doc.apply(&transaction, view.id);
1597− exit_select_mode(cx);
15981454}
15991455
16001456fn switch_case(cx: &mut Context) {
@@ -1836,8 +1692,8 @@ fn select_regex(cx: &mut Context) {
18361692 "select:".into(),
18371693 Some(reg),
18381694 ui::completers::none,
1839− move |cx, regex, event| {
1840− let (view, doc) = current!(cx.editor);
1695+ move |editor, regex, event| {
1696+ let (view, doc) = current!(editor);
18411697 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
18421698 return;
18431699 }
@@ -1858,8 +1714,8 @@ fn split_selection(cx: &mut Context) {
18581714 "split:".into(),
18591715 Some(reg),
18601716 ui::completers::none,
1861− move |cx, regex, event| {
1862− let (view, doc) = current!(cx.editor);
1717+ move |editor, regex, event| {
1718+ let (view, doc) = current!(editor);
18631719 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
18641720 return;
18651721 }
@@ -1881,12 +1737,6 @@ fn split_selection_on_newline(cx: &mut Context) {
18811737 doc.set_selection(view.id, selection);
18821738}
18831739
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−
18901740fn merge_consecutive_selections(cx: &mut Context) {
18911741 let (view, doc) = current!(cx.editor);
18921742 let selection = doc.selection(view.id).clone().merge_consecutive_ranges();
@@ -1982,11 +1832,11 @@ fn search_impl(
19821832
19831833fn search_completions(cx: &mut Context, reg: Option<char>) -> Vec<String> {
19841834 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());
1835+ .and_then(|reg| cx.editor.registers.get(reg))
1836+ .map_or(Vec::new(), |reg| reg.read().iter().take(200).collect());
19871837 items.sort_unstable();
19881838 items.dedup();
1989− items.into_iter().map(|value| value.to_string()).collect()
1839+ items.into_iter().cloned().collect()
19901840}
19911841
19921842fn search(cx: &mut Context) {
@@ -2023,14 +1873,12 @@ fn searcher(cx: &mut Context, direction: Direction) {
20231873 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
20241874 .collect()
20251875 },
2026− move |cx, regex, event| {
2027− if event == PromptEvent::Validate {
2028− cx.editor.registers.last_search_register = reg;
2029− } else if event != PromptEvent::Update {
1876+ move |editor, regex, event| {
1877+ if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
20301878 return;
20311879 }
20321880 search_impl(
2033− cx.editor,
1881+ editor,
20341882 &contents,
20351883 ®ex,
20361884 Movement::Move,
@@ -2045,13 +1893,11 @@ fn searcher(cx: &mut Context, direction: Direction) {
20451893
20461894fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Direction) {
20471895 let count = cx.count();
2048− let register = cx
2049− .register
2050− .unwrap_or(cx.editor.registers.last_search_register);
20511896 let config = cx.editor.config();
20521897 let scrolloff = config.scrolloff;
2053− if let Some(query) = cx.editor.registers.first(register, cx.editor) {
2054− let doc = doc!(cx.editor);
1898+ let (_, doc) = current!(cx.editor);
1899+ let registers = &cx.editor.registers;
1900+ if let Some(query) = registers.read('/').and_then(|query| query.last()) {
20551901 let contents = doc.text().slice(..).to_string();
20561902 let search_config = &config.search;
20571903 let case_insensitive = if search_config.smart_case {
@@ -2060,7 +1906,7 @@ fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Dir
20601906 false
20611907 };
20621908 let wrap_around = search_config.wrap_around;
2063− if let Ok(regex) = RegexBuilder::new(&query)
1909+ if let Ok(regex) = RegexBuilder::new(query)
20641910 .case_insensitive(case_insensitive)
20651911 .multi_line(true)
20661912 .build()
@@ -2100,7 +1946,6 @@ fn extend_search_prev(cx: &mut Context) {
21001946}
21011947
21021948fn search_selection(cx: &mut Context) {
2103− let register = cx.register.unwrap_or('/');
21041949 let (view, doc) = current!(cx.editor);
21051950 let contents = doc.text().slice(..);
21061951
@@ -2113,24 +1958,13 @@ fn search_selection(cx: &mut Context) {
21131958 .collect::<Vec<_>>()
21141959 .join("|");
21151960
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− }
1961+ let msg = format!("register '{}' set to '{}'", '/', ®ex);
1962+ cx.editor.registers.push('/', regex);
1963+ cx.editor.set_status(msg);
21241964}
21251965
21261966fn 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) {
1967+ let regex = match cx.editor.registers.last('/') {
21341968 Some(regex) => regex,
21351969 None => return,
21361970 };
@@ -2148,19 +1982,14 @@ fn make_search_word_bounded(cx: &mut Context) {
21481982 if !start_anchored {
21491983 new_regex.push_str("\\b");
21501984 }
2151− new_regex.push_str(®ex);
1985+ new_regex.push_str(regex);
21521986 if !end_anchored {
21531987 new_regex.push_str("\\b");
21541988 }
21551989
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− }
1990+ let msg = format!("register '{}' set to '{}'", '/', &new_regex);
1991+ cx.editor.registers.push('/', new_regex);
1992+ cx.editor.set_status(msg);
21641993}
21651994
21661995fn global_search(cx: &mut Context) {
@@ -2199,11 +2028,13 @@ fn global_search(cx: &mut Context) {
21992028 }
22002029 }
22012030
2031+ let (all_matches_sx, all_matches_rx) = tokio::sync::mpsc::unbounded_channel::<FileResult>();
22022032 let config = cx.editor.config();
22032033 let smart_case = config.search.smart_case;
22042034 let file_picker_config = config.file_picker.clone();
22052035
22062036 let reg = cx.register.unwrap_or('/');
2037+
22072038 let completions = search_completions(cx, Some(reg));
22082039 ui::regex_prompt(
22092040 cx,
@@ -2216,67 +2047,43 @@ fn global_search(cx: &mut Context) {
22162047 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
22172048 .collect()
22182049 },
2219− move |cx, regex, event| {
2050+ move |_editor, regex, event| {
22202051 if event != PromptEvent::Validate {
22212052 return;
22222053 }
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();
22312054
22322055 if let Ok(matcher) = RegexMatcherBuilder::new()
22332056 .case_smart(smart_case)
22342057 .build(regex.as_str())
22352058 {
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);
2059+ let searcher = SearcherBuilder::new()
2060+ .binary_detection(BinaryDetection::quit(b'\x00'))
2061+ .build();
22442062
2063+ let search_root = std::env::current_dir()
2064+ .expect("Global search error: Failed to get current dir");
22452065 let dedup_symlinks = file_picker_config.deduplicate_links;
22462066 let absolute_root = search_root
22472067 .canonicalize()
22482068 .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(|| {
2069+
2070+ WalkBuilder::new(search_root)
2071+ .hidden(file_picker_config.hidden)
2072+ .parents(file_picker_config.parents)
2073+ .ignore(file_picker_config.ignore)
2074+ .follow_links(file_picker_config.follow_symlinks)
2075+ .git_ignore(file_picker_config.git_ignore)
2076+ .git_global(file_picker_config.git_global)
2077+ .git_exclude(file_picker_config.git_exclude)
2078+ .max_depth(file_picker_config.max_depth)
2079+ .filter_entry(move |entry| {
2080+ filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2081+ })
2082+ .build_parallel()
2083+ .run(|| {
22762084 let mut searcher = searcher.clone();
22772085 let matcher = matcher.clone();
2278− let injector = injector_.clone();
2279− let documents = &documents;
2086+ let all_matches_sx = all_matches_sx.clone();
22802087 Box::new(move |entry: Result<DirEntry, ignore::Error>| -> WalkState {
22812088 let entry = match entry {
22822089 Ok(entry) => entry,
@@ -2289,39 +2096,17 @@ fn global_search(cx: &mut Context) {
22892096 _ => return WalkState::Continue,
22902097 };
22912098
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− };
2099+ let result = searcher.search_path(
2100+ &matcher,
2101+ entry.path(),
2102+ sinks::UTF8(|line_num, _| {
2103+ all_matches_sx
2104+ .send(FileResult::new(entry.path(), line_num as usize - 1))
2105+ .unwrap();
2106+
2107+ Ok(true)
2108+ }),
2109+ );
23252110
23262111 if let Err(err) = result {
23272112 log::error!(
@@ -2330,66 +2115,67 @@ fn global_search(cx: &mut Context) {
23302115 err
23312116 );
23322117 }
2333− if stop {
2334− WalkState::Quit
2335− } else {
2336− WalkState::Continue
2337− }
2118+ WalkState::Continue
23382119 })
23392120 });
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− })
23872121 } else {
23882122 // Otherwise do nothing
23892123 // log::warn!("Global Search Invalid Pattern")
23902124 }
23912125 },
23922126 );
2127+
2128+ let current_path = doc_mut!(cx.editor).path().cloned();
2129+
2130+ let show_picker = async move {
2131+ let all_matches: Vec<FileResult> =
2132+ UnboundedReceiverStream::new(all_matches_rx).collect().await;
2133+ let call: job::Callback = Callback::EditorCompositor(Box::new(
2134+ move |editor: &mut Editor, compositor: &mut Compositor| {
2135+ if all_matches.is_empty() {
2136+ editor.set_status("No matches found");
2137+ return;
2138+ }
2139+
2140+ let picker = FilePicker::new(
2141+ all_matches,
2142+ current_path,
2143+ move |cx, FileResult { path, line_num }, action| {
2144+ match cx.editor.open(path, action) {
2145+ Ok(_) => {}
2146+ Err(e) => {
2147+ cx.editor.set_error(format!(
2148+ "Failed to open file '{}': {}",
2149+ path.display(),
2150+ e
2151+ ));
2152+ return;
2153+ }
2154+ }
2155+
2156+ let line_num = *line_num;
2157+ let (view, doc) = current!(cx.editor);
2158+ let text = doc.text();
2159+ if line_num >= text.len_lines() {
2160+ cx.editor.set_error("The line you jumped to does not exist anymore because the file has changed.");
2161+ return;
2162+ }
2163+ let start = text.line_to_char(line_num);
2164+ let end = text.line_to_char((line_num + 1).min(text.len_lines()));
2165+
2166+ doc.set_selection(view.id, Selection::single(start, end));
2167+ align_view(doc, view, Align::Center);
2168+ },
2169+ |_editor, FileResult { path, line_num }| {
2170+ Some((path.clone().into(), Some((*line_num, *line_num))))
2171+ },
2172+ );
2173+ compositor.push(Box::new(overlaid(picker)));
2174+ },
2175+ ));
2176+ Ok(call)
2177+ };
2178+ cx.jobs.callback(show_picker);
23932179}
23942180
23952181enum Extend {
@@ -2512,35 +2298,17 @@ enum Operation {
25122298 Change,
25132299}
25142300
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−
25292301fn delete_selection_impl(cx: &mut Context, op: Operation) {
25302302 let (view, doc) = current!(cx.editor);
25312303
25322304 let selection = doc.selection(view.id);
2533− let only_whole_lines = selection_is_linewise(selection, doc.text());
25342305
25352306 if cx.register != Some('_') {
25362307 // first yank the selection
25372308 let text = doc.text().slice(..);
25382309 let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect();
25392310 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− }
2311+ cx.editor.registers.write(reg_name, values);
25442312 };
25452313
25462314 // then delete
@@ -2554,11 +2322,7 @@ fn delete_selection_impl(cx: &mut Context, op: Operation) {
25542322 exit_select_mode(cx);
25552323 }
25562324 Operation::Change => {
2557− if only_whole_lines {
2558− open_above(cx);
2559− } else {
2560− enter_insert_mode(cx);
2561− }
2325+ enter_insert_mode(cx);
25622326 }
25632327 }
25642328}
@@ -2680,10 +2444,6 @@ fn insert_mode(cx: &mut Context) {
26802444 .transform(|range| Range::new(range.to(), range.from()));
26812445
26822446 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();
26872447}
26882448
26892449// inserts at the end of each selection
@@ -2720,10 +2480,6 @@ fn append_mode(cx: &mut Context) {
27202480
27212481fn file_picker(cx: &mut Context) {
27222482 let root = find_workspace().0;
2723− if !root.exists() {
2724− cx.editor.set_error("Workspace directory does not exist");
2725− return;
2726− }
27272483 let picker = ui::file_picker(root, &cx.editor.config());
27282484 cx.push_layer(Box::new(overlaid(picker)));
27292485}
@@ -2744,14 +2500,8 @@ fn file_picker_in_current_buffer_directory(cx: &mut Context) {
27442500 let picker = ui::file_picker(path, &cx.editor.config());
27452501 cx.push_layer(Box::new(overlaid(picker)));
27462502}
2747−
27482503fn 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− }
2504+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("./"));
27552505 let picker = ui::file_picker(cwd, &cx.editor.config());
27562506 cx.push_layer(Box::new(overlaid(picker)));
27572507}
@@ -2810,18 +2560,22 @@ fn buffer_picker(cx: &mut Context) {
28102560 // mru
28112561 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
28122562
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− });
2563+ let picker = FilePicker::new(
2564+ items,
2565+ (),
2566+ |cx, meta, action| {
2567+ cx.editor.switch(meta.id, action);
2568+ },
2569+ |editor, meta| {
2570+ let doc = &editor.documents.get(&meta.id)?;
2571+ let &view_id = doc.selections().keys().next()?;
2572+ let line = doc
2573+ .selection(view_id)
2574+ .primary()
2575+ .cursor_line(doc.text().slice(..));
2576+ Some((meta.id.into(), Some((line, line))))
2577+ },
2578+ );
28252579 cx.push_layer(Box::new(overlaid(picker)));
28262580}
28272581
@@ -2887,7 +2641,7 @@ fn jumplist_picker(cx: &mut Context) {
28872641 }
28882642 };
28892643
2890− let picker = Picker::new(
2644+ let picker = FilePicker::new(
28912645 cx.editor
28922646 .tree
28932647 .views()
@@ -2901,18 +2655,16 @@ fn jumplist_picker(cx: &mut Context) {
29012655 |cx, meta, action| {
29022656 cx.editor.switch(meta.id, action);
29032657 let config = cx.editor.config();
2904− let (view, doc) = (view_mut!(cx.editor), doc_mut!(cx.editor, &meta.id));
2658+ let (view, doc) = current!(cx.editor);
29052659 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− }
2660+ view.ensure_cursor_in_view_center(doc, config.scrolloff);
29092661 },
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− });
2662+ |editor, meta| {
2663+ let doc = &editor.documents.get(&meta.id)?;
2664+ let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2665+ Some((meta.path.clone()?.into(), Some((line, line))))
2666+ },
2667+ );
29162668 cx.push_layer(Box::new(overlaid(picker)));
29172669}
29182670
@@ -2946,9 +2698,6 @@ impl ui::menu::Item for MappableCommand {
29462698}
29472699
29482700pub fn command_palette(cx: &mut Context) {
2949− let register = cx.register;
2950− let count = cx.count;
2951−
29522701 cx.callback = Some(Box::new(
29532702 move |compositor: &mut Compositor, cx: &mut compositor::Context| {
29542703 let keymap = compositor.find::<ui::EditorView>().unwrap().keymaps.map()
@@ -2966,8 +2715,8 @@ pub fn command_palette(cx: &mut Context) {
29662715
29672716 let picker = Picker::new(commands, keymap, move |cx, command, _action| {
29682717 let mut ctx = Context {
2969− register,
2970− count,
2718+ register: None,
2719+ count: std::num::NonZeroUsize::new(1),
29712720 editor: cx.editor,
29722721 callback: None,
29732722 on_next_key_callback: None,
@@ -3006,88 +2755,24 @@ fn last_picker(cx: &mut Context) {
30062755 }));
30072756}
30082757
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.
2758+// I inserts at the first nonwhitespace character of each line with a selection
30172759fn insert_at_line_start(cx: &mut Context) {
3018− insert_with_indent(cx, IndentFallbackPos::LineStart);
2760+ goto_first_nonwhitespace(cx);
2761+ enter_insert_mode(cx);
30192762}
30202763
3021−// `A` inserts at the end of each line with a selection.
3022−// If the line is empty, automatically indent.
2764+// A inserts at the end of each line with a selection
30232765fn 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) {
30302766 enter_insert_mode(cx);
3031−
30322767 let (view, doc) = current!(cx.editor);
30332768
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− }
2769+ let selection = doc.selection(view.id).clone().transform(|range| {
2770+ let text = doc.text().slice(..);
2771+ let line = range.cursor_line(text);
2772+ let pos = line_end_char_index(&text, line);
2773+ Range::new(pos, pos)
30872774 });
3088−
3089− transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3090− doc.apply(&transaction, view.id);
2775+ doc.set_selection(view.id, selection);
30912776}
30922777
30932778// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
@@ -3158,7 +2843,6 @@ fn open(cx: &mut Context, open: Open) {
31582843 Open::Below => graphemes::prev_grapheme_boundary(text, range.to()),
31592844 Open::Above => range.from(),
31602845 });
3161−
31622846 let new_line = match open {
31632847 // adjust position to the end of the line (next line - 1)
31642848 Open::Below => cursor_line + 1,
@@ -3166,15 +2850,13 @@ fn open(cx: &mut Context, open: Open) {
31662850 Open::Above => cursor_line,
31672851 };
31682852
3169− let line_num = new_line.saturating_sub(1);
3170−
31712853 // Index to insert newlines after, as well as the char width
31722854 // to use to compensate for those inserted newlines.
31732855 let (line_end_index, line_end_offset_width) = if new_line == 0 {
31742856 (0, 0)
31752857 } else {
31762858 (
3177− line_end_char_index(&text, line_num),
2859+ line_end_char_index(&doc.text().slice(..), new_line.saturating_sub(1)),
31782860 doc.line_ending.len_chars(),
31792861 )
31802862 };
@@ -3182,15 +2864,13 @@ fn open(cx: &mut Context, open: Open) {
31822864 let indent = indent::indent_for_newline(
31832865 doc.language_config(),
31842866 doc.syntax(),
3185− &doc.config.load().indent_heuristic,
31862867 &doc.indent_style,
31872868 doc.tab_width(),
31882869 text,
3189− line_num,
2870+ new_line.saturating_sub(1),
31902871 line_end_index,
31912872 cursor_line,
31922873 );
3193−
31942874 let indent_len = indent.len();
31952875 let mut text = String::with_capacity(1 + indent_len);
31962876 text.push_str(doc.line_ending.as_str());
@@ -3396,6 +3076,8 @@ fn goto_prev_diag(cx: &mut Context) {
33963076
33973077 let diag = doc
33983078 .shown_diagnostics()
3079+ .collect::<Vec<_>>()
3080+ .into_iter()
33993081 .rev()
34003082 .find(|diag| diag.range.start < cursor_pos)
34013083 .or_else(|| doc.shown_diagnostics().last());
@@ -3489,7 +3171,8 @@ fn goto_next_change_impl(cx: &mut Context, direction: Direction) {
34893171
34903172 doc.set_selection(view.id, selection)
34913173 };
3492− cx.editor.apply_motion(motion);
3174+ motion(cx.editor);
3175+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
34933176}
34943177
34953178/// Returns the [Range] for a [Hunk] in the given text.
@@ -3554,9 +3237,12 @@ pub mod insert {
35543237 let doc = doc_mut!(cx.editor);
35553238 let trigger_completion = doc
35563239 .language_servers_with_feature(LanguageServerFeature::Completion)
3240+ .iter()
35573241 .any(|ls| {
3242+ let capabilities = ls.capabilities();
3243+
35583244 // TODO: what if trigger is multiple chars long
3559− matches!(&ls.capabilities().completion_provider, Some(lsp::CompletionOptions {
3245+ matches!(&capabilities.completion_provider, Some(lsp::CompletionOptions {
35603246 trigger_characters: Some(triggers),
35613247 ..
35623248 }) if triggers.iter().any(|trigger| trigger.contains(ch)))
@@ -3569,39 +3255,52 @@ pub mod insert {
35693255 }
35703256
35713257 fn signature_help(cx: &mut Context, ch: char) {
3258+ use futures_util::FutureExt;
35723259 use helix_lsp::lsp;
35733260 // if ch matches signature_help char, trigger
3574− 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
3261+ let (view, doc) = current!(cx.editor);
3262+ // lsp doesn't tell us when to close the signature help, so we request
3263+ // the help information again after common close triggers which should
3264+ // return None, which in turn closes the popup.
3265+ let close_triggers = &[')', ';', '.'];
3266+ // TODO support multiple language servers (not just the first that is found)
3267+ let future = doc
35773268 .language_servers_with_feature(LanguageServerFeature::SignatureHelp)
3578− .next()
3579− else {
3580− return;
3581− };
3582−
3583− let capabilities = language_server.capabilities();
3269+ .iter()
3270+ .find_map(|ls| {
3271+ let capabilities = ls.capabilities();
3272+
3273+ match capabilities {
3274+ lsp::ServerCapabilities {
3275+ signature_help_provider:
3276+ Some(lsp::SignatureHelpOptions {
3277+ trigger_characters: Some(triggers),
3278+ // TODO: retrigger_characters
3279+ ..
3280+ }),
3281+ ..
3282+ } if triggers.iter().any(|trigger| trigger.contains(ch))
3283+ || close_triggers.contains(&ch) =>
3284+ {
3285+ let pos = doc.position(view.id, ls.offset_encoding());
3286+ ls.text_document_signature_help(doc.identifier(), pos, None)
3287+ }
3288+ _ if close_triggers.contains(&ch) => ls.text_document_signature_help(
3289+ doc.identifier(),
3290+ doc.position(view.id, ls.offset_encoding()),
3291+ None,
3292+ ),
3293+ // TODO: what if trigger is multiple chars long
3294+ _ => None,
3295+ }
3296+ });
35843297
3585− if let lsp::ServerCapabilities {
3586− signature_help_provider:
3587− Some(lsp::SignatureHelpOptions {
3588− trigger_characters: Some(triggers),
3589− // TODO: retrigger_characters
3590− ..
3591− }),
3592− ..
3593− } = capabilities
3594− {
3595− // TODO: what if trigger is multiple chars long
3596− let is_trigger = triggers.iter().any(|trigger| trigger.contains(ch));
3597− // lsp doesn't tell us when to close the signature help, so we request
3598− // the help information again after common close triggers which should
3599− // return None, which in turn closes the popup.
3600− let close_triggers = &[')', ';', '.'];
3601−
3602− if is_trigger || close_triggers.contains(&ch) {
3603− super::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
3604− }
3298+ if let Some(future) = future {
3299+ super::signature_help_impl_with_future(
3300+ cx,
3301+ future.boxed(),
3302+ SignatureHelpInvoked::Automatic,
3303+ )
36053304 }
36063305 }
36073306
@@ -3615,8 +3314,7 @@ pub mod insert {
36153314 Some(transaction)
36163315 }
36173316
3618− use helix_core::auto_pairs;
3619− use helix_view::editor::SmartTabConfig;
3317+ use helix_core::{auto_pairs, syntax::LanguageServerFeature};
36203318
36213319 pub fn insert_char(cx: &mut Context, c: char) {
36223320 let (view, doc) = current_ref!(cx.editor);
@@ -3642,31 +3340,6 @@ pub mod insert {
36423340 }
36433341 }
36443342
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−
36703343 pub fn insert_tab(cx: &mut Context) {
36713344 let (view, doc) = current!(cx.editor);
36723345 // TODO: round out to nearest indentation level (for example a line with 3 spaces should
@@ -3722,7 +3395,6 @@ pub mod insert {
37223395 let indent = indent::indent_for_newline(
37233396 doc.language_config(),
37243397 doc.syntax(),
3725− &doc.config.load().indent_heuristic,
37263398 &doc.indent_style,
37273399 doc.tab_width(),
37283400 text,
@@ -3963,21 +3635,34 @@ fn commit_undo_checkpoint(cx: &mut Context) {
39633635// Yank / Paste
39643636
39653637fn yank(cx: &mut Context) {
3966− yank_impl(cx.editor, cx.register.unwrap_or('"'));
3967− exit_select_mode(cx);
3968−}
3638+ let (view, doc) = current!(cx.editor);
3639+ let text = doc.text().slice(..);
39693640
3970−fn yank_to_clipboard(cx: &mut Context) {
3971− yank_impl(cx.editor, '+');
3972− exit_select_mode(cx);
3973−}
3641+ let values: Vec<String> = doc
3642+ .selection(view.id)
3643+ .fragments(text)
3644+ .map(Cow::into_owned)
3645+ .collect();
39743646
3975−fn yank_to_primary_clipboard(cx: &mut Context) {
3976− yank_impl(cx.editor, '*');
3647+ let msg = format!(
3648+ "yanked {} selection(s) to register {}",
3649+ values.len(),
3650+ cx.register.unwrap_or('"')
3651+ );
3652+
3653+ cx.editor
3654+ .registers
3655+ .write(cx.register.unwrap_or('"'), values);
3656+
3657+ cx.editor.set_status(msg);
39773658 exit_select_mode(cx);
39783659}
39793660
3980−fn yank_impl(editor: &mut Editor, register: char) {
3661+fn yank_joined_to_clipboard_impl(
3662+ editor: &mut Editor,
3663+ separator: &str,
3664+ clipboard_type: ClipboardType,
3665+) -> anyhow::Result<()> {
39813666 let (view, doc) = current!(editor);
39823667 let text = doc.text().slice(..);
39833668
@@ -3986,79 +3671,74 @@ fn yank_impl(editor: &mut Editor, register: char) {
39863671 .fragments(text)
39873672 .map(Cow::into_owned)
39883673 .collect();
3989− let selections = values.len();
39903674
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−}
3675+ let clipboard_text = match clipboard_type {
3676+ ClipboardType::Clipboard => "system clipboard",
3677+ ClipboardType::Selection => "primary clipboard",
3678+ };
39993679
4000−fn yank_joined_impl(editor: &mut Editor, separator: &str, register: char) {
4001− let (view, doc) = current!(editor);
4002− let text = doc.text().slice(..);
3680+ let msg = format!(
3681+ "joined and yanked {} selection(s) to {}",
3682+ values.len(),
3683+ clipboard_text,
3684+ );
40033685
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− });
3686+ let joined = values.join(separator);
40153687
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−}
3688+ editor
3689+ .clipboard_provider
3690+ .set_contents(joined, clipboard_type)
3691+ .context("Couldn't set system clipboard content")?;
40243692
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−}
3693+ editor.set_status(msg);
40303694
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);
3695+ Ok(())
40353696}
40363697
4037−fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3698+fn yank_joined_to_clipboard(cx: &mut Context) {
40383699 let line_ending = doc!(cx.editor).line_ending;
4039− yank_joined_impl(cx.editor, line_ending.as_str(), '*');
3700+ let _ =
3701+ yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Clipboard);
40403702 exit_select_mode(cx);
40413703}
40423704
4043−fn yank_primary_selection_impl(editor: &mut Editor, register: char) {
3705+fn yank_main_selection_to_clipboard_impl(
3706+ editor: &mut Editor,
3707+ clipboard_type: ClipboardType,
3708+) -> anyhow::Result<()> {
40443709 let (view, doc) = current!(editor);
40453710 let text = doc.text().slice(..);
40463711
4047− let selection = doc.selection(view.id).primary().fragment(text).to_string();
3712+ let message_text = match clipboard_type {
3713+ ClipboardType::Clipboard => "yanked main selection to system clipboard",
3714+ ClipboardType::Selection => "yanked main selection to primary clipboard",
3715+ };
3716+
3717+ let value = doc.selection(view.id).primary().fragment(text);
40483718
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()),
3719+ if let Err(e) = editor
3720+ .clipboard_provider
3721+ .set_contents(value.into_owned(), clipboard_type)
3722+ {
3723+ bail!("Couldn't set system clipboard content: {}", e);
40523724 }
3725+
3726+ editor.set_status(message_text);
3727+ Ok(())
40533728}
40543729
40553730fn yank_main_selection_to_clipboard(cx: &mut Context) {
4056− yank_primary_selection_impl(cx.editor, '+');
4057− exit_select_mode(cx);
3731+ let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Clipboard);
3732+}
3733+
3734+fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3735+ let line_ending = doc!(cx.editor).line_ending;
3736+ let _ =
3737+ yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Selection);
40583738}
40593739
40603740fn yank_main_selection_to_primary_clipboard(cx: &mut Context) {
4061− yank_primary_selection_impl(cx.editor, '*');
3741+ let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Selection);
40623742 exit_select_mode(cx);
40633743}
40643744
@@ -4156,99 +3836,146 @@ pub(crate) fn paste_bracketed_value(cx: &mut Context, contents: String) {
41563836 };
41573837 let (view, doc) = current!(cx.editor);
41583838 paste_impl(&[contents], doc, view, paste, count, cx.editor.mode);
4159− exit_select_mode(cx);
3839+}
3840+
3841+fn paste_clipboard_impl(
3842+ editor: &mut Editor,
3843+ action: Paste,
3844+ clipboard_type: ClipboardType,
3845+ count: usize,
3846+) -> anyhow::Result<()> {
3847+ let (view, doc) = current!(editor);
3848+ match editor.clipboard_provider.get_contents(clipboard_type) {
3849+ Ok(contents) => {
3850+ paste_impl(&[contents], doc, view, action, count, editor.mode);
3851+ Ok(())
3852+ }
3853+ Err(e) => Err(e.context("Couldn't get system clipboard contents")),
3854+ }
41603855}
41613856
41623857fn paste_clipboard_after(cx: &mut Context) {
4163− paste(cx.editor, '+', Paste::After, cx.count());
4164− exit_select_mode(cx);
3858+ let _ = paste_clipboard_impl(
3859+ cx.editor,
3860+ Paste::After,
3861+ ClipboardType::Clipboard,
3862+ cx.count(),
3863+ );
41653864}
41663865
41673866fn paste_clipboard_before(cx: &mut Context) {
4168− paste(cx.editor, '+', Paste::Before, cx.count());
4169− exit_select_mode(cx);
3867+ let _ = paste_clipboard_impl(
3868+ cx.editor,
3869+ Paste::Before,
3870+ ClipboardType::Clipboard,
3871+ cx.count(),
3872+ );
41703873}
41713874
41723875fn paste_primary_clipboard_after(cx: &mut Context) {
4173− paste(cx.editor, '*', Paste::After, cx.count());
4174− exit_select_mode(cx);
3876+ let _ = paste_clipboard_impl(
3877+ cx.editor,
3878+ Paste::After,
3879+ ClipboardType::Selection,
3880+ cx.count(),
3881+ );
41753882}
41763883
41773884fn paste_primary_clipboard_before(cx: &mut Context) {
4178− paste(cx.editor, '*', Paste::Before, cx.count());
4179− exit_select_mode(cx);
3885+ let _ = paste_clipboard_impl(
3886+ cx.editor,
3887+ Paste::Before,
3888+ ClipboardType::Selection,
3889+ cx.count(),
3890+ );
41803891}
41813892
41823893fn replace_with_yanked(cx: &mut Context) {
4183− replace_with_yanked_impl(cx.editor, cx.register.unwrap_or('"'), cx.count());
4184− exit_select_mode(cx);
3894+ let count = cx.count();
3895+ let reg_name = cx.register.unwrap_or('"');
3896+ let (view, doc) = current!(cx.editor);
3897+ let registers = &mut cx.editor.registers;
3898+
3899+ if let Some(values) = registers.read(reg_name) {
3900+ if !values.is_empty() {
3901+ let repeat = std::iter::repeat(
3902+ values
3903+ .last()
3904+ .map(|value| Tendril::from(&value.repeat(count)))
3905+ .unwrap(),
3906+ );
3907+ let mut values = values
3908+ .iter()
3909+ .map(|value| Tendril::from(&value.repeat(count)))
3910+ .chain(repeat);
3911+ let selection = doc.selection(view.id);
3912+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3913+ if !range.is_empty() {
3914+ (range.from(), range.to(), Some(values.next().unwrap()))
3915+ } else {
3916+ (range.from(), range.to(), None)
3917+ }
3918+ });
3919+
3920+ doc.apply(&transaction, view.id);
3921+ exit_select_mode(cx);
3922+ }
3923+ }
41853924}
41863925
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();
3926+fn replace_selections_with_clipboard_impl(
3927+ cx: &mut Context,
3928+ clipboard_type: ClipboardType,
3929+) -> anyhow::Result<()> {
3930+ let count = cx.count();
3931+ let (view, doc) = current!(cx.editor);
41923932
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)
3933+ match cx.editor.clipboard_provider.get_contents(clipboard_type) {
3934+ Ok(contents) => {
3935+ let selection = doc.selection(view.id);
3936+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3937+ (
3938+ range.from(),
3939+ range.to(),
3940+ Some(contents.repeat(count).as_str().into()),
3941+ )
3942+ });
3943+
3944+ doc.apply(&transaction, view.id);
3945+ doc.append_changes_to_history(view);
42103946 }
4211− });
3947+ Err(e) => return Err(e.context("Couldn't get system clipboard contents")),
3948+ }
42123949
4213− doc.apply(&transaction, view.id);
3950+ exit_select_mode(cx);
3951+ Ok(())
42143952}
42153953
42163954fn replace_selections_with_clipboard(cx: &mut Context) {
4217− replace_with_yanked_impl(cx.editor, '+', cx.count());
4218− exit_select_mode(cx);
3955+ let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Clipboard);
42193956}
42203957
42213958fn replace_selections_with_primary_clipboard(cx: &mut Context) {
4222− replace_with_yanked_impl(cx.editor, '*', cx.count());
4223− exit_select_mode(cx);
3959+ let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Selection);
42243960}
42253961
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();
3962+fn paste(cx: &mut Context, pos: Paste) {
3963+ let count = cx.count();
3964+ let reg_name = cx.register.unwrap_or('"');
3965+ let (view, doc) = current!(cx.editor);
3966+ let registers = &mut cx.editor.registers;
42293967
4230− let (view, doc) = current!(editor);
4231− paste_impl(&values, doc, view, pos, count, editor.mode);
3968+ if let Some(values) = registers.read(reg_name) {
3969+ paste_impl(values, doc, view, pos, count, cx.editor.mode);
3970+ }
42323971}
42333972
42343973fn 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);
3974+ paste(cx, Paste::After)
42423975}
42433976
42443977fn 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);
3978+ paste(cx, Paste::Before)
42523979}
42533980
42543981fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
@@ -4287,7 +4014,6 @@ fn indent(cx: &mut Context) {
42874014 }),
42884015 );
42894016 doc.apply(&transaction, view.id);
4290− exit_select_mode(cx);
42914017}
42924018
42934019fn unindent(cx: &mut Context) {
@@ -4327,7 +4053,6 @@ fn unindent(cx: &mut Context) {
43274053 let transaction = Transaction::change(doc.text(), changes.into_iter());
43284054
43294055 doc.apply(&transaction, view.id);
4330− exit_select_mode(cx);
43314056}
43324057
43334058fn format_selections(cx: &mut Context) {
@@ -4345,42 +4070,37 @@ fn format_selections(cx: &mut Context) {
43454070 return;
43464071 }
43474072
4348− // TODO extra LanguageServerFeature::FormatSelections?
4349− // maybe such that LanguageServerFeature::Format contains it as well
4350− let Some(language_server) = doc
4073+ let (future, offset_encoding) = match doc
43514074 .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;
4362− };
4363−
4364− let offset_encoding = language_server.offset_encoding();
4365− let ranges: Vec<lsp::Range> = doc
4366− .selection(view_id)
43674075 .iter()
4368− .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
4369− .collect();
4076+ .find_map(|language_server| {
4077+ let offset_encoding = language_server.offset_encoding();
4078+ let ranges: Vec<lsp::Range> = doc
4079+ .selection(view_id)
4080+ .iter()
4081+ .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
4082+ .collect();
43704083
4371− // TODO: handle fails
4372− // TODO: concurrent map over all ranges
4084+ // TODO: handle fails
4085+ // TODO: concurrent map over all ranges
43734086
4374− let range = ranges[0];
4087+ let range = ranges[0];
43754088
4376− let future = language_server
4377− .text_document_range_formatting(
4378− doc.identifier(),
4379− range,
4380− lsp::FormattingOptions::default(),
4381− None,
4382− )
4383− .unwrap();
4089+ let future = language_server.text_document_range_formatting(
4090+ doc.identifier(),
4091+ range,
4092+ lsp::FormattingOptions::default(),
4093+ None,
4094+ )?;
4095+ Some((future, offset_encoding))
4096+ }) {
4097+ Some(future_offset_encoding) => future_offset_encoding,
4098+ None => {
4099+ cx.editor
4100+ .set_error("No language server supports range formatting");
4101+ return;
4102+ }
4103+ };
43844104
43854105 let edits = tokio::task::block_in_place(|| helix_lsp::block_on(future)).unwrap_or_default();
43864106
@@ -4394,9 +4114,10 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
43944114 use movement::skip_while;
43954115 let (view, doc) = current!(cx.editor);
43964116 let text = doc.text();
4397− let slice = text.slice(..);
4117+ let slice = doc.text().slice(..);
43984118
43994119 let mut changes = Vec::new();
4120+ let fragment = Tendril::from(" ");
44004121
44014122 for selection in doc.selection(view.id) {
44024123 let (start, mut end) = selection.line_range(slice);
@@ -4412,13 +4133,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44124133 let mut end = text.line_to_char(line + 1);
44134134 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
44144135
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));
4136+ // need to skip from start, not end
4137+ let change = (start, end, Some(fragment.clone()));
4138+ changes.push(change);
44224139 }
44234140 }
44244141
@@ -4430,6 +4147,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44304147 changes.sort_unstable_by_key(|(from, _to, _text)| *from);
44314148 changes.dedup();
44324149
4150+ // TODO: joining multiple empty lines should be replaced by a single space.
4151+ // need to merge change ranges that touch
4152+
44334153 // select inserted spaces
44344154 let transaction = if select_space {
44354155 let ranges: SmallVec<_> = changes
@@ -4441,9 +4161,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44414161 })
44424162 .collect();
44434163 let selection = Selection::new(ranges, 0);
4444− Transaction::change(text, changes.into_iter()).with_selection(selection)
4164+ Transaction::change(doc.text(), changes.into_iter()).with_selection(selection)
44454165 } else {
4446− Transaction::change(text, changes.into_iter())
4166+ Transaction::change(doc.text(), changes.into_iter())
44474167 };
44484168
44494169 doc.apply(&transaction, view.id);
@@ -4457,8 +4177,8 @@ fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) {
44574177 if remove { "remove:" } else { "keep:" }.into(),
44584178 Some(reg),
44594179 ui::completers::none,
4460− move |cx, regex, event| {
4461− let (view, doc) = current!(cx.editor);
4180+ move |editor, regex, event| {
4181+ let (view, doc) = current!(editor);
44624182 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
44634183 return;
44644184 }
@@ -4527,19 +4247,17 @@ pub fn completion(cx: &mut Context) {
45274247 let text = savepoint.text.clone();
45284248 let cursor = savepoint.cursor();
45294249
4530− let mut seen_language_servers = HashSet::new();
4531−
45324250 let mut futures: FuturesUnordered<_> = doc
45334251 .language_servers_with_feature(LanguageServerFeature::Completion)
4534− .filter(|ls| seen_language_servers.insert(ls.id()))
4535− .map(|language_server| {
4252+ .iter()
4253+ // TODO this should probably already been filtered in something like "language_servers_with_feature"
4254+ .filter_map(|language_server| {
45364255 let language_server_id = language_server.id();
45374256 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();
4257+ let pos = pos_to_lsp_pos(doc.text(), cursor, offset_encoding);
4258+ let completion_request = language_server.completion(doc.identifier(), pos, None)?;
45414259
4542− async move {
4260+ Some(async move {
45434261 let json = completion_request.await?;
45444262 let response: Option<lsp::CompletionResponse> = serde_json::from_value(json)?;
45454263
@@ -4556,12 +4274,13 @@ pub fn completion(cx: &mut Context) {
45564274 .map(|item| CompletionItem {
45574275 item,
45584276 language_server_id,
4277+ offset_encoding,
45594278 resolved: false,
45604279 })
45614280 .collect();
45624281
45634282 anyhow::Ok(items)
4564− }
4283+ })
45654284 })
45664285 .collect();
45674286
@@ -4692,13 +4411,7 @@ fn rotate_selections_backward(cx: &mut Context) {
46924411 rotate_selections(cx, Direction::Backward)
46934412}
46944413
4695−enum ReorderStrategy {
4696− RotateForward,
4697− RotateBackward,
4698− Reverse,
4699−}
4700−
4701−fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
4414+fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
47024415 let count = cx.count;
47034416 let (view, doc) = current!(cx.editor);
47044417 let text = doc.text().slice(..);
@@ -4716,10 +4429,9 @@ fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
47164429
47174430 for chunk in fragments.chunks_mut(group) {
47184431 // 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(),
4432+ match direction {
4433+ Direction::Forward => chunk.rotate_right(1),
4434+ Direction::Backward => chunk.rotate_left(1),
47234435 };
47244436 }
47254437
@@ -4736,13 +4448,10 @@ fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
47364448}
47374449
47384450fn rotate_selection_contents_forward(cx: &mut Context) {
4739− reorder_selection_contents(cx, ReorderStrategy::RotateForward)
4451+ rotate_selection_contents(cx, Direction::Forward)
47404452}
47414453fn 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)
4454+ rotate_selection_contents(cx, Direction::Backward)
47464455}
47474456
47484457// tree sitter node selection
@@ -4766,7 +4475,8 @@ fn expand_selection(cx: &mut Context) {
47664475 }
47674476 }
47684477 };
4769− cx.editor.apply_motion(motion);
4478+ motion(cx.editor);
4479+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
47704480}
47714481
47724482fn shrink_selection(cx: &mut Context) {
@@ -4790,7 +4500,8 @@ fn shrink_selection(cx: &mut Context) {
47904500 doc.set_selection(view.id, selection);
47914501 }
47924502 };
4793− cx.editor.apply_motion(motion);
4503+ motion(cx.editor);
4504+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
47944505}
47954506
47964507fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: &'static F)
@@ -4808,7 +4519,8 @@ where
48084519 doc.set_selection(view.id, selection);
48094520 }
48104521 };
4811− cx.editor.apply_motion(motion);
4522+ motion(cx.editor);
4523+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
48124524}
48134525
48144526fn select_next_sibling(cx: &mut Context) {
@@ -4819,68 +4531,22 @@ fn select_prev_sibling(cx: &mut Context) {
48194531 select_sibling_impl(cx, &|node| Node::prev_sibling(&node))
48204532}
48214533
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−
48654534fn match_brackets(cx: &mut Context) {
48664535 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− });
48824536
4883− doc.set_selection(view.id, selection);
4537+ if let Some(syntax) = doc.syntax() {
4538+ let text = doc.text().slice(..);
4539+ let selection = doc.selection(view.id).clone().transform(|range| {
4540+ if let Some(pos) =
4541+ match_brackets::find_matching_bracket_fuzzy(syntax, doc.text(), range.cursor(text))
4542+ {
4543+ range.put_cursor(text, pos, cx.editor.mode == Mode::Select)
4544+ } else {
4545+ range
4546+ }
4547+ });
4548+ doc.set_selection(view.id, selection);
4549+ }
48844550}
48854551
48864552//
@@ -4975,19 +4641,17 @@ fn transpose_view(cx: &mut Context) {
49754641 cx.editor.transpose_view()
49764642}
49774643
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);
4644+// split helper, clear it later
4645+fn split(cx: &mut Context, action: Action) {
4646+ let (view, doc) = current!(cx.editor);
49834647 let id = doc.id();
49844648 let selection = doc.selection(view.id).clone();
49854649 let offset = view.offset;
49864650
4987− editor.switch(id, action);
4651+ cx.editor.switch(id, action);
49884652
49894653 // match the selection in the previous view
4990− let (view, doc) = current!(editor);
4654+ let (view, doc) = current!(cx.editor);
49914655 doc.set_selection(view.id, selection);
49924656 // match the view scroll offset (switch doesn't handle this fully
49934657 // since the selection is only matched after the split)
@@ -4995,7 +4659,7 @@ fn split(editor: &mut Editor, action: Action) {
49954659}
49964660
49974661fn hsplit(cx: &mut Context) {
4998− split(cx.editor, Action::HorizontalSplit);
4662+ split(cx, Action::HorizontalSplit);
49994663}
50004664
50014665fn hsplit_new(cx: &mut Context) {
@@ -5003,7 +4667,7 @@ fn hsplit_new(cx: &mut Context) {
50034667}
50044668
50054669fn vsplit(cx: &mut Context) {
5006− split(cx.editor, Action::VerticalSplit);
4670+ split(cx, Action::VerticalSplit);
50074671}
50084672
50094673fn vsplit_new(cx: &mut Context) {
@@ -5052,12 +4716,7 @@ fn insert_register(cx: &mut Context) {
50524716 if let Some(ch) = event.char() {
50534717 cx.editor.autoinfo = None;
50544718 cx.register = Some(ch);
5055− paste(
5056− cx.editor,
5057− cx.register.unwrap_or('"'),
5058− Paste::Cursor,
5059− cx.count(),
5060− );
4719+ paste(cx, Paste::Cursor);
50614720 }
50624721 })
50634722}
@@ -5141,7 +4800,8 @@ fn goto_ts_object_impl(cx: &mut Context, object: &'static str, direction: Direct
51414800 editor.set_status("Syntax-tree is not available in current buffer");
51424801 }
51434802 };
5144− cx.editor.apply_motion(motion);
4803+ motion(cx.editor);
4804+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
51454805}
51464806
51474807fn goto_next_function(cx: &mut Context) {
@@ -5262,7 +4922,8 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
52624922 });
52634923 doc.set_selection(view.id, selection);
52644924 };
5265− cx.editor.apply_motion(textobject);
4925+ textobject(cx.editor);
4926+ cx.editor.last_motion = Some(Motion(Box::new(textobject)));
52664927 }
52674928 });
52684929
@@ -5352,18 +5013,11 @@ fn surround_replace(cx: &mut Context) {
53525013 }
53535014 };
53545015
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−
53625016 cx.on_next_key(move |cx, event| {
53635017 let (view, doc) = current!(cx.editor);
53645018 let to = match event.char() {
53655019 Some(to) => to,
5366− None => return doc.set_selection(view.id, selection),
5020+ None => return,
53675021 };
53685022 let (open, close) = surround::get_pair(to);
53695023 let transaction = Transaction::change(
@@ -5374,7 +5028,6 @@ fn surround_replace(cx: &mut Context) {
53745028 (pos, pos + 1, Some(t))
53755029 }),
53765030 );
5377− doc.set_selection(view.id, selection);
53785031 doc.apply(&transaction, view.id);
53795032 exit_select_mode(cx);
53805033 });
@@ -5609,18 +5262,12 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
56095262 };
56105263
56115264 // 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");
5265+ // Once the MSRV is 1.66.0 (mixed_integer_ops is stabilized), we can use checked
5266+ // arithmetic to assert this.
5267+ let anchor = (to as isize + offset - deleted_len as isize) as usize;
56175268 let new_range = Range::new(anchor, anchor + output_len).with_direction(range.direction());
56185269 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");
5270+ offset = offset + output_len as isize - deleted_len as isize;
56245271
56255272 changes.push((from, to, Some(output)));
56265273 }
@@ -5642,7 +5289,7 @@ fn shell_prompt(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBeha
56425289 cx,
56435290 prompt,
56445291 Some('|'),
5645− ui::completers::filename,
5292+ ui::completers::none,
56465293 move |cx, input: &str, event: PromptEvent| {
56475294 if event != PromptEvent::Validate {
56485295 return;
@@ -5759,7 +5406,6 @@ fn increment_impl(cx: &mut Context, increment_direction: IncrementDirection) {
57595406 let transaction = Transaction::change(doc.text(), changes.into_iter());
57605407 let transaction = transaction.with_selection(new_selection);
57615408 doc.apply(&transaction, view.id);
5762− exit_select_mode(cx);
57635409 }
57645410}
57655411
@@ -5778,12 +5424,9 @@ fn record_macro(cx: &mut Context) {
57785424 }
57795425 })
57805426 .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− }
5427+ cx.editor.registers.write(reg, vec![s]);
5428+ cx.editor
5429+ .set_status(format!("Recorded to register [{}]", reg));
57875430 } else {
57885431 let reg = cx.register.take().unwrap_or('@');
57895432 cx.editor.macro_recording = Some((reg, Vec::new()));
@@ -5803,14 +5446,8 @@ fn replay_macro(cx: &mut Context) {
58035446 return;
58045447 }
58055448
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) {
5449+ let keys: Vec<KeyEvent> = if let Some([keys_str]) = cx.editor.registers.read(reg) {
5450+ match helix_view::input::parse_macro(keys_str) {
58145451 Ok(keys) => keys,
58155452 Err(err) => {
58165453 cx.editor.set_error(format!("Invalid macro: {}", err));