##// END OF EJS Templates
Rewrite %history magic using magic_arguments
Takafumi Arakaki -
Show More
@@ -16,10 +16,13 b' from __future__ import print_function'
16 # Stdlib
16 # Stdlib
17 import os
17 import os
18 from io import open as io_open
18 from io import open as io_open
19 from argparse import Action
19
20
20 # Our own packages
21 # Our own packages
21 from IPython.core.error import StdinNotImplementedError
22 from IPython.core.error import StdinNotImplementedError
22 from IPython.core.magic import Magics, magics_class, line_magic
23 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.core.magic_arguments import (argument, magic_arguments,
25 parse_argstring)
23 from IPython.testing.skipdoctest import skip_doctest
26 from IPython.testing.skipdoctest import skip_doctest
24 from IPython.utils import io
27 from IPython.utils import io
25
28
@@ -27,16 +30,74 b' from IPython.utils import io'
27 # Magics class implementation
30 # Magics class implementation
28 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
29
32
33
34 class HistoryArgLimitAction(Action):
35 def __call__(self, parser, namespace, values, option_string=None):
36 namespace.limit_specified = True
37 namespace.limit = values
38
39
30 @magics_class
40 @magics_class
31 class HistoryMagics(Magics):
41 class HistoryMagics(Magics):
32
42
43 @magic_arguments()
44 @argument(
45 '-n', dest='print_nums', action='store_true', default=False,
46 help="""
47 print line numbers for each input.
48 This feature is only available if numbered prompts are in use.
49 """)
50 @argument(
51 '-o', dest='get_output', action='store_true', default=False,
52 help="also print outputs for each input.")
53 @argument(
54 '-p', dest='pyprompts', action='store_true', default=False,
55 help="""
56 print classic '>>>' python prompts before each input.
57 This is useful for making documentation, and in conjunction
58 with -o, for producing doctest-ready output.
59 """)
60 @argument(
61 '-t', dest='raw', action='store_false', default=True,
62 help="""
63 print the 'translated' history, as IPython understands it.
64 IPython filters your input and converts it all into valid Python
65 source before executing it (things like magics or aliases are turned
66 into function calls, for example). With this option, you'll see the
67 native history instead of the user-entered version: '%%cd /' will be
68 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
69 """)
70 @argument(
71 '-f', dest='filename',
72 help="""
73 FILENAME: instead of printing the output to the screen, redirect
74 it to the given file. The file is always overwritten, though *when
75 it can*, IPython asks for confirmation first. In particular, running
76 the command 'history -f FILENAME' from the IPython Notebook
77 interface will replace FILENAME even if it already exists *without*
78 confirmation.
79 """)
80 @argument(
81 '-g', dest='pattern', nargs='*', default=None,
82 help="""
83 treat the arg as a pattern to grep for in (full) history.
84 This includes the saved history (almost all commands ever written).
85 The pattern may contain '?' to match one unknown character and '*'
86 to match any number of unknown characters. Use '%%hist -g' to show
87 full saved history (may be very long).
88 """)
89 @argument(
90 '-l', dest='limit', type=int, nargs='?', action=HistoryArgLimitAction,
91 help="""
92 get the last n lines from all sessions. Specify n as a single
93 arg, or the default is the last 10 lines.
94 """)
95 @argument('range', nargs='*')
33 @skip_doctest
96 @skip_doctest
34 @line_magic
97 @line_magic
35 def history(self, parameter_s = ''):
98 def history(self, parameter_s = ''):
36 """Print input history (_i<n> variables), with most recent last.
99 """Print input history (_i<n> variables), with most recent last.
37
100
38 %history [-o -p -t -n] [-f filename] [range | -g pattern | -l number]
39
40 By default, input history is printed without line numbers so it can be
101 By default, input history is printed without line numbers so it can be
41 directly pasted into an editor. Use -n to show them.
102 directly pasted into an editor. Use -n to show them.
42
103
@@ -52,43 +113,6 b' class HistoryMagics(Magics):'
52
113
53 The same syntax is used by %macro, %save, %edit, %rerun
114 The same syntax is used by %macro, %save, %edit, %rerun
54
115
55 Options:
56
57 -n: print line numbers for each input.
58 This feature is only available if numbered prompts are in use.
59
60 -o: also print outputs for each input.
61
62 -p: print classic '>>>' python prompts before each input. This is
63 useful for making documentation, and in conjunction with -o, for
64 producing doctest-ready output.
65
66 -r: (default) print the 'raw' history, i.e. the actual commands you
67 typed.
68
69 -t: print the 'translated' history, as IPython understands it.
70 IPython filters your input and converts it all into valid Python
71 source before executing it (things like magics or aliases are turned
72 into function calls, for example). With this option, you'll see the
73 native history instead of the user-entered version: '%cd /' will be
74 seen as 'get_ipython().magic("%cd /")' instead of '%cd /'.
75
76 -g: treat the arg as a pattern to grep for in (full) history.
77 This includes the saved history (almost all commands ever written).
78 The pattern may contain '?' to match one unknown character and '*'
79 to match any number of unknown characters. Use '%hist -g' to show
80 full saved history (may be very long).
81
82 -l: get the last n lines from all sessions. Specify n as a single
83 arg, or the default is the last 10 lines.
84
85 -f FILENAME: instead of printing the output to the screen, redirect
86 it to the given file. The file is always overwritten, though *when
87 it can*, IPython asks for confirmation first. In particular, running
88 the command 'history -f FILENAME' from the IPython Notebook
89 interface will replace FILENAME even if it already exists *without*
90 confirmation.
91
92 Examples
116 Examples
93 --------
117 --------
94 ::
118 ::
@@ -104,7 +128,7 b' class HistoryMagics(Magics):'
104 print('This feature is only available if numbered prompts '
128 print('This feature is only available if numbered prompts '
105 'are in use.')
129 'are in use.')
106 return
130 return
107 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
131 args = parse_argstring(self.history, parameter_s)
108
132
109 # For brevity
133 # For brevity
110 history_manager = self.shell.history_manager
134 history_manager = self.shell.history_manager
@@ -116,9 +140,8 b' class HistoryMagics(Magics):'
116 return "%s/%s" % (session, line)
140 return "%s/%s" % (session, line)
117
141
118 # Check if output to specific file was requested.
142 # Check if output to specific file was requested.
119 try:
143 outfname = args.filename
120 outfname = opts['f']
144 if not outfname:
121 except KeyError:
122 outfile = io.stdout # default
145 outfile = io.stdout # default
123 # We don't want to close stdout at the end!
146 # We don't want to close stdout at the end!
124 close_at_end = False
147 close_at_end = False
@@ -135,27 +158,27 b' class HistoryMagics(Magics):'
135 outfile = io_open(outfname, 'w', encoding='utf-8')
158 outfile = io_open(outfname, 'w', encoding='utf-8')
136 close_at_end = True
159 close_at_end = True
137
160
138 print_nums = 'n' in opts
161 print_nums = args.print_nums
139 get_output = 'o' in opts
162 get_output = args.get_output
140 pyprompts = 'p' in opts
163 pyprompts = args.pyprompts
141 # Raw history is the default
164 raw = args.raw
142 raw = not('t' in opts)
143
165
144 pattern = None
166 pattern = None
145
167
146 if 'g' in opts: # Glob search
168 if args.pattern is not None:
147 pattern = "*" + args + "*" if args else "*"
169 if args.pattern:
170 pattern = "*" + " ".join(args.pattern) + "*"
171 else:
172 pattern = "*"
148 hist = history_manager.search(pattern, raw=raw, output=get_output)
173 hist = history_manager.search(pattern, raw=raw, output=get_output)
149 print_nums = True
174 print_nums = True
150 elif 'l' in opts: # Get 'tail'
175 elif getattr(args, 'limit_specified', False):
151 try:
176 n = 10 if args.limit is None else args.limit
152 n = int(args)
153 except (ValueError, IndexError):
154 n = 10
155 hist = history_manager.get_tail(n, raw=raw, output=get_output)
177 hist = history_manager.get_tail(n, raw=raw, output=get_output)
156 else:
178 else:
157 if args: # Get history by ranges
179 if args.range: # Get history by ranges
158 hist = history_manager.get_range_by_str(args, raw, get_output)
180 hist = history_manager.get_range_by_str(" ".join(args.range),
181 raw, get_output)
159 else: # Just get history for the current session
182 else: # Just get history for the current session
160 hist = history_manager.get_range(raw=raw, output=get_output)
183 hist = history_manager.get_range(raw=raw, output=get_output)
161
184
General Comments 0
You need to be logged in to leave comments. Login now