Skip to content

Commit b309959

Browse files
authored
fix(chat): Fix display of square brackets in chat output (#971)
* fix(cli): Fix display of square brackets in chat output Modify URL parser to properly handle square brackets in text by saving the input position and resetting it when the complete URL pattern does not match. This ensures square brackets are correctly displayed in chat output when they are not part of a markdown link. * fix fmt, improve test coverage * add testcase * change testcase name * fix format
1 parent f4b1edd commit b309959

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

crates/q_cli/src/cli/chat/parse.rs

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,9 +404,30 @@ fn url<'a, 'b>(
404404
state: &'b mut ParseState,
405405
) -> impl FnMut(&mut Partial<&'a str>) -> PResult<(), Error<'a>> + 'b {
406406
move |i| {
407-
let display = delimited("[", take_until(1.., "]("), "]").parse_next(i)?;
408-
let link = delimited("(", take_till(0.., ')'), ")").parse_next(i)?;
407+
// Save the current input position
408+
let start = i.checkpoint();
409+
410+
// Try to match the first part of URL pattern "[text]"
411+
let display = match delimited::<_, _, _, _, Error<'a>, _, _, _>("[", take_until(1.., "]("), "]").parse_next(i) {
412+
Ok(display) => display,
413+
Err(_) => {
414+
// If it doesn't match, reset position and fail
415+
i.reset(&start);
416+
return Err(ErrMode::from_error_kind(i, ErrorKind::Fail));
417+
},
418+
};
419+
420+
// Try to match the second part of URL pattern "(url)"
421+
let link = match delimited::<_, _, _, _, Error<'a>, _, _, _>("(", take_till(0.., ')'), ")").parse_next(i) {
422+
Ok(link) => link,
423+
Err(_) => {
424+
// If it doesn't match, reset position and fail
425+
i.reset(&start);
426+
return Err(ErrMode::from_error_kind(i, ErrorKind::Fail));
427+
},
428+
};
409429

430+
// Only generate output if the complete URL pattern matches
410431
queue_newline_or_advance(&mut o, state, display.width() + 1)?;
411432
queue(&mut o, style::SetForegroundColor(URL_TEXT_COLOR))?;
412433
queue(&mut o, style::Print(format!("{display} ")))?;
@@ -726,4 +747,16 @@ mod tests {
726747
style::SetForegroundColor(BLOCKQUOTE_COLOR),
727748
style::Print("│ hello"),
728749
]);
750+
validate!(square_bracket_1, "[test]", [style::Print("[test]")]);
751+
validate!(square_bracket_2, "Text with [brackets]", [style::Print(
752+
"Text with [brackets]"
753+
)]);
754+
validate!(square_bracket_empty, "[]", [style::Print("[]")]);
755+
validate!(square_bracket_array, "a[i]", [style::Print("a[i]")]);
756+
validate!(square_bracket_url_like_1, "[text] without url part", [style::Print(
757+
"[text] without url part"
758+
)]);
759+
validate!(square_bracket_url_like_2, "[text](without url part", [style::Print(
760+
"[text](without url part"
761+
)]);
729762
}

0 commit comments

Comments
 (0)