Skip to content

Parsing and Removing Frontmatter in Obsidian Plugins

How can Obsidian plugin developers process the body of a note without its metadata?

In this code block, we will learn how to remove frontmatter from a message and parse it using two different functions. These functions are useful for Obsidian plugin developers who need to process the body of a note without its metadata.

The first function removeYMLFromMessage removes the YAML front matter from a given string by replacing it with an empty string. The second function getFrontmatter uses the gray-matter library to extract the front matter object from a MarkdownView instance in Obsidian. Let's dive into each of these functions:

Removing Front Matter

removeYMLFromMessage(message: string) {
	try {
		const YAMLFrontMatter = /---\s*[\s\S]*?\s*---/g;
		const newMessage = message.replace(YAMLFrontMatter, "");
		return newMessage;
	} catch (err) {
		throw new Error("Error removing YML from message" + err);
	}
}

This function takes in a message parameter which is expected to be a string containing YAML front matter at the beginning of it. It then creates a regular expression pattern that matches any text between two sets of three dashes (---). This pattern is stored in YAMLFrontMatter. Finally, it replaces all instances of this pattern with an empty string using JavaScript's built-in replace method.

Parsing Front Matter

import matter from "gray-matter";

getFrontmatter(view: MarkdownView): Chat_MD_FrontMatter {
	try {
        const metaMatter =
            app.metadataCache.getFileCache(noteFile)?.frontmatter;
        const data = matter(view.getViewData());

        const frontmatter = {
	        title: metaMatter?.title || view.file.basename,
	        ...,
	        ...data.data
        };

        return frontmatter;
    } catch (err) {
        throw new Error("Error getting frontmatter");
    }
}

This function takes in an instance of MarkdownView, which represents the currently active view within Obsidian's editor window. It then retrieves information about the current file being viewed through Obsidian's API and extracts its cached metadata using .getFileCache().

Next, it uses gray-matter library to extract both content and metadata objects as separate properties on returned object called 'data'. Then, we create our own custom object called 'frontmatter' where we can add additional properties or override existing ones if needed.

Finally, this parsed data is returned as an object containing various fields such as title, tags etc., which can be used by plugins for further processing.

bramadams.dev is a reader-supported published Zettelkasten. Both free and paid subscriptions are available. If you want to support my work, the best way is by taking out a paid subscription.

Comments