internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: ipython/ipython

Issue:
`%save` magic does not work, just warns that `'' was not found in history`
<!-- This is the repository for IPython command line, if you can try to make sure this question/bug/feature belong here and not on one of the Jupyter repositories. 

If it's a generic Python/Jupyter question, try other forums or discourse.jupyter.org.

If you are unsure, it's ok to post here, though, there are few maintainer so you might not get a fast response. 

-->

```pycon
In [1]: %save file.py
'' was not found in history, as a file, url, nor in the user namespace.
```


Discussion:
That's because it expects a history range there:
```
%save file.py 1-5
```

This has been improved in #13049, which is scheduled for v8.0.

Resolving patch:
diff --git a/IPython/core/magics/code.py b/IPython/core/magics/code.py
--- a/IPython/core/magics/code.py
+++ b/IPython/core/magics/code.py
@@ -185,7 +185,7 @@ def save(self, parameter_s=''):
         """Save a set of lines or a macro to a given filename.
 
         Usage:\\
-          %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
+          %save [options] filename [history]
 
         Options:
 
@@ -199,7 +199,7 @@ def save(self, parameter_s=''):
 
           -a: append to the file instead of overwriting it.
 
-        This function uses the same syntax as %history for input ranges,
+        The history argument uses the same syntax as %history for input ranges,
         then saves the lines to the filename you specify.
 
         If no ranges are specified, saves history of the current session up to


Test patch:
Repository: ipython/ipython

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)


Discussion:

Resolving patch:
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 @@ def rerun(self, parameter_s=''):
         """
         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")


Test patch:
Repository: ipython/ipython

Issue:
Wrong argument to `Path` in ipython in version 8.0.0a1 
<!-- This is the repository for IPython command line, if you can try to make sure this question/bug/feature belong here and not on one of the Jupyter repositories. 

If it's a generic Python/Jupyter question, try other forums or discourse.jupyter.org.

If you are unsure, it's ok to post here, though, there are few maintainer so you might not get a fast response. 

-->

I have pre-release tests on my package and I got such error (only on windows  https://github.com/4DNucleome/PartSeg/runs/4559230495?check_suite_focus=true) :

```
  D:\tmp\tox\py38-PyQt5-all\lib\site-packages\PartSeg\common_gui\qt_console.py:9: in <module>
      from ipykernel.inprocess.ipkernel import InProcessInteractiveShell
  D:\tmp\tox\py38-PyQt5-all\lib\site-packages\ipykernel\inprocess\ipkernel.py:10: in <module>
      from IPython.core.interactiveshell import InteractiveShellABC
  D:\tmp\tox\py38-PyQt5-all\lib\site-packages\IPython\__init__.py:51: in <module>
      from .core.application import Application
  D:\tmp\tox\py38-PyQt5-all\lib\site-packages\IPython\core\application.py:37: in <module>
      programdata = Path(os.environ.get("PROGRAMDATA", None))
  c:\hostedtoolcache\windows\python\3.8.10\x64\lib\pathlib.py:1042: in __new__
      self = cls._from_parts(args, init=False)
  c:\hostedtoolcache\windows\python\3.8.10\x64\lib\pathlib.py:683: in _from_parts
      drv, root, parts = self._parse_args(args)
  c:\hostedtoolcache\windows\python\3.8.10\x64\lib\pathlib.py:667: in _parse_args
      a = os.fspath(a)
  E   TypeError: expected str, bytes or os.PathLike object, not NoneType
  ERROR: InvocationError for command 'D:\tmp\tox\py38-PyQt5-all\Scripts\pytest.EXE' package/tests --no-cov (exited with code 4)
  ```

It looks like wrong default value is provided here `os.environ.get("PROGRAMDATA", None)`



Discussion:
Thanks, will fix for next alpha or beta relese. 

Resolving patch:
diff --git a/IPython/core/application.py b/IPython/core/application.py
--- a/IPython/core/application.py
+++ b/IPython/core/application.py
@@ -34,9 +34,9 @@
 )
 
 if os.name == "nt":
-    programdata = Path(os.environ.get("PROGRAMDATA", None))
-    if programdata:
-        SYSTEM_CONFIG_DIRS = [str(programdata / "ipython")]
+    programdata = os.environ.get("PROGRAMDATA", None)
+    if programdata is not None:
+        SYSTEM_CONFIG_DIRS = [str(Path(programdata) / "ipython")]
     else:  # PROGRAMDATA is not defined by default on XP.
         SYSTEM_CONFIG_DIRS = []
 else:


