ZTWHHH commited on
Commit
0069dcf
·
verified ·
1 Parent(s): 353166a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava/lib/python3.10/idlelib/CREDITS.txt +47 -0
  2. llava/lib/python3.10/idlelib/HISTORY.txt +296 -0
  3. llava/lib/python3.10/idlelib/NEWS2x.txt +660 -0
  4. llava/lib/python3.10/idlelib/README.txt +290 -0
  5. llava/lib/python3.10/idlelib/__init__.py +10 -0
  6. llava/lib/python3.10/idlelib/autocomplete.py +228 -0
  7. llava/lib/python3.10/idlelib/autoexpand.py +96 -0
  8. llava/lib/python3.10/idlelib/config-highlight.def +105 -0
  9. llava/lib/python3.10/idlelib/config-keys.def +309 -0
  10. llava/lib/python3.10/idlelib/config-main.def +93 -0
  11. llava/lib/python3.10/idlelib/configdialog.py +0 -0
  12. llava/lib/python3.10/idlelib/dynoption.py +55 -0
  13. llava/lib/python3.10/idlelib/editor.py +1683 -0
  14. llava/lib/python3.10/idlelib/format.py +426 -0
  15. llava/lib/python3.10/idlelib/help.html +1178 -0
  16. llava/lib/python3.10/idlelib/help.py +294 -0
  17. llava/lib/python3.10/idlelib/percolator.py +118 -0
  18. llava/lib/python3.10/idlelib/query.py +392 -0
  19. llava/lib/python3.10/idlelib/replace.py +307 -0
  20. llava/lib/python3.10/idlelib/rpc.py +635 -0
  21. llava/lib/python3.10/idlelib/run.py +642 -0
  22. llava/lib/python3.10/idlelib/search.py +164 -0
  23. llava/lib/python3.10/idlelib/searchengine.py +234 -0
  24. llava/lib/python3.10/idlelib/stackviewer.py +155 -0
  25. llava/lib/python3.10/idlelib/textview.py +193 -0
  26. llava/lib/python3.10/idlelib/tooltip.py +186 -0
  27. llava/lib/python3.10/idlelib/window.py +98 -0
  28. llava/lib/python3.10/idlelib/zoomheight.py +124 -0
  29. llava/lib/python3.10/idlelib/zzdummy.py +73 -0
  30. llava/lib/python3.10/lib2to3/__pycache__/__init__.cpython-310.pyc +0 -0
  31. llava/lib/python3.10/lib2to3/__pycache__/__main__.cpython-310.pyc +0 -0
  32. llava/lib/python3.10/lib2to3/__pycache__/btm_matcher.cpython-310.pyc +0 -0
  33. llava/lib/python3.10/lib2to3/__pycache__/btm_utils.cpython-310.pyc +0 -0
  34. llava/lib/python3.10/lib2to3/__pycache__/fixer_base.cpython-310.pyc +0 -0
  35. llava/lib/python3.10/lib2to3/__pycache__/fixer_util.cpython-310.pyc +0 -0
  36. llava/lib/python3.10/lib2to3/__pycache__/main.cpython-310.pyc +0 -0
  37. llava/lib/python3.10/lib2to3/__pycache__/patcomp.cpython-310.pyc +0 -0
  38. llava/lib/python3.10/lib2to3/__pycache__/pygram.cpython-310.pyc +0 -0
  39. llava/lib/python3.10/lib2to3/__pycache__/pytree.cpython-310.pyc +0 -0
  40. llava/lib/python3.10/lib2to3/__pycache__/refactor.cpython-310.pyc +0 -0
  41. llava/lib/python3.10/lib2to3/pgen2/__init__.py +4 -0
  42. llava/lib/python3.10/lib2to3/pgen2/__pycache__/__init__.cpython-310.pyc +0 -0
  43. llava/lib/python3.10/lib2to3/pgen2/__pycache__/conv.cpython-310.pyc +0 -0
  44. llava/lib/python3.10/lib2to3/pgen2/__pycache__/driver.cpython-310.pyc +0 -0
  45. llava/lib/python3.10/lib2to3/pgen2/__pycache__/grammar.cpython-310.pyc +0 -0
  46. llava/lib/python3.10/lib2to3/pgen2/__pycache__/literals.cpython-310.pyc +0 -0
  47. llava/lib/python3.10/lib2to3/pgen2/__pycache__/parse.cpython-310.pyc +0 -0
  48. llava/lib/python3.10/lib2to3/pgen2/__pycache__/pgen.cpython-310.pyc +0 -0
  49. llava/lib/python3.10/lib2to3/pgen2/__pycache__/token.cpython-310.pyc +0 -0
  50. llava/lib/python3.10/lib2to3/pgen2/__pycache__/tokenize.cpython-310.pyc +0 -0
llava/lib/python3.10/idlelib/CREDITS.txt ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Guido van Rossum, as well as being the creator of the Python language, is the
2
+ original creator of IDLE. Other contributors prior to Version 0.8 include
3
+ Mark Hammond, Jeremy Hylton, Tim Peters, and Moshe Zadka.
4
+
5
+ Until Python 2.3, IDLE's development was carried out in the SF IDLEfork project. The
6
+ objective was to develop a version of IDLE which had an execution environment
7
+ which could be initialized prior to each run of user code.
8
+ IDLefork was merged into the Python code base in 2003.
9
+
10
+ The IDLEfork project was initiated by David Scherer, with some help from Peter
11
+ Schneider-Kamp and Nicholas Riley. David wrote the first version of the RPC
12
+ code and designed a fast turn-around environment for VPython. Guido developed
13
+ the RPC code and Remote Debugger currently integrated in IDLE. Bruce Sherwood
14
+ contributed considerable time testing and suggesting improvements.
15
+
16
+ Besides David and Guido, the main developers who were active on IDLEfork
17
+ are Stephen M. Gava, who implemented the configuration GUI, the new
18
+ configuration system, and the About dialog, and Kurt B. Kaiser, who completed
19
+ the integration of the RPC and remote debugger, implemented the threaded
20
+ subprocess, and made a number of usability enhancements.
21
+
22
+ Other contributors include Raymond Hettinger, Tony Lownds (Mac integration),
23
+ Neal Norwitz (code check and clean-up), Ronald Oussoren (Mac integration),
24
+ Noam Raphael (Code Context, Call Tips, many other patches), and Chui Tey (RPC
25
+ integration, debugger integration and persistent breakpoints).
26
+
27
+ Scott David Daniels, Tal Einat, Hernan Foffani, Christos Georgiou,
28
+ Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb,
29
+ Nigel Rowe, Bruce Sherwood, Jeff Shute, and Weeble have submitted useful
30
+ patches. Thanks, guys!
31
+
32
+ Major contributors since 2005:
33
+
34
+ - 2005: Tal Einat
35
+ - 2010: Terry Jan Reedy (current maintainer)
36
+ - 2013: Roger Serwys
37
+ - 2014: Saimadhav Heblikar
38
+ - 2015: Mark Roseman
39
+ - 2017: Louie Lu, Cheryl Sabella, and Serhiy Storchaka
40
+
41
+ For additional details refer to NEWS.txt and Changelog.
42
+
43
+ Please contact the IDLE maintainer (kbk@shore.net) to have yourself included
44
+ here if you are one of those we missed!
45
+
46
+
47
+
llava/lib/python3.10/idlelib/HISTORY.txt ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ IDLE History
2
+ ============
3
+
4
+ This file contains the release messages for previous IDLE releases.
5
+ As you read on you go back to the dark ages of IDLE's history.
6
+
7
+
8
+ What's New in IDLEfork 0.8.1?
9
+ =============================
10
+
11
+ *Release date: 22-Jul-2001*
12
+
13
+ - New tarball released as a result of the 'revitalisation' of the IDLEfork
14
+ project.
15
+
16
+ - This release requires python 2.1 or better. Compatibility with earlier
17
+ versions of python (especially ancient ones like 1.5x) is no longer a
18
+ priority in IDLEfork development.
19
+
20
+ - This release is based on a merging of the earlier IDLE fork work with current
21
+ cvs IDLE (post IDLE version 0.8), with some minor additional coding by Kurt
22
+ B. Kaiser and Stephen M. Gava.
23
+
24
+ - This release is basically functional but also contains some known breakages,
25
+ particularly with running things from the shell window. Also the debugger is
26
+ not working, but I believe this was the case with the previous IDLE fork
27
+ release (0.7.1) as well.
28
+
29
+ - This release is being made now to mark the point at which IDLEfork is
30
+ launching into a new stage of development.
31
+
32
+ - IDLEfork CVS will now be branched to enable further development and
33
+ exploration of the two "execution in a remote process" patches submitted by
34
+ David Scherer (David's is currently in IDLEfork) and GvR, while stabilisation
35
+ and development of less heavyweight improvements (like user customisation)
36
+ can continue on the trunk.
37
+
38
+
39
+ What's New in IDLEfork 0.7.1?
40
+ ==============================
41
+
42
+ *Release date: 15-Aug-2000*
43
+
44
+ - First project tarball released.
45
+
46
+ - This was the first release of IDLE fork, which at this stage was a
47
+ combination of IDLE 0.5 and the VPython idle fork, with additional changes
48
+ coded by David Scherer, Peter Schneider-Kamp and Nicholas Riley.
49
+
50
+
51
+
52
+ IDLEfork 0.7.1 - 29 May 2000
53
+ -----------------------------
54
+
55
+ David Scherer <dscherer@cmu.edu>
56
+
57
+ - This is a modification of the CVS version of IDLE 0.5, updated as of
58
+ 2000-03-09. It is alpha software and might be unstable. If it breaks, you
59
+ get to keep both pieces.
60
+
61
+ - If you have problems or suggestions, you should either contact me or post to
62
+ the list at http://www.python.org/mailman/listinfo/idle-dev (making it clear
63
+ that you are using this modified version of IDLE).
64
+
65
+ - Changes:
66
+
67
+ - The ExecBinding module, a replacement for ScriptBinding, executes programs
68
+ in a separate process, piping standard I/O through an RPC mechanism to an
69
+ OnDemandOutputWindow in IDLE. It supports executing unnamed programs
70
+ (through a temporary file). It does not yet support debugging.
71
+
72
+ - When running programs with ExecBinding, tracebacks will be clipped to
73
+ exclude system modules. If, however, a system module calls back into the
74
+ user program, that part of the traceback will be shown.
75
+
76
+ - The OnDemandOutputWindow class has been improved. In particular, it now
77
+ supports a readline() function used to implement user input, and a
78
+ scroll_clear() operation which is used to hide the output of a previous run
79
+ by scrolling it out of the window.
80
+
81
+ - Startup behavior has been changed. By default IDLE starts up with just a
82
+ blank editor window, rather than an interactive window. Opening a file in
83
+ such a blank window replaces the (nonexistent) contents of that window
84
+ instead of creating another window. Because of the need to have a
85
+ well-known port for the ExecBinding protocol, only one copy of IDLE can be
86
+ running. Additional invocations use the RPC mechanism to report their
87
+ command line arguments to the copy already running.
88
+
89
+ - The menus have been reorganized. In particular, the excessively large
90
+ 'edit' menu has been split up into 'edit', 'format', and 'run'.
91
+
92
+ - 'Python Documentation' now works on Windows, if the win32api module is
93
+ present.
94
+
95
+ - A few key bindings have been changed: F1 now loads Python Documentation
96
+ instead of the IDLE help; shift-TAB is now a synonym for unindent.
97
+
98
+ - New modules:
99
+
100
+ ExecBinding.py Executes program through loader
101
+ loader.py Bootstraps user program
102
+ protocol.py RPC protocol
103
+ Remote.py User-process interpreter
104
+ spawn.py OS-specific code to start programs
105
+
106
+ - Files modified:
107
+
108
+ autoindent.py ( bindings tweaked )
109
+ bindings.py ( menus reorganized )
110
+ config.txt ( execbinding enabled )
111
+ editorwindow.py ( new menus, fixed 'Python Documentation' )
112
+ filelist.py ( hook for "open in same window" )
113
+ formatparagraph.py ( bindings tweaked )
114
+ idle.bat ( removed absolute pathname )
115
+ idle.pyw ( weird bug due to import with same name? )
116
+ iobinding.py ( open in same window, EOL convention )
117
+ keydefs.py ( bindings tweaked )
118
+ outputwindow.py ( readline, scroll_clear, etc )
119
+ pyshell.py ( changed startup behavior )
120
+ readme.txt ( <Recursion on file with id=1234567> )
121
+
122
+
123
+
124
+ IDLE 0.5 - February 2000 - Release Notes
125
+ ----------------------------------------
126
+
127
+ This is an early release of IDLE, my own attempt at a Tkinter-based
128
+ IDE for Python.
129
+
130
+ (For a more detailed change log, see the file ChangeLog.)
131
+
132
+ FEATURES
133
+
134
+ IDLE has the following features:
135
+
136
+ - coded in 100% pure Python, using the Tkinter GUI toolkit (i.e. Tcl/Tk)
137
+
138
+ - cross-platform: works on Windows and Unix (on the Mac, there are
139
+ currently problems with Tcl/Tk)
140
+
141
+ - multi-window text editor with multiple undo, Python colorizing
142
+ and many other features, e.g. smart indent and call tips
143
+
144
+ - Python shell window (a.k.a. interactive interpreter)
145
+
146
+ - debugger (not complete, but you can set breakpoints, view and step)
147
+
148
+ USAGE
149
+
150
+ The main program is in the file "idle.py"; on Unix, you should be able
151
+ to run it by typing "./idle.py" to your shell. On Windows, you can
152
+ run it by double-clicking it; you can use idle.pyw to avoid popping up
153
+ a DOS console. If you want to pass command line arguments on Windows,
154
+ use the batch file idle.bat.
155
+
156
+ Command line arguments: files passed on the command line are executed,
157
+ not opened for editing, unless you give the -e command line option.
158
+ Try "./idle.py -h" to see other command line options.
159
+
160
+ IDLE requires Python 1.5.2, so it is currently only usable with a
161
+ Python 1.5.2 distribution. (An older version of IDLE is distributed
162
+ with Python 1.5.2; you can drop this version on top of it.)
163
+
164
+ COPYRIGHT
165
+
166
+ IDLE is covered by the standard Python copyright notice
167
+ (http://www.python.org/doc/Copyright.html).
168
+
169
+
170
+ New in IDLE 0.5 (2/15/2000)
171
+ ---------------------------
172
+
173
+ Tons of stuff, much of it contributed by Tim Peters and Mark Hammond:
174
+
175
+ - Status bar, displaying current line/column (Moshe Zadka).
176
+
177
+ - Better stack viewer, using tree widget. (XXX Only used by Stack
178
+ Viewer menu, not by the debugger.)
179
+
180
+ - Format paragraph now recognizes Python block comments and reformats
181
+ them correctly (MH)
182
+
183
+ - New version of pyclbr.py parses top-level functions and understands
184
+ much more of Python's syntax; this is reflected in the class and path
185
+ browsers (TP)
186
+
187
+ - Much better auto-indent; knows how to indent the insides of
188
+ multi-line statements (TP)
189
+
190
+ - Call tip window pops up when you type the name of a known function
191
+ followed by an open parenthesis. Hit ESC or click elsewhere in the
192
+ window to close the tip window (MH)
193
+
194
+ - Comment out region now inserts ## to make it stand out more (TP)
195
+
196
+ - New path and class browsers based on a tree widget that looks
197
+ familiar to Windows users
198
+
199
+ - Reworked script running commands to be more intuitive: I/O now
200
+ always goes to the *Python Shell* window, and raw_input() works
201
+ correctly. You use F5 to import/reload a module: this adds the module
202
+ name to the __main__ namespace. You use Control-F5 to run a script:
203
+ this runs the script *in* the __main__ namespace. The latter also
204
+ sets sys.argv[] to the script name
205
+
206
+
207
+ New in IDLE 0.4 (4/7/99)
208
+ ------------------------
209
+
210
+ Most important change: a new menu entry "File -> Path browser", shows
211
+ a 4-column hierarchical browser which lets you browse sys.path,
212
+ directories, modules, and classes. Yes, it's a superset of the Class
213
+ browser menu entry. There's also a new internal module,
214
+ MultiScrolledLists.py, which provides the framework for this dialog.
215
+
216
+
217
+ New in IDLE 0.3 (2/17/99)
218
+ -------------------------
219
+
220
+ Most important changes:
221
+
222
+ - Enabled support for running a module, with or without the debugger.
223
+ Output goes to a new window. Pressing F5 in a module is effectively a
224
+ reload of that module; Control-F5 loads it under the debugger.
225
+
226
+ - Re-enable tearing off the Windows menu, and make a torn-off Windows
227
+ menu update itself whenever a window is opened or closed.
228
+
229
+ - Menu items can now be have a checkbox (when the menu label starts
230
+ with "!"); use this for the Debugger and "Auto-open stack viewer"
231
+ (was: JIT stack viewer) menu items.
232
+
233
+ - Added a Quit button to the Debugger API.
234
+
235
+ - The current directory is explicitly inserted into sys.path.
236
+
237
+ - Fix the debugger (when using Python 1.5.2b2) to use canonical
238
+ filenames for breakpoints, so these actually work. (There's still a
239
+ lot of work to be done to the management of breakpoints in the
240
+ debugger though.)
241
+
242
+ - Closing a window that is still colorizing now actually works.
243
+
244
+ - Allow dragging of the separator between the two list boxes in the
245
+ class browser.
246
+
247
+ - Bind ESC to "close window" of the debugger, stack viewer and class
248
+ browser. It removes the selection highlighting in regular text
249
+ windows. (These are standard Windows conventions.)
250
+
251
+
252
+ New in IDLE 0.2 (1/8/99)
253
+ ------------------------
254
+
255
+ Lots of changes; here are the highlights:
256
+
257
+ General:
258
+
259
+ - You can now write and configure your own IDLE extension modules; see
260
+ extend.txt.
261
+
262
+
263
+ File menu:
264
+
265
+ The command to open the Python shell window is now in the File menu.
266
+
267
+
268
+ Edit menu:
269
+
270
+ New Find dialog with more options; replace dialog; find in files dialog.
271
+
272
+ Commands to tabify or untabify a region.
273
+
274
+ Command to format a paragraph.
275
+
276
+
277
+ Debug menu:
278
+
279
+ JIT (Just-In-Time) stack viewer toggle -- if set, the stack viewer
280
+ automaticall pops up when you get a traceback.
281
+
282
+ Windows menu:
283
+
284
+ Zoom height -- make the window full height.
285
+
286
+
287
+ Help menu:
288
+
289
+ The help text now show up in a regular window so you can search and
290
+ even edit it if you like.
291
+
292
+
293
+
294
+ IDLE 0.1 was distributed with the Python 1.5.2b1 release on 12/22/98.
295
+
296
+ ======================================================================
llava/lib/python3.10/idlelib/NEWS2x.txt ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ What's New in IDLE 2.7? (Merged into 3.1 before 2.7 release.)
2
+ =======================
3
+ *Release date: XX-XXX-2010*
4
+
5
+ - idle.py modified and simplified to better support developing experimental
6
+ versions of IDLE which are not installed in the standard location.
7
+
8
+ - OutputWindow/PyShell right click menu "Go to file/line" wasn't working with
9
+ file paths containing spaces. Bug 5559.
10
+
11
+ - Windows: Version string for the .chm help file changed, file not being
12
+ accessed Patch 5783 Guilherme Polo
13
+
14
+ - Allow multiple IDLE GUI/subprocess pairs to exist simultaneously. Thanks to
15
+ David Scherer for suggesting the use of an ephemeral port for the GUI.
16
+ Patch 1529142 Weeble.
17
+
18
+ - Remove port spec from run.py and fix bug where subprocess fails to
19
+ extract port from command line when warnings are present.
20
+
21
+ - Tk 8.5 Text widget requires 'wordprocessor' tabstyle attr to handle
22
+ mixed space/tab properly. Issue 5129, patch by Guilherme Polo.
23
+
24
+ - Issue #3549: On MacOS the preferences menu was not present
25
+
26
+ - IDLE would print a "Unhandled server exception!" message when internal
27
+ debugging is enabled.
28
+
29
+ - Issue #4455: IDLE failed to display the windows list when two windows have
30
+ the same title.
31
+
32
+ - Issue #4383: When IDLE cannot make the connection to its subprocess, it would
33
+ fail to properly display the error message.
34
+
35
+ - help() was not paging to the shell. Issue1650.
36
+
37
+ - CodeContext was not importing.
38
+
39
+ - Corrected two 3.0 compatibility errors reported by Mark Summerfield:
40
+ http://mail.python.org/pipermail/python-3000/2007-December/011491.html
41
+
42
+ - Shell was not colorizing due to bug introduced at r57998, Bug 1586.
43
+
44
+ - Issue #1585: IDLE uses non-existent xrange() function.
45
+
46
+ - Windows EOL sequence not converted correctly, encoding error.
47
+ Caused file save to fail. Bug 1130.
48
+
49
+ - IDLE converted to Python 3000 syntax.
50
+
51
+ - Strings became Unicode.
52
+
53
+ - CallTips module now uses the inspect module to produce the argspec.
54
+
55
+ - IDLE modules now use absolute import instead of implied relative import.
56
+
57
+ - atexit call replaces sys.exitfunc. The functionality of delete-exitfunc flag
58
+ in config-main.cfg remains unchanged: if set, registered exit functions will
59
+ be cleared before IDLE exits.
60
+
61
+
62
+ What's New in IDLE 2.6
63
+ ======================
64
+ *Release date: 01-Oct-2008*, merged into 3.0 releases detailed above (3.0rc2)
65
+
66
+ - Issue #2665: On Windows, an IDLE installation upgraded from an old version
67
+ would not start if a custom theme was defined.
68
+
69
+ - Home / Control-A toggles between left margin and end of leading white
70
+ space. issue1196903, patch by Jeff Shute.
71
+
72
+ - Improved AutoCompleteWindow logic. issue2062, patch by Tal Einat.
73
+
74
+ - Autocompletion of filenames now support alternate separators, e.g. the
75
+ '/' char on Windows. issue2061 Patch by Tal Einat.
76
+
77
+ - Configured selection highlighting colors were ignored; updating highlighting
78
+ in the config dialog would cause non-Python files to be colored as if they
79
+ were Python source; improve use of ColorDelagator. Patch 1334. Tal Einat.
80
+
81
+ - ScriptBinding event handlers weren't returning 'break'. Patch 2050, Tal Einat
82
+
83
+ - There was an error on exit if no sys.exitfunc was defined. Issue 1647.
84
+
85
+ - Could not open files in .idlerc directory if latter was hidden on Windows.
86
+ Issue 1743, Issue 1862.
87
+
88
+ - Configure Dialog: improved layout for keybinding. Patch 1457 Tal Einat.
89
+
90
+ - tabpage.py updated: tabbedPages.py now supports multiple dynamic rows
91
+ of tabs. Patch 1612746 Tal Einat.
92
+
93
+ - Add confirmation dialog before printing. Patch 1717170 Tal Einat.
94
+
95
+ - Show paste position if > 80 col. Patch 1659326 Tal Einat.
96
+
97
+ - Update cursor color without restarting. Patch 1725576 Tal Einat.
98
+
99
+ - Allow keyboard interrupt only when user code is executing in subprocess.
100
+ Patch 1225 Tal Einat (reworked from IDLE-Spoon).
101
+
102
+ - configDialog cleanup. Patch 1730217 Tal Einat.
103
+
104
+ - textView cleanup. Patch 1718043 Tal Einat.
105
+
106
+ - Clean up EditorWindow close.
107
+
108
+ - Patch 1693258: Fix for duplicate "preferences" menu-OS X. Backport of r56204.
109
+
110
+ - OSX: Avoid crash for those versions of Tcl/Tk which don't have a console
111
+
112
+ - Bug in idlelib.MultiCall: Options dialog was crashing IDLE if there was an
113
+ option in config-extensions w/o a value. Patch #1672481, Tal Einat
114
+
115
+ - Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented;
116
+ mouse and cursor selection in ACWindow implemented; double Tab inserts
117
+ current selection and closes ACW (similar to double-click and Return); scroll
118
+ wheel now works in ACW. Added AutoComplete instructions to IDLE Help.
119
+
120
+ - AutoCompleteWindow moved below input line, will move above if there
121
+ isn't enough space. Patch 1621265 Tal Einat
122
+
123
+ - Calltips now 'handle' tuples in the argument list (display '<tuple>' :)
124
+ Suggested solution by Christos Georgiou, Bug 791968.
125
+
126
+ - Add 'raw' support to configHandler. Patch 1650174 Tal Einat.
127
+
128
+ - Avoid hang when encountering a duplicate in a completion list. Bug 1571112.
129
+
130
+ - Patch #1362975: Rework CodeContext indentation algorithm to
131
+ avoid hard-coding pixel widths.
132
+
133
+ - Bug #813342: Start the IDLE subprocess with -Qnew if the parent
134
+ is started with that option.
135
+
136
+ - Honor the "Cancel" action in the save dialog (Debian bug #299092)
137
+
138
+ - Some syntax errors were being caught by tokenize during the tabnanny
139
+ check, resulting in obscure error messages. Do the syntax check
140
+ first. Bug 1562716, 1562719
141
+
142
+ - IDLE's version number takes a big jump to match the version number of
143
+ the Python release of which it's a part.
144
+
145
+
146
+ What's New in IDLE 1.2?
147
+ =======================
148
+ *Release date: 19-SEP-2006*
149
+
150
+ - File menu hotkeys: there were three 'p' assignments. Reassign the
151
+ 'Save Copy As' and 'Print' hotkeys to 'y' and 't'. Change the
152
+ Shell hotkey from 's' to 'l'.
153
+
154
+ - IDLE honors new quit() and exit() commands from site.py Quitter() object.
155
+ Patch 1540892, Jim Jewett
156
+
157
+ - The 'with' statement is now a Code Context block opener.
158
+ Patch 1540851, Jim Jewett
159
+
160
+ - Retrieval of previous shell command was not always preserving indentation
161
+ (since 1.2a1) Patch 1528468 Tal Einat.
162
+
163
+ - Changing tokenize (39046) to detect dedent broke tabnanny check (since 1.2a1)
164
+
165
+ - ToggleTab dialog was setting indent to 8 even if cancelled (since 1.2a1).
166
+
167
+ - When used w/o subprocess, all exceptions were preceded by an error
168
+ message claiming they were IDLE internal errors (since 1.2a1).
169
+
170
+ - Bug #1525817: Don't truncate short lines in IDLE's tool tips.
171
+
172
+ - Bug #1517990: IDLE keybindings on MacOS X now work correctly
173
+
174
+ - Bug #1517996: IDLE now longer shows the default Tk menu when a
175
+ path browser, class browser or debugger is the frontmost window on MacOS X
176
+
177
+ - EditorWindow.test() was failing. Bug 1417598
178
+
179
+ - EditorWindow failed when used stand-alone if sys.ps1 not set.
180
+ Bug 1010370 Dave Florek
181
+
182
+ - Tooltips failed on new-syle class __init__ args. Bug 1027566 Loren Guthrie
183
+
184
+ - Avoid occasional failure to detect closing paren properly.
185
+ Patch 1407280 Tal Einat
186
+
187
+ - Rebinding Tab key was inserting 'tab' instead of 'Tab'. Bug 1179168.
188
+
189
+ - Colorizer now handles #<builtin> correctly, also unicode strings and
190
+ 'as' keyword in comment directly following import command. Closes 1325071.
191
+ Patch 1479219 Tal Einat
192
+
193
+ - Patch #1162825: Support non-ASCII characters in IDLE window titles.
194
+
195
+ - Source file f.flush() after writing; trying to avoid lossage if user
196
+ kills GUI.
197
+
198
+ - Options / Keys / Advanced dialog made functional. Also, allow binding
199
+ of 'movement' keys.
200
+
201
+ - 'syntax' patch adds improved calltips and a new class attribute listbox.
202
+ MultiCall module allows binding multiple actions to an event.
203
+ Patch 906702 Noam Raphael
204
+
205
+ - Better indentation after first line of string continuation.
206
+ IDLEfork Patch 681992, Noam Raphael
207
+
208
+ - Fixed CodeContext alignment problem, following suggestion from Tal Einat.
209
+
210
+ - Increased performance in CodeContext extension Patch 936169 Noam Raphael
211
+
212
+ - Mac line endings were incorrect when pasting code from some browsers
213
+ when using X11 and the Fink distribution. Python Bug 1263656.
214
+
215
+ - <Enter> when cursor is on a previous command retrieves that command. Instead
216
+ of replacing the input line, the previous command is now appended to the
217
+ input line. Indentation is preserved, and undo is enabled.
218
+ Patch 1196917 Jeff Shute
219
+
220
+ - Clarify "tab/space" Error Dialog and "Tab Width" Dialog associated with
221
+ the Untabify command.
222
+
223
+ - Corrected "tab/space" Error Dialog to show correct menu for Untabify.
224
+ Patch 1196980 Jeff Shute
225
+
226
+ - New files are colorized by default, and colorizing is removed when
227
+ saving as non-Python files. Patch 1196895 Jeff Shute
228
+ Closes Python Bugs 775012 and 800432, partial fix IDLEfork 763524
229
+
230
+ - Improve subprocess link error notification.
231
+
232
+ - run.py: use Queue's blocking feature instead of sleeping in the main
233
+ loop. Patch # 1190163 Michiel de Hoon
234
+
235
+ - Add config-main option to make the 'history' feature non-cyclic.
236
+ Default remains cyclic. Python Patch 914546 Noam Raphael.
237
+
238
+ - Removed ability to configure tabs indent from Options dialog. This 'feature'
239
+ has never worked and no one has complained. It is still possible to set a
240
+ default tabs (v. spaces) indent 'manually' via config-main.def (or to turn on
241
+ tabs for the current EditorWindow via the Format menu) but IDLE will
242
+ encourage indentation via spaces.
243
+
244
+ - Enable setting the indentation width using the Options dialog.
245
+ Bug # 783877
246
+
247
+ - Add keybindings for del-word-left and del-word-right.
248
+
249
+ - Discourage using an indent width other than 8 when using tabs to indent
250
+ Python code.
251
+
252
+ - Restore use of EditorWindow.set_indentation_params(), was dead code since
253
+ Autoindent was merged into EditorWindow. This allows IDLE to conform to the
254
+ indentation width of a loaded file. (But it still will not switch to tabs
255
+ even if the file uses tabs.) Any change in indent width is local to that
256
+ window.
257
+
258
+ - Add Tabnanny check before Run/F5, not just when Checking module.
259
+
260
+ - If an extension can't be loaded, print warning and skip it instead of
261
+ erroring out.
262
+
263
+ - Improve error handling when .idlerc can't be created (warn and exit).
264
+
265
+ - The GUI was hanging if the shell window was closed while a raw_input()
266
+ was pending. Restored the quit() of the readline() mainloop().
267
+ http://mail.python.org/pipermail/idle-dev/2004-December/002307.html
268
+
269
+ - The remote procedure call module rpc.py can now access data attributes of
270
+ remote registered objects. Changes to these attributes are local, however.
271
+
272
+
273
+ What's New in IDLE 1.1?
274
+ =======================
275
+ *Release date: 30-NOV-2004*
276
+
277
+ - On OpenBSD, terminating IDLE with ctrl-c from the command line caused a
278
+ stuck subprocess MainThread because only the SocketThread was exiting.
279
+
280
+ - Saving a Keyset w/o making changes (by using the "Save as New Custom Key Set"
281
+ button) caused IDLE to fail on restart (no new keyset was created in
282
+ config-keys.cfg). Also true for Theme/highlights. Python Bug 1064535.
283
+
284
+ - A change to the linecache.py API caused IDLE to exit when an exception was
285
+ raised while running without the subprocess (-n switch). Python Bug 1063840.
286
+
287
+ - When paragraph reformat width was made configurable, a bug was
288
+ introduced that caused reformatting of comment blocks to ignore how
289
+ far the block was indented, effectively adding the indentation width
290
+ to the reformat width. This has been repaired, and the reformat
291
+ width is again a bound on the total width of reformatted lines.
292
+
293
+ - Improve keyboard focus binding, especially in Windows menu. Improve
294
+ window raising, especially in the Windows menu and in the debugger.
295
+ IDLEfork 763524.
296
+
297
+ - If user passes a non-existent filename on the commandline, just
298
+ open a new file, don't raise a dialog. IDLEfork 854928.
299
+
300
+ - EditorWindow.py was not finding the .chm help file on Windows. Typo
301
+ at Rev 1.54. Python Bug 990954
302
+
303
+ - checking sys.platform for substring 'win' was breaking IDLE docs on Mac
304
+ (darwin). Also, Mac Safari browser requires full file:// URIs. SF 900580.
305
+
306
+ - Redirect the warning stream to the shell during the ScriptBinding check of
307
+ user code and format the warning similarly to an exception for both that
308
+ check and for runtime warnings raised in the subprocess.
309
+
310
+ - CodeContext hint pane visibility state is now persistent across sessions.
311
+ The pane no longer appears in the shell window. Added capability to limit
312
+ extensions to shell window or editor windows. Noam Raphael addition
313
+ to Patch 936169.
314
+
315
+ - Paragraph reformat width is now a configurable parameter in the
316
+ Options GUI.
317
+
318
+ - New Extension: CodeContext. Provides block structuring hints for code
319
+ which has scrolled above an edit window. Patch 936169 Noam Raphael.
320
+
321
+ - If nulls somehow got into the strings in recent-files.lst
322
+ EditorWindow.update_recent_files_list() was failing. Python Bug 931336.
323
+
324
+ - If the normal background is changed via Configure/Highlighting, it will
325
+ update immediately, thanks to the previously mentioned patch by Nigel Rowe.
326
+
327
+ - Add a highlight theme for builtin keywords. Python Patch 805830 Nigel Rowe
328
+ This also fixed IDLEfork bug [ 693418 ] Normal text background color not
329
+ refreshed and Python bug [897872 ] Unknown color name on HP-UX
330
+
331
+ - rpc.py:SocketIO - Large modules were generating large pickles when downloaded
332
+ to the execution server. The return of the OK response from the subprocess
333
+ initialization was interfering and causing the sending socket to be not
334
+ ready. Add an IO ready test to fix this. Moved the polling IO ready test
335
+ into pollpacket().
336
+
337
+ - Fix typo in rpc.py, s/b "pickle.PicklingError" not "pickle.UnpicklingError".
338
+
339
+ - Added a Tk error dialog to run.py inform the user if the subprocess can't
340
+ connect to the user GUI process. Added a timeout to the GUI's listening
341
+ socket. Added Tk error dialogs to PyShell.py to announce a failure to bind
342
+ the port or connect to the subprocess. Clean up error handling during
343
+ connection initiation phase. This is an update of Python Patch 778323.
344
+
345
+ - Print correct exception even if source file changed since shell was
346
+ restarted. IDLEfork Patch 869012 Noam Raphael
347
+
348
+ - Keybindings with the Shift modifier now work correctly. So do bindings which
349
+ use the Space key. Limit unmodified user keybindings to the function keys.
350
+ Python Bug 775353, IDLEfork Bugs 755647, 761557
351
+
352
+ - After an exception, run.py was not setting the exception vector. Noam
353
+ Raphael suggested correcting this so pdb's postmortem pm() would work.
354
+ IDLEfork Patch 844675
355
+
356
+ - IDLE now does not fail to save the file anymore if the Tk buffer is not a
357
+ Unicode string, yet eol_convention is. Python Bugs 774680, 788378
358
+
359
+ - IDLE didn't start correctly when Python was installed in "Program Files" on
360
+ W2K and XP. Python Bugs 780451, 784183
361
+
362
+ - config-main.def documentation incorrectly referred to idle- instead of
363
+ config- filenames. SF 782759 Also added note about .idlerc location.
364
+
365
+
366
+ What's New in IDLE 1.0?
367
+ =======================
368
+ *Release date: 29-Jul-2003*
369
+
370
+ - Added a banner to the shell discussing warnings possibly raised by personal
371
+ firewall software. Added same comment to README.txt.
372
+
373
+ - Calltip error when docstring was None Python Bug 775541
374
+
375
+ - Updated extend.txt, help.txt, and config-extensions.def to correctly
376
+ reflect the current status of the configuration system. Python Bug 768469
377
+
378
+ - Fixed: Call Tip Trimming May Loop Forever. Python Patch 769142 (Daniels)
379
+
380
+ - Replaced apply(f, args, kwds) with f(*args, **kwargs) to improve performance
381
+ Python Patch 768187
382
+
383
+ - Break or continue statements outside a loop were causing IDLE crash
384
+ Python Bug 767794
385
+
386
+ - Convert Unicode strings from readline to IOBinding.encoding. Also set
387
+ sys.std{in|out|err}.encoding, for both the local and the subprocess case.
388
+ SF IDLEfork patch 682347.
389
+
390
+ - Extend AboutDialog.ViewFile() to support file encodings. Make the CREDITS
391
+ file Latin-1.
392
+
393
+ - Updated the About dialog to reflect re-integration into Python. Provide
394
+ buttons to display Python's NEWS, License, and Credits, plus additional
395
+ buttons for IDLE's README and NEWS.
396
+
397
+ - TextViewer() now has a third parameter which allows inserting text into the
398
+ viewer instead of reading from a file.
399
+
400
+ - (Created the .../Lib/idlelib directory in the Python CVS, which is a clone of
401
+ IDLEfork modified to install in the Python environment. The code in the
402
+ interrupt module has been moved to thread.interrupt_main(). )
403
+
404
+ - Printing the Shell window was failing if it was not saved first SF 748975
405
+
406
+ - When using the Search in Files dialog, if the user had a selection
407
+ highlighted in his Editor window, insert it into the dialog search field.
408
+
409
+ - The Python Shell entry was disappearing from the Windows menu.
410
+
411
+ - Update the Windows file list when a file name change occurs
412
+
413
+ - Change to File / Open Module: always pop up the dialog, using the current
414
+ selection as the default value. This is easier to use habitually.
415
+
416
+ - Avoided a problem with starting the subprocess when 'localhost' doesn't
417
+ resolve to the user's loopback interface. SF 747772
418
+
419
+ - Fixed an issue with highlighted errors never de-colorizing. SF 747677. Also
420
+ improved notification of Tabnanny Token Error.
421
+
422
+ - File / New will by default save in the directory of the Edit window from
423
+ which it was initiated. SF 748973 Guido van Rossum patch.
424
+
425
+
426
+ What's New in IDLEfork 0.9b1?
427
+ =============================
428
+ *Release date: 02-Jun-2003*
429
+
430
+ - The current working directory of the execution environment (and shell
431
+ following completion of execution) is now that of the module being run.
432
+
433
+ - Added the delete-exitfunc option to config-main.def. (This option is not
434
+ included in the Options dialog.) Setting this to True (the default) will
435
+ cause IDLE to not run sys.exitfunc/atexit when the subprocess exits.
436
+
437
+ - IDLE now preserves the line ending codes when editing a file produced on
438
+ a different platform. SF 661759, SF 538584
439
+
440
+ - Reduced default editor font size to 10 point and increased window height
441
+ to provide a better initial impression on Windows.
442
+
443
+ - Options / Fonts/Tabs / Set Base Editor Font: List box was not highlighting
444
+ the default font when first installed on Windows. SF 661676
445
+
446
+ - Added Autosave feature: when user runs code from edit window, if the file
447
+ has been modified IDLE will silently save it if Autosave is enabled. The
448
+ option is set in the Options dialog, and the default is to prompt the
449
+ user to save the file. SF 661318 Bruce Sherwood patch.
450
+
451
+ - Improved the RESTART annotation in the shell window when the user restarts
452
+ the shell while it is generating output. Also improved annotation when user
453
+ repeatedly hammers the Ctrl-F6 restart.
454
+
455
+ - Allow IDLE to run when not installed and cwd is not the IDLE directory
456
+ SF Patch 686254 "Run IDLEfork from any directory without set-up" - Raphael
457
+
458
+ - When a module is run from an EditorWindow: if its directory is not in
459
+ sys.path, prepend it. This allows the module to import other modules in
460
+ the same directory. Do the same for a script run from the command line.
461
+
462
+ - Correctly restart the subprocess if it is running user code and the user
463
+ attempts to run some other module or restarts the shell. Do the same if
464
+ the link is broken and it is possible to restart the subprocess and re-
465
+ connect to the GUI. SF RFE 661321.
466
+
467
+ - Improved exception reporting when running commands or scripts from the
468
+ command line.
469
+
470
+ - Added a -n command line switch to start IDLE without the subprocess.
471
+ Removed the Shell menu when running in that mode. Updated help messages.
472
+
473
+ - Added a comment to the shell startup header to indicate when IDLE is not
474
+ using the subprocess.
475
+
476
+ - Restore the ability to run without the subprocess. This can be important for
477
+ some platforms or configurations. (Running without the subprocess allows the
478
+ debugger to trace through parts of IDLE itself, which may or may not be
479
+ desirable, depending on your point of view. In addition, the traditional
480
+ reload/import tricks must be use if user source code is changed.) This is
481
+ helpful for developing IDLE using IDLE, because one instance can be used to
482
+ edit the code and a separate instance run to test changes. (Multiple
483
+ concurrent IDLE instances with subprocesses is a future feature)
484
+
485
+ - Improve the error message a user gets when saving a file with non-ASCII
486
+ characters and no source encoding is specified. Done by adding a dialog
487
+ 'EncodingMessage', which contains the line to add in a fixed-font entry
488
+ widget, and which has a button to add that line to the file automatically.
489
+ Also, add a configuration option 'EditorWindow/encoding', which has three
490
+ possible values: none, utf-8, and locale. None is the default: IDLE will show
491
+ this dialog when non-ASCII characters are encountered. utf-8 means that files
492
+ with non-ASCII characters are saved as utf-8-with-bom. locale means that
493
+ files are saved in the locale's encoding; the dialog is only displayed if the
494
+ source contains characters outside the locale's charset. SF 710733 - Loewis
495
+
496
+ - Improved I/O response by tweaking the wait parameter in various
497
+ calls to signal.signal().
498
+
499
+ - Implemented a threaded subprocess which allows interrupting a pass
500
+ loop in user code using the 'interrupt' extension. User code runs
501
+ in MainThread, while the RPCServer is handled by SockThread. This is
502
+ necessary because Windows doesn't support signals.
503
+
504
+ - Implemented the 'interrupt' extension module, which allows a subthread
505
+ to raise a KeyboardInterrupt in the main thread.
506
+
507
+ - Attempting to save the shell raised an error related to saving
508
+ breakpoints, which are not implemented in the shell
509
+
510
+ - Provide a correct message when 'exit' or 'quit' are entered at the
511
+ IDLE command prompt SF 695861
512
+
513
+ - Eliminate extra blank line in shell output caused by not flushing
514
+ stdout when user code ends with an unterminated print. SF 695861
515
+
516
+ - Moved responsibility for exception formatting (i.e. pruning IDLE internal
517
+ calls) out of rpc.py into the client and server.
518
+
519
+ - Exit IDLE cleanly even when doing subprocess I/O
520
+
521
+ - Handle subprocess interrupt with an RPC message.
522
+
523
+ - Restart the subprocess if it terminates itself. (VPython programs do that)
524
+
525
+ - Support subclassing of exceptions, including in the shell, by moving the
526
+ exception formatting to the subprocess.
527
+
528
+
529
+ What's New in IDLEfork 0.9 Alpha 2?
530
+ ===================================
531
+ *Release date: 27-Jan-2003*
532
+
533
+ - Updated INSTALL.txt to claify use of the python2 rpm.
534
+
535
+ - Improved formatting in IDLE Help.
536
+
537
+ - Run menu: Replace "Run Script" with "Run Module".
538
+
539
+ - Code encountering an unhandled exception under the debugger now shows
540
+ the correct traceback, with IDLE internal levels pruned out.
541
+
542
+ - If an exception occurs entirely in IDLE, don't prune the IDLE internal
543
+ modules from the traceback displayed.
544
+
545
+ - Class Browser and Path Browser now use Alt-Key-2 for vertical zoom.
546
+
547
+ - IDLE icons will now install correctly even when setup.py is run from the
548
+ build directory
549
+
550
+ - Class Browser now compatible with Python2.3 version of pyclbr.py
551
+
552
+ - Left cursor move in presence of selected text now moves from left end
553
+ of the selection.
554
+
555
+ - Add Meta keybindings to "IDLE Classic Windows" to handle reversed
556
+ Alt/Meta on some Linux distros.
557
+
558
+ - Change default: IDLE now starts with Python Shell.
559
+
560
+ - Removed the File Path from the Additional Help Sources scrolled list.
561
+
562
+ - Add capability to access Additional Help Sources on the web if the
563
+ Help File Path begins with //http or www. (Otherwise local path is
564
+ validated, as before.)
565
+
566
+ - Additional Help Sources were not being posted on the Help menu in the
567
+ order entered. Implement sorting the list by [HelpFiles] 'option'
568
+ number.
569
+
570
+ - Add Browse button to New Help Source dialog. Arrange to start in
571
+ Python/Doc if platform is Windows, otherwise start in current directory.
572
+
573
+ - Put the Additional Help Sources directly on the Help menu instead of in
574
+ an Extra Help cascade menu. Rearrange the Help menu so the Additional
575
+ Help Sources come last. Update help.txt appropriately.
576
+
577
+ - Fix Tk root pop-ups in configSectionNameDialog.py and configDialog.py
578
+
579
+ - Uniform capitalization in General tab of ConfigDialog, update the doc string.
580
+
581
+ - Fix bug in ConfigDialog where SaveAllChangedConfig() was unexpectedly
582
+ deleting Additional Help Sources from the user's config file.
583
+
584
+ - Make configHelpSourceEdit OK button the default and bind <Return>
585
+
586
+ - Fix Tk root pop-ups in configHelpSourceEdit: error dialogs not attached
587
+ to parents.
588
+
589
+ - Use os.startfile() to open both Additional Help and Python Help on the
590
+ Windows platform. The application associated with the file type will act as
591
+ the viewer. Windows help files (.chm) are now supported via the
592
+ Settings/General/Additional Help facility.
593
+
594
+ - If Python Help files are installed locally on Linux, use them instead of
595
+ accessing python.org.
596
+
597
+ - Make the methods for finding the Python help docs more robust, and make
598
+ them work in the installed configuration, also.
599
+
600
+ - On the Save Before Run dialog, make the OK button the default. One
601
+ less mouse action!
602
+
603
+ - Add a method: EditorWindow.get_geometry() for future use in implementing
604
+ window location persistence.
605
+
606
+ - Removed the "Help/Advice" menu entry. Thanks, David! We'll remember!
607
+
608
+ - Change the "Classic Windows" theme's paste key to be <ctrl-v>.
609
+
610
+ - Rearrange the Shell menu to put Stack Viewer entries adjacent.
611
+
612
+ - Add the ability to restart the subprocess interpreter from the shell window;
613
+ add an associated menu entry "Shell/Restart" with binding Control-F6. Update
614
+ IDLE help.
615
+
616
+ - Upon a restart, annotate the shell window with a "restart boundary". Add a
617
+ shell window menu "Shell/View Restart" with binding F6 to jump to the most
618
+ recent restart boundary.
619
+
620
+ - Add Shell menu to Python Shell; change "Settings" to "Options".
621
+
622
+ - Remove incorrect comment in setup.py: IDLEfork is now installed as a package.
623
+
624
+ - Add INSTALL.txt, HISTORY.txt, NEWS.txt to installed configuration.
625
+
626
+ - In installer text, fix reference to Visual Python, should be VPython.
627
+ Properly credit David Scherer.
628
+
629
+ - Modified idle, idle.py, idle.pyw to improve exception handling.
630
+
631
+
632
+ What's New in IDLEfork 0.9 Alpha 1?
633
+ ===================================
634
+ *Release date: 31-Dec-2002*
635
+
636
+ - First release of major new functionality. For further details refer to
637
+ Idle-dev and/or the Sourceforge CVS.
638
+
639
+ - Adapted to the Mac platform.
640
+
641
+ - Overhauled the IDLE startup options and revised the idle -h help message,
642
+ which provides details of command line usage.
643
+
644
+ - Multiple bug fixes and usability enhancements.
645
+
646
+ - Introduced the new RPC implementation, which includes a debugger. The output
647
+ of user code is to the shell, and the shell may be used to inspect the
648
+ environment after the run has finished. (In version 0.8.1 the shell
649
+ environment was separate from the environment of the user code.)
650
+
651
+ - Introduced the configuration GUI and a new About dialog.
652
+
653
+ - Removed David Scherer's Remote Procedure Call code and replaced with Guido
654
+ van Rossum's. GvR code has support for the IDLE debugger and uses the shell
655
+ to inspect the environment of code Run from an Edit window. Files removed:
656
+ ExecBinding.py, loader.py, protocol.py, Remote.py, spawn.py
657
+
658
+ --------------------------------------------------------------------
659
+ Refer to HISTORY.txt for additional information on earlier releases.
660
+ --------------------------------------------------------------------
llava/lib/python3.10/idlelib/README.txt ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ README.txt: an index to idlelib files and the IDLE menu.
2
+
3
+ IDLE is Python's Integrated Development and Learning
4
+ Environment. The user documentation is part of the Library Reference and
5
+ is available in IDLE by selecting Help => IDLE Help. This README documents
6
+ idlelib for IDLE developers and curious users.
7
+
8
+ IDLELIB FILES lists files alphabetically by category,
9
+ with a short description of each.
10
+
11
+ IDLE MENU show the menu tree, annotated with the module
12
+ or module object that implements the corresponding function.
13
+
14
+ This file is descriptive, not prescriptive, and may have errors
15
+ and omissions and lag behind changes in idlelib.
16
+
17
+
18
+ IDLELIB FILES
19
+ =============
20
+
21
+ Implementation files not in IDLE MENU are marked (nim).
22
+
23
+ Startup
24
+ -------
25
+ __init__.py # import, does nothing
26
+ __main__.py # -m, starts IDLE
27
+ idle.bat
28
+ idle.py
29
+ idle.pyw
30
+
31
+ Implementation
32
+ --------------
33
+ autocomplete.py # Complete attribute names or filenames.
34
+ autocomplete_w.py # Display completions.
35
+ autoexpand.py # Expand word with previous word in file.
36
+ browser.py # Create module browser window.
37
+ calltip.py # Create calltip text.
38
+ calltip_w.py # Display calltip.
39
+ codecontext.py # Show compound statement headers otherwise not visible.
40
+ colorizer.py # Colorize text (nim).
41
+ config.py # Load, fetch, and save configuration (nim).
42
+ configdialog.py # Display user configuration dialogs.
43
+ config_key.py # Change keybindings.
44
+ debugger.py # Debug code run from shell or editor; show window.
45
+ debugger_r.py # Debug code run in remote process.
46
+ debugobj.py # Define class used in stackviewer.
47
+ debugobj_r.py # Communicate objects between processes with rpc (nim).
48
+ delegator.py # Define base class for delegators (nim).
49
+ dynoption.py # Define mutable OptionMenu widget (nim)
50
+ editor.py # Define most of editor and utility functions.
51
+ filelist.py # Open files and manage list of open windows (nim).
52
+ format.py # Define format menu options.
53
+ grep.py # Find all occurrences of pattern in multiple files.
54
+ help.py # Display IDLE's html doc.
55
+ help_about.py # Display About IDLE dialog.
56
+ history.py # Get previous or next user input in shell (nim)
57
+ hyperparser.py # Parse code around a given index.
58
+ iomenu.py # Open, read, and write files
59
+ macosx.py # Help IDLE run on Macs (nim).
60
+ mainmenu.py # Define most of IDLE menu.
61
+ multicall.py # Wrap tk widget to allow multiple calls per event (nim).
62
+ outwin.py # Create window for grep output.
63
+ parenmatch.py # Match fenceposts: (), [], and {}.
64
+ pathbrowser.py # Create path browser window.
65
+ percolator.py # Manage delegator stack (nim).
66
+ pyparse.py # Give information on code indentation
67
+ pyshell.py # Start IDLE, manage shell, complete editor window
68
+ query.py # Query user for information
69
+ redirector.py # Intercept widget subcommands (for percolator) (nim).
70
+ replace.py # Search and replace pattern in text.
71
+ rpc.py # Communicate between idle and user processes (nim).
72
+ run.py # Manage user code execution subprocess.
73
+ runscript.py # Check and run user code.
74
+ scrolledlist.py # Define scrolledlist widget for IDLE (nim).
75
+ search.py # Search for pattern in text.
76
+ searchbase.py # Define base for search, replace, and grep dialogs.
77
+ searchengine.py # Define engine for all 3 search dialogs.
78
+ sidebar.py # Define line number and shell prompt sidebars.
79
+ squeezer.py # Squeeze long shell output (nim).
80
+ stackviewer.py # View stack after exception.
81
+ statusbar.py # Define status bar for windows (nim).
82
+ tabbedpages.py # Define tabbed pages widget (nim).
83
+ textview.py # Define read-only text widget (nim).
84
+ tooltip.py # Define popups for calltips, squeezer (nim).
85
+ tree.py # Define tree widget, used in browsers (nim).
86
+ undo.py # Manage undo stack.
87
+ util.py # Define common objects imported elsewhere (nim).
88
+ windows.py # Manage window list and define listed top level.
89
+ zoomheight.py # Zoom window to full height of screen.
90
+ zzdummy.py # Example extension.
91
+
92
+ Configuration
93
+ -------------
94
+ config-extensions.def # Defaults for extensions
95
+ config-highlight.def # Defaults for colorizing
96
+ config-keys.def # Defaults for key bindings
97
+ config-main.def # Defaults for font and general tabs
98
+
99
+ Text
100
+ ----
101
+ CREDITS.txt # not maintained, displayed by About IDLE
102
+ HISTORY.txt # NEWS up to July 2001
103
+ NEWS.txt # commits, displayed by About IDLE
104
+ NEWS2.txt # commits to Python2
105
+ README.txt # this file, displayed by About IDLE
106
+ TODO.txt # needs review
107
+ extend.txt # about writing extensions
108
+ help.html # copy of idle.html in docs, displayed by IDLE Help
109
+
110
+ Subdirectories
111
+ --------------
112
+ Icons # small image files
113
+ idle_test # files for human test and automated unit tests
114
+
115
+
116
+ IDLE MENUS
117
+ ==========
118
+
119
+ Top level items and most submenu items are defined in mainmenu.
120
+ Extensions add submenu items when active. The names given are
121
+ found, quoted, in one of these modules, paired with a '<<pseudoevent>>'.
122
+ Each pseudoevent is bound to an event handler. Some event handlers
123
+ call another function that does the actual work. The annotations below
124
+ are intended to at least give the module where the actual work is done.
125
+ 'eEW' = editor.EditorWindow
126
+
127
+ File
128
+ New File # eEW.new_callback
129
+ Open... # iomenu.open
130
+ Open Module # eEw.open_module
131
+ Recent Files
132
+ Class Browser # eEW.open_class_browser, browser.ClassBrowser
133
+ Path Browser # eEW.open_path_browser, pathbrowser
134
+ ---
135
+ Save # iomenu.save
136
+ Save As... # iomenu.save_as
137
+ Save Copy As... # iomenu.save_a_copy
138
+ ---
139
+ Print Window # iomenu.print_window
140
+ ---
141
+ Close # eEW.close_event
142
+ Exit # flist.close_all_callback (bound in eEW)
143
+
144
+ Edit
145
+ Undo # undodelegator
146
+ Redo # undodelegator
147
+ --- # eEW.right_menu_event
148
+ Cut # eEW.cut
149
+ Copy # eEW.copy
150
+ Paste # eEW.past
151
+ Select All # eEW.select_all (+ see eEW.remove_selection)
152
+ --- # Next 5 items use searchengine; dialogs use searchbase
153
+ Find # eEW.find_event, search.SearchDialog.find
154
+ Find Again # eEW.find_again_event, sSD.find_again
155
+ Find Selection # eEW.find_selection_event, sSD.find_selection
156
+ Find in Files... # eEW.find_in_files_event, grep
157
+ Replace... # eEW.replace_event, replace.ReplaceDialog.replace
158
+ Go to Line # eEW.goto_line_event
159
+ Show Completions # autocomplete extension and autocompleteWidow (&HP)
160
+ Expand Word # autoexpand extension
161
+ Show call tip # Calltips extension and CalltipWindow (& Hyperparser)
162
+ Show surrounding parens # parenmatch (& Hyperparser)
163
+
164
+ Format (Editor only) [fFR = format.FormatRegion]
165
+ Format Paragraph # format.FormatParagraph.format_paragraph_event
166
+ Indent Region # fFR.indent_region_event
167
+ Dedent Region # fFR.dedent_region_event
168
+ Comment Out Reg. # fFR.comment_region_event
169
+ Uncomment Region # fFR.uncomment_region_event
170
+ Tabify Region # fFR.tabify_region_event
171
+ Untabify Region # fFR.untabify_region_event
172
+ Toggle Tabs # format.Indents.toggle_tabs_event
173
+ New Indent Width # format.Indents.change_indentwidth_event
174
+ Strip tailing whitespace # format.rstrip
175
+ Zin # zzdummy
176
+ Zout # zzdummy
177
+
178
+ Run (Editor only)
179
+ Run Module # runscript.ScriptBinding.run_module_event
180
+ Run... Customized # runscript.ScriptBinding.run_custom_event
181
+ Check Module # runscript.ScriptBinding.check_module_event
182
+ Python Shell # pyshell.Pyshell, pyshell.ModifiedInterpreter
183
+
184
+ Shell # pyshell
185
+ View Last Restart # pyshell.PyShell.view_restart_mark
186
+ Restart Shell # pyshell.PyShell.restart_shell
187
+ Previous History # history.History.history_prev
188
+ Next History # history.History.history_next
189
+ Interrupt Execution # pyshell.PyShell.cancel_callback
190
+
191
+ Debug (Shell only)
192
+ Go to File/Line # outwin.OutputWindow.goto_file_line
193
+ debugger # debugger, debugger_r, PyShell.toggle_debugger
194
+ Stack Viewer # stackviewer, PyShell.open_stack_viewer
195
+ Auto-open Stack Viewer # stackviewer
196
+
197
+ Options
198
+ Configure IDLE # eEW.config_dialog, config, configdialog (cd)
199
+ (Parts of the dialog)
200
+ Buttons # cd.ConfigDialog
201
+ Font tab # cd.FontPage, config-main.def
202
+ Highlight tab # cd.HighPage, query, config-highlight.def
203
+ Keys tab # cd.KeysPage, query, config_key, config_keys.def
204
+ Windows tab # cd.WinPage, config_main.def
205
+ Shell/Ed tab # cd.ShedPage, config-main.def
206
+ Extensions tab # config-extensions.def, corresponding .py files
207
+ ---
208
+ ... Code Context # codecontext
209
+ ... Line Numbers # sidebar
210
+ Zoomheight # zoomheight
211
+
212
+ Window
213
+ <open windows> # windows
214
+
215
+ Help
216
+ About IDLE # eEW.about_dialog, help_about.AboutDialog
217
+ ---
218
+ IDLE Help # eEW.help_dialog, help.show_idlehelp
219
+ Python Docs # eEW.python_docs
220
+ Turtle Demo # eEW.open_turtle_demo
221
+ ---
222
+ <other help sources>
223
+
224
+ <Context Menu> (right click)
225
+ Defined in editor, PyShell.pyshell
226
+ Cut
227
+ Copy
228
+ Paste
229
+ ---
230
+ Go to file/line (shell and output only)
231
+ Set Breakpoint (editor only)
232
+ Clear Breakpoint (editor only)
233
+ Defined in debugger
234
+ Go to source line
235
+ Show stack frame
236
+
237
+ <No menu>
238
+ Center Insert # eEW.center_insert_event
239
+
240
+
241
+ OTHER TOPICS
242
+ ============
243
+
244
+ Generally use PEP 8.
245
+
246
+ import statements
247
+ -----------------
248
+ Put imports at the top, unless there is a good reason otherwise.
249
+ PEP 8 says to group stdlib, 3rd-party dependencies, and package imports.
250
+ For idlelib, the groups are general stdlib, tkinter, and idlelib.
251
+ Sort modules within each group, except that tkinter.ttk follows tkinter.
252
+ Sort 'from idlelib import mod1' and 'from idlelib.mod2 import object'
253
+ together by module, ignoring within module objects.
254
+ Put 'import __main__' after other idlelib imports.
255
+
256
+ Imports only needed for testing are put not at the top but in an
257
+ htest function def or "if __name__ == '__main__'" clause.
258
+
259
+ Within module imports like "from idlelib.mod import class" may cause
260
+ circular imports to deadlock. Even without this, circular imports may
261
+ require at least one of the imports to be delayed until a function call.
262
+
263
+ What's New entries
264
+ ------------------
265
+
266
+ Repository directory Doc/whatsnew/ has a file 3.n.rst for each 3.n
267
+ Python version. For the first entry in each file, add subsection
268
+ 'IDLE and idlelib', in alphabetical position, to the 'Improved Modules'
269
+ section. For the rest of cpython, entries to 3.(n+1).rst begin with
270
+ the release of 3.n.0b1. For IDLE, entries for features backported from
271
+ 'main' to '3.n' during its beta period do not got in 3.(n+1).rst. The
272
+ latter usually gets its first entry during the 3.n.0 candidate period
273
+ or after the 3.n.0 release.
274
+
275
+ When, as per PEP 434, feature changes are backported, entries are placed
276
+ in the 3.n.rst file *in the main branch* for each Python version n that
277
+ gets the backport. (Note: the format of entries have varied between
278
+ versions.) Add a line "New in 3.n maintenance releases." before the
279
+ first back-ported feature after 3.n.0 is released. Since each older
280
+ version file gets a different number of backports, it is easiest to
281
+ make a separate PR for each file and label it with the backports
282
+ needed.
283
+
284
+ Github repository and issues
285
+ ----------------------------
286
+
287
+ The CPython repository is https://github.com/python/cpython. The
288
+ IDLE Issues listing is https://github.com/orgs/python/projects/31.
289
+ The main classification is by Topic, based on the IDLE menu. View the
290
+ topics list by clicking the [<]] button in the upper right.
llava/lib/python3.10/idlelib/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """The idlelib package implements the Idle application.
2
+
3
+ Idle includes an interactive shell and editor.
4
+ Starting with Python 3.6, IDLE requires tcl/tk 8.5 or later.
5
+ Use the files named idle.* to start Idle.
6
+
7
+ The other files are private implementations. Their details are subject to
8
+ change. See PEP 434 for more. Import them at your own risk.
9
+ """
10
+ testing = False # Set True by test.test_idle.
llava/lib/python3.10/idlelib/autocomplete.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Complete either attribute names or file names.
2
+
3
+ Either on demand or after a user-selected delay after a key character,
4
+ pop up a list of candidates.
5
+ """
6
+ import __main__
7
+ import keyword
8
+ import os
9
+ import string
10
+ import sys
11
+
12
+ # Modified keyword list is used in fetch_completions.
13
+ completion_kwds = [s for s in keyword.kwlist
14
+ if s not in {'True', 'False', 'None'}] # In builtins.
15
+ completion_kwds.extend(('match', 'case')) # Context keywords.
16
+ completion_kwds.sort()
17
+
18
+ # Two types of completions; defined here for autocomplete_w import below.
19
+ ATTRS, FILES = 0, 1
20
+ from idlelib import autocomplete_w
21
+ from idlelib.config import idleConf
22
+ from idlelib.hyperparser import HyperParser
23
+
24
+ # Tuples passed to open_completions.
25
+ # EvalFunc, Complete, WantWin, Mode
26
+ FORCE = True, False, True, None # Control-Space.
27
+ TAB = False, True, True, None # Tab.
28
+ TRY_A = False, False, False, ATTRS # '.' for attributes.
29
+ TRY_F = False, False, False, FILES # '/' in quotes for file name.
30
+
31
+ # This string includes all chars that may be in an identifier.
32
+ # TODO Update this here and elsewhere.
33
+ ID_CHARS = string.ascii_letters + string.digits + "_"
34
+
35
+ SEPS = f"{os.sep}{os.altsep if os.altsep else ''}"
36
+ TRIGGERS = f".{SEPS}"
37
+
38
+ class AutoComplete:
39
+
40
+ def __init__(self, editwin=None, tags=None):
41
+ self.editwin = editwin
42
+ if editwin is not None: # not in subprocess or no-gui test
43
+ self.text = editwin.text
44
+ self.tags = tags
45
+ self.autocompletewindow = None
46
+ # id of delayed call, and the index of the text insert when
47
+ # the delayed call was issued. If _delayed_completion_id is
48
+ # None, there is no delayed call.
49
+ self._delayed_completion_id = None
50
+ self._delayed_completion_index = None
51
+
52
+ @classmethod
53
+ def reload(cls):
54
+ cls.popupwait = idleConf.GetOption(
55
+ "extensions", "AutoComplete", "popupwait", type="int", default=0)
56
+
57
+ def _make_autocomplete_window(self): # Makes mocking easier.
58
+ return autocomplete_w.AutoCompleteWindow(self.text, tags=self.tags)
59
+
60
+ def _remove_autocomplete_window(self, event=None):
61
+ if self.autocompletewindow:
62
+ self.autocompletewindow.hide_window()
63
+ self.autocompletewindow = None
64
+
65
+ def force_open_completions_event(self, event):
66
+ "(^space) Open completion list, even if a function call is needed."
67
+ self.open_completions(FORCE)
68
+ return "break"
69
+
70
+ def autocomplete_event(self, event):
71
+ "(tab) Complete word or open list if multiple options."
72
+ if hasattr(event, "mc_state") and event.mc_state or\
73
+ not self.text.get("insert linestart", "insert").strip():
74
+ # A modifier was pressed along with the tab or
75
+ # there is only previous whitespace on this line, so tab.
76
+ return None
77
+ if self.autocompletewindow and self.autocompletewindow.is_active():
78
+ self.autocompletewindow.complete()
79
+ return "break"
80
+ else:
81
+ opened = self.open_completions(TAB)
82
+ return "break" if opened else None
83
+
84
+ def try_open_completions_event(self, event=None):
85
+ "(./) Open completion list after pause with no movement."
86
+ lastchar = self.text.get("insert-1c")
87
+ if lastchar in TRIGGERS:
88
+ args = TRY_A if lastchar == "." else TRY_F
89
+ self._delayed_completion_index = self.text.index("insert")
90
+ if self._delayed_completion_id is not None:
91
+ self.text.after_cancel(self._delayed_completion_id)
92
+ self._delayed_completion_id = self.text.after(
93
+ self.popupwait, self._delayed_open_completions, args)
94
+
95
+ def _delayed_open_completions(self, args):
96
+ "Call open_completions if index unchanged."
97
+ self._delayed_completion_id = None
98
+ if self.text.index("insert") == self._delayed_completion_index:
99
+ self.open_completions(args)
100
+
101
+ def open_completions(self, args):
102
+ """Find the completions and create the AutoCompleteWindow.
103
+ Return True if successful (no syntax error or so found).
104
+ If complete is True, then if there's nothing to complete and no
105
+ start of completion, won't open completions and return False.
106
+ If mode is given, will open a completion list only in this mode.
107
+ """
108
+ evalfuncs, complete, wantwin, mode = args
109
+ # Cancel another delayed call, if it exists.
110
+ if self._delayed_completion_id is not None:
111
+ self.text.after_cancel(self._delayed_completion_id)
112
+ self._delayed_completion_id = None
113
+
114
+ hp = HyperParser(self.editwin, "insert")
115
+ curline = self.text.get("insert linestart", "insert")
116
+ i = j = len(curline)
117
+ if hp.is_in_string() and (not mode or mode==FILES):
118
+ # Find the beginning of the string.
119
+ # fetch_completions will look at the file system to determine
120
+ # whether the string value constitutes an actual file name
121
+ # XXX could consider raw strings here and unescape the string
122
+ # value if it's not raw.
123
+ self._remove_autocomplete_window()
124
+ mode = FILES
125
+ # Find last separator or string start
126
+ while i and curline[i-1] not in "'\"" + SEPS:
127
+ i -= 1
128
+ comp_start = curline[i:j]
129
+ j = i
130
+ # Find string start
131
+ while i and curline[i-1] not in "'\"":
132
+ i -= 1
133
+ comp_what = curline[i:j]
134
+ elif hp.is_in_code() and (not mode or mode==ATTRS):
135
+ self._remove_autocomplete_window()
136
+ mode = ATTRS
137
+ while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127):
138
+ i -= 1
139
+ comp_start = curline[i:j]
140
+ if i and curline[i-1] == '.': # Need object with attributes.
141
+ hp.set_index("insert-%dc" % (len(curline)-(i-1)))
142
+ comp_what = hp.get_expression()
143
+ if (not comp_what or
144
+ (not evalfuncs and comp_what.find('(') != -1)):
145
+ return None
146
+ else:
147
+ comp_what = ""
148
+ else:
149
+ return None
150
+
151
+ if complete and not comp_what and not comp_start:
152
+ return None
153
+ comp_lists = self.fetch_completions(comp_what, mode)
154
+ if not comp_lists[0]:
155
+ return None
156
+ self.autocompletewindow = self._make_autocomplete_window()
157
+ return not self.autocompletewindow.show_window(
158
+ comp_lists, "insert-%dc" % len(comp_start),
159
+ complete, mode, wantwin)
160
+
161
+ def fetch_completions(self, what, mode):
162
+ """Return a pair of lists of completions for something. The first list
163
+ is a sublist of the second. Both are sorted.
164
+
165
+ If there is a Python subprocess, get the comp. list there. Otherwise,
166
+ either fetch_completions() is running in the subprocess itself or it
167
+ was called in an IDLE EditorWindow before any script had been run.
168
+
169
+ The subprocess environment is that of the most recently run script. If
170
+ two unrelated modules are being edited some calltips in the current
171
+ module may be inoperative if the module was not the last to run.
172
+ """
173
+ try:
174
+ rpcclt = self.editwin.flist.pyshell.interp.rpcclt
175
+ except:
176
+ rpcclt = None
177
+ if rpcclt:
178
+ return rpcclt.remotecall("exec", "get_the_completion_list",
179
+ (what, mode), {})
180
+ else:
181
+ if mode == ATTRS:
182
+ if what == "": # Main module names.
183
+ namespace = {**__main__.__builtins__.__dict__,
184
+ **__main__.__dict__}
185
+ bigl = eval("dir()", namespace)
186
+ bigl.extend(completion_kwds)
187
+ bigl.sort()
188
+ if "__all__" in bigl:
189
+ smalll = sorted(eval("__all__", namespace))
190
+ else:
191
+ smalll = [s for s in bigl if s[:1] != '_']
192
+ else:
193
+ try:
194
+ entity = self.get_entity(what)
195
+ bigl = dir(entity)
196
+ bigl.sort()
197
+ if "__all__" in bigl:
198
+ smalll = sorted(entity.__all__)
199
+ else:
200
+ smalll = [s for s in bigl if s[:1] != '_']
201
+ except:
202
+ return [], []
203
+
204
+ elif mode == FILES:
205
+ if what == "":
206
+ what = "."
207
+ try:
208
+ expandedpath = os.path.expanduser(what)
209
+ bigl = os.listdir(expandedpath)
210
+ bigl.sort()
211
+ smalll = [s for s in bigl if s[:1] != '.']
212
+ except OSError:
213
+ return [], []
214
+
215
+ if not smalll:
216
+ smalll = bigl
217
+ return smalll, bigl
218
+
219
+ def get_entity(self, name):
220
+ "Lookup name in a namespace spanning sys.modules and __main.dict__."
221
+ return eval(name, {**sys.modules, **__main__.__dict__})
222
+
223
+
224
+ AutoComplete.reload()
225
+
226
+ if __name__ == '__main__':
227
+ from unittest import main
228
+ main('idlelib.idle_test.test_autocomplete', verbosity=2)
llava/lib/python3.10/idlelib/autoexpand.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Complete the current word before the cursor with words in the editor.
2
+
3
+ Each menu selection or shortcut key selection replaces the word with a
4
+ different word with the same prefix. The search for matches begins
5
+ before the target and moves toward the top of the editor. It then starts
6
+ after the cursor and moves down. It then returns to the original word and
7
+ the cycle starts again.
8
+
9
+ Changing the current text line or leaving the cursor in a different
10
+ place before requesting the next selection causes AutoExpand to reset
11
+ its state.
12
+
13
+ There is only one instance of Autoexpand.
14
+ '''
15
+ import re
16
+ import string
17
+
18
+
19
+ class AutoExpand:
20
+ wordchars = string.ascii_letters + string.digits + "_"
21
+
22
+ def __init__(self, editwin):
23
+ self.text = editwin.text
24
+ self.bell = self.text.bell
25
+ self.state = None
26
+
27
+ def expand_word_event(self, event):
28
+ "Replace the current word with the next expansion."
29
+ curinsert = self.text.index("insert")
30
+ curline = self.text.get("insert linestart", "insert lineend")
31
+ if not self.state:
32
+ words = self.getwords()
33
+ index = 0
34
+ else:
35
+ words, index, insert, line = self.state
36
+ if insert != curinsert or line != curline:
37
+ words = self.getwords()
38
+ index = 0
39
+ if not words:
40
+ self.bell()
41
+ return "break"
42
+ word = self.getprevword()
43
+ self.text.delete("insert - %d chars" % len(word), "insert")
44
+ newword = words[index]
45
+ index = (index + 1) % len(words)
46
+ if index == 0:
47
+ self.bell() # Warn we cycled around
48
+ self.text.insert("insert", newword)
49
+ curinsert = self.text.index("insert")
50
+ curline = self.text.get("insert linestart", "insert lineend")
51
+ self.state = words, index, curinsert, curline
52
+ return "break"
53
+
54
+ def getwords(self):
55
+ "Return a list of words that match the prefix before the cursor."
56
+ word = self.getprevword()
57
+ if not word:
58
+ return []
59
+ before = self.text.get("1.0", "insert wordstart")
60
+ wbefore = re.findall(r"\b" + word + r"\w+\b", before)
61
+ del before
62
+ after = self.text.get("insert wordend", "end")
63
+ wafter = re.findall(r"\b" + word + r"\w+\b", after)
64
+ del after
65
+ if not wbefore and not wafter:
66
+ return []
67
+ words = []
68
+ dict = {}
69
+ # search backwards through words before
70
+ wbefore.reverse()
71
+ for w in wbefore:
72
+ if dict.get(w):
73
+ continue
74
+ words.append(w)
75
+ dict[w] = w
76
+ # search onwards through words after
77
+ for w in wafter:
78
+ if dict.get(w):
79
+ continue
80
+ words.append(w)
81
+ dict[w] = w
82
+ words.append(word)
83
+ return words
84
+
85
+ def getprevword(self):
86
+ "Return the word prefix before the cursor."
87
+ line = self.text.get("insert linestart", "insert")
88
+ i = len(line)
89
+ while i > 0 and line[i-1] in self.wordchars:
90
+ i = i-1
91
+ return line[i:]
92
+
93
+
94
+ if __name__ == '__main__':
95
+ from unittest import main
96
+ main('idlelib.idle_test.test_autoexpand', verbosity=2)
llava/lib/python3.10/idlelib/config-highlight.def ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IDLE reads several config files to determine user preferences. This
2
+ # file is the default config file for idle highlight theme settings.
3
+
4
+ [IDLE Classic]
5
+ normal-foreground= #000000
6
+ normal-background= #ffffff
7
+ keyword-foreground= #ff7700
8
+ keyword-background= #ffffff
9
+ builtin-foreground= #900090
10
+ builtin-background= #ffffff
11
+ comment-foreground= #dd0000
12
+ comment-background= #ffffff
13
+ string-foreground= #00aa00
14
+ string-background= #ffffff
15
+ definition-foreground= #0000ff
16
+ definition-background= #ffffff
17
+ hilite-foreground= #000000
18
+ hilite-background= gray
19
+ break-foreground= black
20
+ break-background= #ffff55
21
+ hit-foreground= #ffffff
22
+ hit-background= #000000
23
+ error-foreground= #000000
24
+ error-background= #ff7777
25
+ context-foreground= #000000
26
+ context-background= lightgray
27
+ linenumber-foreground= gray
28
+ linenumber-background= #ffffff
29
+ #cursor (only foreground can be set, restart IDLE)
30
+ cursor-foreground= black
31
+ #shell window
32
+ stdout-foreground= blue
33
+ stdout-background= #ffffff
34
+ stderr-foreground= red
35
+ stderr-background= #ffffff
36
+ console-foreground= #770000
37
+ console-background= #ffffff
38
+
39
+ [IDLE New]
40
+ normal-foreground= #000000
41
+ normal-background= #ffffff
42
+ keyword-foreground= #ff7700
43
+ keyword-background= #ffffff
44
+ builtin-foreground= #900090
45
+ builtin-background= #ffffff
46
+ comment-foreground= #dd0000
47
+ comment-background= #ffffff
48
+ string-foreground= #00aa00
49
+ string-background= #ffffff
50
+ definition-foreground= #0000ff
51
+ definition-background= #ffffff
52
+ hilite-foreground= #000000
53
+ hilite-background= gray
54
+ break-foreground= black
55
+ break-background= #ffff55
56
+ hit-foreground= #ffffff
57
+ hit-background= #000000
58
+ error-foreground= #000000
59
+ error-background= #ff7777
60
+ context-foreground= #000000
61
+ context-background= lightgray
62
+ linenumber-foreground= gray
63
+ linenumber-background= #ffffff
64
+ #cursor (only foreground can be set, restart IDLE)
65
+ cursor-foreground= black
66
+ #shell window
67
+ stdout-foreground= blue
68
+ stdout-background= #ffffff
69
+ stderr-foreground= red
70
+ stderr-background= #ffffff
71
+ console-foreground= #770000
72
+ console-background= #ffffff
73
+
74
+ [IDLE Dark]
75
+ comment-foreground = #dd0000
76
+ console-foreground = #ff4d4d
77
+ error-foreground = #FFFFFF
78
+ hilite-background = #7e7e7e
79
+ string-foreground = #02ff02
80
+ stderr-background = #002240
81
+ stderr-foreground = #ffb3b3
82
+ console-background = #002240
83
+ hit-background = #fbfbfb
84
+ string-background = #002240
85
+ normal-background = #002240
86
+ hilite-foreground = #FFFFFF
87
+ keyword-foreground = #ff8000
88
+ error-background = #c86464
89
+ keyword-background = #002240
90
+ builtin-background = #002240
91
+ break-background = #808000
92
+ builtin-foreground = #ff00ff
93
+ definition-foreground = #5e5eff
94
+ stdout-foreground = #c2d1fa
95
+ definition-background = #002240
96
+ normal-foreground = #FFFFFF
97
+ cursor-foreground = #ffffff
98
+ stdout-background = #002240
99
+ hit-foreground = #002240
100
+ comment-background = #002240
101
+ break-foreground = #FFFFFF
102
+ context-foreground= #ffffff
103
+ context-background= #454545
104
+ linenumber-foreground= gray
105
+ linenumber-background= #002240
llava/lib/python3.10/idlelib/config-keys.def ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IDLE reads several config files to determine user preferences. This
2
+ # file is the default config file for idle key binding settings.
3
+ # Where multiple keys are specified for an action: if they are separated
4
+ # by a space (eg. action=<key1> <key2>) then the keys are alternatives, if
5
+ # there is no space (eg. action=<key1><key2>) then the keys comprise a
6
+ # single 'emacs style' multi-keystoke binding. The tk event specifier 'Key'
7
+ # is used in all cases, for consistency in auto key conflict checking in the
8
+ # configuration gui.
9
+
10
+ [IDLE Classic Windows]
11
+ copy=<Control-Key-c> <Control-Key-C>
12
+ cut=<Control-Key-x> <Control-Key-X>
13
+ paste=<Control-Key-v> <Control-Key-V>
14
+ beginning-of-line= <Key-Home>
15
+ center-insert=<Control-Key-l> <Control-Key-L>
16
+ close-all-windows=<Control-Key-q> <Control-Key-Q>
17
+ close-window=<Alt-Key-F4> <Meta-Key-F4>
18
+ do-nothing=<Control-Key-F12>
19
+ end-of-file=<Control-Key-d> <Control-Key-D>
20
+ python-docs=<Key-F1>
21
+ python-context-help=<Shift-Key-F1>
22
+ history-next=<Alt-Key-n> <Meta-Key-n> <Alt-Key-N> <Meta-Key-N>
23
+ history-previous=<Alt-Key-p> <Meta-Key-p> <Alt-Key-P> <Meta-Key-P>
24
+ interrupt-execution=<Control-Key-c> <Control-Key-C>
25
+ view-restart=<Key-F6>
26
+ restart-shell=<Control-Key-F6>
27
+ open-class-browser=<Alt-Key-c> <Meta-Key-c> <Alt-Key-C> <Meta-Key-C>
28
+ open-module=<Alt-Key-m> <Meta-Key-m> <Alt-Key-M> <Meta-Key-M>
29
+ open-new-window=<Control-Key-n> <Control-Key-N>
30
+ open-window-from-file=<Control-Key-o> <Control-Key-O>
31
+ plain-newline-and-indent=<Control-Key-j> <Control-Key-J>
32
+ print-window=<Control-Key-p> <Control-Key-P>
33
+ redo=<Control-Shift-Key-Z> <Control-Shift-Key-z>
34
+ remove-selection=<Key-Escape>
35
+ save-copy-of-window-as-file=<Alt-Shift-Key-S> <Alt-Shift-Key-s>
36
+ save-window-as-file=<Control-Shift-Key-S> <Control-Shift-Key-s>
37
+ save-window=<Control-Key-s> <Control-Key-S>
38
+ select-all=<Control-Key-a> <Control-Key-A>
39
+ toggle-auto-coloring=<Control-Key-slash>
40
+ undo=<Control-Key-z> <Control-Key-Z>
41
+ find=<Control-Key-f> <Control-Key-F>
42
+ find-again=<Control-Key-g> <Key-F3> <Control-Key-G>
43
+ find-in-files=<Alt-Key-F3> <Meta-Key-F3>
44
+ find-selection=<Control-Key-F3>
45
+ replace=<Control-Key-h> <Control-Key-H>
46
+ goto-line=<Alt-Key-g> <Meta-Key-g> <Alt-Key-G> <Meta-Key-G>
47
+ smart-backspace=<Key-BackSpace>
48
+ newline-and-indent=<Key-Return> <Key-KP_Enter>
49
+ smart-indent=<Key-Tab>
50
+ indent-region=<Control-Key-bracketright>
51
+ dedent-region=<Control-Key-bracketleft>
52
+ comment-region=<Alt-Key-3> <Meta-Key-3>
53
+ uncomment-region=<Alt-Key-4> <Meta-Key-4>
54
+ tabify-region=<Alt-Key-5> <Meta-Key-5>
55
+ untabify-region=<Alt-Key-6> <Meta-Key-6>
56
+ toggle-tabs=<Alt-Key-t> <Meta-Key-t> <Alt-Key-T> <Meta-Key-T>
57
+ change-indentwidth=<Alt-Key-u> <Meta-Key-u> <Alt-Key-U> <Meta-Key-U>
58
+ del-word-left=<Control-Key-BackSpace>
59
+ del-word-right=<Control-Key-Delete>
60
+ force-open-completions= <Control-Key-space>
61
+ expand-word= <Alt-Key-slash>
62
+ force-open-calltip= <Control-Key-backslash>
63
+ format-paragraph= <Alt-Key-q>
64
+ flash-paren= <Control-Key-0>
65
+ run-module= <Key-F5>
66
+ run-custom= <Shift-Key-F5>
67
+ check-module= <Alt-Key-x>
68
+ zoom-height= <Alt-Key-2>
69
+
70
+ [IDLE Classic Unix]
71
+ copy=<Alt-Key-w> <Meta-Key-w>
72
+ cut=<Control-Key-w>
73
+ paste=<Control-Key-y>
74
+ beginning-of-line=<Control-Key-a> <Key-Home>
75
+ center-insert=<Control-Key-l>
76
+ close-all-windows=<Control-Key-x><Control-Key-c>
77
+ close-window=<Control-Key-x><Control-Key-0>
78
+ do-nothing=<Control-Key-x>
79
+ end-of-file=<Control-Key-d>
80
+ history-next=<Alt-Key-n> <Meta-Key-n>
81
+ history-previous=<Alt-Key-p> <Meta-Key-p>
82
+ interrupt-execution=<Control-Key-c>
83
+ view-restart=<Key-F6>
84
+ restart-shell=<Control-Key-F6>
85
+ open-class-browser=<Control-Key-x><Control-Key-b>
86
+ open-module=<Control-Key-x><Control-Key-m>
87
+ open-new-window=<Control-Key-x><Control-Key-n>
88
+ open-window-from-file=<Control-Key-x><Control-Key-f>
89
+ plain-newline-and-indent=<Control-Key-j>
90
+ print-window=<Control-x><Control-Key-p>
91
+ python-docs=<Control-Key-h>
92
+ python-context-help=<Control-Shift-Key-H>
93
+ redo=<Alt-Key-z> <Meta-Key-z>
94
+ remove-selection=<Key-Escape>
95
+ save-copy-of-window-as-file=<Control-Key-x><Control-Key-y>
96
+ save-window-as-file=<Control-Key-x><Control-Key-w>
97
+ save-window=<Control-Key-x><Control-Key-s>
98
+ select-all=<Alt-Key-a> <Meta-Key-a>
99
+ toggle-auto-coloring=<Control-Key-slash>
100
+ undo=<Control-Key-z>
101
+ find=<Control-Key-u><Control-Key-u><Control-Key-s>
102
+ find-again=<Control-Key-u><Control-Key-s>
103
+ find-in-files=<Alt-Key-s> <Meta-Key-s>
104
+ find-selection=<Control-Key-s>
105
+ replace=<Control-Key-r>
106
+ goto-line=<Alt-Key-g> <Meta-Key-g>
107
+ smart-backspace=<Key-BackSpace>
108
+ newline-and-indent=<Key-Return> <Key-KP_Enter>
109
+ smart-indent=<Key-Tab>
110
+ indent-region=<Control-Key-bracketright>
111
+ dedent-region=<Control-Key-bracketleft>
112
+ comment-region=<Alt-Key-3>
113
+ uncomment-region=<Alt-Key-4>
114
+ tabify-region=<Alt-Key-5>
115
+ untabify-region=<Alt-Key-6>
116
+ toggle-tabs=<Alt-Key-t>
117
+ change-indentwidth=<Alt-Key-u>
118
+ del-word-left=<Alt-Key-BackSpace>
119
+ del-word-right=<Alt-Key-d>
120
+ force-open-completions= <Control-Key-space>
121
+ expand-word= <Alt-Key-slash>
122
+ force-open-calltip= <Control-Key-backslash>
123
+ format-paragraph= <Alt-Key-q>
124
+ flash-paren= <Control-Key-0>
125
+ run-module= <Key-F5>
126
+ run-custom= <Shift-Key-F5>
127
+ check-module= <Alt-Key-x>
128
+ zoom-height= <Alt-Key-2>
129
+
130
+ [IDLE Modern Unix]
131
+ copy = <Control-Shift-Key-C> <Control-Key-Insert>
132
+ cut = <Control-Key-x> <Shift-Key-Delete>
133
+ paste = <Control-Key-v> <Shift-Key-Insert>
134
+ beginning-of-line = <Key-Home>
135
+ center-insert = <Control-Key-l>
136
+ close-all-windows = <Control-Key-q>
137
+ close-window = <Control-Key-w> <Control-Shift-Key-W>
138
+ do-nothing = <Control-Key-F12>
139
+ end-of-file = <Control-Key-d>
140
+ history-next = <Alt-Key-n> <Meta-Key-n>
141
+ history-previous = <Alt-Key-p> <Meta-Key-p>
142
+ interrupt-execution = <Control-Key-c>
143
+ view-restart = <Key-F6>
144
+ restart-shell = <Control-Key-F6>
145
+ open-class-browser = <Control-Key-b>
146
+ open-module = <Control-Key-m>
147
+ open-new-window = <Control-Key-n>
148
+ open-window-from-file = <Control-Key-o>
149
+ plain-newline-and-indent = <Control-Key-j>
150
+ print-window = <Control-Key-p>
151
+ python-context-help = <Shift-Key-F1>
152
+ python-docs = <Key-F1>
153
+ redo = <Control-Shift-Key-Z>
154
+ remove-selection = <Key-Escape>
155
+ save-copy-of-window-as-file = <Alt-Shift-Key-S>
156
+ save-window-as-file = <Control-Shift-Key-S>
157
+ save-window = <Control-Key-s>
158
+ select-all = <Control-Key-a>
159
+ toggle-auto-coloring = <Control-Key-slash>
160
+ undo = <Control-Key-z>
161
+ find = <Control-Key-f>
162
+ find-again = <Key-F3>
163
+ find-in-files = <Control-Shift-Key-f>
164
+ find-selection = <Control-Key-h>
165
+ replace = <Control-Key-r>
166
+ goto-line = <Control-Key-g>
167
+ smart-backspace = <Key-BackSpace>
168
+ newline-and-indent = <Key-Return> <Key-KP_Enter>
169
+ smart-indent = <Key-Tab>
170
+ indent-region = <Control-Key-bracketright>
171
+ dedent-region = <Control-Key-bracketleft>
172
+ comment-region = <Control-Key-d>
173
+ uncomment-region = <Control-Shift-Key-D>
174
+ tabify-region = <Alt-Key-5>
175
+ untabify-region = <Alt-Key-6>
176
+ toggle-tabs = <Control-Key-T>
177
+ change-indentwidth = <Alt-Key-u>
178
+ del-word-left = <Control-Key-BackSpace>
179
+ del-word-right = <Control-Key-Delete>
180
+ force-open-completions= <Control-Key-space>
181
+ expand-word= <Alt-Key-slash>
182
+ force-open-calltip= <Control-Key-backslash>
183
+ format-paragraph= <Alt-Key-q>
184
+ flash-paren= <Control-Key-0>
185
+ run-module= <Key-F5>
186
+ run-custom= <Shift-Key-F5>
187
+ check-module= <Alt-Key-x>
188
+ zoom-height= <Alt-Key-2>
189
+
190
+ [IDLE Classic Mac]
191
+ copy=<Command-Key-c>
192
+ cut=<Command-Key-x>
193
+ paste=<Command-Key-v>
194
+ beginning-of-line= <Key-Home>
195
+ center-insert=<Control-Key-l>
196
+ close-all-windows=<Command-Key-q>
197
+ close-window=<Command-Key-w>
198
+ do-nothing=<Control-Key-F12>
199
+ end-of-file=<Control-Key-d>
200
+ python-docs=<Key-F1>
201
+ python-context-help=<Shift-Key-F1>
202
+ history-next=<Control-Key-n>
203
+ history-previous=<Control-Key-p>
204
+ interrupt-execution=<Control-Key-c>
205
+ view-restart=<Key-F6>
206
+ restart-shell=<Control-Key-F6>
207
+ open-class-browser=<Command-Key-b>
208
+ open-module=<Command-Key-m>
209
+ open-new-window=<Command-Key-n>
210
+ open-window-from-file=<Command-Key-o>
211
+ plain-newline-and-indent=<Control-Key-j>
212
+ print-window=<Command-Key-p>
213
+ redo=<Shift-Command-Key-Z>
214
+ remove-selection=<Key-Escape>
215
+ save-window-as-file=<Shift-Command-Key-S>
216
+ save-window=<Command-Key-s>
217
+ save-copy-of-window-as-file=<Option-Command-Key-s>
218
+ select-all=<Command-Key-a>
219
+ toggle-auto-coloring=<Control-Key-slash>
220
+ undo=<Command-Key-z>
221
+ find=<Command-Key-f>
222
+ find-again=<Command-Key-g> <Key-F3>
223
+ find-in-files=<Command-Key-F3>
224
+ find-selection=<Shift-Command-Key-F3>
225
+ replace=<Command-Key-r>
226
+ goto-line=<Command-Key-j>
227
+ smart-backspace=<Key-BackSpace>
228
+ newline-and-indent=<Key-Return> <Key-KP_Enter>
229
+ smart-indent=<Key-Tab>
230
+ indent-region=<Command-Key-bracketright>
231
+ dedent-region=<Command-Key-bracketleft>
232
+ comment-region=<Control-Key-3>
233
+ uncomment-region=<Control-Key-4>
234
+ tabify-region=<Control-Key-5>
235
+ untabify-region=<Control-Key-6>
236
+ toggle-tabs=<Control-Key-t>
237
+ change-indentwidth=<Control-Key-u>
238
+ del-word-left=<Control-Key-BackSpace>
239
+ del-word-right=<Control-Key-Delete>
240
+ force-open-completions= <Control-Key-space>
241
+ expand-word= <Option-Key-slash>
242
+ force-open-calltip= <Control-Key-backslash>
243
+ format-paragraph= <Option-Key-q>
244
+ flash-paren= <Control-Key-0>
245
+ run-module= <Key-F5>
246
+ run-custom= <Shift-Key-F5>
247
+ check-module= <Option-Key-x>
248
+ zoom-height= <Option-Key-0>
249
+
250
+ [IDLE Classic OSX]
251
+ toggle-tabs = <Control-Key-t>
252
+ interrupt-execution = <Control-Key-c>
253
+ untabify-region = <Control-Key-6>
254
+ remove-selection = <Key-Escape>
255
+ print-window = <Command-Key-p>
256
+ replace = <Command-Key-r>
257
+ goto-line = <Command-Key-j>
258
+ plain-newline-and-indent = <Control-Key-j>
259
+ history-previous = <Control-Key-p>
260
+ beginning-of-line = <Control-Key-Left>
261
+ end-of-line = <Control-Key-Right>
262
+ comment-region = <Control-Key-3>
263
+ redo = <Shift-Command-Key-Z>
264
+ close-window = <Command-Key-w>
265
+ restart-shell = <Control-Key-F6>
266
+ save-window-as-file = <Shift-Command-Key-S>
267
+ close-all-windows = <Command-Key-q>
268
+ view-restart = <Key-F6>
269
+ tabify-region = <Control-Key-5>
270
+ find-again = <Command-Key-g> <Key-F3>
271
+ find = <Command-Key-f>
272
+ toggle-auto-coloring = <Control-Key-slash>
273
+ select-all = <Command-Key-a>
274
+ smart-backspace = <Key-BackSpace>
275
+ change-indentwidth = <Control-Key-u>
276
+ do-nothing = <Control-Key-F12>
277
+ smart-indent = <Key-Tab>
278
+ center-insert = <Control-Key-l>
279
+ history-next = <Control-Key-n>
280
+ del-word-right = <Option-Key-Delete>
281
+ undo = <Command-Key-z>
282
+ save-window = <Command-Key-s>
283
+ uncomment-region = <Control-Key-4>
284
+ cut = <Command-Key-x>
285
+ find-in-files = <Command-Key-F3>
286
+ dedent-region = <Command-Key-bracketleft>
287
+ copy = <Command-Key-c>
288
+ paste = <Command-Key-v>
289
+ indent-region = <Command-Key-bracketright>
290
+ del-word-left = <Option-Key-BackSpace> <Option-Command-Key-BackSpace>
291
+ newline-and-indent = <Key-Return> <Key-KP_Enter>
292
+ end-of-file = <Control-Key-d>
293
+ open-class-browser = <Command-Key-b>
294
+ open-new-window = <Command-Key-n>
295
+ open-module = <Command-Key-m>
296
+ find-selection = <Shift-Command-Key-F3>
297
+ python-context-help = <Shift-Key-F1>
298
+ save-copy-of-window-as-file = <Option-Command-Key-s>
299
+ open-window-from-file = <Command-Key-o>
300
+ python-docs = <Key-F1>
301
+ force-open-completions= <Control-Key-space>
302
+ expand-word= <Option-Key-slash>
303
+ force-open-calltip= <Control-Key-backslash>
304
+ format-paragraph= <Option-Key-q>
305
+ flash-paren= <Control-Key-0>
306
+ run-module= <Key-F5>
307
+ run-custom= <Shift-Key-F5>
308
+ check-module= <Option-Key-x>
309
+ zoom-height= <Option-Key-0>
llava/lib/python3.10/idlelib/config-main.def ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IDLE reads several config files to determine user preferences. This
2
+ # file is the default config file for general idle settings.
3
+ #
4
+ # When IDLE starts, it will look in
5
+ # the following two sets of files, in order:
6
+ #
7
+ # default configuration files in idlelib
8
+ # --------------------------------------
9
+ # config-main.def default general config file
10
+ # config-extensions.def default extension config file
11
+ # config-highlight.def default highlighting config file
12
+ # config-keys.def default keybinding config file
13
+ #
14
+ # user configuration files in ~/.idlerc
15
+ # -------------------------------------
16
+ # config-main.cfg user general config file
17
+ # config-extensions.cfg user extension config file
18
+ # config-highlight.cfg user highlighting config file
19
+ # config-keys.cfg user keybinding config file
20
+ #
21
+ # On Windows, the default location of the home directory ('~' above)
22
+ # depends on the version. For Windows 10, it is C:\Users\<username>.
23
+ #
24
+ # Any options the user saves through the config dialog will be saved to
25
+ # the relevant user config file. Reverting any general or extension
26
+ # setting to the default causes that entry to be wiped from the user
27
+ # file and re-read from the default file. This rule applies to each
28
+ # item, except that the three editor font items are saved as a group.
29
+ #
30
+ # User highlighting themes and keybinding sets must have (section) names
31
+ # distinct from the default names. All items are added and saved as a
32
+ # group. They are retained unless specifically deleted within the config
33
+ # dialog. Choosing one of the default themes or keysets just applies the
34
+ # relevant settings from the default file.
35
+ #
36
+ # Additional help sources are listed in the [HelpFiles] section below
37
+ # and should be viewable by a web browser (or the Windows Help viewer in
38
+ # the case of .chm files). These sources will be listed on the Help
39
+ # menu. The pattern, and two examples, are:
40
+ #
41
+ # <sequence_number = menu item;/path/to/help/source>
42
+ # 1 = IDLE;C:/Programs/Python36/Lib/idlelib/help.html
43
+ # 2 = Pillow;https://pillow.readthedocs.io/en/latest/
44
+ #
45
+ # You can't use a semi-colon in a menu item or path. The path will be
46
+ # platform specific because of path separators, drive specs etc.
47
+ #
48
+ # The default files should not be edited except to add new sections to
49
+ # config-extensions.def for added extensions. The user files should be
50
+ # modified through the Settings dialog.
51
+
52
+ [General]
53
+ editor-on-startup= 0
54
+ autosave= 0
55
+ print-command-posix=lpr %%s
56
+ print-command-win=start /min notepad /p %%s
57
+ delete-exitfunc= 1
58
+
59
+ [EditorWindow]
60
+ width= 80
61
+ height= 40
62
+ cursor-blink= 1
63
+ font= TkFixedFont
64
+ # For TkFixedFont, the actual size and boldness are obtained from tk
65
+ # and override 10 and 0. See idlelib.config.IdleConf.GetFont
66
+ font-size= 10
67
+ font-bold= 0
68
+ encoding= none
69
+ line-numbers-default= 0
70
+
71
+ [PyShell]
72
+ auto-squeeze-min-lines= 50
73
+
74
+ [Indent]
75
+ use-spaces= 1
76
+ num-spaces= 4
77
+
78
+ [Theme]
79
+ default= 1
80
+ name= IDLE Classic
81
+ name2=
82
+ # name2 set in user config-main.cfg for themes added after 2015 Oct 1
83
+
84
+ [Keys]
85
+ default= 1
86
+ name=
87
+ name2=
88
+ # name2 set in user config-main.cfg for keys added after 2016 July 1
89
+
90
+ [History]
91
+ cyclic=1
92
+
93
+ [HelpFiles]
llava/lib/python3.10/idlelib/configdialog.py ADDED
The diff for this file is too large to render. See raw diff
 
llava/lib/python3.10/idlelib/dynoption.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OptionMenu widget modified to allow dynamic menu reconfiguration
3
+ and setting of highlightthickness
4
+ """
5
+ from tkinter import OptionMenu, _setit, StringVar, Button
6
+
7
+ class DynOptionMenu(OptionMenu):
8
+ """Add SetMenu and highlightthickness to OptionMenu.
9
+
10
+ Highlightthickness adds space around menu button.
11
+ """
12
+ def __init__(self, master, variable, value, *values, **kwargs):
13
+ highlightthickness = kwargs.pop('highlightthickness', None)
14
+ OptionMenu.__init__(self, master, variable, value, *values, **kwargs)
15
+ self['highlightthickness'] = highlightthickness
16
+ self.variable = variable
17
+ self.command = kwargs.get('command')
18
+
19
+ def SetMenu(self,valueList,value=None):
20
+ """
21
+ clear and reload the menu with a new set of options.
22
+ valueList - list of new options
23
+ value - initial value to set the optionmenu's menubutton to
24
+ """
25
+ self['menu'].delete(0,'end')
26
+ for item in valueList:
27
+ self['menu'].add_command(label=item,
28
+ command=_setit(self.variable,item,self.command))
29
+ if value:
30
+ self.variable.set(value)
31
+
32
+ def _dyn_option_menu(parent): # htest #
33
+ from tkinter import Toplevel # + StringVar, Button
34
+
35
+ top = Toplevel(parent)
36
+ top.title("Test dynamic option menu")
37
+ x, y = map(int, parent.geometry().split('+')[1:])
38
+ top.geometry("200x100+%d+%d" % (x + 250, y + 175))
39
+ top.focus_set()
40
+
41
+ var = StringVar(top)
42
+ var.set("Old option set") #Set the default value
43
+ dyn = DynOptionMenu(top, var, "old1","old2","old3","old4",
44
+ highlightthickness=5)
45
+ dyn.pack()
46
+
47
+ def update():
48
+ dyn.SetMenu(["new1","new2","new3","new4"], value="new option set")
49
+ button = Button(top, text="Change option set", command=update)
50
+ button.pack()
51
+
52
+ if __name__ == '__main__':
53
+ # Only module without unittests because of intention to replace.
54
+ from idlelib.idle_test.htest import run
55
+ run(_dyn_option_menu)
llava/lib/python3.10/idlelib/editor.py ADDED
@@ -0,0 +1,1683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.abc
2
+ import importlib.util
3
+ import os
4
+ import platform
5
+ import re
6
+ import string
7
+ import sys
8
+ import tokenize
9
+ import traceback
10
+ import webbrowser
11
+
12
+ from tkinter import *
13
+ from tkinter.font import Font
14
+ from tkinter.ttk import Scrollbar
15
+ from tkinter import simpledialog
16
+ from tkinter import messagebox
17
+
18
+ from idlelib.config import idleConf
19
+ from idlelib import configdialog
20
+ from idlelib import grep
21
+ from idlelib import help
22
+ from idlelib import help_about
23
+ from idlelib import macosx
24
+ from idlelib.multicall import MultiCallCreator
25
+ from idlelib import pyparse
26
+ from idlelib import query
27
+ from idlelib import replace
28
+ from idlelib import search
29
+ from idlelib.tree import wheel_event
30
+ from idlelib.util import py_extensions
31
+ from idlelib import window
32
+
33
+ # The default tab setting for a Text widget, in average-width characters.
34
+ TK_TABWIDTH_DEFAULT = 8
35
+ _py_version = ' (%s)' % platform.python_version()
36
+ darwin = sys.platform == 'darwin'
37
+
38
+ def _sphinx_version():
39
+ "Format sys.version_info to produce the Sphinx version string used to install the chm docs"
40
+ major, minor, micro, level, serial = sys.version_info
41
+ release = '%s%s' % (major, minor)
42
+ release += '%s' % (micro,)
43
+ if level == 'candidate':
44
+ release += 'rc%s' % (serial,)
45
+ elif level != 'final':
46
+ release += '%s%s' % (level[0], serial)
47
+ return release
48
+
49
+
50
+ class EditorWindow:
51
+ from idlelib.percolator import Percolator
52
+ from idlelib.colorizer import ColorDelegator, color_config
53
+ from idlelib.undo import UndoDelegator
54
+ from idlelib.iomenu import IOBinding, encoding
55
+ from idlelib import mainmenu
56
+ from idlelib.statusbar import MultiStatusBar
57
+ from idlelib.autocomplete import AutoComplete
58
+ from idlelib.autoexpand import AutoExpand
59
+ from idlelib.calltip import Calltip
60
+ from idlelib.codecontext import CodeContext
61
+ from idlelib.sidebar import LineNumbers
62
+ from idlelib.format import FormatParagraph, FormatRegion, Indents, Rstrip
63
+ from idlelib.parenmatch import ParenMatch
64
+ from idlelib.zoomheight import ZoomHeight
65
+
66
+ filesystemencoding = sys.getfilesystemencoding() # for file names
67
+ help_url = None
68
+
69
+ allow_code_context = True
70
+ allow_line_numbers = True
71
+ user_input_insert_tags = None
72
+
73
+ def __init__(self, flist=None, filename=None, key=None, root=None):
74
+ # Delay import: runscript imports pyshell imports EditorWindow.
75
+ from idlelib.runscript import ScriptBinding
76
+
77
+ if EditorWindow.help_url is None:
78
+ dochome = os.path.join(sys.base_prefix, 'Doc', 'index.html')
79
+ if sys.platform.count('linux'):
80
+ # look for html docs in a couple of standard places
81
+ pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3]
82
+ if os.path.isdir('/var/www/html/python/'): # "python2" rpm
83
+ dochome = '/var/www/html/python/index.html'
84
+ else:
85
+ basepath = '/usr/share/doc/' # standard location
86
+ dochome = os.path.join(basepath, pyver,
87
+ 'Doc', 'index.html')
88
+ elif sys.platform[:3] == 'win':
89
+ import winreg # Windows only, block only executed once.
90
+ docfile = ''
91
+ KEY = (rf"Software\Python\PythonCore\{sys.winver}"
92
+ r"\Help\Main Python Documentation")
93
+ try:
94
+ docfile = winreg.QueryValue(winreg.HKEY_CURRENT_USER, KEY)
95
+ except FileNotFoundError:
96
+ try:
97
+ docfile = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE,
98
+ KEY)
99
+ except FileNotFoundError:
100
+ pass
101
+ if os.path.isfile(docfile):
102
+ dochome = docfile
103
+ elif sys.platform == 'darwin':
104
+ # documentation may be stored inside a python framework
105
+ dochome = os.path.join(sys.base_prefix,
106
+ 'Resources/English.lproj/Documentation/index.html')
107
+ dochome = os.path.normpath(dochome)
108
+ if os.path.isfile(dochome):
109
+ EditorWindow.help_url = dochome
110
+ if sys.platform == 'darwin':
111
+ # Safari requires real file:-URLs
112
+ EditorWindow.help_url = 'file://' + EditorWindow.help_url
113
+ else:
114
+ EditorWindow.help_url = ("https://docs.python.org/%d.%d/"
115
+ % sys.version_info[:2])
116
+ self.flist = flist
117
+ root = root or flist.root
118
+ self.root = root
119
+ self.menubar = Menu(root)
120
+ self.top = top = window.ListedToplevel(root, menu=self.menubar)
121
+ if flist:
122
+ self.tkinter_vars = flist.vars
123
+ #self.top.instance_dict makes flist.inversedict available to
124
+ #configdialog.py so it can access all EditorWindow instances
125
+ self.top.instance_dict = flist.inversedict
126
+ else:
127
+ self.tkinter_vars = {} # keys: Tkinter event names
128
+ # values: Tkinter variable instances
129
+ self.top.instance_dict = {}
130
+ self.recent_files_path = idleConf.userdir and os.path.join(
131
+ idleConf.userdir, 'recent-files.lst')
132
+
133
+ self.prompt_last_line = '' # Override in PyShell
134
+ self.text_frame = text_frame = Frame(top)
135
+ self.vbar = vbar = Scrollbar(text_frame, name='vbar')
136
+ width = idleConf.GetOption('main', 'EditorWindow', 'width', type='int')
137
+ text_options = {
138
+ 'name': 'text',
139
+ 'padx': 5,
140
+ 'wrap': 'none',
141
+ 'highlightthickness': 0,
142
+ 'width': width,
143
+ 'tabstyle': 'wordprocessor', # new in 8.5
144
+ 'height': idleConf.GetOption(
145
+ 'main', 'EditorWindow', 'height', type='int'),
146
+ }
147
+ self.text = text = MultiCallCreator(Text)(text_frame, **text_options)
148
+ self.top.focused_widget = self.text
149
+
150
+ self.createmenubar()
151
+ self.apply_bindings()
152
+
153
+ self.top.protocol("WM_DELETE_WINDOW", self.close)
154
+ self.top.bind("<<close-window>>", self.close_event)
155
+ if macosx.isAquaTk():
156
+ # Command-W on editor windows doesn't work without this.
157
+ text.bind('<<close-window>>', self.close_event)
158
+ # Some OS X systems have only one mouse button, so use
159
+ # control-click for popup context menus there. For two
160
+ # buttons, AquaTk defines <2> as the right button, not <3>.
161
+ text.bind("<Control-Button-1>",self.right_menu_event)
162
+ text.bind("<2>", self.right_menu_event)
163
+ else:
164
+ # Elsewhere, use right-click for popup menus.
165
+ text.bind("<3>",self.right_menu_event)
166
+
167
+ text.bind('<MouseWheel>', wheel_event)
168
+ text.bind('<Button-4>', wheel_event)
169
+ text.bind('<Button-5>', wheel_event)
170
+ text.bind('<Configure>', self.handle_winconfig)
171
+ text.bind("<<cut>>", self.cut)
172
+ text.bind("<<copy>>", self.copy)
173
+ text.bind("<<paste>>", self.paste)
174
+ text.bind("<<center-insert>>", self.center_insert_event)
175
+ text.bind("<<help>>", self.help_dialog)
176
+ text.bind("<<python-docs>>", self.python_docs)
177
+ text.bind("<<about-idle>>", self.about_dialog)
178
+ text.bind("<<open-config-dialog>>", self.config_dialog)
179
+ text.bind("<<open-module>>", self.open_module_event)
180
+ text.bind("<<do-nothing>>", lambda event: "break")
181
+ text.bind("<<select-all>>", self.select_all)
182
+ text.bind("<<remove-selection>>", self.remove_selection)
183
+ text.bind("<<find>>", self.find_event)
184
+ text.bind("<<find-again>>", self.find_again_event)
185
+ text.bind("<<find-in-files>>", self.find_in_files_event)
186
+ text.bind("<<find-selection>>", self.find_selection_event)
187
+ text.bind("<<replace>>", self.replace_event)
188
+ text.bind("<<goto-line>>", self.goto_line_event)
189
+ text.bind("<<smart-backspace>>",self.smart_backspace_event)
190
+ text.bind("<<newline-and-indent>>",self.newline_and_indent_event)
191
+ text.bind("<<smart-indent>>",self.smart_indent_event)
192
+ self.fregion = fregion = self.FormatRegion(self)
193
+ # self.fregion used in smart_indent_event to access indent_region.
194
+ text.bind("<<indent-region>>", fregion.indent_region_event)
195
+ text.bind("<<dedent-region>>", fregion.dedent_region_event)
196
+ text.bind("<<comment-region>>", fregion.comment_region_event)
197
+ text.bind("<<uncomment-region>>", fregion.uncomment_region_event)
198
+ text.bind("<<tabify-region>>", fregion.tabify_region_event)
199
+ text.bind("<<untabify-region>>", fregion.untabify_region_event)
200
+ indents = self.Indents(self)
201
+ text.bind("<<toggle-tabs>>", indents.toggle_tabs_event)
202
+ text.bind("<<change-indentwidth>>", indents.change_indentwidth_event)
203
+ text.bind("<Left>", self.move_at_edge_if_selection(0))
204
+ text.bind("<Right>", self.move_at_edge_if_selection(1))
205
+ text.bind("<<del-word-left>>", self.del_word_left)
206
+ text.bind("<<del-word-right>>", self.del_word_right)
207
+ text.bind("<<beginning-of-line>>", self.home_callback)
208
+
209
+ if flist:
210
+ flist.inversedict[self] = key
211
+ if key:
212
+ flist.dict[key] = self
213
+ text.bind("<<open-new-window>>", self.new_callback)
214
+ text.bind("<<close-all-windows>>", self.flist.close_all_callback)
215
+ text.bind("<<open-class-browser>>", self.open_module_browser)
216
+ text.bind("<<open-path-browser>>", self.open_path_browser)
217
+ text.bind("<<open-turtle-demo>>", self.open_turtle_demo)
218
+
219
+ self.set_status_bar()
220
+ text_frame.pack(side=LEFT, fill=BOTH, expand=1)
221
+ text_frame.rowconfigure(1, weight=1)
222
+ text_frame.columnconfigure(1, weight=1)
223
+ vbar['command'] = self.handle_yview
224
+ vbar.grid(row=1, column=2, sticky=NSEW)
225
+ text['yscrollcommand'] = vbar.set
226
+ text['font'] = idleConf.GetFont(self.root, 'main', 'EditorWindow')
227
+ text.grid(row=1, column=1, sticky=NSEW)
228
+ text.focus_set()
229
+ self.set_width()
230
+
231
+ # usetabs true -> literal tab characters are used by indent and
232
+ # dedent cmds, possibly mixed with spaces if
233
+ # indentwidth is not a multiple of tabwidth,
234
+ # which will cause Tabnanny to nag!
235
+ # false -> tab characters are converted to spaces by indent
236
+ # and dedent cmds, and ditto TAB keystrokes
237
+ # Although use-spaces=0 can be configured manually in config-main.def,
238
+ # configuration of tabs v. spaces is not supported in the configuration
239
+ # dialog. IDLE promotes the preferred Python indentation: use spaces!
240
+ usespaces = idleConf.GetOption('main', 'Indent',
241
+ 'use-spaces', type='bool')
242
+ self.usetabs = not usespaces
243
+
244
+ # tabwidth is the display width of a literal tab character.
245
+ # CAUTION: telling Tk to use anything other than its default
246
+ # tab setting causes it to use an entirely different tabbing algorithm,
247
+ # treating tab stops as fixed distances from the left margin.
248
+ # Nobody expects this, so for now tabwidth should never be changed.
249
+ self.tabwidth = 8 # must remain 8 until Tk is fixed.
250
+
251
+ # indentwidth is the number of screen characters per indent level.
252
+ # The recommended Python indentation is four spaces.
253
+ self.indentwidth = self.tabwidth
254
+ self.set_notabs_indentwidth()
255
+
256
+ # Store the current value of the insertofftime now so we can restore
257
+ # it if needed.
258
+ if not hasattr(idleConf, 'blink_off_time'):
259
+ idleConf.blink_off_time = self.text['insertofftime']
260
+ self.update_cursor_blink()
261
+
262
+ # When searching backwards for a reliable place to begin parsing,
263
+ # first start num_context_lines[0] lines back, then
264
+ # num_context_lines[1] lines back if that didn't work, and so on.
265
+ # The last value should be huge (larger than the # of lines in a
266
+ # conceivable file).
267
+ # Making the initial values larger slows things down more often.
268
+ self.num_context_lines = 50, 500, 5000000
269
+ self.per = per = self.Percolator(text)
270
+ self.undo = undo = self.UndoDelegator()
271
+ per.insertfilter(undo)
272
+ text.undo_block_start = undo.undo_block_start
273
+ text.undo_block_stop = undo.undo_block_stop
274
+ undo.set_saved_change_hook(self.saved_change_hook)
275
+ # IOBinding implements file I/O and printing functionality
276
+ self.io = io = self.IOBinding(self)
277
+ io.set_filename_change_hook(self.filename_change_hook)
278
+ self.good_load = False
279
+ self.set_indentation_params(False)
280
+ self.color = None # initialized below in self.ResetColorizer
281
+ self.code_context = None # optionally initialized later below
282
+ self.line_numbers = None # optionally initialized later below
283
+ if filename:
284
+ if os.path.exists(filename) and not os.path.isdir(filename):
285
+ if io.loadfile(filename):
286
+ self.good_load = True
287
+ is_py_src = self.ispythonsource(filename)
288
+ self.set_indentation_params(is_py_src)
289
+ else:
290
+ io.set_filename(filename)
291
+ self.good_load = True
292
+
293
+ self.ResetColorizer()
294
+ self.saved_change_hook()
295
+ self.update_recent_files_list()
296
+ self.load_extensions()
297
+ menu = self.menudict.get('window')
298
+ if menu:
299
+ end = menu.index("end")
300
+ if end is None:
301
+ end = -1
302
+ if end >= 0:
303
+ menu.add_separator()
304
+ end = end + 1
305
+ self.wmenu_end = end
306
+ window.register_callback(self.postwindowsmenu)
307
+
308
+ # Some abstractions so IDLE extensions are cross-IDE
309
+ self.askinteger = simpledialog.askinteger
310
+ self.askyesno = messagebox.askyesno
311
+ self.showerror = messagebox.showerror
312
+
313
+ # Add pseudoevents for former extension fixed keys.
314
+ # (This probably needs to be done once in the process.)
315
+ text.event_add('<<autocomplete>>', '<Key-Tab>')
316
+ text.event_add('<<try-open-completions>>', '<KeyRelease-period>',
317
+ '<KeyRelease-slash>', '<KeyRelease-backslash>')
318
+ text.event_add('<<try-open-calltip>>', '<KeyRelease-parenleft>')
319
+ text.event_add('<<refresh-calltip>>', '<KeyRelease-parenright>')
320
+ text.event_add('<<paren-closed>>', '<KeyRelease-parenright>',
321
+ '<KeyRelease-bracketright>', '<KeyRelease-braceright>')
322
+
323
+ # Former extension bindings depends on frame.text being packed
324
+ # (called from self.ResetColorizer()).
325
+ autocomplete = self.AutoComplete(self, self.user_input_insert_tags)
326
+ text.bind("<<autocomplete>>", autocomplete.autocomplete_event)
327
+ text.bind("<<try-open-completions>>",
328
+ autocomplete.try_open_completions_event)
329
+ text.bind("<<force-open-completions>>",
330
+ autocomplete.force_open_completions_event)
331
+ text.bind("<<expand-word>>", self.AutoExpand(self).expand_word_event)
332
+ text.bind("<<format-paragraph>>",
333
+ self.FormatParagraph(self).format_paragraph_event)
334
+ parenmatch = self.ParenMatch(self)
335
+ text.bind("<<flash-paren>>", parenmatch.flash_paren_event)
336
+ text.bind("<<paren-closed>>", parenmatch.paren_closed_event)
337
+ scriptbinding = ScriptBinding(self)
338
+ text.bind("<<check-module>>", scriptbinding.check_module_event)
339
+ text.bind("<<run-module>>", scriptbinding.run_module_event)
340
+ text.bind("<<run-custom>>", scriptbinding.run_custom_event)
341
+ text.bind("<<do-rstrip>>", self.Rstrip(self).do_rstrip)
342
+ self.ctip = ctip = self.Calltip(self)
343
+ text.bind("<<try-open-calltip>>", ctip.try_open_calltip_event)
344
+ #refresh-calltip must come after paren-closed to work right
345
+ text.bind("<<refresh-calltip>>", ctip.refresh_calltip_event)
346
+ text.bind("<<force-open-calltip>>", ctip.force_open_calltip_event)
347
+ text.bind("<<zoom-height>>", self.ZoomHeight(self).zoom_height_event)
348
+ if self.allow_code_context:
349
+ self.code_context = self.CodeContext(self)
350
+ text.bind("<<toggle-code-context>>",
351
+ self.code_context.toggle_code_context_event)
352
+ else:
353
+ self.update_menu_state('options', '*ode*ontext', 'disabled')
354
+ if self.allow_line_numbers:
355
+ self.line_numbers = self.LineNumbers(self)
356
+ if idleConf.GetOption('main', 'EditorWindow',
357
+ 'line-numbers-default', type='bool'):
358
+ self.toggle_line_numbers_event()
359
+ text.bind("<<toggle-line-numbers>>", self.toggle_line_numbers_event)
360
+ else:
361
+ self.update_menu_state('options', '*ine*umbers', 'disabled')
362
+
363
+ def handle_winconfig(self, event=None):
364
+ self.set_width()
365
+
366
+ def set_width(self):
367
+ text = self.text
368
+ inner_padding = sum(map(text.tk.getint, [text.cget('border'),
369
+ text.cget('padx')]))
370
+ pixel_width = text.winfo_width() - 2 * inner_padding
371
+
372
+ # Divide the width of the Text widget by the font width,
373
+ # which is taken to be the width of '0' (zero).
374
+ # http://www.tcl.tk/man/tcl8.6/TkCmd/text.htm#M21
375
+ zero_char_width = \
376
+ Font(text, font=text.cget('font')).measure('0')
377
+ self.width = pixel_width // zero_char_width
378
+
379
+ def new_callback(self, event):
380
+ dirname, basename = self.io.defaultfilename()
381
+ self.flist.new(dirname)
382
+ return "break"
383
+
384
+ def home_callback(self, event):
385
+ if (event.state & 4) != 0 and event.keysym == "Home":
386
+ # state&4==Control. If <Control-Home>, use the Tk binding.
387
+ return None
388
+ if self.text.index("iomark") and \
389
+ self.text.compare("iomark", "<=", "insert lineend") and \
390
+ self.text.compare("insert linestart", "<=", "iomark"):
391
+ # In Shell on input line, go to just after prompt
392
+ insertpt = int(self.text.index("iomark").split(".")[1])
393
+ else:
394
+ line = self.text.get("insert linestart", "insert lineend")
395
+ for insertpt in range(len(line)):
396
+ if line[insertpt] not in (' ','\t'):
397
+ break
398
+ else:
399
+ insertpt=len(line)
400
+ lineat = int(self.text.index("insert").split('.')[1])
401
+ if insertpt == lineat:
402
+ insertpt = 0
403
+ dest = "insert linestart+"+str(insertpt)+"c"
404
+ if (event.state&1) == 0:
405
+ # shift was not pressed
406
+ self.text.tag_remove("sel", "1.0", "end")
407
+ else:
408
+ if not self.text.index("sel.first"):
409
+ # there was no previous selection
410
+ self.text.mark_set("my_anchor", "insert")
411
+ else:
412
+ if self.text.compare(self.text.index("sel.first"), "<",
413
+ self.text.index("insert")):
414
+ self.text.mark_set("my_anchor", "sel.first") # extend back
415
+ else:
416
+ self.text.mark_set("my_anchor", "sel.last") # extend forward
417
+ first = self.text.index(dest)
418
+ last = self.text.index("my_anchor")
419
+ if self.text.compare(first,">",last):
420
+ first,last = last,first
421
+ self.text.tag_remove("sel", "1.0", "end")
422
+ self.text.tag_add("sel", first, last)
423
+ self.text.mark_set("insert", dest)
424
+ self.text.see("insert")
425
+ return "break"
426
+
427
+ def set_status_bar(self):
428
+ self.status_bar = self.MultiStatusBar(self.top)
429
+ sep = Frame(self.top, height=1, borderwidth=1, background='grey75')
430
+ if sys.platform == "darwin":
431
+ # Insert some padding to avoid obscuring some of the statusbar
432
+ # by the resize widget.
433
+ self.status_bar.set_label('_padding1', ' ', side=RIGHT)
434
+ self.status_bar.set_label('column', 'Col: ?', side=RIGHT)
435
+ self.status_bar.set_label('line', 'Ln: ?', side=RIGHT)
436
+ self.status_bar.pack(side=BOTTOM, fill=X)
437
+ sep.pack(side=BOTTOM, fill=X)
438
+ self.text.bind("<<set-line-and-column>>", self.set_line_and_column)
439
+ self.text.event_add("<<set-line-and-column>>",
440
+ "<KeyRelease>", "<ButtonRelease>")
441
+ self.text.after_idle(self.set_line_and_column)
442
+
443
+ def set_line_and_column(self, event=None):
444
+ line, column = self.text.index(INSERT).split('.')
445
+ self.status_bar.set_label('column', 'Col: %s' % column)
446
+ self.status_bar.set_label('line', 'Ln: %s' % line)
447
+
448
+ menu_specs = [
449
+ ("file", "_File"),
450
+ ("edit", "_Edit"),
451
+ ("format", "F_ormat"),
452
+ ("run", "_Run"),
453
+ ("options", "_Options"),
454
+ ("window", "_Window"),
455
+ ("help", "_Help"),
456
+ ]
457
+
458
+
459
+ def createmenubar(self):
460
+ mbar = self.menubar
461
+ self.menudict = menudict = {}
462
+ for name, label in self.menu_specs:
463
+ underline, label = prepstr(label)
464
+ postcommand = getattr(self, f'{name}_menu_postcommand', None)
465
+ menudict[name] = menu = Menu(mbar, name=name, tearoff=0,
466
+ postcommand=postcommand)
467
+ mbar.add_cascade(label=label, menu=menu, underline=underline)
468
+ if macosx.isCarbonTk():
469
+ # Insert the application menu
470
+ menudict['application'] = menu = Menu(mbar, name='apple',
471
+ tearoff=0)
472
+ mbar.add_cascade(label='IDLE', menu=menu)
473
+ self.fill_menus()
474
+ self.recent_files_menu = Menu(self.menubar, tearoff=0)
475
+ self.menudict['file'].insert_cascade(3, label='Recent Files',
476
+ underline=0,
477
+ menu=self.recent_files_menu)
478
+ self.base_helpmenu_length = self.menudict['help'].index(END)
479
+ self.reset_help_menu_entries()
480
+
481
+ def postwindowsmenu(self):
482
+ # Only called when Window menu exists
483
+ menu = self.menudict['window']
484
+ end = menu.index("end")
485
+ if end is None:
486
+ end = -1
487
+ if end > self.wmenu_end:
488
+ menu.delete(self.wmenu_end+1, end)
489
+ window.add_windows_to_menu(menu)
490
+
491
+ def update_menu_label(self, menu, index, label):
492
+ "Update label for menu item at index."
493
+ menuitem = self.menudict[menu]
494
+ menuitem.entryconfig(index, label=label)
495
+
496
+ def update_menu_state(self, menu, index, state):
497
+ "Update state for menu item at index."
498
+ menuitem = self.menudict[menu]
499
+ menuitem.entryconfig(index, state=state)
500
+
501
+ def handle_yview(self, event, *args):
502
+ "Handle scrollbar."
503
+ if event == 'moveto':
504
+ fraction = float(args[0])
505
+ lines = (round(self.getlineno('end') * fraction) -
506
+ self.getlineno('@0,0'))
507
+ event = 'scroll'
508
+ args = (lines, 'units')
509
+ self.text.yview(event, *args)
510
+ return 'break'
511
+
512
+ rmenu = None
513
+
514
+ def right_menu_event(self, event):
515
+ text = self.text
516
+ newdex = text.index(f'@{event.x},{event.y}')
517
+ try:
518
+ in_selection = (text.compare('sel.first', '<=', newdex) and
519
+ text.compare(newdex, '<=', 'sel.last'))
520
+ except TclError:
521
+ in_selection = False
522
+ if not in_selection:
523
+ text.tag_remove("sel", "1.0", "end")
524
+ text.mark_set("insert", newdex)
525
+ if not self.rmenu:
526
+ self.make_rmenu()
527
+ rmenu = self.rmenu
528
+ self.event = event
529
+ iswin = sys.platform[:3] == 'win'
530
+ if iswin:
531
+ text.config(cursor="arrow")
532
+
533
+ for item in self.rmenu_specs:
534
+ try:
535
+ label, eventname, verify_state = item
536
+ except ValueError: # see issue1207589
537
+ continue
538
+
539
+ if verify_state is None:
540
+ continue
541
+ state = getattr(self, verify_state)()
542
+ rmenu.entryconfigure(label, state=state)
543
+
544
+ rmenu.tk_popup(event.x_root, event.y_root)
545
+ if iswin:
546
+ self.text.config(cursor="ibeam")
547
+ return "break"
548
+
549
+ rmenu_specs = [
550
+ # ("Label", "<<virtual-event>>", "statefuncname"), ...
551
+ ("Close", "<<close-window>>", None), # Example
552
+ ]
553
+
554
+ def make_rmenu(self):
555
+ rmenu = Menu(self.text, tearoff=0)
556
+ for item in self.rmenu_specs:
557
+ label, eventname = item[0], item[1]
558
+ if label is not None:
559
+ def command(text=self.text, eventname=eventname):
560
+ text.event_generate(eventname)
561
+ rmenu.add_command(label=label, command=command)
562
+ else:
563
+ rmenu.add_separator()
564
+ self.rmenu = rmenu
565
+
566
+ def rmenu_check_cut(self):
567
+ return self.rmenu_check_copy()
568
+
569
+ def rmenu_check_copy(self):
570
+ try:
571
+ indx = self.text.index('sel.first')
572
+ except TclError:
573
+ return 'disabled'
574
+ else:
575
+ return 'normal' if indx else 'disabled'
576
+
577
+ def rmenu_check_paste(self):
578
+ try:
579
+ self.text.tk.call('tk::GetSelection', self.text, 'CLIPBOARD')
580
+ except TclError:
581
+ return 'disabled'
582
+ else:
583
+ return 'normal'
584
+
585
+ def about_dialog(self, event=None):
586
+ "Handle Help 'About IDLE' event."
587
+ # Synchronize with macosx.overrideRootMenu.about_dialog.
588
+ help_about.AboutDialog(self.top)
589
+ return "break"
590
+
591
+ def config_dialog(self, event=None):
592
+ "Handle Options 'Configure IDLE' event."
593
+ # Synchronize with macosx.overrideRootMenu.config_dialog.
594
+ configdialog.ConfigDialog(self.top,'Settings')
595
+ return "break"
596
+
597
+ def help_dialog(self, event=None):
598
+ "Handle Help 'IDLE Help' event."
599
+ # Synchronize with macosx.overrideRootMenu.help_dialog.
600
+ if self.root:
601
+ parent = self.root
602
+ else:
603
+ parent = self.top
604
+ help.show_idlehelp(parent)
605
+ return "break"
606
+
607
+ def python_docs(self, event=None):
608
+ if sys.platform[:3] == 'win':
609
+ try:
610
+ os.startfile(self.help_url)
611
+ except OSError as why:
612
+ messagebox.showerror(title='Document Start Failure',
613
+ message=str(why), parent=self.text)
614
+ else:
615
+ webbrowser.open(self.help_url)
616
+ return "break"
617
+
618
+ def cut(self,event):
619
+ self.text.event_generate("<<Cut>>")
620
+ return "break"
621
+
622
+ def copy(self,event):
623
+ if not self.text.tag_ranges("sel"):
624
+ # There is no selection, so do nothing and maybe interrupt.
625
+ return None
626
+ self.text.event_generate("<<Copy>>")
627
+ return "break"
628
+
629
+ def paste(self,event):
630
+ self.text.event_generate("<<Paste>>")
631
+ self.text.see("insert")
632
+ return "break"
633
+
634
+ def select_all(self, event=None):
635
+ self.text.tag_add("sel", "1.0", "end-1c")
636
+ self.text.mark_set("insert", "1.0")
637
+ self.text.see("insert")
638
+ return "break"
639
+
640
+ def remove_selection(self, event=None):
641
+ self.text.tag_remove("sel", "1.0", "end")
642
+ self.text.see("insert")
643
+ return "break"
644
+
645
+ def move_at_edge_if_selection(self, edge_index):
646
+ """Cursor move begins at start or end of selection
647
+
648
+ When a left/right cursor key is pressed create and return to Tkinter a
649
+ function which causes a cursor move from the associated edge of the
650
+ selection.
651
+
652
+ """
653
+ self_text_index = self.text.index
654
+ self_text_mark_set = self.text.mark_set
655
+ edges_table = ("sel.first+1c", "sel.last-1c")
656
+ def move_at_edge(event):
657
+ if (event.state & 5) == 0: # no shift(==1) or control(==4) pressed
658
+ try:
659
+ self_text_index("sel.first")
660
+ self_text_mark_set("insert", edges_table[edge_index])
661
+ except TclError:
662
+ pass
663
+ return move_at_edge
664
+
665
+ def del_word_left(self, event):
666
+ self.text.event_generate('<Meta-Delete>')
667
+ return "break"
668
+
669
+ def del_word_right(self, event):
670
+ self.text.event_generate('<Meta-d>')
671
+ return "break"
672
+
673
+ def find_event(self, event):
674
+ search.find(self.text)
675
+ return "break"
676
+
677
+ def find_again_event(self, event):
678
+ search.find_again(self.text)
679
+ return "break"
680
+
681
+ def find_selection_event(self, event):
682
+ search.find_selection(self.text)
683
+ return "break"
684
+
685
+ def find_in_files_event(self, event):
686
+ grep.grep(self.text, self.io, self.flist)
687
+ return "break"
688
+
689
+ def replace_event(self, event):
690
+ replace.replace(self.text)
691
+ return "break"
692
+
693
+ def goto_line_event(self, event):
694
+ text = self.text
695
+ lineno = query.Goto(
696
+ text, "Go To Line",
697
+ "Enter a positive integer\n"
698
+ "('big' = end of file):"
699
+ ).result
700
+ if lineno is not None:
701
+ text.tag_remove("sel", "1.0", "end")
702
+ text.mark_set("insert", f'{lineno}.0')
703
+ text.see("insert")
704
+ self.set_line_and_column()
705
+ return "break"
706
+
707
+ def open_module(self):
708
+ """Get module name from user and open it.
709
+
710
+ Return module path or None for calls by open_module_browser
711
+ when latter is not invoked in named editor window.
712
+ """
713
+ # XXX This, open_module_browser, and open_path_browser
714
+ # would fit better in iomenu.IOBinding.
715
+ try:
716
+ name = self.text.get("sel.first", "sel.last").strip()
717
+ except TclError:
718
+ name = ''
719
+ file_path = query.ModuleName(
720
+ self.text, "Open Module",
721
+ "Enter the name of a Python module\n"
722
+ "to search on sys.path and open:",
723
+ name).result
724
+ if file_path is not None:
725
+ if self.flist:
726
+ self.flist.open(file_path)
727
+ else:
728
+ self.io.loadfile(file_path)
729
+ return file_path
730
+
731
+ def open_module_event(self, event):
732
+ self.open_module()
733
+ return "break"
734
+
735
+ def open_module_browser(self, event=None):
736
+ filename = self.io.filename
737
+ if not (self.__class__.__name__ == 'PyShellEditorWindow'
738
+ and filename):
739
+ filename = self.open_module()
740
+ if filename is None:
741
+ return "break"
742
+ from idlelib import browser
743
+ browser.ModuleBrowser(self.root, filename)
744
+ return "break"
745
+
746
+ def open_path_browser(self, event=None):
747
+ from idlelib import pathbrowser
748
+ pathbrowser.PathBrowser(self.root)
749
+ return "break"
750
+
751
+ def open_turtle_demo(self, event = None):
752
+ import subprocess
753
+
754
+ cmd = [sys.executable,
755
+ '-c',
756
+ 'from turtledemo.__main__ import main; main()']
757
+ subprocess.Popen(cmd, shell=False)
758
+ return "break"
759
+
760
+ def gotoline(self, lineno):
761
+ if lineno is not None and lineno > 0:
762
+ self.text.mark_set("insert", "%d.0" % lineno)
763
+ self.text.tag_remove("sel", "1.0", "end")
764
+ self.text.tag_add("sel", "insert", "insert +1l")
765
+ self.center()
766
+
767
+ def ispythonsource(self, filename):
768
+ if not filename or os.path.isdir(filename):
769
+ return True
770
+ base, ext = os.path.splitext(os.path.basename(filename))
771
+ if os.path.normcase(ext) in py_extensions:
772
+ return True
773
+ line = self.text.get('1.0', '1.0 lineend')
774
+ return line.startswith('#!') and 'python' in line
775
+
776
+ def close_hook(self):
777
+ if self.flist:
778
+ self.flist.unregister_maybe_terminate(self)
779
+ self.flist = None
780
+
781
+ def set_close_hook(self, close_hook):
782
+ self.close_hook = close_hook
783
+
784
+ def filename_change_hook(self):
785
+ if self.flist:
786
+ self.flist.filename_changed_edit(self)
787
+ self.saved_change_hook()
788
+ self.top.update_windowlist_registry(self)
789
+ self.ResetColorizer()
790
+
791
+ def _addcolorizer(self):
792
+ if self.color:
793
+ return
794
+ if self.ispythonsource(self.io.filename):
795
+ self.color = self.ColorDelegator()
796
+ # can add more colorizers here...
797
+ if self.color:
798
+ self.per.insertfilterafter(filter=self.color, after=self.undo)
799
+
800
+ def _rmcolorizer(self):
801
+ if not self.color:
802
+ return
803
+ self.color.removecolors()
804
+ self.per.removefilter(self.color)
805
+ self.color = None
806
+
807
+ def ResetColorizer(self):
808
+ "Update the color theme"
809
+ # Called from self.filename_change_hook and from configdialog.py
810
+ self._rmcolorizer()
811
+ self._addcolorizer()
812
+ EditorWindow.color_config(self.text)
813
+
814
+ if self.code_context is not None:
815
+ self.code_context.update_highlight_colors()
816
+
817
+ if self.line_numbers is not None:
818
+ self.line_numbers.update_colors()
819
+
820
+ IDENTCHARS = string.ascii_letters + string.digits + "_"
821
+
822
+ def colorize_syntax_error(self, text, pos):
823
+ text.tag_add("ERROR", pos)
824
+ char = text.get(pos)
825
+ if char and char in self.IDENTCHARS:
826
+ text.tag_add("ERROR", pos + " wordstart", pos)
827
+ if '\n' == text.get(pos): # error at line end
828
+ text.mark_set("insert", pos)
829
+ else:
830
+ text.mark_set("insert", pos + "+1c")
831
+ text.see(pos)
832
+
833
+ def update_cursor_blink(self):
834
+ "Update the cursor blink configuration."
835
+ cursorblink = idleConf.GetOption(
836
+ 'main', 'EditorWindow', 'cursor-blink', type='bool')
837
+ if not cursorblink:
838
+ self.text['insertofftime'] = 0
839
+ else:
840
+ # Restore the original value
841
+ self.text['insertofftime'] = idleConf.blink_off_time
842
+
843
+ def ResetFont(self):
844
+ "Update the text widgets' font if it is changed"
845
+ # Called from configdialog.py
846
+
847
+ # Update the code context widget first, since its height affects
848
+ # the height of the text widget. This avoids double re-rendering.
849
+ if self.code_context is not None:
850
+ self.code_context.update_font()
851
+ # Next, update the line numbers widget, since its width affects
852
+ # the width of the text widget.
853
+ if self.line_numbers is not None:
854
+ self.line_numbers.update_font()
855
+ # Finally, update the main text widget.
856
+ new_font = idleConf.GetFont(self.root, 'main', 'EditorWindow')
857
+ self.text['font'] = new_font
858
+ self.set_width()
859
+
860
+ def RemoveKeybindings(self):
861
+ "Remove the keybindings before they are changed."
862
+ # Called from configdialog.py
863
+ self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
864
+ for event, keylist in keydefs.items():
865
+ self.text.event_delete(event, *keylist)
866
+ for extensionName in self.get_standard_extension_names():
867
+ xkeydefs = idleConf.GetExtensionBindings(extensionName)
868
+ if xkeydefs:
869
+ for event, keylist in xkeydefs.items():
870
+ self.text.event_delete(event, *keylist)
871
+
872
+ def ApplyKeybindings(self):
873
+ "Update the keybindings after they are changed"
874
+ # Called from configdialog.py
875
+ self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
876
+ self.apply_bindings()
877
+ for extensionName in self.get_standard_extension_names():
878
+ xkeydefs = idleConf.GetExtensionBindings(extensionName)
879
+ if xkeydefs:
880
+ self.apply_bindings(xkeydefs)
881
+ #update menu accelerators
882
+ menuEventDict = {}
883
+ for menu in self.mainmenu.menudefs:
884
+ menuEventDict[menu[0]] = {}
885
+ for item in menu[1]:
886
+ if item:
887
+ menuEventDict[menu[0]][prepstr(item[0])[1]] = item[1]
888
+ for menubarItem in self.menudict:
889
+ menu = self.menudict[menubarItem]
890
+ end = menu.index(END)
891
+ if end is None:
892
+ # Skip empty menus
893
+ continue
894
+ end += 1
895
+ for index in range(0, end):
896
+ if menu.type(index) == 'command':
897
+ accel = menu.entrycget(index, 'accelerator')
898
+ if accel:
899
+ itemName = menu.entrycget(index, 'label')
900
+ event = ''
901
+ if menubarItem in menuEventDict:
902
+ if itemName in menuEventDict[menubarItem]:
903
+ event = menuEventDict[menubarItem][itemName]
904
+ if event:
905
+ accel = get_accelerator(keydefs, event)
906
+ menu.entryconfig(index, accelerator=accel)
907
+
908
+ def set_notabs_indentwidth(self):
909
+ "Update the indentwidth if changed and not using tabs in this window"
910
+ # Called from configdialog.py
911
+ if not self.usetabs:
912
+ self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces',
913
+ type='int')
914
+
915
+ def reset_help_menu_entries(self):
916
+ "Update the additional help entries on the Help menu"
917
+ help_list = idleConf.GetAllExtraHelpSourcesList()
918
+ helpmenu = self.menudict['help']
919
+ # first delete the extra help entries, if any
920
+ helpmenu_length = helpmenu.index(END)
921
+ if helpmenu_length > self.base_helpmenu_length:
922
+ helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length)
923
+ # then rebuild them
924
+ if help_list:
925
+ helpmenu.add_separator()
926
+ for entry in help_list:
927
+ cmd = self.__extra_help_callback(entry[1])
928
+ helpmenu.add_command(label=entry[0], command=cmd)
929
+ # and update the menu dictionary
930
+ self.menudict['help'] = helpmenu
931
+
932
+ def __extra_help_callback(self, helpfile):
933
+ "Create a callback with the helpfile value frozen at definition time"
934
+ def display_extra_help(helpfile=helpfile):
935
+ if not helpfile.startswith(('www', 'http')):
936
+ helpfile = os.path.normpath(helpfile)
937
+ if sys.platform[:3] == 'win':
938
+ try:
939
+ os.startfile(helpfile)
940
+ except OSError as why:
941
+ messagebox.showerror(title='Document Start Failure',
942
+ message=str(why), parent=self.text)
943
+ else:
944
+ webbrowser.open(helpfile)
945
+ return display_extra_help
946
+
947
+ def update_recent_files_list(self, new_file=None):
948
+ "Load and update the recent files list and menus"
949
+ # TODO: move to iomenu.
950
+ rf_list = []
951
+ file_path = self.recent_files_path
952
+ if file_path and os.path.exists(file_path):
953
+ with open(file_path, 'r',
954
+ encoding='utf_8', errors='replace') as rf_list_file:
955
+ rf_list = rf_list_file.readlines()
956
+ if new_file:
957
+ new_file = os.path.abspath(new_file) + '\n'
958
+ if new_file in rf_list:
959
+ rf_list.remove(new_file) # move to top
960
+ rf_list.insert(0, new_file)
961
+ # clean and save the recent files list
962
+ bad_paths = []
963
+ for path in rf_list:
964
+ if '\0' in path or not os.path.exists(path[0:-1]):
965
+ bad_paths.append(path)
966
+ rf_list = [path for path in rf_list if path not in bad_paths]
967
+ ulchars = "1234567890ABCDEFGHIJK"
968
+ rf_list = rf_list[0:len(ulchars)]
969
+ if file_path:
970
+ try:
971
+ with open(file_path, 'w',
972
+ encoding='utf_8', errors='replace') as rf_file:
973
+ rf_file.writelines(rf_list)
974
+ except OSError as err:
975
+ if not getattr(self.root, "recentfiles_message", False):
976
+ self.root.recentfiles_message = True
977
+ messagebox.showwarning(title='IDLE Warning',
978
+ message="Cannot save Recent Files list to disk.\n"
979
+ f" {err}\n"
980
+ "Select OK to continue.",
981
+ parent=self.text)
982
+ # for each edit window instance, construct the recent files menu
983
+ for instance in self.top.instance_dict:
984
+ menu = instance.recent_files_menu
985
+ menu.delete(0, END) # clear, and rebuild:
986
+ for i, file_name in enumerate(rf_list):
987
+ file_name = file_name.rstrip() # zap \n
988
+ callback = instance.__recent_file_callback(file_name)
989
+ menu.add_command(label=ulchars[i] + " " + file_name,
990
+ command=callback,
991
+ underline=0)
992
+
993
+ def __recent_file_callback(self, file_name):
994
+ def open_recent_file(fn_closure=file_name):
995
+ self.io.open(editFile=fn_closure)
996
+ return open_recent_file
997
+
998
+ def saved_change_hook(self):
999
+ short = self.short_title()
1000
+ long = self.long_title()
1001
+ if short and long:
1002
+ title = short + " - " + long + _py_version
1003
+ elif short:
1004
+ title = short
1005
+ elif long:
1006
+ title = long
1007
+ else:
1008
+ title = "untitled"
1009
+ icon = short or long or title
1010
+ if not self.get_saved():
1011
+ title = "*%s*" % title
1012
+ icon = "*%s" % icon
1013
+ self.top.wm_title(title)
1014
+ self.top.wm_iconname(icon)
1015
+
1016
+ def get_saved(self):
1017
+ return self.undo.get_saved()
1018
+
1019
+ def set_saved(self, flag):
1020
+ self.undo.set_saved(flag)
1021
+
1022
+ def reset_undo(self):
1023
+ self.undo.reset_undo()
1024
+
1025
+ def short_title(self):
1026
+ filename = self.io.filename
1027
+ return os.path.basename(filename) if filename else "untitled"
1028
+
1029
+ def long_title(self):
1030
+ return self.io.filename or ""
1031
+
1032
+ def center_insert_event(self, event):
1033
+ self.center()
1034
+ return "break"
1035
+
1036
+ def center(self, mark="insert"):
1037
+ text = self.text
1038
+ top, bot = self.getwindowlines()
1039
+ lineno = self.getlineno(mark)
1040
+ height = bot - top
1041
+ newtop = max(1, lineno - height//2)
1042
+ text.yview(float(newtop))
1043
+
1044
+ def getwindowlines(self):
1045
+ text = self.text
1046
+ top = self.getlineno("@0,0")
1047
+ bot = self.getlineno("@0,65535")
1048
+ if top == bot and text.winfo_height() == 1:
1049
+ # Geometry manager hasn't run yet
1050
+ height = int(text['height'])
1051
+ bot = top + height - 1
1052
+ return top, bot
1053
+
1054
+ def getlineno(self, mark="insert"):
1055
+ text = self.text
1056
+ return int(float(text.index(mark)))
1057
+
1058
+ def get_geometry(self):
1059
+ "Return (width, height, x, y)"
1060
+ geom = self.top.wm_geometry()
1061
+ m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
1062
+ return list(map(int, m.groups()))
1063
+
1064
+ def close_event(self, event):
1065
+ self.close()
1066
+ return "break"
1067
+
1068
+ def maybesave(self):
1069
+ if self.io:
1070
+ if not self.get_saved():
1071
+ if self.top.state()!='normal':
1072
+ self.top.deiconify()
1073
+ self.top.lower()
1074
+ self.top.lift()
1075
+ return self.io.maybesave()
1076
+
1077
+ def close(self):
1078
+ try:
1079
+ reply = self.maybesave()
1080
+ if str(reply) != "cancel":
1081
+ self._close()
1082
+ return reply
1083
+ except AttributeError: # bpo-35379: close called twice
1084
+ pass
1085
+
1086
+ def _close(self):
1087
+ if self.io.filename:
1088
+ self.update_recent_files_list(new_file=self.io.filename)
1089
+ window.unregister_callback(self.postwindowsmenu)
1090
+ self.unload_extensions()
1091
+ self.io.close()
1092
+ self.io = None
1093
+ self.undo = None
1094
+ if self.color:
1095
+ self.color.close()
1096
+ self.color = None
1097
+ self.text = None
1098
+ self.tkinter_vars = None
1099
+ self.per.close()
1100
+ self.per = None
1101
+ self.top.destroy()
1102
+ if self.close_hook:
1103
+ # unless override: unregister from flist, terminate if last window
1104
+ self.close_hook()
1105
+
1106
+ def load_extensions(self):
1107
+ self.extensions = {}
1108
+ self.load_standard_extensions()
1109
+
1110
+ def unload_extensions(self):
1111
+ for ins in list(self.extensions.values()):
1112
+ if hasattr(ins, "close"):
1113
+ ins.close()
1114
+ self.extensions = {}
1115
+
1116
+ def load_standard_extensions(self):
1117
+ for name in self.get_standard_extension_names():
1118
+ try:
1119
+ self.load_extension(name)
1120
+ except:
1121
+ print("Failed to load extension", repr(name))
1122
+ traceback.print_exc()
1123
+
1124
+ def get_standard_extension_names(self):
1125
+ return idleConf.GetExtensions(editor_only=True)
1126
+
1127
+ extfiles = { # Map built-in config-extension section names to file names.
1128
+ 'ZzDummy': 'zzdummy',
1129
+ }
1130
+
1131
+ def load_extension(self, name):
1132
+ fname = self.extfiles.get(name, name)
1133
+ try:
1134
+ try:
1135
+ mod = importlib.import_module('.' + fname, package=__package__)
1136
+ except (ImportError, TypeError):
1137
+ mod = importlib.import_module(fname)
1138
+ except ImportError:
1139
+ print("\nFailed to import extension: ", name)
1140
+ raise
1141
+ cls = getattr(mod, name)
1142
+ keydefs = idleConf.GetExtensionBindings(name)
1143
+ if hasattr(cls, "menudefs"):
1144
+ self.fill_menus(cls.menudefs, keydefs)
1145
+ ins = cls(self)
1146
+ self.extensions[name] = ins
1147
+ if keydefs:
1148
+ self.apply_bindings(keydefs)
1149
+ for vevent in keydefs:
1150
+ methodname = vevent.replace("-", "_")
1151
+ while methodname[:1] == '<':
1152
+ methodname = methodname[1:]
1153
+ while methodname[-1:] == '>':
1154
+ methodname = methodname[:-1]
1155
+ methodname = methodname + "_event"
1156
+ if hasattr(ins, methodname):
1157
+ self.text.bind(vevent, getattr(ins, methodname))
1158
+
1159
+ def apply_bindings(self, keydefs=None):
1160
+ if keydefs is None:
1161
+ keydefs = self.mainmenu.default_keydefs
1162
+ text = self.text
1163
+ text.keydefs = keydefs
1164
+ for event, keylist in keydefs.items():
1165
+ if keylist:
1166
+ text.event_add(event, *keylist)
1167
+
1168
+ def fill_menus(self, menudefs=None, keydefs=None):
1169
+ """Add appropriate entries to the menus and submenus
1170
+
1171
+ Menus that are absent or None in self.menudict are ignored.
1172
+ """
1173
+ if menudefs is None:
1174
+ menudefs = self.mainmenu.menudefs
1175
+ if keydefs is None:
1176
+ keydefs = self.mainmenu.default_keydefs
1177
+ menudict = self.menudict
1178
+ text = self.text
1179
+ for mname, entrylist in menudefs:
1180
+ menu = menudict.get(mname)
1181
+ if not menu:
1182
+ continue
1183
+ for entry in entrylist:
1184
+ if not entry:
1185
+ menu.add_separator()
1186
+ else:
1187
+ label, eventname = entry
1188
+ checkbutton = (label[:1] == '!')
1189
+ if checkbutton:
1190
+ label = label[1:]
1191
+ underline, label = prepstr(label)
1192
+ accelerator = get_accelerator(keydefs, eventname)
1193
+ def command(text=text, eventname=eventname):
1194
+ text.event_generate(eventname)
1195
+ if checkbutton:
1196
+ var = self.get_var_obj(eventname, BooleanVar)
1197
+ menu.add_checkbutton(label=label, underline=underline,
1198
+ command=command, accelerator=accelerator,
1199
+ variable=var)
1200
+ else:
1201
+ menu.add_command(label=label, underline=underline,
1202
+ command=command,
1203
+ accelerator=accelerator)
1204
+
1205
+ def getvar(self, name):
1206
+ var = self.get_var_obj(name)
1207
+ if var:
1208
+ value = var.get()
1209
+ return value
1210
+ else:
1211
+ raise NameError(name)
1212
+
1213
+ def setvar(self, name, value, vartype=None):
1214
+ var = self.get_var_obj(name, vartype)
1215
+ if var:
1216
+ var.set(value)
1217
+ else:
1218
+ raise NameError(name)
1219
+
1220
+ def get_var_obj(self, name, vartype=None):
1221
+ var = self.tkinter_vars.get(name)
1222
+ if not var and vartype:
1223
+ # create a Tkinter variable object with self.text as master:
1224
+ self.tkinter_vars[name] = var = vartype(self.text)
1225
+ return var
1226
+
1227
+ # Tk implementations of "virtual text methods" -- each platform
1228
+ # reusing IDLE's support code needs to define these for its GUI's
1229
+ # flavor of widget.
1230
+
1231
+ # Is character at text_index in a Python string? Return 0 for
1232
+ # "guaranteed no", true for anything else. This info is expensive
1233
+ # to compute ab initio, but is probably already known by the
1234
+ # platform's colorizer.
1235
+
1236
+ def is_char_in_string(self, text_index):
1237
+ if self.color:
1238
+ # Return true iff colorizer hasn't (re)gotten this far
1239
+ # yet, or the character is tagged as being in a string
1240
+ return self.text.tag_prevrange("TODO", text_index) or \
1241
+ "STRING" in self.text.tag_names(text_index)
1242
+ else:
1243
+ # The colorizer is missing: assume the worst
1244
+ return 1
1245
+
1246
+ # If a selection is defined in the text widget, return (start,
1247
+ # end) as Tkinter text indices, otherwise return (None, None)
1248
+ def get_selection_indices(self):
1249
+ try:
1250
+ first = self.text.index("sel.first")
1251
+ last = self.text.index("sel.last")
1252
+ return first, last
1253
+ except TclError:
1254
+ return None, None
1255
+
1256
+ # Return the text widget's current view of what a tab stop means
1257
+ # (equivalent width in spaces).
1258
+
1259
+ def get_tk_tabwidth(self):
1260
+ current = self.text['tabs'] or TK_TABWIDTH_DEFAULT
1261
+ return int(current)
1262
+
1263
+ # Set the text widget's current view of what a tab stop means.
1264
+
1265
+ def set_tk_tabwidth(self, newtabwidth):
1266
+ text = self.text
1267
+ if self.get_tk_tabwidth() != newtabwidth:
1268
+ # Set text widget tab width
1269
+ pixels = text.tk.call("font", "measure", text["font"],
1270
+ "-displayof", text.master,
1271
+ "n" * newtabwidth)
1272
+ text.configure(tabs=pixels)
1273
+
1274
+ ### begin autoindent code ### (configuration was moved to beginning of class)
1275
+
1276
+ def set_indentation_params(self, is_py_src, guess=True):
1277
+ if is_py_src and guess:
1278
+ i = self.guess_indent()
1279
+ if 2 <= i <= 8:
1280
+ self.indentwidth = i
1281
+ if self.indentwidth != self.tabwidth:
1282
+ self.usetabs = False
1283
+ self.set_tk_tabwidth(self.tabwidth)
1284
+
1285
+ def smart_backspace_event(self, event):
1286
+ text = self.text
1287
+ first, last = self.get_selection_indices()
1288
+ if first and last:
1289
+ text.delete(first, last)
1290
+ text.mark_set("insert", first)
1291
+ return "break"
1292
+ # Delete whitespace left, until hitting a real char or closest
1293
+ # preceding virtual tab stop.
1294
+ chars = text.get("insert linestart", "insert")
1295
+ if chars == '':
1296
+ if text.compare("insert", ">", "1.0"):
1297
+ # easy: delete preceding newline
1298
+ text.delete("insert-1c")
1299
+ else:
1300
+ text.bell() # at start of buffer
1301
+ return "break"
1302
+ if chars[-1] not in " \t":
1303
+ # easy: delete preceding real char
1304
+ text.delete("insert-1c")
1305
+ return "break"
1306
+ # Ick. It may require *inserting* spaces if we back up over a
1307
+ # tab character! This is written to be clear, not fast.
1308
+ tabwidth = self.tabwidth
1309
+ have = len(chars.expandtabs(tabwidth))
1310
+ assert have > 0
1311
+ want = ((have - 1) // self.indentwidth) * self.indentwidth
1312
+ # Debug prompt is multilined....
1313
+ ncharsdeleted = 0
1314
+ while True:
1315
+ chars = chars[:-1]
1316
+ ncharsdeleted = ncharsdeleted + 1
1317
+ have = len(chars.expandtabs(tabwidth))
1318
+ if have <= want or chars[-1] not in " \t":
1319
+ break
1320
+ text.undo_block_start()
1321
+ text.delete("insert-%dc" % ncharsdeleted, "insert")
1322
+ if have < want:
1323
+ text.insert("insert", ' ' * (want - have),
1324
+ self.user_input_insert_tags)
1325
+ text.undo_block_stop()
1326
+ return "break"
1327
+
1328
+ def smart_indent_event(self, event):
1329
+ # if intraline selection:
1330
+ # delete it
1331
+ # elif multiline selection:
1332
+ # do indent-region
1333
+ # else:
1334
+ # indent one level
1335
+ text = self.text
1336
+ first, last = self.get_selection_indices()
1337
+ text.undo_block_start()
1338
+ try:
1339
+ if first and last:
1340
+ if index2line(first) != index2line(last):
1341
+ return self.fregion.indent_region_event(event)
1342
+ text.delete(first, last)
1343
+ text.mark_set("insert", first)
1344
+ prefix = text.get("insert linestart", "insert")
1345
+ raw, effective = get_line_indent(prefix, self.tabwidth)
1346
+ if raw == len(prefix):
1347
+ # only whitespace to the left
1348
+ self.reindent_to(effective + self.indentwidth)
1349
+ else:
1350
+ # tab to the next 'stop' within or to right of line's text:
1351
+ if self.usetabs:
1352
+ pad = '\t'
1353
+ else:
1354
+ effective = len(prefix.expandtabs(self.tabwidth))
1355
+ n = self.indentwidth
1356
+ pad = ' ' * (n - effective % n)
1357
+ text.insert("insert", pad, self.user_input_insert_tags)
1358
+ text.see("insert")
1359
+ return "break"
1360
+ finally:
1361
+ text.undo_block_stop()
1362
+
1363
+ def newline_and_indent_event(self, event):
1364
+ """Insert a newline and indentation after Enter keypress event.
1365
+
1366
+ Properly position the cursor on the new line based on information
1367
+ from the current line. This takes into account if the current line
1368
+ is a shell prompt, is empty, has selected text, contains a block
1369
+ opener, contains a block closer, is a continuation line, or
1370
+ is inside a string.
1371
+ """
1372
+ text = self.text
1373
+ first, last = self.get_selection_indices()
1374
+ text.undo_block_start()
1375
+ try: # Close undo block and expose new line in finally clause.
1376
+ if first and last:
1377
+ text.delete(first, last)
1378
+ text.mark_set("insert", first)
1379
+ line = text.get("insert linestart", "insert")
1380
+
1381
+ # Count leading whitespace for indent size.
1382
+ i, n = 0, len(line)
1383
+ while i < n and line[i] in " \t":
1384
+ i += 1
1385
+ if i == n:
1386
+ # The cursor is in or at leading indentation in a continuation
1387
+ # line; just inject an empty line at the start.
1388
+ text.insert("insert linestart", '\n',
1389
+ self.user_input_insert_tags)
1390
+ return "break"
1391
+ indent = line[:i]
1392
+
1393
+ # Strip whitespace before insert point unless it's in the prompt.
1394
+ i = 0
1395
+ while line and line[-1] in " \t":
1396
+ line = line[:-1]
1397
+ i += 1
1398
+ if i:
1399
+ text.delete("insert - %d chars" % i, "insert")
1400
+
1401
+ # Strip whitespace after insert point.
1402
+ while text.get("insert") in " \t":
1403
+ text.delete("insert")
1404
+
1405
+ # Insert new line.
1406
+ text.insert("insert", '\n', self.user_input_insert_tags)
1407
+
1408
+ # Adjust indentation for continuations and block open/close.
1409
+ # First need to find the last statement.
1410
+ lno = index2line(text.index('insert'))
1411
+ y = pyparse.Parser(self.indentwidth, self.tabwidth)
1412
+ if not self.prompt_last_line:
1413
+ for context in self.num_context_lines:
1414
+ startat = max(lno - context, 1)
1415
+ startatindex = repr(startat) + ".0"
1416
+ rawtext = text.get(startatindex, "insert")
1417
+ y.set_code(rawtext)
1418
+ bod = y.find_good_parse_start(
1419
+ self._build_char_in_string_func(startatindex))
1420
+ if bod is not None or startat == 1:
1421
+ break
1422
+ y.set_lo(bod or 0)
1423
+ else:
1424
+ r = text.tag_prevrange("console", "insert")
1425
+ if r:
1426
+ startatindex = r[1]
1427
+ else:
1428
+ startatindex = "1.0"
1429
+ rawtext = text.get(startatindex, "insert")
1430
+ y.set_code(rawtext)
1431
+ y.set_lo(0)
1432
+
1433
+ c = y.get_continuation_type()
1434
+ if c != pyparse.C_NONE:
1435
+ # The current statement hasn't ended yet.
1436
+ if c == pyparse.C_STRING_FIRST_LINE:
1437
+ # After the first line of a string do not indent at all.
1438
+ pass
1439
+ elif c == pyparse.C_STRING_NEXT_LINES:
1440
+ # Inside a string which started before this line;
1441
+ # just mimic the current indent.
1442
+ text.insert("insert", indent, self.user_input_insert_tags)
1443
+ elif c == pyparse.C_BRACKET:
1444
+ # Line up with the first (if any) element of the
1445
+ # last open bracket structure; else indent one
1446
+ # level beyond the indent of the line with the
1447
+ # last open bracket.
1448
+ self.reindent_to(y.compute_bracket_indent())
1449
+ elif c == pyparse.C_BACKSLASH:
1450
+ # If more than one line in this statement already, just
1451
+ # mimic the current indent; else if initial line
1452
+ # has a start on an assignment stmt, indent to
1453
+ # beyond leftmost =; else to beyond first chunk of
1454
+ # non-whitespace on initial line.
1455
+ if y.get_num_lines_in_stmt() > 1:
1456
+ text.insert("insert", indent,
1457
+ self.user_input_insert_tags)
1458
+ else:
1459
+ self.reindent_to(y.compute_backslash_indent())
1460
+ else:
1461
+ assert 0, "bogus continuation type %r" % (c,)
1462
+ return "break"
1463
+
1464
+ # This line starts a brand new statement; indent relative to
1465
+ # indentation of initial line of closest preceding
1466
+ # interesting statement.
1467
+ indent = y.get_base_indent_string()
1468
+ text.insert("insert", indent, self.user_input_insert_tags)
1469
+ if y.is_block_opener():
1470
+ self.smart_indent_event(event)
1471
+ elif indent and y.is_block_closer():
1472
+ self.smart_backspace_event(event)
1473
+ return "break"
1474
+ finally:
1475
+ text.see("insert")
1476
+ text.undo_block_stop()
1477
+
1478
+ # Our editwin provides an is_char_in_string function that works
1479
+ # with a Tk text index, but PyParse only knows about offsets into
1480
+ # a string. This builds a function for PyParse that accepts an
1481
+ # offset.
1482
+
1483
+ def _build_char_in_string_func(self, startindex):
1484
+ def inner(offset, _startindex=startindex,
1485
+ _icis=self.is_char_in_string):
1486
+ return _icis(_startindex + "+%dc" % offset)
1487
+ return inner
1488
+
1489
+ # XXX this isn't bound to anything -- see tabwidth comments
1490
+ ## def change_tabwidth_event(self, event):
1491
+ ## new = self._asktabwidth()
1492
+ ## if new != self.tabwidth:
1493
+ ## self.tabwidth = new
1494
+ ## self.set_indentation_params(0, guess=0)
1495
+ ## return "break"
1496
+
1497
+ # Make string that displays as n leading blanks.
1498
+
1499
+ def _make_blanks(self, n):
1500
+ if self.usetabs:
1501
+ ntabs, nspaces = divmod(n, self.tabwidth)
1502
+ return '\t' * ntabs + ' ' * nspaces
1503
+ else:
1504
+ return ' ' * n
1505
+
1506
+ # Delete from beginning of line to insert point, then reinsert
1507
+ # column logical (meaning use tabs if appropriate) spaces.
1508
+
1509
+ def reindent_to(self, column):
1510
+ text = self.text
1511
+ text.undo_block_start()
1512
+ if text.compare("insert linestart", "!=", "insert"):
1513
+ text.delete("insert linestart", "insert")
1514
+ if column:
1515
+ text.insert("insert", self._make_blanks(column),
1516
+ self.user_input_insert_tags)
1517
+ text.undo_block_stop()
1518
+
1519
+ # Guess indentwidth from text content.
1520
+ # Return guessed indentwidth. This should not be believed unless
1521
+ # it's in a reasonable range (e.g., it will be 0 if no indented
1522
+ # blocks are found).
1523
+
1524
+ def guess_indent(self):
1525
+ opener, indented = IndentSearcher(self.text, self.tabwidth).run()
1526
+ if opener and indented:
1527
+ raw, indentsmall = get_line_indent(opener, self.tabwidth)
1528
+ raw, indentlarge = get_line_indent(indented, self.tabwidth)
1529
+ else:
1530
+ indentsmall = indentlarge = 0
1531
+ return indentlarge - indentsmall
1532
+
1533
+ def toggle_line_numbers_event(self, event=None):
1534
+ if self.line_numbers is None:
1535
+ return
1536
+
1537
+ if self.line_numbers.is_shown:
1538
+ self.line_numbers.hide_sidebar()
1539
+ menu_label = "Show"
1540
+ else:
1541
+ self.line_numbers.show_sidebar()
1542
+ menu_label = "Hide"
1543
+ self.update_menu_label(menu='options', index='*ine*umbers',
1544
+ label=f'{menu_label} Line Numbers')
1545
+
1546
+ # "line.col" -> line, as an int
1547
+ def index2line(index):
1548
+ return int(float(index))
1549
+
1550
+
1551
+ _line_indent_re = re.compile(r'[ \t]*')
1552
+ def get_line_indent(line, tabwidth):
1553
+ """Return a line's indentation as (# chars, effective # of spaces).
1554
+
1555
+ The effective # of spaces is the length after properly "expanding"
1556
+ the tabs into spaces, as done by str.expandtabs(tabwidth).
1557
+ """
1558
+ m = _line_indent_re.match(line)
1559
+ return m.end(), len(m.group().expandtabs(tabwidth))
1560
+
1561
+
1562
+ class IndentSearcher:
1563
+
1564
+ # .run() chews over the Text widget, looking for a block opener
1565
+ # and the stmt following it. Returns a pair,
1566
+ # (line containing block opener, line containing stmt)
1567
+ # Either or both may be None.
1568
+
1569
+ def __init__(self, text, tabwidth):
1570
+ self.text = text
1571
+ self.tabwidth = tabwidth
1572
+ self.i = self.finished = 0
1573
+ self.blkopenline = self.indentedline = None
1574
+
1575
+ def readline(self):
1576
+ if self.finished:
1577
+ return ""
1578
+ i = self.i = self.i + 1
1579
+ mark = repr(i) + ".0"
1580
+ if self.text.compare(mark, ">=", "end"):
1581
+ return ""
1582
+ return self.text.get(mark, mark + " lineend+1c")
1583
+
1584
+ def tokeneater(self, type, token, start, end, line,
1585
+ INDENT=tokenize.INDENT,
1586
+ NAME=tokenize.NAME,
1587
+ OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
1588
+ if self.finished:
1589
+ pass
1590
+ elif type == NAME and token in OPENERS:
1591
+ self.blkopenline = line
1592
+ elif type == INDENT and self.blkopenline:
1593
+ self.indentedline = line
1594
+ self.finished = 1
1595
+
1596
+ def run(self):
1597
+ save_tabsize = tokenize.tabsize
1598
+ tokenize.tabsize = self.tabwidth
1599
+ try:
1600
+ try:
1601
+ tokens = tokenize.generate_tokens(self.readline)
1602
+ for token in tokens:
1603
+ self.tokeneater(*token)
1604
+ except (tokenize.TokenError, SyntaxError):
1605
+ # since we cut off the tokenizer early, we can trigger
1606
+ # spurious errors
1607
+ pass
1608
+ finally:
1609
+ tokenize.tabsize = save_tabsize
1610
+ return self.blkopenline, self.indentedline
1611
+
1612
+ ### end autoindent code ###
1613
+
1614
+ def prepstr(s):
1615
+ # Helper to extract the underscore from a string, e.g.
1616
+ # prepstr("Co_py") returns (2, "Copy").
1617
+ i = s.find('_')
1618
+ if i >= 0:
1619
+ s = s[:i] + s[i+1:]
1620
+ return i, s
1621
+
1622
+
1623
+ keynames = {
1624
+ 'bracketleft': '[',
1625
+ 'bracketright': ']',
1626
+ 'slash': '/',
1627
+ }
1628
+
1629
+ def get_accelerator(keydefs, eventname):
1630
+ keylist = keydefs.get(eventname)
1631
+ # issue10940: temporary workaround to prevent hang with OS X Cocoa Tk 8.5
1632
+ # if not keylist:
1633
+ if (not keylist) or (macosx.isCocoaTk() and eventname in {
1634
+ "<<open-module>>",
1635
+ "<<goto-line>>",
1636
+ "<<change-indentwidth>>"}):
1637
+ return ""
1638
+ s = keylist[0]
1639
+ s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s)
1640
+ s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s)
1641
+ s = re.sub("Key-", "", s)
1642
+ s = re.sub("Cancel","Ctrl-Break",s) # dscherer@cmu.edu
1643
+ s = re.sub("Control-", "Ctrl-", s)
1644
+ s = re.sub("-", "+", s)
1645
+ s = re.sub("><", " ", s)
1646
+ s = re.sub("<", "", s)
1647
+ s = re.sub(">", "", s)
1648
+ return s
1649
+
1650
+
1651
+ def fixwordbreaks(root):
1652
+ # On Windows, tcl/tk breaks 'words' only on spaces, as in Command Prompt.
1653
+ # We want Motif style everywhere. See #21474, msg218992 and followup.
1654
+ tk = root.tk
1655
+ tk.call('tcl_wordBreakAfter', 'a b', 0) # make sure word.tcl is loaded
1656
+ tk.call('set', 'tcl_wordchars', r'\w')
1657
+ tk.call('set', 'tcl_nonwordchars', r'\W')
1658
+
1659
+
1660
+ def _editor_window(parent): # htest #
1661
+ # error if close master window first - timer event, after script
1662
+ root = parent
1663
+ fixwordbreaks(root)
1664
+ if sys.argv[1:]:
1665
+ filename = sys.argv[1]
1666
+ else:
1667
+ filename = None
1668
+ macosx.setupApp(root, None)
1669
+ edit = EditorWindow(root=root, filename=filename)
1670
+ text = edit.text
1671
+ text['height'] = 10
1672
+ for i in range(20):
1673
+ text.insert('insert', ' '*i + str(i) + '\n')
1674
+ # text.bind("<<close-all-windows>>", edit.close_event)
1675
+ # Does not stop error, neither does following
1676
+ # edit.text.bind("<<close-window>>", edit.close_event)
1677
+
1678
+ if __name__ == '__main__':
1679
+ from unittest import main
1680
+ main('idlelib.idle_test.test_editor', verbosity=2, exit=False)
1681
+
1682
+ from idlelib.idle_test.htest import run
1683
+ run(_editor_window)
llava/lib/python3.10/idlelib/format.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Format all or a selected region (line slice) of text.
2
+
3
+ Region formatting options: paragraph, comment block, indent, deindent,
4
+ comment, uncomment, tabify, and untabify.
5
+
6
+ File renamed from paragraph.py with functions added from editor.py.
7
+ """
8
+ import re
9
+ from tkinter.messagebox import askyesno
10
+ from tkinter.simpledialog import askinteger
11
+ from idlelib.config import idleConf
12
+
13
+
14
+ class FormatParagraph:
15
+ """Format a paragraph, comment block, or selection to a max width.
16
+
17
+ Does basic, standard text formatting, and also understands Python
18
+ comment blocks. Thus, for editing Python source code, this
19
+ extension is really only suitable for reformatting these comment
20
+ blocks or triple-quoted strings.
21
+
22
+ Known problems with comment reformatting:
23
+ * If there is a selection marked, and the first line of the
24
+ selection is not complete, the block will probably not be detected
25
+ as comments, and will have the normal "text formatting" rules
26
+ applied.
27
+ * If a comment block has leading whitespace that mixes tabs and
28
+ spaces, they will not be considered part of the same block.
29
+ * Fancy comments, like this bulleted list, aren't handled :-)
30
+ """
31
+ def __init__(self, editwin):
32
+ self.editwin = editwin
33
+
34
+ @classmethod
35
+ def reload(cls):
36
+ cls.max_width = idleConf.GetOption('extensions', 'FormatParagraph',
37
+ 'max-width', type='int', default=72)
38
+
39
+ def close(self):
40
+ self.editwin = None
41
+
42
+ def format_paragraph_event(self, event, limit=None):
43
+ """Formats paragraph to a max width specified in idleConf.
44
+
45
+ If text is selected, format_paragraph_event will start breaking lines
46
+ at the max width, starting from the beginning selection.
47
+
48
+ If no text is selected, format_paragraph_event uses the current
49
+ cursor location to determine the paragraph (lines of text surrounded
50
+ by blank lines) and formats it.
51
+
52
+ The length limit parameter is for testing with a known value.
53
+ """
54
+ limit = self.max_width if limit is None else limit
55
+ text = self.editwin.text
56
+ first, last = self.editwin.get_selection_indices()
57
+ if first and last:
58
+ data = text.get(first, last)
59
+ comment_header = get_comment_header(data)
60
+ else:
61
+ first, last, comment_header, data = \
62
+ find_paragraph(text, text.index("insert"))
63
+ if comment_header:
64
+ newdata = reformat_comment(data, limit, comment_header)
65
+ else:
66
+ newdata = reformat_paragraph(data, limit)
67
+ text.tag_remove("sel", "1.0", "end")
68
+
69
+ if newdata != data:
70
+ text.mark_set("insert", first)
71
+ text.undo_block_start()
72
+ text.delete(first, last)
73
+ text.insert(first, newdata)
74
+ text.undo_block_stop()
75
+ else:
76
+ text.mark_set("insert", last)
77
+ text.see("insert")
78
+ return "break"
79
+
80
+
81
+ FormatParagraph.reload()
82
+
83
+ def find_paragraph(text, mark):
84
+ """Returns the start/stop indices enclosing the paragraph that mark is in.
85
+
86
+ Also returns the comment format string, if any, and paragraph of text
87
+ between the start/stop indices.
88
+ """
89
+ lineno, col = map(int, mark.split("."))
90
+ line = text.get("%d.0" % lineno, "%d.end" % lineno)
91
+
92
+ # Look for start of next paragraph if the index passed in is a blank line
93
+ while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line):
94
+ lineno = lineno + 1
95
+ line = text.get("%d.0" % lineno, "%d.end" % lineno)
96
+ first_lineno = lineno
97
+ comment_header = get_comment_header(line)
98
+ comment_header_len = len(comment_header)
99
+
100
+ # Once start line found, search for end of paragraph (a blank line)
101
+ while get_comment_header(line)==comment_header and \
102
+ not is_all_white(line[comment_header_len:]):
103
+ lineno = lineno + 1
104
+ line = text.get("%d.0" % lineno, "%d.end" % lineno)
105
+ last = "%d.0" % lineno
106
+
107
+ # Search back to beginning of paragraph (first blank line before)
108
+ lineno = first_lineno - 1
109
+ line = text.get("%d.0" % lineno, "%d.end" % lineno)
110
+ while lineno > 0 and \
111
+ get_comment_header(line)==comment_header and \
112
+ not is_all_white(line[comment_header_len:]):
113
+ lineno = lineno - 1
114
+ line = text.get("%d.0" % lineno, "%d.end" % lineno)
115
+ first = "%d.0" % (lineno+1)
116
+
117
+ return first, last, comment_header, text.get(first, last)
118
+
119
+ # This should perhaps be replaced with textwrap.wrap
120
+ def reformat_paragraph(data, limit):
121
+ """Return data reformatted to specified width (limit)."""
122
+ lines = data.split("\n")
123
+ i = 0
124
+ n = len(lines)
125
+ while i < n and is_all_white(lines[i]):
126
+ i = i+1
127
+ if i >= n:
128
+ return data
129
+ indent1 = get_indent(lines[i])
130
+ if i+1 < n and not is_all_white(lines[i+1]):
131
+ indent2 = get_indent(lines[i+1])
132
+ else:
133
+ indent2 = indent1
134
+ new = lines[:i]
135
+ partial = indent1
136
+ while i < n and not is_all_white(lines[i]):
137
+ # XXX Should take double space after period (etc.) into account
138
+ words = re.split(r"(\s+)", lines[i])
139
+ for j in range(0, len(words), 2):
140
+ word = words[j]
141
+ if not word:
142
+ continue # Can happen when line ends in whitespace
143
+ if len((partial + word).expandtabs()) > limit and \
144
+ partial != indent1:
145
+ new.append(partial.rstrip())
146
+ partial = indent2
147
+ partial = partial + word + " "
148
+ if j+1 < len(words) and words[j+1] != " ":
149
+ partial = partial + " "
150
+ i = i+1
151
+ new.append(partial.rstrip())
152
+ # XXX Should reformat remaining paragraphs as well
153
+ new.extend(lines[i:])
154
+ return "\n".join(new)
155
+
156
+ def reformat_comment(data, limit, comment_header):
157
+ """Return data reformatted to specified width with comment header."""
158
+
159
+ # Remove header from the comment lines
160
+ lc = len(comment_header)
161
+ data = "\n".join(line[lc:] for line in data.split("\n"))
162
+ # Reformat to maxformatwidth chars or a 20 char width,
163
+ # whichever is greater.
164
+ format_width = max(limit - len(comment_header), 20)
165
+ newdata = reformat_paragraph(data, format_width)
166
+ # re-split and re-insert the comment header.
167
+ newdata = newdata.split("\n")
168
+ # If the block ends in a \n, we don't want the comment prefix
169
+ # inserted after it. (Im not sure it makes sense to reformat a
170
+ # comment block that is not made of complete lines, but whatever!)
171
+ # Can't think of a clean solution, so we hack away
172
+ block_suffix = ""
173
+ if not newdata[-1]:
174
+ block_suffix = "\n"
175
+ newdata = newdata[:-1]
176
+ return '\n'.join(comment_header+line for line in newdata) + block_suffix
177
+
178
+ def is_all_white(line):
179
+ """Return True if line is empty or all whitespace."""
180
+
181
+ return re.match(r"^\s*$", line) is not None
182
+
183
+ def get_indent(line):
184
+ """Return the initial space or tab indent of line."""
185
+ return re.match(r"^([ \t]*)", line).group()
186
+
187
+ def get_comment_header(line):
188
+ """Return string with leading whitespace and '#' from line or ''.
189
+
190
+ A null return indicates that the line is not a comment line. A non-
191
+ null return, such as ' #', will be used to find the other lines of
192
+ a comment block with the same indent.
193
+ """
194
+ m = re.match(r"^([ \t]*#*)", line)
195
+ if m is None: return ""
196
+ return m.group(1)
197
+
198
+
199
+ # Copied from editor.py; importing it would cause an import cycle.
200
+ _line_indent_re = re.compile(r'[ \t]*')
201
+
202
+ def get_line_indent(line, tabwidth):
203
+ """Return a line's indentation as (# chars, effective # of spaces).
204
+
205
+ The effective # of spaces is the length after properly "expanding"
206
+ the tabs into spaces, as done by str.expandtabs(tabwidth).
207
+ """
208
+ m = _line_indent_re.match(line)
209
+ return m.end(), len(m.group().expandtabs(tabwidth))
210
+
211
+
212
+ class FormatRegion:
213
+ "Format selected text (region)."
214
+
215
+ def __init__(self, editwin):
216
+ self.editwin = editwin
217
+
218
+ def get_region(self):
219
+ """Return line information about the selected text region.
220
+
221
+ If text is selected, the first and last indices will be
222
+ for the selection. If there is no text selected, the
223
+ indices will be the current cursor location.
224
+
225
+ Return a tuple containing (first index, last index,
226
+ string representation of text, list of text lines).
227
+ """
228
+ text = self.editwin.text
229
+ first, last = self.editwin.get_selection_indices()
230
+ if first and last:
231
+ head = text.index(first + " linestart")
232
+ tail = text.index(last + "-1c lineend +1c")
233
+ else:
234
+ head = text.index("insert linestart")
235
+ tail = text.index("insert lineend +1c")
236
+ chars = text.get(head, tail)
237
+ lines = chars.split("\n")
238
+ return head, tail, chars, lines
239
+
240
+ def set_region(self, head, tail, chars, lines):
241
+ """Replace the text between the given indices.
242
+
243
+ Args:
244
+ head: Starting index of text to replace.
245
+ tail: Ending index of text to replace.
246
+ chars: Expected to be string of current text
247
+ between head and tail.
248
+ lines: List of new lines to insert between head
249
+ and tail.
250
+ """
251
+ text = self.editwin.text
252
+ newchars = "\n".join(lines)
253
+ if newchars == chars:
254
+ text.bell()
255
+ return
256
+ text.tag_remove("sel", "1.0", "end")
257
+ text.mark_set("insert", head)
258
+ text.undo_block_start()
259
+ text.delete(head, tail)
260
+ text.insert(head, newchars)
261
+ text.undo_block_stop()
262
+ text.tag_add("sel", head, "insert")
263
+
264
+ def indent_region_event(self, event=None):
265
+ "Indent region by indentwidth spaces."
266
+ head, tail, chars, lines = self.get_region()
267
+ for pos in range(len(lines)):
268
+ line = lines[pos]
269
+ if line:
270
+ raw, effective = get_line_indent(line, self.editwin.tabwidth)
271
+ effective = effective + self.editwin.indentwidth
272
+ lines[pos] = self.editwin._make_blanks(effective) + line[raw:]
273
+ self.set_region(head, tail, chars, lines)
274
+ return "break"
275
+
276
+ def dedent_region_event(self, event=None):
277
+ "Dedent region by indentwidth spaces."
278
+ head, tail, chars, lines = self.get_region()
279
+ for pos in range(len(lines)):
280
+ line = lines[pos]
281
+ if line:
282
+ raw, effective = get_line_indent(line, self.editwin.tabwidth)
283
+ effective = max(effective - self.editwin.indentwidth, 0)
284
+ lines[pos] = self.editwin._make_blanks(effective) + line[raw:]
285
+ self.set_region(head, tail, chars, lines)
286
+ return "break"
287
+
288
+ def comment_region_event(self, event=None):
289
+ """Comment out each line in region.
290
+
291
+ ## is appended to the beginning of each line to comment it out.
292
+ """
293
+ head, tail, chars, lines = self.get_region()
294
+ for pos in range(len(lines) - 1):
295
+ line = lines[pos]
296
+ lines[pos] = '##' + line
297
+ self.set_region(head, tail, chars, lines)
298
+ return "break"
299
+
300
+ def uncomment_region_event(self, event=None):
301
+ """Uncomment each line in region.
302
+
303
+ Remove ## or # in the first positions of a line. If the comment
304
+ is not in the beginning position, this command will have no effect.
305
+ """
306
+ head, tail, chars, lines = self.get_region()
307
+ for pos in range(len(lines)):
308
+ line = lines[pos]
309
+ if not line:
310
+ continue
311
+ if line[:2] == '##':
312
+ line = line[2:]
313
+ elif line[:1] == '#':
314
+ line = line[1:]
315
+ lines[pos] = line
316
+ self.set_region(head, tail, chars, lines)
317
+ return "break"
318
+
319
+ def tabify_region_event(self, event=None):
320
+ "Convert leading spaces to tabs for each line in selected region."
321
+ head, tail, chars, lines = self.get_region()
322
+ tabwidth = self._asktabwidth()
323
+ if tabwidth is None:
324
+ return
325
+ for pos in range(len(lines)):
326
+ line = lines[pos]
327
+ if line:
328
+ raw, effective = get_line_indent(line, tabwidth)
329
+ ntabs, nspaces = divmod(effective, tabwidth)
330
+ lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
331
+ self.set_region(head, tail, chars, lines)
332
+ return "break"
333
+
334
+ def untabify_region_event(self, event=None):
335
+ "Expand tabs to spaces for each line in region."
336
+ head, tail, chars, lines = self.get_region()
337
+ tabwidth = self._asktabwidth()
338
+ if tabwidth is None:
339
+ return
340
+ for pos in range(len(lines)):
341
+ lines[pos] = lines[pos].expandtabs(tabwidth)
342
+ self.set_region(head, tail, chars, lines)
343
+ return "break"
344
+
345
+ def _asktabwidth(self):
346
+ "Return value for tab width."
347
+ return askinteger(
348
+ "Tab width",
349
+ "Columns per tab? (2-16)",
350
+ parent=self.editwin.text,
351
+ initialvalue=self.editwin.indentwidth,
352
+ minvalue=2,
353
+ maxvalue=16)
354
+
355
+
356
+ class Indents:
357
+ "Change future indents."
358
+
359
+ def __init__(self, editwin):
360
+ self.editwin = editwin
361
+
362
+ def toggle_tabs_event(self, event):
363
+ editwin = self.editwin
364
+ usetabs = editwin.usetabs
365
+ if askyesno(
366
+ "Toggle tabs",
367
+ "Turn tabs " + ("on", "off")[usetabs] +
368
+ "?\nIndent width " +
369
+ ("will be", "remains at")[usetabs] + " 8." +
370
+ "\n Note: a tab is always 8 columns",
371
+ parent=editwin.text):
372
+ editwin.usetabs = not usetabs
373
+ # Try to prevent inconsistent indentation.
374
+ # User must change indent width manually after using tabs.
375
+ editwin.indentwidth = 8
376
+ return "break"
377
+
378
+ def change_indentwidth_event(self, event):
379
+ editwin = self.editwin
380
+ new = askinteger(
381
+ "Indent width",
382
+ "New indent width (2-16)\n(Always use 8 when using tabs)",
383
+ parent=editwin.text,
384
+ initialvalue=editwin.indentwidth,
385
+ minvalue=2,
386
+ maxvalue=16)
387
+ if new and new != editwin.indentwidth and not editwin.usetabs:
388
+ editwin.indentwidth = new
389
+ return "break"
390
+
391
+
392
+ class Rstrip: # 'Strip Trailing Whitespace" on "Format" menu.
393
+ def __init__(self, editwin):
394
+ self.editwin = editwin
395
+
396
+ def do_rstrip(self, event=None):
397
+ text = self.editwin.text
398
+ undo = self.editwin.undo
399
+ undo.undo_block_start()
400
+
401
+ end_line = int(float(text.index('end')))
402
+ for cur in range(1, end_line):
403
+ txt = text.get('%i.0' % cur, '%i.end' % cur)
404
+ raw = len(txt)
405
+ cut = len(txt.rstrip())
406
+ # Since text.delete() marks file as changed, even if not,
407
+ # only call it when needed to actually delete something.
408
+ if cut < raw:
409
+ text.delete('%i.%i' % (cur, cut), '%i.end' % cur)
410
+
411
+ if (text.get('end-2c') == '\n' # File ends with at least 1 newline;
412
+ and not hasattr(self.editwin, 'interp')): # & is not Shell.
413
+ # Delete extra user endlines.
414
+ while (text.index('end-1c') > '1.0' # Stop if file empty.
415
+ and text.get('end-3c') == '\n'):
416
+ text.delete('end-3c')
417
+ # Because tk indexes are slice indexes and never raise,
418
+ # a file with only newlines will be emptied.
419
+ # patchcheck.py does the same.
420
+
421
+ undo.undo_block_stop()
422
+
423
+
424
+ if __name__ == "__main__":
425
+ from unittest import main
426
+ main('idlelib.idle_test.test_format', verbosity=2, exit=False)
llava/lib/python3.10/idlelib/help.html ADDED
@@ -0,0 +1,1178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <!DOCTYPE html>
3
+
4
+ <html lang="en">
5
+ <head>
6
+ <meta charset="utf-8" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.18.1: http://docutils.sourceforge.net/" />
8
+
9
+ <title>IDLE &#8212; Python 3.12.0a0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
10
+
11
+ <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
12
+ <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?2022.1" />
13
+
14
+ <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
15
+ <script src="../_static/jquery.js"></script>
16
+ <script src="../_static/underscore.js"></script>
17
+ <script src="../_static/_sphinx_javascript_frameworks_compat.js"></script>
18
+ <script src="../_static/doctools.js"></script>
19
+
20
+ <script src="../_static/sidebar.js"></script>
21
+
22
+ <link rel="search" type="application/opensearchdescription+xml"
23
+ title="Search within Python 3.12.0a0 documentation"
24
+ href="../_static/opensearch.xml"/>
25
+ <link rel="author" title="About these documents" href="../about.html" />
26
+ <link rel="index" title="Index" href="../genindex.html" />
27
+ <link rel="search" title="Search" href="../search.html" />
28
+ <link rel="copyright" title="Copyright" href="../copyright.html" />
29
+ <link rel="next" title="Development Tools" href="development.html" />
30
+ <link rel="prev" title="tkinter.tix — Extension widgets for Tk" href="tkinter.tix.html" />
31
+ <link rel="canonical" href="https://docs.python.org/3/library/idle.html" />
32
+
33
+
34
+
35
+
36
+
37
+ <style>
38
+ @media only screen {
39
+ table.full-width-table {
40
+ width: 100%;
41
+ }
42
+ }
43
+ </style>
44
+ <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
45
+ <script type="text/javascript" src="../_static/copybutton.js"></script>
46
+ <script type="text/javascript" src="../_static/menu.js"></script>
47
+
48
+ </head>
49
+ <body>
50
+ <div class="mobile-nav">
51
+ <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
52
+ aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
53
+ <label for="menuToggler" class="toggler__label">
54
+ <span></span>
55
+ </label>
56
+ <nav class="nav-content" role="navigation">
57
+ <a href="https://www.python.org/" class="nav-logo">
58
+ <img src="../_static/py.svg" alt="Logo"/>
59
+ </a>
60
+ <div class="version_switcher_placeholder"></div>
61
+ <form role="search" class="search" action="../search.html" method="get">
62
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
63
+ <path fill-rule="nonzero"
64
+ d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="#444"></path>
65
+ </svg>
66
+ <input type="text" name="q" aria-label="Quick search"/>
67
+ <input type="submit" value="Go"/>
68
+ </form>
69
+ </nav>
70
+ <div class="menu-wrapper">
71
+ <nav class="menu" role="navigation" aria-label="main navigation">
72
+ <div class="language_switcher_placeholder"></div>
73
+ <div>
74
+ <h3><a href="../contents.html">Table of Contents</a></h3>
75
+ <ul>
76
+ <li><a class="reference internal" href="#">IDLE</a><ul>
77
+ <li><a class="reference internal" href="#menus">Menus</a><ul>
78
+ <li><a class="reference internal" href="#file-menu-shell-and-editor">File menu (Shell and Editor)</a></li>
79
+ <li><a class="reference internal" href="#edit-menu-shell-and-editor">Edit menu (Shell and Editor)</a></li>
80
+ <li><a class="reference internal" href="#format-menu-editor-window-only">Format menu (Editor window only)</a></li>
81
+ <li><a class="reference internal" href="#run-menu-editor-window-only">Run menu (Editor window only)</a></li>
82
+ <li><a class="reference internal" href="#shell-menu-shell-window-only">Shell menu (Shell window only)</a></li>
83
+ <li><a class="reference internal" href="#debug-menu-shell-window-only">Debug menu (Shell window only)</a></li>
84
+ <li><a class="reference internal" href="#options-menu-shell-and-editor">Options menu (Shell and Editor)</a></li>
85
+ <li><a class="reference internal" href="#window-menu-shell-and-editor">Window menu (Shell and Editor)</a></li>
86
+ <li><a class="reference internal" href="#help-menu-shell-and-editor">Help menu (Shell and Editor)</a></li>
87
+ <li><a class="reference internal" href="#context-menus">Context menus</a></li>
88
+ </ul>
89
+ </li>
90
+ <li><a class="reference internal" href="#editing-and-navigation">Editing and Navigation</a><ul>
91
+ <li><a class="reference internal" href="#editor-windows">Editor windows</a></li>
92
+ <li><a class="reference internal" href="#key-bindings">Key bindings</a></li>
93
+ <li><a class="reference internal" href="#automatic-indentation">Automatic indentation</a></li>
94
+ <li><a class="reference internal" href="#search-and-replace">Search and Replace</a></li>
95
+ <li><a class="reference internal" href="#completions">Completions</a></li>
96
+ <li><a class="reference internal" href="#calltips">Calltips</a></li>
97
+ <li><a class="reference internal" href="#code-context">Code Context</a></li>
98
+ <li><a class="reference internal" href="#shell-window">Shell window</a></li>
99
+ <li><a class="reference internal" href="#text-colors">Text colors</a></li>
100
+ </ul>
101
+ </li>
102
+ <li><a class="reference internal" href="#startup-and-code-execution">Startup and Code Execution</a><ul>
103
+ <li><a class="reference internal" href="#command-line-usage">Command line usage</a></li>
104
+ <li><a class="reference internal" href="#startup-failure">Startup failure</a></li>
105
+ <li><a class="reference internal" href="#running-user-code">Running user code</a></li>
106
+ <li><a class="reference internal" href="#user-output-in-shell">User output in Shell</a></li>
107
+ <li><a class="reference internal" href="#developing-tkinter-applications">Developing tkinter applications</a></li>
108
+ <li><a class="reference internal" href="#running-without-a-subprocess">Running without a subprocess</a></li>
109
+ </ul>
110
+ </li>
111
+ <li><a class="reference internal" href="#help-and-preferences">Help and Preferences</a><ul>
112
+ <li><a class="reference internal" href="#help-sources">Help sources</a></li>
113
+ <li><a class="reference internal" href="#setting-preferences">Setting preferences</a></li>
114
+ <li><a class="reference internal" href="#idle-on-macos">IDLE on macOS</a></li>
115
+ <li><a class="reference internal" href="#extensions">Extensions</a></li>
116
+ </ul>
117
+ </li>
118
+ <li><a class="reference internal" href="#module-idlelib">idlelib</a></li>
119
+ </ul>
120
+ </li>
121
+ </ul>
122
+
123
+ </div>
124
+ <div>
125
+ <h4>Previous topic</h4>
126
+ <p class="topless"><a href="tkinter.tix.html"
127
+ title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter.tix</span></code> — Extension widgets for Tk</a></p>
128
+ </div>
129
+ <div>
130
+ <h4>Next topic</h4>
131
+ <p class="topless"><a href="development.html"
132
+ title="next chapter">Development Tools</a></p>
133
+ </div>
134
+ <div role="note" aria-label="source link">
135
+ <h3>This Page</h3>
136
+ <ul class="this-page-menu">
137
+ <li><a href="../bugs.html">Report a Bug</a></li>
138
+ <li>
139
+ <a href="https://github.com/python/cpython/blob/main/Doc/library/idle.rst"
140
+ rel="nofollow">Show Source
141
+ </a>
142
+ </li>
143
+ </ul>
144
+ </div>
145
+ </nav>
146
+ </div>
147
+ </div>
148
+
149
+
150
+ <div class="related" role="navigation" aria-label="related navigation">
151
+ <h3>Navigation</h3>
152
+ <ul>
153
+ <li class="right" style="margin-right: 10px">
154
+ <a href="../genindex.html" title="General Index"
155
+ accesskey="I">index</a></li>
156
+ <li class="right" >
157
+ <a href="../py-modindex.html" title="Python Module Index"
158
+ >modules</a> |</li>
159
+ <li class="right" >
160
+ <a href="development.html" title="Development Tools"
161
+ accesskey="N">next</a> |</li>
162
+ <li class="right" >
163
+ <a href="tkinter.tix.html" title="tkinter.tix — Extension widgets for Tk"
164
+ accesskey="P">previous</a> |</li>
165
+
166
+ <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
167
+ <li><a href="https://www.python.org/">Python</a> &#187;</li>
168
+ <li class="switchers">
169
+ <div class="language_switcher_placeholder"></div>
170
+ <div class="version_switcher_placeholder"></div>
171
+ </li>
172
+ <li>
173
+
174
+ </li>
175
+ <li id="cpython-language-and-version">
176
+ <a href="../index.html">3.12.0a0 Documentation</a> &#187;
177
+ </li>
178
+
179
+ <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
180
+ <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">Graphical User Interfaces with Tk</a> &#187;</li>
181
+ <li class="nav-item nav-item-this"><a href="">IDLE</a></li>
182
+ <li class="right">
183
+
184
+
185
+ <div class="inline-search" role="search">
186
+ <form class="inline-search" action="../search.html" method="get">
187
+ <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" />
188
+ <input type="submit" value="Go" />
189
+ <input type="hidden" name="check_keywords" value="yes" />
190
+ <input type="hidden" name="area" value="default" />
191
+ </form>
192
+ </div>
193
+ |
194
+ </li>
195
+
196
+ </ul>
197
+ </div>
198
+
199
+ <div class="document">
200
+ <div class="documentwrapper">
201
+ <div class="bodywrapper">
202
+ <div class="body" role="main">
203
+
204
+ <section id="idle">
205
+ <span id="id1"></span><h1>IDLE<a class="headerlink" href="#idle" title="Permalink to this heading">¶</a></h1>
206
+ <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/main/Lib/idlelib/">Lib/idlelib/</a></p>
207
+ <hr class="docutils" id="index-0" />
208
+ <p>IDLE is Python’s Integrated Development and Learning Environment.</p>
209
+ <p>IDLE has the following features:</p>
210
+ <ul class="simple">
211
+ <li><p>coded in 100% pure Python, using the <a class="reference internal" href="tkinter.html#module-tkinter" title="tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter</span></code></a> GUI toolkit</p></li>
212
+ <li><p>cross-platform: works mostly the same on Windows, Unix, and macOS</p></li>
213
+ <li><p>Python shell window (interactive interpreter) with colorizing
214
+ of code input, output, and error messages</p></li>
215
+ <li><p>multi-window text editor with multiple undo, Python colorizing,
216
+ smart indent, call tips, auto completion, and other features</p></li>
217
+ <li><p>search within any window, replace within editor windows, and search
218
+ through multiple files (grep)</p></li>
219
+ <li><p>debugger with persistent breakpoints, stepping, and viewing
220
+ of global and local namespaces</p></li>
221
+ <li><p>configuration, browsers, and other dialogs</p></li>
222
+ </ul>
223
+ <section id="menus">
224
+ <h2>Menus<a class="headerlink" href="#menus" title="Permalink to this heading">¶</a></h2>
225
+ <p>IDLE has two main window types, the Shell window and the Editor window. It is
226
+ possible to have multiple editor windows simultaneously. On Windows and
227
+ Linux, each has its own top menu. Each menu documented below indicates
228
+ which window type it is associated with.</p>
229
+ <p>Output windows, such as used for Edit =&gt; Find in Files, are a subtype of editor
230
+ window. They currently have the same top menu but a different
231
+ default title and context menu.</p>
232
+ <p>On macOS, there is one application menu. It dynamically changes according
233
+ to the window currently selected. It has an IDLE menu, and some entries
234
+ described below are moved around to conform to Apple guidelines.</p>
235
+ <section id="file-menu-shell-and-editor">
236
+ <h3>File menu (Shell and Editor)<a class="headerlink" href="#file-menu-shell-and-editor" title="Permalink to this heading">¶</a></h3>
237
+ <dl class="simple">
238
+ <dt>New File</dt><dd><p>Create a new file editing window.</p>
239
+ </dd>
240
+ <dt>Open…</dt><dd><p>Open an existing file with an Open dialog.</p>
241
+ </dd>
242
+ <dt>Open Module…</dt><dd><p>Open an existing module (searches sys.path).</p>
243
+ </dd>
244
+ <dt>Recent Files</dt><dd><p>Open a list of recent files. Click one to open it.</p>
245
+ </dd>
246
+ </dl>
247
+ <dl class="simple" id="index-1">
248
+ <dt>Module Browser</dt><dd><p>Show functions, classes, and methods in the current Editor file in a
249
+ tree structure. In the shell, open a module first.</p>
250
+ </dd>
251
+ <dt>Path Browser</dt><dd><p>Show sys.path directories, modules, functions, classes and methods in a
252
+ tree structure.</p>
253
+ </dd>
254
+ <dt>Save</dt><dd><p>Save the current window to the associated file, if there is one. Windows
255
+ that have been changed since being opened or last saved have a * before
256
+ and after the window title. If there is no associated file,
257
+ do Save As instead.</p>
258
+ </dd>
259
+ <dt>Save As…</dt><dd><p>Save the current window with a Save As dialog. The file saved becomes the
260
+ new associated file for the window. (If your file namager is set to hide
261
+ extensions, the current extension will be omitted in the file name box.
262
+ If the new filename has no ‘.’, ‘.py’ and ‘.txt’ will be added for Python
263
+ and text files, except that on macOS Aqua,’.py’ is added for all files.)</p>
264
+ </dd>
265
+ <dt>Save Copy As…</dt><dd><p>Save the current window to different file without changing the associated
266
+ file. (See Save As note above about filename extensions.)</p>
267
+ </dd>
268
+ <dt>Print Window</dt><dd><p>Print the current window to the default printer.</p>
269
+ </dd>
270
+ <dt>Close Window</dt><dd><p>Close the current window (if an unsaved editor, ask to save; if an unsaved
271
+ Shell, ask to quit execution). Calling <code class="docutils literal notranslate"><span class="pre">exit()</span></code> or <code class="docutils literal notranslate"><span class="pre">close()</span></code> in the Shell
272
+ window also closes Shell. If this is the only window, also exit IDLE.</p>
273
+ </dd>
274
+ <dt>Exit IDLE</dt><dd><p>Close all windows and quit IDLE (ask to save unsaved edit windows).</p>
275
+ </dd>
276
+ </dl>
277
+ </section>
278
+ <section id="edit-menu-shell-and-editor">
279
+ <h3>Edit menu (Shell and Editor)<a class="headerlink" href="#edit-menu-shell-and-editor" title="Permalink to this heading">¶</a></h3>
280
+ <dl class="simple">
281
+ <dt>Undo</dt><dd><p>Undo the last change to the current window. A maximum of 1000 changes may
282
+ be undone.</p>
283
+ </dd>
284
+ <dt>Redo</dt><dd><p>Redo the last undone change to the current window.</p>
285
+ </dd>
286
+ <dt>Select All</dt><dd><p>Select the entire contents of the current window.</p>
287
+ </dd>
288
+ <dt>Cut</dt><dd><p>Copy selection into the system-wide clipboard; then delete the selection.</p>
289
+ </dd>
290
+ <dt>Copy</dt><dd><p>Copy selection into the system-wide clipboard.</p>
291
+ </dd>
292
+ <dt>Paste</dt><dd><p>Insert contents of the system-wide clipboard into the current window.</p>
293
+ </dd>
294
+ </dl>
295
+ <p>The clipboard functions are also available in context menus.</p>
296
+ <dl class="simple">
297
+ <dt>Find…</dt><dd><p>Open a search dialog with many options</p>
298
+ </dd>
299
+ <dt>Find Again</dt><dd><p>Repeat the last search, if there is one.</p>
300
+ </dd>
301
+ <dt>Find Selection</dt><dd><p>Search for the currently selected string, if there is one.</p>
302
+ </dd>
303
+ <dt>Find in Files…</dt><dd><p>Open a file search dialog. Put results in a new output window.</p>
304
+ </dd>
305
+ <dt>Replace…</dt><dd><p>Open a search-and-replace dialog.</p>
306
+ </dd>
307
+ <dt>Go to Line</dt><dd><p>Move the cursor to the beginning of the line requested and make that
308
+ line visible. A request past the end of the file goes to the end.
309
+ Clear any selection and update the line and column status.</p>
310
+ </dd>
311
+ <dt>Show Completions</dt><dd><p>Open a scrollable list allowing selection of existing names. See
312
+ <a class="reference internal" href="#completions"><span class="std std-ref">Completions</span></a> in the Editing and navigation section below.</p>
313
+ </dd>
314
+ <dt>Expand Word</dt><dd><p>Expand a prefix you have typed to match a full word in the same window;
315
+ repeat to get a different expansion.</p>
316
+ </dd>
317
+ <dt>Show Call Tip</dt><dd><p>After an unclosed parenthesis for a function, open a small window with
318
+ function parameter hints. See <a class="reference internal" href="#calltips"><span class="std std-ref">Calltips</span></a> in the
319
+ Editing and navigation section below.</p>
320
+ </dd>
321
+ <dt>Show Surrounding Parens</dt><dd><p>Highlight the surrounding parenthesis.</p>
322
+ </dd>
323
+ </dl>
324
+ </section>
325
+ <section id="format-menu-editor-window-only">
326
+ <span id="format-menu"></span><h3>Format menu (Editor window only)<a class="headerlink" href="#format-menu-editor-window-only" title="Permalink to this heading">¶</a></h3>
327
+ <dl class="simple">
328
+ <dt>Format Paragraph</dt><dd><p>Reformat the current blank-line-delimited paragraph in comment block or
329
+ multiline string or selected line in a string. All lines in the
330
+ paragraph will be formatted to less than N columns, where N defaults to 72.</p>
331
+ </dd>
332
+ <dt>Indent Region</dt><dd><p>Shift selected lines right by the indent width (default 4 spaces).</p>
333
+ </dd>
334
+ <dt>Dedent Region</dt><dd><p>Shift selected lines left by the indent width (default 4 spaces).</p>
335
+ </dd>
336
+ <dt>Comment Out Region</dt><dd><p>Insert ## in front of selected lines.</p>
337
+ </dd>
338
+ <dt>Uncomment Region</dt><dd><p>Remove leading # or ## from selected lines.</p>
339
+ </dd>
340
+ <dt>Tabify Region</dt><dd><p>Turn <em>leading</em> stretches of spaces into tabs. (Note: We recommend using
341
+ 4 space blocks to indent Python code.)</p>
342
+ </dd>
343
+ <dt>Untabify Region</dt><dd><p>Turn <em>all</em> tabs into the correct number of spaces.</p>
344
+ </dd>
345
+ <dt>Toggle Tabs</dt><dd><p>Open a dialog to switch between indenting with spaces and tabs.</p>
346
+ </dd>
347
+ <dt>New Indent Width</dt><dd><p>Open a dialog to change indent width. The accepted default by the Python
348
+ community is 4 spaces.</p>
349
+ </dd>
350
+ <dt>Strip Trailing Chitespace</dt><dd><p>Remove trailing space and other whitespace characters after the last
351
+ non-whitespace character of a line by applying str.rstrip to each line,
352
+ including lines within multiline strings. Except for Shell windows,
353
+ remove extra newlines at the end of the file.</p>
354
+ </dd>
355
+ </dl>
356
+ </section>
357
+ <section id="run-menu-editor-window-only">
358
+ <span id="index-2"></span><h3>Run menu (Editor window only)<a class="headerlink" href="#run-menu-editor-window-only" title="Permalink to this heading">¶</a></h3>
359
+ <dl class="simple" id="run-module">
360
+ <dt>Run Module</dt><dd><p>Do <a class="reference internal" href="#check-module"><span class="std std-ref">Check Module</span></a>. If no error, restart the shell to clean the
361
+ environment, then execute the module. Output is displayed in the Shell
362
+ window. Note that output requires use of <code class="docutils literal notranslate"><span class="pre">print</span></code> or <code class="docutils literal notranslate"><span class="pre">write</span></code>.
363
+ When execution is complete, the Shell retains focus and displays a prompt.
364
+ At this point, one may interactively explore the result of execution.
365
+ This is similar to executing a file with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-i</span> <span class="pre">file</span></code> at a command
366
+ line.</p>
367
+ </dd>
368
+ </dl>
369
+ <dl class="simple" id="run-custom">
370
+ <dt>Run… Customized</dt><dd><p>Same as <a class="reference internal" href="#run-module"><span class="std std-ref">Run Module</span></a>, but run the module with customized
371
+ settings. <em>Command Line Arguments</em> extend <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> as if passed
372
+ on a command line. The module can be run in the Shell without restarting.</p>
373
+ </dd>
374
+ </dl>
375
+ <dl class="simple" id="check-module">
376
+ <dt>Check Module</dt><dd><p>Check the syntax of the module currently open in the Editor window. If the
377
+ module has not been saved IDLE will either prompt the user to save or
378
+ autosave, as selected in the General tab of the Idle Settings dialog. If
379
+ there is a syntax error, the approximate location is indicated in the
380
+ Editor window.</p>
381
+ </dd>
382
+ </dl>
383
+ <dl class="simple" id="python-shell">
384
+ <dt>Python Shell</dt><dd><p>Open or wake up the Python Shell window.</p>
385
+ </dd>
386
+ </dl>
387
+ </section>
388
+ <section id="shell-menu-shell-window-only">
389
+ <h3>Shell menu (Shell window only)<a class="headerlink" href="#shell-menu-shell-window-only" title="Permalink to this heading">¶</a></h3>
390
+ <dl class="simple">
391
+ <dt>View Last Restart</dt><dd><p>Scroll the shell window to the last Shell restart.</p>
392
+ </dd>
393
+ <dt>Restart Shell</dt><dd><p>Restart the shell to clean the environment and reset display and exception handling.</p>
394
+ </dd>
395
+ <dt>Previous History</dt><dd><p>Cycle through earlier commands in history which match the current entry.</p>
396
+ </dd>
397
+ <dt>Next History</dt><dd><p>Cycle through later commands in history which match the current entry.</p>
398
+ </dd>
399
+ <dt>Interrupt Execution</dt><dd><p>Stop a running program.</p>
400
+ </dd>
401
+ </dl>
402
+ </section>
403
+ <section id="debug-menu-shell-window-only">
404
+ <h3>Debug menu (Shell window only)<a class="headerlink" href="#debug-menu-shell-window-only" title="Permalink to this heading">¶</a></h3>
405
+ <dl class="simple">
406
+ <dt>Go to File/Line</dt><dd><p>Look on the current line. with the cursor, and the line above for a filename
407
+ and line number. If found, open the file if not already open, and show the
408
+ line. Use this to view source lines referenced in an exception traceback
409
+ and lines found by Find in Files. Also available in the context menu of
410
+ the Shell window and Output windows.</p>
411
+ </dd>
412
+ </dl>
413
+ <dl class="simple" id="index-3">
414
+ <dt>Debugger (toggle)</dt><dd><p>When activated, code entered in the Shell or run from an Editor will run
415
+ under the debugger. In the Editor, breakpoints can be set with the context
416
+ menu. This feature is still incomplete and somewhat experimental.</p>
417
+ </dd>
418
+ <dt>Stack Viewer</dt><dd><p>Show the stack traceback of the last exception in a tree widget, with
419
+ access to locals and globals.</p>
420
+ </dd>
421
+ <dt>Auto-open Stack Viewer</dt><dd><p>Toggle automatically opening the stack viewer on an unhandled exception.</p>
422
+ </dd>
423
+ </dl>
424
+ </section>
425
+ <section id="options-menu-shell-and-editor">
426
+ <h3>Options menu (Shell and Editor)<a class="headerlink" href="#options-menu-shell-and-editor" title="Permalink to this heading">¶</a></h3>
427
+ <dl class="simple">
428
+ <dt>Configure IDLE</dt><dd><p>Open a configuration dialog and change preferences for the following:
429
+ fonts, indentation, keybindings, text color themes, startup windows and
430
+ size, additional help sources, and extensions. On macOS, open the
431
+ configuration dialog by selecting Preferences in the application
432
+ menu. For more details, see
433
+ <a class="reference internal" href="#preferences"><span class="std std-ref">Setting preferences</span></a> under Help and preferences.</p>
434
+ </dd>
435
+ </dl>
436
+ <p>Most configuration options apply to all windows or all future windows.
437
+ The option items below only apply to the active window.</p>
438
+ <dl class="simple">
439
+ <dt>Show/Hide Code Context (Editor Window only)</dt><dd><p>Open a pane at the top of the edit window which shows the block context
440
+ of the code which has scrolled above the top of the window. See
441
+ <a class="reference internal" href="#code-context"><span class="std std-ref">Code Context</span></a> in the Editing and Navigation section
442
+ below.</p>
443
+ </dd>
444
+ <dt>Show/Hide Line Numbers (Editor Window only)</dt><dd><p>Open a column to the left of the edit window which shows the number
445
+ of each line of text. The default is off, which may be changed in the
446
+ preferences (see <a class="reference internal" href="#preferences"><span class="std std-ref">Setting preferences</span></a>).</p>
447
+ </dd>
448
+ <dt>Zoom/Restore Height</dt><dd><p>Toggles the window between normal size and maximum height. The initial size
449
+ defaults to 40 lines by 80 chars unless changed on the General tab of the
450
+ Configure IDLE dialog. The maximum height for a screen is determined by
451
+ momentarily maximizing a window the first time one is zoomed on the screen.
452
+ Changing screen settings may invalidate the saved height. This toggle has
453
+ no effect when a window is maximized.</p>
454
+ </dd>
455
+ </dl>
456
+ </section>
457
+ <section id="window-menu-shell-and-editor">
458
+ <h3>Window menu (Shell and Editor)<a class="headerlink" href="#window-menu-shell-and-editor" title="Permalink to this heading">¶</a></h3>
459
+ <p>Lists the names of all open windows; select one to bring it to the foreground
460
+ (deiconifying it if necessary).</p>
461
+ </section>
462
+ <section id="help-menu-shell-and-editor">
463
+ <h3>Help menu (Shell and Editor)<a class="headerlink" href="#help-menu-shell-and-editor" title="Permalink to this heading">¶</a></h3>
464
+ <dl class="simple">
465
+ <dt>About IDLE</dt><dd><p>Display version, copyright, license, credits, and more.</p>
466
+ </dd>
467
+ <dt>IDLE Help</dt><dd><p>Display this IDLE document, detailing the menu options, basic editing and
468
+ navigation, and other tips.</p>
469
+ </dd>
470
+ <dt>Python Docs</dt><dd><p>Access local Python documentation, if installed, or start a web browser
471
+ and open docs.python.org showing the latest Python documentation.</p>
472
+ </dd>
473
+ <dt>Turtle Demo</dt><dd><p>Run the turtledemo module with example Python code and turtle drawings.</p>
474
+ </dd>
475
+ </dl>
476
+ <p>Additional help sources may be added here with the Configure IDLE dialog under
477
+ the General tab. See the <a class="reference internal" href="#help-sources"><span class="std std-ref">Help sources</span></a> subsection below
478
+ for more on Help menu choices.</p>
479
+ </section>
480
+ <section id="context-menus">
481
+ <span id="index-4"></span><h3>Context menus<a class="headerlink" href="#context-menus" title="Permalink to this heading">¶</a></h3>
482
+ <p>Open a context menu by right-clicking in a window (Control-click on macOS).
483
+ Context menus have the standard clipboard functions also on the Edit menu.</p>
484
+ <dl class="simple">
485
+ <dt>Cut</dt><dd><p>Copy selection into the system-wide clipboard; then delete the selection.</p>
486
+ </dd>
487
+ <dt>Copy</dt><dd><p>Copy selection into the system-wide clipboard.</p>
488
+ </dd>
489
+ <dt>Paste</dt><dd><p>Insert contents of the system-wide clipboard into the current window.</p>
490
+ </dd>
491
+ </dl>
492
+ <p>Editor windows also have breakpoint functions. Lines with a breakpoint set are
493
+ specially marked. Breakpoints only have an effect when running under the
494
+ debugger. Breakpoints for a file are saved in the user’s <code class="docutils literal notranslate"><span class="pre">.idlerc</span></code>
495
+ directory.</p>
496
+ <dl class="simple">
497
+ <dt>Set Breakpoint</dt><dd><p>Set a breakpoint on the current line.</p>
498
+ </dd>
499
+ <dt>Clear Breakpoint</dt><dd><p>Clear the breakpoint on that line.</p>
500
+ </dd>
501
+ </dl>
502
+ <p>Shell and Output windows also have the following.</p>
503
+ <dl class="simple">
504
+ <dt>Go to file/line</dt><dd><p>Same as in Debug menu.</p>
505
+ </dd>
506
+ </dl>
507
+ <p>The Shell window also has an output squeezing facility explained in the <em>Python
508
+ Shell window</em> subsection below.</p>
509
+ <dl class="simple">
510
+ <dt>Squeeze</dt><dd><p>If the cursor is over an output line, squeeze all the output between
511
+ the code above and the prompt below down to a ‘Squeezed text’ label.</p>
512
+ </dd>
513
+ </dl>
514
+ </section>
515
+ </section>
516
+ <section id="editing-and-navigation">
517
+ <span id="id2"></span><h2>Editing and Navigation<a class="headerlink" href="#editing-and-navigation" title="Permalink to this heading">¶</a></h2>
518
+ <section id="editor-windows">
519
+ <h3>Editor windows<a class="headerlink" href="#editor-windows" title="Permalink to this heading">¶</a></h3>
520
+ <p>IDLE may open editor windows when it starts, depending on settings
521
+ and how you start IDLE. Thereafter, use the File menu. There can be only
522
+ one open editor window for a given file.</p>
523
+ <p>The title bar contains the name of the file, the full path, and the version
524
+ of Python and IDLE running the window. The status bar contains the line
525
+ number (‘Ln’) and column number (‘Col’). Line numbers start with 1;
526
+ column numbers with 0.</p>
527
+ <p>IDLE assumes that files with a known .py* extension contain Python code
528
+ and that other files do not. Run Python code with the Run menu.</p>
529
+ </section>
530
+ <section id="key-bindings">
531
+ <h3>Key bindings<a class="headerlink" href="#key-bindings" title="Permalink to this heading">¶</a></h3>
532
+ <p>In this section, ‘C’ refers to the <kbd class="kbd docutils literal notranslate">Control</kbd> key on Windows and Unix and
533
+ the <kbd class="kbd docutils literal notranslate">Command</kbd> key on macOS.</p>
534
+ <ul>
535
+ <li><p><kbd class="kbd docutils literal notranslate">Backspace</kbd> deletes to the left; <kbd class="kbd docutils literal notranslate">Del</kbd> deletes to the right</p></li>
536
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">Backspace</kbd></kbd> delete word left; <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">Del</kbd></kbd> delete word to the right</p></li>
537
+ <li><p>Arrow keys and <kbd class="kbd docutils literal notranslate">Page Up</kbd>/<kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Page</kbd> <kbd class="kbd docutils literal notranslate">Down</kbd></kbd> to move around</p></li>
538
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">LeftArrow</kbd></kbd> and <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">RightArrow</kbd></kbd> moves by words</p></li>
539
+ <li><p><kbd class="kbd docutils literal notranslate">Home</kbd>/<kbd class="kbd docutils literal notranslate">End</kbd> go to begin/end of line</p></li>
540
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">Home</kbd></kbd>/<kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">End</kbd></kbd> go to begin/end of file</p></li>
541
+ <li><p>Some useful Emacs bindings are inherited from Tcl/Tk:</p>
542
+ <blockquote>
543
+ <div><ul class="simple">
544
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">a</kbd></kbd> beginning of line</p></li>
545
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">e</kbd></kbd> end of line</p></li>
546
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">k</kbd></kbd> kill line (but doesn’t put it in clipboard)</p></li>
547
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">l</kbd></kbd> center window around the insertion point</p></li>
548
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">b</kbd></kbd> go backward one character without deleting (usually you can
549
+ also use the cursor key for this)</p></li>
550
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">f</kbd></kbd> go forward one character without deleting (usually you can
551
+ also use the cursor key for this)</p></li>
552
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">p</kbd></kbd> go up one line (usually you can also use the cursor key for
553
+ this)</p></li>
554
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">d</kbd></kbd> delete next character</p></li>
555
+ </ul>
556
+ </div></blockquote>
557
+ </li>
558
+ </ul>
559
+ <p>Standard keybindings (like <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">c</kbd></kbd> to copy and <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">v</kbd></kbd> to paste)
560
+ may work. Keybindings are selected in the Configure IDLE dialog.</p>
561
+ </section>
562
+ <section id="automatic-indentation">
563
+ <h3>Automatic indentation<a class="headerlink" href="#automatic-indentation" title="Permalink to this heading">¶</a></h3>
564
+ <p>After a block-opening statement, the next line is indented by 4 spaces (in the
565
+ Python Shell window by one tab). After certain keywords (break, return etc.)
566
+ the next line is dedented. In leading indentation, <kbd class="kbd docutils literal notranslate">Backspace</kbd> deletes up
567
+ to 4 spaces if they are there. <kbd class="kbd docutils literal notranslate">Tab</kbd> inserts spaces (in the Python
568
+ Shell window one tab), number depends on Indent width. Currently, tabs
569
+ are restricted to four spaces due to Tcl/Tk limitations.</p>
570
+ <p>See also the indent/dedent region commands on the
571
+ <a class="reference internal" href="#format-menu"><span class="std std-ref">Format menu</span></a>.</p>
572
+ </section>
573
+ <section id="search-and-replace">
574
+ <h3>Search and Replace<a class="headerlink" href="#search-and-replace" title="Permalink to this heading">¶</a></h3>
575
+ <p>Any selection becomes a search target. However, only selections within
576
+ a line work because searches are only performed within lines with the
577
+ terminal newline removed. If <code class="docutils literal notranslate"><span class="pre">[x]</span> <span class="pre">Regular</span> <span class="pre">expresion</span></code> is checked, the
578
+ target is interpreted according to the Python re module.</p>
579
+ </section>
580
+ <section id="completions">
581
+ <span id="id3"></span><h3>Completions<a class="headerlink" href="#completions" title="Permalink to this heading">¶</a></h3>
582
+ <p>Completions are supplied, when requested and available, for module
583
+ names, attributes of classes or functions, or filenames. Each request
584
+ method displays a completion box with existing names. (See tab
585
+ completions below for an exception.) For any box, change the name
586
+ being completed and the item highlighted in the box by
587
+ typing and deleting characters; by hitting <kbd class="kbd docutils literal notranslate">Up</kbd>, <kbd class="kbd docutils literal notranslate">Down</kbd>,
588
+ <kbd class="kbd docutils literal notranslate">PageUp</kbd>, <kbd class="kbd docutils literal notranslate">PageDown</kbd>, <kbd class="kbd docutils literal notranslate">Home</kbd>, and <kbd class="kbd docutils literal notranslate">End</kbd> keys;
589
+ and by a single click within the box. Close the box with <kbd class="kbd docutils literal notranslate">Escape</kbd>,
590
+ <kbd class="kbd docutils literal notranslate">Enter</kbd>, and double <kbd class="kbd docutils literal notranslate">Tab</kbd> keys or clicks outside the box.
591
+ A double click within the box selects and closes.</p>
592
+ <p>One way to open a box is to type a key character and wait for a
593
+ predefined interval. This defaults to 2 seconds; customize it
594
+ in the settings dialog. (To prevent auto popups, set the delay to a
595
+ large number of milliseconds, such as 100000000.) For imported module
596
+ names or class or function attributes, type ‘.’.
597
+ For filenames in the root directory, type <a class="reference internal" href="os.html#os.sep" title="os.sep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.sep</span></code></a> or
598
+ <a class="reference internal" href="os.html#os.altsep" title="os.altsep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.altsep</span></code></a> immediately after an opening quote. (On Windows,
599
+ one can specify a drive first.) Move into subdirectories by typing a
600
+ directory name and a separator.</p>
601
+ <p>Instead of waiting, or after a box is closed, open a completion box
602
+ immediately with Show Completions on the Edit menu. The default hot
603
+ key is <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">space</kbd></kbd>. If one types a prefix for the desired name
604
+ before opening the box, the first match or near miss is made visible.
605
+ The result is the same as if one enters a prefix
606
+ after the box is displayed. Show Completions after a quote completes
607
+ filenames in the current directory instead of a root directory.</p>
608
+ <p>Hitting <kbd class="kbd docutils literal notranslate">Tab</kbd> after a prefix usually has the same effect as Show
609
+ Completions. (With no prefix, it indents.) However, if there is only
610
+ one match to the prefix, that match is immediately added to the editor
611
+ text without opening a box.</p>
612
+ <p>Invoking ‘Show Completions’, or hitting <kbd class="kbd docutils literal notranslate">Tab</kbd> after a prefix,
613
+ outside of a string and without a preceding ‘.’ opens a box with
614
+ keywords, builtin names, and available module-level names.</p>
615
+ <p>When editing code in an editor (as oppose to Shell), increase the
616
+ available module-level names by running your code
617
+ and not restarting the Shell thereafter. This is especially useful
618
+ after adding imports at the top of a file. This also increases
619
+ possible attribute completions.</p>
620
+ <p>Completion boxes initially exclude names beginning with ‘_’ or, for
621
+ modules, not included in ‘__all__’. The hidden names can be accessed
622
+ by typing ‘_’ after ‘.’, either before or after the box is opened.</p>
623
+ </section>
624
+ <section id="calltips">
625
+ <span id="id4"></span><h3>Calltips<a class="headerlink" href="#calltips" title="Permalink to this heading">¶</a></h3>
626
+ <p>A calltip is shown automatically when one types <kbd class="kbd docutils literal notranslate">(</kbd> after the name
627
+ of an <em>accessible</em> function. A function name expression may include
628
+ dots and subscripts. A calltip remains until it is clicked, the cursor
629
+ is moved out of the argument area, or <kbd class="kbd docutils literal notranslate">)</kbd> is typed. Whenever the
630
+ cursor is in the argument part of a definition, select Edit and “Show
631
+ Call Tip” on the menu or enter its shortcut to display a calltip.</p>
632
+ <p>The calltip consists of the function’s signature and docstring up to
633
+ the latter’s first blank line or the fifth non-blank line. (Some builtin
634
+ functions lack an accessible signature.) A ‘/’ or ‘*’ in the signature
635
+ indicates that the preceding or following arguments are passed by
636
+ position or name (keyword) only. Details are subject to change.</p>
637
+ <p>In Shell, the accessible functions depends on what modules have been
638
+ imported into the user process, including those imported by Idle itself,
639
+ and which definitions have been run, all since the last restart.</p>
640
+ <p>For example, restart the Shell and enter <code class="docutils literal notranslate"><span class="pre">itertools.count(</span></code>. A calltip
641
+ appears because Idle imports itertools into the user process for its own
642
+ use. (This could change.) Enter <code class="docutils literal notranslate"><span class="pre">turtle.write(</span></code> and nothing appears.
643
+ Idle does not itself import turtle. The menu entry and shortcut also do
644
+ nothing. Enter <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">turtle</span></code>. Thereafter, <code class="docutils literal notranslate"><span class="pre">turtle.write(</span></code>
645
+ will display a calltip.</p>
646
+ <p>In an editor, import statements have no effect until one runs the file.
647
+ One might want to run a file after writing import statements, after
648
+ adding function definitions, or after opening an existing file.</p>
649
+ </section>
650
+ <section id="code-context">
651
+ <span id="id5"></span><h3>Code Context<a class="headerlink" href="#code-context" title="Permalink to this heading">¶</a></h3>
652
+ <p>Within an editor window containing Python code, code context can be toggled
653
+ in order to show or hide a pane at the top of the window. When shown, this
654
+ pane freezes the opening lines for block code, such as those beginning with
655
+ <code class="docutils literal notranslate"><span class="pre">class</span></code>, <code class="docutils literal notranslate"><span class="pre">def</span></code>, or <code class="docutils literal notranslate"><span class="pre">if</span></code> keywords, that would have otherwise scrolled
656
+ out of view. The size of the pane will be expanded and contracted as needed
657
+ to show the all current levels of context, up to the maximum number of
658
+ lines defined in the Configure IDLE dialog (which defaults to 15). If there
659
+ are no current context lines and the feature is toggled on, a single blank
660
+ line will display. Clicking on a line in the context pane will move that
661
+ line to the top of the editor.</p>
662
+ <p>The text and background colors for the context pane can be configured under
663
+ the Highlights tab in the Configure IDLE dialog.</p>
664
+ </section>
665
+ <section id="shell-window">
666
+ <h3>Shell window<a class="headerlink" href="#shell-window" title="Permalink to this heading">¶</a></h3>
667
+ <p>In IDLE’s Shell, enter, edit, and recall complete statements. (Most
668
+ consoles and terminals only work with a single physical line at a time).</p>
669
+ <p>Submit a single-line statement for execution by hitting <kbd class="kbd docutils literal notranslate">Return</kbd>
670
+ with the cursor anywhere on the line. If a line is extended with
671
+ Backslash (<kbd class="kbd docutils literal notranslate">\</kbd>), the cursor must be on the last physical line.
672
+ Submit a multi-line compound statement by entering a blank line after
673
+ the statement.</p>
674
+ <p>When one pastes code into Shell, it is not compiled and possibly executed
675
+ until one hits <kbd class="kbd docutils literal notranslate">Return</kbd>, as specified above.
676
+ One may edit pasted code first.
677
+ If one pastes more than one statement into Shell, the result will be a
678
+ <a class="reference internal" href="exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> when multiple statements are compiled as if they were one.</p>
679
+ <p>Lines containing <code class="docutils literal notranslate"><span class="pre">RESTART</span></code> mean that the user execution process has been
680
+ re-started. This occurs when the user execution process has crashed,
681
+ when one requests a restart on the Shell menu, or when one runs code
682
+ in an editor window.</p>
683
+ <p>The editing features described in previous subsections work when entering
684
+ code interactively. IDLE’s Shell window also responds to the following keys.</p>
685
+ <ul>
686
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">c</kbd></kbd> interrupts executing command</p></li>
687
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">d</kbd></kbd> sends end-of-file; closes window if typed at a <code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code> prompt</p></li>
688
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Alt</kbd>-<kbd class="kbd docutils literal notranslate">/</kbd></kbd> (Expand word) is also useful to reduce typing</p>
689
+ <p>Command history</p>
690
+ <ul class="simple">
691
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Alt</kbd>-<kbd class="kbd docutils literal notranslate">p</kbd></kbd> retrieves previous command matching what you have typed. On
692
+ macOS use <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">p</kbd></kbd>.</p></li>
693
+ <li><p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Alt</kbd>-<kbd class="kbd docutils literal notranslate">n</kbd></kbd> retrieves next. On macOS use <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">C</kbd>-<kbd class="kbd docutils literal notranslate">n</kbd></kbd>.</p></li>
694
+ <li><p><kbd class="kbd docutils literal notranslate">Return</kbd> while the cursor is on any previous command
695
+ retrieves that command</p></li>
696
+ </ul>
697
+ </li>
698
+ </ul>
699
+ </section>
700
+ <section id="text-colors">
701
+ <h3>Text colors<a class="headerlink" href="#text-colors" title="Permalink to this heading">¶</a></h3>
702
+ <p>Idle defaults to black on white text, but colors text with special meanings.
703
+ For the shell, these are shell output, shell error, user output, and
704
+ user error. For Python code, at the shell prompt or in an editor, these are
705
+ keywords, builtin class and function names, names following <code class="docutils literal notranslate"><span class="pre">class</span></code> and
706
+ <code class="docutils literal notranslate"><span class="pre">def</span></code>, strings, and comments. For any text window, these are the cursor (when
707
+ present), found text (when possible), and selected text.</p>
708
+ <p>IDLE also highlights the <a class="reference internal" href="../reference/lexical_analysis.html#soft-keywords"><span class="std std-ref">soft keywords</span></a> <a class="reference internal" href="../reference/compound_stmts.html#match"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">match</span></code></a>,
709
+ <a class="reference internal" href="../reference/compound_stmts.html#match"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">case</span></code></a>, and <a class="reference internal" href="../reference/compound_stmts.html#wildcard-patterns"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">_</span></code></a> in
710
+ pattern-matching statements. However, this highlighting is not perfect and
711
+ will be incorrect in some rare cases, including some <code class="docutils literal notranslate"><span class="pre">_</span></code>-s in <code class="docutils literal notranslate"><span class="pre">case</span></code>
712
+ patterns.</p>
713
+ <p>Text coloring is done in the background, so uncolorized text is occasionally
714
+ visible. To change the color scheme, use the Configure IDLE dialog
715
+ Highlighting tab. The marking of debugger breakpoint lines in the editor and
716
+ text in popups and dialogs is not user-configurable.</p>
717
+ </section>
718
+ </section>
719
+ <section id="startup-and-code-execution">
720
+ <h2>Startup and Code Execution<a class="headerlink" href="#startup-and-code-execution" title="Permalink to this heading">¶</a></h2>
721
+ <p>Upon startup with the <code class="docutils literal notranslate"><span class="pre">-s</span></code> option, IDLE will execute the file referenced by
722
+ the environment variables <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code> or <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a>.
723
+ IDLE first checks for <code class="docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code>; if <code class="docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code> is present the file
724
+ referenced is run. If <code class="docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code> is not present, IDLE checks for
725
+ <code class="docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code>. Files referenced by these environment variables are
726
+ convenient places to store functions that are used frequently from the IDLE
727
+ shell, or for executing import statements to import common modules.</p>
728
+ <p>In addition, <code class="docutils literal notranslate"><span class="pre">Tk</span></code> also loads a startup file if it is present. Note that the
729
+ Tk file is loaded unconditionally. This additional file is <code class="docutils literal notranslate"><span class="pre">.Idle.py</span></code> and is
730
+ looked for in the user’s home directory. Statements in this file will be
731
+ executed in the Tk namespace, so this file is not useful for importing
732
+ functions to be used from IDLE’s Python shell.</p>
733
+ <section id="command-line-usage">
734
+ <h3>Command line usage<a class="headerlink" href="#command-line-usage" title="Permalink to this heading">¶</a></h3>
735
+ <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...
736
+
737
+ -c command run command in the shell window
738
+ -d enable debugger and open shell window
739
+ -e open editor window
740
+ -h print help message with legal combinations and exit
741
+ -i open shell window
742
+ -r file run file in shell window
743
+ -s run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
744
+ -t title set title of shell window
745
+ - run stdin in shell (- must be last option before args)
746
+ </pre></div>
747
+ </div>
748
+ <p>If there are arguments:</p>
749
+ <ul class="simple">
750
+ <li><p>If <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">-c</span></code>, or <code class="docutils literal notranslate"><span class="pre">r</span></code> is used, all arguments are placed in
751
+ <code class="docutils literal notranslate"><span class="pre">sys.argv[1:...]</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">''</span></code>, <code class="docutils literal notranslate"><span class="pre">'-c'</span></code>,
752
+ or <code class="docutils literal notranslate"><span class="pre">'-r'</span></code>. No editor window is opened, even if that is the default
753
+ set in the Options dialog.</p></li>
754
+ <li><p>Otherwise, arguments are files opened for editing and
755
+ <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> reflects the arguments passed to IDLE itself.</p></li>
756
+ </ul>
757
+ </section>
758
+ <section id="startup-failure">
759
+ <h3>Startup failure<a class="headerlink" href="#startup-failure" title="Permalink to this heading">¶</a></h3>
760
+ <p>IDLE uses a socket to communicate between the IDLE GUI process and the user
761
+ code execution process. A connection must be established whenever the Shell
762
+ starts or restarts. (The latter is indicated by a divider line that says
763
+ ‘RESTART’). If the user process fails to connect to the GUI process, it
764
+ usually displays a <code class="docutils literal notranslate"><span class="pre">Tk</span></code> error box with a ‘cannot connect’ message
765
+ that directs the user here. It then exits.</p>
766
+ <p>One specific connection failure on Unix systems results from
767
+ misconfigured masquerading rules somewhere in a system’s network setup.
768
+ When IDLE is started from a terminal, one will see a message starting
769
+ with <code class="docutils literal notranslate"><span class="pre">**</span> <span class="pre">Invalid</span> <span class="pre">host:</span></code>.
770
+ The valid value is <code class="docutils literal notranslate"><span class="pre">127.0.0.1</span> <span class="pre">(idlelib.rpc.LOCALHOST)</span></code>.
771
+ One can diagnose with <code class="docutils literal notranslate"><span class="pre">tcpconnect</span> <span class="pre">-irv</span> <span class="pre">127.0.0.1</span> <span class="pre">6543</span></code> in one
772
+ terminal window and <code class="docutils literal notranslate"><span class="pre">tcplisten</span> <span class="pre">&lt;same</span> <span class="pre">args&gt;</span></code> in another.</p>
773
+ <p>A common cause of failure is a user-written file with the same name as a
774
+ standard library module, such as <em>random.py</em> and <em>tkinter.py</em>. When such a
775
+ file is located in the same directory as a file that is about to be run,
776
+ IDLE cannot import the stdlib file. The current fix is to rename the
777
+ user file.</p>
778
+ <p>Though less common than in the past, an antivirus or firewall program may
779
+ stop the connection. If the program cannot be taught to allow the
780
+ connection, then it must be turned off for IDLE to work. It is safe to
781
+ allow this internal connection because no data is visible on external
782
+ ports. A similar problem is a network mis-configuration that blocks
783
+ connections.</p>
784
+ <p>Python installation issues occasionally stop IDLE: multiple versions can
785
+ clash, or a single installation might need admin access. If one undo the
786
+ clash, or cannot or does not want to run as admin, it might be easiest to
787
+ completely remove Python and start over.</p>
788
+ <p>A zombie pythonw.exe process could be a problem. On Windows, use Task
789
+ Manager to check for one and stop it if there is. Sometimes a restart
790
+ initiated by a program crash or Keyboard Interrupt (control-C) may fail
791
+ to connect. Dismissing the error box or using Restart Shell on the Shell
792
+ menu may fix a temporary problem.</p>
793
+ <p>When IDLE first starts, it attempts to read user configuration files in
794
+ <code class="docutils literal notranslate"><span class="pre">~/.idlerc/</span></code> (~ is one’s home directory). If there is a problem, an error
795
+ message should be displayed. Leaving aside random disk glitches, this can
796
+ be prevented by never editing the files by hand. Instead, use the
797
+ configuration dialog, under Options. Once there is an error in a user
798
+ configuration file, the best solution may be to delete it and start over
799
+ with the settings dialog.</p>
800
+ <p>If IDLE quits with no message, and it was not started from a console, try
801
+ starting it from a console or terminal (<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">idlelib</span></code>) and see if
802
+ this results in an error message.</p>
803
+ <p>On Unix-based systems with tcl/tk older than <code class="docutils literal notranslate"><span class="pre">8.6.11</span></code> (see
804
+ <code class="docutils literal notranslate"><span class="pre">About</span> <span class="pre">IDLE</span></code>) certain characters of certain fonts can cause
805
+ a tk failure with a message to the terminal. This can happen either
806
+ if one starts IDLE to edit a file with such a character or later
807
+ when entering such a character. If one cannot upgrade tcl/tk,
808
+ then re-configure IDLE to use a font that works better.</p>
809
+ </section>
810
+ <section id="running-user-code">
811
+ <h3>Running user code<a class="headerlink" href="#running-user-code" title="Permalink to this heading">¶</a></h3>
812
+ <p>With rare exceptions, the result of executing Python code with IDLE is
813
+ intended to be the same as executing the same code by the default method,
814
+ directly with Python in a text-mode system console or terminal window.
815
+ However, the different interface and operation occasionally affect
816
+ visible results. For instance, <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> starts with more entries,
817
+ and <code class="docutils literal notranslate"><span class="pre">threading.active_count()</span></code> returns 2 instead of 1.</p>
818
+ <p>By default, IDLE runs user code in a separate OS process rather than in
819
+ the user interface process that runs the shell and editor. In the execution
820
+ process, it replaces <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>, and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>
821
+ with objects that get input from and send output to the Shell window.
822
+ The original values stored in <code class="docutils literal notranslate"><span class="pre">sys.__stdin__</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.__stdout__</span></code>, and
823
+ <code class="docutils literal notranslate"><span class="pre">sys.__stderr__</span></code> are not touched, but may be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
824
+ <p>Sending print output from one process to a text widget in another is
825
+ slower than printing to a system terminal in the same process.
826
+ This has the most effect when printing multiple arguments, as the string
827
+ for each argument, each separator, the newline are sent separately.
828
+ For development, this is usually not a problem, but if one wants to
829
+ print faster in IDLE, format and join together everything one wants
830
+ displayed together and then print a single string. Both format strings
831
+ and <a class="reference internal" href="stdtypes.html#str.join" title="str.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.join()</span></code></a> can help combine fields and lines.</p>
832
+ <p>IDLE’s standard stream replacements are not inherited by subprocesses
833
+ created in the execution process, whether directly by user code or by
834
+ modules such as multiprocessing. If such subprocess use <code class="docutils literal notranslate"><span class="pre">input</span></code> from
835
+ sys.stdin or <code class="docutils literal notranslate"><span class="pre">print</span></code> or <code class="docutils literal notranslate"><span class="pre">write</span></code> to sys.stdout or sys.stderr,
836
+ IDLE should be started in a command line window. (On Windows,
837
+ use <code class="docutils literal notranslate"><span class="pre">python</span></code> or <code class="docutils literal notranslate"><span class="pre">py</span></code> rather than <code class="docutils literal notranslate"><span class="pre">pythonw</span></code> or <code class="docutils literal notranslate"><span class="pre">pyw</span></code>.)
838
+ The secondary subprocess
839
+ will then be attached to that window for input and output.</p>
840
+ <p>If <code class="docutils literal notranslate"><span class="pre">sys</span></code> is reset by user code, such as with <code class="docutils literal notranslate"><span class="pre">importlib.reload(sys)</span></code>,
841
+ IDLE’s changes are lost and input from the keyboard and output to the screen
842
+ will not work correctly.</p>
843
+ <p>When Shell has the focus, it controls the keyboard and screen. This is
844
+ normally transparent, but functions that directly access the keyboard
845
+ and screen will not work. These include system-specific functions that
846
+ determine whether a key has been pressed and if so, which.</p>
847
+ <p>The IDLE code running in the execution process adds frames to the call stack
848
+ that would not be there otherwise. IDLE wraps <code class="docutils literal notranslate"><span class="pre">sys.getrecursionlimit</span></code> and
849
+ <code class="docutils literal notranslate"><span class="pre">sys.setrecursionlimit</span></code> to reduce the effect of the additional stack
850
+ frames.</p>
851
+ <p>When user code raises SystemExit either directly or by calling sys.exit,
852
+ IDLE returns to a Shell prompt instead of exiting.</p>
853
+ </section>
854
+ <section id="user-output-in-shell">
855
+ <h3>User output in Shell<a class="headerlink" href="#user-output-in-shell" title="Permalink to this heading">¶</a></h3>
856
+ <p>When a program outputs text, the result is determined by the
857
+ corresponding output device. When IDLE executes user code, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>
858
+ and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> are connected to the display area of IDLE’s Shell. Some of
859
+ its features are inherited from the underlying Tk Text widget. Others
860
+ are programmed additions. Where it matters, Shell is designed for development
861
+ rather than production runs.</p>
862
+ <p>For instance, Shell never throws away output. A program that sends unlimited
863
+ output to Shell will eventually fill memory, resulting in a memory error.
864
+ In contrast, some system text windows only keep the last n lines of output.
865
+ A Windows console, for instance, keeps a user-settable 1 to 9999 lines,
866
+ with 300 the default.</p>
867
+ <p>A Tk Text widget, and hence IDLE’s Shell, displays characters (codepoints) in
868
+ the BMP (Basic Multilingual Plane) subset of Unicode. Which characters are
869
+ displayed with a proper glyph and which with a replacement box depends on the
870
+ operating system and installed fonts. Tab characters cause the following text
871
+ to begin after the next tab stop. (They occur every 8 ‘characters’). Newline
872
+ characters cause following text to appear on a new line. Other control
873
+ characters are ignored or displayed as a space, box, or something else,
874
+ depending on the operating system and font. (Moving the text cursor through
875
+ such output with arrow keys may exhibit some surprising spacing behavior.)</p>
876
+ <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;a</span><span class="se">\t</span><span class="s1">b</span><span class="se">\a</span><span class="s1">&lt;</span><span class="se">\x02</span><span class="s1">&gt;&lt;</span><span class="se">\r</span><span class="s1">&gt;</span><span class="se">\b</span><span class="s1">c</span><span class="se">\n</span><span class="s1">d&#39;</span> <span class="c1"># Enter 22 chars.</span>
877
+ <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
878
+ <span class="go">14</span>
879
+ <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="c1"># Display repr(s)</span>
880
+ <span class="go">&#39;a\tb\x07&lt;\x02&gt;&lt;\r&gt;\x08c\nd&#39;</span>
881
+ <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="c1"># Display s as is.</span>
882
+ <span class="go"># Result varies by OS and font. Try it.</span>
883
+ </pre></div>
884
+ </div>
885
+ <p>The <code class="docutils literal notranslate"><span class="pre">repr</span></code> function is used for interactive echo of expression
886
+ values. It returns an altered version of the input string in which
887
+ control codes, some BMP codepoints, and all non-BMP codepoints are
888
+ replaced with escape codes. As demonstrated above, it allows one to
889
+ identify the characters in a string, regardless of how they are displayed.</p>
890
+ <p>Normal and error output are generally kept separate (on separate lines)
891
+ from code input and each other. They each get different highlight colors.</p>
892
+ <p>For SyntaxError tracebacks, the normal ‘^’ marking where the error was
893
+ detected is replaced by coloring the text with an error highlight.
894
+ When code run from a file causes other exceptions, one may right click
895
+ on a traceback line to jump to the corresponding line in an IDLE editor.
896
+ The file will be opened if necessary.</p>
897
+ <p>Shell has a special facility for squeezing output lines down to a
898
+ ‘Squeezed text’ label. This is done automatically
899
+ for output over N lines (N = 50 by default).
900
+ N can be changed in the PyShell section of the General
901
+ page of the Settings dialog. Output with fewer lines can be squeezed by
902
+ right clicking on the output. This can be useful lines long enough to slow
903
+ down scrolling.</p>
904
+ <p>Squeezed output is expanded in place by double-clicking the label.
905
+ It can also be sent to the clipboard or a separate view window by
906
+ right-clicking the label.</p>
907
+ </section>
908
+ <section id="developing-tkinter-applications">
909
+ <h3>Developing tkinter applications<a class="headerlink" href="#developing-tkinter-applications" title="Permalink to this heading">¶</a></h3>
910
+ <p>IDLE is intentionally different from standard Python in order to
911
+ facilitate development of tkinter programs. Enter <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">tkinter</span> <span class="pre">as</span> <span class="pre">tk;</span>
912
+ <span class="pre">root</span> <span class="pre">=</span> <span class="pre">tk.Tk()</span></code> in standard Python and nothing appears. Enter the same
913
+ in IDLE and a tk window appears. In standard Python, one must also enter
914
+ <code class="docutils literal notranslate"><span class="pre">root.update()</span></code> to see the window. IDLE does the equivalent in the
915
+ background, about 20 times a second, which is about every 50 milliseconds.
916
+ Next enter <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">=</span> <span class="pre">tk.Button(root,</span> <span class="pre">text='button');</span> <span class="pre">b.pack()</span></code>. Again,
917
+ nothing visibly changes in standard Python until one enters <code class="docutils literal notranslate"><span class="pre">root.update()</span></code>.</p>
918
+ <p>Most tkinter programs run <code class="docutils literal notranslate"><span class="pre">root.mainloop()</span></code>, which usually does not
919
+ return until the tk app is destroyed. If the program is run with
920
+ <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-i</span></code> or from an IDLE editor, a <code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code> shell prompt does not
921
+ appear until <code class="docutils literal notranslate"><span class="pre">mainloop()</span></code> returns, at which time there is nothing left
922
+ to interact with.</p>
923
+ <p>When running a tkinter program from an IDLE editor, one can comment out
924
+ the mainloop call. One then gets a shell prompt immediately and can
925
+ interact with the live application. One just has to remember to
926
+ re-enable the mainloop call when running in standard Python.</p>
927
+ </section>
928
+ <section id="running-without-a-subprocess">
929
+ <h3>Running without a subprocess<a class="headerlink" href="#running-without-a-subprocess" title="Permalink to this heading">¶</a></h3>
930
+ <p>By default, IDLE executes user code in a separate subprocess via a socket,
931
+ which uses the internal loopback interface. This connection is not
932
+ externally visible and no data is sent to or received from the internet.
933
+ If firewall software complains anyway, you can ignore it.</p>
934
+ <p>If the attempt to make the socket connection fails, Idle will notify you.
935
+ Such failures are sometimes transient, but if persistent, the problem
936
+ may be either a firewall blocking the connection or misconfiguration of
937
+ a particular system. Until the problem is fixed, one can run Idle with
938
+ the -n command line switch.</p>
939
+ <p>If IDLE is started with the -n command line switch it will run in a
940
+ single process and will not create the subprocess which runs the RPC
941
+ Python execution server. This can be useful if Python cannot create
942
+ the subprocess or the RPC socket interface on your platform. However,
943
+ in this mode user code is not isolated from IDLE itself. Also, the
944
+ environment is not restarted when Run/Run Module (F5) is selected. If
945
+ your code has been modified, you must reload() the affected modules and
946
+ re-import any specific items (e.g. from foo import baz) if the changes
947
+ are to take effect. For these reasons, it is preferable to run IDLE
948
+ with the default subprocess if at all possible.</p>
949
+ <div class="deprecated">
950
+ <p><span class="versionmodified deprecated">Deprecated since version 3.4.</span></p>
951
+ </div>
952
+ </section>
953
+ </section>
954
+ <section id="help-and-preferences">
955
+ <h2>Help and Preferences<a class="headerlink" href="#help-and-preferences" title="Permalink to this heading">¶</a></h2>
956
+ <section id="help-sources">
957
+ <span id="id6"></span><h3>Help sources<a class="headerlink" href="#help-sources" title="Permalink to this heading">¶</a></h3>
958
+ <p>Help menu entry “IDLE Help” displays a formatted html version of the
959
+ IDLE chapter of the Library Reference. The result, in a read-only
960
+ tkinter text window, is close to what one sees in a web browser.
961
+ Navigate through the text with a mousewheel,
962
+ the scrollbar, or up and down arrow keys held down.
963
+ Or click the TOC (Table of Contents) button and select a section
964
+ header in the opened box.</p>
965
+ <p>Help menu entry “Python Docs” opens the extensive sources of help,
966
+ including tutorials, available at <code class="docutils literal notranslate"><span class="pre">docs.python.org/x.y</span></code>, where ‘x.y’
967
+ is the currently running Python version. If your system
968
+ has an off-line copy of the docs (this may be an installation option),
969
+ that will be opened instead.</p>
970
+ <p>Selected URLs can be added or removed from the help menu at any time using the
971
+ General tab of the Configure IDLE dialog.</p>
972
+ </section>
973
+ <section id="setting-preferences">
974
+ <span id="preferences"></span><h3>Setting preferences<a class="headerlink" href="#setting-preferences" title="Permalink to this heading">¶</a></h3>
975
+ <p>The font preferences, highlighting, keys, and general preferences can be
976
+ changed via Configure IDLE on the Option menu.
977
+ Non-default user settings are saved in a <code class="docutils literal notranslate"><span class="pre">.idlerc</span></code> directory in the user’s
978
+ home directory. Problems caused by bad user configuration files are solved
979
+ by editing or deleting one or more of the files in <code class="docutils literal notranslate"><span class="pre">.idlerc</span></code>.</p>
980
+ <p>On the Font tab, see the text sample for the effect of font face and size
981
+ on multiple characters in multiple languages. Edit the sample to add
982
+ other characters of personal interest. Use the sample to select
983
+ monospaced fonts. If particular characters have problems in Shell or an
984
+ editor, add them to the top of the sample and try changing first size
985
+ and then font.</p>
986
+ <p>On the Highlights and Keys tab, select a built-in or custom color theme
987
+ and key set. To use a newer built-in color theme or key set with older
988
+ IDLEs, save it as a new custom theme or key set and it well be accessible
989
+ to older IDLEs.</p>
990
+ </section>
991
+ <section id="idle-on-macos">
992
+ <h3>IDLE on macOS<a class="headerlink" href="#idle-on-macos" title="Permalink to this heading">¶</a></h3>
993
+ <p>Under System Preferences: Dock, one can set “Prefer tabs when opening
994
+ documents” to “Always”. This setting is not compatible with the tk/tkinter
995
+ GUI framework used by IDLE, and it breaks a few IDLE features.</p>
996
+ </section>
997
+ <section id="extensions">
998
+ <h3>Extensions<a class="headerlink" href="#extensions" title="Permalink to this heading">¶</a></h3>
999
+ <p>IDLE contains an extension facility. Preferences for extensions can be
1000
+ changed with the Extensions tab of the preferences dialog. See the
1001
+ beginning of config-extensions.def in the idlelib directory for further
1002
+ information. The only current default extension is zzdummy, an example
1003
+ also used for testing.</p>
1004
+ </section>
1005
+ </section>
1006
+ <section id="module-idlelib">
1007
+ <span id="idlelib"></span><h2>idlelib<a class="headerlink" href="#module-idlelib" title="Permalink to this heading">¶</a></h2>
1008
+ <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/main/Lib/idlelib">Lib/idlelib</a></p>
1009
+ <hr class="docutils" />
1010
+ <p>The Lib/idlelib package implements the IDLE application. See the rest
1011
+ of this page for how to use IDLE.</p>
1012
+ <p>The files in idlelib are described in idlelib/README.txt. Access it
1013
+ either in idlelib or click Help =&gt; About IDLE on the IDLE menu. This
1014
+ file also maps IDLE menu items to the code that implements the item.
1015
+ Except for files listed under ‘Startup’, the idlelib code is ‘private’ in
1016
+ sense that feature changes can be backported (see <span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0434/"><strong>PEP 434</strong></a>).</p>
1017
+ </section>
1018
+ </section>
1019
+
1020
+
1021
+ <div class="clearer"></div>
1022
+ </div>
1023
+ </div>
1024
+ </div>
1025
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
1026
+ <div class="sphinxsidebarwrapper">
1027
+ <div>
1028
+ <h3><a href="../contents.html">Table of Contents</a></h3>
1029
+ <ul>
1030
+ <li><a class="reference internal" href="#">IDLE</a><ul>
1031
+ <li><a class="reference internal" href="#menus">Menus</a><ul>
1032
+ <li><a class="reference internal" href="#file-menu-shell-and-editor">File menu (Shell and Editor)</a></li>
1033
+ <li><a class="reference internal" href="#edit-menu-shell-and-editor">Edit menu (Shell and Editor)</a></li>
1034
+ <li><a class="reference internal" href="#format-menu-editor-window-only">Format menu (Editor window only)</a></li>
1035
+ <li><a class="reference internal" href="#run-menu-editor-window-only">Run menu (Editor window only)</a></li>
1036
+ <li><a class="reference internal" href="#shell-menu-shell-window-only">Shell menu (Shell window only)</a></li>
1037
+ <li><a class="reference internal" href="#debug-menu-shell-window-only">Debug menu (Shell window only)</a></li>
1038
+ <li><a class="reference internal" href="#options-menu-shell-and-editor">Options menu (Shell and Editor)</a></li>
1039
+ <li><a class="reference internal" href="#window-menu-shell-and-editor">Window menu (Shell and Editor)</a></li>
1040
+ <li><a class="reference internal" href="#help-menu-shell-and-editor">Help menu (Shell and Editor)</a></li>
1041
+ <li><a class="reference internal" href="#context-menus">Context menus</a></li>
1042
+ </ul>
1043
+ </li>
1044
+ <li><a class="reference internal" href="#editing-and-navigation">Editing and Navigation</a><ul>
1045
+ <li><a class="reference internal" href="#editor-windows">Editor windows</a></li>
1046
+ <li><a class="reference internal" href="#key-bindings">Key bindings</a></li>
1047
+ <li><a class="reference internal" href="#automatic-indentation">Automatic indentation</a></li>
1048
+ <li><a class="reference internal" href="#search-and-replace">Search and Replace</a></li>
1049
+ <li><a class="reference internal" href="#completions">Completions</a></li>
1050
+ <li><a class="reference internal" href="#calltips">Calltips</a></li>
1051
+ <li><a class="reference internal" href="#code-context">Code Context</a></li>
1052
+ <li><a class="reference internal" href="#shell-window">Shell window</a></li>
1053
+ <li><a class="reference internal" href="#text-colors">Text colors</a></li>
1054
+ </ul>
1055
+ </li>
1056
+ <li><a class="reference internal" href="#startup-and-code-execution">Startup and Code Execution</a><ul>
1057
+ <li><a class="reference internal" href="#command-line-usage">Command line usage</a></li>
1058
+ <li><a class="reference internal" href="#startup-failure">Startup failure</a></li>
1059
+ <li><a class="reference internal" href="#running-user-code">Running user code</a></li>
1060
+ <li><a class="reference internal" href="#user-output-in-shell">User output in Shell</a></li>
1061
+ <li><a class="reference internal" href="#developing-tkinter-applications">Developing tkinter applications</a></li>
1062
+ <li><a class="reference internal" href="#running-without-a-subprocess">Running without a subprocess</a></li>
1063
+ </ul>
1064
+ </li>
1065
+ <li><a class="reference internal" href="#help-and-preferences">Help and Preferences</a><ul>
1066
+ <li><a class="reference internal" href="#help-sources">Help sources</a></li>
1067
+ <li><a class="reference internal" href="#setting-preferences">Setting preferences</a></li>
1068
+ <li><a class="reference internal" href="#idle-on-macos">IDLE on macOS</a></li>
1069
+ <li><a class="reference internal" href="#extensions">Extensions</a></li>
1070
+ </ul>
1071
+ </li>
1072
+ <li><a class="reference internal" href="#module-idlelib">idlelib</a></li>
1073
+ </ul>
1074
+ </li>
1075
+ </ul>
1076
+
1077
+ </div>
1078
+ <div>
1079
+ <h4>Previous topic</h4>
1080
+ <p class="topless"><a href="tkinter.tix.html"
1081
+ title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter.tix</span></code> — Extension widgets for Tk</a></p>
1082
+ </div>
1083
+ <div>
1084
+ <h4>Next topic</h4>
1085
+ <p class="topless"><a href="development.html"
1086
+ title="next chapter">Development Tools</a></p>
1087
+ </div>
1088
+ <div role="note" aria-label="source link">
1089
+ <h3>This Page</h3>
1090
+ <ul class="this-page-menu">
1091
+ <li><a href="../bugs.html">Report a Bug</a></li>
1092
+ <li>
1093
+ <a href="https://github.com/python/cpython/blob/main/Doc/library/idle.rst"
1094
+ rel="nofollow">Show Source
1095
+ </a>
1096
+ </li>
1097
+ </ul>
1098
+ </div>
1099
+ </div>
1100
+ <div id="sidebarbutton" title="Collapse sidebar">
1101
+ <span>«</span>
1102
+ </div>
1103
+
1104
+ </div>
1105
+ <div class="clearer"></div>
1106
+ </div>
1107
+ <div class="related" role="navigation" aria-label="related navigation">
1108
+ <h3>Navigation</h3>
1109
+ <ul>
1110
+ <li class="right" style="margin-right: 10px">
1111
+ <a href="../genindex.html" title="General Index"
1112
+ >index</a></li>
1113
+ <li class="right" >
1114
+ <a href="../py-modindex.html" title="Python Module Index"
1115
+ >modules</a> |</li>
1116
+ <li class="right" >
1117
+ <a href="development.html" title="Development Tools"
1118
+ >next</a> |</li>
1119
+ <li class="right" >
1120
+ <a href="tkinter.tix.html" title="tkinter.tix — Extension widgets for Tk"
1121
+ >previous</a> |</li>
1122
+
1123
+ <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
1124
+ <li><a href="https://www.python.org/">Python</a> &#187;</li>
1125
+ <li class="switchers">
1126
+ <div class="language_switcher_placeholder"></div>
1127
+ <div class="version_switcher_placeholder"></div>
1128
+ </li>
1129
+ <li>
1130
+
1131
+ </li>
1132
+ <li id="cpython-language-and-version">
1133
+ <a href="../index.html">3.12.0a0 Documentation</a> &#187;
1134
+ </li>
1135
+
1136
+ <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
1137
+ <li class="nav-item nav-item-2"><a href="tk.html" >Graphical User Interfaces with Tk</a> &#187;</li>
1138
+ <li class="nav-item nav-item-this"><a href="">IDLE</a></li>
1139
+ <li class="right">
1140
+
1141
+
1142
+ <div class="inline-search" role="search">
1143
+ <form class="inline-search" action="../search.html" method="get">
1144
+ <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" />
1145
+ <input type="submit" value="Go" />
1146
+ <input type="hidden" name="check_keywords" value="yes" />
1147
+ <input type="hidden" name="area" value="default" />
1148
+ </form>
1149
+ </div>
1150
+ |
1151
+ </li>
1152
+
1153
+ </ul>
1154
+ </div>
1155
+ <div class="footer">
1156
+ &copy; <a href="../copyright.html">Copyright</a> 2001-2022, Python Software Foundation.
1157
+ <br />
1158
+ This page is licensed under the Python Software Foundation License Version 2.
1159
+ <br />
1160
+ Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
1161
+ <br />
1162
+ See <a href="/license.html">History and License</a> for more information.<br />
1163
+ <br />
1164
+
1165
+ The Python Software Foundation is a non-profit corporation.
1166
+ <a href="https://www.python.org/psf/donations/">Please donate.</a>
1167
+ <br />
1168
+ <br />
1169
+
1170
+ Last updated on Sep 03, 2022.
1171
+ <a href="/bugs.html">Found a bug</a>?
1172
+ <br />
1173
+
1174
+ Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 5.0.2.
1175
+ </div>
1176
+
1177
+ </body>
1178
+ </html>
llava/lib/python3.10/idlelib/help.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ help.py: Implement the Idle help menu.
2
+ Contents are subject to revision at any time, without notice.
3
+
4
+
5
+ Help => About IDLE: display About Idle dialog
6
+
7
+ <to be moved here from help_about.py>
8
+
9
+
10
+ Help => IDLE Help: Display help.html with proper formatting.
11
+ Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html
12
+ (help.copy_strip)=> Lib/idlelib/help.html
13
+
14
+ HelpParser - Parse help.html and render to tk Text.
15
+
16
+ HelpText - Display formatted help.html.
17
+
18
+ HelpFrame - Contain text, scrollbar, and table-of-contents.
19
+ (This will be needed for display in a future tabbed window.)
20
+
21
+ HelpWindow - Display HelpFrame in a standalone window.
22
+
23
+ copy_strip - Copy idle.html to help.html, rstripping each line.
24
+
25
+ show_idlehelp - Create HelpWindow. Called in EditorWindow.help_dialog.
26
+ """
27
+ from html.parser import HTMLParser
28
+ from os.path import abspath, dirname, isfile, join
29
+ from platform import python_version
30
+
31
+ from tkinter import Toplevel, Text, Menu
32
+ from tkinter.ttk import Frame, Menubutton, Scrollbar, Style
33
+ from tkinter import font as tkfont
34
+
35
+ from idlelib.config import idleConf
36
+
37
+ ## About IDLE ##
38
+
39
+
40
+ ## IDLE Help ##
41
+
42
+ class HelpParser(HTMLParser):
43
+ """Render help.html into a text widget.
44
+
45
+ The overridden handle_xyz methods handle a subset of html tags.
46
+ The supplied text should have the needed tag configurations.
47
+ The behavior for unsupported tags, such as table, is undefined.
48
+ If the tags generated by Sphinx change, this class, especially
49
+ the handle_starttag and handle_endtags methods, might have to also.
50
+ """
51
+ def __init__(self, text):
52
+ HTMLParser.__init__(self, convert_charrefs=True)
53
+ self.text = text # Text widget we're rendering into.
54
+ self.tags = '' # Current block level text tags to apply.
55
+ self.chartags = '' # Current character level text tags.
56
+ self.show = False # Exclude html page navigation.
57
+ self.hdrlink = False # Exclude html header links.
58
+ self.level = 0 # Track indentation level.
59
+ self.pre = False # Displaying preformatted text?
60
+ self.hprefix = '' # Heading prefix (like '25.5'?) to remove.
61
+ self.nested_dl = False # In a nested <dl>?
62
+ self.simplelist = False # In a simple list (no double spacing)?
63
+ self.toc = [] # Pair headers with text indexes for toc.
64
+ self.header = '' # Text within header tags for toc.
65
+ self.prevtag = None # Previous tag info (opener?, tag).
66
+
67
+ def indent(self, amt=1):
68
+ "Change indent (+1, 0, -1) and tags."
69
+ self.level += amt
70
+ self.tags = '' if self.level == 0 else 'l'+str(self.level)
71
+
72
+ def handle_starttag(self, tag, attrs):
73
+ "Handle starttags in help.html."
74
+ class_ = ''
75
+ for a, v in attrs:
76
+ if a == 'class':
77
+ class_ = v
78
+ s = ''
79
+ if tag == 'section' and attrs == [('id', 'idle')]:
80
+ self.show = True # Start main content.
81
+ elif tag == 'div' and class_ == 'clearer':
82
+ self.show = False # End main content.
83
+ elif tag == 'p' and self.prevtag and not self.prevtag[0]:
84
+ # Begin a new block for <p> tags after a closed tag.
85
+ # Avoid extra lines, e.g. after <pre> tags.
86
+ lastline = self.text.get('end-1c linestart', 'end-1c')
87
+ s = '\n\n' if lastline and not lastline.isspace() else '\n'
88
+ elif tag == 'span' and class_ == 'pre':
89
+ self.chartags = 'pre'
90
+ elif tag == 'span' and class_ == 'versionmodified':
91
+ self.chartags = 'em'
92
+ elif tag == 'em':
93
+ self.chartags = 'em'
94
+ elif tag in ['ul', 'ol']:
95
+ if class_.find('simple') != -1:
96
+ s = '\n'
97
+ self.simplelist = True
98
+ else:
99
+ self.simplelist = False
100
+ self.indent()
101
+ elif tag == 'dl':
102
+ if self.level > 0:
103
+ self.nested_dl = True
104
+ elif tag == 'li':
105
+ s = '\n* ' if self.simplelist else '\n\n* '
106
+ elif tag == 'dt':
107
+ s = '\n\n' if not self.nested_dl else '\n' # Avoid extra line.
108
+ self.nested_dl = False
109
+ elif tag == 'dd':
110
+ self.indent()
111
+ s = '\n'
112
+ elif tag == 'pre':
113
+ self.pre = True
114
+ if self.show:
115
+ self.text.insert('end', '\n\n')
116
+ self.tags = 'preblock'
117
+ elif tag == 'a' and class_ == 'headerlink':
118
+ self.hdrlink = True
119
+ elif tag == 'h1':
120
+ self.tags = tag
121
+ elif tag in ['h2', 'h3']:
122
+ if self.show:
123
+ self.header = ''
124
+ self.text.insert('end', '\n\n')
125
+ self.tags = tag
126
+ if self.show:
127
+ self.text.insert('end', s, (self.tags, self.chartags))
128
+ self.prevtag = (True, tag)
129
+
130
+ def handle_endtag(self, tag):
131
+ "Handle endtags in help.html."
132
+ if tag in ['h1', 'h2', 'h3']:
133
+ assert self.level == 0
134
+ if self.show:
135
+ indent = (' ' if tag == 'h3' else
136
+ ' ' if tag == 'h2' else
137
+ '')
138
+ self.toc.append((indent+self.header, self.text.index('insert')))
139
+ self.tags = ''
140
+ elif tag in ['span', 'em']:
141
+ self.chartags = ''
142
+ elif tag == 'a':
143
+ self.hdrlink = False
144
+ elif tag == 'pre':
145
+ self.pre = False
146
+ self.tags = ''
147
+ elif tag in ['ul', 'dd', 'ol']:
148
+ self.indent(-1)
149
+ self.prevtag = (False, tag)
150
+
151
+ def handle_data(self, data):
152
+ "Handle date segments in help.html."
153
+ if self.show and not self.hdrlink:
154
+ d = data if self.pre else data.replace('\n', ' ')
155
+ if self.tags == 'h1':
156
+ try:
157
+ self.hprefix = d[0:d.index(' ')]
158
+ except ValueError:
159
+ self.hprefix = ''
160
+ if self.tags in ['h1', 'h2', 'h3']:
161
+ if (self.hprefix != '' and
162
+ d[0:len(self.hprefix)] == self.hprefix):
163
+ d = d[len(self.hprefix):]
164
+ self.header += d.strip()
165
+ self.text.insert('end', d, (self.tags, self.chartags))
166
+
167
+
168
+ class HelpText(Text):
169
+ "Display help.html."
170
+ def __init__(self, parent, filename):
171
+ "Configure tags and feed file to parser."
172
+ uwide = idleConf.GetOption('main', 'EditorWindow', 'width', type='int')
173
+ uhigh = idleConf.GetOption('main', 'EditorWindow', 'height', type='int')
174
+ uhigh = 3 * uhigh // 4 # Lines average 4/3 of editor line height.
175
+ Text.__init__(self, parent, wrap='word', highlightthickness=0,
176
+ padx=5, borderwidth=0, width=uwide, height=uhigh)
177
+
178
+ normalfont = self.findfont(['TkDefaultFont', 'arial', 'helvetica'])
179
+ fixedfont = self.findfont(['TkFixedFont', 'monaco', 'courier'])
180
+ self['font'] = (normalfont, 12)
181
+ self.tag_configure('em', font=(normalfont, 12, 'italic'))
182
+ self.tag_configure('h1', font=(normalfont, 20, 'bold'))
183
+ self.tag_configure('h2', font=(normalfont, 18, 'bold'))
184
+ self.tag_configure('h3', font=(normalfont, 15, 'bold'))
185
+ self.tag_configure('pre', font=(fixedfont, 12), background='#f6f6ff')
186
+ self.tag_configure('preblock', font=(fixedfont, 10), lmargin1=25,
187
+ borderwidth=1, relief='solid', background='#eeffcc')
188
+ self.tag_configure('l1', lmargin1=25, lmargin2=25)
189
+ self.tag_configure('l2', lmargin1=50, lmargin2=50)
190
+ self.tag_configure('l3', lmargin1=75, lmargin2=75)
191
+ self.tag_configure('l4', lmargin1=100, lmargin2=100)
192
+
193
+ self.parser = HelpParser(self)
194
+ with open(filename, encoding='utf-8') as f:
195
+ contents = f.read()
196
+ self.parser.feed(contents)
197
+ self['state'] = 'disabled'
198
+
199
+ def findfont(self, names):
200
+ "Return name of first font family derived from names."
201
+ for name in names:
202
+ if name.lower() in (x.lower() for x in tkfont.names(root=self)):
203
+ font = tkfont.Font(name=name, exists=True, root=self)
204
+ return font.actual()['family']
205
+ elif name.lower() in (x.lower()
206
+ for x in tkfont.families(root=self)):
207
+ return name
208
+
209
+
210
+ class HelpFrame(Frame):
211
+ "Display html text, scrollbar, and toc."
212
+ def __init__(self, parent, filename):
213
+ Frame.__init__(self, parent)
214
+ self.text = text = HelpText(self, filename)
215
+ self.style = Style(parent)
216
+ self['style'] = 'helpframe.TFrame'
217
+ self.style.configure('helpframe.TFrame', background=text['background'])
218
+ self.toc = toc = self.toc_menu(text)
219
+ self.scroll = scroll = Scrollbar(self, command=text.yview)
220
+ text['yscrollcommand'] = scroll.set
221
+
222
+ self.rowconfigure(0, weight=1)
223
+ self.columnconfigure(1, weight=1) # Only expand the text widget.
224
+ toc.grid(row=0, column=0, sticky='nw')
225
+ text.grid(row=0, column=1, sticky='nsew')
226
+ scroll.grid(row=0, column=2, sticky='ns')
227
+
228
+ def toc_menu(self, text):
229
+ "Create table of contents as drop-down menu."
230
+ toc = Menubutton(self, text='TOC')
231
+ drop = Menu(toc, tearoff=False)
232
+ for lbl, dex in text.parser.toc:
233
+ drop.add_command(label=lbl, command=lambda dex=dex:text.yview(dex))
234
+ toc['menu'] = drop
235
+ return toc
236
+
237
+
238
+ class HelpWindow(Toplevel):
239
+ "Display frame with rendered html."
240
+ def __init__(self, parent, filename, title):
241
+ Toplevel.__init__(self, parent)
242
+ self.wm_title(title)
243
+ self.protocol("WM_DELETE_WINDOW", self.destroy)
244
+ HelpFrame(self, filename).grid(column=0, row=0, sticky='nsew')
245
+ self.grid_columnconfigure(0, weight=1)
246
+ self.grid_rowconfigure(0, weight=1)
247
+
248
+
249
+ def copy_strip():
250
+ """Copy idle.html to idlelib/help.html, stripping trailing whitespace.
251
+
252
+ Files with trailing whitespace cannot be pushed to the git cpython
253
+ repository. For 3.x (on Windows), help.html is generated, after
254
+ editing idle.rst on the master branch, with
255
+ sphinx-build -bhtml . build/html
256
+ python_d.exe -c "from idlelib.help import copy_strip; copy_strip()"
257
+ Check build/html/library/idle.html, the help.html diff, and the text
258
+ displayed by Help => IDLE Help. Add a blurb and create a PR.
259
+
260
+ It can be worthwhile to occasionally generate help.html without
261
+ touching idle.rst. Changes to the master version and to the doc
262
+ build system may result in changes that should not changed
263
+ the displayed text, but might break HelpParser.
264
+
265
+ As long as master and maintenance versions of idle.rst remain the
266
+ same, help.html can be backported. The internal Python version
267
+ number is not displayed. If maintenance idle.rst diverges from
268
+ the master version, then instead of backporting help.html from
269
+ master, repeat the procedure above to generate a maintenance
270
+ version.
271
+ """
272
+ src = join(abspath(dirname(dirname(dirname(__file__)))),
273
+ 'Doc', 'build', 'html', 'library', 'idle.html')
274
+ dst = join(abspath(dirname(__file__)), 'help.html')
275
+ with open(src, 'rb') as inn,\
276
+ open(dst, 'wb') as out:
277
+ for line in inn:
278
+ out.write(line.rstrip() + b'\n')
279
+ print(f'{src} copied to {dst}')
280
+
281
+ def show_idlehelp(parent):
282
+ "Create HelpWindow; called from Idle Help event handler."
283
+ filename = join(abspath(dirname(__file__)), 'help.html')
284
+ if not isfile(filename):
285
+ # Try copy_strip, present message.
286
+ return
287
+ HelpWindow(parent, filename, 'IDLE Help (%s)' % python_version())
288
+
289
+ if __name__ == '__main__':
290
+ from unittest import main
291
+ main('idlelib.idle_test.test_help', verbosity=2, exit=False)
292
+
293
+ from idlelib.idle_test.htest import run
294
+ run(show_idlehelp)
llava/lib/python3.10/idlelib/percolator.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from idlelib.delegator import Delegator
2
+ from idlelib.redirector import WidgetRedirector
3
+
4
+
5
+ class Percolator:
6
+
7
+ def __init__(self, text):
8
+ # XXX would be nice to inherit from Delegator
9
+ self.text = text
10
+ self.redir = WidgetRedirector(text)
11
+ self.top = self.bottom = Delegator(text)
12
+ self.bottom.insert = self.redir.register("insert", self.insert)
13
+ self.bottom.delete = self.redir.register("delete", self.delete)
14
+ self.filters = []
15
+
16
+ def close(self):
17
+ while self.top is not self.bottom:
18
+ self.removefilter(self.top)
19
+ self.top = None
20
+ self.bottom.setdelegate(None)
21
+ self.bottom = None
22
+ self.redir.close()
23
+ self.redir = None
24
+ self.text = None
25
+
26
+ def insert(self, index, chars, tags=None):
27
+ # Could go away if inheriting from Delegator
28
+ self.top.insert(index, chars, tags)
29
+
30
+ def delete(self, index1, index2=None):
31
+ # Could go away if inheriting from Delegator
32
+ self.top.delete(index1, index2)
33
+
34
+ def insertfilter(self, filter):
35
+ # Perhaps rename to pushfilter()?
36
+ assert isinstance(filter, Delegator)
37
+ assert filter.delegate is None
38
+ filter.setdelegate(self.top)
39
+ self.top = filter
40
+
41
+ def insertfilterafter(self, filter, after):
42
+ assert isinstance(filter, Delegator)
43
+ assert isinstance(after, Delegator)
44
+ assert filter.delegate is None
45
+
46
+ f = self.top
47
+ f.resetcache()
48
+ while f is not after:
49
+ assert f is not self.bottom
50
+ f = f.delegate
51
+ f.resetcache()
52
+
53
+ filter.setdelegate(f.delegate)
54
+ f.setdelegate(filter)
55
+
56
+ def removefilter(self, filter):
57
+ # XXX Perhaps should only support popfilter()?
58
+ assert isinstance(filter, Delegator)
59
+ assert filter.delegate is not None
60
+ f = self.top
61
+ if f is filter:
62
+ self.top = filter.delegate
63
+ filter.setdelegate(None)
64
+ else:
65
+ while f.delegate is not filter:
66
+ assert f is not self.bottom
67
+ f.resetcache()
68
+ f = f.delegate
69
+ f.setdelegate(filter.delegate)
70
+ filter.setdelegate(None)
71
+
72
+
73
+ def _percolator(parent): # htest #
74
+ import tkinter as tk
75
+
76
+ class Tracer(Delegator):
77
+ def __init__(self, name):
78
+ self.name = name
79
+ Delegator.__init__(self, None)
80
+
81
+ def insert(self, *args):
82
+ print(self.name, ": insert", args)
83
+ self.delegate.insert(*args)
84
+
85
+ def delete(self, *args):
86
+ print(self.name, ": delete", args)
87
+ self.delegate.delete(*args)
88
+
89
+ box = tk.Toplevel(parent)
90
+ box.title("Test Percolator")
91
+ x, y = map(int, parent.geometry().split('+')[1:])
92
+ box.geometry("+%d+%d" % (x, y + 175))
93
+ text = tk.Text(box)
94
+ p = Percolator(text)
95
+ pin = p.insertfilter
96
+ pout = p.removefilter
97
+ t1 = Tracer("t1")
98
+ t2 = Tracer("t2")
99
+
100
+ def toggle1():
101
+ (pin if var1.get() else pout)(t1)
102
+ def toggle2():
103
+ (pin if var2.get() else pout)(t2)
104
+
105
+ text.pack()
106
+ var1 = tk.IntVar(parent)
107
+ cb1 = tk.Checkbutton(box, text="Tracer1", command=toggle1, variable=var1)
108
+ cb1.pack()
109
+ var2 = tk.IntVar(parent)
110
+ cb2 = tk.Checkbutton(box, text="Tracer2", command=toggle2, variable=var2)
111
+ cb2.pack()
112
+
113
+ if __name__ == "__main__":
114
+ from unittest import main
115
+ main('idlelib.idle_test.test_percolator', verbosity=2, exit=False)
116
+
117
+ from idlelib.idle_test.htest import run
118
+ run(_percolator)
llava/lib/python3.10/idlelib/query.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dialogs that query users and verify the answer before accepting.
3
+
4
+ Query is the generic base class for a popup dialog.
5
+ The user must either enter a valid answer or close the dialog.
6
+ Entries are validated when <Return> is entered or [Ok] is clicked.
7
+ Entries are ignored when [Cancel] or [X] are clicked.
8
+ The 'return value' is .result set to either a valid answer or None.
9
+
10
+ Subclass SectionName gets a name for a new config file section.
11
+ Configdialog uses it for new highlight theme and keybinding set names.
12
+ Subclass ModuleName gets a name for File => Open Module.
13
+ Subclass HelpSource gets menu item and path for additions to Help menu.
14
+ """
15
+ # Query and Section name result from splitting GetCfgSectionNameDialog
16
+ # of configSectionNameDialog.py (temporarily config_sec.py) into
17
+ # generic and specific parts. 3.6 only, July 2016.
18
+ # ModuleName.entry_ok came from editor.EditorWindow.load_module.
19
+ # HelpSource was extracted from configHelpSourceEdit.py (temporarily
20
+ # config_help.py), with darwin code moved from ok to path_ok.
21
+
22
+ import importlib.util, importlib.abc
23
+ import os
24
+ import shlex
25
+ from sys import executable, platform # Platform is set for one test.
26
+
27
+ from tkinter import Toplevel, StringVar, BooleanVar, W, E, S
28
+ from tkinter.ttk import Frame, Button, Entry, Label, Checkbutton
29
+ from tkinter import filedialog
30
+ from tkinter.font import Font
31
+ from tkinter.simpledialog import _setup_dialog
32
+
33
+ class Query(Toplevel):
34
+ """Base class for getting verified answer from a user.
35
+
36
+ For this base class, accept any non-blank string.
37
+ """
38
+ def __init__(self, parent, title, message, *, text0='', used_names={},
39
+ _htest=False, _utest=False):
40
+ """Create modal popup, return when destroyed.
41
+
42
+ Additional subclass init must be done before this unless
43
+ _utest=True is passed to suppress wait_window().
44
+
45
+ title - string, title of popup dialog
46
+ message - string, informational message to display
47
+ text0 - initial value for entry
48
+ used_names - names already in use
49
+ _htest - bool, change box location when running htest
50
+ _utest - bool, leave window hidden and not modal
51
+ """
52
+ self.parent = parent # Needed for Font call.
53
+ self.message = message
54
+ self.text0 = text0
55
+ self.used_names = used_names
56
+
57
+ Toplevel.__init__(self, parent)
58
+ self.withdraw() # Hide while configuring, especially geometry.
59
+ self.title(title)
60
+ self.transient(parent)
61
+ if not _utest: # Otherwise fail when directly run unittest.
62
+ self.grab_set()
63
+
64
+ _setup_dialog(self)
65
+ if self._windowingsystem == 'aqua':
66
+ self.bind("<Command-.>", self.cancel)
67
+ self.bind('<Key-Escape>', self.cancel)
68
+ self.protocol("WM_DELETE_WINDOW", self.cancel)
69
+ self.bind('<Key-Return>', self.ok)
70
+ self.bind("<KP_Enter>", self.ok)
71
+
72
+ self.create_widgets()
73
+ self.update_idletasks() # Need here for winfo_reqwidth below.
74
+ self.geometry( # Center dialog over parent (or below htest box).
75
+ "+%d+%d" % (
76
+ parent.winfo_rootx() +
77
+ (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
78
+ parent.winfo_rooty() +
79
+ ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
80
+ if not _htest else 150)
81
+ ) )
82
+ self.resizable(height=False, width=False)
83
+
84
+ if not _utest:
85
+ self.deiconify() # Unhide now that geometry set.
86
+ self.entry.focus_set()
87
+ self.wait_window()
88
+
89
+ def create_widgets(self, ok_text='OK'): # Do not replace.
90
+ """Create entry (rows, extras, buttons.
91
+
92
+ Entry stuff on rows 0-2, spanning cols 0-2.
93
+ Buttons on row 99, cols 1, 2.
94
+ """
95
+ # Bind to self the widgets needed for entry_ok or unittest.
96
+ self.frame = frame = Frame(self, padding=10)
97
+ frame.grid(column=0, row=0, sticky='news')
98
+ frame.grid_columnconfigure(0, weight=1)
99
+
100
+ entrylabel = Label(frame, anchor='w', justify='left',
101
+ text=self.message)
102
+ self.entryvar = StringVar(self, self.text0)
103
+ self.entry = Entry(frame, width=30, textvariable=self.entryvar)
104
+ self.error_font = Font(name='TkCaptionFont',
105
+ exists=True, root=self.parent)
106
+ self.entry_error = Label(frame, text=' ', foreground='red',
107
+ font=self.error_font)
108
+ # Display or blank error by setting ['text'] =.
109
+ entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W)
110
+ self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E,
111
+ pady=[10,0])
112
+ self.entry_error.grid(column=0, row=2, columnspan=3, padx=5,
113
+ sticky=W+E)
114
+
115
+ self.create_extra()
116
+
117
+ self.button_ok = Button(
118
+ frame, text=ok_text, default='active', command=self.ok)
119
+ self.button_cancel = Button(
120
+ frame, text='Cancel', command=self.cancel)
121
+
122
+ self.button_ok.grid(column=1, row=99, padx=5)
123
+ self.button_cancel.grid(column=2, row=99, padx=5)
124
+
125
+ def create_extra(self): pass # Override to add widgets.
126
+
127
+ def showerror(self, message, widget=None):
128
+ #self.bell(displayof=self)
129
+ (widget or self.entry_error)['text'] = 'ERROR: ' + message
130
+
131
+ def entry_ok(self): # Example: usually replace.
132
+ "Return non-blank entry or None."
133
+ entry = self.entry.get().strip()
134
+ if not entry:
135
+ self.showerror('blank line.')
136
+ return None
137
+ return entry
138
+
139
+ def ok(self, event=None): # Do not replace.
140
+ '''If entry is valid, bind it to 'result' and destroy tk widget.
141
+
142
+ Otherwise leave dialog open for user to correct entry or cancel.
143
+ '''
144
+ self.entry_error['text'] = ''
145
+ entry = self.entry_ok()
146
+ if entry is not None:
147
+ self.result = entry
148
+ self.destroy()
149
+ else:
150
+ # [Ok] moves focus. (<Return> does not.) Move it back.
151
+ self.entry.focus_set()
152
+
153
+ def cancel(self, event=None): # Do not replace.
154
+ "Set dialog result to None and destroy tk widget."
155
+ self.result = None
156
+ self.destroy()
157
+
158
+ def destroy(self):
159
+ self.grab_release()
160
+ super().destroy()
161
+
162
+
163
+ class SectionName(Query):
164
+ "Get a name for a config file section name."
165
+ # Used in ConfigDialog.GetNewKeysName, .GetNewThemeName (837)
166
+
167
+ def __init__(self, parent, title, message, used_names,
168
+ *, _htest=False, _utest=False):
169
+ super().__init__(parent, title, message, used_names=used_names,
170
+ _htest=_htest, _utest=_utest)
171
+
172
+ def entry_ok(self):
173
+ "Return sensible ConfigParser section name or None."
174
+ name = self.entry.get().strip()
175
+ if not name:
176
+ self.showerror('no name specified.')
177
+ return None
178
+ elif len(name)>30:
179
+ self.showerror('name is longer than 30 characters.')
180
+ return None
181
+ elif name in self.used_names:
182
+ self.showerror('name is already in use.')
183
+ return None
184
+ return name
185
+
186
+
187
+ class ModuleName(Query):
188
+ "Get a module name for Open Module menu entry."
189
+ # Used in open_module (editor.EditorWindow until move to iobinding).
190
+
191
+ def __init__(self, parent, title, message, text0,
192
+ *, _htest=False, _utest=False):
193
+ super().__init__(parent, title, message, text0=text0,
194
+ _htest=_htest, _utest=_utest)
195
+
196
+ def entry_ok(self):
197
+ "Return entered module name as file path or None."
198
+ name = self.entry.get().strip()
199
+ if not name:
200
+ self.showerror('no name specified.')
201
+ return None
202
+ # XXX Ought to insert current file's directory in front of path.
203
+ try:
204
+ spec = importlib.util.find_spec(name)
205
+ except (ValueError, ImportError) as msg:
206
+ self.showerror(str(msg))
207
+ return None
208
+ if spec is None:
209
+ self.showerror("module not found.")
210
+ return None
211
+ if not isinstance(spec.loader, importlib.abc.SourceLoader):
212
+ self.showerror("not a source-based module.")
213
+ return None
214
+ try:
215
+ file_path = spec.loader.get_filename(name)
216
+ except AttributeError:
217
+ self.showerror("loader does not support get_filename.")
218
+ return None
219
+ except ImportError:
220
+ # Some special modules require this (e.g. os.path)
221
+ try:
222
+ file_path = spec.loader.get_filename()
223
+ except TypeError:
224
+ self.showerror("loader failed to get filename.")
225
+ return None
226
+ return file_path
227
+
228
+
229
+ class Goto(Query):
230
+ "Get a positive line number for editor Go To Line."
231
+ # Used in editor.EditorWindow.goto_line_event.
232
+
233
+ def entry_ok(self):
234
+ try:
235
+ lineno = int(self.entry.get())
236
+ except ValueError:
237
+ self.showerror('not a base 10 integer.')
238
+ return None
239
+ if lineno <= 0:
240
+ self.showerror('not a positive integer.')
241
+ return None
242
+ return lineno
243
+
244
+
245
+ class HelpSource(Query):
246
+ "Get menu name and help source for Help menu."
247
+ # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9)
248
+
249
+ def __init__(self, parent, title, *, menuitem='', filepath='',
250
+ used_names={}, _htest=False, _utest=False):
251
+ """Get menu entry and url/local file for Additional Help.
252
+
253
+ User enters a name for the Help resource and a web url or file
254
+ name. The user can browse for the file.
255
+ """
256
+ self.filepath = filepath
257
+ message = 'Name for item on Help menu:'
258
+ super().__init__(
259
+ parent, title, message, text0=menuitem,
260
+ used_names=used_names, _htest=_htest, _utest=_utest)
261
+
262
+ def create_extra(self):
263
+ "Add path widjets to rows 10-12."
264
+ frame = self.frame
265
+ pathlabel = Label(frame, anchor='w', justify='left',
266
+ text='Help File Path: Enter URL or browse for file')
267
+ self.pathvar = StringVar(self, self.filepath)
268
+ self.path = Entry(frame, textvariable=self.pathvar, width=40)
269
+ browse = Button(frame, text='Browse', width=8,
270
+ command=self.browse_file)
271
+ self.path_error = Label(frame, text=' ', foreground='red',
272
+ font=self.error_font)
273
+
274
+ pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0],
275
+ sticky=W)
276
+ self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E,
277
+ pady=[10,0])
278
+ browse.grid(column=2, row=11, padx=5, sticky=W+S)
279
+ self.path_error.grid(column=0, row=12, columnspan=3, padx=5,
280
+ sticky=W+E)
281
+
282
+ def askfilename(self, filetypes, initdir, initfile): # htest #
283
+ # Extracted from browse_file so can mock for unittests.
284
+ # Cannot unittest as cannot simulate button clicks.
285
+ # Test by running htest, such as by running this file.
286
+ return filedialog.Open(parent=self, filetypes=filetypes)\
287
+ .show(initialdir=initdir, initialfile=initfile)
288
+
289
+ def browse_file(self):
290
+ filetypes = [
291
+ ("HTML Files", "*.htm *.html", "TEXT"),
292
+ ("PDF Files", "*.pdf", "TEXT"),
293
+ ("Windows Help Files", "*.chm"),
294
+ ("Text Files", "*.txt", "TEXT"),
295
+ ("All Files", "*")]
296
+ path = self.pathvar.get()
297
+ if path:
298
+ dir, base = os.path.split(path)
299
+ else:
300
+ base = None
301
+ if platform[:3] == 'win':
302
+ dir = os.path.join(os.path.dirname(executable), 'Doc')
303
+ if not os.path.isdir(dir):
304
+ dir = os.getcwd()
305
+ else:
306
+ dir = os.getcwd()
307
+ file = self.askfilename(filetypes, dir, base)
308
+ if file:
309
+ self.pathvar.set(file)
310
+
311
+ item_ok = SectionName.entry_ok # localize for test override
312
+
313
+ def path_ok(self):
314
+ "Simple validity check for menu file path"
315
+ path = self.path.get().strip()
316
+ if not path: #no path specified
317
+ self.showerror('no help file path specified.', self.path_error)
318
+ return None
319
+ elif not path.startswith(('www.', 'http')):
320
+ if path[:5] == 'file:':
321
+ path = path[5:]
322
+ if not os.path.exists(path):
323
+ self.showerror('help file path does not exist.',
324
+ self.path_error)
325
+ return None
326
+ if platform == 'darwin': # for Mac Safari
327
+ path = "file://" + path
328
+ return path
329
+
330
+ def entry_ok(self):
331
+ "Return apparently valid (name, path) or None"
332
+ self.path_error['text'] = ''
333
+ name = self.item_ok()
334
+ path = self.path_ok()
335
+ return None if name is None or path is None else (name, path)
336
+
337
+ class CustomRun(Query):
338
+ """Get settings for custom run of module.
339
+
340
+ 1. Command line arguments to extend sys.argv.
341
+ 2. Whether to restart Shell or not.
342
+ """
343
+ # Used in runscript.run_custom_event
344
+
345
+ def __init__(self, parent, title, *, cli_args=[],
346
+ _htest=False, _utest=False):
347
+ """cli_args is a list of strings.
348
+
349
+ The list is assigned to the default Entry StringVar.
350
+ The strings are displayed joined by ' ' for display.
351
+ """
352
+ message = 'Command Line Arguments for sys.argv:'
353
+ super().__init__(
354
+ parent, title, message, text0=cli_args,
355
+ _htest=_htest, _utest=_utest)
356
+
357
+ def create_extra(self):
358
+ "Add run mode on rows 10-12."
359
+ frame = self.frame
360
+ self.restartvar = BooleanVar(self, value=True)
361
+ restart = Checkbutton(frame, variable=self.restartvar, onvalue=True,
362
+ offvalue=False, text='Restart shell')
363
+ self.args_error = Label(frame, text=' ', foreground='red',
364
+ font=self.error_font)
365
+
366
+ restart.grid(column=0, row=10, columnspan=3, padx=5, sticky='w')
367
+ self.args_error.grid(column=0, row=12, columnspan=3, padx=5,
368
+ sticky='we')
369
+
370
+ def cli_args_ok(self):
371
+ "Validity check and parsing for command line arguments."
372
+ cli_string = self.entry.get().strip()
373
+ try:
374
+ cli_args = shlex.split(cli_string, posix=True)
375
+ except ValueError as err:
376
+ self.showerror(str(err))
377
+ return None
378
+ return cli_args
379
+
380
+ def entry_ok(self):
381
+ "Return apparently valid (cli_args, restart) or None."
382
+ cli_args = self.cli_args_ok()
383
+ restart = self.restartvar.get()
384
+ return None if cli_args is None else (cli_args, restart)
385
+
386
+
387
+ if __name__ == '__main__':
388
+ from unittest import main
389
+ main('idlelib.idle_test.test_query', verbosity=2, exit=False)
390
+
391
+ from idlelib.idle_test.htest import run
392
+ run(Query, HelpSource, CustomRun)
llava/lib/python3.10/idlelib/replace.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replace dialog for IDLE. Inherits SearchDialogBase for GUI.
2
+ Uses idlelib.searchengine.SearchEngine for search capability.
3
+ Defines various replace related functions like replace, replace all,
4
+ and replace+find.
5
+ """
6
+ import re
7
+
8
+ from tkinter import StringVar, TclError
9
+
10
+ from idlelib.searchbase import SearchDialogBase
11
+ from idlelib import searchengine
12
+
13
+
14
+ def replace(text, insert_tags=None):
15
+ """Create or reuse a singleton ReplaceDialog instance.
16
+
17
+ The singleton dialog saves user entries and preferences
18
+ across instances.
19
+
20
+ Args:
21
+ text: Text widget containing the text to be searched.
22
+ """
23
+ root = text._root()
24
+ engine = searchengine.get(root)
25
+ if not hasattr(engine, "_replacedialog"):
26
+ engine._replacedialog = ReplaceDialog(root, engine)
27
+ dialog = engine._replacedialog
28
+ dialog.open(text, insert_tags=insert_tags)
29
+
30
+
31
+ class ReplaceDialog(SearchDialogBase):
32
+ "Dialog for finding and replacing a pattern in text."
33
+
34
+ title = "Replace Dialog"
35
+ icon = "Replace"
36
+
37
+ def __init__(self, root, engine):
38
+ """Create search dialog for finding and replacing text.
39
+
40
+ Uses SearchDialogBase as the basis for the GUI and a
41
+ searchengine instance to prepare the search.
42
+
43
+ Attributes:
44
+ replvar: StringVar containing 'Replace with:' value.
45
+ replent: Entry widget for replvar. Created in
46
+ create_entries().
47
+ ok: Boolean used in searchengine.search_text to indicate
48
+ whether the search includes the selection.
49
+ """
50
+ super().__init__(root, engine)
51
+ self.replvar = StringVar(root)
52
+ self.insert_tags = None
53
+
54
+ def open(self, text, insert_tags=None):
55
+ """Make dialog visible on top of others and ready to use.
56
+
57
+ Also, highlight the currently selected text and set the
58
+ search to include the current selection (self.ok).
59
+
60
+ Args:
61
+ text: Text widget being searched.
62
+ """
63
+ SearchDialogBase.open(self, text)
64
+ try:
65
+ first = text.index("sel.first")
66
+ except TclError:
67
+ first = None
68
+ try:
69
+ last = text.index("sel.last")
70
+ except TclError:
71
+ last = None
72
+ first = first or text.index("insert")
73
+ last = last or first
74
+ self.show_hit(first, last)
75
+ self.ok = True
76
+ self.insert_tags = insert_tags
77
+
78
+ def create_entries(self):
79
+ "Create base and additional label and text entry widgets."
80
+ SearchDialogBase.create_entries(self)
81
+ self.replent = self.make_entry("Replace with:", self.replvar)[0]
82
+
83
+ def create_command_buttons(self):
84
+ """Create base and additional command buttons.
85
+
86
+ The additional buttons are for Find, Replace,
87
+ Replace+Find, and Replace All.
88
+ """
89
+ SearchDialogBase.create_command_buttons(self)
90
+ self.make_button("Find", self.find_it)
91
+ self.make_button("Replace", self.replace_it)
92
+ self.make_button("Replace+Find", self.default_command, isdef=True)
93
+ self.make_button("Replace All", self.replace_all)
94
+
95
+ def find_it(self, event=None):
96
+ "Handle the Find button."
97
+ self.do_find(False)
98
+
99
+ def replace_it(self, event=None):
100
+ """Handle the Replace button.
101
+
102
+ If the find is successful, then perform replace.
103
+ """
104
+ if self.do_find(self.ok):
105
+ self.do_replace()
106
+
107
+ def default_command(self, event=None):
108
+ """Handle the Replace+Find button as the default command.
109
+
110
+ First performs a replace and then, if the replace was
111
+ successful, a find next.
112
+ """
113
+ if self.do_find(self.ok):
114
+ if self.do_replace(): # Only find next match if replace succeeded.
115
+ # A bad re can cause it to fail.
116
+ self.do_find(False)
117
+
118
+ def _replace_expand(self, m, repl):
119
+ "Expand replacement text if regular expression."
120
+ if self.engine.isre():
121
+ try:
122
+ new = m.expand(repl)
123
+ except re.error:
124
+ self.engine.report_error(repl, 'Invalid Replace Expression')
125
+ new = None
126
+ else:
127
+ new = repl
128
+
129
+ return new
130
+
131
+ def replace_all(self, event=None):
132
+ """Handle the Replace All button.
133
+
134
+ Search text for occurrences of the Find value and replace
135
+ each of them. The 'wrap around' value controls the start
136
+ point for searching. If wrap isn't set, then the searching
137
+ starts at the first occurrence after the current selection;
138
+ if wrap is set, the replacement starts at the first line.
139
+ The replacement is always done top-to-bottom in the text.
140
+ """
141
+ prog = self.engine.getprog()
142
+ if not prog:
143
+ return
144
+ repl = self.replvar.get()
145
+ text = self.text
146
+ res = self.engine.search_text(text, prog)
147
+ if not res:
148
+ self.bell()
149
+ return
150
+ text.tag_remove("sel", "1.0", "end")
151
+ text.tag_remove("hit", "1.0", "end")
152
+ line = res[0]
153
+ col = res[1].start()
154
+ if self.engine.iswrap():
155
+ line = 1
156
+ col = 0
157
+ ok = True
158
+ first = last = None
159
+ # XXX ought to replace circular instead of top-to-bottom when wrapping
160
+ text.undo_block_start()
161
+ while res := self.engine.search_forward(
162
+ text, prog, line, col, wrap=False, ok=ok):
163
+ line, m = res
164
+ chars = text.get("%d.0" % line, "%d.0" % (line+1))
165
+ orig = m.group()
166
+ new = self._replace_expand(m, repl)
167
+ if new is None:
168
+ break
169
+ i, j = m.span()
170
+ first = "%d.%d" % (line, i)
171
+ last = "%d.%d" % (line, j)
172
+ if new == orig:
173
+ text.mark_set("insert", last)
174
+ else:
175
+ text.mark_set("insert", first)
176
+ if first != last:
177
+ text.delete(first, last)
178
+ if new:
179
+ text.insert(first, new, self.insert_tags)
180
+ col = i + len(new)
181
+ ok = False
182
+ text.undo_block_stop()
183
+ if first and last:
184
+ self.show_hit(first, last)
185
+ self.close()
186
+
187
+ def do_find(self, ok=False):
188
+ """Search for and highlight next occurrence of pattern in text.
189
+
190
+ No text replacement is done with this option.
191
+ """
192
+ if not self.engine.getprog():
193
+ return False
194
+ text = self.text
195
+ res = self.engine.search_text(text, None, ok)
196
+ if not res:
197
+ self.bell()
198
+ return False
199
+ line, m = res
200
+ i, j = m.span()
201
+ first = "%d.%d" % (line, i)
202
+ last = "%d.%d" % (line, j)
203
+ self.show_hit(first, last)
204
+ self.ok = True
205
+ return True
206
+
207
+ def do_replace(self):
208
+ "Replace search pattern in text with replacement value."
209
+ prog = self.engine.getprog()
210
+ if not prog:
211
+ return False
212
+ text = self.text
213
+ try:
214
+ first = pos = text.index("sel.first")
215
+ last = text.index("sel.last")
216
+ except TclError:
217
+ pos = None
218
+ if not pos:
219
+ first = last = pos = text.index("insert")
220
+ line, col = searchengine.get_line_col(pos)
221
+ chars = text.get("%d.0" % line, "%d.0" % (line+1))
222
+ m = prog.match(chars, col)
223
+ if not prog:
224
+ return False
225
+ new = self._replace_expand(m, self.replvar.get())
226
+ if new is None:
227
+ return False
228
+ text.mark_set("insert", first)
229
+ text.undo_block_start()
230
+ if m.group():
231
+ text.delete(first, last)
232
+ if new:
233
+ text.insert(first, new, self.insert_tags)
234
+ text.undo_block_stop()
235
+ self.show_hit(first, text.index("insert"))
236
+ self.ok = False
237
+ return True
238
+
239
+ def show_hit(self, first, last):
240
+ """Highlight text between first and last indices.
241
+
242
+ Text is highlighted via the 'hit' tag and the marked
243
+ section is brought into view.
244
+
245
+ The colors from the 'hit' tag aren't currently shown
246
+ when the text is displayed. This is due to the 'sel'
247
+ tag being added first, so the colors in the 'sel'
248
+ config are seen instead of the colors for 'hit'.
249
+ """
250
+ text = self.text
251
+ text.mark_set("insert", first)
252
+ text.tag_remove("sel", "1.0", "end")
253
+ text.tag_add("sel", first, last)
254
+ text.tag_remove("hit", "1.0", "end")
255
+ if first == last:
256
+ text.tag_add("hit", first)
257
+ else:
258
+ text.tag_add("hit", first, last)
259
+ text.see("insert")
260
+ text.update_idletasks()
261
+
262
+ def close(self, event=None):
263
+ "Close the dialog and remove hit tags."
264
+ SearchDialogBase.close(self, event)
265
+ self.text.tag_remove("hit", "1.0", "end")
266
+ self.insert_tags = None
267
+
268
+
269
+ def _replace_dialog(parent): # htest #
270
+ from tkinter import Toplevel, Text, END, SEL
271
+ from tkinter.ttk import Frame, Button
272
+
273
+ top = Toplevel(parent)
274
+ top.title("Test ReplaceDialog")
275
+ x, y = map(int, parent.geometry().split('+')[1:])
276
+ top.geometry("+%d+%d" % (x, y + 175))
277
+
278
+ # mock undo delegator methods
279
+ def undo_block_start():
280
+ pass
281
+
282
+ def undo_block_stop():
283
+ pass
284
+
285
+ frame = Frame(top)
286
+ frame.pack()
287
+ text = Text(frame, inactiveselectbackground='gray')
288
+ text.undo_block_start = undo_block_start
289
+ text.undo_block_stop = undo_block_stop
290
+ text.pack()
291
+ text.insert("insert","This is a sample sTring\nPlus MORE.")
292
+ text.focus_set()
293
+
294
+ def show_replace():
295
+ text.tag_add(SEL, "1.0", END)
296
+ replace(text)
297
+ text.tag_remove(SEL, "1.0", END)
298
+
299
+ button = Button(frame, text="Replace", command=show_replace)
300
+ button.pack()
301
+
302
+ if __name__ == '__main__':
303
+ from unittest import main
304
+ main('idlelib.idle_test.test_replace', verbosity=2, exit=False)
305
+
306
+ from idlelib.idle_test.htest import run
307
+ run(_replace_dialog)
llava/lib/python3.10/idlelib/rpc.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RPC Implementation, originally written for the Python Idle IDE
2
+
3
+ For security reasons, GvR requested that Idle's Python execution server process
4
+ connect to the Idle process, which listens for the connection. Since Idle has
5
+ only one client per server, this was not a limitation.
6
+
7
+ +---------------------------------+ +-------------+
8
+ | socketserver.BaseRequestHandler | | SocketIO |
9
+ +---------------------------------+ +-------------+
10
+ ^ | register() |
11
+ | | unregister()|
12
+ | +-------------+
13
+ | ^ ^
14
+ | | |
15
+ | + -------------------+ |
16
+ | | |
17
+ +-------------------------+ +-----------------+
18
+ | RPCHandler | | RPCClient |
19
+ | [attribute of RPCServer]| | |
20
+ +-------------------------+ +-----------------+
21
+
22
+ The RPCServer handler class is expected to provide register/unregister methods.
23
+ RPCHandler inherits the mix-in class SocketIO, which provides these methods.
24
+
25
+ See the Idle run.main() docstring for further information on how this was
26
+ accomplished in Idle.
27
+
28
+ """
29
+ import builtins
30
+ import copyreg
31
+ import io
32
+ import marshal
33
+ import os
34
+ import pickle
35
+ import queue
36
+ import select
37
+ import socket
38
+ import socketserver
39
+ import struct
40
+ import sys
41
+ import threading
42
+ import traceback
43
+ import types
44
+
45
+ def unpickle_code(ms):
46
+ "Return code object from marshal string ms."
47
+ co = marshal.loads(ms)
48
+ assert isinstance(co, types.CodeType)
49
+ return co
50
+
51
+ def pickle_code(co):
52
+ "Return unpickle function and tuple with marshalled co code object."
53
+ assert isinstance(co, types.CodeType)
54
+ ms = marshal.dumps(co)
55
+ return unpickle_code, (ms,)
56
+
57
+ def dumps(obj, protocol=None):
58
+ "Return pickled (or marshalled) string for obj."
59
+ # IDLE passes 'None' to select pickle.DEFAULT_PROTOCOL.
60
+ f = io.BytesIO()
61
+ p = CodePickler(f, protocol)
62
+ p.dump(obj)
63
+ return f.getvalue()
64
+
65
+
66
+ class CodePickler(pickle.Pickler):
67
+ dispatch_table = {types.CodeType: pickle_code, **copyreg.dispatch_table}
68
+
69
+
70
+ BUFSIZE = 8*1024
71
+ LOCALHOST = '127.0.0.1'
72
+
73
+ class RPCServer(socketserver.TCPServer):
74
+
75
+ def __init__(self, addr, handlerclass=None):
76
+ if handlerclass is None:
77
+ handlerclass = RPCHandler
78
+ socketserver.TCPServer.__init__(self, addr, handlerclass)
79
+
80
+ def server_bind(self):
81
+ "Override TCPServer method, no bind() phase for connecting entity"
82
+ pass
83
+
84
+ def server_activate(self):
85
+ """Override TCPServer method, connect() instead of listen()
86
+
87
+ Due to the reversed connection, self.server_address is actually the
88
+ address of the Idle Client to which we are connecting.
89
+
90
+ """
91
+ self.socket.connect(self.server_address)
92
+
93
+ def get_request(self):
94
+ "Override TCPServer method, return already connected socket"
95
+ return self.socket, self.server_address
96
+
97
+ def handle_error(self, request, client_address):
98
+ """Override TCPServer method
99
+
100
+ Error message goes to __stderr__. No error message if exiting
101
+ normally or socket raised EOF. Other exceptions not handled in
102
+ server code will cause os._exit.
103
+
104
+ """
105
+ try:
106
+ raise
107
+ except SystemExit:
108
+ raise
109
+ except:
110
+ erf = sys.__stderr__
111
+ print('\n' + '-'*40, file=erf)
112
+ print('Unhandled server exception!', file=erf)
113
+ print('Thread: %s' % threading.current_thread().name, file=erf)
114
+ print('Client Address: ', client_address, file=erf)
115
+ print('Request: ', repr(request), file=erf)
116
+ traceback.print_exc(file=erf)
117
+ print('\n*** Unrecoverable, server exiting!', file=erf)
118
+ print('-'*40, file=erf)
119
+ os._exit(0)
120
+
121
+ #----------------- end class RPCServer --------------------
122
+
123
+ objecttable = {}
124
+ request_queue = queue.Queue(0)
125
+ response_queue = queue.Queue(0)
126
+
127
+
128
+ class SocketIO:
129
+
130
+ nextseq = 0
131
+
132
+ def __init__(self, sock, objtable=None, debugging=None):
133
+ self.sockthread = threading.current_thread()
134
+ if debugging is not None:
135
+ self.debugging = debugging
136
+ self.sock = sock
137
+ if objtable is None:
138
+ objtable = objecttable
139
+ self.objtable = objtable
140
+ self.responses = {}
141
+ self.cvars = {}
142
+
143
+ def close(self):
144
+ sock = self.sock
145
+ self.sock = None
146
+ if sock is not None:
147
+ sock.close()
148
+
149
+ def exithook(self):
150
+ "override for specific exit action"
151
+ os._exit(0)
152
+
153
+ def debug(self, *args):
154
+ if not self.debugging:
155
+ return
156
+ s = self.location + " " + str(threading.current_thread().name)
157
+ for a in args:
158
+ s = s + " " + str(a)
159
+ print(s, file=sys.__stderr__)
160
+
161
+ def register(self, oid, object):
162
+ self.objtable[oid] = object
163
+
164
+ def unregister(self, oid):
165
+ try:
166
+ del self.objtable[oid]
167
+ except KeyError:
168
+ pass
169
+
170
+ def localcall(self, seq, request):
171
+ self.debug("localcall:", request)
172
+ try:
173
+ how, (oid, methodname, args, kwargs) = request
174
+ except TypeError:
175
+ return ("ERROR", "Bad request format")
176
+ if oid not in self.objtable:
177
+ return ("ERROR", "Unknown object id: %r" % (oid,))
178
+ obj = self.objtable[oid]
179
+ if methodname == "__methods__":
180
+ methods = {}
181
+ _getmethods(obj, methods)
182
+ return ("OK", methods)
183
+ if methodname == "__attributes__":
184
+ attributes = {}
185
+ _getattributes(obj, attributes)
186
+ return ("OK", attributes)
187
+ if not hasattr(obj, methodname):
188
+ return ("ERROR", "Unsupported method name: %r" % (methodname,))
189
+ method = getattr(obj, methodname)
190
+ try:
191
+ if how == 'CALL':
192
+ ret = method(*args, **kwargs)
193
+ if isinstance(ret, RemoteObject):
194
+ ret = remoteref(ret)
195
+ return ("OK", ret)
196
+ elif how == 'QUEUE':
197
+ request_queue.put((seq, (method, args, kwargs)))
198
+ return("QUEUED", None)
199
+ else:
200
+ return ("ERROR", "Unsupported message type: %s" % how)
201
+ except SystemExit:
202
+ raise
203
+ except KeyboardInterrupt:
204
+ raise
205
+ except OSError:
206
+ raise
207
+ except Exception as ex:
208
+ return ("CALLEXC", ex)
209
+ except:
210
+ msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\
211
+ " Object: %s \n Method: %s \n Args: %s\n"
212
+ print(msg % (oid, method, args), file=sys.__stderr__)
213
+ traceback.print_exc(file=sys.__stderr__)
214
+ return ("EXCEPTION", None)
215
+
216
+ def remotecall(self, oid, methodname, args, kwargs):
217
+ self.debug("remotecall:asynccall: ", oid, methodname)
218
+ seq = self.asynccall(oid, methodname, args, kwargs)
219
+ return self.asyncreturn(seq)
220
+
221
+ def remotequeue(self, oid, methodname, args, kwargs):
222
+ self.debug("remotequeue:asyncqueue: ", oid, methodname)
223
+ seq = self.asyncqueue(oid, methodname, args, kwargs)
224
+ return self.asyncreturn(seq)
225
+
226
+ def asynccall(self, oid, methodname, args, kwargs):
227
+ request = ("CALL", (oid, methodname, args, kwargs))
228
+ seq = self.newseq()
229
+ if threading.current_thread() != self.sockthread:
230
+ cvar = threading.Condition()
231
+ self.cvars[seq] = cvar
232
+ self.debug(("asynccall:%d:" % seq), oid, methodname, args, kwargs)
233
+ self.putmessage((seq, request))
234
+ return seq
235
+
236
+ def asyncqueue(self, oid, methodname, args, kwargs):
237
+ request = ("QUEUE", (oid, methodname, args, kwargs))
238
+ seq = self.newseq()
239
+ if threading.current_thread() != self.sockthread:
240
+ cvar = threading.Condition()
241
+ self.cvars[seq] = cvar
242
+ self.debug(("asyncqueue:%d:" % seq), oid, methodname, args, kwargs)
243
+ self.putmessage((seq, request))
244
+ return seq
245
+
246
+ def asyncreturn(self, seq):
247
+ self.debug("asyncreturn:%d:call getresponse(): " % seq)
248
+ response = self.getresponse(seq, wait=0.05)
249
+ self.debug(("asyncreturn:%d:response: " % seq), response)
250
+ return self.decoderesponse(response)
251
+
252
+ def decoderesponse(self, response):
253
+ how, what = response
254
+ if how == "OK":
255
+ return what
256
+ if how == "QUEUED":
257
+ return None
258
+ if how == "EXCEPTION":
259
+ self.debug("decoderesponse: EXCEPTION")
260
+ return None
261
+ if how == "EOF":
262
+ self.debug("decoderesponse: EOF")
263
+ self.decode_interrupthook()
264
+ return None
265
+ if how == "ERROR":
266
+ self.debug("decoderesponse: Internal ERROR:", what)
267
+ raise RuntimeError(what)
268
+ if how == "CALLEXC":
269
+ self.debug("decoderesponse: Call Exception:", what)
270
+ raise what
271
+ raise SystemError(how, what)
272
+
273
+ def decode_interrupthook(self):
274
+ ""
275
+ raise EOFError
276
+
277
+ def mainloop(self):
278
+ """Listen on socket until I/O not ready or EOF
279
+
280
+ pollresponse() will loop looking for seq number None, which
281
+ never comes, and exit on EOFError.
282
+
283
+ """
284
+ try:
285
+ self.getresponse(myseq=None, wait=0.05)
286
+ except EOFError:
287
+ self.debug("mainloop:return")
288
+ return
289
+
290
+ def getresponse(self, myseq, wait):
291
+ response = self._getresponse(myseq, wait)
292
+ if response is not None:
293
+ how, what = response
294
+ if how == "OK":
295
+ response = how, self._proxify(what)
296
+ return response
297
+
298
+ def _proxify(self, obj):
299
+ if isinstance(obj, RemoteProxy):
300
+ return RPCProxy(self, obj.oid)
301
+ if isinstance(obj, list):
302
+ return list(map(self._proxify, obj))
303
+ # XXX Check for other types -- not currently needed
304
+ return obj
305
+
306
+ def _getresponse(self, myseq, wait):
307
+ self.debug("_getresponse:myseq:", myseq)
308
+ if threading.current_thread() is self.sockthread:
309
+ # this thread does all reading of requests or responses
310
+ while True:
311
+ response = self.pollresponse(myseq, wait)
312
+ if response is not None:
313
+ return response
314
+ else:
315
+ # wait for notification from socket handling thread
316
+ cvar = self.cvars[myseq]
317
+ cvar.acquire()
318
+ while myseq not in self.responses:
319
+ cvar.wait()
320
+ response = self.responses[myseq]
321
+ self.debug("_getresponse:%s: thread woke up: response: %s" %
322
+ (myseq, response))
323
+ del self.responses[myseq]
324
+ del self.cvars[myseq]
325
+ cvar.release()
326
+ return response
327
+
328
+ def newseq(self):
329
+ self.nextseq = seq = self.nextseq + 2
330
+ return seq
331
+
332
+ def putmessage(self, message):
333
+ self.debug("putmessage:%d:" % message[0])
334
+ try:
335
+ s = dumps(message)
336
+ except pickle.PicklingError:
337
+ print("Cannot pickle:", repr(message), file=sys.__stderr__)
338
+ raise
339
+ s = struct.pack("<i", len(s)) + s
340
+ while len(s) > 0:
341
+ try:
342
+ r, w, x = select.select([], [self.sock], [])
343
+ n = self.sock.send(s[:BUFSIZE])
344
+ except (AttributeError, TypeError):
345
+ raise OSError("socket no longer exists")
346
+ s = s[n:]
347
+
348
+ buff = b''
349
+ bufneed = 4
350
+ bufstate = 0 # meaning: 0 => reading count; 1 => reading data
351
+
352
+ def pollpacket(self, wait):
353
+ self._stage0()
354
+ if len(self.buff) < self.bufneed:
355
+ r, w, x = select.select([self.sock.fileno()], [], [], wait)
356
+ if len(r) == 0:
357
+ return None
358
+ try:
359
+ s = self.sock.recv(BUFSIZE)
360
+ except OSError:
361
+ raise EOFError
362
+ if len(s) == 0:
363
+ raise EOFError
364
+ self.buff += s
365
+ self._stage0()
366
+ return self._stage1()
367
+
368
+ def _stage0(self):
369
+ if self.bufstate == 0 and len(self.buff) >= 4:
370
+ s = self.buff[:4]
371
+ self.buff = self.buff[4:]
372
+ self.bufneed = struct.unpack("<i", s)[0]
373
+ self.bufstate = 1
374
+
375
+ def _stage1(self):
376
+ if self.bufstate == 1 and len(self.buff) >= self.bufneed:
377
+ packet = self.buff[:self.bufneed]
378
+ self.buff = self.buff[self.bufneed:]
379
+ self.bufneed = 4
380
+ self.bufstate = 0
381
+ return packet
382
+
383
+ def pollmessage(self, wait):
384
+ packet = self.pollpacket(wait)
385
+ if packet is None:
386
+ return None
387
+ try:
388
+ message = pickle.loads(packet)
389
+ except pickle.UnpicklingError:
390
+ print("-----------------------", file=sys.__stderr__)
391
+ print("cannot unpickle packet:", repr(packet), file=sys.__stderr__)
392
+ traceback.print_stack(file=sys.__stderr__)
393
+ print("-----------------------", file=sys.__stderr__)
394
+ raise
395
+ return message
396
+
397
+ def pollresponse(self, myseq, wait):
398
+ """Handle messages received on the socket.
399
+
400
+ Some messages received may be asynchronous 'call' or 'queue' requests,
401
+ and some may be responses for other threads.
402
+
403
+ 'call' requests are passed to self.localcall() with the expectation of
404
+ immediate execution, during which time the socket is not serviced.
405
+
406
+ 'queue' requests are used for tasks (which may block or hang) to be
407
+ processed in a different thread. These requests are fed into
408
+ request_queue by self.localcall(). Responses to queued requests are
409
+ taken from response_queue and sent across the link with the associated
410
+ sequence numbers. Messages in the queues are (sequence_number,
411
+ request/response) tuples and code using this module removing messages
412
+ from the request_queue is responsible for returning the correct
413
+ sequence number in the response_queue.
414
+
415
+ pollresponse() will loop until a response message with the myseq
416
+ sequence number is received, and will save other responses in
417
+ self.responses and notify the owning thread.
418
+
419
+ """
420
+ while True:
421
+ # send queued response if there is one available
422
+ try:
423
+ qmsg = response_queue.get(0)
424
+ except queue.Empty:
425
+ pass
426
+ else:
427
+ seq, response = qmsg
428
+ message = (seq, ('OK', response))
429
+ self.putmessage(message)
430
+ # poll for message on link
431
+ try:
432
+ message = self.pollmessage(wait)
433
+ if message is None: # socket not ready
434
+ return None
435
+ except EOFError:
436
+ self.handle_EOF()
437
+ return None
438
+ except AttributeError:
439
+ return None
440
+ seq, resq = message
441
+ how = resq[0]
442
+ self.debug("pollresponse:%d:myseq:%s" % (seq, myseq))
443
+ # process or queue a request
444
+ if how in ("CALL", "QUEUE"):
445
+ self.debug("pollresponse:%d:localcall:call:" % seq)
446
+ response = self.localcall(seq, resq)
447
+ self.debug("pollresponse:%d:localcall:response:%s"
448
+ % (seq, response))
449
+ if how == "CALL":
450
+ self.putmessage((seq, response))
451
+ elif how == "QUEUE":
452
+ # don't acknowledge the 'queue' request!
453
+ pass
454
+ continue
455
+ # return if completed message transaction
456
+ elif seq == myseq:
457
+ return resq
458
+ # must be a response for a different thread:
459
+ else:
460
+ cv = self.cvars.get(seq, None)
461
+ # response involving unknown sequence number is discarded,
462
+ # probably intended for prior incarnation of server
463
+ if cv is not None:
464
+ cv.acquire()
465
+ self.responses[seq] = resq
466
+ cv.notify()
467
+ cv.release()
468
+ continue
469
+
470
+ def handle_EOF(self):
471
+ "action taken upon link being closed by peer"
472
+ self.EOFhook()
473
+ self.debug("handle_EOF")
474
+ for key in self.cvars:
475
+ cv = self.cvars[key]
476
+ cv.acquire()
477
+ self.responses[key] = ('EOF', None)
478
+ cv.notify()
479
+ cv.release()
480
+ # call our (possibly overridden) exit function
481
+ self.exithook()
482
+
483
+ def EOFhook(self):
484
+ "Classes using rpc client/server can override to augment EOF action"
485
+ pass
486
+
487
+ #----------------- end class SocketIO --------------------
488
+
489
+ class RemoteObject:
490
+ # Token mix-in class
491
+ pass
492
+
493
+
494
+ def remoteref(obj):
495
+ oid = id(obj)
496
+ objecttable[oid] = obj
497
+ return RemoteProxy(oid)
498
+
499
+
500
+ class RemoteProxy:
501
+
502
+ def __init__(self, oid):
503
+ self.oid = oid
504
+
505
+
506
+ class RPCHandler(socketserver.BaseRequestHandler, SocketIO):
507
+
508
+ debugging = False
509
+ location = "#S" # Server
510
+
511
+ def __init__(self, sock, addr, svr):
512
+ svr.current_handler = self ## cgt xxx
513
+ SocketIO.__init__(self, sock)
514
+ socketserver.BaseRequestHandler.__init__(self, sock, addr, svr)
515
+
516
+ def handle(self):
517
+ "handle() method required by socketserver"
518
+ self.mainloop()
519
+
520
+ def get_remote_proxy(self, oid):
521
+ return RPCProxy(self, oid)
522
+
523
+
524
+ class RPCClient(SocketIO):
525
+
526
+ debugging = False
527
+ location = "#C" # Client
528
+
529
+ nextseq = 1 # Requests coming from the client are odd numbered
530
+
531
+ def __init__(self, address, family=socket.AF_INET, type=socket.SOCK_STREAM):
532
+ self.listening_sock = socket.socket(family, type)
533
+ self.listening_sock.bind(address)
534
+ self.listening_sock.listen(1)
535
+
536
+ def accept(self):
537
+ working_sock, address = self.listening_sock.accept()
538
+ if self.debugging:
539
+ print("****** Connection request from ", address, file=sys.__stderr__)
540
+ if address[0] == LOCALHOST:
541
+ SocketIO.__init__(self, working_sock)
542
+ else:
543
+ print("** Invalid host: ", address, file=sys.__stderr__)
544
+ raise OSError
545
+
546
+ def get_remote_proxy(self, oid):
547
+ return RPCProxy(self, oid)
548
+
549
+
550
+ class RPCProxy:
551
+
552
+ __methods = None
553
+ __attributes = None
554
+
555
+ def __init__(self, sockio, oid):
556
+ self.sockio = sockio
557
+ self.oid = oid
558
+
559
+ def __getattr__(self, name):
560
+ if self.__methods is None:
561
+ self.__getmethods()
562
+ if self.__methods.get(name):
563
+ return MethodProxy(self.sockio, self.oid, name)
564
+ if self.__attributes is None:
565
+ self.__getattributes()
566
+ if name in self.__attributes:
567
+ value = self.sockio.remotecall(self.oid, '__getattribute__',
568
+ (name,), {})
569
+ return value
570
+ else:
571
+ raise AttributeError(name)
572
+
573
+ def __getattributes(self):
574
+ self.__attributes = self.sockio.remotecall(self.oid,
575
+ "__attributes__", (), {})
576
+
577
+ def __getmethods(self):
578
+ self.__methods = self.sockio.remotecall(self.oid,
579
+ "__methods__", (), {})
580
+
581
+ def _getmethods(obj, methods):
582
+ # Helper to get a list of methods from an object
583
+ # Adds names to dictionary argument 'methods'
584
+ for name in dir(obj):
585
+ attr = getattr(obj, name)
586
+ if callable(attr):
587
+ methods[name] = 1
588
+ if isinstance(obj, type):
589
+ for super in obj.__bases__:
590
+ _getmethods(super, methods)
591
+
592
+ def _getattributes(obj, attributes):
593
+ for name in dir(obj):
594
+ attr = getattr(obj, name)
595
+ if not callable(attr):
596
+ attributes[name] = 1
597
+
598
+
599
+ class MethodProxy:
600
+
601
+ def __init__(self, sockio, oid, name):
602
+ self.sockio = sockio
603
+ self.oid = oid
604
+ self.name = name
605
+
606
+ def __call__(self, /, *args, **kwargs):
607
+ value = self.sockio.remotecall(self.oid, self.name, args, kwargs)
608
+ return value
609
+
610
+
611
+ # XXX KBK 09Sep03 We need a proper unit test for this module. Previously
612
+ # existing test code was removed at Rev 1.27 (r34098).
613
+
614
+ def displayhook(value):
615
+ """Override standard display hook to use non-locale encoding"""
616
+ if value is None:
617
+ return
618
+ # Set '_' to None to avoid recursion
619
+ builtins._ = None
620
+ text = repr(value)
621
+ try:
622
+ sys.stdout.write(text)
623
+ except UnicodeEncodeError:
624
+ # let's use ascii while utf8-bmp codec doesn't present
625
+ encoding = 'ascii'
626
+ bytes = text.encode(encoding, 'backslashreplace')
627
+ text = bytes.decode(encoding, 'strict')
628
+ sys.stdout.write(text)
629
+ sys.stdout.write("\n")
630
+ builtins._ = value
631
+
632
+
633
+ if __name__ == '__main__':
634
+ from unittest import main
635
+ main('idlelib.idle_test.test_rpc', verbosity=2,)
llava/lib/python3.10/idlelib/run.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ idlelib.run
2
+
3
+ Simplified, pyshell.ModifiedInterpreter spawns a subprocess with
4
+ f'''{sys.executable} -c "__import__('idlelib.run').run.main()"'''
5
+ '.run' is needed because __import__ returns idlelib, not idlelib.run.
6
+ """
7
+ import contextlib
8
+ import functools
9
+ import io
10
+ import linecache
11
+ import queue
12
+ import sys
13
+ import textwrap
14
+ import time
15
+ import traceback
16
+ import _thread as thread
17
+ import threading
18
+ import warnings
19
+
20
+ import idlelib # testing
21
+ from idlelib import autocomplete # AutoComplete, fetch_encodings
22
+ from idlelib import calltip # Calltip
23
+ from idlelib import debugger_r # start_debugger
24
+ from idlelib import debugobj_r # remote_object_tree_item
25
+ from idlelib import iomenu # encoding
26
+ from idlelib import rpc # multiple objects
27
+ from idlelib import stackviewer # StackTreeItem
28
+ import __main__
29
+
30
+ import tkinter # Use tcl and, if startup fails, messagebox.
31
+ if not hasattr(sys.modules['idlelib.run'], 'firstrun'):
32
+ # Undo modifications of tkinter by idlelib imports; see bpo-25507.
33
+ for mod in ('simpledialog', 'messagebox', 'font',
34
+ 'dialog', 'filedialog', 'commondialog',
35
+ 'ttk'):
36
+ delattr(tkinter, mod)
37
+ del sys.modules['tkinter.' + mod]
38
+ # Avoid AttributeError if run again; see bpo-37038.
39
+ sys.modules['idlelib.run'].firstrun = False
40
+
41
+ LOCALHOST = '127.0.0.1'
42
+
43
+ try:
44
+ eof = 'Ctrl-D (end-of-file)'
45
+ exit.eof = eof
46
+ quit.eof = eof
47
+ except NameError: # In case subprocess started with -S (maybe in future).
48
+ pass
49
+
50
+
51
+ def idle_formatwarning(message, category, filename, lineno, line=None):
52
+ """Format warnings the IDLE way."""
53
+
54
+ s = "\nWarning (from warnings module):\n"
55
+ s += ' File \"%s\", line %s\n' % (filename, lineno)
56
+ if line is None:
57
+ line = linecache.getline(filename, lineno)
58
+ line = line.strip()
59
+ if line:
60
+ s += " %s\n" % line
61
+ s += "%s: %s\n" % (category.__name__, message)
62
+ return s
63
+
64
+ def idle_showwarning_subproc(
65
+ message, category, filename, lineno, file=None, line=None):
66
+ """Show Idle-format warning after replacing warnings.showwarning.
67
+
68
+ The only difference is the formatter called.
69
+ """
70
+ if file is None:
71
+ file = sys.stderr
72
+ try:
73
+ file.write(idle_formatwarning(
74
+ message, category, filename, lineno, line))
75
+ except OSError:
76
+ pass # the file (probably stderr) is invalid - this warning gets lost.
77
+
78
+ _warnings_showwarning = None
79
+
80
+ def capture_warnings(capture):
81
+ "Replace warning.showwarning with idle_showwarning_subproc, or reverse."
82
+
83
+ global _warnings_showwarning
84
+ if capture:
85
+ if _warnings_showwarning is None:
86
+ _warnings_showwarning = warnings.showwarning
87
+ warnings.showwarning = idle_showwarning_subproc
88
+ else:
89
+ if _warnings_showwarning is not None:
90
+ warnings.showwarning = _warnings_showwarning
91
+ _warnings_showwarning = None
92
+
93
+ capture_warnings(True)
94
+ tcl = tkinter.Tcl()
95
+
96
+ def handle_tk_events(tcl=tcl):
97
+ """Process any tk events that are ready to be dispatched if tkinter
98
+ has been imported, a tcl interpreter has been created and tk has been
99
+ loaded."""
100
+ tcl.eval("update")
101
+
102
+ # Thread shared globals: Establish a queue between a subthread (which handles
103
+ # the socket) and the main thread (which runs user code), plus global
104
+ # completion, exit and interruptable (the main thread) flags:
105
+
106
+ exit_now = False
107
+ quitting = False
108
+ interruptable = False
109
+
110
+ def main(del_exitfunc=False):
111
+ """Start the Python execution server in a subprocess
112
+
113
+ In the Python subprocess, RPCServer is instantiated with handlerclass
114
+ MyHandler, which inherits register/unregister methods from RPCHandler via
115
+ the mix-in class SocketIO.
116
+
117
+ When the RPCServer 'server' is instantiated, the TCPServer initialization
118
+ creates an instance of run.MyHandler and calls its handle() method.
119
+ handle() instantiates a run.Executive object, passing it a reference to the
120
+ MyHandler object. That reference is saved as attribute rpchandler of the
121
+ Executive instance. The Executive methods have access to the reference and
122
+ can pass it on to entities that they command
123
+ (e.g. debugger_r.Debugger.start_debugger()). The latter, in turn, can
124
+ call MyHandler(SocketIO) register/unregister methods via the reference to
125
+ register and unregister themselves.
126
+
127
+ """
128
+ global exit_now
129
+ global quitting
130
+ global no_exitfunc
131
+ no_exitfunc = del_exitfunc
132
+ #time.sleep(15) # test subprocess not responding
133
+ try:
134
+ assert(len(sys.argv) > 1)
135
+ port = int(sys.argv[-1])
136
+ except:
137
+ print("IDLE Subprocess: no IP port passed in sys.argv.",
138
+ file=sys.__stderr__)
139
+ return
140
+
141
+ capture_warnings(True)
142
+ sys.argv[:] = [""]
143
+ sockthread = threading.Thread(target=manage_socket,
144
+ name='SockThread',
145
+ args=((LOCALHOST, port),))
146
+ sockthread.daemon = True
147
+ sockthread.start()
148
+ while True:
149
+ try:
150
+ if exit_now:
151
+ try:
152
+ exit()
153
+ except KeyboardInterrupt:
154
+ # exiting but got an extra KBI? Try again!
155
+ continue
156
+ try:
157
+ request = rpc.request_queue.get(block=True, timeout=0.05)
158
+ except queue.Empty:
159
+ request = None
160
+ # Issue 32207: calling handle_tk_events here adds spurious
161
+ # queue.Empty traceback to event handling exceptions.
162
+ if request:
163
+ seq, (method, args, kwargs) = request
164
+ ret = method(*args, **kwargs)
165
+ rpc.response_queue.put((seq, ret))
166
+ else:
167
+ handle_tk_events()
168
+ except KeyboardInterrupt:
169
+ if quitting:
170
+ exit_now = True
171
+ continue
172
+ except SystemExit:
173
+ capture_warnings(False)
174
+ raise
175
+ except:
176
+ type, value, tb = sys.exc_info()
177
+ try:
178
+ print_exception()
179
+ rpc.response_queue.put((seq, None))
180
+ except:
181
+ # Link didn't work, print same exception to __stderr__
182
+ traceback.print_exception(type, value, tb, file=sys.__stderr__)
183
+ exit()
184
+ else:
185
+ continue
186
+
187
+ def manage_socket(address):
188
+ for i in range(3):
189
+ time.sleep(i)
190
+ try:
191
+ server = MyRPCServer(address, MyHandler)
192
+ break
193
+ except OSError as err:
194
+ print("IDLE Subprocess: OSError: " + err.args[1] +
195
+ ", retrying....", file=sys.__stderr__)
196
+ socket_error = err
197
+ else:
198
+ print("IDLE Subprocess: Connection to "
199
+ "IDLE GUI failed, exiting.", file=sys.__stderr__)
200
+ show_socket_error(socket_error, address)
201
+ global exit_now
202
+ exit_now = True
203
+ return
204
+ server.handle_request() # A single request only
205
+
206
+ def show_socket_error(err, address):
207
+ "Display socket error from manage_socket."
208
+ import tkinter
209
+ from tkinter.messagebox import showerror
210
+ root = tkinter.Tk()
211
+ fix_scaling(root)
212
+ root.withdraw()
213
+ showerror(
214
+ "Subprocess Connection Error",
215
+ f"IDLE's subprocess can't connect to {address[0]}:{address[1]}.\n"
216
+ f"Fatal OSError #{err.errno}: {err.strerror}.\n"
217
+ "See the 'Startup failure' section of the IDLE doc, online at\n"
218
+ "https://docs.python.org/3/library/idle.html#startup-failure",
219
+ parent=root)
220
+ root.destroy()
221
+
222
+
223
+ def get_message_lines(typ, exc, tb):
224
+ "Return line composing the exception message."
225
+ if typ in (AttributeError, NameError):
226
+ # 3.10+ hints are not directly accessible from python (#44026).
227
+ err = io.StringIO()
228
+ with contextlib.redirect_stderr(err):
229
+ sys.__excepthook__(typ, exc, tb)
230
+ return [err.getvalue().split("\n")[-2] + "\n"]
231
+ else:
232
+ return traceback.format_exception_only(typ, exc)
233
+
234
+
235
+ def print_exception():
236
+ import linecache
237
+ linecache.checkcache()
238
+ flush_stdout()
239
+ efile = sys.stderr
240
+ typ, val, tb = excinfo = sys.exc_info()
241
+ sys.last_type, sys.last_value, sys.last_traceback = excinfo
242
+ seen = set()
243
+
244
+ def print_exc(typ, exc, tb):
245
+ seen.add(id(exc))
246
+ context = exc.__context__
247
+ cause = exc.__cause__
248
+ if cause is not None and id(cause) not in seen:
249
+ print_exc(type(cause), cause, cause.__traceback__)
250
+ print("\nThe above exception was the direct cause "
251
+ "of the following exception:\n", file=efile)
252
+ elif (context is not None and
253
+ not exc.__suppress_context__ and
254
+ id(context) not in seen):
255
+ print_exc(type(context), context, context.__traceback__)
256
+ print("\nDuring handling of the above exception, "
257
+ "another exception occurred:\n", file=efile)
258
+ if tb:
259
+ tbe = traceback.extract_tb(tb)
260
+ print('Traceback (most recent call last):', file=efile)
261
+ exclude = ("run.py", "rpc.py", "threading.py", "queue.py",
262
+ "debugger_r.py", "bdb.py")
263
+ cleanup_traceback(tbe, exclude)
264
+ traceback.print_list(tbe, file=efile)
265
+ lines = get_message_lines(typ, exc, tb)
266
+ for line in lines:
267
+ print(line, end='', file=efile)
268
+
269
+ print_exc(typ, val, tb)
270
+
271
+ def cleanup_traceback(tb, exclude):
272
+ "Remove excluded traces from beginning/end of tb; get cached lines"
273
+ orig_tb = tb[:]
274
+ while tb:
275
+ for rpcfile in exclude:
276
+ if tb[0][0].count(rpcfile):
277
+ break # found an exclude, break for: and delete tb[0]
278
+ else:
279
+ break # no excludes, have left RPC code, break while:
280
+ del tb[0]
281
+ while tb:
282
+ for rpcfile in exclude:
283
+ if tb[-1][0].count(rpcfile):
284
+ break
285
+ else:
286
+ break
287
+ del tb[-1]
288
+ if len(tb) == 0:
289
+ # exception was in IDLE internals, don't prune!
290
+ tb[:] = orig_tb[:]
291
+ print("** IDLE Internal Exception: ", file=sys.stderr)
292
+ rpchandler = rpc.objecttable['exec'].rpchandler
293
+ for i in range(len(tb)):
294
+ fn, ln, nm, line = tb[i]
295
+ if nm == '?':
296
+ nm = "-toplevel-"
297
+ if not line and fn.startswith("<pyshell#"):
298
+ line = rpchandler.remotecall('linecache', 'getline',
299
+ (fn, ln), {})
300
+ tb[i] = fn, ln, nm, line
301
+
302
+ def flush_stdout():
303
+ """XXX How to do this now?"""
304
+
305
+ def exit():
306
+ """Exit subprocess, possibly after first clearing exit functions.
307
+
308
+ If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any
309
+ functions registered with atexit will be removed before exiting.
310
+ (VPython support)
311
+
312
+ """
313
+ if no_exitfunc:
314
+ import atexit
315
+ atexit._clear()
316
+ capture_warnings(False)
317
+ sys.exit(0)
318
+
319
+
320
+ def fix_scaling(root):
321
+ """Scale fonts on HiDPI displays."""
322
+ import tkinter.font
323
+ scaling = float(root.tk.call('tk', 'scaling'))
324
+ if scaling > 1.4:
325
+ for name in tkinter.font.names(root):
326
+ font = tkinter.font.Font(root=root, name=name, exists=True)
327
+ size = int(font['size'])
328
+ if size < 0:
329
+ font['size'] = round(-0.75*size)
330
+
331
+
332
+ def fixdoc(fun, text):
333
+ tem = (fun.__doc__ + '\n\n') if fun.__doc__ is not None else ''
334
+ fun.__doc__ = tem + textwrap.fill(textwrap.dedent(text))
335
+
336
+ RECURSIONLIMIT_DELTA = 30
337
+
338
+ def install_recursionlimit_wrappers():
339
+ """Install wrappers to always add 30 to the recursion limit."""
340
+ # see: bpo-26806
341
+
342
+ @functools.wraps(sys.setrecursionlimit)
343
+ def setrecursionlimit(*args, **kwargs):
344
+ # mimic the original sys.setrecursionlimit()'s input handling
345
+ if kwargs:
346
+ raise TypeError(
347
+ "setrecursionlimit() takes no keyword arguments")
348
+ try:
349
+ limit, = args
350
+ except ValueError:
351
+ raise TypeError(f"setrecursionlimit() takes exactly one "
352
+ f"argument ({len(args)} given)")
353
+ if not limit > 0:
354
+ raise ValueError(
355
+ "recursion limit must be greater or equal than 1")
356
+
357
+ return setrecursionlimit.__wrapped__(limit + RECURSIONLIMIT_DELTA)
358
+
359
+ fixdoc(setrecursionlimit, f"""\
360
+ This IDLE wrapper adds {RECURSIONLIMIT_DELTA} to prevent possible
361
+ uninterruptible loops.""")
362
+
363
+ @functools.wraps(sys.getrecursionlimit)
364
+ def getrecursionlimit():
365
+ return getrecursionlimit.__wrapped__() - RECURSIONLIMIT_DELTA
366
+
367
+ fixdoc(getrecursionlimit, f"""\
368
+ This IDLE wrapper subtracts {RECURSIONLIMIT_DELTA} to compensate
369
+ for the {RECURSIONLIMIT_DELTA} IDLE adds when setting the limit.""")
370
+
371
+ # add the delta to the default recursion limit, to compensate
372
+ sys.setrecursionlimit(sys.getrecursionlimit() + RECURSIONLIMIT_DELTA)
373
+
374
+ sys.setrecursionlimit = setrecursionlimit
375
+ sys.getrecursionlimit = getrecursionlimit
376
+
377
+
378
+ def uninstall_recursionlimit_wrappers():
379
+ """Uninstall the recursion limit wrappers from the sys module.
380
+
381
+ IDLE only uses this for tests. Users can import run and call
382
+ this to remove the wrapping.
383
+ """
384
+ if (
385
+ getattr(sys.setrecursionlimit, '__wrapped__', None) and
386
+ getattr(sys.getrecursionlimit, '__wrapped__', None)
387
+ ):
388
+ sys.setrecursionlimit = sys.setrecursionlimit.__wrapped__
389
+ sys.getrecursionlimit = sys.getrecursionlimit.__wrapped__
390
+ sys.setrecursionlimit(sys.getrecursionlimit() - RECURSIONLIMIT_DELTA)
391
+
392
+
393
+ class MyRPCServer(rpc.RPCServer):
394
+
395
+ def handle_error(self, request, client_address):
396
+ """Override RPCServer method for IDLE
397
+
398
+ Interrupt the MainThread and exit server if link is dropped.
399
+
400
+ """
401
+ global quitting
402
+ try:
403
+ raise
404
+ except SystemExit:
405
+ raise
406
+ except EOFError:
407
+ global exit_now
408
+ exit_now = True
409
+ thread.interrupt_main()
410
+ except:
411
+ erf = sys.__stderr__
412
+ print(textwrap.dedent(f"""
413
+ {'-'*40}
414
+ Unhandled exception in user code execution server!'
415
+ Thread: {threading.current_thread().name}
416
+ IDLE Client Address: {client_address}
417
+ Request: {request!r}
418
+ """), file=erf)
419
+ traceback.print_exc(limit=-20, file=erf)
420
+ print(textwrap.dedent(f"""
421
+ *** Unrecoverable, server exiting!
422
+
423
+ Users should never see this message; it is likely transient.
424
+ If this recurs, report this with a copy of the message
425
+ and an explanation of how to make it repeat.
426
+ {'-'*40}"""), file=erf)
427
+ quitting = True
428
+ thread.interrupt_main()
429
+
430
+
431
+ # Pseudofiles for shell-remote communication (also used in pyshell)
432
+
433
+ class StdioFile(io.TextIOBase):
434
+
435
+ def __init__(self, shell, tags, encoding='utf-8', errors='strict'):
436
+ self.shell = shell
437
+ self.tags = tags
438
+ self._encoding = encoding
439
+ self._errors = errors
440
+
441
+ @property
442
+ def encoding(self):
443
+ return self._encoding
444
+
445
+ @property
446
+ def errors(self):
447
+ return self._errors
448
+
449
+ @property
450
+ def name(self):
451
+ return '<%s>' % self.tags
452
+
453
+ def isatty(self):
454
+ return True
455
+
456
+
457
+ class StdOutputFile(StdioFile):
458
+
459
+ def writable(self):
460
+ return True
461
+
462
+ def write(self, s):
463
+ if self.closed:
464
+ raise ValueError("write to closed file")
465
+ s = str.encode(s, self.encoding, self.errors).decode(self.encoding, self.errors)
466
+ return self.shell.write(s, self.tags)
467
+
468
+
469
+ class StdInputFile(StdioFile):
470
+ _line_buffer = ''
471
+
472
+ def readable(self):
473
+ return True
474
+
475
+ def read(self, size=-1):
476
+ if self.closed:
477
+ raise ValueError("read from closed file")
478
+ if size is None:
479
+ size = -1
480
+ elif not isinstance(size, int):
481
+ raise TypeError('must be int, not ' + type(size).__name__)
482
+ result = self._line_buffer
483
+ self._line_buffer = ''
484
+ if size < 0:
485
+ while line := self.shell.readline():
486
+ result += line
487
+ else:
488
+ while len(result) < size:
489
+ line = self.shell.readline()
490
+ if not line: break
491
+ result += line
492
+ self._line_buffer = result[size:]
493
+ result = result[:size]
494
+ return result
495
+
496
+ def readline(self, size=-1):
497
+ if self.closed:
498
+ raise ValueError("read from closed file")
499
+ if size is None:
500
+ size = -1
501
+ elif not isinstance(size, int):
502
+ raise TypeError('must be int, not ' + type(size).__name__)
503
+ line = self._line_buffer or self.shell.readline()
504
+ if size < 0:
505
+ size = len(line)
506
+ eol = line.find('\n', 0, size)
507
+ if eol >= 0:
508
+ size = eol + 1
509
+ self._line_buffer = line[size:]
510
+ return line[:size]
511
+
512
+ def close(self):
513
+ self.shell.close()
514
+
515
+
516
+ class MyHandler(rpc.RPCHandler):
517
+
518
+ def handle(self):
519
+ """Override base method"""
520
+ executive = Executive(self)
521
+ self.register("exec", executive)
522
+ self.console = self.get_remote_proxy("console")
523
+ sys.stdin = StdInputFile(self.console, "stdin",
524
+ iomenu.encoding, iomenu.errors)
525
+ sys.stdout = StdOutputFile(self.console, "stdout",
526
+ iomenu.encoding, iomenu.errors)
527
+ sys.stderr = StdOutputFile(self.console, "stderr",
528
+ iomenu.encoding, "backslashreplace")
529
+
530
+ sys.displayhook = rpc.displayhook
531
+ # page help() text to shell.
532
+ import pydoc # import must be done here to capture i/o binding
533
+ pydoc.pager = pydoc.plainpager
534
+
535
+ # Keep a reference to stdin so that it won't try to exit IDLE if
536
+ # sys.stdin gets changed from within IDLE's shell. See issue17838.
537
+ self._keep_stdin = sys.stdin
538
+
539
+ install_recursionlimit_wrappers()
540
+
541
+ self.interp = self.get_remote_proxy("interp")
542
+ rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
543
+
544
+ def exithook(self):
545
+ "override SocketIO method - wait for MainThread to shut us down"
546
+ time.sleep(10)
547
+
548
+ def EOFhook(self):
549
+ "Override SocketIO method - terminate wait on callback and exit thread"
550
+ global quitting
551
+ quitting = True
552
+ thread.interrupt_main()
553
+
554
+ def decode_interrupthook(self):
555
+ "interrupt awakened thread"
556
+ global quitting
557
+ quitting = True
558
+ thread.interrupt_main()
559
+
560
+
561
+ class Executive:
562
+
563
+ def __init__(self, rpchandler):
564
+ self.rpchandler = rpchandler
565
+ if idlelib.testing is False:
566
+ self.locals = __main__.__dict__
567
+ self.calltip = calltip.Calltip()
568
+ self.autocomplete = autocomplete.AutoComplete()
569
+ else:
570
+ self.locals = {}
571
+
572
+ def runcode(self, code):
573
+ global interruptable
574
+ try:
575
+ self.user_exc_info = None
576
+ interruptable = True
577
+ try:
578
+ exec(code, self.locals)
579
+ finally:
580
+ interruptable = False
581
+ except SystemExit as e:
582
+ if e.args: # SystemExit called with an argument.
583
+ ob = e.args[0]
584
+ if not isinstance(ob, (type(None), int)):
585
+ print('SystemExit: ' + str(ob), file=sys.stderr)
586
+ # Return to the interactive prompt.
587
+ except:
588
+ self.user_exc_info = sys.exc_info() # For testing, hook, viewer.
589
+ if quitting:
590
+ exit()
591
+ if sys.excepthook is sys.__excepthook__:
592
+ print_exception()
593
+ else:
594
+ try:
595
+ sys.excepthook(*self.user_exc_info)
596
+ except:
597
+ self.user_exc_info = sys.exc_info() # For testing.
598
+ print_exception()
599
+ jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
600
+ if jit:
601
+ self.rpchandler.interp.open_remote_stack_viewer()
602
+ else:
603
+ flush_stdout()
604
+
605
+ def interrupt_the_server(self):
606
+ if interruptable:
607
+ thread.interrupt_main()
608
+
609
+ def start_the_debugger(self, gui_adap_oid):
610
+ return debugger_r.start_debugger(self.rpchandler, gui_adap_oid)
611
+
612
+ def stop_the_debugger(self, idb_adap_oid):
613
+ "Unregister the Idb Adapter. Link objects and Idb then subject to GC"
614
+ self.rpchandler.unregister(idb_adap_oid)
615
+
616
+ def get_the_calltip(self, name):
617
+ return self.calltip.fetch_tip(name)
618
+
619
+ def get_the_completion_list(self, what, mode):
620
+ return self.autocomplete.fetch_completions(what, mode)
621
+
622
+ def stackviewer(self, flist_oid=None):
623
+ if self.user_exc_info:
624
+ typ, val, tb = self.user_exc_info
625
+ else:
626
+ return None
627
+ flist = None
628
+ if flist_oid is not None:
629
+ flist = self.rpchandler.get_remote_proxy(flist_oid)
630
+ while tb and tb.tb_frame.f_globals["__name__"] in ["rpc", "run"]:
631
+ tb = tb.tb_next
632
+ sys.last_type = typ
633
+ sys.last_value = val
634
+ item = stackviewer.StackTreeItem(flist, tb)
635
+ return debugobj_r.remote_object_tree_item(item)
636
+
637
+
638
+ if __name__ == '__main__':
639
+ from unittest import main
640
+ main('idlelib.idle_test.test_run', verbosity=2)
641
+
642
+ capture_warnings(False) # Make sure turned off; see bpo-18081.
llava/lib/python3.10/idlelib/search.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Search dialog for Find, Find Again, and Find Selection
2
+ functionality.
3
+
4
+ Inherits from SearchDialogBase for GUI and uses searchengine
5
+ to prepare search pattern.
6
+ """
7
+ from tkinter import TclError
8
+
9
+ from idlelib import searchengine
10
+ from idlelib.searchbase import SearchDialogBase
11
+
12
+ def _setup(text):
13
+ """Return the new or existing singleton SearchDialog instance.
14
+
15
+ The singleton dialog saves user entries and preferences
16
+ across instances.
17
+
18
+ Args:
19
+ text: Text widget containing the text to be searched.
20
+ """
21
+ root = text._root()
22
+ engine = searchengine.get(root)
23
+ if not hasattr(engine, "_searchdialog"):
24
+ engine._searchdialog = SearchDialog(root, engine)
25
+ return engine._searchdialog
26
+
27
+ def find(text):
28
+ """Open the search dialog.
29
+
30
+ Module-level function to access the singleton SearchDialog
31
+ instance and open the dialog. If text is selected, it is
32
+ used as the search phrase; otherwise, the previous entry
33
+ is used. No search is done with this command.
34
+ """
35
+ pat = text.get("sel.first", "sel.last")
36
+ return _setup(text).open(text, pat) # Open is inherited from SDBase.
37
+
38
+ def find_again(text):
39
+ """Repeat the search for the last pattern and preferences.
40
+
41
+ Module-level function to access the singleton SearchDialog
42
+ instance to search again using the user entries and preferences
43
+ from the last dialog. If there was no prior search, open the
44
+ search dialog; otherwise, perform the search without showing the
45
+ dialog.
46
+ """
47
+ return _setup(text).find_again(text)
48
+
49
+ def find_selection(text):
50
+ """Search for the selected pattern in the text.
51
+
52
+ Module-level function to access the singleton SearchDialog
53
+ instance to search using the selected text. With a text
54
+ selection, perform the search without displaying the dialog.
55
+ Without a selection, use the prior entry as the search phrase
56
+ and don't display the dialog. If there has been no prior
57
+ search, open the search dialog.
58
+ """
59
+ return _setup(text).find_selection(text)
60
+
61
+
62
+ class SearchDialog(SearchDialogBase):
63
+ "Dialog for finding a pattern in text."
64
+
65
+ def create_widgets(self):
66
+ "Create the base search dialog and add a button for Find Next."
67
+ SearchDialogBase.create_widgets(self)
68
+ # TODO - why is this here and not in a create_command_buttons?
69
+ self.make_button("Find Next", self.default_command, isdef=True)
70
+
71
+ def default_command(self, event=None):
72
+ "Handle the Find Next button as the default command."
73
+ if not self.engine.getprog():
74
+ return
75
+ self.find_again(self.text)
76
+
77
+ def find_again(self, text):
78
+ """Repeat the last search.
79
+
80
+ If no search was previously run, open a new search dialog. In
81
+ this case, no search is done.
82
+
83
+ If a search was previously run, the search dialog won't be
84
+ shown and the options from the previous search (including the
85
+ search pattern) will be used to find the next occurrence
86
+ of the pattern. Next is relative based on direction.
87
+
88
+ Position the window to display the located occurrence in the
89
+ text.
90
+
91
+ Return True if the search was successful and False otherwise.
92
+ """
93
+ if not self.engine.getpat():
94
+ self.open(text)
95
+ return False
96
+ if not self.engine.getprog():
97
+ return False
98
+ res = self.engine.search_text(text)
99
+ if res:
100
+ line, m = res
101
+ i, j = m.span()
102
+ first = "%d.%d" % (line, i)
103
+ last = "%d.%d" % (line, j)
104
+ try:
105
+ selfirst = text.index("sel.first")
106
+ sellast = text.index("sel.last")
107
+ if selfirst == first and sellast == last:
108
+ self.bell()
109
+ return False
110
+ except TclError:
111
+ pass
112
+ text.tag_remove("sel", "1.0", "end")
113
+ text.tag_add("sel", first, last)
114
+ text.mark_set("insert", self.engine.isback() and first or last)
115
+ text.see("insert")
116
+ return True
117
+ else:
118
+ self.bell()
119
+ return False
120
+
121
+ def find_selection(self, text):
122
+ """Search for selected text with previous dialog preferences.
123
+
124
+ Instead of using the same pattern for searching (as Find
125
+ Again does), this first resets the pattern to the currently
126
+ selected text. If the selected text isn't changed, then use
127
+ the prior search phrase.
128
+ """
129
+ pat = text.get("sel.first", "sel.last")
130
+ if pat:
131
+ self.engine.setcookedpat(pat)
132
+ return self.find_again(text)
133
+
134
+
135
+ def _search_dialog(parent): # htest #
136
+ "Display search test box."
137
+ from tkinter import Toplevel, Text
138
+ from tkinter.ttk import Frame, Button
139
+
140
+ top = Toplevel(parent)
141
+ top.title("Test SearchDialog")
142
+ x, y = map(int, parent.geometry().split('+')[1:])
143
+ top.geometry("+%d+%d" % (x, y + 175))
144
+
145
+ frame = Frame(top)
146
+ frame.pack()
147
+ text = Text(frame, inactiveselectbackground='gray')
148
+ text.pack()
149
+ text.insert("insert","This is a sample string.\n"*5)
150
+
151
+ def show_find():
152
+ text.tag_add('sel', '1.0', 'end')
153
+ _setup(text).open(text)
154
+ text.tag_remove('sel', '1.0', 'end')
155
+
156
+ button = Button(frame, text="Search (selection ignored)", command=show_find)
157
+ button.pack()
158
+
159
+ if __name__ == '__main__':
160
+ from unittest import main
161
+ main('idlelib.idle_test.test_search', verbosity=2, exit=False)
162
+
163
+ from idlelib.idle_test.htest import run
164
+ run(_search_dialog)
llava/lib/python3.10/idlelib/searchengine.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Define SearchEngine for search dialogs.'''
2
+ import re
3
+
4
+ from tkinter import StringVar, BooleanVar, TclError
5
+ from tkinter import messagebox
6
+
7
+ def get(root):
8
+ '''Return the singleton SearchEngine instance for the process.
9
+
10
+ The single SearchEngine saves settings between dialog instances.
11
+ If there is not a SearchEngine already, make one.
12
+ '''
13
+ if not hasattr(root, "_searchengine"):
14
+ root._searchengine = SearchEngine(root)
15
+ # This creates a cycle that persists until root is deleted.
16
+ return root._searchengine
17
+
18
+
19
+ class SearchEngine:
20
+ """Handles searching a text widget for Find, Replace, and Grep."""
21
+
22
+ def __init__(self, root):
23
+ '''Initialize Variables that save search state.
24
+
25
+ The dialogs bind these to the UI elements present in the dialogs.
26
+ '''
27
+ self.root = root # need for report_error()
28
+ self.patvar = StringVar(root, '') # search pattern
29
+ self.revar = BooleanVar(root, False) # regular expression?
30
+ self.casevar = BooleanVar(root, False) # match case?
31
+ self.wordvar = BooleanVar(root, False) # match whole word?
32
+ self.wrapvar = BooleanVar(root, True) # wrap around buffer?
33
+ self.backvar = BooleanVar(root, False) # search backwards?
34
+
35
+ # Access methods
36
+
37
+ def getpat(self):
38
+ return self.patvar.get()
39
+
40
+ def setpat(self, pat):
41
+ self.patvar.set(pat)
42
+
43
+ def isre(self):
44
+ return self.revar.get()
45
+
46
+ def iscase(self):
47
+ return self.casevar.get()
48
+
49
+ def isword(self):
50
+ return self.wordvar.get()
51
+
52
+ def iswrap(self):
53
+ return self.wrapvar.get()
54
+
55
+ def isback(self):
56
+ return self.backvar.get()
57
+
58
+ # Higher level access methods
59
+
60
+ def setcookedpat(self, pat):
61
+ "Set pattern after escaping if re."
62
+ # called only in search.py: 66
63
+ if self.isre():
64
+ pat = re.escape(pat)
65
+ self.setpat(pat)
66
+
67
+ def getcookedpat(self):
68
+ pat = self.getpat()
69
+ if not self.isre(): # if True, see setcookedpat
70
+ pat = re.escape(pat)
71
+ if self.isword():
72
+ pat = r"\b%s\b" % pat
73
+ return pat
74
+
75
+ def getprog(self):
76
+ "Return compiled cooked search pattern."
77
+ pat = self.getpat()
78
+ if not pat:
79
+ self.report_error(pat, "Empty regular expression")
80
+ return None
81
+ pat = self.getcookedpat()
82
+ flags = 0
83
+ if not self.iscase():
84
+ flags = flags | re.IGNORECASE
85
+ try:
86
+ prog = re.compile(pat, flags)
87
+ except re.error as e:
88
+ self.report_error(pat, e.msg, e.pos)
89
+ return None
90
+ return prog
91
+
92
+ def report_error(self, pat, msg, col=None):
93
+ # Derived class could override this with something fancier
94
+ msg = "Error: " + str(msg)
95
+ if pat:
96
+ msg = msg + "\nPattern: " + str(pat)
97
+ if col is not None:
98
+ msg = msg + "\nOffset: " + str(col)
99
+ messagebox.showerror("Regular expression error",
100
+ msg, master=self.root)
101
+
102
+ def search_text(self, text, prog=None, ok=0):
103
+ '''Return (lineno, matchobj) or None for forward/backward search.
104
+
105
+ This function calls the right function with the right arguments.
106
+ It directly return the result of that call.
107
+
108
+ Text is a text widget. Prog is a precompiled pattern.
109
+ The ok parameter is a bit complicated as it has two effects.
110
+
111
+ If there is a selection, the search begin at either end,
112
+ depending on the direction setting and ok, with ok meaning that
113
+ the search starts with the selection. Otherwise, search begins
114
+ at the insert mark.
115
+
116
+ To aid progress, the search functions do not return an empty
117
+ match at the starting position unless ok is True.
118
+ '''
119
+
120
+ if not prog:
121
+ prog = self.getprog()
122
+ if not prog:
123
+ return None # Compilation failed -- stop
124
+ wrap = self.wrapvar.get()
125
+ first, last = get_selection(text)
126
+ if self.isback():
127
+ if ok:
128
+ start = last
129
+ else:
130
+ start = first
131
+ line, col = get_line_col(start)
132
+ res = self.search_backward(text, prog, line, col, wrap, ok)
133
+ else:
134
+ if ok:
135
+ start = first
136
+ else:
137
+ start = last
138
+ line, col = get_line_col(start)
139
+ res = self.search_forward(text, prog, line, col, wrap, ok)
140
+ return res
141
+
142
+ def search_forward(self, text, prog, line, col, wrap, ok=0):
143
+ wrapped = 0
144
+ startline = line
145
+ chars = text.get("%d.0" % line, "%d.0" % (line+1))
146
+ while chars:
147
+ m = prog.search(chars[:-1], col)
148
+ if m:
149
+ if ok or m.end() > col:
150
+ return line, m
151
+ line = line + 1
152
+ if wrapped and line > startline:
153
+ break
154
+ col = 0
155
+ ok = 1
156
+ chars = text.get("%d.0" % line, "%d.0" % (line+1))
157
+ if not chars and wrap:
158
+ wrapped = 1
159
+ wrap = 0
160
+ line = 1
161
+ chars = text.get("1.0", "2.0")
162
+ return None
163
+
164
+ def search_backward(self, text, prog, line, col, wrap, ok=0):
165
+ wrapped = 0
166
+ startline = line
167
+ chars = text.get("%d.0" % line, "%d.0" % (line+1))
168
+ while True:
169
+ m = search_reverse(prog, chars[:-1], col)
170
+ if m:
171
+ if ok or m.start() < col:
172
+ return line, m
173
+ line = line - 1
174
+ if wrapped and line < startline:
175
+ break
176
+ ok = 1
177
+ if line <= 0:
178
+ if not wrap:
179
+ break
180
+ wrapped = 1
181
+ wrap = 0
182
+ pos = text.index("end-1c")
183
+ line, col = map(int, pos.split("."))
184
+ chars = text.get("%d.0" % line, "%d.0" % (line+1))
185
+ col = len(chars) - 1
186
+ return None
187
+
188
+
189
+ def search_reverse(prog, chars, col):
190
+ '''Search backwards and return an re match object or None.
191
+
192
+ This is done by searching forwards until there is no match.
193
+ Prog: compiled re object with a search method returning a match.
194
+ Chars: line of text, without \\n.
195
+ Col: stop index for the search; the limit for match.end().
196
+ '''
197
+ m = prog.search(chars)
198
+ if not m:
199
+ return None
200
+ found = None
201
+ i, j = m.span() # m.start(), m.end() == match slice indexes
202
+ while i < col and j <= col:
203
+ found = m
204
+ if i == j:
205
+ j = j+1
206
+ m = prog.search(chars, j)
207
+ if not m:
208
+ break
209
+ i, j = m.span()
210
+ return found
211
+
212
+ def get_selection(text):
213
+ '''Return tuple of 'line.col' indexes from selection or insert mark.
214
+ '''
215
+ try:
216
+ first = text.index("sel.first")
217
+ last = text.index("sel.last")
218
+ except TclError:
219
+ first = last = None
220
+ if not first:
221
+ first = text.index("insert")
222
+ if not last:
223
+ last = first
224
+ return first, last
225
+
226
+ def get_line_col(index):
227
+ '''Return (line, col) tuple of ints from 'line.col' string.'''
228
+ line, col = map(int, index.split(".")) # Fails on invalid index
229
+ return line, col
230
+
231
+
232
+ if __name__ == "__main__":
233
+ from unittest import main
234
+ main('idlelib.idle_test.test_searchengine', verbosity=2)
llava/lib/python3.10/idlelib/stackviewer.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import linecache
2
+ import os
3
+ import sys
4
+
5
+ import tkinter as tk
6
+
7
+ from idlelib.debugobj import ObjectTreeItem, make_objecttreeitem
8
+ from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
9
+
10
+ def StackBrowser(root, flist=None, tb=None, top=None):
11
+ global sc, item, node # For testing.
12
+ if top is None:
13
+ top = tk.Toplevel(root)
14
+ sc = ScrolledCanvas(top, bg="white", highlightthickness=0)
15
+ sc.frame.pack(expand=1, fill="both")
16
+ item = StackTreeItem(flist, tb)
17
+ node = TreeNode(sc.canvas, None, item)
18
+ node.expand()
19
+
20
+
21
+ class StackTreeItem(TreeItem):
22
+
23
+ def __init__(self, flist=None, tb=None):
24
+ self.flist = flist
25
+ self.stack = self.get_stack(tb)
26
+ self.text = self.get_exception()
27
+
28
+ def get_stack(self, tb):
29
+ if tb is None:
30
+ tb = sys.last_traceback
31
+ stack = []
32
+ if tb and tb.tb_frame is None:
33
+ tb = tb.tb_next
34
+ while tb is not None:
35
+ stack.append((tb.tb_frame, tb.tb_lineno))
36
+ tb = tb.tb_next
37
+ return stack
38
+
39
+ def get_exception(self):
40
+ type = sys.last_type
41
+ value = sys.last_value
42
+ if hasattr(type, "__name__"):
43
+ type = type.__name__
44
+ s = str(type)
45
+ if value is not None:
46
+ s = s + ": " + str(value)
47
+ return s
48
+
49
+ def GetText(self):
50
+ return self.text
51
+
52
+ def GetSubList(self):
53
+ sublist = []
54
+ for info in self.stack:
55
+ item = FrameTreeItem(info, self.flist)
56
+ sublist.append(item)
57
+ return sublist
58
+
59
+
60
+ class FrameTreeItem(TreeItem):
61
+
62
+ def __init__(self, info, flist):
63
+ self.info = info
64
+ self.flist = flist
65
+
66
+ def GetText(self):
67
+ frame, lineno = self.info
68
+ try:
69
+ modname = frame.f_globals["__name__"]
70
+ except:
71
+ modname = "?"
72
+ code = frame.f_code
73
+ filename = code.co_filename
74
+ funcname = code.co_name
75
+ sourceline = linecache.getline(filename, lineno)
76
+ sourceline = sourceline.strip()
77
+ if funcname in ("?", "", None):
78
+ item = "%s, line %d: %s" % (modname, lineno, sourceline)
79
+ else:
80
+ item = "%s.%s(...), line %d: %s" % (modname, funcname,
81
+ lineno, sourceline)
82
+ return item
83
+
84
+ def GetSubList(self):
85
+ frame, lineno = self.info
86
+ sublist = []
87
+ if frame.f_globals is not frame.f_locals:
88
+ item = VariablesTreeItem("<locals>", frame.f_locals, self.flist)
89
+ sublist.append(item)
90
+ item = VariablesTreeItem("<globals>", frame.f_globals, self.flist)
91
+ sublist.append(item)
92
+ return sublist
93
+
94
+ def OnDoubleClick(self):
95
+ if self.flist:
96
+ frame, lineno = self.info
97
+ filename = frame.f_code.co_filename
98
+ if os.path.isfile(filename):
99
+ self.flist.gotofileline(filename, lineno)
100
+
101
+
102
+ class VariablesTreeItem(ObjectTreeItem):
103
+
104
+ def GetText(self):
105
+ return self.labeltext
106
+
107
+ def GetLabelText(self):
108
+ return None
109
+
110
+ def IsExpandable(self):
111
+ return len(self.object) > 0
112
+
113
+ def GetSubList(self):
114
+ sublist = []
115
+ for key in self.object.keys():
116
+ try:
117
+ value = self.object[key]
118
+ except KeyError:
119
+ continue
120
+ def setfunction(value, key=key, object=self.object):
121
+ object[key] = value
122
+ item = make_objecttreeitem(key + " =", value, setfunction)
123
+ sublist.append(item)
124
+ return sublist
125
+
126
+
127
+ def _stack_viewer(parent): # htest #
128
+ from idlelib.pyshell import PyShellFileList
129
+ top = tk.Toplevel(parent)
130
+ top.title("Test StackViewer")
131
+ x, y = map(int, parent.geometry().split('+')[1:])
132
+ top.geometry("+%d+%d" % (x + 50, y + 175))
133
+ flist = PyShellFileList(top)
134
+ try: # to obtain a traceback object
135
+ intentional_name_error
136
+ except NameError:
137
+ exc_type, exc_value, exc_tb = sys.exc_info()
138
+ # inject stack trace to sys
139
+ sys.last_type = exc_type
140
+ sys.last_value = exc_value
141
+ sys.last_traceback = exc_tb
142
+
143
+ StackBrowser(top, flist=flist, top=top, tb=exc_tb)
144
+
145
+ # restore sys to original state
146
+ del sys.last_type
147
+ del sys.last_value
148
+ del sys.last_traceback
149
+
150
+ if __name__ == '__main__':
151
+ from unittest import main
152
+ main('idlelib.idle_test.test_stackviewer', verbosity=2, exit=False)
153
+
154
+ from idlelib.idle_test.htest import run
155
+ run(_stack_viewer)
llava/lib/python3.10/idlelib/textview.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple text browser for IDLE
2
+
3
+ """
4
+ from tkinter import Toplevel, Text, TclError,\
5
+ HORIZONTAL, VERTICAL, NS, EW, NSEW, NONE, WORD, SUNKEN
6
+ from tkinter.ttk import Frame, Scrollbar, Button
7
+ from tkinter.messagebox import showerror
8
+
9
+ from idlelib.colorizer import color_config
10
+
11
+
12
+ class AutoHideScrollbar(Scrollbar):
13
+ """A scrollbar that is automatically hidden when not needed.
14
+
15
+ Only the grid geometry manager is supported.
16
+ """
17
+ def set(self, lo, hi):
18
+ if float(lo) > 0.0 or float(hi) < 1.0:
19
+ self.grid()
20
+ else:
21
+ self.grid_remove()
22
+ super().set(lo, hi)
23
+
24
+ def pack(self, **kwargs):
25
+ raise TclError(f'{self.__class__.__name__} does not support "pack"')
26
+
27
+ def place(self, **kwargs):
28
+ raise TclError(f'{self.__class__.__name__} does not support "place"')
29
+
30
+
31
+ class ScrollableTextFrame(Frame):
32
+ """Display text with scrollbar(s)."""
33
+
34
+ def __init__(self, master, wrap=NONE, **kwargs):
35
+ """Create a frame for Textview.
36
+
37
+ master - master widget for this frame
38
+ wrap - type of text wrapping to use ('word', 'char' or 'none')
39
+
40
+ All parameters except for 'wrap' are passed to Frame.__init__().
41
+
42
+ The Text widget is accessible via the 'text' attribute.
43
+
44
+ Note: Changing the wrapping mode of the text widget after
45
+ instantiation is not supported.
46
+ """
47
+ super().__init__(master, **kwargs)
48
+
49
+ text = self.text = Text(self, wrap=wrap)
50
+ text.grid(row=0, column=0, sticky=NSEW)
51
+ self.grid_rowconfigure(0, weight=1)
52
+ self.grid_columnconfigure(0, weight=1)
53
+
54
+ # vertical scrollbar
55
+ self.yscroll = AutoHideScrollbar(self, orient=VERTICAL,
56
+ takefocus=False,
57
+ command=text.yview)
58
+ self.yscroll.grid(row=0, column=1, sticky=NS)
59
+ text['yscrollcommand'] = self.yscroll.set
60
+
61
+ # horizontal scrollbar - only when wrap is set to NONE
62
+ if wrap == NONE:
63
+ self.xscroll = AutoHideScrollbar(self, orient=HORIZONTAL,
64
+ takefocus=False,
65
+ command=text.xview)
66
+ self.xscroll.grid(row=1, column=0, sticky=EW)
67
+ text['xscrollcommand'] = self.xscroll.set
68
+ else:
69
+ self.xscroll = None
70
+
71
+
72
+ class ViewFrame(Frame):
73
+ "Display TextFrame and Close button."
74
+ def __init__(self, parent, contents, wrap='word'):
75
+ """Create a frame for viewing text with a "Close" button.
76
+
77
+ parent - parent widget for this frame
78
+ contents - text to display
79
+ wrap - type of text wrapping to use ('word', 'char' or 'none')
80
+
81
+ The Text widget is accessible via the 'text' attribute.
82
+ """
83
+ super().__init__(parent)
84
+ self.parent = parent
85
+ self.bind('<Return>', self.ok)
86
+ self.bind('<Escape>', self.ok)
87
+ self.textframe = ScrollableTextFrame(self, relief=SUNKEN, height=700)
88
+
89
+ text = self.text = self.textframe.text
90
+ text.insert('1.0', contents)
91
+ text.configure(wrap=wrap, highlightthickness=0, state='disabled')
92
+ color_config(text)
93
+ text.focus_set()
94
+
95
+ self.button_ok = button_ok = Button(
96
+ self, text='Close', command=self.ok, takefocus=False)
97
+ self.textframe.pack(side='top', expand=True, fill='both')
98
+ button_ok.pack(side='bottom')
99
+
100
+ def ok(self, event=None):
101
+ """Dismiss text viewer dialog."""
102
+ self.parent.destroy()
103
+
104
+
105
+ class ViewWindow(Toplevel):
106
+ "A simple text viewer dialog for IDLE."
107
+
108
+ def __init__(self, parent, title, contents, modal=True, wrap=WORD,
109
+ *, _htest=False, _utest=False):
110
+ """Show the given text in a scrollable window with a 'close' button.
111
+
112
+ If modal is left True, users cannot interact with other windows
113
+ until the textview window is closed.
114
+
115
+ parent - parent of this dialog
116
+ title - string which is title of popup dialog
117
+ contents - text to display in dialog
118
+ wrap - type of text wrapping to use ('word', 'char' or 'none')
119
+ _htest - bool; change box location when running htest.
120
+ _utest - bool; don't wait_window when running unittest.
121
+ """
122
+ super().__init__(parent)
123
+ self['borderwidth'] = 5
124
+ # Place dialog below parent if running htest.
125
+ x = parent.winfo_rootx() + 10
126
+ y = parent.winfo_rooty() + (10 if not _htest else 100)
127
+ self.geometry(f'=750x500+{x}+{y}')
128
+
129
+ self.title(title)
130
+ self.viewframe = ViewFrame(self, contents, wrap=wrap)
131
+ self.protocol("WM_DELETE_WINDOW", self.ok)
132
+ self.button_ok = button_ok = Button(self, text='Close',
133
+ command=self.ok, takefocus=False)
134
+ self.viewframe.pack(side='top', expand=True, fill='both')
135
+
136
+ self.is_modal = modal
137
+ if self.is_modal:
138
+ self.transient(parent)
139
+ self.grab_set()
140
+ if not _utest:
141
+ self.wait_window()
142
+
143
+ def ok(self, event=None):
144
+ """Dismiss text viewer dialog."""
145
+ if self.is_modal:
146
+ self.grab_release()
147
+ self.destroy()
148
+
149
+
150
+ def view_text(parent, title, contents, modal=True, wrap='word', _utest=False):
151
+ """Create text viewer for given text.
152
+
153
+ parent - parent of this dialog
154
+ title - string which is the title of popup dialog
155
+ contents - text to display in this dialog
156
+ wrap - type of text wrapping to use ('word', 'char' or 'none')
157
+ modal - controls if users can interact with other windows while this
158
+ dialog is displayed
159
+ _utest - bool; controls wait_window on unittest
160
+ """
161
+ return ViewWindow(parent, title, contents, modal, wrap=wrap, _utest=_utest)
162
+
163
+
164
+ def view_file(parent, title, filename, encoding, modal=True, wrap='word',
165
+ _utest=False):
166
+ """Create text viewer for text in filename.
167
+
168
+ Return error message if file cannot be read. Otherwise calls view_text
169
+ with contents of the file.
170
+ """
171
+ try:
172
+ with open(filename, 'r', encoding=encoding) as file:
173
+ contents = file.read()
174
+ except OSError:
175
+ showerror(title='File Load Error',
176
+ message=f'Unable to load file {filename!r} .',
177
+ parent=parent)
178
+ except UnicodeDecodeError as err:
179
+ showerror(title='Unicode Decode Error',
180
+ message=str(err),
181
+ parent=parent)
182
+ else:
183
+ return view_text(parent, title, contents, modal, wrap=wrap,
184
+ _utest=_utest)
185
+ return None
186
+
187
+
188
+ if __name__ == '__main__':
189
+ from unittest import main
190
+ main('idlelib.idle_test.test_textview', verbosity=2, exit=False)
191
+
192
+ from idlelib.idle_test.htest import run
193
+ run(ViewWindow)
llava/lib/python3.10/idlelib/tooltip.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for displaying tool-tips.
2
+
3
+ This includes:
4
+ * an abstract base-class for different kinds of tooltips
5
+ * a simple text-only Tooltip class
6
+ """
7
+ from tkinter import *
8
+
9
+
10
+ class TooltipBase:
11
+ """abstract base class for tooltips"""
12
+
13
+ def __init__(self, anchor_widget):
14
+ """Create a tooltip.
15
+
16
+ anchor_widget: the widget next to which the tooltip will be shown
17
+
18
+ Note that a widget will only be shown when showtip() is called.
19
+ """
20
+ self.anchor_widget = anchor_widget
21
+ self.tipwindow = None
22
+
23
+ def __del__(self):
24
+ self.hidetip()
25
+
26
+ def showtip(self):
27
+ """display the tooltip"""
28
+ if self.tipwindow:
29
+ return
30
+ self.tipwindow = tw = Toplevel(self.anchor_widget)
31
+ # show no border on the top level window
32
+ tw.wm_overrideredirect(1)
33
+ try:
34
+ # This command is only needed and available on Tk >= 8.4.0 for OSX.
35
+ # Without it, call tips intrude on the typing process by grabbing
36
+ # the focus.
37
+ tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w,
38
+ "help", "noActivates")
39
+ except TclError:
40
+ pass
41
+
42
+ self.position_window()
43
+ self.showcontents()
44
+ self.tipwindow.update_idletasks() # Needed on MacOS -- see #34275.
45
+ self.tipwindow.lift() # work around bug in Tk 8.5.18+ (issue #24570)
46
+
47
+ def position_window(self):
48
+ """(re)-set the tooltip's screen position"""
49
+ x, y = self.get_position()
50
+ root_x = self.anchor_widget.winfo_rootx() + x
51
+ root_y = self.anchor_widget.winfo_rooty() + y
52
+ self.tipwindow.wm_geometry("+%d+%d" % (root_x, root_y))
53
+
54
+ def get_position(self):
55
+ """choose a screen position for the tooltip"""
56
+ # The tip window must be completely outside the anchor widget;
57
+ # otherwise when the mouse enters the tip window we get
58
+ # a leave event and it disappears, and then we get an enter
59
+ # event and it reappears, and so on forever :-(
60
+ #
61
+ # Note: This is a simplistic implementation; sub-classes will likely
62
+ # want to override this.
63
+ return 20, self.anchor_widget.winfo_height() + 1
64
+
65
+ def showcontents(self):
66
+ """content display hook for sub-classes"""
67
+ # See ToolTip for an example
68
+ raise NotImplementedError
69
+
70
+ def hidetip(self):
71
+ """hide the tooltip"""
72
+ # Note: This is called by __del__, so careful when overriding/extending
73
+ tw = self.tipwindow
74
+ self.tipwindow = None
75
+ if tw:
76
+ try:
77
+ tw.destroy()
78
+ except TclError: # pragma: no cover
79
+ pass
80
+
81
+
82
+ class OnHoverTooltipBase(TooltipBase):
83
+ """abstract base class for tooltips, with delayed on-hover display"""
84
+
85
+ def __init__(self, anchor_widget, hover_delay=1000):
86
+ """Create a tooltip with a mouse hover delay.
87
+
88
+ anchor_widget: the widget next to which the tooltip will be shown
89
+ hover_delay: time to delay before showing the tooltip, in milliseconds
90
+
91
+ Note that a widget will only be shown when showtip() is called,
92
+ e.g. after hovering over the anchor widget with the mouse for enough
93
+ time.
94
+ """
95
+ super(OnHoverTooltipBase, self).__init__(anchor_widget)
96
+ self.hover_delay = hover_delay
97
+
98
+ self._after_id = None
99
+ self._id1 = self.anchor_widget.bind("<Enter>", self._show_event)
100
+ self._id2 = self.anchor_widget.bind("<Leave>", self._hide_event)
101
+ self._id3 = self.anchor_widget.bind("<Button>", self._hide_event)
102
+
103
+ def __del__(self):
104
+ try:
105
+ self.anchor_widget.unbind("<Enter>", self._id1)
106
+ self.anchor_widget.unbind("<Leave>", self._id2) # pragma: no cover
107
+ self.anchor_widget.unbind("<Button>", self._id3) # pragma: no cover
108
+ except TclError:
109
+ pass
110
+ super(OnHoverTooltipBase, self).__del__()
111
+
112
+ def _show_event(self, event=None):
113
+ """event handler to display the tooltip"""
114
+ if self.hover_delay:
115
+ self.schedule()
116
+ else:
117
+ self.showtip()
118
+
119
+ def _hide_event(self, event=None):
120
+ """event handler to hide the tooltip"""
121
+ self.hidetip()
122
+
123
+ def schedule(self):
124
+ """schedule the future display of the tooltip"""
125
+ self.unschedule()
126
+ self._after_id = self.anchor_widget.after(self.hover_delay,
127
+ self.showtip)
128
+
129
+ def unschedule(self):
130
+ """cancel the future display of the tooltip"""
131
+ after_id = self._after_id
132
+ self._after_id = None
133
+ if after_id:
134
+ self.anchor_widget.after_cancel(after_id)
135
+
136
+ def hidetip(self):
137
+ """hide the tooltip"""
138
+ try:
139
+ self.unschedule()
140
+ except TclError: # pragma: no cover
141
+ pass
142
+ super(OnHoverTooltipBase, self).hidetip()
143
+
144
+
145
+ class Hovertip(OnHoverTooltipBase):
146
+ "A tooltip that pops up when a mouse hovers over an anchor widget."
147
+ def __init__(self, anchor_widget, text, hover_delay=1000):
148
+ """Create a text tooltip with a mouse hover delay.
149
+
150
+ anchor_widget: the widget next to which the tooltip will be shown
151
+ hover_delay: time to delay before showing the tooltip, in milliseconds
152
+
153
+ Note that a widget will only be shown when showtip() is called,
154
+ e.g. after hovering over the anchor widget with the mouse for enough
155
+ time.
156
+ """
157
+ super(Hovertip, self).__init__(anchor_widget, hover_delay=hover_delay)
158
+ self.text = text
159
+
160
+ def showcontents(self):
161
+ label = Label(self.tipwindow, text=self.text, justify=LEFT,
162
+ background="#ffffe0", relief=SOLID, borderwidth=1)
163
+ label.pack()
164
+
165
+
166
+ def _tooltip(parent): # htest #
167
+ top = Toplevel(parent)
168
+ top.title("Test tooltip")
169
+ x, y = map(int, parent.geometry().split('+')[1:])
170
+ top.geometry("+%d+%d" % (x, y + 150))
171
+ label = Label(top, text="Place your mouse over buttons")
172
+ label.pack()
173
+ button1 = Button(top, text="Button 1 -- 1/2 second hover delay")
174
+ button1.pack()
175
+ Hovertip(button1, "This is tooltip text for button1.", hover_delay=500)
176
+ button2 = Button(top, text="Button 2 -- no hover delay")
177
+ button2.pack()
178
+ Hovertip(button2, "This is tooltip\ntext for button2.", hover_delay=None)
179
+
180
+
181
+ if __name__ == '__main__':
182
+ from unittest import main
183
+ main('idlelib.idle_test.test_tooltip', verbosity=2, exit=False)
184
+
185
+ from idlelib.idle_test.htest import run
186
+ run(_tooltip)
llava/lib/python3.10/idlelib/window.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tkinter import Toplevel, TclError
2
+ import sys
3
+
4
+
5
+ class WindowList:
6
+
7
+ def __init__(self):
8
+ self.dict = {}
9
+ self.callbacks = []
10
+
11
+ def add(self, window):
12
+ window.after_idle(self.call_callbacks)
13
+ self.dict[str(window)] = window
14
+
15
+ def delete(self, window):
16
+ try:
17
+ del self.dict[str(window)]
18
+ except KeyError:
19
+ # Sometimes, destroy() is called twice
20
+ pass
21
+ self.call_callbacks()
22
+
23
+ def add_windows_to_menu(self, menu):
24
+ list = []
25
+ for key in self.dict:
26
+ window = self.dict[key]
27
+ try:
28
+ title = window.get_title()
29
+ except TclError:
30
+ continue
31
+ list.append((title, key, window))
32
+ list.sort()
33
+ for title, key, window in list:
34
+ menu.add_command(label=title, command=window.wakeup)
35
+
36
+ def register_callback(self, callback):
37
+ self.callbacks.append(callback)
38
+
39
+ def unregister_callback(self, callback):
40
+ try:
41
+ self.callbacks.remove(callback)
42
+ except ValueError:
43
+ pass
44
+
45
+ def call_callbacks(self):
46
+ for callback in self.callbacks:
47
+ try:
48
+ callback()
49
+ except:
50
+ t, v, tb = sys.exc_info()
51
+ print("warning: callback failed in WindowList", t, ":", v)
52
+
53
+
54
+ registry = WindowList()
55
+
56
+ add_windows_to_menu = registry.add_windows_to_menu
57
+ register_callback = registry.register_callback
58
+ unregister_callback = registry.unregister_callback
59
+
60
+
61
+ class ListedToplevel(Toplevel):
62
+
63
+ def __init__(self, master, **kw):
64
+ Toplevel.__init__(self, master, kw)
65
+ registry.add(self)
66
+ self.focused_widget = self
67
+
68
+ def destroy(self):
69
+ registry.delete(self)
70
+ Toplevel.destroy(self)
71
+ # If this is Idle's last window then quit the mainloop
72
+ # (Needed for clean exit on Windows 98)
73
+ if not registry.dict:
74
+ self.quit()
75
+
76
+ def update_windowlist_registry(self, window):
77
+ registry.call_callbacks()
78
+
79
+ def get_title(self):
80
+ # Subclass can override
81
+ return self.wm_title()
82
+
83
+ def wakeup(self):
84
+ try:
85
+ if self.wm_state() == "iconic":
86
+ self.wm_withdraw()
87
+ self.wm_deiconify()
88
+ self.tkraise()
89
+ self.focused_widget.focus_set()
90
+ except TclError:
91
+ # This can happen when the Window menu was torn off.
92
+ # Simply ignore it.
93
+ pass
94
+
95
+
96
+ if __name__ == "__main__":
97
+ from unittest import main
98
+ main('idlelib.idle_test.test_window', verbosity=2)
llava/lib/python3.10/idlelib/zoomheight.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Zoom a window to maximum height."
2
+
3
+ import re
4
+ import sys
5
+ import tkinter
6
+
7
+
8
+ class WmInfoGatheringError(Exception):
9
+ pass
10
+
11
+
12
+ class ZoomHeight:
13
+ # Cached values for maximized window dimensions, one for each set
14
+ # of screen dimensions.
15
+ _max_height_and_y_coords = {}
16
+
17
+ def __init__(self, editwin):
18
+ self.editwin = editwin
19
+ self.top = self.editwin.top
20
+
21
+ def zoom_height_event(self, event=None):
22
+ zoomed = self.zoom_height()
23
+
24
+ if zoomed is None:
25
+ self.top.bell()
26
+ else:
27
+ menu_status = 'Restore' if zoomed else 'Zoom'
28
+ self.editwin.update_menu_label(menu='options', index='* Height',
29
+ label=f'{menu_status} Height')
30
+
31
+ return "break"
32
+
33
+ def zoom_height(self):
34
+ top = self.top
35
+
36
+ width, height, x, y = get_window_geometry(top)
37
+
38
+ if top.wm_state() != 'normal':
39
+ # Can't zoom/restore window height for windows not in the 'normal'
40
+ # state, e.g. maximized and full-screen windows.
41
+ return None
42
+
43
+ try:
44
+ maxheight, maxy = self.get_max_height_and_y_coord()
45
+ except WmInfoGatheringError:
46
+ return None
47
+
48
+ if height != maxheight:
49
+ # Maximize the window's height.
50
+ set_window_geometry(top, (width, maxheight, x, maxy))
51
+ return True
52
+ else:
53
+ # Restore the window's height.
54
+ #
55
+ # .wm_geometry('') makes the window revert to the size requested
56
+ # by the widgets it contains.
57
+ top.wm_geometry('')
58
+ return False
59
+
60
+ def get_max_height_and_y_coord(self):
61
+ top = self.top
62
+
63
+ screen_dimensions = (top.winfo_screenwidth(),
64
+ top.winfo_screenheight())
65
+ if screen_dimensions not in self._max_height_and_y_coords:
66
+ orig_state = top.wm_state()
67
+
68
+ # Get window geometry info for maximized windows.
69
+ try:
70
+ top.wm_state('zoomed')
71
+ except tkinter.TclError:
72
+ # The 'zoomed' state is not supported by some esoteric WMs,
73
+ # such as Xvfb.
74
+ raise WmInfoGatheringError(
75
+ 'Failed getting geometry of maximized windows, because ' +
76
+ 'the "zoomed" window state is unavailable.')
77
+ top.update()
78
+ maxwidth, maxheight, maxx, maxy = get_window_geometry(top)
79
+ if sys.platform == 'win32':
80
+ # On Windows, the returned Y coordinate is the one before
81
+ # maximizing, so we use 0 which is correct unless a user puts
82
+ # their dock on the top of the screen (very rare).
83
+ maxy = 0
84
+ maxrooty = top.winfo_rooty()
85
+
86
+ # Get the "root y" coordinate for non-maximized windows with their
87
+ # y coordinate set to that of maximized windows. This is needed
88
+ # to properly handle different title bar heights for non-maximized
89
+ # vs. maximized windows, as seen e.g. in Windows 10.
90
+ top.wm_state('normal')
91
+ top.update()
92
+ orig_geom = get_window_geometry(top)
93
+ max_y_geom = orig_geom[:3] + (maxy,)
94
+ set_window_geometry(top, max_y_geom)
95
+ top.update()
96
+ max_y_geom_rooty = top.winfo_rooty()
97
+
98
+ # Adjust the maximum window height to account for the different
99
+ # title bar heights of non-maximized vs. maximized windows.
100
+ maxheight += maxrooty - max_y_geom_rooty
101
+
102
+ self._max_height_and_y_coords[screen_dimensions] = maxheight, maxy
103
+
104
+ set_window_geometry(top, orig_geom)
105
+ top.wm_state(orig_state)
106
+
107
+ return self._max_height_and_y_coords[screen_dimensions]
108
+
109
+
110
+ def get_window_geometry(top):
111
+ geom = top.wm_geometry()
112
+ m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
113
+ return tuple(map(int, m.groups()))
114
+
115
+
116
+ def set_window_geometry(top, geometry):
117
+ top.wm_geometry("{:d}x{:d}+{:d}+{:d}".format(*geometry))
118
+
119
+
120
+ if __name__ == "__main__":
121
+ from unittest import main
122
+ main('idlelib.idle_test.test_zoomheight', verbosity=2, exit=False)
123
+
124
+ # Add htest?
llava/lib/python3.10/idlelib/zzdummy.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example extension, also used for testing.
2
+
3
+ See extend.txt for more details on creating an extension.
4
+ See config-extension.def for configuring an extension.
5
+ """
6
+
7
+ from idlelib.config import idleConf
8
+ from functools import wraps
9
+
10
+
11
+ def format_selection(format_line):
12
+ "Apply a formatting function to all of the selected lines."
13
+
14
+ @wraps(format_line)
15
+ def apply(self, event=None):
16
+ head, tail, chars, lines = self.formatter.get_region()
17
+ for pos in range(len(lines) - 1):
18
+ line = lines[pos]
19
+ lines[pos] = format_line(self, line)
20
+ self.formatter.set_region(head, tail, chars, lines)
21
+ return 'break'
22
+
23
+ return apply
24
+
25
+
26
+ class ZzDummy:
27
+ """Prepend or remove initial text from selected lines."""
28
+
29
+ # Extend the format menu.
30
+ menudefs = [
31
+ ('format', [
32
+ ('Z in', '<<z-in>>'),
33
+ ('Z out', '<<z-out>>'),
34
+ ] )
35
+ ]
36
+
37
+ def __init__(self, editwin):
38
+ "Initialize the settings for this extension."
39
+ self.editwin = editwin
40
+ self.text = editwin.text
41
+ self.formatter = editwin.fregion
42
+
43
+ @classmethod
44
+ def reload(cls):
45
+ "Load class variables from config."
46
+ cls.ztext = idleConf.GetOption('extensions', 'ZzDummy', 'z-text')
47
+
48
+ @format_selection
49
+ def z_in_event(self, line):
50
+ """Insert text at the beginning of each selected line.
51
+
52
+ This is bound to the <<z-in>> virtual event when the extensions
53
+ are loaded.
54
+ """
55
+ return f'{self.ztext}{line}'
56
+
57
+ @format_selection
58
+ def z_out_event(self, line):
59
+ """Remove specific text from the beginning of each selected line.
60
+
61
+ This is bound to the <<z-out>> virtual event when the extensions
62
+ are loaded.
63
+ """
64
+ zlength = 0 if not line.startswith(self.ztext) else len(self.ztext)
65
+ return line[zlength:]
66
+
67
+
68
+ ZzDummy.reload()
69
+
70
+
71
+ if __name__ == "__main__":
72
+ import unittest
73
+ unittest.main('idlelib.idle_test.test_zzdummy', verbosity=2, exit=False)
llava/lib/python3.10/lib2to3/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (557 Bytes). View file
 
llava/lib/python3.10/lib2to3/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (470 Bytes). View file
 
llava/lib/python3.10/lib2to3/__pycache__/btm_matcher.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/btm_utils.cpython-310.pyc ADDED
Binary file (6.42 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/fixer_base.cpython-310.pyc ADDED
Binary file (6.27 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/fixer_util.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/main.cpython-310.pyc ADDED
Binary file (8.96 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/patcomp.cpython-310.pyc ADDED
Binary file (5.53 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/pygram.cpython-310.pyc ADDED
Binary file (1.52 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/pytree.cpython-310.pyc ADDED
Binary file (24.7 kB). View file
 
llava/lib/python3.10/lib2to3/__pycache__/refactor.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """The pgen2 package."""
llava/lib/python3.10/lib2to3/pgen2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (422 Bytes). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/conv.cpython-310.pyc ADDED
Binary file (7.01 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/driver.cpython-310.pyc ADDED
Binary file (5.39 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/grammar.cpython-310.pyc ADDED
Binary file (5.97 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/literals.cpython-310.pyc ADDED
Binary file (1.8 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/parse.cpython-310.pyc ADDED
Binary file (6.51 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/pgen.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/token.cpython-310.pyc ADDED
Binary file (2.14 kB). View file
 
llava/lib/python3.10/lib2to3/pgen2/__pycache__/tokenize.cpython-310.pyc ADDED
Binary file (15.4 kB). View file