示例#1
0
def insert_snippet(text, cursor, variables):
    """Inserts a normal text snippet.
    
    After the insert, the cursor points to the end of the inserted snippet.
    
    If this function returns a cursor it must be set as the cursor for the view
    after the snippet has been inserted.
    
    """
    exp_base = expand.Expander(cursor)
    
    evs = [] # make a list of events, either text or a constant
    for text, key in snippets.expand(text):
        if text:
            evs.append(text)
        if key == '$':
            evs.append('$')
        elif key:
            # basic variables
            func = getattr(exp_base, key, None)
            if func:
                evs.append(func())
    
    selectionUsed = expand.SELECTION in evs
    # do the padding if 'selection: strip;' is used
    if selectionUsed and 'strip' in variables.get('selection', ''):
        space = '\n' if '\n' in cursor.selection().toPlainText() else ' '
        # change whitespace in previous and next piece of text
        i = evs.index(expand.SELECTION)
        for j in range(i-1, -i, -1):
            if evs[j] not in expand.constants:
                evs[j] = evs[j].rstrip() + space
                break
        for j in range(i+1, len(evs)):
            if evs[j] not in expand.constants:
                evs[j] = space + evs[j].lstrip()
                break
    # now insert the text
    ins = QTextCursor(cursor)
    selectionUsed and ins.setPosition(cursor.selectionStart())
    a, c = -1, -1
    for e in evs:
        if e == expand.ANCHOR:
            a = ins.position()
        elif e == expand.CURSOR:
            c = ins.position()
        elif e == expand.SELECTION:
            ins.setPosition(cursor.selectionEnd())
        else:
            ins.insertText(e)
    cursor.setPosition(ins.position())
    # return a new cursor if requested
    if (a, c) != (-1, -1):
        new = QTextCursor(cursor)
        if a != -1:
            new.setPosition(a)
        if c != -1:
            new.setPosition(c, QTextCursor.KeepAnchor if a != -1 else QTextCursor.MoveAnchor)
        return new
示例#2
0
def insert_snippet(text, cursor, variables):
    """Inserts a normal text snippet.
    
    After the insert, the cursor points to the end of the inserted snippet.
    
    If this function returns a cursor it must be set as the cursor for the view
    after the snippet has been inserted.
    
    """
    exp_base = expand.Expander(cursor)
    
    evs = [] # make a list of events, either text or a constant
    for text, key in snippets.expand(text):
        if text:
            evs.append(text)
        if key == '$':
            evs.append('$')
        elif key:
            # basic variables
            func = getattr(exp_base, key, None)
            if func:
                evs.append(func())
    
    selectionUsed = expand.SELECTION in evs
    # do the padding if 'selection: strip;' is used
    if selectionUsed and 'strip' in variables.get('selection', ''):
        space = '\n' if '\n' in cursor.selection().toPlainText() else ' '
        # change whitespace in previous and next piece of text
        i = evs.index(expand.SELECTION)
        for j in range(i-1, -i, -1):
            if evs[j] not in expand.constants:
                evs[j] = evs[j].rstrip() + space
                break
        for j in range(i+1, len(evs)):
            if evs[j] not in expand.constants:
                evs[j] = space + evs[j].lstrip()
                break
    # now insert the text
    ins = QTextCursor(cursor)
    selectionUsed and ins.setPosition(cursor.selectionStart())
    a, c = -1, -1
    for e in evs:
        if e == expand.ANCHOR:
            a = ins.position()
        elif e == expand.CURSOR:
            c = ins.position()
        elif e == expand.SELECTION:
            ins.setPosition(cursor.selectionEnd())
        else:
            ins.insertText(e)
    cursor.setPosition(ins.position())
    # return a new cursor if requested
    if (a, c) != (-1, -1):
        new = QTextCursor(cursor)
        if a != -1:
            new.setPosition(a)
        if c != -1:
            new.setPosition(c, QTextCursor.KeepAnchor if a != -1 else QTextCursor.MoveAnchor)
        return new
