changeset 31004:2b4f7287aa3a stable

fix removing trailing spaces on closing a modified file (bug #62271) * file-editor-tab.cc (do_save_file): remove trailing spaces before the file is opened, make sure edit area is writeable before removing spaces, open the file in read-write mode avoiding truncation of existing parts of the file
author Torsten Lilge <ttl-octave@mailbox.org>
date Mon, 16 May 2022 23:00:27 +0200
parents c05aa021e971
children 35d37e433532
files libgui/src/m-editor/file-editor-tab.cc
diffstat 1 files changed, 18 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/libgui/src/m-editor/file-editor-tab.cc	Sun May 15 18:06:02 2022 -0700
+++ b/libgui/src/m-editor/file-editor-tab.cc	Mon May 16 23:00:27 2022 +0200
@@ -2190,8 +2190,24 @@
     if (trackedFiles.contains (file_to_save))
       m_file_system_watcher.removePath (file_to_save);
 
-    // open the file for writing
-    if (! file.open (QIODevice::WriteOnly))
+    // Remove trailing white spaces if desired
+    resource_manager& rmgr = m_octave_qobj.get_resource_manager ();
+    gui_settings *settings = rmgr.get_settings ();
+
+    if (settings->value (ed_rm_trailing_spaces).toBool ())
+      {
+        // Replace trailing spaces, make sure edit area is writable,
+        // which is not the case when saving at exit or when closing
+        // the modified file.
+        bool ro = m_edit_area->isReadOnly ();
+        m_edit_area->setReadOnly (false); // allow writing for replace_all
+        m_edit_area->replace_all ("[ \\t]+$", "", true, false, false);
+        m_edit_area->setReadOnly (ro);    // recover read only state
+      }
+
+    // open the file for writing (use QIODevice::ReadWrite for avoiding
+    // truncating the previous file contents)
+    if (! file.open (QIODevice::ReadWrite))
       {
         // Unsuccessful, begin watching file again if it was being
         // watched previously.
@@ -2220,13 +2236,6 @@
     if (! codec)
       return;   // No valid codec
 
-    // Remove trailing white spaces if desired
-    resource_manager& rmgr = m_octave_qobj.get_resource_manager ();
-    gui_settings *settings = rmgr.get_settings ();
-
-    if (settings->value (ed_rm_trailing_spaces).toBool ())
-      m_edit_area->replace_all ("[ \\t]+$", "", true, false, false);
-
     // Save the file
     out.setCodec (codec);