Refactor formatting: simplify message formatting logic by replacing multiline normalization and wrapping with concise trim and line collection.
This commit is contained in:
@@ -36,50 +36,6 @@ impl MessageFormatter {
|
||||
}
|
||||
|
||||
pub fn format_message(&self, message: &Message) -> Vec<String> {
|
||||
// 1) Normalize line breaks to '\n' (handles CR, NEL, LS, PS)
|
||||
let normalized: String = message
|
||||
.content
|
||||
.chars()
|
||||
.map(|ch| match ch {
|
||||
'\r' | '\u{0085}' | '\u{2028}' | '\u{2029}' => '\n',
|
||||
_ => ch,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// 2) Collapse: remove whitespace-only lines; keep exactly one '\n' between content lines
|
||||
let mut content = normalized
|
||||
.split('\n')
|
||||
.map(|l| l.trim_end()) // trim trailing spaces per line
|
||||
.filter(|l| !l.trim().is_empty()) // drop blank/whitespace-only lines
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
.trim() // trim leading/trailing whitespace
|
||||
.to_string();
|
||||
|
||||
if content.is_empty() && self.preserve_empty_lines {
|
||||
content.push(' ');
|
||||
}
|
||||
|
||||
// 3) Wrap
|
||||
let options = Options::new(self.wrap_width)
|
||||
.break_words(true)
|
||||
.word_separator(textwrap::WordSeparator::UnicodeBreakProperties);
|
||||
|
||||
// 4) Post: rtrim each visual line; drop any whitespace-only lines
|
||||
let mut lines: Vec<String> = wrap(&content, &options)
|
||||
.into_iter()
|
||||
.map(|s| s.trim_end().to_string())
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.collect();
|
||||
|
||||
// 5) Belt & suspenders: remove leading/trailing blanks if any survived
|
||||
while lines.first().map_or(false, |s| s.trim().is_empty()) {
|
||||
lines.remove(0);
|
||||
}
|
||||
while lines.last().map_or(false, |s| s.trim().is_empty()) {
|
||||
lines.pop();
|
||||
}
|
||||
|
||||
lines
|
||||
message.content.trim().lines().map(|s| s.to_string()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user