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".into();
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 self.parsing_markdown_task = Some(self.parse_markdown_in_background(
316 wait_for_debounce,
317 state.editor.clone(),
318 window,
319 cx,
320 ));
321 }
322 }
323
324 fn parse_markdown_in_background(
325 &mut self,
326 wait_for_debounce: bool,
327 editor: Entity<Editor>,
328 window: &mut Window,
329 cx: &mut Context<Self>,
330 ) -> Task<Result<()>> {
331 let language_registry = self.language_registry.clone();
332
333 cx.spawn_in(window, async move |view, cx| {
334 if wait_for_debounce {
335 // Wait for the user to stop typing
336 cx.background_executor().timer(REPARSE_DEBOUNCE).await;
337 }
338
339 let (contents, file_location) = view.update(cx, |_, cx| {
340 let editor = editor.read(cx);
341 let contents = editor.buffer().read(cx).snapshot(cx).text();
342 let file_location = MarkdownPreviewView::get_folder_for_active_editor(editor, cx);
343 (contents, file_location)
344 })?;
345
346 let parsing_task = cx.background_spawn(async move {
347 parse_markdown(&contents, file_location, Some(language_registry)).await
348 });
349 let contents = parsing_task.await;
350
351 view.update(cx, move |view, cx| {
352 view.mermaid_state.update(&contents, cx);
353 let markdown_blocks_count = contents.children.len();
354 view.contents = Some(contents);
355 let scroll_top = view.list_state.logical_scroll_top();
356 view.list_state.reset(markdown_blocks_count);
357 view.list_state.scroll_to(scroll_top);
358 cx.notify();
359 })
360 })
361 }
362
363 fn move_cursor_to_block(
364 &self,
365 window: &mut Window,
366 cx: &mut Context<Self>,
367 selection: Range<MultiBufferOffset>,
368 ) {
369 if let Some(state) = &self.active_editor {
370 state.editor.update(cx, |editor, cx| {
371 editor.change_selections(
372 SelectionEffects::scroll(Autoscroll::center()),
373 window,
374 cx,
375 |selections| selections.select_ranges(vec![selection]),
376 );
377 window.focus(&editor.focus_handle(cx), cx);
378 });
379 }
380 }
381
382 /// The absolute path of the file that is currently being previewed.
383 fn get_folder_for_active_editor(editor: &Editor, cx: &App) -> Option<PathBuf> {
384 if let Some(file) = editor.file_at(MultiBufferOffset(0), cx) {
385 if let Some(file) = file.as_local() {
386 file.abs_path(cx).parent().map(|p| p.to_path_buf())
387 } else {
388 None
389 }
390 } else {
391 None
392 }
393 }
394
395 fn get_block_index_under_cursor(&self, selection_range: Range<MultiBufferOffset>) -> usize {
396 let mut block_index = None;
397 let cursor = selection_range.start.0;
398
399 let mut last_end = 0;
400 if let Some(content) = &self.contents {
401 for (i, block) in content.children.iter().enumerate() {
402 let Some(Range { start, end }) = block.source_range() else {
403 continue;
404 };
405
406 // Check if the cursor is between the last block and the current block
407 if last_end <= cursor && cursor < start {
408 block_index = Some(i.saturating_sub(1));
409 break;
410 }
411
412 if start <= cursor && end >= cursor {
413 block_index = Some(i);
414 break;
415 }
416 last_end = end;
417 }
418
419 if block_index.is_none() && last_end < cursor {
420 block_index = Some(content.children.len().saturating_sub(1));
421 }
422 }
423
424 block_index.unwrap_or_default()
425 }
426
427 fn should_apply_padding_between(
428 current_block: &ParsedMarkdownElement,
429 next_block: Option<&ParsedMarkdownElement>,
430 ) -> bool {
431 !(current_block.is_list_item() && next_block.map(|b| b.is_list_item()).unwrap_or(false))
432 }
433
434 fn scroll_page_up(&mut self, _: &ScrollPageUp, _window: &mut Window, cx: &mut Context<Self>) {
435 let viewport_height = self.list_state.viewport_bounds().size.height;
436 if viewport_height.is_zero() {
437 return;
438 }
439
440 self.list_state.scroll_by(-viewport_height);
441 cx.notify();
442 }
443
444 fn scroll_page_down(
445 &mut self,
446 _: &ScrollPageDown,
447 _window: &mut Window,
448 cx: &mut Context<Self>,
449 ) {
450 let viewport_height = self.list_state.viewport_bounds().size.height;
451 if viewport_height.is_zero() {
452 return;
453 }
454
455 self.list_state.scroll_by(viewport_height);
456 cx.notify();
457 }
458
459 fn scroll_up(&mut self, _: &ScrollUp, window: &mut Window, cx: &mut Context<Self>) {
460 let scroll_top = self.list_state.logical_scroll_top();
461 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
462 let item_height = bounds.size.height;
463 // Scroll no more than the rough equivalent of a large headline
464 let max_height = window.rem_size() * 2;
465 let scroll_height = min(item_height, max_height);
466 self.list_state.scroll_by(-scroll_height);
467 }
468 cx.notify();
469 }
470
471 fn scroll_down(&mut self, _: &ScrollDown, window: &mut Window, cx: &mut Context<Self>) {
472 let scroll_top = self.list_state.logical_scroll_top();
473 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
474 let item_height = bounds.size.height;
475 // Scroll no more than the rough equivalent of a large headline
476 let max_height = window.rem_size() * 2;
477 let scroll_height = min(item_height, max_height);
478 self.list_state.scroll_by(scroll_height);
479 }
480 cx.notify();
481 }
482
483 fn scroll_up_by_item(
484 &mut self,
485 _: &ScrollUpByItem,
486 _window: &mut Window,
487 cx: &mut Context<Self>,
488 ) {
489 let scroll_top = self.list_state.logical_scroll_top();
490 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
491 self.list_state.scroll_by(-bounds.size.height);
492 }
493 cx.notify();
494 }
495
496 fn scroll_down_by_item(
497 &mut self,
498 _: &ScrollDownByItem,
499 _window: &mut Window,
500 cx: &mut Context<Self>,
501 ) {
502 let scroll_top = self.list_state.logical_scroll_top();
503 if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
504 self.list_state.scroll_by(bounds.size.height);
505 }
506 cx.notify();
507 }
508}
509
510impl Focusable for MarkdownPreviewView {
511 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
512 self.focus_handle.clone()
513 }
514}
515
516impl EventEmitter<()> for MarkdownPreviewView {}
517
518impl Item for MarkdownPreviewView {
519 type Event = ();
520
521 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
522 Some(Icon::new(IconName::FileDoc))
523 }
524
525 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
526 self.active_editor
527 .as_ref()
528 .map(|editor_state| {
529 let buffer = editor_state.editor.read(cx).buffer().read(cx);
530 let title = buffer.title(cx);
531 format!("Preview {}", title).into()
532 })
533 .unwrap_or_else(|| SharedString::from("Markdown Preview"))
534 }
535
536 fn telemetry_event_text(&self) -> Option<&'static str> {
537 Some("Markdown Preview Opened")
538 }
539
540 fn to_item_events(_event: &Self::Event, _f: &mut dyn FnMut(workspace::item::ItemEvent)) {}
541}
542
543impl Render for MarkdownPreviewView {
544 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
545 let buffer_size = ThemeSettings::get_global(cx).buffer_font_size(cx);
546 let buffer_line_height = ThemeSettings::get_global(cx).buffer_line_height;
547
548 v_flex()
549 .image_cache(self.image_cache.clone())
550 .id("MarkdownPreview")
551 .key_context("MarkdownPreview")
552 .track_focus(&self.focus_handle(cx))
553 .on_action(cx.listener(MarkdownPreviewView::scroll_page_up))
554 .on_action(cx.listener(MarkdownPreviewView::scroll_page_down))
555 .on_action(cx.listener(MarkdownPreviewView::scroll_up))
556 .on_action(cx.listener(MarkdownPreviewView::scroll_down))
557 .on_action(cx.listener(MarkdownPreviewView::scroll_up_by_item))
558 .on_action(cx.listener(MarkdownPreviewView::scroll_down_by_item))
559 .size_full()
560 .bg(cx.theme().colors().editor_background)
561 .p_4()
562 .text_size(buffer_size)
563 .line_height(relative(buffer_line_height.value()))
564 .child(div().flex_grow().map(|this| {
565 this.child(
566 list(
567 self.list_state.clone(),
568 cx.processor(|this, ix, window, cx| {
569 let Some(contents) = &this.contents else {
570 return div().into_any();
571 };
572
573 let mut render_cx = RenderContext::new(
574 Some(this.workspace.clone()),
575 &this.mermaid_state,
576 window,
577 cx,
578 )
579 .with_checkbox_clicked_callback(cx.listener(
580 move |this, e: &CheckboxClickedEvent, window, cx| {
581 if let Some(editor) =
582 this.active_editor.as_ref().map(|s| s.editor.clone())
583 {
584 editor.update(cx, |editor, cx| {
585 let task_marker =
586 if e.checked() { "[x]" } else { "[ ]" };
587
588 editor.edit(
589 [(
590 MultiBufferOffset(e.source_range().start)
591 ..MultiBufferOffset(e.source_range().end),
592 task_marker,
593 )],
594 cx,
595 );
596 });
597 this.parse_markdown_from_active_editor(false, window, cx);
598 cx.notify();
599 }
600 },
601 ));
602
603 let block = contents.children.get(ix).unwrap();
604 let rendered_block = render_markdown_block(block, &mut render_cx);
605
606 let should_apply_padding = Self::should_apply_padding_between(
607 block,
608 contents.children.get(ix + 1),
609 );
610
611 let selected_block = this.selected_block;
612 let scaled_rems = render_cx.scaled_rems(1.0);
613 div()
614 .id(ix)
615 .when(should_apply_padding, |this| {
616 this.pb(render_cx.scaled_rems(0.75))
617 })
618 .group("markdown-block")
619 .on_click(cx.listener(
620 move |this, event: &ClickEvent, window, cx| {
621 if event.click_count() == 2
622 && let Some(source_range) = this
623 .contents
624 .as_ref()
625 .and_then(|c| c.children.get(ix))
626 .and_then(|block: &ParsedMarkdownElement| {
627 block.source_range()
628 })
629 {
630 this.move_cursor_to_block(
631 window,
632 cx,
633 MultiBufferOffset(source_range.start)
634 ..MultiBufferOffset(source_range.start),
635 );
636 }
637 },
638 ))
639 .map(move |container| {
640 let indicator = div()
641 .h_full()
642 .w(px(4.0))
643 .when(ix == selected_block, |this| {
644 this.bg(cx.theme().colors().border)
645 })
646 .group_hover("markdown-block", |s| {
647 if ix == selected_block {
648 s
649 } else {
650 s.bg(cx.theme().colors().border_variant)
651 }
652 })
653 .rounded_xs();
654
655 container.child(
656 div()
657 .relative()
658 .child(div().pl(scaled_rems).child(rendered_block))
659 .child(indicator.absolute().left_0().top_0()),
660 )
661 })
662 .into_any()
663 }),
664 )
665 .size_full(),
666 )
667 }))
668 .vertical_scrollbar_for(&self.list_state, window, cx)
669 }
670}