helix/helix-view/src/info.rs

81 lines
2.1 KiB
Rust
Raw Normal View History

use crate::register::Registers;
use helix_core::unicode::width::UnicodeWidthStr;
use std::fmt::Write;
2021-06-19 23:54:37 +08:00
#[derive(Debug)]
/// Info box used in editor. Rendering logic will be in other crate.
pub struct Info {
/// Title shown at top.
pub title: String,
/// Text body, should contain newlines.
2021-06-19 23:54:37 +08:00
pub text: String,
/// Body width.
pub width: u16,
/// Body height.
pub height: u16,
}
impl Info {
pub fn new<T, U>(title: &str, body: &[(T, U)]) -> Self
where
T: AsRef<str>,
U: AsRef<str>,
{
2021-11-05 02:33:31 +08:00
if body.is_empty() {
return Self {
title: title.to_string(),
height: 1,
width: title.len() as u16,
text: "".to_string(),
};
}
let item_width = body
.iter()
.map(|(item, _)| item.as_ref().width())
.max()
.unwrap();
2021-06-19 23:54:37 +08:00
let mut text = String::new();
2023-07-12 12:23:03 +08:00
let mut height = 0;
for (item, desc) in body {
2023-07-12 12:23:03 +08:00
let mut line_iter = desc.as_ref().lines();
if let Some(first_line) = line_iter.next() {
let _ = writeln!(
text,
"{:width$} {}",
item.as_ref(),
first_line,
width = item_width
);
height += 1;
}
for line in line_iter {
let _ = writeln!(text, "{:width$} {}", "", line, width = item_width);
height += 1;
}
2021-06-19 23:54:37 +08:00
}
Self {
title: title.to_string(),
2023-08-24 00:29:42 +08:00
width: text.lines().map(|l| l.width()).max().unwrap_or(body.len()) as u16,
2023-07-12 12:23:03 +08:00
height,
2021-06-19 23:54:37 +08:00
text,
}
}
2021-11-05 02:33:31 +08:00
pub fn from_registers(registers: &Registers) -> Self {
let body: Vec<_> = registers
.iter_preview()
.map(|(ch, preview)| (ch.to_string(), preview))
2021-11-05 02:33:31 +08:00
.collect();
let mut infobox = Self::new("Registers", &body);
2021-11-05 02:33:31 +08:00
infobox.width = 30; // copied content could be very long
infobox
}
2021-06-19 23:54:37 +08:00
}