How to add your own styles to Markdown globally and incrementally

There was recently the request to display a table in a markdown file flush left (the default is to center tables). Although that’s possible with a global stylesheet in “Preferences/Files/Markdown”, doing so is at the same time disabling all default styles. Which is the intendend behaviour, according to @cgrunenberg.

If someone wanted to replace only some of the default styles with their own ones, they’d have to modify each and every MD file separately, by adding the required styles.

There’s an alternative way that permits to set the styles globally without removing all the defaults. It requires a globally defined JavaScript file (again, in “Preferences/Files/Markdown”) with a content like this:

document.addEventListener("DOMContentLoaded", (event) =>  {
/* Put all your style definitions in the variable "style" below */
  const style = 'table { margin: 0.5em ;}';
  const styleEl=document.createElement('style');
  styleEl.innerHTML = style;
  document.body.appendChild(styleEl);
})

The JavaScript file can be a record in a DT database or a file in your filesystem or a URL to a file on a remote server.

In this version, the styles are defined verbatim in the script by setting the variable style to whatever you want.

An alternative would be to add a <link rel="stylesheet" href="..."> element to the head element (instead of adding a style element to body). In that case, you could put all your styles in an external file (again, in your DT database, in your local filesystem or on a webserver). Sample code:

document.addEventListener("DOMContentLoaded", (event) =>  {
  const linkEl=document.createElement('link');
  linkEl.rel = "stylesheet";
  linkEl.href="x-devonthink-item://<UUID>"; 
  document.head.appendChild(styleEl);
})

Note: In order to see the changes, you have to restart DT after changing the preferences!

3 Likes