Lua: function to perform visual line selection

Hey there I want to perform a visual line select programmatically and here’s the function I came up with…

function visual_select(from, to)
	local diff = from - to
	local motion = "k"

	if diff == 0 then
		vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<esc><s-v>", true, false, true), 'n', true)
		return
	end

	if diff < 0 then
		vim.cmd(tostring(from))
		motion = "j"
	end

	local seq = "<s-v>"..math.abs(diff)..motion

	vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<esc>"..seq, true, false, true), 'n', true)
end

It selects the line starting from line number from to line number to.

Is there any other better way to perform the same task? I feel like nvim should have a function like vim.fn.visual_select_range(from, to) or something.

1 Like