0

I would like to map > (and <) in normal mode to a function such that it indents the line and keeps the cursor at the original position after performing the indent

Here my code in the file mymodule.lua:

local M = {}

function M.reset_cursor_pos(fct, offset, ...)
  offset = offset or 2
  -- e.g. lua require("user.utils").reset_cursor_pos(function() print('x') end)
  local _, cursor_line, cursor_col, _, _ = unpack(vim.fn.getcurpos())
  fct()
  vim.fn.setpos('.', {0, cursor_line, cursor_col + offset, 0}) -- 15G25|
end

return M

and the keymap in lua

vim.api.nvim_set_keymap("n", ">", "<cmd>lua require('mymodule').reset_cursor_pos(function() vim.cmd[[normal >>]] end, vim.o.shiftwidth)", {})

or in vim

nmap > :lua require('mymodule').reset_cursor_pos(function() vim.cmd[[normal >>]] end, vim.o.shiftwidth)

The function execution works as intended but not the keypmap. Does anyone know how I could make the key-mapping work?

4
  • Annex: I am using Neovim 0.8 on Linux Mint 21 Vanessa
    – kraxli
    Commented Jan 16, 2023 at 6:38
  • If you've ended up with two accounts, we can merge them for you.
    – D. Ben Knoble
    Commented Jan 17, 2023 at 14:22
  • Welcome vi.SE @kraxli I think you're looking for <Left> and <Right> as keys name.
    – gildux
    Commented Jan 19, 2023 at 17:09
  • 1
    wow, so much junk for a trivial 3 line function in VimScript :( Commented Jan 19, 2023 at 19:15

1 Answer 1

0

In my understanding, < and > are special keys, and are anyway used for Vim special keys notation… There are 3 ways to mention such keys: Use

  • the ^v trick to insert the terminal code (cons: it may work differently on some other terminal. pros: it's a standard and easy practice.) → n/a
  • the ^k and hit the key instead of a defined digraph combination (cons: I never managed to do it. pros: there's alternative numbering that should work) → n/a
  • the termcap entry xx in the form <t_xx> (pros: it's like the first but in a portable way. cons: depends on the absence of one cpoptions flag.) → n/a
  • the Vim key notation (pros: it's the easiest and portable way known by all vimers. cons: depends on the absence of one cpoptions flag.) → <lt> (and >)

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.