Debian Codegraph @

helix-term/src/commands/syntax.rs

raw symbols SCIP
1 use std::{
2 collections::HashSet,
3 iter,
4 path::{Path, PathBuf},
5 sync::Arc,
6 };
7
8 use dashmap::DashMap;
9 use futures_util::FutureExt;
10 use grep_regex::RegexMatcherBuilder;
11 use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
12 use helix_core::{
13 syntax::{Loader, QueryMatchIterEvent},
14 Rope, RopeSlice, Selection, Syntax, Uri,
15 };
16 use helix_stdx::{
17 path,
18 rope::{self, RopeSliceExt},
19 };
20 use helix_view::{
21 align_view,
22 document::{from_reader, SCRATCH_BUFFER_NAME},
23 Align, Document, DocumentId, Editor,
24 };
25 use ignore::{DirEntry, WalkBuilder, WalkState};
26
27 use crate::{
28 filter_picker_entry,
29 ui::{
30 overlay::overlaid,
31 picker::{Injector, PathOrId},
32 Picker, PickerColumn,
33 },
34 };
35
36 use super::Context;
37
38 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
39 enum TagKind {
40 Class,
41 Constant,
42 Enum,
43 Field,
44 Function,
45 Interface,
46 Macro,
47 Module,
48 Section,
49 Struct,
50 Type,
51 }
52
53 impl TagKind {
54 fn as_str(&self) -> &'static str {
55 match self {
56 Self::Class => "class",
57 Self::Constant => "constant",
58 Self::Enum => "enum",
59 Self::Field => "field",
60 Self::Function => "function",
61 Self::Interface => "interface",
62 Self::Macro => "macro",
63 Self::Module => "module",
64 Self::Section => "section",
65 Self::Struct => "struct",
66 Self::Type => "type",
67 }
68 }
69
70 fn from_name(name: &str) -> Option<Self> {
71 match name {
72 "class" => Some(TagKind::Class),
73 "constant" => Some(TagKind::Constant),
74 "enum" => Some(TagKind::Enum),
75 "field" => Some(TagKind::Field),
76 "function" => Some(TagKind::Function),
77 "interface" => Some(TagKind::Interface),
78 "macro" => Some(TagKind::Macro),
79 "module" => Some(TagKind::Module),
80 "section" => Some(TagKind::Section),
81 "struct" => Some(TagKind::Struct),
82 "type" => Some(TagKind::Type),
83 _ => None,
84 }
85 }
86 }
87
88 // NOTE: Uri is cheap to clone and DocumentId is Copy
89 #[derive(Debug, Clone)]
90 enum UriOrDocumentId {
91 Uri(Uri),
92 Id(DocumentId),
93 }
94
95 impl UriOrDocumentId {
96 fn path_or_id(&self) -> Option<PathOrId<'_>> {
97 match self {
98 Self::Id(id) => Some(PathOrId::Id(*id)),
99 Self::Uri(uri) => uri.as_path().map(PathOrId::Path),
100 }
101 }
102 }
103
104 #[derive(Debug)]
105 struct Tag {
106 kind: TagKind,
107 name: String,
108 start: usize,
109 end: usize,
110 start_line: usize,
111 end_line: usize,
112 doc: UriOrDocumentId,
113 }
114
115 fn tags_iter<'a>(
116 syntax: &'a Syntax,
117 loader: &'a Loader,
118 text: RopeSlice<'a>,
119 doc: UriOrDocumentId,
120 pattern: Option<&'a rope::Regex>,
121 ) -> impl Iterator<Item = Tag> + 'a {
122 let mut tags_iter = syntax.tags(text, loader, ..);
123
124 iter::from_fn(move || loop {
125 let QueryMatchIterEvent::Match(mat) = tags_iter.next()? else {
126 continue;
127 };
128 let query = &loader
129 .tag_query(tags_iter.current_language())
130 .expect("must have a tags query to emit matches")
131 .query;
132
133 // Find the @definition.* and optional @name captures in this match.
134 let mut def_capture = None::<(TagKind, std::ops::Range<u32>)>;
135 let mut name_range = None::<std::ops::Range<u32>>;
136 let name_capture = query.get_capture("name");
137
138 for node in mat.nodes.iter() {
139 let capture_name = query.capture_name(node.capture);
140 if let Some(kind) = capture_name
141 .strip_prefix("definition.")
142 .and_then(TagKind::from_name)
143 {
144 def_capture = Some((kind, node.node.byte_range()));
145 } else if name_capture == Some(node.capture) {
146 name_range = Some(node.node.byte_range());
147 }
148 }
149
150 let Some((kind, def_byte_range)) = def_capture else {
151 continue;
152 };
153 let name_byte_range = name_range.unwrap_or_else(|| def_byte_range.clone());
154
155 if pattern.is_some_and(|re| {
156 !re.is_match(
157 text.regex_input_at_bytes(
158 name_byte_range.start as usize..name_byte_range.end as usize,
159 ),
160 )
161 }) {
162 continue;
163 }
164
165 let name_start = text.byte_to_char(name_byte_range.start as usize);
166 let name_end = text.byte_to_char(name_byte_range.end as usize);
167 let def_start = text.byte_to_char(def_byte_range.start as usize);
168 let def_end = text.byte_to_char(def_byte_range.end as usize);
169
170 return Some(Tag {
171 kind,
172 name: text.slice(name_start..name_end).to_string(),
173 start: def_start,
174 end: def_end,
175 start_line: text.char_to_line(def_start),
176 end_line: text.char_to_line(def_end),
177 doc: doc.clone(),
178 });
179 })
180 }
181
182 pub fn syntax_symbol_picker(cx: &mut Context) {
183 let doc = doc!(cx.editor);
184 let Some(syntax) = doc.syntax() else {
185 cx.editor
186 .set_error("Syntax tree is not available on this buffer");
187 return;
188 };
189 let doc_id = doc.id();
190 let text = doc.text().slice(..);
191 let loader = cx.editor.syn_loader.load();
192 let tags = tags_iter(syntax, &loader, text, UriOrDocumentId::Id(doc.id()), None);
193
194 let columns = vec![
195 PickerColumn::new("kind", |tag: &Tag, _| tag.kind.as_str().into()),
196 PickerColumn::new("name", |tag: &Tag, _| tag.name.as_str().into()),
197 ];
198
199 let picker = Picker::new(
200 columns,
201 1, // name
202 tags,
203 (),
204 move |cx, tag, action| {
205 cx.editor.switch(doc_id, action);
206 let view = view_mut!(cx.editor);
207 let doc = doc_mut!(cx.editor, &doc_id);
208 doc.set_selection(view.id, Selection::single(tag.start, tag.end));
209 if action.align_view(view, doc.id()) {
210 align_view(doc, view, Align::Center)
211 }
212 },
213 )
214 .with_preview(|_editor, tag| {
215 Some((tag.doc.path_or_id()?, Some((tag.start_line, tag.end_line))))
216 })
217 .truncate_start(false);
218
219 cx.push_layer(Box::new(overlaid(picker)));
220 }
221
222 pub fn syntax_workspace_symbol_picker(cx: &mut Context) {
223 #[derive(Debug)]
224 struct SearchState {
225 searcher_builder: SearcherBuilder,
226 walk_builder: WalkBuilder,
227 regex_matcher_builder: RegexMatcherBuilder,
228 rope_regex_builder: rope::RegexBuilder,
229 search_root: PathBuf,
230 /// A cache of files that have been parsed in prior searches.
231 syntax_cache: DashMap<PathBuf, Option<(Rope, Syntax)>>,
232 }
233
234 let mut searcher_builder = SearcherBuilder::new();
235 searcher_builder.binary_detection(BinaryDetection::quit(b'\x00'));
236
237 // Search from the workspace that the currently focused document is within. This behaves like global
238 // search most of the time but helps when you have two projects open in splits.
239 let search_root = if let Some(path) = doc!(cx.editor).path() {
240 helix_loader::find_workspace_in(path).0
241 } else {
242 helix_loader::find_workspace().0
243 };
244
245 let absolute_root = search_root
246 .canonicalize()
247 .unwrap_or_else(|_| search_root.clone());
248
249 let config = cx.editor.config();
250 let dedup_symlinks = config.file_picker.deduplicate_links;
251
252 let mut walk_builder = WalkBuilder::new(&search_root);
253 walk_builder
254 .hidden(config.file_picker.hidden)
255 .parents(config.file_picker.parents)
256 .ignore(config.file_picker.ignore)
257 .follow_links(config.file_picker.follow_symlinks)
258 .git_ignore(config.file_picker.git_ignore)
259 .git_global(config.file_picker.git_global)
260 .git_exclude(config.file_picker.git_exclude)
261 .max_depth(config.file_picker.max_depth)
262 .filter_entry(move |entry| filter_picker_entry(entry, &absolute_root, dedup_symlinks))
263 .add_custom_ignore_filename(helix_loader::config_dir().join("ignore"))
264 .add_custom_ignore_filename(".helix/ignore");
265
266 let mut regex_matcher_builder = RegexMatcherBuilder::new();
267 regex_matcher_builder.case_smart(config.search.smart_case);
268 let mut rope_regex_builder = rope::RegexBuilder::new();
269 rope_regex_builder.syntax(rope::Config::new().case_insensitive(config.search.smart_case));
270 let state = SearchState {
271 searcher_builder,
272 walk_builder,
273 regex_matcher_builder,
274 rope_regex_builder,
275 search_root,
276 syntax_cache: DashMap::default(),
277 };
278 let reg = cx.register.unwrap_or('/');
279 cx.editor.registers.last_search_register = reg;
280 let columns = vec![
281 PickerColumn::new("kind", |tag: &Tag, _| tag.kind.as_str().into()),
282 PickerColumn::new("name", |tag: &Tag, _| tag.name.as_str().into()).without_filtering(),
283 PickerColumn::new("path", |tag: &Tag, state: &SearchState| {
284 match &tag.doc {
285 UriOrDocumentId::Uri(uri) => {
286 if let Some(path) = uri.as_path() {
287 let path = if let Ok(stripped) = path.strip_prefix(&state.search_root) {
288 stripped
289 } else {
290 path
291 };
292 path.to_string_lossy().into()
293 } else {
294 uri.to_string().into()
295 }
296 }
297 // This picker only uses `Id` for scratch buffers for better display.
298 UriOrDocumentId::Id(_) => SCRATCH_BUFFER_NAME.into(),
299 }
300 }),
301 ];
302
303 let get_tags = |query: &str,
304 editor: &mut Editor,
305 state: Arc<SearchState>,
306 injector: &Injector<_, _>| {
307 if query.len() < 3 {
308 return async { Ok(()) }.boxed();
309 }
310 // Attempt to find the tag in any open documents.
311 let pattern = match state.rope_regex_builder.build(query) {
312 Ok(pattern) => pattern,
313 Err(err) => return async { Err(anyhow::anyhow!(err)) }.boxed(),
314 };
315 let loader = editor.syn_loader.load();
316 for doc in editor.documents() {
317 let Some(syntax) = doc.syntax() else { continue };
318 let text = doc.text().slice(..);
319 let uri_or_id = doc
320 .uri()
321 .map(UriOrDocumentId::Uri)
322 .unwrap_or_else(|| UriOrDocumentId::Id(doc.id()));
323 for tag in tags_iter(syntax, &loader, text.slice(..), uri_or_id, Some(&pattern)) {
324 if injector.push(tag).is_err() {
325 return async { Ok(()) }.boxed();
326 }
327 }
328 }
329 if !state.search_root.exists() {
330 return async { Err(anyhow::anyhow!("Current working directory does not exist")) }
331 .boxed();
332 }
333 let matcher = match state.regex_matcher_builder.build(query) {
334 Ok(matcher) => {
335 // Clear any "Failed to compile regex" errors out of the statusline.
336 editor.clear_status();
337 matcher
338 }
339 Err(err) => {
340 log::info!(
341 "Failed to compile search pattern in workspace symbol search: {}",
342 err
343 );
344 return async { Err(anyhow::anyhow!("Failed to compile regex")) }.boxed();
345 }
346 };
347 let pattern = Arc::new(pattern);
348 let injector = injector.clone();
349 let loader = editor.syn_loader.load();
350
351 let documents: HashSet<_> = editor
352 .documents()
353 .filter_map(Document::path)
354 .map(ToOwned::to_owned)
355 .collect();
356
357 async move {
358 let searcher = state.searcher_builder.build();
359 state.walk_builder.build_parallel().run(|| {
360 let mut searcher = searcher.clone();
361 let matcher = matcher.clone();
362 let injector = injector.clone();
363 let loader = loader.clone();
364 let documents = &documents;
365 let pattern = pattern.clone();
366 let syntax_cache = &state.syntax_cache;
367 Box::new(move |entry: Result<DirEntry, ignore::Error>| -> WalkState {
368 let entry = match entry {
369 Ok(entry) => entry,
370 Err(_) => return WalkState::Continue,
371 };
372 if !entry.path().is_file() {
373 return WalkState::Continue;
374 }
375 let path = entry.path();
376 // If this document is open, skip it because we've already processed it above.
377 if documents.contains(path) {
378 return WalkState::Continue;
379 };
380 let mut quit = false;
381 let sink = sinks::UTF8(|_line, _content| {
382 if !syntax_cache.contains_key(path) {
383 // Read the file into a Rope and attempt to recognize the language
384 // and parse it with tree-sitter. Save the Rope and Syntax for future
385 // queries.
386 syntax_cache.insert(path.to_path_buf(), syntax_for_path(path, &loader));
387 };
388 let entry = syntax_cache.get(path).unwrap();
389 let Some((text, syntax)) = entry.value() else {
390 // If the file couldn't be parsed, move on.
391 return Ok(false);
392 };
393 let uri = Uri::from(path::normalize(path));
394 for tag in tags_iter(
395 syntax,
396 &loader,
397 text.slice(..),
398 UriOrDocumentId::Uri(uri),
399 Some(&pattern),
400 ) {
401 if injector.push(tag).is_err() {
402 quit = true;
403 break;
404 }
405 }
406 // Quit after seeing the first regex match. We only care to find files
407 // that contain the pattern and then we run the tags query within
408 // those. The location and contents of a match are irrelevant - it's
409 // only important _if_ a file matches.
410 Ok(false)
411 });
412 if let Err(err) = searcher.search_path(&matcher, path, sink) {
413 log::info!("Workspace syntax search error: {}, {}", path.display(), err);
414 }
415 if quit {
416 WalkState::Quit
417 } else {
418 WalkState::Continue
419 }
420 })
421 });
422 Ok(())
423 }
424 .boxed()
425 };
426 let picker = Picker::new(
427 columns,
428 1, // name
429 [],
430 state,
431 move |cx, tag, action| {
432 let doc_id = match &tag.doc {
433 UriOrDocumentId::Id(id) => *id,
434 UriOrDocumentId::Uri(uri) => match cx.editor.open(uri.as_path().expect(""), action) {
435 Ok(id) => id,
436 Err(e) => {
437 cx.editor
438 .set_error(format!("Failed to open file '{uri:?}': {e}"));
439 return;
440 }
441 }
442 };
443 let doc = doc_mut!(cx.editor, &doc_id);
444 let view = view_mut!(cx.editor);
445 let len_chars = doc.text().len_chars();
446 if tag.start >= len_chars || tag.end > len_chars {
447 cx.editor.set_error("The location you jumped to does not exist anymore because the file has changed.");
448 return;
449 }
450 doc.set_selection(view.id, Selection::single(tag.start, tag.end));
451 if action.align_view(view, doc.id()) {
452 align_view(doc, view, Align::Center)
453 }
454 },
455 )
456 .with_dynamic_query(get_tags, Some(275))
457 .with_preview(move |_editor, tag| {
458 Some((
459 tag.doc.path_or_id()?,
460 Some((tag.start_line, tag.end_line)),
461 ))
462 })
463 .with_history_register(Some(reg))
464 .truncate_start(false);
465 cx.push_layer(Box::new(overlaid(picker)));
466 }
467
468 /// Create a Rope and language config for a given existing path without creating a full Document.
469 fn syntax_for_path(path: &Path, loader: &Loader) -> Option<(Rope, Syntax)> {
470 let mut file = std::fs::File::open(path).ok()?;
471 let (rope, _encoding, _has_bom) = from_reader(&mut file, None).ok()?;
472 let text = rope.slice(..);
473 let language = loader
474 .language_for_filename(path)
475 .or_else(|| loader.language_for_shebang(text))?;
476 Syntax::new(text, language, loader)
477 .ok()
478 .map(|syntax| (rope, syntax))
479 }