##// END OF EJS Templates
Initial changes to make alias system use magics
Thomas Kluyver -
Show More
@@ -104,6 +104,35 b' class AliasError(Exception):'
104 class InvalidAliasError(AliasError):
104 class InvalidAliasError(AliasError):
105 pass
105 pass
106
106
107 class AliasCaller(object):
108 def __init__(self, shell, cmd):
109 self.shell = shell
110 self.cmd = cmd
111 self.nargs = cmd.count('%s')
112 if (self.nargs > 0) and (cmd.find('%l') >= 0):
113 raise InvalidAliasError('The %s and %l specifiers are mutually '
114 'exclusive in alias definitions.')
115
116 def __call__(self, rest=''):
117 cmd = self.cmd
118 nargs = self.nargs
119 # Expand the %l special to be the user's input line
120 if cmd.find('%l') >= 0:
121 cmd = cmd.replace('%l', rest)
122 rest = ''
123 if nargs==0:
124 # Simple, argument-less aliases
125 cmd = '%s %s' % (cmd, rest)
126 else:
127 # Handle aliases with positional arguments
128 args = rest.split(None, nargs)
129 if len(args) < nargs:
130 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
131 (alias, nargs, len(args)))
132 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
133
134 self.shell.system(cmd)
135
107 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
108 # Main AliasManager class
137 # Main AliasManager class
109 #-----------------------------------------------------------------------------
138 #-----------------------------------------------------------------------------
@@ -117,7 +146,7 b' class AliasManager(Configurable):'
117 def __init__(self, shell=None, **kwargs):
146 def __init__(self, shell=None, **kwargs):
118 super(AliasManager, self).__init__(shell=shell, **kwargs)
147 super(AliasManager, self).__init__(shell=shell, **kwargs)
119 self.alias_table = {}
148 self.alias_table = {}
120 self.exclude_aliases()
149 self.init_exclusions()
121 self.init_aliases()
150 self.init_aliases()
122
151
123 def __contains__(self, name):
152 def __contains__(self, name):
@@ -127,9 +156,9 b' class AliasManager(Configurable):'
127 def aliases(self):
156 def aliases(self):
128 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
157 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
129
158
130 def exclude_aliases(self):
159 def init_exclusions(self):
131 # set of things NOT to alias (keywords, builtins and some magics)
160 # set of things NOT to alias (keywords, builtins and some magics)
132 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
161 no_alias = {'cd','popd','pushd','dhist','alias','unalias'}
133 no_alias.update(set(keyword.kwlist))
162 no_alias.update(set(keyword.kwlist))
134 no_alias.update(set(__builtin__.__dict__.keys()))
163 no_alias.update(set(__builtin__.__dict__.keys()))
135 self.no_alias = no_alias
164 self.no_alias = no_alias
@@ -159,12 +188,18 b' class AliasManager(Configurable):'
159 This will raise an :exc:`AliasError` if there are validation
188 This will raise an :exc:`AliasError` if there are validation
160 problems.
189 problems.
161 """
190 """
162 nargs = self.validate_alias(name, cmd)
191 self.validate_alias(name, cmd)
163 self.alias_table[name] = (nargs, cmd)
192 caller = AliasCaller(shell=self.shell, cmd=cmd)
193 self.shell.magics_manager.register_function(caller, magic_kind='line',
194 magic_name=name)
164
195
165 def undefine_alias(self, name):
196 def undefine_alias(self, name):
166 if name in self.alias_table:
197 linemagics = self.shell.magics_manager.magics['line']
167 del self.alias_table[name]
198 caller = linemagics.get(name, None)
199 if isinstance(caller, AliasCaller):
200 del linemagics[name]
201 else:
202 raise ValueError('%s is not an alias' % name)
168
203
169 def validate_alias(self, name, cmd):
204 def validate_alias(self, name, cmd):
170 """Validate an alias and return the its number of arguments."""
205 """Validate an alias and return the its number of arguments."""
@@ -174,11 +209,7 b' class AliasManager(Configurable):'
174 if not (isinstance(cmd, basestring)):
209 if not (isinstance(cmd, basestring)):
175 raise InvalidAliasError("An alias command must be a string, "
210 raise InvalidAliasError("An alias command must be a string, "
176 "got: %r" % cmd)
211 "got: %r" % cmd)
177 nargs = cmd.count('%s')
212 return True
178 if nargs>0 and cmd.find('%l')>=0:
179 raise InvalidAliasError('The %s and %l specifiers are mutually '
180 'exclusive in alias definitions.')
181 return nargs
182
213
183 def call_alias(self, alias, rest=''):
214 def call_alias(self, alias, rest=''):
184 """Call an alias given its name and the rest of the line."""
215 """Call an alias given its name and the rest of the line."""
@@ -470,7 +470,6 b' class InteractiveShell(SingletonConfigurable):'
470 # because it and init_io have to come after init_readline.
470 # because it and init_io have to come after init_readline.
471 self.init_user_ns()
471 self.init_user_ns()
472 self.init_logger()
472 self.init_logger()
473 self.init_alias()
474 self.init_builtins()
473 self.init_builtins()
475
474
476 # The following was in post_config_initialization
475 # The following was in post_config_initialization
@@ -502,6 +501,7 b' class InteractiveShell(SingletonConfigurable):'
502 self.init_displayhook()
501 self.init_displayhook()
503 self.init_latextool()
502 self.init_latextool()
504 self.init_magics()
503 self.init_magics()
504 self.init_alias()
505 self.init_logstart()
505 self.init_logstart()
506 self.init_pdb()
506 self.init_pdb()
507 self.init_extension_manager()
507 self.init_extension_manager()
@@ -1940,7 +1940,7 b' class InteractiveShell(SingletonConfigurable):'
1940 self.Completer = IPCompleter(shell=self,
1940 self.Completer = IPCompleter(shell=self,
1941 namespace=self.user_ns,
1941 namespace=self.user_ns,
1942 global_namespace=self.user_global_ns,
1942 global_namespace=self.user_global_ns,
1943 alias_table=self.alias_manager.alias_table,
1943 #alias_table=self.alias_manager.alias_table,
1944 use_readline=self.has_readline,
1944 use_readline=self.has_readline,
1945 parent=self,
1945 parent=self,
1946 )
1946 )
@@ -26,6 +26,7 b' from pprint import pformat'
26 from IPython.core import magic_arguments
26 from IPython.core import magic_arguments
27 from IPython.core import oinspect
27 from IPython.core import oinspect
28 from IPython.core import page
28 from IPython.core import page
29 from IPython.core.alias import AliasError
29 from IPython.core.error import UsageError
30 from IPython.core.error import UsageError
30 from IPython.core.magic import (
31 from IPython.core.magic import (
31 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
32 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
@@ -113,10 +114,14 b' class OSMagics(Magics):'
113 # Now try to define a new one
114 # Now try to define a new one
114 try:
115 try:
115 alias,cmd = par.split(None, 1)
116 alias,cmd = par.split(None, 1)
116 except:
117 except TypeError:
117 print oinspect.getdoc(self.alias)
118 print(oinspect.getdoc(self.alias))
118 else:
119 return
119 self.shell.alias_manager.soft_define_alias(alias, cmd)
120
121 try:
122 self.shell.alias_manager.define_alias(alias, cmd)
123 except AliasError as e:
124 print(e)
120 # end magic_alias
125 # end magic_alias
121
126
122 @line_magic
127 @line_magic
@@ -124,7 +129,12 b' class OSMagics(Magics):'
124 """Remove an alias"""
129 """Remove an alias"""
125
130
126 aname = parameter_s.strip()
131 aname = parameter_s.strip()
127 self.shell.alias_manager.undefine_alias(aname)
132 try:
133 self.shell.alias_manager.undefine_alias(aname)
134 except ValueError as e:
135 print(e)
136 return
137
128 stored = self.shell.db.get('stored_aliases', {} )
138 stored = self.shell.db.get('stored_aliases', {} )
129 if aname in stored:
139 if aname in stored:
130 print "Removing %stored alias",aname
140 print "Removing %stored alias",aname
General Comments 0
You need to be logged in to leave comments. Login now