gVim 启动时窗口自动居中

By | 2015-05-01

最近折腾 vim, 除了配置巨麻烦外, 另一个很蛋疼的就是窗口位置问题了, 折腾了半天无法启动时自动居中, 找遍各地也只有保存上次位置, 下次启动时恢复的方法
废话不多说, 直接上代码, 丢到 vimrc 中即可:

function WindowCenterInScreen()
    set lines=9999 columns=9999
    let g:windowsSizeFixX = 58
    let g:windowsSizeFixY = 118
    let g:windowsScaleX = 7.75
    let g:windowsScaleY = 17.0
    let g:windowsPosOldX = getwinposx()
    let g:windowsPosOldY = getwinposy()
    let g:windowsScreenWidth = float2nr(winwidth(0) * g:windowsScaleX) + g:windowsPosOldX + g:windowsSizeFixX
    let g:windowsScreenHeight = float2nr(winheight(0) * g:windowsScaleY) + g:windowsPosOldY + g:windowsSizeFixY
    set lines=30 columns=108
    let g:windowsSizeWidth = float2nr(winwidth(0) * g:windowsScaleX) + g:windowsSizeFixX
    let g:windowsSizeHeight = float2nr(winheight(0) * g:windowsScaleY) + g:windowsSizeFixY
    let g:windowsPosX = ((g:windowsScreenWidth - g:windowsSizeWidth) / 2)
    let g:windowsPosY = ((g:windowsScreenHeight - g:windowsSizeHeight) / 2)
    exec ':winpos ' . g:windowsPosX . ' ' . g:windowsPosY
endfunc
au GUIEnter * call WindowCenterInScreen()

几个 magic number 的解释:

  • windowsSizeFixX/Y

    系统窗口边框的大小, 像素为单位

  • windowsScaleX/Y

    单个字符的平均宽高, 像素为单位

    可以把窗口最大化, 计算一下总像素和总字符数, 除法一下就好了

在相同 DPI 的屏幕下, 无论什么分辨率都能自动居中

不同 DPI 的屏幕下, 需重新计算那几个 magic number

over

转载请注明来自: http://zsaber.com/blog/p/14

既然都来了, 有啥想法顺便留个言呗? (无奈小广告太多, 需审核, 见谅)

Category: vim

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注