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
... | 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.setDocumentM... | 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)
... | 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 ... | 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:
... | 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.ExtraSele... | 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' ... | 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.cursorP... | 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:
... | 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 = s... | 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" )
... | 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._... | 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 = Synt... | 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 Non... | 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.... | 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 conte... | 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(textToM... | 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... | 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 ^ - chec... | 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.compil... | 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.cu... | 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(),
... | 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,
... | 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:
w... | 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().rfin... | 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 lin... | 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, '{')
exce... | 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, not... | 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 comm... | 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.f... | 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)', cur... | 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.findBracketBackw... | 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:
... | 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, '(')
... | 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.startswi... | 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
... | 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.repl... | 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 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)
... | 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()... | 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()
... | 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 _getSmartIn... | 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)
retur... | 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.warni... | 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 == 'dsComme... | 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(bloc... | 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('I... | 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():
... | 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
retu... | 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', 'Pytho... | 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.mod... | 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
... | 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.m... | 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()):
... | 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(enum... | 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._saveLastEditSi... | 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... | 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()
... | 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.removeSelected... | 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.findBracket... | 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(shortcu... | 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():
rais... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.