Skip to content

Commit

Permalink
feat: Support control characters in surrounds. (#179) (#211)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: User defined `invalid_key_behavior` handlers will be
activated for control characters that don't have defined `surrounds`.

Supports Vim's notation of special characters in `surrounds`. One can simply write:

```lua
surrounds = {
    ["<BS>"] = { ... }
},
```
  • Loading branch information
idanarye authored Feb 21, 2023
1 parent 9739e85 commit ebdd22d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
11 changes: 11 additions & 0 deletions lua/nvim-surround/config.lua
Original file line number Diff line number Diff line change
Expand Up @@ -227,14 +227,23 @@ M.default_opts = {
},
invalid_key_behavior = {
add = function(char)
if char:find("%c") then
return
end
return { { char }, { char } }
end,
find = function(char)
if char:find("%c") then
return
end
return M.get_selection({
pattern = vim.pesc(char) .. ".-" .. vim.pesc(char),
})
end,
delete = function(char)
if char:find("%c") then
return
end
return M.get_selections({
char = char,
pattern = "^(.)().-(.)()$",
Expand Down Expand Up @@ -583,6 +592,8 @@ M.translate_opts = function(user_opts)
"nvim-surround"
)
end
-- Support Vim's notation for special characters
char = vim.api.nvim_replace_termcodes(char, true, true, true)
-- Check if the delimiter has not been disabled
if not user_surround then
opts.surrounds[char] = false
Expand Down
7 changes: 3 additions & 4 deletions lua/nvim-surround/input.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ local M = {}
---@return string? @The input character, or nil if a control character is pressed.
---@nodiscard
M.get_char = function()
local ret_val, char_num = pcall(vim.fn.getchar)
-- Return nil if error (e.g. <C-c>) or for control characters
if not ret_val or type(char_num) ~= "number" or char_num < 32 then
local ret_val, char = pcall(vim.fn.getcharstr)
-- Return nil if error (e.g. <C-c>) or for <Esc>/<C-[> (ascii code 27)
if not ret_val or char == "\27" then
return nil
end
local char = vim.fn.nr2char(char_num)
return char
end

Expand Down

0 comments on commit ebdd22d

Please sign in to comment.