code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not self._isValidTrigger(block, ch): return None prevStmt = self.findPrevStmt(block) if not prevStmt.endBlock.isValid(): return None # Can't indent the first line prevBlock = self._prevNonEmptyBlock(block) # HACK Detect here documents if self._qpart.isHereDoc(prevBlock.blockNumber(), prevBlock.length() - 2): return None # HACK Detect embedded comments if self._qpart.isBlockComment(prevBlock.blockNumber(), prevBlock.length() - 2): return None prevStmtCnt = prevStmt.content() prevStmtInd = prevStmt.indent() # Are we inside a parameter list, array or hash? foundBlock, foundColumn, foundChar = self.lastAnchor(block, 0) if foundBlock is not None: shouldIndent = foundBlock == prevStmt.endBlock or \ self.testAtEnd(prevStmt, re.compile(',\s*')) if (not self._isLastCodeColumn(foundBlock, foundColumn)) or \ self.lastAnchor(foundBlock, foundColumn)[0] is not None: # TODO This is alignment, should force using spaces instead of tabs: if shouldIndent: foundColumn += 1 nextCol = self._nextNonSpaceColumn(foundBlock, foundColumn) if nextCol > 0 and \ (not self._isComment(foundBlock, nextCol)): foundColumn = nextCol # Keep indent of previous statement, while aligning to the anchor column if len(prevStmtInd) > foundColumn: return prevStmtInd else: return self._makeIndentAsColumn(foundBlock, foundColumn) else: indent = self._blockIndent(foundBlock) if shouldIndent: indent = self._increaseIndent(indent) return indent # Handle indenting of multiline statements. if (prevStmt.endBlock == block.previous() and \ self._isBlockContinuing(prevStmt.endBlock)) or \ self.isStmtContinuing(prevStmt.endBlock): if prevStmt.startBlock == prevStmt.endBlock: if ch == '' and \ len(self._blockIndent(block)) > len(self._blockIndent(prevStmt.endBlock)): return None # Don't force a specific indent level when aligning manually return self._increaseIndent(self._increaseIndent(prevStmtInd)) else: return self._blockIndent(prevStmt.endBlock) if rxUnindent.match(block.text()): startStmt = self.findBlockStart(block) if startStmt.startBlock.isValid(): return startStmt.indent() else: return None if self.isBlockStart(prevStmt) and not rxBlockEnd.search(prevStmt.content()): return self._increaseIndent(prevStmtInd) elif re.search(r'[\[\{]\s*$', prevStmtCnt) is not None: return self._increaseIndent(prevStmtInd) # Keep current return prevStmtInd
def computeSmartIndent(self, block, ch)
indent gets three arguments: line, indentWidth in spaces, typed character indent
4.908095
4.917072
0.998174
option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItem(option) self.initStyleOption(options,index) style = QApplication.style() if options.widget is None else options.widget.style() doc = QTextDocument() doc.setDocumentMargin(1) doc.setHtml(options.text) if options.widget is not None: doc.setDefaultFont(options.widget.font()) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter); ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) doc.documentLayout().draw(painter, ctx) painter.restore()
def paint(self, painter, option, index)
QStyledItemDelegate.paint implementation
2.926168
2.82976
1.034069
return self._start is not None and \ (keyEvent.matches(QKeySequence.Delete) or \ (keyEvent.key() == Qt.Key_Backspace and keyEvent.modifiers() == Qt.NoModifier))
def isDeleteKeyEvent(self, keyEvent)
Check if key event should be handled as Delete command
3.541857
3.410743
1.038442
with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
def delete(self)
Del or Backspace pressed. Delete selection
15.344491
11.426171
1.342925
return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, Qt.Key_PageUp, Qt.Key_PageDown, Qt.Key_Home, Qt.Key_End)
def isExpandKeyEvent(self, keyEvent)
Check if key event should expand rectangular selection
1.932645
1.816407
1.063993
if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn(currentBlockText, self._qpart.cursorPosition[1]) self._start = (line, visibleColumn) modifiersWithoutAltShift = keyEvent.modifiers() & ( ~ (Qt.AltModifier | Qt.ShiftModifier)) newEvent = QKeyEvent(keyEvent.type(), keyEvent.key(), modifiersWithoutAltShift, keyEvent.text(), keyEvent.isAutoRepeat(), keyEvent.count()) self._qpart.cursorPositionChanged.disconnect(self._reset) self._qpart.selectionChanged.disconnect(self._reset) super(self._qpart.__class__, self._qpart).keyPressEvent(newEvent) self._qpart.cursorPositionChanged.connect(self._reset) self._qpart.selectionChanged.connect(self._reset)
def onExpandKeyEvent(self, keyEvent)
One of expand selection key events
3.568727
3.506179
1.01784
generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(generator) val = next(generator) return val
def _realToVisibleColumn(self, text, realColumn)
If \t is used, real position of symbol in block and visible position differs This function converts real to visible
6.578538
6.421788
1.024409
if visiblePos == 0: return 0 elif not '\t' in text: return visiblePos else: currentIndex = 1 for currentVisiblePos in self._visibleCharPositionGenerator(text): if currentVisiblePos >= visiblePos: return currentIndex - 1 currentIndex += 1 return None
def _visibleToRealColumn(self, text, visiblePos)
If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short
4.397759
3.828562
1.148671
cursors = [] if self._start is not None: startLine, startVisibleCol = self._start currentLine, currentCol = self._qpart.cursorPosition if abs(startLine - currentLine) > self._MAX_SIZE or \ abs(startVisibleCol - currentCol) > self._MAX_SIZE: # Too big rectangular selection freezes the GUI self._qpart.userWarning.emit('Rectangular selection area is too big') self._start = None return [] currentBlockText = self._qpart.textCursor().block().text() currentVisibleCol = self._realToVisibleColumn(currentBlockText, currentCol) for lineNumber in range(min(startLine, currentLine), max(startLine, currentLine) + 1): block = self._qpart.document().findBlockByNumber(lineNumber) cursor = QTextCursor(block) realStartCol = self._visibleToRealColumn(block.text(), startVisibleCol) realCurrentCol = self._visibleToRealColumn(block.text(), currentVisibleCol) if realStartCol is None: realStartCol = block.length() # out of range value if realCurrentCol is None: realCurrentCol = block.length() # out of range value cursor.setPosition(cursor.block().position() + min(realStartCol, block.length() - 1)) cursor.setPosition(cursor.block().position() + min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor) cursors.append(cursor) return cursors
def cursors(self)
Cursors for rectangular selection. 1 cursor for every line
3.016597
2.94132
1.025593
selections = [] cursors = self.cursors() if cursors: background = self._qpart.palette().color(QPalette.Highlight) foreground = self._qpart.palette().color(QPalette.HighlightedText) for cursor in cursors: selection = QTextEdit.ExtraSelection() selection.format.setBackground(background) selection.format.setForeground(foreground) selection.cursor = cursor selections.append(selection) return selections
def selections(self)
Build list of extra selections for rectangular selection
2.658849
2.559844
1.038676
data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
def copy(self)
Copy to the clipboard
4.195453
3.612635
1.161328
cursorPos = self._qpart.cursorPosition topLeft = (min(self._start[0], cursorPos[0]), min(self._start[1], cursorPos[1])) self.copy() self.delete() self._qpart.cursorPosition = topLeft
def cut(self)
Cut action. Copy and delete
6.627823
5.492195
1.206771
visibleTextWidth = self._realToVisibleColumn(text, len(text)) diff = width - visibleTextWidth if diff <= 0: return '' elif self._qpart.indentUseTabs and \ all([char == '\t' for char in text]): # if using tabs and only tabs in text return '\t' * (diff // self._qpart.indentWidth) + \ ' ' * (diff % self._qpart.indentWidth) else: return ' ' * int(diff)
def _indentUpTo(self, text, width)
Add space to text, so text width will be at least width. Return text, which must be added
5.552895
5.920533
0.937905
if self.isActive(): self.delete() elif self._qpart.textCursor().hasSelection(): self._qpart.textCursor().deleteChar() text = bytes(mimeData.data(self.MIME_TYPE)).decode('utf8') lines = text.splitlines() cursorLine, cursorCol = self._qpart.cursorPosition if cursorLine + len(lines) > len(self._qpart.lines): for i in range(cursorLine + len(lines) - len(self._qpart.lines)): self._qpart.lines.append('') with self._qpart: for index, line in enumerate(lines): currentLine = self._qpart.lines[cursorLine + index] newLine = currentLine[:cursorCol] + \ self._indentUpTo(currentLine, cursorCol) + \ line + \ currentLine[cursorCol:] self._qpart.lines[cursorLine + index] = newLine self._qpart.cursorPosition = cursorLine, cursorCol
def paste(self, mimeData)
Paste recrangular selection. Add space at the beginning of line, if necessary
2.909526
2.836059
1.025905
if self._bit_count < 0: raise Exception( "A margin cannot request negative number of bits" ) if self._bit_count == 0: return # Build a list of occupied ranges margins = self._qpart.getMargins() occupiedRanges = [] for margin in margins: bitRange = margin.getBitRange() if bitRange is not None: # pick the right position added = False for index in range( len( occupiedRanges ) ): r = occupiedRanges[ index ] if bitRange[ 1 ] < r[ 0 ]: occupiedRanges.insert(index, bitRange) added = True break if not added: occupiedRanges.append(bitRange) vacant = 0 for r in occupiedRanges: if r[ 0 ] - vacant >= self._bit_count: self._bitRange = (vacant, vacant + self._bit_count - 1) return vacant = r[ 1 ] + 1 # Not allocated, i.e. grab the tail bits self._bitRange = (vacant, vacant + self._bit_count - 1)
def __allocateBits(self)
Allocates the bit range depending on the required bit count
3.498238
3.381692
1.034464
if dy: self.scroll(0, dy) elif self._countCache[0] != self._qpart.blockCount() or \ self._countCache[1] != self._qpart.textCursor().block().lineCount(): # if block height not added to rect, last line number sometimes is not drawn blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock()).height() self.update(0, rect.y(), self.width(), rect.height() + blockHeight) self._countCache = (self._qpart.blockCount(), self._qpart.textCursor().block().lineCount()) if rect.contains(self._qpart.viewport().rect()): self._qpart.updateViewportMargins()
def __updateRequest(self, rect, dy)
Repaint line number area if necessary
4.296521
4.093339
1.049637
if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") if value < 0: raise Exception( "The margin '" + self._name + "' must be a positive integer" ) if value >= 2 ** self._bit_count: raise Exception( "The margin '" + self._name + "' value exceeds the allocated bit range" ) newMarginValue = value << self._bitRange[ 0 ] currentUserState = block.userState() if currentUserState in [ 0, -1 ]: block.setUserState(newMarginValue) else: marginMask = 2 ** self._bit_count - 1 otherMarginsValue = currentUserState & ~marginMask block.setUserState(newMarginValue | otherMarginsValue)
def setBlockValue(self, block, value)
Sets the required value to the block without damaging the other bits
4.692552
4.545224
1.032414
if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") val = block.userState() if val in [ 0, -1 ]: return 0 # Shift the value to the right val >>= self._bitRange[ 0 ] # Apply the mask to the value mask = 2 ** self._bit_count - 1 val &= mask return val
def getBlockValue(self, block)
Provides the previously set block value respecting the bits range. 0 value and not marked block are treated the same way and 0 is provided.
7.861387
7.086789
1.109302
if not self.isHidden(): QWidget.hide(self) self._qpart.updateViewport()
def hide(self)
Override the QWidget::hide() method to properly recalculate the editor viewport.
15.348399
8.777104
1.748686
if self.isHidden(): QWidget.show(self) self._qpart.updateViewport()
def show(self)
Override the QWidget::show() method to properly recalculate the editor viewport.
18.389063
10.482985
1.754182
if val != self.isVisible(): if val: QWidget.setVisible(self, True) else: QWidget.setVisible(self, False) self._qpart.updateViewport()
def setVisible(self, val)
Override the QWidget::setVisible(bool) method to properly recalculate the editor viewport.
4.398652
3.870866
1.136348
if self._bit_count == 0: return block = self._qpart.document().begin() while block.isValid(): if self.getBlockValue(block): self.setBlockValue(block, 0) block = block.next()
def clear(self)
Convenience method to reset all the block values to 0
7.394004
5.657308
1.306983
if lineData is None: return ' ' # default is code textTypeMap = lineData[1] if column >= len(textTypeMap): # probably, not actual data, not updated yet return ' ' return textTypeMap[column]
def _getTextType(self, lineData, column)
Get text type (letter)
10.799085
9.47526
1.139714
import qutepart.syntax.loader # delayed import for avoid cross-imports problem with self._loadedSyntaxesLock: if not xmlFileName in self._loadedSyntaxes: xmlFilePath = os.path.join(os.path.dirname(__file__), "data", "xml", xmlFileName) syntax = Syntax(self) self._loadedSyntaxes[xmlFileName] = syntax qutepart.syntax.loader.loadSyntax(syntax, xmlFilePath) return self._loadedSyntaxes[xmlFileName]
def _getSyntaxByXmlFileName(self, xmlFileName)
Get syntax by its xml file name
3.995073
3.930927
1.016318
xmlFileName = self._syntaxNameToXmlFileName[syntaxName] return self._getSyntaxByXmlFileName(xmlFileName)
def _getSyntaxByLanguageName(self, syntaxName)
Get syntax by its name. Name is defined in the xml file
5.004992
4.125945
1.213053
for regExp, xmlFileName in self._extensionToXmlFileName.items(): if regExp.match(name): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + name)
def _getSyntaxBySourceFileName(self, name)
Get syntax by source name of file, which is going to be highlighted
4.93793
4.792934
1.030252
xmlFileName = self._mimeTypeToXmlFileName[mimeType] return self._getSyntaxByXmlFileName(xmlFileName)
def _getSyntaxByMimeType(self, mimeType)
Get syntax by first line of the file
4.970667
4.602231
1.080056
for pattern, xmlFileName in self._firstLineToXmlFileName.items(): if fnmatch.fnmatch(firstLine, pattern): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + firstLine)
def _getSyntaxByFirstLine(self, firstLine)
Get syntax by first line of the file
4.401877
3.794896
1.159947
syntax = None if syntax is None and xmlFileName is not None: try: syntax = self._getSyntaxByXmlFileName(xmlFileName) except KeyError: _logger.warning('No xml definition %s' % xmlFileName) if syntax is None and mimeType is not None: try: syntax = self._getSyntaxByMimeType(mimeType) except KeyError: _logger.warning('No syntax for mime type %s' % mimeType) if syntax is None and languageName is not None: try: syntax = self._getSyntaxByLanguageName(languageName) except KeyError: _logger.warning('No syntax for language %s' % languageName) if syntax is None and sourceFilePath is not None: baseName = os.path.basename(sourceFilePath) try: syntax = self._getSyntaxBySourceFileName(baseName) except KeyError: pass if syntax is None and firstLine is not None: try: syntax = self._getSyntaxByFirstLine(firstLine) except KeyError: pass return syntax
def getSyntax(self, xmlFileName=None, mimeType=None, languageName=None, sourceFilePath=None, firstLine=None)
Get syntax by one of parameters: * xmlFileName * mimeType * languageName * sourceFilePath First parameter in the list has biggest priority
1.645811
1.664154
0.988977
if len(self._contexts) - 1 < count: _logger.error("#pop value is too big %d", len(self._contexts)) if len(self._contexts) > 1: return ContextStack(self._contexts[:1], self._data[:1]) else: return self return ContextStack(self._contexts[:-count], self._data[:-count])
def pop(self, count)
Returns new context stack, which doesn't contain few levels
4.367466
3.645486
1.198048
return ContextStack(self._contexts + [context], self._data + [data])
def append(self, context, data)
Returns new context, which contains current stack and new frame
11.041058
9.140646
1.207908
if self._popsCount: contextStack = contextStack.pop(self._popsCount) if self._contextToSwitch is not None: if not self._contextToSwitch.dynamic: data = None contextStack = contextStack.append(self._contextToSwitch, data) return contextStack
def getNextContextStack(self, contextStack, data=None)
Apply modification to the contextStack. This method never modifies input parameter list
5.060625
5.133519
0.9858
# Skip if column doesn't match if self.column != -1 and \ self.column != textToMatchObject.currentColumnIndex: return None if self.firstNonSpace and \ (not textToMatchObject.firstNonSpace): return None return self._tryMatch(textToMatchObject)
def tryMatch(self, textToMatchObject)
Try to find themselves in the text. Returns (contextStack, count, matchedRule) or (contextStack, None, None) if doesn't match
5.821964
5.768786
1.009218
def _replaceFunc(escapeMatchObject): stringIndex = escapeMatchObject.group(0)[1] index = int(stringIndex) if index < len(contextData): return contextData[index] else: return escapeMatchObject.group(0) # no any replacements, return original value return _numSeqReplacer.sub(_replaceFunc, string)
def _makeDynamicSubsctitutions(string, contextData)
For dynamic rules, replace %d patterns with actual strings Python function, which is used by C extension.
5.864607
5.393631
1.087321
# Special case. if pattern starts with \b, we have to check it manually, # because string is passed to .match(..) without beginning if self.wordStart and \ (not textToMatchObject.isWordStart): return None #Special case. If pattern starts with ^ - check column number manually if self.lineStart and \ textToMatchObject.currentColumnIndex > 0: return None if self.dynamic: string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData) regExp = self._compileRegExp(string, self.insensitive, self.minimal) else: regExp = self.regExp if regExp is None: return None wholeMatch, groups = self._matchPattern(regExp, textToMatchObject.text) if wholeMatch is not None: count = len(wholeMatch) return RuleTryMatchResult(self, count, groups) else: return None
def _tryMatch(self, textToMatchObject)
Tries to parse text. If matched - saves data for dynamic context
7.523707
7.375702
1.020067
flags = 0 if insensitive: flags = re.IGNORECASE string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser string = string.replace('[:digit:]', '\\d') string = string.replace('[:blank:]', '\\s') try: return re.compile(string, flags) except (re.error, AssertionError) as ex: _logger.warning("Invalid pattern '%s': %s", string, str(ex)) return None
def _compileRegExp(string, insensitive, minimal)
Compile regular expression. Python function, used by C code NOTE minimal flag is not supported here, but supported on PCRE
3.670546
3.645194
1.006955
match = regExp.match(string) if match is not None and match.group(0): return match.group(0), (match.group(0), ) + match.groups() else: return None, None
def _matchPattern(regExp, string)
Try to match pattern. Returns tuple (whole match, groups) or (None, None) Python function, used by C code
3.010876
2.639055
1.140892
# andreikop: This check is not described in kate docs, and I haven't found it in the code if not textToMatchObject.isWordStart: return None index = self._tryMatchText(textToMatchObject.text) if index is None: return None if textToMatchObject.currentColumnIndex + index < len(textToMatchObject.wholeLineText): newTextToMatchObject = TextToMatchObject(textToMatchObject.currentColumnIndex + index, textToMatchObject.wholeLineText, self.parentContext.parser.deliminatorSet, textToMatchObject.contextData) for rule in self.childRules: ruleTryMatchResult = rule.tryMatch(newTextToMatchObject) if ruleTryMatchResult is not None: index += ruleTryMatchResult.length break # child rule context and attribute ignored return RuleTryMatchResult(self, index)
def _tryMatch(self, textToMatchObject)
Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match
6.439448
6.379683
1.009368
index = 0 while index < len(text): if not text[index].isdigit(): break index += 1 return index
def _countDigits(self, text)
Count digits at start of text
2.512532
2.389134
1.05165
for rule in self.context.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None: _logger.debug('\tmatched rule %s at %d in included context %s/%s', rule.shortId(), textToMatchObject.currentColumnIndex, self.context.parser.syntax.name, self.context.name) return ruleTryMatchResult else: return None
def _tryMatch(self, textToMatchObject)
Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match
5.36167
5.200686
1.030955
startColumnIndex = currentColumnIndex countOfNotMatchedSymbols = 0 highlightedSegments = [] textTypeMap = [] ruleTryMatchResult = None while currentColumnIndex < len(text): textToMatchObject = TextToMatchObject(currentColumnIndex, text, self.parser.deliminatorSet, contextStack.currentData()) for rule in self.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None: # if something matched _logger.debug('\tmatched rule %s at %d', rule.shortId(), currentColumnIndex) if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] countOfNotMatchedSymbols = 0 if ruleTryMatchResult.rule.context is not None: newContextStack = ruleTryMatchResult.rule.context.getNextContextStack(contextStack, ruleTryMatchResult.data) else: newContextStack = contextStack format = ruleTryMatchResult.rule.format if ruleTryMatchResult.rule.attribute else newContextStack.currentContext().format textType = ruleTryMatchResult.rule.textType or newContextStack.currentContext().textType highlightedSegments.append((ruleTryMatchResult.length, format)) textTypeMap += textType * ruleTryMatchResult.length currentColumnIndex += ruleTryMatchResult.length if newContextStack != contextStack: lineContinue = isinstance(ruleTryMatchResult.rule, LineContinue) return currentColumnIndex - startColumnIndex, newContextStack, highlightedSegments, textTypeMap, lineContinue break # for loop else: # no matched rules if self.fallthroughContext is not None: newContextStack = self.fallthroughContext.getNextContextStack(contextStack) if newContextStack != contextStack: if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] return (currentColumnIndex - startColumnIndex, newContextStack, highlightedSegments, textTypeMap, False) currentColumnIndex += 1 countOfNotMatchedSymbols += 1 if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] lineContinue = ruleTryMatchResult is not None and \ isinstance(ruleTryMatchResult.rule, LineContinue) return currentColumnIndex - startColumnIndex, contextStack, highlightedSegments, textTypeMap, lineContinue
def parseBlock(self, contextStack, currentColumnIndex, text)
Parse block Exits, when reached end of the text, or when context is switched Returns (length, newContextStack, highlightedSegments, lineContinue)
2.704748
2.560589
1.056299
if prevContextStack is not None: contextStack = prevContextStack else: contextStack = self._defaultContextStack highlightedSegments = [] lineContinue = False currentColumnIndex = 0 textTypeMap = [] if len(text) > 0: while currentColumnIndex < len(text): _logger.debug('In context %s', contextStack.currentContext().name) length, newContextStack, segments, textTypeMapPart, lineContinue = \ contextStack.currentContext().parseBlock(contextStack, currentColumnIndex, text) highlightedSegments += segments contextStack = newContextStack textTypeMap += textTypeMapPart currentColumnIndex += length if not lineContinue: while contextStack.currentContext().lineEndContext is not None: oldStack = contextStack contextStack = contextStack.currentContext().lineEndContext.getNextContextStack(contextStack) if oldStack == contextStack: # avoid infinite while loop if nothing to switch break # this code is not tested, because lineBeginContext is not defined by any xml file if contextStack.currentContext().lineBeginContext is not None: contextStack = contextStack.currentContext().lineBeginContext.getNextContextStack(contextStack) elif contextStack.currentContext().lineEmptyContext is not None: contextStack = contextStack.currentContext().lineEmptyContext.getNextContextStack(contextStack) lineData = (contextStack, textTypeMap) return lineData, highlightedSegments
def highlightBlock(self, text, prevContextStack)
Parse block and return ParseBlockFullResult return (lineData, highlightedSegments) where lineData is (contextStack, textTypeMap) where textTypeMap is a string of textType characters
3.879879
3.376095
1.149221
if column is not None: index = block.text()[:column].rfind(needle) else: index = block.text().rfind(needle) if index != -1: return block, index for block in self.iterateBlocksBackFrom(block.previous()): column = block.text().rfind(needle) if column != -1: return block, column raise ValueError('Not found')
def findTextBackward(self, block, column, needle)
Search for a needle and return (block, column) Raise ValueError, if not found
3.204461
2.878732
1.11315
block, column = self.findBracketBackward(block, column, '{') # raise ValueError if not found try: block, column = self.tryParenthesisBeforeBrace(block, column) except ValueError: pass # leave previous values return self._blockIndent(block)
def findLeftBrace(self, block, column)
Search for a corresponding '{' and return its indentation If not found return None
11.093173
9.973542
1.11226
text = block.text()[:column - 1].rstrip() if not text.endswith(')'): raise ValueError() return self.findBracketBackward(block, len(text) - 1, '(')
def tryParenthesisBeforeBrace(self, block, column)
Character at (block, column) has to be a '{'. Now try to find the right line for indentation for constructs like: if (a == b and c == d) { <- check for ')', and find '(', then return its indentation Returns input params, if no success, otherwise block and column of '('
6.818708
7.584594
0.899021
if not re.match(r'^\s*(default\s*|case\b.*):', block.text()): return None for block in self.iterateBlocksBackFrom(block.previous()): text = block.text() if re.match(r"^\s*(default\s*|case\b.*):", text): dbg("trySwitchStatement: success in line %d" % block.blockNumber()) return self._lineIndent(text) elif re.match(r"^\s*switch\b", text): if CFG_INDENT_CASE: return self._increaseIndent(self._lineIndent(text)) else: return self._lineIndent(text) return None
def trySwitchStatement(self, block)
Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found.
4.86058
4.266709
1.139187
if CFG_ACCESS_MODIFIERS < 0: return None if not re.match(r'^\s*((public|protected|private)\s*(slots|Q_SLOTS)?|(signals|Q_SIGNALS)\s*):\s*$', block.text()): return None try: block, notUsedColumn = self.findBracketBackward(block, 0, '{') except ValueError: return None indentation = self._blockIndent(block) for i in range(CFG_ACCESS_MODIFIERS): indentation = self._increaseIndent(indentation) dbg("tryAccessModifiers: success in line %d" % block.blockNumber()) return indentation
def tryAccessModifiers(self, block)
Check for private, protected, public, signals etc... and assume we are in a class definition. Try to find a previous private/protected/private... or class and return its indentation or null if not found.
7.800624
6.786462
1.149439
indentation = None prevNonEmptyBlock = self._prevNonEmptyBlock(block) if not prevNonEmptyBlock.isValid(): return None prevNonEmptyBlockText = prevNonEmptyBlock.text() if prevNonEmptyBlockText.endswith('*/'): try: foundBlock, notUsedColumn = self.findTextBackward(prevNonEmptyBlock, prevNonEmptyBlock.length(), '/*') except ValueError: foundBlock = None if foundBlock is not None: dbg("tryCComment: success (1) in line %d" % foundBlock.blockNumber()) return self._lineIndent(foundBlock.text()) if prevNonEmptyBlock != block.previous(): # inbetween was an empty line, so do not copy the "*" character return None blockTextStripped = block.text().strip() prevBlockTextStripped = prevNonEmptyBlockText.strip() if prevBlockTextStripped.startswith('/*') and not '*/' in prevBlockTextStripped: indentation = self._blockIndent(prevNonEmptyBlock) if CFG_AUTO_INSERT_STAR: # only add '*', if there is none yet. indentation += ' ' if not blockTextStripped.endswith('*'): indentation += '*' secondCharIsSpace = len(blockTextStripped) > 1 and blockTextStripped[1].isspace() if not secondCharIsSpace and \ not blockTextStripped.endswith("*/"): indentation += ' ' dbg("tryCComment: success (2) in line %d" % block.blockNumber()) return indentation elif prevBlockTextStripped.startswith('*') and \ (len(prevBlockTextStripped) == 1 or prevBlockTextStripped[1].isspace()): # in theory, we could search for opening /*, and use its indentation # and then one alignment character. Let's not do this for now, though. indentation = self._lineIndent(prevNonEmptyBlockText) # only add '*', if there is none yet. if CFG_AUTO_INSERT_STAR and not blockTextStripped.startswith('*'): indentation += '*' if len(blockTextStripped) < 2 or not blockTextStripped[1].isspace(): indentation += ' ' dbg("tryCComment: success (2) in line %d" % block.blockNumber()) return indentation return None
def tryCComment(self, block)
C comment checking. If the previous line begins with a "/*" or a "* ", then return its leading white spaces + ' *' + the white spaces after the * return: filler string or null, if not in a C comment
3.759752
3.745006
1.003937
if not block.previous().isValid() or \ not CFG_AUTO_INSERT_SLACHES: return None prevLineText = block.previous().text() indentation = None comment = prevLineText.lstrip().startswith('#') # allowed are: #, #/, #! #/<, #!< and ##... if comment: prevLineText = block.previous().text() lstrippedText = block.previous().text().lstrip() if len(lstrippedText) >= 4: char3 = lstrippedText[2] char4 = lstrippedText[3] indentation = self._lineIndent(prevLineText) if CFG_AUTO_INSERT_SLACHES: if prevLineText[2:4] == '//': # match ##... and replace by only two: # match = re.match(r'^\s*(\/\/)', prevLineText) elif (char3 == '/' or char3 == '!'): # match #/, #!, #/< and #! match = re.match(r'^\s*(\/\/[\/!][<]?\s*)', prevLineText) else: # only #, nothing else: match = re.match(r'^\s*(\/\/\s*)', prevLineText) if match is not None: self._qpart.insertText((block.blockNumber(), 0), match.group(1)) if indentation is not None: dbg("tryCppComment: success in line %d" % block.previous().blockNumber()) return indentation
def tryCppComment(self, block)
C++ comment checking. when we want to insert slashes: #, #/, #! #/<, #!< and ##... return: filler string or null, if not in a star comment NOTE: otherwise comments get skipped generally and we use the last code-line
5.228401
4.442766
1.176835
currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None # if line ends with ')', find the '(' and check this line then. if currentBlock.text().rstrip().endswith(')'): try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(currentBlock.text()), '(') except ValueError: pass else: currentBlock = foundBlock # found non-empty line currentBlockText = currentBlock.text() if re.match(r'^\s*(if\b|for|do\b|while|switch|[}]?\s*else|((private|public|protected|case|default|signals|Q_SIGNALS).*:))', currentBlockText) is None: return None indentation = None # ignore trailing comments see: https:#bugs.kde.org/show_bug.cgi?id=189339 try: index = currentBlockText.index('//') except ValueError: pass else: currentBlockText = currentBlockText[:index] # try to ignore lines like: if (a) b; or if (a) { b; } if not currentBlockText.endswith(';') and \ not currentBlockText.endswith('}'): # take its indentation and add one indentation level indentation = self._lineIndent(currentBlockText) if not isBrace: indentation = self._increaseIndent(indentation) elif currentBlockText.endswith(';'): # stuff like: # for(int b; # b < 10; # --b) try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, None, '(') except ValueError: pass else: dbg("tryCKeywords: success 1 in line %d" % block.blockNumber()) return self._makeIndentAsColumn(foundBlock, foundColumn, 1) if indentation is not None: dbg("tryCKeywords: success in line %d" % block.blockNumber()) return indentation
def tryCKeywords(self, block, isBrace)
Check for if, else, while, do, switch, private, public, protected, signals, default, case etc... keywords, as we want to indent then. If is non-null/True, then indentation is not increased. Note: The code is written to be called *after* tryCComment and tryCppComment!
5.214019
4.976143
1.047803
currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None # found non-empty line currentText = currentBlock.text() if currentText.rstrip().endswith(';') and \ re.search(r'^\s*(if\b|[}]?\s*else|do\b|while\b|for)', currentText) is None: # idea: we had something like: # if/while/for (expression) # statement(); <-- we catch this trailing ';' # Now, look for a line that starts with if/for/while, that has one # indent level less. currentIndentation = self._lineIndent(currentText) if not currentIndentation: return None for block in self.iterateBlocksBackFrom(currentBlock.previous()): if block.text().strip(): # not empty indentation = self._blockIndent(block) if len(indentation) < len(currentIndentation): if re.search(r'^\s*(if\b|[}]?\s*else|do\b|while\b|for)[^{]*$', block.text()) is not None: dbg("tryCondition: success in line %d" % block.blockNumber()) return indentation break return None
def tryCondition(self, block)
Search for if, do, while, for, ... as we want to indent then. Return null, if nothing useful found. Note: The code is written to be called *after* tryCComment and tryCppComment!
6.029704
5.828775
1.034472
oposite = { ')': '(', '}': '{', ']': '['} char = self._firstNonSpaceChar(block) if not char in oposite.keys(): return None # we pressed enter in e.g. () try: foundBlock, foundColumn = self.findBracketBackward(block, 0, oposite[char]) except ValueError: return None if autoIndent: # when aligning only, don't be too smart and just take the indent level of the open anchor return self._blockIndent(foundBlock) lastChar = self._lastNonSpaceChar(block.previous()) charsMatch = ( lastChar == '(' and char == ')' ) or \ ( lastChar == '{' and char == '}' ) or \ ( lastChar == '[' and char == ']' ) indentation = None if (not charsMatch) and char != '}': # otherwise check whether the last line has the expected # indentation, if not use it instead and place the closing # anchor on the level of the opening anchor expectedIndentation = self._increaseIndent(self._blockIndent(foundBlock)) actualIndentation = self._increaseIndent(self._blockIndent(block.previous())) indentation = None if len(expectedIndentation) <= len(actualIndentation): if lastChar == ',': # use indentation of last line instead and place closing anchor # in same column of the opening anchor self._qpart.insertText((block.blockNumber(), self._firstNonSpaceColumn(block.text())), '\n') self._qpart.cursorPosition = (block.blockNumber(), len(actualIndentation)) # indent closing anchor self._setBlockIndent(block.next(), self._makeIndentAsColumn(foundBlock, foundColumn)) indentation = actualIndentation elif expectedIndentation == self._blockIndent(block.previous()): # otherwise don't add a new line, just use indentation of closing anchor line indentation = self._blockIndent(foundBlock) else: # otherwise don't add a new line, just align on closing anchor indentation = self._makeIndentAsColumn(foundBlock, foundColumn) dbg("tryMatchedAnchor: success in line %d" % foundBlock.blockNumber()) return indentation # otherwise we i.e. pressed enter between (), [] or when we enter before curly brace # increase indentation and place closing anchor on the next line indentation = self._blockIndent(foundBlock) self._qpart.replaceText((block.blockNumber(), 0), len(self._blockIndent(block)), "\n") self._qpart.cursorPosition = (block.blockNumber(), len(indentation)) # indent closing brace self._setBlockIndent(block.next(), indentation) dbg("tryMatchedAnchor: success in line %d" % foundBlock.blockNumber()) return self._increaseIndent(indentation)
def tryMatchedAnchor(self, block, autoIndent)
find out whether we pressed return in something like {} or () or [] and indent properly: {} becomes: { | }
4.792859
4.716011
1.016295
indent = None if indent is None: indent = self.tryMatchedAnchor(block, autoIndent) if indent is None: indent = self.tryCComment(block) if indent is None and not autoIndent: indent = self.tryCppComment(block) if indent is None: indent = self.trySwitchStatement(block) if indent is None: indent = self.tryAccessModifiers(block) if indent is None: indent = self.tryBrace(block) if indent is None: indent = self.tryCKeywords(block, block.text().lstrip().startswith('{')) if indent is None: indent = self.tryCondition(block) if indent is None: indent = self.tryStatement(block) if indent is not None: return indent else: dbg("Nothing matched") return self._prevNonEmptyBlockIndent(block)
def indentLine(self, block, autoIndent)
Indent line. Return filler or null.
3.397178
3.429959
0.990443
while block.isValid(): column = self._lastColumn(block) if column > 0: return block, column block = block.previous() raise UserWarning()
def _findExpressionEnd(self, block)
Find end of the last expression
8.270486
7.890786
1.048119
for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: return text
def _lastWord(self, text)
Move backward to the start of the word at the end of a string. Return the word
4.540156
4.942793
0.918541
# raise expession on next level, if not found expEndBlock, expEndColumn = self._findExpressionEnd(block) text = expEndBlock.text()[:expEndColumn + 1] if text.endswith(')'): try: return self.findBracketBackward(expEndBlock, expEndColumn, '(') except ValueError: raise UserWarning() else: return expEndBlock, len(text) - len(self._lastWord(text))
def _findExpressionStart(self, block)
Find start of not finished expression Raise UserWarning, if not found
7.738449
6.527434
1.185527
try: foundBlock, foundColumn = self._findExpressionStart(block.previous()) except UserWarning: return '' expression = foundBlock.text()[foundColumn:].rstrip() beforeExpression = foundBlock.text()[:foundColumn].strip() if beforeExpression.startswith('(module'): # special case return '' elif beforeExpression.endswith('define'): # special case return ' ' * (len(beforeExpression) - len('define') + 1) elif beforeExpression.endswith('let'): # special case return ' ' * (len(beforeExpression) - len('let') + 1) else: return ' ' * foundColumn
def computeSmartIndent(self, block, char)
Compute indent for the block
3.939844
3.966448
0.993293
indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter)
def _getSmartIndenter(indenterName, qpart, indenter)
Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols
2.039177
1.858678
1.097112
currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent)
def autoIndentBlock(self, block, char='\n')
Indent block after Enter pressed or trigger character typed
4.70889
4.652612
1.012096
def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith(self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if(cursor.selectionStart() != cursor.selectionEnd() and endBlock.position() == cursor.selectionEnd() and endBlock.previous().isValid()): endBlock = endBlock.previous() # do not indent not selected line if indenting multiple lines indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock)
def onChangeSelectedBlocksIndent(self, increase, withSpace=False)
Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks
2.82598
2.814246
1.004169
cursor = self._qpart.textCursor() def insertIndent(): if self.useTabs: cursor.insertText('\t') else: # indent to integer count of indents from line start charsToInsert = self.width - (len(self._qpart.textBeforeCursor()) % self.width) cursor.insertText(' ' * charsToInsert) if cursor.positionInBlock() == 0: # if no any indent - indent smartly block = cursor.block() self.autoIndentBlock(block, '') # if no smart indentation - just insert one indent if self._qpart.textBeforeCursor() == '': insertIndent() else: insertIndent()
def onShortcutIndentAfterCursor(self)
Tab pressed and no selection. Insert text after cursor
6.192763
6.406634
0.966617
assert self._qpart.textBeforeCursor().endswith(self.text()) charsToRemove = len(self._qpart.textBeforeCursor()) % len(self.text()) if charsToRemove == 0: charsToRemove = len(self.text()) cursor = self._qpart.textCursor() cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText()
def onShortcutUnindentWithBackspace(self)
Backspace pressed, unindent
3.40765
3.367619
1.011887
cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: self.autoIndentBlock(block, '') block = block.next() else: # indent 1 line self.autoIndentBlock(startBlock, '')
def onAutoIndentTriggered(self)
Indent current line or selected lines
3.806898
3.753916
1.014114
if syntax.indenter is not None: try: return _getSmartIndenter(syntax.indenter, self._qpart, self) except KeyError: logger.error("Indenter '%s' is not finished yet. But you can do it!" % syntax.indenter) try: return _getSmartIndenter(syntax.name, self._qpart, self) except KeyError: pass return _getSmartIndenter('normal', self._qpart, self)
def _chooseSmartIndenter(self, syntax)
Get indenter for syntax
4.004191
3.76589
1.063279
def _replaceFunc(escapeMatchObject): char = escapeMatchObject.group(0)[1] if char in _escapeSequences: return _escapeSequences[char] return escapeMatchObject.group(0) # no any replacements, return original value return _seqReplacer.sub(_replaceFunc, replaceText)
def _processEscapeSequences(replaceText)
Replace symbols like \n \\, etc
5.821161
5.591548
1.041064
rules = [] for ruleElement in xmlElement.getchildren(): if not ruleElement.tag in _ruleClassDict: raise ValueError("Not supported rule '%s'" % ruleElement.tag) rule = _ruleClassDict[ruleElement.tag](context, ruleElement, attributeToFormatMap) rules.append(rule) return rules
def _loadChildRules(context, xmlElement, attributeToFormatMap)
Extract rules from Context or Rule xml element
2.614505
2.467233
1.059691
attribute = _safeGetRequiredAttribute(xmlElement, 'attribute', '<not set>').lower() if attribute != '<not set>': # there are no attributes for internal contexts, used by rules. See perl.xml try: format = attributeToFormatMap[attribute] except KeyError: _logger.warning('Unknown context attribute %s', attribute) format = TextFormat() else: format = None textType = format.textType if format is not None else ' ' if format is not None: format = _convertFormat(format) lineEndContextText = xmlElement.attrib.get('lineEndContext', '#stay') lineEndContext = _makeContextSwitcher(lineEndContextText, context.parser) lineBeginContextText = xmlElement.attrib.get('lineBeginContext', '#stay') lineBeginContext = _makeContextSwitcher(lineBeginContextText, context.parser) lineEmptyContextText = xmlElement.attrib.get('lineEmptyContext', '#stay') lineEmptyContext = _makeContextSwitcher(lineEmptyContextText, context.parser) if _parseBoolAttribute(xmlElement.attrib.get('fallthrough', 'false')): fallthroughContextText = _safeGetRequiredAttribute(xmlElement, 'fallthroughContext', '#stay') fallthroughContext = _makeContextSwitcher(fallthroughContextText, context.parser) else: fallthroughContext = None dynamic = _parseBoolAttribute(xmlElement.attrib.get('dynamic', 'false')) context.setValues(attribute, format, lineEndContext, lineBeginContext, lineEmptyContext, fallthroughContext, dynamic, textType) # load rules rules = _loadChildRules(context, xmlElement, attributeToFormatMap) context.setRules(rules)
def _loadContext(context, xmlElement, attributeToFormatMap)
Construct context from XML element Contexts are at first constructed, and only then loaded, because when loading context, _makeContextSwitcher must have references to all defined contexts
3.221663
3.151051
1.022409
if 'here' in attribute.lower() and defStyleName == 'dsOthers': return 'h' # ruby elif 'block' in attribute.lower() and defStyleName == 'dsComment': return 'b' elif defStyleName in ('dsString', 'dsRegionMarker', 'dsChar', 'dsOthers'): return 's' elif defStyleName == 'dsComment': return 'c' else: return ' '
def _textTypeForDefStyleName(attribute, defStyleName)
' ' for code 'c' for comments 'b' for block comments 'h' for here documents
5.385108
4.443234
1.211979
prevBlockText = block.previous().text() # invalid block returns empty text if char == '\n' and \ prevBlockText.strip() == '': # continue indentation, if no text return self._prevBlockIndent(block) else: # be smart return self.computeSmartIndent(block, char)
def computeIndent(self, block, char)
Compute indent for the block. Basic alorightm, which knows nothing about programming languages May be used by child classes
10.269018
10.962174
0.936768
if indent.endswith(self._qpartIndent()): return indent[:-len(self._qpartIndent())] else: # oops, strange indentation, just return previous indent return indent
def _decreaseIndent(self, indent)
Remove 1 indentation level
9.827108
9.847195
0.99796
if self._indenter.useTabs: tabCount, spaceCount = divmod(width, self._indenter.width) return ('\t' * tabCount) + (' ' * spaceCount) else: return ' ' * width
def _makeIndentFromWidth(self, width)
Make indent text with specified with. Contains width count of spaces, or tabs and spaces
3.498505
3.188194
1.097331
blockText = block.text() textBeforeColumn = blockText[:column] tabCount = textBeforeColumn.count('\t') visibleColumn = column + (tabCount * (self._indenter.width - 1)) return self._makeIndentFromWidth(visibleColumn + offset)
def _makeIndentAsColumn(self, block, column, offset=0)
Make indent equal to column indent. Shiftted by offset
5.910782
5.832537
1.013415
currentIndent = self._blockIndent(block) self._qpart.replaceText((block.blockNumber(), 0), len(currentIndent), indent)
def _setBlockIndent(self, block, indent)
Set blocks indent. Modify text in qpart
12.613752
7.192689
1.753691
count = 0 while block.isValid() and count < MAX_SEARCH_OFFSET_LINES: yield block block = block.next() count += 1
def iterateBlocksFrom(block)
Generator, which iterates QTextBlocks from block until the End of a document But, yields not more than MAX_SEARCH_OFFSET_LINES
5.792411
2.496227
2.320467
count = 0 while block.isValid() and count < MAX_SEARCH_OFFSET_LINES: yield block block = block.previous() count += 1
def iterateBlocksBackFrom(block)
Generator, which iterates QTextBlocks from block until the Start of a document But, yields not more than MAX_SEARCH_OFFSET_LINES
6.11492
2.557805
2.39069
if bracket in ('(', ')'): opening = '(' closing = ')' elif bracket in ('[', ']'): opening = '[' closing = ']' elif bracket in ('{', '}'): opening = '{' closing = '}' else: raise AssertionError('Invalid bracket "%s"' % bracket) depth = 1 for foundBlock, foundColumn, char in self.iterateCharsBackwardFrom(block, column): if not self._qpart.isComment(foundBlock.blockNumber(), foundColumn): if char == opening: depth = depth - 1 elif char == closing: depth = depth + 1 if depth == 0: return foundBlock, foundColumn else: raise ValueError('Not found')
def findBracketBackward(self, block, column, bracket)
Search for a needle and return (block, column) Raise ValueError, if not found NOTE this method ignores comments
3.169486
2.901369
1.09241
depth = {'()': 1, '[]': 1, '{}': 1 } for foundBlock, foundColumn, char in self.iterateCharsBackwardFrom(block, column): if self._qpart.isCode(foundBlock.blockNumber(), foundColumn): for brackets in depth.keys(): opening, closing = brackets if char == opening: depth[brackets] -= 1 if depth[brackets] == 0: return foundBlock, foundColumn elif char == closing: depth[brackets] += 1 else: raise ValueError('Not found')
def findAnyBracketBackward(self, block, column)
Search for a needle and return (block, column) Raise ValueError, if not found NOTE this methods ignores strings and comments
4.782383
4.437032
1.077834
text = block.text() index = len(block.text()) - 1 while index >= 0 and \ (text[index].isspace() or \ self._qpart.isComment(block.blockNumber(), index)): index -= 1 return index
def _lastColumn(self, block)
Returns the last non-whitespace column in the given line. If there are only whitespaces in the line, the return value is -1.
4.976908
4.134857
1.203647
textAfter = block.text()[column:] if textAfter.strip(): spaceLen = len(textAfter) - len(textAfter.lstrip()) return column + spaceLen else: return -1
def _nextNonSpaceColumn(block, column)
Returns the column with a non-whitespace characters starting at the given cursor position and searching forwards.
3.494047
3.717322
0.939937
values = [arg[len(param_start):] for arg in sys.argv if arg.startswith(param_start)] # remove recognized arguments from the sys.argv otherArgs = [arg for arg in sys.argv if not arg.startswith(param_start)] sys.argv = otherArgs return values
def parse_arg_list(param_start)
Exctract values like --libdir=bla/bla/bla param_start must be '--libdir='
3.615802
2.988928
1.209732
compiler = distutils.ccompiler.new_compiler() if not compiler.has_function('rand', includes=['stdlib.h']): print("It seems like C compiler is not installed or not operable.") return False if not compiler.has_function('rand', includes=['stdlib.h', 'Python.h'], include_dirs=[distutils.sysconfig.get_python_inc()], library_dirs=[os.path.join(os.path.dirname(sys.executable), 'libs')]): print("Failed to find Python headers.") print("Try to install python-dev package") print("If not standard directories are used, pass parameters") print("\tpython setup.py install --lib-dir=c://github/pcre-8.37/build/Release --include-dir=c://github/pcre-8.37/build") print("\tpython setup.py install --lib-dir=/my/local/lib --include-dir=/my/local/include") print("--lib-dir= and --include-dir= may be used multiple times") return False if not compiler.has_function('pcre_version', includes=['pcre.h'], libraries=['pcre'], include_dirs=include_dirs, library_dirs=library_dirs): print("Failed to find pcre library.") print("Try to install libpcre{version}-dev package, or go to http://pcre.org") print("If not standard directories are used, pass parameters:") print("\tpython setup.py install --lib-dir=c://github/pcre-8.37/build/Release --include-dir=c://github/pcre-8.37/build") print("\tpython setup.py install --lib-dir=/my/local/lib --include-dir=/my/local/include") print("--lib-dir= and --include-dir= may be used multiple times") return False return True
def _checkBuildDependencies()
check if function without parameters from stdlib can be called There should be better way to check, if C compiler is installed
3.175316
3.043029
1.043472
text = ev.text() if len(text) != 1: return False if ev.modifiers() not in (Qt.ShiftModifier, Qt.KeypadModifier, Qt.NoModifier): return False asciiCode = ord(text) if asciiCode <= 31 or asciiCode == 0x7f: # control characters return False if text == ' ' and ev.modifiers() == Qt.ShiftModifier: return False # Shift+Space is a shortcut, not a text return True
def isChar(ev)
Check if an event may be a typed character
3.29212
3.179575
1.035396
if ev.key() in (Qt.Key_Shift, Qt.Key_Control, Qt.Key_Meta, Qt.Key_Alt, Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_ScrollLock): return False # ignore modifier pressing. Will process key pressing later self._processingKeyPress = True try: ret = self._mode.keyPressEvent(ev) finally: self._processingKeyPress = False return ret
def keyPressEvent(self, ev)
Check the event. Return True if processed and False otherwise
3.608858
3.35046
1.077123
if not isinstance(self._mode, Normal): return [] selection = QTextEdit.ExtraSelection() selection.format.setBackground(QColor('#ffcc22')) selection.format.setForeground(QColor('#000000')) selection.cursor = self._qpart.textCursor() selection.cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) return [selection]
def extraSelections(self)
In normal mode - QTextEdit.ExtraSelection which highlightes the cursor
3.466465
2.820952
1.228828
# Chars in the start line for columnIndex, char in list(enumerate(block.text()))[startColumnIndex:]: yield block, columnIndex, char block = block.next() # Next lines while block.isValid(): for columnIndex, char in enumerate(block.text()): yield block, columnIndex, char block = block.next()
def _iterateDocumentCharsForward(self, block, startColumnIndex)
Traverse document forward. Yield (block, columnIndex, char) Raise _TimeoutException if time is over
4.066825
3.694479
1.100784
# Chars in the start line for columnIndex, char in reversed(list(enumerate(block.text()[:startColumnIndex]))): yield block, columnIndex, char block = block.previous() # Next lines while block.isValid(): for columnIndex, char in reversed(list(enumerate(block.text()))): yield block, columnIndex, char block = block.previous()
def _iterateDocumentCharsBackward(self, block, startColumnIndex)
Traverse document forward. Yield (block, columnIndex, char) Raise _TimeoutException if time is over
3.405597
3.078747
1.106163
ancor, pos = self._qpart.selectedPosition dst = min(ancor, pos) if moveToTop else pos self._qpart.cursorPosition = dst
def _resetSelection(self, moveToTop=False)
Reset selection. If moveToTop is True - move cursor to the top position
13.231333
12.599551
1.050143
(startLine, startCol), (endLine, endCol) = self._qpart.selectedPosition start = min(startLine, endLine) end = max(startLine, endLine) return start, end
def _selectedLinesRange(self)
Selected lines range for line manipulation methods
4.202259
4.151816
1.01215
if count != 1: with self._qpart: for _ in range(count): func() else: func()
def _repeat(self, count, func)
Repeat action 1 or more times. If more than one - do it as 1 undoble action
6.353156
5.826901
1.090315
cursor = self._qpart.textCursor() for _ in range(count): cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) if cursor.selectedText(): _globalClipboard.value = cursor.selectedText() cursor.removeSelectedText() self._saveLastEditSimpleCmd(cmd, count) self.switchMode(Insert)
def cmdSubstitute(self, cmd, count)
s
7.547495
7.338348
1.028501
lineIndex = self._qpart.cursorPosition[0] availableCount = len(self._qpart.lines) - lineIndex effectiveCount = min(availableCount, count) _globalClipboard.value = self._qpart.lines[lineIndex:lineIndex + effectiveCount] with self._qpart: del self._qpart.lines[lineIndex:lineIndex + effectiveCount] self._qpart.lines.insert(lineIndex, '') self._qpart.cursorPosition = (lineIndex, 0) self._qpart._indenter.autoIndentBlock(self._qpart.textCursor().block()) self._saveLastEditSimpleCmd(cmd, count) self.switchMode(Insert)
def cmdSubstituteLines(self, cmd, count)
S
5.127576
5.031331
1.019129
cursor = self._qpart.textCursor() direction = QTextCursor.Left if cmd == _X else QTextCursor.Right for _ in range(count): cursor.movePosition(direction, QTextCursor.KeepAnchor) if cursor.selectedText(): _globalClipboard.value = cursor.selectedText() cursor.removeSelectedText() self._saveLastEditSimpleCmd(cmd, count)
def cmdDelete(self, cmd, count)
x
7.019457
6.554157
1.070993
cursor = self._qpart.textCursor() for _ in range(count - 1): cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) _globalClipboard.value = cursor.selectedText() cursor.removeSelectedText() if cmd == _C: self.switchMode(Insert) self._saveLastEditSimpleCmd(cmd, count)
def cmdDeleteUntilEndOfBlock(self, cmd, count)
C and D
5.810463
5.63045
1.031971
lineStripped = block.text()[:column].strip() # empty text from invalid block is ok spaceLen = len(block.text()) - len(block.text().lstrip()) if lineStripped and \ lineStripped[-1] in ')]}': try: foundBlock, foundColumn = self.findBracketBackward(block, spaceLen + len(lineStripped) - 1, lineStripped[-1]) except ValueError: pass else: return self._computeSmartIndent(foundBlock, foundColumn) if len(lineStripped) > 1 and \ lineStripped[-1] == ',' and \ lineStripped[-2] in ')]}': try: foundBlock, foundColumn = self.findBracketBackward(block, len(block.text()[:column].rstrip()) - 2, lineStripped[-2]) except ValueError: pass else: return self._computeSmartIndent(foundBlock, foundColumn) try: foundBlock, foundColumn = self.findAnyBracketBackward(block, column) except ValueError: pass else: # indent this way only line, which contains 'y', not 'z' if foundBlock.blockNumber() == block.blockNumber(): return self._makeIndentAsColumn(foundBlock, foundColumn + 1) # finally, a raise, pass, and continue should unindent if lineStripped in ('continue', 'break', 'pass', 'raise', 'return') or \ lineStripped.startswith('raise ') or \ lineStripped.startswith('return '): return self._decreaseIndent(self._blockIndent(block)) if lineStripped.endswith(':'): newColumn = spaceLen + len(lineStripped) - 1 prevIndent = self._computeSmartIndent(block, newColumn) return self._increaseIndent(prevIndent) if lineStripped.endswith('{['): return self._increaseIndent(self._blockIndent(block)) return self._blockIndent(block)
def _computeSmartIndent(self, block, column)
Compute smart indent for case when cursor is on (block, column)
3.672979
3.590013
1.02311
self.text = '' self._completer.terminate() if self._highlighter is not None: self._highlighter.terminate() if self._vim is not None: self._vim.terminate()
def terminate(self)
Terminate Qutepart instance. This method MUST be called before application stop to avoid crashes and some other interesting effects Call it on close to free memory and stop background highlighting
4.96046
4.581962
1.082606
def createAction(text, shortcut, slot, iconFileName=None): action = QAction(text, self) if iconFileName is not None: action.setIcon(getIcon(iconFileName)) keySeq = shortcut if isinstance(shortcut, QKeySequence) else QKeySequence(shortcut) action.setShortcut(keySeq) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(slot) self.addAction(action) return action # scrolling self.scrollUpAction = createAction('Scroll up', 'Ctrl+Up', lambda: self._onShortcutScroll(down = False), 'go-up') self.scrollDownAction = createAction('Scroll down', 'Ctrl+Down', lambda: self._onShortcutScroll(down = True), 'go-down') self.selectAndScrollUpAction = createAction('Select and scroll Up', 'Ctrl+Shift+Up', lambda: self._onShortcutSelectAndScroll(down = False)) self.selectAndScrollDownAction = createAction('Select and scroll Down', 'Ctrl+Shift+Down', lambda: self._onShortcutSelectAndScroll(down = True)) # indentation self.increaseIndentAction = createAction('Increase indentation', 'Tab', self._onShortcutIndent, 'format-indent-more') self.decreaseIndentAction = createAction('Decrease indentation', 'Shift+Tab', lambda: self._indenter.onChangeSelectedBlocksIndent(increase = False), 'format-indent-less') self.autoIndentLineAction = createAction('Autoindent line', 'Ctrl+I', self._indenter.onAutoIndentTriggered) self.indentWithSpaceAction = createAction('Indent with 1 space', 'Ctrl+Shift+Space', lambda: self._indenter.onChangeSelectedBlocksIndent(increase=True, withSpace=True)) self.unIndentWithSpaceAction = createAction('Unindent with 1 space', 'Ctrl+Shift+Backspace', lambda: self._indenter.onChangeSelectedBlocksIndent(increase=False, withSpace=True)) # editing self.undoAction = createAction('Undo', QKeySequence.Undo, self.undo, 'edit-undo') self.redoAction = createAction('Redo', QKeySequence.Redo, self.redo, 'edit-redo') self.moveLineUpAction = createAction('Move line up', 'Alt+Up', lambda: self._onShortcutMoveLine(down = False), 'go-up') self.moveLineDownAction = createAction('Move line down', 'Alt+Down', lambda: self._onShortcutMoveLine(down = True), 'go-down') self.deleteLineAction = createAction('Delete line', 'Alt+Del', self._onShortcutDeleteLine, 'edit-delete') self.cutLineAction = createAction('Cut line', 'Alt+X', self._onShortcutCutLine, 'edit-cut') self.copyLineAction = createAction('Copy line', 'Alt+C', self._onShortcutCopyLine, 'edit-copy') self.pasteLineAction = createAction('Paste line', 'Alt+V', self._onShortcutPasteLine, 'edit-paste') self.duplicateLineAction = createAction('Duplicate line', 'Alt+D', self._onShortcutDuplicateLine) self.invokeCompletionAction = createAction('Invoke completion', 'Ctrl+Space', self._completer.invokeCompletion) # other self.printAction = createAction('Print', 'Ctrl+P', self._onShortcutPrint, 'document-print')
def _initActions(self)
Init shortcuts for text editing
2.008979
1.970032
1.01977
self.setTabStopWidth(self.fontMetrics().width(' ' * self._indenter.width))
def _updateTabStopWidth(self)
Update tabstop width after font or indentation changed
10.127176
7.446001
1.360083
lines = self.text.splitlines() if self.text.endswith('\n'): # splitlines ignores last \n lines.append('') return self.eol.join(lines) + self.eol
def textForSaving(self)
Get text with correct EOL symbols. Use this method for saving a file to storage
5.287075
4.729105
1.117986
cursor = self.textCursor() cursor.setPosition(cursor.position()) self.setTextCursor(cursor)
def resetSelection(self)
Reset selection. Nothing will be selected.
4.278551
3.898312
1.097539
if isinstance(pos, tuple): pos = self.mapToAbsPosition(*pos) endPos = pos + length if not self.document().findBlock(pos).isValid(): raise IndexError('Invalid start position %d' % pos) if not self.document().findBlock(endPos).isValid(): raise IndexError('Invalid end position %d' % endPos) cursor = QTextCursor(self.document()) cursor.setPosition(pos) cursor.setPosition(endPos, QTextCursor.KeepAnchor) cursor.insertText(text)
def replaceText(self, pos, length, text)
Replace length symbols from ``pos`` with new text. If ``pos`` is an integer, it is interpreted as absolute position, if a tuple - as ``(line, column)``
2.397706
2.376851
1.008774