Autocmd to lua for filetype

Hi,
I would like to covert to following vim autocmd:

vim.cmd [[
    autocmd BufNewFile,BufRead * if search('{{.\+}}', 'nw') | setlocal filetype=gotmpl | endif
]]

to using neovim lua.

I have tried to following:

vim.api.nvim_create_autocmd(
    "BufEnter",
    {
        pattern = "*.yaml,*.yml",
        callback = function()
            if vim.fn.search("{{.\\+}}", "nw") ~= 0 then
                local buf = vim.api.nvim_get_current_buf()
                vim.api.nvim_buf_set_option(buf, "filetype", "gotmpl")
            end
        end
    }
)

it changes the filetype (:set filetype?) to gotmpl but the yaml lsp is still showing errors.

vim.api.nvim_create_autocmd(
    "BufNewFile,BufRead",
    {
        pattern = "*.yaml,*.yml",
        callback = function()
            if vim.fn.search("{{.\\+}}", "nw") ~= 0 then
                local buf = vim.api.nvim_get_current_buf()
                vim.api.nvim_buf_set_option(buf, "filetype", "gotmpl")
            end
        end
    }
)

when I open neovim it is never triggered.

Any suggestions?

Thanks

Found the solution:

vim.api.nvim_create_autocmd(
    {
        "BufNewFile",
        "BufRead",
    },
    {
        pattern = "*.yaml,*.yml",
        callback = function()
            if vim.fn.search("{{.\\+}}", "nw") ~= 0 then
                local buf = vim.api.nvim_get_current_buf()
                vim.api.nvim_buf_set_option(buf, "filetype", "gotmpl")
            end
        end
    }
)
1 Like

Try: Introducing filetype.lua and a call for help (filetype.lua)