We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
%rerun doesn't handle integer parsing errors
## Steps to reproduce

* Execute `%rerun -l one`

## Expected result
An error message is printed, explaining the usage of the `-l` option.

## Actual result
An uncaught `ValueError` with the traceback that's exposing the internals of the implementation and not being too helpful.

## System info
Manjaro Linux, Python 3.9.4, IPython 7.22.0 (reproduces on IPython 8.0.0.dev)

--- END ISSUE ---

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

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/IPython/core/magics/history.py b/IPython/core/magics/history.py
--- a/IPython/core/magics/history.py
+++ b/IPython/core/magics/history.py
@@ -299,7 +299,11 @@
         """
         opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
         if "l" in opts:         # Last n lines
-            n = int(opts['l'])
+            try:
+                n = int(opts["l"])
+            except ValueError:
+                print("Number of lines must be an integer")
+                return
 
             if n == 0:
                 print("Requested 0 last lines - nothing to run")

{"golden_diff": "diff --git a/IPython/core/magics/history.py b/IPython/core/magics/history.py\n--- a/IPython/core/magics/history.py\n+++ b/IPython/core/magics/history.py\n@@ -299,7 +299,11 @@\n         \"\"\"\n         opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')\n         if \"l\" in opts:         # Last n lines\n-            n = int(opts['l'])\n+            try:\n+                n = int(opts[\"l\"])\n+            except ValueError:\n+                print(\"Number of lines must be an integer\")\n+                return\n \n             if n == 0:\n                 print(\"Requested 0 last lines - nothing to run\")\n", "issue": "%rerun doesn't handle integer parsing errors\n## Steps to reproduce\r\n\r\n* Execute `%rerun -l one`\r\n\r\n## Expected result\r\nAn error message is printed, explaining the usage of the `-l` option.\r\n\r\n## Actual result\r\nAn uncaught `ValueError` with the traceback that's exposing the internals of the implementation and not being too helpful.\r\n\r\n## System info\r\nManjaro Linux, Python 3.9.4, IPython 7.22.0 (reproduces on IPython 8.0.0.dev)\n", "before_files": [{"content": "\"\"\"Implementation of magic functions related to History.\n\"\"\"\n#-----------------------------------------------------------------------------\n#  Copyright (c) 2012, IPython Development Team.\n#\n#  Distributed under the terms of the Modified BSD License.\n#\n#  The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Stdlib\nimport os\nimport sys\nfrom io import open as io_open\nimport fnmatch\n\n# Our own packages\nfrom IPython.core.error import StdinNotImplementedError\nfrom IPython.core.magic import Magics, magics_class, line_magic\nfrom IPython.core.magic_arguments import (argument, magic_arguments,\n                                          parse_argstring)\nfrom IPython.testing.skipdoctest import skip_doctest\nfrom IPython.utils import io\n\n#-----------------------------------------------------------------------------\n# Magics class implementation\n#-----------------------------------------------------------------------------\n\n\n_unspecified = object()\n\n\n@magics_class\nclass HistoryMagics(Magics):\n\n    @magic_arguments()\n    @argument(\n        '-n', dest='print_nums', action='store_true', default=False,\n        help=\"\"\"\n        print line numbers for each input.\n        This feature is only available if numbered prompts are in use.\n        \"\"\")\n    @argument(\n        '-o', dest='get_output', action='store_true', default=False,\n        help=\"also print outputs for each input.\")\n    @argument(\n        '-p', dest='pyprompts', action='store_true', default=False,\n        help=\"\"\"\n        print classic '>>>' python prompts before each input.\n        This is useful for making documentation, and in conjunction\n        with -o, for producing doctest-ready output.\n        \"\"\")\n    @argument(\n        '-t', dest='raw', action='store_false', default=True,\n        help=\"\"\"\n        print the 'translated' history, as IPython understands it.\n        IPython filters your input and converts it all into valid Python\n        source before executing it (things like magics or aliases are turned\n        into function calls, for example). With this option, you'll see the\n        native history instead of the user-entered version: '%%cd /' will be\n        seen as 'get_ipython().run_line_magic(\"cd\", \"/\")' instead of '%%cd /'.\n        \"\"\")\n    @argument(\n        '-f', dest='filename',\n        help=\"\"\"\n        FILENAME: instead of printing the output to the screen, redirect\n        it to the given file.  The file is always overwritten, though *when\n        it can*, IPython asks for confirmation first. In particular, running\n        the command 'history -f FILENAME' from the IPython Notebook\n        interface will replace FILENAME even if it already exists *without*\n        confirmation.\n        \"\"\")\n    @argument(\n        '-g', dest='pattern', nargs='*', default=None,\n        help=\"\"\"\n        treat the arg as a glob pattern to search for in (full) history.\n        This includes the saved history (almost all commands ever written).\n        The pattern may contain '?' to match one unknown character and '*'\n        to match any number of unknown characters. Use '%%hist -g' to show\n        full saved history (may be very long).\n        \"\"\")\n    @argument(\n        '-l', dest='limit', type=int, nargs='?', default=_unspecified,\n        help=\"\"\"\n        get the last n lines from all sessions. Specify n as a single\n        arg, or the default is the last 10 lines.\n        \"\"\")\n    @argument(\n        '-u', dest='unique', action='store_true',\n        help=\"\"\"\n        when searching history using `-g`, show only unique history.\n        \"\"\")\n    @argument('range', nargs='*')\n    @skip_doctest\n    @line_magic\n    def history(self, parameter_s = ''):\n        \"\"\"Print input history (_i<n> variables), with most recent last.\n\n        By default, input history is printed without line numbers so it can be\n        directly pasted into an editor. Use -n to show them.\n\n        By default, all input history from the current session is displayed.\n        Ranges of history can be indicated using the syntax:\n        \n        ``4``\n            Line 4, current session\n        ``4-6``\n            Lines 4-6, current session\n        ``243/1-5``\n            Lines 1-5, session 243\n        ``~2/7``\n            Line 7, session 2 before current\n        ``~8/1-~6/5``\n            From the first line of 8 sessions ago, to the fifth line of 6\n            sessions ago.\n        \n        Multiple ranges can be entered, separated by spaces\n\n        The same syntax is used by %macro, %save, %edit, %rerun\n\n        Examples\n        --------\n        ::\n\n          In [6]: %history -n 4-6\n          4:a = 12\n          5:print a**2\n          6:%history -n 4-6\n\n        \"\"\"\n\n        args = parse_argstring(self.history, parameter_s)\n\n        # For brevity\n        history_manager = self.shell.history_manager\n\n        def _format_lineno(session, line):\n            \"\"\"Helper function to format line numbers properly.\"\"\"\n            if session in (0, history_manager.session_number):\n                return str(line)\n            return \"%s/%s\" % (session, line)\n\n        # Check if output to specific file was requested.\n        outfname = args.filename\n        if not outfname:\n            outfile = sys.stdout  # default\n            # We don't want to close stdout at the end!\n            close_at_end = False\n        else:\n            if os.path.exists(outfname):\n                try:\n                    ans = io.ask_yes_no(\"File %r exists. Overwrite?\" % outfname)\n                except StdinNotImplementedError:\n                    ans = True\n                if not ans:\n                    print('Aborting.')\n                    return\n                print(\"Overwriting file.\")\n            outfile = io_open(outfname, 'w', encoding='utf-8')\n            close_at_end = True\n\n        print_nums = args.print_nums\n        get_output = args.get_output\n        pyprompts = args.pyprompts\n        raw = args.raw\n\n        pattern = None\n        limit = None if args.limit is _unspecified else args.limit\n\n        range_pattern = False\n        if args.pattern is not None and not args.range:\n            if args.pattern:\n                pattern = \"*\" + \" \".join(args.pattern) + \"*\"\n            else:\n                pattern = \"*\"\n            hist = history_manager.search(pattern, raw=raw, output=get_output,\n                                          n=limit, unique=args.unique)\n            print_nums = True\n        elif args.limit is not _unspecified:\n            n = 10 if limit is None else limit\n            hist = history_manager.get_tail(n, raw=raw, output=get_output)\n        else:\n            if args.pattern:\n                range_pattern = \"*\" + \" \".join(args.pattern) + \"*\"\n                print_nums = True\n            hist = history_manager.get_range_by_str(\n                \" \".join(args.range), raw, get_output\n            )\n\n        # We could be displaying the entire history, so let's not try to pull\n        # it into a list in memory. Anything that needs more space will just\n        # misalign.\n        width = 4\n\n        for session, lineno, inline in hist:\n            # Print user history with tabs expanded to 4 spaces.  The GUI\n            # clients use hard tabs for easier usability in auto-indented code,\n            # but we want to produce PEP-8 compliant history for safe pasting\n            # into an editor.\n            if get_output:\n                inline, output = inline\n            if range_pattern:\n                if not fnmatch.fnmatch(inline, range_pattern):\n                    continue\n            inline = inline.expandtabs(4).rstrip()\n\n            multiline = \"\\n\" in inline\n            line_sep = '\\n' if multiline else ' '\n            if print_nums:\n                print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),\n                        line_sep),  file=outfile, end=u'')\n            if pyprompts:\n                print(u\">>> \", end=u\"\", file=outfile)\n                if multiline:\n                    inline = \"\\n... \".join(inline.splitlines()) + \"\\n...\"\n            print(inline, file=outfile)\n            if get_output and output:\n                print(output, file=outfile)\n\n        if close_at_end:\n            outfile.close()\n\n    @line_magic\n    def recall(self, arg):\n        r\"\"\"Repeat a command, or get command to input line for editing.\n\n        %recall and %rep are equivalent.\n\n        - %recall (no arguments):\n\n        Place a string version of last computation result (stored in the\n        special '_' variable) to the next input prompt. Allows you to create\n        elaborate command lines without using copy-paste::\n\n             In[1]: l = [\"hei\", \"vaan\"]\n             In[2]: \"\".join(l)\n            Out[2]: heivaan\n             In[3]: %recall\n             In[4]: heivaan_ <== cursor blinking\n\n        %recall 45\n\n        Place history line 45 on the next input prompt. Use %hist to find\n        out the number.\n\n        %recall 1-4\n\n        Combine the specified lines into one cell, and place it on the next\n        input prompt. See %history for the slice syntax.\n\n        %recall foo+bar\n\n        If foo+bar can be evaluated in the user namespace, the result is\n        placed at the next input prompt. Otherwise, the history is searched\n        for lines which contain that substring, and the most recent one is\n        placed at the next input prompt.\n        \"\"\"\n        if not arg:                 # Last output\n            self.shell.set_next_input(str(self.shell.user_ns[\"_\"]))\n            return\n                                    # Get history range\n        histlines = self.shell.history_manager.get_range_by_str(arg)\n        cmd = \"\\n\".join(x[2] for x in histlines)\n        if cmd:\n            self.shell.set_next_input(cmd.rstrip())\n            return\n\n        try:                        # Variable in user namespace\n            cmd = str(eval(arg, self.shell.user_ns))\n        except Exception:           # Search for term in history\n            histlines = self.shell.history_manager.search(\"*\"+arg+\"*\")\n            for h in reversed([x[2] for x in histlines]):\n                if 'recall' in h or 'rep' in h:\n                    continue\n                self.shell.set_next_input(h.rstrip())\n                return\n        else:\n            self.shell.set_next_input(cmd.rstrip())\n            return\n        print(\"Couldn't evaluate or find in history:\", arg)\n\n    @line_magic\n    def rerun(self, parameter_s=''):\n        \"\"\"Re-run previous input\n\n        By default, you can specify ranges of input history to be repeated\n        (as with %history). With no arguments, it will repeat the last line.\n\n        Options:\n\n          -l <n> : Repeat the last n lines of input, not including the\n          current command.\n\n          -g foo : Repeat the most recent line which contains foo\n        \"\"\"\n        opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')\n        if \"l\" in opts:         # Last n lines\n            n = int(opts['l'])\n\n            if n == 0:\n                print(\"Requested 0 last lines - nothing to run\")\n                return\n            elif n < 0:\n                print(\"Number of lines to rerun cannot be negative\")\n                return\n\n            hist = self.shell.history_manager.get_tail(n)\n        elif \"g\" in opts:       # Search\n            p = \"*\"+opts['g']+\"*\"\n            hist = list(self.shell.history_manager.search(p))\n            for l in reversed(hist):\n                if \"rerun\" not in l[2]:\n                    hist = [l]     # The last match which isn't a %rerun\n                    break\n            else:\n                hist = []          # No matches except %rerun\n        elif args:              # Specify history ranges\n            hist = self.shell.history_manager.get_range_by_str(args)\n        else:                   # Last line\n            hist = self.shell.history_manager.get_tail(1)\n        hist = [x[2] for x in hist]\n        if not hist:\n            print(\"No lines in history match specification\")\n            return\n        histlines = \"\\n\".join(hist)\n        print(\"=== Executing: ===\")\n        print(histlines)\n        print(\"=== Output: ===\")\n        self.shell.run_cell(\"\\n\".join(hist), store_history=False)\n", "path": "IPython/core/magics/history.py"}], "after_files": [{"content": "\"\"\"Implementation of magic functions related to History.\n\"\"\"\n#-----------------------------------------------------------------------------\n#  Copyright (c) 2012, IPython Development Team.\n#\n#  Distributed under the terms of the Modified BSD License.\n#\n#  The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Stdlib\nimport os\nimport sys\nfrom io import open as io_open\nimport fnmatch\n\n# Our own packages\nfrom IPython.core.error import StdinNotImplementedError\nfrom IPython.core.magic import Magics, magics_class, line_magic\nfrom IPython.core.magic_arguments import (argument, magic_arguments,\n                                          parse_argstring)\nfrom IPython.testing.skipdoctest import skip_doctest\nfrom IPython.utils import io\n\n#-----------------------------------------------------------------------------\n# Magics class implementation\n#-----------------------------------------------------------------------------\n\n\n_unspecified = object()\n\n\n@magics_class\nclass HistoryMagics(Magics):\n\n    @magic_arguments()\n    @argument(\n        '-n', dest='print_nums', action='store_true', default=False,\n        help=\"\"\"\n        print line numbers for each input.\n        This feature is only available if numbered prompts are in use.\n        \"\"\")\n    @argument(\n        '-o', dest='get_output', action='store_true', default=False,\n        help=\"also print outputs for each input.\")\n    @argument(\n        '-p', dest='pyprompts', action='store_true', default=False,\n        help=\"\"\"\n        print classic '>>>' python prompts before each input.\n        This is useful for making documentation, and in conjunction\n        with -o, for producing doctest-ready output.\n        \"\"\")\n    @argument(\n        '-t', dest='raw', action='store_false', default=True,\n        help=\"\"\"\n        print the 'translated' history, as IPython understands it.\n        IPython filters your input and converts it all into valid Python\n        source before executing it (things like magics or aliases are turned\n        into function calls, for example). With this option, you'll see the\n        native history instead of the user-entered version: '%%cd /' will be\n        seen as 'get_ipython().run_line_magic(\"cd\", \"/\")' instead of '%%cd /'.\n        \"\"\")\n    @argument(\n        '-f', dest='filename',\n        help=\"\"\"\n        FILENAME: instead of printing the output to the screen, redirect\n        it to the given file.  The file is always overwritten, though *when\n        it can*, IPython asks for confirmation first. In particular, running\n        the command 'history -f FILENAME' from the IPython Notebook\n        interface will replace FILENAME even if it already exists *without*\n        confirmation.\n        \"\"\")\n    @argument(\n        '-g', dest='pattern', nargs='*', default=None,\n        help=\"\"\"\n        treat the arg as a glob pattern to search for in (full) history.\n        This includes the saved history (almost all commands ever written).\n        The pattern may contain '?' to match one unknown character and '*'\n        to match any number of unknown characters. Use '%%hist -g' to show\n        full saved history (may be very long).\n        \"\"\")\n    @argument(\n        '-l', dest='limit', type=int, nargs='?', default=_unspecified,\n        help=\"\"\"\n        get the last n lines from all sessions. Specify n as a single\n        arg, or the default is the last 10 lines.\n        \"\"\")\n    @argument(\n        '-u', dest='unique', action='store_true',\n        help=\"\"\"\n        when searching history using `-g`, show only unique history.\n        \"\"\")\n    @argument('range', nargs='*')\n    @skip_doctest\n    @line_magic\n    def history(self, parameter_s = ''):\n        \"\"\"Print input history (_i<n> variables), with most recent last.\n\n        By default, input history is printed without line numbers so it can be\n        directly pasted into an editor. Use -n to show them.\n\n        By default, all input history from the current session is displayed.\n        Ranges of history can be indicated using the syntax:\n        \n        ``4``\n            Line 4, current session\n        ``4-6``\n            Lines 4-6, current session\n        ``243/1-5``\n            Lines 1-5, session 243\n        ``~2/7``\n            Line 7, session 2 before current\n        ``~8/1-~6/5``\n            From the first line of 8 sessions ago, to the fifth line of 6\n            sessions ago.\n        \n        Multiple ranges can be entered, separated by spaces\n\n        The same syntax is used by %macro, %save, %edit, %rerun\n\n        Examples\n        --------\n        ::\n\n          In [6]: %history -n 4-6\n          4:a = 12\n          5:print a**2\n          6:%history -n 4-6\n\n        \"\"\"\n\n        args = parse_argstring(self.history, parameter_s)\n\n        # For brevity\n        history_manager = self.shell.history_manager\n\n        def _format_lineno(session, line):\n            \"\"\"Helper function to format line numbers properly.\"\"\"\n            if session in (0, history_manager.session_number):\n                return str(line)\n            return \"%s/%s\" % (session, line)\n\n        # Check if output to specific file was requested.\n        outfname = args.filename\n        if not outfname:\n            outfile = sys.stdout  # default\n            # We don't want to close stdout at the end!\n            close_at_end = False\n        else:\n            if os.path.exists(outfname):\n                try:\n                    ans = io.ask_yes_no(\"File %r exists. Overwrite?\" % outfname)\n                except StdinNotImplementedError:\n                    ans = True\n                if not ans:\n                    print('Aborting.')\n                    return\n                print(\"Overwriting file.\")\n            outfile = io_open(outfname, 'w', encoding='utf-8')\n            close_at_end = True\n\n        print_nums = args.print_nums\n        get_output = args.get_output\n        pyprompts = args.pyprompts\n        raw = args.raw\n\n        pattern = None\n        limit = None if args.limit is _unspecified else args.limit\n\n        range_pattern = False\n        if args.pattern is not None and not args.range:\n            if args.pattern:\n                pattern = \"*\" + \" \".join(args.pattern) + \"*\"\n            else:\n                pattern = \"*\"\n            hist = history_manager.search(pattern, raw=raw, output=get_output,\n                                          n=limit, unique=args.unique)\n            print_nums = True\n        elif args.limit is not _unspecified:\n            n = 10 if limit is None else limit\n            hist = history_manager.get_tail(n, raw=raw, output=get_output)\n        else:\n            if args.pattern:\n                range_pattern = \"*\" + \" \".join(args.pattern) + \"*\"\n                print_nums = True\n            hist = history_manager.get_range_by_str(\n                \" \".join(args.range), raw, get_output\n            )\n\n        # We could be displaying the entire history, so let's not try to pull\n        # it into a list in memory. Anything that needs more space will just\n        # misalign.\n        width = 4\n\n        for session, lineno, inline in hist:\n            # Print user history with tabs expanded to 4 spaces.  The GUI\n            # clients use hard tabs for easier usability in auto-indented code,\n            # but we want to produce PEP-8 compliant history for safe pasting\n            # into an editor.\n            if get_output:\n                inline, output = inline\n            if range_pattern:\n                if not fnmatch.fnmatch(inline, range_pattern):\n                    continue\n            inline = inline.expandtabs(4).rstrip()\n\n            multiline = \"\\n\" in inline\n            line_sep = '\\n' if multiline else ' '\n            if print_nums:\n                print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),\n                        line_sep),  file=outfile, end=u'')\n            if pyprompts:\n                print(u\">>> \", end=u\"\", file=outfile)\n                if multiline:\n                    inline = \"\\n... \".join(inline.splitlines()) + \"\\n...\"\n            print(inline, file=outfile)\n            if get_output and output:\n                print(output, file=outfile)\n\n        if close_at_end:\n            outfile.close()\n\n    @line_magic\n    def recall(self, arg):\n        r\"\"\"Repeat a command, or get command to input line for editing.\n\n        %recall and %rep are equivalent.\n\n        - %recall (no arguments):\n\n        Place a string version of last computation result (stored in the\n        special '_' variable) to the next input prompt. Allows you to create\n        elaborate command lines without using copy-paste::\n\n             In[1]: l = [\"hei\", \"vaan\"]\n             In[2]: \"\".join(l)\n            Out[2]: heivaan\n             In[3]: %recall\n             In[4]: heivaan_ <== cursor blinking\n\n        %recall 45\n\n        Place history line 45 on the next input prompt. Use %hist to find\n        out the number.\n\n        %recall 1-4\n\n        Combine the specified lines into one cell, and place it on the next\n        input prompt. See %history for the slice syntax.\n\n        %recall foo+bar\n\n        If foo+bar can be evaluated in the user namespace, the result is\n        placed at the next input prompt. Otherwise, the history is searched\n        for lines which contain that substring, and the most recent one is\n        placed at the next input prompt.\n        \"\"\"\n        if not arg:                 # Last output\n            self.shell.set_next_input(str(self.shell.user_ns[\"_\"]))\n            return\n                                    # Get history range\n        histlines = self.shell.history_manager.get_range_by_str(arg)\n        cmd = \"\\n\".join(x[2] for x in histlines)\n        if cmd:\n            self.shell.set_next_input(cmd.rstrip())\n            return\n\n        try:                        # Variable in user namespace\n            cmd = str(eval(arg, self.shell.user_ns))\n        except Exception:           # Search for term in history\n            histlines = self.shell.history_manager.search(\"*\"+arg+\"*\")\n            for h in reversed([x[2] for x in histlines]):\n                if 'recall' in h or 'rep' in h:\n                    continue\n                self.shell.set_next_input(h.rstrip())\n                return\n        else:\n            self.shell.set_next_input(cmd.rstrip())\n            return\n        print(\"Couldn't evaluate or find in history:\", arg)\n\n    @line_magic\n    def rerun(self, parameter_s=''):\n        \"\"\"Re-run previous input\n\n        By default, you can specify ranges of input history to be repeated\n        (as with %history). With no arguments, it will repeat the last line.\n\n        Options:\n\n          -l <n> : Repeat the last n lines of input, not including the\n          current command.\n\n          -g foo : Repeat the most recent line which contains foo\n        \"\"\"\n        opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')\n        if \"l\" in opts:         # Last n lines\n            try:\n                n = int(opts[\"l\"])\n            except ValueError:\n                print(\"Number of lines must be an integer\")\n                return\n\n            if n == 0:\n                print(\"Requested 0 last lines - nothing to run\")\n                return\n            elif n < 0:\n                print(\"Number of lines to rerun cannot be negative\")\n                return\n\n            hist = self.shell.history_manager.get_tail(n)\n        elif \"g\" in opts:       # Search\n            p = \"*\"+opts['g']+\"*\"\n            hist = list(self.shell.history_manager.search(p))\n            for l in reversed(hist):\n                if \"rerun\" not in l[2]:\n                    hist = [l]     # The last match which isn't a %rerun\n                    break\n            else:\n                hist = []          # No matches except %rerun\n        elif args:              # Specify history ranges\n            hist = self.shell.history_manager.get_range_by_str(args)\n        else:                   # Last line\n            hist = self.shell.history_manager.get_tail(1)\n        hist = [x[2] for x in hist]\n        if not hist:\n            print(\"No lines in history match specification\")\n            return\n        histlines = \"\\n\".join(hist)\n        print(\"=== Executing: ===\")\n        print(histlines)\n        print(\"=== Output: ===\")\n        self.shell.run_cell(\"\\n\".join(hist), store_history=False)\n", "path": "IPython/core/magics/history.py"}]}