Coder Social home page Coder Social logo

vim-ipython's Introduction

vim-ipython

A two-way integration between Vim and IPython.

IPython versions 0.11.x, 0.12.x, 0.13.x, 1.x, 2.x and 3.x

Using this plugin, you can send lines or whole files for IPython to execute, and also get back object introspection and word completions in Vim, like what you get with: object?<enter> and object.<tab> in IPython.

The big change from previous versions of ipy.vim is that it no longer requires the old brittle ipy_vimserver.py instantiation, and since it uses just vim and python, it is platform independent (i.e. works even on windows, unlike the previous *nix only solution). The requirements are IPython 0.11 or newer with zeromq capabilities, vim compiled with +python.

If you can launch ipython qtconsole or ipython kernel, and :echo has('python') returns 1 in vim, you should be good to go.

Quickstart Guide:

Start ipython qtconsole [*]. Source ipy.vim file, which provides new IPython command:

:source ipy.vim
(or copy it to ~/.vim/ftplugin/python to load automatically)

:IPython

The :IPython command allows you to put the full connection string. For IPython 0.11, it would look like this:

:IPython --existing --shell=41882 --iopub=43286 --stdin=34987 --hb=36697

and for IPython 0.12 through IPython 2.0 like this:

:IPython --existing kernel-85997.json

There also exists to convenience commands: :IPythonClipboard just uses the + register to get the connection string, whereas :IPythonXSelection uses the * register and passes it to :IPython.

NEW in IPython 2.0

vim-ipython can now interoperate with non-Python kernels.

NEW in IPython 0.12! Since IPython 0.12, you can simply use:

:IPython

