use std::{borrow::Cow, fmt::Write as WriteStr};
use termcolor::NoColor;
#[cfg(feature = "svg")]
use crate::write::{SvgLine, SvgWriter};
use crate::{
utils::{normalize_newlines, WriteAdapter},
write::HtmlWriter,
TermError,
};
mod parser;
#[cfg(test)]
mod tests;
pub(crate) use self::parser::TermOutputParser;
pub trait TermOutput: Clone + Send + Sync + 'static {}
#[derive(Debug, Clone)]
pub struct Captured(String);
impl AsRef<str> for Captured {
fn as_ref(&self) -> &str {
&self.0
}
}
impl From<String> for Captured {
fn from(raw: String) -> Self {
Self(match normalize_newlines(&raw) {
Cow::Owned(normalized) => normalized,
Cow::Borrowed(_) => raw,
})
}
}
impl Captured {
pub(crate) fn write_as_html(
&self,
output: &mut dyn WriteStr,
wrap_width: Option<usize>,
) -> Result<(), TermError> {
let mut html_writer = HtmlWriter::new(output, wrap_width);
TermOutputParser::new(&mut html_writer).parse(self.0.as_bytes())
}
#[cfg(feature = "svg")]
pub(crate) fn write_as_svg(
&self,
wrap_width: Option<usize>,
) -> Result<Vec<SvgLine>, TermError> {
let mut svg_writer = SvgWriter::new(wrap_width);
TermOutputParser::new(&mut svg_writer).parse(self.0.as_bytes())?;
Ok(svg_writer.into_lines())
}
pub fn to_html(&self) -> Result<String, TermError> {
let mut output = String::with_capacity(self.0.len());
self.write_as_html(&mut output, None)?;
Ok(output)
}
fn write_as_plaintext(&self, output: &mut dyn WriteStr) -> Result<(), TermError> {
let mut plaintext_writer = NoColor::new(WriteAdapter::new(output));
TermOutputParser::new(&mut plaintext_writer).parse(self.0.as_bytes())
}
pub fn to_plaintext(&self) -> Result<String, TermError> {
let mut output = String::with_capacity(self.0.len());
self.write_as_plaintext(&mut output)?;
Ok(output)
}
}
impl TermOutput for Captured {}