blob: 929d3581c9706c523af9a57d8e31be61d3af91bd [file] [log] [blame]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00001"""AutoComplete.py - An IDLE extension for automatically completing names.
2
3This extension can complete either attribute names of file names. It can pop
4a window with all available names, for the user to select from.
5"""
6import os
7import sys
8import string
9
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000010from idlelib.configHandler 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
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000018from idlelib import AutoCompleteWindow
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
Benjamin Peterson2a691a82008-03-31 01:51:45 +000040 if editwin is None: # subprocess and test
41 return
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000042 self.text = editwin.text
43 self.autocompletewindow = None
44
45 # id of delayed call, and the index of the text insert when the delayed
46 # call was issued. If _delayed_completion_id is None, there is no
47 # delayed call.
48 self._delayed_completion_id = None
49 self._delayed_completion_index = None
50
51 def _make_autocomplete_window(self):
52 return AutoCompleteWindow.AutoCompleteWindow(self.text)
53
54 def _remove_autocomplete_window(self, event=None):
55 if self.autocompletewindow:
56 self.autocompletewindow.hide_window()
57 self.autocompletewindow = None
58
59 def force_open_completions_event(self, event):
60 """Happens when the user really wants to open a completion list, even
61 if a function call is needed.
62 """
63 self.open_completions(True, False, True)
64
65 def try_open_completions_event(self, event):
66 """Happens when it would be nice to open a completion list, but not
Mark Dickinson934896d2009-02-21 20:59:32 +000067 really necessary, for example after an 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 """
83 if hasattr(event, "mc_state") and event.mc_state:
84 # A modifier was pressed along with the tab, continue as usual.
85 return
86 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)
91 if opened:
92 return "break"
93
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
104 if self.text.index("insert") != self._delayed_completion_index:
105 return
106 self.open_completions(*args)
107
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):
151 return
152 else:
153 comp_what = ""
154 else:
155 return
156
157 if complete and not comp_what and not comp_start:
158 return
159 comp_lists = self.fetch_completions(comp_what, mode)
160 if not comp_lists[0]:
161 return
162 self.autocompletewindow = self._make_autocomplete_window()
163 self.autocompletewindow.show_window(comp_lists,
164 "insert-%dc" % len(comp_start),
165 complete,
166 mode,
167 userWantsWin)
168 return True
169
170 def fetch_completions(self, what, mode):
171 """Return a pair of lists of completions for something. The first list
172 is a sublist of the second. Both are sorted.
173
174 If there is a Python subprocess, get the comp. list there. Otherwise,
175 either fetch_completions() is running in the subprocess itself or it
176 was called in an IDLE EditorWindow before any script had been run.
177
178 The subprocess environment is that of the most recently run script. If
179 two unrelated modules are being edited some calltips in the current
180 module may be inoperative if the module was not the last to run.
181 """
182 try:
183 rpcclt = self.editwin.flist.pyshell.interp.rpcclt
184 except:
185 rpcclt = None
186 if rpcclt:
187 return rpcclt.remotecall("exec", "get_the_completion_list",
188 (what, mode), {})
189 else:
190 if mode == COMPLETE_ATTRIBUTES:
191 if what == "":
192 namespace = __main__.__dict__.copy()
193 namespace.update(__main__.__builtins__.__dict__)
194 bigl = eval("dir()", namespace)
195 bigl.sort()
196 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500197 smalll = sorted(eval("__all__", namespace))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000198 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000199 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000200 else:
201 try:
202 entity = self.get_entity(what)
203 bigl = dir(entity)
204 bigl.sort()
205 if "__all__" in bigl:
Terry Jan Reedya77aa692012-02-05 14:31:16 -0500206 smalll = sorted(entity.__all__)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000207 else:
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000208 smalll = [s for s in bigl if s[:1] != '_']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000209 except:
210 return [], []
211
212 elif mode == COMPLETE_FILES:
213 if what == "":
214 what = "."
215 try:
216 expandedpath = os.path.expanduser(what)
217 bigl = os.listdir(expandedpath)
218 bigl.sort()
Kurt B. Kaiserf2335a92007-08-10 02:41:21 +0000219 smalll = [s for s in bigl if s[:1] != '.']
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000220 except OSError:
221 return [], []
222
223 if not smalll:
224 smalll = bigl
225 return smalll, bigl
226
227 def get_entity(self, name):
228 """Lookup name in a namespace spanning sys.modules and __main.dict__"""
229 namespace = sys.modules.copy()
230 namespace.update(__main__.__dict__)
231 return eval(name, namespace)