示例#3
0
 def actionTriggered(self, name):
     # convert arpeggio_normal to arpeggioNormal, etc.
     name = _arpeggioTypes[name]
     cursor = self.mainwindow().textCursor()
     # which arpeggio type is last used?
     lastused = '\\arpeggioNormal'
     types = set(_arpeggioTypes.values())
     block = cursor.block()
     while block.isValid():
         s = types.intersection(tokeniter.tokens(block))
         if s:
             lastused = s.pop()
             break
         block = block.previous()
     # where to insert
     c = lydocument.cursor(cursor)
     c.select_end_of_block()
     with cursortools.compress_undo(cursor):
         for item in ly.rhythm.music_items(c, partial=ly.document.OUTSIDE):
             c = QTextCursor(cursor.document())
             c.setPosition(item.end)
             c.insertText('\\arpeggio')
             if name != lastused:
                 cursortools.strip_indent(c)
                 indent = c.block().text()[:c.position() -
                                           c.block().position()]
                 c.insertText(name + '\n' + indent)
             # just pick the first place
             return
示例#4
0
    def _find(self, textEdit=None, backward=False):
        if textEdit is None:
            textEdit = self.textEdit

        found = False

        if textEdit is not None:
            cursor = textEdit.textCursor()
            text, flags = self._textAndFindFlags(backward=backward)
            position = cursor.position()
            cursor = textEdit.document().find(text, cursor, flags)

            if not cursor.isNull():
                textEdit.setTextCursor(cursor)
                found = True
            elif self.wrapAroundCheckBox.isChecked():
                cursor = QTextCursor(textEdit.textCursor())
                cursor.movePosition(backward and QTextCursor.End or QTextCursor.Start)
                cursor = textEdit.document().find(text, cursor, flags)
                if not cursor.isNull():
                    if position == cursor.position():
                        pass #todo
                    textEdit.setTextCursor(cursor)
                    found = True
            self.writeSettings()

        if not found:
            QApplication.beep()
            self.feedbackLabel.setText(self.tr("Not found"))
        else:
            self.clearFeedback()
示例#5
0
    def _find(self, textEdit=None, backward=False):
        if textEdit is None:
            textEdit = self.textEdit

        found = False

        if textEdit is not None:
            cursor = textEdit.textCursor()
            text, flags = self._textAndFindFlags(backward=backward)
            position = cursor.position()
            cursor = textEdit.document().find(text, cursor, flags)

            if not cursor.isNull():
                textEdit.setTextCursor(cursor)
                found = True
            elif self.wrapAroundCheckBox.isChecked():
                cursor = QTextCursor(textEdit.textCursor())
                cursor.movePosition(backward and QTextCursor.End
                                    or QTextCursor.Start)
                cursor = textEdit.document().find(text, cursor, flags)
                if not cursor.isNull():
                    if position == cursor.position():
                        pass  #todo
                    textEdit.setTextCursor(cursor)
                    found = True
            self.writeSettings()

        if not found:
            QApplication.beep()
            self.feedbackLabel.setText(self.tr("Not found"))
        else:
            self.clearFeedback()
示例#6
0
 def actionTriggered(self, name):
     # convert arpeggio_normal to arpeggioNormal, etc.
     name = _arpeggioTypes[name]
     cursor = self.mainwindow().textCursor()
     # which arpeggio type is last used?
     lastused = '\\arpeggioNormal'
     types = set(_arpeggioTypes.values())
     block = cursor.block()
     while block.isValid():
         s = types.intersection(tokeniter.tokens(block))
         if s:
             lastused = s.pop()
             break
         block = block.previous()
     # where to insert
     c = lydocument.cursor(cursor)
     c.select_end_of_block()
     with cursortools.compress_undo(cursor):
         for item in ly.rhythm.music_items(c, partial=ly.document.OUTSIDE):
             c = QTextCursor(cursor.document())
             c.setPosition(item.end)
             c.insertText('\\arpeggio')
             if name != lastused:
                 cursortools.strip_indent(c)
                 indent = c.block().text()[:c.position()-c.block().position()]
                 c.insertText(name + '\n' + indent)
             # just pick the first place
             return
示例#7
0
def keep_selection(cursor, edit=None):
    """Performs operations inside the selection and restore the selection afterwards.
    
    If edit is given, call setTextCursor(cursor) on the Q(Plain)TextEdit afterwards.
    
    """
    start, end, pos = cursor.selectionStart(), cursor.selectionEnd(), cursor.position()
    cur2 = QTextCursor(cursor)
    cur2.setPosition(end)
    
    try:
        yield
    finally:
        if pos == start:
            cursor.setPosition(cur2.position())
            cursor.setPosition(start, QTextCursor.KeepAnchor)
        else:
            cursor.setPosition(start)
            cursor.setPosition(cur2.position(), QTextCursor.KeepAnchor)
        if edit:
            edit.setTextCursor(cursor)
