use std::borrow::Cow;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
#[must_use]
pub fn cells(text: &str) -> usize {
text.width()
}
fn put(buf: &mut Buffer, x: u16, y: u16, text: &str, width: usize, style: Style) {
if buf.area().contains(ratatui::layout::Position { x, y }) {
buf.set_stringn(x, y, text, width, style);
}
}
fn fitting(word: &str, width: usize, first: bool) -> (usize, usize) {
let mut used = 0;
let mut end = 0;
for grapheme in word.graphemes(true) {
let wide = grapheme.width();
if used + wide > width && (end > 0 || !first) {
break;
}
used += wide;
end += grapheme.len();
}
(end, used)
}
struct Placed<'s> {
row: usize,
column: usize,
text: &'s str,
style: Style,
}
fn walk<'s>(spans: &'s [Span<'_>], width: u16, mut place: impl FnMut(Placed<'s>)) -> usize {
if width == 0 {
return 0;
}
let mut wrap = Wrap {
width: width as usize,
row: 0,
column: 0,
placed: false,
separator: None,
};
let mut word: Vec<(&'s str, Style)> = Vec::new();
let mut wide = 0usize;
for span in spans {
let mut rest: &'s str = span.content.as_ref();
while !rest.is_empty() {
let gap = rest
.find(|c: char| !c.is_whitespace())
.unwrap_or(rest.len());
if gap > 0 {
wrap.word(&word, wide, &mut place);
word.clear();
wide = 0;
let breaks = rest[..gap].matches('\n').count();
if breaks > 0 {
wrap.row += breaks;
wrap.column = 0;
}
wrap.separator = Some(span.style);
rest = &rest[gap..];
continue;
}
let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
let (piece, after) = rest.split_at(end);
rest = after;
word.push((piece, span.style));
wide += cells(piece);
}
}
wrap.word(&word, wide, &mut place);
if wrap.row == 0 && !wrap.placed {
0
} else {
wrap.row + 1
}
}
struct Wrap {
width: usize,
row: usize,
column: usize,
placed: bool,
separator: Option<Style>,
}
impl Wrap {
fn word<'s>(
&mut self,
pieces: &[(&'s str, Style)],
mut wide: usize,
place: &mut impl FnMut(Placed<'s>),
) {
let Some((&(mut head, mut style), mut tail)) = pieces.split_first() else {
return;
};
while wide > self.width {
if self.column > 0 {
self.row += 1;
self.column = 0;
}
if tail.is_empty() && fitting(head, self.width, true).0 == head.len() {
break;
}
let mut used = 0usize;
loop {
let (cut, taken) = fitting(head, self.width - used, used == 0);
if cut > 0 {
place(Placed {
row: self.row,
column: used,
text: &head[..cut],
style,
});
used += taken;
wide = wide.saturating_sub(taken);
head = &head[cut..];
}
if !head.is_empty() || used >= self.width {
break;
}
let Some((&(next, next_style), rest)) = tail.split_first() else {
break;
};
head = next;
style = next_style;
tail = rest;
}
self.row += 1;
if head.is_empty() {
let Some((&(next, next_style), rest)) = tail.split_first() else {
return;
};
head = next;
style = next_style;
tail = rest;
}
}
let room = self.width.saturating_sub(self.column);
let wanted = wide + usize::from(self.column > 0);
if wanted > room && self.column > 0 {
self.row += 1;
self.column = 0;
}
if self.column > 0 {
place(Placed {
row: self.row,
column: self.column,
text: " ",
style: self.separator.unwrap_or(style),
});
self.column += 1;
}
self.separator = None;
for (text, style) in std::iter::once((head, style)).chain(tail.iter().copied()) {
place(Placed {
row: self.row,
column: self.column,
text,
style,
});
self.column += cells(text);
}
self.placed = true;
}
}
pub fn wrap_spans(spans: &[Span<'_>], width: u16) -> Vec<Line<'static>> {
let mut lines: Vec<Vec<Span<'static>>> = Vec::new();
let rows = walk(spans, width, |placed| {
if lines.len() <= placed.row {
lines.resize_with(placed.row + 1, Vec::new);
}
lines[placed.row].push(Span::styled(placed.text.to_string(), placed.style));
});
lines.resize_with(rows, Vec::new);
lines.into_iter().map(Line::from).collect()
}
pub fn wrap(text: &str, width: u16) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
let spans = [Span::raw(text)];
let rows = walk(&spans, width, |placed| {
if lines.len() <= placed.row {
lines.resize_with(placed.row + 1, String::new);
}
lines[placed.row].push_str(placed.text);
});
lines.resize_with(rows, String::new);
lines
}
pub fn height(text: &str, width: u16) -> u16 {
spans_height(&[Span::raw(text)], width)
}
pub fn spans_height(spans: &[Span<'_>], width: u16) -> u16 {
u16::try_from(walk(spans, width, |_| {})).unwrap_or(u16::MAX)
}
pub fn draw(text: &str, style: Style, area: Rect, buf: &mut Buffer) -> u16 {
draw_spans(&[Span::styled(text, style)], area, buf)
}
pub fn draw_spans(spans: &[Span<'_>], area: Rect, buf: &mut Buffer) -> u16 {
let rows = walk(spans, area.width, |placed| {
let (Ok(row), Ok(column)) = (u16::try_from(placed.row), u16::try_from(placed.column))
else {
return;
};
let room = area.width.saturating_sub(column) as usize;
if row >= area.height || room == 0 {
return;
}
put(
buf,
area.x.saturating_add(column),
area.y.saturating_add(row),
placed.text,
room,
placed.style,
);
});
u16::try_from(rows).unwrap_or(u16::MAX).min(area.height)
}
pub fn draw_line(line: &Line<'_>, area: Rect, buf: &mut Buffer) -> u16 {
draw_spans(&line.spans, area, buf)
}
pub fn line_height(line: &Line<'_>, width: u16) -> u16 {
spans_height(&line.spans, width)
}
fn is_bidi(c: char) -> bool {
matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
}
pub(crate) fn sanitise(line: Line<'_>) -> Line<'_> {
let mut line = line;
for span in &mut line.spans {
if span.content.chars().any(is_bidi) {
span.content = Cow::Owned(span.content.chars().filter(|c| !is_bidi(*c)).collect());
}
}
line
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::style::Modifier;
#[test]
fn a_paragraph_wraps_on_words_and_counts_the_rows_it_took() {
assert_eq!(wrap("the quick brown fox", 10), ["the quick", "brown fox"]);
assert_eq!(height("the quick brown fox", 10), 2);
}
#[test]
fn nothing_to_say_costs_no_rows_rather_than_one_blank_one() {
assert_eq!(height("", 10), 0);
let found = wrap("", 10);
assert!(found.is_empty(), "{found:?}");
let found = wrap("anything", 0);
assert!(found.is_empty(), "{found:?}");
}
#[test]
fn an_authored_break_is_a_break() {
assert_eq!(wrap("one\ntwo", 20), ["one", "two"]);
}
#[test]
fn a_word_wider_than_the_region_is_cut_rather_than_overflowed() {
assert_eq!(
wrap("supercalifragilistic", 6),
["superc", "alifra", "gilist", "ic"]
);
}
#[test]
fn the_space_between_two_runs_belongs_to_the_run_that_held_it() {
let struck = Style::new().add_modifier(Modifier::CROSSED_OUT);
let spans = [Span::raw("lean "), Span::styled("gone", struck)];
let lines = wrap_spans(&spans, 20);
assert_eq!(lines.len(), 1);
let separator = lines[0]
.spans
.iter()
.find(|span| span.content.as_ref() == " ")
.expect("a separator between the two words");
assert!(!separator.style.add_modifier.contains(Modifier::CROSSED_OUT));
}
#[test]
fn a_drawing_stops_at_the_bottom_of_the_area_it_was_given() {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 2));
let used = draw(
"the quick brown fox jumps over",
Style::new(),
buf.area,
&mut buf,
);
assert_eq!(used, 2);
}
#[test]
fn a_wide_glyph_takes_two_cells_and_nothing_is_lost() {
let lines = wrap("日本語テã‚スト", 8);
assert_eq!(lines, ["日本語テ", "ã‚スト"]);
assert_eq!(height("日本語テã‚スト", 8), 2);
assert_eq!(lines.concat(), "日本語テã‚スト");
let area = Rect::new(0, 0, 8, 2);
let mut buf = Buffer::empty(area);
assert_eq!(draw("日本語テã‚スト", Style::default(), area, &mut buf), 2);
let row = |y: u16| {
(0..8)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
};
assert_eq!(row(0).replace(' ', ""), "日本語テ");
assert_eq!(row(1).replace(' ', ""), "ã‚スト");
}
#[test]
fn a_glyph_wider_than_the_line_is_taken_alone_rather_than_looped_on() {
assert_eq!(wrap("è¨å®š", 1), ["è¨", "定"]);
}
#[test]
fn a_word_after_a_glyph_wider_than_the_line_starts_a_new_one() {
assert_eq!(wrap("\u{4e2d} a", 1), ["\u{4e2d}", "a"]);
assert_eq!(height("\u{4e2d} a", 1), 2);
assert_eq!(
wrap("\u{4e2d}\u{6587} ab", 1),
["\u{4e2d}", "\u{6587}", "a", "b"]
);
}
#[test]
fn an_accent_is_never_cut_from_its_letter() {
let accented = "cafe\u{301}s";
assert_eq!(wrap(accented, 4), ["cafe\u{301}", "s"]);
}
#[test]
fn a_grapheme_cluster_is_cut_as_a_unit_and_not_through_its_chars() {
let hearts = "\u{2764}\u{fe0f}\u{2764}\u{fe0f}\u{2764}\u{fe0f}";
assert_eq!(
wrap(hearts, 4),
["\u{2764}\u{fe0f}\u{2764}\u{fe0f}", "\u{2764}\u{fe0f}"]
);
let keys = "1\u{fe0f}\u{20e3}2\u{fe0f}\u{20e3}3\u{fe0f}\u{20e3}";
assert_eq!(
wrap(keys, 3),
[
"1\u{fe0f}\u{20e3}",
"2\u{fe0f}\u{20e3}",
"3\u{fe0f}\u{20e3}"
]
);
for line in wrap(keys, 3) {
assert!(cells(&line) <= 3, "line {line:?} is wider than the region");
}
}
#[test]
fn a_zwj_family_and_a_flag_pair_are_not_split_between_their_chars() {
let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}";
let two = format!("{family}{family}");
assert_eq!(wrap(&two, 3), [family, family]);
assert_eq!(wrap(family, 1), [family]);
assert_eq!(
wrap("\u{1f1fa}\u{1f1f8}\u{1f1ec}\u{1f1e7}", 3),
["\u{1f1fa}\u{1f1f8}", "\u{1f1ec}\u{1f1e7}"]
);
}
#[test]
fn spans_after_a_wide_glyph_start_where_it_ends() {
let area = Rect::new(0, 0, 10, 1);
let mut buf = Buffer::empty(area);
let spans = [Span::raw("è¨å®š"), Span::raw("x")];
draw_spans(&spans, area, &mut buf);
assert_eq!(buf[(4, 0)].symbol(), "x");
let spans = [Span::raw("è¨å®š "), Span::raw("y")];
draw_spans(&spans, area, &mut buf);
assert_eq!(buf[(5, 0)].symbol(), "y");
}
#[test]
fn a_word_across_spans_wraps_as_one_word_and_is_cut_as_one() {
let spans = [
Span::raw("abc "),
Span::raw("["),
Span::raw("ok"),
Span::raw("]"),
];
let lines: Vec<String> = wrap_spans(&spans, 5)
.iter()
.map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect())
.collect();
assert_eq!(lines, ["abc", "[ok]"]);
let bold = Style::new().add_modifier(Modifier::BOLD);
let spans = [Span::raw("ab"), Span::styled("cdef", bold), Span::raw("g")];
let lines = wrap_spans(&spans, 3);
let text: Vec<String> = lines
.iter()
.map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect())
.collect();
assert_eq!(text, ["abc", "def", "g"]);
assert_eq!(spans_height(&spans, 3), 3);
assert_eq!(lines[1].spans[0].style, bold);
assert_eq!(lines[2].spans[0].style, Style::new());
}
#[test]
fn drawing_outside_the_buffer_loses_the_overshoot_and_not_the_process() {
let mut buf = Buffer::empty(Rect::new(0, 0, 4, 2));
for area in [
Rect::new(0, 1, 4, 5),
Rect::new(3, 0, 10, 1),
Rect::new(9, 9, 4, 4),
] {
draw("one two three", Style::default(), area, &mut buf);
draw_spans(&[Span::raw("one two")], area, &mut buf);
}
}
#[test]
fn a_bidi_override_is_stripped_from_every_span() {
let line = sanitise(Line::from("x\u{202e}"));
assert_eq!(line.spans[0].content.as_ref(), "x");
let line = sanitise(Line::from(vec![
Span::raw("a\u{202a}b"),
Span::raw("c\u{2069}d"),
]));
assert_eq!(line.spans[0].content.as_ref(), "ab");
assert_eq!(line.spans[1].content.as_ref(), "cd");
}
#[test]
fn a_line_without_bidi_controls_passes_through_unchanged() {
let line = sanitise(Line::from("plain"));
assert!(matches!(
line.spans[0].content,
std::borrow::Cow::Borrowed("plain")
));
}
#[test]
fn repro_adjoining_spans_get_separator() {
let line = Line::from(vec![Span::raw("["), Span::raw("ok"), Span::raw("]")]);
let area = Rect::new(0, 0, 10, 1);
let mut buf = Buffer::empty(area);
assert_eq!(draw_line(&line, area, &mut buf), 1);
let row: String = (0..10).map(|x| buf[(x, 0)].symbol().to_string()).collect();
assert_eq!(row.trim_end(), "[ok]");
assert_eq!(cells(row.trim_end()), line.width());
let bold = Style::new().add_modifier(Modifier::BOLD);
let line = Line::from(vec![
Span::raw("["),
Span::styled("ok", bold),
Span::raw("]"),
]);
let mut buf = Buffer::empty(area);
draw_line(&line, area, &mut buf);
assert!(buf[(1, 0)].modifier.contains(Modifier::BOLD));
assert!(!buf[(0, 0)].modifier.contains(Modifier::BOLD));
assert!(!buf[(3, 0)].modifier.contains(Modifier::BOLD));
}
}