outline.rs

  1use anyhow::Result;
  2use gpui::{AsyncApp, Entity};
  3use language::{Buffer, OutlineItem};
  4use regex::Regex;
  5use std::fmt::Write;
  6use text::Point;
  7
  8/// For files over this size, instead of reading them (or including them in context),
  9/// we automatically provide the file's symbol outline instead, with line numbers.
 10pub const AUTO_OUTLINE_SIZE: usize = 16384;
 11
 12/// Result of getting buffer content, which can be either full content or an outline.
 13pub struct BufferContent {
 14    /// The actual content (either full text or outline)
 15    pub text: String,
 16    /// Whether this is an outline (true) or full content (false)
 17    pub is_outline: bool,
 18}
 19
 20/// Returns either the full content of a buffer or its outline, depending on size.
 21/// For files larger than AUTO_OUTLINE_SIZE, returns an outline with a header.
 22/// For smaller files, returns the full content.
 23pub async fn get_buffer_content_or_outline(
 24    buffer: Entity<Buffer>,
 25    path: Option<&str>,
 26    cx: &AsyncApp,
 27) -> Result<BufferContent> {
 28    let file_size = buffer.read_with(cx, |buffer, _| buffer.text().len())?;
 29
 30    if file_size > AUTO_OUTLINE_SIZE {
 31        // For large files, use outline instead of full content
 32        // Wait until the buffer has been fully parsed, so we can read its outline
 33        buffer
 34            .read_with(cx, |buffer, _| buffer.parsing_idle())?
 35            .await;
 36
 37        let outline_items = buffer.read_with(cx, |buffer, _| {
 38            let snapshot = buffer.snapshot();
 39            snapshot
 40                .outline(None)
 41                .items
 42                .into_iter()
 43                .map(|item| item.to_point(&snapshot))
 44                .collect::<Vec<_>>()
 45        })?;
 46
 47        let outline_text = render_outline(outline_items, None, 0, usize::MAX).await?;
 48
 49        let text = if let Some(path) = path {
 50            format!(
 51                "# File outline for {path} (file too large to show full content)\n\n{outline_text}",
 52            )
 53        } else {
 54            format!("# File outline (file too large to show full content)\n\n{outline_text}",)
 55        };
 56        Ok(BufferContent {
 57            text,
 58            is_outline: true,
 59        })
 60    } else {
 61        // File is small enough, return full content
 62        let text = buffer.read_with(cx, |buffer, _| buffer.text())?;
 63        Ok(BufferContent {
 64            text,
 65            is_outline: false,
 66        })
 67    }
 68}
 69
 70async fn render_outline(
 71    items: impl IntoIterator<Item = OutlineItem<Point>>,
 72    regex: Option<Regex>,
 73    offset: usize,
 74    results_per_page: usize,
 75) -> Result<String> {
 76    let mut items = items.into_iter().skip(offset);
 77
 78    let entries = items
 79        .by_ref()
 80        .filter(|item| {
 81            regex
 82                .as_ref()
 83                .is_none_or(|regex| regex.is_match(&item.text))
 84        })
 85        .take(results_per_page)
 86        .collect::<Vec<_>>();
 87    let has_more = items.next().is_some();
 88
 89    let mut output = String::new();
 90    let entries_rendered = render_entries(&mut output, entries);
 91
 92    // Calculate pagination information
 93    let page_start = offset + 1;
 94    let page_end = offset + entries_rendered;
 95    let total_symbols = if has_more {
 96        format!("more than {}", page_end)
 97    } else {
 98        page_end.to_string()
 99    };
100
101    // Add pagination information
102    if has_more {
103        writeln!(&mut output, "\nShowing symbols {page_start}-{page_end} (there were more symbols found; use offset: {page_end} to see next page)",
104        )
105    } else {
106        writeln!(
107            &mut output,
108            "\nShowing symbols {page_start}-{page_end} (total symbols: {total_symbols})",
109        )
110    }
111    .ok();
112
113    Ok(output)
114}
115
116fn render_entries(
117    output: &mut String,
118    items: impl IntoIterator<Item = OutlineItem<Point>>,
119) -> usize {
120    let mut entries_rendered = 0;
121
122    for item in items {
123        // Indent based on depth ("" for level 0, "  " for level 1, etc.)
124        for _ in 0..item.depth {
125            output.push(' ');
126        }
127        output.push_str(&item.text);
128
129        // Add position information - convert to 1-based line numbers for display
130        let start_line = item.range.start.row + 1;
131        let end_line = item.range.end.row + 1;
132
133        if start_line == end_line {
134            writeln!(output, " [L{}]", start_line).ok();
135        } else {
136            writeln!(output, " [L{}-{}]", start_line, end_line).ok();
137        }
138        entries_rendered += 1;
139    }
140
141    entries_rendered
142}