def __init__(self, text): '''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). ''' 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)
def format_paragraph_event(self, event): maxformatwidth = int( idleConf.GetOption('main', 'FormatParagraph', 'paragraph')) text = self.editwin.text first, last = self.editwin.get_selection_indices() if first and last: data = text.get(first, last) comment_header = '' else: first, last, comment_header, data = \ find_paragraph(text, text.index("insert")) if comment_header: # Reformat the comment lines - convert to text sans header. lines = data.split("\n") lines = map(lambda st, l=len(comment_header): st[l:], lines) data = "\n".join(lines) # Reformat to maxformatwidth chars or a 20 char width, whichever is greater. format_width = max(maxformatwidth - len(comment_header), 20) newdata = reformat_paragraph(data, format_width) # re-split and re-insert the comment header. newdata = newdata.split("\n") # If the block ends in a \n, we dont want the comment # prefix inserted after it. (Im not sure it makes sense to # reformat a comment block that isnt made of complete # lines, but whatever!) Can't think of a clean solution, # so we hack away block_suffix = "" if not newdata[-1]: block_suffix = "\n" newdata = newdata[:-1] builder = lambda item, prefix=comment_header: prefix + item newdata = '\n'.join(map(builder, newdata)) + block_suffix else: # Just a normal text format newdata = reformat_paragraph(data, maxformatwidth) text.tag_remove("sel", "1.0", "end") if newdata != data: text.mark_set("insert", first) text.undo_block_start() text.delete(first, last) text.insert(first, newdata) text.undo_block_stop() else: text.mark_set("insert", last) text.see("insert") return "break"
def LoadTagDefs(self): theme = idleConf.GetOption('main','Theme','name') self.tagdefs = { "COMMENT": idleConf.GetHighlight(theme, "comment"), "KEYWORD": idleConf.GetHighlight(theme, "keyword"), "BUILTIN": idleConf.GetHighlight(theme, "builtin"), "STRING": idleConf.GetHighlight(theme, "string"), "DEFINITION": idleConf.GetHighlight(theme, "definition"), "SYNC": {'background':None,'foreground':None}, "TODO": {'background':None,'foreground':None}, "BREAK": idleConf.GetHighlight(theme, "break"), "ERROR": idleConf.GetHighlight(theme, "error"), # The following is used by ReplaceDialog: "hit": idleConf.GetHighlight(theme, "hit"), } if DEBUG: print 'tagdefs',self.tagdefs
def LoadGeneralCfg(self): self.startupEdit.set(idleConf.GetOption('main', 'General', 'editor-on-startup', default=1, type='bool')) self.autoSave.set(idleConf.GetOption('main', 'General', 'autosave', default=0, type='bool')) self.winWidth.set(idleConf.GetOption('main', 'EditorWindow', 'width', type='int')) self.winHeight.set(idleConf.GetOption('main', 'EditorWindow', 'height', type='int')) self.paraWidth.set(idleConf.GetOption('main', 'FormatParagraph', 'paragraph', type='int')) self.encoding.set(idleConf.GetOption('main', 'EditorWindow', 'encoding', default='none')) self.userHelpList = idleConf.GetAllExtraHelpSourcesList() for helpItem in self.userHelpList: self.listHelp.insert(END, helpItem[0]) self.SetHelpListButtonStates()
def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.textfont = self.text['font'] self.label = None self.info = [(0, -1, '', False)] self.topvisible = 1 visible = idleConf.GetOption('extensions', 'CodeContext', 'visible', type='bool', default=False) if visible: self.toggle_code_context_event() self.editwin.setvar('<<toggle-code-context>>', True) self.text.after(UPDATEINTERVAL, self.timer_event) self.text.after(FONTUPDATEINTERVAL, self.font_timer_event) return
def __init__(self, text): """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). """ 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) return
def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.TB = None # pointer to toolbar tkinter object self.visible = idleConf.GetOption("extensions", "SubCodeToolbar", "visible", type="bool", default=True) self.setvars() self.text.bind('<<subcode-enable>>', self.subcode_enable_event, '+') self.text.bind('<<subcode-disable>>', self.subcode_disable_event, '+') #self.text.bind('<<subcode-toolbar-plus>>', self.subcode_plus_event, '+') #self.text.bind('<<subcode-toolbar-minus>>', self.subcode_minus_event, '+') sc = self.editwin.extensions.get('SubCode') if sc and sc.enable: self.subcode_enable_event()
def format_paragraph_event(self, event, limit=None): """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 blank lines) and formats it. The length limit parameter is for testing with a known value. """ if limit is None: # The default length limit is that defined by pep8 limit = idleConf.GetOption('extensions', 'FormatParagraph', 'max-width', type='int', default=72) 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: first, last, comment_header, data = \ find_paragraph(text, text.index("insert")) if comment_header: newdata = reformat_comment(data, limit, comment_header) else: newdata = reformat_paragraph(data, limit) text.tag_remove("sel", "1.0", "end") if newdata != data: text.mark_set("insert", first) text.undo_block_start() text.delete(first, last) text.insert(first, newdata) text.undo_block_stop() else: text.mark_set("insert", last) text.see("insert") return "break"
def __init__(self, editwin): self.editwin = editwin self.text = self.editwin.text self.enabled = idleConf.GetOption("extensions", "Terminal", "terminal", type="bool", default=True) self.editwin.setvar("<<terminal-toggle>>", not not self.enabled) # this extension is loaded from EditorWindow.py, but before # PyShell.py makes its changes. Will use tk .after to make # changes self.last_insert = 'end-1c' if self.enabled: self.text.after(10, self.delay_init)
def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.textfont = self.text['font'] self.label = None self.info = [(0, -1, '', False)] self.topvisible = 1 self.bottomvisible = 1 visible = idleConf.GetOption('extensions', 'LineNumber', 'visible', type='bool', default=False) if visible: self.toggle_line_number_event() self.editwin.setvar('<<toggle-line-number>>', True) self.text.after(UPDATEINTERVAL, self.timer_event) self.text.after(FONTUPDATEINTERVAL, self.font_timer_event)
def init(self, flist): self.flist = flist # reset pyclbr pyclbr._modules.clear() # create top self.top = top = ListedToplevel(flist.root) top.protocol("WM_DELETE_WINDOW", self.close) top.bind("<Escape>", self.close) self.settitle() top.focus_set() # create scrolled canvas theme = idleConf.GetOption('main','Theme','name') background = idleConf.GetHighlight(theme, 'normal')['background'] sc = ScrolledCanvas(top, bg=background, highlightthickness=0, takefocus=1) sc.frame.pack(expand=1, fill="both") item = self.rootnode() self.node = node = TreeNode(sc.canvas, None, item) node.update() node.expand()
def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.textfont = self.text["font"] self.label = None # self.info is a list of (line number, indent level, line text, block # keyword) tuples providing the block structure associated with # self.topvisible (the linenumber of the line displayed at the top of # the edit window). self.info[0] is initialized as a 'dummy' line which # starts the toplevel 'block' of the module. self.info = [(0, -1, "", False)] self.topvisible = 1 visible = idleConf.GetOption("extensions", "CodeContext", "visible", type="bool", default=False) if visible: self.toggle_code_context_event() self.editwin.setvar('<<toggle-code-context>>', True) # Start two update cycles, one for context lines, one for font changes. self.text.after(UPDATEINTERVAL, self.timer_event) self.text.after(FONTUPDATEINTERVAL, self.font_timer_event)
def __init__(self, editwin): self.editwin = editwin # reference to the editor window self.text = text = self.editwin.text self.text.bind("<<horizontal-show>>", self.show_toggle) # See __init__ in EditorWindow.py to understand # the widget layout self.xbar = xbar = tk.Scrollbar( editwin.text_frame, orient=tk.HORIZONTAL) # create the scroll bar xbar['command'] = text.xview # connect it to the text widget text['xscrollcommand'] = xbar.set # connext text widget to scroll bar self.visible = idleConf.GetOption("extensions", "Horizontal", "visible", type='bool', default=True) if self.visible: self._show_bar()
def populate_gui(self): IDLE_DEFAULT_EXT = extensionManager.IDLE_EXTENSIONS ext_list = idleConf.GetExtensions(active_only=False) ext_list.sort(key=str.lower) if 'idlexManager' in ext_list: ext_list.remove('idlexManager') # idlex enabled by default. lb = self.gui['extension_list'] lb.delete(0, END) # reset the list for item in ext_list: ext_found = True try: extensionManager.find_extension(item) except ImportError: ext_found = False en = idleConf.GetOption('extensions', item, 'enable', type='int') info = '' if item in IDLE_DEFAULT_EXT: info += ' (built-in) ' if not ext_found: if item not in IDLE_DEFAULT_EXT: if sys.modules.get('idlexlib.extensions.%s' % item) is not None: info += ' (RESTART TO UNLOAD) ' else: info += ' (NOT FOUND IN PATH) ' if en: enstr = '1' else: enstr = '0' text = ' [%s] %s %s' % (enstr, item, info) lb.insert(END, text) self.extensions = ext_list
def format_paragraph_event(self, event): """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 blank lines) and formats it. """ maxformatwidth = 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: first, last, comment_header, data = \ find_paragraph(text, text.index("insert")) if comment_header: newdata = reformat_comment(data, maxformatwidth, comment_header) else: newdata = reformat_paragraph(data, maxformatwidth) text.tag_remove("sel", "1.0", "end") if newdata != data: text.mark_set("insert", first) text.undo_block_start() text.delete(first, last) text.insert(first, newdata) text.undo_block_stop() else: text.mark_set("insert", last) text.see("insert") return "break"
def drawtext(self): textx = self.x + 20 - 1 texty = self.y - 1 labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor='nw', text=labeltext) self.canvas.tag_bind(id, '<1>', self.select) self.canvas.tag_bind(id, '<Double-1>', self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 text = self.item.GetText() or '<no text>' try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2) theme = idleConf.GetOption('main', 'Theme', 'name') if self.selected: self.label.configure(idleConf.GetHighlight(theme, 'hilite')) else: self.label.configure(idleConf.GetHighlight(theme, 'normal')) id = self.canvas.create_window(textx, texty, anchor='nw', window=self.label) self.label.bind('<1>', self.select_or_edit) self.label.bind('<Double-1>', self.flip) self.text_id = id
def LoadTagDefs(self): theme = idleConf.GetOption('main', 'Theme', 'name') self.tagdefs = { 'COMMENT': idleConf.GetHighlight(theme, 'comment'), 'KEYWORD': idleConf.GetHighlight(theme, 'keyword'), 'BUILTIN': idleConf.GetHighlight(theme, 'builtin'), 'STRING': idleConf.GetHighlight(theme, 'string'), 'DEFINITION': idleConf.GetHighlight(theme, 'definition'), 'SYNC': { 'background': None, 'foreground': None }, 'TODO': { 'background': None, 'foreground': None }, 'BREAK': idleConf.GetHighlight(theme, 'break'), 'ERROR': idleConf.GetHighlight(theme, 'error'), 'hit': idleConf.GetHighlight(theme, 'hit') } if DEBUG: print 'tagdefs', self.tagdefs return
def drawtext(self): textx = self.x + 20 - 1 texty = self.y - 4 labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: self.label except AttributeError: # padding carefully selected (on Windows) to match Entry widget: self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2) theme = idleConf.GetOption('main', 'Theme', 'name') if self.selected: self.label.configure(idleConf.GetHighlight(theme, 'hilite')) else: self.label.configure(idleConf.GetHighlight(theme, 'normal')) id = self.canvas.create_window(textx, texty, anchor="nw", window=self.label) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.text_id = id
def format_paragraph_event(self, event): maxformatwidth = int( idleConf.GetOption('main', 'FormatParagraph', 'paragraph')) text = self.editwin.text first, last = self.editwin.get_selection_indices() if first and last: data = text.get(first, last) comment_header = '' else: first, last, comment_header, data = find_paragraph( text, text.index('insert')) if comment_header: lines = data.split('\n') lines = map(lambda st, l=len(comment_header): st[l:], lines) data = '\n'.join(lines) format_width = max(maxformatwidth - len(comment_header), 20) newdata = reformat_paragraph(data, format_width) newdata = newdata.split('\n') block_suffix = '' if not newdata[-1]: block_suffix = '\n' newdata = newdata[:-1] builder = lambda item, prefix=comment_header: prefix + item newdata = '\n'.join(map(builder, newdata)) + block_suffix else: newdata = reformat_paragraph(data, maxformatwidth) text.tag_remove('sel', '1.0', 'end') if newdata != data: text.mark_set('insert', first) text.undo_block_start() text.delete(first, last) text.insert(first, newdata) text.undo_block_stop() else: text.mark_set('insert', last) text.see('insert') return 'break'
def LoadKeyCfg(self): self.keysAreBuiltin.set(idleConf.GetOption('main', 'Keys', 'default', type='bool', default=1)) currentOption = idleConf.CurrentKeys() if self.keysAreBuiltin.get(): itemList = idleConf.GetSectionList('default', 'keys') itemList.sort() self.optMenuKeysBuiltin.SetMenu(itemList, currentOption) itemList = idleConf.GetSectionList('user', 'keys') itemList.sort() if not itemList: self.radioKeysCustom.config(state=DISABLED) self.customKeys.set('- no custom keys -') else: self.optMenuKeysCustom.SetMenu(itemList, itemList[0]) else: itemList = idleConf.GetSectionList('user', 'keys') itemList.sort() self.optMenuKeysCustom.SetMenu(itemList, currentOption) itemList = idleConf.GetSectionList('default', 'keys') itemList.sort() self.optMenuKeysBuiltin.SetMenu(itemList, itemList[0]) self.SetKeysType() keySetName = idleConf.CurrentKeys() self.LoadKeysList(keySetName)
def set_notabs_indentwidth(self): """Update the indentwidth if changed and not using tabs in this window""" if not self.usetabs: self.indentwidth = idleConf.GetOption('main', 'Indent', 'num-spaces', type='int')
def encode(self, chars): if isinstance(chars, str): # This is either plain ASCII, or Tk was returning mixed-encoding # text to us. Don't try to guess further. return chars # See whether there is anything non-ASCII in it. # If not, no need to figure out the encoding. try: return chars.encode('ascii') except UnicodeError: pass # If there is an encoding declared, try this first. try: enc = coding_spec(chars) failed = None except LookupError as msg: failed = msg enc = None if enc: try: return chars.encode(enc) except UnicodeError: failed = "Invalid encoding '%s'" % enc if failed: tkMessageBox.showerror("I/O Error", "%s. Saving as UTF-8" % failed, parent=self.text) # If there was a UTF-8 signature, use that. This should not fail if self.fileencoding == BOM_UTF8 or failed: return BOM_UTF8 + chars.encode("utf-8") # Try the original file encoding next, if any if self.fileencoding: try: return chars.encode(self.fileencoding) except UnicodeError: tkMessageBox.showerror( "I/O Error", "Cannot save this as '%s' anymore. Saving as UTF-8" \ % self.fileencoding, parent = self.text) return BOM_UTF8 + chars.encode("utf-8") # Nothing was declared, and we had not determined an encoding # on loading. Recommend an encoding line. config_encoding = idleConf.GetOption("main", "EditorWindow", "encoding") if config_encoding == 'utf-8': # User has requested that we save files as UTF-8 return BOM_UTF8 + chars.encode("utf-8") ask_user = True try: chars = chars.encode(encoding) enc = encoding if config_encoding == 'locale': ask_user = False except UnicodeError: chars = BOM_UTF8 + chars.encode("utf-8") enc = "utf-8" if not ask_user: return chars dialog = EncodingMessage(self.editwin.top, enc) dialog.go() if dialog.num == 1: # User asked us to edit the file encline = "# -*- coding: %s -*-\n" % enc firstline = self.text.get("1.0", "2.0") if firstline.startswith("#!"): # Insert encoding after #! line self.text.insert("2.0", encline) else: self.text.insert("1.0", encline) return self.encode(self.text.get("1.0", "end-1c")) return chars
class LineNumber: menudefs = [('options', [('!Line _Number', '<<toggle-line-number>>')])] digit = 4 bgcolor = idleConf.GetOption('extensions', 'LineNumber', 'bgcolor', type='str', default='White') fgcolor = idleConf.GetOption('extensions', 'LineNumber', 'fgcolor', type='str', default='Black') def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.textfont = self.text['font'] self.label = None self.info = [(0, -1, '', False)] self.topvisible = 1 self.bottomvisible = 1 visible = idleConf.GetOption('extensions', 'LineNumber', 'visible', type='bool', default=False) if visible: self.toggle_line_number_event() self.editwin.setvar('<<toggle-line-number>>', True) self.text.after(UPDATEINTERVAL, self.timer_event) self.text.after(FONTUPDATEINTERVAL, self.font_timer_event) def toggle_line_number_event(self, event=None): if not self.label: widgets = self.editwin.text, self.editwin.text_frame pady = 0 for widget in widgets: pady += int(str(widget.pack_info()['pady'])) pady += int(str(widget.cget('pady'))) border = 0 for widget in widgets: border += int(str(widget.cget('border'))) self.label = Tkinter.Label( self.editwin.top, ## text='\n'.join(['%d'%(i+1) for i in range(50)]), text='1', anchor=N, justify=RIGHT, font=self.textfont, bg=self.bgcolor, fg=self.fgcolor, width=self.digit, pady=pady, border=border, relief=SUNKEN) self.label.pack(side=LEFT, fill=Y, expand=False, before=self.editwin.text_frame) else: self.label.destroy() self.label = None idleConf.SetOption('extensions', 'LineNumber', 'visible', str(self.label is not None)) idleConf.SaveUserCfgFiles() def timer_event(self): if self.label: self.update_line_number() self.text.after(UPDATEINTERVAL, self.timer_event) def font_timer_event(self): newtextfont = self.text["font"] if self.label and newtextfont != self.textfont: self.textfont = newtextfont self.label["font"] = self.textfont self.text.after(FONTUPDATEINTERVAL, self.font_timer_event) def update_line_number(self): topvisible = int(self.text.index('@0,0').split('.')[0]) bottomvisible = int(self.text.index('@0,%s' % INFINITY).split('.')[0]) ## print bottomvisible - topvisible, ## print self.bottomvisible - self.topvisible, ## topvisible = int(math.ceil(float(self.text.index('@0,0')))) ## bottomvisible = int(math.ceil(float(self.text.index('@0,16383')))) ## print self.text.index('@0,0'), ## print bottomvisible, if self.bottomvisible == bottomvisible: return self.label['text'] = '\n'.join([ '%d' % i for i in range( topvisible, ## min(topvisible+39, bottomvisible)+1)] bottomvisible + 1) ]) ## if min(topvisible+50, bottomvisible) >= 999: #### self.label['width'] = len(str(min(topvisible+39, bottomvisible)+1))+1 ## self.label['width'] = len(str(bottomvisible))+1 self.label['height'] = 1 self.label['width'] = max(len(str(bottomvisible)) + 1, 4) self.topvisible = topvisible self.bottomvisible = bottomvisible
def get_cfg(cfg, type="bool", default=True): return idleConf.GetOption("extensions", "TabExtension", cfg, type=type, default=default)
class ParenMatch: """Highlight matching parentheses There are three supported style of paren matching, based loosely on the Emacs options. The style is select based on the HILITE_STYLE attribute; it can be changed used the set_style method. The supported styles are: default -- When a right paren is typed, highlight the matching left paren for 1/2 sec. expression -- When a right paren is typed, highlight the entire expression from the left paren to the right paren. TODO: - extend IDLE with configuration dialog to change options - implement rest of Emacs highlight styles (see below) - print mismatch warning in IDLE status window Note: In Emacs, there are several styles of highlight where the matching paren is highlighted whenever the cursor is immediately to the right of a right paren. I don't know how to do that in Tk, so I haven't bothered. """ menudefs = [('edit', [ ("Show surrounding parens", "<<flash-paren>>"), ])] STYLE = idleConf.GetOption('extensions', 'ParenMatch', 'style', default='expression') FLASH_DELAY = idleConf.GetOption('extensions', 'ParenMatch', 'flash-delay', type='int', default=500) HILITE_CONFIG = idleConf.GetHighlight(idleConf.CurrentTheme(), 'hilite') BELL = idleConf.GetOption('extensions', 'ParenMatch', 'bell', type='bool', default=1) RESTORE_VIRTUAL_EVENT_NAME = "<<parenmatch-check-restore>>" # We want the restore event be called before the usual return and # backspace events. RESTORE_SEQUENCES = ("<KeyPress>", "<ButtonPress>", "<Key-Return>", "<Key-BackSpace>") def __init__(self, editwin): self.editwin = editwin self.text = editwin.text # Bind the check-restore event to the function restore_event, # so that we can then use activate_restore (which calls event_add) # and deactivate_restore (which calls event_delete). editwin.text.bind(self.RESTORE_VIRTUAL_EVENT_NAME, self.restore_event) self.counter = 0 self.is_restore_active = 0 self.set_style(self.STYLE) def activate_restore(self): if not self.is_restore_active: for seq in self.RESTORE_SEQUENCES: self.text.event_add(self.RESTORE_VIRTUAL_EVENT_NAME, seq) self.is_restore_active = True def deactivate_restore(self): if self.is_restore_active: for seq in self.RESTORE_SEQUENCES: self.text.event_delete(self.RESTORE_VIRTUAL_EVENT_NAME, seq) self.is_restore_active = False def set_style(self, style): self.STYLE = style if style == "default": self.create_tag = self.create_tag_default self.set_timeout = self.set_timeout_last elif style == "expression": self.create_tag = self.create_tag_expression self.set_timeout = self.set_timeout_none def flash_paren_event(self, event): indices = HyperParser(self.editwin, "insert").get_surrounding_brackets() if indices is None: self.warn_mismatched() return self.activate_restore() self.create_tag(indices) self.set_timeout_last() def paren_closed_event(self, event): # If it was a shortcut and not really a closing paren, quit. closer = self.text.get("insert-1c") if closer not in _openers: return hp = HyperParser(self.editwin, "insert-1c") if not hp.is_in_code(): return indices = hp.get_surrounding_brackets(_openers[closer], True) if indices is None: self.warn_mismatched() return self.activate_restore() self.create_tag(indices) self.set_timeout() def restore_event(self, event=None): self.text.tag_delete("paren") self.deactivate_restore() self.counter += 1 # disable the last timer, if there is one. def handle_restore_timer(self, timer_count): if timer_count == self.counter: self.restore_event() def warn_mismatched(self): if self.BELL: self.text.bell() # any one of the create_tag_XXX methods can be used depending on # the style def create_tag_default(self, indices): """Highlight the single paren that matches""" self.text.tag_add("paren", indices[0]) self.text.tag_config("paren", self.HILITE_CONFIG) def create_tag_expression(self, indices): """Highlight the entire expression""" 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) # any one of the set_timeout_XXX methods can be used depending on # the style def set_timeout_none(self): """Highlight will remain until user input turns it off or the insert has moved""" # After CHECK_DELAY, call a function which disables the "paren" tag # if the event is for the most recent timer and the insert has changed, # or schedules another call for itself. 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_DELAY, callme, callme) def set_timeout_last(self): """The last highlight created will be removed after .5 sec""" # associate a counter with an event; only disable the "paren" # tag if the event is for the most recent timer. self.counter += 1 self.editwin.text_frame.after(self.FLASH_DELAY, lambda self=self, c=self.counter: \ self.handle_restore_timer(c))
class AutoComplete: menudefs = [ ('edit', [ ("Show Completions", "<<force-open-completions>>"), ]) ] popupwait = idleConf.GetOption("extensions", "AutoComplete", "popupwait", type="int", default=0) def __init__(self, editwin=None): self.editwin = editwin if editwin is None: # subprocess and test return self.text = editwin.text self.autocompletewindow = None # id of delayed call, and the index of the text insert when the delayed # call was issued. If _delayed_completion_id is None, there is no # delayed call. self._delayed_completion_id = None self._delayed_completion_index = None def _make_autocomplete_window(self): return AutoCompleteWindow.AutoCompleteWindow(self.text) def _remove_autocomplete_window(self, event=None): if self.autocompletewindow: self.autocompletewindow.hide_window() self.autocompletewindow = None def force_open_completions_event(self, event): """Happens when the user really wants to open a completion list, even if a function call is needed. """ self.open_completions(True, False, True) def try_open_completions_event(self, event): """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. """ 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) def autocomplete_event(self, event): """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) """ if hasattr(event, "mc_state") and event.mc_state: # A modifier was pressed along with the tab, continue as usual. 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 "break" def _open_completions_later(self, *args): self._delayed_completion_index = self.text.index("insert") if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = \ self.text.after(self.popupwait, self._delayed_open_completions, *args) def _delayed_open_completions(self, *args): self._delayed_completion_id = None if self.text.index("insert") != self._delayed_completion_index: return self.open_completions(*args) def open_completions(self, evalfuncs, complete, userWantsWin, mode=None): """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. """ # Cancel another delayed call, if it exists. 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 mode or mode==COMPLETE_FILES): # Find the beginning of the string # fetch_completions will look at the file system to determine whether the # string value constitutes an actual file name # XXX could consider raw strings here and unescape the string value if it's # not raw. self._remove_autocomplete_window() mode = COMPLETE_FILES # Find last separator or string start while i and curline[i-1] not in "'\"" + SEPS: i -= 1 comp_start = curline[i:j] j = i # Find string start while i and curline[i-1] not in "'\"": i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode==COMPLETE_ATTRIBUTES): self._remove_autocomplete_window() mode = COMPLETE_ATTRIBUTES while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127): i -= 1 comp_start = curline[i:j] if i and curline[i-1] == '.': hp.set_index("insert-%dc" % (len(curline)-(i-1))) comp_what = hp.get_expression() if not comp_what or \ (not evalfuncs and comp_what.find('(') != -1): return else: comp_what = "" else: return if complete and not comp_what and not comp_start: return comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return self.autocompletewindow = self._make_autocomplete_window() self.autocompletewindow.show_window(comp_lists, "insert-%dc" % len(comp_start), complete, mode, userWantsWin) return True def fetch_completions(self, what, mode): """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. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. """ 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__.__dict__.copy() namespace.update(__main__.__builtins__.__dict__) bigl = eval("dir()", namespace) bigl.sort() if "__all__" in bigl: smalll = sorted(eval("__all__", namespace)) else: smalll = [s for s in bigl if s[:1] != '_'] else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if "__all__" in bigl: smalll = sorted(entity.__all__) else: smalll = [s for s in bigl if s[:1] != '_'] except: return [], [] elif mode == COMPLETE_FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = [s for s in bigl if s[:1] != '.'] except OSError: return [], [] if not smalll: smalll = bigl return smalll, bigl def get_entity(self, name): """Lookup name in a namespace spanning sys.modules and __main.dict__""" namespace = sys.modules.copy() namespace.update(__main__.__dict__) return eval(name, namespace)
#!/usr/bin/env python from idlelib.configHandler import idleConf font = idleConf.GetOption('main', 'EditorWindow', 'font') _f = 'foreground' _b = 'background' GREY = '#969696' RED = '#a71d5d' SKY = '#0086b3' INDIGO = '#183691' PURPLE = '#795da3' ORANGE = '#ed6a43' GREEN = '#63a35c' WHITE = '#ffffff' BLACK = '#333333' append_tags = { 'COMMENT': {_f: GREY, _b: WHITE}, 'KEYWORD': {_f: RED, _b: WHITE, 'font': (font, 10, 'bold')}, 'BUILTIN': {_f: SKY, _b: WHITE}, 'STRING': {_f: INDIGO, _b: WHITE, 'font': (font, 10, 'bold')}, 'DEFINITION': {_f: PURPLE, _b: WHITE, 'font': (font, 10, 'italic')}, 'ERROR': {_f: '#f8f8f8', _b: '#b52a1d'}, 'SELECTED': {_f: BLACK, _b: '#ffffc5'}, # TODO 'SP_VARIABLE': {_f: ORANGE, _b: WHITE}, 'FORMAT': {_f: SKY, _b: WHITE},
class AutoComplete: menudefs = [('edit', [('Show Completions', '<<force-open-completions>>')])] popupwait = idleConf.GetOption('extensions', 'AutoComplete', 'popupwait', type='int', default=0) def __init__(self, editwin=None): self.editwin = editwin if editwin is None: return else: self.text = editwin.text self.autocompletewindow = None self._delayed_completion_id = None self._delayed_completion_index = None return def _make_autocomplete_window(self): return AutoCompleteWindow.AutoCompleteWindow(self.text) def _remove_autocomplete_window(self, event=None): if self.autocompletewindow: self.autocompletewindow.hide_window() self.autocompletewindow = None return def force_open_completions_event(self, event): self.open_completions(True, False, True) 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) 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' opened = self.open_completions(False, True, True) return 'break' if opened else None def _open_completions_later(self, *args): self._delayed_completion_index = self.text.index('insert') if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = self.text.after( self.popupwait, self._delayed_open_completions, *args) return def _delayed_open_completions(self, *args): self._delayed_completion_id = None if self.text.index('insert') != self._delayed_completion_index: return else: self.open_completions(*args) return 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 mode or mode == COMPLETE_FILES): self._remove_autocomplete_window() mode = COMPLETE_FILES while i and curline[i - 1] in FILENAME_CHARS: i -= 1 comp_start = curline[i:j] j = i while i and curline[i - 1] in FILENAME_CHARS + SEPS: i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode == COMPLETE_ATTRIBUTES): self._remove_autocomplete_window() mode = COMPLETE_ATTRIBUTES while i and curline[i - 1] in ID_CHARS: i -= 1 comp_start = curline[i:j] if i and curline[i - 1] == '.': hp.set_index('insert-%dc' % (len(curline) - (i - 1))) comp_what = hp.get_expression() if not comp_what or not evalfuncs and comp_what.find( '(') != -1: return else: comp_what = '' else: return if complete and not comp_what and not comp_start: return else: comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return self.autocompletewindow = self._make_autocomplete_window() return not self.autocompletewindow.show_window( comp_lists, 'insert-%dc' % len(comp_start), complete, mode, userWantsWin) 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__.__dict__.copy() namespace.update(__main__.__builtins__.__dict__) bigl = eval('dir()', namespace) bigl.sort() if '__all__' in bigl: smalll = sorted(eval('__all__', namespace)) else: smalll = [s for s in bigl if s[:1] != '_'] else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if '__all__' in bigl: smalll = sorted(entity.__all__) else: smalll = [s for s in bigl if s[:1] != '_'] except: return ([], []) elif mode == COMPLETE_FILES: if what == '': what = '.' try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = [s for s in bigl if s[:1] != '.'] except OSError: return ([], []) if not smalll: smalll = bigl return (smalll, bigl) return def get_entity(self, name): namespace = sys.modules.copy() namespace.update(__main__.__dict__) return eval(name, namespace)
def __init__(self, flist=None, filename=None, key=None, root=None): if EditorWindow.help_url is None: dochome = os.path.join(sys.prefix, 'Doc', 'index.html') if sys.platform.count('linux'): pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3] if os.path.isdir('/var/www/html/python/'): dochome = '/var/www/html/python/index.html' else: basepath = '/usr/share/doc/' dochome = os.path.join(basepath, pyver, 'Doc', 'index.html') elif sys.platform[:3] == 'win': chmfile = os.path.join(sys.prefix, 'Doc', 'Python%s.chm' % _sphinx_version()) if os.path.isfile(chmfile): dochome = chmfile elif macosxSupport.runningAsOSXApp(): dochome = os.path.join(sys.prefix, 'Resources/English.lproj/Documentation/index.html') dochome = os.path.normpath(dochome) if os.path.isfile(dochome): EditorWindow.help_url = dochome if sys.platform == 'darwin': EditorWindow.help_url = 'file://' + EditorWindow.help_url else: EditorWindow.help_url = 'http://docs.python.org/%d.%d' % sys.version_info[:2] currentTheme = idleConf.CurrentTheme() self.flist = flist root = root or flist.root self.root = root try: sys.ps1 except AttributeError: sys.ps1 = '>>> ' self.menubar = Menu(root) self.top = top = WindowList.ListedToplevel(root, menu=self.menubar) if flist: self.tkinter_vars = flist.vars self.top.instance_dict = flist.inversedict else: self.tkinter_vars = {} self.top.instance_dict = {} self.recent_files_path = os.path.join(idleConf.GetUserCfgDir(), 'recent-files.lst') self.text_frame = text_frame = Frame(top) self.vbar = vbar = Scrollbar(text_frame, name='vbar') self.width = idleConf.GetOption('main', 'EditorWindow', 'width') text_options = {'name': 'text', 'padx': 5, 'wrap': 'none', 'width': self.width, 'height': idleConf.GetOption('main', 'EditorWindow', 'height') } if TkVersion >= 8.5: text_options['tabstyle'] = 'wordprocessor' self.text = text = MultiCallCreator(Text)(text_frame, **text_options) self.top.focused_widget = self.text self.createmenubar() self.apply_bindings() self.top.protocol('WM_DELETE_WINDOW', self.close) self.top.bind('<<close-window>>', self.close_event) if macosxSupport.runningAsOSXApp(): text.bind('<<close-window>>', self.close_event) text.bind('<Control-Button-1>', self.right_menu_event) else: text.bind('<3>', self.right_menu_event) text.bind('<<cut>>', self.cut) text.bind('<<copy>>', self.copy) text.bind('<<paste>>', self.paste) text.bind('<<center-insert>>', self.center_insert_event) text.bind('<<help>>', self.help_dialog) text.bind('<<python-docs>>', self.python_docs) text.bind('<<about-idle>>', self.about_dialog) text.bind('<<open-config-dialog>>', self.config_dialog) text.bind('<<open-module>>', self.open_module) text.bind('<<do-nothing>>', lambda event: 'break') text.bind('<<select-all>>', self.select_all) text.bind('<<remove-selection>>', self.remove_selection) text.bind('<<find>>', self.find_event) text.bind('<<find-again>>', self.find_again_event) text.bind('<<find-in-files>>', self.find_in_files_event) text.bind('<<find-selection>>', self.find_selection_event) text.bind('<<replace>>', self.replace_event) text.bind('<<goto-line>>', self.goto_line_event) text.bind('<<smart-backspace>>', self.smart_backspace_event) text.bind('<<newline-and-indent>>', self.newline_and_indent_event) text.bind('<<smart-indent>>', self.smart_indent_event) text.bind('<<indent-region>>', self.indent_region_event) text.bind('<<dedent-region>>', self.dedent_region_event) text.bind('<<comment-region>>', self.comment_region_event) text.bind('<<uncomment-region>>', self.uncomment_region_event) text.bind('<<tabify-region>>', self.tabify_region_event) text.bind('<<untabify-region>>', self.untabify_region_event) text.bind('<<toggle-tabs>>', self.toggle_tabs_event) text.bind('<<change-indentwidth>>', self.change_indentwidth_event) text.bind('<Left>', self.move_at_edge_if_selection(0)) text.bind('<Right>', self.move_at_edge_if_selection(1)) text.bind('<<del-word-left>>', self.del_word_left) text.bind('<<del-word-right>>', self.del_word_right) text.bind('<<beginning-of-line>>', self.home_callback) if flist: flist.inversedict[self] = key if key: flist.dict[key] = self text.bind('<<open-new-window>>', self.new_callback) text.bind('<<close-all-windows>>', self.flist.close_all_callback) text.bind('<<open-class-browser>>', self.open_class_browser) text.bind('<<open-path-browser>>', self.open_path_browser) self.set_status_bar() vbar['command'] = text.yview vbar.pack(side=RIGHT, fill=Y) text['yscrollcommand'] = vbar.set fontWeight = 'normal' if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'): fontWeight = 'bold' text.config(font=(idleConf.GetOption('main', 'EditorWindow', 'font'), idleConf.GetOption('main', 'EditorWindow', 'font-size'), fontWeight)) text_frame.pack(side=LEFT, fill=BOTH, expand=1) text.pack(side=TOP, fill=BOTH, expand=1) text.focus_set() usespaces = idleConf.GetOption('main', 'Indent', 'use-spaces', type='bool') self.usetabs = not usespaces self.tabwidth = 8 self.indentwidth = self.tabwidth self.set_notabs_indentwidth() self.context_use_ps1 = False self.num_context_lines = (50, 500, 5000000) self.per = per = self.Percolator(text) self.undo = undo = self.UndoDelegator() per.insertfilter(undo) text.undo_block_start = undo.undo_block_start text.undo_block_stop = undo.undo_block_stop undo.set_saved_change_hook(self.saved_change_hook) self.io = io = self.IOBinding(self) io.set_filename_change_hook(self.filename_change_hook) self.recent_files_menu = Menu(self.menubar) self.menudict['file'].insert_cascade(3, label='Recent Files', underline=0, menu=self.recent_files_menu) self.update_recent_files_list() self.color = None if filename: if os.path.exists(filename) and not os.path.isdir(filename): io.loadfile(filename) else: io.set_filename(filename) self.ResetColorizer() self.saved_change_hook() self.set_indentation_params(self.ispythonsource(filename)) self.load_extensions() menu = self.menudict.get('windows') if menu: end = menu.index('end') if end is None: end = -1 if end >= 0: menu.add_separator() end = end + 1 self.wmenu_end = end WindowList.register_callback(self.postwindowsmenu) self.askyesno = tkMessageBox.askyesno self.askinteger = tkSimpleDialog.askinteger self.showerror = tkMessageBox.showerror return
sys.argv = [script] + args elif args: enable_edit = True pathx = [] for filename in args: pathx.append(os.path.dirname(filename)) for dir in pathx: dir = os.path.abspath(dir) if dir not in sys.path: sys.path.insert(0, dir) else: dir = os.getcwd() if not dir in sys.path: sys.path.insert(0, dir) # check the IDLE settings configuration (but command line overrides) edit_start = idleConf.GetOption('main', 'General', 'editor-on-startup', type='bool') enable_edit = enable_edit or edit_start #Start LabVIEW GUI ActiveX Server if(create_LabVIEW_ActiveX): LV_Options=LV_ActiveX_Option_Val.split(",") if(len(LV_Options)<2): print "expected 2 arguments but got ", len(LV_Options) sys.exit() else: pass LV_Options=LV_ActiveX_Option_Val.split(",") GUI_Module_Name=LV_Options[0].strip() GUI_Module_Path=LV_Options[1].strip() GUI_Module_App_Name=LV_Options[2].strip() GUI_Module_Info=imp.find_module(GUI_Module_Name,[GUI_Module_Path])