erebus 0.1.7

A CLI message generation library
Documentation
use crate::Style;

use super::print_gap;

#[must_use]
/// Breaks text into a series of lines, each of which is no longer than `width` characters.  
/// Breaks text in-between words, if possible.
pub fn break_line(text: &str, indent: usize, ln_width: Option<usize>, style: &Style) -> String {
    let mut result = String::new();
    let mut line = String::new();
    let indent_str = ln_width.map_or_else(
        || " ".repeat(indent),
        |ln_width| {
            let mut result = String::new();
            print_gap(&mut result, ln_width, style);
            result
        },
    );
    for c in text.chars() {
        if c == '\n' {
            result.push_str(&line);
            result.push('\n');
            line.clear();
        } else {
            line.push(c);
            if c == ' ' && line.len() + indent > style.max_width {
                let mut last_space = 0;
                for (i, c) in line.chars().enumerate() {
                    if c == ' ' {
                        last_space = i;
                    }
                    if i == style.max_width - indent {
                        result.push_str(&indent_str);
                        result.push_str(&line[..last_space]);
                        result.push('\n');
                        line = line[last_space + 1..].to_string();
                        break;
                    }
                }
            }
        }
    }
    if !line.trim().is_empty() {
        if line.len() > style.max_width + indent {
            let mut last_space = 0;
            for (i, c) in line.chars().enumerate() {
                if c == ' ' {
                    last_space = i;
                }
                if i == style.max_width - indent {
                    result.push_str(&indent_str);
                    result.push_str(&line[..last_space]);
                    result.push('\n');
                    line = line[last_space + 1..].to_string();
                    break;
                }
            }
        }
        result.push_str(&indent_str);
        result.push_str(&line);
    }
    result.trim_start_matches(&indent_str).to_string()
}