blob: cd212ccb143a3c7a0a30327e2777326bbef48d02 [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)
Serhiy Storchaka213ce122017-06-27 07:02:32 +030063 return "break"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000064
65 def try_open_completions_event(self, event):
66 """Happens when it would be nice to open a completion list, but not
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +030067 really necessary, for example after a dot, so function
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000068 calls won't be made.
69 """
70 lastchar = self.text.get("insert-1c")
71 if lastchar == ".":
72 self._open_completions_later(False, False, False,
73 COMPLETE_ATTRIBUTES)
Christian Heimes81ee3ef2008-05-04 22:42:01 +000074 elif lastchar in SEPS:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000075 self._open_completions_later(False, False, False,
76 COMPLETE_FILES)
77
78 def autocomplete_event(self, event):
Mark Dickinson934896d2009-02-21 20:59:32 +000079 """Happens when the user wants to complete his word, and if necessary,
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000080 open a completion list after that (if there is more than one
81 completion)
82 """
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -040083 if hasattr(event, "mc_state") and event.mc_state or\
84 not self.text.get("insert linestart", "insert").strip():
85 # A modifier was pressed along with the tab or
86 # there is only previous whitespace on this line, so tab.
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -040087 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000088 if self.autocompletewindow and self.autocompletewindow.is_active():
89 self.autocompletewindow.complete()
90 return "break"
91 else:
92 opened = self.open_completions(False, True, True)
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -040093 return "break" if opened else None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000094
95 def _open_completions_later(self, *args):
96 self._delayed_completion_index = self.text.index("insert")
97 if self._delayed_completion_id is not None:
98 self.text.after_cancel(self._delayed_completion_id)
99 self._delayed_completion_id = \
100 self.text.after(self.popupwait, self._delayed_open_completions,
101 *args)
102
103 def _delayed_open_completions(self, *args):
104 self._delayed_completion_id = None
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400105 if self.text.index("insert") == self._delayed_completion_index:
106 self.open_completions(*args)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000107
108 def open_completions(self, evalfuncs, complete, userWantsWin, mode=None):
109 """Find the completions and create the AutoCompleteWindow.
110 Return True if successful (no syntax error or so found).
111 if complete is True, then if there's nothing to complete and no
112 start of completion, won't open completions and return False.
113 If mode is given, will open a completion list only in this mode.
114 """
115 # Cancel another delayed call, if it exists.
116 if self._delayed_completion_id is not None:
117 self.text.after_cancel(self._delayed_completion_id)
118 self._delayed_completion_id = None
119
120 hp = HyperParser(self.editwin, "insert")
121 curline = self.text.get("insert linestart", "insert")
122 i = j = len(curline)
123 if hp.is_in_string() and (not mode or mode==COMPLETE_FILES):
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200124 # Find the beginning of the string
125 # fetch_completions will look at the file system to determine whether the
126 # string value constitutes an actual file name
127 # XXX could consider raw strings here and unescape the string value if it's
128 # not raw.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000129 self._remove_autocomplete_window()
130 mode = COMPLETE_FILES
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200131 # Find last separator or string start
132 while i and curline[i-1] not in "'\"" + SEPS:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000133 i -= 1
134 comp_start = curline[i:j]
135 j = i
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200136 # Find string start
137 while i and curline[i-1] not in "'\"":
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000138 i -= 1
139 comp_what = curline[i:j]
140 elif hp.is_in_code() and (not mode or mode==COMPLETE_ATTRIBUTES):
141 self._remove_autocomplete_window()
142 mode = COMPLETE_ATTRIBUTES
Martin v. Löwis993fe3f2012-06-14 15:37:21 +0200143 while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000144 i -= 1
145 comp_start = curline[i:j]
146 if i and curline[i-1] == '.':
147 hp.set_index("insert-%dc" % (len(curline)-(i-1)))
148 comp_what = hp.get_expression()
149 if not comp_what or \
150 (not evalfuncs and comp_what.find('(') != -1):
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400151 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000152 else:
153 comp_what = ""
154 else:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400155 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000156
157 if complete and not comp_what and not comp_start:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400158 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000159 comp_lists = self.fetch_completions(comp_what, mode)
160 if not comp_lists[0]:
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400161 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000162 self.autocompletewindow = self._make_autocomplete_window()
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300163 return not self.autocompletewindow.show_window(
164 comp_lists, "insert-%dc" % len(comp_start),
165 complete, mode, userWantsWin)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000166
167 def fetch_completions(self, what, mode):
168 """Return a pair of lists of completions for something. The first list
169 is a sublist of the second. Both are sorted.
170
171 If there is a Python subprocess, get the comp. list there. Otherwise,
172 either fetch_completions() is running in the subprocess itself or it
173 was called in an IDLE EditorWindow before any script had been run.
174
175 The subprocess environment is that of the most recently run script. If
176 two unrelated modules are being edited some calltips in the current
177 module may be inoperative if the module was not the last to run.
178 """
179 try:
180 rpcclt = self.editwin.flist.pyshell.interp.rpcclt
181 except:
182 rpcclt = None
183 if rpcclt:
184 return rpcclt.remotecall("exec", "get_the_completion_list",
185 (what, mode), {})
186 else:
187 if mode == COMPLETE_ATTRIBUTES:
188 if what == "":
189 namespace = __main__.__dict__.copy()
190 namespace.update(__main__.__builtins__.__dict__)
191 bigl = eval("dir()", namespace)
192 bigl.sort()
193 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500194 smalll = sorted(eval("__all__", namespace))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000195 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000196 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000197 else:
198 try:
199 entity = self.get_entity(what)
200 bigl = dir(entity)
201 bigl.sort()
202 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500203 smalll = sorted(entity.__all__)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000204 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000205 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000206 except:
207 return [], []
208
209 elif mode == COMPLETE_FILES:
210 if what == "":
211 what = "."
212 try:
213 expandedpath = os.path.expanduser(what)
214 bigl = os.listdir(expandedpath)
215 bigl.sort()
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000216 smalll = [s for s in bigl if s[:1] != '.']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000217 except OSError:
218 return [], []
219
220 if not smalll:
221 smalll = bigl
222 return smalll, bigl
223
224 def get_entity(self, name):
225 """Lookup name in a namespace spanning sys.modules and __main.dict__"""
226 namespace = sys.modules.copy()
227 namespace.update(__main__.__dict__)
228 return eval(name, namespace)
Terry Jan Reedye3fcfc22014-06-03 20:54:21 -0400229
230
231if __name__ == '__main__':
232 from unittest import main
233 main('idlelib.idle_test.test_autocomplete', verbosity=2)