Vim.keymap.set behaves differently than manual key presses

I have the following keymap (I usually prefer LSP formatting to this, but I still don’t understand why this doesn’t work as intended):

vim.keymap.set('n',
    '<leader>=',
    'gg=G<C-o>',
    -- function()
    --     local _, lnum, col, _, _ = unpack(vim.fn.getcursorcharpos())
    --     vim.cmd([[execute "normal gg=G"]])
    --     vim.fn.setcursorcharpos({ lnum, col })
    -- end,
    { silent = true, desc = 'Indent buffer' }
)

If I manually enter “gg” then “=” then “G” then “<C-o>” on my keyboard, then it does what I would expect: It indents the buffer and returns me to the line I started the command on.

But when I use the keymap it always puts me 2 or 3 lines below the line I started on.

I have tried to use [[ gg=G’’ ]] instead of the above, I have tried the commented out function and other things I could think of (changing the keymap to “g=” or “g1” or “i”, removing silent = true, checking my :map definitions etc.), but nothing seems to make the keymap work as intended.

Does anyone have any idea what could be wrong here? If the manual entering of the keys didn’t work, that would make more sense to me, but I am confused about why this keymap behaves different than the command. (This is not a problem for all of my other keymaps.)

How can I try to figure out what is causing this problem?

EDIT: In case anyone else runs into this problem, I ended up using the following, which has the expected behavior:

vim.keymap.set('n',
    '<leader>=',
    'ggVG=<C-o>',
    -- The following two methods don't work for some reason
    -- 'gg=G<C-o>',
    -- function()
    --     local _, lnum, col, _, _ = unpack(vim.fn.getcursorcharpos())
    --     vim.cmd([[execute "normal gg=G"]])
    --     vim.fn.setcursorcharpos({ lnum, col })
    -- end,
    { silent = true, desc = 'Indent buffer' }
)

I would still like to know what the problem with the original code is though.

I cannot reproduce your problem. Your original mapping works fine for me. Try starting a clean session (nvim --clean ), defining the mapping, and see how that goes. It could be that the mapping is clashing with other plugins or configurations.

Thank you for trying to reproduce this. When starting a clean session with nvim --clean and defining the mapping, I did not have my previous problem, so it must be something in my setup elsewhere (or a package) that interferes, but since my posted “solution” above solves the problem I will probably not spend much time trying to track down the exact problem.