From cb545eeeca3255c70d2a0a16490bc36abfab2bee Mon Sep 17 00:00:00 2001 From: Takafumi Arakaki Date: Fri, 24 Aug 2018 01:02:49 -0700 Subject: [PATCH] Add IPython completion hook --- julia/magic.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/julia/magic.py b/julia/magic.py index 96b3d7ae..cbb3e91b 100644 --- a/julia/magic.py +++ b/julia/magic.py @@ -66,6 +66,37 @@ def julia(self, line, cell=None): return ans +def julia_completer(self, event): + pos = event.line.find("%julia") + if pos < 0: + return [] + pos += len("%julia") # pos: beginning of Julia code + julia_code = event.line[pos:] + julia_pos = len(event.text_until_cursor) - pos + + julia = Julia() + completions = julia.eval(""" + import REPL + (string, pos) -> begin + ret, _, should_complete = + REPL.completions(string, pos) + if should_complete + return map(REPL.completion_text, ret) + else + return String[] + end + end + """)(julia_code, julia_pos) + + if "." in event.symbol: + # When completing (say) "Base.s" we need to add the prefix "Base." + prefix = event.symbol.rsplit(".", 1)[0] + completions = [".".join((prefix, c)) for c in completions] + return completions +# See: +# IPython.core.completer.dispatch_custom_completer + + # Add to the global docstring the class information. __doc__ = __doc__.format( JULIAMAGICS_DOC=' ' * 8 + JuliaMagics.__doc__, @@ -80,3 +111,9 @@ def julia(self, line, cell=None): def load_ipython_extension(ip): """Load the extension in IPython.""" ip.register_magics(JuliaMagics) + ip.set_hook("complete_command", julia_completer, + re_key="%?%julia") +# See: +# https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.hooks.html +# IPython.core.interactiveshell.init_completer +# IPython.core.completerlib (quick_completer etc.)