| 1 | //! Pretty-print all urls and fit them into N characters |
| 2 | |
| 3 | use crate::parser::linkfmt::{LinkFormatter, MDLinkFormatter}; |
| 4 | use crate::MarkdownIt; |
| 5 | |
| 6 | #[derive(Debug)] |
| 7 | struct LinkBeautifier { |
| 8 | max_length: usize, |
| 9 | parent: Box<dyn LinkFormatter>, |
| 10 | } |
| 11 | |
| 12 | impl LinkFormatter for LinkBeautifier { |
| 13 | fn validate_link(&self, url: &str) -> Option<()> { |
| 14 | self.parent.as_ref().validate_link(url) |
| 15 | } |
| 16 | |
| 17 | fn normalize_link(&self, url: &str) -> String { |
| 18 | mdurl::format_url_for_computers(url) |
| 19 | } |
| 20 | |
| 21 | fn normalize_link_text(&self, url: &str) -> String { |
| 22 | mdurl::format_url_for_humans(url, self.max_length) |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | |
| 27 | /// Add beautifier plugin, limiting urls to default 50 characters |
| 28 | pub fn add(md: &mut MarkdownIt) { |
| 29 | add_with_char_limit(md, 50); |
| 30 | } |
| 31 | |
| 32 | /// Add beautifier plugin, limiting urls to `max_length` characters |
| 33 | pub fn add_with_char_limit(md: &mut MarkdownIt, max_length: usize) { |
| 34 | let parent = std::mem::replace(&mut md.link_formatter, Box::new(MDLinkFormatter::new())); |
| 35 | md.link_formatter = Box::new(LinkBeautifier { |
| 36 | max_length, |
| 37 | parent, |
| 38 | }); |
| 39 | } |