function! Scroll()
" what count was given with j? defaults to 1 (e.g. 10j to move 10 lines
" down, j the same as 1j)
let l:count = v:count1
" how far from the end of the file is the current cursor position?
let l:distance = line("$") - line(".")
" if the number of times j should be pressed is greater than the number of
" lines until the bottom of the file
if l:count > l:distance
" if the cursor isn't on the last line already
if l:distance > 0
" press j to get to the bottom of the file
execute "normal! " . l:distance . "j"
endif
" then press Ctrl+E for the rest of the count
execute "normal! " . (l:count - l:distance) . "\<C-e>"
" if the count is smaller and the cursor isn't on the last line
elseif l:distance > 0
" press j the requested number of times
execute "normal! " . l:count . "j"
else
" otherwise press Ctrl+E the requested number of times
execute "normal! " . l:count . "\<C-e>"
endif
endfunction
nnoremap j <Cmd>call Scroll()<CR>
nnoremap <Down> <Cmd>call Scroll()<CR>
local line = vim.fn.line
local nvim_input = vim.api.nvim_input
local function scroll()
-- what count was given with j? defaults to 1 (e.g. 10j to move 10 lines
-- down, j the same as 1j)
local count1 = vim.v.count1
-- how far from the end of the file is the current cursor position?
local distance = line("$") - line(".")
-- if the number of times j should be pressed is greater than the number of
-- lines until the bottom of the file
if count1 > distance then
-- if the cursor isn't on the last line already
if distance > 0 then
-- press j to get to the bottom of the file
nvim_input(distance.."<Down>")
end
-- then press Ctrl+E for the rest of the count
nvim_input((count1 - distance).."<C-e>")
-- if the count is smaller and the cursor isn't on the last line
elseif distance > 0 then
-- press j as much as requested
nvim_input(count1.."<Down>")
else
-- otherwise press Ctrl+E the requested number of times
nvim_input(count1.."<C-e>")
end
end
vim.keymap.set("n", "j", scroll, {
desc = "continue scrolling past end of file with j",
})
vim.keymap.set("n", "<Down>", scroll, {
desc = "continue scrolling past end of file with ↓",
})
4条答案
按热度按时间bfrts1fy1#
除了@肯特的回答,
zz
还允许您将当前行移到屏幕中间,在我看来,这更便于查看当前行文本/代码的上下文。此外,
zb
会将当前行置于屏幕底部,这有时也会有所帮助。ddhy6vgd2#
是否有办法滚动到文档末尾的下方,以便文档中的最后几行可以显示在屏幕的顶部?
如果我没理解错你的要求,
zt
(或z<cr>
)可以在你的光标位于最后一行时完成这一操作(事实上,:h zt
可以在任何一行上工作,详细信息请参阅)例如:
46qrfjad3#
在正常模式下,您可以使用
CTRL-E
向下滚动,使用CTRL-Y
向上滚动,而不移动光标的位置(除非光标被推离屏幕)。如果你在文档的结尾,按CTRL-E
会滚动到最后一行,直到最后一行出现在屏幕顶部。我倾向于喜欢这种方法比zt
或zz
更好,因为我可以看到它滚动,而不是有屏幕只是跳到前面。有一些警告。例如,
CTRL-Y
在使用Windows键绑定时被Map为重做。请查看:help scrolling
以了解更多信息。zxlwwiss4#
除了
set scrolloff=10
,其他一些答案提到了Ctrl+E。如果光标不在文件的最后一行,我希望默认的移动键j可以正常滚动光标,然后当光标在最后一行时,j应该滚动文件(在本例中使用Ctrl+E)。
将以下内容放在
.vimrc
文件中可实现此行为。最后一行也为向下箭头键↓启用了相同的行为。
对于Neovim,在
init.lua
中放入以下内容也可以实现相同的效果: