1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
|
//! Command processor
use log::debug;
use std::fmt;
use unicode_segmentation::UnicodeSegmentation;
use super::{Context, Helper, Result};
use crate::error::{ReadlineError, Signal};
use crate::highlight::{CmdKind, Highlighter};
use crate::hint::Hint;
use crate::history::SearchDirection;
use crate::keymap::{Anchor, At, CharSearch, Cmd, Movement, RepeatCount, Word};
use crate::keymap::{InputState, Invoke, Refresher};
use crate::layout::{cwidh, Layout, Position, Unit};
use crate::line_buffer::{DeleteListener, Direction, LineBuffer, NoListener, WordAction, MAX_LINE};
use crate::tty::{Renderer, Term, Terminal};
use crate::undo::Changeset;
use crate::validate::{ValidationContext, ValidationResult};
use crate::KillRing;
/// Represent the state during line editing.
/// Implement rendering.
pub struct State<'out, 'prompt, H: Helper> {
pub out: &'out mut <Terminal as Term>::Writer,
prompt: &'prompt str, // Prompt to display (rl_prompt)
prompt_size: Position, // Prompt Unicode/visible width and height
pub line: LineBuffer, // Edited line buffer
pub layout: Layout,
saved_line_for_history: LineBuffer, // Current edited line before history browsing
byte_buffer: [u8; 4],
pub changes: Changeset, // changes to line, for undo/redo
pub helper: Option<&'out H>,
pub ctx: Context<'out>, // Give access to history for `hinter`
pub hint: Option<Box<dyn Hint>>, // last hint displayed
pub highlight_char: bool, // `true` if a char has been highlighted
}
enum Info<'m> {
NoHint,
Hint,
Msg(Option<&'m str>),
}
impl<'out, 'prompt, H: Helper> State<'out, 'prompt, H> {
pub fn new(
out: &'out mut <Terminal as Term>::Writer,
prompt: &'prompt str,
helper: Option<&'out H>,
ctx: Context<'out>,
) -> Self {
let prompt_size = out.calculate_position(prompt, Position::default());
let gcm = out.grapheme_cluster_mode();
Self {
out,
prompt,
prompt_size,
line: LineBuffer::with_capacity(MAX_LINE).can_growth(true),
layout: Layout::new(gcm),
saved_line_for_history: LineBuffer::with_capacity(MAX_LINE).can_growth(true),
byte_buffer: [0; 4],
changes: Changeset::new(),
helper,
ctx,
hint: None,
highlight_char: false,
}
}
pub fn highlighter(&self) -> Option<&dyn Highlighter> {
if self.out.colors_enabled() {
self.helper.map(|h| h as &dyn Highlighter)
} else {
None
}
}
pub fn next_cmd(
&mut self,
input_state: &mut InputState,
rdr: &mut <Terminal as Term>::Reader,
single_esc_abort: bool,
ignore_external_print: bool,
) -> Result<Cmd> {
loop {
let rc = input_state.next_cmd(rdr, self, single_esc_abort, ignore_external_print);
if let Err(ReadlineError::Signal(signal)) = rc {
match signal {
#[cfg(unix)]
Signal::Interrupt => {
debug!(target: "rustyline", "SIGINT");
return Ok(Cmd::Interrupt);
}
Signal::Resize => {
debug!(target: "rustyline", "SIGWINCH");
let old_cols = self.out.get_columns();
self.out.update_size();
let new_cols = self.out.get_columns();
if new_cols != old_cols
&& (self.layout.end.row > 0 || self.layout.end.col >= new_cols)
{
self.prompt_size = self
.out
.calculate_position(self.prompt, Position::default());
self.refresh_line()?;
}
continue;
}
}
}
if let Ok(Cmd::Replace(..)) = rc {
self.changes.begin();
}
return rc;
}
}
pub fn backup(&mut self) {
self.saved_line_for_history
.update(self.line.as_str(), self.line.pos(), &mut NoListener);
}
pub fn restore(&mut self) {
self.line.update(
self.saved_line_for_history.as_str(),
self.saved_line_for_history.pos(),
&mut self.changes,
);
}
pub fn move_cursor(&mut self, kind: CmdKind) -> Result<()> {
// calculate the desired position of the cursor
let cursor = self
.out
.calculate_position(&self.line[..self.line.pos()], self.prompt_size);
if self.layout.cursor == cursor {
return Ok(());
}
if self.highlight_char(kind) {
let prompt_size = self.prompt_size;
self.refresh(self.prompt, prompt_size, true, Info::NoHint)?;
} else {
self.out.move_cursor(self.layout.cursor, cursor)?;
self.layout.prompt_size = self.prompt_size;
self.layout.cursor = cursor;
debug_assert!(self.layout.prompt_size <= self.layout.cursor);
debug_assert!(self.layout.cursor <= self.layout.end);
}
Ok(())
}
pub fn move_cursor_to_end(&mut self) -> Result<()> {
if self.layout.cursor == self.layout.end {
return Ok(());
}
self.out.move_cursor(self.layout.cursor, self.layout.end)?;
self.layout.cursor = self.layout.end;
Ok(())
}
pub fn move_cursor_at_leftmost(&mut self, rdr: &mut <Terminal as Term>::Reader) -> Result<()> {
self.out.move_cursor_at_leftmost(rdr)
}
fn refresh(
&mut self,
prompt: &str,
prompt_size: Position,
default_prompt: bool,
info: Info<'_>,
) -> Result<()> {
let info = match info {
Info::NoHint => None,
Info::Hint => self.hint.as_ref().map(|h| h.display()),
Info::Msg(msg) => msg,
};
let highlighter = if self.out.colors_enabled() {
self.helper.map(|h| h as &dyn Highlighter)
} else {
None
};
let new_layout = self
.out
.compute_layout(prompt_size, default_prompt, &self.line, info);
debug!(target: "rustyline", "old layout: {:?}", self.layout);
debug!(target: "rustyline", "new layout: {new_layout:?}");
self.out.refresh_line(
prompt,
&self.line,
info,
&self.layout,
&new_layout,
highlighter,
)?;
self.layout = new_layout;
Ok(())
}
pub fn hint(&mut self) {
if let Some(hinter) = self.helper {
let hint = hinter.hint(self.line.as_str(), self.line.pos(), &self.ctx);
self.hint = match hint {
Some(val) if !val.display().is_empty() => Some(Box::new(val) as Box<dyn Hint>),
_ => None,
};
} else {
self.hint = None;
}
}
fn highlight_char(&mut self, kind: CmdKind) -> bool {
if let Some(highlighter) = self.highlighter() {
let highlight_char = highlighter.highlight_char(&self.line, self.line.pos(), kind);
if highlight_char {
self.highlight_char = true;
true
} else if self.highlight_char {
// previously highlighted => force a full refresh
self.highlight_char = false;
true
} else {
false
}
} else {
false
}
}
pub fn is_default_prompt(&self) -> bool {
self.layout.default_prompt
}
pub fn validate(&mut self) -> Result<ValidationResult> {
if let Some(validator) = self.helper {
self.changes.begin();
let result = validator.validate(&mut ValidationContext::new(self))?;
let corrected = self.changes.end();
match result {
ValidationResult::Incomplete => {}
ValidationResult::Valid(ref msg) => {
// Accept the line regardless of where the cursor is.
if corrected || self.has_hint() || msg.is_some() {
// Force a refresh without hints to leave the previous
// line as the user typed it after a newline.
self.refresh_line_with_msg(msg.as_deref(), CmdKind::ForcedRefresh)?;
}
}
ValidationResult::Invalid(ref msg) => {
if corrected || self.has_hint() || msg.is_some() {
self.refresh_line_with_msg(msg.as_deref(), CmdKind::Other)?;
}
}
}
Ok(result)
} else {
Ok(ValidationResult::Valid(None))
}
}
}
impl<H: Helper> Invoke for State<'_, '_, H> {
fn input(&self) -> &str {
self.line.as_str()
}
}
impl<H: Helper> Refresher for State<'_, '_, H> {
fn refresh_line(&mut self) -> Result<()> {
self.hint();
self.highlight_char(CmdKind::Other);
self.refresh(self.prompt, self.prompt_size, true, Info::Hint)
}
fn refresh_line_with_msg(&mut self, msg: Option<&str>, kind: CmdKind) -> Result<()> {
self.hint = None;
self.highlight_char(kind);
self.refresh(self.prompt, self.prompt_size, true, Info::Msg(msg))
}
fn refresh_prompt_and_line(&mut self, prompt: &str) -> Result<()> {
let prompt_size = self.out.calculate_position(prompt, Position::default());
self.hint();
self.highlight_char(CmdKind::Other);
self.refresh(prompt, prompt_size, false, Info::Hint)
}
fn doing_insert(&mut self) {
self.changes.begin();
}
fn done_inserting(&mut self) {
self.changes.end();
}
fn last_insert(&self) -> Option<String> {
self.changes.last_insert()
}
fn is_cursor_at_end(&self) -> bool {
self.line.is_cursor_at_end()
}
fn has_hint(&self) -> bool {
self.hint.is_some()
}
fn hint_text(&self) -> Option<&str> {
self.hint.as_ref().and_then(|hint| hint.completion())
}
fn line(&self) -> &str {
self.line.as_str()
}
fn pos(&self) -> usize {
self.line.pos()
}
fn external_print(&mut self, msg: String) -> Result<()> {
self.out.begin_synchronized_update()?;
self.out.clear_rows(&self.layout)?;
self.layout.end.row = 0;
self.layout.cursor.row = 0;
self.out.write_and_flush(msg.as_str())?;
if !msg.ends_with('\n') {
self.out.write_and_flush("\n")?;
}
self.refresh_line()?;
self.out.end_synchronized_update()
}
}
impl<H: Helper> fmt::Debug for State<'_, '_, H> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("State")
.field("prompt", &self.prompt)
.field("prompt_size", &self.prompt_size)
.field("buf", &self.line)
.field("cols", &self.out.get_columns())
.field("layout", &self.layout)
.field("saved_line_for_history", &self.saved_line_for_history)
.finish()
}
}
impl<H: Helper> State<'_, '_, H> {
pub fn clear_screen(&mut self) -> Result<()> {
self.out.clear_screen()?;
self.layout.cursor = Position::default();
self.layout.end = Position::default();
Ok(())
}
/// Insert the character `ch` at cursor current position.
pub fn edit_insert(&mut self, ch: char, n: RepeatCount) -> Result<()> {
if let Some(push) = self.line.insert(ch, n, &mut self.changes) {
if push {
let no_previous_msg = !self.layout.has_info;
self.hint();
let highlight_char = self.highlight_char(CmdKind::Other);
let width = cwidh(ch);
if n == 1
&& width != 0 // Ctrl-V + \t or \n ...
&& self.layout.cursor.col + width < self.out.get_columns()
&& (self.hint.is_none() && no_previous_msg) // TODO refresh only current line
&& !highlight_char
{
// Avoid a full update of the line in the trivial case.
self.layout.cursor.col += width;
self.layout.end.col += width;
debug_assert!(self.layout.prompt_size <= self.layout.cursor);
debug_assert!(self.layout.cursor <= self.layout.end);
let bits = ch.encode_utf8(&mut self.byte_buffer);
self.out.write_and_flush(bits)
} else {
self.refresh(self.prompt, self.prompt_size, true, Info::Hint)
}
} else {
self.refresh_line()
}
} else {
Ok(())
}
}
/// Replace a single (or n) character(s) under the cursor (Vi mode)
pub fn edit_replace_char(&mut self, ch: char, n: RepeatCount) -> Result<()> {
self.changes.begin();
let succeed = if let Some(chars) = self.line.delete(n, &mut self.changes) {
let count = RepeatCount::try_from(chars.graphemes(true).count()).unwrap();
self.line.insert(ch, count, &mut self.changes);
self.line.move_backward(1);
true
} else {
false
};
self.changes.end();
if succeed {
self.refresh_line()
} else {
Ok(())
}
}
/// Overwrite the character under the cursor (Vi mode)
pub fn edit_overwrite_char(&mut self, ch: char) -> Result<()> {
if let Some(end) = self.line.next_pos(1) {
{
let text = ch.encode_utf8(&mut self.byte_buffer);
let start = self.line.pos();
self.line.replace(start..end, text, &mut self.changes);
}
self.refresh_line()
} else {
Ok(())
}
}
// Yank/paste `text` at current position.
pub fn edit_yank(
&mut self,
input_state: &InputState,
text: &str,
anchor: Anchor,
n: RepeatCount,
) -> Result<()> {
if let Anchor::After = anchor {
self.line.move_forward(1);
}
if self.line.yank(text, n, &mut self.changes).is_some() {
if !input_state.is_emacs_mode() {
self.line.move_backward(1);
}
self.refresh_line()
} else {
Ok(())
}
}
// Delete previously yanked text and yank/paste `text` at current position.
pub fn edit_yank_pop(&mut self, yank_size: usize, text: &str) -> Result<()> {
self.changes.begin();
let result = if self
.line
.yank_pop(yank_size, text, &mut self.changes)
.is_some()
{
self.refresh_line()
} else {
Ok(())
};
self.changes.end();
result
}
/// Move cursor on the left.
pub fn edit_move_backward(&mut self, n: RepeatCount) -> Result<()> {
if self.line.move_backward(n) {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
/// Move cursor on the right.
pub fn edit_move_forward(&mut self, n: RepeatCount) -> Result<()> {
if self.line.move_forward(n) {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
/// Move cursor to the start of the line.
pub fn edit_move_home(&mut self) -> Result<()> {
if self.line.move_home() {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
/// Move cursor to the end of the line.
pub fn edit_move_end(&mut self) -> Result<()> {
if self.line.move_end() {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
/// Move cursor to the start of the buffer.
pub fn edit_move_buffer_start(&mut self) -> Result<()> {
if self.line.move_buffer_start() {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
/// Move cursor to the end of the buffer.
pub fn edit_move_buffer_end(&mut self, kind: CmdKind) -> Result<()> {
if self.line.move_buffer_end() {
self.move_cursor(kind)
} else {
Ok(())
}
}
pub fn edit_kill(&mut self, mvt: &Movement, kill_ring: &mut KillRing) -> Result<()> {
struct Proxy<'p> {
changes: &'p mut Changeset,
kill_ring: &'p mut KillRing,
layout: &'p Layout, // current layout (before kill)
pos: usize, // current cursor (byte) position (before kill)
end: usize, // end (before kill)
cursor_shift: Unit, // cursor shift (columns) after kill
end_shift: Unit, // end of line shift (columns) after kill
trivial: bool, // true if a partial screen update can be done
}
let mut proxy = Proxy {
changes: &mut self.changes,
kill_ring,
layout: &self.layout,
pos: self.line.pos(),
end: self.line.len(),
cursor_shift: 0,
end_shift: 0,
trivial: self.layout.cursor.row == self.layout.end.row,
};
impl DeleteListener for Proxy<'_> {
fn start_killing(&mut self) {
self.kill_ring.start_killing();
}
fn delete(&mut self, idx: usize, string: &str, dir: Direction) {
self.changes.delete(idx, string);
self.kill_ring.delete(idx, string, dir);
if self.trivial {
if dir == Direction::Backward {
if self.pos == self.end {
// backward from eol
let width = self.layout.width(string);
self.cursor_shift += width;
self.end_shift += width;
} else {
self.trivial = false;
}
} else if idx == self.pos && self.pos + string.len() == self.end {
// forward to eol
self.end_shift += self.layout.width(string);
} else {
self.trivial = false;
}
}
}
fn stop_killing(&mut self) {
self.kill_ring.stop_killing()
}
}
if self.line.kill(mvt, &mut proxy) {
let (trivial, cursor_shift, end_shift) =
(proxy.trivial, proxy.cursor_shift, proxy.end_shift);
let no_previous_msg = !self.layout.has_info;
self.hint();
let highlight_char = self.highlight_char(CmdKind::Other);
if trivial
&& cursor_shift <= self.layout.cursor.col
&& end_shift <= self.layout.end.col
&& (self.hint.is_none() && no_previous_msg)
&& !highlight_char
{
// Avoid a full update of the line in the trivial case.
debug_assert!(self.line.is_cursor_at_end());
if cursor_shift != 0 {
let old = self.layout.cursor;
self.layout.cursor.col -= cursor_shift;
debug!(target: "rustyline", "old cursor: {:?}", old.col);
debug!(target: "rustyline", "new cursor: {:?}", self.layout.cursor.col);
self.out.move_cursor(old, self.layout.cursor)?;
}
self.layout.end.col -= end_shift;
debug_assert_eq!(self.layout.cursor, self.layout.end);
self.out.clear_to_eol()
} else {
self.refresh(self.prompt, self.prompt_size, true, Info::Hint)
}
} else {
Ok(())
}
}
pub fn edit_insert_text(&mut self, text: &str) -> Result<()> {
if text.is_empty() {
return Ok(());
}
let cursor = self.line.pos();
self.line.insert_str(cursor, text, &mut self.changes);
self.refresh_line()
}
/// Exchange the char before cursor with the character at cursor.
pub fn edit_transpose_chars(&mut self) -> Result<()> {
self.changes.begin();
let succeed = self.line.transpose_chars(&mut self.changes);
self.changes.end();
if succeed {
self.refresh_line()
} else {
Ok(())
}
}
pub fn edit_move_to_prev_word(&mut self, word_def: Word, n: RepeatCount) -> Result<()> {
if self.line.move_to_prev_word(word_def, n) {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
pub fn edit_move_to_next_word(&mut self, at: At, word_def: Word, n: RepeatCount) -> Result<()> {
if self.line.move_to_next_word(at, word_def, n) {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
/// Moves the cursor to the same column in the line above
pub fn edit_move_line_up(&mut self, n: RepeatCount) -> Result<bool> {
if self.line.move_to_line_up(n, &self.layout) {
self.move_cursor(CmdKind::MoveCursor)?;
Ok(true)
} else {
Ok(false)
}
}
/// Moves the cursor to the same column in the line above
pub fn edit_move_line_down(&mut self, n: RepeatCount) -> Result<bool> {
if self.line.move_to_line_down(n, &self.layout) {
self.move_cursor(CmdKind::MoveCursor)?;
Ok(true)
} else {
Ok(false)
}
}
pub fn edit_move_to(&mut self, cs: CharSearch, n: RepeatCount) -> Result<()> {
if self.line.move_to(cs, n) {
self.move_cursor(CmdKind::MoveCursor)
} else {
Ok(())
}
}
pub fn edit_word(&mut self, a: WordAction) -> Result<()> {
self.changes.begin();
let succeed = self.line.edit_word(a, &mut self.changes);
self.changes.end();
if succeed {
self.refresh_line()
} else {
Ok(())
}
}
pub fn edit_transpose_words(&mut self, n: RepeatCount) -> Result<()> {
self.changes.begin();
let succeed = self.line.transpose_words(n, &mut self.changes);
self.changes.end();
if succeed {
self.refresh_line()
} else {
Ok(())
}
}
/// Substitute the currently edited line with the next or previous history
/// entry.
pub fn edit_history_next(&mut self, prev: bool) -> Result<()> {
let history = self.ctx.history;
if history.is_empty() {
return Ok(());
}
if self.ctx.history_index == history.len() {
if prev {
// Save the current edited line before overwriting it
self.backup();
} else {
return Ok(());
}
} else if self.ctx.history_index == 0 && prev {
return Ok(());
}
let (idx, dir) = if prev {
(self.ctx.history_index - 1, SearchDirection::Reverse)
} else {
self.ctx.history_index += 1;
(self.ctx.history_index, SearchDirection::Forward)
};
if idx < history.len() {
if let Some(r) = history.get(idx, dir)? {
let buf = r.entry;
self.ctx.history_index = r.idx;
self.changes.begin();
self.line.update(&buf, buf.len(), &mut self.changes);
self.changes.end();
} else {
return Ok(());
}
} else {
// Restore current edited line
self.restore();
}
self.refresh_line()
}
// Non-incremental, anchored search
pub fn edit_history_search(&mut self, dir: SearchDirection) -> Result<()> {
let history = self.ctx.history;
if history.is_empty() {
return self.out.beep();
}
if self.ctx.history_index == history.len() && dir == SearchDirection::Forward
|| self.ctx.history_index == 0 && dir == SearchDirection::Reverse
{
return self.out.beep();
}
if dir == SearchDirection::Reverse {
self.ctx.history_index -= 1;
} else {
self.ctx.history_index += 1;
}
if let Some(sr) = history.starts_with(
&self.line.as_str()[..self.line.pos()],
self.ctx.history_index,
dir,
)? {
self.ctx.history_index = sr.idx;
self.changes.begin();
self.line.update(&sr.entry, sr.pos, &mut self.changes);
self.changes.end();
self.refresh_line()
} else {
self.out.beep()
}
}
/// Substitute the currently edited line with the first/last history entry.
pub fn edit_history(&mut self, first: bool) -> Result<()> {
let history = self.ctx.history;
if history.is_empty() {
return Ok(());
}
if self.ctx.history_index == history.len() {
if first {
// Save the current edited line before overwriting it
self.backup();
} else {
return Ok(());
}
} else if self.ctx.history_index == 0 && first {
return Ok(());
}
if first {
if let Some(r) = history.get(0, SearchDirection::Forward)? {
let buf = r.entry;
self.ctx.history_index = r.idx;
self.changes.begin();
self.line.update(&buf, buf.len(), &mut self.changes);
self.changes.end();
} else {
return Ok(());
}
} else {
self.ctx.history_index = history.len();
// Restore current edited line
self.restore();
}
self.refresh_line()
}
/// Change the indentation of the lines covered by movement
pub fn edit_indent(&mut self, mvt: &Movement, amount: u8, dedent: bool) -> Result<()> {
if self.line.indent(mvt, amount, dedent, &mut self.changes) {
self.refresh_line()
} else {
Ok(())
}
}
}
#[cfg(test)]
pub fn init_state<'out, H: Helper>(
out: &'out mut <Terminal as Term>::Writer,
line: &str,
pos: usize,
helper: Option<&'out H>,
history: &'out crate::history::DefaultHistory,
) -> State<'out, 'static, H> {
State {
out,
prompt: "",
prompt_size: Position::default(),
line: LineBuffer::init(line, pos),
layout: Layout::default(),
saved_line_for_history: LineBuffer::with_capacity(100),
byte_buffer: [0; 4],
changes: Changeset::new(),
helper,
ctx: Context::new(history),
hint: Some(Box::new("hint".to_owned())),
highlight_char: false,
}
}
#[cfg(test)]
mod test {
use super::init_state;
use crate::history::{DefaultHistory, History};
use crate::tty::Sink;
#[test]
fn edit_history_next() {
let mut out = Sink::default();
let mut history = DefaultHistory::new();
history.add("line0").unwrap();
history.add("line1").unwrap();
let line = "current edited line";
let helper: Option<()> = None;
let mut s = init_state(&mut out, line, 6, helper.as_ref(), &history);
s.ctx.history_index = history.len();
for _ in 0..2 {
s.edit_history_next(false).unwrap();
assert_eq!(line, s.line.as_str());
}
s.edit_history_next(true).unwrap();
assert_eq!(line, s.saved_line_for_history.as_str());
assert_eq!(1, s.ctx.history_index);
assert_eq!("line1", s.line.as_str());
for _ in 0..2 {
s.edit_history_next(true).unwrap();
assert_eq!(line, s.saved_line_for_history.as_str());
assert_eq!(0, s.ctx.history_index);
assert_eq!("line0", s.line.as_str());
}
s.edit_history_next(false).unwrap();
assert_eq!(line, s.saved_line_for_history.as_str());
assert_eq!(1, s.ctx.history_index);
assert_eq!("line1", s.line.as_str());
s.edit_history_next(false).unwrap();
// assert_eq!(line, s.saved_line_for_history);
assert_eq!(2, s.ctx.history_index);
assert_eq!(line, s.line.as_str());
}
}
|