1
# -*- coding: utf-8 -*-
3
""" History related magics and functionality """
10
from IPython.genutils import Term, ask_yes_no
12
def magic_history(self, parameter_s = ''):
13
"""Print input history (_i<n> variables), with most recent last.
15
%history -> print at most 40 inputs (some may be multi-line)\\
16
%history n -> print at most n inputs\\
17
%history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
19
Each input's number <n> is shown, and is accessible as the
20
automatically generated variable _i<n>. Multi-line statements are
21
printed starting at a new line for easy copy/paste.
26
-n: do NOT print line numbers. This is useful if you want to get a
27
printout of many lines which can be directly pasted into a text
30
This feature is only available if numbered prompts are in use.
32
-t: (default) print the 'translated' history, as IPython understands it.
33
IPython filters your input and converts it all into valid Python source
34
before executing it (things like magics or aliases are turned into
35
function calls, for example). With this option, you'll see the native
36
history instead of the user-entered version: '%cd /' will be seen as
37
'_ip.magic("%cd /")' instead of '%cd /'.
39
-r: print the 'raw' history, i.e. the actual commands you typed.
41
-g: treat the arg as a pattern to grep for in (full) history.
42
This includes the "shadow history" (almost all commands ever written).
43
Use '%hist -g' to show full shadow history (may be very long).
44
In shadow history, every index nuwber starts with 0.
46
-f FILENAME: instead of printing the output to the screen, redirect it to
47
the given file. The file is always overwritten, though IPython asks for
48
confirmation first if it already exists.
55
if not shell.outputcache.do_full_cache:
56
print 'This feature is only available if numbered prompts are in use.'
58
opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')
60
# Check if output to specific file was requested.
65
# We don't want to close stdout at the end!
68
if os.path.exists(outfname):
69
ans = ask_yes_no("File %r exists. Overwrite?" % outfname)
74
outfile = open(outfname,'w')
79
input_hist = shell.input_hist
80
elif opts.has_key('r'):
81
input_hist = shell.input_hist_raw
83
input_hist = shell.input_hist
90
final = len(input_hist)
91
parts = parameter_s.split(None,1)
95
pattern = "*" + pattern + "*"
97
final = len(input_hist)
98
init = max(1,final-default_length)
100
final = len(input_hist)
101
init = max(1,final-int(args[0]))
103
init,final = map(int,args)
105
warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
106
print self.magic_hist.__doc__
108
width = len(str(final))
110
print_nums = not opts.has_key('n')
113
if pattern is not None:
114
sh = ip.IP.shadowhist.all()
116
if fnmatch.fnmatch(s, pattern):
117
print "0%d: %s" %(idx, s)
122
print "shadow history ends, fetch by %rep <number> (must start with 0)"
123
print "=== start of normal history ==="
125
for in_num in range(init,final):
126
inline = input_hist[in_num]
127
if pattern is not None and not fnmatch.fnmatch(inline, pattern):
130
multiline = int(inline.count('\n') > 1)
133
'%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
134
print >> outfile, inline,
141
def magic_hist(self, parameter_s=''):
142
"""Alternate name for %history."""
143
return self.magic_history(parameter_s)
147
def rep_f(self, arg):
148
r""" Repeat a command, or get command to input line for editing
150
- %rep (no arguments):
152
Place a string version of last computation result (stored in the special '_'
153
variable) to the next input prompt. Allows you to create elaborate command
154
lines without using copy-paste::
156
$ l = ["hei", "vaan"]
160
$ heivaan_ <== cursor blinking
164
Place history line 45 to next input prompt. Use %hist to find out the
169
Repeat the specified lines immediately. Input slice syntax is the same as
174
Place the most recent line that has the substring "foo" to next input.
175
(e.g. 'svn ci -m foobar').
180
opts,args = self.parse_options(arg,'',mode='list')
183
ip.set_next_input(str(ip.user_ns["_"]))
186
if len(args) == 1 and not '-' in args[0]:
188
if len(arg) > 1 and arg.startswith('0'):
189
# get from shadow hist
191
line = self.shadowhist.get(num)
192
ip.set_next_input(str(line))
196
ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
201
for h in reversed(self.shell.input_hist_raw):
204
if fnmatch.fnmatch(h,'*' + arg + '*'):
205
ip.set_next_input(str(h).rstrip())
210
lines = self.extract_input_slices(args, True)
214
print "Not found in recent history:", args
221
def __init__(self,db):
227
idx = self.db.get('shadowhist_idx', 1)
228
self.db['shadowhist_idx'] = idx + 1
232
old = self.db.hget('shadowhist', ent, _sentinel)
233
if old is not _sentinel:
235
newidx = self.inc_idx()
236
#print "new",newidx # dbg
237
self.db.hset('shadowhist',ent, newidx)
240
d = self.db.hdict('shadowhist')
241
items = [(i,s) for (s,i) in d.items()]
254
from IPython.Extensions import pickleshare
255
db = pickleshare.PickleShareDB('~/shist')
265
def init_ipython(ip):
266
ip.expose_magic("rep",rep_f)
267
ip.expose_magic("hist",magic_hist)
268
ip.expose_magic("history",magic_history)
270
import ipy_completers
271
ipy_completers.quick_completer('%hist' ,'-g -t -r -n')