pub mod parser; use crate::parser::CodeBlockKind;use futures::FutureExt;use gpui::{ actions, point, quad, AnyElement, App, Bounds, ClipboardItem, CursorStyle, DispatchPhase, Edges, Entity, FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla, KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent, Point, Render, Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task, TextLayout, TextRun, TextStyle, TextStyleRefinement,};use language::{Language, LanguageRegistry, Rope};use parser::{parse_links_only, parse_markdown, MarkdownEvent, MarkdownTag, MarkdownTagEnd}; use std::{iter, mem, ops::Range, rc::Rc, sync::Arc};use theme::SyntaxTheme;use ui::{prelude::*, Tooltip};use util::{ResultExt, TryFutureExt}; #[derive(Clone)]pub struct MarkdownStyle { pub base_text_style: TextStyle, pub code_block: StyleRefinement, pub inline_code: TextStyleRefinement, pub block_quote: TextStyleRefinement, pub link: TextStyleRefinement, pub rule_color: Hsla, pub block_quote_border_color: Hsla, pub syntax: Arc<SyntaxTheme>, pub selection_background_color: Hsla, pub break_style: StyleRefinement, pub heading: StyleRefinement,} impl Default for MarkdownStyle { fn default() -> Self { Self { base_text_style: Default::default(), code_block: Default::default(), inline_code: Default::default(), block_quote: Default::default(), link: Default::default(), rule_color: Default::default(), block_quote_border_color: Default::default(), syntax: Arc::new(SyntaxTheme::default()), selection_background_color: Default::default(), break_style: Default::default(), heading: Default::default(), } }}pub struct Markdown { source: String, selection: Selection, pressed_link: Option<RenderedLink>, autoscroll_request: Option<usize>, style: MarkdownStyle, parsed_markdown: ParsedMarkdown, should_reparse: bool, pending_parse: Option<Task<Option<()>>>, focus_handle: FocusHandle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, options: Options,} #[derive(Debug)]struct Options { parse_links_only: bool, copy_code_block_buttons: bool,} actions!(markdown, [Copy]); impl Markdown { pub fn new( source: String, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, window: &mut Window, cx: &mut Context<Self>, ) -> Self { let focus_handle = cx.focus_handle(); let mut this = Self { source, selection: Selection::default(), pressed_link: None, autoscroll_request: None, style, should_reparse: false, parsed_markdown: ParsedMarkdown::default(), pending_parse: None, focus_handle, language_registry, fallback_code_block_language, options: Options { parse_links_only: false, copy_code_block_buttons: true, }, }; this.parse(window, cx); this } pub fn new_text( source: String, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, window: &mut Window, cx: &mut Context<Self>, ) -> Self { let focus_handle = cx.focus_handle(); let mut this = Self { source, selection: Selection::default(), pressed_link: None, autoscroll_request: None, style, should_reparse: false, parsed_markdown: ParsedMarkdown::default(), pending_parse: None, focus_handle, language_registry, fallback_code_block_language, options: Options { parse_links_only: true, copy_code_block_buttons: true, }, }; this.parse(window, cx); this } pub fn source(&self) -> &str { &self.source } pub fn append(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) { self.source.push_str(text); self.parse(window, cx); } pub fn reset(&mut self, source: String, window: &mut Window, cx: &mut Context<Self>) { if source == self.source() { return; } self.source = source; self.selection = Selection::default(); self.autoscroll_request = None; self.pending_parse = None; self.should_reparse = false; self.parsed_markdown = ParsedMarkdown::default(); self.parse(window, cx); } pub fn parsed_markdown(&self) -> &ParsedMarkdown { &self.parsed_markdown } fn copy(&self, text: &RenderedText, _: &mut Window, cx: &mut Context<Self>) { if self.selection.end <= self.selection.start { return; } let text = text.text_for_range(self.selection.start..self.selection.end); cx.write_to_clipboard(ClipboardItem::new_string(text)); } fn parse(&mut self, window: &mut Window, cx: &mut Context<Self>) { if self.source.is_empty() { return; } if self.pending_parse.is_some() { self.should_reparse = true; return; } let text = self.source.clone(); let parse_text_only = self.options.parse_links_only; let parsed = cx.background_executor().spawn(async move { let text = SharedString::from(text); let events = match parse_text_only { true => Arc::from(parse_links_only(text.as_ref())), false => Arc::from(parse_markdown(text.as_ref())), }; anyhow::Ok(ParsedMarkdown { source: text, events, }) }); self.should_reparse = false; self.pending_parse = Some(cx.spawn_in(window, |this, mut cx| { async move { let parsed = parsed.await?; this.update_in(&mut cx, |this, window, cx| { this.parsed_markdown = parsed; this.pending_parse.take(); if this.should_reparse { this.parse(window, cx); } cx.notify(); }) .ok(); anyhow::Ok(()) } .log_err() })); } pub fn copy_code_block_buttons(mut self, should_copy: bool) -> Self { self.options.copy_code_block_buttons = should_copy; self }} impl Render for Markdown { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { MarkdownElement::new( cx.entity().clone(), self.style.clone(), self.language_registry.clone(), self.fallback_code_block_language.clone(), ) }} impl Focusable for Markdown { fn focus_handle(&self, _cx: &App) -> FocusHandle { self.focus_handle.clone() }} #[derive(Copy, Clone, Default, Debug)]struct Selection { start: usize, end: usize, reversed: bool, pending: bool,} impl Selection { fn set_head(&mut self, head: usize) { if head < self.tail() { if !self.reversed { self.end = self.start; self.reversed = true; } self.start = head; } else { if self.reversed { self.start = self.end; self.reversed = false; } self.end = head; } } fn tail(&self) -> usize { if self.reversed { self.end } else { self.start } }} #[derive(Clone, Default)]pub struct ParsedMarkdown { source: SharedString, events: Arc<[(Range<usize>, MarkdownEvent)]>,} impl ParsedMarkdown { pub fn source(&self) -> &SharedString { &self.source } pub fn events(&self) -> &Arc<[(Range<usize>, MarkdownEvent)]> { &self.events }} pub struct MarkdownElement { markdown: Entity<Markdown>, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>,} impl MarkdownElement { fn new( markdown: Entity<Markdown>, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, ) -> Self { Self { markdown, style, language_registry, fallback_code_block_language, } } fn load_language( &self, name: &str, window: &mut Window, cx: &mut App, ) -> Option<Arc<Language>> { let language_test = self.language_registry.as_ref()?.language_for_name(name); let language_name = match language_test.now_or_never() { Some(Ok(_)) => String::from(name), Some(Err(_)) if !name.is_empty() && self.fallback_code_block_language.is_some() => { self.fallback_code_block_language.clone().unwrap() } _ => String::new(), }; let language = self .language_registry .as_ref()? .language_for_name(language_name.as_str()) .map(|language| language.ok()) .shared(); match language.clone().now_or_never() { Some(language) => language, None => { let markdown = self.markdown.downgrade(); window .spawn(cx, |mut cx| async move { language.await; markdown.update(&mut cx, |_, cx| cx.notify()) }) .detach_and_log_err(cx); None } } } fn paint_selection( &self, bounds: Bounds<Pixels>, rendered_text: &RenderedText, window: &mut Window, cx: &mut App, ) { let selection = self.markdown.read(cx).selection; let selection_start = rendered_text.position_for_source_index(selection.start); let selection_end = rendered_text.position_for_source_index(selection.end); if let Some(((start_position, start_line_height), (end_position, end_line_height))) = selection_start.zip(selection_end) { if start_position.y == end_position.y { window.paint_quad(quad( Bounds::from_corners( start_position, point(end_position.x, end_position.y + end_line_height), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); } else { window.paint_quad(quad( Bounds::from_corners( start_position, point(bounds.right(), start_position.y + start_line_height), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); if end_position.y > start_position.y + start_line_height { window.paint_quad(quad( Bounds::from_corners( point(bounds.left(), start_position.y + start_line_height), point(bounds.right(), end_position.y), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); } window.paint_quad(quad( Bounds::from_corners( point(bounds.left(), end_position.y), point(end_position.x, end_position.y + end_line_height), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); } } } fn paint_mouse_listeners( &self, hitbox: &Hitbox, rendered_text: &RenderedText, window: &mut Window, cx: &mut App, ) { let is_hovering_link = hitbox.is_hovered(window) && !self.markdown.read(cx).selection.pending && rendered_text .link_for_position(window.mouse_position()) .is_some(); if is_hovering_link { window.set_cursor_style(CursorStyle::PointingHand, hitbox); } else { window.set_cursor_style(CursorStyle::IBeam, hitbox); } self.on_mouse_event(window, cx, { let rendered_text = rendered_text.clone(); let hitbox = hitbox.clone(); move |markdown, event: &MouseDownEvent, phase, window, cx| { if hitbox.is_hovered(window) { if phase.bubble() { if let Some(link) = rendered_text.link_for_position(event.position) { markdown.pressed_link = Some(link.clone()); } else { let source_index = match rendered_text.source_index_for_position(event.position) { Ok(ix) | Err(ix) => ix, }; let range = if event.click_count == 2 { rendered_text.surrounding_word_range(source_index) } else if event.click_count == 3 { rendered_text.surrounding_line_range(source_index) } else { source_index..source_index }; markdown.selection = Selection { start: range.start, end: range.end, reversed: false, pending: true, }; window.focus(&markdown.focus_handle); window.prevent_default() } cx.notify(); } } else if phase.capture() { markdown.selection = Selection::default(); markdown.pressed_link = None; cx.notify(); } } }); self.on_mouse_event(window, cx, { let rendered_text = rendered_text.clone(); let hitbox = hitbox.clone(); let was_hovering_link = is_hovering_link; move |markdown, event: &MouseMoveEvent, phase, window, cx| { if phase.capture() { return; } if markdown.selection.pending { let source_index = match rendered_text.source_index_for_position(event.position) { Ok(ix) | Err(ix) => ix, }; markdown.selection.set_head(source_index); markdown.autoscroll_request = Some(source_index); cx.notify(); } else { let is_hovering_link = hitbox.is_hovered(window) && rendered_text.link_for_position(event.position).is_some(); if is_hovering_link != was_hovering_link { cx.notify(); } } } }); self.on_mouse_event(window, cx, { let rendered_text = rendered_text.clone(); move |markdown, event: &MouseUpEvent, phase, _, cx| { if phase.bubble() { if let Some(pressed_link) = markdown.pressed_link.take() { if Some(&pressed_link) == rendered_text.link_for_position(event.position) { cx.open_url(&pressed_link.destination_url);Lines 1–500 of 1330. Load more
pub mod parser; use crate::parser::CodeBlockKind; use futures::FutureExt; use gpui::{ actions, point, quad, AnyElement, App, Bounds, ClipboardItem, CursorStyle, DispatchPhase, Edges, Entity, FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla, KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent, Point, Render, Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task, TextLayout, TextRun, TextStyle, TextStyleRefinement, }; use language::{Language, LanguageRegistry, Rope}; use parser::{parse_links_only, parse_markdown, MarkdownEvent, MarkdownTag, MarkdownTagEnd}; use std::{iter, mem, ops::Range, rc::Rc, sync::Arc}; use theme::SyntaxTheme; use ui::{prelude::*, Tooltip}; use util::{ResultExt, TryFutureExt}; #[derive(Clone)] pub struct MarkdownStyle { pub base_text_style: TextStyle, pub code_block: StyleRefinement, pub inline_code: TextStyleRefinement, pub block_quote: TextStyleRefinement, pub link: TextStyleRefinement, pub rule_color: Hsla, pub block_quote_border_color: Hsla, pub syntax: Arc<SyntaxTheme>, pub selection_background_color: Hsla, pub break_style: StyleRefinement, pub heading: StyleRefinement, } impl Default for MarkdownStyle { fn default() -> Self { Self { base_text_style: Default::default(), code_block: Default::default(), inline_code: Default::default(), block_quote: Default::default(), link: Default::default(), rule_color: Default::default(), block_quote_border_color: Default::default(), syntax: Arc::new(SyntaxTheme::default()), selection_background_color: Default::default(), break_style: Default::default(), heading: Default::default(), } } } pub struct Markdown { source: String, selection: Selection, pressed_link: Option<RenderedLink>, autoscroll_request: Option<usize>, style: MarkdownStyle, parsed_markdown: ParsedMarkdown, should_reparse: bool, pending_parse: Option<Task<Option<()>>>, focus_handle: FocusHandle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, options: Options, } #[derive(Debug)] struct Options { parse_links_only: bool, copy_code_block_buttons: bool, } actions!(markdown, [Copy]); impl Markdown { pub fn new( source: String, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, window: &mut Window, cx: &mut Context<Self>, ) -> Self { let focus_handle = cx.focus_handle(); let mut this = Self { source, selection: Selection::default(), pressed_link: None, autoscroll_request: None, style, should_reparse: false, parsed_markdown: ParsedMarkdown::default(), pending_parse: None, focus_handle, language_registry, fallback_code_block_language, options: Options { parse_links_only: false, copy_code_block_buttons: true, }, }; this.parse(window, cx); this } pub fn new_text( source: String, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, window: &mut Window, cx: &mut Context<Self>, ) -> Self { let focus_handle = cx.focus_handle(); let mut this = Self { source, selection: Selection::default(), pressed_link: None, autoscroll_request: None, style, should_reparse: false, parsed_markdown: ParsedMarkdown::default(), pending_parse: None, focus_handle, language_registry, fallback_code_block_language, options: Options { parse_links_only: true, copy_code_block_buttons: true, }, }; this.parse(window, cx); this } pub fn source(&self) -> &str { &self.source } pub fn append(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) { self.source.push_str(text); self.parse(window, cx); } pub fn reset(&mut self, source: String, window: &mut Window, cx: &mut Context<Self>) { if source == self.source() { return; } self.source = source; self.selection = Selection::default(); self.autoscroll_request = None; self.pending_parse = None; self.should_reparse = false; self.parsed_markdown = ParsedMarkdown::default(); self.parse(window, cx); } pub fn parsed_markdown(&self) -> &ParsedMarkdown { &self.parsed_markdown } fn copy(&self, text: &RenderedText, _: &mut Window, cx: &mut Context<Self>) { if self.selection.end <= self.selection.start { return; } let text = text.text_for_range(self.selection.start..self.selection.end); cx.write_to_clipboard(ClipboardItem::new_string(text)); } fn parse(&mut self, window: &mut Window, cx: &mut Context<Self>) { if self.source.is_empty() { return; } if self.pending_parse.is_some() { self.should_reparse = true; return; } let text = self.source.clone(); let parse_text_only = self.options.parse_links_only; let parsed = cx.background_executor().spawn(async move { let text = SharedString::from(text); let events = match parse_text_only { true => Arc::from(parse_links_only(text.as_ref())), false => Arc::from(parse_markdown(text.as_ref())), }; anyhow::Ok(ParsedMarkdown { source: text, events, }) }); self.should_reparse = false; self.pending_parse = Some(cx.spawn_in(window, |this, mut cx| { async move { let parsed = parsed.await?; this.update_in(&mut cx, |this, window, cx| { this.parsed_markdown = parsed; this.pending_parse.take(); if this.should_reparse { this.parse(window, cx); } cx.notify(); }) .ok(); anyhow::Ok(()) } .log_err() })); } pub fn copy_code_block_buttons(mut self, should_copy: bool) -> Self { self.options.copy_code_block_buttons = should_copy; self } } impl Render for Markdown { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { MarkdownElement::new( cx.entity().clone(), self.style.clone(), self.language_registry.clone(), self.fallback_code_block_language.clone(), ) } } impl Focusable for Markdown { fn focus_handle(&self, _cx: &App) -> FocusHandle { self.focus_handle.clone() } } #[derive(Copy, Clone, Default, Debug)] struct Selection { start: usize, end: usize, reversed: bool, pending: bool, } impl Selection { fn set_head(&mut self, head: usize) { if head < self.tail() { if !self.reversed { self.end = self.start; self.reversed = true; } self.start = head; } else { if self.reversed { self.start = self.end; self.reversed = false; } self.end = head; } } fn tail(&self) -> usize { if self.reversed { self.end } else { self.start } } } #[derive(Clone, Default)] pub struct ParsedMarkdown { source: SharedString, events: Arc<[(Range<usize>, MarkdownEvent)]>, } impl ParsedMarkdown { pub fn source(&self) -> &SharedString { &self.source } pub fn events(&self) -> &Arc<[(Range<usize>, MarkdownEvent)]> { &self.events } } pub struct MarkdownElement { markdown: Entity<Markdown>, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, } impl MarkdownElement { fn new( markdown: Entity<Markdown>, style: MarkdownStyle, language_registry: Option<Arc<LanguageRegistry>>, fallback_code_block_language: Option<String>, ) -> Self { Self { markdown, style, language_registry, fallback_code_block_language, } } fn load_language( &self, name: &str, window: &mut Window, cx: &mut App, ) -> Option<Arc<Language>> { let language_test = self.language_registry.as_ref()?.language_for_name(name); let language_name = match language_test.now_or_never() { Some(Ok(_)) => String::from(name), Some(Err(_)) if !name.is_empty() && self.fallback_code_block_language.is_some() => { self.fallback_code_block_language.clone().unwrap() } _ => String::new(), }; let language = self .language_registry .as_ref()? .language_for_name(language_name.as_str()) .map(|language| language.ok()) .shared(); match language.clone().now_or_never() { Some(language) => language, None => { let markdown = self.markdown.downgrade(); window .spawn(cx, |mut cx| async move { language.await; markdown.update(&mut cx, |_, cx| cx.notify()) }) .detach_and_log_err(cx); None } } } fn paint_selection( &self, bounds: Bounds<Pixels>, rendered_text: &RenderedText, window: &mut Window, cx: &mut App, ) { let selection = self.markdown.read(cx).selection; let selection_start = rendered_text.position_for_source_index(selection.start); let selection_end = rendered_text.position_for_source_index(selection.end); if let Some(((start_position, start_line_height), (end_position, end_line_height))) = selection_start.zip(selection_end) { if start_position.y == end_position.y { window.paint_quad(quad( Bounds::from_corners( start_position, point(end_position.x, end_position.y + end_line_height), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); } else { window.paint_quad(quad( Bounds::from_corners( start_position, point(bounds.right(), start_position.y + start_line_height), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); if end_position.y > start_position.y + start_line_height { window.paint_quad(quad( Bounds::from_corners( point(bounds.left(), start_position.y + start_line_height), point(bounds.right(), end_position.y), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); } window.paint_quad(quad( Bounds::from_corners( point(bounds.left(), end_position.y), point(end_position.x, end_position.y + end_line_height), ), Pixels::ZERO, self.style.selection_background_color, Edges::default(), Hsla::transparent_black(), )); } } } fn paint_mouse_listeners( &self, hitbox: &Hitbox, rendered_text: &RenderedText, window: &mut Window, cx: &mut App, ) { let is_hovering_link = hitbox.is_hovered(window) && !self.markdown.read(cx).selection.pending && rendered_text .link_for_position(window.mouse_position()) .is_some(); if is_hovering_link { window.set_cursor_style(CursorStyle::PointingHand, hitbox); } else { window.set_cursor_style(CursorStyle::IBeam, hitbox); } self.on_mouse_event(window, cx, { let rendered_text = rendered_text.clone(); let hitbox = hitbox.clone(); move |markdown, event: &MouseDownEvent, phase, window, cx| { if hitbox.is_hovered(window) { if phase.bubble() { if let Some(link) = rendered_text.link_for_position(event.position) { markdown.pressed_link = Some(link.clone()); } else { let source_index = match rendered_text.source_index_for_position(event.position) { Ok(ix) | Err(ix) => ix, }; let range = if event.click_count == 2 { rendered_text.surrounding_word_range(source_index) } else if event.click_count == 3 { rendered_text.surrounding_line_range(source_index) } else { source_index..source_index }; markdown.selection = Selection { start: range.start, end: range.end, reversed: false, pending: true, }; window.focus(&markdown.focus_handle); window.prevent_default() } cx.notify(); } } else if phase.capture() { markdown.selection = Selection::default(); markdown.pressed_link = None; cx.notify(); } } }); self.on_mouse_event(window, cx, { let rendered_text = rendered_text.clone(); let hitbox = hitbox.clone(); let was_hovering_link = is_hovering_link; move |markdown, event: &MouseMoveEvent, phase, window, cx| { if phase.capture() { return; } if markdown.selection.pending { let source_index = match rendered_text.source_index_for_position(event.position) { Ok(ix) | Err(ix) => ix, }; markdown.selection.set_head(source_index); markdown.autoscroll_request = Some(source_index); cx.notify(); } else { let is_hovering_link = hitbox.is_hovered(window) && rendered_text.link_for_position(event.position).is_some(); if is_hovering_link != was_hovering_link { cx.notify(); } } } }); self.on_mouse_event(window, cx, { let rendered_text = rendered_text.clone(); move |markdown, event: &MouseUpEvent, phase, _, cx| { if phase.bubble() { if let Some(pressed_link) = markdown.pressed_link.take() { if Some(&pressed_link) == rendered_text.link_for_position(event.position) { cx.open_url(&pressed_link.destination_url);