use super::*;
fn inner_reflow(
state: &mut Ed<'_>,
selection: (usize, usize),
width: usize,
) -> Result<usize> {
state.history.current().verify_selection(selection)?;
let buffer = state.history.current_mut()?;
let mut tail = buffer.split_off(selection.1);
let data = buffer.split_off(selection.0 - 1);
let mut chars = Vec::new();
for line in &data {
for ch in line.text.chars() {
chars.push(match ch{
'\n' => ' ',
c => c,
});
}
}
state.clipboard = data[..].into();
chars.pop();
let mut w = 0; let mut latest_space = None;
for i in 0..chars.len() {
w += 1;
if chars[i] == ' ' { latest_space = Some(i); }
if w > width {
if let Some(s) = latest_space {
chars[s] = '\n';
w = i - s;
latest_space = None;
}
}
}
for line in chars.split(|c| c == &'\n') {
buffer.push(Line::new(line.iter().collect::<String>(), '\0'));
}
let end = buffer.len();
buffer.append(&mut tail);
Ok(end)
}
pub fn reflow(
state: &mut Ed<'_>,
pflags: &mut PrintingFlags,
selection: Option<Sel<'_>>,
tail: &str,
) -> Result<()> {
let selection = interpret_selection(&state, selection, state.selection)?;
let nr_end = tail.find( |c: char| !c.is_numeric() ).unwrap_or(tail.len());
let width = if nr_end == 0 {
80
} else {
tail[.. nr_end] .parse::<usize>()
.map_err(|e| EdError::ReflowNotInt{error: e.to_string(), text: tail[..nr_end].into()})
?
};
let mut flags = parse_flags(&tail[nr_end ..], "pnl")?;
pflags.p = flags.remove(&'p').unwrap();
pflags.n = flags.remove(&'n').unwrap();
pflags.l = flags.remove(&'l').unwrap();
let end = inner_reflow(state, selection, width)?;
state.selection = (selection.0.min(end).max(1), end);
Ok(())
}