import os, sys
import neovim
class IPythonPlugin(object):
    def __init__(self, vim):
        self.vim = vim

    def create_outbuf(self):
        vim = self.vim
        for b in vim.buffers:
            if "[ipython]" in b.name:
                self.buf = b
                return
        vim.command(":new")
        buf = vim.current.buffer
        buf.options["buflisted"] = False
        buf.options["swapfile"] = False
        buf.options["buftype"] = "nofile"
        try:
            buf.name = "[ipython]"
        except:
            #FIXME: this is not unique either
            buf.name = "[ipy-{}]".format(os.getpid())
        self.buf = buf

    def append_outbuf(self, data):
        # FIXME: encoding
        print(repr(data))
        lastline = self.buf[-1]
        txt = lastline + data
        self.buf[-1:] = txt.split("\n") # not splitlines
    def get_selection(self, kind):
        vim = self.vim
        if kind == "visual":
            b = vim.current.buffer
            start = b.mark('<')
            end = b.mark('>')
            lines = b[start[0]-1:end[0]]
            txt = '\n'.join(lines) + '\n'
            return txt
        elif kind == "line":
            return vim.current.line + '\n'

    def on_ipy_runline(self, msg):
        line = self.get_selection('line')
        self.append_outbuf(line)

    def do_ev(self):
        msg = self.vim.next_message()
        method = "on_" + msg.name
        if hasattr(self, method):
            getattr(self, method)(msg)
        else:
            print("warning: ignore", msg.name)

    def run(self):
        self.create_outbuf()
        self.vim.subscribe("ipy_runline")
        while True: self.do_ev()
        
if __name__ == "__main__":
    vim = neovim.connect(sys.argv[1])
    IPythonPlugin(vim).run()

        

@@ -102,16 +102,87 @@
 im = vim
+%0A        self.create_outbuf()%0A        self.vim.subscribe(%22ipy_runline%22)
 %0A%0A    de
@@ -1413,27 +1413,57 @@
 f do_ev(self
-):%0A
+,timeout=None):%0A        try:%0A    
         msg 
@@ -1486,17 +1486,113 @@
 message(
-)
+timeout)%0A        except NameError: #FIXME: upstream should emit TimeoutError%0A            return 0
 %0A       
@@ -1756,117 +1756,313 @@
 me)%0A
-%0A    def run(self):%0A        self.create_outbuf()%0A        self.vim.subscribe(%22ipy_runline%22)%0A        while True
+        return 0 #inputhook shall return 0%0A%0A    def run(self):%0A        while True: self.do_ev()%0A%0A    # debug ipython client plugint using ipython console...%0A    def ipython_inputhook_register(self):%0A        from IPython.lib.inputhook import inputhook_manager%0A        inputhook_manager.set_inputhook(lambda
 : se
@@ -2070,16 +2070,18 @@
 f.do_ev(
+0)
 )%0A      
@@ -2083,16 +2083,152 @@
        %0A
+def test_ipython(path):%0A    vim = neovim.connect(path)%0A    p = IPythonPlugin(vim)%0A    p.ipython_inputhook_register()%0A    return vim, p%0A%0A
 if __nam

integrate with ipython console's inputhook