Skip to content

Commit f9beae7

Browse files
authored
Implementation to preserve undo across saves (#501)
* Added initial implementation to preserve undo across saves * Prevent modulefinder from erroring on normal use of CQ in imported modules * Improved the modulefinder cadquery check
1 parent 2198069 commit f9beae7

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

cq_editor/widgets/editor.py

+30-5
Original file line numberDiff line numberDiff line change
@@ -269,8 +269,28 @@ def _file_changed(self):
269269
vertical_scroll_pos = self.verticalScrollBar().value()
270270
horizontal_scroll_pos = self.horizontalScrollBar().value()
271271

272-
# Reload the file in case it was modified by an external editor
273-
self.set_text_from_file(self._filename)
272+
# Save undo stack before reloading text
273+
undo_stack = self.document().isUndoAvailable()
274+
275+
# Block signals to avoid reset issues
276+
self.blockSignals(True)
277+
278+
# Read the contents of the file into a string
279+
with open(self._filename, "r", encoding="utf-8") as f:
280+
file_contents = f.read()
281+
282+
# Insert new text while preserving history
283+
cursor = self.textCursor()
284+
cursor.select(QTextCursor.Document)
285+
cursor.insertText(file_contents)
286+
287+
# Stop blocking signals
288+
self.blockSignals(False)
289+
290+
# Restore undo stack availability
291+
if undo_stack:
292+
self.document().setModified(True)
293+
self.document().undo() # Prevents the need for a double undo
274294

275295
# Restore the cursor position and selection
276296
cursor.setPosition(anchor_position)
@@ -324,9 +344,14 @@ def get_imported_module_paths(self, module_path):
324344
except SyntaxError as err:
325345
self._logger.warning(f"Syntax error in {module_path}: {err}")
326346
except Exception as err:
327-
self._logger.warning(
328-
f"Cannot determine imported modules in {module_path}: {type(err).__name__} {err}"
329-
)
347+
# The module finder has trouble when CadQuery is imported in the top level script and in
348+
# imported modules. The warning about it can be ignored.
349+
if "cadquery" not in finder.badmodules or (
350+
"cadquery" in finder.badmodules and len(finder.badmodules) > 1
351+
):
352+
self._logger.warning(
353+
f"Cannot determine imported modules in {module_path}: {type(err).__name__} {err}"
354+
)
330355
else:
331356
for module_name, module in finder.modules.items():
332357
if module_name != "__main__":

0 commit comments

Comments
 (0)