Create Markdown Syntax within MarkdownPostProcessor

Hey there,

I am developing my own plugin to do some automation in Obsidian. MarkdownPostProcessors have come in pretty useful here. I am wondering however whether it is possible to build a MarkdownPostProcessor so that it outputs markdown that ist then processed by another MarkdownPostProcessor. Kind of an inception I guess.

The usecase specifically is that I would like to automate the generation of Mermaid diagrams. My MarkdownPostProcessor would gather some data from different places and then return markdown code that would in turn generate a Mermaid diagram.

Would be awesome if anyone of you knew whether or how this is possible - thanks in advance!

So you want to generate a mermaid diagrams, but you want to achieve that by returning a markdown code block like this?

```mermaid
some code
```

If so, it sounds like you will want to use MarkdownRenderer.render inside your post processor.

I haven’t tested it but I guess something like this will work.

this.registerMarkdownPostProcessor((el, ctx) => {
    if (someCondition(el, ctx)) {
        ctx.addChild(new YourMarkdownRenderChild(this.app, el)) 
    }    
})

class YourMarkdownRenderChild extends MarkdownRenderChild {
    constructor(public app: App, containerEl: HTMLElement) {
        super(containerEl);
        this.app = app;
    }
    async onload() {
             const markdown = someLogic()
             await MarkdownRenderer.render(this.app, markdown, this.containerEl, "", this)
    }
}

That was exactly what I was looking for - thanks a lot!

One small detail if anyone wants to recreate this: this.el must be changed to this.containerEl as the MarkdownRenderChild class names this attribute differently.

A follow-up question if I may: Do you know of any additional lifecycle management that would be considered best practice, e.g. freeing up memory in the onunload() function? I’m quite new to this unfortunately so not sure if it’s necessary. Haven’t run into any obvious performance issues with my previous MarkdownPostProcessors and this also seems to work flawlessly, so just curious.

You’re right, I’ve replaced el with containerEl. Thanks!

In this particular example, I don’t think you need extra memory management. I reckon that MarkdownRenderer.render does its memory management on its own (that’s why we passed this as the component parameter so that if this component = YourMarkdownRenderChild is unloaded, the related resources will be freed up).

1 Like