##// END OF EJS Templates
Fix help string of -g option for %history
Takafumi Arakaki -
Show More
@@ -1,314 +1,314 b''
1 1 """Implementation of magic functions related to History.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012, IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14 from __future__ import print_function
15 15
16 16 # Stdlib
17 17 import os
18 18 from io import open as io_open
19 19 from IPython.external.argparse import Action
20 20
21 21 # Our own packages
22 22 from IPython.core.error import StdinNotImplementedError
23 23 from IPython.core.magic import Magics, magics_class, line_magic
24 24 from IPython.core.magic_arguments import (argument, defaults, magic_arguments,
25 25 parse_argstring)
26 26 from IPython.testing.skipdoctest import skip_doctest
27 27 from IPython.utils import io
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Magics class implementation
31 31 #-----------------------------------------------------------------------------
32 32
33 33
34 34 class HistoryArgLimitAction(Action):
35 35 def __call__(self, parser, namespace, values, option_string=None):
36 36 namespace.limit_specified = True
37 37 namespace.limit = values
38 38
39 39
40 40 @magics_class
41 41 class HistoryMagics(Magics):
42 42
43 43 @magic_arguments()
44 44 @argument(
45 45 '-n', dest='print_nums', action='store_true', default=False,
46 46 help="""
47 47 print line numbers for each input.
48 48 This feature is only available if numbered prompts are in use.
49 49 """)
50 50 @argument(
51 51 '-o', dest='get_output', action='store_true', default=False,
52 52 help="also print outputs for each input.")
53 53 @argument(
54 54 '-p', dest='pyprompts', action='store_true', default=False,
55 55 help="""
56 56 print classic '>>>' python prompts before each input.
57 57 This is useful for making documentation, and in conjunction
58 58 with -o, for producing doctest-ready output.
59 59 """)
60 60 @argument(
61 61 '-t', dest='raw', action='store_false', default=True,
62 62 help="""
63 63 print the 'translated' history, as IPython understands it.
64 64 IPython filters your input and converts it all into valid Python
65 65 source before executing it (things like magics or aliases are turned
66 66 into function calls, for example). With this option, you'll see the
67 67 native history instead of the user-entered version: '%%cd /' will be
68 68 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
69 69 """)
70 70 @argument(
71 71 '-f', dest='filename',
72 72 help="""
73 73 FILENAME: instead of printing the output to the screen, redirect
74 74 it to the given file. The file is always overwritten, though *when
75 75 it can*, IPython asks for confirmation first. In particular, running
76 76 the command 'history -f FILENAME' from the IPython Notebook
77 77 interface will replace FILENAME even if it already exists *without*
78 78 confirmation.
79 79 """)
80 80 @argument(
81 81 '-g', dest='pattern', nargs='*', default=None,
82 82 help="""
83 treat the arg as a pattern to grep for in (full) history.
83 treat the arg as a glob pattern to search for in (full) history.
84 84 This includes the saved history (almost all commands ever written).
85 85 The pattern may contain '?' to match one unknown character and '*'
86 86 to match any number of unknown characters. Use '%%hist -g' to show
87 87 full saved history (may be very long).
88 88 """)
89 89 @argument(
90 90 '-l', dest='limit', type=int, nargs='?', action=HistoryArgLimitAction,
91 91 help="""
92 92 get the last n lines from all sessions. Specify n as a single
93 93 arg, or the default is the last 10 lines.
94 94 """)
95 95 @argument('range', nargs='*')
96 96 @defaults(limit_specified=False)
97 97 @skip_doctest
98 98 @line_magic
99 99 def history(self, parameter_s = ''):
100 100 """Print input history (_i<n> variables), with most recent last.
101 101
102 102 By default, input history is printed without line numbers so it can be
103 103 directly pasted into an editor. Use -n to show them.
104 104
105 105 By default, all input history from the current session is displayed.
106 106 Ranges of history can be indicated using the syntax:
107 107 4 : Line 4, current session
108 108 4-6 : Lines 4-6, current session
109 109 243/1-5: Lines 1-5, session 243
110 110 ~2/7 : Line 7, session 2 before current
111 111 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
112 112 of 6 sessions ago.
113 113 Multiple ranges can be entered, separated by spaces
114 114
115 115 The same syntax is used by %macro, %save, %edit, %rerun
116 116
117 117 Examples
118 118 --------
119 119 ::
120 120
121 121 In [6]: %history -n 4-6
122 122 4:a = 12
123 123 5:print a**2
124 124 6:%history -n 4-6
125 125
126 126 """
127 127
128 128 if not self.shell.displayhook.do_full_cache:
129 129 print('This feature is only available if numbered prompts '
130 130 'are in use.')
131 131 return
132 132 args = parse_argstring(self.history, parameter_s)
133 133
134 134 # For brevity
135 135 history_manager = self.shell.history_manager
136 136
137 137 def _format_lineno(session, line):
138 138 """Helper function to format line numbers properly."""
139 139 if session in (0, history_manager.session_number):
140 140 return str(line)
141 141 return "%s/%s" % (session, line)
142 142
143 143 # Check if output to specific file was requested.
144 144 outfname = args.filename
145 145 if not outfname:
146 146 outfile = io.stdout # default
147 147 # We don't want to close stdout at the end!
148 148 close_at_end = False
149 149 else:
150 150 if os.path.exists(outfname):
151 151 try:
152 152 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
153 153 except StdinNotImplementedError:
154 154 ans = True
155 155 if not ans:
156 156 print('Aborting.')
157 157 return
158 158 print("Overwriting file.")
159 159 outfile = io_open(outfname, 'w', encoding='utf-8')
160 160 close_at_end = True
161 161
162 162 print_nums = args.print_nums
163 163 get_output = args.get_output
164 164 pyprompts = args.pyprompts
165 165 raw = args.raw
166 166
167 167 pattern = None
168 168
169 169 if args.pattern is not None:
170 170 if args.pattern:
171 171 pattern = "*" + " ".join(args.pattern) + "*"
172 172 else:
173 173 pattern = "*"
174 174 hist = history_manager.search(pattern, raw=raw, output=get_output,
175 175 n=args.limit)
176 176 print_nums = True
177 177 elif args.limit_specified:
178 178 n = 10 if args.limit is None else args.limit
179 179 hist = history_manager.get_tail(n, raw=raw, output=get_output)
180 180 else:
181 181 if args.range: # Get history by ranges
182 182 hist = history_manager.get_range_by_str(" ".join(args.range),
183 183 raw, get_output)
184 184 else: # Just get history for the current session
185 185 hist = history_manager.get_range(raw=raw, output=get_output)
186 186
187 187 # We could be displaying the entire history, so let's not try to pull
188 188 # it into a list in memory. Anything that needs more space will just
189 189 # misalign.
190 190 width = 4
191 191
192 192 for session, lineno, inline in hist:
193 193 # Print user history with tabs expanded to 4 spaces. The GUI
194 194 # clients use hard tabs for easier usability in auto-indented code,
195 195 # but we want to produce PEP-8 compliant history for safe pasting
196 196 # into an editor.
197 197 if get_output:
198 198 inline, output = inline
199 199 inline = inline.expandtabs(4).rstrip()
200 200
201 201 multiline = "\n" in inline
202 202 line_sep = '\n' if multiline else ' '
203 203 if print_nums:
204 204 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
205 205 line_sep), file=outfile, end=u'')
206 206 if pyprompts:
207 207 print(u">>> ", end=u"", file=outfile)
208 208 if multiline:
209 209 inline = "\n... ".join(inline.splitlines()) + "\n..."
210 210 print(inline, file=outfile)
211 211 if get_output and output:
212 212 print(output, file=outfile)
213 213
214 214 if close_at_end:
215 215 outfile.close()
216 216
217 217 @line_magic
218 218 def recall(self, arg):
219 219 r"""Repeat a command, or get command to input line for editing.
220 220
221 221 %recall and %rep are equivalent.
222 222
223 223 - %recall (no arguments):
224 224
225 225 Place a string version of last computation result (stored in the
226 226 special '_' variable) to the next input prompt. Allows you to create
227 227 elaborate command lines without using copy-paste::
228 228
229 229 In[1]: l = ["hei", "vaan"]
230 230 In[2]: "".join(l)
231 231 Out[2]: heivaan
232 232 In[3]: %recall
233 233 In[4]: heivaan_ <== cursor blinking
234 234
235 235 %recall 45
236 236
237 237 Place history line 45 on the next input prompt. Use %hist to find
238 238 out the number.
239 239
240 240 %recall 1-4
241 241
242 242 Combine the specified lines into one cell, and place it on the next
243 243 input prompt. See %history for the slice syntax.
244 244
245 245 %recall foo+bar
246 246
247 247 If foo+bar can be evaluated in the user namespace, the result is
248 248 placed at the next input prompt. Otherwise, the history is searched
249 249 for lines which contain that substring, and the most recent one is
250 250 placed at the next input prompt.
251 251 """
252 252 if not arg: # Last output
253 253 self.shell.set_next_input(str(self.shell.user_ns["_"]))
254 254 return
255 255 # Get history range
256 256 histlines = self.shell.history_manager.get_range_by_str(arg)
257 257 cmd = "\n".join(x[2] for x in histlines)
258 258 if cmd:
259 259 self.shell.set_next_input(cmd.rstrip())
260 260 return
261 261
262 262 try: # Variable in user namespace
263 263 cmd = str(eval(arg, self.shell.user_ns))
264 264 except Exception: # Search for term in history
265 265 histlines = self.shell.history_manager.search("*"+arg+"*")
266 266 for h in reversed([x[2] for x in histlines]):
267 267 if 'recall' in h or 'rep' in h:
268 268 continue
269 269 self.shell.set_next_input(h.rstrip())
270 270 return
271 271 else:
272 272 self.shell.set_next_input(cmd.rstrip())
273 273 print("Couldn't evaluate or find in history:", arg)
274 274
275 275 @line_magic
276 276 def rerun(self, parameter_s=''):
277 277 """Re-run previous input
278 278
279 279 By default, you can specify ranges of input history to be repeated
280 280 (as with %history). With no arguments, it will repeat the last line.
281 281
282 282 Options:
283 283
284 284 -l <n> : Repeat the last n lines of input, not including the
285 285 current command.
286 286
287 287 -g foo : Repeat the most recent line which contains foo
288 288 """
289 289 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
290 290 if "l" in opts: # Last n lines
291 291 n = int(opts['l'])
292 292 hist = self.shell.history_manager.get_tail(n)
293 293 elif "g" in opts: # Search
294 294 p = "*"+opts['g']+"*"
295 295 hist = list(self.shell.history_manager.search(p))
296 296 for l in reversed(hist):
297 297 if "rerun" not in l[2]:
298 298 hist = [l] # The last match which isn't a %rerun
299 299 break
300 300 else:
301 301 hist = [] # No matches except %rerun
302 302 elif args: # Specify history ranges
303 303 hist = self.shell.history_manager.get_range_by_str(args)
304 304 else: # Last line
305 305 hist = self.shell.history_manager.get_tail(1)
306 306 hist = [x[2] for x in hist]
307 307 if not hist:
308 308 print("No lines in history match specification")
309 309 return
310 310 histlines = "\n".join(hist)
311 311 print("=== Executing: ===")
312 312 print(histlines)
313 313 print("=== Output: ===")
314 314 self.shell.run_cell("\n".join(hist), store_history=False)
General Comments 0
You need to be logged in to leave comments. Login now