magic.py 28 KB

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