Skip to content

Commit 2766951

Browse files
feat: add line numbers to nonstylized text (#662)
1 parent b7f3335 commit 2766951

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

crates/q_cli/src/cli/chat/tools/fs_write.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ impl FsWrite {
148148
let file = stylize_output_if_able(&relative_path, file_text, None, None);
149149
queue!(
150150
updates,
151-
style::Print("\n\nContents:\n"),
151+
style::Print("Contents:\n"),
152152
style::Print(file),
153153
style::ResetColor,
154154
)?;

crates/q_cli/src/cli/chat/tools/mod.rs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ pub mod fs_read;
33
pub mod fs_write;
44
pub mod use_aws;
55

6-
use std::borrow::Cow;
76
use std::io::Write;
87
use std::path::{
98
Path,
@@ -222,21 +221,33 @@ fn terminal_width(line_count: usize) -> usize {
222221
((line_count as f32 + 0.1).log10().ceil()) as usize
223222
}
224223

225-
fn stylize_output_if_able<'a>(
224+
fn stylize_output_if_able(
226225
path: impl AsRef<Path>,
227-
file_text: &'a str,
226+
file_text: &str,
228227
starting_line: Option<usize>,
229228
gutter_prefix: Option<&str>,
230-
) -> Cow<'a, str> {
229+
) -> String {
231230
match stylized_file(path, file_text, starting_line, gutter_prefix) {
232-
Ok(s) => s.into(),
231+
Ok(s) => s,
233232
Err(err) => {
234233
error!(?err, "unable to syntax highlight the output");
235-
file_text.into()
234+
format!("\n{}", nonstylized_file(file_text))
236235
},
237236
}
238237
}
239238

239+
fn nonstylized_file(file_text: impl AsRef<str>) -> String {
240+
let file_text = file_text.as_ref();
241+
let line_count = file_text.lines().count();
242+
let width = terminal_width(line_count);
243+
let lines = LinesWithEndings::from(file_text);
244+
let mut f = String::new();
245+
for (i, line) in lines.enumerate() {
246+
f.push_str(&format!(" {:>width$}: {}", i + 1, line, width = width));
247+
}
248+
f
249+
}
250+
240251
/// Returns a 24bit terminal escaped syntax-highlighted [String] of the file pointed to by `path`,
241252
/// if able.
242253
///

0 commit comments

Comments
 (0)