Toggle cursor position "keyma"

I want to make the zero mapped to toggle between tree positions = { “0”, “^”, “$” }

the first if tests if we are recording a macro, in this case i want norma behavior

I have this function:

-- --@ rturns trur or false
-- function is_recording()
--   return vim.fn.reg_recording() ~= nil
-- end

vim.keymap.set('n', '0',
  function()
    if vim.fn.reg_recording() ~= nil then
      return '0'
    end
    local pos = vim.api.nvim_win_get_cursor(0)[2] + 1
    if pos == vim.api.nvim_win_get_cursor(0)[2] + 1 then
      return '0'
    elseif pos == 1 then
      return '$'
    else
      return '^'
    end
  end, { desc = "toggle between start of the line or first non-blank or cursor column", }
)

What can be wrong with that?

I’m not sure what is the exact expected behavior, could you explain it, please.

However, I can see that:

See :h reg_recording(),

Returns an empty string when not recording

So the first check, where you compare it to nil is wrong, you should compare it to empty string

In the second if statement you compare the pos with the same expression, so it will always be true.

1 Like

After the interaction i fixed the code:

function ToggleColumn()
  if vim.fn.reg_recording() ~= "" then
    vim.api.nvim_feedkeys('0', 'n', true)
  else
    local pos = vim.fn.col('.')
    if pos == 1 then
      vim.api.nvim_feedkeys('^', 'n', true)
    elseif pos == vim.fn.col('$') - 1 then
      vim.api.nvim_feedkeys('0', 'n', true)
    else
      vim.api.nvim_feedkeys('$', 'n', true)
    end
  end
end

vim.api.nvim_set_keymap('n', '0', ':lua ToggleColumn()<CR>', { silent = true })