Skip to content

Commit

Permalink
Merge pull request #823 from gwenn/reduce_size
Browse files Browse the repository at this point in the history
Reduce size
  • Loading branch information
gwenn authored Dec 14, 2024
2 parents 5b92355 + ffb94cc commit 727a414
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 72 deletions.
20 changes: 10 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ pub struct Config {
/// Whether to use stdio or not
behavior: Behavior,
/// Horizontal space taken by a tab.
tab_stop: usize,
tab_stop: u8,
/// Indentation size for indent/dedent commands
indent_size: usize,
indent_size: u8,
/// Check if cursor position is at leftmost before displaying prompt
check_cursor_position: bool,
/// Bracketed paste on unix platform
Expand Down Expand Up @@ -160,11 +160,11 @@ impl Config {
///
/// By default, 8.
#[must_use]
pub fn tab_stop(&self) -> usize {
pub fn tab_stop(&self) -> u8 {
self.tab_stop
}

pub(crate) fn set_tab_stop(&mut self, tab_stop: usize) {
pub(crate) fn set_tab_stop(&mut self, tab_stop: u8) {
self.tab_stop = tab_stop;
}

Expand All @@ -180,11 +180,11 @@ impl Config {
///
/// By default, 2.
#[must_use]
pub fn indent_size(&self) -> usize {
pub fn indent_size(&self) -> u8 {
self.indent_size
}

pub(crate) fn set_indent_size(&mut self, indent_size: usize) {
pub(crate) fn set_indent_size(&mut self, indent_size: u8) {
self.indent_size = indent_size;
}

Expand Down Expand Up @@ -433,7 +433,7 @@ impl Builder {
///
/// By default, `8`
#[must_use]
pub fn tab_stop(mut self, tab_stop: usize) -> Self {
pub fn tab_stop(mut self, tab_stop: u8) -> Self {
self.set_tab_stop(tab_stop);
self
}
Expand All @@ -451,7 +451,7 @@ impl Builder {
///
/// By default, `2`
#[must_use]
pub fn indent_size(mut self, indent_size: usize) -> Self {
pub fn indent_size(mut self, indent_size: u8) -> Self {
self.set_indent_size(indent_size);
self
}
Expand Down Expand Up @@ -568,7 +568,7 @@ pub trait Configurer {
/// Horizontal space taken by a tab.
///
/// By default, `8`
fn set_tab_stop(&mut self, tab_stop: usize) {
fn set_tab_stop(&mut self, tab_stop: u8) {
self.config_mut().set_tab_stop(tab_stop);
}

Expand All @@ -581,7 +581,7 @@ pub trait Configurer {
/// Indentation size for indent/dedent commands
///
/// By default, `2`
fn set_indent_size(&mut self, size: usize) {
fn set_indent_size(&mut self, size: u8) {
self.config_mut().set_indent_size(size);
}

Expand Down
9 changes: 4 additions & 5 deletions src/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use log::debug;
use std::fmt;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthChar;

use super::{Context, Helper, Result};
use crate::error::ReadlineError;
Expand All @@ -12,7 +11,7 @@ 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::{Layout, Position};
use crate::layout::{cwidh, Layout, Position};
use crate::line_buffer::{
ChangeListener, DeleteListener, Direction, LineBuffer, NoListener, WordAction, MAX_LINE,
};
Expand Down Expand Up @@ -353,7 +352,7 @@ impl<H: Helper> State<'_, '_, H> {
let prompt_size = self.prompt_size;
let no_previous_hint = self.hint.is_none();
self.hint();
let width = ch.width().unwrap_or(0);
let width = cwidh(ch);
if n == 1
&& width != 0 // Ctrl-V + \t or \n ...
&& self.layout.cursor.col + width < self.out.get_columns()
Expand Down Expand Up @@ -382,7 +381,7 @@ impl<H: Helper> State<'_, '_, H> {
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 = chars.graphemes(true).count();
let count = RepeatCount::try_from(chars.graphemes(true).count()).unwrap();
self.line.insert(ch, count, &mut self.changes);
self.line.move_backward(1);
true
Expand Down Expand Up @@ -732,7 +731,7 @@ impl<H: Helper> State<'_, '_, H> {
}

/// Change the indentation of the lines covered by movement
pub fn edit_indent(&mut self, mvt: &Movement, amount: usize, dedent: bool) -> Result<()> {
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 {
Expand Down
7 changes: 5 additions & 2 deletions src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{Config, EditMode};
use crate::{Event, EventContext, EventHandler};

/// The number of times one command should be repeated.
pub type RepeatCount = usize;
pub type RepeatCount = u16;

/// Commands
#[derive(Debug, Clone, Eq, PartialEq)]
Expand Down Expand Up @@ -183,7 +183,10 @@ impl Cmd {
let last_insert = wrt.last_insert();
if let Movement::ForwardChar(0) = mvt {
Self::Replace(
Movement::ForwardChar(last_insert.as_ref().map_or(0, String::len)),
Movement::ForwardChar(
RepeatCount::try_from(last_insert.as_ref().map_or(0, String::len))
.unwrap(),
),
last_insert,
)
} else {
Expand Down
16 changes: 14 additions & 2 deletions src/layout.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
use std::cmp::Ordering;

/// Height, width
pub type Unit = u16;

pub(crate) fn cwidh(c: char) -> Unit {
use unicode_width::UnicodeWidthChar;
Unit::try_from(c.width().unwrap_or(0)).unwrap()
}
pub(crate) fn swidth(s: &str) -> Unit {
use unicode_width::UnicodeWidthStr;
Unit::try_from(s.width()).unwrap()
}

#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct Position {
pub col: usize, // The leftmost column is number 0.
pub row: usize, // The highest row is number 0.
pub col: Unit, // The leftmost column is number 0.
pub row: Unit, // The highest row is number 0.
}

impl PartialOrd for Position {
Expand Down
19 changes: 10 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ use log::debug;
#[cfg(feature = "derive")]
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
pub use rustyline_derive::{Completer, Helper, Highlighter, Hinter, Validator};
use unicode_width::UnicodeWidthStr;

use crate::tty::{Buffer, RawMode, RawReader, Renderer, Term, Terminal};

Expand All @@ -66,6 +65,7 @@ pub use crate::keymap::{Anchor, At, CharSearch, Cmd, InputMode, Movement, Repeat
use crate::keymap::{Bindings, InputState, Refresher};
pub use crate::keys::{KeyCode, KeyEvent, Modifiers};
use crate::kill_ring::KillRing;
use crate::layout::{swidth, Unit};
pub use crate::tty::ExternalPrinter;
pub use crate::undo::Changeset;
use crate::validate::Validator;
Expand Down Expand Up @@ -292,15 +292,16 @@ fn page_completions<C: Candidate, H: Helper>(
cols,
candidates
.iter()
.map(|s| s.display().width())
.map(|s| swidth(s.display()))
.max()
.unwrap()
+ min_col_pad,
);
let num_cols = cols / max_width;
let nbc = u16::try_from(candidates.len()).unwrap();

let mut pause_row = s.out.get_rows() - 1;
let num_rows = candidates.len().div_ceil(num_cols);
let num_rows = nbc.div_ceil(num_cols);
let mut ab = String::new();
for row in 0..num_rows {
if row == pause_row {
Expand Down Expand Up @@ -334,15 +335,15 @@ fn page_completions<C: Candidate, H: Helper>(
ab.clear();
for col in 0..num_cols {
let i = (col * num_rows) + row;
if i < candidates.len() {
let candidate = &candidates[i].display();
let width = candidate.width();
if i < nbc {
let candidate = &candidates[i as usize].display();
let width = swidth(candidate);
if let Some(highlighter) = s.highlighter() {
ab.push_str(&highlighter.highlight_candidate(candidate, CompletionType::List));
} else {
ab.push_str(candidate);
}
if ((col + 1) * num_rows) + row < candidates.len() {
if ((col + 1) * num_rows) + row < nbc {
for _ in width..max_width {
ab.push(' ');
}
Expand Down Expand Up @@ -776,7 +777,7 @@ impl<H: Helper, I: History> Editor<H, I> {
cmd,
Cmd::AcceptLine | Cmd::Newline | Cmd::AcceptOrInsertLine { .. }
) {
self.term.cursor = s.layout.cursor.col;
self.term.cursor = s.layout.cursor.col as usize;
}

// Execute things can be done solely on a state object
Expand Down Expand Up @@ -894,7 +895,7 @@ impl<H: Helper, I: History> Editor<H, I> {

/// If output stream is a tty, this function returns its width and height as
/// a number of characters.
pub fn dimensions(&mut self) -> Option<(usize, usize)> {
pub fn dimensions(&mut self) -> Option<(Unit, Unit)> {
if self.term.is_output_tty() {
let out = self.term.create_writer();
Some((out.get_columns(), out.get_rows()))
Expand Down
10 changes: 7 additions & 3 deletions src/line_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ impl LineBuffer {
}
self.buf[self.pos..]
.grapheme_indices(true)
.take(n)
.take(usize::from(n))
.last()
.map(|(i, s)| i + self.pos + s.len())
}
Expand All @@ -216,7 +216,7 @@ impl LineBuffer {
self.buf[..self.pos]
.grapheme_indices(true)
.rev()
.take(n)
.take(usize::from(n))
.last()
.map(|(i, _)| i)
}
Expand All @@ -231,6 +231,7 @@ impl LineBuffer {
n: RepeatCount,
cl: &mut C,
) -> Option<bool> {
let n = usize::from(n);
let shift = ch.len_utf8() * n;
if self.must_truncate(self.buf.len() + shift) {
return None;
Expand All @@ -257,6 +258,7 @@ impl LineBuffer {
n: RepeatCount,
cl: &mut C,
) -> Option<bool> {
let n = usize::from(n);
let shift = text.len() * n;
if text.is_empty() || self.must_truncate(self.buf.len() + shift) {
return None;
Expand Down Expand Up @@ -682,6 +684,7 @@ impl LineBuffer {
}

fn search_char_pos(&self, cs: CharSearch, n: RepeatCount) -> Option<usize> {
let n = usize::from(n);
let mut shift = 0;
let search_result = match cs {
CharSearch::Backward(c) | CharSearch::BackwardAfter(c) => self.buf[..self.pos]
Expand Down Expand Up @@ -1083,7 +1086,7 @@ impl LineBuffer {
pub fn indent<C: ChangeListener>(
&mut self,
mvt: &Movement,
amount: usize,
amount: u8,
dedent: bool,
cl: &mut C,
) -> bool {
Expand All @@ -1108,6 +1111,7 @@ impl LineBuffer {
Movement::LineUp(n) => self.n_lines_up(n),
Movement::LineDown(n) => self.n_lines_down(n),
};
let amount = usize::from(amount);
let (start, end) = pair.unwrap_or((self.pos, self.pos));
let start = self.buf[..start].rfind('\n').map_or(0, |pos| pos + 1);
let end = self.buf[end..]
Expand Down
14 changes: 6 additions & 8 deletions src/tty/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
//! This module implements and describes common TTY methods & traits
use unicode_width::UnicodeWidthStr;

use crate::config::{Behavior, BellStyle, ColorMode, Config};
use crate::highlight::Highlighter;
use crate::keys::KeyEvent;
use crate::layout::{Layout, Position};
use crate::layout::{swidth, Layout, Position, Unit};
use crate::line_buffer::LineBuffer;
use crate::{Cmd, Result};

Expand Down Expand Up @@ -108,9 +106,9 @@ pub trait Renderer {
/// Update the number of columns/rows in the current terminal.
fn update_size(&mut self);
/// Get the number of columns in the current terminal.
fn get_columns(&self) -> usize;
fn get_columns(&self) -> Unit;
/// Get the number of rows in the current terminal.
fn get_rows(&self) -> usize;
fn get_rows(&self) -> Unit;
/// Check if output supports colors.
fn colors_enabled(&self) -> bool;

Expand All @@ -119,7 +117,7 @@ pub trait Renderer {
}

// ignore ANSI escape sequence
fn width(s: &str, esc_seq: &mut u8) -> usize {
fn width(s: &str, esc_seq: &mut u8) -> Unit {
if *esc_seq == 1 {
if s == "[" {
// CSI
Expand All @@ -145,7 +143,7 @@ fn width(s: &str, esc_seq: &mut u8) -> usize {
} else if s == "\n" {
0
} else {
s.width()
swidth(s)
}
}

Expand All @@ -168,7 +166,7 @@ pub trait Term {
fn new(
color_mode: ColorMode,
behavior: Behavior,
tab_stop: usize,
tab_stop: u8,
bell_style: BellStyle,
enable_bracketed_paste: bool,
enable_signals: bool,
Expand Down
10 changes: 5 additions & 5 deletions src/tty/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::config::{Behavior, BellStyle, ColorMode, Config};
use crate::error::ReadlineError;
use crate::highlight::Highlighter;
use crate::keys::KeyEvent;
use crate::layout::{Layout, Position};
use crate::layout::{Layout, Position, Unit};
use crate::line_buffer::LineBuffer;
use crate::{Cmd, Result};

Expand Down Expand Up @@ -114,7 +114,7 @@ impl Renderer for Sink {

fn calculate_position(&self, s: &str, orig: Position) -> Position {
let mut pos = orig;
pos.col += s.len();
pos.col += u16::try_from(s.len()).unwrap();
pos
}

Expand All @@ -136,11 +136,11 @@ impl Renderer for Sink {

fn update_size(&mut self) {}

fn get_columns(&self) -> usize {
fn get_columns(&self) -> Unit {
80
}

fn get_rows(&self) -> usize {
fn get_rows(&self) -> Unit {
24
}

Expand Down Expand Up @@ -183,7 +183,7 @@ impl Term for DummyTerminal {
fn new(
color_mode: ColorMode,
_behavior: Behavior,
_tab_stop: usize,
_tab_stop: u8,
bell_style: BellStyle,
_enable_bracketed_paste: bool,
_enable_signals: bool,
Expand Down
Loading

0 comments on commit 727a414

Please sign in to comment.