How to append mappings in lua

Thanslate a vimscript code to lua

I have a plugin called Beacon installed, basicle:

Whenever cursor jumps some distance or moves between windows, it will flash so you can see where it is. This plugin is heavily inspired by emacs package beacon.

Some of suggested mappings are (using my map-helper function):

-- map helper
local function map(mode, lhs, rhs, opts)
    local options = { noremap = true }
    if opts then
        options = vim.tbl_extend("force", options, opts)
    end
    vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end

map('n', 'n', 'n:Beacon<cr>')
map('n', 'N', 'N:Beacon<cr>')
map('n', '*', '*:Beacon<cr>')
map('n', '#', '#:Beacon<cr>')

With no mappings, when I press n I can see the search count in the status bar, something like: [3/8].

I have found a vimscript solution that goes like this:

function! AppendMap(name, mode, rhs)
    let l:oldrhs = maparg(a:name, a:mode)
    exe printf('%smap %s %s', a:mode, a:name, l:oldrhs.a:rhs)
endf

call AppendMap('n', 'n', ':echo "detected"<CR>')
" If key 'n' was mapped to 'nzz', then it is now mapped to 'nzz:echo "detected"<CR>'

The one milion dolar question is: How to translate the vimscript function to lua?

A simple implementation can be like this

local function amap(mode, lhs, rhs)
  local map = vim.tbl_filter(function (x)
                  return x.lhs == lhs end, vim.api.nvim_get_keymap(mode))[1]
  if not map then return end
  vim.keymap.set(mode, lhs, map.rhs..rhs)
end

-- amap('n', 'n', ':echo "detected"<CR>')

You could call vim.fn.maparg too like before.

The problem I was trying to solve is mmapping n to nzz and keep seeing the search count like [3/15] in the statusbar. It seems this do not solve the problem, I have even tryied using this approach:

The maparg() function can be used to chain map commands. For example, let us say you want to define a map for . But at the same time you don’t want to lose the existing map (if any) for . Then you can do the following:

:exe 'nnoremap <Tab> ==' . maparg('<Tab>', 'n')

In my case it would be:

:exe 'nnoremap n nzz' . maparg('n', 'n')

It in fact adds an extra mapping along with the default behavior but the number of matches does not apper anymore in the status bar.

NOTE: I have also asked at the vi stackexchang the same question, just in case I get an answer I will publish it here.

I got a nice answer on the vi.stackexchange: key bindings - How to change "n" behavior withou loosing the count like [4/15] in the statusbar - Vi and Vim Stack Exchange

zz will remove the count display ( [n/nn] ) in the statusbar if the view is changed. A quick and dirty solution to show the count again is to hit n or N again, ie.

nnoremap n nzzNn