λ ryan. himmelwright. net

Enable Syntax Highlighting for .keymap Files in Neovim

test

PNC Arena, Raleigh NC

I’ve made a few minor tweaks to my keyboard layout (both in qmk and zmk) in the last few weeks. Each time, I’ve been annoyed with the non-highlighted text of the .keymap files when I edit them in neovim. I learned how to fix this, and the solution is very simple.

Background

The keymap file before syntax highlighting added.
My .keymap in neovim before fixing the syntax highlighting.

Neovim has been my editor of choice for awhile now, especially when in a terminal. I converted my configuration to a .lua setup, with treesitter for syntax highlighting about a year ago. Generally, this works well. However, the system didn’t recognize to use c highlighting for my keymap files.

:setfiletype

After some digging, I was reminded about the setfiletype option in vim. This lets you change the buffer’s file type. For example, :setfiletype markdown. When I tried setting the buffer to c, everything looked much better.

Adding to my Configuration

With a potential fix, I wanted to add it to the configuration to keep it persistent. I didn’t feel like converting this to the equivalent lua, so I just used a vim.cmd in the general file of my home-manager neovim configuration:

-- Generally read .keymap files as C ones
vim.cmd[[autocmd BufNewFile,BufRead *.keymap setfiletype c]]

This line tells vim to set the file type to c for any file that ends in .keymap. Maybe one day I’ll convert it to lua, but for now … it works 😄.

Conclusion

The keymap file with syntax highlighting added.
My .keymap in neovim after fixing the syntax highlighting.

After adding that line and rebuilding my home-manager config, neovim opens .keymap files with syntax highlighting on all my machines. Quick and simple!

Next Post:
Prev Post:

Trying Choc Sunset Switches My Required MacOs Apps (2023)