blob: d20c708ef9c814c5d0b80e200f4396cf4fa254c3 [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001import os
Kurt B. Kaiser01166da2002-09-16 22:03:37 +00002import types
3import sys
4import codecs
Steven M. Gava7981ce52002-06-11 04:45:34 +00005import tempfile
Georg Brandl14fc4272008-05-17 18:39:55 +00006import tkinter.filedialog as tkFileDialog
7import tkinter.messagebox as tkMessageBox
David Scherer7aced172000-08-15 01:13:23 +00008import re
Georg Brandl14fc4272008-05-17 18:39:55 +00009from tkinter import *
Martin v. Löwis7e158452009-01-18 20:23:36 +000010from tkinter.simpledialog import askstring
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +000011
Kurt B. Kaiser3a4e24b2007-08-22 18:06:14 +000012from idlelib.configHandler import idleConf
David Scherer7aced172000-08-15 01:13:23 +000013
Kurt B. Kaiser1963ad32007-09-01 19:47:39 +000014from codecs import BOM_UTF8
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000015
16# Try setting the locale, so that we can find out
17# what encoding to use
18try:
19 import locale
20 locale.setlocale(locale.LC_CTYPE, "")
Kurt B. Kaiser188e25f2003-11-25 05:01:00 +000021except (ImportError, locale.Error):
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000022 pass
23
Martin v. Löwis307021f2005-11-27 16:59:04 +000024# Encoding for file names
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000025filesystemencoding = sys.getfilesystemencoding() ### currently unused
Martin v. Löwis307021f2005-11-27 16:59:04 +000026
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000027locale_encoding = 'ascii'
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000028if sys.platform == 'win32':
29 # On Windows, we could use "mbcs". However, to give the user
30 # a portable encoding name, we need to find the code page
31 try:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000032 locale_encoding = locale.getdefaultlocale()[1]
33 codecs.lookup(locale_encoding)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000034 except LookupError:
35 pass
36else:
37 try:
38 # Different things can fail here: the locale module may not be
39 # loaded, it may not offer nl_langinfo, or CODESET, or the
40 # resulting codeset may be unknown to Python. We ignore all
41 # these problems, falling back to ASCII
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000042 locale_encoding = locale.nl_langinfo(locale.CODESET)
43 if locale_encoding is None or locale_encoding is '':
Tony Lowndse555fc72002-09-23 01:01:20 +000044 # situation occurs on Mac OS X
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000045 locale_encoding = 'ascii'
46 codecs.lookup(locale_encoding)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000047 except (NameError, AttributeError, LookupError):
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000048 # Try getdefaultlocale: it parses environment variables,
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000049 # which may give a clue. Unfortunately, getdefaultlocale has
50 # bugs that can cause ValueError.
51 try:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000052 locale_encoding = locale.getdefaultlocale()[1]
53 if locale_encoding is None or locale_encoding is '':
Tony Lowndse555fc72002-09-23 01:01:20 +000054 # situation occurs on Mac OS X
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000055 locale_encoding = 'ascii'
56 codecs.lookup(locale_encoding)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000057 except (ValueError, LookupError):
58 pass
59
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000060locale_encoding = locale_encoding.lower()
61
62encoding = locale_encoding ### KBK 07Sep07 This is used all over IDLE, check!
63 ### 'encoding' is used below in encode(), check!
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000064
65coding_re = re.compile("coding[:=]\s*([-\w_.]+)")
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +000066
Kurt B. Kaiser1963ad32007-09-01 19:47:39 +000067def coding_spec(data):
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000068 """Return the encoding declaration according to PEP 263.
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000069
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000070 When checking encoded data, only the first two lines should be passed
71 in to avoid a UnicodeDecodeError if the rest of the data is not unicode.
72 The first two lines would contain the encoding specification.
73
74 Raise a LookupError if the encoding is declared but unknown.
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +000075 """
Kurt B. Kaiser1963ad32007-09-01 19:47:39 +000076 if isinstance(data, bytes):
Martin v. Löwis975a0792009-01-18 20:15:42 +000077 # This encoding might be wrong. However, the coding
78 # spec must be ASCII-only, so any non-ASCII characters
79 # around here will be ignored. Decoding to Latin-1 should
80 # never fail (except for memory outage)
81 lines = data.decode('iso-8859-1')
Kurt B. Kaiser1963ad32007-09-01 19:47:39 +000082 else:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +000083 lines = data
84 # consider only the first two lines
85 if '\n' in lines:
86 lst = lines.split('\n')[:2]
87 elif '\r' in lines:
88 lst = lines.split('\r')[:2]
89 else:
90 lst = list(lines)
91 str = '\n'.join(lst)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000092 match = coding_re.search(str)
93 if not match:
94 return None
95 name = match.group(1)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +000096 try:
97 codecs.lookup(name)
98 except LookupError:
99 # The standard encoding error does not indicate the encoding
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000100 raise LookupError("Unknown encoding: "+name)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000101 return name
David Scherer7aced172000-08-15 01:13:23 +0000102
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000103
David Scherer7aced172000-08-15 01:13:23 +0000104class IOBinding:
105
106 def __init__(self, editwin):
107 self.editwin = editwin
108 self.text = editwin.text
109 self.__id_open = self.text.bind("<<open-window-from-file>>", self.open)
110 self.__id_save = self.text.bind("<<save-window>>", self.save)
111 self.__id_saveas = self.text.bind("<<save-window-as-file>>",
112 self.save_as)
113 self.__id_savecopy = self.text.bind("<<save-copy-of-window-as-file>>",
114 self.save_a_copy)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000115 self.fileencoding = None
Steven M. Gava7981ce52002-06-11 04:45:34 +0000116 self.__id_print = self.text.bind("<<print-window>>", self.print_window)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000117
David Scherer7aced172000-08-15 01:13:23 +0000118 def close(self):
119 # Undo command bindings
120 self.text.unbind("<<open-window-from-file>>", self.__id_open)
121 self.text.unbind("<<save-window>>", self.__id_save)
122 self.text.unbind("<<save-window-as-file>>",self.__id_saveas)
123 self.text.unbind("<<save-copy-of-window-as-file>>", self.__id_savecopy)
Steven M. Gava7981ce52002-06-11 04:45:34 +0000124 self.text.unbind("<<print-window>>", self.__id_print)
David Scherer7aced172000-08-15 01:13:23 +0000125 # Break cycles
126 self.editwin = None
127 self.text = None
128 self.filename_change_hook = None
129
130 def get_saved(self):
131 return self.editwin.get_saved()
132
133 def set_saved(self, flag):
134 self.editwin.set_saved(flag)
135
136 def reset_undo(self):
137 self.editwin.reset_undo()
138
139 filename_change_hook = None
140
141 def set_filename_change_hook(self, hook):
142 self.filename_change_hook = hook
143
144 filename = None
Kurt B. Kaiserd2f48612003-06-05 02:34:04 +0000145 dirname = None
David Scherer7aced172000-08-15 01:13:23 +0000146
147 def set_filename(self, filename):
Kurt B. Kaiserd2f48612003-06-05 02:34:04 +0000148 if filename and os.path.isdir(filename):
149 self.filename = None
150 self.dirname = filename
151 else:
152 self.filename = filename
153 self.dirname = None
154 self.set_saved(1)
155 if self.filename_change_hook:
156 self.filename_change_hook()
David Scherer7aced172000-08-15 01:13:23 +0000157
Steven M. Gava1d46e402002-03-27 08:40:46 +0000158 def open(self, event=None, editFile=None):
David Scherer7aced172000-08-15 01:13:23 +0000159 if self.editwin.flist:
Steven M. Gava1d46e402002-03-27 08:40:46 +0000160 if not editFile:
161 filename = self.askopenfile()
162 else:
163 filename=editFile
David Scherer7aced172000-08-15 01:13:23 +0000164 if filename:
Kurt B. Kaiser1bf4c2d2002-07-21 01:24:28 +0000165 # If the current window has no filename and hasn't been
166 # modified, we replace its contents (no loss). Otherwise
167 # we open a new window. But we won't replace the
168 # shell window (which has an interp(reter) attribute), which
169 # gets set to "not modified" at every new prompt.
170 try:
171 interp = self.editwin.interp
Thomas Wouterscf297e42007-02-23 15:07:44 +0000172 except AttributeError:
Kurt B. Kaiser1bf4c2d2002-07-21 01:24:28 +0000173 interp = None
174 if not self.filename and self.get_saved() and not interp:
David Scherer7aced172000-08-15 01:13:23 +0000175 self.editwin.flist.open(filename, self.loadfile)
176 else:
177 self.editwin.flist.open(filename)
178 else:
179 self.text.focus_set()
David Scherer7aced172000-08-15 01:13:23 +0000180 return "break"
Kurt B. Kaiser1bf4c2d2002-07-21 01:24:28 +0000181 #
David Scherer7aced172000-08-15 01:13:23 +0000182 # Code for use outside IDLE:
183 if self.get_saved():
184 reply = self.maybesave()
185 if reply == "cancel":
186 self.text.focus_set()
187 return "break"
Steven M. Gava1d46e402002-03-27 08:40:46 +0000188 if not editFile:
189 filename = self.askopenfile()
190 else:
191 filename=editFile
David Scherer7aced172000-08-15 01:13:23 +0000192 if filename:
193 self.loadfile(filename)
194 else:
195 self.text.focus_set()
196 return "break"
197
Guido van Rossumc2f77dd2003-04-25 18:36:31 +0000198 eol = r"(\r\n)|\n|\r" # \r\n (Windows), \n (UNIX), or \r (Mac)
199 eol_re = re.compile(eol)
Kurt B. Kaiser8d5c8b52007-10-10 00:36:38 +0000200 eol_convention = os.linesep # default
Guido van Rossumc2f77dd2003-04-25 18:36:31 +0000201
David Scherer7aced172000-08-15 01:13:23 +0000202 def loadfile(self, filename):
203 try:
204 # open the file in binary mode so that we can handle
Kurt B. Kaiser3a4e24b2007-08-22 18:06:14 +0000205 # end-of-line convention ourselves.
David Scherer7aced172000-08-15 01:13:23 +0000206 f = open(filename,'rb')
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000207 two_lines = f.readline() + f.readline()
208 f.seek(0)
Kurt B. Kaiser1963ad32007-09-01 19:47:39 +0000209 bytes = f.read()
David Scherer7aced172000-08-15 01:13:23 +0000210 f.close()
Guido van Rossumb940e112007-01-10 16:19:56 +0000211 except IOError as msg:
David Scherer7aced172000-08-15 01:13:23 +0000212 tkMessageBox.showerror("I/O Error", str(msg), master=self.text)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000213 return False
Martin v. Löwis7e158452009-01-18 20:23:36 +0000214 chars, converted = self._decode(two_lines, bytes)
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000215 if chars is None:
216 tkMessageBox.showerror("Decoding Error",
217 "File %s\nFailed to Decode" % filename,
218 parent=self.text)
219 return False
David Scherer7aced172000-08-15 01:13:23 +0000220 # We now convert all end-of-lines to '\n's
Guido van Rossumc2f77dd2003-04-25 18:36:31 +0000221 firsteol = self.eol_re.search(chars)
222 if firsteol:
223 self.eol_convention = firsteol.group(0)
224 chars = self.eol_re.sub(r"\n", chars)
David Scherer7aced172000-08-15 01:13:23 +0000225 self.text.delete("1.0", "end")
226 self.set_filename(None)
227 self.text.insert("1.0", chars)
228 self.reset_undo()
229 self.set_filename(filename)
Martin v. Löwis7e158452009-01-18 20:23:36 +0000230 if converted:
231 # We need to save the conversion results first
232 # before being able to execute the code
233 self.set_saved(False)
David Scherer7aced172000-08-15 01:13:23 +0000234 self.text.mark_set("insert", "1.0")
Ned Deilyf25e3d52011-07-26 18:17:33 -0700235 self.text.yview("insert")
Chui Tey993e81a2002-11-04 03:11:10 +0000236 self.updaterecentfileslist(filename)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000237 return True
238
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000239 def _decode(self, two_lines, bytes):
240 "Create a Unicode string."
241 chars = None
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000242 # Check presence of a UTF-8 signature first
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000243 if bytes.startswith(BOM_UTF8):
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000244 try:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000245 chars = bytes[3:].decode("utf-8")
246 except UnicodeDecodeError:
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000247 # has UTF-8 signature, but fails to decode...
Martin v. Löwis7e158452009-01-18 20:23:36 +0000248 return None, False
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000249 else:
250 # Indicates that this file originally had a BOM
Kurt B. Kaiser1963ad32007-09-01 19:47:39 +0000251 self.fileencoding = 'BOM'
Martin v. Löwis7e158452009-01-18 20:23:36 +0000252 return chars, False
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000253 # Next look for coding specification
254 try:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000255 enc = coding_spec(two_lines)
Guido van Rossumb940e112007-01-10 16:19:56 +0000256 except LookupError as name:
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000257 tkMessageBox.showerror(
258 title="Error loading the file",
259 message="The encoding '%s' is not known to this Python "\
260 "installation. The file may not display correctly" % name,
261 master = self.text)
262 enc = None
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000263 except UnicodeDecodeError:
Martin v. Löwis7e158452009-01-18 20:23:36 +0000264 return None, False
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000265 if enc:
266 try:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000267 chars = str(bytes, enc)
268 self.fileencoding = enc
Martin v. Löwis7e158452009-01-18 20:23:36 +0000269 return chars, False
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000270 except UnicodeDecodeError:
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000271 pass
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000272 # Try ascii:
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000273 try:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000274 chars = str(bytes, 'ascii')
275 self.fileencoding = None
Martin v. Löwis7e158452009-01-18 20:23:36 +0000276 return chars, False
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000277 except UnicodeDecodeError:
278 pass
279 # Try utf-8:
280 try:
281 chars = str(bytes, 'utf-8')
282 self.fileencoding = 'utf-8'
Martin v. Löwis7e158452009-01-18 20:23:36 +0000283 return chars, False
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000284 except UnicodeDecodeError:
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000285 pass
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000286 # Finally, try the locale's encoding. This is deprecated;
287 # the user should declare a non-ASCII encoding
288 try:
Martin v. Löwis7e158452009-01-18 20:23:36 +0000289 # Wait for the editor window to appear
290 self.editwin.text.update()
291 enc = askstring(
292 "Specify file encoding",
293 "The file's encoding is invalid for Python 3.x.\n"
294 "IDLE will convert it to UTF-8.\n"
295 "What is the current encoding of the file?",
296 initialvalue = locale_encoding,
297 parent = self.editwin.text)
298
299 if enc:
300 chars = str(bytes, enc)
301 self.fileencoding = None
302 return chars, True
303 except (UnicodeDecodeError, LookupError):
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000304 pass
Martin v. Löwis7e158452009-01-18 20:23:36 +0000305 return None, False # None on failure
David Scherer7aced172000-08-15 01:13:23 +0000306
307 def maybesave(self):
308 if self.get_saved():
309 return "yes"
310 message = "Do you want to save %s before closing?" % (
311 self.filename or "this untitled document")
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400312 confirm = tkMessageBox.askyesnocancel(
313 title="Save On Close",
314 message=message,
315 default=tkMessageBox.YES,
316 master=self.text)
317 if confirm:
318 reply = "yes"
David Scherer7aced172000-08-15 01:13:23 +0000319 self.save(None)
320 if not self.get_saved():
321 reply = "cancel"
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400322 elif confirm is None:
323 reply = "cancel"
324 else:
325 reply = "no"
David Scherer7aced172000-08-15 01:13:23 +0000326 self.text.focus_set()
327 return reply
328
329 def save(self, event):
330 if not self.filename:
331 self.save_as(event)
332 else:
333 if self.writefile(self.filename):
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400334 self.set_saved(True)
Kurt B. Kaiserddeaf112003-03-04 04:42:04 +0000335 try:
336 self.editwin.store_file_breaks()
337 except AttributeError: # may be a PyShell
338 pass
David Scherer7aced172000-08-15 01:13:23 +0000339 self.text.focus_set()
340 return "break"
341
342 def save_as(self, event):
343 filename = self.asksavefile()
344 if filename:
345 if self.writefile(filename):
346 self.set_filename(filename)
347 self.set_saved(1)
Kurt B. Kaiserddeaf112003-03-04 04:42:04 +0000348 try:
349 self.editwin.store_file_breaks()
350 except AttributeError:
351 pass
David Scherer7aced172000-08-15 01:13:23 +0000352 self.text.focus_set()
Chui Tey993e81a2002-11-04 03:11:10 +0000353 self.updaterecentfileslist(filename)
David Scherer7aced172000-08-15 01:13:23 +0000354 return "break"
355
356 def save_a_copy(self, event):
357 filename = self.asksavefile()
358 if filename:
359 self.writefile(filename)
360 self.text.focus_set()
Chui Tey993e81a2002-11-04 03:11:10 +0000361 self.updaterecentfileslist(filename)
David Scherer7aced172000-08-15 01:13:23 +0000362 return "break"
363
364 def writefile(self, filename):
365 self.fixlastline()
Kurt B. Kaiser3e623ba2007-10-09 23:12:31 +0000366 text = self.text.get("1.0", "end-1c")
Guido van Rossumc2f77dd2003-04-25 18:36:31 +0000367 if self.eol_convention != "\n":
Kurt B. Kaiser3e623ba2007-10-09 23:12:31 +0000368 text = text.replace("\n", self.eol_convention)
Kurt B. Kaisercdadf242007-10-15 02:40:08 +0000369 chars = self.encode(text)
David Scherer7aced172000-08-15 01:13:23 +0000370 try:
Guido van Rossumc2f77dd2003-04-25 18:36:31 +0000371 f = open(filename, "wb")
David Scherer7aced172000-08-15 01:13:23 +0000372 f.write(chars)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000373 f.flush()
David Scherer7aced172000-08-15 01:13:23 +0000374 f.close()
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000375 return True
Guido van Rossumb940e112007-01-10 16:19:56 +0000376 except IOError as msg:
David Scherer7aced172000-08-15 01:13:23 +0000377 tkMessageBox.showerror("I/O Error", str(msg),
378 master=self.text)
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000379 return False
380
381 def encode(self, chars):
Martin v. Löwis4d9ed9f2007-08-13 13:30:04 +0000382 if isinstance(chars, bytes):
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000383 # This is either plain ASCII, or Tk was returning mixed-encoding
384 # text to us. Don't try to guess further.
385 return chars
Martin v. Löwis5216d082008-12-29 18:43:40 +0000386 # Preserve a BOM that might have been present on opening
387 if self.fileencoding == 'BOM':
388 return BOM_UTF8 + chars.encode("utf-8")
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000389 # See whether there is anything non-ASCII in it.
390 # If not, no need to figure out the encoding.
391 try:
392 return chars.encode('ascii')
393 except UnicodeError:
394 pass
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000395 # Check if there is an encoding declared
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000396 try:
Kurt B. Kaiser44fa8f62007-09-07 05:06:21 +0000397 # a string, let coding_spec slice it to the first two lines
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000398 enc = coding_spec(chars)
399 failed = None
Guido van Rossumb940e112007-01-10 16:19:56 +0000400 except LookupError as msg:
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000401 failed = msg
402 enc = None
Martin v. Löwis5216d082008-12-29 18:43:40 +0000403 else:
404 if not enc:
405 # PEP 3120: default source encoding is UTF-8
406 enc = 'utf-8'
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000407 if enc:
408 try:
409 return chars.encode(enc)
410 except UnicodeError:
411 failed = "Invalid encoding '%s'" % enc
Martin v. Löwis5216d082008-12-29 18:43:40 +0000412 tkMessageBox.showerror(
413 "I/O Error",
414 "%s.\nSaving as UTF-8" % failed,
415 master = self.text)
416 # Fallback: save as UTF-8, with BOM - ignoring the incorrect
417 # declared encoding
418 return BOM_UTF8 + chars.encode("utf-8")
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000419
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000420 def fixlastline(self):
421 c = self.text.get("end-2c")
422 if c != '\n':
423 self.text.insert("end-1c", "\n")
424
Steven M. Gava7981ce52002-06-11 04:45:34 +0000425 def print_window(self, event):
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400426 confirm = tkMessageBox.askokcancel(
427 title="Print",
428 message="Print to Default Printer",
429 default=tkMessageBox.OK,
430 master=self.text)
431 if not confirm:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000432 self.text.focus_set()
433 return "break"
Steven M. Gava7981ce52002-06-11 04:45:34 +0000434 tempfilename = None
Kurt B. Kaiser9067c8d2003-06-09 03:12:42 +0000435 saved = self.get_saved()
436 if saved:
Steven M. Gava7981ce52002-06-11 04:45:34 +0000437 filename = self.filename
Kurt B. Kaiser9067c8d2003-06-09 03:12:42 +0000438 # shell undo is reset after every prompt, looks saved, probably isn't
439 if not saved or filename is None:
Kurt B. Kaiser61e2c9a2003-06-14 17:56:25 +0000440 (tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_')
441 filename = tempfilename
442 os.close(tfd)
443 if not self.writefile(tempfilename):
Steven M. Gava7981ce52002-06-11 04:45:34 +0000444 os.unlink(tempfilename)
445 return "break"
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400446 platform = os.name
447 printPlatform = True
Steven M. Gava7981ce52002-06-11 04:45:34 +0000448 if platform == 'posix': #posix platform
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000449 command = idleConf.GetOption('main','General',
450 'print-command-posix')
Steven M. Gava7981ce52002-06-11 04:45:34 +0000451 command = command + " 2>&1"
452 elif platform == 'nt': #win32 platform
453 command = idleConf.GetOption('main','General','print-command-win')
454 else: #no printing for this platform
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400455 printPlatform = False
Steven M. Gava7981ce52002-06-11 04:45:34 +0000456 if printPlatform: #we can try to print for this platform
457 command = command % filename
458 pipe = os.popen(command, "r")
Kurt B. Kaiser9067c8d2003-06-09 03:12:42 +0000459 # things can get ugly on NT if there is no printer available.
Steven M. Gava7981ce52002-06-11 04:45:34 +0000460 output = pipe.read().strip()
461 status = pipe.close()
462 if status:
Kurt B. Kaiser01166da2002-09-16 22:03:37 +0000463 output = "Printing failed (exit status 0x%x)\n" % \
464 status + output
Steven M. Gava7981ce52002-06-11 04:45:34 +0000465 if output:
466 output = "Printing command: %s\n" % repr(command) + output
467 tkMessageBox.showerror("Print status", output, master=self.text)
468 else: #no printing for this platform
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400469 message = "Printing is not enabled for this platform: %s" % platform
Steven M. Gava7981ce52002-06-11 04:45:34 +0000470 tkMessageBox.showinfo("Print status", message, master=self.text)
Kurt B. Kaiser61e2c9a2003-06-14 17:56:25 +0000471 if tempfilename:
472 os.unlink(tempfilename)
Steven M. Gava7981ce52002-06-11 04:45:34 +0000473 return "break"
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000474
David Scherer7aced172000-08-15 01:13:23 +0000475 opendialog = None
476 savedialog = None
477
478 filetypes = [
Terry Reedy2b4cb962010-11-23 06:07:04 +0000479 ("Python files", "*.py *.pyw", "TEXT"),
480 ("Text files", "*.txt", "TEXT"),
David Scherer7aced172000-08-15 01:13:23 +0000481 ("All files", "*"),
482 ]
483
484 def askopenfile(self):
485 dir, base = self.defaultfilename("open")
486 if not self.opendialog:
487 self.opendialog = tkFileDialog.Open(master=self.text,
488 filetypes=self.filetypes)
Martin v. Löwis307021f2005-11-27 16:59:04 +0000489 filename = self.opendialog.show(initialdir=dir, initialfile=base)
Martin v. Löwis307021f2005-11-27 16:59:04 +0000490 return filename
David Scherer7aced172000-08-15 01:13:23 +0000491
492 def defaultfilename(self, mode="open"):
493 if self.filename:
494 return os.path.split(self.filename)
Kurt B. Kaiserd2f48612003-06-05 02:34:04 +0000495 elif self.dirname:
496 return self.dirname, ""
David Scherer7aced172000-08-15 01:13:23 +0000497 else:
498 try:
499 pwd = os.getcwd()
500 except os.error:
501 pwd = ""
502 return pwd, ""
503
504 def asksavefile(self):
505 dir, base = self.defaultfilename("save")
506 if not self.savedialog:
507 self.savedialog = tkFileDialog.SaveAs(master=self.text,
508 filetypes=self.filetypes)
Martin v. Löwis307021f2005-11-27 16:59:04 +0000509 filename = self.savedialog.show(initialdir=dir, initialfile=base)
Martin v. Löwis307021f2005-11-27 16:59:04 +0000510 return filename
David Scherer7aced172000-08-15 01:13:23 +0000511
Chui Tey993e81a2002-11-04 03:11:10 +0000512 def updaterecentfileslist(self,filename):
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000513 "Update recent file list on all editor windows"
Kurt B. Kaiser3a4e24b2007-08-22 18:06:14 +0000514 if self.editwin.flist:
515 self.editwin.update_recent_files_list(filename)
Chui Tey993e81a2002-11-04 03:11:10 +0000516
David Scherer7aced172000-08-15 01:13:23 +0000517def test():
David Scherer7aced172000-08-15 01:13:23 +0000518 root = Tk()
519 class MyEditWin:
520 def __init__(self, text):
521 self.text = text
522 self.flist = None
523 self.text.bind("<Control-o>", self.open)
524 self.text.bind("<Control-s>", self.save)
525 self.text.bind("<Alt-s>", self.save_as)
526 self.text.bind("<Alt-z>", self.save_a_copy)
527 def get_saved(self): return 0
528 def set_saved(self, flag): pass
529 def reset_undo(self): pass
530 def open(self, event):
531 self.text.event_generate("<<open-window-from-file>>")
532 def save(self, event):
533 self.text.event_generate("<<save-window>>")
534 def save_as(self, event):
535 self.text.event_generate("<<save-window-as-file>>")
536 def save_a_copy(self, event):
537 self.text.event_generate("<<save-copy-of-window-as-file>>")
538 text = Text(root)
539 text.pack()
540 text.focus_set()
541 editwin = MyEditWin(text)
542 io = IOBinding(editwin)
543 root.mainloop()
544
545if __name__ == "__main__":
David Scherer7aced172000-08-15 01:13:23 +0000546 test()