Repository: spyder-ide/spyder

Issue:
`Trim all newlines after the final one` when saving a file causes Spyder to freeze when saving a blank file
<!--- **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

* [:)] Searched the [issues page](https://github.com/spyder-ide/spyder/issues?q=is%3Aissue) for similar reports
* [:)] Read the relevant sections of the [Spyder Troubleshooting Guide](https://github.com/spyder-ide/spyder/wiki/Troubleshooting-Guide-and-FAQ) and followed its advice
* [:)] Reproduced the issue after updating with ``conda update spyder`` (or ``pip``, if not using Anaconda)
* [:)] Could not reproduce inside ``jupyter qtconsole`` (if console-related)
* [:)] Tried basic troubleshooting (if a bug/error)
    * [:)] Restarted Spyder
    * [:)] Reset preferences with ``spyder --reset``
    * [ ] Reinstalled the latest version of [Anaconda](https://www.anaconda.com/download/)
    * [:)] Tried the other applicable steps from the Troubleshooting Guide
* [:)] Completed the **Problem Description**, **Steps to Reproduce** and **Version** sections below


## Problem Description

If you set the "Trim all newlines after the final one when saving a file" preference, then saving a blank file causes Spyder to totally hang.

I think this is maybe the cause of these bug reports:
https://github.com/spyder-ide/spyder/issues/14926
https://github.com/spyder-ide/spyder/issues/15284

You won't get this symptom with the default Spyder preferences (as of 5.0.5) which explains the lack of reproducibility.

## 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 5.0.5
Python 3.9.5 64-bit | Qt 5.9.7 | PyQt5 5.9.2 | Darwin 17.7.0 


### Dependencies
<!--- Please go to the menu entry Help > Dependencies,
press the Copy to clipboard button and paste below --->

```

# Mandatory:
applaunchservices >=0.1.7     :  0.2.1 (OK)
atomicwrites >=1.2.0          :  1.4.0 (OK)
chardet >=2.0.0               :  4.0.0 (OK)
cloudpickle >=0.5.0           :  1.6.0 (OK)
cookiecutter >=1.6.0          :  1.7.2 (OK)
diff_match_patch >=20181111   :  20200713 (OK)
intervaltree >=3.0.2          :  3.1.0 (OK)
IPython >=7.6.0               :  7.22.0 (OK)
jedi =0.17.2                  :  0.17.2 (OK)
jsonschema >=3.2.0            :  3.2.0 (OK)
keyring >=17.0.0              :  23.0.1 (OK)
nbconvert >=4.0               :  6.1.0 (OK)
numpydoc >=0.6.0              :  1.1.0 (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.8.0 (OK)
pygments >=2.0                :  2.9.0 (OK)
pylint >=1.0                  :  2.9.5 (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.2;<0.4.0    :  0.3.2 (OK)
qdarkstyle =3.0.2             :  3.0.2 (OK)
qstylizer >=0.1.10            :  0.1.10 (OK)
qtawesome >=1.0.2             :  1.0.2 (OK)
qtconsole >=5.1.0             :  5.1.1 (OK)
qtpy >=1.5.0                  :  1.9.0 (OK)
rtree >=0.9.7                 :  0.9.7 (OK)
setuptools >=39.0.0           :  52.0.0.post20210125 (OK)
sphinx >=0.6.6                :  4.0.2 (OK)
spyder_kernels >=2.0.4;<2.1.0 :  2.0.5 (OK)
textdistance >=4.2.0          :  4.2.1 (OK)
three_merge >=0.1.1           :  0.1.1 (OK)
watchdog >=0.10.3             :  2.1.3 (OK)
zmq >=17                      :  20.0.0 (OK)

# Optional:
cython >=0.21                 :  0.29.24 (OK)
matplotlib >=2.0.0            :  3.3.4 (OK)
numpy >=1.7                   :  1.20.3 (OK)
pandas >=1.1.1                :  1.3.0 (OK)
scipy >=0.17.0                :  1.6.2 (OK)
sympy >=0.7.3                 :  1.8 (OK)
```



Discussion:
Hey @battaglia01, thanks for reporting. I could reproduce this problem and will try to fix it soon.

Resolving patch:
diff --git a/spyder/plugins/editor/widgets/codeeditor.py b/spyder/plugins/editor/widgets/codeeditor.py
--- a/spyder/plugins/editor/widgets/codeeditor.py
+++ b/spyder/plugins/editor/widgets/codeeditor.py
@@ -2268,21 +2268,24 @@ def trim_trailing_newlines(self):
         this_line = self.get_text_line(line)
         previous_line = self.get_text_line(line - 1)
 
-        while this_line == '':
-            cursor.movePosition(QTextCursor.PreviousBlock,
-                                QTextCursor.KeepAnchor)
-
-            if self.add_newline:
-                if this_line == '' and previous_line != '':
-                    cursor.movePosition(QTextCursor.NextBlock,
-                                        QTextCursor.KeepAnchor)
-
-            line -= 1
-            if line == 0:
-                break
+        # Don't try to trim new lines for a file with a single line.
+        # Fixes spyder-ide/spyder#16401
+        if self.get_line_count() > 1:
+            while this_line == '':
+                cursor.movePosition(QTextCursor.PreviousBlock,
+                                    QTextCursor.KeepAnchor)
+
+                if self.add_newline:
+                    if this_line == '' and previous_line != '':
+                        cursor.movePosition(QTextCursor.NextBlock,
+                                            QTextCursor.KeepAnchor)
+
+                line -= 1
+                if line == 0:
+                    break
 
-            this_line = self.get_text_line(line)
-            previous_line = self.get_text_line(line - 1)
+                this_line = self.get_text_line(line)
+                previous_line = self.get_text_line(line - 1)
 
         if not self.add_newline:
             cursor.movePosition(QTextCursor.EndOfBlock,
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
@@ -2650,6 +2650,7 @@ def set_os_eol_chars(self, index=None, osname=None):
             index = self.get_stack_index()
         finfo = self.data[index]
         eol_chars = sourcecode.get_eol_chars_from_os_name(osname)
+        logger.debug(f"Set OS eol chars {eol_chars} for file {finfo.filename}")
         finfo.editor.set_eol_chars(eol_chars)
         finfo.editor.document().setModified(True)
 
@@ -2658,18 +2659,21 @@ def remove_trailing_spaces(self, index=None):
         if index is None:
             index = self.get_stack_index()
         finfo = self.data[index]
+        logger.debug(f"Remove trailing spaces for file {finfo.filename}")
         finfo.editor.trim_trailing_spaces()
 
     def trim_trailing_newlines(self, index=None):
         if index is None:
             index = self.get_stack_index()
         finfo = self.data[index]
+        logger.debug(f"Trim trailing new lines for file {finfo.filename}")
         finfo.editor.trim_trailing_newlines()
 
     def add_newline_to_file(self, index=None):
         if index is None:
             index = self.get_stack_index()
         finfo = self.data[index]
+        logger.debug(f"Add new line to file {finfo.filename}")
         finfo.editor.add_newline_to_file()
 
     def fix_indentation(self, index=None):
@@ -2677,12 +2681,14 @@ def fix_indentation(self, index=None):
         if index is None:
             index = self.get_stack_index()
         finfo = self.data[index]
+        logger.debug(f"Fix indentation for file {finfo.filename}")
         finfo.editor.fix_indentation()
 
     def format_document_or_selection(self, index=None):
         if index is None:
             index = self.get_stack_index()
         finfo = self.data[index]
+        logger.debug(f"Run formatting in file {finfo.filename}")
         finfo.editor.format_document_or_range()
 
     #  ------ Run


Test patch: