neovim / neovim-ruby

Ruby support for Neovim
MIT License
340 stars 17 forks source link

Get visual selected text #66

Closed AlexVKO closed 4 years ago

AlexVKO commented 4 years ago

Hi,

I'm building a plugin that works in visual mode,

Is there a way to easily get the selected text with ruby? (Inside the plugin block)

Thank you for the great work.

alexgenco commented 4 years ago

If you pass range: true in the plugin hook it will yield the line numbers selected (1-indexed): https://github.com/neovim/neovim-ruby/blob/898f88db603410da7e461e0833238547f5f18eea/spec/acceptance/runtime/rplugin/ruby/functions.rb#L6-L8

If you want to convert these to the line contents, you can use nvim.current.buffer.lines[start-1..stop-1]. Note you have to convert to 0-indexed.

AlexVKO commented 4 years ago

Cool, that helps, but what about

Screen Shot 2020-05-24 at 7 30 42 PM

alexgenco commented 4 years ago

That's not quite as straightforward! Here's something I came up with that puts the selection into a yank buffer and evaluates it back out:

Neovim.plugin do |p|
  p.command(:GetSelected, range: true) do |nvim|
    # Recover visual selection (`gv`), and yank it to the `a` register (`"ay`)
    nvim.command("normal! gv\"ay")

    # Evaluate contents of `a` register
    selection = nvim.evaluate("@a")

    # ...
  end
end

Not sure if there's a more straightforward way.

AlexVKO commented 4 years ago

Nice! thank you very much @alexgenco