如何修改Neovim弹窗的文本及边框颜色为红色?
问题:Neovim弹窗文本及边框设置为红色(v0.7.2)
我希望通过弹窗输出关键信息,相关Neovim代码如下:
:function! PopupDemo() let message = 'Hello World' for i in range(10) let message = message . ' ' . message endfor let s:win_buf = bufadd('popup-demo') call bufload(s:win_buf) call setbufline(s:win_buf, 1, message) echo 'buf id: ' . s:win_buf let width = 40 let height = 10 " Set the new window as the current window. let enter = v:false " Calculate the centering coordinates. let win_x = &columns / 2 - width / 2 let win_y = &lines / 2 - height / 2 let s:win_id = nvim_open_win(s:win_buf, enter, { \'relative': 'editor', \'row': win_y, \'col': win_x, \'width': width, \'height': height, \'focusable': v:false, \'style': 'minimal', \'border': ['╔', '═','╗', '║', '╝', '═', '╚', '║'], \'noautocmd': v:false, \'bufpos': [0, 0] \}) call nvim_win_set_option(s:win_id, 'wrap', v:true) echo 'win id: ' . s:win_id call timer_start(5000, 'PopupClose') :endfunction :function! PopupClose(timer) if s:win_id != 0 call nvim_win_close(s:win_id, v:false) endif if s:win_buf != 0 call nvim_buf_delete(s:win_buf, {'force': v:true}) endif :endfunction
当前效果如图所示,我需要将弹窗中的普通文本及边框设置为红色,使用的Neovim版本为v0.7.2,请问该如何实现?
解决方案
要实现弹窗文本和边框的红色效果,需通过自定义高亮组分别控制两者颜色,以下是修改后的完整代码:
:function! PopupDemo() " 1. 定义自定义红色高亮组:设置前景色为红色 call nvim_set_hl(0, 'RedPopup', {'fg': '#ff0000'}) let message = 'Hello World' for i in range(10) let message = message . ' ' . message endfor let s:win_buf = bufadd('popup-demo') call bufload(s:win_buf) call setbufline(s:win_buf, 1, message) echo 'buf id: ' . s:win_buf " 2. 给缓冲区文本添加红色高亮(覆盖第1行全部内容) call nvim_buf_add_highlight(s:win_buf, -1, 'RedPopup', 0, 0, -1) let width = 40 let height = 10 let enter = v:false let win_x = &columns / 2 - width / 2 let win_y = &lines / 2 - height / 2 let s:win_id = nvim_open_win(s:win_buf, enter, { \'relative': 'editor', \'row': win_y, \'col': win_x, \'width': width, \'height': height, \'focusable': v:false, \'style': 'minimal', \'border': ['╔', '═','╗', '║', '╝', '═', '╚', '║'], \'border_hl': 'RedPopup', " 3. 指定边框使用自定义红色高亮组 \'noautocmd': v:false, \'bufpos': [0, 0] \}) call nvim_win_set_option(s:win_id, 'wrap', v:true) echo 'win id: ' . s:win_id call timer_start(5000, 'PopupClose') :endfunction :function! PopupClose(timer) if s:win_id != 0 call nvim_win_close(s:win_id, v:false) endif if s:win_buf != 0 call nvim_buf_delete(s:win_buf, {'force': v:true}) endif " 可选:删除自定义高亮组(如果不需要复用) " call nvim_set_hl(0, 'RedPopup', {}) :endfunction
关键修改说明:
- 步骤1:用
nvim_set_hl创建RedPopup高亮组,fg参数设为红色(支持十六进制值#ff0000或内置颜色名red),第一个参数0表示全局命名空间。 - 步骤2:通过
nvim_buf_add_highlight给缓冲区第1行(索引从0开始)添加高亮,0, -1表示覆盖该行全部字符。 - 步骤3:在
nvim_open_win选项中添加border_hl字段,关联自定义高亮组,让边框应用红色。
补充说明:
- 若需局部文本变色,可多次调用
nvim_buf_add_highlight指定不同的起始/结束列。 - 颜色值支持多种格式:内置颜色名、十六进制值、RGB值(如
rgb(255,0,0))。
内容的提问来源于stack exchange,提问作者aszswaz
相关产品推荐
相关产品推荐

