home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_1968 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  54.8 KB  |  1,956 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import __builtin__
  5. import bdb
  6. import inspect
  7. import os
  8. import pdb
  9. import pydoc
  10. import sys
  11. import re
  12. import tempfile
  13. import time
  14. import cPickle as pickle
  15. import textwrap
  16. from cStringIO import StringIO
  17. from getopt import getopt, GetoptError
  18. from pprint import pprint, pformat
  19.  
  20. try:
  21.     import cProfile as profile
  22.     import pstats
  23. except ImportError:
  24.     
  25.     try:
  26.         import profile
  27.         import pstats
  28.     except ImportError:
  29.         profile = None
  30.         pstats = None
  31.     except:
  32.         None<EXCEPTION MATCH>ImportError
  33.     
  34.  
  35.     None<EXCEPTION MATCH>ImportError
  36.  
  37. import IPython
  38. from IPython import Debugger, OInspect, wildcard
  39. from IPython.FakeModule import FakeModule
  40. from IPython.Itpl import Itpl, itpl, printpl, itplns
  41. from IPython.PyColorize import Parser
  42. from IPython.ipstruct import Struct
  43. from IPython.macro import Macro
  44. from IPython.genutils import *
  45. from IPython import platutils
  46. import IPython.generics as IPython
  47. import IPython.ipapi as IPython
  48. from IPython.ipapi import UsageError
  49. from IPython.testing import decorators as testdec
  50.  
  51. def on_off(tag):
  52.     return [
  53.         'OFF',
  54.         'ON'][tag]
  55.  
  56.  
  57. class Bunch:
  58.     pass
  59.  
  60.  
  61. def compress_dhist(dh):
  62.     head = dh[:-10]
  63.     tail = dh[-10:]
  64.     newhead = []
  65.     done = set()
  66.     for h in head:
  67.         if h in done:
  68.             continue
  69.         
  70.         newhead.append(h)
  71.         done.add(h)
  72.     
  73.     return newhead + tail
  74.  
  75.  
  76. class Magic:
  77.     auto_status = [
  78.         'Automagic is OFF, % prefix IS needed for magic functions.',
  79.         'Automagic is ON, % prefix NOT needed for magic functions.']
  80.     
  81.     def __init__(self, shell):
  82.         self.options_table = { }
  83.         if profile is None:
  84.             self.magic_prun = self.profile_missing_notice
  85.         
  86.         self.shell = shell
  87.         self._magic_state = Bunch()
  88.  
  89.     
  90.     def profile_missing_notice(self, *args, **kwargs):
  91.         error('The profile module could not be found. It has been removed from the standard\npython packages because of its non-free license. To use profiling, install the\npython-profiler package from non-free.')
  92.  
  93.     
  94.     def default_option(self, fn, optstr):
  95.         if fn not in self.lsmagic():
  96.             error('%s is not a magic function' % fn)
  97.         
  98.         self.options_table[fn] = optstr
  99.  
  100.     
  101.     def lsmagic(self):
  102.         
  103.         class_magic = lambda fn: if fn.startswith('magic_'):
  104. passcallable(Magic.__dict__[fn])
  105.         
  106.         inst_magic = lambda fn: if fn.startswith('magic_'):
  107. passcallable(self.__dict__[fn])
  108.         
  109.         inst_bound_magic = lambda fn: if fn.startswith('magic_'):
  110. passcallable(self.__class__.__dict__[fn])
  111.         magics = filter(class_magic, Magic.__dict__.keys()) + filter(inst_magic, self.__dict__.keys()) + filter(inst_bound_magic, self.__class__.__dict__.keys())
  112.         out = []
  113.         for fn in set(magics):
  114.             out.append(fn.replace('magic_', '', 1))
  115.         
  116.         out.sort()
  117.         return out
  118.  
  119.     
  120.     def extract_input_slices(self, slices, raw = False):
  121.         if raw:
  122.             hist = self.shell.input_hist_raw
  123.         else:
  124.             hist = self.shell.input_hist
  125.         cmds = []
  126.         for chunk in slices:
  127.             if ':' in chunk:
  128.                 (ini, fin) = map(int, chunk.split(':'))
  129.             elif '-' in chunk:
  130.                 (ini, fin) = map(int, chunk.split('-'))
  131.                 fin += 1
  132.             else:
  133.                 ini = int(chunk)
  134.                 fin = ini + 1
  135.             cmds.append(hist[ini:fin])
  136.         
  137.         return cmds
  138.  
  139.     
  140.     def _ofind(self, oname, namespaces = None):
  141.         oname = oname.strip()
  142.         alias_ns = None
  143.         if namespaces is None:
  144.             namespaces = [
  145.                 ('Interactive', self.shell.user_ns),
  146.                 ('IPython internal', self.shell.internal_ns),
  147.                 ('Python builtin', __builtin__.__dict__),
  148.                 ('Alias', self.shell.alias_table)]
  149.             alias_ns = self.shell.alias_table
  150.         
  151.         found = 0
  152.         obj = None
  153.         ospace = None
  154.         ds = None
  155.         ismagic = 0
  156.         isalias = 0
  157.         parent = None
  158.         oname_parts = oname.split('.')
  159.         oname_head = oname_parts[0]
  160.         oname_rest = oname_parts[1:]
  161.         for nsname, ns in namespaces:
  162.             
  163.             try:
  164.                 obj = ns[oname_head]
  165.             except KeyError:
  166.                 continue
  167.                 continue
  168.  
  169.             for part in oname_rest:
  170.                 
  171.                 try:
  172.                     parent = obj
  173.                     obj = getattr(obj, part)
  174.                 continue
  175.                 break
  176.                 continue
  177.  
  178.             else:
  179.                 found = 1
  180.                 ospace = nsname
  181.                 if ns == alias_ns:
  182.                     isalias = 1
  183.                 
  184.                 break
  185.         
  186.         if not found:
  187.             if oname.startswith(self.shell.ESC_MAGIC):
  188.                 oname = oname[1:]
  189.             
  190.             obj = getattr(self, 'magic_' + oname, None)
  191.             if obj is not None:
  192.                 found = 1
  193.                 ospace = 'IPython internal'
  194.                 ismagic = 1
  195.             
  196.         
  197.         if not found and oname_head in ("''", '""', '[]', '{}', '()'):
  198.             obj = eval(oname_head)
  199.             found = 1
  200.             ospace = 'Interactive'
  201.         
  202.         return {
  203.             'found': found,
  204.             'obj': obj,
  205.             'namespace': ospace,
  206.             'ismagic': ismagic,
  207.             'isalias': isalias,
  208.             'parent': parent }
  209.  
  210.     
  211.     def arg_err(self, func):
  212.         print 'Error in arguments:'
  213.         print OInspect.getdoc(func)
  214.  
  215.     
  216.     def format_latex(self, strng):
  217.         escape_re = re.compile('(%|_|\\$|#|&)', re.MULTILINE)
  218.         cmd_name_re = re.compile('^(%s.*?):' % self.shell.ESC_MAGIC, re.MULTILINE)
  219.         cmd_re = re.compile('(?P<cmd>%s.+?\\b)(?!\\}\\}:)' % self.shell.ESC_MAGIC, re.MULTILINE)
  220.         par_re = re.compile('\\\\$', re.MULTILINE)
  221.         newline_re = re.compile('\\\\n')
  222.         strng = cmd_name_re.sub('\\n\\\\bigskip\\n\\\\texttt{\\\\textbf{ \\1}}:', strng)
  223.         strng = cmd_re.sub('\\\\texttt{\\g<cmd>}', strng)
  224.         strng = par_re.sub('\\\\\\\\', strng)
  225.         strng = escape_re.sub('\\\\\\1', strng)
  226.         strng = newline_re.sub('\\\\textbackslash{}n', strng)
  227.         return strng
  228.  
  229.     
  230.     def format_screen(self, strng):
  231.         par_re = re.compile('\\\\$', re.MULTILINE)
  232.         strng = par_re.sub('', strng)
  233.         return strng
  234.  
  235.     
  236.     def parse_options(self, arg_str, opt_str, *long_opts, **kw):
  237.         caller = sys._getframe(1).f_code.co_name.replace('magic_', '')
  238.         arg_str = '%s %s' % (self.options_table.get(caller, ''), arg_str)
  239.         mode = kw.get('mode', 'string')
  240.         if mode not in ('string', 'list'):
  241.             raise ValueError, 'incorrect mode given: %s' % mode
  242.         mode not in ('string', 'list')
  243.         list_all = kw.get('list_all', 0)
  244.         posix = kw.get('posix', True)
  245.         odict = { }
  246.         args = arg_str.split()
  247.         if len(args) >= 1:
  248.             argv = arg_split(arg_str, posix)
  249.             
  250.             try:
  251.                 (opts, args) = getopt(argv, opt_str, *long_opts)
  252.             except GetoptError:
  253.                 e = None
  254.                 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg, opt_str, ' '.join(long_opts)))
  255.  
  256.             for o, a in opts:
  257.                 if o.startswith('--'):
  258.                     o = o[2:]
  259.                 else:
  260.                     o = o[1:]
  261.                 
  262.                 try:
  263.                     odict[o].append(a)
  264.                 continue
  265.                 except AttributeError:
  266.                     odict[o] = [
  267.                         odict[o],
  268.                         a]
  269.                     continue
  270.                     except KeyError:
  271.                         if list_all:
  272.                             odict[o] = [
  273.                                 a]
  274.                         else:
  275.                             odict[o] = a
  276.                         list_all
  277.                     
  278.                 except:
  279.                     None<EXCEPTION MATCH>AttributeError
  280.                     opts = Struct(odict)
  281.                     if mode == 'string':
  282.                         args = ' '.join(args)
  283.                     
  284.  
  285.         return (opts, args)
  286.  
  287.     
  288.     def magic_lsmagic(self, parameter_s = ''):
  289.         mesc = self.shell.ESC_MAGIC
  290.         print 'Available magic functions:\n' + mesc + ('  ' + mesc).join(self.lsmagic())
  291.         print '\n' + Magic.auto_status[self.shell.rc.automagic]
  292.  
  293.     
  294.     def magic_magic(self, parameter_s = ''):
  295.         mode = ''
  296.         
  297.         try:
  298.             if parameter_s.split()[0] == '-latex':
  299.                 mode = 'latex'
  300.             
  301.             if parameter_s.split()[0] == '-brief':
  302.                 mode = 'brief'
  303.             
  304.             if parameter_s.split()[0] == '-rest':
  305.                 mode = 'rest'
  306.                 rest_docs = []
  307.         except:
  308.             pass
  309.  
  310.         magic_docs = []
  311.         for fname in self.lsmagic():
  312.             mname = 'magic_' + fname
  313.             for space in (Magic, self, self.__class__):
  314.                 
  315.                 try:
  316.                     fn = space.__dict__[mname]
  317.                 except KeyError:
  318.                     continue
  319.  
  320.             
  321.             if mode == 'brief':
  322.                 if fn.__doc__:
  323.                     fndoc = fn.__doc__.split('\n', 1)[0]
  324.                 else:
  325.                     fndoc = 'No documentation'
  326.             elif fn.__doc__:
  327.                 fndoc = fn.__doc__.rstrip()
  328.             else:
  329.                 fndoc = 'No documentation'
  330.             if mode == 'rest':
  331.                 rest_docs.append('**%s%s**::\n\n\t%s\n\n' % (self.shell.ESC_MAGIC, fname, fndoc))
  332.                 continue
  333.             magic_docs.append('%s%s:\n\t%s\n' % (self.shell.ESC_MAGIC, fname, fndoc))
  334.         
  335.         magic_docs = ''.join(magic_docs)
  336.         if mode == 'rest':
  337.             return ''.join(rest_docs)
  338.         if mode == 'latex':
  339.             print self.format_latex(magic_docs)
  340.             return None
  341.         magic_docs = self.format_screen(magic_docs)
  342.         if mode == 'brief':
  343.             return magic_docs
  344.         outmsg = "\nIPython's 'magic' functions\n===========================\n\nThe magic function system provides a series of functions which allow you to\ncontrol the behavior of IPython itself, plus a lot of system-type\nfeatures. All these functions are prefixed with a % character, but parameters\nare given without parentheses or quotes.\n\nNOTE: If you have 'automagic' enabled (via the command line option or with the\n%automagic function), you don't need to type in the % explicitly.  By default,\nIPython ships with automagic on, so you should only rarely need the % escape.\n\nExample: typing '%cd mydir' (without the quotes) changes you working directory\nto 'mydir', if it exists.\n\nYou can define your own magic functions to extend the system. See the supplied\nipythonrc and example-magic.py files for details (in your ipython\nconfiguration directory, typically $HOME/.ipython/).\n\nYou can also define your own aliased names for magic functions. In your\nipythonrc file, placing a line like:\n\n  execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile\n\nwill define %pf as a new name for %profile.\n\nYou can also call magics in code using the ipmagic() function, which IPython\nautomatically adds to the builtin namespace.  Type 'ipmagic?' for details.\n\nFor a list of the available magic functions, use %lsmagic. For a description\nof any of them, type %magic_name?, e.g. '%cd?'.\n\nCurrently the magic system has the following functions:\n"
  345.         mesc = self.shell.ESC_MAGIC
  346.         outmsg = '%s\n%s\n\nSummary of magic functions (from %slsmagic):\n\n%s%s\n\n%s' % (outmsg, magic_docs, mesc, mesc, ('  ' + mesc).join(self.lsmagic()), Magic.auto_status[self.shell.rc.automagic])
  347.         page(outmsg, screen_lines = self.shell.rc.screen_length)
  348.  
  349.     
  350.     def magic_autoindent(self, parameter_s = ''):
  351.         self.shell.set_autoindent()
  352.         print 'Automatic indentation is:', [
  353.             'OFF',
  354.             'ON'][self.shell.autoindent]
  355.  
  356.     
  357.     def magic_automagic(self, parameter_s = ''):
  358.         rc = self.shell.rc
  359.         arg = parameter_s.lower()
  360.         if parameter_s in ('on', '1', 'true'):
  361.             rc.automagic = True
  362.         elif parameter_s in ('off', '0', 'false'):
  363.             rc.automagic = False
  364.         else:
  365.             rc.automagic = not (rc.automagic)
  366.         print '\n' + Magic.auto_status[rc.automagic]
  367.  
  368.     
  369.     def magic_autocall(self, parameter_s = ''):
  370.         rc = self.shell.rc
  371.         if parameter_s:
  372.             arg = int(parameter_s)
  373.         else:
  374.             arg = 'toggle'
  375.         if arg not in (0, 1, 2, 'toggle'):
  376.             error('Valid modes: (0->Off, 1->Smart, 2->Full')
  377.             return None
  378.         if arg in (0, 1, 2):
  379.             rc.autocall = arg
  380.         elif rc.autocall:
  381.             self._magic_state.autocall_save = rc.autocall
  382.             rc.autocall = 0
  383.         else:
  384.             
  385.             try:
  386.                 rc.autocall = self._magic_state.autocall_save
  387.             except AttributeError:
  388.                 rc.autocall = self._magic_state.autocall_save = 1
  389.  
  390.         print 'Automatic calling is:', [
  391.             'OFF',
  392.             'Smart',
  393.             'Full'][rc.autocall]
  394.  
  395.     magic_autocall = testdec.skip_doctest(magic_autocall)
  396.     
  397.     def magic_system_verbose(self, parameter_s = ''):
  398.         if parameter_s:
  399.             val = bool(eval(parameter_s))
  400.         else:
  401.             val = None
  402.         self.shell.rc_set_toggle('system_verbose', val)
  403.         print 'System verbose printing is:', [
  404.             'OFF',
  405.             'ON'][self.shell.rc.system_verbose]
  406.  
  407.     
  408.     def magic_page(self, parameter_s = ''):
  409.         (opts, args) = self.parse_options(parameter_s, 'r')
  410.         raw = 'r' in opts
  411.         if not args or args:
  412.             pass
  413.         oname = '_'
  414.         info = self._ofind(oname)
  415.         if info['found']:
  416.             if not raw or str:
  417.                 pass
  418.             txt = pformat(info['obj'])
  419.             page(txt)
  420.         else:
  421.             print 'Object `%s` not found' % oname
  422.  
  423.     
  424.     def magic_profile(self, parameter_s = ''):
  425.         if self.shell.rc.profile:
  426.             printpl('Current IPython profile: $self.shell.rc.profile.')
  427.         else:
  428.             print 'No profile active.'
  429.  
  430.     
  431.     def magic_pinfo(self, parameter_s = '', namespaces = None):
  432.         detail_level = 0
  433.         (pinfo, qmark1, oname, qmark2) = re.match('(pinfo )?(\\?*)(.*?)(\\??$)', parameter_s).groups()
  434.         if pinfo and qmark1 or qmark2:
  435.             detail_level = 1
  436.         
  437.         if '*' in oname:
  438.             self.magic_psearch(oname)
  439.         else:
  440.             self._inspect('pinfo', oname, detail_level = detail_level, namespaces = namespaces)
  441.  
  442.     
  443.     def magic_pdef(self, parameter_s = '', namespaces = None):
  444.         self._inspect('pdef', parameter_s, namespaces)
  445.  
  446.     
  447.     def magic_pdoc(self, parameter_s = '', namespaces = None):
  448.         self._inspect('pdoc', parameter_s, namespaces)
  449.  
  450.     
  451.     def magic_psource(self, parameter_s = '', namespaces = None):
  452.         self._inspect('psource', parameter_s, namespaces)
  453.  
  454.     
  455.     def magic_pfile(self, parameter_s = ''):
  456.         out = self._inspect('pfile', parameter_s)
  457.         if out == 'not found':
  458.             
  459.             try:
  460.                 filename = get_py_filename(parameter_s)
  461.             except IOError:
  462.                 msg = None
  463.                 print msg
  464.                 return None
  465.  
  466.             page(self.shell.inspector.format(file(filename).read()))
  467.         
  468.  
  469.     
  470.     def _inspect(self, meth, oname, namespaces = None, **kw):
  471.         
  472.         try:
  473.             oname = oname.strip().encode('ascii')
  474.         except UnicodeEncodeError:
  475.             print 'Python identifiers can only contain ascii characters.'
  476.             return 'not found'
  477.  
  478.         info = Struct(self._ofind(oname, namespaces))
  479.         if info.found:
  480.             
  481.             try:
  482.                 IPython.generics.inspect_object(info.obj)
  483.                 return None
  484.             except IPython.ipapi.TryNext:
  485.                 pass
  486.  
  487.             path = oname.split('.')
  488.             root = '.'.join(path[:-1])
  489.             if info.parent is not None:
  490.                 
  491.                 try:
  492.                     target = getattr(info.parent, '__class__')
  493.                     
  494.                     try:
  495.                         target = getattr(target, path[-1])
  496.                         if isinstance(target, property):
  497.                             oname = root + '.__class__.' + path[-1]
  498.                             info = Struct(self._ofind(oname))
  499.                     except AttributeError:
  500.                         pass
  501.  
  502.                 except AttributeError:
  503.                     pass
  504.                 except:
  505.                     None<EXCEPTION MATCH>AttributeError
  506.                 
  507.  
  508.             None<EXCEPTION MATCH>AttributeError
  509.             pmethod = getattr(self.shell.inspector, meth)
  510.             if not info.ismagic or self.format_screen:
  511.                 pass
  512.             formatter = None
  513.             if meth == 'pdoc':
  514.                 pmethod(info.obj, oname, formatter)
  515.             elif meth == 'pinfo':
  516.                 pmethod(info.obj, oname, formatter, info, **kw)
  517.             else:
  518.                 pmethod(info.obj, oname)
  519.         else:
  520.             print 'Object `%s` not found.' % oname
  521.             return 'not found'
  522.         return info.found
  523.  
  524.     
  525.     def magic_psearch(self, parameter_s = ''):
  526.         
  527.         try:
  528.             parameter_s = parameter_s.encode('ascii')
  529.         except UnicodeEncodeError:
  530.             print 'Python identifiers can only contain ascii characters.'
  531.             return None
  532.  
  533.         def_search = [
  534.             'user',
  535.             'builtin']
  536.         (opts, args) = self.parse_options(parameter_s, 'cias:e:', list_all = True)
  537.         opt = opts.get
  538.         shell = self.shell
  539.         psearch = shell.inspector.psearch
  540.         if opts.has_key('i'):
  541.             ignore_case = True
  542.         elif opts.has_key('c'):
  543.             ignore_case = False
  544.         else:
  545.             ignore_case = not (shell.rc.wildcards_case_sensitive)
  546.         def_search.extend(opt('s', []))
  547.         ns_exclude = ns_exclude = opt('e', [])
  548.         ns_search = _[1]
  549.         
  550.         try:
  551.             psearch(args, shell.ns_table, ns_search, show_all = opt('a'), ignore_case = ignore_case)
  552.         except:
  553.             []
  554.             []
  555.             shell.showtraceback()
  556.  
  557.  
  558.     
  559.     def magic_who_ls(self, parameter_s = ''):
  560.         user_ns = self.shell.user_ns
  561.         internal_ns = self.shell.internal_ns
  562.         user_config_ns = self.shell.user_config_ns
  563.         out = []
  564.         typelist = parameter_s.split()
  565.         for i in user_ns:
  566.             if not i.startswith('_'):
  567.                 pass
  568.             if not i.startswith('_i'):
  569.                 if not i in internal_ns:
  570.                     pass
  571.                 if not (i in user_config_ns):
  572.                     if typelist:
  573.                         if type(user_ns[i]).__name__ in typelist:
  574.                             out.append(i)
  575.                         
  576.                     else:
  577.                         out.append(i)
  578.             typelist
  579.         
  580.         out.sort()
  581.         return out
  582.  
  583.     
  584.     def magic_who(self, parameter_s = ''):
  585.         varlist = self.magic_who_ls(parameter_s)
  586.         if not varlist:
  587.             if parameter_s:
  588.                 print 'No variables match your requested type.'
  589.             else:
  590.                 print 'Interactive namespace is empty.'
  591.             return None
  592.         count = 0
  593.         for i in varlist:
  594.             print i + '\t',
  595.             count += 1
  596.             if count > 8:
  597.                 count = 0
  598.                 print 
  599.                 continue
  600.         
  601.         print 
  602.  
  603.     
  604.     def magic_whos(self, parameter_s = ''):
  605.         varnames = self.magic_who_ls(parameter_s)
  606.         if not varnames:
  607.             if parameter_s:
  608.                 print 'No variables match your requested type.'
  609.             else:
  610.                 print 'Interactive namespace is empty.'
  611.             return None
  612.         seq_types = [
  613.             types.DictType,
  614.             types.ListType,
  615.             types.TupleType]
  616.         
  617.         try:
  618.             import numpy
  619.         except ImportError:
  620.             varnames
  621.             varnames
  622.             ndarray_type = None
  623.         except:
  624.             varnames
  625.  
  626.         ndarray_type = numpy.ndarray.__name__
  627.         
  628.         try:
  629.             import Numeric
  630.         except ImportError:
  631.             varnames
  632.             varnames
  633.             array_type = None
  634.         except:
  635.             varnames
  636.  
  637.         array_type = Numeric.ArrayType.__name__
  638.         
  639.         def get_vars(i):
  640.             return self.shell.user_ns[i]
  641.  
  642.         abbrevs = {
  643.             'IPython.macro.Macro': 'Macro' }
  644.         
  645.         def type_name(v):
  646.             tn = type(v).__name__
  647.             return abbrevs.get(tn, tn)
  648.  
  649.         varlist = map(get_vars, varnames)
  650.         typelist = []
  651.         for vv in varlist:
  652.             tt = type_name(vv)
  653.             if tt == 'instance':
  654.                 typelist.append(abbrevs.get(str(vv.__class__), str(vv.__class__)))
  655.                 continue
  656.             ((varnames,),)
  657.             typelist.append(tt)
  658.         
  659.         varlabel = 'Variable'
  660.         typelabel = 'Type'
  661.         datalabel = 'Data/Info'
  662.         colsep = 3
  663.         vformat = '$vname.ljust(varwidth)$vtype.ljust(typewidth)'
  664.         vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
  665.         aformat = '%s: %s elems, type `%s`, %s bytes'
  666.         varwidth = max(max(map(len, varnames)), len(varlabel)) + colsep
  667.         typewidth = max(max(map(len, typelist)), len(typelabel)) + colsep
  668.         print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + ' ' + datalabel + '\n' + '-' * (varwidth + typewidth + len(datalabel) + 1)
  669.         kb = 1024
  670.         Mb = 1048576
  671.         for vname, var, vtype in zip(varnames, varlist, typelist):
  672.             print itpl(vformat),
  673.             if vtype in seq_types:
  674.                 print len(var)
  675.                 continue
  676.             if vtype in [
  677.                 array_type,
  678.                 ndarray_type]:
  679.                 vshape = str(var.shape).replace(',', '').replace(' ', 'x')[1:-1]
  680.                 if vtype == ndarray_type:
  681.                     vsize = var.size
  682.                     vbytes = vsize * var.itemsize
  683.                     vdtype = var.dtype
  684.                 else:
  685.                     vsize = Numeric.size(var)
  686.                     vbytes = vsize * var.itemsize()
  687.                     vdtype = var.typecode()
  688.             None if vbytes < 100000 else vbytes < Mb
  689.             
  690.             try:
  691.                 vstr = str(var)
  692.             except UnicodeEncodeError:
  693.                 vstr = unicode(var).encode(sys.getdefaultencoding(), 'backslashreplace')
  694.  
  695.             vstr = vstr.replace('\n', '\\n')
  696.             if len(vstr) < 50:
  697.                 print vstr
  698.                 continue
  699.             printpl(vfmt_short)
  700.         
  701.  
  702.     
  703.     def magic_reset(self, parameter_s = ''):
  704.         if parameter_s == '-f':
  705.             ans = True
  706.         else:
  707.             ans = self.shell.ask_yes_no('Once deleted, variables cannot be recovered. Proceed (y/[n])? ')
  708.         if not ans:
  709.             print 'Nothing done.'
  710.             return None
  711.         user_ns = self.shell.user_ns
  712.         for i in self.magic_who_ls():
  713.             del user_ns[i]
  714.         
  715.         self.shell.clear_main_mod_cache()
  716.  
  717.     
  718.     def magic_logstart(self, parameter_s = ''):
  719.         (opts, par) = self.parse_options(parameter_s, 'ort')
  720.         log_output = 'o' in opts
  721.         log_raw_input = 'r' in opts
  722.         timestamp = 't' in opts
  723.         rc = self.shell.rc
  724.         logger = self.shell.logger
  725.         if par:
  726.             
  727.             try:
  728.                 (logfname, logmode) = par.split()
  729.             logfname = par
  730.             logmode = 'backup'
  731.  
  732.         else:
  733.             logfname = logger.logfname
  734.             logmode = logger.logmode
  735.         old_logfile = rc.opts.get('logfile', '')
  736.         if logfname:
  737.             logfname = os.path.expanduser(logfname)
  738.         
  739.         rc.opts.logfile = logfname
  740.         loghead = self.shell.loghead_tpl % (rc.opts, rc.args)
  741.         
  742.         try:
  743.             started = logger.logstart(logfname, loghead, logmode, log_output, timestamp, log_raw_input)
  744.         except:
  745.             rc.opts.logfile = old_logfile
  746.             warn("Couldn't start log: %s" % sys.exc_info()[1])
  747.  
  748.         if timestamp:
  749.             logger.timestamp = False
  750.         
  751.         if log_raw_input:
  752.             input_hist = self.shell.input_hist_raw
  753.         else:
  754.             input_hist = self.shell.input_hist
  755.         if log_output:
  756.             log_write = logger.log_write
  757.             output_hist = self.shell.output_hist
  758.             for n in range(1, len(input_hist) - 1):
  759.                 log_write(input_hist[n].rstrip())
  760.                 if n in output_hist:
  761.                     log_write(repr(output_hist[n]), 'output')
  762.                     continue
  763.             
  764.         else:
  765.             logger.log_write(input_hist[1:])
  766.         if timestamp:
  767.             logger.timestamp = True
  768.         
  769.         print 'Activating auto-logging. Current session state plus future input saved.'
  770.         logger.logstate()
  771.  
  772.     
  773.     def magic_logstop(self, parameter_s = ''):
  774.         self.logger.logstop()
  775.  
  776.     
  777.     def magic_logoff(self, parameter_s = ''):
  778.         self.shell.logger.switch_log(0)
  779.  
  780.     
  781.     def magic_logon(self, parameter_s = ''):
  782.         self.shell.logger.switch_log(1)
  783.  
  784.     
  785.     def magic_logstate(self, parameter_s = ''):
  786.         self.shell.logger.logstate()
  787.  
  788.     
  789.     def magic_pdb(self, parameter_s = ''):
  790.         par = parameter_s.strip().lower()
  791.         if par:
  792.             
  793.             try:
  794.                 new_pdb = {
  795.                     'off': 0,
  796.                     '0': 0,
  797.                     'on': 1,
  798.                     '1': 1 }[par]
  799.             except KeyError:
  800.                 print 'Incorrect argument. Use on/1, off/0, or nothing for a toggle.'
  801.                 return None
  802.             
  803.  
  804.         None<EXCEPTION MATCH>KeyError
  805.         new_pdb = not (self.shell.call_pdb)
  806.         self.shell.call_pdb = new_pdb
  807.         print 'Automatic pdb calling has been turned', on_off(new_pdb)
  808.  
  809.     
  810.     def magic_debug(self, parameter_s = ''):
  811.         self.shell.debugger(force = True)
  812.  
  813.     
  814.     def magic_prun(self, parameter_s = '', user_mode = 1, opts = None, arg_lst = None, prog_ns = None):
  815.         opts_def = Struct(D = [
  816.             ''], l = [], s = [
  817.             'time'], T = [
  818.             ''])
  819.         parameter_s = parameter_s.replace('"', '\\"').replace("'", "\\'")
  820.         if user_mode:
  821.             (opts, arg_str) = self.parse_options(parameter_s, 'D:l:rs:T:', list_all = 1)
  822.             namespace = self.shell.user_ns
  823.         else:
  824.             
  825.             try:
  826.                 filename = get_py_filename(arg_lst[0])
  827.             except IOError:
  828.                 msg = None
  829.                 error(msg)
  830.                 return None
  831.  
  832.             arg_str = 'execfile(filename,prog_ns)'
  833.             namespace = locals()
  834.         opts.merge(opts_def)
  835.         prof = profile.Profile()
  836.         
  837.         try:
  838.             prof = prof.runctx(arg_str, namespace, namespace)
  839.             sys_exit = ''
  840.         except SystemExit:
  841.             sys_exit = '*** SystemExit exception caught in code being profiled.'
  842.  
  843.         stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
  844.         lims = opts.l
  845.         if lims:
  846.             lims = []
  847.             for lim in opts.l:
  848.                 
  849.                 try:
  850.                     lims.append(int(lim))
  851.                 continue
  852.                 except ValueError:
  853.                     
  854.                     try:
  855.                         lims.append(float(lim))
  856.                     except ValueError:
  857.                         lims.append(lim)
  858.                     except:
  859.                         None<EXCEPTION MATCH>ValueError
  860.                     
  861.  
  862.                     None<EXCEPTION MATCH>ValueError
  863.                 
  864.  
  865.             
  866.         
  867.         stdout_trap = StringIO()
  868.         if hasattr(stats, 'stream'):
  869.             stats.stream = stdout_trap
  870.             stats.print_stats(*lims)
  871.         else:
  872.             sys_stdout = sys.stdout
  873.             
  874.             try:
  875.                 sys.stdout = stdout_trap
  876.                 stats.print_stats(*lims)
  877.             finally:
  878.                 sys.stdout = sys_stdout
  879.  
  880.         output = stdout_trap.getvalue()
  881.         output = output.rstrip()
  882.         page(output, screen_lines = self.shell.rc.screen_length)
  883.         print sys_exit,
  884.         dump_file = opts.D[0]
  885.         text_file = opts.T[0]
  886.         if dump_file:
  887.             prof.dump_stats(dump_file)
  888.             print '\n*** Profile stats marshalled to file', `dump_file` + '.', sys_exit
  889.         
  890.         if text_file:
  891.             pfile = file(text_file, 'w')
  892.             pfile.write(output)
  893.             pfile.close()
  894.             print '\n*** Profile printout saved to text file', `text_file` + '.', sys_exit
  895.         
  896.         if opts.has_key('r'):
  897.             return stats
  898.         return None
  899.  
  900.     magic_prun = testdec.skip_doctest(magic_prun)
  901.     
  902.     def magic_run(self, parameter_s = '', runner = None, file_finder = get_py_filename):
  903.         (opts, arg_lst) = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:e', mode = 'list', list_all = 1)
  904.         
  905.         try:
  906.             filename = file_finder(arg_lst[0])
  907.         except IndexError:
  908.             warn('you must provide at least a filename.')
  909.             print '\n%run:\n', OInspect.getdoc(self.magic_run)
  910.             return None
  911.             except IOError:
  912.                 msg = None
  913.                 error(msg)
  914.                 return None
  915.             elif filename.lower().endswith('.ipy'):
  916.                 self.api.runlines(open(filename).read())
  917.                 return None
  918.  
  919.         exit_ignore = opts.has_key('e')
  920.         save_argv = sys.argv
  921.         sys.argv = [
  922.             filename] + arg_lst[1:]
  923.         if opts.has_key('i'):
  924.             prog_ns = self.shell.user_ns
  925.             _Magic__name__save = self.shell.user_ns['__name__']
  926.             prog_ns['__name__'] = '__main__'
  927.             main_mod = self.shell.new_main_mod(prog_ns)
  928.         elif opts.has_key('n'):
  929.             name = os.path.splitext(os.path.basename(filename))[0]
  930.         else:
  931.             name = '__main__'
  932.         main_mod = self.shell.new_main_mod()
  933.         prog_ns = main_mod.__dict__
  934.         prog_ns['__name__'] = name
  935.         prog_ns['__file__'] = filename
  936.         main_mod_name = prog_ns['__name__']
  937.         if main_mod_name == '__main__':
  938.             restore_main = sys.modules['__main__']
  939.         else:
  940.             restore_main = False
  941.         sys.modules[main_mod_name] = main_mod
  942.         stats = None
  943.         
  944.         try:
  945.             self.shell.savehist()
  946.             if opts.has_key('p'):
  947.                 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
  948.             elif opts.has_key('d'):
  949.                 deb = Debugger.Pdb(self.shell.rc.colors)
  950.                 bdb.Breakpoint.next = 1
  951.                 bdb.Breakpoint.bplist = { }
  952.                 bdb.Breakpoint.bpbynumber = [
  953.                     None]
  954.                 maxtries = 10
  955.                 bp = int(opts.get('b', [
  956.                     1])[0])
  957.                 checkline = deb.checkline(filename, bp)
  958.                 if not checkline:
  959.                     for bp in range(bp + 1, bp + maxtries + 1):
  960.                         if deb.checkline(filename, bp):
  961.                             break
  962.                             continue
  963.                     else:
  964.                         msg = '\nI failed to find a valid line to set a breakpoint\nafter trying up to line: %s.\nPlease set a valid breakpoint manually with the -b option.' % bp
  965.                         return None
  966.                 deb.do_break('%s:%s' % (filename, bp))
  967.                 print "NOTE: Enter 'c' at the", '%s prompt to start your script.' % deb.prompt
  968.                 
  969.                 try:
  970.                     deb.run('execfile("%s")' % filename, prog_ns)
  971.                 (etype, value, tb) = sys.exc_info()
  972.                 self.shell.InteractiveTB(etype, value, tb, tb_offset = 3)
  973.  
  974.             elif runner is None:
  975.                 runner = self.shell.safe_execfile
  976.             
  977.             if opts.has_key('t'):
  978.                 
  979.                 try:
  980.                     nruns = int(opts['N'][0])
  981.                     if nruns < 1:
  982.                         error('Number of runs must be >=1')
  983.                         return None
  984.                 except KeyError:
  985.                     nruns = 1
  986.  
  987.                 if nruns == 1:
  988.                     t0 = clock2()
  989.                     runner(filename, prog_ns, prog_ns, exit_ignore = exit_ignore)
  990.                     t1 = clock2()
  991.                     t_usr = t1[0] - t0[0]
  992.                     t_sys = t1[1] - t0[1]
  993.                     print '\nIPython CPU timings (estimated):'
  994.                     print '  User  : %10s s.' % t_usr
  995.                     print '  System: %10s s.' % t_sys
  996.                 else:
  997.                     runs = range(nruns)
  998.                     t0 = clock2()
  999.                     for nr in runs:
  1000.                         runner(filename, prog_ns, prog_ns, exit_ignore = exit_ignore)
  1001.                     
  1002.                     t1 = clock2()
  1003.                     t_usr = t1[0] - t0[0]
  1004.                     t_sys = t1[1] - t0[1]
  1005.                     print '\nIPython CPU timings (estimated):'
  1006.                     print 'Total runs performed:', nruns
  1007.                     print '  Times : %10s    %10s' % ('Total', 'Per run')
  1008.                     print '  User  : %10s s, %10s s.' % (t_usr, t_usr / nruns)
  1009.                     print '  System: %10s s, %10s s.' % (t_sys, t_sys / nruns)
  1010.             else:
  1011.                 runner(filename, prog_ns, prog_ns, exit_ignore = exit_ignore)
  1012.             if opts.has_key('i'):
  1013.                 self.shell.user_ns['__name__'] = _Magic__name__save
  1014.             else:
  1015.                 self.shell.cache_main_mod(prog_ns, filename)
  1016.                 prog_ns.pop('__name__', None)
  1017.                 self.shell.user_ns.update(prog_ns)
  1018.         finally:
  1019.             self.shell.user_ns['__builtins__'] = __builtin__
  1020.             sys.argv = save_argv
  1021.             if restore_main:
  1022.                 sys.modules['__main__'] = restore_main
  1023.             else:
  1024.                 del sys.modules[main_mod_name]
  1025.             self.shell.reloadhist()
  1026.  
  1027.         return stats
  1028.  
  1029.     magic_run = testdec.skip_doctest(magic_run)
  1030.     
  1031.     def magic_runlog(self, parameter_s = ''):
  1032.         for f in parameter_s.split():
  1033.             self.shell.safe_execfile(f, self.shell.user_ns, self.shell.user_ns, islog = 1)
  1034.         
  1035.  
  1036.     
  1037.     def magic_timeit(self, parameter_s = ''):
  1038.         import timeit
  1039.         import math
  1040.         units = [
  1041.             u's',
  1042.             u'ms',
  1043.             u'us',
  1044.             'ns']
  1045.         scaling = [
  1046.             1,
  1047.             1000,
  1048.             1e+06,
  1049.             1e+09]
  1050.         (opts, stmt) = self.parse_options(parameter_s, 'n:r:tcp:', posix = False)
  1051.         if stmt == '':
  1052.             return None
  1053.         timefunc = timeit.default_timer
  1054.         number = int(getattr(opts, 'n', 0))
  1055.         repeat = int(getattr(opts, 'r', timeit.default_repeat))
  1056.         precision = int(getattr(opts, 'p', 3))
  1057.         if hasattr(opts, 't'):
  1058.             timefunc = time.time
  1059.         
  1060.         if hasattr(opts, 'c'):
  1061.             timefunc = clock
  1062.         
  1063.         timer = timeit.Timer(timer = timefunc)
  1064.         src = timeit.template % {
  1065.             'stmt': timeit.reindent(stmt, 8),
  1066.             'setup': 'pass' }
  1067.         tc_min = 0.1
  1068.         t0 = clock()
  1069.         code = compile(src, '<magic-timeit>', 'exec')
  1070.         tc = clock() - t0
  1071.         ns = { }
  1072.         exec code in self.shell.user_ns, ns
  1073.         timer.inner = ns['inner']
  1074.         if number == 0:
  1075.             number = 1
  1076.             for i in range(1, 10):
  1077.                 if timer.timeit(number) >= 0.2:
  1078.                     break
  1079.                 
  1080.                 number *= 10
  1081.             
  1082.         
  1083.         best = min(timer.repeat(repeat, number)) / number
  1084.         if best > 0:
  1085.             order = min(-int(math.floor(math.log10(best)) // 3), 3)
  1086.         else:
  1087.             order = 3
  1088.         print u'%d loops, best of %d: %.*g %s per loop' % (number, repeat, precision, best * scaling[order], units[order])
  1089.         if tc > tc_min:
  1090.             print 'Compiler time: %.2f s' % tc
  1091.         
  1092.  
  1093.     magic_timeit = testdec.skip_doctest(magic_timeit)
  1094.     
  1095.     def magic_time(self, parameter_s = ''):
  1096.         expr = self.shell.prefilter(parameter_s, False)
  1097.         tc_min = 0.1
  1098.         
  1099.         try:
  1100.             mode = 'eval'
  1101.             t0 = clock()
  1102.             code = compile(expr, '<timed eval>', mode)
  1103.             tc = clock() - t0
  1104.         except SyntaxError:
  1105.             mode = 'exec'
  1106.             t0 = clock()
  1107.             code = compile(expr, '<timed exec>', mode)
  1108.             tc = clock() - t0
  1109.  
  1110.         glob = self.shell.user_ns
  1111.         clk = clock2
  1112.         wtime = time.time
  1113.         wall_st = wtime()
  1114.         if mode == 'eval':
  1115.             st = clk()
  1116.             out = eval(code, glob)
  1117.             end = clk()
  1118.         else:
  1119.             st = clk()
  1120.             exec code in glob
  1121.             end = clk()
  1122.             out = None
  1123.         wall_end = wtime()
  1124.         wall_time = wall_end - wall_st
  1125.         cpu_user = end[0] - st[0]
  1126.         cpu_sys = end[1] - st[1]
  1127.         cpu_tot = cpu_user + cpu_sys
  1128.         print 'CPU times: user %.2f s, sys: %.2f s, total: %.2f s' % (cpu_user, cpu_sys, cpu_tot)
  1129.         print 'Wall time: %.2f s' % wall_time
  1130.         if tc > tc_min:
  1131.             print 'Compiler : %.2f s' % tc
  1132.         
  1133.         return out
  1134.  
  1135.     magic_time = testdec.skip_doctest(magic_time)
  1136.     
  1137.     def magic_macro(self, parameter_s = ''):
  1138.         (opts, args) = self.parse_options(parameter_s, 'r', mode = 'list')
  1139.         if not args:
  1140.             macs = _[1]
  1141.             macs.sort()
  1142.             return macs
  1143.         if len(args) == 1:
  1144.             raise UsageError("%macro insufficient args; usage '%macro name n1-n2 n3-4...")
  1145.         len(args) == 1
  1146.         name = args[0]
  1147.         ranges = args[1:]
  1148.         lines = self.extract_input_slices(ranges, opts.has_key('r'))
  1149.         macro = Macro(lines)
  1150.         self.shell.user_ns.update({
  1151.             name: macro })
  1152.         print 'Macro `%s` created. To execute, type its name (without quotes).' % name
  1153.         print 'Macro contents:'
  1154.         print macro,
  1155.  
  1156.     magic_macro = testdec.skip_doctest(magic_macro)
  1157.     
  1158.     def magic_save(self, parameter_s = ''):
  1159.         (opts, args) = self.parse_options(parameter_s, 'r', mode = 'list')
  1160.         fname = args[0]
  1161.         ranges = args[1:]
  1162.         if not fname.endswith('.py'):
  1163.             fname += '.py'
  1164.         
  1165.         if os.path.isfile(fname):
  1166.             ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
  1167.             if ans.lower() not in ('y', 'yes'):
  1168.                 print 'Operation cancelled.'
  1169.                 return None
  1170.         
  1171.         cmds = ''.join(self.extract_input_slices(ranges, opts.has_key('r')))
  1172.         f = file(fname, 'w')
  1173.         f.write(cmds)
  1174.         f.close()
  1175.         print 'The following commands were written to file `%s`:' % fname
  1176.         print cmds
  1177.  
  1178.     
  1179.     def _edit_macro(self, mname, macro):
  1180.         filename = self.shell.mktempfile(macro.value)
  1181.         self.shell.hooks.editor(filename)
  1182.         mfile = open(filename)
  1183.         mvalue = mfile.read()
  1184.         mfile.close()
  1185.         self.shell.user_ns[mname] = Macro(mvalue)
  1186.  
  1187.     
  1188.     def magic_ed(self, parameter_s = ''):
  1189.         return self.magic_edit(parameter_s)
  1190.  
  1191.     
  1192.     def magic_edit(self, parameter_s = '', last_call = [
  1193.         '',
  1194.         '']):
  1195.         
  1196.         def make_filename(arg):
  1197.             
  1198.             try:
  1199.                 filename = get_py_filename(arg)
  1200.             except IOError:
  1201.                 if args.endswith('.py'):
  1202.                     filename = arg
  1203.                 else:
  1204.                     filename = None
  1205.             except:
  1206.                 args.endswith('.py')
  1207.  
  1208.             return filename
  1209.  
  1210.         
  1211.         class DataIsObject(Exception):
  1212.             pass
  1213.  
  1214.         (opts, args) = self.parse_options(parameter_s, 'prxn:')
  1215.         opts_p = opts.has_key('p')
  1216.         opts_r = opts.has_key('r')
  1217.         lineno = opts.get('n', None)
  1218.         if opts_p:
  1219.             args = '_%s' % last_call[0]
  1220.             if not self.shell.user_ns.has_key(args):
  1221.                 args = last_call[1]
  1222.             
  1223.         
  1224.         
  1225.         try:
  1226.             last_call[0] = self.shell.outputcache.prompt_count
  1227.             if not opts_p:
  1228.                 last_call[1] = parameter_s
  1229.         except:
  1230.             pass
  1231.  
  1232.         use_temp = 1
  1233.         if re.match('\\d', args):
  1234.             ranges = args.split()
  1235.             data = ''.join(self.extract_input_slices(ranges, opts_r))
  1236.         elif args.endswith('.py'):
  1237.             filename = make_filename(args)
  1238.             data = ''
  1239.             use_temp = 0
  1240.         elif args:
  1241.             
  1242.             try:
  1243.                 data = eval(args, self.shell.user_ns)
  1244.                 if type(data) not in StringTypes:
  1245.                     raise DataIsObject
  1246.                 type(data) not in StringTypes
  1247.             except (NameError, SyntaxError):
  1248.                 filename = make_filename(args)
  1249.                 if filename is None:
  1250.                     warn("Argument given (%s) can't be found as a variable or as a filename." % args)
  1251.                     return None
  1252.                 data = ''
  1253.                 use_temp = 0
  1254.             except DataIsObject:
  1255.                 if isinstance(data, Macro):
  1256.                     self._edit_macro(args, data)
  1257.                     return None
  1258.                 
  1259.                 try:
  1260.                     filename = inspect.getabsfile(data)
  1261.                     if 'fakemodule' in filename.lower() and inspect.isclass(data):
  1262.                         attrs = [ getattr(data, aname) for aname in dir(data) ]
  1263.                         for attr in attrs:
  1264.                             filename = inspect.getabsfile(attr)
  1265.                             if filename and 'fakemodule' not in filename.lower():
  1266.                                 data = attr
  1267.                                 break
  1268.                                 continue
  1269.                             isinstance(data, Macro) if not inspect.ismethod(attr) else []
  1270.                         
  1271.                     
  1272.                     datafile = 1
  1273.                 except TypeError:
  1274.                     isinstance(data, Macro)
  1275.                     isinstance(data, Macro)
  1276.                     filename = make_filename(args)
  1277.                     datafile = 1
  1278.                     warn('Could not find file where `%s` is defined.\nOpening a file named `%s`' % (args, filename))
  1279.                 except:
  1280.                     isinstance(data, Macro)
  1281.  
  1282.                 if datafile:
  1283.                     
  1284.                     try:
  1285.                         if lineno is None:
  1286.                             lineno = inspect.getsourcelines(data)[1]
  1287.                     except IOError:
  1288.                         isinstance(data, Macro)
  1289.                         isinstance(data, Macro)
  1290.                         filename = make_filename(args)
  1291.                         if filename is None:
  1292.                             warn('The file `%s` where `%s` was defined cannot be read.' % (filename, data))
  1293.                             return None
  1294.                     except:
  1295.                         isinstance(data, Macro)<EXCEPTION MATCH>IOError
  1296.                     
  1297.  
  1298.                 isinstance(data, Macro)
  1299.                 use_temp = 0
  1300.             except:
  1301.                 None<EXCEPTION MATCH>(NameError, SyntaxError)
  1302.             
  1303.  
  1304.         None<EXCEPTION MATCH>(NameError, SyntaxError)
  1305.         data = ''
  1306.         if use_temp:
  1307.             filename = self.shell.mktempfile(data)
  1308.             print 'IPython will make a temporary file named:', filename
  1309.         
  1310.         print 'Editing...',
  1311.         sys.stdout.flush()
  1312.         
  1313.         try:
  1314.             self.shell.hooks.editor(filename, lineno)
  1315.         except IPython.ipapi.TryNext:
  1316.             warn('Could not open editor')
  1317.             return None
  1318.  
  1319.         if args.strip() == 'pasted_block':
  1320.             self.shell.user_ns['pasted_block'] = file_read(filename)
  1321.         
  1322.         if opts.has_key('x'):
  1323.             print 
  1324.         else:
  1325.             print 'done. Executing edited code...'
  1326.             if opts_r:
  1327.                 self.shell.runlines(file_read(filename))
  1328.             else:
  1329.                 self.shell.safe_execfile(filename, self.shell.user_ns, self.shell.user_ns)
  1330.         if use_temp:
  1331.             
  1332.             try:
  1333.                 return open(filename).read()
  1334.             except IOError:
  1335.                 msg = None
  1336.                 if msg.filename == filename:
  1337.                     warn('File not found. Did you forget to save?')
  1338.                     return None
  1339.                 self.shell.showtraceback()
  1340.             except:
  1341.                 None<EXCEPTION MATCH>IOError
  1342.             
  1343.  
  1344.         None<EXCEPTION MATCH>IOError
  1345.  
  1346.     magic_edit = testdec.skip_doctest(magic_edit)
  1347.     
  1348.     def magic_xmode(self, parameter_s = ''):
  1349.         
  1350.         def xmode_switch_err(name):
  1351.             warn('Error changing %s exception modes.\n%s' % (name, sys.exc_info()[1]))
  1352.  
  1353.         shell = self.shell
  1354.         new_mode = parameter_s.strip().capitalize()
  1355.         
  1356.         try:
  1357.             shell.InteractiveTB.set_mode(mode = new_mode)
  1358.             print 'Exception reporting mode:', shell.InteractiveTB.mode
  1359.         except:
  1360.             xmode_switch_err('user')
  1361.  
  1362.         if shell.isthreaded:
  1363.             
  1364.             try:
  1365.                 shell.sys_excepthook.set_mode(mode = new_mode)
  1366.             xmode_switch_err('threaded')
  1367.  
  1368.         
  1369.  
  1370.     
  1371.     def magic_colors(self, parameter_s = ''):
  1372.         
  1373.         def color_switch_err(name):
  1374.             warn('Error changing %s color schemes.\n%s' % (name, sys.exc_info()[1]))
  1375.  
  1376.         new_scheme = parameter_s.strip()
  1377.         if not new_scheme:
  1378.             raise UsageError("%colors: you must specify a color scheme. See '%colors?'")
  1379.         return new_scheme
  1380.         shell = self.shell
  1381.         import IPython.rlineimpl as readline
  1382.         if not (readline.have_readline) and sys.platform == 'win32':
  1383.             msg = "Proper color support under MS Windows requires the pyreadline library.\nYou can find it at:\nhttp://ipython.scipy.org/moin/PyReadline/Intro\nGary's readline needs the ctypes module, from:\nhttp://starship.python.net/crew/theller/ctypes\n(Note that ctypes is already part of Python versions 2.5 and newer).\n\nDefaulting color scheme to 'NoColor'"
  1384.             new_scheme = 'NoColor'
  1385.             warn(msg)
  1386.         
  1387.         if not shell.has_readline:
  1388.             new_scheme = 'NoColor'
  1389.         
  1390.         
  1391.         try:
  1392.             shell.outputcache.set_colors(new_scheme)
  1393.         except:
  1394.             color_switch_err('prompt')
  1395.  
  1396.         shell.rc.colors = shell.outputcache.color_table.active_scheme_name
  1397.         
  1398.         try:
  1399.             shell.InteractiveTB.set_colors(scheme = new_scheme)
  1400.             shell.SyntaxTB.set_colors(scheme = new_scheme)
  1401.         except:
  1402.             color_switch_err('exception')
  1403.  
  1404.         if shell.isthreaded:
  1405.             
  1406.             try:
  1407.                 shell.sys_excepthook.set_colors(scheme = new_scheme)
  1408.             color_switch_err('system exception handler')
  1409.  
  1410.         
  1411.         if shell.rc.color_info:
  1412.             
  1413.             try:
  1414.                 shell.inspector.set_active_scheme(new_scheme)
  1415.             color_switch_err('object inspector')
  1416.  
  1417.         else:
  1418.             shell.inspector.set_active_scheme('NoColor')
  1419.  
  1420.     
  1421.     def magic_color_info(self, parameter_s = ''):
  1422.         self.shell.rc.color_info = 1 - self.shell.rc.color_info
  1423.         self.magic_colors(self.shell.rc.colors)
  1424.         print 'Object introspection functions have now coloring:', [
  1425.             'OFF',
  1426.             'ON'][self.shell.rc.color_info]
  1427.  
  1428.     
  1429.     def magic_Pprint(self, parameter_s = ''):
  1430.         self.shell.rc.pprint = 1 - self.shell.rc.pprint
  1431.         print 'Pretty printing has been turned', [
  1432.             'OFF',
  1433.             'ON'][self.shell.rc.pprint]
  1434.  
  1435.     
  1436.     def magic_exit(self, parameter_s = ''):
  1437.         self.shell.exit()
  1438.  
  1439.     
  1440.     def magic_quit(self, parameter_s = ''):
  1441.         self.shell.exit()
  1442.  
  1443.     
  1444.     def magic_Exit(self, parameter_s = ''):
  1445.         self.shell.ask_exit()
  1446.  
  1447.     
  1448.     def magic_alias(self, parameter_s = ''):
  1449.         par = parameter_s.strip()
  1450.         if not par:
  1451.             stored = self.db.get('stored_aliases', { })
  1452.             atab = self.shell.alias_table
  1453.             aliases = atab.keys()
  1454.             aliases.sort()
  1455.             res = []
  1456.             showlast = []
  1457.             for alias in aliases:
  1458.                 special = False
  1459.                 
  1460.                 try:
  1461.                     tgt = atab[alias][1]
  1462.                 except (TypeError, AttributeError):
  1463.                     tgt = atab[alias]
  1464.                     special = True
  1465.  
  1466.                 if alias in stored and special and alias.lower() != os.path.splitext(tgt)[0].lower() or ' ' in tgt:
  1467.                     showlast.append((alias, tgt))
  1468.                     continue
  1469.                 res.append((alias, tgt))
  1470.             
  1471.             res.extend(showlast)
  1472.             print 'Total number of aliases:', len(aliases)
  1473.             return res
  1474.         
  1475.         try:
  1476.             (alias, cmd) = par.split(None, 1)
  1477.         except:
  1478.             par
  1479.             print OInspect.getdoc(self.magic_alias)
  1480.  
  1481.         nargs = cmd.count('%s')
  1482.         if nargs > 0 and cmd.find('%l') >= 0:
  1483.             error('The %s and %l specifiers are mutually exclusive in alias definitions.')
  1484.         else:
  1485.             self.shell.alias_table[alias] = (nargs, cmd)
  1486.             self.shell.alias_table_validate(verbose = 0)
  1487.  
  1488.     magic_alias = testdec.skip_doctest(magic_alias)
  1489.     
  1490.     def magic_unalias(self, parameter_s = ''):
  1491.         aname = parameter_s.strip()
  1492.         if aname in self.shell.alias_table:
  1493.             del self.shell.alias_table[aname]
  1494.         
  1495.         stored = self.db.get('stored_aliases', { })
  1496.         if aname in stored:
  1497.             print 'Removing %stored alias', aname
  1498.             del stored[aname]
  1499.             self.db['stored_aliases'] = stored
  1500.         
  1501.  
  1502.     
  1503.     def magic_rehashx(self, parameter_s = ''):
  1504.         ip = self.api
  1505.         del ip.db['rootmodules']
  1506.         path = [ os.path.abspath(os.path.expanduser(p)) for p in os.environ.get('PATH', '').split(os.pathsep) ]
  1507.         path = filter(os.path.isdir, path)
  1508.         alias_table = self.shell.alias_table
  1509.         syscmdlist = []
  1510.         savedir = os.getcwd()
  1511.         
  1512.         try:
  1513.             if os.name == 'posix':
  1514.                 for pdir in path:
  1515.                     os.chdir(pdir)
  1516.                     for ff in os.listdir(pdir):
  1517.                         if isexec(ff) and ff not in self.shell.no_alias:
  1518.                             alias_table[ff.replace('.', '')] = (0, ff)
  1519.                             syscmdlist.append(ff)
  1520.                             continue
  1521.                         None if os.name == 'posix' else (None,)
  1522.                     
  1523.                 
  1524.             else:
  1525.                 for pdir in path:
  1526.                     os.chdir(pdir)
  1527.                     for ff in os.listdir(pdir):
  1528.                         (base, ext) = os.path.splitext(ff)
  1529.                         if isexec(ff) and base.lower() not in self.shell.no_alias:
  1530.                             if ext.lower() == '.exe':
  1531.                                 ff = base
  1532.                             
  1533.                             alias_table[base.lower().replace('.', '')] = (0, ff)
  1534.                             syscmdlist.append(ff)
  1535.                             continue
  1536.                     
  1537.                 
  1538.             self.shell.alias_table_validate()
  1539.             db = ip.db
  1540.             db['syscmdlist'] = syscmdlist
  1541.         finally:
  1542.             os.chdir(savedir)
  1543.  
  1544.  
  1545.     
  1546.     def magic_pwd(self, parameter_s = ''):
  1547.         return os.getcwd()
  1548.  
  1549.     
  1550.     def magic_cd(self, parameter_s = ''):
  1551.         parameter_s = parameter_s.strip()
  1552.         oldcwd = os.getcwd()
  1553.         numcd = re.match('(-)(\\d+)$', parameter_s)
  1554.         if numcd:
  1555.             nn = int(numcd.group(2))
  1556.             
  1557.             try:
  1558.                 ps = self.shell.user_ns['_dh'][nn]
  1559.             except IndexError:
  1560.                 print 'The requested directory does not exist in history.'
  1561.                 return None
  1562.  
  1563.             opts = { }
  1564.         elif parameter_s.startswith('--'):
  1565.             ps = None
  1566.             fallback = None
  1567.             pat = parameter_s[2:]
  1568.             dh = self.shell.user_ns['_dh']
  1569.             for ent in reversed(dh):
  1570.                 if pat in os.path.basename(ent) and os.path.isdir(ent):
  1571.                     ps = ent
  1572.                     break
  1573.                 
  1574.                 if fallback is None and pat in ent and os.path.isdir(ent):
  1575.                     fallback = ent
  1576.                     continue
  1577.             
  1578.             if ps is None:
  1579.                 ps = fallback
  1580.             
  1581.             if ps is None:
  1582.                 print 'No matching entry in directory history'
  1583.                 return None
  1584.             opts = { }
  1585.         else:
  1586.             parameter_s = re.sub('\\\\(?! )', '/', parameter_s)
  1587.             (opts, ps) = self.parse_options(parameter_s, 'qb', mode = 'string')
  1588.         if ps == '-':
  1589.             
  1590.             try:
  1591.                 ps = self.shell.user_ns['_dh'][-2]
  1592.             except IndexError:
  1593.                 raise UsageError('%cd -: No previous directory to change to.')
  1594.             except:
  1595.                 None<EXCEPTION MATCH>IndexError
  1596.             
  1597.  
  1598.         None<EXCEPTION MATCH>IndexError
  1599.         if not os.path.isdir(ps) or opts.has_key('b'):
  1600.             bkms = self.db.get('bookmarks', { })
  1601.             if bkms.has_key(ps):
  1602.                 target = bkms[ps]
  1603.                 print '(bookmark:%s) -> %s' % (ps, target)
  1604.                 ps = target
  1605.             elif opts.has_key('b'):
  1606.                 raise UsageError("Bookmark '%s' not found.  Use '%%bookmark -l' to see your bookmarks." % ps)
  1607.             
  1608.         
  1609.         if ps:
  1610.             
  1611.             try:
  1612.                 os.chdir(os.path.expanduser(ps))
  1613.                 if self.shell.rc.term_title:
  1614.                     platutils.set_term_title('IPy ' + abbrev_cwd())
  1615.             except OSError:
  1616.                 print sys.exc_info()[1]
  1617.  
  1618.             cwd = os.getcwd()
  1619.             dhist = self.shell.user_ns['_dh']
  1620.             if oldcwd != cwd:
  1621.                 dhist.append(cwd)
  1622.                 self.db['dhist'] = compress_dhist(dhist)[-100:]
  1623.             
  1624.         else:
  1625.             os.chdir(self.shell.home_dir)
  1626.             if self.shell.rc.term_title:
  1627.                 platutils.set_term_title('IPy ~')
  1628.             
  1629.             cwd = os.getcwd()
  1630.             dhist = self.shell.user_ns['_dh']
  1631.             if oldcwd != cwd:
  1632.                 dhist.append(cwd)
  1633.                 self.db['dhist'] = compress_dhist(dhist)[-100:]
  1634.             
  1635.         if 'q' not in opts and self.shell.user_ns['_dh']:
  1636.             print self.shell.user_ns['_dh'][-1]
  1637.         
  1638.  
  1639.     
  1640.     def magic_env(self, parameter_s = ''):
  1641.         return os.environ.data
  1642.  
  1643.     
  1644.     def magic_pushd(self, parameter_s = ''):
  1645.         dir_s = self.shell.dir_stack
  1646.         tgt = os.path.expanduser(parameter_s)
  1647.         cwd = os.getcwd().replace(self.home_dir, '~')
  1648.         if tgt:
  1649.             self.magic_cd(parameter_s)
  1650.         
  1651.         dir_s.insert(0, cwd)
  1652.         return self.magic_dirs()
  1653.  
  1654.     
  1655.     def magic_popd(self, parameter_s = ''):
  1656.         if not self.shell.dir_stack:
  1657.             raise UsageError('%popd on empty stack')
  1658.         self.shell.dir_stack
  1659.         top = self.shell.dir_stack.pop(0)
  1660.         self.magic_cd(top)
  1661.         print 'popd ->', top
  1662.  
  1663.     
  1664.     def magic_dirs(self, parameter_s = ''):
  1665.         return self.shell.dir_stack
  1666.  
  1667.     
  1668.     def magic_dhist(self, parameter_s = ''):
  1669.         dh = self.shell.user_ns['_dh']
  1670.         if parameter_s:
  1671.             
  1672.             try:
  1673.                 args = map(int, parameter_s.split())
  1674.             except:
  1675.                 self.arg_err(Magic.magic_dhist)
  1676.                 return None
  1677.  
  1678.             if len(args) == 1:
  1679.                 ini = max(len(dh) - args[0], 0)
  1680.                 fin = len(dh)
  1681.             elif len(args) == 2:
  1682.                 (ini, fin) = args
  1683.             else:
  1684.                 self.arg_err(Magic.magic_dhist)
  1685.                 return None
  1686.         len(args) == 1
  1687.         ini = 0
  1688.         fin = len(dh)
  1689.         nlprint(dh, header = 'Directory history (kept in _dh)', start = ini, stop = fin)
  1690.  
  1691.     
  1692.     def magic_sc(self, parameter_s = ''):
  1693.         (opts, args) = self.parse_options(parameter_s, 'lv')
  1694.         
  1695.         try:
  1696.             (var, _) = args.split('=', 1)
  1697.             var = var.strip()
  1698.             (_, cmd) = parameter_s.split('=', 1)
  1699.         except ValueError:
  1700.             (var, cmd) = ('', '')
  1701.  
  1702.         (out, err) = self.shell.getoutputerror(cmd)
  1703.         if err:
  1704.             print >>Term.cerr, err
  1705.         
  1706.         if opts.has_key('l'):
  1707.             out = SList(out.split('\n'))
  1708.         else:
  1709.             out = LSString(out)
  1710.         if opts.has_key('v'):
  1711.             print '%s ==\n%s' % (var, pformat(out))
  1712.         
  1713.         if var:
  1714.             self.shell.user_ns.update({
  1715.                 var: out })
  1716.         else:
  1717.             return out
  1718.         return var
  1719.  
  1720.     magic_sc = testdec.skip_doctest(magic_sc)
  1721.     
  1722.     def magic_sx(self, parameter_s = ''):
  1723.         if parameter_s:
  1724.             (out, err) = self.shell.getoutputerror(parameter_s)
  1725.             if err:
  1726.                 print >>Term.cerr, err
  1727.             
  1728.             return SList(out.split('\n'))
  1729.  
  1730.     
  1731.     def magic_bg(self, parameter_s = ''):
  1732.         self.shell.jobs.new(parameter_s, self.shell.user_ns)
  1733.  
  1734.     
  1735.     def magic_r(self, parameter_s = ''):
  1736.         start = parameter_s.strip()
  1737.         esc_magic = self.shell.ESC_MAGIC
  1738.         if self.shell.rc.automagic:
  1739.             start_magic = esc_magic + start
  1740.         else:
  1741.             start_magic = start
  1742.         for n in range(len(self.shell.input_hist) - 2, 0, -1):
  1743.             input = self.shell.input_hist[n]
  1744.             if input != '_ip.magic("r")\n':
  1745.                 if input.startswith(start) or input.startswith(start_magic):
  1746.                     print 'Executing:', input,
  1747.                     self.shell.runlines(input)
  1748.                     return None
  1749.         print 'No previous input matching `%s` found.' % start
  1750.  
  1751.     
  1752.     def magic_bookmark(self, parameter_s = ''):
  1753.         (opts, args) = self.parse_options(parameter_s, 'drl', mode = 'list')
  1754.         if len(args) > 2:
  1755.             raise UsageError('%bookmark: too many arguments')
  1756.         len(args) > 2
  1757.         bkms = self.db.get('bookmarks', { })
  1758.         if opts.has_key('d'):
  1759.             
  1760.             try:
  1761.                 todel = args[0]
  1762.             except IndexError:
  1763.                 raise UsageError('%bookmark -d: must provide a bookmark to delete')
  1764.  
  1765.             
  1766.             try:
  1767.                 del bkms[todel]
  1768.             except KeyError:
  1769.                 raise UsageError("%%bookmark -d: Can't delete bookmark '%s'" % todel)
  1770.             except:
  1771.                 None<EXCEPTION MATCH>KeyError
  1772.             
  1773.  
  1774.         None<EXCEPTION MATCH>KeyError
  1775.         if opts.has_key('r'):
  1776.             bkms = { }
  1777.         elif opts.has_key('l'):
  1778.             bks = bkms.keys()
  1779.             bks.sort()
  1780.             if bks:
  1781.                 size = max(map(len, bks))
  1782.             else:
  1783.                 size = 0
  1784.             fmt = '%-' + str(size) + 's -> %s'
  1785.             print 'Current bookmarks:'
  1786.             for bk in bks:
  1787.                 print fmt % (bk, bkms[bk])
  1788.             
  1789.         elif not args:
  1790.             raise UsageError('%bookmark: You must specify the bookmark name')
  1791.         elif len(args) == 1:
  1792.             bkms[args[0]] = os.getcwd()
  1793.         elif len(args) == 2:
  1794.             bkms[args[0]] = args[1]
  1795.         
  1796.         self.db['bookmarks'] = bkms
  1797.  
  1798.     
  1799.     def magic_pycat(self, parameter_s = ''):
  1800.         
  1801.         try:
  1802.             filename = get_py_filename(parameter_s)
  1803.             cont = file_read(filename)
  1804.         except IOError:
  1805.             
  1806.             try:
  1807.                 cont = eval(parameter_s, self.user_ns)
  1808.             except NameError:
  1809.                 cont = None
  1810.             except:
  1811.                 None<EXCEPTION MATCH>NameError
  1812.             
  1813.  
  1814.             None<EXCEPTION MATCH>NameError
  1815.  
  1816.         if cont is None:
  1817.             print 'Error: no such file or variable'
  1818.             return None
  1819.         page(self.shell.pycolorize(cont), screen_lines = self.shell.rc.screen_length)
  1820.  
  1821.     
  1822.     def _rerun_pasted(self):
  1823.         b = self.user_ns.get('pasted_block', None)
  1824.         if b is None:
  1825.             raise UsageError('No previous pasted block available')
  1826.         b is None
  1827.         print "Re-executing '%s...' (%d chars)" % (b.split('\n', 1)[0], len(b))
  1828.         exec b in self.user_ns
  1829.  
  1830.     
  1831.     def _get_pasted_lines(self, sentinel):
  1832.         iplib = iplib
  1833.         import IPython
  1834.         print "Pasting code; enter '%s' alone on the line to stop." % sentinel
  1835.         while True:
  1836.             l = iplib.raw_input_original(':')
  1837.             if l == sentinel:
  1838.                 return None
  1839.             yield l
  1840.             l == sentinel
  1841.  
  1842.     
  1843.     def _strip_pasted_lines_for_code(self, raw_lines):
  1844.         strip_re = [
  1845.             '^\\s*In \\[\\d+\\]:',
  1846.             '^\\s*(\\s?>)+',
  1847.             '^\\s*\\.{3,}',
  1848.             '^\\++']
  1849.         strip_from_start = map(re.compile, strip_re)
  1850.         lines = []
  1851.         for l in raw_lines:
  1852.             for pat in strip_from_start:
  1853.                 l = pat.sub('', l)
  1854.             
  1855.             lines.append(l)
  1856.         
  1857.         block = '\n'.join(lines) + '\n'
  1858.         return block
  1859.  
  1860.     
  1861.     def _execute_block(self, block, par):
  1862.         if not par:
  1863.             b = textwrap.dedent(block)
  1864.             self.user_ns['pasted_block'] = b
  1865.             exec b in self.user_ns
  1866.         else:
  1867.             self.user_ns[par] = SList(block.splitlines())
  1868.             print "Block assigned to '%s'" % par
  1869.  
  1870.     
  1871.     def magic_cpaste(self, parameter_s = ''):
  1872.         (opts, args) = self.parse_options(parameter_s, 'rs:', mode = 'string')
  1873.         par = args.strip()
  1874.         if opts.has_key('r'):
  1875.             self._rerun_pasted()
  1876.             return None
  1877.         sentinel = opts.get('s', '--')
  1878.         block = self._strip_pasted_lines_for_code(self._get_pasted_lines(sentinel))
  1879.         self._execute_block(block, par)
  1880.  
  1881.     
  1882.     def magic_paste(self, parameter_s = ''):
  1883.         (opts, args) = self.parse_options(parameter_s, 'r:', mode = 'string')
  1884.         par = args.strip()
  1885.         if opts.has_key('r'):
  1886.             self._rerun_pasted()
  1887.             return None
  1888.         text = self.shell.hooks.clipboard_get()
  1889.         block = self._strip_pasted_lines_for_code(text.splitlines())
  1890.         self._execute_block(block, par)
  1891.  
  1892.     
  1893.     def magic_quickref(self, arg):
  1894.         import IPython.usage as IPython
  1895.         qr = IPython.usage.quick_reference + self.magic_magic('-brief')
  1896.         page(qr)
  1897.  
  1898.     
  1899.     def magic_upgrade(self, arg):
  1900.         ip = self.getapi()
  1901.         ipinstallation = path(IPython.__file__).dirname()
  1902.         upgrade_script = '%s "%s"' % (sys.executable, ipinstallation / 'upgrade_dir.py')
  1903.         src_config = ipinstallation / 'UserConfig'
  1904.         userdir = path(ip.options.ipythondir)
  1905.         cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
  1906.         print '>', cmd
  1907.         shell(cmd)
  1908.  
  1909.     
  1910.     def magic_doctest_mode(self, parameter_s = ''):
  1911.         ipaste = InterpreterPasteInput
  1912.         import IPython.Extensions
  1913.         Struct = Struct
  1914.         import IPython.ipstruct
  1915.         shell = self.shell
  1916.         oc = shell.outputcache
  1917.         rc = shell.rc
  1918.         meta = shell.meta
  1919.         dstore = meta.setdefault('doctest_mode', Struct())
  1920.         save_dstore = dstore.setdefault
  1921.         mode = save_dstore('mode', False)
  1922.         save_dstore('rc_pprint', rc.pprint)
  1923.         save_dstore('xmode', shell.InteractiveTB.mode)
  1924.         save_dstore('rc_separate_out', rc.separate_out)
  1925.         save_dstore('rc_separate_out2', rc.separate_out2)
  1926.         save_dstore('rc_prompts_pad_left', rc.prompts_pad_left)
  1927.         save_dstore('rc_separate_in', rc.separate_in)
  1928.         if mode == False:
  1929.             ipaste.activate_prefilter()
  1930.             oc.prompt1.p_template = '>>> '
  1931.             oc.prompt2.p_template = '... '
  1932.             oc.prompt_out.p_template = ''
  1933.             oc.input_sep = oc.prompt1.sep = ''
  1934.             oc.output_sep = ''
  1935.             oc.output_sep2 = ''
  1936.             oc.prompt1.pad_left = oc.prompt2.pad_left = oc.prompt_out.pad_left = False
  1937.             rc.pprint = False
  1938.             shell.magic_xmode('Plain')
  1939.         else:
  1940.             ipaste.deactivate_prefilter()
  1941.             oc.prompt1.p_template = rc.prompt_in1
  1942.             oc.prompt2.p_template = rc.prompt_in2
  1943.             oc.prompt_out.p_template = rc.prompt_out
  1944.             oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
  1945.             oc.output_sep = dstore.rc_separate_out
  1946.             oc.output_sep2 = dstore.rc_separate_out2
  1947.             oc.prompt1.pad_left = oc.prompt2.pad_left = oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
  1948.             rc.pprint = dstore.rc_pprint
  1949.             shell.magic_xmode(dstore.xmode)
  1950.         dstore.mode = bool(1 - int(mode))
  1951.         print 'Doctest mode is:', [
  1952.             'OFF',
  1953.             'ON'][dstore.mode]
  1954.  
  1955.  
  1956.