@@ -12,7 +12,7 @@ pub use typed::*;
1212use helix_core::{
1313 char_idx_at_visual_offset, comment,
1414 doc_formatter::TextFormat,
15− encoding, find_first_non_whitespace_char, find_root, graphemes,
15+ encoding, find_first_non_whitespace_char, find_workspace, graphemes,
1616 history::UndoKind,
1717 increment, indent,
1818 indent::IndentStyle,
@@ -23,17 +23,17 @@ use helix_core::{
2323 regex::{self, Regex, RegexBuilder},
2424 search::{self, CharMatcher},
2525 selection, shellwords, surround,
26+ syntax::LanguageServerFeature,
2627 text_annotations::TextAnnotations,
2728 textobject,
2829 tree_sitter::Node,
2930 unicode::width::UnicodeWidthChar,
30− visual_offset_from_block, LineEnding, Position, Range, Rope, RopeGraphemes, RopeSlice,
31− Selection, SmallVec, Tendril, Transaction,
31+ visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes,
32+ RopeReader, RopeSlice, Selection, SmallVec, Tendril, Transaction,
3233};
3334use helix_view::{
34− clipboard::ClipboardType,
3535 document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
36− editor::{Action, Motion},
36+ editor::{Action, CompleteAction},
3737 info::Info,
3838 input::KeyEvent,
3939 keyboard::KeyCode,
@@ -43,7 +43,6 @@ use helix_view::{
4343};
4444
4545use anyhow::{anyhow, bail, ensure, Context as _};
46−use fuzzy_matcher::FuzzyMatcher;
4746use insert::*;
4847use movement::Movement;
4948
@@ -54,15 +53,20 @@ use crate::{
5453 job::Callback,
5554 keymap::ReverseKeymap,
5655 ui::{
57− self, editor::InsertEvent, overlay::overlayed, FilePicker, Picker, Popup, Prompt,
58− PromptEvent,
56+ self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem, Picker,
57+ Popup, Prompt, PromptEvent,
5958 },
6059};
6160
6261use crate::job::{self, Jobs};
63−use futures_util::StreamExt;
64−use std::{collections::HashMap, fmt, future::Future};
65−use std::{collections::HashSet, num::NonZeroUsize};
62+use futures_util::{stream::FuturesUnordered, TryStreamExt};
63+use std::{
64+ collections::{HashMap, HashSet},
65+ fmt,
66+ future::Future,
67+ io::Read,
68+ num::NonZeroUsize,
69+};
6670
6771use std::{
6872 borrow::Cow,
@@ -71,11 +75,11 @@ use std::{
7175
7276use once_cell::sync::Lazy;
7377use serde::de::{self, Deserialize, Deserializer};
78+use url::Url;
7479
7580use grep_regex::RegexMatcherBuilder;
7681use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
7782use ignore::{DirEntry, WalkBuilder, WalkState};
78−use tokio_stream::wrappers::UnboundedReceiverStream;
7983
8084pub type OnKeyCallback = Box<dyn FnOnce(&mut Context, KeyEvent)>;
8185
@@ -97,6 +101,13 @@ impl<'a> Context<'a> {
97101 }));
98102 }
99103
104+ /// Call `replace_or_push` on the Compositor
105+ pub fn replace_or_push_layer<T: Component>(&mut self, id: &'static str, component: T) {
106+ self.callback = Some(Box::new(move |compositor: &mut Compositor, _| {
107+ compositor.replace_or_push(id, component);
108+ }));
109+ }
110+
100111 #[inline]
101112 pub fn on_next_key(
102113 &mut self,
@@ -239,6 +250,9 @@ impl MappableCommand {
239250 move_next_long_word_start, "Move to start of next long word",
240251 move_prev_long_word_start, "Move to start of previous long word",
241252 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",
242256 extend_next_word_start, "Extend to start of next word",
243257 extend_prev_word_start, "Extend to start of previous word",
244258 extend_next_word_end, "Extend to end of next word",
@@ -246,6 +260,9 @@ impl MappableCommand {
246260 extend_next_long_word_start, "Extend to start of next long word",
247261 extend_prev_long_word_start, "Extend to start of previous long word",
248262 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",
249266 find_till_char, "Move till next occurrence of char",
250267 find_next_char, "Move to next occurrence of char",
251268 extend_till_char, "Extend till next occurrence of char",
@@ -267,6 +284,7 @@ impl MappableCommand {
267284 select_regex, "Select all regex matches inside selections",
268285 split_selection, "Split selections on regex matches",
269286 split_selection_on_newline, "Split selection on newlines",
287+ merge_selections, "Merge selections",
270288 merge_consecutive_selections, "Merge consecutive selections",
271289 search, "Search for regex pattern",
272290 rsearch, "Reverse search for regex pattern",
@@ -319,7 +337,7 @@ impl MappableCommand {
319337 goto_implementation, "Goto implementation",
320338 goto_file_start, "Goto line number <n> else file start",
321339 goto_file_end, "Goto file end",
322− goto_file, "Goto files in selection",
340+ goto_file, "Goto files/URLs in selection",
323341 goto_file_hsplit, "Goto files in selection (hsplit)",
324342 goto_file_vsplit, "Goto files in selection (vsplit)",
325343 goto_reference, "Goto references",
@@ -347,9 +365,11 @@ impl MappableCommand {
347365 goto_first_nonwhitespace, "Goto first non-blank in line",
348366 trim_selections, "Trim whitespace from selections",
349367 extend_to_line_start, "Extend to line start",
368+ extend_to_first_nonwhitespace, "Extend to first non-blank in line",
350369 extend_to_line_end, "Extend to line end",
351370 extend_to_line_end_newline, "Extend to line end",
352371 signature_help, "Show signature help",
372+ smart_tab, "Insert tab if all cursors have all whitespace to their left; otherwise, run a separate command.",
353373 insert_tab, "Insert tab char",
354374 insert_newline, "Insert newline char",
355375 delete_char_backward, "Delete previous char",
@@ -364,6 +384,9 @@ impl MappableCommand {
364384 later, "Move forward in history",
365385 commit_undo_checkpoint, "Commit changes to new checkpoint",
366386 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",
367390 yank_joined_to_clipboard, "Join and yank selections to clipboard",
368391 yank_main_selection_to_clipboard, "Yank main selection to clipboard",
369392 yank_joined_to_primary_clipboard, "Join and yank selections to primary clipboard",
@@ -394,6 +417,7 @@ impl MappableCommand {
394417 rotate_selections_backward, "Rotate selections backward",
395418 rotate_selection_contents_forward, "Rotate selection contents forward",
396419 rotate_selection_contents_backward, "Rotate selections contents backward",
420+ reverse_selection_contents, "Reverse selections contents",
397421 expand_selection, "Expand selection to parent syntax node",
398422 shrink_selection, "Shrink selection to previously expanded syntax node",
399423 select_next_sibling, "Select next sibling in syntax tree",
@@ -501,7 +525,7 @@ impl std::str::FromStr for MappableCommand {
501525
502526 fn from_str(s: &str) -> Result<Self, Self::Err> {
503527 if let Some(suffix) = s.strip_prefix(':') {
504− let mut typable_command = suffix.split(' ').into_iter().map(|arg| arg.trim());
528+ let mut typable_command = suffix.split(' ').map(|arg| arg.trim());
505529 let name = typable_command
506530 .next()
507531 .ok_or_else(|| anyhow!("Expected typable command name"))?;
@@ -787,58 +811,72 @@ fn extend_to_line_start(cx: &mut Context) {
787811}
788812
789813fn kill_to_line_start(cx: &mut Context) {
790− let (view, doc) = current!(cx.editor);
791− let text = doc.text().slice(..);
792−
793− let selection = doc.selection(view.id).clone().transform(|range| {
794− let line = range.cursor_line(text);
795− let first_char = text.line_to_char(line);
796− let anchor = range.cursor(text);
797− let head = if anchor == first_char && line != 0 {
798− // select until previous line
799− line_end_char_index(&text, line - 1)
800− } else if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
801− if first_char + pos < anchor {
802− // select until first non-blank in line if cursor is after it
803− first_char + pos
814+ delete_by_selection_insert_mode(
815+ cx,
816+ move |text, range| {
817+ let line = range.cursor_line(text);
818+ let first_char = text.line_to_char(line);
819+ let anchor = range.cursor(text);
820+ let head = if anchor == first_char && line != 0 {
821+ // select until previous line
822+ line_end_char_index(&text, line - 1)
823+ } else if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
824+ if first_char + pos < anchor {
825+ // select until first non-blank in line if cursor is after it
826+ first_char + pos
827+ } else {
828+ // select until start of line
829+ first_char
830+ }
804831 } else {
805832 // select until start of line
806833 first_char
807− }
808− } else {
809− // select until start of line
810− first_char
811− };
812− Range::new(head, anchor)
813− });
814− delete_selection_insert_mode(doc, view, &selection);
815−
816− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
834+ };
835+ (head, anchor)
836+ },
837+ Direction::Backward,
838+ );
817839}
818840
819841fn kill_to_line_end(cx: &mut Context) {
820− let (view, doc) = current!(cx.editor);
821− let text = doc.text().slice(..);
842+ delete_by_selection_insert_mode(
843+ cx,
844+ |text, range| {
845+ let line = range.cursor_line(text);
846+ let line_end_pos = line_end_char_index(&text, line);
847+ let pos = range.cursor(text);
822848
823− let selection = doc.selection(view.id).clone().transform(|range| {
824− let line = range.cursor_line(text);
825− let line_end_pos = line_end_char_index(&text, line);
826− let pos = range.cursor(text);
849+ // if the cursor is on the newline char delete that
850+ if pos == line_end_pos {
851+ (pos, text.line_to_char(line + 1))
852+ } else {
853+ (pos, line_end_pos)
854+ }
855+ },
856+ Direction::Forward,
857+ );
858+}
827859
828− let mut new_range = range.put_cursor(text, line_end_pos, true);
829− // don't want to remove the line separator itself if the cursor doesn't reach the end of line.
830− if pos != line_end_pos {
831− new_range.head = line_end_pos;
832− }
833− new_range
834− });
835− delete_selection_insert_mode(doc, view, &selection);
860+fn goto_first_nonwhitespace(cx: &mut Context) {
861+ let (view, doc) = current!(cx.editor);
836862
837− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
863+ goto_first_nonwhitespace_impl(
864+ view,
865+ doc,
866+ if cx.editor.mode == Mode::Select {
867+ Movement::Extend
868+ } else {
869+ Movement::Move
870+ },
871+ )
838872}
839873
840−fn goto_first_nonwhitespace(cx: &mut Context) {
874+fn extend_to_first_nonwhitespace(cx: &mut Context) {
841875 let (view, doc) = current!(cx.editor);
876+ goto_first_nonwhitespace_impl(view, doc, Movement::Extend)
877+}
878+
879+fn goto_first_nonwhitespace_impl(view: &mut View, doc: &mut Document, movement: Movement) {
842880 let text = doc.text().slice(..);
843881
844882 let selection = doc.selection(view.id).clone().transform(|range| {
@@ -846,7 +884,7 @@ fn goto_first_nonwhitespace(cx: &mut Context) {
846884
847885 if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
848886 let pos = pos + text.line_to_char(line);
849− range.put_cursor(text, pos, cx.editor.mode == Mode::Select)
887+ range.put_cursor(text, pos, movement == Movement::Extend)
850888 } else {
851889 range
852890 }
@@ -952,6 +990,7 @@ fn align_selections(cx: &mut Context) {
952990
953991 let transaction = Transaction::change(doc.text(), changes.into_iter());
954992 doc.apply(&transaction, view.id);
993+ exit_select_mode(cx);
955994}
956995
957996fn goto_window(cx: &mut Context, align: Align) {
@@ -1043,6 +1082,10 @@ fn move_prev_long_word_start(cx: &mut Context) {
10431082 move_word_impl(cx, movement::move_prev_long_word_start)
10441083}
10451084
1085+fn move_prev_long_word_end(cx: &mut Context) {
1086+ move_word_impl(cx, movement::move_prev_long_word_end)
1087+}
1088+
10461089fn move_next_long_word_end(cx: &mut Context) {
10471090 move_word_impl(cx, movement::move_next_long_word_end)
10481091}
@@ -1067,8 +1110,7 @@ where
10671110 .transform(|range| move_fn(text, range, count, behavior));
10681111 doc.set_selection(view.id, selection);
10691112 };
1070− motion(cx.editor);
1071− cx.editor.last_motion = Some(Motion(Box::new(motion)));
1113+ cx.editor.apply_motion(motion)
10721114}
10731115
10741116fn goto_prev_paragraph(cx: &mut Context) {
@@ -1123,6 +1165,10 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11231165 let (view, doc) = current_ref!(cx.editor);
11241166 let text = doc.text();
11251167 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();
11261172 let mut paths: Vec<_> = selections
11271173 .iter()
11281174 .map(|r| text.slice(r.from()..r.to()).to_string())
@@ -1150,16 +1196,80 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
11501196 .to_string(),
11511197 );
11521198 }
1199+
11531200 for sel in paths {
11541201 let p = sel.trim();
1155− if !p.is_empty() {
1156− if let Err(e) = cx.editor.open(&PathBuf::from(p), action) {
1202+ if p.is_empty() {
1203+ continue;
1204+ }
1205+
1206+ if let Ok(url) = Url::parse(p) {
1207+ return open_url(cx, url, action);
1208+ }
1209+
1210+ let path = &rel_path.join(p);
1211+ if path.is_dir() {
1212+ let picker = ui::file_picker(path.into(), &cx.editor.config());
1213+ cx.push_layer(Box::new(overlaid(picker)));
1214+ } else if let Err(e) = cx.editor.open(path, action) {
1215+ cx.editor.set_error(format!("Open file failed: {:?}", e));
1216+ }
1217+ }
1218+}
1219+
1220+/// Opens the given url. If the URL points to a valid textual file it is open in helix.
1221+// Otherwise, the file is open using external program.
1222+fn open_url(cx: &mut Context, url: Url, action: Action) {
1223+ let doc = doc!(cx.editor);
1224+ let rel_path = doc
1225+ .relative_path()
1226+ .map(|path| path.parent().unwrap().to_path_buf())
1227+ .unwrap_or_default();
1228+
1229+ if url.scheme() != "file" {
1230+ return open_external_url(cx, url);
1231+ }
1232+
1233+ let content_type = std::fs::File::open(url.path()).and_then(|file| {
1234+ // Read up to 1kb to detect the content type
1235+ let mut read_buffer = Vec::new();
1236+ let n = file.take(1024).read_to_end(&mut read_buffer)?;
1237+ Ok(content_inspector::inspect(&read_buffer[..n]))
1238+ });
1239+
1240+ // we attempt to open binary files - files that can't be open in helix - using external
1241+ // program as well, e.g. pdf files or images
1242+ match content_type {
1243+ Ok(content_inspector::ContentType::BINARY) => open_external_url(cx, url),
1244+ Ok(_) | Err(_) => {
1245+ let path = &rel_path.join(url.path());
1246+ if path.is_dir() {
1247+ let picker = ui::file_picker(path.into(), &cx.editor.config());
1248+ cx.push_layer(Box::new(overlaid(picker)));
1249+ } else if let Err(e) = cx.editor.open(path, action) {
11571250 cx.editor.set_error(format!("Open file failed: {:?}", e));
11581251 }
11591252 }
11601253 }
11611254}
11621255
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+
11631273fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
11641274where
11651275 F: Fn(RopeSlice, Range, usize) -> Range,
@@ -1200,14 +1310,74 @@ fn extend_prev_long_word_start(cx: &mut Context) {
12001310 extend_word_impl(cx, movement::move_prev_long_word_start)
12011311}
12021312
1313+fn extend_prev_long_word_end(cx: &mut Context) {
1314+ extend_word_impl(cx, movement::move_prev_long_word_end)
1315+}
1316+
12031317fn extend_next_long_word_end(cx: &mut Context) {
12041318 extend_word_impl(cx, movement::move_next_long_word_end)
12051319}
12061320
1207−fn will_find_char<F>(cx: &mut Context, search_fn: F, inclusive: bool, extend: bool)
1208−where
1209− F: Fn(RopeSlice, char, usize, usize, bool) -> Option<usize> + 'static,
1210−{
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) {
12111381 // TODO: count is reset to 1 before next key so we move it into the closure here.
12121382 // Would be nice to carry over.
12131383 let count = cx.count();
@@ -1220,13 +1390,9 @@ where
12201390 KeyEvent {
12211391 code: KeyCode::Enter,
12221392 ..
1223− } =>
1224− // TODO: this isn't quite correct when CRLF is involved.
1225− // This hack will work in most cases, since documents don't
1226− // usually mix line endings. But we should fix it eventually
1227− // anyway.
1228− {
1229− doc!(cx.editor).line_ending.as_str().chars().next().unwrap()
1393+ } => {
1394+ find_char_line_ending(cx, count, direction, inclusive, extend);
1395+ return;
12301396 }
12311397
12321398 KeyEvent {
@@ -1239,11 +1405,18 @@ where
12391405 } => ch,
12401406 _ => return,
12411407 };
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+ };
12421418
1243− find_char_impl(cx.editor, &search_fn, inclusive, extend, ch, count);
1244− cx.editor.last_motion = Some(Motion(Box::new(move |editor: &mut Editor| {
1245− find_char_impl(editor, &search_fn, inclusive, true, ch, 1);
1246− })));
1419+ cx.editor.apply_motion(motion);
12471420 })
12481421}
12491422
@@ -1322,46 +1495,39 @@ fn find_prev_char_impl(
13221495}
13231496
13241497fn find_till_char(cx: &mut Context) {
1325− will_find_char(cx, find_next_char_impl, false, false)
1498+ find_char(cx, Direction::Forward, false, false);
13261499}
13271500
13281501fn find_next_char(cx: &mut Context) {
1329− will_find_char(cx, find_next_char_impl, true, false)
1502+ find_char(cx, Direction::Forward, true, false)
13301503}
13311504
13321505fn extend_till_char(cx: &mut Context) {
1333− will_find_char(cx, find_next_char_impl, false, true)
1506+ find_char(cx, Direction::Forward, false, true)
13341507}
13351508
13361509fn extend_next_char(cx: &mut Context) {
1337− will_find_char(cx, find_next_char_impl, true, true)
1510+ find_char(cx, Direction::Forward, true, true)
13381511}
13391512
13401513fn till_prev_char(cx: &mut Context) {
1341− will_find_char(cx, find_prev_char_impl, false, false)
1514+ find_char(cx, Direction::Backward, false, false)
13421515}
13431516
13441517fn find_prev_char(cx: &mut Context) {
1345− will_find_char(cx, find_prev_char_impl, true, false)
1518+ find_char(cx, Direction::Backward, true, false)
13461519}
13471520
13481521fn extend_till_prev_char(cx: &mut Context) {
1349− will_find_char(cx, find_prev_char_impl, false, true)
1522+ find_char(cx, Direction::Backward, false, true)
13501523}
13511524
13521525fn extend_prev_char(cx: &mut Context) {
1353− will_find_char(cx, find_prev_char_impl, true, true)
1526+ find_char(cx, Direction::Backward, true, true)
13541527}
13551528
13561529fn repeat_last_motion(cx: &mut Context) {
1357− let count = cx.count();
1358− let last_motion = cx.editor.last_motion.take();
1359− if let Some(m) = &last_motion {
1360− for _ in 0..count {
1361− m.run(cx.editor);
1362− }
1363− cx.editor.last_motion = last_motion;
1364− }
1530+ cx.editor.repeat_last_motion(cx.count())
13651531}
13661532
13671533fn replace(cx: &mut Context) {
@@ -1428,6 +1594,7 @@ where
14281594 });
14291595
14301596 doc.apply(&transaction, view.id);
1597+ exit_select_mode(cx);
14311598}
14321599
14331600fn switch_case(cx: &mut Context) {
@@ -1470,7 +1637,7 @@ pub fn scroll(cx: &mut Context, offset: usize, direction: Direction) {
14701637 let cursor = range.cursor(text);
14711638 let height = view.inner_height();
14721639
1473− let scrolloff = config.scrolloff.min(height.saturating_sub(1) as usize / 2);
1640+ let scrolloff = config.scrolloff.min(height.saturating_sub(1) / 2);
14741641 let offset = match direction {
14751642 Forward => offset as isize,
14761643 Backward => -(offset as isize),
@@ -1561,7 +1728,7 @@ fn half_page_down(cx: &mut Context) {
15611728}
15621729
15631730#[allow(deprecated)]
1564−// currently uses the deprected `visual_coords_at_pos`/`pos_at_visual_coords` functions
1731+// currently uses the deprecated `visual_coords_at_pos`/`pos_at_visual_coords` functions
15651732// as this function ignores softwrapping (and virtual text) and instead only cares
15661733// about "text visual position"
15671734//
@@ -1669,8 +1836,8 @@ fn select_regex(cx: &mut Context) {
16691836 "select:".into(),
16701837 Some(reg),
16711838 ui::completers::none,
1672− move |editor, regex, event| {
1673− let (view, doc) = current!(editor);
1839+ move |cx, regex, event| {
1840+ let (view, doc) = current!(cx.editor);
16741841 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
16751842 return;
16761843 }
@@ -1691,8 +1858,8 @@ fn split_selection(cx: &mut Context) {
16911858 "split:".into(),
16921859 Some(reg),
16931860 ui::completers::none,
1694− move |editor, regex, event| {
1695− let (view, doc) = current!(editor);
1861+ move |cx, regex, event| {
1862+ let (view, doc) = current!(cx.editor);
16961863 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
16971864 return;
16981865 }
@@ -1714,6 +1881,12 @@ fn split_selection_on_newline(cx: &mut Context) {
17141881 doc.set_selection(view.id, selection);
17151882}
17161883
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+
17171890fn merge_consecutive_selections(cx: &mut Context) {
17181891 let (view, doc) = current!(cx.editor);
17191892 let selection = doc.selection(view.id).clone().merge_consecutive_ranges();
@@ -1809,11 +1982,11 @@ fn search_impl(
18091982
18101983fn search_completions(cx: &mut Context, reg: Option<char>) -> Vec<String> {
18111984 let mut items = reg
1812− .and_then(|reg| cx.editor.registers.get(reg))
1813− .map_or(Vec::new(), |reg| reg.read().iter().take(200).collect());
1985+ .and_then(|reg| cx.editor.registers.read(reg, cx.editor))
1986+ .map_or(Vec::new(), |reg| reg.take(200).collect());
18141987 items.sort_unstable();
18151988 items.dedup();
1816− items.into_iter().cloned().collect()
1989+ items.into_iter().map(|value| value.to_string()).collect()
18171990}
18181991
18191992fn search(cx: &mut Context) {
@@ -1850,12 +2023,14 @@ fn searcher(cx: &mut Context, direction: Direction) {
18502023 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
18512024 .collect()
18522025 },
1853− move |editor, regex, event| {
1854− if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
2026+ move |cx, regex, event| {
2027+ if event == PromptEvent::Validate {
2028+ cx.editor.registers.last_search_register = reg;
2029+ } else if event != PromptEvent::Update {
18552030 return;
18562031 }
18572032 search_impl(
1858− editor,
2033+ cx.editor,
18592034 &contents,
18602035 ®ex,
18612036 Movement::Move,
@@ -1870,11 +2045,13 @@ fn searcher(cx: &mut Context, direction: Direction) {
18702045
18712046fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Direction) {
18722047 let count = cx.count();
2048+ let register = cx
2049+ .register
2050+ .unwrap_or(cx.editor.registers.last_search_register);
18732051 let config = cx.editor.config();
18742052 let scrolloff = config.scrolloff;
1875− let (_, doc) = current!(cx.editor);
1876− let registers = &cx.editor.registers;
1877− if let Some(query) = registers.read('/').and_then(|query| query.last()) {
2053+ if let Some(query) = cx.editor.registers.first(register, cx.editor) {
2054+ let doc = doc!(cx.editor);
18782055 let contents = doc.text().slice(..).to_string();
18792056 let search_config = &config.search;
18802057 let case_insensitive = if search_config.smart_case {
@@ -1883,7 +2060,7 @@ fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Dir
18832060 false
18842061 };
18852062 let wrap_around = search_config.wrap_around;
1886− if let Ok(regex) = RegexBuilder::new(query)
2063+ if let Ok(regex) = RegexBuilder::new(&query)
18872064 .case_insensitive(case_insensitive)
18882065 .multi_line(true)
18892066 .build()
@@ -1923,6 +2100,7 @@ fn extend_search_prev(cx: &mut Context) {
19232100}
19242101
19252102fn search_selection(cx: &mut Context) {
2103+ let register = cx.register.unwrap_or('/');
19262104 let (view, doc) = current!(cx.editor);
19272105 let contents = doc.text().slice(..);
19282106
@@ -1935,13 +2113,24 @@ fn search_selection(cx: &mut Context) {
19352113 .collect::<Vec<_>>()
19362114 .join("|");
19372115
1938− let msg = format!("register '{}' set to '{}'", '/', ®ex);
1939− cx.editor.registers.push('/', regex);
1940− cx.editor.set_status(msg);
2116+ let msg = format!("register '{}' set to '{}'", register, ®ex);
2117+ match cx.editor.registers.push(register, regex) {
2118+ Ok(_) => {
2119+ cx.editor.registers.last_search_register = register;
2120+ cx.editor.set_status(msg)
2121+ }
2122+ Err(err) => cx.editor.set_error(err.to_string()),
2123+ }
19412124}
19422125
19432126fn make_search_word_bounded(cx: &mut Context) {
1944− let regex = match cx.editor.registers.last('/') {
2127+ // Defaults to the active search register instead `/` to be more ergonomic assuming most people
2128+ // would use this command following `search_selection`. This avoids selecting the register
2129+ // twice.
2130+ let register = cx
2131+ .register
2132+ .unwrap_or(cx.editor.registers.last_search_register);
2133+ let regex = match cx.editor.registers.first(register, cx.editor) {
19452134 Some(regex) => regex,
19462135 None => return,
19472136 };
@@ -1959,14 +2148,19 @@ fn make_search_word_bounded(cx: &mut Context) {
19592148 if !start_anchored {
19602149 new_regex.push_str("\\b");
19612150 }
1962− new_regex.push_str(regex);
2151+ new_regex.push_str(®ex);
19632152 if !end_anchored {
19642153 new_regex.push_str("\\b");
19652154 }
19662155
1967− let msg = format!("register '{}' set to '{}'", '/', &new_regex);
1968− cx.editor.registers.push('/', new_regex);
1969− cx.editor.set_status(msg);
2156+ let msg = format!("register '{}' set to '{}'", register, &new_regex);
2157+ match cx.editor.registers.push(register, new_regex) {
2158+ Ok(_) => {
2159+ cx.editor.registers.last_search_register = register;
2160+ cx.editor.set_status(msg)
2161+ }
2162+ Err(err) => cx.editor.set_error(err.to_string()),
2163+ }
19702164}
19712165
19722166fn global_search(cx: &mut Context) {
@@ -2005,13 +2199,11 @@ fn global_search(cx: &mut Context) {
20052199 }
20062200 }
20072201
2008− let (all_matches_sx, all_matches_rx) = tokio::sync::mpsc::unbounded_channel::<FileResult>();
20092202 let config = cx.editor.config();
20102203 let smart_case = config.search.smart_case;
20112204 let file_picker_config = config.file_picker.clone();
20122205
20132206 let reg = cx.register.unwrap_or('/');
2014−
20152207 let completions = search_completions(cx, Some(reg));
20162208 ui::regex_prompt(
20172209 cx,
@@ -2024,43 +2216,67 @@ fn global_search(cx: &mut Context) {
20242216 .map(|comp| (0.., std::borrow::Cow::Owned(comp.clone())))
20252217 .collect()
20262218 },
2027− move |_editor, regex, event| {
2219+ move |cx, regex, event| {
20282220 if event != PromptEvent::Validate {
20292221 return;
20302222 }
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();
20312231
20322232 if let Ok(matcher) = RegexMatcherBuilder::new()
20332233 .case_smart(smart_case)
20342234 .build(regex.as_str())
20352235 {
2036− let searcher = SearcherBuilder::new()
2037− .binary_detection(BinaryDetection::quit(b'\x00'))
2038− .build();
2236+ let search_root = helix_loader::current_working_dir();
2237+ if !search_root.exists() {
2238+ cx.editor
2239+ .set_error("Current working directory does not exist");
2240+ return;
2241+ }
2242+
2243+ let (picker, injector) = Picker::stream(current_path);
20392244
2040− let search_root = std::env::current_dir()
2041− .expect("Global search error: Failed to get current dir");
20422245 let dedup_symlinks = file_picker_config.deduplicate_links;
20432246 let absolute_root = search_root
20442247 .canonicalize()
20452248 .unwrap_or_else(|_| search_root.clone());
2046−
2047− WalkBuilder::new(search_root)
2048− .hidden(file_picker_config.hidden)
2049− .parents(file_picker_config.parents)
2050− .ignore(file_picker_config.ignore)
2051− .follow_links(file_picker_config.follow_symlinks)
2052− .git_ignore(file_picker_config.git_ignore)
2053− .git_global(file_picker_config.git_global)
2054− .git_exclude(file_picker_config.git_exclude)
2055− .max_depth(file_picker_config.max_depth)
2056− .filter_entry(move |entry| {
2057− filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2058− })
2059− .build_parallel()
2060− .run(|| {
2249+ let injector_ = injector.clone();
2250+
2251+ std::thread::spawn(move || {
2252+ let searcher = SearcherBuilder::new()
2253+ .binary_detection(BinaryDetection::quit(b'\x00'))
2254+ .build();
2255+
2256+ let mut walk_builder = WalkBuilder::new(search_root);
2257+
2258+ walk_builder
2259+ .hidden(file_picker_config.hidden)
2260+ .parents(file_picker_config.parents)
2261+ .ignore(file_picker_config.ignore)
2262+ .follow_links(file_picker_config.follow_symlinks)
2263+ .git_ignore(file_picker_config.git_ignore)
2264+ .git_global(file_picker_config.git_global)
2265+ .git_exclude(file_picker_config.git_exclude)
2266+ .max_depth(file_picker_config.max_depth)
2267+ .filter_entry(move |entry| {
2268+ filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2269+ });
2270+
2271+ walk_builder
2272+ .add_custom_ignore_filename(helix_loader::config_dir().join("ignore"));
2273+ walk_builder.add_custom_ignore_filename(".helix/ignore");
2274+
2275+ walk_builder.build_parallel().run(|| {
20612276 let mut searcher = searcher.clone();
20622277 let matcher = matcher.clone();
2063− let all_matches_sx = all_matches_sx.clone();
2278+ let injector = injector_.clone();
2279+ let documents = &documents;
20642280 Box::new(move |entry: Result<DirEntry, ignore::Error>| -> WalkState {
20652281 let entry = match entry {
20662282 Ok(entry) => entry,
@@ -2073,17 +2289,39 @@ fn global_search(cx: &mut Context) {
20732289 _ => return WalkState::Continue,
20742290 };
20752291
2076− let result = searcher.search_path(
2077− &matcher,
2078− entry.path(),
2079− sinks::UTF8(|line_num, _| {
2080− all_matches_sx
2081− .send(FileResult::new(entry.path(), line_num as usize - 1))
2082− .unwrap();
2083−
2084− Ok(true)
2085− }),
2086− );
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+ };
20872325
20882326 if let Err(err) = result {
20892327 log::error!(
@@ -2092,67 +2330,66 @@ fn global_search(cx: &mut Context) {
20922330 err
20932331 );
20942332 }
2095− WalkState::Continue
2333+ if stop {
2334+ WalkState::Quit
2335+ } else {
2336+ WalkState::Continue
2337+ }
20962338 })
20972339 });
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+ })
20982387 } else {
20992388 // Otherwise do nothing
21002389 // log::warn!("Global Search Invalid Pattern")
21012390 }
21022391 },
21032392 );
2104−
2105− let current_path = doc_mut!(cx.editor).path().cloned();
2106−
2107− let show_picker = async move {
2108− let all_matches: Vec<FileResult> =
2109− UnboundedReceiverStream::new(all_matches_rx).collect().await;
2110− let call: job::Callback = Callback::EditorCompositor(Box::new(
2111− move |editor: &mut Editor, compositor: &mut Compositor| {
2112− if all_matches.is_empty() {
2113− editor.set_status("No matches found");
2114− return;
2115− }
2116−
2117− let picker = FilePicker::new(
2118− all_matches,
2119− current_path,
2120− move |cx, FileResult { path, line_num }, action| {
2121− match cx.editor.open(path, action) {
2122− Ok(_) => {}
2123− Err(e) => {
2124− cx.editor.set_error(format!(
2125− "Failed to open file '{}': {}",
2126− path.display(),
2127− e
2128− ));
2129− return;
2130− }
2131− }
2132−
2133− let line_num = *line_num;
2134− let (view, doc) = current!(cx.editor);
2135− let text = doc.text();
2136− if line_num >= text.len_lines() {
2137− cx.editor.set_error("The line you jumped to does not exist anymore because the file has changed.");
2138− return;
2139− }
2140− let start = text.line_to_char(line_num);
2141− let end = text.line_to_char((line_num + 1).min(text.len_lines()));
2142−
2143− doc.set_selection(view.id, Selection::single(start, end));
2144− align_view(doc, view, Align::Center);
2145− },
2146− |_editor, FileResult { path, line_num }| {
2147− Some((path.clone().into(), Some((*line_num, *line_num))))
2148− },
2149− );
2150− compositor.push(Box::new(overlayed(picker)));
2151− },
2152− ));
2153− Ok(call)
2154− };
2155− cx.jobs.callback(show_picker);
21562393}
21572394
21582395enum Extend {
@@ -2275,23 +2512,40 @@ enum Operation {
22752512 Change,
22762513}
22772514
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+
22782529fn delete_selection_impl(cx: &mut Context, op: Operation) {
22792530 let (view, doc) = current!(cx.editor);
22802531
22812532 let selection = doc.selection(view.id);
2533+ let only_whole_lines = selection_is_linewise(selection, doc.text());
22822534
22832535 if cx.register != Some('_') {
22842536 // first yank the selection
22852537 let text = doc.text().slice(..);
22862538 let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect();
22872539 let reg_name = cx.register.unwrap_or('"');
2288− cx.editor.registers.write(reg_name, values);
2540+ if let Err(err) = cx.editor.registers.write(reg_name, values) {
2541+ cx.editor.set_error(err.to_string());
2542+ return;
2543+ }
22892544 };
22902545
22912546 // then delete
2292− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
2293− (range.from(), range.to(), None)
2294− });
2547+ let transaction =
2548+ Transaction::delete_by_selection(doc.text(), selection, |range| (range.from(), range.to()));
22952549 doc.apply(&transaction, view.id);
22962550
22972551 match op {
@@ -2300,17 +2554,59 @@ fn delete_selection_impl(cx: &mut Context, op: Operation) {
23002554 exit_select_mode(cx);
23012555 }
23022556 Operation::Change => {
2303− enter_insert_mode(cx);
2557+ if only_whole_lines {
2558+ open_above(cx);
2559+ } else {
2560+ enter_insert_mode(cx);
2561+ }
23042562 }
23052563 }
23062564}
23072565
23082566#[inline]
2309−fn delete_selection_insert_mode(doc: &mut Document, view: &mut View, selection: &Selection) {
2310− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
2311− (range.from(), range.to(), None)
2312− });
2567+fn delete_by_selection_insert_mode(
2568+ cx: &mut Context,
2569+ mut f: impl FnMut(RopeSlice, &Range) -> Deletion,
2570+ direction: Direction,
2571+) {
2572+ let (view, doc) = current!(cx.editor);
2573+ let text = doc.text().slice(..);
2574+ let mut selection = SmallVec::new();
2575+ let mut insert_newline = false;
2576+ let text_len = text.len_chars();
2577+ let mut transaction =
2578+ Transaction::delete_by_selection(doc.text(), doc.selection(view.id), |range| {
2579+ let (start, end) = f(text, range);
2580+ if direction == Direction::Forward {
2581+ let mut range = *range;
2582+ if range.head > range.anchor {
2583+ insert_newline |= end == text_len;
2584+ // move the cursor to the right so that the selection
2585+ // doesn't shrink when deleting forward (so the text appears to
2586+ // move to left)
2587+ // += 1 is enough here as the range is normalized to grapheme boundaries
2588+ // later anyway
2589+ range.head += 1;
2590+ }
2591+ selection.push(range);
2592+ }
2593+ (start, end)
2594+ });
2595+
2596+ // in case we delete the last character and the cursor would be moved to the EOF char
2597+ // insert a newline, just like when entering append mode
2598+ if insert_newline {
2599+ transaction = transaction.insert_at_eof(doc.line_ending.as_str().into());
2600+ }
2601+
2602+ if direction == Direction::Forward {
2603+ doc.set_selection(
2604+ view.id,
2605+ Selection::new(selection, doc.selection(view.id).primary_index()),
2606+ );
2607+ }
23132608 doc.apply(&transaction, view.id);
2609+ lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
23142610}
23152611
23162612fn delete_selection(cx: &mut Context) {
@@ -2384,6 +2680,10 @@ fn insert_mode(cx: &mut Context) {
23842680 .transform(|range| Range::new(range.to(), range.from()));
23852681
23862682 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();
23872687}
23882688
23892689// inserts at the end of each selection
@@ -2419,11 +2719,13 @@ fn append_mode(cx: &mut Context) {
24192719}
24202720
24212721fn file_picker(cx: &mut Context) {
2422− // We don't specify language markers, root will be the root of the current
2423− // git repo or the current dir if we're not in a repo
2424− let root = find_root(None, &[]);
2722+ let root = find_workspace().0;
2723+ if !root.exists() {
2724+ cx.editor.set_error("Workspace directory does not exist");
2725+ return;
2726+ }
24252727 let picker = ui::file_picker(root, &cx.editor.config());
2426− cx.push_layer(Box::new(overlayed(picker)));
2728+ cx.push_layer(Box::new(overlaid(picker)));
24272729}
24282730
24292731fn file_picker_in_current_buffer_directory(cx: &mut Context) {
@@ -2440,12 +2742,18 @@ fn file_picker_in_current_buffer_directory(cx: &mut Context) {
24402742 };
24412743
24422744 let picker = ui::file_picker(path, &cx.editor.config());
2443− cx.push_layer(Box::new(overlayed(picker)));
2745+ cx.push_layer(Box::new(overlaid(picker)));
24442746}
2747+
24452748fn file_picker_in_current_directory(cx: &mut Context) {
2446− let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("./"));
2749+ let cwd = helix_loader::current_working_dir();
2750+ if !cwd.exists() {
2751+ cx.editor
2752+ .set_error("Current working directory does not exist");
2753+ return;
2754+ }
24472755 let picker = ui::file_picker(cwd, &cx.editor.config());
2448− cx.push_layer(Box::new(overlayed(picker)));
2756+ cx.push_layer(Box::new(overlaid(picker)));
24492757}
24502758
24512759fn buffer_picker(cx: &mut Context) {
@@ -2456,6 +2764,7 @@ fn buffer_picker(cx: &mut Context) {
24562764 path: Option<PathBuf>,
24572765 is_modified: bool,
24582766 is_current: bool,
2767+ focused_at: std::time::Instant,
24592768 }
24602769
24612770 impl ui::menu::Item for BufferMeta {
@@ -2488,29 +2797,32 @@ fn buffer_picker(cx: &mut Context) {
24882797 path: doc.path().cloned(),
24892798 is_modified: doc.is_modified(),
24902799 is_current: doc.id() == current,
2800+ focused_at: doc.focused_at,
24912801 };
24922802
2493− let picker = FilePicker::new(
2494− cx.editor
2495− .documents
2496− .values()
2497− .map(|doc| new_meta(doc))
2498− .collect(),
2499− (),
2500− |cx, meta, action| {
2501− cx.editor.switch(meta.id, action);
2502− },
2503− |editor, meta| {
2504− let doc = &editor.documents.get(&meta.id)?;
2505− let &view_id = doc.selections().keys().next()?;
2506− let line = doc
2507− .selection(view_id)
2508− .primary()
2509− .cursor_line(doc.text().slice(..));
2510− Some((meta.id.into(), Some((line, line))))
2511− },
2512− );
2513− cx.push_layer(Box::new(overlayed(picker)));
2803+ let mut items = cx
2804+ .editor
2805+ .documents
2806+ .values()
2807+ .map(|doc| new_meta(doc))
2808+ .collect::<Vec<BufferMeta>>();
2809+
2810+ // mru
2811+ items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
2812+
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+ });
2825+ cx.push_layer(Box::new(overlaid(picker)));
25142826}
25152827
25162828fn jumplist_picker(cx: &mut Context) {
@@ -2549,6 +2861,13 @@ fn jumplist_picker(cx: &mut Context) {
25492861 }
25502862 }
25512863
2864+ for (view, _) in cx.editor.tree.views_mut() {
2865+ for doc_id in view.jumps.iter().map(|e| e.0).collect::<Vec<_>>().iter() {
2866+ let doc = doc_mut!(cx.editor, doc_id);
2867+ view.sync_changes(doc);
2868+ }
2869+ }
2870+
25522871 let new_meta = |view: &View, doc_id: DocumentId, selection: Selection| {
25532872 let doc = &cx.editor.documents.get(&doc_id);
25542873 let text = doc.map_or("".into(), |d| {
@@ -2568,7 +2887,7 @@ fn jumplist_picker(cx: &mut Context) {
25682887 }
25692888 };
25702889
2571− let picker = FilePicker::new(
2890+ let picker = Picker::new(
25722891 cx.editor
25732892 .tree
25742893 .views()
@@ -2582,17 +2901,19 @@ fn jumplist_picker(cx: &mut Context) {
25822901 |cx, meta, action| {
25832902 cx.editor.switch(meta.id, action);
25842903 let config = cx.editor.config();
2585− let (view, doc) = current!(cx.editor);
2904+ let (view, doc) = (view_mut!(cx.editor), doc_mut!(cx.editor, &meta.id));
25862905 doc.set_selection(view.id, meta.selection.clone());
2587− view.ensure_cursor_in_view_center(doc, config.scrolloff);
2588− },
2589− |editor, meta| {
2590− let doc = &editor.documents.get(&meta.id)?;
2591− let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2592− Some((meta.path.clone()?.into(), Some((line, line))))
2906+ if action.align_view(view, doc.id()) {
2907+ view.ensure_cursor_in_view_center(doc, config.scrolloff);
2908+ }
25932909 },
2594− );
2595− cx.push_layer(Box::new(overlayed(picker)));
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+ });
2916+ cx.push_layer(Box::new(overlaid(picker)));
25962917}
25972918
25982919impl ui::menu::Item for MappableCommand {
@@ -2625,6 +2946,9 @@ impl ui::menu::Item for MappableCommand {
26252946}
26262947
26272948pub fn command_palette(cx: &mut Context) {
2949+ let register = cx.register;
2950+ let count = cx.count;
2951+
26282952 cx.callback = Some(Box::new(
26292953 move |compositor: &mut Compositor, cx: &mut compositor::Context| {
26302954 let keymap = compositor.find::<ui::EditorView>().unwrap().keymaps.map()
@@ -2642,8 +2966,8 @@ pub fn command_palette(cx: &mut Context) {
26422966
26432967 let picker = Picker::new(commands, keymap, move |cx, command, _action| {
26442968 let mut ctx = Context {
2645− register: None,
2646− count: std::num::NonZeroUsize::new(1),
2969+ register,
2970+ count,
26472971 editor: cx.editor,
26482972 callback: None,
26492973 on_next_key_callback: None,
@@ -2666,7 +2990,7 @@ pub fn command_palette(cx: &mut Context) {
26662990 }
26672991 }
26682992 });
2669− compositor.push(Box::new(overlayed(picker)));
2993+ compositor.push(Box::new(overlaid(picker)));
26702994 },
26712995 ));
26722996}
@@ -2682,38 +3006,102 @@ fn last_picker(cx: &mut Context) {
26823006 }));
26833007}
26843008
2685−// I inserts at the first nonwhitespace character of each line with a selection
3009+/// Fallback position to use for [`insert_with_indent`].
3010+enum IndentFallbackPos {
3011+ LineStart,
3012+ LineEnd,
3013+}
3014+
3015+// `I` inserts at the first nonwhitespace character of each line with a selection.
3016+// If the line is empty, automatically indent.
26863017fn insert_at_line_start(cx: &mut Context) {
2687− goto_first_nonwhitespace(cx);
2688− enter_insert_mode(cx);
3018+ insert_with_indent(cx, IndentFallbackPos::LineStart);
26893019}
26903020
2691−// A inserts at the end of each line with a selection
3021+// `A` inserts at the end of each line with a selection.
3022+// If the line is empty, automatically indent.
26923023fn 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) {
26933030 enter_insert_mode(cx);
3031+
26943032 let (view, doc) = current!(cx.editor);
26953033
2696− let selection = doc.selection(view.id).clone().transform(|range| {
2697− let text = doc.text().slice(..);
2698− let line = range.cursor_line(text);
2699− let pos = line_end_char_index(&text, line);
2700− Range::new(pos, pos)
2701− });
2702− doc.set_selection(view.id, selection);
2703−}
3034+ let text = doc.text().slice(..);
3035+ let contents = doc.text();
3036+ let selection = doc.selection(view.id);
27043037
2705−// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
2706−// it applies them, but only if the doc hasn't changed.
2707−//
2708−// TODO: provide some way to cancel this, probably as part of a more general job cancellation
2709−// scheme
2710−async fn make_format_callback(
2711− doc_id: DocumentId,
2712− doc_version: i32,
2713− view_id: ViewId,
2714− format: impl Future<Output = Result<Transaction, FormatterError>> + Send + 'static,
2715− write: Option<(Option<PathBuf>, bool)>,
2716−) -> anyhow::Result<job::Callback> {
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+ }
3087+ });
3088+
3089+ transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3090+ doc.apply(&transaction, view.id);
3091+}
3092+
3093+// Creates an LspCallback that waits for formatting changes to be computed. When they're done,
3094+// it applies them, but only if the doc hasn't changed.
3095+//
3096+// TODO: provide some way to cancel this, probably as part of a more general job cancellation
3097+// scheme
3098+async fn make_format_callback(
3099+ doc_id: DocumentId,
3100+ doc_version: i32,
3101+ view_id: ViewId,
3102+ format: impl Future<Output = Result<Transaction, FormatterError>> + Send + 'static,
3103+ write: Option<(Option<PathBuf>, bool)>,
3104+) -> anyhow::Result<job::Callback> {
27173105 let format = format.await;
27183106
27193107 let call: job::Callback = Callback::Editor(Box::new(move |editor| {
@@ -2770,6 +3158,7 @@ fn open(cx: &mut Context, open: Open) {
27703158 Open::Below => graphemes::prev_grapheme_boundary(text, range.to()),
27713159 Open::Above => range.from(),
27723160 });
3161+
27733162 let new_line = match open {
27743163 // adjust position to the end of the line (next line - 1)
27753164 Open::Below => cursor_line + 1,
@@ -2777,13 +3166,15 @@ fn open(cx: &mut Context, open: Open) {
27773166 Open::Above => cursor_line,
27783167 };
27793168
3169+ let line_num = new_line.saturating_sub(1);
3170+
27803171 // Index to insert newlines after, as well as the char width
27813172 // to use to compensate for those inserted newlines.
27823173 let (line_end_index, line_end_offset_width) = if new_line == 0 {
27833174 (0, 0)
27843175 } else {
27853176 (
2786− line_end_char_index(&doc.text().slice(..), new_line.saturating_sub(1)),
3177+ line_end_char_index(&text, line_num),
27873178 doc.line_ending.len_chars(),
27883179 )
27893180 };
@@ -2791,13 +3182,15 @@ fn open(cx: &mut Context, open: Open) {
27913182 let indent = indent::indent_for_newline(
27923183 doc.language_config(),
27933184 doc.syntax(),
3185+ &doc.config.load().indent_heuristic,
27943186 &doc.indent_style,
27953187 doc.tab_width(),
27963188 text,
2797− new_line.saturating_sub(1),
3189+ line_num,
27983190 line_end_index,
27993191 cursor_line,
28003192 );
3193+
28013194 let indent_len = indent.len();
28023195 let mut text = String::with_capacity(1 + indent_len);
28033196 text.push_str(doc.line_ending.as_str());
@@ -2957,7 +3350,7 @@ fn exit_select_mode(cx: &mut Context) {
29573350
29583351fn goto_first_diag(cx: &mut Context) {
29593352 let (view, doc) = current!(cx.editor);
2960− let selection = match doc.diagnostics().first() {
3353+ let selection = match doc.shown_diagnostics().next() {
29613354 Some(diag) => Selection::single(diag.range.start, diag.range.end),
29623355 None => return,
29633356 };
@@ -2966,7 +3359,7 @@ fn goto_first_diag(cx: &mut Context) {
29663359
29673360fn goto_last_diag(cx: &mut Context) {
29683361 let (view, doc) = current!(cx.editor);
2969− let selection = match doc.diagnostics().last() {
3362+ let selection = match doc.shown_diagnostics().last() {
29703363 Some(diag) => Selection::single(diag.range.start, diag.range.end),
29713364 None => return,
29723365 };
@@ -2982,10 +3375,9 @@ fn goto_next_diag(cx: &mut Context) {
29823375 .cursor(doc.text().slice(..));
29833376
29843377 let diag = doc
2985− .diagnostics()
2986− .iter()
3378+ .shown_diagnostics()
29873379 .find(|diag| diag.range.start > cursor_pos)
2988− .or_else(|| doc.diagnostics().first());
3380+ .or_else(|| doc.shown_diagnostics().next());
29893381
29903382 let selection = match diag {
29913383 Some(diag) => Selection::single(diag.range.start, diag.range.end),
@@ -3003,11 +3395,10 @@ fn goto_prev_diag(cx: &mut Context) {
30033395 .cursor(doc.text().slice(..));
30043396
30053397 let diag = doc
3006− .diagnostics()
3007− .iter()
3398+ .shown_diagnostics()
30083399 .rev()
30093400 .find(|diag| diag.range.start < cursor_pos)
3010− .or_else(|| doc.diagnostics().last());
3401+ .or_else(|| doc.shown_diagnostics().last());
30113402
30123403 let selection = match diag {
30133404 // NOTE: the selection is reversed because we're jumping to the
@@ -3098,8 +3489,7 @@ fn goto_next_change_impl(cx: &mut Context, direction: Direction) {
30983489
30993490 doc.set_selection(view.id, selection)
31003491 };
3101− motion(cx.editor);
3102− cx.editor.last_motion = Some(Motion(Box::new(motion)));
3492+ cx.editor.apply_motion(motion);
31033493}
31043494
31053495/// Returns the [Range] for a [Hunk] in the given text.
@@ -3162,23 +3552,19 @@ pub mod insert {
31623552 use helix_lsp::lsp;
31633553 // if ch matches completion char, trigger completion
31643554 let doc = doc_mut!(cx.editor);
3165− let language_server = match doc.language_server() {
3166− Some(language_server) => language_server,
3167− None => return,
3168− };
3169−
3170− let capabilities = language_server.capabilities();
3555+ let trigger_completion = doc
3556+ .language_servers_with_feature(LanguageServerFeature::Completion)
3557+ .any(|ls| {
3558+ // TODO: what if trigger is multiple chars long
3559+ matches!(&ls.capabilities().completion_provider, Some(lsp::CompletionOptions {
3560+ trigger_characters: Some(triggers),
3561+ ..
3562+ }) if triggers.iter().any(|trigger| trigger.contains(ch)))
3563+ });
31713564
3172− if let Some(lsp::CompletionOptions {
3173− trigger_characters: Some(triggers),
3174− ..
3175− }) = &capabilities.completion_provider
3176− {
3177− // TODO: what if trigger is multiple chars long
3178− if triggers.iter().any(|trigger| trigger.contains(ch)) {
3179− cx.editor.clear_idle_timer();
3180− super::completion(cx);
3181− }
3565+ if trigger_completion {
3566+ cx.editor.clear_idle_timer();
3567+ super::completion(cx);
31823568 }
31833569 }
31843570
@@ -3186,12 +3572,12 @@ pub mod insert {
31863572 use helix_lsp::lsp;
31873573 // if ch matches signature_help char, trigger
31883574 let doc = doc_mut!(cx.editor);
3189− // The language_server!() macro is not used here since it will
3190− // print an "LSP not active for current buffer" message on
3191− // every keypress.
3192− let language_server = match doc.language_server() {
3193− Some(language_server) => language_server,
3194− None => return,
3575+ // TODO support multiple language servers (not just the first that is found), likely by merging UI somehow
3576+ let Some(language_server) = doc
3577+ .language_servers_with_feature(LanguageServerFeature::SignatureHelp)
3578+ .next()
3579+ else {
3580+ return;
31953581 };
31963582
31973583 let capabilities = language_server.capabilities();
@@ -3230,6 +3616,7 @@ pub mod insert {
32303616 }
32313617
32323618 use helix_core::auto_pairs;
3619+ use helix_view::editor::SmartTabConfig;
32333620
32343621 pub fn insert_char(cx: &mut Context, c: char) {
32353622 let (view, doc) = current_ref!(cx.editor);
@@ -3255,6 +3642,31 @@ pub mod insert {
32553642 }
32563643 }
32573644
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+
32583670 pub fn insert_tab(cx: &mut Context) {
32593671 let (view, doc) = current!(cx.editor);
32603672 // TODO: round out to nearest indentation level (for example a line with 3 spaces should
@@ -3310,6 +3722,7 @@ pub mod insert {
33103722 let indent = indent::indent_for_newline(
33113723 doc.language_config(),
33123724 doc.syntax(),
3725+ &doc.config.load().indent_heuristic,
33133726 &doc.indent_style,
33143727 doc.tab_width(),
33153728 text,
@@ -3383,10 +3796,10 @@ pub mod insert {
33833796 let auto_pairs = doc.auto_pairs(cx.editor);
33843797
33853798 let transaction =
3386− Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
3799+ Transaction::delete_by_selection(doc.text(), doc.selection(view.id), |range| {
33873800 let pos = range.cursor(text);
33883801 if pos == 0 {
3389− return (pos, pos, None);
3802+ return (pos, pos);
33903803 }
33913804 let line_start_pos = text.line_to_char(range.cursor_line(text));
33923805 // consider to delete by indent level if all characters before `pos` are indent units.
@@ -3394,11 +3807,7 @@ pub mod insert {
33943807 if !fragment.is_empty() && fragment.chars().all(|ch| ch == ' ' || ch == '\t') {
33953808 if text.get_char(pos.saturating_sub(1)) == Some('\t') {
33963809 // fast path, delete one char
3397− (
3398− graphemes::nth_prev_grapheme_boundary(text, pos, 1),
3399− pos,
3400− None,
3401− )
3810+ (graphemes::nth_prev_grapheme_boundary(text, pos, 1), pos)
34023811 } else {
34033812 let width: usize = fragment
34043813 .chars()
@@ -3425,7 +3834,7 @@ pub mod insert {
34253834 _ => break,
34263835 }
34273836 }
3428− (start, pos, None) // delete!
3837+ (start, pos) // delete!
34293838 }
34303839 } else {
34313840 match (
@@ -3443,17 +3852,12 @@ pub mod insert {
34433852 (
34443853 graphemes::nth_prev_grapheme_boundary(text, pos, count),
34453854 graphemes::nth_next_grapheme_boundary(text, pos, count),
3446− None,
34473855 )
34483856 }
34493857 _ =>
34503858 // delete 1 char
34513859 {
3452− (
3453− graphemes::nth_prev_grapheme_boundary(text, pos, count),
3454− pos,
3455− None,
3456− )
3860+ (graphemes::nth_prev_grapheme_boundary(text, pos, count), pos)
34573861 }
34583862 }
34593863 }
@@ -3466,50 +3870,40 @@ pub mod insert {
34663870
34673871 pub fn delete_char_forward(cx: &mut Context) {
34683872 let count = cx.count();
3469− let (view, doc) = current!(cx.editor);
3470− let text = doc.text().slice(..);
3471− let transaction =
3472− Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
3873+ delete_by_selection_insert_mode(
3874+ cx,
3875+ |text, range| {
34733876 let pos = range.cursor(text);
3474− (
3475− pos,
3476− graphemes::nth_next_grapheme_boundary(text, pos, count),
3477− None,
3478− )
3479− });
3480− doc.apply(&transaction, view.id);
3481−
3482− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
3877+ (pos, graphemes::nth_next_grapheme_boundary(text, pos, count))
3878+ },
3879+ Direction::Forward,
3880+ )
34833881 }
34843882
34853883 pub fn delete_word_backward(cx: &mut Context) {
34863884 let count = cx.count();
3487− let (view, doc) = current!(cx.editor);
3488− let text = doc.text().slice(..);
3489−
3490− let selection = doc.selection(view.id).clone().transform(|range| {
3491− let anchor = movement::move_prev_word_start(text, range, count).from();
3492− let next = Range::new(anchor, range.cursor(text));
3493− exclude_cursor(text, next, range)
3494− });
3495− delete_selection_insert_mode(doc, view, &selection);
3496−
3497− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
3885+ delete_by_selection_insert_mode(
3886+ cx,
3887+ |text, range| {
3888+ let anchor = movement::move_prev_word_start(text, *range, count).from();
3889+ let next = Range::new(anchor, range.cursor(text));
3890+ let range = exclude_cursor(text, next, *range);
3891+ (range.from(), range.to())
3892+ },
3893+ Direction::Backward,
3894+ );
34983895 }
34993896
35003897 pub fn delete_word_forward(cx: &mut Context) {
35013898 let count = cx.count();
3502− let (view, doc) = current!(cx.editor);
3503− let text = doc.text().slice(..);
3504−
3505− let selection = doc.selection(view.id).clone().transform(|range| {
3506− let head = movement::move_next_word_end(text, range, count).to();
3507− Range::new(range.cursor(text), head)
3508− });
3509−
3510− delete_selection_insert_mode(doc, view, &selection);
3511−
3512− lsp::signature_help_impl(cx, SignatureHelpInvoked::Automatic);
3899+ delete_by_selection_insert_mode(
3900+ cx,
3901+ |text, range| {
3902+ let head = movement::move_next_word_end(text, *range, count).to();
3903+ (range.cursor(text), head)
3904+ },
3905+ Direction::Forward,
3906+ );
35133907 }
35143908}
35153909
@@ -3569,34 +3963,21 @@ fn commit_undo_checkpoint(cx: &mut Context) {
35693963// Yank / Paste
35703964
35713965fn yank(cx: &mut Context) {
3572− let (view, doc) = current!(cx.editor);
3573− let text = doc.text().slice(..);
3574−
3575− let values: Vec<String> = doc
3576− .selection(view.id)
3577− .fragments(text)
3578− .map(Cow::into_owned)
3579− .collect();
3580−
3581− let msg = format!(
3582− "yanked {} selection(s) to register {}",
3583− values.len(),
3584− cx.register.unwrap_or('"')
3585− );
3966+ yank_impl(cx.editor, cx.register.unwrap_or('"'));
3967+ exit_select_mode(cx);
3968+}
35863969
3587− cx.editor
3588− .registers
3589− .write(cx.register.unwrap_or('"'), values);
3970+fn yank_to_clipboard(cx: &mut Context) {
3971+ yank_impl(cx.editor, '+');
3972+ exit_select_mode(cx);
3973+}
35903974
3591− cx.editor.set_status(msg);
3975+fn yank_to_primary_clipboard(cx: &mut Context) {
3976+ yank_impl(cx.editor, '*');
35923977 exit_select_mode(cx);
35933978}
35943979
3595−fn yank_joined_to_clipboard_impl(
3596− editor: &mut Editor,
3597− separator: &str,
3598− clipboard_type: ClipboardType,
3599−) -> anyhow::Result<()> {
3980+fn yank_impl(editor: &mut Editor, register: char) {
36003981 let (view, doc) = current!(editor);
36013982 let text = doc.text().slice(..);
36023983
@@ -3605,74 +3986,79 @@ fn yank_joined_to_clipboard_impl(
36053986 .fragments(text)
36063987 .map(Cow::into_owned)
36073988 .collect();
3989+ let selections = values.len();
36083990
3609− let clipboard_text = match clipboard_type {
3610− ClipboardType::Clipboard => "system clipboard",
3611− ClipboardType::Selection => "primary clipboard",
3612− };
3613−
3614− let msg = format!(
3615− "joined and yanked {} selection(s) to {}",
3616− values.len(),
3617− clipboard_text,
3618− );
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+}
36193999
3620− let joined = values.join(separator);
4000+fn yank_joined_impl(editor: &mut Editor, separator: &str, register: char) {
4001+ let (view, doc) = current!(editor);
4002+ let text = doc.text().slice(..);
36214003
3622− editor
3623− .clipboard_provider
3624− .set_contents(joined, clipboard_type)
3625− .context("Couldn't set system clipboard content")?;
4004+ let selection = doc.selection(view.id);
4005+ let selections = selection.len();
4006+ let joined = selection
4007+ .fragments(text)
4008+ .fold(String::new(), |mut acc, fragment| {
4009+ if !acc.is_empty() {
4010+ acc.push_str(separator);
4011+ }
4012+ acc.push_str(&fragment);
4013+ acc
4014+ });
36264015
3627− editor.set_status(msg);
4016+ match editor.registers.write(register, vec![joined]) {
4017+ Ok(_) => editor.set_status(format!(
4018+ "joined and yanked {selections} selection{} to register {register}",
4019+ if selections == 1 { "" } else { "s" }
4020+ )),
4021+ Err(err) => editor.set_error(err.to_string()),
4022+ }
4023+}
36284024
3629− Ok(())
4025+fn yank_joined(cx: &mut Context) {
4026+ let separator = doc!(cx.editor).line_ending.as_str();
4027+ yank_joined_impl(cx.editor, separator, cx.register.unwrap_or('"'));
4028+ exit_select_mode(cx);
36304029}
36314030
36324031fn yank_joined_to_clipboard(cx: &mut Context) {
36334032 let line_ending = doc!(cx.editor).line_ending;
3634− let _ =
3635− yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Clipboard);
4033+ yank_joined_impl(cx.editor, line_ending.as_str(), '+');
36364034 exit_select_mode(cx);
36374035}
36384036
3639−fn yank_main_selection_to_clipboard_impl(
3640− editor: &mut Editor,
3641− clipboard_type: ClipboardType,
3642−) -> anyhow::Result<()> {
4037+fn yank_joined_to_primary_clipboard(cx: &mut Context) {
4038+ let line_ending = doc!(cx.editor).line_ending;
4039+ yank_joined_impl(cx.editor, line_ending.as_str(), '*');
4040+ exit_select_mode(cx);
4041+}
4042+
4043+fn yank_primary_selection_impl(editor: &mut Editor, register: char) {
36434044 let (view, doc) = current!(editor);
36444045 let text = doc.text().slice(..);
36454046
3646− let message_text = match clipboard_type {
3647− ClipboardType::Clipboard => "yanked main selection to system clipboard",
3648− ClipboardType::Selection => "yanked main selection to primary clipboard",
3649− };
3650−
3651− let value = doc.selection(view.id).primary().fragment(text);
4047+ let selection = doc.selection(view.id).primary().fragment(text).to_string();
36524048
3653− if let Err(e) = editor
3654− .clipboard_provider
3655− .set_contents(value.into_owned(), clipboard_type)
3656− {
3657− bail!("Couldn't set system clipboard content: {}", e);
4049+ match editor.registers.write(register, vec![selection]) {
4050+ Ok(_) => editor.set_status(format!("yanked primary selection to register {register}",)),
4051+ Err(err) => editor.set_error(err.to_string()),
36584052 }
3659−
3660− editor.set_status(message_text);
3661− Ok(())
36624053}
36634054
36644055fn yank_main_selection_to_clipboard(cx: &mut Context) {
3665− let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Clipboard);
3666−}
3667−
3668−fn yank_joined_to_primary_clipboard(cx: &mut Context) {
3669− let line_ending = doc!(cx.editor).line_ending;
3670− let _ =
3671− yank_joined_to_clipboard_impl(cx.editor, line_ending.as_str(), ClipboardType::Selection);
4056+ yank_primary_selection_impl(cx.editor, '+');
4057+ exit_select_mode(cx);
36724058}
36734059
36744060fn yank_main_selection_to_primary_clipboard(cx: &mut Context) {
3675− let _ = yank_main_selection_to_clipboard_impl(cx.editor, ClipboardType::Selection);
4061+ yank_primary_selection_impl(cx.editor, '*');
36764062 exit_select_mode(cx);
36774063}
36784064
@@ -3770,146 +4156,99 @@ pub(crate) fn paste_bracketed_value(cx: &mut Context, contents: String) {
37704156 };
37714157 let (view, doc) = current!(cx.editor);
37724158 paste_impl(&[contents], doc, view, paste, count, cx.editor.mode);
3773−}
3774−
3775−fn paste_clipboard_impl(
3776− editor: &mut Editor,
3777− action: Paste,
3778− clipboard_type: ClipboardType,
3779− count: usize,
3780−) -> anyhow::Result<()> {
3781− let (view, doc) = current!(editor);
3782− match editor.clipboard_provider.get_contents(clipboard_type) {
3783− Ok(contents) => {
3784− paste_impl(&[contents], doc, view, action, count, editor.mode);
3785− Ok(())
3786− }
3787− Err(e) => Err(e.context("Couldn't get system clipboard contents")),
3788− }
4159+ exit_select_mode(cx);
37894160}
37904161
37914162fn paste_clipboard_after(cx: &mut Context) {
3792− let _ = paste_clipboard_impl(
3793− cx.editor,
3794− Paste::After,
3795− ClipboardType::Clipboard,
3796− cx.count(),
3797− );
4163+ paste(cx.editor, '+', Paste::After, cx.count());
4164+ exit_select_mode(cx);
37984165}
37994166
38004167fn paste_clipboard_before(cx: &mut Context) {
3801− let _ = paste_clipboard_impl(
3802− cx.editor,
3803− Paste::Before,
3804− ClipboardType::Clipboard,
3805− cx.count(),
3806− );
4168+ paste(cx.editor, '+', Paste::Before, cx.count());
4169+ exit_select_mode(cx);
38074170}
38084171
38094172fn paste_primary_clipboard_after(cx: &mut Context) {
3810− let _ = paste_clipboard_impl(
3811− cx.editor,
3812− Paste::After,
3813− ClipboardType::Selection,
3814− cx.count(),
3815− );
4173+ paste(cx.editor, '*', Paste::After, cx.count());
4174+ exit_select_mode(cx);
38164175}
38174176
38184177fn paste_primary_clipboard_before(cx: &mut Context) {
3819− let _ = paste_clipboard_impl(
3820− cx.editor,
3821− Paste::Before,
3822− ClipboardType::Selection,
3823− cx.count(),
3824− );
4178+ paste(cx.editor, '*', Paste::Before, cx.count());
4179+ exit_select_mode(cx);
38254180}
38264181
38274182fn replace_with_yanked(cx: &mut Context) {
3828− let count = cx.count();
3829− let reg_name = cx.register.unwrap_or('"');
3830− let (view, doc) = current!(cx.editor);
3831− let registers = &mut cx.editor.registers;
3832−
3833− if let Some(values) = registers.read(reg_name) {
3834− if !values.is_empty() {
3835− let repeat = std::iter::repeat(
3836− values
3837− .last()
3838− .map(|value| Tendril::from(&value.repeat(count)))
3839− .unwrap(),
3840− );
3841− let mut values = values
3842− .iter()
3843− .map(|value| Tendril::from(&value.repeat(count)))
3844− .chain(repeat);
3845− let selection = doc.selection(view.id);
3846− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3847− if !range.is_empty() {
3848− (range.from(), range.to(), Some(values.next().unwrap()))
3849− } else {
3850− (range.from(), range.to(), None)
3851− }
3852− });
3853−
3854− doc.apply(&transaction, view.id);
3855− exit_select_mode(cx);
3856− }
3857− }
4183+ replace_with_yanked_impl(cx.editor, cx.register.unwrap_or('"'), cx.count());
4184+ exit_select_mode(cx);
38584185}
38594186
3860−fn replace_selections_with_clipboard_impl(
3861− cx: &mut Context,
3862− clipboard_type: ClipboardType,
3863−) -> anyhow::Result<()> {
3864− let count = cx.count();
3865− let (view, doc) = current!(cx.editor);
3866−
3867− match cx.editor.clipboard_provider.get_contents(clipboard_type) {
3868− Ok(contents) => {
3869− let selection = doc.selection(view.id);
3870− let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
3871− (
3872− range.from(),
3873− range.to(),
3874− Some(contents.repeat(count).as_str().into()),
3875− )
3876− });
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();
38774192
3878− doc.apply(&transaction, view.id);
3879− doc.append_changes_to_history(view);
4193+ let (view, doc) = current!(editor);
4194+ let repeat = std::iter::repeat(
4195+ values
4196+ .last()
4197+ .map(|value| Tendril::from(&value.repeat(count)))
4198+ .unwrap(),
4199+ );
4200+ let mut values = values
4201+ .iter()
4202+ .map(|value| Tendril::from(&value.repeat(count)))
4203+ .chain(repeat);
4204+ let selection = doc.selection(view.id);
4205+ let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
4206+ if !range.is_empty() {
4207+ (range.from(), range.to(), Some(values.next().unwrap()))
4208+ } else {
4209+ (range.from(), range.to(), None)
38804210 }
3881− Err(e) => return Err(e.context("Couldn't get system clipboard contents")),
3882− }
4211+ });
38834212
3884− exit_select_mode(cx);
3885− Ok(())
4213+ doc.apply(&transaction, view.id);
38864214}
38874215
38884216fn replace_selections_with_clipboard(cx: &mut Context) {
3889− let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Clipboard);
4217+ replace_with_yanked_impl(cx.editor, '+', cx.count());
4218+ exit_select_mode(cx);
38904219}
38914220
38924221fn replace_selections_with_primary_clipboard(cx: &mut Context) {
3893− let _ = replace_selections_with_clipboard_impl(cx, ClipboardType::Selection);
4222+ replace_with_yanked_impl(cx.editor, '*', cx.count());
4223+ exit_select_mode(cx);
38944224}
38954225
3896−fn paste(cx: &mut Context, pos: Paste) {
3897− let count = cx.count();
3898− let reg_name = cx.register.unwrap_or('"');
3899− let (view, doc) = current!(cx.editor);
3900− let registers = &mut cx.editor.registers;
4226+fn paste(editor: &mut Editor, register: char, pos: Paste, count: usize) {
4227+ let Some(values) = editor.registers.read(register, editor) else { return };
4228+ let values: Vec<_> = values.map(|value| value.to_string()).collect();
39014229
3902− if let Some(values) = registers.read(reg_name) {
3903− paste_impl(values, doc, view, pos, count, cx.editor.mode);
3904− }
4230+ let (view, doc) = current!(editor);
4231+ paste_impl(&values, doc, view, pos, count, editor.mode);
39054232}
39064233
39074234fn paste_after(cx: &mut Context) {
3908− paste(cx, Paste::After)
4235+ paste(
4236+ cx.editor,
4237+ cx.register.unwrap_or('"'),
4238+ Paste::After,
4239+ cx.count(),
4240+ );
4241+ exit_select_mode(cx);
39094242}
39104243
39114244fn paste_before(cx: &mut Context) {
3912− paste(cx, Paste::Before)
4245+ paste(
4246+ cx.editor,
4247+ cx.register.unwrap_or('"'),
4248+ Paste::Before,
4249+ cx.count(),
4250+ );
4251+ exit_select_mode(cx);
39134252}
39144253
39154254fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
@@ -3948,6 +4287,7 @@ fn indent(cx: &mut Context) {
39484287 }),
39494288 );
39504289 doc.apply(&transaction, view.id);
4290+ exit_select_mode(cx);
39514291}
39524292
39534293fn unindent(cx: &mut Context) {
@@ -3987,71 +4327,76 @@ fn unindent(cx: &mut Context) {
39874327 let transaction = Transaction::change(doc.text(), changes.into_iter());
39884328
39894329 doc.apply(&transaction, view.id);
4330+ exit_select_mode(cx);
39904331}
39914332
39924333fn format_selections(cx: &mut Context) {
39934334 use helix_lsp::{lsp, util::range_to_lsp_range};
39944335
39954336 let (view, doc) = current!(cx.editor);
4337+ let view_id = view.id;
39964338
39974339 // via lsp if available
39984340 // TODO: else via tree-sitter indentation calculations
39994341
4000− let language_server = match doc.language_server() {
4001− Some(language_server) => language_server,
4002− None => return,
4342+ if doc.selection(view_id).len() != 1 {
4343+ cx.editor
4344+ .set_error("format_selections only supports a single selection for now");
4345+ return;
4346+ }
4347+
4348+ // TODO extra LanguageServerFeature::FormatSelections?
4349+ // maybe such that LanguageServerFeature::Format contains it as well
4350+ let Some(language_server) = doc
4351+ .language_servers_with_feature(LanguageServerFeature::Format)
4352+ .find(|ls| {
4353+ matches!(
4354+ ls.capabilities().document_range_formatting_provider,
4355+ Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_))
4356+ )
4357+ })
4358+ else {
4359+ cx.editor
4360+ .set_error("No configured language server supports range formatting");
4361+ return;
40034362 };
40044363
4364+ let offset_encoding = language_server.offset_encoding();
40054365 let ranges: Vec<lsp::Range> = doc
4006− .selection(view.id)
4366+ .selection(view_id)
40074367 .iter()
4008− .map(|range| range_to_lsp_range(doc.text(), *range, language_server.offset_encoding()))
4368+ .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
40094369 .collect();
40104370
4011− if ranges.len() != 1 {
4012− cx.editor
4013− .set_error("format_selections only supports a single selection for now");
4014− return;
4015− }
4016−
40174371 // TODO: handle fails
40184372 // TODO: concurrent map over all ranges
40194373
40204374 let range = ranges[0];
40214375
4022− let request = match language_server.text_document_range_formatting(
4023− doc.identifier(),
4024− range,
4025− lsp::FormattingOptions::default(),
4026− None,
4027− ) {
4028− Some(future) => future,
4029− None => {
4030− cx.editor
4031− .set_error("Language server does not support range formatting");
4032− return;
4033− }
4034− };
4376+ let future = language_server
4377+ .text_document_range_formatting(
4378+ doc.identifier(),
4379+ range,
4380+ lsp::FormattingOptions::default(),
4381+ None,
4382+ )
4383+ .unwrap();
40354384
4036− let edits = tokio::task::block_in_place(|| helix_lsp::block_on(request)).unwrap_or_default();
4385+ let edits = tokio::task::block_in_place(|| helix_lsp::block_on(future)).unwrap_or_default();
40374386
4038− let transaction = helix_lsp::util::generate_transaction_from_edits(
4039− doc.text(),
4040− edits,
4041− language_server.offset_encoding(),
4042− );
4387+ let transaction =
4388+ helix_lsp::util::generate_transaction_from_edits(doc.text(), edits, offset_encoding);
40434389
4044− doc.apply(&transaction, view.id);
4390+ doc.apply(&transaction, view_id);
40454391}
40464392
40474393fn join_selections_impl(cx: &mut Context, select_space: bool) {
40484394 use movement::skip_while;
40494395 let (view, doc) = current!(cx.editor);
40504396 let text = doc.text();
4051− let slice = doc.text().slice(..);
4397+ let slice = text.slice(..);
40524398
40534399 let mut changes = Vec::new();
4054− let fragment = Tendril::from(" ");
40554400
40564401 for selection in doc.selection(view.id) {
40574402 let (start, mut end) = selection.line_range(slice);
@@ -4067,9 +4412,13 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
40674412 let mut end = text.line_to_char(line + 1);
40684413 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
40694414
4070− // need to skip from start, not end
4071− let change = (start, end, Some(fragment.clone()));
4072− changes.push(change);
4415+ let separator = if end == line_end_char_index(&slice, line + 1) {
4416+ // the joining line contains only space-characters => don't include a whitespace when joining
4417+ None
4418+ } else {
4419+ Some(Tendril::from(" "))
4420+ };
4421+ changes.push((start, end, separator));
40734422 }
40744423 }
40754424
@@ -4081,9 +4430,6 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
40814430 changes.sort_unstable_by_key(|(from, _to, _text)| *from);
40824431 changes.dedup();
40834432
4084− // TODO: joining multiple empty lines should be replaced by a single space.
4085− // need to merge change ranges that touch
4086−
40874433 // select inserted spaces
40884434 let transaction = if select_space {
40894435 let ranges: SmallVec<_> = changes
@@ -4095,9 +4441,9 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
40954441 })
40964442 .collect();
40974443 let selection = Selection::new(ranges, 0);
4098− Transaction::change(doc.text(), changes.into_iter()).with_selection(selection)
4444+ Transaction::change(text, changes.into_iter()).with_selection(selection)
40994445 } else {
4100− Transaction::change(doc.text(), changes.into_iter())
4446+ Transaction::change(text, changes.into_iter())
41014447 };
41024448
41034449 doc.apply(&transaction, view.id);
@@ -4111,8 +4457,8 @@ fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) {
41114457 if remove { "remove:" } else { "keep:" }.into(),
41124458 Some(reg),
41134459 ui::completers::none,
4114− move |editor, regex, event| {
4115− let (view, doc) = current!(editor);
4460+ move |cx, regex, event| {
4461+ let (view, doc) = current!(cx.editor);
41164462 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
41174463 return;
41184464 }
@@ -4171,35 +4517,75 @@ pub fn completion(cx: &mut Context) {
41714517
41724518 let (view, doc) = current!(cx.editor);
41734519
4174− let language_server = match doc.language_server() {
4175− Some(language_server) => language_server,
4176− None => return,
4520+ let savepoint = if let Some(CompleteAction::Selected { savepoint }) = &cx.editor.last_completion
4521+ {
4522+ savepoint.clone()
4523+ } else {
4524+ doc.savepoint(view)
41774525 };
41784526
4179− let offset_encoding = language_server.offset_encoding();
4180− let text = doc.text().slice(..);
4181− let cursor = doc.selection(view.id).primary().cursor(text);
4182−
4183− let pos = pos_to_lsp_pos(doc.text(), cursor, offset_encoding);
4527+ let text = savepoint.text.clone();
4528+ let cursor = savepoint.cursor();
4529+
4530+ let mut seen_language_servers = HashSet::new();
4531+
4532+ let mut futures: FuturesUnordered<_> = doc
4533+ .language_servers_with_feature(LanguageServerFeature::Completion)
4534+ .filter(|ls| seen_language_servers.insert(ls.id()))
4535+ .map(|language_server| {
4536+ let language_server_id = language_server.id();
4537+ let offset_encoding = language_server.offset_encoding();
4538+ let pos = pos_to_lsp_pos(&text, cursor, offset_encoding);
4539+ let doc_id = doc.identifier();
4540+ let completion_request = language_server.completion(doc_id, pos, None).unwrap();
4541+
4542+ async move {
4543+ let json = completion_request.await?;
4544+ let response: Option<lsp::CompletionResponse> = serde_json::from_value(json)?;
4545+
4546+ let items = match response {
4547+ Some(lsp::CompletionResponse::Array(items)) => items,
4548+ // TODO: do something with is_incomplete
4549+ Some(lsp::CompletionResponse::List(lsp::CompletionList {
4550+ is_incomplete: _is_incomplete,
4551+ items,
4552+ })) => items,
4553+ None => Vec::new(),
4554+ }
4555+ .into_iter()
4556+ .map(|item| CompletionItem {
4557+ item,
4558+ language_server_id,
4559+ resolved: false,
4560+ })
4561+ .collect();
41844562
4185− let future = match language_server.completion(doc.identifier(), pos, None) {
4186− Some(future) => future,
4187− None => return,
4188− };
4563+ anyhow::Ok(items)
4564+ }
4565+ })
4566+ .collect();
41894567
4190− // setup a chanel that allows the request to be canceled
4568+ // setup a channel that allows the request to be canceled
41914569 let (tx, rx) = oneshot::channel();
41924570 // set completion_request so that this request can be canceled
41934571 // by setting completion_request, the old channel stored there is dropped
41944572 // and the associated request is automatically dropped
41954573 cx.editor.completion_request_handle = Some(tx);
41964574 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+ };
41974583 tokio::select! {
41984584 biased;
41994585 _ = rx => {
4200− Ok(serde_json::Value::Null)
4586+ Ok(Vec::new())
42014587 }
4202− res = future => {
4588+ res = items_future => {
42034589 res
42044590 }
42054591 }
@@ -4215,7 +4601,6 @@ pub fn completion(cx: &mut Context) {
42154601 iter.reverse();
42164602 let offset = iter.take_while(|ch| chars::char_is_word(*ch)).count();
42174603 let start_offset = cursor.saturating_sub(offset);
4218− let savepoint = doc.savepoint(view);
42194604
42204605 let trigger_doc = doc.id();
42214606 let trigger_view = view.id;
@@ -4234,46 +4619,45 @@ pub fn completion(cx: &mut Context) {
42344619 },
42354620 ));
42364621
4237− cx.callback(
4238− future,
4239− move |editor, compositor, response: Option<lsp::CompletionResponse>| {
4622+ cx.jobs.callback(async move {
4623+ let items = future.await?;
4624+ let call = move |editor: &mut Editor, compositor: &mut Compositor| {
42404625 let (view, doc) = current_ref!(editor);
42414626 // check if the completion request is stale.
42424627 //
4243− // Completions are completed asynchrounsly and therefore the user could
4628+ // Completions are completed asynchronously and therefore the user could
42444629 //switch document/view or leave insert mode. In all of thoise cases the
42454630 // completion should be discarded
42464631 if editor.mode != Mode::Insert || view.id != trigger_view || doc.id() != trigger_doc {
42474632 return;
42484633 }
42494634
4250− let items = match response {
4251− Some(lsp::CompletionResponse::Array(items)) => items,
4252− // TODO: do something with is_incomplete
4253− Some(lsp::CompletionResponse::List(lsp::CompletionList {
4254− is_incomplete: _is_incomplete,
4255− items,
4256− })) => items,
4257− None => Vec::new(),
4258− };
4259−
42604635 if items.is_empty() {
42614636 // editor.set_error("No completion available");
42624637 return;
42634638 }
42644639 let size = compositor.size();
42654640 let ui = compositor.find::<ui::EditorView>().unwrap();
4266− ui.set_completion(
4641+ let completion_area = ui.set_completion(
42674642 editor,
42684643 savepoint,
42694644 items,
4270− offset_encoding,
42714645 start_offset,
42724646 trigger_offset,
42734647 size,
42744648 );
4275− },
4276− );
4649+ let size = compositor.size();
4650+ let signature_help_area = compositor
4651+ .find_id::<Popup<SignatureHelp>>(SignatureHelp::ID)
4652+ .map(|signature_help| signature_help.area(size, editor));
4653+ // Delete the signature help popup if they intersect.
4654+ if matches!((completion_area, signature_help_area),(Some(a), Some(b)) if a.intersects(b))
4655+ {
4656+ compositor.remove(SignatureHelp::ID);
4657+ }
4658+ };
4659+ Ok(Callback::EditorCompositor(Box::new(call)))
4660+ });
42774661}
42784662
42794663// comments
@@ -4308,7 +4692,13 @@ fn rotate_selections_backward(cx: &mut Context) {
43084692 rotate_selections(cx, Direction::Backward)
43094693}
43104694
4311−fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
4695+enum ReorderStrategy {
4696+ RotateForward,
4697+ RotateBackward,
4698+ Reverse,
4699+}
4700+
4701+fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
43124702 let count = cx.count;
43134703 let (view, doc) = current!(cx.editor);
43144704 let text = doc.text().slice(..);
@@ -4326,9 +4716,10 @@ fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
43264716
43274717 for chunk in fragments.chunks_mut(group) {
43284718 // TODO: also modify main index
4329− match direction {
4330− Direction::Forward => chunk.rotate_right(1),
4331− Direction::Backward => chunk.rotate_left(1),
4719+ match strategy {
4720+ ReorderStrategy::RotateForward => chunk.rotate_right(1),
4721+ ReorderStrategy::RotateBackward => chunk.rotate_left(1),
4722+ ReorderStrategy::Reverse => chunk.reverse(),
43324723 };
43334724 }
43344725
@@ -4345,10 +4736,13 @@ fn rotate_selection_contents(cx: &mut Context, direction: Direction) {
43454736}
43464737
43474738fn rotate_selection_contents_forward(cx: &mut Context) {
4348− rotate_selection_contents(cx, Direction::Forward)
4739+ reorder_selection_contents(cx, ReorderStrategy::RotateForward)
43494740}
43504741fn rotate_selection_contents_backward(cx: &mut Context) {
4351− rotate_selection_contents(cx, Direction::Backward)
4742+ reorder_selection_contents(cx, ReorderStrategy::RotateBackward)
4743+}
4744+fn reverse_selection_contents(cx: &mut Context) {
4745+ reorder_selection_contents(cx, ReorderStrategy::Reverse)
43524746}
43534747
43544748// tree sitter node selection
@@ -4372,8 +4766,7 @@ fn expand_selection(cx: &mut Context) {
43724766 }
43734767 }
43744768 };
4375− motion(cx.editor);
4376− cx.editor.last_motion = Some(Motion(Box::new(motion)));
4769+ cx.editor.apply_motion(motion);
43774770}
43784771
43794772fn shrink_selection(cx: &mut Context) {
@@ -4397,8 +4790,7 @@ fn shrink_selection(cx: &mut Context) {
43974790 doc.set_selection(view.id, selection);
43984791 }
43994792 };
4400− motion(cx.editor);
4401− cx.editor.last_motion = Some(Motion(Box::new(motion)));
4793+ cx.editor.apply_motion(motion);
44024794}
44034795
44044796fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: &'static F)
@@ -4416,8 +4808,7 @@ where
44164808 doc.set_selection(view.id, selection);
44174809 }
44184810 };
4419− motion(cx.editor);
4420− cx.editor.last_motion = Some(Motion(Box::new(motion)));
4811+ cx.editor.apply_motion(motion);
44214812}
44224813
44234814fn select_next_sibling(cx: &mut Context) {
@@ -4428,22 +4819,68 @@ fn select_prev_sibling(cx: &mut Context) {
44284819 select_sibling_impl(cx, &|node| Node::prev_sibling(&node))
44294820}
44304821
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+
44314865fn match_brackets(cx: &mut Context) {
44324866 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(..);
44334870
4434− if let Some(syntax) = doc.syntax() {
4435− let text = doc.text().slice(..);
4436− let selection = doc.selection(view.id).clone().transform(|range| {
4437− if let Some(pos) =
4438− match_brackets::find_matching_bracket_fuzzy(syntax, doc.text(), range.cursor(text))
4439− {
4440− range.put_cursor(text, pos, cx.editor.mode == Mode::Select)
4441− } else {
4442− range
4443− }
4444− });
4445− doc.set_selection(view.id, selection);
4446− }
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);
44474884}
44484885
44494886//
@@ -4538,17 +4975,19 @@ fn transpose_view(cx: &mut Context) {
45384975 cx.editor.transpose_view()
45394976}
45404977
4541−// split helper, clear it later
4542−fn split(cx: &mut Context, action: Action) {
4543− let (view, doc) = current!(cx.editor);
4978+/// Open a new split in the given direction specified by the action.
4979+///
4980+/// Maintain the current view (both the cursor's position and view in document).
4981+fn split(editor: &mut Editor, action: Action) {
4982+ let (view, doc) = current!(editor);
45444983 let id = doc.id();
45454984 let selection = doc.selection(view.id).clone();
45464985 let offset = view.offset;
45474986
4548− cx.editor.switch(id, action);
4987+ editor.switch(id, action);
45494988
45504989 // match the selection in the previous view
4551− let (view, doc) = current!(cx.editor);
4990+ let (view, doc) = current!(editor);
45524991 doc.set_selection(view.id, selection);
45534992 // match the view scroll offset (switch doesn't handle this fully
45544993 // since the selection is only matched after the split)
@@ -4556,7 +4995,7 @@ fn split(cx: &mut Context, action: Action) {
45564995}
45574996
45584997fn hsplit(cx: &mut Context) {
4559− split(cx, Action::HorizontalSplit);
4998+ split(cx.editor, Action::HorizontalSplit);
45604999}
45615000
45625001fn hsplit_new(cx: &mut Context) {
@@ -4564,7 +5003,7 @@ fn hsplit_new(cx: &mut Context) {
45645003}
45655004
45665005fn vsplit(cx: &mut Context) {
4567− split(cx, Action::VerticalSplit);
5006+ split(cx.editor, Action::VerticalSplit);
45685007}
45695008
45705009fn vsplit_new(cx: &mut Context) {
@@ -4613,7 +5052,12 @@ fn insert_register(cx: &mut Context) {
46135052 if let Some(ch) = event.char() {
46145053 cx.editor.autoinfo = None;
46155054 cx.register = Some(ch);
4616− paste(cx, Paste::Cursor);
5055+ paste(
5056+ cx.editor,
5057+ cx.register.unwrap_or('"'),
5058+ Paste::Cursor,
5059+ cx.count(),
5060+ );
46175061 }
46185062 })
46195063}
@@ -4697,8 +5141,7 @@ fn goto_ts_object_impl(cx: &mut Context, object: &'static str, direction: Direct
46975141 editor.set_status("Syntax-tree is not available in current buffer");
46985142 }
46995143 };
4700− motion(cx.editor);
4701− cx.editor.last_motion = Some(Motion(Box::new(motion)));
5144+ cx.editor.apply_motion(motion);
47025145}
47035146
47045147fn goto_next_function(cx: &mut Context) {
@@ -4819,8 +5262,7 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
48195262 });
48205263 doc.set_selection(view.id, selection);
48215264 };
4822− textobject(cx.editor);
4823− cx.editor.last_motion = Some(Motion(Box::new(textobject)));
5265+ cx.editor.apply_motion(textobject);
48245266 }
48255267 });
48265268
@@ -4910,11 +5352,18 @@ fn surround_replace(cx: &mut Context) {
49105352 }
49115353 };
49125354
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+
49135362 cx.on_next_key(move |cx, event| {
49145363 let (view, doc) = current!(cx.editor);
49155364 let to = match event.char() {
49165365 Some(to) => to,
4917− None => return,
5366+ None => return doc.set_selection(view.id, selection),
49185367 };
49195368 let (open, close) = surround::get_pair(to);
49205369 let transaction = Transaction::change(
@@ -4925,6 +5374,7 @@ fn surround_replace(cx: &mut Context) {
49255374 (pos, pos + 1, Some(t))
49265375 }),
49275376 );
5377+ doc.set_selection(view.id, selection);
49285378 doc.apply(&transaction, view.id);
49295379 exit_select_mode(cx);
49305380 });
@@ -5070,9 +5520,10 @@ async fn shell_impl_async(
50705520 let output = if let Some(mut stdin) = process.stdin.take() {
50715521 let input_task = tokio::spawn(async move {
50725522 if let Some(input) = input {
5073− helix_view::document::to_writer(&mut stdin, encoding::UTF_8, &input).await?;
5523+ helix_view::document::to_writer(&mut stdin, (encoding::UTF_8, false), &input)
5524+ .await?;
50745525 }
5075− Ok::<_, anyhow::Error>(())
5526+ anyhow::Ok(())
50765527 });
50775528 let (output, _) = tokio::join! {
50785529 process.wait_with_output(),
@@ -5158,12 +5609,18 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
51585609 };
51595610
51605611 // These `usize`s cannot underflow because selection ranges cannot overlap.
5161− // Once the MSRV is 1.66.0 (mixed_integer_ops is stabilized), we can use checked
5162− // arithmetic to assert this.
5163− let anchor = (to as isize + offset - deleted_len as isize) as usize;
5612+ let anchor = to
5613+ .checked_add_signed(offset)
5614+ .expect("Selection ranges cannot overlap")
5615+ .checked_sub(deleted_len)
5616+ .expect("Selection ranges cannot overlap");
51645617 let new_range = Range::new(anchor, anchor + output_len).with_direction(range.direction());
51655618 ranges.push(new_range);
5166− offset = offset + output_len as isize - deleted_len as isize;
5619+ offset = offset
5620+ .checked_add_unsigned(output_len)
5621+ .expect("Selection ranges cannot overlap")
5622+ .checked_sub_unsigned(deleted_len)
5623+ .expect("Selection ranges cannot overlap");
51675624
51685625 changes.push((from, to, Some(output)));
51695626 }
@@ -5185,7 +5642,7 @@ fn shell_prompt(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBeha
51855642 cx,
51865643 prompt,
51875644 Some('|'),
5188− ui::completers::none,
5645+ ui::completers::filename,
51895646 move |cx, input: &str, event: PromptEvent| {
51905647 if event != PromptEvent::Validate {
51915648 return;
@@ -5302,6 +5759,7 @@ fn increment_impl(cx: &mut Context, increment_direction: IncrementDirection) {
53025759 let transaction = Transaction::change(doc.text(), changes.into_iter());
53035760 let transaction = transaction.with_selection(new_selection);
53045761 doc.apply(&transaction, view.id);
5762+ exit_select_mode(cx);
53055763 }
53065764}
53075765
@@ -5320,9 +5778,12 @@ fn record_macro(cx: &mut Context) {
53205778 }
53215779 })
53225780 .collect::<String>();
5323− cx.editor.registers.write(reg, vec![s]);
5324− cx.editor
5325− .set_status(format!("Recorded to register [{}]", reg));
5781+ match cx.editor.registers.write(reg, vec![s]) {
5782+ Ok(_) => cx
5783+ .editor
5784+ .set_status(format!("Recorded to register [{}]", reg)),
5785+ Err(err) => cx.editor.set_error(err.to_string()),
5786+ }
53265787 } else {
53275788 let reg = cx.register.take().unwrap_or('@');
53285789 cx.editor.macro_recording = Some((reg, Vec::new()));
@@ -5342,8 +5803,14 @@ fn replay_macro(cx: &mut Context) {
53425803 return;
53435804 }
53445805
5345− let keys: Vec<KeyEvent> = if let Some([keys_str]) = cx.editor.registers.read(reg) {
5346− match helix_view::input::parse_macro(keys_str) {
5806+ let keys: Vec<KeyEvent> = if let Some(keys) = cx
5807+ .editor
5808+ .registers
5809+ .read(reg, cx.editor)
5810+ .filter(|values| values.len() == 1)
5811+ .map(|mut values| values.next().unwrap())
5812+ {
5813+ match helix_view::input::parse_macro(&keys) {
53475814 Ok(keys) => keys,
53485815 Err(err) => {
53495816 cx.editor.set_error(format!("Invalid macro: {}", err));