desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Constructor arguments:
select_command -- A callable which will be called when a tab is
selected. It is called with the name of the selected tab as an
argument.
tabs -- A list of strings, the names of the tabs. Should be specified in
the desired tab order. The first tab will be the default and first
active tab. If tabs... | def __init__(self, page_set, select_command, tabs=None, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw):
| Frame.__init__(self, page_set, **kw)
self.select_command = select_command
self.n_rows = n_rows
self.max_tabs_per_row = max_tabs_per_row
self.expand_tabs = expand_tabs
self.page_set = page_set
self._tabs = {}
self._tab2row = {}
if tabs:
self._tab_names = list(tabs)
else:
... |
'Add a new tab with the name given in tab_name.'
| def add_tab(self, tab_name):
| if (not tab_name):
raise InvalidNameError(("Invalid Tab name: '%s'" % tab_name))
if (tab_name in self._tab_names):
raise AlreadyExistsError(("Tab named '%s' already exists" % tab_name))
self._tab_names.append(tab_name)
self._arrange_tabs()
|
'Remove the tab named <tab_name>'
| def remove_tab(self, tab_name):
| if (not (tab_name in self._tab_names)):
raise KeyError(("No such Tab: '%s" % tab_name))
self._tab_names.remove(tab_name)
self._arrange_tabs()
|
'Show the tab named <tab_name> as the selected one'
| def set_selected_tab(self, tab_name):
| if (tab_name == self._selected_tab):
return
if ((tab_name is not None) and (tab_name not in self._tabs)):
raise KeyError(("No such Tab: '%s" % tab_name))
if (self._selected_tab is not None):
self._tabs[self._selected_tab].set_normal()
self._selected_tab = None
if (ta... |
'Arrange the tabs in rows, in the order in which they were added.
If n_rows >= 1, this will be the number of rows used. Otherwise the
number of rows will be calculated according to the number of tabs and
max_tabs_per_row. In this case, the number of rows may change when
adding/removing tabs.'
| def _arrange_tabs(self):
| while self._tabs:
self._tabs.popitem()[1].destroy()
self._reset_tab_rows()
if (not self._tab_names):
return
if ((self.n_rows is not None) and (self.n_rows > 0)):
n_rows = self.n_rows
else:
n_rows = (((len(self._tab_names) - 1) // self.max_tabs_per_row) + 1)
expand... |
'Constructor arguments:
name -- The tab\'s name, which will appear in its button.
select_command -- The command to be called upon selection of the
tab. It is called with the tab\'s name as an argument.'
| def __init__(self, name, select_command, tab_row, tab_set):
| Frame.__init__(self, tab_row, borderwidth=self.bw, relief=RAISED)
self.name = name
self.select_command = select_command
self.tab_set = tab_set
self.is_last_in_row = False
self.button = Radiobutton(self, text=name, command=self._select_event, padx=5, pady=1, takefocus=FALSE, indicatoron=FALSE, hi... |
'Event handler for tab selection.
With TabbedPageSet, this calls TabbedPageSet.change_page, so that
selecting a tab changes the page.
Note that this does -not- call set_selected -- it will be called by
TabSet.set_selected_tab, which should be called when whatever the
tabs are related to changes.'
| def _select_event(self, *args):
| self.select_command(self.name)
return
|
'Assume selected look'
| def set_selected(self):
| self._place_masks(selected=True)
|
'Assume normal look'
| def set_normal(self):
| self._place_masks(selected=False)
|
'Constructor arguments:
page_names -- A list of strings, each will be the dictionary key to a
page\'s widget, and the name displayed on the page\'s tab. Should be
specified in the desired page order. The first page will be the default
and first active page. If page_names is None or empty, the
TabbedPageSet will be init... | def __init__(self, parent, page_names=None, page_class=PageLift, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw):
| Frame.__init__(self, parent, **kw)
self.page_class = page_class
self.pages = {}
self._pages_order = []
self._current_page = None
self._default_page = None
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.pages_frame = Frame(self)
self.pages_frame.grid(row=1, ... |
'Add a new page with the name given in page_name.'
| def add_page(self, page_name):
| if (not page_name):
raise InvalidNameError(("Invalid TabPage name: '%s'" % page_name))
if (page_name in self.pages):
raise AlreadyExistsError(("TabPage named '%s' already exists" % page_name))
self.pages[page_name] = self.page_class(self.pages_frame)
self._pages_orde... |
'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... |
'Initialize attributes and setup redirection.
_operations: dict mapping operation name to new function.
widget: the widget whose tcl command is to be intercepted.
tk: widget.tk, a convenience attribute, probably not needed.
orig: new name of the original tcl command.
Since renaming to orig fails with TclError when orig... | def __init__(self, widget):
| self._operations = {}
self.widget = widget
self.tk = tk = widget.tk
w = widget._w
self.orig = (w + '_orig')
tk.call('rename', w, self.orig)
tk.createcommand(w, self.dispatch)
|
'Unregister operations and revert redirection created by .__init__.'
| def close(self):
| for operation in list(self._operations):
self.unregister(operation)
widget = self.widget
tk = widget.tk
w = widget._w
tk.deletecommand(w)
tk.call('rename', self.orig, w)
del self.widget, self.tk
|
'Return OriginalCommand(operation) after registering function.
Registration adds an operation: function pair to ._operations.
It also adds an widget function attribute that masks the tkinter
class instance method. Method masking operates independently
from command dispatch.
If a second function is registered for the s... | def register(self, operation, function):
| self._operations[operation] = function
setattr(self.widget, operation, function)
return OriginalCommand(self, operation)
|
'Return the function for the operation, or None.
Deleting the instance attribute unmasks the class attribute.'
| def unregister(self, operation):
| if (operation in self._operations):
function = self._operations[operation]
del self._operations[operation]
try:
delattr(self.widget, operation)
except AttributeError:
pass
return function
else:
return None
|
'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 ''
|
'Create .tk_call and .orig_and_operation for .__call__ method.
.redir and .operation store the input args for __repr__.
.tk and .orig copy attributes of .redir (probably not needed).'
| def __init__(self, redir, operation):
| self.redir = redir
self.operation = operation
self.tk = redir.tk
self.orig = redir.orig
self.tk_call = redir.tk.call
self.orig_and_operation = (redir.orig, operation)
|
'The user selected the menu entry or hotkey, open the tip.'
| 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)
|
'Return the argument list and docstring of a function or class.
If there is a Python subprocess, get the calltip there. Otherwise,
either this fetch_tip() is running in the subprocess or it was
called in an IDLE running without the subprocess.
The subprocess environment is that of the most recently run script. If
two... | def fetch_tip(self, expression):
| try:
rpcclt = self.editwin.flist.pyshell.interp.rpcclt
except AttributeError:
rpcclt = None
if rpcclt:
return rpcclt.remotecall('exec', 'get_the_calltip', (expression,), {})
else:
return get_argspec(get_entity(expression))
|
'_htest - bool, change box location when running htest
_utest - bool, don\'t wait_window when running unittest'
| def __init__(self, parent, title, _htest=False, _utest=False):
| Toplevel.__init__(self, parent)
self.parent = parent
if _htest:
parent.instance_dict = {}
self.wm_withdraw()
self.configure(borderwidth=5)
self.title('IDLE Preferences')
self.geometry(('+%d+%d' % ((parent.winfo_rootx() + 20), (parent.winfo_rooty() + (30 if (not _htest) else 150)))... |
'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), ';'.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:
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:
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:
cfgTypeHasChanges = False
for section in self.changedItems[configType]:
if (section == 'HelpFiles'):
idleConf.userCfg['main'].remove_section('HelpFiles')
cfgTypeHasChanges = True
... |
'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.
_htest - bool, change box location when running htest'
| def __init__(self, parent, title, menuItem='', filePath='', _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.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
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:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.