Skip to main content

reflex/
formatter.rs

1//! Terminal output formatting for query results
2//!
3//! This module provides beautiful, syntax-highlighted terminal output using ratatui.
4//! It supports both static output (print and exit) and prepares for future interactive mode.
5
6use anyhow::Result;
7use crossterm::terminal;
8use crossterm::tty::IsTty;
9use std::collections::HashMap;
10use std::io;
11use syntect::easy::HighlightLines;
12use syntect::highlighting::{Style as SyntectStyle, ThemeSet};
13use syntect::parsing::SyntaxSet;
14use syntect::util::{LinesWithEndings, as_24_bit_terminal_escaped};
15
16use crate::models::{DependencyInfo, Language, SearchResult, SymbolKind};
17
18/// Lazy-loaded syntax highlighting resources
19struct SyntaxHighlighter {
20    syntax_set: SyntaxSet,
21    theme_set: ThemeSet,
22}
23
24impl SyntaxHighlighter {
25    fn new() -> Self {
26        Self {
27            syntax_set: SyntaxSet::load_defaults_newlines(),
28            theme_set: ThemeSet::load_defaults(),
29        }
30    }
31
32    /// Get syntax reference for a language using extension-based lookup (most reliable)
33    ///
34    /// This uses file extensions to find syntaxes, which is more reliable than name-based
35    /// lookup because syntect (based on Sublime Text) primarily uses extension matching.
36    ///
37    /// For languages not in the default syntect set (TypeScript, Vue, Svelte), we fall back
38    /// to related syntaxes (JavaScript for TypeScript, HTML for Vue/Svelte).
39    fn get_syntax(&self, lang: &Language) -> Option<&syntect::parsing::SyntaxReference> {
40        let (extension, fallback_extension) = match lang {
41            Language::Rust => ("rs", None),
42            Language::Python => ("py", None),
43            Language::JavaScript => ("js", None),
44            Language::TypeScript => ("ts", Some("js")), // Fallback to JavaScript
45            Language::Go => ("go", None),
46            Language::Java => ("java", None),
47            Language::C => ("c", None),
48            Language::Cpp => ("cpp", None),
49            Language::CSharp => ("cs", None),
50            Language::PHP => ("php", None),
51            Language::Ruby => ("rb", None),
52            Language::Kotlin => ("kt", None),
53            Language::Swift => ("swift", None),
54            Language::Zig => ("zig", None),
55            Language::Vue => ("vue", Some("html")), // Fallback to HTML
56            Language::Svelte => ("svelte", Some("html")), // Fallback to HTML
57            // The text tier spans markdown, YAML, shell and more, so no single
58            // syntax fits. Render it plain, as Unknown already is.
59            Language::Text | Language::Lock | Language::Generated => return None,
60            Language::Unknown => return None,
61        };
62
63        // Try extension-based lookup first (most reliable)
64        self.syntax_set
65            .find_syntax_by_extension(extension)
66            .or_else(|| {
67                // Try token-based search (searches by extension then name)
68                self.syntax_set.find_syntax_by_token(extension)
69            })
70            .or_else(|| {
71                // If we have a fallback extension (for TypeScript, Vue, Svelte), try it
72                fallback_extension.and_then(|fallback| {
73                    self.syntax_set
74                        .find_syntax_by_extension(fallback)
75                        .or_else(|| self.syntax_set.find_syntax_by_token(fallback))
76                })
77            })
78    }
79}
80
81// Global syntax highlighter (initialized on first use)
82use std::sync::OnceLock;
83static SYNTAX_HIGHLIGHTER: OnceLock<SyntaxHighlighter> = OnceLock::new();
84
85fn get_syntax_highlighter() -> &'static SyntaxHighlighter {
86    SYNTAX_HIGHLIGHTER.get_or_init(SyntaxHighlighter::new)
87}
88
89/// Output formatter configuration
90pub struct OutputFormatter {
91    /// Whether to use colors and formatting
92    pub use_colors: bool,
93    /// Whether to use syntax highlighting
94    pub use_syntax_highlighting: bool,
95    /// Terminal width for full-width separators
96    terminal_width: u16,
97}
98
99impl OutputFormatter {
100    /// Create a new formatter with automatic TTY detection
101    pub fn new(plain: bool) -> Self {
102        let is_tty = io::stdout().is_tty();
103        let no_color = std::env::var("NO_COLOR").is_ok();
104
105        let use_colors = !plain && !no_color && is_tty;
106
107        // Get terminal width, default to 80 if detection fails
108        let terminal_width = terminal::size().map(|(w, _)| w).unwrap_or(80);
109
110        Self {
111            use_colors,
112            use_syntax_highlighting: use_colors, // Enable syntax highlighting if colors enabled
113            terminal_width,
114        }
115    }
116
117    /// Format and print search results to stdout
118    pub fn format_results(&self, results: &[SearchResult], pattern: &str) -> Result<()> {
119        if results.is_empty() {
120            println!("No results found.");
121            return Ok(());
122        }
123
124        // Group results by file
125        let grouped = self.group_by_file(results);
126
127        // Print each file group
128        for (idx, (file_path, file_results)) in grouped.iter().enumerate() {
129            self.print_file_group(file_path, file_results, pattern, idx == grouped.len() - 1)?;
130        }
131
132        Ok(())
133    }
134
135    /// Group results by file path
136    fn group_by_file<'a>(
137        &self,
138        results: &'a [SearchResult],
139    ) -> Vec<(String, Vec<&'a SearchResult>)> {
140        let mut grouped: HashMap<String, Vec<&'a SearchResult>> = HashMap::new();
141
142        for result in results {
143            grouped.entry(result.path.clone()).or_default().push(result);
144        }
145
146        // Convert to sorted vec (by file path)
147        let mut grouped_vec: Vec<_> = grouped.into_iter().collect();
148        grouped_vec.sort_by(|a, b| a.0.cmp(&b.0));
149
150        grouped_vec
151    }
152
153    /// Print a group of results for a single file
154    fn print_file_group(
155        &self,
156        file_path: &str,
157        results: &[&SearchResult],
158        pattern: &str,
159        is_last_file: bool,
160    ) -> Result<()> {
161        // Print file header
162        self.print_file_header(file_path, results.len())?;
163
164        // Print each result
165        for (idx, result) in results.iter().enumerate() {
166            let is_last_in_file = idx == results.len() - 1;
167            let is_last_overall = is_last_file && is_last_in_file;
168            self.print_result(result, pattern, is_last_overall)?;
169        }
170
171        // Add spacing between file groups (but not after the last file)
172        if !is_last_file {
173            println!();
174        }
175
176        Ok(())
177    }
178
179    /// Print file header with match count
180    fn print_file_header(&self, file_path: &str, count: usize) -> Result<()> {
181        if self.use_colors {
182            // Colorized header with file icon
183            println!(
184                "  {} {} {}",
185                "📁".bright_blue(),
186                file_path.bright_cyan().bold(),
187                format!(
188                    "({} {})",
189                    count,
190                    if count == 1 { "match" } else { "matches" }
191                )
192                .dimmed()
193            );
194        } else {
195            // Plain text header
196            println!(
197                "  {} ({} {})",
198                file_path,
199                count,
200                if count == 1 { "match" } else { "matches" }
201            );
202        }
203
204        Ok(())
205    }
206
207    /// Print a single search result
208    fn print_result(&self, result: &SearchResult, pattern: &str, is_last: bool) -> Result<()> {
209        // Format line number (right-aligned to 4 digits)
210        let line_no = format!("{:>4}", result.span.start_line);
211
212        // Get symbol badge if available
213        let symbol_badge = self.format_symbol_badge(&result.kind, result.symbol.as_deref());
214
215        // Print the line with result
216        if self.use_colors {
217            // Line number and symbol badge
218            println!("    {} {}", line_no.yellow(), symbol_badge);
219
220            // Print code preview with syntax highlighting (indented)
221            let highlighted = self.highlight_code(&result.preview, &result.lang, pattern);
222            println!("        {}", highlighted);
223
224            // Print internal dependencies if available
225            if let Some(deps_formatted) = self.format_internal_dependencies(&result.dependencies) {
226                println!();
227                println!("        {}", "Dependencies:".dimmed());
228                for dep in deps_formatted {
229                    println!("          {}", dep.bright_magenta());
230                }
231            }
232
233            // Add separator line between results (except for the very last one)
234            if !is_last {
235                let separator_width = self.terminal_width.saturating_sub(2) as usize;
236                println!("  {}", "─".repeat(separator_width).truecolor(60, 60, 60));
237            }
238        } else {
239            // Plain text output
240            println!("    {} {}", line_no, symbol_badge);
241            println!("        {}", result.preview);
242
243            // Print internal dependencies if available
244            if let Some(deps_formatted) = self.format_internal_dependencies(&result.dependencies) {
245                println!();
246                println!("        Dependencies:");
247                for dep in deps_formatted {
248                    println!("          {}", dep);
249                }
250            }
251
252            // Add separator line between results (except for the very last one)
253            if !is_last {
254                let separator_width = self.terminal_width.saturating_sub(2) as usize;
255                println!("  {}", "─".repeat(separator_width));
256            }
257        }
258
259        Ok(())
260    }
261
262    /// Format dependencies for display
263    /// Returns None if no dependencies exist
264    /// Note: Database only contains internal dependencies (external/stdlib filtered during indexing)
265    fn format_internal_dependencies(
266        &self,
267        dependencies: &Option<Vec<DependencyInfo>>,
268    ) -> Option<Vec<String>> {
269        dependencies.as_ref().and_then(|deps| {
270            let dep_paths: Vec<String> = deps.iter().map(|dep| dep.path.clone()).collect();
271
272            if dep_paths.is_empty() {
273                None
274            } else {
275                Some(dep_paths)
276            }
277        })
278    }
279
280    /// Format symbol kind badge
281    fn format_symbol_badge(&self, kind: &SymbolKind, symbol: Option<&str>) -> String {
282        let (kind_str, color_fn): (&str, fn(&str) -> String) = match kind {
283            SymbolKind::Function => ("fn", |s| s.green().to_string()),
284            SymbolKind::Class => ("class", |s| s.blue().to_string()),
285            SymbolKind::Struct => ("struct", |s| s.cyan().to_string()),
286            SymbolKind::Enum => ("enum", |s| s.magenta().to_string()),
287            SymbolKind::Trait => ("trait", |s| s.yellow().to_string()),
288            SymbolKind::Interface => ("interface", |s| s.blue().to_string()),
289            SymbolKind::Method => ("method", |s| s.green().to_string()),
290            SymbolKind::Constant => ("const", |s| s.red().to_string()),
291            SymbolKind::Variable => ("var", |s| s.white().to_string()),
292            SymbolKind::Module => ("mod", |s| s.bright_magenta().to_string()),
293            SymbolKind::Namespace => ("namespace", |s| s.bright_magenta().to_string()),
294            SymbolKind::Type => ("type", |s| s.cyan().to_string()),
295            SymbolKind::Macro => ("macro", |s| s.bright_yellow().to_string()),
296            SymbolKind::Property => ("property", |s| s.bright_green().to_string()),
297            SymbolKind::Event => ("event", |s| s.bright_red().to_string()),
298            SymbolKind::Import => ("import", |s| s.bright_blue().to_string()),
299            SymbolKind::Export => ("export", |s| s.bright_blue().to_string()),
300            SymbolKind::Attribute => ("attribute", |s| s.bright_yellow().to_string()),
301            SymbolKind::Unknown(_) => ("", |s| s.white().to_string()),
302        };
303
304        if self.use_colors && !kind_str.is_empty() {
305            if let Some(sym) = symbol {
306                format!("{} {}", color_fn(&format!("[{}]", kind_str)), sym.bold())
307            } else {
308                color_fn(&format!("[{}]", kind_str))
309            }
310        } else if !kind_str.is_empty() {
311            if let Some(sym) = symbol {
312                format!("[{}] {}", kind_str, sym)
313            } else {
314                format!("[{}]", kind_str)
315            }
316        } else {
317            symbol.unwrap_or("").to_string()
318        }
319    }
320
321    /// Highlight code with syntax highlighting
322    fn highlight_code(&self, code: &str, lang: &Language, pattern: &str) -> String {
323        if !self.use_syntax_highlighting {
324            return code.to_string();
325        }
326
327        let highlighter = get_syntax_highlighter();
328
329        // Try to get syntax for the language
330        let syntax = match highlighter.get_syntax(lang) {
331            Some(s) => s,
332            None => {
333                // Fallback: highlight the pattern match manually
334                return self.highlight_pattern(code, pattern);
335            }
336        };
337
338        // Get theme - try Monokai Extended, fall back to base16-ocean.dark or first available
339        let theme = highlighter
340            .theme_set
341            .themes
342            .get("Monokai Extended")
343            .or_else(|| highlighter.theme_set.themes.get("base16-ocean.dark"))
344            .or_else(|| highlighter.theme_set.themes.values().next())
345            .expect("No themes available in syntect");
346
347        let mut output = String::new();
348        let mut h = HighlightLines::new(syntax, theme);
349
350        for line in LinesWithEndings::from(code) {
351            let ranges: Vec<(SyntectStyle, &str)> = h
352                .highlight_line(line, &highlighter.syntax_set)
353                .unwrap_or_default();
354            let escaped = as_24_bit_terminal_escaped(&ranges[..], false);
355            output.push_str(&escaped);
356        }
357
358        // Reset colors to prevent bleeding into subsequent output
359        output.push_str("\x1b[0m");
360
361        output
362    }
363
364    /// Fallback: manually highlight pattern matches in code
365    fn highlight_pattern(&self, code: &str, pattern: &str) -> String {
366        if pattern.is_empty() || !self.use_colors {
367            return code.to_string();
368        }
369
370        // Simple substring highlighting (case-sensitive)
371        if let Some(pos) = code.find(pattern) {
372            let before = &code[..pos];
373            let matched = &code[pos..pos + pattern.len()];
374            let after = &code[pos + pattern.len()..];
375
376            format!("{}{}{}", before, matched.black().on_yellow().bold(), after)
377        } else {
378            code.to_string()
379        }
380    }
381}
382
383// Import color trait extensions
384use owo_colors::OwoColorize;
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use crate::models::Span;
390
391    #[test]
392    fn test_formatter_creation() {
393        // Set NO_COLOR to ensure deterministic test behavior regardless of TTY
394        unsafe {
395            std::env::set_var("NO_COLOR", "1");
396        }
397        let formatter = OutputFormatter::new(false);
398        // With NO_COLOR set, colors should always be disabled
399        assert!(!formatter.use_colors);
400        unsafe {
401            std::env::remove_var("NO_COLOR");
402        }
403    }
404
405    #[test]
406    fn test_plain_mode() {
407        let formatter = OutputFormatter::new(true);
408        assert!(!formatter.use_colors);
409        assert!(!formatter.use_syntax_highlighting);
410    }
411
412    #[test]
413    fn test_group_by_file() {
414        let formatter = OutputFormatter::new(true);
415
416        let results = vec![
417            SearchResult {
418                path: "a.rs".to_string(),
419                lang: Language::Rust,
420                kind: SymbolKind::Function,
421                symbol: Some("foo".to_string()),
422                span: Span {
423                    start_line: 1,
424                    end_line: 1,
425                },
426                preview: "fn foo() {}".to_string(),
427                dependencies: None,
428            },
429            SearchResult {
430                path: "a.rs".to_string(),
431                lang: Language::Rust,
432                kind: SymbolKind::Function,
433                symbol: Some("bar".to_string()),
434                span: Span {
435                    start_line: 2,
436                    end_line: 2,
437                },
438                preview: "fn bar() {}".to_string(),
439                dependencies: None,
440            },
441            SearchResult {
442                path: "b.rs".to_string(),
443                lang: Language::Rust,
444                kind: SymbolKind::Function,
445                symbol: Some("baz".to_string()),
446                span: Span {
447                    start_line: 1,
448                    end_line: 1,
449                },
450                preview: "fn baz() {}".to_string(),
451                dependencies: None,
452            },
453        ];
454
455        let grouped = formatter.group_by_file(&results);
456
457        assert_eq!(grouped.len(), 2);
458        assert_eq!(grouped[0].0, "a.rs");
459        assert_eq!(grouped[0].1.len(), 2);
460        assert_eq!(grouped[1].0, "b.rs");
461        assert_eq!(grouped[1].1.len(), 1);
462    }
463
464    #[test]
465    fn test_symbol_badge_formatting() {
466        let formatter = OutputFormatter::new(true);
467
468        let badge = formatter.format_symbol_badge(&SymbolKind::Function, Some("test"));
469        assert_eq!(badge, "[fn] test");
470
471        let badge = formatter.format_symbol_badge(&SymbolKind::Class, None);
472        assert_eq!(badge, "[class]");
473    }
474}