Skip to main content

treesearch/output/
tty.rs

1//! Colored terminal output for search results.
2//!
3//! Uses `termcolor` for cross-platform ANSI color support and
4//! `unicode-width` for correct CJK character alignment.
5
6use std::io::Write;
7
8use regex::RegexBuilder;
9use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
10use unicode_width::UnicodeWidthStr;
11
12use crate::document::SearchResult;
13
14use super::OutputFormat;
15
16/// Terminal width used for truncation. Falls back to 100.
17fn terminal_width() -> usize {
18    // Simple fallback — a full implementation could query the terminal.
19    100
20}
21
22/// Truncate a string to fit within `max_width` display columns,
23/// accounting for CJK double-width characters.
24fn truncate_to_width(s: &str, max_width: usize) -> String {
25    if s.width() <= max_width {
26        return s.to_string();
27    }
28    if max_width <= 3 {
29        return ".".repeat(max_width);
30    }
31    let mut width = 0;
32    let mut result = String::new();
33    for ch in s.chars() {
34        let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
35        if width + cw + 3 > max_width {
36            // Leave room for "..."
37            result.push_str("...");
38            break;
39        }
40        result.push(ch);
41        width += cw;
42    }
43    result
44}
45
46/// Highlight matching query terms in text by wrapping them with ANSI yellow.
47/// Returns segments for writing with color support.
48struct HighlightSegment {
49    text: String,
50    is_highlight: bool,
51}
52
53fn highlight_terms(text: &str, terms: &[String]) -> Vec<HighlightSegment> {
54    let mut patterns: Vec<String> = terms
55        .iter()
56        .filter(|term| !term.is_empty())
57        .map(|term| regex::escape(term))
58        .collect();
59    patterns.sort_by_key(|pattern| std::cmp::Reverse(pattern.len()));
60    patterns.dedup();
61    if patterns.is_empty() {
62        return vec![HighlightSegment {
63            text: text.to_string(),
64            is_highlight: false,
65        }];
66    }
67
68    let Ok(matcher) = RegexBuilder::new(&patterns.join("|"))
69        .case_insensitive(true)
70        .build()
71    else {
72        return vec![HighlightSegment {
73            text: text.to_string(),
74            is_highlight: false,
75        }];
76    };
77    let mut segments = Vec::new();
78    let mut last_end = 0;
79
80    // Regex offsets always refer to valid boundaries in the original UTF-8 text.
81    for matched in matcher.find_iter(text) {
82        let (mstart, mend) = (matched.start(), matched.end());
83        if mstart > last_end {
84            segments.push(HighlightSegment {
85                text: text[last_end..mstart].to_string(),
86                is_highlight: false,
87            });
88        }
89        segments.push(HighlightSegment {
90            text: text[mstart..mend].to_string(),
91            is_highlight: true,
92        });
93        last_end = mend;
94    }
95
96    if last_end < text.len() {
97        segments.push(HighlightSegment {
98            text: text[last_end..].to_string(),
99            is_highlight: false,
100        });
101    }
102
103    if segments.is_empty() {
104        segments.push(HighlightSegment {
105            text: text.to_string(),
106            is_highlight: false,
107        });
108    }
109
110    segments
111}
112
113/// TTY output formatter with colors and tree structure.
114pub struct TtyOutput {
115    /// Query terms for highlighting matches.
116    pub query_terms: Vec<String>,
117}
118
119impl TtyOutput {
120    pub fn new(query_terms: Vec<String>) -> Self {
121        Self { query_terms }
122    }
123
124    /// Write a single result entry to the buffer with colors.
125    fn write_result(
126        &self,
127        buf: &mut Buffer,
128        result: &SearchResult,
129        _verbose: u8,
130    ) -> std::io::Result<()> {
131        let tw = terminal_width();
132
133        // Header: source_path [source_type] (score: X.XX)
134        buf.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))?;
135        write!(buf, "{}", result.source_path)?;
136        buf.set_color(ColorSpec::new().set_fg(Some(Color::Cyan)))?;
137        write!(buf, " [{}]", result.source_type)?;
138        buf.set_color(ColorSpec::new().set_fg(Some(Color::White)).set_dimmed(true))?;
139        writeln!(buf, " (score: {:.2})", result.score)?;
140        buf.reset()?;
141
142        // Breadcrumb path with tree chars
143        if !result.breadcrumb.is_empty() {
144            let crumb_len = result.breadcrumb.len();
145            for (i, crumb) in result.breadcrumb.iter().enumerate() {
146                let is_last = i == crumb_len - 1;
147                let prefix = if is_last {
148                    "  └── "
149                } else {
150                    "  ├── "
151                };
152
153                buf.set_color(ColorSpec::new().set_fg(Some(Color::White)).set_dimmed(true))?;
154                write!(buf, "{}", prefix)?;
155                buf.reset()?;
156
157                let truncated = truncate_to_width(crumb, tw.saturating_sub(8));
158                write!(buf, "{}", truncated)?;
159                writeln!(buf)?;
160
161                // Vertical connector for non-last items
162                if !is_last {
163                    buf.set_color(ColorSpec::new().set_fg(Some(Color::White)).set_dimmed(true))?;
164                    buf.reset()?;
165                }
166            }
167        }
168
169        // Title (bold)
170        if !result.title.is_empty() {
171            buf.set_color(ColorSpec::new().set_bold(true))?;
172            write!(buf, "  Title: ")?;
173            let segments = highlight_terms(&result.title, &self.query_terms);
174            for seg in &segments {
175                if seg.is_highlight {
176                    buf.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)).set_bold(true))?;
177                } else {
178                    buf.set_color(ColorSpec::new().set_bold(true))?;
179                }
180                write!(buf, "{}", seg.text)?;
181            }
182            buf.reset()?;
183            writeln!(buf)?;
184        }
185
186        // Summary (normal)
187        if !result.summary.is_empty() {
188            let summary = truncate_to_width(&result.summary, tw.saturating_sub(12));
189            write!(buf, "  Summary: ")?;
190            let segments = highlight_terms(&summary, &self.query_terms);
191            for seg in &segments {
192                if seg.is_highlight {
193                    buf.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)).set_bold(true))?;
194                } else {
195                    buf.reset()?;
196                }
197                write!(buf, "{}", seg.text)?;
198            }
199            buf.reset()?;
200            writeln!(buf)?;
201        }
202
203        // Text snippet (verbose >= 2)
204        if _verbose >= 2 && !result.text.is_empty() {
205            let text = truncate_to_width(&result.text, tw.saturating_sub(12));
206            write!(buf, "  Text: ")?;
207            let segments = highlight_terms(&text, &self.query_terms);
208            for seg in &segments {
209                if seg.is_highlight {
210                    buf.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)).set_bold(true))?;
211                } else {
212                    buf.reset()?;
213                }
214                write!(buf, "{}", seg.text)?;
215            }
216            buf.reset()?;
217            writeln!(buf)?;
218        }
219
220        // Line numbers (dim)
221        if let (Some(start), Some(end)) = (result.line_start, result.line_end) {
222            buf.set_color(ColorSpec::new().set_fg(Some(Color::White)).set_dimmed(true))?;
223            writeln!(buf, "  Lines: {}-{}", start, end)?;
224            buf.reset()?;
225        }
226
227        writeln!(buf)?; // Blank line between results
228        Ok(())
229    }
230}
231
232impl OutputFormat for TtyOutput {
233    fn render(&self, results: &[SearchResult], verbose: u8) -> String {
234        let writer = BufferWriter::stdout(ColorChoice::Auto);
235        let mut buf = writer.buffer();
236
237        if results.is_empty() {
238            let _ = writeln!(buf, "No results found.");
239            return String::from_utf8_lossy(buf.as_slice()).to_string();
240        }
241
242        for (i, result) in results.iter().enumerate() {
243            // Result number header
244            let _ = buf.set_color(ColorSpec::new().set_fg(Some(Color::White)).set_dimmed(true));
245            let _ = writeln!(buf, "── Result {} ──", i + 1);
246            let _ = buf.reset();
247            let _ = self.write_result(&mut buf, result, verbose);
248        }
249
250        String::from_utf8_lossy(buf.as_slice()).to_string()
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    fn sample_result() -> SearchResult {
259        SearchResult {
260            node_id: "1".into(),
261            doc_id: "doc1".into(),
262            doc_name: "test.rs".into(),
263            title: "Machine Learning Overview".into(),
264            summary: "An overview of machine learning techniques".into(),
265            text: "Machine learning is a subset of AI".into(),
266            source_type: "code".into(),
267            source_path: "src/test.rs".into(),
268            line_start: Some(10),
269            line_end: Some(25),
270            score: 0.85,
271            depth: 1,
272            breadcrumb: vec!["Root".into(), "Chapter 1".into(), "ML Overview".into()],
273        }
274    }
275
276    #[test]
277    fn test_tty_output_nonempty() {
278        let tty = TtyOutput::new(vec!["machine".into()]);
279        let output = tty.render(&[sample_result()], 1);
280        assert!(!output.is_empty());
281        assert!(output.contains("src/test.rs"));
282        assert!(output.contains("0.85"));
283    }
284
285    #[test]
286    fn test_tty_output_empty_results() {
287        let tty = TtyOutput::new(vec![]);
288        let output = tty.render(&[], 0);
289        assert!(output.contains("No results"));
290    }
291
292    #[test]
293    fn test_truncate_to_width_short() {
294        assert_eq!(truncate_to_width("hello", 100), "hello");
295    }
296
297    #[test]
298    fn test_truncate_to_width_long() {
299        let long = "a".repeat(200);
300        let truncated = truncate_to_width(&long, 50);
301        assert!(truncated.ends_with("..."));
302        assert!(truncated.width() <= 50);
303    }
304
305    #[test]
306    fn test_truncate_to_tiny_width_never_exceeds_limit() {
307        for width in 0..=3 {
308            assert_eq!(truncate_to_width("知识库", width).width(), width);
309        }
310    }
311
312    #[test]
313    fn test_highlight_terms_no_terms() {
314        let segs = highlight_terms("hello world", &[]);
315        assert_eq!(segs.len(), 1);
316        assert!(!segs[0].is_highlight);
317    }
318
319    #[test]
320    fn test_highlight_terms_is_utf8_safe_and_ignores_empty_terms() {
321        let segments = highlight_terms("İstanbul 知识库", &[String::new(), "知识".into()]);
322        assert_eq!(
323            segments
324                .iter()
325                .map(|segment| segment.text.as_str())
326                .collect::<String>(),
327            "İstanbul 知识库"
328        );
329        assert!(segments
330            .iter()
331            .any(|segment| segment.is_highlight && segment.text == "知识"));
332    }
333
334    #[test]
335    fn test_highlight_terms_basic() {
336        let terms = vec!["hello".into()];
337        let segs = highlight_terms("say hello world", &terms);
338        assert!(segs.iter().any(|s| s.is_highlight && s.text == "hello"));
339    }
340
341    #[test]
342    fn test_highlight_terms_no_match() {
343        let terms = vec!["xyz".into()];
344        let segs = highlight_terms("hello world", &terms);
345        assert!(segs.iter().all(|s| !s.is_highlight));
346    }
347}