1use std::cmp::min;
2use std::sync::Arc;
3use std::time::Duration;
4use std::{ops::Range, path::PathBuf};
5
6use anyhow::Result;
7use editor::scroll::Autoscroll;
8use editor::{Editor, EditorEvent, MultiBufferOffset, SelectionEffects};
9use gpui::{
10 App, ClickEvent, Context, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
11 IntoElement, IsZero, ListState, ParentElement, Render, RetainAllImageCache, Styled,
12 Subscription, Task, WeakEntity, Window, list,
13};
14use language::LanguageRegistry;
15use settings::Settings;
16use theme::ThemeSettings;
17use ui::{WithScrollbar, prelude::*};
18use workspace::item::{Item, ItemHandle};
19use workspace::{Pane, Workspace};
20
21use crate::markdown_elements::ParsedMarkdownElement;
22use crate::markdown_renderer::{CheckboxClickedEvent, MermaidState};
23use crate::{
24 OpenFollowingPreview, OpenPreview, OpenPreviewToTheSide, ScrollPageDown, ScrollPageUp,
25 markdown_elements::ParsedMarkdown,
26 markdown_parser::parse_markdown,
27 markdown_renderer::{RenderContext, render_markdown_block},
28};
29use crate::{ScrollDown, ScrollDownByItem, ScrollUp, ScrollUpByItem};
30
31const REPARSE_DEBOUNCE: Duration = Duration::from_millis(200);
32
33pub struct MarkdownPreviewView {
34 workspace: WeakEntity<Workspace>,
35 image_cache: Entity<RetainAllImageCache>,
36 active_editor: Option<EditorState>,
37 focus_handle: FocusHandle,
38 contents: Option<ParsedMarkdown>,
39 selected_block: usize,
40 list_state: ListState,
41 language_registry: Arc<LanguageRegistry>,
42 mermaid_state: MermaidState,
43 parsing_markdown_task: Option<Task<Result<()>>>,
44 mode: MarkdownPreviewMode,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq)]
48pub enum MarkdownPreviewMode {
49 /// The preview will always show the contents of the provided editor.
50 Default,
51 /// The preview will "follow" the currently active editor.
52 Follow,
53}
54
55struct EditorState {
56 editor: Entity<Editor>,
57 _subscription: Subscription,
58}
59
60impl MarkdownPreviewView {
61 pub fn register(workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>) {
62 workspace.register_action(move |workspace, _: &OpenPreview, window, cx| {
63 if let Some(editor) = Self::resolve_active_item_as_markdown_editor(workspace, cx) {
64 let view = Self::create_markdown_view(workspace, editor.clone(), window, cx);
65 workspace.active_pane().update(cx, |pane, cx| {
66 if let Some(existing_view_idx) =
67 Self::find_existing_independent_preview_item_idx(pane, &editor, cx)
68 {
69 pane.activate_item(existing_view_idx, true, true, window, cx);
70 } else {
71 pane.add_item(Box::new(view.clone()), true, true, None, window, cx)
72 }
73 });
74 cx.notify();
75 }
76 });
77
78 workspace.register_action(move |workspace, _: &OpenPreviewToTheSide, window, cx| {
79 if let Some(editor) = Self::resolve_active_item_as_markdown_editor(workspace, cx) {
80 let view = Self::create_markdown_view(workspace, editor.clone(), window, cx);
81 let pane = workspace
82 .find_pane_in_direction(workspace::SplitDirection::Right, cx)
83 .unwrap_or_else(|| {
84 workspace.split_pane(
85 workspace.active_pane().clone(),
86 workspace::SplitDirection::Right,
87 window,
88 cx,
89 )
90 });
91 pane.update(cx, |pane, cx| {
92 if let Some(existing_view_idx) =
93 Self::find_existing_independent_preview_item_idx(pane, &editor, cx)
94 {
95 pane.activate_item(existing_view_idx, true, true, window, cx);
96 } else {
97 pane.add_item(Box::new(view.clone()), false, false, None, window, cx)
98 }
99 });
100 editor.focus_handle(cx).focus(window, cx);
101 cx.notify();
102 }
103 });
104
105 workspace.register_action(move |workspace, _: &OpenFollowingPreview, window, cx| {
106 if let Some(editor) = Self::resolve_active_item_as_markdown_editor(workspace, cx) {
107 // Check if there's already a following preview
108 let existing_follow_view_idx = {
109 let active_pane = workspace.active_pane().read(cx);
110 active_pane
111 .items_of_type::<MarkdownPreviewView>()
112 .find(|view| view.read(cx).mode == MarkdownPreviewMode::Follow)
113 .and_then(|view| active_pane.index_for_item(&view))
114 };
115
116 if let Some(existing_follow_view_idx) = existing_follow_view_idx {
117 workspace.active_pane().update(cx, |pane, cx| {
118 pane.activate_item(existing_follow_view_idx, true, true, window, cx);
119 });
120 } else {
121 let view = Self::create_following_markdown_view(workspace, editor, window, cx);
122 workspace.active_pane().update(cx, |pane, cx| {
123 pane.add_item(Box::new(view.clone()), true, true, None, window, cx)
124 });
125 }
126 cx.notify();
127 }
128 });
129 }
130
131 fn find_existing_independent_preview_item_idx(
132 pane: &Pane,
133 editor: &Entity<Editor>,
134 cx: &App,
135 ) -> Option<usize> {
136 pane.items_of_type::<MarkdownPreviewView>()
137 .find(|view| {
138 let view_read = view.read(cx);
139 // Only look for independent (Default mode) previews, not Follow previews
140 view_read.mode == MarkdownPreviewMode::Default
141 && view_read
142 .active_editor
143 .as_ref()
144 .is_some_and(|active_editor| active_editor.editor == *editor)
145 })
146 .and_then(|view| pane.index_for_item(&view))
147 }
148
149 pub fn resolve_active_item_as_markdown_editor(
150 workspace: &Workspace,
151 cx: &mut Context<Workspace>,
152 ) -> Option<Entity<Editor>> {
153 if let Some(editor) = workspace
154 .active_item(cx)
155 .and_then(|item| item.act_as::<Editor>(cx))
156 && Self::is_markdown_file(&editor, cx)
157 {
158 return Some(editor);
159 }
160 None
161 }
162
163 fn create_markdown_view(
164 workspace: &mut Workspace,
165 editor: Entity<Editor>,
166 window: &mut Window,
167 cx: &mut Context<Workspace>,
168 ) -> Entity<MarkdownPreviewView> {
169 let language_registry = workspace.project().read(cx).languages().clone();
170 let workspace_handle = workspace.weak_handle();
171 MarkdownPreviewView::new(
172 MarkdownPreviewMode::Default,
173 editor,
174 workspace_handle,
175 language_registry,
176 window,
177 cx,
178 )
179 }
180
181 fn create_following_markdown_view(
182 workspace: &mut Workspace,
183 editor: Entity<Editor>,
184 window: &mut Window,
185 cx: &mut Context<Workspace>,
186 ) -> Entity<MarkdownPreviewView> {
187 let language_registry = workspace.project().read(cx).languages().clone();
188 let workspace_handle = workspace.weak_handle();
189 MarkdownPreviewView::new(
190 MarkdownPreviewMode::Follow,
191 editor,
192 workspace_handle,
193 language_registry,
194 window,
195 cx,
196 )
197 }
198
199 pub fn new(
200 mode: MarkdownPreviewMode,
201 active_editor: Entity<Editor>,
202 workspace: WeakEntity<Workspace>,
203 language_registry: Arc<LanguageRegistry>,
204 window: &mut Window,
205 cx: &mut Context<Workspace>,
206 ) -> Entity<Self> {
207 cx.new(|cx| {
208 let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.));
209
210 let mut this = Self {
211 selected_block: 0,
212 active_editor: None,
213 focus_handle: cx.focus_handle(),
214 workspace: workspace.clone(),
215 contents: None,
216 list_state,
217 language_registry,
218 mermaid_state: Default::default(),
219 parsing_markdown_task: None,
220 image_cache: RetainAllImageCache::new(cx),
221 mode,
222 };
223
224 this.set_editor(active_editor, window, cx);
225
226 if mode == MarkdownPreviewMode::Follow {
227 if let Some(workspace) = &workspace.upgrade() {
228 cx.observe_in(workspace, window, |this, workspace, window, cx| {
229 let item = workspace.read(cx).active_item(cx);
230 this.workspace_updated(item, window, cx);
231 })
232 .detach();
233 } else {
234 log::error!("Failed to listen to workspace updates");
235 }
236 }
237
238 this
239 })
240 }
241
242 fn workspace_updated(
243 &mut self,
244 active_item: Option<Box<dyn ItemHandle>>,
245 window: &mut Window,
246 cx: &mut Context<Self>,
247 ) {
248 if let Some(item) = active_item
249 && item.item_id() != cx.entity_id()
250 && let Some(editor) = item.act_as::<Editor>(cx)
251 && Self::is_markdown_file(&editor, cx)
252 {
253 self.set_editor(editor, window, cx);
254 }
255 }
256
257 pub fn is_markdown_file<V>(editor: &Entity<Editor>, cx: &mut Context<V>) -> bool {
258 let buffer = editor.read(cx).buffer().read(cx);
259 if let Some(buffer) = buffer.as_singleton()
260 && let Some(language) = buffer.read(cx).language()
261 {
262 return language.name() == "Markdown";
263 }
264 false
265 }
266
267 fn set_editor(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut Context<Self>) {
268 if let Some(active) = &self.active_editor
269 && active.editor == editor
270 {
271 return;
272 }
273
274 let subscription = cx.subscribe_in(
275 &editor,
276 window,
277 |this, editor, event: &EditorEvent, window, cx| {
278 match event {
279 EditorEvent::Edited { .. }
280 | EditorEvent::DirtyChanged
281 | EditorEvent::ExcerptsEdited { .. } => {
282 this.parse_markdown_from_active_editor(true, window, cx);
283 }
284 EditorEvent::SelectionsChanged { .. } => {
285 let selection_range = editor.update(cx, |editor, cx| {
286 editor
287 .selections
288 .last::<MultiBufferOffset>(&editor.display_snapshot(cx))
289 .range()
290 });
291 this.selected_block = this.get_block_index_under_cursor(selection_range);
292 this.list_state.scroll_to_reveal_item(this.selected_block);
293 cx.notify();
294 }
295 _ => {}
296 };
297 },
298 );
299
300 self.active_editor = Some(EditorState {
301 editor,
302 _subscription: subscription,
303 });
304
305 self.parse_markdown_from_active_editor(false, window, cx);
306 }
307
308 fn parse_markdown_from_active_editor(
309 &mut self,
310 wait_for_debounce: bool,
311 window: &mut Window,
312 cx: &mut Context<Self>,
313 ) {
314 if let Some(state) = &self.active_editor {
315 // if there is already a task to update the ui and the current task is also debounced (not high priority), do nothing
316 if wait_for_debounce && self.parsing_markdown_task.is_some() {
317 return;
318 }
319 self.parsing_markdown_task = Some(self.parse_markdown_in_background(
320 wait_for_debounce,
321 state.editor.clone(),
322 window,
323 cx,
324 ));
325 }
326 }
327
328 fn parse_markdown_in_background(
329 &mut self,
330 wait_for_debounce: bool,
331 editor: Entity<Editor>,
332 window: &mut Window,
333 cx: &mut Context<Self>,
334 ) -> Task<Result<()>> {
335 let language_registry = self.language_registry.clone();
336
337 cx.spawn_in(window, async move |view, cx| {
338 if wait_for_debounce {
339 // Wait for the user to stop typing
340 cx.background_executor().timer(REPARSE_DEBOUNCE).await;
341 }
342
343 let (contents, file_location) = view.update(cx, |_, cx| {
344 let editor = editor.read(cx);
345 let contents = editor.buffer().read(cx).snapshot(cx).text();
346 let file_location = MarkdownPreviewView::get_folder_for_active_editor(editor, cx);
347 (contents, file_location)
348 })?;
349
350 let parsing_task = cx.background_spawn(async move {
351 parse_markdown(&contents, file_location, Some(language_registry)).await
352 });
353 let contents = parsing_task.await;
354
355 view.update(cx, move |view, cx| {
356 view.mermaid_state.update(&contents, cx);
357 let markdown_blocks_count = contents.children.len();
358 view.contents = Some(contents);
359 let scroll_top = view.list_state.logical_scroll_top();
360 view.list_state.reset(markdown_blocks_count);
361 view.list_state.scroll_to(scroll_top);
362 view.parsing_markdown_task = None;
363 cx.notify();
364 })
365 })
366 }
367
368 fn move_cursor_to_block(
369 &self,
370 window: &mut Window,
371 cx: &mut Context<Self>,
372 selection: Range<MultiBufferOffset>,
373 ) {
374 if let Some(state) = &self.active_editor {
375 state.editor.update(cx, |editor, cx| {
376 editor.change_selections(
377 SelectionEffects::scroll(Autoscroll::center()),
378 window,
379 cx,
380 |selections| selections.select_ranges(vec![selection]),
381 );
382 window.focus(&editor.focus_handle(cx), cx);
383 });
384 }
385 }
386
387 /// The absolute path of the file that is currently being previewed.
388 fn get_folder_for_active_editor(editor: &Editor, cx: &App) -> Option<PathBuf> {
389 if let Some(file) = editor.file_at(MultiBufferOffset(0), cx) {
390 if let Some(file) = file.as_local() {
391 file.abs_path(cx).parent().map(|p| p.to_path_buf())
392 } else {
393 None
394 }
395 } else {
396 None
397 }
398 }
399
400 fn get_block_index_under_cursor(&self, selection_range: Range<MultiBufferOffset>) -> usize {
401 let mut block_index = None;
402 let cursor = selection_range.start.0;
403
404 let mut last_end = 0;
405 if let Some(content) = &self.contents {
406 for (i, block) in content.children.iter().enumerate() {
407 let Some(Range { start, end }) = block.source_range() else {
408 continue;
409 };
410
411 // Check if the cursor is between the last block and the current block
412 if last_end <= cursor && cursor < start {
413 block_index = Some(i.saturating_sub(1));
414 break;
415 }
416
417 if start <= cursor && end >= cursor {
418 block_index = Some(i);
419 break;
420 }
421 last_end = end;
422 }
423
424 if block_index.is_none() && last_end < cursor {
425 block_index = Some(content.children.len().saturating_sub(1));
426 }
427 }
428
429 block_index.unwrap_or_default()
430 }
431
432 fn should_apply_padding_between(
433 current_block: &ParsedMarkdownElement,
434 next_block: Option<&ParsedMarkdownElement>,
435 ) -> bool {
436 !(current_block.is_list_item() && next_block.map(|b| b.is_list_item()).unwrap_or(false))
437 }
438
439 fn scroll_page_up(&mut self, _: &ScrollPageUp, _window: &mut Window, cx: &mut Context<Self>) {
440 let viewport_height = self.list_state.viewport_bounds().size.height;
441 if viewport_height.is_zero() {
442 return;
443 }
444
445 self.list_state.scroll_by(-viewport_height);
446 cx.notify();
447 }
448
449 fn scroll_page_down(
450 &mut self,
451 _: &ScrollPageDown,
452 _window: &mut Window,
453 cx: &mut Context<Self>,
454 ) {
455 let viewport_height = self.list_state.viewport_bounds().size.height;
456 if viewport_height.is_zero() {
457 return;
458 }
459
460 self.list_state.scroll_by(viewport_height);
461 cx.notify();
462 }
463
464 fn scroll_up(&mut self, _: &ScrollUp, window: &mut Window, cx: &mut Context<Self>) {
465 let scroll_top = self.list_state.logical_scroll_top();
466 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
467 let item_height = bounds.size.height;
468 // Scroll no more than the rough equivalent of a large headline
469 let max_height = window.rem_size() * 2;
470 let scroll_height = min(item_height, max_height);
471 self.list_state.scroll_by(-scroll_height);
472 }
473 cx.notify();
474 }
475
476 fn scroll_down(&mut self, _: &ScrollDown, window: &mut Window, cx: &mut Context<Self>) {
477 let scroll_top = self.list_state.logical_scroll_top();
478 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
479 let item_height = bounds.size.height;
480 // Scroll no more than the rough equivalent of a large headline
481 let max_height = window.rem_size() * 2;
482 let scroll_height = min(item_height, max_height);
483 self.list_state.scroll_by(scroll_height);
484 }
485 cx.notify();
486 }
487
488 fn scroll_up_by_item(
489 &mut self,
490 _: &ScrollUpByItem,
491 _window: &mut Window,
492 cx: &mut Context<Self>,
493 ) {
494 let scroll_top = self.list_state.logical_scroll_top();
495 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
496 self.list_state.scroll_by(-bounds.size.height);
497 }
498 cx.notify();
499 }
500
501 fn scroll_down_by_item(
502 &mut self,
503 _: &ScrollDownByItem,
504 _window: &mut Window,
505 cx: &mut Context<Self>,
506 ) {
507 let scroll_top = self.list_state.logical_scroll_top();
508 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
509 self.list_state.scroll_by(bounds.size.height);
510 }
511 cx.notify();
512 }
513}
514
515impl Focusable for MarkdownPreviewView {
516 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
517 self.focus_handle.clone()
518 }
519}
520
521impl EventEmitter<()> for MarkdownPreviewView {}
522
523impl Item for MarkdownPreviewView {
524 type Event = ();
525
526 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
527 Some(Icon::new(IconName::FileDoc))
528 }
529
530 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
531 self.active_editor
532 .as_ref()
533 .map(|editor_state| {
534 let buffer = editor_state.editor.read(cx).buffer().read(cx);
535 let title = buffer.title(cx);
536 format!("Preview {}", title).into()
537 })
538 .unwrap_or_else(|| SharedString::from("Markdown Preview"))
539 }
540
541 fn telemetry_event_text(&self) -> Option<&'static str> {
542 Some("Markdown Preview Opened")
543 }
544
545 fn to_item_events(_event: &Self::Event, _f: &mut dyn FnMut(workspace::item::ItemEvent)) {}
546}
547
548impl Render for MarkdownPreviewView {
549 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
550 let buffer_size = ThemeSettings::get_global(cx).buffer_font_size(cx);
551 let buffer_line_height = ThemeSettings::get_global(cx).buffer_line_height;
552
553 v_flex()
554 .image_cache(self.image_cache.clone())
555 .id("MarkdownPreview")
556 .key_context("MarkdownPreview")
557 .track_focus(&self.focus_handle(cx))
558 .on_action(cx.listener(MarkdownPreviewView::scroll_page_up))
559 .on_action(cx.listener(MarkdownPreviewView::scroll_page_down))
560 .on_action(cx.listener(MarkdownPreviewView::scroll_up))
561 .on_action(cx.listener(MarkdownPreviewView::scroll_down))
562 .on_action(cx.listener(MarkdownPreviewView::scroll_up_by_item))
563 .on_action(cx.listener(MarkdownPreviewView::scroll_down_by_item))
564 .size_full()
565 .bg(cx.theme().colors().editor_background)
566 .p_4()
567 .text_size(buffer_size)
568 .line_height(relative(buffer_line_height.value()))
569 .child(div().flex_grow().map(|this| {
570 this.child(
571 list(
572 self.list_state.clone(),
573 cx.processor(|this, ix, window, cx| {
574 let Some(contents) = &this.contents else {
575 return div().into_any();
576 };
577
578 let mut render_cx = RenderContext::new(
579 Some(this.workspace.clone()),
580 &this.mermaid_state,
581 window,
582 cx,
583 )
584 .with_checkbox_clicked_callback(cx.listener(
585 move |this, e: &CheckboxClickedEvent, window, cx| {
586 if let Some(editor) =
587 this.active_editor.as_ref().map(|s| s.editor.clone())
588 {
589 editor.update(cx, |editor, cx| {
590 let task_marker =
591 if e.checked() { "[x]" } else { "[ ]" };
592
593 editor.edit(
594 [(
595 MultiBufferOffset(e.source_range().start)
596 ..MultiBufferOffset(e.source_range().end),
597 task_marker,
598 )],
599 cx,
600 );
601 });
602 this.parse_markdown_from_active_editor(false, window, cx);
603 cx.notify();
604 }
605 },
606 ));
607
608 let block = contents.children.get(ix).unwrap();
609 let rendered_block = render_markdown_block(block, &mut render_cx);
610
611 let should_apply_padding = Self::should_apply_padding_between(
612 block,
613 contents.children.get(ix + 1),
614 );
615
616 let selected_block = this.selected_block;
617 let scaled_rems = render_cx.scaled_rems(1.0);
618 div()
619 .id(ix)
620 .when(should_apply_padding, |this| {
621 this.pb(render_cx.scaled_rems(0.75))
622 })
623 .group("markdown-block")
624 .on_click(cx.listener(
625 move |this, event: &ClickEvent, window, cx| {
626 if event.click_count() == 2
627 && let Some(source_range) = this
628 .contents
629 .as_ref()
630 .and_then(|c| c.children.get(ix))
631 .and_then(|block: &ParsedMarkdownElement| {
632 block.source_range()
633 })
634 {
635 this.move_cursor_to_block(
636 window,
637 cx,
638 MultiBufferOffset(source_range.start)
639 ..MultiBufferOffset(source_range.start),
640 );
641 }
642 },
643 ))
644 .map(move |container| {
645 let indicator = div()
646 .h_full()
647 .w(px(4.0))
648 .when(ix == selected_block, |this| {
649 this.bg(cx.theme().colors().border)
650 })
651 .group_hover("markdown-block", |s| {
652 if ix == selected_block {
653 s
654 } else {
655 s.bg(cx.theme().colors().border_variant)
656 }
657 })
658 .rounded_xs();
659
660 container.child(
661 div()
662 .relative()
663 .child(div().pl(scaled_rems).child(rendered_block))
664 .child(indicator.absolute().left_0().top_0()),
665 )
666 })
667 .into_any()
668 }),
669 )
670 .size_full(),
671 )
672 }))
673 .vertical_scrollbar_for(&self.list_state, window, cx)
674 }
675}