1

I want a simple command that changes the range that the user selected to a constant string I set (with possibly differently number of lines) - effectively adding lines if the constant string has more. The following code does nothing but randomly inserts newline. What went wrong?

class Plugin(object):
    def __init__(self, nvim):
        self.nvim = nvim

    @neovim.command("MyCommand", range="", nargs="*", sync=True)
    def my_command(self, args, range):
        start_line, end_line = range
        region = self.nvim.current.buffer.range(start_line-1, end_line)
        aa="string \r ssss"  
        if len(aa)>0:
            region[:] = '\r'.split(aa)

2
  • 1
    I'm not sure to understand what you want to achieve. Maybe is you would give an example: current buffer content, command call with all its arguments and expected result it would help. Apr 21, 2023 at 4:21
  • I think i confused you with the word buffer. I want the equivalent of 'csomestring\n' from visual. and perhaps it can work as well by commands (when doing :MyCommand after selecting ramge)
    – eyal karni
    Apr 21, 2023 at 12:37

1 Answer 1

1
+200

I would add a file: nvim\rplugin\python3\mycommand.py to the nvim configuration.

With the following content:

import pynvim

@pynvim.plugin
class Plugin(object):
    def __init__(self, nvim):
        self.nvim = nvim

    @pynvim.command("MyCommand", range="", nargs=0, sync=True)
    def my_command(self, args, rgn):
        start_line, end_line = rgn
        self.nvim.command(f"echo {start_line} {end_line}")

        text="alpha\rbeta\rgamma"
        lines = text.split("\r")

        if len(lines) < end_line + 1 - start_line:
            # Remove lines in excess:
            self.nvim.call("deletebufline", "%", start_line + len(lines), end_line)

        for i in range(len(lines) - (end_line + 1 - start_line)):
            # Insert missing blank lines:
            self.nvim.call("appendbufline", "%", end_line, "")

        for index, line in enumerate(lines):
            # Replace lines with the text:
            self.nvim.call("setbufline", "%", start_line + index, line)

It assumes that pynvim package is available in the Python version that Neovim is using (defined in g:python3_host_prog)

5
  • @eyal, Did you had the chance to test the solution? Is it working for you? Apr 27, 2023 at 14:30
  • 1
    No, will check it tomorrow. Looks good. I thought a 5 line solution should be possible. Maybe not.
    – eyal karni
    Apr 27, 2023 at 23:25
  • 1
    Works really good. Thanks. I had to change nargs to "*" . The code will be in repo under MIT license , if you dont mind
    – eyal karni
    Apr 28, 2023 at 13:10
  • Thanks for your feedback :-) no problem for the MIT license ;-) Apr 28, 2023 at 13:31
  • 1

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.