Test patch:
Repository: ipython/ipython

Issue:
Improvement of  `core.magic_arguments` example
Currently, there is only a [very raw example](https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.magic_arguments.html?highlight=%40magic_arguments.argumen#module-IPython.core.magic_arguments
) of using `magic_arguments` with custom cell magic.
Therefore, I have the idea to add a second, more fleshed out example that might help people to easier understand and use cell magic arguments: 
![image](https://user-images.githubusercontent.com/44469195/148220767-d59ad4ca-e713-434a-8241-c212580fba6b.png)
Here is the code:
```py
from IPython.core import magic_arguments
from IPython.core.magic import register_cell_magic


@magic_arguments.magic_arguments()
@magic_arguments.argument(
    "--option",
    help=("Add an option here"),
)
@magic_arguments.argument(
    "--style",
    default=None,
    help=("Add some style arguments"),
)
@register_cell_magic
def my_cell_magic(line, cell):
    """Cool cell magic"""
    args = magic_arguments.parse_argstring(my_cell_magic, line)
    print(args.style)
    print(args.option)
```


Discussion:
Sure, do you want to send a PR ?

Resolving patch:
diff --git a/IPython/core/magic_arguments.py b/IPython/core/magic_arguments.py
--- a/IPython/core/magic_arguments.py
+++ b/IPython/core/magic_arguments.py
@@ -37,6 +37,38 @@ def magic_cool(self, arg):
           -o OPTION, --option OPTION
                                 An optional argument.
 
+Here is an elaborated example that uses default parameters in `argument` and calls the `args` in the cell magic::
+
+    from IPython.core.magic import register_cell_magic
+    from IPython.core.magic_arguments import (argument, magic_arguments,
+                                            parse_argstring)
+
+
+    @magic_arguments()
+    @argument(
+        "--option",
+        "-o",
+        help=("Add an option here"),
+    )
+    @argument(
+        "--style",
+        "-s",
+        default="foo",
+        help=("Add some style arguments"),
+    )
+    @register_cell_magic
+    def my_cell_magic(line, cell):
+        args = parse_argstring(my_cell_magic, line)
+        print(f"{args.option=}")
+        print(f"{args.style=}")
+        print(f"{cell=}")
+
+In a jupyter notebook, this cell magic can be executed like this::
+
+    %%my_cell_magic -o Hello
+    print("bar")
+    i = 42
+
 Inheritance diagram:
 
 .. inheritance-diagram:: IPython.core.magic_arguments


Test patch:
Repository: ipython/ipython

Issue:
Revert “Black by default”
Version 8.0 added automatic formatting with Black. This was added in #13397 without much discussion - at least there is none linked.

IMO this is not desirable. It is surprising for a REPL to change what you wrote, and it introduces a large dependency (Black). As @rhettinger has pointed out on Twitter it reduces the utility of IPython in educational contexts: https://twitter.com/raymondh/status/1482225220475883522

Additionally the release note read:

> If `black` is installed in the same environment as IPython...

But this is misleading, implying that it's opt-in by installing Black. The change made IPython depend on Black, so it is always be installed.



Discussion:

Resolving patch:
diff --git a/IPython/terminal/interactiveshell.py b/IPython/terminal/interactiveshell.py
--- a/IPython/terminal/interactiveshell.py
+++ b/IPython/terminal/interactiveshell.py
@@ -200,7 +200,7 @@ def debugger_cls(self):
     ).tag(config=True)
 
     autoformatter = Unicode(
-        "black",
+        None,
         help="Autoformatter to reformat Terminal code. Can be `'black'`, `'yapf'` or `None`",
         allow_none=True
     ).tag(config=True)


Test patch:
Repository: ipython/ipython

Issue:
Typing % doesn't restrict autocompletion to just magics
## Steps to reproduce

* Write `%` in the prompt
* Hit "Tab"

## Expected result
The autocompletion list presents the user with a choice of magics.

## Actual result
Every name in the local namespace is present in the list, including locals, builtins, IPython-custom variables (`_`, for example) and all magics, but at the very end.

## System info
Manjaro Linux, Python 3.9.4, IPython 7.22.0 (reproduces on IPython 8.0.0.dev)


Discussion:
Possibly related to #11538

