From 95db1c29845ae683a176e4d957dc57f4bc9d8819 Mon Sep 17 00:00:00 2001 From: Price Hiller Date: Tue, 29 Aug 2023 21:31:28 -0500 Subject: [PATCH] feat: add header plugin to allow headers to be linked to --- src/markdown/mod.rs | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/src/markdown/mod.rs b/src/markdown/mod.rs index 77b492c..9379f43 100644 --- a/src/markdown/mod.rs +++ b/src/markdown/mod.rs @@ -1,6 +1,5 @@ -use std::io::Cursor; - -use comrak::{nodes::AstNode, ComrakOptions, ComrakPlugins, plugins::syntect::{SyntectAdapter, SyntectAdapterBuilder}}; +use std::io::{Cursor, Write}; +use comrak::{nodes::{AstNode, Sourcepos}, ComrakOptions, ComrakPlugins, plugins::syntect::{SyntectAdapter, SyntectAdapterBuilder}, adapters::{HeadingAdapter, HeadingMeta}, Anchorizer}; use lazy_static::lazy_static; use syntect::highlighting::ThemeSet; @@ -25,6 +24,31 @@ where } } +struct HeaderLinkAdapter; + +impl HeadingAdapter for HeaderLinkAdapter { + fn enter( + &self, + output: &mut dyn Write, + heading: &HeadingMeta, + _: Option, + ) -> std::io::Result<()> { + let mut anchorizer = Anchorizer::new(); + let id = anchorizer.anchorize(heading.content.to_string()); + + write!(output, "", heading.level)?; + write!( + output, + "", + id, id + ) + } + + fn exit(&self, output: &mut dyn Write, heading: &HeadingMeta) -> std::io::Result<()> { + write!(output, "", heading.level) + } +} + #[derive(Debug)] pub struct MDComrakSettings<'a> { pub options: ComrakOptions, @@ -40,12 +64,11 @@ impl MDComrakSettings<'_> { options.extension.table = true; options.extension.tasklist = true; options.extension.superscript = true; - options.extension.header_ids = Some("header-id-".to_string()); options.extension.footnotes = true; - let mut plugins = ComrakPlugins::default(); plugins.render.codefence_syntax_highlighter = Some(&*SYNTECT_ADAPTER); + plugins.render.heading_adapter = Some(&HeaderLinkAdapter); Ok(MDComrakSettings { options, plugins }) }