aboutsummaryrefslogtreecommitdiffstats
path: root/plugin/50-smooth_scroll.lua
blob: 3c2ef053ba8b8539c02e2273e3afbcf17dab685d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
local Dir = {
	UP = 1,
	DOWN = 2,
}

local function smooth_scroll(dir)
	local at_boundary
	if dir == Dir.DOWN then
		at_boundary = function()
			return vim.fn.line("w$") == vim.api.nvim_buf_line_count(0)
		end
	else
		at_boundary = function()
			return vim.fn.line("w0") == 1
		end
	end
	-- bail at boundaries: <C-e>/<C-y> would no-op but j/k would still walk the cursor
	if at_boundary() then
		return
	end
	local win_height = vim.api.nvim_win_get_height(0)
	local duration, sleep_duration = 100, 16 -- 60 fps
	local distance = math.floor(win_height / 2)
	local steps_number = math.ceil(duration / sleep_duration) -- We want a movement every `sleep_duration` msec
	local step = distance / steps_number
	local keys = dir == Dir.DOWN and "\\<C-e>j" or "\\<C-y>k"
	local prev = 0
	for i = 1, steps_number do
		local cur = math.ceil(step * i)
		local delta = cur - prev
		prev = cur
		vim.defer_fn(function()
			for _ = 1, delta do
				if at_boundary() then
					return
				end
				vim.cmd('exec "normal! ' .. keys .. '"')
			end
		end, sleep_duration * i)
	end
end

vim.api.nvim_create_user_command("ScrollSmoothDown", function()
	smooth_scroll(Dir.DOWN)
end, { desc = "Scroll down smoothly" })
vim.api.nvim_create_user_command("ScrollSmoothUp", function()
	smooth_scroll(Dir.UP)
end, { desc = "Scroll up smoothly" })