Repository: spyder-ide/spyder

Issue:
Inconsistent behavior with creating/saving files with default names
<!--- **PLEASE READ:** When submitting here, please ensure you've completed the following checklist and checked the boxes to confirm. Issue reports without it may be closed. Thanks! --->

### Issue Report Checklist

* [x] Searched the [issues page](https://github.com/spyder-ide/spyder/issues?q=is%3Aissue) for similar reports
* [x] Read the relevant sections of the [Spyder Troubleshooting Guide](https://github.com/spyder-ide/spyder/wiki/Troubleshooting-Guide-and-FAQ) and followed its advice
* [x] Reproduced the issue after updating with ``conda update spyder`` (or ``pip``, if not using Anaconda)
* [x] Could not reproduce inside ``jupyter qtconsole`` (if console-related)
* [x] Tried basic troubleshooting (if a bug/error)
    * [x] Restarted Spyder
    * [x] Reset preferences with ``spyder --reset``
    * [x] Reinstalled the latest version of [Anaconda](https://www.anaconda.com/download/)
    * [x] Tried the other applicable steps from the Troubleshooting Guide
* [x] Completed the **Problem Description**, **Steps to Reproduce** and **Version** sections below


## Problem Description

Creating a new file (after restarting spyder) when a tab with a default file name 'untitled0.py' already exists as a tab, creates a new tab with the name 'untitled0.p - untitled0.py' which points to 'untitled0.py' on disk. When the new tab content is saved, it will overwrite the content of the original file on disk.

### What steps reproduce the problem?

1. Remove all tabs within spyder
2. Create a new file and leave the default name as unititled0.py
3. Close spyder and restart
4. The tab 'untitled0.py' should be showing by default (normal behavior)
5. Click "New file". This will create a new tab called 'untitled0.py - untitled0.py' (unexpected behavior)
6. When you click the 'untitled0.py - untitled0.py' tab, python shows that it is pointing to 'untitled0.py' on disk. In addition, the tab 'untitled0.py' for some reason gets renamed to 'untitled0.py - untitled0.py'. So now you have two tabs with the name 'untitled0.py - untitled0.py' (unexpected behavior)
7. When saving the content of 'untitled0.py - untitled0.py', it overwrites the content of 'untitled0.py' on disk (unexpected behavior)
8. The above behavior occurs for tabs named untitled2.py, untitled3.py etc, but not for tabs with non-default user defined names.


### What is the expected output? What do you see instead?

Irrespective of what tabs are open, and what they are named, pressing 'New file' should create a tab with a unique name, which ideally does not reference a file on disk within the default save path. 

In its current state, if a tab called 'untitled0.py - untitled0.py' is created, then it should create a file called 'untitled0.py - untitled0.py' when saved, but not overwrite 'untitled0.py' as it does now.


## Versions
<!--- You can get this information from Help > About Spyder...
or (if Spyder won't launch) the "conda list" command
from the Anaconda Prompt/Terminal/command line. --->

* Spyder version: 3.3.1
* Python version: 3.6.6
* Qt version: 5.6.2
* PyQt version: 5.6.0
* Operating System name/version: Windows 10 Version 1709 (OS Build 16299.611)

### Dependencies
<!--- Please go to the menu entry Help > Dependencies,
press the Copy to clipboard button and paste below --->

IPython >=4.0     :  6.2.1 (OK)
cython >=0.21     :  0.28.1 (OK)
jedi >=0.9.0      :  0.11.1 (OK)
matplotlib >=2.0.0:  2.2.2 (OK)
nbconvert >=4.0   :  5.3.1 (OK)
numpy >=1.7       :  1.14.5 (OK)
pandas >=0.13.1   :  0.23.3 (OK)
pycodestyle >=2.3 :  2.3.1 (OK)
pyflakes >=0.6.0  :  1.6.0 (OK)
pygments >=2.0    :  2.2.0 (OK)
pylint >=0.25     :  1.8.1 (OK)
qtconsole >=4.2.0 :  4.3.1 (OK)
rope >=0.9.4      :  0.10.7 (OK)
sphinx >=0.6.6    :  1.6.6 (OK)
sympy >=0.7.3     :  None (NOK)




Discussion:
This is low priority for us.
@steff456, please take a look at this one.

Resolving patch:
diff --git a/spyder/plugins/editor/plugin.py b/spyder/plugins/editor/plugin.py
--- a/spyder/plugins/editor/plugin.py
+++ b/spyder/plugins/editor/plugin.py
@@ -1783,6 +1783,17 @@ def new(self, fname=None, editorstack=None, text=None):
             current_es = editorstack
         created_from_here = fname is None
         if created_from_here:
+            if self.untitled_num == 0:
+                for finfo in current_es.data:
+                    current_filename = finfo.editor.filename
+                    if _("untitled") in current_filename:
+                        # Start the counter of the untitled_num with respect
+                        # to this number if there's other untitled file in
+                        # spyder. Please see spyder-ide/spyder#7831
+                        fname_data = osp.splitext(current_filename)
+                        act_num = int(fname_data[0].split(_("untitled"))[-1])
+                        self.untitled_num = act_num + 1
+
             while True:
                 fname = create_fname(self.untitled_num)
                 self.untitled_num += 1


Test patch:
diff --git a/spyder/plugins/editor/tests/conftest.py b/spyder/plugins/editor/tests/conftest.py
--- a/spyder/plugins/editor/tests/conftest.py
+++ b/spyder/plugins/editor/tests/conftest.py
@@ -78,7 +78,8 @@ def python_files(tmpdir_factory):
     tmpdir = osp.normcase(tmpdir.strpath)
 
     filenames = [osp.join(tmpdir, f) for f in
-                 ('file1.py', 'file2.py', 'file3.py', 'file4.py')]
+                 ('file1.py', 'file2.py', 'file3.py', 'file4.py',
+                  'untitled4.py')]
     for filename in filenames:
         with open(filename, 'w') as f:
             f.write("# -*- coding: utf-8 -*-\n"
diff --git a/spyder/plugins/editor/tests/test_plugin.py b/spyder/plugins/editor/tests/test_plugin.py
--- a/spyder/plugins/editor/tests/test_plugin.py
+++ b/spyder/plugins/editor/tests/test_plugin.py
@@ -73,6 +73,24 @@ def test_setup_open_files_cleanprefs(editor_plugin_open_files):
     assert current_filename == expected_current_filename
 
 
+def test_open_untitled_files(editor_plugin_open_files):
+    """
+    Test for checking the counter of the untitled files is starting
+    correctly when there is one or more `untitledx.py` files saved.
+
+    Regression test for spyder-ide/spyder#7831
+    """
+    editor_factory = editor_plugin_open_files
+    editor, expected_filenames, expected_current_filename = (
+        editor_factory(None, None))
+
+    editor.new()
+    filenames = editor.get_current_editorstack().get_filenames()
+    new_filename = filenames[-1]
+    assert 'untitled5.py' in new_filename
+
+
+
 def test_renamed_tree(editor_plugin, mocker):
     """Test editor.renamed_tree().
 
@@ -223,7 +241,7 @@ def test_go_to_prev_next_cursor_position(editor_plugin, python_files):
     filenames = editor_plugin.get_filenames()
     expected_cursor_pos_history = [
         (filenames[0], 0),
-        (filenames[4], len(editorstack.data[4].get_source_code())),
+        (filenames[-1], len(editorstack.data[-1].get_source_code())),
         (filenames[2], 0)
         ]
     assert editor_plugin.cursor_pos_history == expected_cursor_pos_history