def GotoBookmark(self, mark): """Goto the bookmark in the editor @param mark: BookMark """ app = wx.GetApp() mw = app.GetActiveWindow() if mw: nb = mw.GetNotebook() buf = nb.FindBuffer(mark.Filename) use_handle = True if not buf: nb.OpenPage(ebmlib.GetPathName(mark.Filename), ebmlib.GetFileName(mark.Filename)) buf = nb.GetCurrentPage() use_handle = False # Handle is invalid so use line number if buf: # Ensure the tab is the current one nb.GotoPage(mark.Filename) # Jump to the bookmark line if use_handle: lnum = buf.MarkerLineFromHandle(mark.Handle) else: lnum = mark.Line buf.GotoLine(lnum) else: util.Log("[ed_bookmark][err] Failed to locate mainwindow")
def OnAddPyExe(self, event): """Handle adding new item""" config = Profile_Get(PYTOOL_CONFIG, default=dict()) curpy = config.get(TLC_PYTHON_PATH, u'') cdir = ebmlib.GetPathName(curpy) cfile = ebmlib.GetFileName(curpy) dlg = wx.FileDialog(self, _("Select Python Executable"), cdir, cfile, style=wx.FD_OPEN | wx.FD_CHANGE_DIR | wx.FD_FILE_MUST_EXIST) dlg.CenterOnParent() result = dlg.ShowModal() path = dlg.Path dlg.Destroy() if result != wx.ID_OK: return if path and os.path.exists(path): allpy = config.get(TLC_ALL_PYTHON_PATHS, []) if path not in allpy: # Update collection of paths allpy.append(path) allpy.sort() config[TLC_ALL_PYTHON_PATHS] = allpy # Update Choice control and current selection self._python_path_combo.Items = allpy self._python_path_combo.StringSelection = path # Update current python to the newly added one config[TLC_PYTHON_PATH] = path Profile_Set(PYTOOL_CONFIG, config)
def OnDrop(self, files): """Opens dropped files @param files: list of file paths @postcondition: all files that could be properly opend are added to the notebook """ # Check file properties and make a "clean" list of file(s) to open valid_files = list() for fname in files: self.LOG("[ed_pages][evt] File(s) Dropped: %s" % fname) if not os.path.exists(fname): self.frame.PushStatusText(_("Invalid file: %s") % fname, \ ed_glob.SB_INFO) elif os.path.isdir(fname): dcnt = glob.glob(os.path.join(fname, '*')) dcnt = util.FilterFiles(dcnt) dlg = None if not len(dcnt): dlg = wx.MessageDialog(self, _("There are no files that Editra" " can open in %s") % fname, _("No Valid Files to Open"), style=wx.OK | wx.CENTER | \ wx.ICON_INFORMATION) elif len(dcnt) > 5: # Warn when the folder contains many files dlg = wx.MessageDialog(self, _("Do you wish to open all %d files" " in this directory?\n\nWarning:" " opening many files at once may" " cause the editor to temporarily " " freeze.") % len(dcnt), _("Open Directory?"), style=wx.YES | wx.NO | \ wx.ICON_INFORMATION) if dlg is not None: result = dlg.ShowModal() dlg.Destroy() else: result = wx.ID_YES if result == wx.ID_YES: valid_files.extend(dcnt) else: pass else: valid_files.append(fname) for fname in valid_files: pathname = ebmlib.GetPathName(fname) the_file = ebmlib.GetFileName(fname) self.OpenPage(pathname, the_file) self.frame.PushStatusText(_("Opened file: %s") % fname, \ ed_glob.SB_INFO) return
def GenerateHead(self): """Generates the html head block @return: html header information """ return "<head>\n<title>%s</title>\n" \ "<meta name=\"Generator\" content=\"Editra/%s\">\n" \ "<meta http-equiv=\"content-type\" content=\"text/html; " \ "charset=utf-8\">" \ "\n</head>" % (ebmlib.GetFileName(self.stc.GetFileName()), ed_glob.VERSION)
def testGetFileName(self): """Test that getting the file name from a string returns the correct string. """ roots = (("Home", "foo", "projects"), ("usr", "bin"), ("Users", "bar", "Desktop")) fname = "test.py" paths = [os.path.join(os.sep.join(root), fname) for root in roots] for path in paths: self.assertEqual(fname, ebmlib.GetFileName(path), "ebmlib.GetFileName(%s) != %s" % (path, fname))
def OpenFileObject(self, fileobj): """Open a new text editor page with the given file object. The file object must be an instance of ed_txt.EdFile. @param fileobj: File Object """ # Create the control self.GetTopLevelParent().Freeze() control = ed_editv.EdEditorView(self, wx.ID_ANY) control.Hide() # Load the files data path = fileobj.GetPath() filename = ebmlib.GetFileName(path) control.SetDocument(fileobj) result = control.ReloadFile() # Setup the buffer fileobj.AddModifiedCallback(control.FireModified) # Setup the notebook self.control = control self.control.FindLexer() self.control.EmptyUndoBuffer() self.control.Show() self.AddPage(self.control, filename) self.frame.SetTitle(self.control.GetTitleString()) self.frame.AddFileToHistory(path) self.SetPageText(self.GetSelection(), filename) self.LOG("[ed_pages][evt] Opened Page: %s" % filename) # Set tab image cpage = self.GetSelection() if fileobj.ReadOnly: super(EdPages, self).SetPageImage(cpage, self._index[ed_glob.ID_READONLY]) else: self.SetPageImage(cpage, str(self.control.GetLangId())) self.GetTopLevelParent().Thaw() # Refocus on selected page self.GoCurrentPage() ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED, self.control.GetFileName(), context=self.frame.GetId()) if Profile_Get('WARN_EOL', default=True) and not fileobj.IsRawBytes(): self.control.CheckEOL()
def FindLexer(self, set_ext=u''): """Sets Text Controls Lexer Based on File Extension @param set_ext: explicit extension to use in search @postcondition: lexer is configured for file """ if set_ext != u'': ext = set_ext.lower() else: ext = self.file.GetExtension().lower() if ext == u'': fname = self.GetFileName() ext = ebmlib.GetFileName(fname).lower() self.ClearDocumentStyle() # Configure Lexer from File Extension self.ConfigureLexer(ext) # If syntax auto detection fails from file extension try to # see if there is an interpreter line that can be parsed. if self.GetLexer() == wx.stc.STC_LEX_NULL: interp = self.GetLine(0) if interp != wx.EmptyString: interp = interp.split(u"/")[-1] interp = interp.strip().split() if len(interp) and interp[-1][0] != u"-": interp = interp[-1] elif len(interp): interp = interp[0] else: interp = u'' # TODO: should check user config to ensure the explict # extension is still associated with the expected # file type. ex_map = { "python": "py", "wish": "tcl", "ruby": "rb", "bash": "sh", "csh": "csh", "perl": "pl", "ksh": "ksh", "php": "php", "booi": "boo", "pike": "pike" } self.ConfigureLexer(ex_map.get(interp, interp)) self.Colourise(0, -1)
def OpenDocPointer(self, ptr, doc, title=u''): """Open a page using an stc document poiner @param ptr: EdEditorView document Pointer @param doc: EdFile instance @keyword title: tab title """ self.GetTopLevelParent().Freeze() nbuff = self.GetCurrentPage() need_add = False if nbuff.GetFileName() or nbuff.GetLength(): need_add = True nbuff = ed_editv.EdEditorView(self) nbuff.SetDocPointer(ptr) nbuff.SetDocument(doc) doc.AddModifiedCallback(nbuff.FireModified) nbuff.FindLexer() path = nbuff.GetFileName() if Profile_Get('SAVE_POS'): pos = self.DocMgr.GetPos(path) nbuff.SetCaretPos(pos) nbuff.ScrollToColumn(0) if title: filename = title else: filename = ebmlib.GetFileName(path) if need_add: self.AddPage(nbuff, filename) else: self.SetPageText(self.GetSelection(), filename) self.frame.SetTitle(nbuff.GetTitleString()) self.LOG("[ed_pages][evt] Opened Page: %s" % filename) # Set tab image # TODO: Handle read only images self.SetPageImage(self.GetSelection(), str(nbuff.GetLangId())) # Refocus on selected page self.control = nbuff self.GoCurrentPage() self.GetTopLevelParent().Thaw() ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED, nbuff.GetFileName(), context=self.frame.GetId())
def EditCommand(self, cmd): """Perform an edit related command @param cmd: command string to execute """ # e fname: edit file cmd = cmd[1:].strip() frame = self.GetTopLevelParent() if not os.path.isabs(cmd): cmd = os.path.join(self._curdir, cmd) if os.path.exists(cmd): frame.DoOpen(ed_glob.ID_COMMAND_LINE_OPEN, cmd) else: frame.nb.OpenPage(ebmlib.GetPathName(cmd), ebmlib.GetFileName(cmd))
def DoCompileCheck(self, path): """Run a compilation check on the given path @return: tuple(path, output) """ flag, pypath = ToolConfig.GetPythonExecutablePath("CompileCheck") if not flag: # No configured Python return (None, u"No Python") # TODO translations (send error code) # run 'python -m py_compile fname' parentPath = ebmlib.GetPathName(path) fname = ebmlib.GetFileName(path) cmd = [pypath, '-m', 'py_compile', fname] # TODO: pythonpath? processcreator = ProcessCreator("CompileCheck", parentPath, cmd) process = processcreator.createprocess() stdoutdata, stderrdata = process.communicate() processcreator.restorepath() return (path, stderrdata)
def testWriteUTF8Bom(self): """Test writing a file that has utf8 bom character""" txt = self.utf8_bom_file.Read() self.assertTrue(self.utf8_bom_file.HasBom()) new_path = os.path.join(common.GetTempDir(), ebmlib.GetFileName(self.bpath)) self.utf8_bom_file.SetPath(new_path) # write to test temp dir self.utf8_bom_file.Write(txt) # Open and verify that BOM was correctly written back f = open(new_path, 'rb') ntxt = f.read() f.close() self.assertTrue(ntxt.startswith(codecs.BOM_UTF8)) # Ensure that BOM was only written once tmp = ntxt.lstrip(codecs.BOM_UTF8) self.assertFalse(tmp.startswith(codecs.BOM_UTF8)) tmp = tmp.decode('utf-8') self.assertEquals(txt, tmp)
def OnNavigateToPos(self, evt): """Handle buffer position history navigation events""" e_id = evt.GetId() fname, pos = (None, None) cname = self.control.GetFileName() cpos = self.control.GetCurrentPos() if e_id == ed_glob.ID_NEXT_POS: if self.DocMgr.CanNavigateNext(): fname, pos = self.DocMgr.GetNextNaviPos() if (fname, pos) == (cname, cpos): fname, pos = (None, None) tmp = self.DocMgr.GetNextNaviPos() if tmp is not None: fname, pos = tmp elif e_id == ed_glob.ID_PRE_POS: if self.DocMgr.CanNavigatePrev(): fname, pos = self.DocMgr.GetPreviousNaviPos() if (fname, pos) == (cname, cpos): fname, pos = (None, None) tmp = self.DocMgr.GetPreviousNaviPos() if tmp is not None: fname, pos = tmp else: evt.Skip() return ctrl = self.FindBuffer(fname) if ctrl is None: # Open the file in the editor if fname is not None: self.OpenPage(ebmlib.GetPathName(fname), ebmlib.GetFileName(fname)) self.control.SetCaretPos(pos) else: # Raise page to top and goto position pages = [ self.GetPage(page) for page in xrange(self.GetPageCount()) ] idx = pages.index(ctrl) self.ChangePage(idx) ctrl.SetCaretPos(pos)
def process_file(window, d): filename = d["name"] # If the file is open in this window, reuse it. Otherwise, open it. for i in range(window.nb.GetPageCount()): page = window.nb.GetPage(i) if page.GetFileName() == filename: window.nb.ChangePage(i) break else: window.nb.OpenPage(ebmlib.GetPathName(filename), ebmlib.GetFileName(filename), quiet=True) window.nb.GoCurrentPage() buff = window.nb.GetCurrentCtrl() if d.get("revert", False): buff.RevertToSaved() # Go to the line. if "line" in d: buff.GotoLine(d["line"] - 1)
def OpenPage(self, path, filename, quiet=False): """Open a File Inside of a New Page @param path: files base path @param filename: name of file to open @keyword quiet: Open/Switch to the file quietly if it is already open. """ path2file = os.path.join(path, filename) # Resolve links to real file if ebmlib.IsLink(path2file): path2file = ebmlib.ResolveRealPath(path2file) path = ebmlib.GetPathName(path2file) filename = ebmlib.GetFileName(path2file) if self.DocDuplicated(path2file): return # Check if file needs to be opened # TODO: these steps could be combined together with some # refactoring of the _NeedOpen method. Requires extra # testing though to check for dependencies on current # behavior. if quiet and self.HasFileOpen(path2file): self.GotoPage(path2file) return elif not self._NeedOpen(path2file): return # Create new control to place text on if necessary self.GetTopLevelParent().Freeze() new_pg = True if self.GetPageCount(): if self.control.GetModify() or self.control.GetLength() or \ self.control.GetFileName() != u'': control = ed_editv.EdEditorView(self, wx.ID_ANY) control.Hide() else: new_pg = False control = self.control else: control = ed_editv.EdEditorView(self, wx.ID_ANY) control.Hide() # Open file and get contents result = False if os.path.exists(path2file): try: result = control.LoadFile(path2file) except Exception, msg: self.LOG("[ed_pages][err] Failed to open file %s\n" % path2file) self.LOG("[ed_pages][err] %s" % msg) # File could not be opened/read give up # Don't raise a dialog during a session load error as if the # dialog is shown before the mainwindow is ready it can cause # the app to freeze. if not self._ses_load: ed_mdlg.OpenErrorDlg(self, path2file, msg) control.GetDocument().ClearLastError() control.SetFileName('') # Reset the file name if new_pg: control.Destroy() self.GetTopLevelParent().Thaw() return