Format: text/x-python
⬇ Download File (28.2 KB)
   1  # encoding: utf-8
   2  """Magic functions for InteractiveShell.
   3  """
   4  
   5  #-----------------------------------------------------------------------------
   6  #  Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
   7  #  Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
   8  #  Copyright (C) 2008 The IPython Development Team
   9  
  10  #  Distributed under the terms of the BSD License.  The full license is in
  11  #  the file COPYING, distributed as part of this software.
  12  #-----------------------------------------------------------------------------
  13  
  14  import os
  15  import re
  16  import sys
  17  from getopt import getopt, GetoptError
  18  
  19  from traitlets.config.configurable import Configurable
  20  from . import oinspect
  21  from .error import UsageError
  22  from .inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
  23  from ..utils.ipstruct import Struct
  24  from ..utils.process import arg_split
  25  from ..utils.text import dedent
  26  from traitlets import Bool, Dict, Instance, observe
  27  from logging import error
  28  
  29  import typing as t
  30  
  31  #-----------------------------------------------------------------------------
  32  # Globals
  33  #-----------------------------------------------------------------------------
  34  
  35  # A dict we'll use for each class that has magics, used as temporary storage to
  36  # pass information between the @line/cell_magic method decorators and the
  37  # @magics_class class decorator, because the method decorators have no
  38  # access to the class when they run.  See for more details:
  39  # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
  40  
  41  magics: t.Dict = dict(line={}, cell={})
  42  
  43  magic_kinds = ('line', 'cell')
  44  magic_spec = ('line', 'cell', 'line_cell')
  45  magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
  46  
  47  #-----------------------------------------------------------------------------
  48  # Utility classes and functions
  49  #-----------------------------------------------------------------------------
  50  
  51  class Bunch: pass
  52  
  53  
  54  def on_off(tag):
  55      """Return an ON/OFF string for a 1/0 input. Simple utility function."""
  56      return ['OFF','ON'][tag]
  57  
  58  
  59  def compress_dhist(dh):
  60      """Compress a directory history into a new one with at most 20 entries.
  61  
  62      Return a new list made from the first and last 10 elements of dhist after
  63      removal of duplicates.
  64      """
  65      head, tail = dh[:-10], dh[-10:]
  66  
  67      newhead = []
  68      done = set()
  69      for h in head:
  70          if h in done:
  71              continue
  72          newhead.append(h)
  73          done.add(h)
  74  
  75      return newhead + tail
  76  
  77  
  78  def needs_local_scope(func):
  79      """Decorator to mark magic functions which need to local scope to run."""
  80      func.needs_local_scope = True
  81      return func
  82  
  83  #-----------------------------------------------------------------------------
  84  # Class and method decorators for registering magics
  85  #-----------------------------------------------------------------------------
  86  
  87  def magics_class(cls):
  88      """Class decorator for all subclasses of the main Magics class.
  89  
  90      Any class that subclasses Magics *must* also apply this decorator, to
  91      ensure that all the methods that have been decorated as line/cell magics
  92      get correctly registered in the class instance.  This is necessary because
  93      when method decorators run, the class does not exist yet, so they
  94      temporarily store their information into a module global.  Application of
  95      this class decorator copies that global data to the class instance and
  96      clears the global.
  97  
  98      Obviously, this mechanism is not thread-safe, which means that the
  99      *creation* of subclasses of Magic should only be done in a single-thread
 100      context.  Instantiation of the classes has no restrictions.  Given that
 101      these classes are typically created at IPython startup time and before user
 102      application code becomes active, in practice this should not pose any
 103      problems.
 104      """
 105      cls.registered = True
 106      cls.magics = dict(line = magics['line'],
 107                        cell = magics['cell'])
 108      magics['line'] = {}
 109      magics['cell'] = {}
 110      return cls
 111  
 112  
 113  def record_magic(dct, magic_kind, magic_name, func):
 114      """Utility function to store a function as a magic of a specific kind.
 115  
 116      Parameters
 117      ----------
 118      dct : dict
 119          A dictionary with 'line' and 'cell' subdicts.
 120      magic_kind : str
 121          Kind of magic to be stored.
 122      magic_name : str
 123          Key to store the magic as.
 124      func : function
 125          Callable object to store.
 126      """
 127      if magic_kind == 'line_cell':
 128          dct['line'][magic_name] = dct['cell'][magic_name] = func
 129      else:
 130          dct[magic_kind][magic_name] = func
 131  
 132  
 133  def validate_type(magic_kind):
 134      """Ensure that the given magic_kind is valid.
 135  
 136      Check that the given magic_kind is one of the accepted spec types (stored
 137      in the global `magic_spec`), raise ValueError otherwise.
 138      """
 139      if magic_kind not in magic_spec:
 140          raise ValueError('magic_kind must be one of %s, %s given' %
 141                           magic_kinds, magic_kind)
 142  
 143  
 144  # The docstrings for the decorator below will be fairly similar for the two
 145  # types (method and function), so we generate them here once and reuse the
 146  # templates below.
 147  _docstring_template = \
 148  """Decorate the given {0} as {1} magic.
 149  
 150  The decorator can be used with or without arguments, as follows.
 151  
 152  i) without arguments: it will create a {1} magic named as the {0} being
 153  decorated::
 154  
 155      @deco
 156      def foo(...)
 157  
 158  will create a {1} magic named `foo`.
 159  
 160  ii) with one string argument: which will be used as the actual name of the
 161  resulting magic::
 162  
 163      @deco('bar')
 164      def foo(...)
 165  
 166  will create a {1} magic named `bar`.
 167  
 168  To register a class magic use ``Interactiveshell.register_magic(class or instance)``.
 169  """
 170  
 171  # These two are decorator factories.  While they are conceptually very similar,
 172  # there are enough differences in the details that it's simpler to have them
 173  # written as completely standalone functions rather than trying to share code
 174  # and make a single one with convoluted logic.
 175  
 176  def _method_magic_marker(magic_kind):
 177      """Decorator factory for methods in Magics subclasses.
 178      """
 179  
 180      validate_type(magic_kind)
 181  
 182      # This is a closure to capture the magic_kind.  We could also use a class,
 183      # but it's overkill for just that one bit of state.
 184      def magic_deco(arg):
 185          if callable(arg):
 186              # "Naked" decorator call (just @foo, no args)
 187              func = arg
 188              name = func.__name__
 189              retval = arg
 190              record_magic(magics, magic_kind, name, name)
 191          elif isinstance(arg, str):
 192              # Decorator called with arguments (@foo('bar'))
 193              name = arg
 194              def mark(func, *a, **kw):
 195                  record_magic(magics, magic_kind, name, func.__name__)
 196                  return func
 197              retval = mark
 198          else:
 199              raise TypeError("Decorator can only be called with "
 200                              "string or function")
 201          return retval
 202  
 203      # Ensure the resulting decorator has a usable docstring
 204      magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
 205      return magic_deco
 206  
 207  
 208  def _function_magic_marker(magic_kind):
 209      """Decorator factory for standalone functions.
 210      """
 211      validate_type(magic_kind)
 212      
 213      # This is a closure to capture the magic_kind.  We could also use a class,
 214      # but it's overkill for just that one bit of state.
 215      def magic_deco(arg):
 216          # Find get_ipython() in the caller's namespace
 217          caller = sys._getframe(1)
 218          for ns in ['f_locals', 'f_globals', 'f_builtins']:
 219              get_ipython = getattr(caller, ns).get('get_ipython')
 220              if get_ipython is not None:
 221                  break
 222          else:
 223              raise NameError('Decorator can only run in context where '
 224                              '`get_ipython` exists')
 225  
 226          ip = get_ipython()
 227  
 228          if callable(arg):
 229              # "Naked" decorator call (just @foo, no args)
 230              func = arg
 231              name = func.__name__
 232              ip.register_magic_function(func, magic_kind, name)
 233              retval = arg
 234          elif isinstance(arg, str):
 235              # Decorator called with arguments (@foo('bar'))
 236              name = arg
 237              def mark(func, *a, **kw):
 238                  ip.register_magic_function(func, magic_kind, name)
 239                  return func
 240              retval = mark
 241          else:
 242              raise TypeError("Decorator can only be called with "
 243                               "string or function")
 244          return retval
 245  
 246      # Ensure the resulting decorator has a usable docstring
 247      ds = _docstring_template.format('function', magic_kind)
 248  
 249      ds += dedent("""
 250      Note: this decorator can only be used in a context where IPython is already
 251      active, so that the `get_ipython()` call succeeds.  You can therefore use
 252      it in your startup files loaded after IPython initializes, but *not* in the
 253      IPython configuration file itself, which is executed before IPython is
 254      fully up and running.  Any file located in the `startup` subdirectory of
 255      your configuration profile will be OK in this sense.
 256      """)
 257      
 258      magic_deco.__doc__ = ds
 259      return magic_deco
 260  
 261  
 262  MAGIC_NO_VAR_EXPAND_ATTR = "_ipython_magic_no_var_expand"
 263  MAGIC_OUTPUT_CAN_BE_SILENCED = "_ipython_magic_output_can_be_silenced"
 264  
 265  
 266  def no_var_expand(magic_func):
 267      """Mark a magic function as not needing variable expansion
 268  
 269      By default, IPython interprets `{a}` or `$a` in the line passed to magics
 270      as variables that should be interpolated from the interactive namespace
 271      before passing the line to the magic function.
 272      This is not always desirable, e.g. when the magic executes Python code
 273      (%timeit, %time, etc.).
 274      Decorate magics with `@no_var_expand` to opt-out of variable expansion.
 275  
 276      .. versionadded:: 7.3
 277      """
 278      setattr(magic_func, MAGIC_NO_VAR_EXPAND_ATTR, True)
 279      return magic_func
 280  
 281  
 282  def output_can_be_silenced(magic_func):
 283      """Mark a magic function so its output may be silenced.
 284  
 285      The output is silenced if the Python code used as a parameter of
 286      the magic ends in a semicolon, not counting a Python comment that can
 287      follow it.
 288      """
 289      setattr(magic_func, MAGIC_OUTPUT_CAN_BE_SILENCED, True)
 290      return magic_func
 291  
 292  # Create the actual decorators for public use
 293  
 294  # These three are used to decorate methods in class definitions
 295  line_magic = _method_magic_marker('line')
 296  cell_magic = _method_magic_marker('cell')
 297  line_cell_magic = _method_magic_marker('line_cell')
 298  
 299  # These three decorate standalone functions and perform the decoration
 300  # immediately.  They can only run where get_ipython() works
 301  register_line_magic = _function_magic_marker('line')
 302  register_cell_magic = _function_magic_marker('cell')
 303  register_line_cell_magic = _function_magic_marker('line_cell')
 304  
 305  #-----------------------------------------------------------------------------
 306  # Core Magic classes
 307  #-----------------------------------------------------------------------------
 308  
 309  class MagicsManager(Configurable):
 310      """Object that handles all magic-related functionality for IPython.
 311      """
 312      # Non-configurable class attributes
 313  
 314      # A two-level dict, first keyed by magic type, then by magic function, and
 315      # holding the actual callable object as value.  This is the dict used for
 316      # magic function dispatch
 317      magics = Dict()
 318      lazy_magics = Dict(
 319          help="""
 320      Mapping from magic names to modules to load.
 321  
 322      This can be used in IPython/IPykernel configuration to declare lazy magics
 323      that will only be imported/registered on first use.
 324  
 325      For example::
 326  
 327          c.MagicsManager.lazy_magics = {
 328            "my_magic": "slow.to.import",
 329            "my_other_magic": "also.slow",
 330          }
 331  
 332      On first invocation of `%my_magic`, `%%my_magic`, `%%my_other_magic` or
 333      `%%my_other_magic`, the corresponding module will be loaded as an ipython
 334      extensions as if you had previously done `%load_ext ipython`.
 335  
 336      Magics names should be without percent(s) as magics can be both cell
 337      and line magics.
 338  
 339      Lazy loading happen relatively late in execution process, and
 340      complex extensions that manipulate Python/IPython internal state or global state
 341      might not support lazy loading.
 342      """
 343      ).tag(
 344          config=True,
 345      )
 346  
 347      # A registry of the original objects that we've been given holding magics.
 348      registry = Dict()
 349  
 350      shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
 351  
 352      auto_magic = Bool(True, help=
 353          "Automatically call line magics without requiring explicit % prefix"
 354      ).tag(config=True)
 355      @observe('auto_magic')
 356      def _auto_magic_changed(self, change):
 357          self.shell.automagic = change['new']
 358      
 359      _auto_status = [
 360          'Automagic is OFF, % prefix IS needed for line magics.',
 361          'Automagic is ON, % prefix IS NOT needed for line magics.']
 362  
 363      user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
 364  
 365      def __init__(self, shell=None, config=None, user_magics=None, **traits):
 366  
 367          super(MagicsManager, self).__init__(shell=shell, config=config,
 368                                             user_magics=user_magics, **traits)
 369          self.magics = dict(line={}, cell={})
 370          # Let's add the user_magics to the registry for uniformity, so *all*
 371          # registered magic containers can be found there.
 372          self.registry[user_magics.__class__.__name__] = user_magics
 373  
 374      def auto_status(self):
 375          """Return descriptive string with automagic status."""
 376          return self._auto_status[self.auto_magic]
 377      
 378      def lsmagic(self):
 379          """Return a dict of currently available magic functions.
 380  
 381          The return dict has the keys 'line' and 'cell', corresponding to the
 382          two types of magics we support.  Each value is a list of names.
 383          """
 384          return self.magics
 385  
 386      def lsmagic_docs(self, brief=False, missing=''):
 387          """Return dict of documentation of magic functions.
 388  
 389          The return dict has the keys 'line' and 'cell', corresponding to the
 390          two types of magics we support. Each value is a dict keyed by magic
 391          name whose value is the function docstring. If a docstring is
 392          unavailable, the value of `missing` is used instead.
 393  
 394          If brief is True, only the first line of each docstring will be returned.
 395          """
 396          docs = {}
 397          for m_type in self.magics:
 398              m_docs = {}
 399              for m_name, m_func in self.magics[m_type].items():
 400                  if m_func.__doc__:
 401                      if brief:
 402                          m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
 403                      else:
 404                          m_docs[m_name] = m_func.__doc__.rstrip()
 405                  else:
 406                      m_docs[m_name] = missing
 407              docs[m_type] = m_docs
 408          return docs
 409  
 410      def register_lazy(self, name: str, fully_qualified_name: str):
 411          """
 412          Lazily register a magic via an extension.
 413  
 414  
 415          Parameters
 416          ----------
 417          name : str
 418              Name of the magic you wish to register.
 419          fully_qualified_name :
 420              Fully qualified name of the module/submodule that should be loaded
 421              as an extensions when the magic is first called.
 422              It is assumed that loading this extensions will register the given
 423              magic.
 424          """
 425  
 426          self.lazy_magics[name] = fully_qualified_name
 427  
 428      def register(self, *magic_objects):
 429          """Register one or more instances of Magics.
 430  
 431          Take one or more classes or instances of classes that subclass the main
 432          `core.Magic` class, and register them with IPython to use the magic
 433          functions they provide.  The registration process will then ensure that
 434          any methods that have decorated to provide line and/or cell magics will
 435          be recognized with the `%x`/`%%x` syntax as a line/cell magic
 436          respectively.
 437  
 438          If classes are given, they will be instantiated with the default
 439          constructor.  If your classes need a custom constructor, you should
 440          instanitate them first and pass the instance.
 441  
 442          The provided arguments can be an arbitrary mix of classes and instances.
 443  
 444          Parameters
 445          ----------
 446          *magic_objects : one or more classes or instances
 447          """
 448          # Start by validating them to ensure they have all had their magic
 449          # methods registered at the instance level
 450          for m in magic_objects:
 451              if not m.registered:
 452                  raise ValueError("Class of magics %r was constructed without "
 453                                   "the @register_magics class decorator")
 454              if isinstance(m, type):
 455                  # If we're given an uninstantiated class
 456                  m = m(shell=self.shell)
 457  
 458              # Now that we have an instance, we can register it and update the
 459              # table of callables
 460              self.registry[m.__class__.__name__] = m
 461              for mtype in magic_kinds:
 462                  self.magics[mtype].update(m.magics[mtype])
 463  
 464      def register_function(self, func, magic_kind='line', magic_name=None):
 465          """Expose a standalone function as magic function for IPython.
 466  
 467          This will create an IPython magic (line, cell or both) from a
 468          standalone function.  The functions should have the following
 469          signatures:
 470  
 471          * For line magics: `def f(line)`
 472          * For cell magics: `def f(line, cell)`
 473          * For a function that does both: `def f(line, cell=None)`
 474  
 475          In the latter case, the function will be called with `cell==None` when
 476          invoked as `%f`, and with cell as a string when invoked as `%%f`.
 477  
 478          Parameters
 479          ----------
 480          func : callable
 481              Function to be registered as a magic.
 482          magic_kind : str
 483              Kind of magic, one of 'line', 'cell' or 'line_cell'
 484          magic_name : optional str
 485              If given, the name the magic will have in the IPython namespace.  By
 486              default, the name of the function itself is used.
 487          """
 488  
 489          # Create the new method in the user_magics and register it in the
 490          # global table
 491          validate_type(magic_kind)
 492          magic_name = func.__name__ if magic_name is None else magic_name
 493          setattr(self.user_magics, magic_name, func)
 494          record_magic(self.magics, magic_kind, magic_name, func)
 495  
 496      def register_alias(self, alias_name, magic_name, magic_kind='line', magic_params=None):
 497          """Register an alias to a magic function.
 498  
 499          The alias is an instance of :class:`MagicAlias`, which holds the
 500          name and kind of the magic it should call. Binding is done at
 501          call time, so if the underlying magic function is changed the alias
 502          will call the new function.
 503  
 504          Parameters
 505          ----------
 506          alias_name : str
 507              The name of the magic to be registered.
 508          magic_name : str
 509              The name of an existing magic.
 510          magic_kind : str
 511              Kind of magic, one of 'line' or 'cell'
 512          """
 513  
 514          # `validate_type` is too permissive, as it allows 'line_cell'
 515          # which we do not handle.
 516          if magic_kind not in magic_kinds:
 517              raise ValueError('magic_kind must be one of %s, %s given' %
 518                               magic_kinds, magic_kind)
 519  
 520          alias = MagicAlias(self.shell, magic_name, magic_kind, magic_params)
 521          setattr(self.user_magics, alias_name, alias)
 522          record_magic(self.magics, magic_kind, alias_name, alias)
 523  
 524  # Key base class that provides the central functionality for magics.
 525  
 526  
 527  class Magics(Configurable):
 528      """Base class for implementing magic functions.
 529  
 530      Shell functions which can be reached as %function_name. All magic
 531      functions should accept a string, which they can parse for their own
 532      needs. This can make some functions easier to type, eg `%cd ../`
 533      vs. `%cd("../")`
 534  
 535      Classes providing magic functions need to subclass this class, and they
 536      MUST:
 537  
 538      - Use the method decorators `@line_magic` and `@cell_magic` to decorate
 539        individual methods as magic functions, AND
 540  
 541      - Use the class decorator `@magics_class` to ensure that the magic
 542        methods are properly registered at the instance level upon instance
 543        initialization.
 544  
 545      See :mod:`magic_functions` for examples of actual implementation classes.
 546      """
 547      # Dict holding all command-line options for each magic.
 548      options_table = None
 549      # Dict for the mapping of magic names to methods, set by class decorator
 550      magics = None
 551      # Flag to check that the class decorator was properly applied
 552      registered = False
 553      # Instance of IPython shell
 554      shell = None
 555  
 556      def __init__(self, shell=None, **kwargs):
 557          if not(self.__class__.registered):
 558              raise ValueError('Magics subclass without registration - '
 559                               'did you forget to apply @magics_class?')
 560          if shell is not None:
 561              if hasattr(shell, 'configurables'):
 562                  shell.configurables.append(self)
 563              if hasattr(shell, 'config'):
 564                  kwargs.setdefault('parent', shell)
 565  
 566          self.shell = shell
 567          self.options_table = {}
 568          # The method decorators are run when the instance doesn't exist yet, so
 569          # they can only record the names of the methods they are supposed to
 570          # grab.  Only now, that the instance exists, can we create the proper
 571          # mapping to bound methods.  So we read the info off the original names
 572          # table and replace each method name by the actual bound method.
 573          # But we mustn't clobber the *class* mapping, in case of multiple instances.
 574          class_magics = self.magics
 575          self.magics = {}
 576          for mtype in magic_kinds:
 577              tab = self.magics[mtype] = {}
 578              cls_tab = class_magics[mtype]
 579              for magic_name, meth_name in cls_tab.items():
 580                  if isinstance(meth_name, str):
 581                      # it's a method name, grab it
 582                      tab[magic_name] = getattr(self, meth_name)
 583                  else:
 584                      # it's the real thing
 585                      tab[magic_name] = meth_name
 586          # Configurable **needs** to be initiated at the end or the config
 587          # magics get screwed up.
 588          super(Magics, self).__init__(**kwargs)
 589  
 590      def arg_err(self,func):
 591          """Print docstring if incorrect arguments were passed"""
 592          print('Error in arguments:')
 593          print(oinspect.getdoc(func))
 594  
 595      def format_latex(self, strng):
 596          """Format a string for latex inclusion."""
 597  
 598          # Characters that need to be escaped for latex:
 599          escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
 600          # Magic command names as headers:
 601          cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
 602                                   re.MULTILINE)
 603          # Magic commands
 604          cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
 605                              re.MULTILINE)
 606          # Paragraph continue
 607          par_re = re.compile(r'\\$',re.MULTILINE)
 608  
 609          # The "\n" symbol
 610          newline_re = re.compile(r'\\n')
 611  
 612          # Now build the string for output:
 613          #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
 614          strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
 615                                  strng)
 616          strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
 617          strng = par_re.sub(r'\\\\',strng)
 618          strng = escape_re.sub(r'\\\1',strng)
 619          strng = newline_re.sub(r'\\textbackslash{}n',strng)
 620          return strng
 621  
 622      def parse_options(self, arg_str, opt_str, *long_opts, **kw):
 623          """Parse options passed to an argument string.
 624  
 625          The interface is similar to that of :func:`getopt.getopt`, but it
 626          returns a :class:`~IPython.utils.struct.Struct` with the options as keys
 627          and the stripped argument string still as a string.
 628  
 629          arg_str is quoted as a true sys.argv vector by using shlex.split.
 630          This allows us to easily expand variables, glob files, quote
 631          arguments, etc.
 632  
 633          Parameters
 634          ----------
 635          arg_str : str
 636              The arguments to parse.
 637          opt_str : str
 638              The options specification.
 639          mode : str, default 'string'
 640              If given as 'list', the argument string is returned as a list (split
 641              on whitespace) instead of a string.
 642          list_all : bool, default False
 643              Put all option values in lists. Normally only options
 644              appearing more than once are put in a list.
 645          posix : bool, default True
 646              Whether to split the input line in POSIX mode or not, as per the
 647              conventions outlined in the :mod:`shlex` module from the standard
 648              library.
 649          """
 650  
 651          # inject default options at the beginning of the input line
 652          caller = sys._getframe(1).f_code.co_name
 653          arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
 654  
 655          mode = kw.get('mode','string')
 656          if mode not in ['string','list']:
 657              raise ValueError('incorrect mode given: %s' % mode)
 658          # Get options
 659          list_all = kw.get('list_all',0)
 660          posix = kw.get('posix', os.name == 'posix')
 661          strict = kw.get('strict', True)
 662  
 663          preserve_non_opts = kw.get("preserve_non_opts", False)
 664          remainder_arg_str = arg_str
 665  
 666          # Check if we have more than one argument to warrant extra processing:
 667          odict = {}  # Dictionary with options
 668          args = arg_str.split()
 669          if len(args) >= 1:
 670              # If the list of inputs only has 0 or 1 thing in it, there's no
 671              # need to look for options
 672              argv = arg_split(arg_str, posix, strict)
 673              # Do regular option processing
 674              try:
 675                  opts,args = getopt(argv, opt_str, long_opts)
 676              except GetoptError as e:
 677                  raise UsageError(
 678                      '%s ( allowed: "%s" %s)' % (e.msg, opt_str, " ".join(long_opts))
 679                  ) from e
 680              for o, a in opts:
 681                  if mode == "string" and preserve_non_opts:
 682                      # remove option-parts from the original args-string and preserve remaining-part.
 683                      # This relies on the arg_split(...) and getopt(...)'s impl spec, that the parsed options are
 684                      # returned in the original order.
 685                      remainder_arg_str = remainder_arg_str.replace(o, "", 1).replace(
 686                          a, "", 1
 687                      )
 688                  if o.startswith("--"):
 689                      o = o[2:]
 690                  else:
 691                      o = o[1:]
 692                  try:
 693                      odict[o].append(a)
 694                  except AttributeError:
 695                      odict[o] = [odict[o],a]
 696                  except KeyError:
 697                      if list_all:
 698                          odict[o] = [a]
 699                      else:
 700                          odict[o] = a
 701  
 702          # Prepare opts,args for return
 703          opts = Struct(odict)
 704          if mode == 'string':
 705              if preserve_non_opts:
 706                  args = remainder_arg_str.lstrip()
 707              else:
 708                  args = " ".join(args)
 709  
 710          return opts,args
 711  
 712      def default_option(self, fn, optstr):
 713          """Make an entry in the options_table for fn, with value optstr"""
 714  
 715          if fn not in self.lsmagic():
 716              error("%s is not a magic function" % fn)
 717          self.options_table[fn] = optstr
 718  
 719  
 720  class MagicAlias(object):
 721      """An alias to another magic function.
 722  
 723      An alias is determined by its magic name and magic kind. Lookup
 724      is done at call time, so if the underlying magic changes the alias
 725      will call the new function.
 726  
 727      Use the :meth:`MagicsManager.register_alias` method or the
 728      `%alias_magic` magic function to create and register a new alias.
 729      """
 730      def __init__(self, shell, magic_name, magic_kind, magic_params=None):
 731          self.shell = shell
 732          self.magic_name = magic_name
 733          self.magic_params = magic_params
 734          self.magic_kind = magic_kind
 735  
 736          self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
 737          self.__doc__ = "Alias for `%s`." % self.pretty_target
 738  
 739          self._in_call = False
 740  
 741      def __call__(self, *args, **kwargs):
 742          """Call the magic alias."""
 743          fn = self.shell.find_magic(self.magic_name, self.magic_kind)
 744          if fn is None:
 745              raise UsageError("Magic `%s` not found." % self.pretty_target)
 746  
 747          # Protect against infinite recursion.
 748          if self._in_call:
 749              raise UsageError("Infinite recursion detected; "
 750                               "magic aliases cannot call themselves.")
 751          self._in_call = True
 752          try:
 753              if self.magic_params:
 754                  args_list = list(args)
 755                  args_list[0] = self.magic_params + " " + args[0]
 756                  args = tuple(args_list)
 757              return fn(*args, **kwargs)
 758          finally:
 759              self._in_call = False
 760