Resolving patch:
diff --git a/IPython/core/completer.py b/IPython/core/completer.py
--- a/IPython/core/completer.py
+++ b/IPython/core/completer.py
@@ -2139,8 +2139,9 @@ def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
         # different types of objects.  The rlcomplete() method could then
         # simply collapse the dict into a list for readline, but we'd have
         # richer completion semantics in other environments.
-        completions:Iterable[Any] = []
-        if self.use_jedi:
+        is_magic_prefix = len(text) > 0 and text[0] == "%"
+        completions: Iterable[Any] = []
+        if self.use_jedi and not is_magic_prefix:
             if not full_text:
                 full_text = line_buffer
             completions = self._jedi_matches(


Test patch:
diff --git a/IPython/core/tests/test_completer.py b/IPython/core/tests/test_completer.py
--- a/IPython/core/tests/test_completer.py
+++ b/IPython/core/tests/test_completer.py
@@ -1262,3 +1262,14 @@ def meth_2(self, meth2_arg1, meth2_arg2):
         _, matches = ip.complete(None, "test.meth(")
         self.assertIn("meth_arg1=", matches)
         self.assertNotIn("meth2_arg1=", matches)
+
+    def test_percent_symbol_restrict_to_magic_completions(self):
+        ip = get_ipython()
+        completer = ip.Completer
+        text = "%a"
+
+        with provisionalcompleter():
+            completer.use_jedi = True
+            completions = completer.completions(text, len(text))
+            for c in completions:
+                self.assertEqual(c.text[0], "%")
Repository: ipython/ipython

Issue:
IPython 8 changes terminal cursor
<!-- This is the repository for IPython command line, if you can try to make sure this question/bug/feature belong here and not on one of the Jupyter repositories. 

If it's a generic Python/Jupyter question, try other forums or discourse.jupyter.org.

If you are unsure, it's ok to post here, though, there are few maintainer so you might not get a fast response. 

-->
After starting IPython 8.0 and then returning to terminal, the cursor changes from block to I-Beam.

Before:
![ipy-cursor-before](https://user-images.githubusercontent.com/87697/149665338-139ee774-5d90-4ddc-88a8-3a7fcfee6f62.jpg)

After:
![ipy-cursor-after](https://user-images.githubusercontent.com/87697/149665346-78bc9858-96b5-4a79-b820-d4a6fb5d7e9f.jpg)

I need to call `reset` to get the cursor back to block.

Setup: XFCE terminal + zsh + starship


Discussion:
This behavior also occurs in VI edit mode where in [ins] mode the cursor changes to I-Beam but in [nav] mode the cursor changes back to Block. exiting in any of the two scenarios will keep the current cursor instead of getting back to the original cursor before opening IPython.

Setups:   
1. XTERM + zsh
2. terminology + zsh

Hum... @jonathanslenders might have an idea ? I don't think we manipulate the cursor in IPython directly.

Resolving patch:
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -3679,6 +3679,10 @@ def atexit_operations(self):
                 pass
         del self.tempdirs
 
+        # Restore user's cursor
+        if hasattr(self, "editing_mode") and self.editing_mode == "vi":
+            sys.stdout.write("\x1b[0 q")
+            sys.stdout.flush()
 
     def cleanup(self):
         self.restore_sys_module_state()
diff --git a/IPython/terminal/shortcuts.py b/IPython/terminal/shortcuts.py
--- a/IPython/terminal/shortcuts.py
+++ b/IPython/terminal/shortcuts.py
@@ -336,12 +336,7 @@ def set_input_mode(self, mode):
         shape = {InputMode.NAVIGATION: 2, InputMode.REPLACE: 4}.get(mode, 6)
         cursor = "\x1b[{} q".format(shape)
 
-        if hasattr(sys.stdout, "_cli"):
-            write = sys.stdout._cli.output.write_raw
-        else:
-            write = sys.stdout.write
-
-        write(cursor)
+        sys.stdout.write(cursor)
         sys.stdout.flush()
 
         self._input_mode = mode


Test patch:
Repository: ipython/ipython

Issue:
IPython 8.0: built in aliases issue warnings: You executed the system command !ls
Starting with IPython 8 built in aliases `ll`, `ldir`, `lf`, `lx` etc issue warnings:

```
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/IPython/core/interactiveshell.py:2373: UserWarning: You executed the system command !ls which may not work as expected. Try the IPython magic %ls instead.
  warnings.warn(
```


Discussion:

Resolving patch:
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -2414,14 +2414,9 @@ def system_raw(self, cmd):
         cmd = self.var_expand(cmd, depth=1)
         # warn if there is an IPython magic alternative.
         main_cmd = cmd.split()[0]
-        has_magic_alternatives = ("pip", "conda", "cd", "ls")
+        has_magic_alternatives = ("pip", "conda", "cd")
 
-        # had to check if the command was an alias expanded because of `ls`
-        is_alias_expanded = self.alias_manager.is_alias(main_cmd) and (
-            self.alias_manager.retrieve_alias(main_cmd).strip() == cmd.strip()
-        )
-
-        if main_cmd in has_magic_alternatives and not is_alias_expanded:
+        if main_cmd in has_magic_alternatives:
             warnings.warn(
                 (
                     "You executed the system command !{0} which may not work "


Test patch:
diff --git a/IPython/core/tests/test_interactiveshell.py b/IPython/core/tests/test_interactiveshell.py
--- a/IPython/core/tests/test_interactiveshell.py
+++ b/IPython/core/tests/test_interactiveshell.py
@@ -623,7 +623,7 @@ def test_control_c(self, *mocks):
         self.assertEqual(ip.user_ns["_exit_code"], -signal.SIGINT)
 
     def test_magic_warnings(self):
-        for magic_cmd in ("ls", "pip", "conda", "cd"):
+        for magic_cmd in ("pip", "conda", "cd"):
             with self.assertWarnsRegex(Warning, "You executed the system command"):
                 ip.system_raw(magic_cmd)
Repository: ipython/ipython

Issue:
Console bug adds an extra quote on macOS Monterey
<!-- This is the repository for IPython command line, if you can try to make sure this question/bug/feature belong here and not on one of the Jupyter repositories. 

If it's a generic Python/Jupyter question, try other forums or discourse.jupyter.org.

If you are unsure, it's ok to post here, though, there are few maintainer so you might not get a fast response. 

-->

I'm experiencing what seems to be a bug which adds an additional single quote. Here's what happens when I only write `x['odor']`, it becomes `x['odor']'`:

[![console][1]][1]

At first I thought I'm making a mistake but when it repeated multiple times in the same minute, by looking further I noticed an extra `'` being added. I don't know why this is happening besides, I want to change the default quote view from double to single quotes which for some reason changed in the following versions:

* macOS Monterey `12.2.1`
* ipython `8.0.1` installed using brew.


  [1]: https://i.stack.imgur.com/7rUlx.gif



Discussion:

Resolving patch:
diff --git a/IPython/terminal/shortcuts.py b/IPython/terminal/shortcuts.py
--- a/IPython/terminal/shortcuts.py
+++ b/IPython/terminal/shortcuts.py
@@ -139,12 +139,24 @@ def _(event):
         event.current_buffer.insert_text("{}")
         event.current_buffer.cursor_left()
 
-    @kb.add('"', filter=focused_insert & auto_match & following_text(r"[,)}\]]|$"))
+    @kb.add(
+        '"',
+        filter=focused_insert
+        & auto_match
+        & preceding_text(r'^([^"]+|"[^"]*")*$')
+        & following_text(r"[,)}\]]|$"),
+    )
     def _(event):
         event.current_buffer.insert_text('""')
         event.current_buffer.cursor_left()
 
-    @kb.add("'", filter=focused_insert & auto_match & following_text(r"[,)}\]]|$"))
+    @kb.add(
+        "'",
+        filter=focused_insert
+        & auto_match
+        & preceding_text(r"^([^']+|'[^']*')*$")
+        & following_text(r"[,)}\]]|$"),
+    )
     def _(event):
         event.current_buffer.insert_text("''")
         event.current_buffer.cursor_left()
@@ -186,16 +198,6 @@ def _(event):
         event.current_buffer.insert_text("{}" + dashes)
         event.current_buffer.cursor_left(len(dashes) + 1)
 
-    @kb.add('"', filter=focused_insert & auto_match & preceding_text(r".*(r|R)$"))
-    def _(event):
-        event.current_buffer.insert_text('""')
-        event.current_buffer.cursor_left()
-
-    @kb.add("'", filter=focused_insert & auto_match & preceding_text(r".*(r|R)$"))
-    def _(event):
-        event.current_buffer.insert_text("''")
-        event.current_buffer.cursor_left()
-
     # just move cursor
     @kb.add(")", filter=focused_insert & auto_match & following_text(r"^\)"))
     @kb.add("]", filter=focused_insert & auto_match & following_text(r"^\]"))


Test patch:
Repository: ipython/ipython

Issue:
CTRL backslash sends QUIT signal but freezes the terminal
A convenient way to quit Ipython and kill the debugged process is to press CTRL \ (backslash).
Once pressed, the two exit but the terminal freezes. I can type commands, press enter and see the result but I can't see the command I'm typing.
Is there any problem with STD OUT redirection after the signal is sent?
I tested on gnome-terminal and xterm with bash


Discussion:

Resolving patch:
diff --git a/IPython/terminal/shortcuts.py b/IPython/terminal/shortcuts.py
--- a/IPython/terminal/shortcuts.py
+++ b/IPython/terminal/shortcuts.py
@@ -10,6 +10,7 @@
 import signal
 import sys
 import re
+import os
 from typing import Callable
 
 
@@ -56,7 +57,7 @@ def reformat_and_execute(event):
                             & insert_mode
                                       ))(reformat_and_execute)
 
-    kb.add('c-\\')(force_exit)
+    kb.add("c-\\")(quit)
 
     kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
                 )(previous_history_or_previous_completion)
@@ -458,11 +459,16 @@ def reset_search_buffer(event):
 def suspend_to_bg(event):
     event.app.suspend_to_background()
 
-def force_exit(event):
+def quit(event):
     """
-    Force exit (with a non-zero return value)
+    On platforms that support SIGQUIT, send SIGQUIT to the current process.
+    On other platforms, just exit the process with a message.
     """
-    sys.exit("Quit")
+    sigquit = getattr(signal, "SIGQUIT", None)
+    if sigquit is not None:
+        os.kill(0, signal.SIGQUIT)
+    else:
+        sys.exit("Quit")
 
 def indent_buffer(event):
     event.current_buffer.insert_text(' ' * 4)


Test patch:
Repository: ipython/ipython

Issue:
END key no longer reliably working as expected
Having recently updated to iPython 8.2.0 I noticed that my end key is no longer consistently working as expected. Occasionally it will become unresponsive. I'm guessing this is related to the recent addition of [Adding and "End" key binding for applying an auto suggestion](https://github.com/ipython/ipython/pull/13566)

This mainly occurs when I'm in iPython working with SQLAlchemy code. It "feels" like the end key is trying to autocomplete instead of move to the end of the line, even though there is nothing to autocomplete.

If I revert to 8.1.1 I no longer experience this issue.

`Python 3.8.10`

```
ipython                  8.2.0
prompt-toolkit           3.0.29
```



Discussion:
What's the output of `%config TerminalInteractiveShell.editing_mode` in the IPython session where you experience this?
```Out[1]: 'emacs'```
This happens when the current input line equals the autosuggestion generated for it. E.g.:


![image](https://user-images.githubusercontent.com/6691643/161606801-895e2703-c69d-4d39-bb2e-52d294669aa0.png)

Hitting <kbd>End</kbd> fills in the autosuggest:

![image](https://user-images.githubusercontent.com/6691643/161606895-5a0ba894-512e-4cd7-a831-98873e2a3a16.png)

Now, if you move cursor back, the <kbd>End</kbd> key doesn't move it to the end of the line anymore:

![image](https://user-images.githubusercontent.com/6691643/161607059-fae7df2b-fe7f-4969-a0bf-3931f8bf39c1.png)

Looks like an issue with wrong `@kb.add` `filter=` in [#13566 L278](https://github.com/ipython/ipython/pull/13566/files#diff-3b2709b0687ef808e68fb6e467415ce313553aa29ba688d523ddb6ba768a7784R278).

Also, this means that <kbd>End</kbd> no longer works properly in vi mode (when emacs bindings are on).

Resolving patch:
diff --git a/IPython/terminal/shortcuts.py b/IPython/terminal/shortcuts.py
--- a/IPython/terminal/shortcuts.py
+++ b/IPython/terminal/shortcuts.py
@@ -271,7 +271,7 @@ def ebivim():
     def _apply_autosuggest(event):
         b = event.current_buffer
         suggestion = b.suggestion
-        if suggestion:
+        if suggestion is not None and suggestion.text:
             b.insert_text(suggestion.text)
         else:
             nc.end_of_line(event)


Test patch: