blob: 1200008ba9a5185f751e5d4b1f1865d30e3ccd9b [file] [log] [blame]
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -04001"""autocomplete.py - An IDLE extension for automatically completing names.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00002
Martin Pantere26da7c2016-06-02 10:07:09 +00003This extension can complete either attribute names or file names. It can pop
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00004a window with all available names, for the user to select from.
5"""
6import os
7import sys
8import string
9
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040010from idlelib.config import idleConf
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000011
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000012# This string includes all chars that may be in an identifier
13ID_CHARS = string.ascii_letters + string.digits + "_"
14
15# These constants represent the two different types of completions
16COMPLETE_ATTRIBUTES, COMPLETE_FILES = range(1, 2+1)
17
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040018from idlelib import autocomplete_w
19from idlelib.hyperparser import HyperParser
Kurt B. Kaisere1b4a162007-08-10 02:45:06 +000020
21import __main__
22
Christian Heimes81ee3ef2008-05-04 22:42:01 +000023SEPS = os.sep
24if os.altsep: # e.g. '/' on Windows...
25 SEPS += os.altsep
26
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000027class AutoComplete:
28
29 menudefs = [
30 ('edit', [
Guido van Rossum8ce8a782007-11-01 19:42:39 +000031 ("Show Completions", "<<force-open-completions>>"),
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000032 ])
33 ]
34
35 popupwait = idleConf.GetOption("extensions", "AutoComplete",
36 "popupwait", type="int", default=0)
37
38 def __init__(self, editwin=None):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000039 self.editwin = editwin
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -040040 if editwin is not None: # not in subprocess or test
41 self.text = editwin.text
42 self.autocompletewindow = None
43 # id of delayed call, and the index of the text insert when
44 # the delayed call was issued. If _delayed_completion_id is
45 # None, there is no delayed call.
46 self._delayed_completion_id = None
47 self._delayed_completion_index = None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000048
49 def _make_autocomplete_window(self):
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040050 return autocomplete_w.AutoCompleteWindow(self.text)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000051
52 def _remove_autocomplete_window(self, event=None):
53 if self.autocompletewindow:
54 self.autocompletewindow.hide_window()
55 self.autocompletewindow = None
56
57 def force_open_completions_event(self, event):
58 """Happens when the user really wants to open a completion list, even
59 if a function call is needed.
60 """
61 self.open_completions(True, False, True)
62
63 def try_open_completions_event(self, event):
64 """Happens when it would be nice to open a completion list, but not
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +030065 really necessary, for example after a dot, so function
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000066 calls won't be made.
67 """
68 lastchar = self.text.get("insert-1c")
69 if lastchar == ".":
70 self._open_completions_later(False, False, False,
71 COMPLETE_ATTRIBUTES)
Christian Heimes81ee3ef2008-05-04 22:42:01 +000072 elif lastchar in SEPS:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000073 self._open_completions_later(False, False, False,
74 COMPLETE_FILES)
75
76 def autocomplete_event(self, event):
Mark Dickinson934896d2009-02-21 20:59:32 +000077 """Happens when the user wants to complete his word, and if necessary,
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000078 open a completion list after that (if there is more than one
79 completion)
80 """
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -040081 if hasattr(event, "mc_state") and event.mc_state or\
82 not self.text.get("insert linestart", "insert").strip():
83 # A modifier was pressed along with the tab or
84 # there is only previous whitespace on this line, so tab.
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -040085 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000086 if self.autocompletewindow and self.autocompletewindow.is_active():
87 self.autocompletewindow.complete()
88 return "break"
89 else:
90 opened = self.open_completions(False, True, True)
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -040091 return "break" if opened else None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000092
93 def _open_completions_later(self, *args):
94 self._delayed_completion_index = self.text.index("insert")
95 if self._delayed_completion_id is not None:
96 self.text.after_cancel(self._delayed_completion_id)
97 self._delayed_completion_id = \
98 self.text.after(self.popupwait, self._delayed_open_completions,
99 *args)
100
101 def _delayed_open_completions(self, *args):
102 self._delayed_completion_id = None
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400103 if self.text.index("insert") == self._delayed_completion_index:
104 self.open_completions(*args)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000105
106 def open_completions(self, evalfuncs, complete, userWantsWin, mode=None):
107 """Find the completions and create the AutoCompleteWindow.
108 Return True if successful (no syntax error or so found).
109 if complete is True, then if there's nothing to complete and no
110 start of completion, won't open completions and return False.
111 If mode is given, will open a completion list only in this mode.
112 """
113 # Cancel another delayed call, if it exists.
114 if self._delayed_completion_id is not None:
115 self.text.after_cancel(self._delayed_completion_id)
116 self._delayed_completion_id = None
117
118 hp = HyperParser(self.editwin, "insert")
119 curline = self.text.get("insert linestart", "insert")
120 i = j = len(curline)
121 if hp.is_in_string() and (not mode or mode==COMPLETE_FILES):
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200122 # Find the beginning of the string
123 # fetch_completions will look at the file system to determine whether the
124 # string value constitutes an actual file name
125 # XXX could consider raw strings here and unescape the string value if it's
126 # not raw.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000127 self._remove_autocomplete_window()
128 mode = COMPLETE_FILES
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200129 # Find last separator or string start
130 while i and curline[i-1] not in "'\"" + SEPS:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000131 i -= 1
132 comp_start = curline[i:j]
133 j = i
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200134 # Find string start
135 while i and curline[i-1] not in "'\"":
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000136 i -= 1
137 comp_what = curline[i:j]
138 elif hp.is_in_code() and (not mode or mode==COMPLETE_ATTRIBUTES):
139 self._remove_autocomplete_window()
140 mode = COMPLETE_ATTRIBUTES
Martin v. Löwis993fe3f2012-06-14 15:37:21 +0200141 while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000142 i -= 1
143 comp_start = curline[i:j]
144 if i and curline[i-1] == '.':
145 hp.set_index("insert-%dc" % (len(curline)-(i-1)))
146 comp_what = hp.get_expression()
147 if not comp_what or \
148 (not evalfuncs and comp_what.find('(') != -1):
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400149 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000150 else:
151 comp_what = ""
152 else:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400153 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000154
155 if complete and not comp_what and not comp_start:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400156 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000157 comp_lists = self.fetch_completions(comp_what, mode)
158 if not comp_lists[0]:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400159 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000160 self.autocompletewindow = self._make_autocomplete_window()
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300161 return not self.autocompletewindow.show_window(
162 comp_lists, "insert-%dc" % len(comp_start),
163 complete, mode, userWantsWin)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000164
165 def fetch_completions(self, what, mode):
166 """Return a pair of lists of completions for something. The first list
167 is a sublist of the second. Both are sorted.
168
169 If there is a Python subprocess, get the comp. list there. Otherwise,
170 either fetch_completions() is running in the subprocess itself or it
171 was called in an IDLE EditorWindow before any script had been run.
172
173 The subprocess environment is that of the most recently run script. If
174 two unrelated modules are being edited some calltips in the current
175 module may be inoperative if the module was not the last to run.
176 """
177 try:
178 rpcclt = self.editwin.flist.pyshell.interp.rpcclt
179 except:
180 rpcclt = None
181 if rpcclt:
182 return rpcclt.remotecall("exec", "get_the_completion_list",
183 (what, mode), {})
184 else:
185 if mode == COMPLETE_ATTRIBUTES:
186 if what == "":
187 namespace = __main__.__dict__.copy()
188 namespace.update(__main__.__builtins__.__dict__)
189 bigl = eval("dir()", namespace)
190 bigl.sort()
191 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500192 smalll = sorted(eval("__all__", namespace))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000193 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000194 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000195 else:
196 try:
197 entity = self.get_entity(what)
198 bigl = dir(entity)
199 bigl.sort()
200 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500201 smalll = sorted(entity.__all__)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000202 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000203 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000204 except:
205 return [], []
206
207 elif mode == COMPLETE_FILES:
208 if what == "":
209 what = "."
210 try:
211 expandedpath = os.path.expanduser(what)
212 bigl = os.listdir(expandedpath)
213 bigl.sort()
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000214 smalll = [s for s in bigl if s[:1] != '.']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000215 except OSError:
216 return [], []
217
218 if not smalll:
219 smalll = bigl
220 return smalll, bigl
221
222 def get_entity(self, name):
223 """Lookup name in a namespace spanning sys.modules and __main.dict__"""
224 namespace = sys.modules.copy()
225 namespace.update(__main__.__dict__)
226 return eval(name, namespace)
Terry Jan Reedye3fcfc22014-06-03 20:54:21 -0400227
228
229if __name__ == '__main__':
230 from unittest import main
231 main('idlelib.idle_test.test_autocomplete', verbosity=2)