feat: 优化消息内容格式化逻辑,增强对特殊字符和换行符的处理
This commit is contained in:
parent
8830027cbc
commit
ecd945b309
2
.gitignore
vendored
2
.gitignore
vendored
@ -11,3 +11,5 @@ PicoBot.code-workspace
|
|||||||
.picobot
|
.picobot
|
||||||
.claude
|
.claude
|
||||||
output
|
output
|
||||||
|
.python-version
|
||||||
|
pyproject.toml
|
||||||
|
|||||||
@ -257,10 +257,24 @@ pub fn generate_markdown(
|
|||||||
/// 格式化消息内容
|
/// 格式化消息内容
|
||||||
///
|
///
|
||||||
/// 如果内容包含特殊字符,使用代码块包装
|
/// 如果内容包含特殊字符,使用代码块包装
|
||||||
|
/// 使用比内容中最大连续反引号数量多1的反引号来包裹,避免嵌套冲突
|
||||||
pub fn format_message_content(content: &str) -> String {
|
pub fn format_message_content(content: &str) -> String {
|
||||||
// 如果内容包含代码块标记或表格标记,使用原始格式
|
// 如果内容包含表格标记或换行符,使用代码块包裹以保留格式
|
||||||
if content.contains("```") || content.contains("| ") {
|
if content.contains("| ") || content.contains('\n') {
|
||||||
format!("```\n{}\n```", content)
|
// 计算内容中连续反引号的最大数量
|
||||||
|
let max_backticks = content
|
||||||
|
.chars()
|
||||||
|
.fold((0, 0), |(max_count, current_count), c| {
|
||||||
|
if c == '`' {
|
||||||
|
(max_count, current_count + 1)
|
||||||
|
} else {
|
||||||
|
(max_count.max(current_count), 0)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.0;
|
||||||
|
// 使用比最大数量多1的反引号来包裹(至少3个)
|
||||||
|
let fence = "`".repeat(max_backticks.max(3) + 1);
|
||||||
|
format!("{}\n{}\n{}", fence, content, fence)
|
||||||
} else {
|
} else {
|
||||||
content.to_string()
|
content.to_string()
|
||||||
}
|
}
|
||||||
@ -553,10 +567,40 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_format_message_content() {
|
fn test_format_message_content() {
|
||||||
|
// 普通单行文本 - 原样返回
|
||||||
assert_eq!(format_message_content("hello"), "hello");
|
assert_eq!(format_message_content("hello"), "hello");
|
||||||
|
|
||||||
|
// 单行包含反引号 - 原样返回(单行不需要包裹)
|
||||||
|
assert_eq!(format_message_content("`code`"), "`code`");
|
||||||
|
|
||||||
|
// 包含换行符 - 使用4个反引号包裹(最小)
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
format_message_content("```code```"),
|
format_message_content("line1\nline2\nline3"),
|
||||||
"```\n```code```\n```"
|
"````\nline1\nline2\nline3\n````"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 包含表格标记 - 使用4个反引号包裹
|
||||||
|
assert_eq!(
|
||||||
|
format_message_content("| col1 | col2 |"),
|
||||||
|
"````\n| col1 | col2 |\n````"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 多行内容包含3个反引号(代码块标记)- 使用4个反引号包裹
|
||||||
|
assert_eq!(
|
||||||
|
format_message_content("```code```\nmore"),
|
||||||
|
"````\n```code```\nmore\n````"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 多行内容包含多行代码块
|
||||||
|
assert_eq!(
|
||||||
|
format_message_content("```\ncode\n```\nmore"),
|
||||||
|
"````\n```\ncode\n```\nmore\n````"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 多行内容包含4个反引号 - 使用5个反引号包裹
|
||||||
|
assert_eq!(
|
||||||
|
format_message_content("````code````\nmore"),
|
||||||
|
"`````\n````code````\nmore\n`````"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user