7

Let's say I want to create the alias %xed for %edit -x. How would I do it?

Redwood
  • 66,744
  • 41
  • 126
  • 187

2 Answers2

3

The answer given above uses the old magic system. get_ipython().expose_magic is dead. You now just import and use decorators for all this.

See here for more details.

Carl Smith
  • 3,025
  • 24
  • 36
2

Update: The first response( below) does not accept parameters. So put this snippet at the end of the ipy_user_conf.py file ( it is in your home directory ).

def ed_xed(self,arg):
    ip = self.api
    return ip.magic.im_class.magic_edit(ip.IP," -x %s "%arg)

ip.expose_magic('xed',ed_xed)

Before update: Does it has to be %magic? You can use the macro and store magic to reproduce this behavior without the magic %.

In [5]: %edit -x
In [6]: macro xed 5
In [7]: store xed
In [8]: xed

for magic alias from the documentation ( %magic? ):

You can also define your own aliased names for magic functions. In your ipythonrc file, placing a line like:

execute IPYTHON.magic_pf = IPYTHON.magic_profile

will define %pf as a new name for %profile.

But I don't know how too add the parameter.

Igal Serban
  • 10,558
  • 3
  • 35
  • 40
  • This is close, but it then prevents you from typing xed file.py to open a new or existing file of the given name. – Redwood Nov 18 '08 at 03:13
  • Fixed, I think. Ignore the before update. You can delete the macro with: store -d xed – Igal Serban Nov 18 '08 at 08:44
  • Yup, that works. So what you're doing is describing an entirely new %magic, which in turn is calling the usual %edit with the added parameter. self is the current instance of the IPython shell, which it looks like IPython passes in as the first parameter. Is that all more or less accurate? – Redwood Nov 19 '08 at 22:34
  • Yes. But its a lot of guess work, as I don't have real knowledge of the IPython internals. This solution may be broken in subtle ways that I am not aware of currently. But, if we don't break our development tools, what can we break? – Igal Serban Nov 20 '08 at 07:36
  • This is great.. I just modified it to ip.expose_magic('vi',ed_xed) as my fingers could never get uset to typing ed – michael Jun 02 '09 at 06:06
  • This code has 'expired" in relation to [ipython API](https://ipython.readthedocs.io/en/stable/config/custommagics.html) :-(. – ankostis Jul 09 '20 at 08:54