Hook doesn't work in kakrc but does work in file

Hi - I’m trying to set up auto-compilation for LaTeX files. To this end, I want to add a hook to compile on write:
hook global BufWritePost %val{buffile} %{ texlab-build }
This does not work when I put it in my kakrc. Then, I get the following error in my debug buffer:

*** This is the debug buffer, where debug info will be written ***
kak-lsp: config-change detected: 
/home/alice/.config/kak/kakrc:no buffer in context
/nix/store/qh12nffjbs01nf5svifq94hjin9dsz9y-kakoune-2023.08.05/share/kak/kakrc:29:1: 'evaluate-commands': 141:1: 'source': no buffer in context
error while parsing kakrc:
    1:1: 'source': 29:1: 'evaluate-commands': 141:1: 'source': no buffer in context
kak-lsp: config-change detected: 
kak-lsp: config-change detected: 
kak-lsp: config-change detected: 
kak-lsp: Language server is not configured for filetype ``

And writing doesn’t recompile as intended. However, if i insert this hook after starting kakoune, it works perfectly. Why would this be? what additional info can I provide?

The expansion %val{buffile} is replaced with the full path to the current buffer.

One reason this could cause a problem is because the hook filter is supposed to be a regex, and if the filename contains any regex-sensitive characters (like punctuation) that could make the hook trigger more or less frequently than expected.

The big reason this doesn’t work, however, is that the kakrc file is loaded before any buffers exist at all, so trying to execute a command with %val{buffile}gives you that “no buffer in context” error you see.

The simplest fix is to replace %val{buffile} with a static regex like .* that matches every file name, but then you’ll be invoking texlab-build when you write any file, not just LaTeX files.

A better solution might be to change the pattern to .*\.tex (or whatever extension you use for your LaTeX files), so it only fires for them.

The best solution would be, instead of defining this hook globally, define it at window scope in a global WinSetOption filetype=latex hook so that it applies to all files autodetected as LaTeX by whatever means.

There’s some hooks like that in latex.kak in Kakoune’s standard library, you can look at those if you want some examples.

1 Like

awesome, thank you for the info! i’ll try this out

works perfectly! if anyone else finds this thread, here’s the top-level hook I ended up using:

hook   global WinSetOption filetype=latex %{ hook global BufWritePost .* %{ texlab-build } }