You need to enable JavaScript to run this app. Vim设置nowrap时如何用0、$实现类wrap下g0、g$跳转
优惠活动
大模型
产品
解决方案
定价
更多

Vim设置nowrap时如何用0、$实现类wrap下g0、g$跳转

配置实现方法

将以下内容添加到你的Vim配置文件(~/.vimrc 或 Neovim 配置文件 ~/.config/nvim/init.vim)中即可实现需求:

" 兼容wrap/nowrap模式,统一实现可视行首尾跳转
function! s:vis_line_start()
  if &wrap
    normal! g0
  else
    let l:left_offset = winsaveview().leftcol
    execute "normal! " . l:left_offset . "|"
  endif
endfunction

function! s:vis_line_end()
  if &wrap
    normal! g$
  else
    let l:left_offset = winsaveview().leftcol
    let l:visible_end = l:left_offset + winwidth(0) - 1
    execute "normal! " . l:visible_end . "|"
  endif
endfunction

" 绑定0和$到自定义跳转功能
nnoremap 0 :call <SID>vis_line_start()<CR>
nnoremap $ :call <SID>vis_line_end()<CR>

效果说明

  • 开启wrap时,0/$完全复用内置g0/g$的行为,跳转至折行后可视行的首尾
  • 开启nowrap时,长行横向超出屏幕的情况下,0/$仅会跳转至当前窗口可见区域的首尾,不会直接滚动到整个逻辑行的开头或末尾,和wrap模式下g0/g$的跳转逻辑完全等效

如果仅需要在nowrap开启时生效、wrap模式下保持默认映射,可以使用更简洁的自动命令配置:

" nowrap开启时自动绑定自定义跳转
autocmd OptionSet nowrap nnoremap 0 :execute "normal! " . winsaveview().leftcol . "|" <CR>
autocmd OptionSet nowrap nnoremap $ :execute "normal! " . (winsaveview().leftcol + winwidth(0) - 1) . "|" <CR>
" nowrap关闭时自动恢复默认映射
autocmd OptionSet nowrap! unmap 0
autocmd OptionSet nowrap! unmap $

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 03:54:00