Custom mappings with description

I have the following map helper function

local function map(mode, lhs, rhs, opts)
    local options = { noremap = true, silent = true }
    if opts then
        options = vim.tbl_extend('force', options, opts)
    end
    vim.keymap.set(mode, lhs, rhs, options)
end

And I stumbled upon this config with an interesting idea, a way of pretending a string to the each mapping description, where I can use to easily debug my mappings, because there are mappings that come from plugins, from my ftplugins etc. The idea seems like this:

  local nmap = function(keys, func, desc)
    if desc then
      desc = 'LSP: ' .. desc
    end

    vim.keymap.set('n', keys, func, { buffer = bufnr, desc = desc })
  end

As you can see in the above case the description indicates that those mappings come from the LSP.

How can I addapt my function so I can have the same in my map helper?

My attempt, it seems that is working

local function map(mode, lhs, rhs, opts)
    local options = { noremap = true, silent = true }
    if opts then
        if opts['desc'] then
            opts['desc'] = 'keymaps.lua: ' .. opts['desc']
        end
        options = vim.tbl_extend('force', options, opts)
    end
    vim.keymap.set(mode, lhs, rhs, options)
end

my lsp mapping function might be of help

    local function map(mode, lhs, lsp_func, args)
        args = args ~= nil and args or {}
        local opts = { silent = true, desc = 'lsp: ' .. lsp_func }
        local set_keymap = vim.keymap.set
        local lsp_buf = vim.lsp.buf

        set_keymap(mode, lhs, function()
            lsp_buf[lsp_func](args)
        end, opts)
    end
1 Like