0

I want to read texts with Neovim scrolling them down automatically. The following code provides such functionality:

local M = {}

function M.down()
    local timer = vim.loop.new_timer()
    local stop = false
    local sleep = 5000
    timer:start(1000, sleep, vim.schedule_wrap(function()
      local scroll_down = vim.api.nvim_replace_termcodes('normal <C-E>', true, true, true)
      vim.cmd(scroll_down)

      if stop then
        timer:close()
      end
    end))
end

return M

How can I interact with vim.loop by changing stop and sleep variables, so the scrolling can be made faster/slower, or stopped?

2
  • 1
    AFAIK, you can't modify the attributes of a timer while it's running. You'd have to kill the existing timer and start a new one with a new time. As for stop you could use a global variable instead of a local and change that from anywhere, I guess.
    – B Layer
    Commented Aug 9, 2021 at 8:17
  • Yes @B Layer, I thought about global variables, but would love to avoid them.
    – dimus
    Commented Aug 9, 2021 at 8:22

1 Answer 1

3

Incorporating @B Layer's feedback I came up with the following code, that is able to stop scrolling, make it slower/faster without creating global variables.

local M = {sleep = 1000, timer = nil}

function M.down()
    print(M.sleep)
    M.timer = vim.loop.new_timer()
    M.timer:start(1000, M.sleep, vim.schedule_wrap(function()
      local down = vim.api.nvim_replace_termcodes('normal <C-E>', true, true, true)
      vim.cmd(down)
    end))
end

function M.down_stop()
  if M.timer ~= nil then
    M.timer:close()
    M.timer = nil
  end
end

function M.down_slower()
  M.down_change(2)
end

function M.down_faster()
  M.down_change(0.5)
end

function M.down_change(n)
  M.down_stop()
  M.sleep = M.sleep*n
  M.down()
end

return M
1
  • Cool. Glad my comment was of some value. :)
    – B Layer
    Commented Aug 9, 2021 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.