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
use std::fmt;
/// Several lines of output that travel together.
///
/// Every multi-line component in tinsel returns a `Block` ([`Table`](crate::Table),
/// [`Tree`](crate::Tree), [`Card`](crate::Card), [`callout`](crate::callout), …), so they all
/// work the same way: print it, `println!` it, or take its lines and arrange them yourself.
///
/// ```
/// use tinsel::{Block, pairs};
///
/// let block: Block = pairs(&[("region", "eu-west-2"), ("memory", "512 MB")]);
/// block.print(); // print it
/// println!("{block}"); // or format it
/// assert_eq!(block.len(), 2); // or look inside
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Block {
lines: Vec<String>,
}
impl Block {
/// An empty block.
pub fn new() -> Self {
Self::default()
}
/// Add a line to the end.
pub fn push(&mut self, line: impl Into<String>) {
self.lines.push(line.into());
}
/// Add every line of another block to the end.
pub fn extend(&mut self, other: Block) {
self.lines.extend(other.lines);
}
/// The lines, still styled.
pub fn lines(&self) -> &[String] {
&self.lines
}
/// The lines, owned.
pub fn into_lines(self) -> Vec<String> {
self.lines
}
/// How many lines there are.
pub fn len(&self) -> usize {
self.lines.len()
}
/// Whether there are no lines at all.
pub fn is_empty(&self) -> bool {
self.lines.is_empty()
}
/// The text without any colour or styling, lines joined with `\n`. Handy in tests.
pub fn plain(&self) -> String {
crate::text::strip_ansi(&self.to_string())
}
/// Print every line to stdout (or the [`Target`](crate::Target)). With [`Output::Json`](crate::Output::Json) the block is
/// one `{"event":"block","lines":[…]}` event instead.
pub fn print(&self) {
if crate::output::json() {
return self.emit();
}
crate::output::write(&self.lines.iter().map(|l| format!("{l}\n")).collect::<String>());
}
/// Print every line to stderr (or, as JSON, to stdout like everything else).
pub fn eprint(&self) {
if crate::output::json() {
return self.emit();
}
for line in &self.lines {
eprintln!("{line}");
}
}
}
impl Block {
/// Print the block through a pager (`$PAGER`, or `less`) if it's taller than the
/// terminal, so it can be scrolled and searched; otherwise just print it. Colours are
/// kept (`less -R`).
///
/// ```no_run
/// tinsel::markdown(include_str!("../CHANGELOG.md")).page();
/// ```
pub fn page(&self) {
use std::io::{IsTerminal, Write};
let paged = crate::output::target() == crate::Target::Stdout && std::io::stdout().is_terminal();
if crate::output::json() || !paged || self.len() < crate::term::height() {
return self.print();
}
let pager = std::env::var("PAGER").ok().filter(|p| !p.trim().is_empty());
let default = if cfg!(windows) { "more" } else { "less" };
let command = pager.unwrap_or_else(|| default.to_string());
let mut words = command.split_whitespace();
let program = words.next().unwrap_or(default);
let mut cmd = std::process::Command::new(program);
cmd.args(words).stdin(std::process::Stdio::piped());
if program.ends_with("less") && std::env::var_os("LESS").is_none() {
// colours, quit if it fits after all, and leave the text on screen afterwards
cmd.env("LESS", "-RFX");
}
let Ok(mut child) = cmd.spawn() else {
return self.print();
};
if let Some(mut stdin) = child.stdin.take() {
// the reader quitting early closes the pipe; that's fine
let _ = stdin.write_all(format!("{self}\n").as_bytes());
}
let _ = child.wait();
}
/// The block as a web page that looks just like it does in the terminal, colours and all,
/// as [`Frame::html`](crate::app::Frame::html) draws a frame. Draw the block in colour
/// (see [`set_color_mode`](crate::set_color_mode)) to see them.
///
/// ```
/// let page = tinsel::pairs(&[("url", "https://example.com/?a=1&b=2")]).html();
/// assert!(page.contains("a=1&b=2"));
/// ```
pub fn html(&self) -> String {
self.frame().html()
}
/// The block as a `<pre>` element, styled inline so it can go anywhere in a page. See
/// [`html`](Block::html).
///
/// ```
/// let pre = tinsel::Block::from(vec!["<b>".to_string()]).html_pre();
/// assert!(pre.ends_with("<b></pre>"));
/// ```
pub fn html_pre(&self) -> String {
self.frame().html_pre()
}
/// The block drawn into a frame just big enough for it.
fn frame(&self) -> crate::app::Frame {
let width = self.lines.iter().map(|l| crate::text::width(l)).max().unwrap_or(0);
let mut frame = crate::app::Frame::new(width, self.len());
frame.lines(frame.area(), self);
frame
}
fn emit(&self) {
let lines: Vec<String> = self.lines.iter().map(|l| crate::text::strip_ansi(l)).collect();
crate::output::emit("block", &[("lines", crate::output::Val::List(&lines))]);
}
}
impl fmt::Display for Block {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.lines.join("\n"))
}
}
impl From<Vec<String>> for Block {
fn from(lines: Vec<String>) -> Self {
Block { lines }
}
}
impl FromIterator<String> for Block {
fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
Block {
lines: iter.into_iter().collect(),
}
}
}
impl IntoIterator for Block {
type Item = String;
type IntoIter = std::vec::IntoIter<String>;
fn into_iter(self) -> Self::IntoIter {
self.lines.into_iter()
}
}