Hakyll and KaTeX font hack

Posted on June 23, 2024 by Yu Cong
Tags: ,

1 Hakyll > Jekyll

My old Jekyll blog use pandoc and a mathjax filter. It takes about 25s to render 20 posts. Now Hakyll compiles in parallel which takes less than 2 seconds.(switching to also contributes to the speed up)

I’m familiar with neither Haskell or Ruby, so I don’t have a strong feeling that Hakyll is significantly more customizable than Jekyll. I think it is even easier to use command line pandoc filters in Jekyll than in Hakyll.

2 css and templates

The theme of this site is modified from https://mattwetmore.me/.

I like Tex Gyre Pagella font.

3 math font hack

In order to use , one needs to enable the pandoc extension --katex. In site.hs

pandocCompiler_ :: Compiler (Item String)
pandocCompiler_ =
    let
    mathExtensions =
        [ Ext_tex_math_dollars
        , Ext_tex_math_double_backslash
        , Ext_latex_macros
        , Ext_raw_tex
        , Ext_raw_html
        ]
    newExtensions = foldr enableExtension defaultExtensions mathExtensions
    defaultExtensions = writerExtensions defaultHakyllWriterOptions
    writerOptions =
        defaultHakyllWriterOptions
        { writerExtensions = newExtensions
        , writerHTMLMathMethod = KaTeX ""
        }
    in pandocCompilerWith defaultHakyllReaderOptions writerOptions

Then pandoc outputs strings for html file with all math contained in <span class="math inline/display">. Then I use https://github.com/chaoxu/katex_cli to render these formulae.

To change the fonts for , I mostly followed https://yingtongli.me/blog/2022/09/24/katex-custom-fonts.html. katex_cli is a rust project and uses a katex package for rust. cargo will install the katex package in $HOME/.cargo/registry/src/index.crates.io-xxxxxxxx/katex-0.4.6. Then modify entry.js according to https://yingtongli.me/blog/2022/09/24/katex-custom-fonts.html and modify css to change fonts.

var global;
try {
    global = Function('return this')();
} catch (e) {
    global = window;
}
const customMetrics = {...};
katex.__setFontMetrics("custom-Regular", customMetrics);
katex.__setFontMetrics("Math-Italic", customMetrics);
katex.__setFontMetrics("AMS-Regular", customMetrics);
global.katexRenderToString = katex.renderToString;


.katex .mathnormal, .katex .mathrm, .katex .custom-Regular, .katex .amsrm {
	font-family: "Tex Gyre Pagella Math";
}

4 known issues

  • non-italic math characters are not in the correct font, e.g. min and
  • font hack is not perfect, e.g. ($G'$) – I use LibertinusMath font now.
  • currently doesn’t support math in titles, (since I’m using withItemBody (unixFilter ...))
  • code highlighting & sidenotes. https://tony-zorman.com/posts.html has a good tutorial.