How to add custom filetype detection to various ".env" files?

I’m trying to make Neovim detect the following list of files as a cutom dotenv filetype;

  • .env or env
  • .env.local or env.local
  • .env.example or env.example
  • .env.prod or env.prod

(notice the missing preceding dot in some of the filenames).

The code I tried experimenting with in my init.lua file is something like this:

vim.filetype.add({
  -- ...
  -- Some more configurations
  -- ...
  pattern = {
    [".?env.?*"] = "dotenv",
  },
})

But it does not work as I expect it to. While the .env always gets detected as sh file, the others doesn’t get detected at all!

I suspect my regex pattern is wrong so what would be the regex pattern to match the aforementioned filenames?

If it is lua pattern it should be .?env.?.* (you missed . before the *). But it will also match envsomething, not sure if that’s your intention.

After a bit of asking around for more help on this regards, I referred to this dotfiles repository. I took some inspiration from it and added it to my dotfiles.

If you can’t access the links shared above, here are the contents of the filetype.lua I added:

-- Module for defining new filetypes. I picked up these configurations based on inspirations from this dotfiles repo:
-- https://github.com/davidosomething/dotfiles/blob/be22db1fc97d49516f52cef5c2306528e0bf6028/nvim/lua/dko/filetypes.lua

vim.filetype.add({
  -- Detect and assign filetype based on the extension of the filename
  extension = {
    mdx = "mdx",
    log = "log",
    conf = "conf",
    env = "dotenv",
  },
  -- Detect and apply filetypes based on the entire filename
  filename = {
    [".env"] = "dotenv",
    ["env"] = "dotenv",
    ["tsconfig.json"] = "jsonc",
  },
  -- Detect and apply filetypes based on certain patterns of the filenames
  pattern = {
    -- INFO: Match filenames like - ".env.example", ".env.local" and so on
    ["%.env%.[%w_.-]+"] = "dotenv",
  },
})

The aforementioned configurations properly identifies and applies the proper filetype detection (i.e dotenv) to the following list of files:

  • .env or env
  • .env.local or env.local
  • .env.example or env.example

There is probably a better solution to this issue I’m facing but so far I couldn’t come up with anything better. So, if you’ve have better solution (perhaps using the pattern key with a regexp?), please feel free to share it here.

1 Like

This is how I handle it