au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif

This code is valid in vim. It is the syntax of vimscript. It can also work in neovim's configuration file init.vim. how can I achieve the same effect in init.lua?

1 Answer 1


I think that this should do it

vim.api.nvim_create_autocmd({"BufReadPost"}, {
    pattern = {"*"},
    callback = function()
        if vim.fn.line("'\"") > 1 and vim.fn.line("'\"") <= vim.fn.line("$") then
            vim.api.nvim_exec("normal! g'\"",false)

Now it works fine.

  • 1
    Recently getting an error with this one, had to change vim.fn.nvim_exec to vim.api.nvim_exec
    – Jamie
    Commented Jul 30, 2023 at 7:59
  • @Jamie thanks, I updated my answer
    – TornaxO7
    Commented Jun 27 at 22:39

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.