Syntax highlighting
Defining the MIME type#
The first step to supporting a new language for either code blocks or code notes is to define the MIME type. Go to mime_type.ts in packages/commons and add a corresponding entry:
{ title: "ABAP (SAP)", mime: "text/x-abap", mdLanguageCode: "abap" }Where mdLanguageCode is a Markdown-friendly name of the language.
Syntax highlighting for Highlight.js#
The Highlight.js instance in Trilium identifies the code to highlight by the mime type mappings defined in syntax_highlighting.ts in packages/highlightjs.
There are three possible cases, all involving modifying the byMimeType record:
Highlight.js built-in languages:#
Simply add a corresponding entry:
"application/dart": () => import("highlight.js/lib/languages/dart"),External modules from NPM#
Install the module as a dependency in
packages/highlight.jsImport:
"application/x-cypher-query": () => import("highlightjs-cypher")Do this if the npm module is relatively new and it has TypeScript mappings, if not see the last option.
Modules integrated directly into Trilium#
- Allows making small modifications if needed (especially if the module is old).
- Works well for modules missing type definitions, since types are added directly in code.
Steps:
Copy the syntax highlighting file (example) into
packages/highlightjs/src/languages/[code].ts.Add a link in a comment at the top of the file linking to the original source code.
Replace
module.exports =byexport default.Add types to the method:
import { HLJSApi, Language } from "highlight.js"; export default function (hljs: HLJSApi): Language { // [...] }Remove any module loading mechanism or shims outside the main highlight function.
Modify
syntax_highlighting.jsto support the new language:"text/x-abap": () => import("./languages/abap.js"),
Syntax highlighting for CodeMirror#
Adding the MIME type mapping#
Similar to Highlight.js, the mappings for each MIME type are handled in syntax_highlighting.ts in packages/codemirror, by modifying the byMimeType record.
Official modules:
async () => (await import('@codemirror/lang-html')).html(),Legacy modules (ported from CodeMirror 5):
"text/turtle": async () => (await import('@codemirror/legacy-modes/mode/turtle')).turtle,Modules integrated into Trilium:
"application/x-bat": async () => (await import("./languages/batch.js")).batch,
Integrating existing modules#
- Add a comment at the beginning indicating the link to the original source code.
- Some imports might require updating:
- Instead of
import { StreamParser, StringStream } from "@codemirror/stream-parser";, useimport { StreamParser, StringStream } from "@codemirror/language";
- Instead of