You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用vim-surround/nvim-surround删除React片段简写<>?

解决vim-surround/nvim-surround无法识别React空片段<>的问题

不管用的是nvim-surround(Neovim)还是vim-surround(Vim),都可以通过自定义配置让插件识别React的空片段简写<>,以下是具体方案:

针对nvim-surround(Neovim)

在你的Neovim配置文件(比如init.lua)中添加自定义环绕规则,把<>纳入标签识别范围:

require("nvim-surround").setup({
    surrounds = {
        ["<"] = {
            add = function()
                return { { "<>" }, { "" } }
            end,
            find = "<>(.-)</>",
            delete = "^<>(.-)</>$",
            change = {
                target = "^<>(.-)</>$",
                replacement = function()
                    local tag = vim.fn.input("New tag: ")
                    return { { "<" .. tag .. ">" }, { "</" .. tag .. ">" } }
                end,
            },
        },
    },
    aliases = {
        ["t"] = { "<", ">" }, -- 让`t`别名包含自定义的<>规则
    },
})

配置完成后,dst就能直接删除<>包裹的内容,cst会提示输入新标签并完成替换,和普通HTML标签的操作逻辑一致。

针对vim-surround(Vim)

在.vimrc中添加自定义函数和映射,扩展插件对React空片段的支持:

" 检测当前行是否存在React空片段<>
function! SurroundReactEmptyTag()
    let l:line = getline('.')
    let l:start = match(l:line, '<>')
    let l:end = match(l:line, '</>', l:start)
    return l:start != -1 && l:end != -1 ? 1 : 0
endfunction

" 自定义dst映射,优先处理<>片段
nmap dst :call DeleteSurroundReactTag()<CR>
function! DeleteSurroundReactTag()
    let l:cursor_pos = getpos('.')
    if SurroundReactEmptyTag()
        execute 'normal! vf>f<d'
        execute 'normal! f>f<d'
        call setpos('.', l:cursor_pos)
    else
        execute 'normal! dst'
    endif
endfunction

" 自定义cst映射,支持替换<>为其他标签
nmap cst :call ChangeSurroundReactTag()<CR>
function! ChangeSurroundReactTag()
    if SurroundReactEmptyTag()
        let l:new_tag = input('New tag: ')
        execute 'normal! vf>f<ciw' . l:new_tag
        execute 'normal! f>f<ciw' . l:new_tag
    else
        execute 'normal! cst'
    endif
endfunction

这段配置会先检查当前光标所在行是否有React空片段,如果有就执行对应的删除/替换操作,没有则回退到插件默认的dst/cst行为。

注意事项

  • 配置后记得重启Vim/Neovim,或者执行:source %重新加载配置文件。
  • 测试时可以输入<Hello world!</>,光标放在内容上执行dst,应该能删除整个包裹的<>;执行cst输入div,会替换成<div>Hello world!</div>。

内容的提问来源于stack exchange,提问作者Devin Johw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:07:15