Skip to content

Commit 2b86643

Browse files
committed
Include some context with search results
1 parent 847359e commit 2b86643

File tree

2 files changed

+27
-15
lines changed

2 files changed

+27
-15
lines changed

src/file_controller/mod.rs

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ use file_controller::results::{
3030
FileResult,
3131
LineResult,
3232
FindResult,
33-
SymbolResult
33+
SymbolResult,
34+
CONTEXT_SIZE,
3435
};
3536

3637
pub struct Cache {
@@ -131,15 +132,6 @@ impl Cache {
131132
}))
132133
}
133134

134-
pub fn get_highlighted_line(
135-
&self,
136-
file_name: &Path,
137-
line: span::Row<span::ZeroIndexed>,
138-
) -> Result<String, String> {
139-
let lines = self.get_highlighted(file_name)?;
140-
Ok(lines[line.0 as usize].clone())
141-
}
142-
143135
pub fn update_analysis(&self) {
144136
println!("Processing analysis...");
145137
let workspace_root = self
@@ -275,11 +267,26 @@ impl Cache {
275267
}
276268

277269
fn make_line_result(&self, file_path: &Path, span: &Span) -> Result<LineResult, String> {
278-
let text = match self.get_highlighted_line(file_path, span.range.row_start) {
279-
Ok(t) => t,
270+
let (text, context) = match self.get_highlighted(file_path) {
271+
Ok(lines) => {
272+
let line = span.range.row_start.0 as i32;
273+
let text = lines[line as usize].clone();
274+
275+
let mut ctx_start = line - CONTEXT_SIZE;
276+
if ctx_start < 0 {
277+
ctx_start = 0;
278+
}
279+
let mut ctx_end = line + CONTEXT_SIZE;
280+
if ctx_end >= lines.len() as i32 {
281+
ctx_end = lines.len() as i32 - 1;
282+
}
283+
let context = lines[ctx_start as usize..=ctx_end as usize].join("\n");
284+
285+
(text, context)
286+
}
280287
Err(_) => return Err(format!("Error finding text for {:?}", span)),
281288
};
282-
Ok(LineResult::new(span, text))
289+
Ok(LineResult::new(span, text, context))
283290
}
284291

285292
// Sorts a set of search results into buckets by file.

src/file_controller/results.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88

99
use super::Span;
1010

11+
// The number of lines before and after a result line to use as context.
12+
pub const CONTEXT_SIZE: i32 = 3;
13+
1114
#[derive(Serialize, Debug, Clone)]
1215
pub struct SearchResult {
1316
pub defs: Vec<DefResult>,
@@ -32,15 +35,17 @@ pub struct LineResult {
3235
pub column_start: u32,
3336
pub column_end: u32,
3437
pub line: String,
38+
pub context: String,
3539
}
3640

3741
impl LineResult {
38-
pub fn new(span: &Span, line: String) -> LineResult {
42+
pub fn new(span: &Span, line: String, context: String) -> LineResult {
3943
LineResult {
4044
line_start: span.range.row_start.one_indexed().0,
4145
column_start: span.range.col_start.one_indexed().0,
4246
column_end: span.range.col_end.one_indexed().0,
43-
line: line,
47+
line,
48+
context,
4449
}
4550
}
4651
}

0 commit comments

Comments
 (0)