1

Is it possible to map a key (e.g.: Alt h) to _ (to go to the first character in the line), but to |, when already there? Perhaps in nvim/lua?

What I have tried is:

vim.keymap.set({'v', 'n'},   '<A-h>', function()
    if vim.o.wrap== true then
        return "g<Home>"
      else
        return "|"
    end
  end, {expr= true, desc= "goto first character on screen line"})

but I could not find out how to deal with the current cursor position.

10
  • What did you try?
    – romainl
    Sep 25, 2023 at 14:24
  • I was hoping that there is a key for that which I missed, because this seems to be pretty natural movement. Sep 25, 2023 at 16:08
  • Relevant, not exactly duplicate: vi.stackexchange.com/q/35057/10604
    – D. Ben Knoble
    Sep 25, 2023 at 19:00
  • Hoping for something is not really "trying". Yes what you ask is possible and you must try to solve your problem first if you want your question to attract attention.
    – romainl
    Sep 25, 2023 at 19:19
  • 1
    Since when does attention depend on « trying to solve the problem »? Effort asking a good question is certainly appreciated, and you could choose not to answer a question @romainl, but demanding that the querent do more than ask the query to garner your attention seems rude. You choose how to spend your time. Askers will put different levels of effort into their problems and question. I recommend suggesting improvements to the question, or not engaging if it’s not a question you would like to answer.
    – D. Ben Knoble
    Oct 8, 2023 at 19:26

2 Answers 2

1

This is what I came up with, finally, with your help:

vim.keymap.set({'n', 'v'},   '<A-h>', function()
    local col = vim.api.nvim_win_get_cursor(0)[2]
    vim.cmd("normal g^")
    if col == vim.api.nvim_win_get_cursor(0)[2] then
      vim.cmd("normal _")
      if col == vim.api.nvim_win_get_cursor(0)[2] then
        vim.cmd("normal |")
      end
    end
  end, {desc= "goto last character on (screen) line"})
0

To get the column index you can do:

local col = vim.api.nvim_win_get_cursor(0)[2]

Or in your mapping:

vim.keymap.set({'v', 'n'},   '<A-h>', function()
    if vim.api.nvim_win_get_cursor(0)[2] ~= 0 then
        return "g<Home>"
      else
        return "|"
    end
  end, {expr= true, desc= "goto first character on screen line"})

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.