1use command_palette_hooks::CommandPaletteFilter;
2use editor::{Anchor, Editor, ExcerptId, SelectionEffects, scroll::Autoscroll};
3use gpui::{
4 App, AppContext as _, Context, Div, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
5 Hsla, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent,
6 ParentElement, Render, ScrollStrategy, SharedString, Styled, Task, UniformListScrollHandle,
7 WeakEntity, Window, actions, div, rems, uniform_list,
8};
9use language::{Buffer, OwnedSyntaxLayer};
10use std::{any::TypeId, mem, ops::Range};
11use theme::ActiveTheme;
12use tree_sitter::{Node, TreeCursor};
13use ui::{
14 ButtonCommon, ButtonLike, Clickable, Color, ContextMenu, FluentBuilder as _, IconButton,
15 IconName, Label, LabelCommon, LabelSize, PopoverMenu, StyledExt, Tooltip, WithScrollbar,
16 h_flex, v_flex,
17};
18use workspace::{
19 Event as WorkspaceEvent, SplitDirection, ToolbarItemEvent, ToolbarItemLocation,
20 ToolbarItemView, Workspace,
21 item::{Item, ItemHandle},
22};
23
24actions!(
25 dev,
26 [
27 /// Opens the syntax tree view for the current file.
28 OpenSyntaxTreeView,
29 ]
30);
31
32actions!(
33 syntax_tree_view,
34 [
35 /// Update the syntax tree view to show the last focused file.
36 UseActiveEditor
37 ]
38);
39
40pub fn init(cx: &mut App) {
41 let syntax_tree_actions = [TypeId::of::<UseActiveEditor>()];
42
43 CommandPaletteFilter::update_global(cx, |this, _| {
44 this.hide_action_types(&syntax_tree_actions);
45 });
46
47 cx.observe_new(move |workspace: &mut Workspace, _, _| {
48 workspace.register_action(move |workspace, _: &OpenSyntaxTreeView, window, cx| {
49 CommandPaletteFilter::update_global(cx, |this, _| {
50 this.show_action_types(&syntax_tree_actions);
51 });
52
53 let active_item = workspace.active_item(cx);
54 let workspace_handle = workspace.weak_handle();
55 let syntax_tree_view = cx.new(|cx| {
56 cx.on_release(move |view: &mut SyntaxTreeView, cx| {
57 if view
58 .workspace_handle
59 .read_with(cx, |workspace, cx| {
60 workspace.item_of_type::<SyntaxTreeView>(cx).is_none()
61 })
62 .unwrap_or_default()
63 {
64 CommandPaletteFilter::update_global(cx, |this, _| {
65 this.hide_action_types(&syntax_tree_actions);
66 });
67 }
68 })
69 .detach();
70
71 SyntaxTreeView::new(workspace_handle, active_item, window, cx)
72 });
73 workspace.split_item(
74 SplitDirection::Right,
75 Box::new(syntax_tree_view),
76 window,
77 cx,
78 )
79 });
80 workspace.register_action(|workspace, _: &UseActiveEditor, window, cx| {
81 if let Some(tree_view) = workspace.item_of_type::<SyntaxTreeView>(cx) {
82 tree_view.update(cx, |view, cx| {
83 view.update_active_editor(&Default::default(), window, cx)
84 })
85 }
86 });
87 })
88 .detach();
89}
90
91pub struct SyntaxTreeView {
92 workspace_handle: WeakEntity<Workspace>,
93 editor: Option<EditorState>,
94 list_scroll_handle: UniformListScrollHandle,
95 /// The last active editor in the workspace. Note that this is specifically not the
96 /// currently shown editor.
97 last_active_editor: Option<Entity<Editor>>,
98 selected_descendant_ix: Option<usize>,
99 hovered_descendant_ix: Option<usize>,
100 focus_handle: FocusHandle,
101}
102
103pub struct SyntaxTreeToolbarItemView {
104 tree_view: Option<Entity<SyntaxTreeView>>,
105 subscription: Option<gpui::Subscription>,
106}
107
108struct EditorState {
109 editor: Entity<Editor>,
110 active_buffer: Option<BufferState>,
111 _subscription: gpui::Subscription,
112}
113
114impl EditorState {
115 fn has_language(&self) -> bool {
116 self.active_buffer
117 .as_ref()
118 .is_some_and(|buffer| buffer.active_layer.is_some())
119 }
120}
121
122#[derive(Clone)]
123struct BufferState {
124 buffer: Entity<Buffer>,
125 excerpt_id: ExcerptId,
126 active_layer: Option<OwnedSyntaxLayer>,
127}
128
129impl SyntaxTreeView {
130 pub fn new(
131 workspace_handle: WeakEntity<Workspace>,
132 active_item: Option<Box<dyn ItemHandle>>,
133 window: &mut Window,
134 cx: &mut Context<Self>,
135 ) -> Self {
136 let mut this = Self {
137 workspace_handle: workspace_handle.clone(),
138 list_scroll_handle: UniformListScrollHandle::new(),
139 editor: None,
140 last_active_editor: None,
141 hovered_descendant_ix: None,
142 selected_descendant_ix: None,
143 focus_handle: cx.focus_handle(),
144 };
145
146 this.handle_item_updated(active_item, window, cx);
147
148 cx.subscribe_in(
149 &workspace_handle.upgrade().unwrap(),
150 window,
151 move |this, workspace, event, window, cx| match event {
152 WorkspaceEvent::ItemAdded { .. } | WorkspaceEvent::ActiveItemChanged => {
153 this.handle_item_updated(workspace.read(cx).active_item(cx), window, cx)
154 }
155 WorkspaceEvent::ItemRemoved { item_id } => {
156 this.handle_item_removed(item_id, window, cx);
157 }
158 _ => {}
159 },
160 )
161 .detach();
162
163 this
164 }
165
166 fn handle_item_updated(
167 &mut self,
168 active_item: Option<Box<dyn ItemHandle>>,
169 window: &mut Window,
170 cx: &mut Context<Self>,
171 ) {
172 let Some(editor) = active_item
173 .filter(|item| item.item_id() != cx.entity_id())
174 .and_then(|item| item.act_as::<Editor>(cx))
175 else {
176 return;
177 };
178
179 if let Some(editor_state) = self.editor.as_ref().filter(|state| state.has_language()) {
180 self.last_active_editor = (editor_state.editor != editor).then_some(editor);
181 } else {
182 self.set_editor(editor, window, cx);
183 }
184 }
185
186 fn handle_item_removed(
187 &mut self,
188 item_id: &EntityId,
189 window: &mut Window,
190 cx: &mut Context<Self>,
191 ) {
192 if self
193 .editor
194 .as_ref()
195 .is_some_and(|state| state.editor.entity_id() == *item_id)
196 {
197 self.editor = None;
198 // Try activating the last active editor if there is one
199 self.update_active_editor(&Default::default(), window, cx);
200 cx.notify();
201 }
202 }
203
204 fn update_active_editor(
205 &mut self,
206 _: &UseActiveEditor,
207 window: &mut Window,
208 cx: &mut Context<Self>,
209 ) {
210 let Some(editor) = self.last_active_editor.take() else {
211 return;
212 };
213 self.set_editor(editor, window, cx);
214 }
215
216 fn set_editor(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut Context<Self>) {
217 if let Some(state) = &self.editor {
218 if state.editor == editor {
219 return;
220 }
221 editor.update(cx, |editor, cx| {
222 editor.clear_background_highlights::<Self>(cx)
223 });
224 }
225
226 let subscription = cx.subscribe_in(&editor, window, |this, _, event, window, cx| {
227 let did_reparse = match event {
228 editor::EditorEvent::Reparsed(_) => true,
229 editor::EditorEvent::SelectionsChanged { .. } => false,
230 _ => return,
231 };
232 this.editor_updated(did_reparse, window, cx);
233 });
234
235 self.editor = Some(EditorState {
236 editor,
237 _subscription: subscription,
238 active_buffer: None,
239 });
240 self.editor_updated(true, window, cx);
241 }
242
243 fn editor_updated(
244 &mut self,
245 did_reparse: bool,
246 window: &mut Window,
247 cx: &mut Context<Self>,
248 ) -> Option<()> {
249 // Find which excerpt the cursor is in, and the position within that excerpted buffer.
250 let editor_state = self.editor.as_mut()?;
251 let snapshot = editor_state
252 .editor
253 .update(cx, |editor, cx| editor.snapshot(window, cx));
254 let (buffer, range, excerpt_id) = editor_state.editor.update(cx, |editor, cx| {
255 let selection_range = editor
256 .selections
257 .last::<usize>(&editor.display_snapshot(cx))
258 .range();
259 let multi_buffer = editor.buffer().read(cx);
260 let (buffer, range, excerpt_id) = snapshot
261 .buffer_snapshot()
262 .range_to_buffer_ranges(selection_range)
263 .pop()?;
264 let buffer = multi_buffer.buffer(buffer.remote_id()).unwrap();
265 Some((buffer, range, excerpt_id))
266 })?;
267
268 // If the cursor has moved into a different excerpt, retrieve a new syntax layer
269 // from that buffer.
270 let buffer_state = editor_state
271 .active_buffer
272 .get_or_insert_with(|| BufferState {
273 buffer: buffer.clone(),
274 excerpt_id,
275 active_layer: None,
276 });
277 let mut prev_layer = None;
278 if did_reparse {
279 prev_layer = buffer_state.active_layer.take();
280 }
281 if buffer_state.buffer != buffer || buffer_state.excerpt_id != excerpt_id {
282 buffer_state.buffer = buffer.clone();
283 buffer_state.excerpt_id = excerpt_id;
284 buffer_state.active_layer = None;
285 }
286
287 let layer = match &mut buffer_state.active_layer {
288 Some(layer) => layer,
289 None => {
290 let snapshot = buffer.read(cx).snapshot();
291 let layer = if let Some(prev_layer) = prev_layer {
292 let prev_range = prev_layer.node().byte_range();
293 snapshot
294 .syntax_layers()
295 .filter(|layer| layer.language == &prev_layer.language)
296 .min_by_key(|layer| {
297 let range = layer.node().byte_range();
298 ((range.start as i64) - (prev_range.start as i64)).abs()
299 + ((range.end as i64) - (prev_range.end as i64)).abs()
300 })?
301 } else {
302 snapshot.syntax_layers().next()?
303 };
304 buffer_state.active_layer.insert(layer.to_owned())
305 }
306 };
307
308 // Within the active layer, find the syntax node under the cursor,
309 // and scroll to it.
310 let mut cursor = layer.node().walk();
311 while cursor.goto_first_child_for_byte(range.start).is_some() {
312 if !range.is_empty() && cursor.node().end_byte() == range.start {
313 cursor.goto_next_sibling();
314 }
315 }
316
317 // Ascend to the smallest ancestor that contains the range.
318 loop {
319 let node_range = cursor.node().byte_range();
320 if node_range.start <= range.start && node_range.end >= range.end {
321 break;
322 }
323 if !cursor.goto_parent() {
324 break;
325 }
326 }
327
328 let descendant_ix = cursor.descendant_index();
329 self.selected_descendant_ix = Some(descendant_ix);
330 self.list_scroll_handle
331 .scroll_to_item(descendant_ix, ScrollStrategy::Center);
332
333 cx.notify();
334 Some(())
335 }
336
337 fn update_editor_with_range_for_descendant_ix(
338 &self,
339 descendant_ix: usize,
340 window: &mut Window,
341 cx: &mut Context<Self>,
342 mut f: impl FnMut(&mut Editor, Range<Anchor>, &mut Window, &mut Context<Editor>),
343 ) -> Option<()> {
344 let editor_state = self.editor.as_ref()?;
345 let buffer_state = editor_state.active_buffer.as_ref()?;
346 let layer = buffer_state.active_layer.as_ref()?;
347
348 // Find the node.
349 let mut cursor = layer.node().walk();
350 cursor.goto_descendant(descendant_ix);
351 let node = cursor.node();
352 let range = node.byte_range();
353
354 // Build a text anchor range.
355 let buffer = buffer_state.buffer.read(cx);
356 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
357
358 // Build a multibuffer anchor range.
359 let multibuffer = editor_state.editor.read(cx).buffer();
360 let multibuffer = multibuffer.read(cx).snapshot(cx);
361 let excerpt_id = buffer_state.excerpt_id;
362 let range = multibuffer.anchor_range_in_excerpt(excerpt_id, range)?;
363
364 // Update the editor with the anchor range.
365 editor_state.editor.update(cx, |editor, cx| {
366 f(editor, range, window, cx);
367 });
368 Some(())
369 }
370
371 fn render_node(cursor: &TreeCursor, depth: u32, selected: bool, cx: &App) -> Div {
372 let colors = cx.theme().colors();
373 let mut row = h_flex();
374 if let Some(field_name) = cursor.field_name() {
375 row = row.children([Label::new(field_name).color(Color::Info), Label::new(": ")]);
376 }
377
378 let node = cursor.node();
379 row.child(if node.is_named() {
380 Label::new(node.kind()).color(Color::Default)
381 } else {
382 Label::new(format!("\"{}\"", node.kind())).color(Color::Created)
383 })
384 .child(
385 div()
386 .child(Label::new(format_node_range(node)).color(Color::Muted))
387 .pl_1(),
388 )
389 .text_bg(if selected {
390 colors.element_selected
391 } else {
392 Hsla::default()
393 })
394 .pl(rems(depth as f32))
395 .hover(|style| style.bg(colors.element_hover))
396 }
397
398 fn compute_items(
399 &mut self,
400 layer: &OwnedSyntaxLayer,
401 range: Range<usize>,
402 cx: &Context<Self>,
403 ) -> Vec<Div> {
404 let mut items = Vec::new();
405 let mut cursor = layer.node().walk();
406 let mut descendant_ix = range.start;
407 cursor.goto_descendant(descendant_ix);
408 let mut depth = cursor.depth();
409 let mut visited_children = false;
410 while descendant_ix < range.end {
411 if visited_children {
412 if cursor.goto_next_sibling() {
413 visited_children = false;
414 } else if cursor.goto_parent() {
415 depth -= 1;
416 } else {
417 break;
418 }
419 } else {
420 items.push(
421 Self::render_node(
422 &cursor,
423 depth,
424 Some(descendant_ix) == self.selected_descendant_ix,
425 cx,
426 )
427 .on_mouse_down(
428 MouseButton::Left,
429 cx.listener(move |tree_view, _: &MouseDownEvent, window, cx| {
430 tree_view.update_editor_with_range_for_descendant_ix(
431 descendant_ix,
432 window,
433 cx,
434 |editor, mut range, window, cx| {
435 // Put the cursor at the beginning of the node.
436 mem::swap(&mut range.start, &mut range.end);
437
438 editor.change_selections(
439 SelectionEffects::scroll(Autoscroll::newest()),
440 window,
441 cx,
442 |selections| {
443 selections.select_ranges(vec![range]);
444 },
445 );
446 },
447 );
448 }),
449 )
450 .on_mouse_move(cx.listener(
451 move |tree_view, _: &MouseMoveEvent, window, cx| {
452 if tree_view.hovered_descendant_ix != Some(descendant_ix) {
453 tree_view.hovered_descendant_ix = Some(descendant_ix);
454 tree_view.update_editor_with_range_for_descendant_ix(
455 descendant_ix,
456 window,
457 cx,
458 |editor, range, _, cx| {
459 editor.clear_background_highlights::<Self>(cx);
460 editor.highlight_background::<Self>(
461 &[range],
462 |theme| {
463 theme
464 .colors()
465 .editor_document_highlight_write_background
466 },
467 cx,
468 );
469 },
470 );
471 cx.notify();
472 }
473 },
474 )),
475 );
476 descendant_ix += 1;
477 if cursor.goto_first_child() {
478 depth += 1;
479 } else {
480 visited_children = true;
481 }
482 }
483 }
484 items
485 }
486}
487
488impl Render for SyntaxTreeView {
489 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
490 div()
491 .flex_1()
492 .bg(cx.theme().colors().editor_background)
493 .map(|this| {
494 let editor_state = self.editor.as_ref();
495
496 if let Some(layer) = editor_state
497 .and_then(|editor| editor.active_buffer.as_ref())
498 .and_then(|buffer| buffer.active_layer.as_ref())
499 {
500 let layer = layer.clone();
501 this.child(
502 uniform_list(
503 "SyntaxTreeView",
504 layer.node().descendant_count(),
505 cx.processor(move |this, range: Range<usize>, _, cx| {
506 this.compute_items(&layer, range, cx)
507 }),
508 )
509 .size_full()
510 .track_scroll(self.list_scroll_handle.clone())
511 .text_bg(cx.theme().colors().background)
512 .into_any_element(),
513 )
514 .vertical_scrollbar_for(self.list_scroll_handle.clone(), window, cx)
515 .into_any_element()
516 } else {
517 let inner_content = v_flex()
518 .items_center()
519 .text_center()
520 .gap_2()
521 .max_w_3_5()
522 .map(|this| {
523 if editor_state.is_some_and(|state| !state.has_language()) {
524 this.child(Label::new("Current editor has no associated language"))
525 .child(
526 Label::new(concat!(
527 "Try assigning a language or",
528 "switching to a different buffer"
529 ))
530 .size(LabelSize::Small),
531 )
532 } else {
533 this.child(Label::new("Not attached to an editor")).child(
534 Label::new("Focus an editor to show a new tree view")
535 .size(LabelSize::Small),
536 )
537 }
538 });
539
540 this.h_flex()
541 .size_full()
542 .justify_center()
543 .child(inner_content)
544 .into_any_element()
545 }
546 })
547 }
548}
549
550impl EventEmitter<()> for SyntaxTreeView {}
551
552impl Focusable for SyntaxTreeView {
553 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
554 self.focus_handle.clone()
555 }
556}
557
558impl Item for SyntaxTreeView {
559 type Event = ();
560
561 fn to_item_events(_: &Self::Event, _: impl FnMut(workspace::item::ItemEvent)) {}
562
563 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
564 "Syntax Tree".into()
565 }
566
567 fn telemetry_event_text(&self) -> Option<&'static str> {
568 None
569 }
570
571 fn clone_on_split(
572 &self,
573 _: Option<workspace::WorkspaceId>,
574 window: &mut Window,
575 cx: &mut Context<Self>,
576 ) -> Task<Option<Entity<Self>>>
577 where
578 Self: Sized,
579 {
580 Task::ready(Some(cx.new(|cx| {
581 let mut clone = Self::new(self.workspace_handle.clone(), None, window, cx);
582 if let Some(editor) = &self.editor {
583 clone.set_editor(editor.editor.clone(), window, cx)
584 }
585 clone
586 })))
587 }
588}
589
590impl Default for SyntaxTreeToolbarItemView {
591 fn default() -> Self {
592 Self::new()
593 }
594}
595
596impl SyntaxTreeToolbarItemView {
597 pub fn new() -> Self {
598 Self {
599 tree_view: None,
600 subscription: None,
601 }
602 }
603
604 fn render_menu(&mut self, cx: &mut Context<Self>) -> Option<PopoverMenu<ContextMenu>> {
605 let tree_view = self.tree_view.as_ref()?;
606 let tree_view = tree_view.read(cx);
607
608 let editor_state = tree_view.editor.as_ref()?;
609 let buffer_state = editor_state.active_buffer.as_ref()?;
610 let active_layer = buffer_state.active_layer.clone()?;
611 let active_buffer = buffer_state.buffer.read(cx).snapshot();
612
613 let view = cx.entity();
614 Some(
615 PopoverMenu::new("Syntax Tree")
616 .trigger(Self::render_header(&active_layer))
617 .menu(move |window, cx| {
618 ContextMenu::build(window, cx, |mut menu, window, _| {
619 for (layer_ix, layer) in active_buffer.syntax_layers().enumerate() {
620 menu = menu.entry(
621 format!(
622 "{} {}",
623 layer.language.name(),
624 format_node_range(layer.node())
625 ),
626 None,
627 window.handler_for(&view, move |view, window, cx| {
628 view.select_layer(layer_ix, window, cx);
629 }),
630 );
631 }
632 menu
633 })
634 .into()
635 }),
636 )
637 }
638
639 fn select_layer(
640 &mut self,
641 layer_ix: usize,
642 window: &mut Window,
643 cx: &mut Context<Self>,
644 ) -> Option<()> {
645 let tree_view = self.tree_view.as_ref()?;
646 tree_view.update(cx, |view, cx| {
647 let editor_state = view.editor.as_mut()?;
648 let buffer_state = editor_state.active_buffer.as_mut()?;
649 let snapshot = buffer_state.buffer.read(cx).snapshot();
650 let layer = snapshot.syntax_layers().nth(layer_ix)?;
651 buffer_state.active_layer = Some(layer.to_owned());
652 view.selected_descendant_ix = None;
653 cx.notify();
654 view.focus_handle.focus(window);
655 Some(())
656 })
657 }
658
659 fn render_header(active_layer: &OwnedSyntaxLayer) -> ButtonLike {
660 ButtonLike::new("syntax tree header")
661 .child(Label::new(active_layer.language.name()))
662 .child(Label::new(format_node_range(active_layer.node())))
663 }
664
665 fn render_update_button(&mut self, cx: &mut Context<Self>) -> Option<IconButton> {
666 self.tree_view.as_ref().and_then(|view| {
667 view.update(cx, |view, cx| {
668 view.last_active_editor.as_ref().map(|editor| {
669 IconButton::new("syntax-view-update", IconName::RotateCw)
670 .tooltip({
671 let active_tab_name = editor.read_with(cx, |editor, cx| {
672 editor.tab_content_text(Default::default(), cx)
673 });
674
675 Tooltip::text(format!("Update view to '{active_tab_name}'"))
676 })
677 .on_click(cx.listener(|this, _, window, cx| {
678 this.update_active_editor(&Default::default(), window, cx);
679 }))
680 })
681 })
682 })
683 }
684}
685
686fn format_node_range(node: Node) -> String {
687 let start = node.start_position();
688 let end = node.end_position();
689 format!(
690 "[{}:{} - {}:{}]",
691 start.row + 1,
692 start.column + 1,
693 end.row + 1,
694 end.column + 1,
695 )
696}
697
698impl Render for SyntaxTreeToolbarItemView {
699 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
700 h_flex()
701 .gap_1()
702 .children(self.render_menu(cx))
703 .children(self.render_update_button(cx))
704 }
705}
706
707impl EventEmitter<ToolbarItemEvent> for SyntaxTreeToolbarItemView {}
708
709impl ToolbarItemView for SyntaxTreeToolbarItemView {
710 fn set_active_pane_item(
711 &mut self,
712 active_pane_item: Option<&dyn ItemHandle>,
713 window: &mut Window,
714 cx: &mut Context<Self>,
715 ) -> ToolbarItemLocation {
716 if let Some(item) = active_pane_item
717 && let Some(view) = item.downcast::<SyntaxTreeView>()
718 {
719 self.tree_view = Some(view.clone());
720 self.subscription = Some(cx.observe_in(&view, window, |_, _, _, cx| cx.notify()));
721 return ToolbarItemLocation::PrimaryLeft;
722 }
723 self.tree_view = None;
724 self.subscription = None;
725 ToolbarItemLocation::Hidden
726 }
727}