示例#8
0
def keep_selection(cursor, edit=None):
    """Performs operations inside the selection and restore the selection afterwards.
    
    If edit is given, call setTextCursor(cursor) on the Q(Plain)TextEdit afterwards.
    
    """
    start, end, pos = cursor.selectionStart(), cursor.selectionEnd(
    ), cursor.position()
    cur2 = QTextCursor(cursor)
    cur2.setPosition(end)

    try:
        yield
    finally:
        if pos == start:
            cursor.setPosition(cur2.position())
            cursor.setPosition(start, QTextCursor.KeepAnchor)
        else:
            cursor.setPosition(start)
            cursor.setPosition(cur2.position(), QTextCursor.KeepAnchor)
        if edit:
            edit.setTextCursor(cursor)
示例#9
0
 def on_log_received(self, data):
     time_info = datetime.fromtimestamp((data["time"] / 1000)).isoformat()
     log_message = "%s: %s : %s" % (time_info, data["level"], data["message"])
     message_document = self.document()
     cursor_to_add = QTextCursor(message_document)
     cursor_to_add.movePosition(cursor_to_add.End)
     cursor_to_add.insertText(log_message + "\n")
     if data["level"] in COLORS:
         fmt = QTextCharFormat()
         fmt.setForeground(COLORS[data["level"]])
         cursor_to_add.movePosition(cursor_to_add.PreviousBlock)
         cursor_to_add_fmt = message_document.find(data["level"], cursor_to_add.position())
         cursor_to_add_fmt.mergeCharFormat(fmt)
     self.ensureCursorVisible()
示例#10
0
    def selectedPosition(self, pos):
        anchorPos, cursorPos = pos
        anchorLine, anchorCol = anchorPos
        cursorLine, cursorCol = cursorPos

        anchorCursor = QTextCursor(self.document().findBlockByNumber(anchorLine))
        anchorCursor.setPositionInBlock(anchorCol)

        # just get absolute position
        cursor = QTextCursor(self.document().findBlockByNumber(cursorLine))
        cursor.setPositionInBlock(cursorCol)

        anchorCursor.setPosition(cursor.position(), QTextCursor.KeepAnchor)
        self.setTextCursor(anchorCursor)
示例#11
0
文件: __init__.py 项目: vi/qutepart
    def selectedPosition(self, pos):
        anchorPos, cursorPos = pos
        anchorLine, anchorCol = anchorPos
        cursorLine, cursorCol = cursorPos

        anchorCursor = QTextCursor(
            self.document().findBlockByNumber(anchorLine))
        setPositionInBlock(anchorCursor, anchorCol)

        # just get absolute position
        cursor = QTextCursor(self.document().findBlockByNumber(cursorLine))
        setPositionInBlock(cursor, cursorCol)

        anchorCursor.setPosition(cursor.position(), QTextCursor.KeepAnchor)
        self.setTextCursor(anchorCursor)
示例#12
0
 def on_log_received(self, data):
     time_info = datetime.fromtimestamp((data['time']/1000)).isoformat()
     log_message = '%s: %s : %s' % (
         time_info, data['level'], data['message'])
     message_document = self.document()
     cursor_to_add = QTextCursor(message_document)
     cursor_to_add.movePosition(cursor_to_add.End)
     cursor_to_add.insertText(log_message + '\n')
     if data['level'] in COLORS:
         fmt = QTextCharFormat()
         fmt.setForeground(COLORS[data['level']])
         cursor_to_add.movePosition(cursor_to_add.PreviousBlock)
         cursor_to_add_fmt = message_document.find(data['level'],
                                                   cursor_to_add.position())
         cursor_to_add_fmt.mergeCharFormat(fmt)
     self.ensureCursorVisible()
