neovim

Personal neovim configuration files
git clone git://gtms.dev/neovim
Log | Files | Refs

manual_pairs.lua (1927B)


      1 -- © 2024 Adam Blažek <adam@whizzmot.dev>
      2 -- SPDX-License-Identifier: GPL-3.0-or-later
      3 
      4 -- Constants
      5 local modes = { "c", "i" }
      6 local key_left = { c = "<left>", i = "<c-g>U<left>" }
      7 local key_right = { c = "<right>", i = "<c-g>U<right>" }
      8 
      9 -- Escapes a string for vim.keymap.set().
     10 local function escape_keycodes(str)
     11   return str:gsub("<", "<lt>")
     12 end
     13 
     14 -- Escapes a string for vim.fn.search().
     15 local function escape_search(str)
     16   return [[\V\C]] .. str:gsub([[\]], [[\\]])
     17 end
     18 
     19 -- Creates a mapping for inserting a pair of delimiters.
     20 local function map_pair(key, left, right)
     21   local right_len = vim.fn.strcharlen(right)
     22   for _, mode in ipairs(modes) do
     23     local mapping = escape_keycodes(left .. right) .. key_left[mode]:rep(right_len)
     24     vim.keymap.set(mode, key, mapping, {
     25       desc = "[manual-pairs] Pair: " .. left .. "•" .. right,
     26     })
     27   end
     28 end
     29 
     30 -- Creates a mapping for skipping past the nearest delimiter.
     31 local function map_fly(key, right)
     32   vim.keymap.set("i", key, function()
     33     if vim.fn.search(right, "ceWz", 1000) ~= 0 then
     34       vim.api.nvim_input(key_right["i"])
     35     end
     36   end, {
     37     desc = "[manual-pairs] Fly: " .. right,
     38   })
     39 end
     40 
     41 -- Creates a mapping for creating an empty line at the current cursor position.
     42 local function map_cr(key)
     43   vim.keymap.set("i", key, "<cr><c-o>O", {
     44     desc = "[manual-pairs] CR",
     45   })
     46 end
     47 
     48 -- Creates a mapping for moving the cursor to the right.
     49 local function map_right(key)
     50   for _, mode in ipairs(modes) do
     51     vim.keymap.set(mode, key, key_right[mode], {
     52       desc = "[manual-pairs] Right",
     53     })
     54   end
     55 end
     56 
     57 -- Creates a mappping for deleting one character to the left and right of the cursor.
     58 local function map_backspace(key)
     59   vim.keymap.set(modes, key, "<bs><del>", {
     60     desc = "[manual-pairs] Backspace",
     61   })
     62 end
     63 
     64 return {
     65   map_pair = map_pair,
     66   map_fly = map_fly,
     67   map_cr = map_cr,
     68   map_right = map_right,
     69   map_backspace = map_backspace,
     70 }