robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. KeyesMerge #40579 from barrettruth/fix/del-keymap-lhs-only-30258256a88d0ac

master
47.1 KiB1552 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each = t.describe, t.it, t.before_each
5local clear = n.clear
6local command = n.command
7local eq, neq = t.eq, t.neq
8local exec_lua = n.exec_lua
9local exec = n.exec
10local feed = n.feed
11local fn = n.fn
12local api = n.api
13local matches = t.matches
14local source = n.source
15local pcall_err = t.pcall_err
16
17local shallowcopy = t.shallowcopy
18local sleep = vim.uv.sleep
19
20local sid_api_client = -9
21local sid_lua = -8
22
23local mode_bits_map = {
24  ['n'] = 0x01,
25  ['x'] = 0x02,
26  ['o'] = 0x04,
27  ['c'] = 0x08,
28  ['i'] = 0x10,
29  ['l'] = 0x20,
30  ['s'] = 0x40,
31  ['t'] = 0x80,
32  [' '] = 0x47,
33  ['v'] = 0x42,
34  ['!'] = 0x18,
35}
36
37describe('nvim_get_keymap', function()
38  before_each(clear)
39
40  -- Basic mapping and table to be used to describe results
41  local foo_bar_string = 'nnoremap foo bar'
42  local foo_bar_map_table = {
43    lhs = 'foo',
44    lhsraw = 'foo',
45    script = 0,
46    silent = 0,
47    rhs = 'bar',
48    expr = 0,
49    replace_keycodes = 0,
50    sid = 0,
51    scriptversion = 1,
52    buf = 0,
53    buffer = 0, -- deprecated
54    nowait = 0,
55    mode = 'n',
56    mode_bits = 0x01,
57    abbr = 0,
58    noremap = 1,
59    lnum = 0,
60  }
61
62  it('returns empty list when no map', function()
63    eq({}, api.nvim_get_keymap('n'))
64  end)
65
66  it('returns list of all applicable mappings', function()
67    command(foo_bar_string)
68    -- Only one mapping available. Should be the same as `foo_bar_map_table`, and maparg() result
69    -- (plus "buf"), since this is a global map.
70    eq({ foo_bar_map_table }, api.nvim_get_keymap('n'))
71    -- Add "buf" key to maparg() result.
72    local maparg_rv = vim.tbl_deep_extend('force', fn.maparg('foo', 'n', false, true), { buf = 0 })
73    eq({ maparg_rv }, api.nvim_get_keymap('n'))
74
75    -- Add another mapping
76    command('nnoremap foo_longer bar_longer')
77    local foolong_bar_map_table = shallowcopy(foo_bar_map_table)
78    foolong_bar_map_table['lhs'] = 'foo_longer'
79    foolong_bar_map_table['lhsraw'] = 'foo_longer'
80    foolong_bar_map_table['rhs'] = 'bar_longer'
81
82    eq({ foolong_bar_map_table, foo_bar_map_table }, api.nvim_get_keymap('n'))
83
84    -- Remove a mapping
85    command('unmap foo_longer')
86    eq({ foo_bar_map_table }, api.nvim_get_keymap('n'))
87  end)
88
89  it('works for other modes', function()
90    -- Add two mappings, one in insert and one normal
91    -- We'll only check the insert mode one
92    command('nnoremap not_going to_check')
93
94    command('inoremap foo bar')
95    -- The table will be the same except for the mode
96    local insert_table = shallowcopy(foo_bar_map_table)
97    insert_table['mode'] = 'i'
98    insert_table['mode_bits'] = 0x10
99
100    eq({ insert_table }, api.nvim_get_keymap('i'))
101  end)
102
103  it('considers scope', function()
104    -- change the map slightly
105    command('nnoremap foo_longer bar_longer')
106    local foolong_bar_map_table = shallowcopy(foo_bar_map_table)
107    foolong_bar_map_table['lhs'] = 'foo_longer'
108    foolong_bar_map_table['lhsraw'] = 'foo_longer'
109    foolong_bar_map_table['rhs'] = 'bar_longer'
110
111    local buffer_table = shallowcopy(foo_bar_map_table)
112    buffer_table['buf'] = 1
113    buffer_table['buffer'] = 1 -- deprecated
114
115    command('nnoremap <buffer> foo bar')
116
117    -- The buffer mapping should not show up
118    eq({ foolong_bar_map_table }, api.nvim_get_keymap('n'))
119    eq({ buffer_table }, api.nvim_buf_get_keymap(0, 'n'))
120  end)
121
122  it('considers scope for overlapping maps', function()
123    command('nnoremap foo bar')
124
125    local buffer_table = shallowcopy(foo_bar_map_table)
126    buffer_table['buf'] = 1
127    buffer_table['buffer'] = 1 -- deprecated
128
129    command('nnoremap <buffer> foo bar')
130
131    eq({ foo_bar_map_table }, api.nvim_get_keymap('n'))
132    eq({ buffer_table }, api.nvim_buf_get_keymap(0, 'n'))
133  end)
134
135  it('can retrieve mapping for different buffers', function()
136    local original_buffer = api.nvim_buf_get_number(0)
137    -- Place something in each of the buffers to make sure they stick around
138    -- and set hidden so we can leave them
139    command('set hidden')
140    command('new')
141    command('normal! ihello 2')
142    command('new')
143    command('normal! ihello 3')
144
145    local final_buffer = api.nvim_buf_get_number(0)
146
147    command('nnoremap <buffer> foo bar')
148    -- Final buffer will have buffer mappings
149    local buffer_table = shallowcopy(foo_bar_map_table)
150    buffer_table['buf'] = final_buffer
151    buffer_table['buffer'] = final_buffer -- deprecated
152    eq({ buffer_table }, api.nvim_buf_get_keymap(final_buffer, 'n'))
153    eq({ buffer_table }, api.nvim_buf_get_keymap(0, 'n'))
154
155    command('buffer ' .. original_buffer)
156    eq(original_buffer, api.nvim_buf_get_number(0))
157    -- Original buffer won't have any mappings
158    eq({}, api.nvim_get_keymap('n'))
159    eq({}, api.nvim_buf_get_keymap(0, 'n'))
160    eq({ buffer_table }, api.nvim_buf_get_keymap(final_buffer, 'n'))
161  end)
162
163  -- Test toggle switches for basic options
164  -- @param  option  The key represented in the `maparg()` result dict
165  local function global_and_buffer_test(
166    map,
167    option,
168    option_token,
169    global_on_result,
170    buffer_on_result,
171    global_off_result,
172    buffer_off_result,
173    new_windows
174  )
175    local function make_new_windows(number_of_windows)
176      if new_windows == nil then
177        return nil
178      end
179
180      for _ = 1, number_of_windows do
181        command('new')
182      end
183    end
184
185    local mode = string.sub(map, 1, 1)
186    -- Don't run this for the <buffer> mapping, since it doesn't make sense
187    if option_token ~= '<buffer>' then
188      it(
189        string.format(
190          'returns %d for the key "%s" when %s is used globally with %s (%s)',
191          global_on_result,
192          option,
193          option_token,
194          map,
195          mode
196        ),
197        function()
198          make_new_windows(new_windows)
199          command(map .. ' ' .. option_token .. ' foo bar')
200          local result = api.nvim_get_keymap(mode)[1][option]
201          eq(global_on_result, result)
202        end
203      )
204    end
205
206    it(
207      string.format(
208        'returns %d for the key "%s" when %s is used for buffers with %s (%s)',
209        buffer_on_result,
210        option,
211        option_token,
212        map,
213        mode
214      ),
215      function()
216        make_new_windows(new_windows)
217        command(map .. ' <buffer> ' .. option_token .. ' foo bar')
218        local result = api.nvim_buf_get_keymap(0, mode)[1][option]
219        eq(buffer_on_result, result)
220      end
221    )
222
223    -- Don't run these for the <buffer> mapping, since it doesn't make sense
224    if option_token ~= '<buffer>' then
225      it(
226        string.format(
227          'returns %d for the key "%s" when %s is not used globally with %s (%s)',
228          global_off_result,
229          option,
230          option_token,
231          map,
232          mode
233        ),
234        function()
235          make_new_windows(new_windows)
236          command(map .. ' baz bat')
237          local result = api.nvim_get_keymap(mode)[1][option]
238          eq(global_off_result, result)
239        end
240      )
241
242      it(
243        string.format(
244          'returns %d for the key "%s" when %s is not used for buffers with %s (%s)',
245          buffer_off_result,
246          option,
247          option_token,
248          map,
249          mode
250        ),
251        function()
252          make_new_windows(new_windows)
253          command(map .. ' <buffer> foo bar')
254
255          local result = api.nvim_buf_get_keymap(0, mode)[1][option]
256          eq(buffer_off_result, result)
257        end
258      )
259    end
260  end
261
262  -- Standard modes and returns the same values in the dictionary as maparg()
263  local mode_list = { 'nnoremap', 'nmap', 'imap', 'inoremap', 'cnoremap' }
264  for mode in pairs(mode_list) do
265    global_and_buffer_test(mode_list[mode], 'silent', '<silent>', 1, 1, 0, 0)
266    global_and_buffer_test(mode_list[mode], 'nowait', '<nowait>', 1, 1, 0, 0)
267    global_and_buffer_test(mode_list[mode], 'expr', '<expr>', 1, 1, 0, 0)
268  end
269
270  -- noremap will now be 2 if script was used, which is not the same as maparg()
271  global_and_buffer_test('nmap', 'noremap', '<script>', 2, 2, 0, 0)
272  global_and_buffer_test('nnoremap', 'noremap', '<script>', 2, 2, 1, 1)
273
274  -- buffer will return the buffer ID, which is not the same as maparg()
275  -- Three of these tests won't run
276  global_and_buffer_test('nnoremap', 'buffer', '<buffer>', nil, 3, nil, nil, 2)
277
278  it('returns script numbers for global maps', function()
279    source([[
280      function! s:maparg_test_function() abort
281        return 'testing'
282      endfunction
283
284      nnoremap fizz :call <SID>maparg_test_function()<CR>
285    ]])
286    local sid_result = api.nvim_get_keymap('n')[1]['sid']
287    eq(1, sid_result)
288    eq('testing', api.nvim_call_function('<SNR>' .. sid_result .. '_maparg_test_function', {}))
289  end)
290
291  it('returns script numbers for buffer maps', function()
292    source([[
293      function! s:maparg_test_function() abort
294        return 'testing'
295      endfunction
296
297      nnoremap <buffer> fizz :call <SID>maparg_test_function()<CR>
298    ]])
299    local sid_result = api.nvim_buf_get_keymap(0, 'n')[1]['sid']
300    eq(1, sid_result)
301    eq('testing', api.nvim_call_function('<SNR>' .. sid_result .. '_maparg_test_function', {}))
302  end)
303
304  it('works with <F12> and others', function()
305    command('nnoremap <F12> :let g:maparg_test_var = 1<CR>')
306    eq('<F12>', api.nvim_get_keymap('n')[1]['lhs'])
307    eq(':let g:maparg_test_var = 1<CR>', api.nvim_get_keymap('n')[1]['rhs'])
308  end)
309
310  it("works correctly despite 'cpoptions'", function()
311    local cpo_table = {
312      script = 0,
313      silent = 0,
314      expr = 0,
315      replace_keycodes = 0,
316      sid = 0,
317      scriptversion = 1,
318      buf = 0,
319      buffer = 0, -- deprecated
320      nowait = 0,
321      abbr = 0,
322      noremap = 1,
323      lnum = 0,
324    }
325    local function cpomap(lhs, rhs, mode)
326      local ret = shallowcopy(cpo_table)
327      local lhsraw = api.nvim_eval(('"%s"'):format(lhs:gsub('\\', '\\\\'):gsub('<', '\\<*')))
328      local lhsrawalt = api.nvim_eval(('"%s"'):format(lhs:gsub('\\', '\\\\'):gsub('<', '\\<')))
329      ret.lhs = lhs
330      ret.lhsraw = lhsraw
331      ret.lhsrawalt = lhsrawalt ~= lhsraw and lhsrawalt or nil
332      ret.rhs = rhs
333      ret.mode = mode
334      ret.mode_bits = mode_bits_map[mode]
335      return ret
336    end
337
338    command('set cpo+=B')
339    command('nnoremap \\<C-a><C-a><LT>C-a>\\  \\<C-b><C-b><LT>C-b>\\')
340    command('nnoremap <special> \\<C-c><C-c><LT>C-c>\\  \\<C-d><C-d><LT>C-d>\\')
341
342    command('set cpo+=B')
343    command('xnoremap \\<C-a><C-a><LT>C-a>\\  \\<C-b><C-b><LT>C-b>\\')
344    command('xnoremap <special> \\<C-c><C-c><LT>C-c>\\  \\<C-d><C-d><LT>C-d>\\')
345
346    command('set cpo-=B')
347    command('snoremap \\<C-a><C-a><LT>C-a>\\  \\<C-b><C-b><LT>C-b>\\')
348    command('snoremap <special> \\<C-c><C-c><LT>C-c>\\  \\<C-d><C-d><LT>C-d>\\')
349
350    command('set cpo-=B')
351    command('onoremap \\<C-a><C-a><LT>C-a>\\  \\<C-b><C-b><LT>C-b>\\')
352    command('onoremap <special> \\<C-c><C-c><LT>C-c>\\  \\<C-d><C-d><LT>C-d>\\')
353
354    for _, cmd in ipairs({
355      'set cpo-=B',
356      'set cpo+=B',
357    }) do
358      command(cmd)
359      eq({
360        cpomap('\\<C-C><C-C><lt>C-c>\\', '\\<C-D><C-D><lt>C-d>\\', 'n'),
361        cpomap('\\<C-A><C-A><lt>C-a>\\', '\\<C-B><C-B><lt>C-b>\\', 'n'),
362      }, api.nvim_get_keymap('n'))
363      eq({
364        cpomap('\\<C-C><C-C><lt>C-c>\\', '\\<C-D><C-D><lt>C-d>\\', 'x'),
365        cpomap('\\<C-A><C-A><lt>C-a>\\', '\\<C-B><C-B><lt>C-b>\\', 'x'),
366      }, api.nvim_get_keymap('x'))
367      eq({
368        cpomap('<lt>C-c><C-C><lt>C-c> ', '<lt>C-d><C-D><lt>C-d>', 's'),
369        cpomap('<lt>C-a><C-A><lt>C-a> ', '<lt>C-b><C-B><lt>C-b>', 's'),
370      }, api.nvim_get_keymap('s'))
371      eq({
372        cpomap('<lt>C-c><C-C><lt>C-c> ', '<lt>C-d><C-D><lt>C-d>', 'o'),
373        cpomap('<lt>C-a><C-A><lt>C-a> ', '<lt>C-b><C-B><lt>C-b>', 'o'),
374      }, api.nvim_get_keymap('o'))
375    end
376  end)
377
378  it('always uses space for space and bar for bar', function()
379    local space_table = {
380      lhs = '|   |',
381      lhsraw = '|   |',
382      rhs = '|    |',
383      mode = 'n',
384      mode_bits = 0x01,
385      abbr = 0,
386      script = 0,
387      silent = 0,
388      expr = 0,
389      replace_keycodes = 0,
390      sid = 0,
391      scriptversion = 1,
392      buf = 0,
393      buffer = 0, -- deprecated
394      nowait = 0,
395      noremap = 1,
396      lnum = 0,
397    }
398    command('nnoremap \\|<Char-0x20><Char-32><Space><Bar> \\|<Char-0x20><Char-32><Space> <Bar>')
399    eq({ space_table }, api.nvim_get_keymap('n'))
400  end)
401
402  it('can handle lua mappings', function()
403    eq(
404      0,
405      exec_lua([[
406      GlobalCount = 0
407      vim.api.nvim_set_keymap('n', 'asdf', '', {
408        callback = function() GlobalCount = GlobalCount + 1 end,
409      })
410      return GlobalCount
411    ]])
412    )
413
414    feed('asdf\n')
415    eq(1, exec_lua([[return GlobalCount]]))
416
417    eq(
418      2,
419      exec_lua([[
420      vim.api.nvim_get_keymap('n')[1].callback()
421      return GlobalCount
422    ]])
423    )
424
425    exec([[
426      call nvim_get_keymap('n')[0].callback()
427    ]])
428    eq(3, exec_lua([[return GlobalCount]]))
429
430    local mapargs = api.nvim_get_keymap('n')
431    mapargs[1].callback = nil
432    eq({
433      lhs = 'asdf',
434      lhsraw = 'asdf',
435      script = 0,
436      silent = 0,
437      expr = 0,
438      replace_keycodes = 0,
439      sid = sid_lua,
440      scriptversion = 1,
441      buf = 0,
442      buffer = 0, -- deprecated
443      nowait = 0,
444      mode = 'n',
445      mode_bits = 0x01,
446      abbr = 0,
447      noremap = 0,
448      lnum = 0,
449    }, mapargs[1])
450  end)
451
452  it('can handle map descriptions', function()
453    api.nvim_set_keymap('n', 'lhs', 'rhs', { desc = 'map description' })
454    eq({
455      lhs = 'lhs',
456      lhsraw = 'lhs',
457      rhs = 'rhs',
458      script = 0,
459      silent = 0,
460      expr = 0,
461      replace_keycodes = 0,
462      sid = sid_api_client,
463      scriptversion = 1,
464      buf = 0,
465      buffer = 0, -- deprecated
466      nowait = 0,
467      mode = 'n',
468      mode_bits = 0x01,
469      abbr = 0,
470      noremap = 0,
471      lnum = 0,
472      desc = 'map description',
473    }, api.nvim_get_keymap('n')[1])
474  end)
475
476  it('can get abbreviations', function()
477    command('inoreabbr foo bar')
478    command('cnoreabbr <buffer> foo baz')
479
480    local mapargs_i = {
481      abbr = 1,
482      buf = 0,
483      buffer = 0, -- deprecated
484      expr = 0,
485      replace_keycodes = 0,
486      lhs = 'foo',
487      lhsraw = 'foo',
488      lnum = 0,
489      mode = 'i',
490      mode_bits = 0x10,
491      noremap = 1,
492      nowait = 0,
493      rhs = 'bar',
494      script = 0,
495      scriptversion = 1,
496      sid = 0,
497      silent = 0,
498    }
499    local mapargs_c = {
500      abbr = 1,
501      buf = 1,
502      buffer = 1, -- deprecated
503      expr = 0,
504      replace_keycodes = 0,
505      lhs = 'foo',
506      lhsraw = 'foo',
507      lnum = 0,
508      mode = 'c',
509      mode_bits = 0x08,
510      noremap = 1,
511      nowait = 0,
512      rhs = 'baz',
513      script = 0,
514      scriptversion = 1,
515      sid = 0,
516      silent = 0,
517    }
518
519    local curbuf = api.nvim_get_current_buf()
520
521    eq({ mapargs_i }, api.nvim_get_keymap('ia'))
522    eq({}, api.nvim_buf_get_keymap(curbuf, 'ia'))
523
524    eq({}, api.nvim_get_keymap('ca'))
525    eq({ mapargs_c }, api.nvim_buf_get_keymap(curbuf, 'ca'))
526
527    eq({ mapargs_i }, api.nvim_get_keymap('!a'))
528    eq({ mapargs_c }, api.nvim_buf_get_keymap(curbuf, '!a'))
529  end)
530end)
531
532describe('nvim_set_keymap, nvim_del_keymap', function()
533  before_each(clear)
534
535  -- `generate_expected` is truthy: for generating an expected output for
536  -- maparg(), which does not accept "!" (though it returns "!" in its output
537  -- if getting a mapping set with |:map!|).
538  local function normalize_mapmode(mode, generate_expected)
539    if mode:sub(-1) == 'a' then
540      mode = mode:sub(1, -2)
541    end
542    if not generate_expected and mode == '!' then
543      -- Cannot retrieve mapmode-ic mappings with "!", but can with "i" or "c".
544      mode = 'i'
545    elseif mode == '' then
546      mode = generate_expected and ' ' or mode
547    end
548    return mode
549  end
550
551  -- Generate a mapargs dict, for comparison against the mapping that was
552  -- actually set
553  local function generate_mapargs(mode, lhs, rhs, opts)
554    if not opts then
555      opts = {}
556    end
557
558    local to_return = {}
559    local expected_mode = normalize_mapmode(mode, true)
560    to_return.mode = expected_mode
561    to_return.mode_bits = mode_bits_map[expected_mode]
562    to_return.abbr = mode:sub(-1) == 'a' and 1 or 0
563    to_return.noremap = not opts.noremap and 0 or 1
564    to_return.lhs = lhs
565    to_return.rhs = rhs
566    to_return.script = 0
567    to_return.silent = not opts.silent and 0 or 1
568    to_return.nowait = not opts.nowait and 0 or 1
569    to_return.expr = not opts.expr and 0 or 1
570    to_return.replace_keycodes = not opts.replace_keycodes and 0 or 1
571    to_return.sid = not opts.sid and sid_api_client or opts.sid
572    to_return.scriptversion = 1
573    -- to_return.buf = not opts.buffer and 0 or opts.buffer
574    to_return.buffer = not opts.buffer and 0 or opts.buffer
575    to_return.lnum = not opts.lnum and 0 or opts.lnum
576    to_return.desc = opts.desc
577
578    return to_return
579  end
580
581  -- Gets a maparg() dict from Nvim, if one exists.
582  local function get_mapargs(mode, lhs)
583    local mapargs = fn.maparg(lhs, normalize_mapmode(mode), mode:sub(-1) == 'a', true)
584    -- drop "lhsraw" and "lhsrawalt" which are hard to check
585    mapargs.lhsraw = nil
586    mapargs.lhsrawalt = nil
587    return mapargs
588  end
589
590  it('error on empty LHS', function()
591    -- escape parentheses in lua string, else comparison fails erroneously
592    eq('Invalid (empty) LHS', pcall_err(api.nvim_set_keymap, '', '', 'rhs', {}))
593    eq('Invalid (empty) LHS', pcall_err(api.nvim_set_keymap, '', '', '', {}))
594    eq('Invalid (empty) LHS', pcall_err(api.nvim_del_keymap, '', ''))
595  end)
596
597  it('del_keymap preserves {rhs} fallback by default #30258', function()
598    api.nvim_set_keymap('n', 'ge', 'q', {})
599    api.nvim_del_keymap('n', 'q')
600    eq({}, get_mapargs('n', 'ge'))
601  end)
602
603  it('del_keymap with opts.lhs matches only {lhs}, never {rhs} #30258', function()
604    api.nvim_set_keymap('n', 'ge', 'q', {})
605    eq('E31: No such mapping', pcall_err(api.nvim_del_keymap, 'n', 'q', { lhs = true }))
606    eq(generate_mapargs('n', 'ge', 'q'), get_mapargs('n', 'ge'))
607
608    api.nvim_del_keymap('n', 'ge', { lhs = true })
609    eq({}, get_mapargs('n', 'ge'))
610  end)
611
612  it('del_keymap for abbreviations with opts.lhs matches only {lhs}, never {rhs} #30258', function()
613    api.nvim_set_keymap('ia', 'foo', 'bar', {})
614    eq('E31: No such mapping', pcall_err(api.nvim_del_keymap, 'ia', 'bar', { lhs = true }))
615    eq(generate_mapargs('ia', 'foo', 'bar'), get_mapargs('ia', 'foo'))
616
617    api.nvim_del_keymap('ia', 'foo', { lhs = true })
618    eq({}, get_mapargs('ia', 'foo'))
619  end)
620
621  it('buf_del_keymap with opts.lhs matches only {lhs}, never {rhs} #30258', function()
622    api.nvim_buf_set_keymap(0, 'n', 'ge', 'q', {})
623    eq('E31: No such mapping', pcall_err(api.nvim_buf_del_keymap, 0, 'n', 'q', { lhs = true }))
624    eq(generate_mapargs('n', 'ge', 'q', { buffer = 1 }), get_mapargs('n', 'ge'))
625
626    api.nvim_buf_del_keymap(0, 'n', 'ge', { lhs = true })
627    eq({}, get_mapargs('n', 'ge'))
628  end)
629
630  it('error if LHS longer than MAXMAPLEN', function()
631    -- assume MAXMAPLEN of 50 chars, as declared in mapping_defs.h
632    local MAXMAPLEN = 50
633    local lhs = ''
634    for i = 1, MAXMAPLEN do
635      lhs = lhs .. (i % 10)
636    end
637
638    -- exactly 50 chars should be fine
639    api.nvim_set_keymap('', lhs, 'rhs', {})
640
641    -- del_keymap should unmap successfully
642    api.nvim_del_keymap('', lhs)
643    eq({}, get_mapargs('', lhs))
644
645    -- 51 chars should produce an error
646    lhs = lhs .. '1'
647    eq(
648      'LHS exceeds maximum map length: ' .. lhs,
649      pcall_err(api.nvim_set_keymap, '', lhs, 'rhs', {})
650    )
651    eq('LHS exceeds maximum map length: ' .. lhs, pcall_err(api.nvim_del_keymap, '', lhs))
652  end)
653
654  it('does not leak callback LuaRef on too-long LHS #39351', function()
655    eq(
656      0,
657      exec_lua(function()
658        local weak = setmetatable({}, { __mode = 'v' })
659        for i = 1, 2 do
660          local cb = function() end
661          weak[i] = cb
662          local ok = pcall(vim.api.nvim_set_keymap, 'n', ('a'):rep(66), '', { callback = cb })
663          assert(not ok)
664        end
665        collectgarbage('collect')
666        return vim.tbl_count(weak)
667      end)
668    )
669  end)
670
671  it('does not throw errors when rhs is longer than MAXMAPLEN', function()
672    local MAXMAPLEN = 50
673    local rhs = ''
674    for i = 1, MAXMAPLEN do
675      rhs = rhs .. (i % 10)
676    end
677    rhs = rhs .. '1'
678    api.nvim_set_keymap('', 'lhs', rhs, {})
679    eq(generate_mapargs('', 'lhs', rhs), get_mapargs('', 'lhs'))
680  end)
681
682  it('error on invalid mode shortname', function()
683    eq('Invalid mode shortname: " "', pcall_err(api.nvim_set_keymap, ' ', 'lhs', 'rhs', {}))
684    eq('Invalid mode shortname: "m"', pcall_err(api.nvim_set_keymap, 'm', 'lhs', 'rhs', {}))
685    eq('Invalid mode shortname: "?"', pcall_err(api.nvim_set_keymap, '?', 'lhs', 'rhs', {}))
686    eq('Invalid mode shortname: "y"', pcall_err(api.nvim_set_keymap, 'y', 'lhs', 'rhs', {}))
687    eq('Invalid mode shortname: "p"', pcall_err(api.nvim_set_keymap, 'p', 'lhs', 'rhs', {}))
688    eq('Invalid mode shortname: "a"', pcall_err(api.nvim_set_keymap, 'a', 'lhs', 'rhs', {}))
689    eq('Invalid mode shortname: "oa"', pcall_err(api.nvim_set_keymap, 'oa', 'lhs', 'rhs', {}))
690    eq('Invalid mode shortname: "!o"', pcall_err(api.nvim_set_keymap, '!o', 'lhs', 'rhs', {}))
691    eq('Invalid mode shortname: "!i"', pcall_err(api.nvim_set_keymap, '!i', 'lhs', 'rhs', {}))
692    eq('Invalid mode shortname: "!!"', pcall_err(api.nvim_set_keymap, '!!', 'lhs', 'rhs', {}))
693    eq('Invalid mode shortname: "map"', pcall_err(api.nvim_set_keymap, 'map', 'lhs', 'rhs', {}))
694    eq('Invalid mode shortname: "vmap"', pcall_err(api.nvim_set_keymap, 'vmap', 'lhs', 'rhs', {}))
695    eq(
696      'Invalid mode shortname: "xnoremap"',
697      pcall_err(api.nvim_set_keymap, 'xnoremap', 'lhs', 'rhs', {})
698    )
699    eq('Invalid mode shortname: " "', pcall_err(api.nvim_del_keymap, ' ', 'lhs'))
700    eq('Invalid mode shortname: "m"', pcall_err(api.nvim_del_keymap, 'm', 'lhs'))
701    eq('Invalid mode shortname: "?"', pcall_err(api.nvim_del_keymap, '?', 'lhs'))
702    eq('Invalid mode shortname: "y"', pcall_err(api.nvim_del_keymap, 'y', 'lhs'))
703    eq('Invalid mode shortname: "p"', pcall_err(api.nvim_del_keymap, 'p', 'lhs'))
704    eq('Invalid mode shortname: "a"', pcall_err(api.nvim_del_keymap, 'a', 'lhs'))
705    eq('Invalid mode shortname: "oa"', pcall_err(api.nvim_del_keymap, 'oa', 'lhs'))
706    eq('Invalid mode shortname: "!o"', pcall_err(api.nvim_del_keymap, '!o', 'lhs'))
707    eq('Invalid mode shortname: "!i"', pcall_err(api.nvim_del_keymap, '!i', 'lhs'))
708    eq('Invalid mode shortname: "!!"', pcall_err(api.nvim_del_keymap, '!!', 'lhs'))
709    eq('Invalid mode shortname: "map"', pcall_err(api.nvim_del_keymap, 'map', 'lhs'))
710    eq('Invalid mode shortname: "vmap"', pcall_err(api.nvim_del_keymap, 'vmap', 'lhs'))
711    eq('Invalid mode shortname: "xnoremap"', pcall_err(api.nvim_del_keymap, 'xnoremap', 'lhs'))
712  end)
713
714  it('validation', function()
715    eq(
716      "Invalid key: 'silentt'",
717      pcall_err(api.nvim_set_keymap, 'n', 'lhs', 'rhs', { silentt = true })
718    )
719    eq("Invalid key: 'sidd'", pcall_err(api.nvim_set_keymap, 'n', 'lhs', 'rhs', { sidd = false }))
720    eq(
721      "Invalid key: 'nowaiT'",
722      pcall_err(api.nvim_set_keymap, 'n', 'lhs', 'rhs', { nowaiT = false })
723    )
724
725    -- <buffer> option key
726    eq(
727      "Invalid key: 'buffer'",
728      pcall_err(api.nvim_set_keymap, 'n', 'lhs', 'rhs', { buffer = true })
729    )
730
731    eq(
732      '"replace_keycodes" requires "expr"',
733      pcall_err(api.nvim_set_keymap, 'n', 'lhs', 'rhs', { replace_keycodes = true })
734    )
735  end)
736
737  local optnames = { 'nowait', 'silent', 'script', 'expr', 'unique' }
738  for _, opt in ipairs(optnames) do
739    -- note: need '%' to escape hyphens, which have special meaning in lua
740    it('throws an error when given non-boolean value for ' .. opt, function()
741      local opts = {}
742      opts[opt] = 'fooo'
743      eq(
744        ("Invalid '%s': expected boolean"):format(opt),
745        pcall_err(api.nvim_set_keymap, 'n', 'lhs', 'rhs', opts)
746      )
747    end)
748  end
749
750  -- Perform tests of basic functionality
751  it('sets ordinary mappings', function()
752    api.nvim_set_keymap('n', 'lhs', 'rhs', {})
753    eq(generate_mapargs('n', 'lhs', 'rhs'), get_mapargs('n', 'lhs'))
754
755    api.nvim_set_keymap('v', 'lhs', 'rhs', {})
756    eq(generate_mapargs('v', 'lhs', 'rhs'), get_mapargs('v', 'lhs'))
757  end)
758
759  it('does not throw when LHS or RHS have leading/trailing whitespace', function()
760    api.nvim_set_keymap('n', '   lhs', 'rhs', {})
761    eq(generate_mapargs('n', '<Space><Space><Space>lhs', 'rhs'), get_mapargs('n', '   lhs'))
762
763    api.nvim_set_keymap('n', 'lhs    ', 'rhs', {})
764    eq(generate_mapargs('n', 'lhs<Space><Space><Space><Space>', 'rhs'), get_mapargs('n', 'lhs    '))
765
766    api.nvim_set_keymap('v', ' lhs  ', '\trhs\t\f', {})
767    eq(generate_mapargs('v', '<Space>lhs<Space><Space>', '\trhs\t\f'), get_mapargs('v', ' lhs  '))
768  end)
769
770  it('can set noremap mappings', function()
771    api.nvim_set_keymap('x', 'lhs', 'rhs', { noremap = true })
772    eq(generate_mapargs('x', 'lhs', 'rhs', { noremap = true }), get_mapargs('x', 'lhs'))
773
774    api.nvim_set_keymap('t', 'lhs', 'rhs', { noremap = true })
775    eq(generate_mapargs('t', 'lhs', 'rhs', { noremap = true }), get_mapargs('t', 'lhs'))
776  end)
777
778  it('can unmap mappings', function()
779    api.nvim_set_keymap('v', 'lhs', 'rhs', {})
780    api.nvim_del_keymap('v', 'lhs')
781    eq({}, get_mapargs('v', 'lhs'))
782
783    api.nvim_set_keymap('t', 'lhs', 'rhs', { noremap = true })
784    api.nvim_del_keymap('t', 'lhs')
785    eq({}, get_mapargs('t', 'lhs'))
786  end)
787
788  -- Test some edge cases
789  it('"!" and empty string are synonyms for mapmode-nvo', function()
790    local nvo_shortnames = { '', '!' }
791    for _, name in ipairs(nvo_shortnames) do
792      api.nvim_set_keymap(name, 'lhs', 'rhs', {})
793      api.nvim_del_keymap(name, 'lhs')
794      eq({}, get_mapargs(name, 'lhs'))
795    end
796  end)
797
798  local special_chars = { '<C-U>', '<S-Left>', '<F12><F2><Tab>', '<Space><Tab>' }
799  for _, lhs in ipairs(special_chars) do
800    for _, rhs in ipairs(special_chars) do
801      local mapmode = '!'
802      it('can set mappings with special characters, lhs: ' .. lhs .. ', rhs: ' .. rhs, function()
803        api.nvim_set_keymap(mapmode, lhs, rhs, {})
804        eq(generate_mapargs(mapmode, lhs, rhs), get_mapargs(mapmode, lhs))
805      end)
806    end
807  end
808
809  it('can set mappings containing C0 control codes', function()
810    api.nvim_set_keymap('n', '\n\r\n', 'rhs', {})
811    local expected = generate_mapargs('n', '<NL><CR><NL>', 'rhs')
812    eq(expected, get_mapargs('n', '<NL><CR><NL>'))
813  end)
814
815  it('can set mappings whose RHS is a <Nop>', function()
816    api.nvim_set_keymap('i', 'lhs', '<Nop>', {})
817    command('normal ilhs')
818    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, 0)) -- imap to <Nop> does nothing
819    eq(generate_mapargs('i', 'lhs', '<Nop>', {}), get_mapargs('i', 'lhs'))
820
821    -- also test for case insensitivity
822    api.nvim_set_keymap('i', 'lhs', '<nOp>', {})
823    command('normal ilhs')
824    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, 0))
825    -- note: RHS in returned mapargs() dict reflects the original RHS
826    -- provided by the user
827    eq(generate_mapargs('i', 'lhs', '<nOp>', {}), get_mapargs('i', 'lhs'))
828
829    api.nvim_set_keymap('i', 'lhs', '<NOP>', {})
830    command('normal ilhs')
831    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, 0))
832    eq(generate_mapargs('i', 'lhs', '<NOP>', {}), get_mapargs('i', 'lhs'))
833
834    -- a single ^V in RHS is also <Nop> (see :h map-empty-rhs)
835    api.nvim_set_keymap('i', 'lhs', '\022', {})
836    command('normal ilhs')
837    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, 0))
838    eq(generate_mapargs('i', 'lhs', '\022', {}), get_mapargs('i', 'lhs'))
839  end)
840
841  it('treats an empty RHS in a mapping like a <Nop>', function()
842    api.nvim_set_keymap('i', 'lhs', '', {})
843    command('normal ilhs')
844    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, 0))
845    eq(generate_mapargs('i', 'lhs', '', {}), get_mapargs('i', 'lhs'))
846  end)
847
848  it('can set and unset <M-">', function()
849    -- Taken from the legacy test: test_mapping.vim. Exposes a bug in which
850    -- replace_termcodes changes the length of the mapping's LHS, but
851    -- do_map continues to use the *old* length of LHS.
852    api.nvim_set_keymap('i', '<M-">', 'foo', {})
853    api.nvim_del_keymap('i', '<M-">')
854    eq({}, get_mapargs('i', '<M-">'))
855  end)
856
857  it(
858    'interprets control sequences in expr-quotes correctly when called ' .. 'inside vim',
859    function()
860      command([[call nvim_set_keymap('i', "\<space>", "\<tab>", {})]])
861      eq(generate_mapargs('i', '<Space>', '\t', { sid = 0 }), get_mapargs('i', '<Space>'))
862      feed('i ')
863      eq({ '\t' }, api.nvim_buf_get_lines(0, 0, -1, 0))
864    end
865  )
866
867  it('throws appropriate error messages when setting <unique> maps', function()
868    api.nvim_set_keymap('l', 'lhs', 'rhs', {})
869    eq(
870      'E227: Mapping already exists for lhs',
871      pcall_err(api.nvim_set_keymap, 'l', 'lhs', 'rhs', { unique = true })
872    )
873    -- different mapmode, no error should be thrown
874    api.nvim_set_keymap('t', 'lhs', 'rhs', { unique = true })
875
876    api.nvim_set_keymap('n', '<tab>', 'rhs', {})
877    eq(
878      'E227: Mapping already exists for <tab>',
879      pcall_err(api.nvim_set_keymap, 'n', '<tab>', 'rhs', { unique = true })
880    )
881
882    api.nvim_set_keymap('ia', 'lhs', 'rhs', {})
883    eq(
884      'E226: Abbreviation already exists for lhs',
885      pcall_err(api.nvim_set_keymap, 'ia', 'lhs', 'rhs', { unique = true })
886    )
887  end)
888
889  it('can set <expr> mappings whose RHS change dynamically', function()
890    exec([[
891        function! FlipFlop() abort
892          if !exists('g:flip') | let g:flip = 0 | endif
893          let g:flip = !g:flip
894          return g:flip
895        endfunction
896        ]])
897    eq(1, api.nvim_call_function('FlipFlop', {}))
898    eq(0, api.nvim_call_function('FlipFlop', {}))
899    eq(1, api.nvim_call_function('FlipFlop', {}))
900    eq(0, api.nvim_call_function('FlipFlop', {}))
901
902    api.nvim_set_keymap('i', 'lhs', 'FlipFlop()', { expr = true })
903    command('normal ilhs')
904    eq({ '1' }, api.nvim_buf_get_lines(0, 0, -1, 0))
905
906    command('normal! ggVGd')
907
908    command('normal ilhs')
909    eq({ '0' }, api.nvim_buf_get_lines(0, 0, -1, 0))
910  end)
911
912  it('can set mappings that do trigger other mappings', function()
913    api.nvim_set_keymap('i', 'mhs', 'rhs', {})
914    api.nvim_set_keymap('i', 'lhs', 'mhs', {})
915
916    command('normal imhs')
917    eq({ 'rhs' }, api.nvim_buf_get_lines(0, 0, -1, 0))
918
919    command('normal! ggVGd')
920
921    command('normal ilhs')
922    eq({ 'rhs' }, api.nvim_buf_get_lines(0, 0, -1, 0))
923  end)
924
925  it("can set noremap mappings that don't trigger other mappings", function()
926    api.nvim_set_keymap('i', 'mhs', 'rhs', {})
927    api.nvim_set_keymap('i', 'lhs', 'mhs', { noremap = true })
928
929    command('normal imhs')
930    eq({ 'rhs' }, api.nvim_buf_get_lines(0, 0, -1, 0))
931
932    command('normal! ggVGd')
933
934    command('normal ilhs') -- shouldn't trigger mhs-to-rhs mapping
935    eq({ 'mhs' }, api.nvim_buf_get_lines(0, 0, -1, 0))
936  end)
937
938  it('can set nowait mappings that fire without waiting', function()
939    api.nvim_set_keymap('i', '123456', 'longer', {})
940    api.nvim_set_keymap('i', '123', 'shorter', { nowait = true })
941
942    -- feed keys one at a time; if all keys arrive atomically, the longer
943    -- mapping will trigger
944    local keys = 'i123456'
945    for c in string.gmatch(keys, '.') do
946      feed(c)
947      sleep(5)
948    end
949    eq({ 'shorter456' }, api.nvim_buf_get_lines(0, 0, -1, 0))
950  end)
951
952  -- Perform exhaustive tests of basic functionality
953  local mapmodes = { 'n', 'v', 'x', 's', 'o', '!', 'i', 'l', 'c', 't', '', 'ia', 'ca', '!a' }
954  for _, mapmode in ipairs(mapmodes) do
955    it('can set/unset normal mappings in mapmode ' .. mapmode, function()
956      api.nvim_set_keymap(mapmode, 'lhs', 'rhs', {})
957      eq(generate_mapargs(mapmode, 'lhs', 'rhs'), get_mapargs(mapmode, 'lhs'))
958
959      -- some mapmodes (like 'o') will prevent other mapmodes (like '!') from
960      -- taking effect, so unmap after each mapping
961      api.nvim_del_keymap(mapmode, 'lhs')
962      eq({}, get_mapargs(mapmode, 'lhs'))
963    end)
964  end
965
966  for _, mapmode in ipairs(mapmodes) do
967    it('can set/unset noremap mappings using mapmode ' .. mapmode, function()
968      api.nvim_set_keymap(mapmode, 'lhs', 'rhs', { noremap = true })
969      eq(generate_mapargs(mapmode, 'lhs', 'rhs', { noremap = true }), get_mapargs(mapmode, 'lhs'))
970
971      api.nvim_del_keymap(mapmode, 'lhs')
972      eq({}, get_mapargs(mapmode, 'lhs'))
973    end)
974  end
975
976  -- Test map-arguments, using optnames from above
977  -- remove some map arguments that are harder to test, or were already tested
978  optnames = { 'nowait', 'silent', 'expr', 'noremap' }
979  for _, mapmode in ipairs(mapmodes) do
980    -- Test with single mappings
981    for _, maparg in ipairs(optnames) do
982      it('can set/unset ' .. mapmode .. '-mappings with maparg: ' .. maparg, function()
983        api.nvim_set_keymap(mapmode, 'lhs', 'rhs', { [maparg] = true })
984        eq(
985          generate_mapargs(mapmode, 'lhs', 'rhs', { [maparg] = true }),
986          get_mapargs(mapmode, 'lhs')
987        )
988        api.nvim_del_keymap(mapmode, 'lhs')
989        eq({}, get_mapargs(mapmode, 'lhs'))
990      end)
991      it(
992        'can set/unset '
993          .. mapmode
994          .. '-mode mappings with maparg '
995          .. maparg
996          .. ', whose value is false',
997        function()
998          api.nvim_set_keymap(mapmode, 'lhs', 'rhs', { [maparg] = false })
999          eq(generate_mapargs(mapmode, 'lhs', 'rhs'), get_mapargs(mapmode, 'lhs'))
1000          api.nvim_del_keymap(mapmode, 'lhs')
1001          eq({}, get_mapargs(mapmode, 'lhs'))
1002        end
1003      )
1004    end
1005
1006    -- Test with triplets of mappings, one of which is false
1007    for i = 1, (#optnames - 2) do
1008      local opt1, opt2, opt3 = optnames[i], optnames[i + 1], optnames[i + 2]
1009      it(
1010        'can set/unset '
1011          .. mapmode
1012          .. '-mode mappings with mapargs '
1013          .. opt1
1014          .. ', '
1015          .. opt2
1016          .. ', '
1017          .. opt3,
1018        function()
1019          local opts = { [opt1] = true, [opt2] = false, [opt3] = true }
1020          api.nvim_set_keymap(mapmode, 'lhs', 'rhs', opts)
1021          eq(generate_mapargs(mapmode, 'lhs', 'rhs', opts), get_mapargs(mapmode, 'lhs'))
1022          api.nvim_del_keymap(mapmode, 'lhs')
1023          eq({}, get_mapargs(mapmode, 'lhs'))
1024        end
1025      )
1026    end
1027  end
1028
1029  it('can make lua mappings', function()
1030    eq(
1031      0,
1032      exec_lua [[
1033      GlobalCount = 0
1034      vim.api.nvim_set_keymap('n', 'asdf', '', {
1035        callback = function() GlobalCount = GlobalCount + 1 end,
1036      })
1037      return GlobalCount
1038    ]]
1039    )
1040
1041    feed('asdf\n')
1042
1043    eq(1, exec_lua [[return GlobalCount]])
1044  end)
1045
1046  it(':map command shows lua mapping correctly', function()
1047    exec_lua [[
1048      vim.api.nvim_set_keymap('n', 'asdf', '', {
1049        callback = function() print('jkl;') end,
1050      })
1051    ]]
1052    matches(
1053      '^\nn  asdf          <Lua %d+>',
1054      exec_lua [[return vim.api.nvim_exec2(':nmap asdf', { output = true }).output]]
1055    )
1056  end)
1057
1058  it('mapcheck() returns lua mapping correctly', function()
1059    exec_lua [[
1060      vim.api.nvim_set_keymap('n', 'asdf', '', {
1061        callback = function() print('jkl;') end,
1062      })
1063    ]]
1064    matches('^<Lua %d+>', fn.mapcheck('asdf', 'n'))
1065  end)
1066
1067  it('maparg() and maplist() return lua mapping correctly', function()
1068    eq(
1069      0,
1070      exec_lua([[
1071      GlobalCount = 0
1072      vim.api.nvim_set_keymap('n', 'asdf', '', {
1073        callback = function() GlobalCount = GlobalCount + 1 end,
1074      })
1075      return GlobalCount
1076    ]])
1077    )
1078
1079    matches('^<Lua %d+>', fn.maparg('asdf', 'n'))
1080
1081    local mapargs = fn.maparg('asdf', 'n', false, true)
1082    mapargs.callback = nil
1083    mapargs.lhsraw = nil
1084    mapargs.lhsrawalt = nil
1085    eq(generate_mapargs('n', 'asdf', nil, { sid = sid_lua }), mapargs)
1086
1087    eq(
1088      1,
1089      exec_lua([[
1090      vim.fn.maparg('asdf', 'n', false, true).callback()
1091      return GlobalCount
1092    ]])
1093    )
1094
1095    exec([[
1096      call maparg('asdf', 'n', v:false, v:true).callback()
1097    ]])
1098    eq(2, exec_lua([[return GlobalCount]]))
1099
1100    api.nvim_eval([[
1101      maplist()->filter({_, m -> m.lhs == 'asdf'})->foreach({_, m -> m.callback()})
1102    ]])
1103    eq(3, exec_lua([[return GlobalCount]]))
1104  end)
1105
1106  it('can make lua expr mappings replacing keycodes', function()
1107    exec_lua [[
1108      vim.api.nvim_set_keymap('n', 'aa', '', {
1109        callback = function() return '<Insert>π<C-V><M-π>foo<lt><Esc>' end,
1110        expr = true,
1111        replace_keycodes = true,
1112      })
1113    ]]
1114
1115    feed('aa')
1116
1117    eq({ 'π<M-π>foo<' }, api.nvim_buf_get_lines(0, 0, -1, false))
1118  end)
1119
1120  it('can make lua expr mappings without replacing keycodes', function()
1121    exec_lua [[
1122      vim.api.nvim_set_keymap('i', 'aa', '', {
1123        callback = function() return '<space>' end,
1124        expr = true,
1125      })
1126    ]]
1127
1128    feed('iaa<esc>')
1129
1130    eq({ '<space>' }, api.nvim_buf_get_lines(0, 0, -1, false))
1131  end)
1132
1133  it('lua expr mapping returning nil is equivalent to returning an empty string', function()
1134    exec_lua [[
1135      vim.api.nvim_set_keymap('i', 'aa', '', {
1136        callback = function() return nil end,
1137        expr = true,
1138      })
1139    ]]
1140
1141    feed('iaa<esc>')
1142
1143    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, false))
1144  end)
1145
1146  it('does not reset pum in lua mapping', function()
1147    eq(
1148      0,
1149      exec_lua [[
1150      VisibleCount = 0
1151      vim.api.nvim_set_keymap('i', '<F2>', '', {
1152        callback = function() VisibleCount = VisibleCount + vim.fn.pumvisible() end,
1153      })
1154      return VisibleCount
1155    ]]
1156    )
1157    feed('i<C-X><C-V><F2><F2><esc>')
1158    eq(2, exec_lua [[return VisibleCount]])
1159  end)
1160
1161  it('redo of lua mappings in op-pending mode work', function()
1162    eq(
1163      0,
1164      exec_lua [[
1165      OpCount = 0
1166      vim.api.nvim_set_keymap('o', '<F2>', '', {
1167        callback = function() OpCount = OpCount + 1 end,
1168      })
1169      return OpCount
1170    ]]
1171    )
1172    feed('d<F2>')
1173    eq(1, exec_lua [[return OpCount]])
1174    feed('.')
1175    eq(2, exec_lua [[return OpCount]])
1176  end)
1177
1178  it('can overwrite lua mappings', function()
1179    eq(
1180      0,
1181      exec_lua [[
1182      GlobalCount = 0
1183      vim.api.nvim_set_keymap('n', 'asdf', '', {
1184        callback = function() GlobalCount = GlobalCount + 1 end,
1185      })
1186      return GlobalCount
1187    ]]
1188    )
1189
1190    feed('asdf\n')
1191
1192    eq(1, exec_lua [[return GlobalCount]])
1193
1194    exec_lua [[
1195      vim.api.nvim_set_keymap('n', 'asdf', '', {
1196        callback = function() GlobalCount = GlobalCount - 1 end,
1197      })
1198    ]]
1199
1200    feed('asdf\n')
1201
1202    eq(0, exec_lua [[return GlobalCount]])
1203  end)
1204
1205  it('can unmap lua mappings', function()
1206    eq(
1207      0,
1208      exec_lua [[
1209      GlobalCount = 0
1210      vim.api.nvim_set_keymap('n', 'asdf', '', {
1211        callback = function() GlobalCount = GlobalCount + 1 end,
1212      })
1213      return GlobalCount
1214    ]]
1215    )
1216
1217    feed('asdf\n')
1218
1219    eq(1, exec_lua [[return GlobalCount]])
1220
1221    exec_lua [[vim.api.nvim_del_keymap('n', 'asdf' )]]
1222
1223    feed('asdf\n')
1224
1225    eq(1, exec_lua [[return GlobalCount]])
1226    eq('\nNo mapping found', n.exec_capture('nmap asdf'))
1227  end)
1228
1229  it('no double-free when unmapping simplifiable lua mappings', function()
1230    eq(
1231      0,
1232      exec_lua [[
1233      GlobalCount = 0
1234      vim.api.nvim_set_keymap('n', '<C-I>', '', {
1235        callback = function() GlobalCount = GlobalCount + 1 end,
1236      })
1237      return GlobalCount
1238    ]]
1239    )
1240
1241    feed('<C-I>\n')
1242
1243    eq(1, exec_lua [[return GlobalCount]])
1244
1245    exec_lua [[vim.api.nvim_del_keymap('n', '<C-I>')]]
1246
1247    feed('<C-I>\n')
1248
1249    eq(1, exec_lua [[return GlobalCount]])
1250    eq('\nNo mapping found', n.exec_capture('nmap <C-I>'))
1251  end)
1252
1253  it('can set descriptions on mappings', function()
1254    api.nvim_set_keymap('n', 'lhs', 'rhs', { desc = 'map description' })
1255    eq(generate_mapargs('n', 'lhs', 'rhs', { desc = 'map description' }), get_mapargs('n', 'lhs'))
1256    eq('\nn  lhs           rhs\n                 map description', n.exec_capture('nmap lhs'))
1257  end)
1258
1259  it('can define !-mode abbreviations with lua callbacks', function()
1260    exec_lua [[
1261      GlobalCount = 0
1262      vim.api.nvim_set_keymap('!a', 'foo', '', {
1263        expr = true,
1264        callback = function()
1265          GlobalCount = GlobalCount + 1
1266          return tostring(GlobalCount)
1267        end,
1268      })
1269    ]]
1270
1271    feed 'iThe foo and the bar and the foo again<esc>'
1272    eq('The 1 and the bar and the 2 again', api.nvim_get_current_line())
1273
1274    feed ':let x = "The foo is the one"<cr>'
1275    eq('The 3 is the one', api.nvim_eval 'x')
1276  end)
1277
1278  it('can define insert mode abbreviations with lua callbacks', function()
1279    exec_lua [[
1280      GlobalCount = 0
1281      vim.api.nvim_set_keymap('ia', 'foo', '', {
1282        expr = true,
1283        callback = function()
1284          GlobalCount = GlobalCount + 1
1285          return tostring(GlobalCount)
1286        end,
1287      })
1288    ]]
1289
1290    feed 'iThe foo and the bar and the foo again<esc>'
1291    eq('The 1 and the bar and the 2 again', api.nvim_get_current_line())
1292
1293    feed ':let x = "The foo is the one"<cr>'
1294    eq('The foo is the one', api.nvim_eval 'x')
1295  end)
1296
1297  it('can define cmdline mode abbreviations with lua callbacks', function()
1298    exec_lua [[
1299      GlobalCount = 0
1300      vim.api.nvim_set_keymap('ca', 'foo', '', {
1301        expr = true,
1302        callback = function()
1303          GlobalCount = GlobalCount + 1
1304          return tostring(GlobalCount)
1305        end,
1306      })
1307    ]]
1308
1309    feed 'iThe foo and the bar and the foo again<esc>'
1310    eq('The foo and the bar and the foo again', api.nvim_get_current_line())
1311
1312    feed ':let x = "The foo is the one"<cr>'
1313    eq('The 1 is the one', api.nvim_eval 'x')
1314  end)
1315end)
1316
1317describe('nvim_buf_set_keymap, nvim_buf_del_keymap', function()
1318  before_each(clear)
1319
1320  -- nvim_set_keymap is implemented as a wrapped call to nvim_buf_set_keymap,
1321  -- so its tests also effectively test nvim_buf_set_keymap
1322
1323  -- here, we mainly test for buffer specificity and other special cases
1324
1325  -- switch to the given buffer, abandoning any changes in the current buffer
1326  local function switch_to_buf(bufnr)
1327    command(bufnr .. 'buffer!')
1328  end
1329
1330  -- `set hidden`, then create two buffers and return their bufnr's
1331  -- If start_from_first is truthy, the first buffer will be open when
1332  -- the function returns; if falsy, the second buffer will be open.
1333  local function make_two_buffers(start_from_first)
1334    command('set hidden')
1335
1336    local first_buf = api.nvim_call_function('bufnr', { '%' })
1337    command('new')
1338    local second_buf = api.nvim_call_function('bufnr', { '%' })
1339    neq(second_buf, first_buf) -- sanity check
1340
1341    if start_from_first then
1342      switch_to_buf(first_buf)
1343    end
1344
1345    return first_buf, second_buf
1346  end
1347
1348  it('rejects negative bufnr values', function()
1349    eq(
1350      'Wrong type for argument 1 when calling nvim_buf_set_keymap, expecting Buffer',
1351      pcall_err(api.nvim_buf_set_keymap, -1, '', 'lhs', 'rhs', {})
1352    )
1353  end)
1354
1355  it('can set mappings active in the current buffer but not others', function()
1356    local first, second = make_two_buffers(true)
1357
1358    api.nvim_buf_set_keymap(0, '', 'lhs', 'irhs<Esc>', {})
1359    command('normal lhs')
1360    eq({ 'rhs' }, api.nvim_buf_get_lines(0, 0, 1, 1))
1361
1362    -- mapping should have no effect in new buffer
1363    switch_to_buf(second)
1364    command('normal lhs')
1365    eq({ '' }, api.nvim_buf_get_lines(0, 0, 1, 1))
1366
1367    -- mapping should remain active in old buffer
1368    switch_to_buf(first)
1369    command('normal ^lhs')
1370    eq({ 'rhsrhs' }, api.nvim_buf_get_lines(0, 0, 1, 1))
1371  end)
1372
1373  it('can set local mappings in buffer other than current', function()
1374    local first = make_two_buffers(false)
1375    api.nvim_buf_set_keymap(first, '', 'lhs', 'irhs<Esc>', {})
1376
1377    -- shouldn't do anything
1378    command('normal lhs')
1379    eq({ '' }, api.nvim_buf_get_lines(0, 0, 1, 1))
1380
1381    -- should take effect
1382    switch_to_buf(first)
1383    command('normal lhs')
1384    eq({ 'rhs' }, api.nvim_buf_get_lines(0, 0, 1, 1))
1385  end)
1386
1387  it('can disable mappings made in another buffer, inside that buffer', function()
1388    local first = make_two_buffers(false)
1389    api.nvim_buf_set_keymap(first, '', 'lhs', 'irhs<Esc>', {})
1390    api.nvim_buf_del_keymap(first, '', 'lhs')
1391    switch_to_buf(first)
1392
1393    -- shouldn't do anything
1394    command('normal lhs')
1395    eq({ '' }, api.nvim_buf_get_lines(0, 0, 1, 1))
1396  end)
1397
1398  it("can't disable mappings given wrong buffer handle", function()
1399    local first, second = make_two_buffers(false)
1400    api.nvim_buf_set_keymap(first, '', 'lhs', 'irhs<Esc>', {})
1401    eq('E31: No such mapping', pcall_err(api.nvim_buf_del_keymap, second, '', 'lhs'))
1402
1403    -- should still work
1404    switch_to_buf(first)
1405    command('normal lhs')
1406    eq({ 'rhs' }, api.nvim_buf_get_lines(0, 0, 1, 1))
1407  end)
1408
1409  it('does not crash when setting mapping in a non-existing buffer #13541', function()
1410    pcall_err(api.nvim_buf_set_keymap, 100, '', 'lsh', 'irhs<Esc>', {})
1411    n.assert_alive()
1412  end)
1413
1414  it('can make lua mappings', function()
1415    eq(
1416      0,
1417      exec_lua [[
1418      GlobalCount = 0
1419      vim.api.nvim_buf_set_keymap(0, 'n', 'asdf', '', {
1420        callback = function() GlobalCount = GlobalCount + 1 end,
1421      })
1422      return GlobalCount
1423    ]]
1424    )
1425
1426    feed('asdf\n')
1427
1428    eq(1, exec_lua [[return GlobalCount]])
1429  end)
1430
1431  it('can make lua expr mappings replacing keycodes', function()
1432    exec_lua [[
1433      vim.api.nvim_buf_set_keymap(0, 'n', 'aa', '', {
1434        callback = function() return '<Insert>π<C-V><M-π>foo<lt><Esc>' end,
1435        expr = true,
1436        replace_keycodes = true,
1437      })
1438    ]]
1439
1440    feed('aa')
1441
1442    eq({ 'π<M-π>foo<' }, api.nvim_buf_get_lines(0, 0, -1, false))
1443  end)
1444
1445  it('can make lua expr mappings without replacing keycodes', function()
1446    exec_lua [[
1447      vim.api.nvim_buf_set_keymap(0, 'i', 'aa', '', {
1448        callback = function() return '<space>' end,
1449        expr = true,
1450      })
1451    ]]
1452
1453    feed('iaa<esc>')
1454
1455    eq({ '<space>' }, api.nvim_buf_get_lines(0, 0, -1, false))
1456  end)
1457
1458  it('can overwrite lua mappings', function()
1459    eq(
1460      0,
1461      exec_lua [[
1462      GlobalCount = 0
1463      vim.api.nvim_buf_set_keymap(0, 'n', 'asdf', '', {
1464        callback = function() GlobalCount = GlobalCount + 1 end,
1465      })
1466      return GlobalCount
1467    ]]
1468    )
1469
1470    feed('asdf\n')
1471
1472    eq(1, exec_lua [[return GlobalCount]])
1473
1474    exec_lua [[
1475      vim.api.nvim_buf_set_keymap(0, 'n', 'asdf', '', {
1476        callback = function() GlobalCount = GlobalCount - 1 end,
1477      })
1478    ]]
1479
1480    feed('asdf\n')
1481
1482    eq(0, exec_lua [[return GlobalCount]])
1483  end)
1484
1485  it('can unmap lua mappings', function()
1486    eq(
1487      0,
1488      exec_lua [[
1489      GlobalCount = 0
1490      vim.api.nvim_buf_set_keymap(0, 'n', 'asdf', '', {
1491        callback = function() GlobalCount = GlobalCount + 1 end,
1492      })
1493      return GlobalCount
1494    ]]
1495    )
1496
1497    feed('asdf\n')
1498
1499    eq(1, exec_lua [[return GlobalCount]])
1500
1501    exec_lua [[vim.api.nvim_buf_del_keymap(0, 'n', 'asdf' )]]
1502
1503    feed('asdf\n')
1504
1505    eq(1, exec_lua [[return GlobalCount]])
1506    eq('\nNo mapping found', n.exec_capture('nmap asdf'))
1507  end)
1508
1509  it('no double-free when unmapping simplifiable lua mappings', function()
1510    eq(
1511      0,
1512      exec_lua [[
1513      GlobalCount = 0
1514      vim.api.nvim_buf_set_keymap(0, 'n', '<C-I>', '', {
1515        callback = function() GlobalCount = GlobalCount + 1 end,
1516      })
1517      return GlobalCount
1518    ]]
1519    )
1520
1521    feed('<C-I>\n')
1522
1523    eq(1, exec_lua [[return GlobalCount]])
1524
1525    exec_lua [[vim.api.nvim_buf_del_keymap(0, 'n', '<C-I>')]]
1526
1527    feed('<C-I>\n')
1528
1529    eq(1, exec_lua [[return GlobalCount]])
1530    eq('\nNo mapping found', n.exec_capture('nmap <C-I>'))
1531  end)
1532
1533  it('does not overwrite in <unique> mappings', function()
1534    api.nvim_buf_set_keymap(0, 'i', 'lhs', 'rhs', {})
1535    eq(
1536      'E227: Mapping already exists for lhs',
1537      pcall_err(api.nvim_buf_set_keymap, 0, 'i', 'lhs', 'rhs', { unique = true })
1538    )
1539
1540    api.nvim_buf_set_keymap(0, 'ia', 'lhs2', 'rhs2', {})
1541    eq(
1542      'E226: Abbreviation already exists for lhs2',
1543      pcall_err(api.nvim_buf_set_keymap, 0, 'ia', 'lhs2', 'rhs2', { unique = true })
1544    )
1545
1546    api.nvim_set_keymap('n', 'lhs', 'rhs', {})
1547    eq(
1548      'E225: Global mapping already exists for lhs',
1549      pcall_err(api.nvim_buf_set_keymap, 0, 'n', 'lhs', 'rhs', { unique = true })
1550    )
1551  end)
1552end)