Home
🦺

Arbitrary language support in code blocks

Notion code blocks only support the following languages as of 652 days ago:

"abap", "arduino", "bash", "basic", "c", "clojure", "coffeescript", "c++", "c#", "css", "dart", "diff", "docker", "elixir", "elm", "erlang", "flow", "fortran", "f#", "gherkin", "glsl", "go", "graphql", "groovy", "haskell", "html", "java", "javascript", "json", "julia", "kotlin", "latex", "less", "lisp", "livescript", "lua", "makefile", "markdown", "markup", "matlab", "mermaid", "nix", "objective-c", "ocaml", "pascal", "perl", "php", "plain text", "powershell", "prolog", "protobuf", "python", "r", "reason", "ruby", "rust", "sass", "scala", "scheme", "scss", "shell", "sql", "swift", "typescript", "vb.net", "verilog", "vhdl", "visual basic", "webassembly", "xml", "yaml", and "java/c/c++/c#"

source: https://developers.notion.com/reference/block#code-blocks
I have a number of J posts under The J Programming language, and it would be nice if they had syntax highlighting too.
To solve this temporarily, I make use of the caption field of code blocks
I wrote a quick script to add these captions automatically on a few posts: https://github.com/jdan/notion-automations/tree/main/auto-caption
Then, I can grab the language not from the language field, but from this custom metadata in the caption like so (via 9fe0758):
const hasCustomLanguage =
  block.code.language === "plain text" &&
  /^lang=/.test(concatenateText(block.code.caption));

const language = hasCustomLanguage
  ? concatenateText(block.code.caption).slice("lang=".length)
  : block.code.language.toLowerCase();
if (language !== "plain text" && !Prism.languages[language]) {
  console.log("Unrecognized language --", language);
}