Search code examples
luaneovim

Neovim autocommand to add current date in markdown files using lua


New to lua. I would like to create an autocmd in my config.lua that would only apply to .md files. Every time the file is saved it would look for the line that start with Date: * and change it to Date: strftime("%Y/%M/%d"). I have been looking at the link and more specifically in the following

:autocmd BufWritePre,FileWritePre *.html   ks|call LastMod()|'s
:fun LastMod()
:  if line("$") > 20
:    let l = 20
:  else
:    let l = line("$")
:  endif
:  exe "1," .. l .. "g/Last modified: /s/Last modified: .*/Last modified: " ..
:  \ strftime("%Y %b %d")
:endfun

But I would like to do that in lua.

Would that be possible?


Solution

  • We create an command for the BufWritePre event. When this event triggers, we retrieve the buffer being written, then loop through its lines. Once we find a line starting with Date: we replace it with current date and then its saved.

    vim.api.nvim_create_autocmd(
      "BufWritePre", {
      pattern = "*.md",
      callback = function()
        local bufnr = vim.api.nvim_get_current_buf()
    
        for line_num = 0, vim.api.nvim_buf_line_count(bufnr) - 1 do
          local line = vim.api.nvim_buf_get_lines(bufnr, line_num, line_num + 1, false)[1]
    
          if line:match("Date:") then
            local new_date = os.date("Date: %Y/%m/%d")
    
            vim.api.nvim_buf_set_lines(bufnr, line_num, line_num + 1, false, { new_date })
            break
          end
        end
      end
    })