annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/idlelib/autocomplete.py @ 68:5028fdace37b

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 16:23:26 -0400
parents
children
rev   line source
jpayne@68 1 """Complete either attribute names or file names.
jpayne@68 2
jpayne@68 3 Either on demand or after a user-selected delay after a key character,
jpayne@68 4 pop up a list of candidates.
jpayne@68 5 """
jpayne@68 6 import __main__
jpayne@68 7 import os
jpayne@68 8 import string
jpayne@68 9 import sys
jpayne@68 10
jpayne@68 11 # Two types of completions; defined here for autocomplete_w import below.
jpayne@68 12 ATTRS, FILES = 0, 1
jpayne@68 13 from idlelib import autocomplete_w
jpayne@68 14 from idlelib.config import idleConf
jpayne@68 15 from idlelib.hyperparser import HyperParser
jpayne@68 16
jpayne@68 17 # Tuples passed to open_completions.
jpayne@68 18 # EvalFunc, Complete, WantWin, Mode
jpayne@68 19 FORCE = True, False, True, None # Control-Space.
jpayne@68 20 TAB = False, True, True, None # Tab.
jpayne@68 21 TRY_A = False, False, False, ATTRS # '.' for attributes.
jpayne@68 22 TRY_F = False, False, False, FILES # '/' in quotes for file name.
jpayne@68 23
jpayne@68 24 # This string includes all chars that may be in an identifier.
jpayne@68 25 # TODO Update this here and elsewhere.
jpayne@68 26 ID_CHARS = string.ascii_letters + string.digits + "_"
jpayne@68 27
jpayne@68 28 SEPS = f"{os.sep}{os.altsep if os.altsep else ''}"
jpayne@68 29 TRIGGERS = f".{SEPS}"
jpayne@68 30
jpayne@68 31 class AutoComplete:
jpayne@68 32
jpayne@68 33 def __init__(self, editwin=None):
jpayne@68 34 self.editwin = editwin
jpayne@68 35 if editwin is not None: # not in subprocess or no-gui test
jpayne@68 36 self.text = editwin.text
jpayne@68 37 self.autocompletewindow = None
jpayne@68 38 # id of delayed call, and the index of the text insert when
jpayne@68 39 # the delayed call was issued. If _delayed_completion_id is
jpayne@68 40 # None, there is no delayed call.
jpayne@68 41 self._delayed_completion_id = None
jpayne@68 42 self._delayed_completion_index = None
jpayne@68 43
jpayne@68 44 @classmethod
jpayne@68 45 def reload(cls):
jpayne@68 46 cls.popupwait = idleConf.GetOption(
jpayne@68 47 "extensions", "AutoComplete", "popupwait", type="int", default=0)
jpayne@68 48
jpayne@68 49 def _make_autocomplete_window(self): # Makes mocking easier.
jpayne@68 50 return autocomplete_w.AutoCompleteWindow(self.text)
jpayne@68 51
jpayne@68 52 def _remove_autocomplete_window(self, event=None):
jpayne@68 53 if self.autocompletewindow:
jpayne@68 54 self.autocompletewindow.hide_window()
jpayne@68 55 self.autocompletewindow = None
jpayne@68 56
jpayne@68 57 def force_open_completions_event(self, event):
jpayne@68 58 "(^space) Open completion list, even if a function call is needed."
jpayne@68 59 self.open_completions(FORCE)
jpayne@68 60 return "break"
jpayne@68 61
jpayne@68 62 def autocomplete_event(self, event):
jpayne@68 63 "(tab) Complete word or open list if multiple options."
jpayne@68 64 if hasattr(event, "mc_state") and event.mc_state or\
jpayne@68 65 not self.text.get("insert linestart", "insert").strip():
jpayne@68 66 # A modifier was pressed along with the tab or
jpayne@68 67 # there is only previous whitespace on this line, so tab.
jpayne@68 68 return None
jpayne@68 69 if self.autocompletewindow and self.autocompletewindow.is_active():
jpayne@68 70 self.autocompletewindow.complete()
jpayne@68 71 return "break"
jpayne@68 72 else:
jpayne@68 73 opened = self.open_completions(TAB)
jpayne@68 74 return "break" if opened else None
jpayne@68 75
jpayne@68 76 def try_open_completions_event(self, event=None):
jpayne@68 77 "(./) Open completion list after pause with no movement."
jpayne@68 78 lastchar = self.text.get("insert-1c")
jpayne@68 79 if lastchar in TRIGGERS:
jpayne@68 80 args = TRY_A if lastchar == "." else TRY_F
jpayne@68 81 self._delayed_completion_index = self.text.index("insert")
jpayne@68 82 if self._delayed_completion_id is not None:
jpayne@68 83 self.text.after_cancel(self._delayed_completion_id)
jpayne@68 84 self._delayed_completion_id = self.text.after(
jpayne@68 85 self.popupwait, self._delayed_open_completions, args)
jpayne@68 86
jpayne@68 87 def _delayed_open_completions(self, args):
jpayne@68 88 "Call open_completions if index unchanged."
jpayne@68 89 self._delayed_completion_id = None
jpayne@68 90 if self.text.index("insert") == self._delayed_completion_index:
jpayne@68 91 self.open_completions(args)
jpayne@68 92
jpayne@68 93 def open_completions(self, args):
jpayne@68 94 """Find the completions and create the AutoCompleteWindow.
jpayne@68 95 Return True if successful (no syntax error or so found).
jpayne@68 96 If complete is True, then if there's nothing to complete and no
jpayne@68 97 start of completion, won't open completions and return False.
jpayne@68 98 If mode is given, will open a completion list only in this mode.
jpayne@68 99 """
jpayne@68 100 evalfuncs, complete, wantwin, mode = args
jpayne@68 101 # Cancel another delayed call, if it exists.
jpayne@68 102 if self._delayed_completion_id is not None:
jpayne@68 103 self.text.after_cancel(self._delayed_completion_id)
jpayne@68 104 self._delayed_completion_id = None
jpayne@68 105
jpayne@68 106 hp = HyperParser(self.editwin, "insert")
jpayne@68 107 curline = self.text.get("insert linestart", "insert")
jpayne@68 108 i = j = len(curline)
jpayne@68 109 if hp.is_in_string() and (not mode or mode==FILES):
jpayne@68 110 # Find the beginning of the string.
jpayne@68 111 # fetch_completions will look at the file system to determine
jpayne@68 112 # whether the string value constitutes an actual file name
jpayne@68 113 # XXX could consider raw strings here and unescape the string
jpayne@68 114 # value if it's not raw.
jpayne@68 115 self._remove_autocomplete_window()
jpayne@68 116 mode = FILES
jpayne@68 117 # Find last separator or string start
jpayne@68 118 while i and curline[i-1] not in "'\"" + SEPS:
jpayne@68 119 i -= 1
jpayne@68 120 comp_start = curline[i:j]
jpayne@68 121 j = i
jpayne@68 122 # Find string start
jpayne@68 123 while i and curline[i-1] not in "'\"":
jpayne@68 124 i -= 1
jpayne@68 125 comp_what = curline[i:j]
jpayne@68 126 elif hp.is_in_code() and (not mode or mode==ATTRS):
jpayne@68 127 self._remove_autocomplete_window()
jpayne@68 128 mode = ATTRS
jpayne@68 129 while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127):
jpayne@68 130 i -= 1
jpayne@68 131 comp_start = curline[i:j]
jpayne@68 132 if i and curline[i-1] == '.': # Need object with attributes.
jpayne@68 133 hp.set_index("insert-%dc" % (len(curline)-(i-1)))
jpayne@68 134 comp_what = hp.get_expression()
jpayne@68 135 if (not comp_what or
jpayne@68 136 (not evalfuncs and comp_what.find('(') != -1)):
jpayne@68 137 return None
jpayne@68 138 else:
jpayne@68 139 comp_what = ""
jpayne@68 140 else:
jpayne@68 141 return None
jpayne@68 142
jpayne@68 143 if complete and not comp_what and not comp_start:
jpayne@68 144 return None
jpayne@68 145 comp_lists = self.fetch_completions(comp_what, mode)
jpayne@68 146 if not comp_lists[0]:
jpayne@68 147 return None
jpayne@68 148 self.autocompletewindow = self._make_autocomplete_window()
jpayne@68 149 return not self.autocompletewindow.show_window(
jpayne@68 150 comp_lists, "insert-%dc" % len(comp_start),
jpayne@68 151 complete, mode, wantwin)
jpayne@68 152
jpayne@68 153 def fetch_completions(self, what, mode):
jpayne@68 154 """Return a pair of lists of completions for something. The first list
jpayne@68 155 is a sublist of the second. Both are sorted.
jpayne@68 156
jpayne@68 157 If there is a Python subprocess, get the comp. list there. Otherwise,
jpayne@68 158 either fetch_completions() is running in the subprocess itself or it
jpayne@68 159 was called in an IDLE EditorWindow before any script had been run.
jpayne@68 160
jpayne@68 161 The subprocess environment is that of the most recently run script. If
jpayne@68 162 two unrelated modules are being edited some calltips in the current
jpayne@68 163 module may be inoperative if the module was not the last to run.
jpayne@68 164 """
jpayne@68 165 try:
jpayne@68 166 rpcclt = self.editwin.flist.pyshell.interp.rpcclt
jpayne@68 167 except:
jpayne@68 168 rpcclt = None
jpayne@68 169 if rpcclt:
jpayne@68 170 return rpcclt.remotecall("exec", "get_the_completion_list",
jpayne@68 171 (what, mode), {})
jpayne@68 172 else:
jpayne@68 173 if mode == ATTRS:
jpayne@68 174 if what == "":
jpayne@68 175 namespace = {**__main__.__builtins__.__dict__,
jpayne@68 176 **__main__.__dict__}
jpayne@68 177 bigl = eval("dir()", namespace)
jpayne@68 178 bigl.sort()
jpayne@68 179 if "__all__" in bigl:
jpayne@68 180 smalll = sorted(eval("__all__", namespace))
jpayne@68 181 else:
jpayne@68 182 smalll = [s for s in bigl if s[:1] != '_']
jpayne@68 183 else:
jpayne@68 184 try:
jpayne@68 185 entity = self.get_entity(what)
jpayne@68 186 bigl = dir(entity)
jpayne@68 187 bigl.sort()
jpayne@68 188 if "__all__" in bigl:
jpayne@68 189 smalll = sorted(entity.__all__)
jpayne@68 190 else:
jpayne@68 191 smalll = [s for s in bigl if s[:1] != '_']
jpayne@68 192 except:
jpayne@68 193 return [], []
jpayne@68 194
jpayne@68 195 elif mode == FILES:
jpayne@68 196 if what == "":
jpayne@68 197 what = "."
jpayne@68 198 try:
jpayne@68 199 expandedpath = os.path.expanduser(what)
jpayne@68 200 bigl = os.listdir(expandedpath)
jpayne@68 201 bigl.sort()
jpayne@68 202 smalll = [s for s in bigl if s[:1] != '.']
jpayne@68 203 except OSError:
jpayne@68 204 return [], []
jpayne@68 205
jpayne@68 206 if not smalll:
jpayne@68 207 smalll = bigl
jpayne@68 208 return smalll, bigl
jpayne@68 209
jpayne@68 210 def get_entity(self, name):
jpayne@68 211 "Lookup name in a namespace spanning sys.modules and __main.dict__."
jpayne@68 212 return eval(name, {**sys.modules, **__main__.__dict__})
jpayne@68 213
jpayne@68 214
jpayne@68 215 AutoComplete.reload()
jpayne@68 216
jpayne@68 217 if __name__ == '__main__':
jpayne@68 218 from unittest import main
jpayne@68 219 main('idlelib.idle_test.test_autocomplete', verbosity=2)