Skip to content

Commit abaae04

Browse files
committed
Exit IPython with backspace
1 parent b202d53 commit abaae04

3 files changed

Lines changed: 47 additions & 4 deletions

File tree

README.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
## Usage
1212

1313
Run `using IPython` and then type `.` in empty `julia>` prompt or run
14-
`IPython.start_ipython()`. Exiting IPython as usual (e.g., `Ctrl-D`)
15-
brings you back to the Julia REPL. Re-entering IPython keeps the
16-
previous state. Use pre-defined `Main` object to access Julia
17-
namespace from IPython.
14+
`IPython.start_ipython()`. If you are using IPython 7.0 or above, you
15+
can switch back to Julia REPl by `backspace` or `ctrl-h` key (like
16+
other REPL modes). For older versions of IPython, exiting IPython as
17+
usual (e.g., `ctrl-d`) brings you back to the Julia REPL. Re-entering
18+
IPython keeps the previous state. Use pre-defined `Main` object to
19+
access Julia namespace from IPython.
1820

1921
**Note:**
2022
First launch of IPython may be slow.

src/replhelper/ipyext.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
from .core import get_cached_api
22

3+
try:
4+
from .key_bindings import register_key_bindings
5+
except ImportError:
6+
def register_key_bindings(_):
7+
return lambda: None
8+
9+
10+
def _unregister_key_bindings():
11+
""" No-op placeholder function to be replaced. """
12+
313

414
def julia_completer(julia, self, event):
515
pos = event.line.find("Main.eval")
@@ -26,9 +36,16 @@ def _julia_completer(self, event):
2636

2737

2838
def load_ipython_extension(ip):
39+
global _unregister_key_bindings
40+
_unregister_key_bindings = register_key_bindings(ip)
41+
2942
ip.set_hook("complete_command", _julia_completer,
3043
re_key=r""".*\bMain\.eval\(["']""")
3144
# See:
3245
# https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.hooks.html
3346
# IPython.core.interactiveshell.init_completer
3447
# IPython.core.completerlib (quick_completer etc.)
48+
49+
50+
def unload_ipython_extension(ip):
51+
_unregister_key_bindings()

src/replhelper/key_bindings.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from prompt_toolkit.application.current import get_app
2+
from prompt_toolkit.filters import Condition
3+
4+
5+
@Condition
6+
def is_buffer_empty():
7+
return get_app().current_buffer.text.strip() == ""
8+
9+
10+
def register_key_bindings(ip):
11+
try:
12+
add = ip.pt_app.key_bindings.add
13+
except AttributeError:
14+
return lambda: None
15+
16+
@add("c-h", filter=is_buffer_empty, eager=True)
17+
def exit_with_backspace(event):
18+
ip.ask_exit()
19+
event.app.exit()
20+
21+
def unregister():
22+
ip.pt_app.key_bindings.remove(exit_with_backspace)
23+
24+
return unregister

0 commit comments

Comments
 (0)