Home > Software design >  Correctly escaping arguments of substitute for key mapping in nvim lua
Correctly escaping arguments of substitute for key mapping in nvim lua

Time:03-25

I created a keymapping in nvim to swap the left and right side of an C equality comparison insice parentheses. It works like a charm from the nvim command prompt.

:nnoremap <F3> ci(:let @r=substitute(@*, '\(.*\) == \(.*\)', '\2 == \1', '')<CR><C-r>r<ESC>

Now I wanted to put it into my lua configuration

vim.api.nvim_set_keymap("n", "<F3>", "ci(:let @r=substitute(@*, '\(.*\) == \(.*\)', '\2 == \1', '')<CR><C-r>r<ESC>", { noremap = true, silent = true })

and get an error

invalid escape sequence near '"ci(:let @r=substitute(@*, '

I tried several things but it was pure guessing. So what is the correct lua configuration code?

and as sidenote: how could I debug the error message to solve it myself?

CodePudding user response:

You may not escape parentheses in Lua:

$ lua
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> "\("
stdin:1: invalid escape sequence near '"\('

Remove the backslashes (or if you want backslashes there, escape them) to fix this syntax error.

Without backslashes: "ci(:let @r=substitute(@*, '(.*) == (.*)', '2 == 1', '')<CR><C-r>r<ESC>" doesn't trigger a syntax error anymore.

  • Related