home ~ projects ~ socials

Write To A Neovim Buffer Through A Timer Loop

NOTE: This is what I started doing for the auto-typer before I leared about nvim_paste from the awesome chat of QuLogic.

So, probably don't do this, unless you really stumble elsewhere and need to pull it out of thin air.

local updates = {
  content = {},
  runner = {},
  debug = 1
}

function string:split(delimiter)
  local result = { }
  local from  = 1
  local delim_from, delim_to = string.find( self, delimiter, from  )
  while delim_from do
    table.insert( result, string.sub( self, from , delim_from-1 ) )
    from  = delim_to + 1
    delim_from, delim_to = string.find( self, delimiter, from  )
  end
  table.insert( result, string.sub( self, from  ) )
  return result
end

updates.load_script = function() 
  local fn = "/Users/alan/workshop/nvim_auto_typer/auto-type-script.txt"
  local f = assert(io.open(fn, "r"))
  local script_data = f:read("*all")
  local lines = script_data:split("\n")
  f:close()

  for _, line in ipairs(lines) do
    if line ~= "" then
      local line_parts = line:split("|")
      if line_parts[1] == "newline" then
        table.insert(updates.content, { action = "newline" })
      elseif line_parts[1] == "pause" then
        table.insert(updates.content, { action = "pause", kind = "edit"})
      elseif line_parts[1] == "tab" then
        table.insert(updates.content, { action = "tab" })
      elseif line_parts[1] == "write" then
        table.insert(updates.content, { action = "write", data = line_parts[2] })
      end
    end
  end
end

updates.deploy = function(d)
  vim.cmd('set paste')
  if d.kind == 'char' then
    vim.cmd('normal A' .. d.data)
  elseif d.kind == 'newline' then
    vim.cmd('normal o')
  end
	vim.cmd('set nopaste')
end

updates.make_runner = function() 
  local runner_ping = 1
  for k, v in ipairs(updates.content) do
    if v.action == 'write' then
      for str in string.gmatch(v.data, "(.)") do
        local tics = 5
        if updates.debug == 1 then
          tics = 0
        end
        updates.runner[runner_ping] = { kind = "char", tics = tics, data = str }
        runner_ping = runner_ping + 1
      end
    elseif v.action == 'newline' then
      local tics = 80
      if updates.debug == 1 then
        tics = 0
      end
      updates.runner[runner_ping] = { kind = "newline"
-- end of line --