ยปCore Development>Code coverage>Lib/idlelib/autocomplete_w.py

Python code coverage for Lib/idlelib/autocomplete_w.py

#countcontent
1n/a"""
2n/aAn auto-completion window for IDLE, used by the autocomplete extension
3n/a"""
4n/afrom tkinter import *
5n/afrom tkinter.ttk import Scrollbar
6n/a
7n/afrom idlelib.autocomplete import COMPLETE_FILES, COMPLETE_ATTRIBUTES
8n/afrom idlelib.multicall import MC_SHIFT
9n/a
10n/aHIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
11n/aHIDE_SEQUENCES = ("<FocusOut>", "<ButtonPress>")
12n/aKEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>"
13n/a# We need to bind event beyond <Key> so that the function will be called
14n/a# before the default specific IDLE function
15n/aKEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>", "<Key-Tab>",
16n/a "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>",
17n/a "<Key-Prior>", "<Key-Next>")
18n/aKEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>"
19n/aKEYRELEASE_SEQUENCE = "<KeyRelease>"
20n/aLISTUPDATE_SEQUENCE = "<B1-ButtonRelease>"
21n/aWINCONFIG_SEQUENCE = "<Configure>"
22n/aDOUBLECLICK_SEQUENCE = "<B1-Double-ButtonRelease>"
23n/a
24n/aclass AutoCompleteWindow:
25n/a
26n/a def __init__(self, widget):
27n/a # The widget (Text) on which we place the AutoCompleteWindow
28n/a self.widget = widget
29n/a # The widgets we create
30n/a self.autocompletewindow = self.listbox = self.scrollbar = None
31n/a # The default foreground and background of a selection. Saved because
32n/a # they are changed to the regular colors of list items when the
33n/a # completion start is not a prefix of the selected completion
34n/a self.origselforeground = self.origselbackground = None
35n/a # The list of completions
36n/a self.completions = None
37n/a # A list with more completions, or None
38n/a self.morecompletions = None
39n/a # The completion mode. Either autocomplete.COMPLETE_ATTRIBUTES or
40n/a # autocomplete.COMPLETE_FILES
41n/a self.mode = None
42n/a # The current completion start, on the text box (a string)
43n/a self.start = None
44n/a # The index of the start of the completion
45n/a self.startindex = None
46n/a # The last typed start, used so that when the selection changes,
47n/a # the new start will be as close as possible to the last typed one.
48n/a self.lasttypedstart = None
49n/a # Do we have an indication that the user wants the completion window
50n/a # (for example, he clicked the list)
51n/a self.userwantswindow = None
52n/a # event ids
53n/a self.hideid = self.keypressid = self.listupdateid = self.winconfigid \
54n/a = self.keyreleaseid = self.doubleclickid = None
55n/a # Flag set if last keypress was a tab
56n/a self.lastkey_was_tab = False
57n/a
58n/a def _change_start(self, newstart):
59n/a min_len = min(len(self.start), len(newstart))
60n/a i = 0
61n/a while i < min_len and self.start[i] == newstart[i]:
62n/a i += 1
63n/a if i < len(self.start):
64n/a self.widget.delete("%s+%dc" % (self.startindex, i),
65n/a "%s+%dc" % (self.startindex, len(self.start)))
66n/a if i < len(newstart):
67n/a self.widget.insert("%s+%dc" % (self.startindex, i),
68n/a newstart[i:])
69n/a self.start = newstart
70n/a
71n/a def _binary_search(self, s):
72n/a """Find the first index in self.completions where completions[i] is
73n/a greater or equal to s, or the last index if there is no such
74n/a one."""
75n/a i = 0; j = len(self.completions)
76n/a while j > i:
77n/a m = (i + j) // 2
78n/a if self.completions[m] >= s:
79n/a j = m
80n/a else:
81n/a i = m + 1
82n/a return min(i, len(self.completions)-1)
83n/a
84n/a def _complete_string(self, s):
85n/a """Assuming that s is the prefix of a string in self.completions,
86n/a return the longest string which is a prefix of all the strings which
87n/a s is a prefix of them. If s is not a prefix of a string, return s."""
88n/a first = self._binary_search(s)
89n/a if self.completions[first][:len(s)] != s:
90n/a # There is not even one completion which s is a prefix of.
91n/a return s
92n/a # Find the end of the range of completions where s is a prefix of.
93n/a i = first + 1
94n/a j = len(self.completions)
95n/a while j > i:
96n/a m = (i + j) // 2
97n/a if self.completions[m][:len(s)] != s:
98n/a j = m
99n/a else:
100n/a i = m + 1
101n/a last = i-1
102n/a
103n/a if first == last: # only one possible completion
104n/a return self.completions[first]
105n/a
106n/a # We should return the maximum prefix of first and last
107n/a first_comp = self.completions[first]
108n/a last_comp = self.completions[last]
109n/a min_len = min(len(first_comp), len(last_comp))
110n/a i = len(s)
111n/a while i < min_len and first_comp[i] == last_comp[i]:
112n/a i += 1
113n/a return first_comp[:i]
114n/a
115n/a def _selection_changed(self):
116n/a """Should be called when the selection of the Listbox has changed.
117n/a Updates the Listbox display and calls _change_start."""
118n/a cursel = int(self.listbox.curselection()[0])
119n/a
120n/a self.listbox.see(cursel)
121n/a
122n/a lts = self.lasttypedstart
123n/a selstart = self.completions[cursel]
124n/a if self._binary_search(lts) == cursel:
125n/a newstart = lts
126n/a else:
127n/a min_len = min(len(lts), len(selstart))
128n/a i = 0
129n/a while i < min_len and lts[i] == selstart[i]:
130n/a i += 1
131n/a newstart = selstart[:i]
132n/a self._change_start(newstart)
133n/a
134n/a if self.completions[cursel][:len(self.start)] == self.start:
135n/a # start is a prefix of the selected completion
136n/a self.listbox.configure(selectbackground=self.origselbackground,
137n/a selectforeground=self.origselforeground)
138n/a else:
139n/a self.listbox.configure(selectbackground=self.listbox.cget("bg"),
140n/a selectforeground=self.listbox.cget("fg"))
141n/a # If there are more completions, show them, and call me again.
142n/a if self.morecompletions:
143n/a self.completions = self.morecompletions
144n/a self.morecompletions = None
145n/a self.listbox.delete(0, END)
146n/a for item in self.completions:
147n/a self.listbox.insert(END, item)
148n/a self.listbox.select_set(self._binary_search(self.start))
149n/a self._selection_changed()
150n/a
151n/a def show_window(self, comp_lists, index, complete, mode, userWantsWin):
152n/a """Show the autocomplete list, bind events.
153n/a If complete is True, complete the text, and if there is exactly one
154n/a matching completion, don't open a list."""
155n/a # Handle the start we already have
156n/a self.completions, self.morecompletions = comp_lists
157n/a self.mode = mode
158n/a self.startindex = self.widget.index(index)
159n/a self.start = self.widget.get(self.startindex, "insert")
160n/a if complete:
161n/a completed = self._complete_string(self.start)
162n/a start = self.start
163n/a self._change_start(completed)
164n/a i = self._binary_search(completed)
165n/a if self.completions[i] == completed and \
166n/a (i == len(self.completions)-1 or
167n/a self.completions[i+1][:len(completed)] != completed):
168n/a # There is exactly one matching completion
169n/a return completed == start
170n/a self.userwantswindow = userWantsWin
171n/a self.lasttypedstart = self.start
172n/a
173n/a # Put widgets in place
174n/a self.autocompletewindow = acw = Toplevel(self.widget)
175n/a # Put it in a position so that it is not seen.
176n/a acw.wm_geometry("+10000+10000")
177n/a # Make it float
178n/a acw.wm_overrideredirect(1)
179n/a try:
180n/a # This command is only needed and available on Tk >= 8.4.0 for OSX
181n/a # Without it, call tips intrude on the typing process by grabbing
182n/a # the focus.
183n/a acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
184n/a "help", "noActivates")
185n/a except TclError:
186n/a pass
187n/a self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
188n/a self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set,
189n/a exportselection=False, bg="white")
190n/a for item in self.completions:
191n/a listbox.insert(END, item)
192n/a self.origselforeground = listbox.cget("selectforeground")
193n/a self.origselbackground = listbox.cget("selectbackground")
194n/a scrollbar.config(command=listbox.yview)
195n/a scrollbar.pack(side=RIGHT, fill=Y)
196n/a listbox.pack(side=LEFT, fill=BOTH, expand=True)
197n/a acw.lift() # work around bug in Tk 8.5.18+ (issue #24570)
198n/a
199n/a # Initialize the listbox selection
200n/a self.listbox.select_set(self._binary_search(self.start))
201n/a self._selection_changed()
202n/a
203n/a # bind events
204n/a self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME,
205n/a self.hide_event)
206n/a for seq in HIDE_SEQUENCES:
207n/a self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
208n/a self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
209n/a self.keypress_event)
210n/a for seq in KEYPRESS_SEQUENCES:
211n/a self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
212n/a self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
213n/a self.keyrelease_event)
214n/a self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
215n/a self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
216n/a self.listselect_event)
217n/a self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
218n/a self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
219n/a self.doubleclick_event)
220n/a return None
221n/a
222n/a def winconfig_event(self, event):
223n/a if not self.is_active():
224n/a return
225n/a # Position the completion list window
226n/a text = self.widget
227n/a text.see(self.startindex)
228n/a x, y, cx, cy = text.bbox(self.startindex)
229n/a acw = self.autocompletewindow
230n/a acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
231n/a text_width, text_height = text.winfo_width(), text.winfo_height()
232n/a new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
233n/a new_y = text.winfo_rooty() + y
234n/a if (text_height - (y + cy) >= acw_height # enough height below
235n/a or y < acw_height): # not enough height above
236n/a # place acw below current line
237n/a new_y += cy
238n/a else:
239n/a # place acw above current line
240n/a new_y -= acw_height
241n/a acw.wm_geometry("+%d+%d" % (new_x, new_y))
242n/a
243n/a def hide_event(self, event):
244n/a if self.is_active():
245n/a self.hide_window()
246n/a
247n/a def listselect_event(self, event):
248n/a if self.is_active():
249n/a self.userwantswindow = True
250n/a cursel = int(self.listbox.curselection()[0])
251n/a self._change_start(self.completions[cursel])
252n/a
253n/a def doubleclick_event(self, event):
254n/a # Put the selected completion in the text, and close the list
255n/a cursel = int(self.listbox.curselection()[0])
256n/a self._change_start(self.completions[cursel])
257n/a self.hide_window()
258n/a
259n/a def keypress_event(self, event):
260n/a if not self.is_active():
261n/a return None
262n/a keysym = event.keysym
263n/a if hasattr(event, "mc_state"):
264n/a state = event.mc_state
265n/a else:
266n/a state = 0
267n/a if keysym != "Tab":
268n/a self.lastkey_was_tab = False
269n/a if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
270n/a or (self.mode == COMPLETE_FILES and keysym in
271n/a ("period", "minus"))) \
272n/a and not (state & ~MC_SHIFT):
273n/a # Normal editing of text
274n/a if len(keysym) == 1:
275n/a self._change_start(self.start + keysym)
276n/a elif keysym == "underscore":
277n/a self._change_start(self.start + '_')
278n/a elif keysym == "period":
279n/a self._change_start(self.start + '.')
280n/a elif keysym == "minus":
281n/a self._change_start(self.start + '-')
282n/a else:
283n/a # keysym == "BackSpace"
284n/a if len(self.start) == 0:
285n/a self.hide_window()
286n/a return None
287n/a self._change_start(self.start[:-1])
288n/a self.lasttypedstart = self.start
289n/a self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
290n/a self.listbox.select_set(self._binary_search(self.start))
291n/a self._selection_changed()
292n/a return "break"
293n/a
294n/a elif keysym == "Return":
295n/a self.hide_window()
296n/a return None
297n/a
298n/a elif (self.mode == COMPLETE_ATTRIBUTES and keysym in
299n/a ("period", "space", "parenleft", "parenright", "bracketleft",
300n/a "bracketright")) or \
301n/a (self.mode == COMPLETE_FILES and keysym in
302n/a ("slash", "backslash", "quotedbl", "apostrophe")) \
303n/a and not (state & ~MC_SHIFT):
304n/a # If start is a prefix of the selection, but is not '' when
305n/a # completing file names, put the whole
306n/a # selected completion. Anyway, close the list.
307n/a cursel = int(self.listbox.curselection()[0])
308n/a if self.completions[cursel][:len(self.start)] == self.start \
309n/a and (self.mode == COMPLETE_ATTRIBUTES or self.start):
310n/a self._change_start(self.completions[cursel])
311n/a self.hide_window()
312n/a return None
313n/a
314n/a elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
315n/a not state:
316n/a # Move the selection in the listbox
317n/a self.userwantswindow = True
318n/a cursel = int(self.listbox.curselection()[0])
319n/a if keysym == "Home":
320n/a newsel = 0
321n/a elif keysym == "End":
322n/a newsel = len(self.completions)-1
323n/a elif keysym in ("Prior", "Next"):
324n/a jump = self.listbox.nearest(self.listbox.winfo_height()) - \
325n/a self.listbox.nearest(0)
326n/a if keysym == "Prior":
327n/a newsel = max(0, cursel-jump)
328n/a else:
329n/a assert keysym == "Next"
330n/a newsel = min(len(self.completions)-1, cursel+jump)
331n/a elif keysym == "Up":
332n/a newsel = max(0, cursel-1)
333n/a else:
334n/a assert keysym == "Down"
335n/a newsel = min(len(self.completions)-1, cursel+1)
336n/a self.listbox.select_clear(cursel)
337n/a self.listbox.select_set(newsel)
338n/a self._selection_changed()
339n/a self._change_start(self.completions[newsel])
340n/a return "break"
341n/a
342n/a elif (keysym == "Tab" and not state):
343n/a if self.lastkey_was_tab:
344n/a # two tabs in a row; insert current selection and close acw
345n/a cursel = int(self.listbox.curselection()[0])
346n/a self._change_start(self.completions[cursel])
347n/a self.hide_window()
348n/a return "break"
349n/a else:
350n/a # first tab; let AutoComplete handle the completion
351n/a self.userwantswindow = True
352n/a self.lastkey_was_tab = True
353n/a return None
354n/a
355n/a elif any(s in keysym for s in ("Shift", "Control", "Alt",
356n/a "Meta", "Command", "Option")):
357n/a # A modifier key, so ignore
358n/a return None
359n/a
360n/a elif event.char and event.char >= ' ':
361n/a # Regular character with a non-length-1 keycode
362n/a self._change_start(self.start + event.char)
363n/a self.lasttypedstart = self.start
364n/a self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
365n/a self.listbox.select_set(self._binary_search(self.start))
366n/a self._selection_changed()
367n/a return "break"
368n/a
369n/a else:
370n/a # Unknown event, close the window and let it through.
371n/a self.hide_window()
372n/a return None
373n/a
374n/a def keyrelease_event(self, event):
375n/a if not self.is_active():
376n/a return
377n/a if self.widget.index("insert") != \
378n/a self.widget.index("%s+%dc" % (self.startindex, len(self.start))):
379n/a # If we didn't catch an event which moved the insert, close window
380n/a self.hide_window()
381n/a
382n/a def is_active(self):
383n/a return self.autocompletewindow is not None
384n/a
385n/a def complete(self):
386n/a self._change_start(self._complete_string(self.start))
387n/a # The selection doesn't change.
388n/a
389n/a def hide_window(self):
390n/a if not self.is_active():
391n/a return
392n/a
393n/a # unbind events
394n/a for seq in HIDE_SEQUENCES:
395n/a self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq)
396n/a self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid)
397n/a self.hideid = None
398n/a for seq in KEYPRESS_SEQUENCES:
399n/a self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
400n/a self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid)
401n/a self.keypressid = None
402n/a self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME,
403n/a KEYRELEASE_SEQUENCE)
404n/a self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid)
405n/a self.keyreleaseid = None
406n/a self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid)
407n/a self.listupdateid = None
408n/a self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
409n/a self.winconfigid = None
410n/a
411n/a # destroy widgets
412n/a self.scrollbar.destroy()
413n/a self.scrollbar = None
414n/a self.listbox.destroy()
415n/a self.listbox = None
416n/a self.autocompletewindow.destroy()
417n/a self.autocompletewindow = None