text
stringlengths
18
773k
def _cursor_back(self, value): """ Moves the cursor back. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Left, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.positio...
def _cursor_forward(self, value): """ Moves the cursor forward. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor....
def _delete_chars(self, value): """ Deletes the specified number of charachters. """ value = int(value) if value <= 0: value = 1 for i in range(value): self._cursor.deleteChar() self._text_edit.setTextCursor(self._cursor) self._last...
def get_package_info(package): """Gets the PyPI information for a given package.""" url = 'https://pypi.python.org/pypi/{}/json'.format(package) r = requests.get(url) r.raise_for_status() return r.json()
def read_requirements(req_file): """Reads a requirements file. Args: req_file (str): Filename of requirements file """ items = list(parse_requirements(req_file, session={})) result = [] for item in items: # Get line number from item line_number = item.comes_from.split(r...
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return Tr...
def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be updated.'.format(req)) return req, None if _...
def write_requirements(reqs_linenum, req_file): """Writes a list of req objects out to a given file.""" with open(req_file, 'r') as input: lines = input.readlines() for req in reqs_linenum: line_num = int(req[1]) if hasattr(req[0], 'link'): lines[line_num - 1] = '{}\n'....
def check_req(req): """Checks if a given req is the latest version available.""" if not isinstance(req, Requirement): return None info = get_package_info(req.name) newest_version = _get_newest_version(info) if _is_pinned(req) and _is_version_range(req): return None current_spe...
def check_requirements_file(req_file, skip_packages): """Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore. """ reqs = read_requirements(req_file) if skip_packages is not None: reqs...
def update_command(args): """Updates all dependencies the specified requirements file.""" updated = update_requirements_file( args.requirements_file, args.skip_packages) if updated: print('Updated requirements in {}:'.format(args.requirements_file)) for item in updated: ...
def check_command(args): """Checks that all dependencies in the specified requirements file are up to date.""" outdated = check_requirements_file(args.requirements_file, args.skip_packages) if outdated: print('Requirements in {} are out of date:'.format( ...
def paintEvent(self, event): """ Fills the panel background. """ super(EncodingPanel, self).paintEvent(event) if self.isVisible(): # fill background painter = QtGui.QPainter(self) self._background_brush = QtGui.QBrush(self._color) painter.fillRect(...
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() items = list(style.style_for_token(token).items()) for key, value in items: if value is None and key == 'color': ...
def _get_color(color): """ Returns a QColor built from a Pygments color string. """ color = str(color).replace("#", "") qcolor = QtGui.QColor() qcolor.setRgb(int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16)) r...
def refresh_editor(self, color_scheme): """ Refresh editor settings (background and highlight colors) when color scheme changed. :param color_scheme: new color scheme. """ self.editor.background = color_scheme.background self.editor.foreground = color_scheme.form...
def rehighlight(self): """ Rehighlight the entire document, may be slow. """ start = time.time() QtWidgets.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) try: super(SyntaxHighlighter, self).rehighlight() except Runtime...
def line_number_area_width(self): """ Computes the lineNumber area width depending on the number of lines in the document :return: Widtg """ digits = 1 count = max(1, self.editor.blockCount()) while count >= 10: count /= 10 digits ...
def mousePressEvent(self, e): """ Starts selecting """ self._selecting = True self._sel_start = e.pos().y() start = end = TextHelper(self.editor).line_nbr_from_position( self._sel_start) self._start_line = start TextHelper(self.editor).select_l...
def set_editor(self, editor): """ Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit """ try: self._editor.cursorPositionChanged.disconnect(self.sync) except (AttributeError, TypeError, RuntimeError, Refe...
def _on_changed(self): """ Update the tree items """ self._updating = True to_collapse = [] self.clear() if self._editor and self._outline_mode and self._folding_panel: items, to_collapse = self.to_tree_widget_items( self._outline_mode....
def _on_item_clicked(self, item): """ Go to the item position in the editor. """ if item: name = item.data(0, QtCore.Qt.UserRole) if name: go = name.block.blockNumber() helper = TextHelper(self._editor) if helper.cur...
def to_tree_widget_items(self, definitions, to_collapse=None): """ Converts the list of top level definitions to a list of top level tree items. """ def flatten(definitions): """ Flattens the document structure tree as a simple sequential list. ...
def symbol_pos(self, cursor, character_type=OPEN, symbol_type=PAREN): """ Find the corresponding symbol position (line, column) of the specified symbol. If symbol type is PAREN and character_type is OPEN, the function will look for '('. :param cursor: QTextCursor :param ...
def do_symbols_matching(self): """ Performs symbols matching. """ self._clear_decorations() current_block = self.editor.textCursor().block() data = get_block_symbol_data(self.editor, current_block) pos = self.editor.textCursor().block().position() for symb...
def set_button_visible(self, visible): """ Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden). """ self.button.setVisible(visible) left, top, right, bottom = self.getTextMargins() if visible: right = se...
def import_class(klass): """ Imports a class from a fully qualified name string. :param klass: class string, e.g. "pyqode.core.backend.workers.CodeCompletionWorker" :return: The corresponding class """ path = klass.rfind(".") class_name = klass[path + 1: len(klass)] try: ...
def serve_forever(args=None): """ Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments. """ class Unbuffered(object): def _...
def _create_actions(self): """ Create associated actions """ self.action_to_lower = QtWidgets.QAction(self.editor) self.action_to_lower.triggered.connect(self.to_lower) self.action_to_upper = QtWidgets.QAction(self.editor) self.action_to_upper.triggered.connect(self.to_upper) ...
def _select_word_cursor(self): """ Selects the word under the mouse cursor. """ cursor = TextHelper(self.editor).word_under_mouse_cursor() if (self._previous_cursor_start != cursor.selectionStart() and self._previous_cursor_end != cursor.selectionEnd()): self._remove_...
def _on_mouse_moved(self, event): """ mouse moved callback """ if event.modifiers() & QtCore.Qt.ControlModifier: cursor = TextHelper(self.editor).word_under_mouse_cursor() if (not self._cursor or cursor.position() != self._cursor.position()): s...
def _on_mouse_released(self, event): """ mouse pressed callback """ if event.button() == 1 and self._deco: cursor = TextHelper(self.editor).word_under_mouse_cursor() if cursor and cursor.selectedText(): self._timer.request_job( self.word_clicke...
def _add_decoration(self, cursor): """ Adds a decoration for the word under ``cursor``. """ if self._deco is None: if cursor.selectedText(): self._deco = TextDecoration(cursor) if self.editor.background.lightness() < 128: se...
def _remove_decoration(self): """ Removes the word under cursor's decoration """ if self._deco is not None: self.editor.decorations.remove(self._deco) self._deco = None
def date(date): """DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime`` type and the format changes between DokuWiki versions ... This function convert *date* to a `datetime` object. """ date = date.value return (datetime.strptime(date[:-5], '%Y-%m-%dT%H:%M:%S') if len(...
def utc2local(date): """DokuWiki returns date with a +0000 timezone. This function convert *date* to the local time. """ date_offset = (datetime.now() - datetime.utcnow()) # Python < 2.7 don't have the 'total_seconds' method so calculate it by hand! date_offset = (date_offset.microseconds + ...
def parse_response(self, response): """parse and store cookie""" try: for header in response.msg.get_all("Set-Cookie"): cookie = header.split(";", 1)[0] cookieKey, cookieValue = cookie.split("=", 1) self._cookies[cookieKey] = cookieValue ...
def parse_response(self, response): """parse and store cookie""" try: for header in response.getheader("set-cookie").split(", "): # filter 'expire' information if not header.startswith("D"): continue cookie = header.split(";...
def send(self, command, *args, **kwargs): """Generic method for executing an XML-RPC *command*. *args* and *kwargs* are the arguments and parameters needed by the command. """ args = list(args) if kwargs: args.append(kwargs) method = self.proxy for el...
def add_acl(self, scope, user, permission): """Add an `ACL <https://www.dokuwiki.org/acl>`_ rule that restricts the page/namespace *scope* to *user* (use *@group* syntax for groups) with *permission* level. It returns a boolean that indicate if the rule was correctly added. """ ...
def info(self, page, version=None): """Returns informations of *page*. Informations of the last version is returned if *version* is not set. """ return (self._dokuwiki.send('wiki.getPageInfoVersion', page, version) if version is not None else self._dokuwik...
def get(self, page, version=None): """Returns the content of *page*. The content of the last version is returned if *version* is not set. """ return (self._dokuwiki.send('wiki.getPageVersion', page, version) if version is not None else self._dokuwiki.send(...
def append(self, page, content, **options): """Appends *content* text to *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change """ return self._dokuwiki.send('dokuwiki.appendPage', page, content, options)
def html(self, page, version=None): """Returns HTML content of *page*. The HTML content of the last version of the page is returned if *version* is not set. """ return (self._dokuwiki.send('wiki.getPageHTMLVersion', page, version) if version is not None el...
def set(self, page, content, **options): """Set/replace the *content* of *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change """ try: return self._dokuwiki.send('wiki.putPage', page, content, op...
def lock(self, page): """Locks *page*.""" result = self._dokuwiki.send('dokuwiki.setLocks', lock=[page], unlock=[]) if result['lockfail']: raise DokuWikiError('unable to lock page')
def get(self, media, dirpath=None, filename=None, overwrite=False, b64decode=False): """Returns the binary data of *media* or save it to a file. If *dirpath* is not set the binary data is returned, otherwise the data is saved to a file. By default, the filename is the name of the media but it ca...
def add(self, media, filepath, overwrite=True): """Set *media* from local file *filepath*. *overwrite* parameter specify if the media must be overwrite if it exists remotely. """ with open(filepath, 'rb') as fhandler: self._dokuwiki.send('wiki.putAttachment', media, ...
def set(self, media, _bytes, overwrite=True, b64encode=False): """Set *media* from *_bytes*. *overwrite* parameter specify if the media must be overwrite if it exists remotely. """ data = base64.b64encode(_bytes) if b64encode else Binary(_bytes) self._dokuwiki.send('wiki.putAttac...
def get(content, keep_order=False): """Get dataentry from *content*. *keep_order* indicates whether to return an ordered dictionnay.""" if keep_order: from collections import OrderedDict dataentry = OrderedDict() else: dataentry = {} found = F...
def gen(name, data): """Generate dataentry *name* from *data*.""" return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join( '%s:%s' % (attr, value) for attr, value in data.items()))
def ignore(content): """Remove dataentry from *content*.""" page_content = [] start = False for line in content.split('\n'): if line == '----' and not start: start = True continue if start: page_content.append(line) ...
def _draw_messages(self, painter): """ Draw messages from all subclass of CheckerMode currently installed on the editor. :type painter: QtGui.QPainter """ checker_modes = [] for m in self.editor.modes: if isinstance(m, modes.CheckerMode): ...
def _draw_visible_area(self, painter): """ Draw the visible area. This method does not take folded blocks into account. :type painter: QtGui.QPainter """ if self.editor.visible_blocks: start = self.editor.visible_blocks[0][-1] end = self.editor.v...
def paintEvent(self, event): """ Pains the messages and the visible area on the panel. :param event: paint event infos """ if self.isVisible(): # fill background self._background_brush = QtGui.QBrush(self.editor.background) painter = QtGui.QPai...
def get_marker_height(self): """ Gets the height of message marker. """ return self.editor.viewport().height() / TextHelper( self.editor).line_count()
def get_marker_size(self): """ Gets the size of a message marker. :return: QSize """ h = self.get_marker_height() if h < 1: h = 1 return QtCore.QSize(self.sizeHint().width() / 2, h)
def mimetype_icon(path, fallback=None): """ Tries to create an icon from theme using the file mimetype. E.g.:: return self.mimetype_icon( path, fallback=':/icons/text-x-python.png') :param path: file path for which the icon must be created :param fa...
def main(options): """A simple connection test to login and print the server time.""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) print(client.si.CurrentTime()) client.logout()
def marker_for_line(self, line): """ Returns the marker that is displayed at the specified line number if any. :param line: The marker line. :return: Marker of None :rtype: pyqode.core.Marker """ block = self.editor.document().findBlockByNumber(line) ...
def main(): """ pyqode-console main function. """ global program, args, ret print(os.getcwd()) ret = 0 if '--help' in sys.argv or '-h' in sys.argv or len(sys.argv) == 1: print(__doc__) else: program = sys.argv[1] args = sys.argv[2:] if args: re...
def linkcode_resolve(domain, info): """A simple function to find matching source code.""" module_name = info['module'] fullname = info['fullname'] attribute_name = fullname.split('.')[-1] base_url = 'https://github.com/fmenabe/python-dokuwiki/blob/' if release.endswith('-dev'): base_url...
def pick_free_port(): """ Picks a free port """ test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) test_socket.bind(('127.0.0.1', 0)) free_port = int(test_socket.getsockname()[1]) test_socket.close() return free_port
def start(self, script, interpreter=sys.executable, args=None, error_callback=None, reuse=False): """ Starts the backend process. The backend is a python script that starts a :class:`pyqode.core.backend.JsonServer`. You must write the backend script so that you can...
def stop(self): """ Stops the backend process. """ if self._process is None: return if self._shared: BackendManager.SHARE_COUNT -= 1 if BackendManager.SHARE_COUNT: return comm('stopping backend process') # close ...
def send_request(self, worker_class_or_function, args, on_receive=None): """ Requests some work to be done by the backend. You can get notified of the work results by passing a callback (on_receive). :param worker_class_or_function: Worker class or function :param args: worker a...
def running(self): """ Tells whether the backend process is running. :return: True if the process is running, otherwise False """ try: return (self._process is not None and self._process.state() != self._process.NotRunning) except RuntimeE...
def remove(self, filename): """ Remove a file path from the list of recent files. :param filename: Path of the file to remove """ files = self.get_value('list', []) files.remove(filename) self.set_value('list', files) self.updated.emit()
def get_value(self, key, default=None): """ Reads value from QSettings :param key: value key :param default: default value. :return: value """ def unique(seq, idfun=None): if idfun is None: def idfun(x): return x ...
def set_value(self, key, value): """ Set the recent files value in QSettings. :param key: value key :param value: new value """ if value is None: value = [] value = [os.path.normpath(pth) for pth in value] self._settings.setValue('recent_files/...
def get_recent_files(self): """ Gets the list of recent files. (files that do not exists anymore are automatically filtered) """ ret_val = [] files = self.get_value('list', []) # filter files, remove files that do not exist anymore for file in files: ...
def open_file(self, file): """ Adds a file to the list (and move it to the top of the list if the file already exists) :param file: file path to add the list of recent files. """ files = self.get_recent_files() try: files.remove(file) except ...
def update_actions(self): """ Updates the list of actions. """ self.clear() self.recent_files_actions[:] = [] for file in self.manager.get_recent_files(): action = QtWidgets.QAction(self) action.setText(os.path.split(file)[1]) action.se...
def clear_recent_files(self): """ Clear recent files and menu. """ self.manager.clear() self.update_actions() self.clear_requested.emit()
def _on_action_triggered(self): """ Emits open_requested when a recent file action has been triggered. """ action = self.sender() assert isinstance(action, QtWidgets.QAction) path = action.data() self.open_requested.emit(path) self.update_actions()
def append(self, panel, position=Panel.Position.LEFT): """ Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel """ assert panel is not None pos_to_string ...
def remove(self, name_or_klass): """ Removes the specified panel. :param name_or_klass: Name or class of the panel to remove. :return: The removed panel """ _logger().log(5, 'removing panel %r', name_or_klass) panel = self.get(name_or_klass) panel.on_unin...
def get(self, name_or_klass): """ Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance. """ if not isinstance(name_or_klass, str): name_or_klass = name_or_klass.__name__ fo...
def refresh(self): """ Refreshes the editor panels (resize and update margins) """ _logger().log(5, 'refresh_panels') self.resize() self._update(self.editor.contentsRect(), 0, force_update_margins=True)
def _update(self, rect, delta_y, force_update_margins=False): """ Updates panels """ helper = TextHelper(self.editor) if not self: return for zones_id, zone in self._panels.items(): if zones_id == Panel.Position.TOP or \ zones_id == Panel.Position.B...
def icon(theme_name='', path='', qta_name='', qta_options=None, use_qta=None): """ Creates an icon from qtawesome, from theme or from path. :param theme_name: icon name in the current theme (GNU/Linux only) :param path: path of the icon (from file system or qrc) :param qta_name: icon name in qtawes...
def set_outline(self, color): """ Uses an outline rectangle. :param color: Color of the outline rect :type color: QtGui.QColor """ self.format.setProperty(QtGui.QTextFormat.OutlinePen, QtGui.QPen(color))
def set_full_width(self, flag=True, clear=True): """ Enables FullWidthSelection (the selection does not stops at after the character instead it goes up to the right side of the widget). :param flag: True to use full width selection. :type flag: bool :param clear: True t...
def compile(self, script, bare=False): '''compile a CoffeeScript code to a JavaScript code. if bare is True, then compile the JavaScript without the top-level function safety wrapper (like the coffee command). ''' if not hasattr(self, '_context'): self._context = sel...
def compile_file(self, filename, encoding="utf-8", bare=False): '''compile a CoffeeScript script file to a JavaScript code. filename can be a list or tuple of filenames, then contents of files are concatenated with line feeds. if bare is True, then compile the JavaScript without the to...
def setup_actions(self): """ Connects slots to signals """ self.actionOpen.triggered.connect(self.on_open) self.actionNew.triggered.connect(self.on_new) self.actionSave.triggered.connect(self.on_save) self.actionSave_as.triggered.connect(self.on_save_as) self.actionQuit.t...
def setup_recent_files_menu(self): """ Setup the recent files menu and manager """ self.recent_files_manager = widgets.RecentFilesManager( 'pyQode', 'notepad') self.menu_recents = widgets.MenuRecentFiles( self.menuFile, title='Recents', recent_files_manager=se...
def setup_mimetypes(self): """ Setup additional mime types. """ # setup some specific mimetypes mimetypes.add_type('text/xml', '.ui') # qt designer forms forms mimetypes.add_type('text/x-rst', '.rst') # rst docs mimetypes.add_type('text/x-cython', '.pyx') # cython impl files ...
def open_file(self, path): """ Creates a new GenericCodeEdit, opens the requested file and adds it to the tab widget. :param path: Path of the file to open """ if path: editor = self.tabWidget.open_document(path) editor.cursorPositionChanged.conne...
def on_new(self): """ Add a new empty code editor to the tab widget """ editor = self.tabWidget.create_new_document() editor.cursorPositionChanged.connect(self.on_cursor_pos_changed) self.refresh_color_scheme()
def on_open(self): """ Shows an open file dialog and open the file if the dialog was accepted. """ filename, filter = QtWidgets.QFileDialog.getOpenFileName( self, _('Open')) if filename: self.open_file(filename)
def on_save_as(self): """ Save the current editor document as. """ self.tabWidget.save_current_as() self._update_status_bar(self.tabWidget.current_widget())
def tab_under_menu(self): """ Returns the tab that sits under the context menu. :return: QWidget """ if self._menu_pos: return self.tabBar().tabAt(self._menu_pos) else: return self.currentIndex()
def close_others(self): """ Closes every editors tabs except the current one. """ current_widget = self.widget(self.tab_under_menu()) if self._try_close_dirty_tabs(exept=current_widget): i = 0 while self.count() > 1: widget = self.widget(i)...
def close_left(self): """ Closes every editors tabs on the left of the current one. """ current_widget = self.widget(self.tab_under_menu()) index = self.indexOf(current_widget) if self._try_close_dirty_tabs(tab_range=range(index)): while True: ...
def close_right(self): """ Closes every editors tabs on the left of the current one. """ current_widget = self.widget(self.tab_under_menu()) index = self.indexOf(current_widget) if self._try_close_dirty_tabs(tab_range=range(index + 1, self.count())): while Tru...
def close_all(self): """ Closes all editors """ if self._try_close_dirty_tabs(): while self.count(): widget = self.widget(0) self.remove_tab(0) self.tab_closed.emit(widget) return True return False
def _collect_dirty_tabs(self, skip=None, tab_range=None): """ Collects the list of dirty tabs :param skip: Tab to skip (used for close_others). """ widgets = [] filenames = [] if tab_range is None: tab_range = range(self.count()) for i in tab_...
def _close_widget(widget): """ Closes the given widgets and handles cases where the widget has been clone or is a clone of another widget """ if widget is None: return try: widget.document().setParent(None) widget.syntax_highlighter.set...
def remove_tab(self, index): """ Overrides removeTab to emit tab_closed and last_tab_closed signals. :param index: index of the tab to remove. """ widget = self.widget(index) try: document = widget.document() except AttributeError: documen...