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

如何在(Neo)Vim中获取光标所在字符的高亮组名称?

获取matchadd设置的光标位置高亮组名称

可以通过遍历所有已添加的match项,结合光标位置判断对应的高亮组,下面是实现的Vim脚本函数:

function! GetMatchHighlightGroup()
    let cursor_pos = getcurpos()
    let line_num = cursor_pos[1]
    let col_num = cursor_pos[2]
    let current_line = getline(line_num)
    
    for match_item in getmatches()
        let pattern = match_item.pattern
        let highlight_group = match_item.group
        
        " 获取当前行中该模式的匹配位置
        let match_start = matchend(current_line, pattern, 0, 1) - len(matchstr(current_line, pattern)) + 1
        let match_end = matchend(current_line, pattern, 0, 1)
        
        " 检查光标是否在匹配区间内
        if col_num >= match_start && col_num <= match_end
            return highlight_group
        endif
    endfor
    
    return "无匹配高亮组"
endfunction

使用方法

在Vim/Neovim中执行以下命令,即可输出光标所在字符对应的高亮组名称:

:echo GetMatchHighlightGroup()

原理说明

  1. 通过getcurpos()获取当前光标位置的行号和列号
  2. 用getmatches()获取所有通过matchadd添加的匹配规则
  3. 对每个规则,计算其在当前行的匹配起止位置,判断光标是否落在该区间内
  4. 找到匹配项后返回对应的高亮组名,遍历完无匹配则返回提示文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:55:56