blob: 1e44fa5bc66e8aecdf623ac4a10687b745c9630b [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
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00007import string
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -04008import sys
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00009
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -040010# These constants represent the two different types of completions.
11# They must be defined here so autocomple_w can import them.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000012COMPLETE_ATTRIBUTES, COMPLETE_FILES = range(1, 2+1)
13
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040014from idlelib import autocomplete_w
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -040015from idlelib.config import idleConf
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040016from idlelib.hyperparser import HyperParser
Kurt B. Kaisere1b4a162007-08-10 02:45:06 +000017import __main__
18
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -040019# This string includes all chars that may be in an identifier.
20# TODO Update this here and elsewhere.
21ID_CHARS = string.ascii_letters + string.digits + "_"
22
Christian Heimes81ee3ef2008-05-04 22:42:01 +000023SEPS = os.sep
24if os.altsep: # e.g. '/' on Windows...
25 SEPS += os.altsep
26
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -040027
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000028class AutoComplete:
29
30 menudefs = [
31 ('edit', [
Guido van Rossum8ce8a782007-11-01 19:42:39 +000032 ("Show Completions", "<<force-open-completions>>"),
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000033 ])
34 ]
35
36 popupwait = idleConf.GetOption("extensions", "AutoComplete",
37 "popupwait", type="int", default=0)
38
39 def __init__(self, editwin=None):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000040 self.editwin = editwin
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -040041 if editwin is not None: # not in subprocess or test
42 self.text = editwin.text
43 self.autocompletewindow = None
44 # id of delayed call, and the index of the text insert when
45 # the delayed call was issued. If _delayed_completion_id is
46 # None, there is no delayed call.
47 self._delayed_completion_id = None
48 self._delayed_completion_index = None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000049
50 def _make_autocomplete_window(self):
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040051 return autocomplete_w.AutoCompleteWindow(self.text)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000052
53 def _remove_autocomplete_window(self, event=None):
54 if self.autocompletewindow:
55 self.autocompletewindow.hide_window()
56 self.autocompletewindow = None
57
58 def force_open_completions_event(self, event):
59 """Happens when the user really wants to open a completion list, even
60 if a function call is needed.
61 """
62 self.open_completions(True, False, True)
63
64 def try_open_completions_event(self, event):
65 """Happens when it would be nice to open a completion list, but not
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +030066 really necessary, for example after a dot, so function
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000067 calls won't be made.
68 """
69 lastchar = self.text.get("insert-1c")
70 if lastchar == ".":
71 self._open_completions_later(False, False, False,
72 COMPLETE_ATTRIBUTES)
Christian Heimes81ee3ef2008-05-04 22:42:01 +000073 elif lastchar in SEPS:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000074 self._open_completions_later(False, False, False,
75 COMPLETE_FILES)
76
77 def autocomplete_event(self, event):
Mark Dickinson934896d2009-02-21 20:59:32 +000078 """Happens when the user wants to complete his word, and if necessary,
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000079 open a completion list after that (if there is more than one
80 completion)
81 """
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -040082 if hasattr(event, "mc_state") and event.mc_state or\
83 not self.text.get("insert linestart", "insert").strip():
84 # A modifier was pressed along with the tab or
85 # there is only previous whitespace on this line, so tab.
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -040086 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000087 if self.autocompletewindow and self.autocompletewindow.is_active():
88 self.autocompletewindow.complete()
89 return "break"
90 else:
91 opened = self.open_completions(False, True, True)
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -040092 return "break" if opened else None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000093
94 def _open_completions_later(self, *args):
95 self._delayed_completion_index = self.text.index("insert")
96 if self._delayed_completion_id is not None:
97 self.text.after_cancel(self._delayed_completion_id)
98 self._delayed_completion_id = \
99 self.text.after(self.popupwait, self._delayed_open_completions,
100 *args)
101
102 def _delayed_open_completions(self, *args):
103 self._delayed_completion_id = None
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400104 if self.text.index("insert") == self._delayed_completion_index:
105 self.open_completions(*args)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000106
107 def open_completions(self, evalfuncs, complete, userWantsWin, mode=None):
108 """Find the completions and create the AutoCompleteWindow.
109 Return True if successful (no syntax error or so found).
110 if complete is True, then if there's nothing to complete and no
111 start of completion, won't open completions and return False.
112 If mode is given, will open a completion list only in this mode.
113 """
114 # Cancel another delayed call, if it exists.
115 if self._delayed_completion_id is not None:
116 self.text.after_cancel(self._delayed_completion_id)
117 self._delayed_completion_id = None
118
119 hp = HyperParser(self.editwin, "insert")
120 curline = self.text.get("insert linestart", "insert")
121 i = j = len(curline)
122 if hp.is_in_string() and (not mode or mode==COMPLETE_FILES):
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200123 # Find the beginning of the string
124 # fetch_completions will look at the file system to determine whether the
125 # string value constitutes an actual file name
126 # XXX could consider raw strings here and unescape the string value if it's
127 # not raw.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000128 self._remove_autocomplete_window()
129 mode = COMPLETE_FILES
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200130 # Find last separator or string start
131 while i and curline[i-1] not in "'\"" + SEPS:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000132 i -= 1
133 comp_start = curline[i:j]
134 j = i
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200135 # Find string start
136 while i and curline[i-1] not in "'\"":
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000137 i -= 1
138 comp_what = curline[i:j]
139 elif hp.is_in_code() and (not mode or mode==COMPLETE_ATTRIBUTES):
140 self._remove_autocomplete_window()
141 mode = COMPLETE_ATTRIBUTES
Martin v. Löwis993fe3f2012-06-14 15:37:21 +0200142 while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000143 i -= 1
144 comp_start = curline[i:j]
145 if i and curline[i-1] == '.':
146 hp.set_index("insert-%dc" % (len(curline)-(i-1)))
147 comp_what = hp.get_expression()
148 if not comp_what or \
149 (not evalfuncs and comp_what.find('(') != -1):
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400150 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000151 else:
152 comp_what = ""
153 else:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400154 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000155
156 if complete and not comp_what and not comp_start:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400157 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000158 comp_lists = self.fetch_completions(comp_what, mode)
159 if not comp_lists[0]:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400160 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000161 self.autocompletewindow = self._make_autocomplete_window()
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300162 return not self.autocompletewindow.show_window(
163 comp_lists, "insert-%dc" % len(comp_start),
164 complete, mode, userWantsWin)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000165
166 def fetch_completions(self, what, mode):
167 """Return a pair of lists of completions for something. The first list
168 is a sublist of the second. Both are sorted.
169
170 If there is a Python subprocess, get the comp. list there. Otherwise,
171 either fetch_completions() is running in the subprocess itself or it
172 was called in an IDLE EditorWindow before any script had been run.
173
174 The subprocess environment is that of the most recently run script. If
175 two unrelated modules are being edited some calltips in the current
176 module may be inoperative if the module was not the last to run.
177 """
178 try:
179 rpcclt = self.editwin.flist.pyshell.interp.rpcclt
180 except:
181 rpcclt = None
182 if rpcclt:
183 return rpcclt.remotecall("exec", "get_the_completion_list",
184 (what, mode), {})
185 else:
186 if mode == COMPLETE_ATTRIBUTES:
187 if what == "":
188 namespace = __main__.__dict__.copy()
189 namespace.update(__main__.__builtins__.__dict__)
190 bigl = eval("dir()", namespace)
191 bigl.sort()
192 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500193 smalll = sorted(eval("__all__", namespace))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000194 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000195 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000196 else:
197 try:
198 entity = self.get_entity(what)
199 bigl = dir(entity)
200 bigl.sort()
201 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500202 smalll = sorted(entity.__all__)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000203 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000204 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000205 except:
206 return [], []
207
208 elif mode == COMPLETE_FILES:
209 if what == "":
210 what = "."
211 try:
212 expandedpath = os.path.expanduser(what)
213 bigl = os.listdir(expandedpath)
214 bigl.sort()
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000215 smalll = [s for s in bigl if s[:1] != '.']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000216 except OSError:
217 return [], []
218
219 if not smalll:
220 smalll = bigl
221 return smalll, bigl
222
223 def get_entity(self, name):
224 """Lookup name in a namespace spanning sys.modules and __main.dict__"""
225 namespace = sys.modules.copy()
226 namespace.update(__main__.__dict__)
227 return eval(name, namespace)
Terry Jan Reedye3fcfc22014-06-03 20:54:21 -0400228
229
230if __name__ == '__main__':
231 from unittest import main
232 main('idlelib.idle_test.test_autocomplete', verbosity=2)