Repository: spyder-ide/spyder

Issue:
IndexError when saving file and auto-formatting is on
## Description

### What steps will reproduce the problem?

<!--- You can use Markdown here --->

list = ['blah1', 'blah2']
print(sorted(list))
Issue with saving file

### Traceback
```python-traceback
  File "C:\Users\Andy\AppData\Local\Programs\Spyder\pkgs\spyder\plugins\editor\widgets\editor.py", line 2093, in _save_file
    self.modification_changed(index=index)
  File "C:\Users\Andy\AppData\Local\Programs\Spyder\pkgs\spyder\plugins\editor\widgets\editor.py", line 2550, in modification_changed
    finfo = self.data[index]
IndexError: list index out of range
```

## Versions

* Spyder version: 4.2.1 
* Python version: 3.7.9
* Qt version: 5.12.10
* PyQt5 version: 5.12.3
* Operating System: Windows 10

### Dependencies

```

# Mandatory:
atomicwrites >=1.2.0            :  1.4.0 (OK)
chardet >=2.0.0                 :  4.0.0 (OK)
cloudpickle >=0.5.0             :  1.6.0 (OK)
diff_match_patch >=20181111     :  20200713 (OK)
intervaltree                    :  None (OK)
IPython >=7.6.0                 :  7.19.0 (OK)
jedi =0.17.2                    :  0.17.2 (OK)
jsonschema >=3.2.0              :  3.2.0 (OK)
keyring >=17.0.0                :  21.5.0 (OK)
nbconvert >=4.0                 :  6.0.7 (OK)
numpydoc >=0.6.0                :  1.1.0 (OK)
paramiko >=2.4.0                :  2.7.2 (OK)
parso =0.7.0                    :  0.7.0 (OK)
pexpect >=4.4.0                 :  4.8.0 (OK)
pickleshare >=0.4               :  0.7.5 (OK)
psutil >=5.3                    :  5.7.3 (OK)
pygments >=2.0                  :  2.7.3 (OK)
pylint >=1.0                    :  2.6.0 (OK)
pyls >=0.36.2;<1.0.0            :  0.36.2 (OK)
pyls_black >=0.4.6              :  0.4.6 (OK)
pyls_spyder >=0.3.0             :  0.3.0 (OK)
qdarkstyle >=2.8                :  2.8.1 (OK)
qtawesome >=0.5.7               :  1.0.2 (OK)
qtconsole >=5.0.1               :  5.0.1 (OK)
qtpy >=1.5.0                    :  1.9.0 (OK)
rtree >=0.8.3                   :  0.9.4 (OK)
setuptools >=39.0.0             :  51.0.0 (OK)
sphinx >=0.6.6                  :  3.3.1 (OK)
spyder_kernels >=1.10.1;<1.11.0 :  1.10.1 (OK)
textdistance >=4.2.0            :  4.2.0 (OK)
three_merge >=0.1.1             :  0.1.1 (OK)
watchdog                        :  1.0.2 (OK)
zmq >=17                        :  20.0.0 (OK)

# Optional:
cython >=0.21                   :  0.29.21 (OK)
matplotlib >=2.0.0              :  3.3.3 (OK)
numpy >=1.7                     :  1.19.3 (OK)
pandas >=1.1.1                  :  1.1.5 (OK)
scipy >=0.17.0                  :  1.5.4 (OK)
sympy >=0.7.3                   :  1.7.1 (OK)
```



Discussion:
Hey @mil01, thanks for reporting. This problem has been reported a couple of times before but we don't understand how it's generated.

Could you upload an animated gif that shows when the error appears? For that you can use the [Licecap](https://www.cockos.com/licecap/) program.
@ccordoba12  I think I might have the save issue. It happens when I save file.
I think it may be somehow related to the code autoformatting (see gif). In gif I use CMD+S to save my file. 

The problem disappears if I do not use "autoformatting when saving". 

Both autopep-8 and black calls the error.

![spyder](https://user-images.githubusercontent.com/60148493/106291674-39b2fc80-624c-11eb-9419-5c435602d1ec.gif)

Thanks @SergeiDBykov for the insight! It's really useful!
@ccordoba12 After the problems with new version of spyder I returned to 4.2.0 and the error I described above is no more. I hope it helps to you. 
@SergeiDBykov, this error could be fixed in 4.2.2 but we're unsure because we were unable to reproduce it.

Please let us know if you don't observe the error anymore when that version is released (we'll do that next week).
@ccordoba12 I was unable to reproduce this with Spyder 5.3.0 with the standalone installer on Windows:

![format](https://user-images.githubusercontent.com/16781833/163026748-66b2e3c8-99c4-44ba-b0d6-45255b080708.gif)


Could you check by splitting the editor vertically and horizontally several times? And then saving in different split editors?

This could also happen on new editor windows, i.e. the ones you create with

![imagen](https://user-images.githubusercontent.com/365293/163440791-52f3c4b5-ebee-4f86-9d7c-c28b14d8bf16.png)

No error with the Windows installer:

![auto](https://user-images.githubusercontent.com/16781833/163442015-01538a80-ed9d-48a7-a858-c4dbc54781d2.gif)


Ok, that's really good to know, thanks for testing. Let's wait to see if someone with 5.3 has this problem before closing.
Ok, I finally found the cause of this problem: closing tabs in the editor while a formatting operation is in process! That can be seen in the gif below:

![index-error](https://user-images.githubusercontent.com/365293/164305960-607d242f-5785-42a7-8250-bdce08517950.gif)

@dalthviz, I think the solution is to use the file name, instead of the tab index, in the `modification_changed` and `analyze_script` methods of `EditorStack`. I got this clue from a comment in `_save_file`:

https://github.com/spyder-ide/spyder/blob/d8b9b022d08a7b4013426470aa5c15a236f703ba/spyder/plugins/editor/widgets/editor.py#L1930-L1933

Resolving patch:
diff --git a/spyder/plugins/editor/widgets/editor.py b/spyder/plugins/editor/widgets/editor.py
--- a/spyder/plugins/editor/widgets/editor.py
+++ b/spyder/plugins/editor/widgets/editor.py
@@ -1897,10 +1897,10 @@ def save(self, index=None, force=False, save_new_files=True):
             if self.format_on_save and finfo.editor.formatting_enabled:
                 # Autoformat document and then save
                 finfo.editor.sig_stop_operation_in_progress.connect(
-                    functools.partial(self._save_file, finfo, index))
+                    lambda: self._save_file(finfo))
                 finfo.editor.format_document()
             else:
-                self._save_file(finfo, index)
+                self._save_file(finfo)
             return True
         except EnvironmentError as error:
             self.msgbox = QMessageBox(
@@ -1914,7 +1914,8 @@ def save(self, index=None, force=False, save_new_files=True):
             self.msgbox.exec_()
             return False
 
-    def _save_file(self, finfo, index):
+    def _save_file(self, finfo):
+        index = self.data.index(finfo)
         self._write_to_file(finfo, finfo.filename)
         file_hash = self.compute_hash(finfo)
         self.autosave.file_hashes[finfo.filename] = file_hash
@@ -1934,7 +1935,7 @@ def _save_file(self, finfo, index):
 
         finfo.editor.document().setModified(False)
         self.modification_changed(index=index)
-        self.analyze_script(index)
+        self.analyze_script(index=index)
 
         finfo.editor.notify_save()
 


Test patch: