def open_file(self, filename='', cursorPosition=-1, tabIndex=None, positionIsLineNumber=False, notStart=True): if not filename: if settings.WORKSPACE: directory = settings.WORKSPACE else: directory = os.path.expanduser("~") editorWidget = self.get_current_editor() ninjaide = IDE.get_service('ide') if ninjaide: current_project = ninjaide.get_current_project() if current_project is not None: directory = current_project elif editorWidget is not None and editorWidget.ID: directory = file_manager.get_folder(editorWidget.ID) extensions = ';;'.join( ['(*%s)' % e for e in settings.SUPPORTED_EXTENSIONS + ['.*', '']]) fileNames = list(QFileDialog.getOpenFileNames(self, self.tr("Open File"), directory, extensions)) else: fileNames = [filename] if not fileNames: return for filename in fileNames: if file_manager.get_file_extension(filename) in ('jpg', 'png'): self.open_image(filename) elif file_manager.get_file_extension(filename).endswith('ui'): self.w = uic.loadUi(filename) self.w.show() else: self.__open_file(filename, cursorPosition, tabIndex, positionIsLineNumber)
def save_file_as(self): editorWidget = self.get_current_editor() if not editorWidget: return False try: filters = "(*.py);;(*.*)" if editorWidget.file_path: ext = file_manager.get_file_extension(editorWidget.file_path) if ext != "py": filters = "(*.%s);;(*.py);;(*.*)" % ext save_folder = self._get_save_folder(editorWidget.file_path) fileName = QFileDialog.getSaveFileName(self._parent, self.tr("Save File"), save_folder, filters) if not fileName: return False if settings.REMOVE_TRAILING_SPACES: helpers.remove_trailing_spaces(editorWidget) editorWidget.neditable.save_content(path=fileName) editorWidget.register_syntax(file_manager.get_file_extension(fileName)) self.emit(SIGNAL("fileSaved(QString)"), (self.tr("File Saved: %s") % fileName)) self.emit(SIGNAL("currentEditorChanged(QString)"), fileName) return True except file_manager.NinjaFileExistsException as ex: QMessageBox.information( self, self.tr("File Already Exists"), (self.tr("Invalid Path: the file '%s' " " already exists.") % ex.filename), ) except Exception as reason: logger.error("save_file_as: %s", reason) QMessageBox.information(self, self.tr("Save Error"), self.tr("The file couldn't be saved!")) return False
def save_file_as(self): editorWidget = self.get_current_editor() if not editorWidget: return False nfile = editorWidget.nfile try: #editorWidget.just_saved = True filters = '(*.py);;(*.*)' if nfile.file_path: ext = file_manager.get_file_extension(nfile.file_path) if ext != 'py': filters = '(*.%s);;(*.py);;(*.*)' % ext save_folder = self._get_save_folder(nfile.file_path) fileName = QFileDialog.getSaveFileName( self._parent, self.tr("Save File"), save_folder, filters) if not fileName: return False if settings.REMOVE_TRAILING_SPACES: helpers.remove_trailing_spaces(editorWidget) #newFile = file_manager.get_file_extension(fileName) == '' nfile.save(editorWidget.get_text(), path=fileName) print editorWidget.nfile._file_path #fileName = file_manager.store_file_content( #fileName, editorWidget.get_text(), #addExtension=True, newFile=newFile) #self.actualTab.setTabText(self.actualTab.currentIndex(), #file_manager.get_basename(fileName)) editorWidget.register_syntax( file_manager.get_file_extension(fileName)) #self._file_watcher.allow_kill = False #if editorWidget.ID != fileName: #self.remove_standalone_watcher(editorWidget.ID) #editorWidget.ID = fileName self.emit(SIGNAL("fileSaved(QString)"), (self.tr("File Saved: %s") % fileName)) self.emit(SIGNAL("currentTabChanged(QString)"), fileName) editorWidget._file_saved() #self.add_standalone_watcher(fileName) #self._file_watcher.allow_kill = True return True except file_manager.NinjaFileExistsException as ex: #editorWidget.just_saved = False QMessageBox.information(self, self.tr("File Already Exists"), (self.tr("Invalid Path: the file '%s' already exists.") % ex.filename)) except Exception as reason: #editorWidget.just_saved = False logger.error('save_file_as: %s', reason) QMessageBox.information(self, self.tr("Save Error"), self.tr("The file couldn't be saved!")) self.actualTab.setTabText(self.actualTab.currentIndex(), self.tr("New Document")) return False
def save_file_as(self, editor_widget=None): force = False if editor_widget is None: # We invoque from menu editor_widget = self.get_current_editor() if editor_widget is None: # We haven't editor in main container return False force = True try: filters = "(*.py);;(*.*)" if editor_widget.file_path is not None: # Existing file extension = file_manager.get_file_extension( editor_widget.file_path) if extension != 'py': filters = "(*.%s);;(*.py);;(*.*)" % extension save_folder = self._get_save_folder(editor_widget.file_path) else: save_folder = settings.WORKSPACE filename = QFileDialog.getSaveFileName( self, translations.TR_SAVE_FILE_DIALOG, save_folder, filters )[0] if not filename: return False # FIXME: remove trailing spaces extension = file_manager.get_file_extension(filename) if not extension: filename = "%s.%s" % (filename, "py") editor_widget.neditable.save_content(path=filename, force=force) # self._setter_language.set_language_from_extension(extension) self.fileSaved.emit(translations.TR_FILE_SAVED.format(filename)) self.currentEditorChanged.emit(filename) return True except file_manager.NinjaFileExistsException as reason: QMessageBox.information( self, translations.TR_FILE_ALREADY_EXISTS_TITLE, translations.TR_FILE_ALREADY_EXISTS_BODY.format( reason.filename) ) except Exception as reason: logger.error("Save file as: %s", reason) QMessageBox.information( self, translations.TR_SAVE_FILE_ERROR_TITLE, translations.TR_SAVE_FILE_ERROR_BODY ) return False
def _filter_this_file(self, filterOptions, index): at_start = (index == 0) if at_start: main_container = IDE.get_service('main_container') editorWidget = None if main_container: editorWidget = main_container.get_current_editor() index += 2 if editorWidget: exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension( editorWidget.file_path) if file_ext in exts: filterOptions.insert(0, locator.FILTERS['files']) else: filterOptions.insert(0, locator.FILTERS['non-python']) filterOptions.insert(1, editorWidget.file_path) self.tempLocations = \ self.locate_symbols.get_this_file_symbols( editorWidget.file_path) search = filterOptions[index + 1].lstrip().lower() self.tempLocations = [x for x in self.tempLocations if x.comparison.lower().find(search) > -1] else: del filterOptions[index + 1] del filterOptions[index] return index
def _filter_lines(self, filterOptions, index): at_start = (index == 0) if at_start: main_container = IDE.get_service('main_container') editorWidget = None if main_container: editorWidget = main_container.get_current_editor() index = 2 if editorWidget: exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension( editorWidget.file_path) if file_ext in exts: filterOptions.insert(0, locator.FILTERS['files']) else: filterOptions.insert(0, locator.FILTERS['non-python']) filterOptions.insert(1, editorWidget.file_path) self.tempLocations = [ x for x in self.locate_symbols.get_locations() if x.type == filterOptions[0] and x.path == filterOptions[1]] else: currentItem = self._root.currentItem() if currentItem is not None: currentItem = currentItem.toVariant() self.tempLocations = [ x for x in self.locate_symbols.get_locations() if x.type == currentItem[0] and x.path == currentItem[2]] if filterOptions[index + 1].isdigit(): self._line_jump = int(filterOptions[index + 1]) - 1 return index + 2
def _menu_context_tree(self, point, isRoot=False, root_path=None): index = self.indexAt(point) if not index.isValid() and not isRoot: return handler = None menu = QMenu(self) if isRoot or self.model().isDir(index): self._add_context_menu_for_folders(menu, isRoot, root_path) else: filename = self.model().fileName(index) lang = file_manager.get_file_extension(filename) self._add_context_menu_for_files(menu, lang) if isRoot: #get the extra context menu for this projectType handler = settings.get_project_type_handler( self.project.project_type) self._add_context_menu_for_root(menu) menu.addMenu(self._folding_menu) #menu for the Project Type(if present) if handler: for m in handler.get_context_menus(): if isinstance(m, QMenu): menu.addSeparator() menu.addMenu(m) #show the menu! menu.exec_(QCursor.pos())
def contextMenuEvent(self, event): popup_menu = self.createStandardContextMenu() menu_lint = QMenu(self.tr("Ignore Lint")) ignoreLineAction = menu_lint.addAction( self.tr("Ignore This Line")) ignoreSelectedAction = menu_lint.addAction( self.tr("Ignore Selected Area")) self.connect(ignoreLineAction, SIGNAL("triggered()"), lambda: helpers.lint_ignore_line(self)) self.connect(ignoreSelectedAction, SIGNAL("triggered()"), lambda: helpers.lint_ignore_selection(self)) popup_menu.insertSeparator(popup_menu.actions()[0]) popup_menu.insertMenu(popup_menu.actions()[0], menu_lint) popup_menu.insertAction(popup_menu.actions()[0], self.__actionFindOccurrences) #add extra menus (from Plugins) lang = file_manager.get_file_extension(self.ID) extra_menus = self.EXTRA_MENU.get(lang, None) if extra_menus: popup_menu.addSeparator() for menu in extra_menus: popup_menu.addMenu(menu) #show menu popup_menu.exec_(event.globalPos())
def update_explorer(self): """Update the symbols in the Symbol Explorer when a file is saved.""" main_container = IDE.get_service('main_container') if not main_container: return editorWidget = main_container.get_current_editor() if editorWidget: ext = file_manager.get_file_extension(editorWidget.ID) #obtain a symbols handler for this file extension symbols_handler = settings.get_symbols_handler(ext) if symbols_handler: source = editorWidget.toPlainText() if editorWidget.encoding is not None: source = source.encode(editorWidget.encoding) if ext == 'py': args = (source, True) else: args = (source,) symbols = symbols_handler.obtain_symbols(*args) self.update_symbols(symbols, editorWidget.ID) #TODO: Should we change the code below similar to the code above? exts = settings.SYNTAX.get('python')['extension'] if ext in exts or editorWidget.newDocument: self.update_errors(editorWidget.errors, editorWidget.pep8)
def _grep_file_locate(self, file_path, file_name): #type - file_name - file_path global mapping_locations #TODO: Check if the last know state of the file is valid and load that exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(file_path) if file_ext not in exts: mapping_locations[file_path] = [ ResultItem(type=FILTERS['non-python'], name=file_name, path=file_path, lineno=0)] else: mapping_locations[file_path] = [ ResultItem(type=FILTERS['files'], name=file_name, path=file_path, lineno=0)] #obtain a symbols handler for this file extension symbols_handler = settings.get_symbols_handler(file_ext) if symbols_handler is None: return results = [] with open(file_path) as f: content = f.read() symbols = symbols_handler.obtain_symbols(content, filename=file_path) self.__parse_symbols(symbols, results, file_path) if results: mapping_locations[file_path] += results
def _grep_file_symbols(self, file_path, file_name): #type - file_name - file_path global mapping_symbols exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(file_path) if file_ext not in exts: mapping_symbols[file_path] = [ ResultItem(symbol_type=FILTERS['non-python'], name=file_name, path=file_path, lineno=-1)] else: mapping_symbols[file_path] = [ ResultItem(symbol_type=FILTERS['files'], name=file_name, path=file_path, lineno=-1)] data = self._get_file_symbols(file_path) #FIXME: stat not int mtime = int(os.stat(file_path).st_mtime) if data is not None and (mtime == int(data[1])): results = pickle.loads(str(data[2])) mapping_symbols[file_path] += results return #obtain a symbols handler for this file extension symbols_handler = handlers.get_symbols_handler(file_ext) if symbols_handler is None: return results = [] with open(file_path) as f: content = f.read() symbols = symbols_handler.obtain_symbols(content, filename=file_path) self.__parse_symbols(symbols, results, file_path) if results: self._save_file_symbols(file_path, mtime, results) mapping_symbols[file_path] += results
def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) not_imports = dict() if file_ext in exts: self.reset() # source = self._editor.text path = self._editor.file_path checker = nic.Checker(path) not_imports = checker.get_not_imports_on_file( checker.get_imports()) if not_imports is None: pass else: for key, values in not_imports.items(): if isinstance(values['mod_name'], dict): for v in values['mod_name']: message = '[NOTIMP] {}: Dont exist'.format(v) else: message = '[NOTIMP] {}: Dont exist'.format( values['mod_name']) range_ = helpers.get_range(self._editor, values['lineno'] - 1) self.checks[values['lineno'] - 1].append((range_, message)) self.checkerCompleted.emit()
def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: try: self.reset() source = self._editor.text path = self._editor.file_path pep8_style = pycodestyle.StyleGuide( parse_argv=False, config_file='', checker_class=CustomChecker ) temp_data = pep8_style.input_file( path, lines=source.splitlines(True) ) source_lines = source.split('\n') # for lineno, offset, code, text, doc in temp_data: for lineno, col, code, text in temp_data: message = '[PEP8]: %s' % text range_ = helpers.get_range(self._editor, lineno - 1, col) self.checks[lineno - 1].append( (range_, message, source_lines[lineno - 1].strip())) except Exception as reason: logger.warning("Checker not finished: {}".format(reason)) self.checkerCompleted.emit()
def restyle(self, syntaxLang=None): self.apply_editor_style() if self.lang == 'python': parts_scanner, code_scanner, formats = \ syntax_highlighter.load_syntax(python_syntax.syntax) self.highlighter = syntax_highlighter.SyntaxHighlighter( self.document(), parts_scanner, code_scanner, formats, errors=self.errors, pep8=self.pep8, migration=self.migration) if self._mini: self._mini.highlighter = syntax_highlighter.SyntaxHighlighter( self._mini.document(), parts_scanner, code_scanner, formats) return if self.highlighter is None or isinstance(self.highlighter, highlighter.EmpyHighlighter): self.highlighter = highlighter.Highlighter(self.document(), None, resources.CUSTOM_SCHEME, self.errors, self.pep8, self.migration) if not syntaxLang: ext = file_manager.get_file_extension(self.ID) self.highlighter.apply_highlight( settings.EXTENSIONS.get(ext, 'python'), resources.CUSTOM_SCHEME) if self._mini: self._mini.highlighter.apply_highlight( settings.EXTENSIONS.get(ext, 'python'), resources.CUSTOM_SCHEME) else: self.highlighter.apply_highlight( syntaxLang, resources.CUSTOM_SCHEME) if self._mini: self._mini.highlighter.apply_highlight( syntaxLang, resources.CUSTOM_SCHEME)
def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: try: self.reset() source = self._neditor.text text = "[Error]: %s" # Compile into an AST and handle syntax errors try: tree = compile(source, self._path, "exec", _ast.PyCF_ONLY_AST) except SyntaxError as reason: if reason.text is None: logger.error("Syntax error") else: text = text % reason.args[0] range_ = helpers.get_range( self._neditor, reason.lineno - 1, reason.offset) self.checks[reason.lineno - 1].append((range_, text, "")) else: # Okay, now check it lint_checker = checker.Checker(tree, self._path) lint_checker.messages.sort(key=lambda msg: msg.lineno) source_lines = source.split('\n') for message in lint_checker.messages: lineno = message.lineno - 1 text = message.message % message.message_args range_ = helpers.get_range( self._neditor, lineno, message.col) self.checks[lineno].append( (range_, text, source_lines[lineno].strip())) except Exception as reason: logger.warning("Checker not finished: {}".format(reason)) self.checkerCompleted.emit()
def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) not_imports = dict() if file_ext in exts: self.reset() # source = self._editor.text path = self._editor.file_path checker = nic.Checker(path) not_imports = checker.get_not_imports_on_file( checker.get_imports()) if not_imports is None: pass else: for key, values in not_imports.items(): if isinstance(values['mod_name'], dict): for v in values['mod_name']: message = '[NOTIMP] {}: Dont exist'.format( v) else: message = '[NOTIMP] {}: Dont exist'.format( values['mod_name']) range_ = helpers.get_range( self._editor, values['lineno'] - 1) self.checks[values['lineno'] - 1].append( (range_, message, "")) self.checkerCompleted.emit()
def run(self): self.sleep(1) exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: self.reset() source = self._editor.get_text() tempData = pep8mod.run_check(self._path, source) i = 0 while i < len(tempData): lineno = -1 try: offset = 2 + len(file_ext) startPos = tempData[i].find('.%s:' % file_ext) + offset endPos = tempData[i].find(':', startPos) lineno = int(tempData[i][startPos:endPos]) - 1 error = tempData[i][tempData[i].find( ':', endPos + 1) + 2:] line = '\n'.join( [error, tempData[i + 1], tempData[i + 2]]) except Exception: line = '' finally: i += 3 if line and lineno > -1: if lineno not in self.checks: self.checks[lineno] = [line] else: message = self.checks[lineno] message += [line] self.checks[lineno] = message else: self.reset()
def open_file(self, filename='', cursorPosition=-1, tabIndex=None, positionIsLineNumber=False, ignore_checkers=False): logger.debug("will try to open %s" % filename) if not filename: logger.debug("has nofilename") if settings.WORKSPACE: directory = settings.WORKSPACE else: directory = os.path.expanduser("~") editorWidget = self.get_current_editor() ninjaide = IDE.get_service('ide') if ninjaide: current_project = ninjaide.get_current_project() if current_project is not None: directory = current_project elif editorWidget is not None and editorWidget.file_path: directory = file_manager.get_folder( editorWidget.file_path) extensions = ';;'.join([ '(*%s)' % e for e in settings.SUPPORTED_EXTENSIONS + ['.*', ''] ]) fileNames = list( QFileDialog.getOpenFileNames(self, self.tr("Open File"), directory, extensions)) else: logger.debug("has filename") fileNames = [filename] if not fileNames: return for filename in fileNames: if file_manager.get_file_extension(filename) in ('jpg', 'png'): logger.debug("will open as image") self.open_image(filename) elif file_manager.get_file_extension(filename).endswith('ui'): logger.debug("will load in ui editor") self.w = uic.loadUi(filename) self.w.show() else: logger.debug("will try to open") self.__open_file(filename, cursorPosition, tabIndex, positionIsLineNumber, ignore_checkers)
def insert_horizontal_line(editorWidget): line, index = editorWidget.getCursorPosition() lang = file_manager.get_file_extension(editorWidget.file_path) key = settings.EXTENSIONS.get(lang, 'python') comment_wildcard = settings.SYNTAX[key].get('comment', ['#'])[0] comment = comment_wildcard * ( (80 - editorWidget.lineLength(line) / len(comment_wildcard))) editorWidget.insertAt(comment, line, index)
def save_file_as(self): editorWidget = self.get_current_editor() if not editorWidget: return False try: filters = '(*.py);;(*.*)' if editorWidget.file_path: # existing file ext = file_manager.get_file_extension(editorWidget.file_path) if ext != 'py': filters = '(*.%s);;(*.py);;(*.*)' % ext save_folder = self._get_save_folder(editorWidget.file_path) fileName = QFileDialog.getSaveFileName(self._parent, self.tr("Save File"), save_folder, filters)[0] if not fileName: return False if settings.REMOVE_TRAILING_SPACES: helpers.remove_trailing_spaces(editorWidget) ext = file_manager.get_file_extension(fileName) if not ext: fileName = '%s.%s' % ( fileName, 'py', ) editorWidget.neditable.save_content(path=fileName) # editorWidget.register_syntax( # file_manager.get_file_extension(fileName)) self.fileSaved.emit(self.tr("File Saved: {}".format(fileName))) self.currentEditorChanged.emit(fileName) return True except file_manager.NinjaFileExistsException as ex: QMessageBox.information( self, self.tr("File Already Exists"), (self.tr("Invalid Path: the file '%s' " " already exists.") % ex.filename)) except Exception as reason: logger.error('save_file_as: %s', reason) QMessageBox.information(self, self.tr("Save Error"), self.tr("The file couldn't be saved!")) return False
def save_file_as(self, editor_widget=None): force = False if editor_widget is None: # We invoque from menu editor_widget = self.get_current_editor() if editor_widget is None: # We haven't editor in main container return False force = True try: filters = "(*.py);;(*.*)" if editor_widget.file_path is not None: # Existing file extension = file_manager.get_file_extension( editor_widget.file_path) if extension != 'py': filters = "(*.%s);;(*.py);;(*.*)" % extension save_folder = self._get_save_folder(editor_widget.file_path) else: save_folder = settings.WORKSPACE filename = QFileDialog.getSaveFileName( self, translations.TR_SAVE_FILE_DIALOG, save_folder, filters)[0] if not filename: return False # FIXME: remove trailing spaces extension = file_manager.get_file_extension(filename) if not extension: filename = "%s.%s" % (filename, "py") editor_widget.neditable.save_content(path=filename, force=force) # self._setter_language.set_language_from_extension(extension) self.fileSaved.emit(translations.TR_FILE_SAVED.format(filename)) self.currentEditorChanged.emit(filename) return True except file_manager.NinjaFileExistsException as reason: QMessageBox.information( self, translations.TR_FILE_ALREADY_EXISTS_TITLE, translations.TR_FILE_ALREADY_EXISTS_BODY.format( reason.filename)) except Exception as reason: logger.error("Save file as: %s", reason) QMessageBox.information(self, translations.TR_SAVE_FILE_ERROR_TITLE, translations.TR_SAVE_FILE_ERROR_BODY) return False
def insert_horizontal_line(editorWidget): editorWidget.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) text = editorWidget.textCursor().selection().toPlainText() editorWidget.moveCursor(QTextCursor.EndOfLine, QTextCursor.MoveAnchor) lang = file_manager.get_file_extension(editorWidget.file_path) key = settings.EXTENSIONS.get(lang, 'python') comment_wildcard = settings.SYNTAX[key].get('comment', ['#'])[0] comment = comment_wildcard * ((79 - len(text)) / len(comment_wildcard)) editorWidget.textCursor().insertText(comment)
def preview_in_browser(self): """Load the current html file in the default browser.""" editorWidget = self.get_current_editor() if editorWidget: if not editorWidget.file_path: self.save_file() ext = file_manager.get_file_extension(editorWidget.file_path) if ext in ('html', 'shpaml', 'handlebars', 'tpl'): webbrowser.open_new_tab(editorWidget.file_path)
def preview_in_browser(self): """Load the current html file in the default browser.""" editorWidget = self.get_current_editor() if editorWidget: if not editorWidget.file_path: self.save_file() ext = file_manager.get_file_extension(editorWidget.file_path) if ext == 'html': webbrowser.open(editorWidget.file_path)
def preview_in_browser(self): """Load the current html file in the default browser.""" editorWidget = self.get_current_editor() if editorWidget: if not editorWidget.ID: self.save_file() ext = file_manager.get_file_extension(editorWidget.ID) if ext == 'html': webbrowser.open(editorWidget.ID)
def insert_horizontal_line(editorWidget): editorWidget.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) text = editorWidget.textCursor().selection().toPlainText() editorWidget.moveCursor(QTextCursor.EndOfLine, QTextCursor.MoveAnchor) lang = file_manager.get_file_extension(editorWidget.ID) key = settings.EXTENSIONS.get(lang, 'python') comment_wildcard = settings.SYNTAX[key].get('comment', ['#'])[0] comment = comment_wildcard * ((79 - len(text)) / len(comment_wildcard)) editorWidget.textCursor().insertText(comment)
def open_file(self, filename='', line=-1, col=0, ignore_checkers=False): logger.debug("will try to open %s" % filename) if not filename: logger.debug("has nofilename") if settings.WORKSPACE: directory = settings.WORKSPACE else: directory = os.path.expanduser("~") editorWidget = self.get_current_editor() ninjaide = IDE.get_service('ide') if ninjaide: current_project = ninjaide.get_current_project() if current_project is not None: directory = current_project elif editorWidget is not None and editorWidget.file_path: directory = file_manager.get_folder( editorWidget.file_path) extensions = ';;'.join( ['{}(*{})'.format(e.upper()[1:], e) for e in settings.SUPPORTED_EXTENSIONS + ['.*', '']]) fileNames = QFileDialog.getOpenFileNames(self, self.tr("Open File"), directory, extensions)[0] else: logger.debug("has filename") fileNames = [filename] if not fileNames: return for filename in fileNames: image_extensions = ('bmp', 'gif', 'jpeg', 'jpg', 'png') if file_manager.get_file_extension(filename) in image_extensions: logger.debug("will open as image") self.open_image(filename) elif file_manager.get_file_extension(filename).endswith('ui'): logger.debug("will load in ui editor") self.w = uic.loadUi(filename) self.w.show() else: logger.debug("will try to open: " + filename) self.__open_file(filename, line, col, ignore_checkers)
def save_file_as(self, editor_widget=None): force = False if editor_widget is None: # We invoque from menu editor_widget = self.get_current_editor() if editor_widget is None: # We haven't editor in main container return False force = True try: filters = "(*.py);;(*.*)" if editor_widget.file_path is not None: # Existing file extension = file_manager.get_file_extension( editor_widget.file_path) if extension != 'py': filters = "(*.%s);;(*.py);;(*.*)" % extension save_folder = self._get_save_folder(editor_widget.file_path) filename = QFileDialog.getSaveFileName( self, "Save File", save_folder, filters )[0] if not filename: return False # FIXME: remove trailing spaces extension = file_manager.get_file_extension(filename) if not extension: filename = "%s.%s" % (filename, "py") editor_widget.neditable.save_content(path=filename, force=force) self._setter_language.set_language_from_extension(extension) self.fileSaved.emit("File Saved: {}".format(filename)) self.currentEditorChanged.emit(filename) return True except file_manager.NinjaFileExistsException as reason: QMessageBox.information( self, "File Already Exists", "Invalid Path: the file '%s' already exists." % reason.filename ) except Exception as reason: logger.error("save_file_as: %s", reason) QMessageBox.information( self, "Save Error", "The file couldn't be saved!" ) return False
def save_file_as(self): editorWidget = self.get_current_editor() if not editorWidget: return False try: filters = '(*.py);;(*.*)' if editorWidget.file_path: # existing file ext = file_manager.get_file_extension(editorWidget.file_path) if ext != 'py': filters = '(*.%s);;(*.py);;(*.*)' % ext save_folder = self._get_save_folder(editorWidget.file_path) fileName = QFileDialog.getSaveFileName( self._parent, self.tr("Save File"), save_folder, filters)[0] if not fileName: return False if settings.REMOVE_TRAILING_SPACES: helpers.remove_trailing_spaces(editorWidget) ext = file_manager.get_file_extension(fileName) if not ext: fileName = '%s.%s' % (fileName, 'py',) editorWidget.neditable.save_content(path=fileName) # editorWidget.register_syntax( # file_manager.get_file_extension(fileName)) self.fileSaved.emit(self.tr("File Saved: {}".format(fileName))) self.currentEditorChanged.emit(fileName) return True except file_manager.NinjaFileExistsException as ex: QMessageBox.information(self, self.tr("File Already Exists"), (self.tr("Invalid Path: the file '%s' " " already exists.") % ex.filename)) except Exception as reason: logger.error('save_file_as: %s', reason) QMessageBox.information(self, self.tr("Save Error"), self.tr("The file couldn't be saved!")) return False
def get_file_syntax(self, editorWidget=None): """Return the syntax for this file -> {}.""" if editorWidget is None: editorWidget = self._main.get_actual_editor() if editorWidget is not None: ext = file_manager.get_file_extension(editorWidget.ID) lang = settings.EXTENSIONS.get(ext, '') syntax = settings.SYNTAX.get(lang, {}) return syntax return {}
def get_file_syntax(self, editorWidget=None): """Return the syntax for this file -> {}.""" if editorWidget is None: editorWidget = self._main.get_current_editor() if editorWidget is not None: ext = file_manager.get_file_extension(editorWidget.ID) lang = settings.EXTENSIONS.get(ext, '') syntax = settings.SYNTAX.get(lang, {}) return syntax return {}
def get_symbols_for_class(self, file_path, clazzName): results = [] with open(file_path) as f: content = f.read() ext = file_manager.get_file_extension(file_path) #obtain a symbols handler for this file extension symbols_handler = handlers.get_symbols_handler(ext) symbols = symbols_handler.obtain_symbols(content, filename=file_path) self.__parse_symbols(symbols, results, file_path) return results
def get_symbols_for_class(self, file_path, clazzName): results = [] with open(file_path) as f: content = f.read() ext = file_manager.get_file_extension(file_path) #obtain a symbols handler for this file extension symbols_handler = settings.get_symbols_handler(ext) symbols = symbols_handler.obtain_symbols(content, filename=file_path) self.__parse_symbols(symbols, results, file_path) return results
def open_file( self, filename="", cursorPosition=-1, tabIndex=None, positionIsLineNumber=False, ignore_checkers=False ): logger.debug("will try to open %s" % filename) if not filename: logger.debug("has nofilename") if settings.WORKSPACE: directory = settings.WORKSPACE else: directory = os.path.expanduser("~") editorWidget = self.get_current_editor() ninjaide = IDE.get_service("ide") if ninjaide: current_project = ninjaide.get_current_project() if current_project is not None: directory = current_project elif editorWidget is not None and editorWidget.file_path: directory = file_manager.get_folder(editorWidget.file_path) extensions = ";;".join( ["{}(*{})".format(e.upper()[1:], e) for e in settings.SUPPORTED_EXTENSIONS + [".*", ""]] ) fileNames = list(QFileDialog.getOpenFileNames(self, self.tr("Open File"), directory, extensions)) else: logger.debug("has filename") fileNames = [filename] if not fileNames: return for filename in fileNames: if file_manager.get_file_extension(filename) in ("jpg", "png"): logger.debug("will open as image") self.open_image(filename) elif file_manager.get_file_extension(filename).endswith("ui"): logger.debug("will load in ui editor") self.w = uic.loadUi(filename) self.w.show() else: logger.debug("will try to open") self.__open_file(filename, cursorPosition, tabIndex, positionIsLineNumber, ignore_checkers)
def execute_file(self): """Execute the current file""" main_container = IDE.get_service("main_container") editor_widget = main_container.get_current_editor() if editor_widget is not None and (editor_widget.is_modified or editor_widget.file_path): main_container.save_file(editor_widget) # FIXME: Emit a signal for plugin! # self.fileExecuted.emit(editor_widget.file_path) file_path = editor_widget.file_path extension = file_manager.get_file_extension(file_path) # TODO: Remove the IF statment and use Handlers if extension == "py": self.start_process(filename=file_path)
def __post_execution(self): """Execute a script after executing the project.""" filePostExec = QFile(self.postExec) if filePostExec.exists() and \ bool(QFile.ExeUser & filePostExec.permissions()): ext = file_manager.get_file_extension(self.postExec) if not self.pythonExec: self.pythonExec = settings.PYTHON_PATH self.currentProcess = self._postExecScriptProc if ext == 'py': self._postExecScriptProc.start(self.pythonExec, [self.postExec]) else: self._postExecScriptProc.start(self.postExec)
def run(self): self.sleep(1) exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: self.checks = {} lineno = 0 lines_to_remove = [] lines_to_add = [] parsing_adds = False try: output = subprocess.check_output(self._command + [self._path]) output = output.split('\n') except OSError: settings.VALID_2TO3 = False return for line in output[2:]: if line.startswith('+'): lines_to_add.append(line) parsing_adds = True continue if parsing_adds: # Add in migration removes = '\n'.join([liner for _, liner in lines_to_remove]) adds = '\n'.join(lines_to_add) message = self.tr( 'The actual code looks like this:\n%s\n\n' 'For Python3 support should look like:\n%s' % (removes, adds)) lineno = -1 for nro, _ in lines_to_remove: if lineno == -1: lineno = nro self.checks[nro] = (message, lineno) parsing_adds = False lines_to_add = [] lines_to_remove = [] if line.startswith('-'): lines_to_remove.append((lineno, line)) lineno += 1 if line.startswith('@@'): lineno = int(line[line.index('-') + 1:line.index(',')]) - 1 tab_migration = IDE.get_service('tab_migration') if tab_migration: tab_migration.refresh_lists(self.checks)
def run(self): self.sleep(1) exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: self.checks = {} lineno = 0 lines_to_remove = [] lines_to_add = [] parsing_adds = False try: output = subprocess.check_output(self._command + [self._path]) output = output.split('\n') except OSError: settings.VALID_2TO3 = False return for line in output[2:]: if line.startswith('+'): lines_to_add.append(line) parsing_adds = True continue if parsing_adds: # Add in migration removes = '\n'.join([liner for _, liner in lines_to_remove]) adds = '\n'.join(lines_to_add) message = self.tr( 'The actual code looks like this:\n%s\n\n' 'For Python3 support, it should look like:\n%s' % (removes, adds)) lineno = -1 for nro, _ in lines_to_remove: if lineno == -1: lineno = nro self.checks[nro] = (message, lineno) parsing_adds = False lines_to_add = [] lines_to_remove = [] if line.startswith('-'): lines_to_remove.append((lineno, line)) lineno += 1 if line.startswith('@@'): lineno = int(line[line.index('-') + 1:line.index(',')]) - 1 tab_migration = IDE.get_service('tab_migration') if tab_migration: tab_migration.refresh_lists(self.checks)
def create_editor(neditable, syntax=None): editor = Editor(neditable) #if syntax is specified, use it if syntax: editor.register_syntax(syntax) else: #try to set a syntax based on the file extension ext = file_manager.get_file_extension(neditable.ID) if ext not in settings.EXTENSIONS and neditable.ID == '': #by default use python syntax editor.register_syntax('py') else: editor.register_syntax(ext) return editor
def execute_file(self): """Execute the current file""" main_container = IDE.get_service("main_container") editor_widget = main_container.get_current_editor() if editor_widget is not None and (editor_widget.is_modified or editor_widget.file_path): main_container.save_file(editor_widget) file_path = editor_widget.file_path if file_path is None: return # Emit signal for plugin! self.fileExecuted.emit(editor_widget.file_path) extension = file_manager.get_file_extension(file_path) # TODO: Remove the IF statment and use Handlers if extension == "py": self.start_process(filename=file_path)
def execute_file(self): """Execute the current file.""" main_container = IDE.get_service('main_container') if not main_container: return editorWidget = main_container.get_current_editor() if editorWidget: #emit a signal for plugin! self.emit(SIGNAL("fileExecuted(QString)"), editorWidget.file_path) main_container.save_file(editorWidget) ext = file_manager.get_file_extension(editorWidget.file_path) #TODO: Remove the IF statment with polymorphism using Handler if ext == 'py': self.run_application(editorWidget.ID) elif ext == 'html': self.render_web_page(editorWidget.ID)
def __pre_execution(self): """Execute a script before executing the project.""" filePreExec = QFile(self.preExec) if filePreExec.exists() and \ bool(QFile.ExeUser & filePreExec.permissions()): ext = file_manager.get_file_extension(self.preExec) if not self.pythonPath: self.pythonPath = settings.PYTHON_PATH self.currentProcess = self._preExecScriptProc self.__preScriptExecuted = True if ext == 'py': self._preExecScriptProc.start(self.pythonPath, [self.preExec]) else: self._preExecScriptProc.start(self.preExec) else: self.__main_execution()
def execute_file(self): """Execute the current file.""" main_container = IDE.get_service('main_container') if not main_container: return editorWidget = main_container.get_current_editor() if editorWidget: #emit a signal for plugin! self.fileExecuted.emit(editorWidget.file_path) main_container.save_file(editorWidget) ext = file_manager.get_file_extension(editorWidget.file_path) #TODO: Remove the IF statment and use Handlers if ext == 'py': self._run_application(editorWidget.file_path) elif ext == 'html': self.render_web_page(editorWidget.file_path)
def insert_title_comment(editorWidget): result = str( QInputDialog.getText(editorWidget, editorWidget.tr("Title Comment"), editorWidget.tr("Enter the Title Name:"))[0]) if result: line, index = editorWidget.getCursorPosition() lang = file_manager.get_file_extension(editorWidget.file_path) key = settings.EXTENSIONS.get(lang, 'python') comment_wildcard = settings.SYNTAX[key].get('comment', ['#'])[0] comment = comment_wildcard * (80 / len(comment_wildcard)) editorWidget.SendScintilla(editorWidget.SCI_BEGINUNDOACTION, 1) editorWidget.insertAt(comment, line, index) text = "%s %s\n" % (comment_wildcard, result) editorWidget.insertAt(text, line + 1, 0) editorWidget.insertAt("\n", line + 2, 0) editorWidget.insertAt(comment, line + 2, index) editorWidget.SendScintilla(editorWidget.SCI_ENDUNDOACTION, 1)
def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: self.reset() source = self._editor.text path = self._editor.file_path pep8_style = pycodestyle.StyleGuide(parse_argv=False, config_file='', checker_class=CustomChecker) temp_data = pep8_style.input_file(path, lines=source.splitlines(True)) for lineno, col, code, text in temp_data: # for lineno, offset, code, text, doc in temp_data: message = '[PEP8] %s: %s' % (code, text) self.checks[lineno - 1] = (message, col) self.checkerCompleted.emit()
def run(self): self.sleep(1) exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: try: self.reset() source = self._editor.text() if self._encoding is not None: source = source.encode(self._encoding) tree = compile(source, self._path, "exec", _ast.PyCF_ONLY_AST) #parseResult = compiler.parse(source) lint_checker = checker.Checker(tree, self._path, builtins=self._builtins) for m in lint_checker.messages: lineno = m.lineno - 1 if lineno not in self.checks: message = [m.message % m.message_args] else: message = self.checks[lineno] message += [m.message % m.message_args] self.checks[lineno] = message except Exception as reason: message = '' if hasattr(reason, 'msg'): message = reason.msg else: message = reason.message if hasattr(reason, 'lineno') and reason.lineno: self.checks[reason.lineno - 1] = [message] else: self.checks[0] = [message] finally: ignored_range, ignored_lines = self._get_ignore_range() to_remove = [ x for x in self.checks for r in ignored_range if r[0] < x < r[1] ] to_remove += ignored_lines for line in to_remove: self.checks.pop(line, None) else: self.reset() self.checkerCompleted.emit()
def _grep_file_symbols(self, file_path, file_name): # type - file_name - file_path global mapping_symbols exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(file_path) if file_ext not in exts: mapping_symbols[file_path] = [ ResultItem(symbol_type=FILTERS['non-python'], name=file_name, path=file_path, lineno=-1) ] else: mapping_symbols[file_path] = [ ResultItem(symbol_type=FILTERS['files'], name=file_name, path=file_path, lineno=-1) ] data = self._get_file_symbols(file_path) # FIXME: stat not int mtime = int(os.stat(file_path).st_mtime) if data is not None and (mtime == int(data[1])): try: results = pickle.loads(data[2]) mapping_symbols[file_path] += results return except BaseException: print("ResultItem couldn't be loaded, let's analyze it again'") # obtain a symbols handler for this file extension lang = settings.LANGUAGE_MAP.get(file_ext) symbols_handler = handlers.get_symbols_handler(lang) if symbols_handler is None: return results = [] with open(file_path) as f: content = f.read() symbols = symbols_handler.obtain_symbols(content, filename=file_path) self.__parse_symbols(symbols, results, file_path) if results: self._save_file_symbols(file_path, mtime, results) mapping_symbols[file_path] += results
def insert_title_comment(editorWidget): result = str(QInputDialog.getText(editorWidget, editorWidget.tr("Title Comment"), editorWidget.tr("Enter the Title Name:"))[0]) if result: editorWidget.textCursor().beginEditBlock() editorWidget.moveCursor(QTextCursor.StartOfLine, QTextCursor.MoveAnchor) lang = file_manager.get_file_extension(editorWidget.ID) key = settings.EXTENSIONS.get(lang, 'python') comment_wildcard = settings.SYNTAX[key].get('comment', ['#'])[0] comment = comment_wildcard * (79 / len(comment_wildcard)) editorWidget.textCursor().insertText(comment) editorWidget.textCursor().insertBlock() editorWidget.textCursor().insertText(comment_wildcard + ' ' + result) editorWidget.textCursor().insertBlock() editorWidget.textCursor().insertText(comment) editorWidget.textCursor().insertBlock() editorWidget.textCursor().endEditBlock()
def __post_execution(self): """Execute a script after executing the project.""" self.__current_process = self.post_process file_pre_exec = QFile(self.post_script) if file_pre_exec.exists(): ext = file_manager.get_file_extension(self.post_script) args = [] if ext == "py": program = self.python_exec # -u: Force python to unbuffer stding ad stdout args.append("-u") args.append(self.post_script) elif ext == "sh": program = "bash" args.append(self.post_script) else: program = self.post_script self.post_process.setProgram(program) self.post_process.setArguments(args) self.post_process.start()
def run(self): self.sleep(1) exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: self.reset() source = self._editor.text() tempData = pycodestylemod.run_check(self._path, source) for result in tempData: message = "\n".join( ("%s %s" % (result["code"], result["text"]), result["line"], result["pointer"])) if result["line_number"] not in self.checks: self.checks[result["line_number"]] = [message] else: original = self.checks[result["line_number"]] original += [message] self.checks[result["line_number"]] = original else: self.reset() self.checkerCompleted.emit()
def _grep_file_symbols(self, file_path, file_name): #type - file_name - file_path global mapping_symbols exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(file_path) if file_ext not in exts: mapping_symbols[file_path] = [ ResultItem(type=FILTERS['non-python'], name=file_name, path=file_path, lineno=-1) ] else: mapping_symbols[file_path] = [ ResultItem(type=FILTERS['files'], name=file_name, path=file_path, lineno=-1) ] data = self._get_file_symbols(file_path) #FIXME: stat not int mtime = int(os.stat(file_path).st_mtime) if data is not None and (mtime == int(data[1])): results = pickle.loads(str(data[2])) mapping_symbols[file_path] += results return #obtain a symbols handler for this file extension symbols_handler = handlers.get_symbols_handler(file_ext) if symbols_handler is None: return results = [] with open(file_path) as f: content = f.read() symbols = symbols_handler.obtain_symbols(content, filename=file_path) self.__parse_symbols(symbols, results, file_path) if results: self._save_file_symbols(file_path, mtime, results) mapping_symbols[file_path] += results
def uncomment(editorWidget): lstart, istart, lend, iend = editorWidget.getSelection() lang = file_manager.get_file_extension(editorWidget.file_path) key = settings.EXTENSIONS.get(lang, 'python') same_line = (lstart == lend) comment_line_wildcard = settings.SYNTAX[key].get('comment', []) comment_multi_wildcard = settings.SYNTAX[key].get('multiline_comment', {}) comment_wildcard = comment_multi_wildcard if (same_line and comment_line_wildcard): comment_wildcard = comment_line_wildcard elif comment_line_wildcard: comment_wildcard = comment_line_wildcard is_multi = comment_wildcard == comment_multi_wildcard if is_multi: wildopen = comment_wildcard["open"] wildclose = comment_wildcard["close"] else: wildopen = comment_wildcard[0] if same_line: lstart, _ = editorWidget.getCursorPosition() lines = 1 else: lines = (lend - lstart) + 1 editorWidget.SendScintilla(editorWidget.SCI_BEGINUNDOACTION, 1) for l in range(lines): index = len(get_indentation(editorWidget.text(lstart + l))) editorWidget.setSelection(lstart + l, index, lstart + l, index + len(wildopen)) if editorWidget.selectedText() == wildopen: editorWidget.removeSelectedText() if is_multi: length = editorWidget.lineLength(lstart + l) editorWidget.setSelection(lstart + l, length, lstart + l, index - len(wildclose)) if editorWidget.selectedText() == wildopen: editorWidget.removeSelectedText() editorWidget.SendScintilla(editorWidget.SCI_ENDUNDOACTION, 1)
def uncomment(editorWidget): #cursor is a COPY all changes do not affect the QPlainTextEdit's cursor!!! cursor = editorWidget.textCursor() block_start = editorWidget.document().findBlock( cursor.selectionStart()) block_end = editorWidget.document().findBlock( cursor.selectionEnd()).next() lang = file_manager.get_file_extension(editorWidget.ID) key = settings.EXTENSIONS.get(lang, 'python') same_line = (block_start == block_end.previous()) funcs = {'comment': uncomment_single_line, 'multiline_comment': uncomment_multiple_lines} comment_line_wildcard = settings.SYNTAX[key].get('comment', []) comment_multi_wildcard = settings.SYNTAX[key].get('multiline_comment', {}) option = 'multiline_comment' comment_wildcard = comment_multi_wildcard if ((same_line and comment_line_wildcard) or not (same_line or comment_multi_wildcard)): option = 'comment' comment_wildcard = comment_line_wildcard f = funcs[option] f(cursor, block_start, block_end, comment_wildcard)
def execute_file(self): """Execute the current file""" main_container = IDE.get_service("main_container") editor_widget = main_container.get_current_editor() if editor_widget is not None and (editor_widget.is_modified or editor_widget.file_path): main_container.save_file(editor_widget) # FIXME: Emit a signal for plugin! # self.fileExecuted.emit(editor_widget.file_path) file_path = editor_widget.file_path extension = file_manager.get_file_extension(file_path) # TODO: Remove the IF statment and use Handlers if extension == "py": self.start_process(filename=file_path) elif extension == "java": if os.name == 'posix': self.RunMacJavaProgram( file_path ) #thats where my code starts see the RunJavProgram Function below elif os.name == 'nt': self.runWindowsJavaProgram(file_path) '''# Run .c file