use std::io::{BufRead, Lines};
use std::iter::Peekable;
use std::slice::Iter;
use unicode_width::UnicodeWidthChar;
use crate::FileOrStdReader;
use crate::FmtOptions;
fn char_width(c: char) -> usize {
if (c as usize) < 0xA0 {
1
} else {
UnicodeWidthChar::width(c).unwrap_or(1)
}
}
fn is_fmt_whitespace(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C')
}
#[derive(Debug)]
pub enum Line {
FormatLine(FileLine),
NoFormatLine(String, bool),
}
impl Line {
fn get_formatline(self) -> FileLine {
match self {
Self::FormatLine(fl) => fl,
Self::NoFormatLine(..) => panic!("Found NoFormatLine when expecting FormatLine"),
}
}
fn get_noformatline(self) -> (String, bool) {
match self {
Self::NoFormatLine(s, b) => (s, b),
Self::FormatLine(..) => panic!("Found FormatLine when expecting NoFormatLine"),
}
}
}
#[derive(Debug)]
pub struct FileLine {
line: String,
indent_end: usize,
prefix_indent_end: usize,
indent_len: usize,
prefix_len: usize,
}
pub struct FileLines<'a> {
opts: &'a FmtOptions,
lines: Lines<&'a mut FileOrStdReader>,
}
impl FileLines<'_> {
fn new<'b>(opts: &'b FmtOptions, lines: Lines<&'b mut FileOrStdReader>) -> FileLines<'b> {
FileLines { opts, lines }
}
fn match_prefix(&self, line: &str) -> (bool, usize) {
let Some(prefix) = &self.opts.prefix else {
return (true, 0);
};
FileLines::match_prefix_generic(prefix, line, self.opts.xprefix)
}
fn match_anti_prefix(&self, line: &str) -> bool {
let Some(anti_prefix) = &self.opts.anti_prefix else {
return true;
};
match FileLines::match_prefix_generic(anti_prefix, line, self.opts.xanti_prefix) {
(true, _) => false,
(_, _) => true,
}
}
fn match_prefix_generic(pfx: &str, line: &str, exact: bool) -> (bool, usize) {
if line.starts_with(pfx) {
return (true, 0);
}
if !exact {
for (i, char) in line.char_indices() {
if line[i..].starts_with(pfx) {
return (true, i);
} else if !is_fmt_whitespace(char) {
break;
}
}
}
(false, 0)
}
fn compute_indent(&self, string: &str, prefix_end: usize) -> (usize, usize, usize) {
let mut prefix_len = 0;
let mut indent_len = 0;
let mut indent_end = 0;
for (os, c) in string.char_indices() {
if os == prefix_end {
prefix_len = indent_len;
}
if (os >= prefix_end) && !is_fmt_whitespace(c) {
indent_end = os;
break;
} else if c == '\t' {
indent_len = (indent_len / self.opts.tabwidth + 1) * self.opts.tabwidth;
} else {
indent_len += char_width(c);
}
}
(indent_end, prefix_len, indent_len)
}
}
impl Iterator for FileLines<'_> {
type Item = Line;
fn next(&mut self) -> Option<Line> {
let n = self.lines.next()?.ok()?;
if n.chars().all(is_fmt_whitespace) {
return Some(Line::NoFormatLine(String::new(), true));
}
let (pmatch, poffset) = self.match_prefix(&n[..]);
if !pmatch {
return Some(Line::NoFormatLine(n, false));
}
if pmatch
&& n[poffset + self.opts.prefix.as_ref().map_or(0, |s| s.len())..]
.chars()
.all(is_fmt_whitespace)
{
return Some(Line::NoFormatLine(n, false));
}
if !self.match_anti_prefix(&n[..]) {
return Some(Line::NoFormatLine(n, false));
}
let prefix_end = poffset + self.opts.prefix.as_ref().map_or(0, |s| s.len());
let (indent_end, prefix_len, indent_len) = self.compute_indent(&n[..], prefix_end);
Some(Line::FormatLine(FileLine {
line: n,
indent_end,
prefix_indent_end: poffset,
indent_len,
prefix_len,
}))
}
}
#[derive(Debug)]
pub struct Paragraph {
lines: Vec<String>,
pub init_str: String,
pub init_len: usize,
init_end: usize,
pub indent_str: String,
pub indent_len: usize,
indent_end: usize,
pub mail_header: bool,
}
pub struct ParagraphStream<'a> {
lines: Peekable<FileLines<'a>>,
next_mail: bool,
opts: &'a FmtOptions,
}
impl ParagraphStream<'_> {
pub fn new<'b>(opts: &'b FmtOptions, reader: &'b mut FileOrStdReader) -> ParagraphStream<'b> {
let lines = FileLines::new(opts, reader.lines()).peekable();
ParagraphStream {
lines,
next_mail: true,
opts,
}
}
fn is_mail_header(line: &FileLine) -> bool {
if line.indent_end > 0 {
false
} else {
let l_slice = &line.line[..];
if l_slice.starts_with("From ") {
true
} else {
let Some(colon_posn) = l_slice.find(':') else {
return false;
};
if colon_posn == 0 {
return false;
}
l_slice[..colon_posn]
.chars()
.all(|x| !matches!(x as usize, y if !(33..=126).contains(&y)))
}
}
}
}
impl Iterator for ParagraphStream<'_> {
type Item = Result<Paragraph, String>;
#[allow(clippy::cognitive_complexity)]
fn next(&mut self) -> Option<Result<Paragraph, String>> {
let noformat = match self.lines.peek()? {
Line::FormatLine(_) => false,
Line::NoFormatLine(_, _) => true,
};
if noformat {
let (s, nm) = self.lines.next().unwrap().get_noformatline();
self.next_mail = nm;
return Some(Err(s));
}
let mut init_str = String::new();
let mut init_end = 0;
let mut init_len = 0;
let mut indent_str = String::new();
let mut indent_end = 0;
let mut indent_len = 0;
let mut prefix_len = 0;
let mut prefix_indent_end = 0;
let mut p_lines = Vec::new();
let mut in_mail = false;
let mut second_done = false; loop {
let Some(Line::FormatLine(fl)) = self.lines.peek() else {
break;
};
if p_lines.is_empty() {
if self.opts.mail && self.next_mail && ParagraphStream::is_mail_header(fl) {
in_mail = true;
indent_str.push_str(" ");
indent_len = 2;
} else {
if self.opts.crown || self.opts.tagged {
init_str.push_str(&fl.line[..fl.indent_end]);
init_len = fl.indent_len;
init_end = fl.indent_end;
} else {
second_done = true;
}
indent_str.push_str(&fl.line[..fl.indent_end]);
indent_len = fl.indent_len;
indent_end = fl.indent_end;
prefix_len = fl.prefix_len;
prefix_indent_end = fl.prefix_indent_end;
if self.opts.tagged {
indent_str.push_str(" ");
indent_len += 4;
}
}
} else if in_mail {
if fl.indent_end == 0 || (self.opts.prefix.is_some() && fl.prefix_indent_end == 0) {
break; }
} else if !second_done {
if prefix_len != fl.prefix_len || prefix_indent_end != fl.prefix_indent_end {
break;
}
if self.opts.tagged
&& indent_len - 4 == fl.indent_len
&& indent_end == fl.indent_end
{
break;
}
indent_str.clear();
indent_str.push_str(&fl.line[..fl.indent_end]);
indent_len = fl.indent_len;
indent_end = fl.indent_end;
second_done = true;
} else {
if indent_end != fl.indent_end
|| prefix_indent_end != fl.prefix_indent_end
|| indent_len != fl.indent_len
|| prefix_len != fl.prefix_len
{
break;
}
}
p_lines.push(self.lines.next().unwrap().get_formatline().line);
if self.opts.split_only {
break;
}
}
self.next_mail = in_mail;
Some(Ok(Paragraph {
lines: p_lines,
init_str,
init_len,
init_end,
indent_str,
indent_len,
indent_end,
mail_header: in_mail,
}))
}
}
pub struct ParaWords<'a> {
opts: &'a FmtOptions,
para: &'a Paragraph,
words: Vec<WordInfo<'a>>,
}
impl<'a> ParaWords<'a> {
pub fn new(opts: &'a FmtOptions, para: &'a Paragraph) -> Self {
let mut pw = ParaWords {
opts,
para,
words: Vec::new(),
};
pw.create_words();
pw
}
fn create_words(&mut self) {
if self.para.mail_header {
self.words.extend(
self.para
.lines
.iter()
.flat_map(|x| x.split_whitespace())
.map(|x| WordInfo {
word: x,
word_start: 0,
word_nchars: x.len(), before_tab: None,
after_tab: 0,
sentence_start: false,
ends_punct: false,
new_line: false,
}),
);
} else {
self.words.extend(if self.opts.crown || self.opts.tagged {
WordSplit::new(self.opts, &self.para.lines[0][self.para.init_end..])
} else {
WordSplit::new(self.opts, &self.para.lines[0][self.para.indent_end..])
});
if self.para.lines.len() > 1 {
let indent_end = self.para.indent_end;
let opts = self.opts;
self.words.extend(
self.para
.lines
.iter()
.skip(1)
.flat_map(|x| WordSplit::new(opts, &x[indent_end..])),
);
}
}
}
pub fn words(&'a self) -> Iter<'a, WordInfo<'a>> {
self.words.iter()
}
}
struct WordSplit<'a> {
opts: &'a FmtOptions,
string: &'a str,
length: usize,
position: usize,
prev_punct: bool,
}
impl WordSplit<'_> {
fn analyze_tabs(&self, string: &str) -> (Option<usize>, usize, Option<usize>) {
let mut beforetab = None;
let mut aftertab = 0;
let mut word_start = None;
for (os, c) in string.char_indices() {
if !is_fmt_whitespace(c) {
word_start = Some(os);
break;
} else if c == '\t' {
if beforetab.is_none() {
beforetab = Some(aftertab);
aftertab = 0;
} else {
aftertab = (aftertab / self.opts.tabwidth + 1) * self.opts.tabwidth;
}
} else {
aftertab += 1;
}
}
(beforetab, aftertab, word_start)
}
}
impl WordSplit<'_> {
fn new<'b>(opts: &'b FmtOptions, string: &'b str) -> WordSplit<'b> {
let trim_string = string.trim_start_matches(is_fmt_whitespace);
WordSplit {
opts,
string: trim_string,
length: string.len(),
position: 0,
prev_punct: false,
}
}
fn is_punctuation(c: char) -> bool {
matches!(c, '!' | '.' | '?')
}
}
pub struct WordInfo<'a> {
pub word: &'a str,
pub word_start: usize,
pub word_nchars: usize,
pub before_tab: Option<usize>,
pub after_tab: usize,
pub sentence_start: bool,
pub ends_punct: bool,
pub new_line: bool,
}
impl<'a> Iterator for WordSplit<'a> {
type Item = WordInfo<'a>;
fn next(&mut self) -> Option<WordInfo<'a>> {
if self.position >= self.length {
return None;
}
let old_position = self.position;
let new_line = old_position == 0;
let (before_tab, after_tab, word_start) =
if let (b, a, Some(s)) = self.analyze_tabs(&self.string[old_position..]) {
(b, a, s + old_position)
} else {
self.position = self.length;
return None;
};
let mut word_nchars = 0;
self.position = match self.string[word_start..].find(|x: char| {
if is_fmt_whitespace(x) {
true
} else {
word_nchars += char_width(x);
false
}
}) {
None => self.length,
Some(s) => s + word_start,
};
let word_start_relative = word_start - old_position;
let is_start_of_sentence =
self.prev_punct && (before_tab.is_some() || word_start_relative > 1);
self.prev_punct = match self.string[..self.position].chars().next_back() {
Some(ch) => WordSplit::is_punctuation(ch),
_ => panic!("fatal: expected word not to be empty"),
};
let (word, word_start_relative, before_tab, after_tab) = if self.opts.uniform {
(&self.string[word_start..self.position], 0, None, 0)
} else {
(
&self.string[old_position..self.position],
word_start_relative,
before_tab,
after_tab,
)
};
Some(WordInfo {
word,
word_start: word_start_relative,
word_nchars,
before_tab,
after_tab,
sentence_start: is_start_of_sentence,
ends_punct: self.prev_punct,
new_line,
})
}
}