3

In IPython, it is fairly easy to provide tab-completion for user-defined object: simply define a __dir__ method that returns a list of strings to the object.

IPython also provide us with a way to define our own custom magic functions using the handy register_line_magic utility. In some ~/.ipython/profile_default/startup/magictest.py:

from IPython.core.magic import register_line_magic

@register_line_magic
def show(dataType):
    # do something depending on the given `dataType` value

Now my question is: how to provide auto-completion to this magic function?

According to this email, one should look into IPython.core.interactiveshell.InteractiveShell.init_completer() for an example of magic function completers such as %reset, '%cd', etc...

However, in the same startup file as the one in which my magic function is defined, the following code didn't work:

from IPython.core.interactiveshell import InteractiveShell

def show_complete():
     return ['dbs', 'databases', 'collections']

InteractiveShell._instance.set_hook(
    'complete_command', show_complete, str_key='%show')

In the IPython shell, typing %show TAB triggers nothing (print statements in the function show that the function is not even called).

Could somebody point me out on some documentation or examples on how to define such user-magic command parameters completion from within the Ipython startup files?

Thanks!

Romain G
  • 1,276
  • 1
  • 15
  • 27

1 Answers1

4

You can use this:

def load_ipython_extension(ipython):
    def apt_completers(self, event):
        """ This should return a list of strings with possible completions.

        Note that all the included strings that don't start with event.symbol
        are removed, in order to not confuse readline.
        """

        return ['update', 'upgrade', 'install', 'remove']

    ipython.set_hook('complete_command', apt_completers, re_key = '%%apt')

%%apt is the magic keyword

dwjbosman
  • 906
  • 9
  • 33
  • Typing `%%apt foo` then hitting tab would yield an event like so: `namespace(command='%%apt', line='%%apt foo', symbol='foo', text_until_cursor='%%apt foo')`. – Evidlo May 17 '19 at 14:19
  • 1
    Tx! This works for me however I always get these completions too: ```and is if not in or ``` - default options? Is there a way to suppress them? – magicrebirth Sep 05 '19 at 11:44