0

Related to this post How to display multiple changed files on disk in Vim?,

I want to implement this feature in Lua. Some help would be appreciated.

set autoread
autocmd FocusGained,BufEnter,CursorHold,CursorHoldI *
  \ if mode() !~ '\v(c|r.?|!|t)' && getcmdwintype() == '' | checktime | endif

let g:filechanged_timer = 0
let g:filechanged = ""

function! FileChangedCallback(timer)
  echohl WarningMsg
  echo "File " . g:filechanged . " changed on disk. Buffer reloaded."
  echohl None

  " Reset the timer and the list of files:
  let g:filechanged_timer = 0
  let g:filechanged = ""
endfunction

function! FileChanged(path)
  if g:filechanged_timer == 0
    " First change detected
    let g:filechanged = a:path
    " Wait 0.1 seconds for a new changes to come:
    let g:filechanged_timer = timer_start(100, 'FileChangedCallback')
  else
    " Some more change detected
    " Add the file path to the list:
    let g:filechanged = g:filechanged .. ', ' .. a:path
  endif
endfunction

autocmd! FileChangedShellPost * call FileChanged(expand('<afile>'))

1 Answer 1

1

Here is a lua version of the same:

vim.g.filechanged = ""

function FileChangedCallback()
    vim.api.nvim_command([[
        echohl WarningMsg
        echom "File " . g:filechanged . " changed on disk. Buffer reloaded."
        echohl None
        ]])
end

function FileChanged(path)
    if vim.g.filechanged == "" then
        vim.g.filechanged = path
        vim.defer_fn(FileChangedCallback, 100)
    else
        vim.g.filechanged = vim.g.filechanged .. ' ' .. path
    end
end

vim.o.autoread = 1

vim.api.nvim_create_autocmd({'FocusGained', 'BufEnter', 'CursorHold', 'CursorHoldI'}, { callback = function()
    if not string.match(vim.fn.mode(), '^(c|r.?|!|t)') and vim.api.nvim_eval('getcmdwintype()') == '' then
        vim.cmd([[checktime]])
    end
end
})

vim.api.nvim_create_autocmd({'FileChangedShellPost'}, { callback = function()
    FileChanged(vim.fn.expand('<afile>'))
end
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.