tui_markup/generator/ansi/mod.rs
1//! Generator for asni terminal string.
2
3mod span;
4mod tag;
5
6use ansi_term::{ANSIString, Style};
7
8use super::{
9 helper::{flatten, CustomTagParser, GeneratorInfallible, NoopCustomTagParser},
10 Generator,
11};
12
13pub use tag::ANSITermTagConvertor;
14
15/// Generator for ansi terminal strings.
16///
17/// See [docs/ansi-tags.ebnf] for supported tags.
18///
19/// ## Example
20///
21/// ```
22/// use ansi_term::ANSIStrings;
23/// use tui_markup::{compile, generator::ANSIStringsGenerator};
24///
25/// let result = compile::<ANSIStringsGenerator>("I have a <green green text>").unwrap();
26///
27/// println!("{}", ANSIStrings(&result));
28/// ```
29///
30/// ### With custom tags
31///
32/// ```
33/// use ansi_term::{ANSIStrings, Style, Color};
34/// use tui_markup::{compile_with, generator::ANSIStringsGenerator};
35///
36/// let gen = ANSIStringsGenerator::new(|tag: &str| match tag {
37/// "keyboard" => Some(Style::default().fg(Color::Green).on(Color::White).bold()),
38/// _ => None,
39/// });
40///
41/// let result = compile_with("Press <keyboard W> to move up", gen).unwrap();
42///
43/// println!("{}", ANSIStrings(&result));
44/// ```
45///
46/// ## Show output
47///
48/// Like example above, use [`ansi_term::ANSIStrings()`] to make a temp variable and just print it.
49///
50/// [docs/ansi-tags.ebnf]: https://github.com/7sDream/tui-markup/blob/master/docs/ansi-tags.ebnf
51#[cfg_attr(docsrs, doc(cfg(feature = "ansi")))]
52#[derive(Debug)]
53pub struct ANSIStringsGenerator<P = NoopCustomTagParser<Style>> {
54 convertor: ANSITermTagConvertor<P>,
55}
56
57impl<P> Default for ANSIStringsGenerator<P> {
58 fn default() -> Self {
59 Self {
60 convertor: ANSITermTagConvertor::<P>::default(),
61 }
62 }
63}
64
65impl<P> ANSIStringsGenerator<P> {
66 /// Create a new ansi term string generator from a custom tag parser.
67 pub fn new(p: P) -> Self {
68 Self {
69 convertor: ANSITermTagConvertor::new(p),
70 }
71 }
72}
73
74impl<'a, P> Generator<'a> for ANSIStringsGenerator<P>
75where
76 P: CustomTagParser<Output = Style>,
77{
78 type Convertor = ANSITermTagConvertor<P>;
79
80 type Output = Vec<ANSIString<'a>>;
81
82 type Err = GeneratorInfallible;
83
84 fn convertor(&mut self) -> &mut Self::Convertor {
85 &mut self.convertor
86 }
87
88 fn generate(&mut self, markup: Vec<Vec<crate::parser::ItemG<'a, Self>>>) -> Result<Self::Output, Self::Err> {
89 Ok(markup.into_iter().map(flatten).fold(vec![], |mut acc, line| {
90 if !acc.is_empty() {
91 acc.push(Style::default().paint("\n"));
92 }
93 acc.extend(line);
94 acc
95 }))
96 }
97}