history.py
598 lines
| 21.9 KiB
| text/x-python
|
PythonLexer
vivainio
|
r851 | """ History related magics and functionality """ | ||
Fernando Perez
|
r3079 | #----------------------------------------------------------------------------- | ||
# Copyright (C) 2010 The IPython Development Team. | ||||
# | ||||
# Distributed under the terms of the BSD License. | ||||
# | ||||
# The full license is in the file COPYING.txt, distributed with this software. | ||||
#----------------------------------------------------------------------------- | ||||
#----------------------------------------------------------------------------- | ||||
# Imports | ||||
#----------------------------------------------------------------------------- | ||||
from __future__ import print_function | ||||
vivainio
|
r851 | |||
fperez
|
r960 | # Stdlib imports | ||
import os | ||||
Thomas Kluyver
|
r3394 | import re | ||
Thomas Kluyver
|
r3388 | import sqlite3 | ||
fperez
|
r960 | |||
Fernando Perez
|
r3079 | # Our own packages | ||
Thomas Kluyver
|
r3393 | from IPython.config.configurable import Configurable | ||
Brian Granger
|
r2775 | import IPython.utils.io | ||
Fernando Perez
|
r3079 | |||
Thomas Kluyver
|
r3341 | from IPython.testing import decorators as testdec | ||
Brian Granger
|
r2775 | from IPython.utils.io import ask_yes_no | ||
Thomas Kluyver
|
r3393 | from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode | ||
Brian Granger
|
r2498 | from IPython.utils.warn import warn | ||
Fernando Perez
|
r3079 | |||
#----------------------------------------------------------------------------- | ||||
# Classes and functions | ||||
#----------------------------------------------------------------------------- | ||||
Thomas Kluyver
|
r3393 | class HistoryManager(Configurable): | ||
Fernando Perez
|
r3079 | """A class to organize all history-related functionality in one place. | ||
""" | ||||
Fernando Perez
|
r3095 | # Public interface | ||
# An instance of the IPython shell we are attached to | ||||
Thomas Kluyver
|
r3393 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | ||
# Lists to hold processed and raw history. These start with a blank entry | ||||
# so that we can index them starting from 1 | ||||
input_hist_parsed = List([""]) | ||||
input_hist_raw = List([""]) | ||||
Fernando Perez
|
r3095 | # A list of directories visited during session | ||
Thomas Kluyver
|
r3393 | dir_hist = List() | ||
Fernando Perez
|
r3095 | # A dict of output history, keyed with ints from the shell's execution count | ||
Thomas Kluyver
|
r3393 | output_hist = Dict() | ||
# String holding the path to the history file | ||||
hist_file = Unicode() | ||||
Thomas Kluyver
|
r3388 | # The SQLite database | ||
Thomas Kluyver
|
r3393 | db = Instance(sqlite3.Connection) | ||
Thomas Kluyver
|
r3388 | # The number of the current session in the history database | ||
Thomas Kluyver
|
r3393 | session_number = Int() | ||
Thomas Kluyver
|
r3391 | # Should we log output to the database? (default no) | ||
Thomas Kluyver
|
r3393 | db_log_output = Bool(False, config=True) | ||
Thomas Kluyver
|
r3391 | # Write to database every x commands (higher values save disk access & power) | ||
# Values of 1 or less effectively disable caching. | ||||
Thomas Kluyver
|
r3393 | db_cache_size = Int(0, config=True) | ||
Thomas Kluyver
|
r3391 | # The input and output caches | ||
Thomas Kluyver
|
r3393 | db_input_cache = List() | ||
db_output_cache = List() | ||||
Thomas Kluyver
|
r3382 | |||
Fernando Perez
|
r3095 | # Private interface | ||
# Variables used to store the three last inputs from the user. On each new | ||||
# history update, we populate the user's namespace with these, shifted as | ||||
# necessary. | ||||
_i00, _i, _ii, _iii = '','','','' | ||||
Fernando Perez
|
r3246 | |||
# A set with all forms of the exit command, so that we don't store them in | ||||
# the history (it's annoying to rewind the first entry and land on an exit | ||||
# call). | ||||
_exit_commands = None | ||||
Fernando Perez
|
r3095 | |||
Thomas Kluyver
|
r3393 | def __init__(self, shell, config=None): | ||
Fernando Perez
|
r3079 | """Create a new history manager associated with a shell instance. | ||
""" | ||||
Fernando Perez
|
r3087 | # We need a pointer back to the shell for various tasks. | ||
Thomas Kluyver
|
r3393 | super(HistoryManager, self).__init__(shell=shell, config=config) | ||
Fernando Perez
|
r3079 | |||
# list of visited directories | ||||
try: | ||||
self.dir_hist = [os.getcwd()] | ||||
except OSError: | ||||
self.dir_hist = [] | ||||
# Now the history file | ||||
if shell.profile: | ||||
histfname = 'history-%s' % shell.profile | ||||
else: | ||||
histfname = 'history' | ||||
Thomas Kluyver
|
r3388 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite') | ||
Thomas Kluyver
|
r3393 | self.init_db() | ||
Fernando Perez
|
r3079 | |||
Fernando Perez
|
r3087 | self._i00, self._i, self._ii, self._iii = '','','','' | ||
Fernando Perez
|
r3246 | self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit', | ||
'%quit', '%Exit', '%exit']) | ||||
Fernando Perez
|
r3087 | |||
Thomas Kluyver
|
r3388 | def init_db(self): | ||
Thomas Kluyver
|
r3396 | """Connect to the database and get new session number.""" | ||
Thomas Kluyver
|
r3388 | self.db = sqlite3.connect(self.hist_file) | ||
Thomas Kluyver
|
r3391 | self.db.execute("""CREATE TABLE IF NOT EXISTS history | ||
(session integer, line integer, source text, source_raw text, | ||||
PRIMARY KEY (session, line))""") | ||||
# Output history is optional, but ensure the table's there so it can be | ||||
# enabled later. | ||||
self.db.execute("""CREATE TABLE IF NOT EXISTS output_history | ||||
(session integer, line integer, output text, | ||||
Thomas Kluyver
|
r3388 | PRIMARY KEY (session, line))""") | ||
cur = self.db.execute("""SELECT name FROM sqlite_master WHERE | ||||
type='table' AND name='singletons'""") | ||||
if not cur.fetchone(): | ||||
self.db.execute("""CREATE TABLE singletons | ||||
(name text PRIMARY KEY, value)""") | ||||
self.db.execute("""INSERT INTO singletons VALUES | ||||
('session_number', 1)""") | ||||
self.db.commit() | ||||
cur = self.db.execute("""SELECT value FROM singletons WHERE | ||||
name='session_number'""") | ||||
self.session_number = cur.fetchone()[0] | ||||
Thomas Kluyver
|
r3270 | |||
Thomas Kluyver
|
r3388 | #Increment by one for next session. | ||
self.db.execute("""UPDATE singletons SET value=? WHERE | ||||
name='session_number'""", (self.session_number+1,)) | ||||
self.db.commit() | ||||
Thomas Kluyver
|
r3397 | def get_hist_tail(self, n=10, raw=True, output=False): | ||
Thomas Kluyver
|
r3388 | """Get the last n lines from the history database.""" | ||
toget = 'source_raw' if raw else 'source' | ||||
Thomas Kluyver
|
r3397 | sqlfrom = "history" | ||
if output: | ||||
sqlfrom = "history LEFT JOIN output_history USING (session, line)" | ||||
toget = "history.%s, output_history.output" % toget | ||||
Thomas Kluyver
|
r3394 | cur = self.db.execute("SELECT session, line, " + toget +\ | ||
Thomas Kluyver
|
r3397 | " FROM "+sqlfrom+" ORDER BY session DESC, line DESC LIMIT ?", (n,)) | ||
hist = reversed(cur.fetchall()) | ||||
if output: | ||||
return ((ses, lin, (inp, out)) for ses, lin, inp, out in hist) | ||||
return hist | ||||
Satrajit Ghosh
|
r3240 | |||
Thomas Kluyver
|
r3394 | def get_hist_search(self, pattern="*", raw=True): | ||
Thomas Kluyver
|
r3388 | """Search the database using unix glob-style matching (wildcards * and | ||
?, escape using \). | ||||
Returns | ||||
------- | ||||
An iterator over tuples: (session, line_number, command) | ||||
""" | ||||
Thomas Kluyver
|
r3398 | toget = "source_raw" if raw else "source" | ||
Thomas Kluyver
|
r3394 | return self.db.execute("SELECT session, line, " +toget+ \ | ||
Thomas Kluyver
|
r3398 | " FROM history WHERE " +toget+ " GLOB ?", (pattern,)) | ||
Thomas Kluyver
|
r3394 | |||
def _get_hist_session(self, start=1, stop=None, raw=True, output=False): | ||||
"""Get input and output history from the current session. Called by | ||||
get_history, and takes similar parameters.""" | ||||
input_hist = self.input_hist_raw if raw else self.input_hist_parsed | ||||
Thomas Kluyver
|
r3380 | |||
Fernando Perez
|
r3079 | n = len(input_hist) | ||
Thomas Kluyver
|
r3388 | if start < 0: | ||
start += n | ||||
if not stop: | ||||
stop = n | ||||
elif stop < 0: | ||||
stop += n | ||||
Fernando Perez
|
r3079 | for i in range(start, stop): | ||
if output: | ||||
Thomas Kluyver
|
r3397 | line = (input_hist[i], repr(self.output_hist.get(i))) | ||
Fernando Perez
|
r3079 | else: | ||
Thomas Kluyver
|
r3394 | line = input_hist[i] | ||
yield (0, i, line) | ||||
def get_history(self, session=0, start=1, stop=None, raw=True,output=False): | ||||
"""Retrieve input by session. | ||||
Parameters | ||||
---------- | ||||
session : int | ||||
Session number to retrieve. The current session is 0, and negative | ||||
numbers count back from current session, so -1 is previous session. | ||||
start : int | ||||
First line to retrieve. | ||||
stop : int | ||||
Thomas Kluyver
|
r3396 | End of line range (excluded from output itself). If None, retrieve | ||
to the end of the session. | ||||
Thomas Kluyver
|
r3394 | raw : bool | ||
If True, return untranslated input | ||||
output : bool | ||||
If True, attempt to include output. This will be 'real' Python | ||||
objects for the current session, or text reprs from previous | ||||
sessions if db_log_output was enabled at the time. Where no output | ||||
is found, None is used. | ||||
Returns | ||||
------- | ||||
An iterator over the desired lines. Each line is a 3-tuple, either | ||||
(session, line, input) if output is False, or | ||||
(session, line, (input, output)) if output is True. | ||||
""" | ||||
if session == 0 or session==self.session_number: # Current session | ||||
return self._get_hist_session(start, stop, raw, output) | ||||
if session < 0: | ||||
session += self.session_number | ||||
# Assemble the SQL query: | ||||
sqlfrom = "history" | ||||
Thomas Kluyver
|
r3397 | toget = 'source_raw' if raw else 'source' | ||
Thomas Kluyver
|
r3394 | if output: | ||
sqlfrom = "history LEFT JOIN output_history USING (session, line)" | ||||
toget = "history.%s, output_history.output" % toget | ||||
if stop: | ||||
Thomas Kluyver
|
r3395 | lineclause = "line >= ? AND line < ?" | ||
Thomas Kluyver
|
r3394 | params = (session, start, stop) | ||
else: | ||||
lineclause = "line>=?" | ||||
params = (session, start) | ||||
Thomas Kluyver
|
r3397 | cur = self.db.execute("""SELECT session, line, %s FROM %s WHERE | ||
session==? AND %s""" %(toget, sqlfrom, lineclause), params) | ||||
Thomas Kluyver
|
r3394 | if output: # Regroup into 3-tuples | ||
Thomas Kluyver
|
r3397 | return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) | ||
Thomas Kluyver
|
r3394 | return cur | ||
def get_hist_from_rangestr(self, rangestr, raw=True, output=False): | ||||
"""Get lines of history from a string of ranges, as used by magic | ||||
commands %hist, %save, %macro, etc.""" | ||||
Thomas Kluyver
|
r3395 | for sess, s, e in extract_hist_ranges(rangestr): | ||
for line in self.get_history(sess, s, e, raw=raw, output=output): | ||||
Thomas Kluyver
|
r3394 | yield line | ||
Fernando Perez
|
r3079 | |||
Thomas Kluyver
|
r3390 | def store_inputs(self, line_num, source, source_raw=None): | ||
Fernando Perez
|
r3087 | """Store source and raw input in history and create input cache | ||
variables _i*. | ||||
Fernando Perez
|
r3080 | Parameters | ||
---------- | ||||
Thomas Kluyver
|
r3390 | line_num : int | ||
The prompt number of this input. | ||||
Fernando Perez
|
r3080 | source : str | ||
Python input. | ||||
source_raw : str, optional | ||||
If given, this is the raw input without any IPython transformations | ||||
applied to it. If not given, ``source`` is used. | ||||
""" | ||||
if source_raw is None: | ||||
source_raw = source | ||||
Fernando Perez
|
r3246 | |||
# do not store exit/quit commands | ||||
if source_raw.strip() in self._exit_commands: | ||||
Satrajit Ghosh
|
r3243 | return | ||
Fernando Perez
|
r3246 | |||
Satrajit Ghosh
|
r3245 | self.input_hist_parsed.append(source.rstrip()) | ||
self.input_hist_raw.append(source_raw.rstrip()) | ||||
Thomas Kluyver
|
r3390 | |||
Thomas Kluyver
|
r3391 | self.db_input_cache.append((self.session_number, line_num, | ||
source, source_raw)) | ||||
# Trigger to flush cache and write to DB. | ||||
if len(self.db_input_cache) >= self.db_cache_size: | ||||
self.writeout_cache() | ||||
Fernando Perez
|
r3080 | |||
Fernando Perez
|
r3087 | # update the auto _i variables | ||
self._iii = self._ii | ||||
self._ii = self._i | ||||
self._i = self._i00 | ||||
self._i00 = source_raw | ||||
# hackish access to user namespace to create _i1,_i2... dynamically | ||||
Thomas Kluyver
|
r3390 | new_i = '_i%s' % line_num | ||
Fernando Perez
|
r3087 | to_main = {'_i': self._i, | ||
'_ii': self._ii, | ||||
'_iii': self._iii, | ||||
new_i : self._i00 } | ||||
self.shell.user_ns.update(to_main) | ||||
Thomas Kluyver
|
r3389 | |||
Thomas Kluyver
|
r3391 | def store_output(self, line_num, output): | ||
if not self.db_log_output: | ||||
return | ||||
db_row = (self.session_number, line_num, output) | ||||
if self.db_cache_size > 1: | ||||
self.db_output_cache.append(db_row) | ||||
else: | ||||
with self.db: | ||||
self.db.execute("INSERT INTO output_history VALUES (?,?,?)", db_row) | ||||
Thomas Kluyver
|
r3389 | def writeout_cache(self): | ||
Thomas Kluyver
|
r3397 | #print(self.db_input_cache) | ||
Thomas Kluyver
|
r3389 | with self.db: | ||
self.db.executemany("INSERT INTO history VALUES (?, ?, ?, ?)", | ||||
Thomas Kluyver
|
r3391 | self.db_input_cache) | ||
self.db.executemany("INSERT INTO output_history VALUES (?, ?, ?)", | ||||
self.db_output_cache) | ||||
self.db_input_cache = [] | ||||
self.db_output_cache = [] | ||||
Fernando Perez
|
r3087 | |||
Fernando Perez
|
r3080 | def sync_inputs(self): | ||
"""Ensure raw and translated histories have same length.""" | ||||
Thomas Kluyver
|
r3388 | lr = len(self.input_hist_raw) | ||
lp = len(self.input_hist_parsed) | ||||
if lp < lr: | ||||
self.input_hist_raw[:lr-lp] = [] | ||||
elif lr < lp: | ||||
self.input_hist_parsed[:lp-lr] = [] | ||||
Fernando Perez
|
r3080 | |||
Thomas Kluyver
|
r3397 | def reset(self, new_session=True): | ||
"""Clear the current session's history, and (optionally) start a new | ||||
Thomas Kluyver
|
r3396 | session.""" | ||
self.input_hist_parsed[:] = [""] | ||||
self.input_hist_raw[:] = [""] | ||||
Fernando Perez
|
r3080 | self.output_hist.clear() | ||
# The directory history can't be completely empty | ||||
self.dir_hist[:] = [os.getcwd()] | ||||
Thomas Kluyver
|
r3394 | |||
Thomas Kluyver
|
r3397 | if new_session: | ||
self.writeout_cache() | ||||
self.init_db() # Get new session number | ||||
Thomas Kluyver
|
r3396 | |||
Thomas Kluyver
|
r3395 | # To match, e.g. ~5/8-~2/3 | ||
Thomas Kluyver
|
r3394 | range_re = re.compile(r""" | ||
Thomas Kluyver
|
r3395 | ((?P<startsess>~?\d+)/)? | ||
Thomas Kluyver
|
r3394 | (?P<start>\d+) # Only the start line num is compulsory | ||
((?P<sep>[\-:]) | ||||
Thomas Kluyver
|
r3395 | ((?P<endsess>~?\d+)/)? | ||
Thomas Kluyver
|
r3394 | (?P<end>\d+))? | ||
""", re.VERBOSE) | ||||
def extract_hist_ranges(ranges_str): | ||||
"""Turn a string of history ranges into 3-tuples of (session, start, stop). | ||||
Examples | ||||
-------- | ||||
Thomas Kluyver
|
r3395 | list(extract_input_ranges("~8/5-~7/4 2")) | ||
Thomas Kluyver
|
r3394 | [(-8, 5, None), (-7, 1, 4), (0, 2, 3)] | ||
""" | ||||
for range_str in ranges_str.split(): | ||||
rmatch = range_re.match(range_str) | ||||
start = int(rmatch.group("start")) | ||||
end = rmatch.group("end") | ||||
end = int(end) if end else start+1 # If no end specified, get (a, a+1) | ||||
if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] | ||||
end += 1 | ||||
startsess = rmatch.group("startsess") or "0" | ||||
endsess = rmatch.group("endsess") or startsess | ||||
startsess = int(startsess.replace("~","-")) | ||||
endsess = int(endsess.replace("~","-")) | ||||
assert endsess >= startsess | ||||
if endsess == startsess: | ||||
yield (startsess, start, end) | ||||
continue | ||||
# Multiple sessions in one range: | ||||
yield (startsess, start, None) | ||||
for sess in range(startsess+1, endsess): | ||||
yield (sess, 1, None) | ||||
yield (endsess, 1, end) | ||||
def _format_lineno(session, line): | ||||
"""Helper function to format line numbers properly.""" | ||||
if session == 0: | ||||
return str(line) | ||||
return "%s#%s" % (session, line) | ||||
vivainio
|
r851 | |||
Thomas Kluyver
|
r3341 | @testdec.skip_doctest | ||
vivainio
|
r851 | def magic_history(self, parameter_s = ''): | ||
"""Print input history (_i<n> variables), with most recent last. | ||||
%history -> print at most 40 inputs (some may be multi-line)\\ | ||||
%history n -> print at most n inputs\\ | ||||
%history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | ||||
Fernando Perez
|
r2441 | By default, input history is printed without line numbers so it can be | ||
directly pasted into an editor. | ||||
With -n, each input's number <n> is shown, and is accessible as the | ||||
automatically generated variable _i<n> as well as In[<n>]. Multi-line | ||||
statements are printed starting at a new line for easy copy/paste. | ||||
vivainio
|
r851 | |||
Fernando Perez
|
r2441 | Options: | ||
vivainio
|
r851 | |||
Fernando Perez
|
r2441 | -n: print line numbers for each input. | ||
vivainio
|
r851 | This feature is only available if numbered prompts are in use. | ||
Fernando Perez
|
r2441 | -o: also print outputs for each input. | ||
-p: print classic '>>>' python prompts before each input. This is useful | ||||
for making documentation, and in conjunction with -o, for producing | ||||
doctest-ready output. | ||||
Fernando Perez
|
r2899 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. | ||
vivainio
|
r851 | |||
Fernando Perez
|
r2899 | -t: print the 'translated' history, as IPython understands it. IPython | ||
filters your input and converts it all into valid Python source before | ||||
executing it (things like magics or aliases are turned into function | ||||
calls, for example). With this option, you'll see the native history | ||||
instead of the user-entered version: '%cd /' will be seen as | ||||
'get_ipython().magic("%cd /")' instead of '%cd /'. | ||||
vivainio
|
r851 | |||
-g: treat the arg as a pattern to grep for in (full) history. | ||||
Thomas Kluyver
|
r3388 | This includes the saved history (almost all commands ever written). | ||
Use '%hist -g' to show full saved history (may be very long). | ||||
Thomas Kluyver
|
r3394 | |||
-l: get the last n lines from all sessions. Specify n as a single arg, or | ||||
the default is the last 10 lines. | ||||
fperez
|
r961 | |||
-f FILENAME: instead of printing the output to the screen, redirect it to | ||||
the given file. The file is always overwritten, though IPython asks for | ||||
confirmation first if it already exists. | ||||
Vishnu S G
|
r3326 | |||
Thomas Kluyver
|
r3337 | Examples | ||
-------- | ||||
Vishnu S G
|
r3326 | :: | ||
In [6]: %hist -n 4 6 | ||||
4:a = 12 | ||||
5:print a**2 | ||||
vivainio
|
r851 | """ | ||
Fernando Perez
|
r2993 | if not self.shell.displayhook.do_full_cache: | ||
Fernando Perez
|
r3079 | print('This feature is only available if numbered prompts are in use.') | ||
vivainio
|
r851 | return | ||
Thomas Kluyver
|
r3394 | opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string') | ||
Thomas Kluyver
|
r3380 | |||
# For brevity | ||||
history_manager = self.shell.history_manager | ||||
Thomas Kluyver
|
r3398 | |||
def _format_lineno(session, line): | ||||
"""Helper function to format line numbers properly.""" | ||||
if session in (0, history_manager.session_number): | ||||
return str(line) | ||||
return "%s/%s" % (session, line) | ||||
fperez
|
r960 | |||
# Check if output to specific file was requested. | ||||
try: | ||||
outfname = opts['f'] | ||||
except KeyError: | ||||
Brian Granger
|
r2775 | outfile = IPython.utils.io.Term.cout # default | ||
fperez
|
r960 | # We don't want to close stdout at the end! | ||
close_at_end = False | ||||
else: | ||||
if os.path.exists(outfname): | ||||
Fernando Perez
|
r1762 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | ||
Fernando Perez
|
r3079 | print('Aborting.') | ||
fperez
|
r960 | return | ||
vivainio
|
r851 | |||
Fernando Perez
|
r1762 | outfile = open(outfname,'w') | ||
close_at_end = True | ||||
Thomas Kluyver
|
r3380 | |||
print_nums = 'n' in opts | ||||
Thomas Kluyver
|
r3394 | get_output = 'o' in opts | ||
Thomas Kluyver
|
r3380 | pyprompts = 'p' in opts | ||
# Raw history is the default | ||||
raw = not('t' in opts) | ||||
Fernando Perez
|
r1762 | |||
vivainio
|
r851 | default_length = 40 | ||
pattern = None | ||||
Thomas Kluyver
|
r3394 | |||
# Glob search: | ||||
Fernando Perez
|
r1762 | if 'g' in opts: | ||
Thomas Kluyver
|
r3394 | pattern = "*" + args + "*" if args else "*" | ||
Thomas Kluyver
|
r3380 | |||
Thomas Kluyver
|
r3394 | # Display: | ||
matches_current_session = [] | ||||
for session, line, s in history_manager.get_hist_search(pattern, raw): | ||||
if session == history_manager.session_number: | ||||
Thomas Kluyver
|
r3398 | matches_current_session.append((line, s)) | ||
Thomas Kluyver
|
r3394 | continue | ||
Thomas Kluyver
|
r3398 | print("%d/%d: %s" %(session, line, s.expandtabs(4)), file=outfile) | ||
Thomas Kluyver
|
r3394 | if matches_current_session: | ||
print("=== Current session: ===", file=outfile) | ||||
for line, s in matches_current_session: | ||||
print("%d: %s" %(line, s.expandtabs(4)), file=outfile) | ||||
return | ||||
if 'l' in opts: # Get 'tail' | ||||
try: | ||||
n = int(args) | ||||
except ValueError, IndexError: | ||||
n = 10 | ||||
Thomas Kluyver
|
r3397 | hist = history_manager.get_hist_tail(n, raw=raw, output=get_output) | ||
Thomas Kluyver
|
r3394 | else: | ||
if args: # Get history by ranges | ||||
hist = history_manager.get_hist_from_rangestr(args, raw, get_output) | ||||
else: # Just get history for the current session | ||||
hist = history_manager.get_history(raw=raw, output=get_output) | ||||
# Pull hist into a list, so we can get the widest number in it. | ||||
hist = list(hist) | ||||
Thomas Kluyver
|
r3397 | if not hist: | ||
return | ||||
vivainio
|
r851 | |||
Thomas Kluyver
|
r3394 | width = max(len(_format_lineno(s, l)) for s, l, _ in hist) | ||
vivainio
|
r851 | |||
Thomas Kluyver
|
r3394 | for session, lineno, inline in hist: | ||
Fernando Perez
|
r2970 | # Print user history with tabs expanded to 4 spaces. The GUI clients | ||
# use hard tabs for easier usability in auto-indented code, but we want | ||||
# to produce PEP-8 compliant history for safe pasting into an editor. | ||||
Thomas Kluyver
|
r3394 | if get_output: | ||
Thomas Kluyver
|
r3380 | inline, output = inline | ||
inline = inline.expandtabs(4).rstrip() | ||||
Fernando Perez
|
r2993 | |||
vivainio
|
r851 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): | ||
continue | ||||
Thomas Kluyver
|
r3380 | multiline = "\n" in inline | ||
Thomas Kluyver
|
r3394 | line_sep = '\n' if multiline else '' | ||
vivainio
|
r851 | if print_nums: | ||
Thomas Kluyver
|
r3398 | print('%s:%s' % (_format_lineno(session, lineno).rjust(width), | ||
Thomas Kluyver
|
r3396 | line_sep), file=outfile, end='') | ||
Fernando Perez
|
r2441 | if pyprompts: | ||
Thomas Kluyver
|
r3381 | print(">>> ", end="", file=outfile) | ||
Fernando Perez
|
r2441 | if multiline: | ||
Thomas Kluyver
|
r3381 | inline = "\n... ".join(inline.splitlines()) + "\n..." | ||
print(inline, file=outfile) | ||||
Thomas Kluyver
|
r3394 | if get_output and output: | ||
Thomas Kluyver
|
r3397 | print(output, file=outfile) | ||
fperez
|
r960 | |||
if close_at_end: | ||||
outfile.close() | ||||
vivainio
|
r851 | |||
Thomas Kluyver
|
r3380 | # %hist is an alternative name | ||
magic_hist = magic_history | ||||
vivainio
|
r851 | |||
def rep_f(self, arg): | ||||
r""" Repeat a command, or get command to input line for editing | ||||
- %rep (no arguments): | ||||
Place a string version of last computation result (stored in the special '_' | ||||
variable) to the next input prompt. Allows you to create elaborate command | ||||
lines without using copy-paste:: | ||||
$ l = ["hei", "vaan"] | ||||
$ "".join(l) | ||||
==> heivaan | ||||
$ %rep | ||||
$ heivaan_ <== cursor blinking | ||||
%rep 45 | ||||
Place history line 45 to next input prompt. Use %hist to find out the | ||||
number. | ||||
%rep 1-4 6-7 3 | ||||
Repeat the specified lines immediately. Input slice syntax is the same as | ||||
in %macro and %save. | ||||
%rep foo | ||||
Place the most recent line that has the substring "foo" to next input. | ||||
Fernando Perez
|
r1762 | (e.g. 'svn ci -m foobar'). | ||
vivainio
|
r851 | """ | ||
opts,args = self.parse_options(arg,'',mode='list') | ||||
if not args: | ||||
Fernando Perez
|
r2993 | self.set_next_input(str(self.shell.user_ns["_"])) | ||
vivainio
|
r851 | return | ||
if len(args) == 1 and not '-' in args[0]: | ||||
arg = args[0] | ||||
if len(arg) > 1 and arg.startswith('0'): | ||||
# get from shadow hist | ||||
num = int(arg[1:]) | ||||
Fernando Perez
|
r2993 | line = self.shell.shadowhist.get(num) | ||
Brian Granger
|
r2205 | self.set_next_input(str(line)) | ||
vivainio
|
r851 | return | ||
try: | ||||
num = int(args[0]) | ||||
Fernando Perez
|
r2993 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) | ||
vivainio
|
r851 | return | ||
except ValueError: | ||||
pass | ||||
Fernando Perez
|
r2993 | for h in reversed(self.shell.input_hist_raw): | ||
vivainio
|
r851 | if 'rep' in h: | ||
continue | ||||
if fnmatch.fnmatch(h,'*' + arg + '*'): | ||||
Brian Granger
|
r2205 | self.set_next_input(str(h).rstrip()) | ||
vivainio
|
r851 | return | ||
try: | ||||
lines = self.extract_input_slices(args, True) | ||||
Fernando Perez
|
r3079 | print("lines", lines) | ||
Fernando Perez
|
r3087 | self.run_cell(lines) | ||
vivainio
|
r851 | except ValueError: | ||
Fernando Perez
|
r3079 | print("Not found in recent history:", args) | ||
vivainio
|
r851 | |||
def init_ipython(ip): | ||||
Brian Granger
|
r2205 | ip.define_magic("rep",rep_f) | ||
ip.define_magic("hist",magic_hist) | ||||
ip.define_magic("history",magic_history) | ||||
vivainio
|
r851 | |||
Fernando Perez
|
r2421 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | ||
#import ipy_completers | ||||
Fernando Perez
|
r2392 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') | ||