desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'message - string, informational message to display used_names - string collection, names already in use for validity check _htest - bool, change box location when running htest'
def __init__(self, parent, title, message, used_names, _htest=False):
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.used_names = used_names...
'After stripping entered name, check that it is a sensible ConfigParser file section name. Return it if it is, \'\' if not.'
def name_ok(self):
name = self.name.get().strip() if (not name): tkMessageBox.showerror(title='Name Error', message='No name specified.', parent=self) elif (len(name) > 30): tkMessageBox.showerror(title='Name Error', message=('Name too long. It should be no more than ' + ...
'To initialize, 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. The index 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(('Index %s precedes the analyzed statement' % index)) self.indexinrawtext = indexinrawtext self.indexbracket = 0 while ((self.indexbracket < (len(self.b...
'Is the index given to the HyperParser 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 in normal code?'
def is_in_code(self):
return ((not self.isopener[self.indexbracket]) or (self.rawtext[self.bracketing[self.indexbracket][0]] not in ('#', '"', "'")))
'Return bracket indexes or None. 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 com...
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 ...
'Given a string and pos, return the number of chars in the identifier which ends at pos, or 0 if there is no such one. This ignores non-identifier eywords are not identifiers.'
@classmethod def _eat_identifier(cls, str, limit, pos):
is_ascii_id_char = _IS_ASCII_ID_CHAR i = pos while ((i > limit) and ((ord(str[(i - 1)]) < 128) and is_ascii_id_char[ord(str[(i - 1)])])): i -= 1 if ((i > limit) and (ord(str[(i - 1)]) >= 128)): while (((i - 4) >= limit) and ('a' + str[(i - 4):pos]).isidentifier()): i -= 4 ...
'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 calledif index is inside a code.') rawtext = self.rawtext bracketing = self.bracketing brck_index = self.indexbracket brck_limit = bracketing[brck_index][0] pos = self.indexinrawtext ...
'_htest - bool, change box location when running htest'
def __init__(self, parent, title, _htest=False):
Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.geometry(('+%d+%d' % ((parent.winfo_rootx() + 30), (parent.winfo_rooty() + (30 if (not _htest) else 100))))) self.bg = '#707070' self.fg = '#ffffff' self.CreateWidgets() self.resizable(height=FALSE, width=FALSE) self.titl...
'Formats paragraph to a max width specified in idleConf. If text is selected, format_paragraph_event will start breaking lines at the max width, starting from the beginning selection. If no text is selected, format_paragraph_event uses the current cursor location to determine the paragraph (lines of text surrounded by ...
def format_paragraph_event(self, event, limit=None):
if (limit == None): limit = idleConf.GetOption('main', 'FormatParagraph', 'paragraph', type='int') text = self.editwin.text (first, last) = self.editwin.get_selection_indices() if (first and last): data = text.get(first, last) comment_header = get_comment_header(data) else: ...
'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)
'_htest - bool, change box location when running htest'
def __init__(self, flist, _htest=False):
self._htest = _htest self.init(flist)
'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)))
'Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs.'
def __init__(self, root):
self.root = root self.patvar = StringVar(root, '') self.revar = BooleanVar(root, False) self.casevar = BooleanVar(root, False) self.wordvar = BooleanVar(root, False) self.wrapvar = BooleanVar(root, True) self.backvar = BooleanVar(root, False)
'Set pattern after escaping if re.'
def setcookedpat(self, pat):
if self.isre(): pat = re.escape(pat) self.setpat(pat)
'Return compiled cooked search pattern.'
def getprog(self):
pat = self.getpat() if (not pat): self.report_error(pat, 'Empty regular expression') return None pat = self.getcookedpat() flags = 0 if (not self.iscase()): flags = (flags | re.IGNORECASE) try: prog = re.compile(pat, flags) except re.error as what: ...
'Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameteris a bit complicated as it has two effects. If there is a selection, the sear...
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 _htest - bool, change box location when running htest'
def __init__(self, parent, title, action, currentKeySequences, _htest=False):
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):
if (sys.platform == 'darwin'): 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):
self.text = text if (self.tipwindow or (not self.text)): return self.widget.mark_set(MARK_RIGHT, parenright) (self.parenline, self.parencol) = map(int, self.widget.index(parenleft).split('.')) self.tipwindow = tw = Toplevel(self.widget) self.position_window() tw.wm_overrideredirect(1...
'Helper function for expanding a regular expression in the replace field, if needed.'
def _replace_expand(self, m, repl):
if self.engine.isre(): try: new = m.expand(repl) except re.error: self.engine.report_error(repl, 'Invalid Replace Expression') new = None else: new = repl return new
'Initialize root, engine, and top attributes. top (level widget): set in create_widgets() called from open(). text (Text searched): set in open(), only used in subclasses(). ent (ry): created in make_entry() called from create_entry(). row (of grid): 0 in create_widgets(), +1 in make_entry/frame(). default_command: set...
def __init__(self, root, engine):
self.root = root self.engine = engine self.top = None
'Make dialog visible on top of others and ready to use.'
def open(self, text, searchphrase=None):
self.text = text if (not self.top): self.create_widgets() else: self.top.deiconify() self.top.tkraise() if searchphrase: self.ent.delete(0, 'end') self.ent.insert('end', searchphrase) self.ent.focus_set() self.ent.selection_range(0, 'end') self.ent.icu...
'Put dialog away for later use.'
def close(self, event=None):
if self.top: self.top.grab_release() self.top.withdraw()
'Create basic 3 row x 3 col search (find) dialog. Other dialogs override subsidiary create_x methods as needed. Replace and Find-in-Files add another entry row.'
def create_widgets(self):
top = Toplevel(self.root) top.bind('<Return>', self.default_command) top.bind('<Escape>', self.close) top.protocol('WM_DELETE_WINDOW', self.close) top.wm_title(self.title) top.wm_iconname(self.icon) self.top = top self.row = 0 self.top.grid_columnconfigure(0, pad=2, weight=0) sel...
'Return (entry, label), . entry - gridded labeled Entry for text entry. label - Label widget, returned for testing.'
def make_entry(self, label_text, var):
label = Label(self.top, text=label_text) label.grid(row=self.row, column=0, sticky='nw') entry = Entry(self.top, textvariable=var, exportselection=0) entry.grid(row=self.row, column=1, sticky='nwe') self.row = (self.row + 1) return (entry, label)
'Create one or more entry lines with make_entry.'
def create_entries(self):
self.ent = self.make_entry('Find:', self.engine.patvar)[0]
'Return (frame, label). frame - gridded labeled Frame for option or other buttons. label - Label widget, returned for testing.'
def make_frame(self, labeltext=None):
if labeltext: label = Label(self.top, text=labeltext) label.grid(row=self.row, column=0, sticky='nw') else: label = '' frame = Frame(self.top) frame.grid(row=self.row, column=1, columnspan=1, sticky='nwe') self.row = (self.row + 1) return (frame, label)
'Return (filled frame, options) for testing. Options is a list of SearchEngine booleanvar, label pairs. A gridded frame from make_frame is filled with a Checkbutton for each pair, bound to the var, with the corresponding label.'
def create_option_buttons(self):
frame = self.make_frame('Options')[0] engine = self.engine options = [(engine.revar, 'Regular expression'), (engine.casevar, 'Match case'), (engine.wordvar, 'Whole word')] if self.needwrapbutton: options.append((engine.wrapvar, 'Wrap around')) for (var, label) in options: ...
'Return (frame, others) for testing. Others is a list of value, label pairs. A gridded frame from make_frame is filled with radio buttons.'
def create_other_buttons(self):
frame = self.make_frame('Direction')[0] var = self.engine.backvar others = [(1, 'Up'), (0, 'Down')] for (val, label) in others: btn = Radiobutton(frame, anchor='w', variable=var, value=val, text=label) btn.pack(side='left', fill='both') if (var.get() == val): btn.sele...
'Return command button gridded in command frame.'
def make_button(self, label, command, isdef=0):
b = Button(self.buttonframe, text=label, command=command, default=((isdef and 'active') or 'normal')) (cols, rows) = self.buttonframe.grid_size() b.grid(pady=1, row=rows, column=0, sticky='ew') self.buttonframe.grid(rowspan=(rows + 1)) return b
'Place buttons in vertical command frame gridded on right.'
def create_command_buttons(self):
f = self.buttonframe = Frame(self.top) f.grid(row=0, column=2, padx=2, pady=2, ipadx=2, ipady=2) b = self.make_button('close', self.close) b.lower()
'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)
'Happens when it would be nice to open a completion list, but not really necessary, for example after an dot, so function calls won\'t be made.'
def try_open_completions_event(self, event):
lastchar = self.text.get('insert-1c') if (lastchar == '.'): self._open_completions_later(False, False, False, COMPLETE_ATTRIBUTES) elif (lastchar in SEPS): self._open_completions_later(False, False, False, COMPLETE_FILES)
'Happens when the user wants to complete his word, and if necessary, open a completion list after that (if there is more than one completion)'
def autocomplete_event(self, event):
if (hasattr(event, 'mc_state') and event.mc_state): return if (self.autocompletewindow and self.autocompletewindow.is_active()): self.autocompletewindow.complete() return 'break' else: opened = self.open_completions(False, True, True) if opened: return 'br...
'Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). if complete is True, then if there\'s nothing to complete and no start of completion, won\'t open completions and return False. If mode is given, will open a completion list only in this mode.'
def open_completions(self, evalfuncs, complete, userWantsWin, mode=None):
if (self._delayed_completion_id is not None): self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = None hp = HyperParser(self.editwin, 'insert') curline = self.text.get('insert linestart', 'insert') i = j = len(curline) if (hp.is_in_string() and ((not ...
'Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run....
def fetch_completions(self, what, mode):
try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall('exec', 'get_the_completion_list', (what, mode), {}) else: if (mode == COMPLETE_ATTRIBUTES): if (what == ''): namespace = __main__....
'Lookup name in a namespace spanning sys.modules and __main.dict__'
def get_entity(self, name):
namespace = sys.modules.copy() namespace.update(__main__.__dict__) return eval(name, namespace)
'Initialize data attributes and bind event methods. .text - Idle wrapper of tk Text widget, with .bell(). .history - source statements, possibly with multiple lines. .prefix - source already entered at prompt; filters history list. .pointer - index into history. .cyclic - wrap around history list (or not).'
def __init__(self, text):
self.text = text self.history = [] self.prefix = None self.pointer = None self.cyclic = idleConf.GetOption('main', 'History', 'cyclic', 1, 'bool') text.bind('<<history-previous>>', self.history_prev) text.bind('<<history-next>>', self.history_next)
'Fetch later statement; start with ealiest if cyclic.'
def history_next(self, event):
self.fetch(reverse=False) return 'break'
'Fetch earlier statement; start with most recent.'
def history_prev(self, event):
self.fetch(reverse=True) return 'break'
'Fetch statememt and replace current line in text widget. Set prefix and pointer as needed for successive fetches. Reset them to None, None when returning to the start line. Sound bell when return to start line or cannot leave a line because cyclic is False.'
def fetch(self, reverse):
nhist = len(self.history) pointer = self.pointer prefix = self.prefix if ((pointer is not None) and (prefix is not None)): if (self.text.compare('insert', '!=', 'end-1c') or (self.text.get('iomark', 'end-1c') != self.history[pointer])): pointer = prefix = None self.text.m...
'Store Shell input statement into history list.'
def store(self, source):
source = source.strip() if (len(source) > 2): try: self.history.remove(source) except ValueError: pass self.history.append(source) self.pointer = None self.prefix = None
'Return a parser object with index at \'index\''
def get_parser(self, index):
return HyperParser(self.editwin, index)
'test corner cases in the init method'
def test_init(self):
with self.assertRaises(ValueError) as ve: self.text.tag_add('console', '1.0', '1.end') p = self.get_parser('1.5') self.assertIn('precedes', str(ve.exception)) self.editwin.context_use_ps1 = False p = self.get_parser('end') self.assertEqual(p.rawtext, self.text.get('1.0', 'end')) ...
'Test ParenMatch with \'expression\' style.'
def test_paren_expression(self):
text = self.text pm = ParenMatch(self.editwin) pm.set_style('expression') text.insert('insert', 'def foobar(a, b') pm.flash_paren_event('event') self.assertIn('<<parenmatch-check-restore>>', text.event_info()) self.assertTupleEqual(text.tag_prevrange('paren', 'end'), ('1.10', '1.15')) ...
'Test ParenMatch with \'default\' style.'
def test_paren_default(self):
text = self.text pm = ParenMatch(self.editwin) pm.set_style('default') text.insert('insert', 'def foobar(a, b') pm.flash_paren_event('event') self.assertIn('<<parenmatch-check-restore>>', text.event_info()) self.assertTupleEqual(text.tag_prevrange('paren', 'end'), ('1.10', '1.11')) ...
'Test corner cases in flash_paren_event and paren_closed_event. These cases force conditional expression and alternate paths.'
def test_paren_corner(self):
text = self.text pm = ParenMatch(self.editwin) text.insert('insert', '# this is a commen)') self.assertIsNone(pm.paren_closed_event('event')) text.insert('insert', '\ndef') self.assertIsNone(pm.flash_paren_event('event')) self.assertIsNone(pm.paren_closed_event('event')) text...
'Show the given text in a scrollable window with a \'close\' button If modal option set to False, user can interact with other windows, otherwise they will be unable to interact with other windows until the textview window is closed. _htest - bool; change box location when running htest.'
def __init__(self, parent, title, text, modal=True, _htest=False):
Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.geometry(('=%dx%d+%d+%d' % (625, 500, (parent.winfo_rootx() + 10), (parent.winfo_rooty() + (10 if (not _htest) else 100))))) self.bg = '#ffffff' self.fg = '#000000' self.CreateWidgets() self.title(title) self.protocol('WM...
'Get the line indent value, text, and any block start keyword If the line does not start a block, the keyword value is False. The indentation of empty lines (or comment lines) is INFINITY.'
def get_line_info(self, linenum):
text = self.text.get(('%d.0' % linenum), ('%d.end' % linenum)) (spaces, firstword) = getspacesfirstword(text) opener = ((firstword in BLOCKOPENERS) and firstword) if ((len(text) == len(spaces)) or (text[len(spaces)] == '#')): indent = INFINITY else: indent = len(spaces) return (i...
'Get context lines, starting at new_topvisible and working backwards. Stop when stopline or stopindent is reached. Return a tuple of context data and the indent level at the top of the region inspected.'
def get_context(self, new_topvisible, stopline=1, stopindent=0):
assert (stopline > 0) lines = [] lastindent = INFINITY for linenum in range(new_topvisible, (stopline - 1), (-1)): (indent, text, opener) = self.get_line_info(linenum) if (indent < lastindent): lastindent = indent if (opener in ('else', 'elif')): l...
'Update context information and lines visible in the context pane.'
def update_code_context(self):
new_topvisible = int(self.text.index('@0,0').split('.')[0]) if (self.topvisible == new_topvisible): return if (self.topvisible < new_topvisible): (lines, lastindent) = self.get_context(new_topvisible, self.topvisible) while (self.info[(-1)][1] >= lastindent): del self.inf...
'Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such one.'
def _binary_search(self, s):
i = 0 j = len(self.completions) while (j > i): m = ((i + j) // 2) if (self.completions[m] >= s): j = m else: i = (m + 1) return min(i, (len(self.completions) - 1))
'Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s.'
def _complete_string(self, s):
first = self._binary_search(s) if (self.completions[first][:len(s)] != s): return s i = (first + 1) j = len(self.completions) while (j > i): m = ((i + j) // 2) if (self.completions[m][:len(s)] != s): j = m else: i = (m + 1) last = (i - 1) ...
'Should be called when the selection of the Listbox has changed. Updates the Listbox display and calls _change_start.'
def _selection_changed(self):
cursel = int(self.listbox.curselection()[0]) self.listbox.see(cursel) lts = self.lasttypedstart selstart = self.completions[cursel] if (self._binary_search(lts) == cursel): newstart = lts else: min_len = min(len(lts), len(selstart)) i = 0 while ((i < min_len) and ...
'Show the autocomplete list, bind events. If complete is True, complete the text, and if there is exactly one matching completion, don\'t open a list.'
def show_window(self, comp_lists, index, complete, mode, userWantsWin):
(self.completions, self.morecompletions) = comp_lists self.mode = mode self.startindex = self.widget.index(index) self.start = self.widget.get(self.startindex, 'insert') if complete: completed = self._complete_string(self.start) start = self.start self._change_start(completed...
'Display the help dialog. parent - parent widget for the help window near - a Toplevel widget (e.g. EditorWindow or PyShell) to use as a reference for placing the help window'
def display(self, parent, near=None):
if (self.dlg is None): self.show_dialog(parent) if near: self.nearwindow(near)
'convert filename to unicode in order to display it in Tk'
def _filename_to_unicode(self, filename):
if (isinstance(filename, str) or (not filename)): return filename else: try: return filename.decode(self.filesystemencoding) except UnicodeDecodeError: try: return filename.decode(self.encoding) except UnicodeDecodeError: ...
'Cursor move begins at start or end of selection When a left/right cursor key is pressed create and return to Tkinter a function which causes a cursor move from the associated edge of the selection.'
def move_at_edge_if_selection(self, edge_index):
self_text_index = self.text.index self_text_mark_set = self.text.mark_set edges_table = ('sel.first+1c', 'sel.last-1c') def move_at_edge(event): if ((event.state & 5) == 0): try: self_text_index('sel.first') self_text_mark_set('insert', edges_table[edg...
'Update the colour theme'
def ResetColorizer(self):
self._rmcolorizer() self._addcolorizer() theme = idleConf.GetOption('main', 'Theme', 'name') normal_colors = idleConf.GetHighlight(theme, 'normal') cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg') select_colors = idleConf.GetHighlight(theme, 'hilite') self.text.config(foregro...
'Update the text widgets\' font if it is changed'
def ResetFont(self):
fontWeight = 'normal' if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'): fontWeight = 'bold' self.text.config(font=(idleConf.GetOption('main', 'EditorWindow', 'font'), idleConf.GetOption('main', 'EditorWindow', 'font-size', type='int'), fontWeight))
'Remove the keybindings before they are changed.'
def RemoveKeybindings(self):
self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet() for (event, keylist) in keydefs.items(): self.text.event_delete(event, *keylist) for extensionName in self.get_standard_extension_names(): xkeydefs = idleConf.GetExtensionBindings(extensionName) if xkeydefs: ...
'Update the keybindings after they are changed'
def ApplyKeybindings(self):
self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet() self.apply_bindings() for extensionName in self.get_standard_extension_names(): xkeydefs = idleConf.GetExtensionBindings(extensionName) if xkeydefs: self.apply_bindings(xkeydefs) menuEventDict = {} for ...
'Update the indentwidth if changed and not using tabs in this window'
def set_notabs_indentwidth(self):
if (not self.usetabs): self.indentwidth = idleConf.GetOption('main', 'Indent', 'num-spaces', type='int')
'Update the additional help entries on the Help menu'
def reset_help_menu_entries(self):
help_list = idleConf.GetAllExtraHelpSourcesList() helpmenu = self.menudict['help'] helpmenu_length = helpmenu.index(END) if (helpmenu_length > self.base_helpmenu_length): helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length) if help_list: helpmenu.add_separator() ...
'Create a callback with the helpfile value frozen at definition time'
def __extra_help_callback(self, helpfile):
def display_extra_help(helpfile=helpfile): if (not helpfile.startswith(('www', 'http'))): helpfile = os.path.normpath(helpfile) if (sys.platform[:3] == 'win'): try: os.startfile(helpfile) except OSError as why: tkMessageBox.showerro...
'Load and update the recent files list and menus'
def update_recent_files_list(self, new_file=None):
rf_list = [] if os.path.exists(self.recent_files_path): with open(self.recent_files_path, 'r', encoding='utf_8', errors='replace') as rf_list_file: rf_list = rf_list_file.readlines() if new_file: new_file = (os.path.abspath(new_file) + '\n') if (new_file in rf_list): ...
'Return (width, height, x, y)'
def get_geometry(self):
geom = self.top.wm_geometry() m = re.match('(\\d+)x(\\d+)\\+(-?\\d+)\\+(-?\\d+)', geom) return list(map(int, m.groups()))
'Add appropriate entries to the menus and submenus Menus that are absent or None in self.menudict are ignored.'
def fill_menus(self, menudefs=None, keydefs=None):
if (menudefs is None): menudefs = self.Bindings.menudefs if (keydefs is None): keydefs = self.Bindings.default_keydefs menudict = self.menudict text = self.text for (mname, entrylist) in menudefs: menu = menudict.get(mname) if (not menu): continue ...
'_htest - bool, change box when location running htest.'
def __init__(self, flist, name, path, _htest=False):
self.name = name self.file = os.path.join(path[0], (self.name + '.py')) self._htest = _htest self.init(flist)
'Return a (user, account, password) tuple for given host.'
def authenticators(self, host):
if (host in self.hosts): return self.hosts[host] elif ('default' in self.hosts): return self.hosts['default'] else: return None
'Dump the class data in the format of a .netrc file.'
def __repr__(self):
rep = '' for host in self.hosts.keys(): attrs = self.hosts[host] rep = (((((rep + 'machine ') + host) + '\n DCTB login ') + repr(attrs[0])) + '\n') if attrs[1]: rep = ((rep + 'account ') + repr(attrs[1])) rep = (((rep + ' DCTB password ') + repr(attrs[2]))...
'Create a decimal point instance. >>> Decimal(\'3.14\') # string input Decimal(\'3.14\') >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) Decimal(\'3.14\') >>> Decimal(314) # int Decimal(\'314\') >>> Decimal(Decimal(314)) # another decimal instance Decimal(\'314...
def __new__(cls, value='0', context=None):
self = object.__new__(cls) if isinstance(value, str): m = _parser(value.strip()) if (m is None): if (context is None): context = getcontext() return context._raise_error(ConversionSyntax, ('Invalid literal for Decimal: %r' % value)) if ...
'Converts a float to a decimal number, exactly. Note that Decimal.from_float(0.1) is not the same as Decimal(\'0.1\'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. The exact equivalent of the value in decimal is 0...
@classmethod def from_float(cls, f):
if isinstance(f, int): return cls(f) if (not isinstance(f, float)): raise TypeError('argument must be int or float.') if (_math.isinf(f) or _math.isnan(f)): return cls(repr(f)) if (_math.copysign(1.0, f) == 1.0): sign = 0 else: sign = 1 (n, ...
'Returns whether the number is not actually one. 0 if a number 1 if NaN 2 if sNaN'
def _isnan(self):
if self._is_special: exp = self._exp if (exp == 'n'): return 1 elif (exp == 'N'): return 2 return 0
'Returns whether the number is infinite 0 if finite or not a number 1 if +INF -1 if -INF'
def _isinfinity(self):
if (self._exp == 'F'): if self._sign: return (-1) return 1 return 0
'Returns whether the number is not actually one. if self, other are sNaN, signal if self, other are NaN return nan return 0 Done before operations.'
def _check_nans(self, other=None, context=None):
self_is_nan = self._isnan() if (other is None): other_is_nan = False else: other_is_nan = other._isnan() if (self_is_nan or other_is_nan): if (context is None): context = getcontext() if (self_is_nan == 2): return context._raise_error(InvalidOperat...
'Version of _check_nans used for the signaling comparisons compare_signal, __le__, __lt__, __ge__, __gt__. Signal InvalidOperation if either self or other is a (quiet or signaling) NaN. Signaling NaNs take precedence over quiet NaNs. Return 0 if neither operand is a NaN.'
def _compare_check_nans(self, other, context):
if (context is None): context = getcontext() if (self._is_special or other._is_special): if self.is_snan(): return context._raise_error(InvalidOperation, 'comparison involving sNaN', self) elif other.is_snan(): return context._raise_error(InvalidOperation, '...
'Return True if self is nonzero; otherwise return False. NaNs and infinities are considered nonzero.'
def __bool__(self):
return (self._is_special or (self._int != '0'))
'Compare the two non-NaN decimal instances self and other. Returns -1 if self < other, 0 if self == other and 1 if self > other. This routine is for internal use only.'
def _cmp(self, other):
if (self._is_special or other._is_special): self_inf = self._isinfinity() other_inf = other._isinfinity() if (self_inf == other_inf): return 0 elif (self_inf < other_inf): return (-1) else: return 1 if (not self): if (not other)...
'Compares one to another. -1 => a < b 0 => a = b 1 => a > b NaN => one is NaN Like __cmp__, but returns Decimal instances.'
def compare(self, other, context=None):
other = _convert_other(other, raiseit=True) if (self._is_special or (other and other._is_special)): ans = self._check_nans(other, context) if ans: return ans return Decimal(self._cmp(other))
'x.__hash__() <==> hash(x)'
def __hash__(self):
if self._is_special: if self.is_snan(): raise TypeError('Cannot hash a signaling NaN value.') elif self.is_nan(): return _PyHASH_NAN elif self._sign: return (- _PyHASH_INF) else: return _PyHASH_INF if (self._exp >= 0)...
'Represents the number as a triple tuple. To show the internals exactly as they are.'
def as_tuple(self):
return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
'Represents the number as an instance of Decimal.'
def __repr__(self):
return ("Decimal('%s')" % str(self))
'Return string representation of the number in scientific notation. Captures all of the information in the underlying representation.'
def __str__(self, eng=False, context=None):
sign = ['', '-'][self._sign] if self._is_special: if (self._exp == 'F'): return (sign + 'Infinity') elif (self._exp == 'n'): return ((sign + 'NaN') + self._int) else: return ((sign + 'sNaN') + self._int) leftdigits = (self._exp + len(self._int)) ...
'Convert to engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. Same rules for when in exponential and when as a value as in __str__.'
def to_eng_string(self, context=None):
return self.__str__(eng=True, context=context)
'Returns a copy with the sign switched. Rounds, if it has reason.'
def __neg__(self, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans if (context is None): context = getcontext() if ((not self) and (context.rounding != ROUND_FLOOR)): ans = self.copy_abs() else: ans = self.copy_negate() return ans._fix...
'Returns a copy, unless it is a sNaN. Rounds the number (if more then precision digits)'
def __pos__(self, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans if (context is None): context = getcontext() if ((not self) and (context.rounding != ROUND_FLOOR)): ans = self.copy_abs() else: ans = Decimal(self) return ans._fix(cont...
'Returns the absolute value of self. If the keyword argument \'round\' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs().'
def __abs__(self, round=True, context=None):
if (not round): return self.copy_abs() if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans
'Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors.'
def __add__(self, other, context=None):
other = _convert_other(other) if (other is NotImplemented): return other if (context is None): context = getcontext() if (self._is_special or other._is_special): ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): ...