desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Destroy the page whose name is given in page_name.'
def remove_page(self, page_name):
if (not (page_name in self.pages)): raise KeyError(("No such TabPage: '%s" % page_name)) self._pages_order.remove(page_name) if (len(self._pages_order) > 0): if (page_name == self._default_page): self._default_page = self._pages_order[0] else: self._default_p...
'Show the page whose name is given in page_name.'
def change_page(self, page_name):
if (self._current_page == page_name): return if ((page_name is not None) and (page_name not in self.pages)): raise KeyError(("No such TabPage: '%s'" % page_name)) if (self._current_page is not None): self.pages[self._current_page]._hide() self._current_page = None if...
'cfgFile - string, fully specified configuration file name'
def __init__(self, cfgFile, cfgDefaults=None):
self.file = cfgFile ConfigParser.__init__(self, defaults=cfgDefaults)
'Get an option value for given section/option or return default. If type is specified, return as type.'
def Get(self, section, option, type=None, default=None, raw=False):
if (not self.has_option(section, option)): return default if (type == 'bool'): return self.getboolean(section, option) elif (type == 'int'): return self.getint(section, option) else: return self.get(section, option, raw=raw)
'Get an option list for given section'
def GetOptionList(self, section):
if self.has_section(section): return self.options(section) else: return []
'Load the configuration file from disk'
def Load(self):
self.read(self.file)
'if section doesn\'t exist, add it'
def AddSection(self, section):
if (not self.has_section(section)): self.add_section(section)
'remove any sections that have no options'
def RemoveEmptySections(self):
for section in self.sections(): if (not self.GetOptionList(section)): self.remove_section(section)
'Remove empty sections and then return 1 if parser has no sections left, else return 0.'
def IsEmpty(self):
self.RemoveEmptySections() if self.sections(): return 0 else: return 1
'If section/option exists, remove it. Returns 1 if option was removed, 0 otherwise.'
def RemoveOption(self, section, option):
if self.has_section(section): return self.remove_option(section, option)
'Sets option to value, adding section if required. Returns 1 if option was added or changed, otherwise 0.'
def SetOption(self, section, option, value):
if self.has_option(section, option): if (self.get(section, option) == value): return 0 else: self.set(section, option, value) return 1 else: if (not self.has_section(section)): self.add_section(section) self.set(section, option, val...
'Removes the user config file from disk if it exists.'
def RemoveFile(self):
if os.path.exists(self.file): os.remove(self.file)
'Update user configuration file. Remove empty sections. If resulting config isn\'t empty, write the file to disk. If config is empty, remove the file from disk if it exists.'
def Save(self):
if (not self.IsEmpty()): fname = self.file try: cfgFile = open(fname, 'w') except IOError: os.unlink(fname) cfgFile = open(fname, 'w') self.write(cfgFile) else: self.RemoveFile()
'set up a dictionary of config parsers for default and user configurations respectively'
def CreateConfigHandlers(self):
if (__name__ != '__main__'): idleDir = os.path.dirname(__file__) else: idleDir = os.path.abspath(sys.path[0]) userDir = self.GetUserCfgDir() configTypes = ('main', 'extensions', 'highlight', 'keys') defCfgFiles = {} usrCfgFiles = {} for cfgType in configTypes: defCfgF...
'Creates (if required) and returns a filesystem directory for storing user config files.'
def GetUserCfgDir(self):
cfgDir = '.idlerc' userDir = os.path.expanduser('~') if (userDir != '~'): if (not os.path.exists(userDir)): warn = (('\n Warning: os.path.expanduser("~") points to\n ' + userDir) + ',\n but the path does not exist.\n') try: sys...
'Get an option value for given config type and given general configuration section/option or return a default. If type is specified, return as type. Firstly the user configuration is checked, with a fallback to the default configuration, and a final \'catch all\' fallback to a useable passed-in default if the option is...
def GetOption(self, configType, section, option, default=None, type=None, warn_on_default=True, raw=False):
if self.userCfg[configType].has_option(section, option): return self.userCfg[configType].Get(section, option, type=type, raw=raw) elif self.defaultCfg[configType].has_option(section, option): return self.defaultCfg[configType].Get(section, option, type=type, raw=raw) else: if warn_on...
'In user\'s config file, set section\'s option to value.'
def SetOption(self, configType, section, option, value):
self.userCfg[configType].SetOption(section, option, value)
'Get a list of sections from either the user or default config for the given config type. configSet must be either \'user\' or \'default\' configType must be one of (\'main\',\'extensions\',\'highlight\',\'keys\')'
def GetSectionList(self, configSet, configType):
if (not (configType in ('main', 'extensions', 'highlight', 'keys'))): raise InvalidConfigType, 'Invalid configType specified' if (configSet == 'user'): cfgParser = self.userCfg[configType] elif (configSet == 'default'): cfgParser = self.defaultCfg[configType] else: ...
'return individual highlighting theme elements. fgBg - string (\'fg\'or\'bg\') or None, if None return a dictionary containing fg and bg colours (appropriate for passing to Tkinter in, e.g., a tag_config call), otherwise fg or bg colour only as specified.'
def GetHighlight(self, theme, element, fgBg=None):
if self.defaultCfg['highlight'].has_section(theme): themeDict = self.GetThemeDict('default', theme) else: themeDict = self.GetThemeDict('user', theme) fore = themeDict[(element + '-foreground')] if (element == 'cursor'): back = themeDict['normal-background'] else: bac...
'type - string, \'default\' or \'user\' theme type themeName - string, theme name Returns a dictionary which holds {option:value} for each element in the specified theme. Values are loaded over a set of ultimate last fallback defaults to guarantee that all theme elements are present in a newly created theme.'
def GetThemeDict(self, type, themeName):
if (type == 'user'): cfgParser = self.userCfg['highlight'] elif (type == 'default'): cfgParser = self.defaultCfg['highlight'] else: raise InvalidTheme, 'Invalid theme type specified' theme = {'normal-foreground': '#000000', 'normal-background': '#ffffff', 'keyword-foregr...
'Returns the name of the currently active theme'
def CurrentTheme(self):
return self.GetOption('main', 'Theme', 'name', default='')
'Returns the name of the currently active key set'
def CurrentKeys(self):
return self.GetOption('main', 'Keys', 'name', default='')
'Gets a list of all idle extensions declared in the config files. active_only - boolean, if true only return active (enabled) extensions'
def GetExtensions(self, active_only=True, editor_only=False, shell_only=False):
extns = self.RemoveKeyBindNames(self.GetSectionList('default', 'extensions')) userExtns = self.RemoveKeyBindNames(self.GetSectionList('user', 'extensions')) for extn in userExtns: if (extn not in extns): extns.append(extn) if active_only: activeExtns = [] for extn in ...
'Returns the name of the extension that virtualEvent is bound in, or None if not bound in any extension. virtualEvent - string, name of the virtual event to test for, without the enclosing \'<< >>\''
def GetExtnNameForEvent(self, virtualEvent):
extName = None vEvent = (('<<' + virtualEvent) + '>>') for extn in self.GetExtensions(active_only=0): for event in self.GetExtensionKeys(extn).keys(): if (event == vEvent): extName = extn return extName
'returns a dictionary of the configurable keybindings for a particular extension,as they exist in the dictionary returned by GetCurrentKeySet; that is, where previously used bindings are disabled.'
def GetExtensionKeys(self, extensionName):
keysName = (extensionName + '_cfgBindings') activeKeys = self.GetCurrentKeySet() extKeys = {} if self.defaultCfg['extensions'].has_section(keysName): eventNames = self.defaultCfg['extensions'].GetOptionList(keysName) for eventName in eventNames: event = (('<<' + eventName) + ...
'returns a dictionary of the configurable keybindings for a particular extension, as defined in the configuration files, or an empty dictionary if no bindings are found'
def __GetRawExtensionKeys(self, extensionName):
keysName = (extensionName + '_cfgBindings') extKeys = {} if self.defaultCfg['extensions'].has_section(keysName): eventNames = self.defaultCfg['extensions'].GetOptionList(keysName) for eventName in eventNames: binding = self.GetOption('extensions', keysName, eventName, default='')...
'Returns a dictionary of all the event bindings for a particular extension. The configurable keybindings are returned as they exist in the dictionary returned by GetCurrentKeySet; that is, where re-used keybindings are disabled.'
def GetExtensionBindings(self, extensionName):
bindsName = (extensionName + '_bindings') extBinds = self.GetExtensionKeys(extensionName) if self.defaultCfg['extensions'].has_section(bindsName): eventNames = self.defaultCfg['extensions'].GetOptionList(bindsName) for eventName in eventNames: binding = self.GetOption('extensions...
'returns the keybinding for a specific event. keySetName - string, name of key binding set eventStr - string, the virtual event we want the binding for, represented as a string, eg. \'<<event>>\''
def GetKeyBinding(self, keySetName, eventStr):
eventName = eventStr[2:(-2)] binding = self.GetOption('keys', keySetName, eventName, default='').split() return binding
'Returns a dictionary of: all requested core keybindings, plus the keybindings for all currently active extensions. If a binding defined in an extension is already in use, that binding is disabled.'
def GetKeySet(self, keySetName):
keySet = self.GetCoreKeys(keySetName) activeExtns = self.GetExtensions(active_only=1) for extn in activeExtns: extKeys = self.__GetRawExtensionKeys(extn) if extKeys: for event in extKeys.keys(): if (extKeys[event] in keySet.values()): extKeys[e...
'returns true if the virtual event is bound in the core idle keybindings. virtualEvent - string, name of the virtual event to test for, without the enclosing \'<< >>\''
def IsCoreBinding(self, virtualEvent):
return ((('<<' + virtualEvent) + '>>') in self.GetCoreKeys().keys())
'returns the requested set of core keybindings, with fallbacks if required. Keybindings loaded from the config file(s) are loaded _over_ these defaults, so if there is a problem getting any core binding there will be an \'ultimate last resort fallback\' to the CUA-ish bindings defined here.'
def GetCoreKeys(self, keySetName=None):
keyBindings = {'<<copy>>': ['<Control-c>', '<Control-C>'], '<<cut>>': ['<Control-x>', '<Control-X>'], '<<paste>>': ['<Control-v>', '<Control-V>'], '<<beginning-of-line>>': ['<Control-a>', '<Home>'], '<<center-insert>>': ['<Control-l>'], '<<close-all-windows>>': ['<Control-q>'], '<<close-window>>': ['<Alt-F4>'], '<<...
'Fetch list of extra help sources from a given configSet. Valid configSets are \'user\' or \'default\'. Return a list of tuples of the form (menu_item , path_to_help_file , option), or return the empty list. \'option\' is the sequence number of the help resource. \'option\' values determine the position of the menu ...
def GetExtraHelpSourceList(self, configSet):
helpSources = [] if (configSet == 'user'): cfgParser = self.userCfg['main'] elif (configSet == 'default'): cfgParser = self.defaultCfg['main'] else: raise InvalidConfigSet, 'Invalid configSet specified' options = cfgParser.GetOptionList('HelpFiles') for option in op...
'Returns a list of tuples containing the details of all additional help sources configured, or an empty list if there are none. Tuples are of the format returned by GetExtraHelpSourceList.'
def GetAllExtraHelpSourcesList(self):
allHelpSources = (self.GetExtraHelpSourceList('default') + self.GetExtraHelpSourceList('user')) return allHelpSources
'load all configuration files.'
def LoadCfgFiles(self):
for key in self.defaultCfg.keys(): self.defaultCfg[key].Load() self.userCfg[key].Load()
'write all loaded user configuration files back to disk'
def SaveUserCfgFiles(self):
for key in self.userCfg.keys(): self.userCfg[key].Save()
'Callback from Tcl which runs when the widget is referenced. If an operation has been registered in self._operations, apply the associated function to the args passed into Tcl. Otherwise, pass the operation through to Tk via the original Tcl function. Note that if a registered function is called, the operation is not p...
def dispatch(self, operation, *args):
m = self._operations.get(operation) try: if m: return m(*args) else: return self.tk.call(((self.orig, operation) + args)) except TclError: return ''
'Happens when the user really wants to open a CallTip, even if a function call is needed.'
def force_open_calltip_event(self, event):
self.open_calltip(True)
'Happens when it would be nice to open a CallTip, but not really necessary, for example after an opening bracket, so function calls won\'t be made.'
def try_open_calltip_event(self, event):
self.open_calltip(False)
'If there is already a calltip window, check if it is still needed, and if so, reload it.'
def refresh_calltip_event(self, event):
if (self.calltip and self.calltip.is_active()): self.open_calltip(False)
'Return the argument list and docstring of a function or class If there is a Python subprocess, get the calltip there. Otherwise, either fetch_tip() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run s...
def fetch_tip(self, name):
try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall('exec', 'get_the_calltip', (name,), {}) else: entity = self.get_entity(name) return get_arg_text(entity)
'Lookup name in a namespace spanning sys.modules and __main.dict__'
def get_entity(self, name):
if name: namespace = sys.modules.copy() namespace.update(__main__.__dict__) try: return eval(name, namespace) except (NameError, AttributeError): return None
'Clear and rebuild the HelpFiles section in self.changedItems'
def UpdateUserHelpChangedItems(self):
self.changedItems['main']['HelpFiles'] = {} for num in range(1, (len(self.userHelpList) + 1)): self.AddChangedItem('main', 'HelpFiles', str(num), string.join(self.userHelpList[(num - 1)][:2], ';'))
'load configuration from default and user config files and populate the widgets on the config dialog pages.'
def LoadConfigs(self):
self.LoadFontCfg() self.LoadTabCfg() self.LoadThemeCfg() self.LoadKeyCfg() self.LoadGeneralCfg()
'save a newly created core key set. keySetName - string, the name of the new key set keySet - dictionary containing the new key set'
def SaveNewKeySet(self, keySetName, keySet):
if (not idleConf.userCfg['keys'].has_section(keySetName)): idleConf.userCfg['keys'].add_section(keySetName) for event in keySet.keys(): value = keySet[event] idleConf.userCfg['keys'].SetOption(keySetName, event, value)
'save a newly created theme. themeName - string, the name of the new theme theme - dictionary containing the new theme'
def SaveNewTheme(self, themeName, theme):
if (not idleConf.userCfg['highlight'].has_section(themeName)): idleConf.userCfg['highlight'].add_section(themeName) for element in theme.keys(): value = theme[element] idleConf.userCfg['highlight'].SetOption(themeName, element, value)
'Save configuration changes to the user config file.'
def SaveAllChangedConfigs(self):
idleConf.userCfg['main'].Save() for configType in self.changedItems.keys(): cfgTypeHasChanges = False for section in self.changedItems[configType].keys(): if (section == 'HelpFiles'): idleConf.userCfg['main'].remove_section('HelpFiles') cfgTypeHasChang...
'Dynamically apply configuration changes'
def ActivateConfigChanges(self):
winInstances = self.parent.instance_dict.keys() for instance in winInstances: instance.ResetColorizer() instance.ResetFont() instance.set_notabs_indentwidth() instance.ApplyKeybindings() instance.reset_help_menu_entries()
'Get menu entry and url/ local file location for Additional Help User selects a name for the Help resource and provides a web url or a local file as its source. The user can enter a url or browse for the file.'
def __init__(self, parent, title, menuItem='', filePath=''):
Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol('WM_DELETE_WINDOW', self.Cancel) self.parent = parent self.result = None self.CreateWidgets() self.me...
'Simple validity check for a sensible menu item name'
def MenuOk(self):
menuOk = True menu = self.menu.get() menu.strip() if (not menu): tkMessageBox.showerror(title='Menu Item Error', message='No menu item specified', parent=self) self.entryMenu.focus_set() menuOk = False elif (len(menu) > 30): tkMessageBox.showerror(title...
'Simple validity check for menu file path'
def PathOk(self):
pathOk = True path = self.path.get() path.strip() if (not path): tkMessageBox.showerror(title='File Path Error', message='No help file path specified.', parent=self) self.entryPath.focus_set() pathOk = False elif path.startswith(('www.', 'http')): pa...
'message - string, informational message to display usedNames - list, list of names already in use for validity check'
def __init__(self, parent, title, message, usedNames):
Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol('WM_DELETE_WINDOW', self.Cancel) self.parent = parent self.message = message self.usedNames = usedNames ...
'Initialize the HyperParser to analyze the surroundings of the given index.'
def __init__(self, editwin, index):
self.editwin = editwin self.text = text = editwin.text parser = PyParse.Parser(editwin.indentwidth, editwin.tabwidth) def index2line(index): return int(float(index)) lno = index2line(text.index(index)) if (not editwin.context_use_ps1): for context in editwin.num_context_lines: ...
'Set the index to which the functions relate. Note that it must be in the same statement.'
def set_index(self, index):
indexinrawtext = (len(self.rawtext) - len(self.text.get(index, self.stopatindex))) if (indexinrawtext < 0): raise ValueError('The index given is before the analyzed statement') self.indexinrawtext = indexinrawtext self.indexbracket = 0 while ((self.indexbracket < (len(se...
'Is the index given to the HyperParser is in a string?'
def is_in_string(self):
return (self.isopener[self.indexbracket] and (self.rawtext[self.bracketing[self.indexbracket][0]] in ('"', "'")))
'Is the index given to the HyperParser is in a normal code?'
def is_in_code(self):
return ((not self.isopener[self.indexbracket]) or (self.rawtext[self.bracketing[self.indexbracket][0]] not in ('#', '"', "'")))
'If the index given to the HyperParser is surrounded by a bracket defined in openers (or at least has one before it), return the indices of the opening bracket and the closing bracket (or the end of line, whichever comes first). If it is not surrounded by brackets, or the end of line comes before the closing bracket an...
def get_surrounding_brackets(self, openers='([{', mustclose=False):
bracketinglevel = self.bracketing[self.indexbracket][1] before = self.indexbracket while ((not self.isopener[before]) or (self.rawtext[self.bracketing[before][0]] not in openers) or (self.bracketing[before][1] > bracketinglevel)): before -= 1 if (before < 0): return None ...
'Return a string with the Python expression which ends at the given index, which is empty if there is no real one.'
def get_expression(self):
if (not self.is_in_code()): raise ValueError('get_expression should only be called if index is inside a code.') rawtext = self.rawtext bracketing = self.bracketing brck_index = self.indexbracket brck_limit = bracketing[brck_index][0] pos = self.indexinrawtex...
'Save breakpoints when file is saved'
def store_file_breaks(self):
breaks = self.breakpoints filename = self.io.filename try: lines = open(self.breakpointPath, 'r').readlines() except IOError: lines = [] new_file = open(self.breakpointPath, 'w') for line in lines: if (not line.startswith((filename + '='))): new_file.write(lin...
'Retrieves all the breakpoints in the current window'
def update_breakpoints(self):
text = self.text ranges = text.tag_ranges('BREAK') linenumber_list = self.ranges_to_linenumbers(ranges) self.breakpoints = linenumber_list
'Extend base method - clear breaks when module is closed'
def _close(self):
self.clear_file_breaks() EditorWindow._close(self)
'Override the base class - just re-raise EOFError'
def handle_EOF(self):
raise EOFError
'UNIX: make sure subprocess is terminated and collect status'
def unix_terminate(self):
if hasattr(os, 'kill'): try: os.kill(self.rpcpid, SIGTERM) except OSError: return else: try: os.waitpid(self.rpcpid, 0) except OSError: return
'Initiate the remote stack viewer from a separate thread. This method is called from the subprocess, and by returning from this method we allow the subprocess to unblock. After a bit the shell requests the subprocess to open the remote stack viewer which returns a static object looking at the last exception. It is qu...
def open_remote_stack_viewer(self):
self.tkconsole.text.after(300, self.remote_stack_viewer) return
'Like runsource() but assumes complete exec source'
def execsource(self, source):
filename = self.stuffsource(source) self.execfile(filename, source)
'Execute an existing file'
def execfile(self, filename, source=None):
if (source is None): source = open(filename, 'r').read() try: code = compile(source, filename, 'exec') except (OverflowError, SyntaxError): self.tkconsole.resetoutput() tkerr = self.tkconsole.stderr print >>tkerr, '*** Error in script or command!\n' ...
'Extend base class method: Stuff the source in the line cache first'
def runsource(self, source):
filename = self.stuffsource(source) self.more = 0 self.save_warnings_filters = warnings.filters[:] warnings.filterwarnings(action='error', category=SyntaxWarning) if isinstance(source, types.UnicodeType): from idlelib import IOBinding try: source = source.encode(IOBinding...
'Stuff source in the filename cache'
def stuffsource(self, source):
filename = ('<pyshell#%d>' % self.gid) self.gid = (self.gid + 1) lines = source.split('\n') linecache.cache[filename] = ((len(source) + 1), 0, lines, filename) return filename
'Prepend sys.path with file\'s directory if not already included'
def prepend_syspath(self, filename):
self.runcommand(('if 1:\n _filename = %r\n import sys as _sys\n from os.path import dirname as _dirname\n ...
'Extend base class method: Add Colorizing Color the offending position instead of printing it and pointing at it with a caret.'
def showsyntaxerror(self, filename=None):
text = self.tkconsole.text stuff = self.unpackerror() if stuff: (msg, lineno, offset, line) = stuff if (lineno == 1): pos = ('iomark + %d chars' % (offset - 1)) else: pos = ('iomark linestart + %d lines + %d chars' % ((lineno - 1)...
'Extend base class method to reset output properly'
def showtraceback(self):
self.tkconsole.resetoutput() self.checklinecache() InteractiveInterpreter.showtraceback(self) if self.tkconsole.getvar('<<toggle-jit-stack-viewer>>'): self.tkconsole.open_stack_viewer()
'Run the code without invoking the debugger'
def runcommand(self, code):
if self.tkconsole.executing: self.display_executing_dialog() return 0 if self.rpcclt: self.rpcclt.remotequeue('exec', 'runcode', (code,), {}) else: exec code in self.locals return 1
'Override base class method'
def runcode(self, code):
if self.tkconsole.executing: self.interp.restart_subprocess() self.checklinecache() if (self.save_warnings_filters is not None): warnings.filters[:] = self.save_warnings_filters self.save_warnings_filters = None debugger = self.debugger try: self.tkconsole.beginexecut...
'Override base class method'
def write(self, s):
self.tkconsole.stderr.write(s)
'Helper for ModifiedInterpreter'
def beginexecuting(self):
self.resetoutput() self.executing = 1
'Helper for ModifiedInterpreter'
def endexecuting(self):
self.executing = 0 self.canceled = 0 self.showprompt()
'Extend EditorWindow.close()'
def close(self):
if self.executing: response = tkMessageBox.askokcancel('Kill?', 'The program is still running!\n Do you want to kill it?', default='ok', parent=self.text) if (response is False): return 'cancel' if self.reading: self.top.quit() self.canceled ...
'Extend EditorWindow._close(), shut down debugger and execution server'
def _close(self):
self.close_debugger() if use_subprocess: self.interp.kill_subprocess() sys.stdout = self.save_stdout sys.stderr = self.save_stderr sys.stdin = self.save_stdin self.interp = None self.console = None self.flist.pyshell = None self.history = None EditorWindow._close(self)
'Override EditorWindow method: never remove the colorizer'
def ispythonsource(self, filename):
return True
'Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped.'
def handle_error(self, request, client_address):
global quitting try: raise except SystemExit: raise except EOFError: global exit_now exit_now = True thread.interrupt_main() except: erf = sys.__stderr__ print >>erf, ('\n' + ('-' * 40)) print >>erf, 'Unhandled server exception!' ...
'Override base method'
def handle(self):
executive = Executive(self) self.register('exec', executive) sys.stdin = self.console = self.get_remote_proxy('stdin') sys.stdout = self.get_remote_proxy('stdout') sys.stderr = self.get_remote_proxy('stderr') from idlelib import IOBinding sys.stdin.encoding = sys.stdout.encoding = sys.stderr...
'override SocketIO method - wait for MainThread to shut us down'
def exithook(self):
time.sleep(10)
'Override SocketIO method - terminate wait on callback and exit thread'
def EOFhook(self):
global quitting quitting = True thread.interrupt_main()
'interrupt awakened thread'
def decode_interrupthook(self):
global quitting quitting = True thread.interrupt_main()
'Unregister the Idb Adapter. Link objects and Idb then subject to GC'
def stop_the_debugger(self, idb_adap_oid):
self.rpchandler.unregister(idb_adap_oid)
'clear and reload the menu with a new set of options. valueList - list of new options value - initial value to set the optionmenu\'s menubutton to'
def SetMenu(self, valueList, value=None):
self['menu'].delete(0, 'end') for item in valueList: self['menu'].add_command(label=item, command=_setit(self.variable, item, self.command)) if value: self.variable.set(value)
'Highlight the single paren that matches'
def create_tag_default(self, indices):
self.text.tag_add('paren', indices[0]) self.text.tag_config('paren', self.HILITE_CONFIG)
'Highlight the entire expression'
def create_tag_expression(self, indices):
if (self.text.get(indices[1]) in (')', ']', '}')): rightindex = (indices[1] + '+1c') else: rightindex = indices[1] self.text.tag_add('paren', indices[0], rightindex) self.text.tag_config('paren', self.HILITE_CONFIG)
'Highlight will remain until user input turns it off or the insert has moved'
def set_timeout_none(self):
self.counter += 1 def callme(callme, self=self, c=self.counter, index=self.text.index('insert')): if (index != self.text.index('insert')): self.handle_restore_timer(c) else: self.editwin.text_frame.after(CHECK_DELAY, callme, callme) self.editwin.text_frame.after(CHECK...
'The last highlight created will be removed after .5 sec'
def set_timeout_last(self):
self.counter += 1 self.editwin.text_frame.after(self.FLASH_DELAY, (lambda self=self, c=self.counter: self.handle_restore_timer(c)))
'Search a text widget for the pattern. If prog is given, it should be the precompiled pattern. Return a tuple (lineno, matchobj); None if not found. This obeys the wrap and direction (back) settings. The search starts at the selection (if there is one) or at the insert mark (otherwise). If the search is forward, it st...
def search_text(self, text, prog=None, ok=0):
if (not prog): prog = self.getprog() if (not prog): return None wrap = self.wrapvar.get() (first, last) = get_selection(text) if self.isback(): if ok: start = last else: start = first (line, col) = get_line_col(start) re...
'Do not override! Called by TreeNode.'
def _IsExpandable(self):
if (self.expandable is None): self.expandable = self.IsExpandable() return self.expandable
'Return whether there are subitems.'
def IsExpandable(self):
return 1
'Do not override! Called by TreeNode.'
def _GetSubList(self):
if (not self.IsExpandable()): return [] sublist = self.GetSubList() if (not sublist): self.expandable = 0 return sublist
'action - string, the name of the virtual event these keys will be mapped to currentKeys - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking'
def __init__(self, parent, title, action, currentKeySequences):
Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol('WM_DELETE_WINDOW', self.Cancel) self.parent = parent self.action = action self.currentKeySequences = cur...
'Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn\'t matter if the keyboard has these keys, it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering.'
def SetModifiersForPlatform(self):
from idlelib import macosxSupport if macosxSupport.runningAsOSXApp(): self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'}
'Translate from keycap symbol to the Tkinter keysym'
def TranslateKey(self, key, modifiers):
translateDict = {'Space': 'space', '~': 'asciitilde', '!': 'exclam', '@': 'at', '#': 'numbersign', '%': 'percent', '^': 'asciicircum', '&': 'ampersand', '*': 'asterisk', '(': 'parenleft', ')': 'parenright', '_': 'underscore', '-': 'minus', '+': 'plus', '=': 'equal', '{': 'braceleft', '}': 'braceright', '[': 'bracke...
'Validity check on user\'s \'basic\' keybinding selection. Doesn\'t check the string produced by the advanced dialog because \'modifiers\' isn\'t set.'
def KeysOK(self):
keys = self.keyString.get() keys.strip() finalKey = self.listKeysFinal.get(ANCHOR) modifiers = self.GetModifiers() keySequence = keys.split() keysOK = False title = 'Key Sequence Error' if (not keys): tkMessageBox.showerror(title=title, parent=self, message='No keys s...
'Check if needs to reposition the window, and if so - do it.'
def position_window(self):
curline = int(self.widget.index('insert').split('.')[0]) if (curline == self.lastline): return self.lastline = curline self.widget.see('insert') if (curline == self.parenline): box = self.widget.bbox(('%d.%d' % (self.parenline, self.parencol))) else: box = self.widget.bbo...
'Show the calltip, bind events which will close it and reposition it.'
def showtip(self, text, parenleft, parenright):
if (len(text) >= 79): textlines = text.splitlines() for (i, line) in enumerate(textlines): if (len(line) > 79): textlines[i] = (line[:75] + ' ...') text = '\n'.join(textlines) self.text = text if (self.tipwindow or (not self.text)): return s...
'Happens when the user really wants to open a completion list, even if a function call is needed.'
def force_open_completions_event(self, event):
self.open_completions(True, False, True)