`vim.filetype.add()`, with the `filename` option, seems not working

To set filetype as YAML for the kubernetes config file($HOME/.kube/config), which has no file extension, I configured the lua script following this:

vim.filetype.add({
 filename = {
   ['.kube/config'] = 'yaml',
 },
})

But it is not working. I also tried in a buffer with :lua vim.filetype.add({ filename = { ['.kube/config'] = 'yaml' } }) and/or with the filename as absolute path(like /Users/hans/.kube/config, I use macOS btw) but all of those are not working.

Only :set filetype=yaml for a buffer works.

What I missed?

FYI:
This is the commit on this and you can check all configs from that dotfiles repo.

The script above should be placed in the config directory, which is ~/.config/nvim/filetype.lua on linux.

1 Like

Thank you. It works with changing to absolute path. Great but how? Is there priorities on a config hierachy?

FYI:

  • My $VIMRUNTIME is /usr/local/Cellar/neovim/0.8.0/share/nvim/runtime
  • And $XDG_(CONFIG|DATA)_(HOME|DIRS) are empty

+ Can I reference the $HOME in a lua script?

It is fine to put vim.filetype.add() in your init.vim or init.lua file. It does not need to be in a separate filetype.lua file.

The “filename” key matches on the file name exactly. That is why it only works for either absolute paths or on just the name of the file itself (not the path of the file). To match on a subpath, use the “pattern” key:

vim.filetype.add({
  pattern = {
    [".*/%.kube/config"] = "yaml",
  },
})
2 Likes

You are right. The script works not only at ~/.config/nvim/filetype.lua, but also anywhere that can be loaded. I was confused.

The suggestion, “pattern” for subpaths, is good, I use the HOME itself, however. I’d like to set it only for that, not in all subpath:

require('os')

vim.filetype.add({
  filename = {
    [os.getenv('HOME') .. '/.kube/config'] = "yaml",
  },
})

1 Like