without arguments to connect to the most recent IPython session (this is the same as passing just the --existing flag to ipython qtconsole and ipython console.

[*]Though the demos above use qtconsole, it is not required for this workflow, it's just that it was the easiest way to show how to make use of the new functionality in 0.11 release. Since IPython 0.12, you can use ipython kernel to create a kernel and get the connection string to use for any frontend (including vim-ipython), or use ipython console to create a kernel and immediately connect to it using a terminal-based client. You can even connect to an active IPython Notebook kernel - just watch for the connection string that gets printed when you open the notebook, or use the %connect_info magic to get the connection string. If you are still using 0.11, you can launch a regular kernel using python -c "from IPython.zmq.ipkernel import main; main()"

Sending lines to IPython

Now type out a line and send it to IPython using <Ctrl-S> from Command mode:

import os

You should see a notification message confirming the line was sent, along with the input number for the line, like so In[1]: import os. If <Ctrl-S> did not work, see the Known Issues for a work-around.

<Ctrl-S> also works from insert mode, but doesn't show notification, unless monitor_subchannel is set to True (see vim-ipython 'shell', below)

It also works blockwise in Visual Mode. Select and send these lines using <Ctrl-S>:

import this,math # secret decoder ring
a,b,c,d,e,f,g,h,i = range(1,10)
code =(c,a,d,a,e,i,)
msg = '...jrer nyy frag sebz Ivz.\nIvz+VClguba=%fyl '+this.s.split()[g]
decode=lambda x:"\n"+"".join([this.d.get(c,c) for c in x])+"!"
format=lambda x:'These lines:\n  '+'\n  '.join([l for l in x.splitlines()])
secret_decoder = lambda a,b: format(a)+decode(msg)%str(b)[:-1]
'%d'*len(code)%code == str(int(math.pi*1e5))

Then, go to the qtconsole and run this line:

print secret_decoder(_i,_)

You can also send whole files to IPython's %run magic using <F5>.

NEW in IPython 0.12! If you're trying to do run code fragments that have leading whitespace, use <Alt-S> instead - it will dedent a single line, and remove the leading whitespace of the first line from all lines in a visual mode selection.

IPython's object? Functionality

If you're using gvim, mouse-over a variable to see IPython's ? equivalent. If you're using vim from a terminal, or want to copy something from the docstring, type <leader>d. <leader> is usually \ (the backslash key). This will open a quickpreview window, which can be closed by hitting q or <escape>.

IPython's tab-completion Functionality

vim-ipython activates a 'completefunc' that queries IPython. A completefunc is activated using Ctrl-X Ctrl-U in Insert Mode (vim default). You can combine this functionality with SuperTab to get tab completion.

vim-ipython 'shell'

By monitoring km.sub_channel, we can recreate what messages were sent to IPython, and what IPython sends back in response.

monitor_subchannel is a parameter that sets whether this 'shell' should updated on every sent command (default: True).

If at any later time you wish to bring this shell up, including if you've set monitor_subchannel=False, hit <leader>s.

NEW since IPython 0.12 For local kernels (kernels running on the same machine as vim), Ctrl-C in the vim-ipython 'shell' sends an keyboard interrupt. (Note: this feature may not work on Windows, please report the issue to ).

Options

You can change these at the top of the vim_ipython.py:

reselect = False            # reselect lines after sending from Visual mode
show_execution_count = True # wait to get numbers for In[43]: feedback?
monitor_subchannel = True   # update vim-ipython 'shell' on every send?
run_flags= "-i"             # flags to for IPython's run magic when using <F5>

Disabling default mappings In your own .vimrc, if you don't like the mappings provided by default, you can define a variable let g:ipy_perform_mappings=0 which will prevent vim-ipython from defining any of the default mappings.

NEW since IPython 0.12 Making completefunc local to a buffer, or disabling it By default, vim-ipython activates the custom completefunc globally. Sometimes, having a completefunc breaks other plugins' completions. Putting the line let g:ipy_completefunc = 'local' in one's vimrc will activate the IPython-based completion only for current buffer. Setting g:ipy_completefunc to anything other than 'local' or 'global' disables it altogether.

NEW since IPython 0.13

Sending ? and ?? now works just like IPython This is only supported for single lines that end with ? and ??, which works just the same as it does in IPython (The ?? variant will show the code, not just the docstring

Sending arbitrary signal to IPython kernel :IPythonInterrupt now supports sending of arbitrary signals. There's a convenience alias for sending SIGTERM via :IPythonTerminate, but you can also send any signal by just passing an argument to :IPythonInterrupt. Here's an example. First, send this code (or just run it in your kernel):

import signal
def greeting_user(signum, stack):
    import sys
    sys.stdout.flush()
    print "Hello, USER!"
    sys.stdout.flush()
signal.signal(signal.SIGUSR1, greeting_user)

Now, proceed to connect up using vim-ipython and run :IPythonInterrupt 10 - where 10 happens to be signal.SIGUSR1 in the POSIX world. This functionality, along with the sourcing of profile-dependent code on startup ( vi `ipython locate profile default`/startup/README ), brings the forgotten world of inter-process communication through signals to your favorite text editor and REPL combination.

Known issues:

  • For now, vim-ipython only connects to an ipython session in progress.

  • The standard ipython clients (console, qtconsole, notebook) do not currently display the result of computation which they did not initialize. This means that if you send print statements for execution from within vim, they will only be shown inside the vim-ipython shell buffer, but not within any of the standard clients. This is not a limitation of vim-ipython, but a limitation of those built-in clients, see ipython/ipython#1873

  • The ipdb integration is not yet re-implemented. Pending [IPython PR #3089](ipython/ipython#3089)

  • If <CTRL-S> does not work inside your terminal, but you are able to run some of the other commands successfully (<F5>, for example), try running this command before launching vim in the terminal (add it to your .bashrc if it fixes the issue):

    stty stop undef # to unmap ctrl-s
    
  • In vim, if you're getting ImportError: No module named IPython.zmq.blockingkernelmanager but are able to import it in regular python, either

    1. your sys.path in vim differs from the sys.path in regular python. Try running these two lines, and comparing their output files:

      $ vim -c 'py import vim, sys; vim.current.buffer.append(sys.path)' -c ':wq vim_syspath'
      $ python -c "import sys; f=file('python_syspath','w'); f.write('\n'.join(sys.path)); f.close()"
      

    or

    1. your vim is compiled against a different python than you are launching. See if there's a difference between

      $ vim -c ':py import os; print os.__file__' -c ':q'
      $ python -c 'import os; print os.__file__'
      
  • For vim inside a terminal, using the arrow keys won't work inside a documentation buffer, because the mapping for <Esc> overlaps with ^[OA and so on, and we use <Esc> as a quick way of closing the documentation preview window. If you want go without this quick close functionality and want to use the arrow keys instead, look for instructions starting with "Known issue: to enable the use of arrow keys..." in the get_doc_buffer function.

  • @fholgado's update to minibufexpl.vim that is up on GitHub will always put the cursor in the minibuf after sending a command when monitor_subchannel is set. This is a bug in minibufexpl.vim and the workaround is described in vim-ipython issue #7.

  • the vim-ipython buffer is set to filetype=python, which provides syntax highlighting, but that syntax highlighting will be broken if a stack trace is returned which contains one half of a quote delimiter.

  • vim-ipython is currently for Python2.X only.

Thanks and Bug Participation

Here's a brief acknowledgment of the folks who have graciously pitched in. If you've been missed, don't hesitate to contact me, or better yet, submit a pull request with your attribution.

  • @minrk for guiding me through the IPython kernel manager protocol, and support of connection_file-based IPython connection (#13), and keeping vim-ipython working across IPython API changes.
  • @nakamuray and @tcheneau for reporting and providing a fix for when vim is compiled without a gui (#1)
  • @unpingco for reporting Windows bugs (#3,#4), providing better multiline dedenting (#15), and suggesting that a resized vim-ipython shell stays resized (#16).
  • @simon-b for terminal vim arrow key issue (#5)
  • @jorgesca and @kwgoodman for shell update problems (#6)
  • @xowlinx and @vladimiroff for Ctrl-S issues in Konsole (#8)
  • @zeekay for easily allowing custom mappings (#9)
  • @jorgesca for reporting the lack of profile handling capability (#14), only open updating 'shell' if it is open (#29)
  • @enzbang for removing mapping that's not currently functional (#17)
  • @ogrisel for fixing documentation typo (#19)
  • @koepsell for gracefully exiting in case python is not available (#23)
  • @mrterry for activating completefunc only after a connection is made (#25), Ctrl-C implementation in vim-ipython 'shell' (#28)
  • @nonameentername for completion on import statements (#26)
  • @dstahlke for setting syntax of doc window to ReST
  • @jtratner for docs with quotes (#30)
  • @pielgrzym for setting completefunc locally to a buffer (#32)
  • @flacjacket for pointing out and providing fix for IPython API change
  • @memeplex for fixing the identifier grabbing on e.g. non-PEP8 compliant code
  • @pydave for IPythonTerminate (sending SIGTERM using our hack)
  • @luispedro for IPythonNew
  • @jjhelmus and @wmvanvliet for IPython 3.x support.

Similar Projects

  • ipython-vimception - vim-within-vim in the IPython Notebook (Paul Ivanov)
  • vim-slime - Grab some text and "send" it to a GNU Screen / tmux session (Jonathan Palardy)
  • screen.vba - Simulate a split shell, using GNU Screen / tmux, that you can send commands to (Eric Van Dewoestine)
  • vimux - vim plugin to interact with tmux (Ben Mills)
  • vimux-pyutils - send code to tmux ipython session (Julien Rebetez)
  • conque - terminal emulator which uses a Vim buffer to display the program output (Nico Raffo)
  • ipyqtmacvim - plugin to send commands from MacVim to IPython Qt console (Justin Kitzes)
  • tslime_ipython - "cell" execution , with cells defined by marks
  • vipy - used vim-ipython as a starting point and ran with it in a slightly different direction. (John David Giese)

Bottom Line

If you find this project useful, please consider donating money to the John Hunter Memorial Fund. A giant in our community, John lead by example and gave us all so much. This is one small way we can give back to his family.

vim-ipython's People

Contributors

arnaldorusso avatar dstahlke avatar enzbang avatar ivanov avatar jjhelmus avatar koepsell avatar luispedro avatar minrk avatar nonameentername avatar ogrisel avatar pag avatar pielgrzym avatar wmvanvliet avatar zeekay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vim-ipython's Issues

object? functionality

While trying to make my way through the quickstart guide I get the following error when trying to inspect an object using d

Error detected while processing function IPythonBalloonExpr:
line 5:
Traceback (most recent call last):
File "", line 2, in
File "", line 153, in get_doc
TypeError: object_info() takes exactly 2 arguments (3 given)
line 6:
E121: Undefined variable: l:doc

CRLF problem

I'm not sure what you can do about this or whether it's even worth mentioning but my vim hick-uped on the line endings. dos2unix thinks ipy.vim is a binary file and just skips processing it so I used something like:

cat ipy.vim | sed 's/\r//g' > newipy.vim
mv newipy.vim ipy.vim

I'm on ubuntu 11.04 and vim 7.3.

Kill connecting process when exiting Vim

After closing vim, there still exists a process which was spawned by the plugin if the kernel was not terminated with ":IPythonTerminate":

Steps to reproduce:

  • start an ipython kernel
  • open vim and connect via :IPython
  • optional: terminate kernel from outside vim
  • close vim

$ ps aux | grep ipython
fixje 14513 0.2 0.4 591408 36236 pts/3 Sl 00:49 0:00 /usr/bin/python2 -c from IPython.zmq.ipkernel import main; main() -f /home/fixje/.ipython/profile_default/security/kernel-14508.json --KernelApp.parent_appname='ipython-console' --parent=1

Request: configurable vim-ipython closing/hiding

Hi,
I had a quick look at the code, but it wasn't evident to me if it is possible to permanently close/hide the vim-ipython window. Sometimes I spent a lot of time writing code/analyzing stuff and the vim-ipython window actually gets in the way. If I close it manually, it appears back after a short while.

Consider this a low priority feature request: It would be nice to be able to close the window and make it appear back only upon request, or some similar configurable behavior.

Thanks for a great work. I love this plugin.

jorgesca

Runtime errors and quickfix window

When running python code, at times errors or exceptions will be raised.
What about sent the error/exception to the quickfix window, so that the user could go to the problematic code position using one click?

no reply from / Invalid Message to kernel (Windows)

Hi,

I've been having an issue with getting vim-ipython to communicate with an IPython kernel. I'm on windows 7, using I believe I've installed everything correctly, and vim is built against the Python on my system (e.g., vim python can import the IPython module, etc.).
:source ipy.vim works without errors. But when I start up an IPython kernel, and then call :IPython in vim, I get following errors:

in vim: "no reply from kernel"

in IPython kernel:

[IPKernelApp] Invalid Message
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\IPython\kernel\zmq\ipkernel.py", line 208, in dispatch_shell
msg = self.session.unserialize(msg, content=True, copy=False)
File "C:\Anaconda\lib\site-packages\IPython\kernel\zmq\session.py", line 722, in unserialize
msg_list[i] = msg_list[i].bytes
IndexError: list index out of range
[IPKernelApp] Invalid Message
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\IPython\kernel\zmq\ipkernel.py", line 208, in dispatch_shell
msg = self.session.unserialize(msg, content=True, copy=False)
File "C:\Anaconda\lib\site-packages\IPython\kernel\zmq\session.py", line 722, in unserialize
msg_list[i] = msg_list[i].bytes
IndexError: list index out of range

I'm not exactly sure what the problem is. My Python installation is 2.7.3; IPython is the latest dev version. Python is 32bit, as is vim, I believe -- I'm assuming I wouldn't have gotten this far otherwise).

Thanks for any help or insight,

-c.

<enter> in insert mode should send the line to ipython

Onti,

Raghuram.O.S., on 2012-03-17 18:09, wrote:

Hi,

Awesome integration plugin. Thanks for this. I had a question regarding
this.

I see that I am able to autocomplete from ipython. But, this happens only
when the code is in the ipython context.

Let me explain with an example.

I have

a = 'abc'
a.s(or )

Gives nothing

But,

a = 'abc'
a.s gives a list

split
splitlines
startswith
...

The same goes for documentation on variables also. Is there a way to keep
everything in ipython context too so that it would behave like a complete
ide (whatever eclipse does for java)?

apologies for not replying sooner (I have a tremendous amount of
email debt). If I understand correctly what you want, the only
way to get that kind of behaviour from the machinery we have
would be to send every line of your code to ipython.

You can imagine how harry that would get if you're writing code,
and then go back up to change some line -- should we always rerun
the entire buffer, or do we have to keep track of dependencies
among your lines to figure out which lines need to be re-run with
the new changes.

now, there would be a relatively straightforward way of getting
this functionality, by just re-binding <enter> to the equivalent
of sending <C-S><enter> when in Insert mode... I think I tried
doing this once, and wasn't able to get it working, but it may be
worth another look.

You can imagine how this would also start to fail for lines which
should not be sent and executed one-by-one, as in the case of a
conditional code block or loop. Try sending a line which only
contains if 1:, and you'll see IPython complaining of a
SyntaxError.

I'm adding this email correspondence as a feature request for
vim-ipython.

ImportError occurs in gvim while no errors occur in regular python shell

My platform is WIN7. I have installed pyzmq-2.1.9,and “import zmq” is right in python and ipython shell, but when i use gvim “:IPythonClipboard” an error occures:”Import error:IPython.zmq requires pyzmq >2.1.4″.In fact, in gvim I type ":py import zmq", "Import Error:DLL load failed special module can not be found" occurs in the line"from zmq.utils import initthreads".In addition,in gvim when i type ":py import nose" etc,it's right.I don't know why.

Error when showing docstring either using <leader>d in vim or mouse over in gvim

I try to get the docstring of "range", when in vim, cursor over r in range, pressing backslash+d, I get:

Traceback (most recent call last):
File "", line 1, in
File "", line 197, in get_doc_buffer
File "", line 153, in get_doc
TypeError: object_info() takes exactly 2 arguments (3 given)

in gvim when mouse over range(normal mode), I get:

Error detected while processing function IPythonBalloonExpr:
line 5:
Traceback (most recent call last):
File "", line 1, in
File "", line 153, in get_doc
TypeError: object_info() takes exactly 2 arguments (3 given)
line 6:
E121: Undefined variable: l:doc
E15: Invalid expression: l:doc

I'm using ubuntu 12.04, vim 7.3, ipython 0.12.1. I tried the same thing in ipython notebook and in ipython console, everything is OK, so I guess it may be the issue with vim-ipython

Another confusion is that even when monitor_subchannel=True, I still need to press backslash+s to open the "shell", ctrl-s just convey the message but the shell won't pop up as shown in tutorial youtube video. Does it have any connection with the main issue above?

Vim fails when closing ipython windows

The error message I'm getting is the following:

Vim(41815,0x7fff702a2cc0) malloc: *** error for object 0x100000000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Vim: Caught deadly signal ABRT
Vim: preserving files...

My vim installation is slightly non-standard, added a hack to the configure file as described [here](http://stackoverflow.com/questions/7294554/vim-compiles-with-wrong-python-version-and-not-working-with-needed-
version/9566769#9566769) because I wanted to use brew python rather than system python. Is this causing the issue? I'm running on mac osx 10.6.8, using Macvim 7.3.

It works on Windows XP (mostly)

I had to make the changes to the completion function to the "old" way that is documented in your code instead of the version that Min recommends:

starting from line 400:

 m = get_child_msg(msg_id)
# get rid of unicode (sporadic issue, haven't tracked down when it happens)
matches = [str(u) for u in m['content']['matches']]
# mirk sez do: completion_str = '[' + ', '.join(msg['content']['matches'] ) + ']'
# because str() won't work for non-ascii characters
#matches = m['content']['matches']
#end = len(base)
#completions = [m[end:]+findstart+base for m in matches]
matches.insert(0,base) # the "no completion" version
#echo(str(matches))
completions = matches

otherwise, it would crash when I would try to do completions and mysteriously would recognize the Ctrl+u part of the completion sequence as the letter 'u' instead of as Ctrl+u. This obviously caused a number of downstream errors that I couldn't isolate.

Great work!

`:IPython` crashes with `ImportError: cannot import name urandom`

First, I start ipython:

$ ipython kernel
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-9920.json

Next, I start Vim and run :IPython --existing kernel-9920.json

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 44, in km_from_string
  File "/usr/local/lib/python2.7/site-packages/IPython/__init__.py", line 43, in
 <module>
    from .config.loader import Config
  File "/usr/local/lib/python2.7/site-packages/IPython/config/__init__.py", line
 16, in <module>
    from .application import *
  File "/usr/local/lib/python2.7/site-packages/IPython/config/application.py", l
ine 31, in <module>
    from IPython.config.configurable import SingletonConfigurable
  File "/usr/local/lib/python2.7/site-packages/IPython/config/configurable.py", 
line 26, in <module>
    from loader import Config
  File "/usr/local/lib/python2.7/site-packages/IPython/config/loader.py", line 2
7, in <module>
    from IPython.utils.path import filefind, get_ipython_dir
  File "/usr/local/lib/python2.7/site-packages/IPython/utils/path.py", line 19, 
in <module>
    import tempfile
  File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/
lib/python2.7/tempfile.py", line 34, in <module>
    from random import Random as _Random
  File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/
lib/python2.7/random.py", line 47, in <module>
    from os import urandom as _urandom
ImportError: cannot import name urandom

When comparing sys.path:

$ diff vim_syspath python_syspath 
24d23
< /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
30c29
< /usr/local/lib/python2.7/site-packages

---
> /usr/local/lib/python2.7/site-packages
\ No newline at end of file```

vim-IPython crashes when starting the plugin

Hello,

When I launch ":IPython", or ":IPython --existing kernel xxxxxx.json", I obtain this message :
Traceback (most recent call last):
File "", line 1, in
File "", line 44, in km_from_string
File "/usr/lib/python3.3/site-packages/IPython/init.py", line 43, in
from .config.loader import Config
File "/usr/lib/python3.3/site-packages/IPython/config/init.py", line 16, in
from .application import *
File "/usr/lib/python3.3/site-packages/IPython/config/application.py", line 29, in
from IPython.external.decorator import decorator
File "/usr/lib/python3.3/site-packages/IPython/external/decorator/init.py", line 4, in
from ._decorator import *
File "/usr/lib/python3.3/site-packages/IPython/external/decorator/_decorator.py", line 165
print('Error in generated code:', file=sys.stderr)
^
SyntaxError: invalid syntax

That seems to be located in IPython itself... My current version is 0.13.2, and I am running an ArchLinux.

How to integrate into django manage shell

Hi ivanov,

I'm very interested in howto integrate this plugin into django shell management command.

Basically, django uses ipython (if ipython is present) as interactive shell for enhancement. And django offers a hook (by subclass) to customize this behavior. Please see django changeset #14895.

My question is that could we get the ipython running information, something like --existing --shell=xxx --iopub=xxx --stdin=xxx --hb=xxx, which is required by this plugin(?) without running qtconsole? If it couldn't, how to embed qtconsole in the django manage shell?

Hope it's a right place to ask this question. Sorry for my poor English.
And please let me know if it's a stupid question, since there is an old way: just setup django environment when qtconsole starts up, which I do not really like.

Thanks,

Profile directory not found in paths: profile_default

After installing in pathogen bundle directory, trying to run the :IPython command, I get the following exception:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 62, in km_from_string
  File "/usr/lib/python2.7/site-packages/ipython-0.13.1-py2.7.egg/IPython/lib/kernel.py", line 96, in find_connection_file profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default')
  File "/usr/lib/python2.7/site-packages/ipython-0.13.1-py2.7.egg/IPython/core/profiledir.py", line 209, in find_profile_dir_by_name
    raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
IPython.core.profiledir.ProfileDirError: Profile directory not found in paths: profile_default

add sending of code selection (c-v) without indent errors?

Within VIM, one can do to highlight blocks of text that start in specified columns (i.e. do not select the entire line). I have tried doing to send the so-selected text to IPython, but I get indent errors.

Would it be possible to configure ipy.vim to handle sending sub-blocks of code to IPython that do not start at column one?

The use case is when you are walking through sub-functions of a larger program that are indented with respect to the file you are editing and want to send these sub-blocks to IPython.

BTW, I'm on windows xp, GVIM 7.3

Thanks!

Jose

Vim can not auto source this plugin?

In the quick start guide, it says:
(or copy it to ~/.vim/ftplugin/python to load automatically)
But it seems vim can not auto source it in this way.

shell update problem

Hi,
I started getting the message below whenever I send a line (CTRL-S) or file (F5) to ipython. The shell doesn't get updated, but the line/file was actually sent to ipython. I just pull'ed from both ipython and vim-ipython repos before discovering the issue.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 232, in f_with_update
  File "<string>", line 173, in update_subchannel_msgs
KeyError: 'msg_type'

Error with pyzmq

I have iPython and all the dependencies installed and working. When I issue :IPython inside vim I get the following error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 44, in km_from_string
  File "/usr/local/lib/python2.7/site-packages/IPython/zmq/__init__.py", line 67, in <module>
    check_for_zmq('2.1.4')
  File "/usr/local/lib/python2.7/site-packages/IPython/zmq/__init__.py", line 53, in check_for_zmq
    raise ImportError("%s requires pyzmq >= %s"%(module, minimum_version))
ImportError: IPython.zmq requires pyzmq >= 2.1.4
Press ENTER or type command to continue

I have pyzmq 2.2.0 installed via pip. Any idea what could be the problem?

start vim from ipdb session to edit current code in debugging?

Not sure if it is proper to post here, but maybe vim-ipython would be the closest tool to fulfill this job.
Sometimes when I was tracing code in ipdb, and felt is necessary to read whole current code file closely, then it would be best if I can kick vim/gvim with ipdb session. Is there such function already?

File-based connection to kernel fails

Hi,
I just pull'ed from both ipython and vim-ipython yesterday, and when I try to connect to the kernel (doing :IPython kernel-5716.json) I get:

IPython kernel-5716.json --profile pylab failed
^-- failed -- kernel-5716.json --profile pylab not found

The strange thing is that if I try to find the connection file inside qtconsole it works:

In [13]: from IPython.lib.kernel import find_connection_file

In [14]: find_connection_file('kernel-5716.json')
Out[14]: u'/home/jscandal/.config/ipython/profile_pylab/security/kernel-5716.json'

Any ideas?

jorges

Sent text shows up in IPython 'In' variable, not in scope of shell

I'm using IPython 0.13.1 and GVim 7.3 and seeing problems with this plugin. I can connect without any problems using the :IPython --existing <json> syntax. However, when I send a line with <Ctrl-S> I don't see the code show up in the global scope as I expected.

I've done some poking around and found that the text is sent to IPython. The text I sent appears as a new list entry in the 'In' list in IPython. For example:

Run ipython console:

[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-12721.json
Exception reporting mode: Plain
Doctest mode is: ON

In [1]: dir()
Out[1]: ['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__name__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', '_sh', 'exit', 'get_ipython', 'help', 'quit']

In [2]: In
Out[2]: ['', u'dir()', u'In']

Now connect with Gvim and send print 'whoops' and look at the IPython shell again:

In [3]: dir()
Out[4]: ['In', 'Out', '_', '_1', '_2', '__', '___', '__builtin__', '__builtins__', '__name__', '__package__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_ih', '_ii', '_iii', '_oh', '_pid', '_sh', 'exit', 'get_ipython', 'help', 'os', 'quit']

In [5]: In
Out[5]: ['', u'dir()', u'In', u"        print 'whoops'", u'dir()', u'In']

So, the text is sent but doesn't show up at the prompt and gets buried away in the 'In' variable. Maybe I'm completely missing something here?

AttributeError: 'NoneType' object has no attribute 'sub_channel'

Intermittently, I'm getting this error on MacVim 7.3 and Python 2.7.2. I haven't looked into it yet to figure out what it's trying to tell me.

Error detected while processing CursorHold Auto commands for "*.*":
Traceback (most recent call last):
Press ENTER or type command to continue
Error detected while processing CursorHold Auto commands for "*.*":
  File "<string>", line 1, in <module>
Press ENTER or type command to continue
Error detected while processing CursorHold Auto commands for "*.*":
  File "<string>", line 180, in update_subchannel_msgs
Press ENTER or type command to continue
Error detected while processing CursorHold Auto commands for "*.*":
AttributeError: 'NoneType' object has no attribute 'sub_channel'
Press ENTER or type command to continue

:IPython not an editor command

Hi,

Many thanks for a wonderful initiative -- i very much look forward to having it all working well.

The issue i have just now is that vim does not appear to accept the vim-ipython commands, even after sourcing ipy.vim.

I have pulled the project down with Bundle, so i sourced it with

:source ~/.vim/bundle/vim-ipython/ftplugin/python/ipy.vim

However, even after doing so, :IPython returns E492: Not an editor command: IPython

I am able to launch ipython qtconsole, and :echo has('python') returns 1 in vim. I have checked the sys.path issue and have also checked that my vim is compiled against the same python as i am using.

Advice is very much appreciated.

thanks -- and Merry Christmas!

Help syntax highlighter handle partial strings gracefully

When there is some error and you get an incomplete string in the traceback in the ipython preview window, your syntax highlighting gets trashed.

Ex. Ending docstring on previous line ruins everything.

Could we try to fix this by making somehow isolating the offending parts? I'm not very knowledgeable on how vim's syntax highlighting really works but maybe we could trick by inserting a " or ' when necessary?

raising error messages/being called even when not invoked

this error occurs when IPython is not open (and also when I don't recall having invoked vim-ipython)

That said, it usually seems to occur when I've left gvim open for a while, so that may mean that I'm just forgetting that I have invoked it.

get_doc is returning an error message that itself throws an error in vim

I sometimes find that when I'm using gvim, I will sometimes get an unexpected error message popping up in the following way (when I haven't invoked :IPython yet).

(unfortunately, I didn't copy the message exactly and it hasn't cropped up recently...so I can't be super helpful)

The error message says something along the lines of

" first line of error message references:
IPython_BalloonExpr()
" error message then reads
Invalid List syntax, (period/comma/something like that missing)
" then it literally quotes this line as an error 
"    (corresponds to the get_doc function error output)
["Not connected to IPython, cannot query \"[WORD]\""] 
" (where WORD is replaced by current highlighted word)

To be clear, the error message is not about the error itself, but rather the formatting of the returned list output for the error message

I tried reformatting the error message multiple ways in Python functions (just literally invoking a function that raises the error) and it didn't raise this error - though as I'm writing this I'm wondering if the problem might occur if BalloonExpr passed a word with a quotation mark in it, thereby throwing off the quotations.

Suggestions for debugging this?

I hope to debug this myself (because it's so intermittent I can't describe the error that well), but I was hoping someone could offer a bit of direction on where to look and what to test. So a few specific questions:

1 - what environment variables are important to record when this occurs?
2 - is it possible that vim-ipython would be starting up either (a) without being invoked or (b) in non *.py files?
3 - does vim-ipython shut itself down automatically if IPython is shut down?

Using nore variants to avoid potential remapping issue

I am using colemak keyboard layout which has : where p key is, and thus I have remapped ; as p. Without nore variants, when I press C-s vim pastes unnamed register.

I added nore to all the commands and now it works fine. Would it be possible to make the change?

Thank you,
Joon

Make ipython shell echo commands sent from vim

This is not an issue per se, as it may not be the intended behaviour -- however is it possible to make the ipython shell echo the commands sent from vim amd therefore to show the output relevant cases (such as when print os.file is sent from vim) ?

Cannot load zmq DLL on Windows 7 (64bit) with gvim/python (32bit)

I am having a similar problem to other people here. In fact I think it is more or less issue 80, although that issue is closed.

I am running:

python 2.7.2    (http://python.org/ftp/python/2.7.2/python-2.7.2.msi)
ipython 0.12    (from http://archive.ipython.org/release/0.12/ipython-0.12.win32-setup.exe)
pyzmq 2.1.11  (http://cloud.github.com/downloads/zeromq/pyzmq/pyzmq-2.1.11.win32-py2.7.msi)
gvim 3.7.46     (ftp://ftp.vim.org/pub/vim/pc/gvim73_46.exe)

(and a few others like pyreadline, setuptools etc, but I don't believe they are relevant to the problem)

My OS is 64bit Windows 7 Enterprise SP1

I get the error doing the following in gvim:

:so C:\Python27\share\doc\ipython\examples\vim\ipy.vim
:IPythonClipboard

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 39, in km_from_string
  File "C:\Python27\lib\site-packages\IPython\zmq\blockingkernelmanager.py", line 25, in <module>
    from .kernelmanager import (KernelManager, SubSocketChannel, HBSocketChannel
  File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 29, in <module>
    import zmq
  File "C:\Python27\lib\site-packages\zmq\__init__.py", line 35, in <module>
    from zmq.utils import initthreads @ initialize threads
ImportError: DLL load failed: The specified module could not be found

If I run C:\Python27\python.exe I can type:

import zmq
from zmq.utils import initthreads 

without any error.

Having tried to trace things a little further, I've notied that

C:\Python27\Lib\site-packages\zmq\utils\initthreads.pyd

show an error in DependancyWalker:

MSVCR90.DLL was not found

Checking C:\Windows\SysWOW64\python27.dll in DependancyWalker shows that it
does have a successful reference to MSVCR90.DLL at the following location:

c:\windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.6161_none_50934f2ebcb7eb57\MSVCR90.DLL

C:\Python27\python.exe also has a successful reference to MSVCR90.DLL
in DependancyWalker (same value):

c:\windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.6161_none_50934f2ebcb7eb57\MSVCR90.DLL

However if I load gvim.exe in DependancyWalker, I find that it no reference
to MSVCR90.DLL at all - it simply doesn't link against it.

This leads my to believe that it is the MSVCR90.DLL dependancy that is the
problem on the machine I'm using, and that it is satisifed by python.exe
itself, and so everything works when you test it in python, but is
not present in gvim.exe, and so when the initthreads.pyd library gets
loaded, it encounters the "DLL load failed" error.

Grepping the interwebs for similar problems, I came across:

http://code.google.com/p/pyodbc/issues/detail?id=214

which looks to me (and I know very little about WOW or manifests etc) like
it might be describing roughly the same problem.

vim-ipython shell window does not open automatically

Hi,

It seems to me with monitor_subchannel = True option, the vim-ipython shell window should open automatically, but window does not open when I use vim-ipython. When I do :py update_subchannel_msgs(force=True) I finally get the window (and it works well)

Is there any other setting that I don't know about? Thanks!

ugly error when mousing over user-defined values

Sometimes, I see the following error. I'm not sure why this happens, but it uses up half the screen when it does, which is incredibly distracting.

Error detected while processing function IPythonBalloonExpr:
line    5:
E696: Missing comma in List: s ', '   id.', '', ':param pool_size=5: the number of connections to keep open', '    inside the connection pool. This us
ed with :class:`~sqlalchemy.pool.QueuePool` as', '    well as :class:`~sqlalchemy.pool.SingletonThreadPool`.  With', '    :class:`~sqlalchemy.pool.Que
uePool`, a ``pool_size`` setting', '    of 0 indicates no limit; to disable pooling, set ``poolclass`` to', '    :class:`~sqlalchemy.pool.NullPool` in
stead.', '', ':param pool_recycle=-1: this setting causes the pool to recycle', '    connections after the given number of seconds has passed. It', '
   defaults to -1, or no timeout. For example, setting to 3600', '    means connections will be recycled after one hour. Note that', '    MySQL in par
ticular will disconnect automatically if no', '    activity is detected on a connection for eight hours (although', '    this is configurable with the
 MySQLDB connection itself and the', '    server configuration as well).', '', ':param pool_reset_on_return=\'rollback\': se
E15: Invalid expression: ['Type Name:   function', "Base Class:  <type 'function'>", 'String Form: <function create_engine at 0x10372da28>', 'Namespac
e:   Interactive', 'File:        /usr/local/lib/python2.7/site-packages/sqlalchemy/engine/__init__.py', 'Definition:  create_engine(*args, **kwargs)',
 'Docstring:   ', 'Create a new :class:`.Engine` instance.', '', 'The standard calling form is to send the URL as the ', 'first positional argument, u
sually a string ', 'that indicates database dialect and connection arguments.', 'Additional keyword arguments may then follow it which', 'establish va
rious options on the resulting :class:`.Engine`', 'and its underlying :class:`.Dialect` and :class:`.Pool`', 'constructs.', '', 'The string form of th
e URL is', '``dialect+driver://user:password@host/dbname[?key=value..]``, where', '``dialect`` is a database name such as ``mysql``, ``oracle``, ', '`
`postgresql``, etc., and ``driver`` the name of a DBAPI, such as ', '``psycopg2``, ``pyodbc``, ``cx_oracle``, etc.  Alternat
Traceback (most recent call last):
  File "<string>", line 3, in <module>
vim.error
line    6:
E121: Undefined variable: l:doc        

IPython refactor

Using recent IPython master blockingkernelmanager has been moved I think, so the plugin won't work.

Bad parsing of identifiers

<Leader>d over decode in this line:

secret_decoder = lambda a,b: format(a)+decode(msg)%str(b)[:-1]

parses "+decode" so that an error:

'+decode' not found

is shown.

The + is not part of the identifier. For example:

:echo expand("<cWORD>") => "decode"

I'm not sure why you use here:

def get_doc_buffer(level=0):
    # empty string in case vim.eval return None
    word = vim.eval('expand("<cfile>")') or ''

Update Behaviour of the IPython shell

When issuing a command via Ctrl-S, there is no reaction in the IPython Qtconsole, f.e. when plotting with the inline mode or sending a simple print statement. Instead, some statements like print are show in the vim-ipython shell, but this one always closes and doesn´t stay open. Wouldn´t it be good to see all the results in the IPython QTconsole (like in RStudio)?

ipython console not updated

Hello,

Great plugin!

Plugin itself seems to work - after pressing on a single line/block a message in statusline appears and qtconsole's/ipython consoles context is updated, but the output is not rendered in ipython (qt)console. Is it the desired behavior?

For example, sending:

x = 2
print x

Ipython console does not print anything, after hitting enter it notices extra line numers and I can refer to x etc.

In [3]: print x
Out[3]: 2

Interaction with minibufexpl

If minibufexpl is loaded then when the "Ctrl-s" command is used (in both command and insert modes) the minibufexpl window is selected.

This is frustrating as it is necessary to manually re-select the window of the file being edited after sending each command.

Completion of user-defined types

Hiya,

I'm having trouble getting completion (and documention) working for types I defined.

Completion for stdlibs works, and under some conditions I am able to get some kind of documentation for a class I defined (e.g. if I create an instance of it, in the same module):

from bar import Bar


class Foo(object):
    """
    Test vim-ipython's completion for user-defined types
    """

    FOO = "FOO"

    def __init__(self):
        self.foo = "foo"

if __name__ == '__main__':
    fooo = Foo()
    print fooo.foo
    print Foo.FOO
    barr = Bar()
    print barr.bar

Hitting <leader>d with the cursor on Foo() yields:

Type Name:   type
Base Class:  <type 'type'>
String Form: <class '__main__.Foo'>
Namespace:   Interactive
Docstring:   <no docstring>

Note that the doc string is missing.

But usually (and particularly when invoked on an instance) <leader>d returns 'fooo' not found.

Invoking completion on fooo using <C-x><C-u> states -- User defined completion (^U^N^P) Back at original.

Same problem for completing Foo.FOO. Completing user-defined types imported from other modules doesn't work either.

In an ipython session I can get completion for instances. completefunc is set to completefunc=CompleteIPython. Sending code to the ipython kernel via <C-s> works.

Is this a known issue/conceptual problem/expected behaviour?

Anyone any idea what to check next?
Let me know if you need any more info.

Thanks in advance
dtk

no reply from IPython kernel

I'm not able to connect from vim to ipython.
That's what I did

start ipython 0.13

ipython kernel
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-10481.json

in vim

:IPython --existing kernel-10481.json

vim output

{u'hb_port': 48088, 
u'iopub_port': 64849,
u'ip': u'127.0.0.1',
u'key': u'4e310002-65b0-4d2d-b3e5-6e6ecda218d9',
u'shell_port': 60717,
u'stdin_port': 57169}
no reply from IPython kernel
Press ENTER or type command to continue

ipython output:

[IPKernelApp] Invalid Message
Traceback (most recent call last):
File "/home/mane/virt_env/scikit-learn/local/lib/python2.7/site-packages/IPython/zmq/ipkernel.py", line 201, in dispatch_shell
msg = self.session.unserialize(msg, content=True, copy=False)
File "/home/mane/virt_env/scikit-learn/local/lib/python2.7/site-packages/IPython/zmq/session.py", line 725, in unserialize
raise ValueError("Invalid Signature: %r"%signature)
ValueError: Invalid Signature: 'f54efdfa8edf4383defb654e8fada95a'

Arrow keys don't work in quickpreview doc window

In vim the arrow keys close the documentation window, enter insert mode and type a letter (A, B, C or D). This is due to line 144 in get_doc_buffer mapping the escape character to quit, conflicting with the control characters used for arrow keys in the terminal.

This is fixed by removing line 144, but that also causes the escape key to no longer close the doc window.

dedent_run_these_lines() should handle indentation less than shiftwidth (e.g., restructured text)

This is for the wishlist. It would be nice to be able to run code directly from restructured text documents where the initial indentation is 2 or 3. For example

This is some sphinx documentation with examples:

.. ipython:: python
   import os
   import matplotlib.pyplot as plt
   import numpy as np
   import scipy.stats

dedent_run_these_lines() will not work on this -- because the indentation is
only three spaces. This is a quick hack I have to get it to work, if count == 0, then set count = 1 so it tries to indent. I'm sure there's a better way..

def dedent_run_these_lines():
    r = vim.current.range
    shiftwidth = vim.eval('&shiftwidth')
    count = int(vim.eval('indent(%d+1)/%s' % (r.start,shiftwidth)))
    if count == 0:
       count = 1
    if count > 0:
       vim.command("'<,'>" + "<"*count)
    run_these_lines()
    if count > 0:
       vim.command("silent undo")

Thanks!

Resize (and stay resized) IPython buffer window in GVIM?

Currently, if you have one open edit buffer and the open IPython buffer (via ipy.vim), you cannot re-size the IPython buffer. In other words, if you try re-sizing the IPython buffer, it will be reset to the original size at the next command.

How can I change this so that the re-sized IPython buffer stays re-sized upon subsequent commands?

Thanks!

Jose

This fixes problem with spaces in filenames on Windows

Starting at line 250:

@with_subchannel
def run_this_file():
import win32api
tmp= win32api.GetShortPathName(vim.current.buffer.name)[:-2]+'py'
tmp= re.sub(r'',r'/',tmp)
msg_id = send('run %s %s' % (run_flags, tmp,))
print_prompt("In[]: run %s %s" % (run_flags, tmp),msg_id)

Windows Issues

Hi,

I've been trying to get GVIM and IPython to play together, without success so far on Windows 7.

Here are the steps I've taken:

  1. I launch IPython qtconsole successfully. I'm using version 0.12, what came with the EPD Python 2.7.2.
  2. :echo has('python') returns 1 for me.
  3. I source ipy.vim successfully in vim.

Things go bad for me when I attempt to run ":IPython" in vim.

I get a "Runtime Error!" alert about "R6034, An application has made an attempt to load the C runtime library incorrectly."

VIM reports the following:

Traceback (most recent call last):
File "", line 1, in
File "", line 39, in km_from_string
File "C:\Python27\lib\site-packages\IPython\zmq__init__.py", line 39, in
check_for_zmq('2.1.4')
File "C:\Python27\lib\site-packages\IPython\zmq__init__.py", line 17, in check_for_zmq
import zmq
File "C:\Python27\lib\site-packages\zmq__init__.py", line 32, in
ctypes.cdll.LoadLibrary(libzmq)
File "C:\Python27\Lib\ctypes__init__.py", line 431, in LoadLibrary
return self.dlltype(name)
File "C:\Python27\Lib\ctypes__init
_.py", line 353, in init
self._handle = _dlopen(self._name, mode)

Any idea what my issue is? From IPython i can import ctypes and zmq. I'm pretty new to Python and IPython, which is probably the biggest problem!

Thanks for any help!
-Patrick

object_info takes exactly 2 arguments (3 given)

When mousing over a variable, gvim can't get information from the object. Function IPythonBalloonExpr calls get_doc(word) which calls object_info(word, level = 0), but Python says: object_info takes exactly 2 arguments (3 given), although it is called with 2 arguments. When I remove 'level' from the argument list, it works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.