示例#13
0
文件: pqEdit.py 项目: jlg234bob/PPQT
 def centerCursor(self):
     tc = QTextCursor(
         self.textCursor())  # copy the working cursor with its selection
     top_point = tc.position()  # one end of selection, in character units
     bot_point = tc.anchor()  # ..and the other end
     if top_point > bot_point:  # often the position is > the anchor
         (top_point, bot_point) = (bot_point, top_point)
     tc.setPosition(top_point)  # cursor for the top of the selection
     selection_top = self.cursorRect(tc).top()  # ..get its top pixel
     line_height = self.cursorRect(
         tc).height()  # and save height of one line
     tc.setPosition(bot_point)  # cursor for the end of the selection
     selection_bot = self.cursorRect(
         tc).bottom()  # ..selection's bottom pixel
     selection_height = selection_bot - selection_top + 1  # selection height in pixels
     view_height = self.viewport().geometry().height(
     )  # scrolled area's height in px
     view_half = view_height >> 1  # int(view_height/2)
     pixel_adjustment = 0
     if selection_height < view_half:
         # selected text is less than half the window height: center the top of the
         # selection, i.e., make the cursor_top equal to view_half.
         pixel_adjustment = selection_top - view_half  # may be negative
     else:
         # selected text is taller than half the window, can we show it all?
         if selection_height < (view_height - line_height):
             # all selected text fits in the viewport (with a little free): center it.
             pixel_adjustment = (selection_top +
                                 (selection_height / 2)) - view_half
         else:
             # not all selected text fits the window, put text top near window top
             pixel_adjustment = selection_top - line_height
     # OK, convert the pixel adjustment to a line-adjustment based on the assumption
     # that a scrollbar pageStep is the height of the viewport in lines.
     adjust_fraction = pixel_adjustment / view_height
     vscroller = self.verticalScrollBar()
     page_step = vscroller.pageStep(
     )  # lines in a viewport page, actually less 1
     adjust_lines = int(page_step * adjust_fraction)
     target = vscroller.value() + adjust_lines
     if (target >= 0) and (target <= vscroller.maximum()):
         vscroller.setValue(target)
示例#14
0
    def on_log_received(self, data):
        time_info = datetime.fromtimestamp((data['time'] / 1000)).isoformat()
        log_message = '%s: %s : %s' % (
            time_info, data['level'], data['message'])
        message_document = self.document()
        cursor_to_add = QTextCursor(message_document)
        cursor_to_add.movePosition(cursor_to_add.End)
        cursor_to_add.insertText(log_message + '\n')

        if data['level'] in COLORS:
            fmt = QTextCharFormat()
            fmt.setForeground(COLORS[data['level']])
            cursor_to_add.movePosition(cursor_to_add.PreviousBlock)
            log_lvl_data = LogLevelData(log_levels[data['level'].upper()])
            cursor_to_add.block().setUserData(log_lvl_data)
            cursor_to_add_fmt = message_document.find(data['level'],
                                                      cursor_to_add.position())
            cursor_to_add_fmt.mergeCharFormat(fmt)
            if log_levels[data['level']] > self.log_lvl:
                cursor_to_add.block().setVisible(False)
        self.ensureCursorVisible()
示例#15
0
 def centerCursor(self) :
     tc = QTextCursor(self.textCursor()) # copy the working cursor with its selection
     top_point = tc.position() # one end of selection, in character units
     bot_point = tc.anchor() # ..and the other end
     if top_point > bot_point : # often the position is > the anchor
         (top_point, bot_point) = (bot_point, top_point)
     tc.setPosition(top_point) # cursor for the top of the selection
     selection_top = self.cursorRect(tc).top() # ..get its top pixel
     line_height = self.cursorRect(tc).height() # and save height of one line
     tc.setPosition(bot_point) # cursor for the end of the selection
     selection_bot = self.cursorRect(tc).bottom() # ..selection's bottom pixel
     selection_height = selection_bot - selection_top + 1 # selection height in pixels
     view_height = self.viewport().geometry().height() # scrolled area's height in px
     view_half = view_height >> 1 # int(view_height/2)
     pixel_adjustment = 0
     if selection_height < view_half :
         # selected text is less than half the window height: center the top of the
         # selection, i.e., make the cursor_top equal to view_half.
         pixel_adjustment = selection_top - view_half # may be negative
     else :
         # selected text is taller than half the window, can we show it all?
         if selection_height < (view_height - line_height) :
             # all selected text fits in the viewport (with a little free): center it.
             pixel_adjustment = (selection_top + (selection_height/2)) - view_half
         else :
             # not all selected text fits the window, put text top near window top
             pixel_adjustment = selection_top - line_height
     # OK, convert the pixel adjustment to a line-adjustment based on the assumption
     # that a scrollbar pageStep is the height of the viewport in lines.
     adjust_fraction = pixel_adjustment / view_height
     vscroller = self.verticalScrollBar()
     page_step = vscroller.pageStep() # lines in a viewport page, actually less 1
     adjust_lines = int(page_step * adjust_fraction)
     target = vscroller.value() + adjust_lines
     if (target >= 0) and (target <= vscroller.maximum()) :
         vscroller.setValue(target)