gh-44968: Add "Reload from Disk" feature to IDLE

This commit is contained in:
Shamil Abdulaev 2025-11-15 00:56:08 +03:00
parent 1281be1caf
commit 39e61879e1
No known key found for this signature in database
GPG key ID: F9F7726024C005E7
4 changed files with 174 additions and 0 deletions

View file

@ -31,6 +31,7 @@ def __init__(self, editwin):
self.save_as)
self.__id_savecopy = self.text.bind("<<save-copy-of-window-as-file>>",
self.save_a_copy)
self.__id_reload = self.text.bind("<<reload-window>>", self.reload)
self.fileencoding = 'utf-8'
self.__id_print = self.text.bind("<<print-window>>", self.print_window)
@ -40,6 +41,7 @@ def close(self):
self.text.unbind("<<save-window>>", self.__id_save)
self.text.unbind("<<save-window-as-file>>",self.__id_saveas)
self.text.unbind("<<save-copy-of-window-as-file>>", self.__id_savecopy)
self.text.unbind("<<reload-window>>", self.__id_reload)
self.text.unbind("<<print-window>>", self.__id_print)
# Break cycles
self.editwin = None
@ -237,6 +239,49 @@ def save_a_copy(self, event):
self.updaterecentfileslist(filename)
return "break"
def reload(self, event):
"""Reload the file from disk, discarding any unsaved changes.
If the file has unsaved changes, ask the user to confirm.
"""
if not self.filename:
messagebox.showinfo(
"No File",
"This window has no associated file to reload.",
parent=self.text)
self.text.focus_set()
return "break"
if not self.get_saved():
confirm = messagebox.askokcancel(
title="Reload File",
message=f"Discard changes to {self.filename}?",
default=messagebox.CANCEL,
parent=self.text)
if not confirm:
self.text.focus_set()
return "break"
# Save cursor position
insert_pos = self.text.index("insert")
yview_pos = self.text.yview()
# Reload the file
if self.loadfile(self.filename):
# Try to restore cursor position if the file still has that line
try:
self.text.mark_set("insert", insert_pos)
self.text.see("insert")
# Restore vertical scroll position
self.text.yview_moveto(yview_pos[0])
except Exception:
# If position doesn't exist anymore, go to top
self.text.mark_set("insert", "1.0")
self.text.see("insert")
self.text.focus_set()
return "break"
def writefile(self, filename):
text = self.fixnewlines()
chars = self.encode(text)