@@ -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,
3130 visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes,
32− RopeReader, RopeSlice, Selection, SmallVec, Tendril, Transaction,
31+ RopeSlice, 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, CompleteAction, 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
@@ -250,9 +246,6 @@ impl MappableCommand {
250246 move_next_long_word_start, "Move to start of next long word",
251247 move_prev_long_word_start, "Move to start of previous long word",
252248 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",
256249 extend_next_word_start, "Extend to start of next word",
257250 extend_prev_word_start, "Extend to start of previous word",
258251 extend_next_word_end, "Extend to end of next word",
@@ -260,9 +253,6 @@ impl MappableCommand {
260253 extend_next_long_word_start, "Extend to start of next long word",
261254 extend_prev_long_word_start, "Extend to start of previous long word",
262255 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",
266256 find_till_char, "Move till next occurrence of char",
267257 find_next_char, "Move to next occurrence of char",
268258 extend_till_char, "Extend till next occurrence of char",
@@ -284,7 +274,6 @@ impl MappableCommand {
284274 select_regex, "Select all regex matches inside selections",
285275 split_selection, "Split selections on regex matches",
286276 split_selection_on_newline, "Split selection on newlines",
287− merge_selections, "Merge selections",
288277 merge_consecutive_selections, "Merge consecutive selections",
289278 search, "Search for regex pattern",
290279 rsearch, "Reverse search for regex pattern",
@@ -337,7 +326,7 @@ impl MappableCommand {
337326 goto_implementation, "Goto implementation",
338327 goto_file_start, "Goto line number <n> else file start",
339328 goto_file_end, "Goto file end",
340− goto_file, "Goto files/URLs in selection",
329+ goto_file, "Goto files in selection",
341330 goto_file_hsplit, "Goto files in selection (hsplit)",
342331 goto_file_vsplit, "Goto files in selection (vsplit)",
343332 goto_reference, "Goto references",
@@ -369,7 +358,6 @@ impl MappableCommand {
369358 extend_to_line_end, "Extend to line end",
370359 extend_to_line_end_newline, "Extend to line end",
371360 signature_help, "Show signature help",
372− smart_tab, "Insert tab if all cursors have all whitespace to their left; otherwise, run a separate command.",
373361 insert_tab, "Insert tab char",
374362 insert_newline, "Insert newline char",
375363 delete_char_backward, "Delete previous char",
@@ -384,9 +372,6 @@ impl MappableCommand {
384372 later, "Move forward in history",
385373 commit_undo_checkpoint, "Commit changes to new checkpoint",
386374 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",
390375 yank_joined_to_clipboard, "Join and yank selections to clipboard",
391376 yank_main_selection_to_clipboard, "Yank main selection to clipboard",
392377 yank_joined_to_primary_clipboard, "Join and yank selections to primary clipboard",
@@ -417,7 +402,6 @@ impl MappableCommand {
417402 rotate_selections_backward, "Rotate selections backward",
418403 rotate_selection_contents_forward, "Rotate selection contents forward",
419404 rotate_selection_contents_backward, "Rotate selections contents backward",
420− reverse_selection_contents, "Reverse selections contents",
421405 expand_selection, "Expand selection to parent syntax node",
422406 shrink_selection, "Shrink selection to previously expanded syntax node",
423407 select_next_sibling, "Select next sibling in syntax tree",
@@ -990,7 +974,6 @@ fn align_selections(cx: &mut Context) {
990974
991975 let transaction = Transaction::change(doc.text(), changes.into_iter());
992976 doc.apply(&transaction, view.id);
993− exit_select_mode(cx);
994977}
995978
996979fn goto_window(cx: &mut Context, align: Align) {
@@ -1082,10 +1065,6 @@ fn move_prev_long_word_start(cx: &mut Context) {
10821065 move_word_impl(cx, movement::move_prev_long_word_start)
10831066}
10841067
1085−fn move_prev_long_word_end(cx: &mut Context) {
1086− move_word_impl(cx, movement::move_prev_long_word_end)
1087−}
1088−
10891068fn move_next_long_word_end(cx: &mut Context) {
10901069 move_word_impl(cx, movement::move_next_long_word_end)
10911070}
@@ -1110,7 +1089,8 @@ where
11101089 .transform(|range| move_fn(text, range, count, behavior));
11111090 doc.set_selection(view.id, selection);
11121091 };
1113− cx.editor.apply_motion(motion)
1092+ motion(cx.editor);
1093+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
11141094}
11151095
11161096fn goto_prev_paragraph(cx: &mut Context) {
@@ -1165,10 +1145,6 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11651145 let (view, doc) = current_ref!(cx.editor);
11661146 let text = doc.text();
11671147 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();
11721148 let mut paths: Vec<_> = selections
11731149 .iter()
11741150 .map(|r| text.slice(r.from()..r.to()).to_string())
@@ -1196,80 +1172,16 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11961172 .to_string(),
11971173 );
11981174 }
1199−
12001175 for sel in paths {
12011176 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) {
1177+ if !p.is_empty() {
1178+ if let Err(e) = cx.editor.open(&PathBuf::from(p), action) {
12501179 cx.editor.set_error(format!("Open file failed: {:?}", e));
12511180 }
12521181 }
12531182 }
12541183}
12551184
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−
12731185fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
12741186where
12751187 F: Fn(RopeSlice, Range, usize) -> Range,
@@ -1310,74 +1222,14 @@ fn extend_prev_long_word_start(cx: &mut Context) {
13101222 extend_word_impl(cx, movement::move_prev_long_word_start)
13111223}
13121224
1313−fn extend_prev_long_word_end(cx: &mut Context) {
1314− extend_word_impl(cx, movement::move_prev_long_word_end)
1315−}
1316−
13171225fn extend_next_long_word_end(cx: &mut Context) {
13181226 extend_word_impl(cx, movement::move_next_long_word_end)
13191227}
13201228
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) {
1229+fn will_find_char<F>(cx: &mut Context, search_fn: F, inclusive: bool, extend: bool)
1230+where
1231+ F: Fn(RopeSlice, char, usize, usize, bool) -> Option<usize> + 'static,
1232+{
13811233 // TODO: count is reset to 1 before next key so we move it into the closure here.
13821234 // Would be nice to carry over.
13831235 let count = cx.count();
@@ -1390,9 +1242,13 @@ fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bo
13901242 KeyEvent {
13911243 code: KeyCode::Enter,
13921244 ..
1393− } => {
1394− find_char_line_ending(cx, count, direction, inclusive, extend);
1395− return;
1245+ } =>
1246+ // TODO: this isn't quite correct when CRLF is involved.
1247+ // This hack will work in most cases, since documents don't
1248+ // usually mix line endings. But we should fix it eventually
1249+ // anyway.
1250+ {
1251+ doc!(cx.editor).line_ending.as_str().chars().next().unwrap()
13961252 }
13971253
13981254 KeyEvent {
@@ -1405,18 +1261,11 @@ fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bo
14051261 } => ch,
14061262 _ => return,
14071263 };
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− };
14181264
1419− cx.editor.apply_motion(motion);
1265+ find_char_impl(cx.editor, &search_fn, inclusive, extend, ch, count);
1266+ cx.editor.last_motion = Some(Motion(Box::new(move |editor: &mut Editor| {
1267+ find_char_impl(editor, &search_fn, inclusive, true, ch, 1);
1268+ })));
14201269 })
14211270}
14221271
@@ -1495,39 +1344,46 @@ fn find_prev_char_impl(
14951344}
14961345
14971346fn find_till_char(cx: &mut Context) {
1498− find_char(cx, Direction::Forward, false, false);
1347+ will_find_char(cx, find_next_char_impl, false, false)
14991348}
15001349
15011350fn find_next_char(cx: &mut Context) {
1502− find_char(cx, Direction::Forward, true, false)
1351+ will_find_char(cx, find_next_char_impl, true, false)
15031352}
15041353
15051354fn extend_till_char(cx: &mut Context) {
1506− find_char(cx, Direction::Forward, false, true)
1355+ will_find_char(cx, find_next_char_impl, false, true)
15071356}
15081357
15091358fn extend_next_char(cx: &mut Context) {
1510− find_char(cx, Direction::Forward, true, true)
1359+ will_find_char(cx, find_next_char_impl, true, true)
15111360}
15121361
15131362fn till_prev_char(cx: &mut Context) {
1514− find_char(cx, Direction::Backward, false, false)
1363+ will_find_char(cx, find_prev_char_impl, false, false)
15151364}
15161365
15171366fn find_prev_char(cx: &mut Context) {
1518− find_char(cx, Direction::Backward, true, false)
1367+ will_find_char(cx, find_prev_char_impl, true, false)
15191368}
15201369
15211370fn extend_till_prev_char(cx: &mut Context) {
1522− find_char(cx, Direction::Backward, false, true)
1371+ will_find_char(cx, find_prev_char_impl, false, true)
15231372}
15241373
15251374fn extend_prev_char(cx: &mut Context) {
1526− find_char(cx, Direction::Backward, true, true)
1375+ will_find_char(cx, find_prev_char_impl, true, true)
15271376}
15281377
15291378fn repeat_last_motion(cx: &mut Context) {
1530− cx.editor.repeat_last_motion(cx.count())
1379+ let count = cx.count();
1380+ let last_motion = cx.editor.last_motion.take();
1381+ if let Some(m) = &last_motion {
1382+ for _ in 0..count {
1383+ m.run(cx.editor);
1384+ }
1385+ cx.editor.last_motion = last_motion;
1386+ }
15311387}
15321388
15331389fn replace(cx: &mut Context) {
@@ -1594,7 +1450,6 @@ where
15941450 });
15951451
15961452 doc.apply(&transaction, view.id);
1597− exit_select_mode(cx);
15981453}
15991454
16001455fn switch_case(cx: &mut Context) {
@@ -1836,8 +1691,8 @@ fn select_regex(cx: &mut Context) {
18361691 "select:".into(),
18371692 Some(reg),
18381693 ui::completers::none,
1839− move |cx, regex, event| {
1840− let (view, doc) = current!(cx.editor);
1694+ move |editor, regex, event| {
1695+ let (view, doc) = current!(editor);
18411696 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
18421697 return;
18431698 }
@@ -1858,8 +1713,8 @@ fn split_selection(cx: &mut Context) {
18581713 "split:".into(),
18591714 Some(reg),
18601715 ui::completers::none,
1861− move |cx, regex, event| {
1862− let (view, doc) = current!(cx.editor);
1716+ move |editor, regex, event| {
1717+ let (view, doc) = current!(editor);
18631718 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
18641719 return;
18651720 }
@@ -1881,12 +1736,6 @@ fn split_selection_on_newline(cx: &mut Context) {
18811736 doc.set_selection(view.id, selection);
18821737}
18831738
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−
18901739fn merge_consecutive_selections(cx: &mut Context) {
18911740 let (view, doc) = current!(cx.editor);
18921741 let selection = doc.selection(view.id).clone().merge_consecutive_ranges();
@@ -1982,11 +1831,11 @@ fn search_impl(
19821831
19831832fn search_completions(cx: &mut Context, reg: Option<char>) -> Vec<String> {
19841833 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());
1834+ .and_then(|reg| cx.editor.registers.get(reg))
1835+ .map_or(Vec::new(), |reg| reg.read().iter().take(200).collect());
19871836 items.sort_unstable();
19881837 items.dedup();
1989− items.into_iter().map(|value| value.to_string()).collect()
1838+ items.into_iter().cloned().collect()
19901839}
19911840
19921841fn search(cx: &mut Context) {
@@ -2023,14 +1872,12 @@ fn searcher(cx: &mut Context, direction: Direction) {
20231872 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
20241873 .collect()
20251874 },
2026− move |cx, regex, event| {
2027− if event == PromptEvent::Validate {
2028− cx.editor.registers.last_search_register = reg;
2029− } else if event != PromptEvent::Update {
1875+ move |editor, regex, event| {
1876+ if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
20301877 return;
20311878 }
20321879 search_impl(
2033− cx.editor,
1880+ editor,
20341881 &contents,
20351882 ®ex,
20361883 Movement::Move,
@@ -2045,13 +1892,11 @@ fn searcher(cx: &mut Context, direction: Direction) {
20451892
20461893fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Direction) {
20471894 let count = cx.count();
2048− let register = cx
2049− .register
2050− .unwrap_or(cx.editor.registers.last_search_register);
20511895 let config = cx.editor.config();
20521896 let scrolloff = config.scrolloff;
2053− if let Some(query) = cx.editor.registers.first(register, cx.editor) {
2054− let doc = doc!(cx.editor);
1897+ let (_, doc) = current!(cx.editor);
1898+ let registers = &cx.editor.registers;
1899+ if let Some(query) = registers.read('/').and_then(|query| query.last()) {
20551900 let contents = doc.text().slice(..).to_string();
20561901 let search_config = &config.search;
20571902 let case_insensitive = if search_config.smart_case {
@@ -2060,7 +1905,7 @@ fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Dir
20601905 false
20611906 };
20621907 let wrap_around = search_config.wrap_around;
2063− if let Ok(regex) = RegexBuilder::new(&query)
1908+ if let Ok(regex) = RegexBuilder::new(query)
20641909 .case_insensitive(case_insensitive)
20651910 .multi_line(true)
20661911 .build()
@@ -2100,7 +1945,6 @@ fn extend_search_prev(cx: &mut Context) {
21001945}
21011946
21021947fn search_selection(cx: &mut Context) {
2103− let register = cx.register.unwrap_or('/');
21041948 let (view, doc) = current!(cx.editor);
21051949 let contents = doc.text().slice(..);
21061950
@@ -2113,24 +1957,13 @@ fn search_selection(cx: &mut Context) {
21131957 .collect::<Vec<_>>()
21141958 .join("|");
21151959
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− }
1960+ let msg = format!("register '{}' set to '{}'", '/', ®ex);
1961+ cx.editor.registers.push('/', regex);
1962+ cx.editor.set_status(msg);
21241963}
21251964
21261965fn 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) {
1966+ let regex = match cx.editor.registers.last('/') {
21341967 Some(regex) => regex,
21351968 None => return,
21361969 };
@@ -2148,19 +1981,14 @@ fn make_search_word_bounded(cx: &mut Context) {
21481981 if !start_anchored {
21491982 new_regex.push_str("\\b");
21501983 }
2151− new_regex.push_str(®ex);
1984+ new_regex.push_str(regex);
21521985 if !end_anchored {
21531986 new_regex.push_str("\\b");
21541987 }
21551988
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− }
1989+ let msg = format!("register '{}' set to '{}'", '/', &new_regex);
1990+ cx.editor.registers.push('/', new_regex);
1991+ cx.editor.set_status(msg);
21641992}
21651993
21661994fn global_search(cx: &mut Context) {
@@ -2199,11 +2027,13 @@ fn global_search(cx: &mut Context) {
21992027 }
22002028 }
22012029
2030+ let (all_matches_sx, all_matches_rx) = tokio::sync::mpsc::unbounded_channel::<FileResult>();
22022031 let config = cx.editor.config();
22032032 let smart_case = config.search.smart_case;
22042033 let file_picker_config = config.file_picker.clone();
22052034
22062035 let reg = cx.register.unwrap_or('/');
2036+
22072037 let completions = search_completions(cx, Some(reg));
22082038 ui::regex_prompt(
22092039 cx,
@@ -2216,67 +2046,43 @@ fn global_search(cx: &mut Context) {
22162046 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
22172047 .collect()
22182048 },
2219− move |cx, regex, event| {
2049+ move |_editor, regex, event| {
22202050 if event != PromptEvent::Validate {
22212051 return;
22222052 }
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();
22312053
22322054 if let Ok(matcher) = RegexMatcherBuilder::new()
22332055 .case_smart(smart_case)
22342056 .build(regex.as_str())
22352057 {
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);
2058+ let searcher = SearcherBuilder::new()
2059+ .binary_detection(BinaryDetection::quit(b'\x00'))
2060+ .build();
22442061
2062+ let search_root = std::env::current_dir()
2063+ .expect("Global search error: Failed to get current dir");
22452064 let dedup_symlinks = file_picker_config.deduplicate_links;
22462065 let absolute_root = search_root
22472066 .canonicalize()
22482067 .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(|| {
2068+
2069+ WalkBuilder::new(search_root)
2070+ .hidden(file_picker_config.hidden)
2071+ .parents(file_picker_config.parents)
2072+ .ignore(file_picker_config.ignore)
2073+ .follow_links(file_picker_config.follow_symlinks)
2074+ .git_ignore(file_picker_config.git_ignore)
2075+ .git_global(file_picker_config.git_global)
2076+ .git_exclude(file_picker_config.git_exclude)
2077+ .max_depth(file_picker_config.max_depth)
2078+ .filter_entry(move |entry| {
2079+ filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2080+ })
2081+ .build_parallel()
2082+ .run(|| {
22762083 let mut searcher = searcher.clone();
22772084 let matcher = matcher.clone();
2278− let injector = injector_.clone();
2279− let documents = &documents;
2085+ let all_matches_sx = all_matches_sx.clone();
22802086 Box::new(move |entry: Result<DirEntry, ignore::Error>| -> WalkState {
22812087 let entry = match entry {
22822088 Ok(entry) => entry,
@@ -2289,39 +2095,17 @@ fn global_search(cx: &mut Context) {
22892095 _ => return WalkState::Continue,
22902096 };
22912097
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− };
2098+ let result = searcher.search_path(
2099+ &matcher,
2100+ entry.path(),
2101+ sinks::UTF8(|line_num, _| {
2102+ all_matches_sx
2103+ .send(FileResult::new(entry.path(), line_num as usize - 1))
2104+ .unwrap();
2105+
2106+ Ok(true)
2107+ }),
2108+ );
23252109
23262110 if let Err(err) = result {
23272111 log::error!(
@@ -2330,66 +2114,67 @@ fn global_search(cx: &mut Context) {
23302114 err
23312115 );
23322116 }
2333− if stop {
2334− WalkState::Quit
2335− } else {
2336− WalkState::Continue
2337− }
2117+ WalkState::Continue
23382118 })
23392119 });
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− })
23872120 } else {
23882121 // Otherwise do nothing
23892122 // log::warn!("Global Search Invalid Pattern")
23902123 }
23912124 },
23922125 );
2126+
2127+ let current_path = doc_mut!(cx.editor).path().cloned();
2128+
2129+ let show_picker = async move {
2130+ let all_matches: Vec<FileResult> =
2131+ UnboundedReceiverStream::new(all_matches_rx).collect().await;
2132+ let call: job::Callback = Callback::EditorCompositor(Box::new(
2133+ move |editor: &mut Editor, compositor: &mut Compositor| {
2134+ if all_matches.is_empty() {
2135+ editor.set_status("No matches found");
2136+ return;
2137+ }
2138+
2139+ let picker = FilePicker::new(
2140+ all_matches,
2141+ current_path,
2142+ move |cx, FileResult { path, line_num }, action| {
2143+ match cx.editor.open(path, action) {
2144+ Ok(_) => {}
2145+ Err(e) => {
2146+ cx.editor.set_error(format!(
2147+ "Failed to open file '{}': {}",
2148+ path.display(),
2149+ e
2150+ ));
2151+ return;
2152+ }
2153+ }
2154+
2155+ let line_num = *line_num;
2156+ let (view, doc) = current!(cx.editor);
2157+ let text = doc.text();
2158+ if line_num >= text.len_lines() {
2159+ cx.editor.set_error("The line you jumped to does not exist anymore because the file has changed.");
2160+ return;
2161+ }
2162+ let start = text.line_to_char(line_num);
2163+ let end = text.line_to_char((line_num + 1).min(text.len_lines()));
2164+
2165+ doc.set_selection(view.id, Selection::single(start, end));
2166+ align_view(doc, view, Align::Center);
2167+ },
2168+ |_editor, FileResult { path, line_num }| {
2169+ Some((path.clone().into(), Some((*line_num, *line_num))))
2170+ },
2171+ );
2172+ compositor.push(Box::new(overlaid(picker)));
2173+ },
2174+ ));
2175+ Ok(call)
2176+ };
2177+ cx.jobs.callback(show_picker);
23932178}
23942179
23952180enum Extend {
@@ -2512,35 +2297,17 @@ enum Operation {
25122297 Change,
25132298}
25142299
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−
25292300fn delete_selection_impl(cx: &mut Context, op: Operation) {
25302301 let (view, doc) = current!(cx.editor);
25312302
25322303 let selection = doc.selection(view.id);
2533− let only_whole_lines = selection_is_linewise(selection, doc.text());
25342304
25352305 if cx.register != Some('_') {
25362306 // first yank the selection
25372307 let text = doc.text().slice(..);
25382308 let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect();
25392309 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− }
2310+ cx.editor.registers.write(reg_name, values);
25442311 };
25452312
25462313 // then delete
@@ -2554,11 +2321,7 @@ fn delete_selection_impl(cx: &mut Context, op: Operation) {
25542321 exit_select_mode(cx);
25552322 }
25562323 Operation::Change => {
2557− if only_whole_lines {
2558− open_above(cx);
2559− } else {
2560− enter_insert_mode(cx);
2561− }
2324+ enter_insert_mode(cx);
25622325 }
25632326 }
25642327}
@@ -2680,10 +2443,6 @@ fn insert_mode(cx: &mut Context) {
26802443 .transform(|range| Range::new(range.to(), range.from()));
26812444
26822445 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();
26872446}
26882447
26892448// inserts at the end of each selection
@@ -2720,10 +2479,6 @@ fn append_mode(cx: &mut Context) {
27202479
27212480fn file_picker(cx: &mut Context) {
27222481 let root = find_workspace().0;
2723− if !root.exists() {
2724− cx.editor.set_error("Workspace directory does not exist");
2725− return;
2726− }
27272482 let picker = ui::file_picker(root, &cx.editor.config());
27282483 cx.push_layer(Box::new(overlaid(picker)));
27292484}
@@ -2744,14 +2499,8 @@ fn file_picker_in_current_buffer_directory(cx: &mut Context) {
27442499 let picker = ui::file_picker(path, &cx.editor.config());
27452500 cx.push_layer(Box::new(overlaid(picker)));
27462501}
2747−
27482502fn 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− }
2503+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("./"));
27552504 let picker = ui::file_picker(cwd, &cx.editor.config());
27562505 cx.push_layer(Box::new(overlaid(picker)));
27572506}
@@ -2810,18 +2559,22 @@ fn buffer_picker(cx: &mut Context) {
28102559 // mru
28112560 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
28122561
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− });
2562+ let picker = FilePicker::new(
2563+ items,
2564+ (),
2565+ |cx, meta, action| {
2566+ cx.editor.switch(meta.id, action);
2567+ },
2568+ |editor, meta| {
2569+ let doc = &editor.documents.get(&meta.id)?;
2570+ let &view_id = doc.selections().keys().next()?;
2571+ let line = doc
2572+ .selection(view_id)
2573+ .primary()
2574+ .cursor_line(doc.text().slice(..));
2575+ Some((meta.id.into(), Some((line, line))))
2576+ },
2577+ );
28252578 cx.push_layer(Box::new(overlaid(picker)));
28262579}
28272580
@@ -2887,7 +2640,7 @@ fn jumplist_picker(cx: &mut Context) {
28872640 }
28882641 };
28892642
2890− let picker = Picker::new(
2643+ let picker = FilePicker::new(
28912644 cx.editor
28922645 .tree
28932646 .views()
@@ -2901,18 +2654,16 @@ fn jumplist_picker(cx: &mut Context) {
29012654 |cx, meta, action| {
29022655 cx.editor.switch(meta.id, action);
29032656 let config = cx.editor.config();
2904− let (view, doc) = (view_mut!(cx.editor), doc_mut!(cx.editor, &meta.id));
2657+ let (view, doc) = current!(cx.editor);
29052658 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− }
2659+ view.ensure_cursor_in_view_center(doc, config.scrolloff);
29092660 },
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− });
2661+ |editor, meta| {
2662+ let doc = &editor.documents.get(&meta.id)?;
2663+ let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2664+ Some((meta.path.clone()?.into(), Some((line, line))))
2665+ },
2666+ );
29162667 cx.push_layer(Box::new(overlaid(picker)));
29172668}
29182669
@@ -2946,9 +2697,6 @@ impl ui::menu::Item for MappableCommand {
29462697}
29472698
29482699pub fn command_palette(cx: &mut Context) {
2949− let register = cx.register;
2950− let count = cx.count;
2951−
29522700 cx.callback = Some(Box::new(
29532701 move |compositor: &mut Compositor, cx: &mut compositor::Context| {
29542702 let keymap = compositor.find::<ui::EditorView>().unwrap().keymaps.map()
@@ -2966,8 +2714,8 @@ pub fn command_palette(cx: &mut Context) {
29662714
29672715 let picker = Picker::new(commands, keymap, move |cx, command, _action| {
29682716 let mut ctx = Context {
2969− register,
2970− count,
2717+ register: None,
2718+ count: std::num::NonZeroUsize::new(1),
29712719 editor: cx.editor,
29722720 callback: None,
29732721 on_next_key_callback: None,
@@ -3006,88 +2754,24 @@ fn last_picker(cx: &mut Context) {
30062754 }));
30072755}
30082756
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.
2757+// I inserts at the first nonwhitespace character of each line with a selection
30172758fn insert_at_line_start(cx: &mut Context) {
3018− insert_with_indent(cx, IndentFallbackPos::LineStart);
2759+ goto_first_nonwhitespace(cx);
2760+ enter_insert_mode(cx);
30192761}
30202762
3021−// `A` inserts at the end of each line with a selection.
3022−// If the line is empty, automatically indent.
2763+// A inserts at the end of each line with a selection
30232764fn 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) {
30302765 enter_insert_mode(cx);
3031−
30322766 let (view, doc) = current!(cx.editor);
30332767
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− }
2768+ let selection = doc.selection(view.id).clone().transform(|range| {
2769+ let text = doc.text().slice(..);
2770+ let line = range.cursor_line(text);
2771+ let pos = line_end_char_index(&text, line);
2772+ Range::new(pos, pos)
30872773 });
3088−
3089− transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3090− doc.apply(&transaction, view.id);
2774+ doc.set_selection(view.id, selection);
30912775}
30922776
30932777// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
@@ -3158,7 +2842,6 @@ fn open(cx: &mut Context, open: Open) {
31582842 Open::Below => graphemes::prev_grapheme_boundary(text, range.to()),
31592843 Open::Above => range.from(),
31602844 });
3161−
31622845 let new_line = match open {
31632846 // adjust position to the end of the line (next line - 1)
31642847 Open::Below => cursor_line + 1,
@@ -3166,15 +2849,13 @@ fn open(cx: &mut Context, open: Open) {
31662849 Open::Above => cursor_line,
31672850 };
31682851
3169− let line_num = new_line.saturating_sub(1);
3170−
31712852 // Index to insert newlines after, as well as the char width
31722853 // to use to compensate for those inserted newlines.
31732854 let (line_end_index, line_end_offset_width) = if new_line == 0 {
31742855 (0, 0)
31752856 } else {
31762857 (
3177− line_end_char_index(&text, line_num),
2858+ line_end_char_index(&doc.text().slice(..), new_line.saturating_sub(1)),
31782859 doc.line_ending.len_chars(),
31792860 )
31802861 };
@@ -3182,15 +2863,13 @@ fn open(cx: &mut Context, open: Open) {
31822863 let indent = indent::indent_for_newline(
31832864 doc.language_config(),
31842865 doc.syntax(),
3185− &doc.config.load().indent_heuristic,
31862866 &doc.indent_style,
31872867 doc.tab_width(),
31882868 text,
3189− line_num,
2869+ new_line.saturating_sub(1),
31902870 line_end_index,
31912871 cursor_line,
31922872 );
3193−
31942873 let indent_len = indent.len();
31952874 let mut text = String::with_capacity(1 + indent_len);
31962875 text.push_str(doc.line_ending.as_str());
@@ -3350,7 +3029,7 @@ fn exit_select_mode(cx: &mut Context) {
33503029
33513030fn goto_first_diag(cx: &mut Context) {
33523031 let (view, doc) = current!(cx.editor);
3353− let selection = match doc.shown_diagnostics().next() {
3032+ let selection = match doc.diagnostics().first() {
33543033 Some(diag) => Selection::single(diag.range.start, diag.range.end),
33553034 None => return,
33563035 };
@@ -3359,7 +3038,7 @@ fn goto_first_diag(cx: &mut Context) {
33593038
33603039fn goto_last_diag(cx: &mut Context) {
33613040 let (view, doc) = current!(cx.editor);
3362− let selection = match doc.shown_diagnostics().last() {
3041+ let selection = match doc.diagnostics().last() {
33633042 Some(diag) => Selection::single(diag.range.start, diag.range.end),
33643043 None => return,
33653044 };
@@ -3375,9 +3054,10 @@ fn goto_next_diag(cx: &mut Context) {
33753054 .cursor(doc.text().slice(..));
33763055
33773056 let diag = doc
3378− .shown_diagnostics()
3057+ .diagnostics()
3058+ .iter()
33793059 .find(|diag| diag.range.start > cursor_pos)
3380− .or_else(|| doc.shown_diagnostics().next());
3060+ .or_else(|| doc.diagnostics().first());
33813061
33823062 let selection = match diag {
33833063 Some(diag) => Selection::single(diag.range.start, diag.range.end),
@@ -3395,10 +3075,11 @@ fn goto_prev_diag(cx: &mut Context) {
33953075 .cursor(doc.text().slice(..));
33963076
33973077 let diag = doc
3398− .shown_diagnostics()
3078+ .diagnostics()
3079+ .iter()
33993080 .rev()
34003081 .find(|diag| diag.range.start < cursor_pos)
3401− .or_else(|| doc.shown_diagnostics().last());
3082+ .or_else(|| doc.diagnostics().last());
34023083
34033084 let selection = match diag {
34043085 // NOTE: the selection is reversed because we're jumping to the
@@ -3489,7 +3170,8 @@ fn goto_next_change_impl(cx: &mut Context, direction: Direction) {
34893170
34903171 doc.set_selection(view.id, selection)
34913172 };
3492− cx.editor.apply_motion(motion);
3173+ motion(cx.editor);
3174+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
34933175}
34943176
34953177/// Returns the [Range] for a [Hunk] in the given text.
@@ -3552,19 +3234,23 @@ pub mod insert {
35523234 use helix_lsp::lsp;
35533235 // if ch matches completion char, trigger completion
35543236 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− });
3237+ let language_server = match doc.language_server() {
3238+ Some(language_server) => language_server,
3239+ None => return,
3240+ };
3241+
3242+ let capabilities = language_server.capabilities();
35643243
3565− if trigger_completion {
3566− cx.editor.clear_idle_timer();
3567− super::completion(cx);
3244+ if let Some(lsp::CompletionOptions {
3245+ trigger_characters: Some(triggers),
3246+ ..
3247+ }) = &capabilities.completion_provider
3248+ {
3249+ // TODO: what if trigger is multiple chars long
3250+ if triggers.iter().any(|trigger| trigger.contains(ch)) {
3251+ cx.editor.clear_idle_timer();
3252+ super::completion(cx);
3253+ }
35683254 }
35693255 }
35703256
@@ -3572,12 +3258,12 @@ pub mod insert {
35723258 use helix_lsp::lsp;
35733259 // if ch matches signature_help char, trigger
35743260 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;
3261+ // The language_server!() macro is not used here since it will
3262+ // print an "LSP not active for current buffer" message on
3263+ // every keypress.
3264+ let language_server = match doc.language_server() {
3265+ Some(language_server) => language_server,
3266+ None => return,
35813267 };
35823268
35833269 let capabilities = language_server.capabilities();
@@ -3616,7 +3302,6 @@ pub mod insert {
36163302 }
36173303
36183304 use helix_core::auto_pairs;
3619− use helix_view::editor::SmartTabConfig;
36203305
36213306 pub fn insert_char(cx: &mut Context, c: char) {
36223307 let (view, doc) = current_ref!(cx.editor);
@@ -3642,31 +3327,6 @@ pub mod insert {
36423327 }
36433328 }
36443329
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−
36703330 pub fn insert_tab(cx: &mut Context) {
36713331 let (view, doc) = current!(cx.editor);
36723332 // TODO: round out to nearest indentation level (for example a line with 3 spaces should
@@ -3722,7 +3382,6 @@ pub mod insert {
37223382 let indent = indent::indent_for_newline(
37233383 doc.language_config(),
37243384 doc.syntax(),
3725− &doc.config.load().indent_heuristic,
37263385 &doc.indent_style,
37273386 doc.tab_width(),
37283387 text,
@@ -3963,21 +3622,34 @@ fn commit_undo_checkpoint(cx: &mut Context) {
39633622// Yank / Paste
39643623
39653624fn yank(cx: &mut Context) {
3966− yank_impl(cx.editor, cx.register.unwrap_or('"'));
3967− exit_select_mode(cx);
3968−}
3625+ let (view, doc) = current!(cx.editor);
3626+ let text = doc.text().slice(..);
39693627
3970−fn yank_to_clipboard(cx: &mut Context) {
3971− yank_impl(cx.editor, '+');
3972− exit_select_mode(cx);
3973−}
3628+ let values: Vec<String> = doc
3629+ .selection(view.id)
3630+ .fragments(text)
3631+ .map(Cow::into_owned)
3632+ .collect();
3633+
3634+ let msg = format!(
3635+ "yanked {} selection(s) to register {}",
3636+ values.len(),
3637+ cx.register.unwrap_or('"')
3638+ );
39743639
3975−fn yank_to_primary_clipboard(cx: &mut Context) {
3976− yank_impl(cx.editor, '*');
3640+ cx.editor
3641+ .registers
3642+ .write(cx.register.unwrap_or('"'), values);
3643+
3644+ cx.editor.set_status(msg);
39773645 exit_select_mode(cx);
39783646}
39793647
3980−fn yank_impl(editor: &mut Editor, register: char) {
3648+fn yank_joined_to_clipboard_impl(
3649+ editor: &mut Editor,
3650+ separator: &str,
3651+ clipboard_type: ClipboardType,
3652+) -> anyhow::Result<()> {
39813653 let (view, doc) = current!(editor);
39823654 let text = doc.text().slice(..);
39833655
@@ -3986,79 +3658,74 @@ fn yank_impl(editor: &mut Editor, register: char) {
39863658 .fragments(text)
39873659 .map(Cow::into_owned)
39883660 .collect();
3989− let selections = values.len();
39903661
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−}
3662+ let clipboard_text = match clipboard_type {
3663+ ClipboardType::Clipboard => "system clipboard",
3664+ ClipboardType::Selection => "primary clipboard",
3665+ };
39993666
4000−fn yank_joined_impl(editor: &mut Editor, separator: &str, register: char) {
4001− let (view, doc) = current!(editor);
4002− let text = doc.text().slice(..);
3667+ let msg = format!(
3668+ "joined and yanked {} selection(s) to {}",
3669+ values.len(),
3670+ clipboard_text,
3671+ );
40033672
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− });
3673+ let joined = values.join(separator);
40153674
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−}
3675+ editor
3676+ .clipboard_provider
3677+ .set_contents(joined, clipboard_type)
3678+ .context("Couldn't set system clipboard content")?;
40243679
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−}
3680+ editor.set_status(msg);
40303681
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);
3682+ Ok(())
40353683}
40363684
4037−fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3685+fn yank_joined_to_clipboard(cx: &mut Context) {
40383686 let line_ending = doc!(cx.editor).line_ending;
4039− yank_joined_impl(cx.editor, line_ending.as_str(), '*');
3687+ let _ =
3688+ yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Clipboard);
40403689 exit_select_mode(cx);
40413690}
40423691
4043−fn yank_primary_selection_impl(editor: &mut Editor, register: char) {
3692+fn yank_main_selection_to_clipboard_impl(
3693+ editor: &mut Editor,
3694+ clipboard_type: ClipboardType,
3695+) -> anyhow::Result<()> {
40443696 let (view, doc) = current!(editor);
40453697 let text = doc.text().slice(..);
40463698
4047− let selection = doc.selection(view.id).primary().fragment(text).to_string();
3699+ let message_text = match clipboard_type {
3700+ ClipboardType::Clipboard => "yanked main selection to system clipboard",
3701+ ClipboardType::Selection => "yanked main selection to primary clipboard",
3702+ };
40483703
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()),
3704+ let value = doc.selection(view.id).primary().fragment(text);
3705+
3706+ if let Err(e) = editor
3707+ .clipboard_provider
3708+ .set_contents(value.into_owned(), clipboard_type)
3709+ {
3710+ bail!("Couldn't set system clipboard content: {}", e);
40523711 }
3712+
3713+ editor.set_status(message_text);
3714+ Ok(())
40533715}
40543716
40553717fn yank_main_selection_to_clipboard(cx: &mut Context) {
4056− yank_primary_selection_impl(cx.editor, '+');
4057− exit_select_mode(cx);
3718+ let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Clipboard);
3719+}
3720+
3721+fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3722+ let line_ending = doc!(cx.editor).line_ending;
3723+ let _ =
3724+ yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Selection);
40583725}
40593726
40603727fn yank_main_selection_to_primary_clipboard(cx: &mut Context) {
4061− yank_primary_selection_impl(cx.editor, '*');
3728+ let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Selection);
40623729 exit_select_mode(cx);
40633730}
40643731
@@ -4156,99 +3823,146 @@ pub(crate) fn paste_bracketed_value(cx: &mut Context, contents: String) {
41563823 };
41573824 let (view, doc) = current!(cx.editor);
41583825 paste_impl(&[contents], doc, view, paste, count, cx.editor.mode);
4159− exit_select_mode(cx);
3826+}
3827+
3828+fn paste_clipboard_impl(
3829+ editor: &mut Editor,
3830+ action: Paste,
3831+ clipboard_type: ClipboardType,
3832+ count: usize,
3833+) -> anyhow::Result<()> {
3834+ let (view, doc) = current!(editor);
3835+ match editor.clipboard_provider.get_contents(clipboard_type) {
3836+ Ok(contents) => {
3837+ paste_impl(&[contents], doc, view, action, count, editor.mode);
3838+ Ok(())
3839+ }
3840+ Err(e) => Err(e.context("Couldn't get system clipboard contents")),
3841+ }
41603842}
41613843
41623844fn paste_clipboard_after(cx: &mut Context) {
4163− paste(cx.editor, '+', Paste::After, cx.count());
4164− exit_select_mode(cx);
3845+ let _ = paste_clipboard_impl(
3846+ cx.editor,
3847+ Paste::After,
3848+ ClipboardType::Clipboard,
3849+ cx.count(),
3850+ );
41653851}
41663852
41673853fn paste_clipboard_before(cx: &mut Context) {
4168− paste(cx.editor, '+', Paste::Before, cx.count());
4169− exit_select_mode(cx);
3854+ let _ = paste_clipboard_impl(
3855+ cx.editor,
3856+ Paste::Before,
3857+ ClipboardType::Clipboard,
3858+ cx.count(),
3859+ );
41703860}
41713861
41723862fn paste_primary_clipboard_after(cx: &mut Context) {
4173− paste(cx.editor, '*', Paste::After, cx.count());
4174− exit_select_mode(cx);
3863+ let _ = paste_clipboard_impl(
3864+ cx.editor,
3865+ Paste::After,
3866+ ClipboardType::Selection,
3867+ cx.count(),
3868+ );
41753869}
41763870
41773871fn paste_primary_clipboard_before(cx: &mut Context) {
4178− paste(cx.editor, '*', Paste::Before, cx.count());
4179− exit_select_mode(cx);
3872+ let _ = paste_clipboard_impl(
3873+ cx.editor,
3874+ Paste::Before,
3875+ ClipboardType::Selection,
3876+ cx.count(),
3877+ );
41803878}
41813879
41823880fn replace_with_yanked(cx: &mut Context) {
4183− replace_with_yanked_impl(cx.editor, cx.register.unwrap_or('"'), cx.count());
4184− exit_select_mode(cx);
3881+ let count = cx.count();
3882+ let reg_name = cx.register.unwrap_or('"');
3883+ let (view, doc) = current!(cx.editor);
3884+ let registers = &mut cx.editor.registers;
3885+
3886+ if let Some(values) = registers.read(reg_name) {
3887+ if !values.is_empty() {
3888+ let repeat = std::iter::repeat(
3889+ values
3890+ .last()
3891+ .map(|value| Tendril::from(&value.repeat(count)))
3892+ .unwrap(),
3893+ );
3894+ let mut values = values
3895+ .iter()
3896+ .map(|value| Tendril::from(&value.repeat(count)))
3897+ .chain(repeat);
3898+ let selection = doc.selection(view.id);
3899+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3900+ if !range.is_empty() {
3901+ (range.from(), range.to(), Some(values.next().unwrap()))
3902+ } else {
3903+ (range.from(), range.to(), None)
3904+ }
3905+ });
3906+
3907+ doc.apply(&transaction, view.id);
3908+ exit_select_mode(cx);
3909+ }
3910+ }
41853911}
41863912
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();
3913+fn replace_selections_with_clipboard_impl(
3914+ cx: &mut Context,
3915+ clipboard_type: ClipboardType,
3916+) -> anyhow::Result<()> {
3917+ let count = cx.count();
3918+ let (view, doc) = current!(cx.editor);
41923919
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)
3920+ match cx.editor.clipboard_provider.get_contents(clipboard_type) {
3921+ Ok(contents) => {
3922+ let selection = doc.selection(view.id);
3923+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3924+ (
3925+ range.from(),
3926+ range.to(),
3927+ Some(contents.repeat(count).as_str().into()),
3928+ )
3929+ });
3930+
3931+ doc.apply(&transaction, view.id);
3932+ doc.append_changes_to_history(view);
42103933 }
4211− });
3934+ Err(e) => return Err(e.context("Couldn't get system clipboard contents")),
3935+ }
42123936
4213− doc.apply(&transaction, view.id);
3937+ exit_select_mode(cx);
3938+ Ok(())
42143939}
42153940
42163941fn replace_selections_with_clipboard(cx: &mut Context) {
4217− replace_with_yanked_impl(cx.editor, '+', cx.count());
4218− exit_select_mode(cx);
3942+ let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Clipboard);
42193943}
42203944
42213945fn replace_selections_with_primary_clipboard(cx: &mut Context) {
4222− replace_with_yanked_impl(cx.editor, '*', cx.count());
4223− exit_select_mode(cx);
3946+ let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Selection);
42243947}
42253948
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();
3949+fn paste(cx: &mut Context, pos: Paste) {
3950+ let count = cx.count();
3951+ let reg_name = cx.register.unwrap_or('"');
3952+ let (view, doc) = current!(cx.editor);
3953+ let registers = &mut cx.editor.registers;
42293954
4230− let (view, doc) = current!(editor);
4231− paste_impl(&values, doc, view, pos, count, editor.mode);
3955+ if let Some(values) = registers.read(reg_name) {
3956+ paste_impl(values, doc, view, pos, count, cx.editor.mode);
3957+ }
42323958}
42333959
42343960fn 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);
3961+ paste(cx, Paste::After)
42423962}
42433963
42443964fn 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);
3965+ paste(cx, Paste::Before)
42523966}
42533967
42543968fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
@@ -4287,7 +4001,6 @@ fn indent(cx: &mut Context) {
42874001 }),
42884002 );
42894003 doc.apply(&transaction, view.id);
4290− exit_select_mode(cx);
42914004}
42924005
42934006fn unindent(cx: &mut Context) {
@@ -4327,76 +4040,71 @@ fn unindent(cx: &mut Context) {
43274040 let transaction = Transaction::change(doc.text(), changes.into_iter());
43284041
43294042 doc.apply(&transaction, view.id);
4330− exit_select_mode(cx);
43314043}
43324044
43334045fn format_selections(cx: &mut Context) {
43344046 use helix_lsp::{lsp, util::range_to_lsp_range};
43354047
43364048 let (view, doc) = current!(cx.editor);
4337− let view_id = view.id;
43384049
43394050 // via lsp if available
43404051 // TODO: else via tree-sitter indentation calculations
43414052
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;
4053+ let language_server = match doc.language_server() {
4054+ Some(language_server) => language_server,
4055+ None => return,
43624056 };
43634057
4364− let offset_encoding = language_server.offset_encoding();
43654058 let ranges: Vec<lsp::Range> = doc
4366− .selection(view_id)
4059+ .selection(view.id)
43674060 .iter()
4368− .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
4061+ .map(|range| range_to_lsp_range(doc.text(), *range, language_server.offset_encoding()))
43694062 .collect();
43704063
4064+ if ranges.len() != 1 {
4065+ cx.editor
4066+ .set_error("format_selections only supports a single selection for now");
4067+ return;
4068+ }
4069+
43714070 // TODO: handle fails
43724071 // TODO: concurrent map over all ranges
43734072
43744073 let range = ranges[0];
43754074
4376− let future = language_server
4377− .text_document_range_formatting(
4378− doc.identifier(),
4379− range,
4380− lsp::FormattingOptions::default(),
4381− None,
4382− )
4383− .unwrap();
4075+ let request = match language_server.text_document_range_formatting(
4076+ doc.identifier(),
4077+ range,
4078+ lsp::FormattingOptions::default(),
4079+ None,
4080+ ) {
4081+ Some(future) => future,
4082+ None => {
4083+ cx.editor
4084+ .set_error("Language server does not support range formatting");
4085+ return;
4086+ }
4087+ };
43844088
4385− let edits = tokio::task::block_in_place(|| helix_lsp::block_on(future)).unwrap_or_default();
4089+ let edits = tokio::task::block_in_place(|| helix_lsp::block_on(request)).unwrap_or_default();
43864090
4387− let transaction =
4388− helix_lsp::util::generate_transaction_from_edits(doc.text(), edits, offset_encoding);
4091+ let transaction = helix_lsp::util::generate_transaction_from_edits(
4092+ doc.text(),
4093+ edits,
4094+ language_server.offset_encoding(),
4095+ );
43894096
4390− doc.apply(&transaction, view_id);
4097+ doc.apply(&transaction, view.id);
43914098}
43924099
43934100fn join_selections_impl(cx: &mut Context, select_space: bool) {
43944101 use movement::skip_while;
43954102 let (view, doc) = current!(cx.editor);
43964103 let text = doc.text();
4397− let slice = text.slice(..);
4104+ let slice = doc.text().slice(..);
43984105
43994106 let mut changes = Vec::new();
4107+ let fragment = Tendril::from(" ");
44004108
44014109 for selection in doc.selection(view.id) {
44024110 let (start, mut end) = selection.line_range(slice);
@@ -4412,13 +4120,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44124120 let mut end = text.line_to_char(line + 1);
44134121 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
44144122
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));
4123+ // need to skip from start, not end
4124+ let change = (start, end, Some(fragment.clone()));
4125+ changes.push(change);
44224126 }
44234127 }
44244128
@@ -4430,6 +4134,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44304134 changes.sort_unstable_by_key(|(from, _to, _text)| *from);
44314135 changes.dedup();
44324136
4137+ // TODO: joining multiple empty lines should be replaced by a single space.
4138+ // need to merge change ranges that touch
4139+
44334140 // select inserted spaces
44344141 let transaction = if select_space {
44354142 let ranges: SmallVec<_> = changes
@@ -4441,9 +4148,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
44414148 })
44424149 .collect();
44434150 let selection = Selection::new(ranges, 0);
4444− Transaction::change(text, changes.into_iter()).with_selection(selection)
4151+ Transaction::change(doc.text(), changes.into_iter()).with_selection(selection)
44454152 } else {
4446− Transaction::change(text, changes.into_iter())
4153+ Transaction::change(doc.text(), changes.into_iter())
44474154 };
44484155
44494156 doc.apply(&transaction, view.id);
@@ -4457,8 +4164,8 @@ fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) {
44574164 if remove { "remove:" } else { "keep:" }.into(),
44584165 Some(reg),
44594166 ui::completers::none,
4460− move |cx, regex, event| {
4461− let (view, doc) = current!(cx.editor);
4167+ move |editor, regex, event| {
4168+ let (view, doc) = current!(editor);
44624169 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
44634170 return;
44644171 }
@@ -4524,46 +4231,21 @@ pub fn completion(cx: &mut Context) {
45244231 doc.savepoint(view)
45254232 };
45264233
4234+ let language_server = match doc.language_server() {
4235+ Some(language_server) => language_server,
4236+ None => return,
4237+ };
4238+
4239+ let offset_encoding = language_server.offset_encoding();
45274240 let text = savepoint.text.clone();
45284241 let cursor = savepoint.cursor();
45294242
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();
4243+ let pos = pos_to_lsp_pos(&text, cursor, offset_encoding);
45624244
4563− anyhow::Ok(items)
4564− }
4565− })
4566− .collect();
4245+ let future = match language_server.completion(doc.identifier(), pos, None) {
4246+ Some(future) => future,
4247+ None => return,
4248+ };
45674249
45684250 // setup a channel that allows the request to be canceled
45694251 let (tx, rx) = oneshot::channel();
@@ -4572,20 +4254,12 @@ pub fn completion(cx: &mut Context) {
45724254 // and the associated request is automatically dropped
45734255 cx.editor.completion_request_handle = Some(tx);
45744256 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− };
45834257 tokio::select! {
45844258 biased;
45854259 _ = rx => {
4586− Ok(Vec::new())
4260+ Ok(serde_json::Value::Null)
45874261 }
4588− res = items_future => {
4262+ res = future => {
45894263 res
45904264 }
45914265 }
@@ -4619,9 +4293,9 @@ pub fn completion(cx: &mut Context) {
46194293 },
46204294 ));
46214295
4622− cx.jobs.callback(async move {
4623− let items = future.await?;
4624− let call = move |editor: &mut Editor, compositor: &mut Compositor| {
4296+ cx.callback(
4297+ future,
4298+ move |editor, compositor, response: Option<lsp::CompletionResponse>| {
46254299 let (view, doc) = current_ref!(editor);
46264300 // check if the completion request is stale.
46274301 //
@@ -4632,6 +4306,16 @@ pub fn completion(cx: &mut Context) {
46324306 return;
46334307 }
46344308
4309+ let items = match response {
4310+ Some(lsp::CompletionResponse::Array(items)) => items,
4311+ // TODO: do something with is_incomplete
4312+ Some(lsp::CompletionResponse::List(lsp::CompletionList {
4313+ is_incomplete: _is_incomplete,
4314+ items,
4315+ })) => items,
4316+ None => Vec::new(),
4317+ };
4318+
46354319 if items.is_empty() {
46364320 // editor.set_error("No completion available");
46374321 return;
@@ -4642,6 +4326,7 @@ pub fn completion(cx: &mut Context) {
46424326 editor,
46434327 savepoint,
46444328 items,
4329+ offset_encoding,
46454330 start_offset,
46464331 trigger_offset,
46474332 size,
@@ -4655,9 +4340,8 @@ pub fn completion(cx: &mut Context) {
46554340 {
46564341 compositor.remove(SignatureHelp::ID);
46574342 }
4658− };
4659− Ok(Callback::EditorCompositor(Box::new(call)))
4660− });
4343+ },
4344+ );
46614345}
46624346
46634347// comments
@@ -4692,13 +4376,7 @@ fn rotate_selections_backward(cx: &mut Context) {
46924376 rotate_selections(cx, Direction::Backward)
46934377}
46944378
4695−enum ReorderStrategy {
4696− RotateForward,
4697− RotateBackward,
4698− Reverse,
4699−}
4700−
4701−fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
4379+fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
47024380 let count = cx.count;
47034381 let (view, doc) = current!(cx.editor);
47044382 let text = doc.text().slice(..);
@@ -4716,10 +4394,9 @@ fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
47164394
47174395 for chunk in fragments.chunks_mut(group) {
47184396 // 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(),
4397+ match direction {
4398+ Direction::Forward => chunk.rotate_right(1),
4399+ Direction::Backward => chunk.rotate_left(1),
47234400 };
47244401 }
47254402
@@ -4736,13 +4413,10 @@ fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
47364413}
47374414
47384415fn rotate_selection_contents_forward(cx: &mut Context) {
4739− reorder_selection_contents(cx, ReorderStrategy::RotateForward)
4416+ rotate_selection_contents(cx, Direction::Forward)
47404417}
47414418fn 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)
4419+ rotate_selection_contents(cx, Direction::Backward)
47464420}
47474421
47484422// tree sitter node selection
@@ -4766,7 +4440,8 @@ fn expand_selection(cx: &mut Context) {
47664440 }
47674441 }
47684442 };
4769− cx.editor.apply_motion(motion);
4443+ motion(cx.editor);
4444+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
47704445}
47714446
47724447fn shrink_selection(cx: &mut Context) {
@@ -4790,7 +4465,8 @@ fn shrink_selection(cx: &mut Context) {
47904465 doc.set_selection(view.id, selection);
47914466 }
47924467 };
4793− cx.editor.apply_motion(motion);
4468+ motion(cx.editor);
4469+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
47944470}
47954471
47964472fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: &'static F)
@@ -4808,7 +4484,8 @@ where
48084484 doc.set_selection(view.id, selection);
48094485 }
48104486 };
4811− cx.editor.apply_motion(motion);
4487+ motion(cx.editor);
4488+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
48124489}
48134490
48144491fn select_next_sibling(cx: &mut Context) {
@@ -4819,68 +4496,22 @@ fn select_prev_sibling(cx: &mut Context) {
48194496 select_sibling_impl(cx, &|node| Node::prev_sibling(&node))
48204497}
48214498
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−
48654499fn match_brackets(cx: &mut Context) {
48664500 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(..);
48704501
4871− let selection = doc.selection(view.id).clone().transform(|range| {
4872− let pos = range.cursor(text_slice);
4873− if let Some(matched_pos) = doc.syntax().map_or_else(
4874− || match_brackets::find_matching_bracket_plaintext(text.slice(..), pos),
4875− |syntax| match_brackets::find_matching_bracket_fuzzy(syntax, text.slice(..), pos),
4876− ) {
4877− range.put_cursor(text_slice, matched_pos, is_select)
4878− } else {
4879− range
4880− }
4881− });
4882−
4883− doc.set_selection(view.id, selection);
4502+ if let Some(syntax) = doc.syntax() {
4503+ let text = doc.text().slice(..);
4504+ let selection = doc.selection(view.id).clone().transform(|range| {
4505+ if let Some(pos) =
4506+ match_brackets::find_matching_bracket_fuzzy(syntax, doc.text(), range.cursor(text))
4507+ {
4508+ range.put_cursor(text, pos, cx.editor.mode == Mode::Select)
4509+ } else {
4510+ range
4511+ }
4512+ });
4513+ doc.set_selection(view.id, selection);
4514+ }
48844515}
48854516
48864517//
@@ -4975,19 +4606,17 @@ fn transpose_view(cx: &mut Context) {
49754606 cx.editor.transpose_view()
49764607}
49774608
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);
4609+// split helper, clear it later
4610+fn split(cx: &mut Context, action: Action) {
4611+ let (view, doc) = current!(cx.editor);
49834612 let id = doc.id();
49844613 let selection = doc.selection(view.id).clone();
49854614 let offset = view.offset;
49864615
4987− editor.switch(id, action);
4616+ cx.editor.switch(id, action);
49884617
49894618 // match the selection in the previous view
4990− let (view, doc) = current!(editor);
4619+ let (view, doc) = current!(cx.editor);
49914620 doc.set_selection(view.id, selection);
49924621 // match the view scroll offset (switch doesn't handle this fully
49934622 // since the selection is only matched after the split)
@@ -4995,7 +4624,7 @@ fn split(editor: &mut Editor, action: Action) {
49954624}
49964625
49974626fn hsplit(cx: &mut Context) {
4998− split(cx.editor, Action::HorizontalSplit);
4627+ split(cx, Action::HorizontalSplit);
49994628}
50004629
50014630fn hsplit_new(cx: &mut Context) {
@@ -5003,7 +4632,7 @@ fn hsplit_new(cx: &mut Context) {
50034632}
50044633
50054634fn vsplit(cx: &mut Context) {
5006− split(cx.editor, Action::VerticalSplit);
4635+ split(cx, Action::VerticalSplit);
50074636}
50084637
50094638fn vsplit_new(cx: &mut Context) {
@@ -5052,12 +4681,7 @@ fn insert_register(cx: &mut Context) {
50524681 if let Some(ch) = event.char() {
50534682 cx.editor.autoinfo = None;
50544683 cx.register = Some(ch);
5055− paste(
5056− cx.editor,
5057− cx.register.unwrap_or('"'),
5058− Paste::Cursor,
5059− cx.count(),
5060− );
4684+ paste(cx, Paste::Cursor);
50614685 }
50624686 })
50634687}
@@ -5141,7 +4765,8 @@ fn goto_ts_object_impl(cx: &mut Context, object: &'static str, direction: Direct
51414765 editor.set_status("Syntax-tree is not available in current buffer");
51424766 }
51434767 };
5144− cx.editor.apply_motion(motion);
4768+ motion(cx.editor);
4769+ cx.editor.last_motion = Some(Motion(Box::new(motion)));
51454770}
51464771
51474772fn goto_next_function(cx: &mut Context) {
@@ -5262,7 +4887,8 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
52624887 });
52634888 doc.set_selection(view.id, selection);
52644889 };
5265− cx.editor.apply_motion(textobject);
4890+ textobject(cx.editor);
4891+ cx.editor.last_motion = Some(Motion(Box::new(textobject)));
52664892 }
52674893 });
52684894
@@ -5352,18 +4978,11 @@ fn surround_replace(cx: &mut Context) {
53524978 }
53534979 };
53544980
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−
53624981 cx.on_next_key(move |cx, event| {
53634982 let (view, doc) = current!(cx.editor);
53644983 let to = match event.char() {
53654984 Some(to) => to,
5366− None => return doc.set_selection(view.id, selection),
4985+ None => return,
53674986 };
53684987 let (open, close) = surround::get_pair(to);
53694988 let transaction = Transaction::change(
@@ -5374,7 +4993,6 @@ fn surround_replace(cx: &mut Context) {
53744993 (pos, pos + 1, Some(t))
53754994 }),
53764995 );
5377− doc.set_selection(view.id, selection);
53784996 doc.apply(&transaction, view.id);
53794997 exit_select_mode(cx);
53804998 });
@@ -5523,7 +5141,7 @@ async fn shell_impl_async(
55235141 helix_view::document::to_writer(&mut stdin, (encoding::UTF_8, false), &input)
55245142 .await?;
55255143 }
5526− anyhow::Ok(())
5144+ Ok::<_, anyhow::Error>(())
55275145 });
55285146 let (output, _) = tokio::join! {
55295147 process.wait_with_output(),
@@ -5609,18 +5227,12 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
56095227 };
56105228
56115229 // 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");
5230+ // Once the MSRV is 1.66.0 (mixed_integer_ops is stabilized), we can use checked
5231+ // arithmetic to assert this.
5232+ let anchor = (to as isize + offset - deleted_len as isize) as usize;
56175233 let new_range = Range::new(anchor, anchor + output_len).with_direction(range.direction());
56185234 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");
5235+ offset = offset + output_len as isize - deleted_len as isize;
56245236
56255237 changes.push((from, to, Some(output)));
56265238 }
@@ -5642,7 +5254,7 @@ fn shell_prompt(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBeha
56425254 cx,
56435255 prompt,
56445256 Some('|'),
5645− ui::completers::filename,
5257+ ui::completers::none,
56465258 move |cx, input: &str, event: PromptEvent| {
56475259 if event != PromptEvent::Validate {
56485260 return;
@@ -5759,7 +5371,6 @@ fn increment_impl(cx: &mut Context, increment_direction: IncrementDirection) {
57595371 let transaction = Transaction::change(doc.text(), changes.into_iter());
57605372 let transaction = transaction.with_selection(new_selection);
57615373 doc.apply(&transaction, view.id);
5762− exit_select_mode(cx);
57635374 }
57645375}
57655376
@@ -5778,12 +5389,9 @@ fn record_macro(cx: &mut Context) {
57785389 }
57795390 })
57805391 .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− }
5392+ cx.editor.registers.write(reg, vec![s]);
5393+ cx.editor
5394+ .set_status(format!("Recorded to register [{}]", reg));
57875395 } else {
57885396 let reg = cx.register.take().unwrap_or('@');
57895397 cx.editor.macro_recording = Some((reg, Vec::new()));
@@ -5803,14 +5411,8 @@ fn replay_macro(cx: &mut Context) {
58035411 return;
58045412 }
58055413
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) {
5414+ let keys: Vec<KeyEvent> = if let Some([keys_str]) = cx.editor.registers.read(reg) {
5415+ match helix_view::input::parse_macro(keys_str) {
58145416 Ok(keys) => keys,
58155417 Err(err) => {
58165418 cx.editor.set_error(format!("Invalid macro: {}", err));