summaryrefslogtreecommitdiffstats
path: root/plugin/50-smooth_scroll.lua
blob: 4915238e32da78468f86ca99b6165e3cc9981d0c (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
--
-- 50-smooth_scroll.lua
--
-- * Animates a half-page scroll by stepping <C-e>/<C-y> (plus j/k) over a short timer.
--
-- User commands:
--   `ScrollSmoothDown`: scroll down smoothly
--   `ScrollSmoothUp`: scroll up smoothly
--

local Dir = {
	UP = 1,
	DOWN = 2,
}

local function smooth_scroll(dir)
	local scroll_at_boundary, cursor_at_boundary
	if dir == Dir.DOWN then
		scroll_at_boundary = function()
			return vim.fn.line("w$") == vim.api.nvim_buf_line_count(0)
		end
		cursor_at_boundary = function()
			return vim.fn.line(".") == vim.api.nvim_buf_line_count(0)
		end
	else
		scroll_at_boundary = function()
			return vim.fn.line("w0") == 1
		end
		cursor_at_boundary = function()
			return vim.fn.line(".") == 1
		end
	end
	-- bail only when the cursor itself can't move further; at the viewport boundary <C-e>/<C-y>
	-- no-op but we still want j/k to walk the cursor
	if cursor_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)
	-- We want a movement every `sleep_duration` msec
	local steps_number = math.ceil(duration / sleep_duration)
	local step = distance / steps_number
	local scroll_keys = dir == Dir.DOWN and "\\<C-e>j" or "\\<C-y>k"
	local cursor_keys = dir == Dir.DOWN and "j" or "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 cursor_at_boundary() then
					return
				end
				-- past the viewport boundary <C-e>/<C-y> no-op; just walk the cursor
				local keys = scroll_at_boundary() and cursor_keys or scroll_keys
				vim.cmd('exec "normal! ' .. keys .. '"')
			end
		end, sleep_duration * i)
	end
end

local function smooth_scroll_up()
	smooth_scroll(Dir.UP)
end

local function smooth_scroll_down()
	smooth_scroll(Dir.DOWN)
end

----------------------------------------------------------------------------------------------------

vim.api.nvim_create_user_command(
	"ScrollSmoothDown",
	smooth_scroll_down,
	{ desc = "Scroll down smoothly" }
)
vim.api.nvim_create_user_command(
	"ScrollSmoothUp",
	smooth_scroll_up,
	{ desc = "Scroll up smoothly" }
)