use std::fmt;
use techy::core::node::NodeRef;
use crate::lang::Flm;
use crate::stdlib::backends::pres;
use super::construct::LatexRawPayload;
use super::escape::{Declared, EscapeConfig, escape_into};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LatexRaw {
text: String,
copied: bool,
}
impl LatexRaw {
pub fn from_raw_payload(payload: &LatexRawPayload) -> LatexRaw {
LatexRaw { text: payload.text.clone(), copied: false }
}
pub fn from_source(nodes: &[NodeRef<'_, Flm>]) -> LatexRaw {
LatexRaw { text: pres::recompose_source(nodes), copied: true }
}
pub fn as_str(&self) -> &str {
&self.text
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawCommentRefused {
pub text: String,
pub at: usize,
}
impl fmt::Display for RawCommentRefused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"raw LaTeX text built by a lowering rule must not contain a LaTeX comment, but \
the `%` at byte {} of {:?} starts one",
self.at, self.text
)
}
}
pub fn comment_percent(text: &str) -> Option<usize> {
let bytes = text.as_bytes();
for (at, byte) in bytes.iter().enumerate() {
if *byte != b'%' {
continue;
}
let mut backslashes = 0usize;
let mut before = at;
while before > 0 && bytes[before - 1] == b'\\' {
backslashes += 1;
before -= 1;
}
if backslashes % 2 == 0 {
return Some(at);
}
}
None
}
pub const ESCVERB_UNESCAPED: char = '@';
pub fn escverb_encode_into(out: &mut String, text: &str) {
for ch in text.chars() {
if ch.is_ascii()
&& !ch.is_ascii_alphanumeric()
&& !ch.is_ascii_control()
&& ch != ESCVERB_UNESCAPED
{
out.push('\\');
}
out.push(ch);
}
}
pub fn escverb_encode(text: &str) -> String {
let mut out = String::with_capacity(text.len() * 2);
escverb_encode_into(&mut out, text);
out
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SinkOutput {
pub text: String,
pub declared: Declared,
pub unknown: Vec<char>,
}
#[derive(Debug, Clone)]
pub struct LatexSink {
out: String,
config: EscapeConfig,
declared: Declared,
unknown: Vec<char>,
}
impl LatexSink {
pub fn new(config: EscapeConfig) -> LatexSink {
LatexSink { out: String::new(), config, declared: Declared::new(), unknown: Vec::new() }
}
pub fn config(&self) -> &EscapeConfig {
&self.config
}
pub fn position(&self) -> usize {
self.out.len()
}
pub fn text(&mut self, text: &str) {
let unknown = escape_into(&mut self.out, text, &self.config, &mut self.declared);
for ch in unknown {
if !self.unknown.contains(&ch) {
self.unknown.push(ch);
}
}
}
pub fn raw(&mut self, raw: &LatexRaw) -> Result<(), RawCommentRefused> {
if !raw.copied {
if let Some(at) = comment_percent(raw.as_str()) {
return Err(RawCommentRefused { text: raw.as_str().to_string(), at });
}
}
self.out.push_str(raw.as_str());
Ok(())
}
pub fn verbatim_block(&mut self, text: &str) {
self.out.push_str(text);
}
pub fn escverb(&mut self, text: &str) {
escverb_encode_into(&mut self.out, text);
}
pub fn control_word(&mut self, name: &str) {
self.out.push('\\');
self.out.push_str(name);
}
pub fn star(&mut self) {
self.out.push('*');
}
pub fn begin(&mut self, name: &str) {
self.out.push_str("\\begin{");
self.out.push_str(name);
self.out.push('}');
}
pub fn end(&mut self, name: &str) {
self.out.push_str("\\end{");
self.out.push_str(name);
self.out.push('}');
}
pub fn open_brace(&mut self) {
self.out.push('{');
}
pub fn close_brace(&mut self) {
self.out.push('}');
}
pub fn open_bracket(&mut self) {
self.out.push('[');
}
pub fn close_bracket(&mut self) {
self.out.push(']');
}
pub fn newline(&mut self) {
self.out.push('\n');
}
pub fn comment(&mut self, prefix: &str, text: &str) {
if !prefix.starts_with('%') {
self.out.push('%');
}
self.out.push_str(prefix);
self.out.push_str(text);
self.out.push('\n');
}
pub fn finish(self) -> SinkOutput {
SinkOutput { text: self.out, declared: self.declared, unknown: self.unknown }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::backends::latex::escape::UnicodeMode;
#[test]
fn every_entry_point_writes_its_own_syntax_and_nothing_else() {
let mut sink = LatexSink::new(EscapeConfig::new(UnicodeMode::Replace));
sink.control_word("section");
sink.star();
sink.open_bracket();
sink.text("short");
sink.close_bracket();
sink.open_brace();
sink.text("100% & more");
sink.close_brace();
sink.newline();
sink.begin("center");
sink.raw(&LatexRaw::from_raw_payload(&LatexRawPayload::new("\\\\[1ex]"))).expect("no comment");
sink.end("center");
sink.newline();
sink.escverb("a b");
let output = sink.finish();
assert_eq!(
output.text,
"\\section*[short]{100\\% \\& more}\n\\begin{center}\\\\[1ex]\\end{center}\na\\ b"
);
assert!(output.unknown.is_empty());
}
#[test]
fn the_comment_gains_a_leading_percent_only_when_the_prefix_lacks_one() {
let mut sink = LatexSink::new(EscapeConfig::default());
sink.comment("%%", " a note");
sink.comment("//", " another");
sink.comment("%", " third");
assert_eq!(sink.finish().text, "%% a note\n%// another\n% third\n");
}
#[test]
fn a_comment_always_ends_its_own_line_whatever_follows_it() {
let mut sink = LatexSink::new(EscapeConfig::default());
sink.comment("%%", " a note");
sink.text("next");
assert_eq!(sink.finish().text, "%% a note\nnext");
}
#[test]
fn a_raw_piece_a_rule_assembled_may_not_hold_a_comment() {
let mut sink = LatexSink::new(EscapeConfig::default());
let ok = LatexRaw::from_raw_payload(&LatexRawPayload::new("100\\% sure"));
assert_eq!(sink.raw(&ok), Ok(()));
let bad = LatexRaw::from_raw_payload(&LatexRawPayload::new("a %% note"));
assert_eq!(
sink.raw(&bad),
Err(RawCommentRefused { text: String::from("a %% note"), at: 2 })
);
let linebreak = LatexRaw::from_raw_payload(&LatexRawPayload::new("\\\\% note"));
assert!(sink.raw(&linebreak).is_err());
assert_eq!(sink.finish().text, "100\\% sure");
}
#[test]
fn source_copied_from_the_document_is_written_as_it_stands() {
let mut sink = LatexSink::new(EscapeConfig::default());
sink.verbatim_block("100% of the time\n");
assert_eq!(sink.finish().text, "100% of the time\n");
}
#[test]
fn the_unknown_characters_and_the_declarations_come_back_with_the_text() {
let mut sink = LatexSink::new(EscapeConfig::new(UnicodeMode::Declare));
sink.text("é ธ");
sink.text("ธ α");
let output = sink.finish();
assert_eq!(output.text, "é ธธ α");
assert_eq!(output.unknown, ['ธ']);
assert_eq!(output.declared.chars().len(), 2);
}
#[test]
fn the_escverb_encoding_escapes_printable_ascii_punctuation_only() {
assert_eq!(escverb_encode("x = {1, 2}; 100% #a\\b"), "x\\ \\=\\ \\{1\\,\\ 2\\}\\;\\ 100\\%\\ \\#a\\\\b");
assert_eq!(escverb_encode("Zé9\n\t"), "Zé9\n\t");
assert_eq!(escverb_encode("~^_$&"), "\\~\\^\\_\\$\\&");
}
#[test]
fn the_escverb_encoding_leaves_the_one_character_fvextra_refuses_escaped() {
assert_eq!(escverb_encode("a@b"), "a@b");
assert_eq!(escverb_encode("@decorator(x)"), "@decorator\\(x\\)");
for code in 0x20u8..=0x7E {
let ch = char::from(code);
let escaped = escverb_encode(&ch.to_string());
if ch.is_ascii_alphanumeric() || ch == ESCVERB_UNESCAPED {
assert_eq!(escaped, ch.to_string(), "{ch:?}");
} else {
assert_eq!(escaped, format!("\\{ch}"), "{ch:?}");
}
}
}
#[test]
fn a_raw_value_carries_its_bytes_unchanged() {
let raw = LatexRaw::from_raw_payload(&LatexRawPayload::new("\n\n"));
assert_eq!(raw.as_str(), "\n\n");
let mut sink = LatexSink::new(EscapeConfig::default());
sink.raw(&raw).expect("no comment");
assert_eq!(sink.finish().text, "\n\n");
}
}