Reputation: 1816
I would like to keep my cursor centered at any time.
I manage, thanks to a high valued scrolloff
as mentioned on this Vim Tips page, to keep it centered when there is line around the cursor but I can't make Vim behave that way when my cursor is near the first or last lines. Is it possible to make Vim adds the "tilde" ~
lines to replace "real lines"?
Upvotes: 15
Views: 4218
Reputation: 263
The mappings suggested by kev work for basic navigation in normal mode, but not more complicated movements such as searching. Nor will they do anything for you in insert mode, which is where I personally spend most of my time: at the bottom of the file writing!
A simple if heavy handed solution I have is
:autocmd CursorMoved,CursorMovedI * call CentreCursor()
with the user-defined function
function! CentreCursor()
let pos = getpos(".")
normal! zz
call setpos(".", pos)
endfunction
which saves the current cursor position, centres the view and then restores the cursor position (I originally tried the autocmd
with just * zz
, but this seemed to break appending to the end of a line).
As the name implies, CursorMoved(I) triggers whenever the cursor moves in Normal or Visual (Insert) mode, so this should cover all bases. It is obviously triggered very often, so using it as a hook is possibly not a good idea. I haven't noticed a performance hit yet; your mileage may vary (ideally there would be a LineMoved
event or similar, but there isn't).
The above gives what, coming to vim, I expected :set scrolloff=999
to do. It will not do anything at the top of the file, since there are no ~
lines there. If you were insistent on having the cursor centred, even when opening a new file, a (very) crude workaround would be to insert a few blank lines on BufRead
. You will probably also want to remove then on BufLeave
or similar. I haven't done any vimscript before now but can get your started on this if you want.
Upvotes: 3
Reputation: 161684
You can try this mapping:
:nnoremap j jzz
:nnoremap k kzz
And if you often use G
to jump to end of a file, you probably also want
:nnoremap G Gzz
Upvotes: 19
Reputation: 2941
Exactly what made kev but if (like me) you're a silly full keyboard user, you can add
:nnoremap j jzz
:nnoremap k kzz
:nnoremap <Down> jzz
:nnoremap <Up> kzz
Thanks to @kev
Upvotes: 2
Reputation: 172590
I can only guess about your motivation, but in case you want a single, uncluttered window with editing front and center, I can recommend the vimroom plugin. While it doesn't nail down the cursor in the middle, it uses 'scrolloff'
and empty padding windows on all sides to avoid that the cursor drifts too much to the editor borders.
Upvotes: 0