0

I want to get the range of ex-mode command in Lua(eg 1 and 3 in 1;3d). The range value should be stored as a:firstline and a:lastline in vim, but based on the doc, a is not implemented in the vim table. How can I get them in Lua?

Update

This is the command I am trying to define:

        vim.api.nvim_exec(
            "command! -range " .. opts.ex_mode_cmd .. " <line1>,<line2>lua require('commented').toggle_comment('c')", true)

From this I expect I can get the value of a:firstline and a:lastline inside toggle_comment, but they all returned nil

local function toggle_comment()
  print('check range', vim.firstline, vim.lastline)
end
6
  • 2
    Can you please explain, from what you'd like to get the range? a:firstline and a:lastline are only ever valid from functions, that are define with the range attribute, but is not always readily available. So this only exists for custom vimscript functions. But I suppose that is not what you want here, it cannot be used to get arbitrarily ranges from ex commands like :g or :m Jun 7, 2021 at 13:49
  • 1
    Are you defining a user-command? If so, see :help :command-range and then you can use <line1> and <line2> in the command definition to pass the range to whatever Lua code you call from there...
    – filbranden
    Jun 7, 2021 at 15:24
  • 1
    @filbranden Yes I am trying to define a user-command, and I guess it would work by passing <line1> and <line2> to the function. But since my function is not accepting start and end range as parameter originally, I want to avoid this unless I cannot find any other solution. Jun 7, 2021 at 16:06
  • 1
    @ChristianBrabandt Sorry for missing that part. I have added the code I am writing back in. Jun 7, 2021 at 16:08
  • 1
    It looks like the code you mentioned will work in Vim, at least the documentation mentions vim.firstline and vim.lastline. In NeoVim, the :lua command takes a range, but no idea where it actually stashes it...
    – filbranden
    Jun 7, 2021 at 17:13

1 Answer 1

1

This is works for me:

command -range Test lua require('test').test_range(<line1>, <line2>)
function test_range(start, end)
  print(start, end)
end

Your Answer

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

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