def edit(self,index=None): """Edit a block. If no number is given, use the last block executed. This edits the in-memory copy of the demo, it does NOT modify the original source file. If you want to do that, simply open the file in an editor and use reload() when you make changes to the file. This method is meant to let you change a block during a demonstration for explanatory purposes, without damaging your original script.""" index = self._get_index(index) if index is None: return # decrease the index by one (unless we're at the very beginning), so # that the default demo.edit() call opens up the sblock we've last run if index>0: index -= 1 filename = self.shell.mktempfile(self.src_blocks[index]) self.shell.hooks.editor(filename,1) new_block = file_read(filename) # update the source and colored block self.src_blocks[index] = new_block self.src_blocks_colored[index] = self.ip_colorize(new_block) self.block_index = index # call to run with the newly edited index self()
def pycat(self, parameter_s=''): """Show a syntax-highlighted file through a pager. This magic is similar to the cat utility, but it will assume the file to be Python source and will show it with syntax highlighting. """ try: filename = get_py_filename(parameter_s) cont = file_read(filename) except IOError: try: cont = eval(parameter_s, self.shell.user_ns) except NameError: cont = None if cont is None: print "Error: no such file or variable" return page.page(self.shell.pycolorize(cont))
def edit(self, parameter_s='', last_call=['', '']): """Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs IPython's editor hook. The default version of this hook is set to call the editor specified by your $EDITOR environment variable. If this isn't found, it will default to vi under Linux/Unix and to notepad under Windows. See the end of this docstring for how to change the editor hook. You can also set the value of this editor via the ``TerminalInteractiveShell.editor`` option in your configuration file. This is useful if you wish to use a different editor from your typical default with IPython (and for Windows users who typically don't set environment variables). This command allows you to conveniently edit multi-line code right in your IPython session. If called without arguments, %edit opens up an empty editor with a temporary file and will execute the contents of this file when you close it (don't forget to save it!). Options: -n <number>: open the editor at a specified line number. By default, the IPython editor hook uses the unix syntax 'editor +N filename', but you can configure this by providing your own modified hook if your favorite editor supports line-number specifications with a different syntax. -p: this will call the editor with the same data as the previous time it was used, regardless of how long ago (in your current session) it was. -r: use 'raw' input. This option only applies to input taken from the user's history. By default, the 'processed' history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. When you exit the editor, it will be executed by IPython's own processor. -x: do not execute the edited code immediately upon exit. This is mainly useful if you are editing programs which need to be called with command line arguments, which you can then do using %run. Arguments: If arguments are given, the following possibilities exist: - If the argument is a filename, IPython will load that into the editor. It will execute its contents with execfile() when you exit, loading any code in the file into your interactive namespace. - The arguments are ranges of input history, e.g. "7 ~1/4-6". The syntax is the same as in the %history magic. - If the argument is a string variable, its contents are loaded into the editor. You can thus edit any string which contains python code (including the result of previous edits). - If the argument is the name of an object (other than a string), IPython will try to locate the file where it was defined and open the editor at the point where it is defined. You can use `%edit function` to load an editor exactly at the point where 'function' is defined, edit it and have the file be executed automatically. - If the object is a macro (see %macro for details), this opens up your specified editor with a temporary file containing the macro's data. Upon exit, the macro is reloaded with the contents of the file. Note: opening at an exact line is only supported under Unix, and some editors (like kedit and gedit up to Gnome 2.8) do not understand the '+NUMBER' parameter necessary for this feature. Good editors like (X)Emacs, vi, jed, pico and joe all do. After executing your code, %edit will return as output the code you typed in the editor (except when it was an existing file). This way you can reload the code in further invocations of %edit as a variable, via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the output. Note that %edit is also available through the alias %ed. This is an example of creating a simple function inside the editor and then modifying it. First, start up the editor:: In [1]: ed Editing... done. Executing edited code... Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' We can then call the function foo():: In [2]: foo() foo() was defined in an editing session Now we edit foo. IPython automatically loads the editor with the (temporary) file where foo() was previously defined:: In [3]: ed foo Editing... done. Executing edited code... And if we call foo() again we get the modified version:: In [4]: foo() foo() has now been changed! Here is an example of how to edit a code snippet successive times. First we call the editor:: In [5]: ed Editing... done. Executing edited code... hello Out[5]: "print 'hello'\\n" Now we call it again with the previous output (stored in _):: In [6]: ed _ Editing... done. Executing edited code... hello world Out[6]: "print 'hello world'\\n" Now we call it with the output #8 (stored in _8, also as Out[8]):: In [7]: ed _8 Editing... done. Executing edited code... hello again Out[7]: "print 'hello again'\\n" Changing the default editor hook: If you wish to write your own editor hook, you can put it in a configuration file which you load at startup time. The default hook is defined in the IPython.core.hooks module, and you can use that as a starting example for further modifications. That file also has general instructions on how to set a new hook for use once you've defined it.""" opts, args = self.parse_options(parameter_s, 'prxn:') try: filename, lineno, is_temp = self._find_edit_target( self.shell, args, opts, last_call) except MacroToEdit as e: self._edit_macro(args, e.args[0]) return # do actual editing here print('Editing...', end=' ') sys.stdout.flush() try: # Quote filenames that may have spaces in them if ' ' in filename: filename = "'%s'" % filename self.shell.hooks.editor(filename, lineno) except TryNext: warn('Could not open editor') return # XXX TODO: should this be generalized for all string vars? # For now, this is special-cased to blocks created by cpaste if args.strip() == 'pasted_block': self.shell.user_ns['pasted_block'] = file_read(filename) if 'x' in opts: # -x prevents actual execution print() else: print('done. Executing edited code...') if 'r' in opts: # Untranslated IPython code self.shell.run_cell(file_read(filename), store_history=False) else: self.shell.safe_execfile(filename, self.shell.user_ns, self.shell.user_ns) if is_temp: try: return open(filename).read() except IOError as msg: if msg.filename == filename: warn('File not found. Did you forget to save?') return else: self.shell.showtraceback()
def edit(self, parameter_s='',last_call=['','']): """Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs IPython's editor hook. The default version of this hook is set to call the editor specified by your $EDITOR environment variable. If this isn't found, it will default to vi under Linux/Unix and to notepad under Windows. See the end of this docstring for how to change the editor hook. You can also set the value of this editor via the ``TerminalInteractiveShell.editor`` option in your configuration file. This is useful if you wish to use a different editor from your typical default with IPython (and for Windows users who typically don't set environment variables). This command allows you to conveniently edit multi-line code right in your IPython session. If called without arguments, %edit opens up an empty editor with a temporary file and will execute the contents of this file when you close it (don't forget to save it!). Options: -n <number>: open the editor at a specified line number. By default, the IPython editor hook uses the unix syntax 'editor +N filename', but you can configure this by providing your own modified hook if your favorite editor supports line-number specifications with a different syntax. -p: this will call the editor with the same data as the previous time it was used, regardless of how long ago (in your current session) it was. -r: use 'raw' input. This option only applies to input taken from the user's history. By default, the 'processed' history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. When you exit the editor, it will be executed by IPython's own processor. -x: do not execute the edited code immediately upon exit. This is mainly useful if you are editing programs which need to be called with command line arguments, which you can then do using %run. Arguments: If arguments are given, the following possibilities exist: - If the argument is a filename, IPython will load that into the editor. It will execute its contents with execfile() when you exit, loading any code in the file into your interactive namespace. - The arguments are ranges of input history, e.g. "7 ~1/4-6". The syntax is the same as in the %history magic. - If the argument is a string variable, its contents are loaded into the editor. You can thus edit any string which contains python code (including the result of previous edits). - If the argument is the name of an object (other than a string), IPython will try to locate the file where it was defined and open the editor at the point where it is defined. You can use `%edit function` to load an editor exactly at the point where 'function' is defined, edit it and have the file be executed automatically. - If the object is a macro (see %macro for details), this opens up your specified editor with a temporary file containing the macro's data. Upon exit, the macro is reloaded with the contents of the file. Note: opening at an exact line is only supported under Unix, and some editors (like kedit and gedit up to Gnome 2.8) do not understand the '+NUMBER' parameter necessary for this feature. Good editors like (X)Emacs, vi, jed, pico and joe all do. After executing your code, %edit will return as output the code you typed in the editor (except when it was an existing file). This way you can reload the code in further invocations of %edit as a variable, via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the output. Note that %edit is also available through the alias %ed. This is an example of creating a simple function inside the editor and then modifying it. First, start up the editor:: In [1]: ed Editing... done. Executing edited code... Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' We can then call the function foo():: In [2]: foo() foo() was defined in an editing session Now we edit foo. IPython automatically loads the editor with the (temporary) file where foo() was previously defined:: In [3]: ed foo Editing... done. Executing edited code... And if we call foo() again we get the modified version:: In [4]: foo() foo() has now been changed! Here is an example of how to edit a code snippet successive times. First we call the editor:: In [5]: ed Editing... done. Executing edited code... hello Out[5]: "print 'hello'\\n" Now we call it again with the previous output (stored in _):: In [6]: ed _ Editing... done. Executing edited code... hello world Out[6]: "print 'hello world'\\n" Now we call it with the output #8 (stored in _8, also as Out[8]):: In [7]: ed _8 Editing... done. Executing edited code... hello again Out[7]: "print 'hello again'\\n" Changing the default editor hook: If you wish to write your own editor hook, you can put it in a configuration file which you load at startup time. The default hook is defined in the IPython.core.hooks module, and you can use that as a starting example for further modifications. That file also has general instructions on how to set a new hook for use once you've defined it.""" opts,args = self.parse_options(parameter_s,'prxn:') try: filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) except MacroToEdit as e: self._edit_macro(args, e.args[0]) return # do actual editing here print('Editing...', end=' ') sys.stdout.flush() try: # Quote filenames that may have spaces in them if ' ' in filename: filename = "'%s'" % filename self.shell.hooks.editor(filename,lineno) except TryNext: warn('Could not open editor') return # XXX TODO: should this be generalized for all string vars? # For now, this is special-cased to blocks created by cpaste if args.strip() == 'pasted_block': self.shell.user_ns['pasted_block'] = file_read(filename) if 'x' in opts: # -x prevents actual execution print() else: print('done. Executing edited code...') if 'r' in opts: # Untranslated IPython code self.shell.run_cell(file_read(filename), store_history=False) else: self.shell.safe_execfile(filename, self.shell.user_ns, self.shell.user_ns) if is_temp: try: return open(filename).read() except IOError as msg: if msg.filename == filename: warn('File not found. Did you forget to save?') return else: self.shell.showtraceback()