MarkdownDeep Delegate Hooks

Tuesday, March 29th, 2011     #markdowndeep #everything

An easier way to hook into MarkdownDeep with delegate methods.

In the original version of MarkdownDeep there were various points where a client could hook in to provide information such image size attributes. These were implemented as virtual methods on the Markdown class. This worked but was clumsy to use. To make this easier, it now supports using function delegates for those hooks:

Func<string, string> QualifyUrl
Equivalent to the OnQualifyUrl virtual method.
Func<ImageInfo, bool> GetImageSize
Similar to the OnGetImageSize virtual method, with out parameters packed into a new ImageInfo class.
Func<HtmlTag, bool> PrepareLink
Equivalent to the OnPrepareLink virtual method.
Func<HtmlTag, bool, bool> PrepareImage
Equivalent to the OnPrepareImage virtual method.

For example, the following is how Jab supplies image size attributes. What's nice about this is that the cache parameter is available for use in the delegate methods. Without the delegate hooks, I'd need to derive the Markdown class, pass the cache to that class and override the methods I needed. This is much nicer.

public string ProcessMarkdown(
            SiteCacheBase cache, 
            string section, 
            out Dictionary<string, MarkdownDeep.LinkDefinition> defs, 
            bool QualifyLinks
            )
{
    var md = new MarkdownDeep.Markdown();
    md.SafeMode = false;
    md.ExtraMode = true;
    md.AutoHeadingIDs = true;
    md.MarkdownInHtml = true;
    md.NewWindowForExternalLinks = true;
    md.HtmlClassTitledImages = "figure";
    md.FormatCodeBlock = Jab.FormatCodePrettyPrint;
    md.UserBreaks = true;
    if (QualifyLinks)
        md.UrlBaseLocation = "http://" + cache.site.PublicDomain;

    if (cache != null)
    {
        md.PrepareImage = delegate(MarkdownDeep.HtmlTag tag, bool TitledImage)
        {
            return Jab.PrepareImage(cache, tag, TitledImage);
        };

        md.GetImageSize = delegate(MarkdownDeep.ImageInfo info)
        {
            // Save the first image url
            if (string.IsNullOrEmpty(this.image_url))
            {
                image_url = Jab.GetImageUrl(cache, info);
            }

            return Jab.GetImageSize(cache, info);
        };
    }

    return md.Transform(section==null ? this.content : section, out defs);
}

These improvements are available now in github and the latest NuGet packages.

« Older - MarkdownDeep Improved URL Qualification Newer - PetaPoco - T4 Template support for SQL Server »