1

my question is simillar to this: How do I surround a quoted string without including leading whitespace?

But not exactly. I am using vim-surround.

I have a string

print he^llo_and_welcome 

where ^ signify my cursor position

I want it to become

print "he^llo_and_welcome"

but ysaW" includes leading whitespace and trying ys2i"" doesn't seem to work.

What should I do?

2 Answers 2

3

Change your command to use inner Word: ysiW"

You might want to read the following help topic to understand better the difference between iW and aW: :h aW :h iW

0

In NVIM you can use this function and map <leader>sw or <leader>sW to use :lua Surround("w") and :lua Surround("W") respectively.

After pressing <leader>sw or <leader>sW in insert mode you will be asked for the character you want to surround with.

If you want to surround with characters whose closing character is different from the opening character, just type the opening one

Note that this is easily reproduced in VIM.

function Surround(w_or_W)
    local open_char = vim.fn.input("Surround with: ")
    local closed_char = nil
    if open_char == "(" then closed_char = ")" end
    if open_char == "[" then closed_char = "]" end
    if open_char == "{" then closed_char = "}" end
    if open_char == "<" then closed_char = ">" end
    if open_char == "'" then closed_char = "'" end
    if open_char == '"' then closed_char = '"' end
    if open_char == "`" then closed_char = "`" end
    if open_char == "/" then closed_char = "/" end
    if open_char == "|" then closed_char = "|" end

    if w_or_W == "w" then
        vim.cmd("normal! ciw" .. open_char)
    elseif w_or_W == "W" then
        vim.cmd([[normal! ciW]] .. open_char)
    end
    vim.cmd("normal! p")
    vim.cmd("normal! a" .. closed_char)
    vim.cmd("normal! a")
end

vim.api.nvim_set_keymap("n", "<leader>sw", ":lua Surround('w')<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>sW", ":lua Surround('W')<CR>", { noremap = true, silent = true })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.