@@ -99,4 +99,89 @@ M.register_handler = function(handler)
9999 return require (" lz.n.handler" ).register_handler (handler )
100100end
101101
102+ --- Creates an equivalent to |vim.keymap| that will load a plugin when a keymap
103+ --- created with `keymap.set` is triggered.
104+ --- This may be useful if you have lots of keymaps defined using `vim.keymap.set`.
105+ ---
106+ --- Examples:
107+ ---
108+ --- Load a plugin by name.
109+ ---
110+ --- >lua
111+ --- local lz = require("lz.n")
112+ --- local keymap = lz.keymap("foo")
113+ --- keymap.set("n", "<leader>f", function() end, {}) -- Will load foo when invoked.
114+ --- <
115+ ---
116+ --- Load a plugin with a |lz.n.PluginSpec|.
117+ ---
118+ --- >lua
119+ --- local lz = require("lz.n")
120+ --- local keymap = lz.keymap({
121+ --- "bar",
122+ --- before = function()
123+ --- -- ...
124+ --- end,
125+ --- })
126+ --- keymap.set("n", "<leader>b", function() end, {}) -- Will load bar when invoked.
127+ --- <
128+ ---
129+ --- @param plugin string | lz.n.PluginSpec The plugin to load (name or spec ).
130+ --- @return lz.n.keymap
131+ M .keymap = function (plugin )
132+ local keymap = {
133+ --- @param mode string | string[] Mode " short-name" (see | nvim_set_keymap ()| ), or a list thereof.
134+ --- @param lhs string Left-hand side |{ lhs }| of the mapping.
135+ --- @param rhs string | function Right-hand side |{ rhs }| of the mapping , can be a Lua function.
136+ --- @param opts ? vim.keymap.set.Opts
137+ set = function (mode , lhs , rhs , opts )
138+ opts = opts or {}
139+ local spec = vim .tbl_deep_extend (" force" , opts , {
140+ [1 ] = lhs ,
141+ [2 ] = rhs ,
142+ mode = mode ,
143+ })
144+ --- @cast spec lz.n.KeysSpec
145+ local h = require (" lz.n.handler.keys" )
146+ --- @type lz.n.Plugin
147+ local plugin_
148+ if type (plugin ) == " string" then
149+ local name = plugin
150+ --- @diagnostic disable-next-line : cast-local-type
151+ plugin_ = M .lookup (name )
152+ if plugin_ then
153+ plugin_ = vim .deepcopy (plugin_ )
154+ else
155+ plugin_ = {
156+ name = name ,
157+ }
158+ end
159+ else
160+ local name = plugin [1 ]
161+ --- @diagnostic disable-next-line : cast-local-type
162+ plugin_ = M .lookup (name )
163+ if plugin_ then
164+ plugin_ = vim .tbl_deep_extend (" force" , plugin_ , plugin )
165+ else
166+ --- @diagnostic disable-next-line : cast-local-type
167+ plugin_ = vim .deepcopy (plugin )
168+ --- @diagnostic disable-next-line : inject-field
169+ plugin_ .name = name
170+ plugin_ [1 ] = nil
171+ --- @cast plugin_ lz.n.Plugin
172+ end
173+ end
174+ plugin_ .keys = nil
175+ h .parse (plugin_ , { spec })
176+ h .add (plugin_ )
177+ end ,
178+ }
179+ return keymap
180+ end
181+
182+ --- @class lz.n.keymap
183+ ---
184+ --- The same signature as |vim.keymap.set()|
185+ --- @field set fun ( mode : string | string[] , lhs : string , rhs : string | function , opts : vim.keymap.set.Opts )
186+
102187return M
0 commit comments