repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
andreikop/qutepart | qutepart/indenter/__init__.py | Indenter.onShortcutIndentAfterCursor | def onShortcutIndentAfterCursor(self):
"""Tab pressed and no selection. Insert text after cursor
"""
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() | python | def onShortcutIndentAfterCursor(self):
"""Tab pressed and no selection. Insert text after cursor
"""
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",
")",
":",
"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",
"(",
")"
] | Tab pressed and no selection. Insert text after cursor | [
"Tab",
"pressed",
"and",
"no",
"selection",
".",
"Insert",
"text",
"after",
"cursor"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L163-L183 |
andreikop/qutepart | qutepart/indenter/__init__.py | Indenter.onShortcutUnindentWithBackspace | def onShortcutUnindentWithBackspace(self):
"""Backspace pressed, unindent
"""
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() | python | def onShortcutUnindentWithBackspace(self):
"""Backspace pressed, unindent
"""
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",
")",
":",
"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",
"(",
")"
] | Backspace pressed, unindent | [
"Backspace",
"pressed",
"unindent"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L186-L197 |
andreikop/qutepart | qutepart/indenter/__init__.py | Indenter.onAutoIndentTriggered | def onAutoIndentTriggered(self):
"""Indent current line or selected lines
"""
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, '') | python | def onAutoIndentTriggered(self):
"""Indent current line or selected lines
"""
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",
")",
":",
"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",
",",
"''",
")"
] | Indent current line or selected lines | [
"Indent",
"current",
"line",
"or",
"selected",
"lines"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L199-L217 |
andreikop/qutepart | qutepart/indenter/__init__.py | Indenter._chooseSmartIndenter | def _chooseSmartIndenter(self, syntax):
"""Get indenter for syntax
"""
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) | python | def _chooseSmartIndenter(self, syntax):
"""Get indenter for syntax
"""
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",
")",
":",
"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",
")"
] | Get indenter for syntax | [
"Get",
"indenter",
"for",
"syntax"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L219-L233 |
andreikop/qutepart | qutepart/syntax/loader.py | _processEscapeSequences | def _processEscapeSequences(replaceText):
"""Replace symbols like \n \\, etc
"""
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) | python | def _processEscapeSequences(replaceText):
"""Replace symbols like \n \\, etc
"""
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",
")",
":",
"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",
")"
] | Replace symbols like \n \\, etc | [
"Replace",
"symbols",
"like",
"\\",
"n",
"\\\\",
"etc"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/loader.py#L40-L50 |
andreikop/qutepart | qutepart/syntax/loader.py | _loadChildRules | def _loadChildRules(context, xmlElement, attributeToFormatMap):
"""Extract rules from Context or Rule xml element
"""
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 | python | def _loadChildRules(context, xmlElement, attributeToFormatMap):
"""Extract rules from Context or Rule xml element
"""
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",
")",
":",
"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"
] | Extract rules from Context or Rule xml element | [
"Extract",
"rules",
"from",
"Context",
"or",
"Rule",
"xml",
"element"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/loader.py#L196-L205 |
andreikop/qutepart | qutepart/syntax/loader.py | _loadContext | 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
"""
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) | python | 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
"""
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",
")",
":",
"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",
")"
] | 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 | [
"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"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/loader.py#L419-L457 |
andreikop/qutepart | qutepart/syntax/loader.py | _textTypeForDefStyleName | def _textTypeForDefStyleName(attribute, defStyleName):
""" ' ' for code
'c' for comments
'b' for block comments
'h' for here documents
"""
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 ' ' | python | def _textTypeForDefStyleName(attribute, defStyleName):
""" ' ' for code
'c' for comments
'b' for block comments
'h' for here documents
"""
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",
")",
":",
"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",
"' '"
] | ' ' for code
'c' for comments
'b' for block comments
'h' for here documents | [
"for",
"code",
"c",
"for",
"comments",
"b",
"for",
"block",
"comments",
"h",
"for",
"here",
"documents"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/loader.py#L462-L477 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase.computeIndent | def computeIndent(self, block, char):
"""Compute indent for the block.
Basic alorightm, which knows nothing about programming languages
May be used by child classes
"""
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) | python | def computeIndent(self, block, char):
"""Compute indent for the block.
Basic alorightm, which knows nothing about programming languages
May be used by child classes
"""
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",
")",
":",
"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",
")"
] | Compute indent for the block.
Basic alorightm, which knows nothing about programming languages
May be used by child classes | [
"Compute",
"indent",
"for",
"the",
"block",
".",
"Basic",
"alorightm",
"which",
"knows",
"nothing",
"about",
"programming",
"languages",
"May",
"be",
"used",
"by",
"child",
"classes"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L29-L39 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase._decreaseIndent | def _decreaseIndent(self, indent):
"""Remove 1 indentation level
"""
if indent.endswith(self._qpartIndent()):
return indent[:-len(self._qpartIndent())]
else: # oops, strange indentation, just return previous indent
return indent | python | def _decreaseIndent(self, indent):
"""Remove 1 indentation level
"""
if indent.endswith(self._qpartIndent()):
return indent[:-len(self._qpartIndent())]
else: # oops, strange indentation, just return previous indent
return indent | [
"def",
"_decreaseIndent",
"(",
"self",
",",
"indent",
")",
":",
"if",
"indent",
".",
"endswith",
"(",
"self",
".",
"_qpartIndent",
"(",
")",
")",
":",
"return",
"indent",
"[",
":",
"-",
"len",
"(",
"self",
".",
"_qpartIndent",
"(",
")",
")",
"]",
"else",
":",
"# oops, strange indentation, just return previous indent",
"return",
"indent"
] | Remove 1 indentation level | [
"Remove",
"1",
"indentation",
"level"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L63-L69 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase._makeIndentFromWidth | def _makeIndentFromWidth(self, width):
"""Make indent text with specified with.
Contains width count of spaces, or tabs and spaces
"""
if self._indenter.useTabs:
tabCount, spaceCount = divmod(width, self._indenter.width)
return ('\t' * tabCount) + (' ' * spaceCount)
else:
return ' ' * width | python | def _makeIndentFromWidth(self, width):
"""Make indent text with specified with.
Contains width count of spaces, or tabs and spaces
"""
if self._indenter.useTabs:
tabCount, spaceCount = divmod(width, self._indenter.width)
return ('\t' * tabCount) + (' ' * spaceCount)
else:
return ' ' * width | [
"def",
"_makeIndentFromWidth",
"(",
"self",
",",
"width",
")",
":",
"if",
"self",
".",
"_indenter",
".",
"useTabs",
":",
"tabCount",
",",
"spaceCount",
"=",
"divmod",
"(",
"width",
",",
"self",
".",
"_indenter",
".",
"width",
")",
"return",
"(",
"'\\t'",
"*",
"tabCount",
")",
"+",
"(",
"' '",
"*",
"spaceCount",
")",
"else",
":",
"return",
"' '",
"*",
"width"
] | Make indent text with specified with.
Contains width count of spaces, or tabs and spaces | [
"Make",
"indent",
"text",
"with",
"specified",
"with",
".",
"Contains",
"width",
"count",
"of",
"spaces",
"or",
"tabs",
"and",
"spaces"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L71-L79 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase._makeIndentAsColumn | def _makeIndentAsColumn(self, block, column, offset=0):
""" Make indent equal to column indent.
Shiftted by offset
"""
blockText = block.text()
textBeforeColumn = blockText[:column]
tabCount = textBeforeColumn.count('\t')
visibleColumn = column + (tabCount * (self._indenter.width - 1))
return self._makeIndentFromWidth(visibleColumn + offset) | python | def _makeIndentAsColumn(self, block, column, offset=0):
""" Make indent equal to column indent.
Shiftted by offset
"""
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",
")",
":",
"blockText",
"=",
"block",
".",
"text",
"(",
")",
"textBeforeColumn",
"=",
"blockText",
"[",
":",
"column",
"]",
"tabCount",
"=",
"textBeforeColumn",
".",
"count",
"(",
"'\\t'",
")",
"visibleColumn",
"=",
"column",
"+",
"(",
"tabCount",
"*",
"(",
"self",
".",
"_indenter",
".",
"width",
"-",
"1",
")",
")",
"return",
"self",
".",
"_makeIndentFromWidth",
"(",
"visibleColumn",
"+",
"offset",
")"
] | Make indent equal to column indent.
Shiftted by offset | [
"Make",
"indent",
"equal",
"to",
"column",
"indent",
".",
"Shiftted",
"by",
"offset"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L81-L90 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase._setBlockIndent | def _setBlockIndent(self, block, indent):
"""Set blocks indent. Modify text in qpart
"""
currentIndent = self._blockIndent(block)
self._qpart.replaceText((block.blockNumber(), 0), len(currentIndent), indent) | python | def _setBlockIndent(self, block, indent):
"""Set blocks indent. Modify text in qpart
"""
currentIndent = self._blockIndent(block)
self._qpart.replaceText((block.blockNumber(), 0), len(currentIndent), indent) | [
"def",
"_setBlockIndent",
"(",
"self",
",",
"block",
",",
"indent",
")",
":",
"currentIndent",
"=",
"self",
".",
"_blockIndent",
"(",
"block",
")",
"self",
".",
"_qpart",
".",
"replaceText",
"(",
"(",
"block",
".",
"blockNumber",
"(",
")",
",",
"0",
")",
",",
"len",
"(",
"currentIndent",
")",
",",
"indent",
")"
] | Set blocks indent. Modify text in qpart | [
"Set",
"blocks",
"indent",
".",
"Modify",
"text",
"in",
"qpart"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L92-L96 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase.iterateBlocksFrom | def iterateBlocksFrom(block):
"""Generator, which iterates QTextBlocks from block until the End of a document
But, yields not more than MAX_SEARCH_OFFSET_LINES
"""
count = 0
while block.isValid() and count < MAX_SEARCH_OFFSET_LINES:
yield block
block = block.next()
count += 1 | python | def iterateBlocksFrom(block):
"""Generator, which iterates QTextBlocks from block until the End of a document
But, yields not more than MAX_SEARCH_OFFSET_LINES
"""
count = 0
while block.isValid() and count < MAX_SEARCH_OFFSET_LINES:
yield block
block = block.next()
count += 1 | [
"def",
"iterateBlocksFrom",
"(",
"block",
")",
":",
"count",
"=",
"0",
"while",
"block",
".",
"isValid",
"(",
")",
"and",
"count",
"<",
"MAX_SEARCH_OFFSET_LINES",
":",
"yield",
"block",
"block",
"=",
"block",
".",
"next",
"(",
")",
"count",
"+=",
"1"
] | Generator, which iterates QTextBlocks from block until the End of a document
But, yields not more than MAX_SEARCH_OFFSET_LINES | [
"Generator",
"which",
"iterates",
"QTextBlocks",
"from",
"block",
"until",
"the",
"End",
"of",
"a",
"document",
"But",
"yields",
"not",
"more",
"than",
"MAX_SEARCH_OFFSET_LINES"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L99-L107 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase.iterateBlocksBackFrom | def iterateBlocksBackFrom(block):
"""Generator, which iterates QTextBlocks from block until the Start of a document
But, yields not more than MAX_SEARCH_OFFSET_LINES
"""
count = 0
while block.isValid() and count < MAX_SEARCH_OFFSET_LINES:
yield block
block = block.previous()
count += 1 | python | def iterateBlocksBackFrom(block):
"""Generator, which iterates QTextBlocks from block until the Start of a document
But, yields not more than MAX_SEARCH_OFFSET_LINES
"""
count = 0
while block.isValid() and count < MAX_SEARCH_OFFSET_LINES:
yield block
block = block.previous()
count += 1 | [
"def",
"iterateBlocksBackFrom",
"(",
"block",
")",
":",
"count",
"=",
"0",
"while",
"block",
".",
"isValid",
"(",
")",
"and",
"count",
"<",
"MAX_SEARCH_OFFSET_LINES",
":",
"yield",
"block",
"block",
"=",
"block",
".",
"previous",
"(",
")",
"count",
"+=",
"1"
] | Generator, which iterates QTextBlocks from block until the Start of a document
But, yields not more than MAX_SEARCH_OFFSET_LINES | [
"Generator",
"which",
"iterates",
"QTextBlocks",
"from",
"block",
"until",
"the",
"Start",
"of",
"a",
"document",
"But",
"yields",
"not",
"more",
"than",
"MAX_SEARCH_OFFSET_LINES"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L110-L118 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase.findBracketBackward | def findBracketBackward(self, block, column, bracket):
"""Search for a needle and return (block, column)
Raise ValueError, if not found
NOTE this method ignores comments
"""
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') | python | def findBracketBackward(self, block, column, bracket):
"""Search for a needle and return (block, column)
Raise ValueError, if not found
NOTE this method ignores comments
"""
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",
")",
":",
"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'",
")"
] | Search for a needle and return (block, column)
Raise ValueError, if not found
NOTE this method ignores comments | [
"Search",
"for",
"a",
"needle",
"and",
"return",
"(",
"block",
"column",
")",
"Raise",
"ValueError",
"if",
"not",
"found"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L132-L161 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase.findAnyBracketBackward | 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
"""
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') | python | 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
"""
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",
")",
":",
"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'",
")"
] | Search for a needle and return (block, column)
Raise ValueError, if not found
NOTE this methods ignores strings and comments | [
"Search",
"for",
"a",
"needle",
"and",
"return",
"(",
"block",
"column",
")",
"Raise",
"ValueError",
"if",
"not",
"found"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L163-L185 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase._lastColumn | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | Returns the last non-whitespace column in the given line.
If there are only whitespaces in the line, the return value is -1. | [
"Returns",
"the",
"last",
"non",
"-",
"whitespace",
"column",
"in",
"the",
"given",
"line",
".",
"If",
"there",
"are",
"only",
"whitespaces",
"in",
"the",
"line",
"the",
"return",
"value",
"is",
"-",
"1",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L257-L268 |
andreikop/qutepart | qutepart/indenter/base.py | IndentAlgBase._nextNonSpaceColumn | def _nextNonSpaceColumn(block, column):
"""Returns the column with a non-whitespace characters
starting at the given cursor position and searching forwards.
"""
textAfter = block.text()[column:]
if textAfter.strip():
spaceLen = len(textAfter) - len(textAfter.lstrip())
return column + spaceLen
else:
return -1 | python | def _nextNonSpaceColumn(block, column):
"""Returns the column with a non-whitespace characters
starting at the given cursor position and searching forwards.
"""
textAfter = block.text()[column:]
if textAfter.strip():
spaceLen = len(textAfter) - len(textAfter.lstrip())
return column + spaceLen
else:
return -1 | [
"def",
"_nextNonSpaceColumn",
"(",
"block",
",",
"column",
")",
":",
"textAfter",
"=",
"block",
".",
"text",
"(",
")",
"[",
"column",
":",
"]",
"if",
"textAfter",
".",
"strip",
"(",
")",
":",
"spaceLen",
"=",
"len",
"(",
"textAfter",
")",
"-",
"len",
"(",
"textAfter",
".",
"lstrip",
"(",
")",
")",
"return",
"column",
"+",
"spaceLen",
"else",
":",
"return",
"-",
"1"
] | Returns the column with a non-whitespace characters
starting at the given cursor position and searching forwards. | [
"Returns",
"the",
"column",
"with",
"a",
"non",
"-",
"whitespace",
"characters",
"starting",
"at",
"the",
"given",
"cursor",
"position",
"and",
"searching",
"forwards",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/base.py#L271-L280 |
andreikop/qutepart | setup.py | parse_arg_list | def parse_arg_list(param_start):
"""Exctract values like --libdir=bla/bla/bla
param_start must be '--libdir='
"""
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 | python | def parse_arg_list(param_start):
"""Exctract values like --libdir=bla/bla/bla
param_start must be '--libdir='
"""
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",
")",
":",
"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"
] | Exctract values like --libdir=bla/bla/bla
param_start must be '--libdir=' | [
"Exctract",
"values",
"like",
"--",
"libdir",
"=",
"bla",
"/",
"bla",
"/",
"bla",
"param_start",
"must",
"be",
"--",
"libdir",
"="
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/setup.py#L25-L39 |
andreikop/qutepart | setup.py | _checkBuildDependencies | def _checkBuildDependencies():
compiler = distutils.ccompiler.new_compiler()
"""check if function without parameters from stdlib can be called
There should be better way to check, if C compiler is installed
"""
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 | python | def _checkBuildDependencies():
compiler = distutils.ccompiler.new_compiler()
"""check if function without parameters from stdlib can be called
There should be better way to check, if C compiler is installed
"""
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",
"(",
")",
":",
"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"
] | check if function without parameters from stdlib can be called
There should be better way to check, if C compiler is installed | [
"check",
"if",
"function",
"without",
"parameters",
"from",
"stdlib",
"can",
"be",
"called",
"There",
"should",
"be",
"better",
"way",
"to",
"check",
"if",
"C",
"compiler",
"is",
"installed"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/setup.py#L83-L117 |
andreikop/qutepart | qutepart/vim.py | isChar | def isChar(ev):
""" Check if an event may be a typed character
"""
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 | python | def isChar(ev):
""" Check if an event may be a typed character
"""
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",
")",
":",
"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"
] | Check if an event may be a typed character | [
"Check",
"if",
"an",
"event",
"may",
"be",
"a",
"typed",
"character"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L47-L64 |
andreikop/qutepart | qutepart/vim.py | Vim.keyPressEvent | def keyPressEvent(self, ev):
"""Check the event. Return True if processed and False otherwise
"""
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 | python | def keyPressEvent(self, ev):
"""Check the event. Return True if processed and False otherwise
"""
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",
")",
":",
"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"
] | Check the event. Return True if processed and False otherwise | [
"Check",
"the",
"event",
".",
"Return",
"True",
"if",
"processed",
"and",
"False",
"otherwise"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L116-L130 |
andreikop/qutepart | qutepart/vim.py | Vim.extraSelections | def extraSelections(self):
""" In normal mode - QTextEdit.ExtraSelection which highlightes the cursor
"""
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] | python | def extraSelections(self):
""" In normal mode - QTextEdit.ExtraSelection which highlightes the cursor
"""
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",
")",
":",
"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",
"]"
] | In normal mode - QTextEdit.ExtraSelection which highlightes the cursor | [
"In",
"normal",
"mode",
"-",
"QTextEdit",
".",
"ExtraSelection",
"which",
"highlightes",
"the",
"cursor"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L145-L157 |
andreikop/qutepart | qutepart/vim.py | BaseCommandMode._moveCursor | def _moveCursor(self, motion, count, searchChar=None, select=False):
""" Move cursor.
Used by Normal and Visual mode
"""
cursor = self._qpart.textCursor()
effectiveCount = count or 1
moveMode = QTextCursor.KeepAnchor if select else QTextCursor.MoveAnchor
moveOperation = {_b: QTextCursor.WordLeft,
_j: QTextCursor.Down,
_Down: QTextCursor.Down,
_k: QTextCursor.Up,
_Up: QTextCursor.Up,
_h: QTextCursor.Left,
_Left: QTextCursor.Left,
_BackSpace: QTextCursor.Left,
_l: QTextCursor.Right,
_Right: QTextCursor.Right,
_Space: QTextCursor.Right,
_w: QTextCursor.WordRight,
_Dollar: QTextCursor.EndOfBlock,
_End: QTextCursor.EndOfBlock,
_0: QTextCursor.StartOfBlock,
_Home: QTextCursor.StartOfBlock,
'gg': QTextCursor.Start,
_G: QTextCursor.End
}
if motion == _G:
if count == 0: # default - go to the end
cursor.movePosition(QTextCursor.End, moveMode)
else: # if count is set - move to line
block = self._qpart.document().findBlockByNumber(count - 1)
if not block.isValid():
return
cursor.setPosition(block.position(), moveMode)
self.moveToFirstNonSpace(cursor, moveMode)
elif motion in moveOperation:
for _ in range(effectiveCount):
cursor.movePosition(moveOperation[motion], moveMode)
elif motion in (_e, _E):
for _ in range(effectiveCount):
# skip spaces
text = cursor.block().text()
pos = cursor.positionInBlock()
for char in text[pos:]:
if char.isspace():
cursor.movePosition(QTextCursor.NextCharacter, moveMode)
else:
break
if cursor.positionInBlock() == len(text): # at the end of line
cursor.movePosition(QTextCursor.NextCharacter, moveMode) # move to the next line
# now move to the end of word
if motion == _e:
cursor.movePosition(QTextCursor.EndOfWord, moveMode)
else:
text = cursor.block().text()
pos = cursor.positionInBlock()
for char in text[pos:]:
if not char.isspace():
cursor.movePosition(QTextCursor.NextCharacter, moveMode)
else:
break
elif motion == _B:
cursor.movePosition(QTextCursor.WordLeft, moveMode)
while cursor.positionInBlock() != 0 and \
(not cursor.block().text()[cursor.positionInBlock() - 1].isspace()):
cursor.movePosition(QTextCursor.WordLeft, moveMode)
elif motion == _W:
cursor.movePosition(QTextCursor.WordRight, moveMode)
while cursor.positionInBlock() != 0 and \
(not cursor.block().text()[cursor.positionInBlock() - 1].isspace()):
cursor.movePosition(QTextCursor.WordRight, moveMode)
elif motion == _Percent:
# Percent move is done only once
if self._qpart._bracketHighlighter.currentMatchedBrackets is not None:
((startBlock, startCol), (endBlock, endCol)) = self._qpart._bracketHighlighter.currentMatchedBrackets
startPos = startBlock.position() + startCol
endPos = endBlock.position() + endCol
if select and \
(endPos > startPos):
endPos += 1 # to select the bracket, not only chars before it
cursor.setPosition(endPos, moveMode)
elif motion == _Caret:
# Caret move is done only once
self.moveToFirstNonSpace(cursor, moveMode)
elif motion in (_f, _F, _t, _T):
if motion in (_f, _t):
iterator = self._iterateDocumentCharsForward(cursor.block(), cursor.columnNumber())
stepForward = QTextCursor.Right
stepBack = QTextCursor.Left
else:
iterator = self._iterateDocumentCharsBackward(cursor.block(), cursor.columnNumber())
stepForward = QTextCursor.Left
stepBack = QTextCursor.Right
for block, columnIndex, char in iterator:
if char == searchChar:
cursor.setPosition(block.position() + columnIndex, moveMode)
if motion in (_t, _T):
cursor.movePosition(stepBack, moveMode)
if select:
cursor.movePosition(stepForward, moveMode)
break
elif motion in (_PageDown, _PageUp):
cursorHeight = self._qpart.cursorRect().height()
qpartHeight = self._qpart.height()
visibleLineCount = qpartHeight / cursorHeight
direction = QTextCursor.Down if motion == _PageDown else QTextCursor.Up
for _ in range(int(visibleLineCount)):
cursor.movePosition(direction, moveMode)
elif motion in (_Enter, _Return):
if cursor.block().next().isValid(): # not the last line
for _ in range(effectiveCount):
cursor.movePosition(QTextCursor.NextBlock, moveMode)
self.moveToFirstNonSpace(cursor, moveMode)
else:
assert 0, 'Not expected motion ' + str(motion)
self._qpart.setTextCursor(cursor) | python | def _moveCursor(self, motion, count, searchChar=None, select=False):
""" Move cursor.
Used by Normal and Visual mode
"""
cursor = self._qpart.textCursor()
effectiveCount = count or 1
moveMode = QTextCursor.KeepAnchor if select else QTextCursor.MoveAnchor
moveOperation = {_b: QTextCursor.WordLeft,
_j: QTextCursor.Down,
_Down: QTextCursor.Down,
_k: QTextCursor.Up,
_Up: QTextCursor.Up,
_h: QTextCursor.Left,
_Left: QTextCursor.Left,
_BackSpace: QTextCursor.Left,
_l: QTextCursor.Right,
_Right: QTextCursor.Right,
_Space: QTextCursor.Right,
_w: QTextCursor.WordRight,
_Dollar: QTextCursor.EndOfBlock,
_End: QTextCursor.EndOfBlock,
_0: QTextCursor.StartOfBlock,
_Home: QTextCursor.StartOfBlock,
'gg': QTextCursor.Start,
_G: QTextCursor.End
}
if motion == _G:
if count == 0: # default - go to the end
cursor.movePosition(QTextCursor.End, moveMode)
else: # if count is set - move to line
block = self._qpart.document().findBlockByNumber(count - 1)
if not block.isValid():
return
cursor.setPosition(block.position(), moveMode)
self.moveToFirstNonSpace(cursor, moveMode)
elif motion in moveOperation:
for _ in range(effectiveCount):
cursor.movePosition(moveOperation[motion], moveMode)
elif motion in (_e, _E):
for _ in range(effectiveCount):
# skip spaces
text = cursor.block().text()
pos = cursor.positionInBlock()
for char in text[pos:]:
if char.isspace():
cursor.movePosition(QTextCursor.NextCharacter, moveMode)
else:
break
if cursor.positionInBlock() == len(text): # at the end of line
cursor.movePosition(QTextCursor.NextCharacter, moveMode) # move to the next line
# now move to the end of word
if motion == _e:
cursor.movePosition(QTextCursor.EndOfWord, moveMode)
else:
text = cursor.block().text()
pos = cursor.positionInBlock()
for char in text[pos:]:
if not char.isspace():
cursor.movePosition(QTextCursor.NextCharacter, moveMode)
else:
break
elif motion == _B:
cursor.movePosition(QTextCursor.WordLeft, moveMode)
while cursor.positionInBlock() != 0 and \
(not cursor.block().text()[cursor.positionInBlock() - 1].isspace()):
cursor.movePosition(QTextCursor.WordLeft, moveMode)
elif motion == _W:
cursor.movePosition(QTextCursor.WordRight, moveMode)
while cursor.positionInBlock() != 0 and \
(not cursor.block().text()[cursor.positionInBlock() - 1].isspace()):
cursor.movePosition(QTextCursor.WordRight, moveMode)
elif motion == _Percent:
# Percent move is done only once
if self._qpart._bracketHighlighter.currentMatchedBrackets is not None:
((startBlock, startCol), (endBlock, endCol)) = self._qpart._bracketHighlighter.currentMatchedBrackets
startPos = startBlock.position() + startCol
endPos = endBlock.position() + endCol
if select and \
(endPos > startPos):
endPos += 1 # to select the bracket, not only chars before it
cursor.setPosition(endPos, moveMode)
elif motion == _Caret:
# Caret move is done only once
self.moveToFirstNonSpace(cursor, moveMode)
elif motion in (_f, _F, _t, _T):
if motion in (_f, _t):
iterator = self._iterateDocumentCharsForward(cursor.block(), cursor.columnNumber())
stepForward = QTextCursor.Right
stepBack = QTextCursor.Left
else:
iterator = self._iterateDocumentCharsBackward(cursor.block(), cursor.columnNumber())
stepForward = QTextCursor.Left
stepBack = QTextCursor.Right
for block, columnIndex, char in iterator:
if char == searchChar:
cursor.setPosition(block.position() + columnIndex, moveMode)
if motion in (_t, _T):
cursor.movePosition(stepBack, moveMode)
if select:
cursor.movePosition(stepForward, moveMode)
break
elif motion in (_PageDown, _PageUp):
cursorHeight = self._qpart.cursorRect().height()
qpartHeight = self._qpart.height()
visibleLineCount = qpartHeight / cursorHeight
direction = QTextCursor.Down if motion == _PageDown else QTextCursor.Up
for _ in range(int(visibleLineCount)):
cursor.movePosition(direction, moveMode)
elif motion in (_Enter, _Return):
if cursor.block().next().isValid(): # not the last line
for _ in range(effectiveCount):
cursor.movePosition(QTextCursor.NextBlock, moveMode)
self.moveToFirstNonSpace(cursor, moveMode)
else:
assert 0, 'Not expected motion ' + str(motion)
self._qpart.setTextCursor(cursor) | [
"def",
"_moveCursor",
"(",
"self",
",",
"motion",
",",
"count",
",",
"searchChar",
"=",
"None",
",",
"select",
"=",
"False",
")",
":",
"cursor",
"=",
"self",
".",
"_qpart",
".",
"textCursor",
"(",
")",
"effectiveCount",
"=",
"count",
"or",
"1",
"moveMode",
"=",
"QTextCursor",
".",
"KeepAnchor",
"if",
"select",
"else",
"QTextCursor",
".",
"MoveAnchor",
"moveOperation",
"=",
"{",
"_b",
":",
"QTextCursor",
".",
"WordLeft",
",",
"_j",
":",
"QTextCursor",
".",
"Down",
",",
"_Down",
":",
"QTextCursor",
".",
"Down",
",",
"_k",
":",
"QTextCursor",
".",
"Up",
",",
"_Up",
":",
"QTextCursor",
".",
"Up",
",",
"_h",
":",
"QTextCursor",
".",
"Left",
",",
"_Left",
":",
"QTextCursor",
".",
"Left",
",",
"_BackSpace",
":",
"QTextCursor",
".",
"Left",
",",
"_l",
":",
"QTextCursor",
".",
"Right",
",",
"_Right",
":",
"QTextCursor",
".",
"Right",
",",
"_Space",
":",
"QTextCursor",
".",
"Right",
",",
"_w",
":",
"QTextCursor",
".",
"WordRight",
",",
"_Dollar",
":",
"QTextCursor",
".",
"EndOfBlock",
",",
"_End",
":",
"QTextCursor",
".",
"EndOfBlock",
",",
"_0",
":",
"QTextCursor",
".",
"StartOfBlock",
",",
"_Home",
":",
"QTextCursor",
".",
"StartOfBlock",
",",
"'gg'",
":",
"QTextCursor",
".",
"Start",
",",
"_G",
":",
"QTextCursor",
".",
"End",
"}",
"if",
"motion",
"==",
"_G",
":",
"if",
"count",
"==",
"0",
":",
"# default - go to the end",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"End",
",",
"moveMode",
")",
"else",
":",
"# if count is set - move to line",
"block",
"=",
"self",
".",
"_qpart",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"count",
"-",
"1",
")",
"if",
"not",
"block",
".",
"isValid",
"(",
")",
":",
"return",
"cursor",
".",
"setPosition",
"(",
"block",
".",
"position",
"(",
")",
",",
"moveMode",
")",
"self",
".",
"moveToFirstNonSpace",
"(",
"cursor",
",",
"moveMode",
")",
"elif",
"motion",
"in",
"moveOperation",
":",
"for",
"_",
"in",
"range",
"(",
"effectiveCount",
")",
":",
"cursor",
".",
"movePosition",
"(",
"moveOperation",
"[",
"motion",
"]",
",",
"moveMode",
")",
"elif",
"motion",
"in",
"(",
"_e",
",",
"_E",
")",
":",
"for",
"_",
"in",
"range",
"(",
"effectiveCount",
")",
":",
"# skip spaces",
"text",
"=",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"pos",
"=",
"cursor",
".",
"positionInBlock",
"(",
")",
"for",
"char",
"in",
"text",
"[",
"pos",
":",
"]",
":",
"if",
"char",
".",
"isspace",
"(",
")",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"NextCharacter",
",",
"moveMode",
")",
"else",
":",
"break",
"if",
"cursor",
".",
"positionInBlock",
"(",
")",
"==",
"len",
"(",
"text",
")",
":",
"# at the end of line",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"NextCharacter",
",",
"moveMode",
")",
"# move to the next line",
"# now move to the end of word",
"if",
"motion",
"==",
"_e",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"EndOfWord",
",",
"moveMode",
")",
"else",
":",
"text",
"=",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"pos",
"=",
"cursor",
".",
"positionInBlock",
"(",
")",
"for",
"char",
"in",
"text",
"[",
"pos",
":",
"]",
":",
"if",
"not",
"char",
".",
"isspace",
"(",
")",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"NextCharacter",
",",
"moveMode",
")",
"else",
":",
"break",
"elif",
"motion",
"==",
"_B",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"WordLeft",
",",
"moveMode",
")",
"while",
"cursor",
".",
"positionInBlock",
"(",
")",
"!=",
"0",
"and",
"(",
"not",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"[",
"cursor",
".",
"positionInBlock",
"(",
")",
"-",
"1",
"]",
".",
"isspace",
"(",
")",
")",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"WordLeft",
",",
"moveMode",
")",
"elif",
"motion",
"==",
"_W",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"WordRight",
",",
"moveMode",
")",
"while",
"cursor",
".",
"positionInBlock",
"(",
")",
"!=",
"0",
"and",
"(",
"not",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"[",
"cursor",
".",
"positionInBlock",
"(",
")",
"-",
"1",
"]",
".",
"isspace",
"(",
")",
")",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"WordRight",
",",
"moveMode",
")",
"elif",
"motion",
"==",
"_Percent",
":",
"# Percent move is done only once",
"if",
"self",
".",
"_qpart",
".",
"_bracketHighlighter",
".",
"currentMatchedBrackets",
"is",
"not",
"None",
":",
"(",
"(",
"startBlock",
",",
"startCol",
")",
",",
"(",
"endBlock",
",",
"endCol",
")",
")",
"=",
"self",
".",
"_qpart",
".",
"_bracketHighlighter",
".",
"currentMatchedBrackets",
"startPos",
"=",
"startBlock",
".",
"position",
"(",
")",
"+",
"startCol",
"endPos",
"=",
"endBlock",
".",
"position",
"(",
")",
"+",
"endCol",
"if",
"select",
"and",
"(",
"endPos",
">",
"startPos",
")",
":",
"endPos",
"+=",
"1",
"# to select the bracket, not only chars before it",
"cursor",
".",
"setPosition",
"(",
"endPos",
",",
"moveMode",
")",
"elif",
"motion",
"==",
"_Caret",
":",
"# Caret move is done only once",
"self",
".",
"moveToFirstNonSpace",
"(",
"cursor",
",",
"moveMode",
")",
"elif",
"motion",
"in",
"(",
"_f",
",",
"_F",
",",
"_t",
",",
"_T",
")",
":",
"if",
"motion",
"in",
"(",
"_f",
",",
"_t",
")",
":",
"iterator",
"=",
"self",
".",
"_iterateDocumentCharsForward",
"(",
"cursor",
".",
"block",
"(",
")",
",",
"cursor",
".",
"columnNumber",
"(",
")",
")",
"stepForward",
"=",
"QTextCursor",
".",
"Right",
"stepBack",
"=",
"QTextCursor",
".",
"Left",
"else",
":",
"iterator",
"=",
"self",
".",
"_iterateDocumentCharsBackward",
"(",
"cursor",
".",
"block",
"(",
")",
",",
"cursor",
".",
"columnNumber",
"(",
")",
")",
"stepForward",
"=",
"QTextCursor",
".",
"Left",
"stepBack",
"=",
"QTextCursor",
".",
"Right",
"for",
"block",
",",
"columnIndex",
",",
"char",
"in",
"iterator",
":",
"if",
"char",
"==",
"searchChar",
":",
"cursor",
".",
"setPosition",
"(",
"block",
".",
"position",
"(",
")",
"+",
"columnIndex",
",",
"moveMode",
")",
"if",
"motion",
"in",
"(",
"_t",
",",
"_T",
")",
":",
"cursor",
".",
"movePosition",
"(",
"stepBack",
",",
"moveMode",
")",
"if",
"select",
":",
"cursor",
".",
"movePosition",
"(",
"stepForward",
",",
"moveMode",
")",
"break",
"elif",
"motion",
"in",
"(",
"_PageDown",
",",
"_PageUp",
")",
":",
"cursorHeight",
"=",
"self",
".",
"_qpart",
".",
"cursorRect",
"(",
")",
".",
"height",
"(",
")",
"qpartHeight",
"=",
"self",
".",
"_qpart",
".",
"height",
"(",
")",
"visibleLineCount",
"=",
"qpartHeight",
"/",
"cursorHeight",
"direction",
"=",
"QTextCursor",
".",
"Down",
"if",
"motion",
"==",
"_PageDown",
"else",
"QTextCursor",
".",
"Up",
"for",
"_",
"in",
"range",
"(",
"int",
"(",
"visibleLineCount",
")",
")",
":",
"cursor",
".",
"movePosition",
"(",
"direction",
",",
"moveMode",
")",
"elif",
"motion",
"in",
"(",
"_Enter",
",",
"_Return",
")",
":",
"if",
"cursor",
".",
"block",
"(",
")",
".",
"next",
"(",
")",
".",
"isValid",
"(",
")",
":",
"# not the last line",
"for",
"_",
"in",
"range",
"(",
"effectiveCount",
")",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"NextBlock",
",",
"moveMode",
")",
"self",
".",
"moveToFirstNonSpace",
"(",
"cursor",
",",
"moveMode",
")",
"else",
":",
"assert",
"0",
",",
"'Not expected motion '",
"+",
"str",
"(",
"motion",
")",
"self",
".",
"_qpart",
".",
"setTextCursor",
"(",
"cursor",
")"
] | Move cursor.
Used by Normal and Visual mode | [
"Move",
"cursor",
".",
"Used",
"by",
"Normal",
"and",
"Visual",
"mode"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L300-L424 |
andreikop/qutepart | qutepart/vim.py | BaseCommandMode._iterateDocumentCharsForward | def _iterateDocumentCharsForward(self, block, startColumnIndex):
"""Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
"""
# 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() | python | def _iterateDocumentCharsForward(self, block, startColumnIndex):
"""Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
"""
# 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",
")",
":",
"# 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",
"(",
")"
] | Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over | [
"Traverse",
"document",
"forward",
".",
"Yield",
"(",
"block",
"columnIndex",
"char",
")",
"Raise",
"_TimeoutException",
"if",
"time",
"is",
"over"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L426-L440 |
andreikop/qutepart | qutepart/vim.py | BaseCommandMode._iterateDocumentCharsBackward | def _iterateDocumentCharsBackward(self, block, startColumnIndex):
"""Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
"""
# 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() | python | def _iterateDocumentCharsBackward(self, block, startColumnIndex):
"""Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
"""
# 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",
")",
":",
"# 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",
"(",
")"
] | Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over | [
"Traverse",
"document",
"forward",
".",
"Yield",
"(",
"block",
"columnIndex",
"char",
")",
"Raise",
"_TimeoutException",
"if",
"time",
"is",
"over"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L442-L456 |
andreikop/qutepart | qutepart/vim.py | BaseCommandMode._resetSelection | def _resetSelection(self, moveToTop=False):
""" Reset selection.
If moveToTop is True - move cursor to the top position
"""
ancor, pos = self._qpart.selectedPosition
dst = min(ancor, pos) if moveToTop else pos
self._qpart.cursorPosition = dst | python | def _resetSelection(self, moveToTop=False):
""" Reset selection.
If moveToTop is True - move cursor to the top position
"""
ancor, pos = self._qpart.selectedPosition
dst = min(ancor, pos) if moveToTop else pos
self._qpart.cursorPosition = dst | [
"def",
"_resetSelection",
"(",
"self",
",",
"moveToTop",
"=",
"False",
")",
":",
"ancor",
",",
"pos",
"=",
"self",
".",
"_qpart",
".",
"selectedPosition",
"dst",
"=",
"min",
"(",
"ancor",
",",
"pos",
")",
"if",
"moveToTop",
"else",
"pos",
"self",
".",
"_qpart",
".",
"cursorPosition",
"=",
"dst"
] | Reset selection.
If moveToTop is True - move cursor to the top position | [
"Reset",
"selection",
".",
"If",
"moveToTop",
"is",
"True",
"-",
"move",
"cursor",
"to",
"the",
"top",
"position"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L458-L464 |
andreikop/qutepart | qutepart/vim.py | BaseVisual._selectedLinesRange | def _selectedLinesRange(self):
""" Selected lines range for line manipulation methods
"""
(startLine, startCol), (endLine, endCol) = self._qpart.selectedPosition
start = min(startLine, endLine)
end = max(startLine, endLine)
return start, end | python | def _selectedLinesRange(self):
""" Selected lines range for line manipulation methods
"""
(startLine, startCol), (endLine, endCol) = self._qpart.selectedPosition
start = min(startLine, endLine)
end = max(startLine, endLine)
return start, end | [
"def",
"_selectedLinesRange",
"(",
"self",
")",
":",
"(",
"startLine",
",",
"startCol",
")",
",",
"(",
"endLine",
",",
"endCol",
")",
"=",
"self",
".",
"_qpart",
".",
"selectedPosition",
"start",
"=",
"min",
"(",
"startLine",
",",
"endLine",
")",
"end",
"=",
"max",
"(",
"startLine",
",",
"endLine",
")",
"return",
"start",
",",
"end"
] | Selected lines range for line manipulation methods | [
"Selected",
"lines",
"range",
"for",
"line",
"manipulation",
"methods"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L583-L589 |
andreikop/qutepart | qutepart/vim.py | Normal._repeat | def _repeat(self, count, func):
""" Repeat action 1 or more times.
If more than one - do it as 1 undoble action
"""
if count != 1:
with self._qpart:
for _ in range(count):
func()
else:
func() | python | def _repeat(self, count, func):
""" Repeat action 1 or more times.
If more than one - do it as 1 undoble action
"""
if count != 1:
with self._qpart:
for _ in range(count):
func()
else:
func() | [
"def",
"_repeat",
"(",
"self",
",",
"count",
",",
"func",
")",
":",
"if",
"count",
"!=",
"1",
":",
"with",
"self",
".",
"_qpart",
":",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"func",
"(",
")",
"else",
":",
"func",
"(",
")"
] | Repeat action 1 or more times.
If more than one - do it as 1 undoble action | [
"Repeat",
"action",
"1",
"or",
"more",
"times",
".",
"If",
"more",
"than",
"one",
"-",
"do",
"it",
"as",
"1",
"undoble",
"action"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L912-L921 |
andreikop/qutepart | qutepart/vim.py | Normal.cmdSubstitute | def cmdSubstitute(self, cmd, count):
""" s
"""
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) | python | def cmdSubstitute(self, cmd, count):
""" s
"""
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",
")",
":",
"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",
")"
] | s | [
"s"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L1049-L1061 |
andreikop/qutepart | qutepart/vim.py | Normal.cmdSubstituteLines | def cmdSubstituteLines(self, cmd, count):
""" S
"""
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) | python | def cmdSubstituteLines(self, cmd, count):
""" S
"""
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",
")",
":",
"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",
")"
] | S | [
"S"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L1063-L1078 |
andreikop/qutepart | qutepart/vim.py | Normal.cmdDelete | def cmdDelete(self, cmd, count):
""" x
"""
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) | python | def cmdDelete(self, cmd, count):
""" x
"""
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",
")",
":",
"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",
")"
] | x | [
"x"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L1089-L1101 |
andreikop/qutepart | qutepart/vim.py | Normal.cmdDeleteUntilEndOfBlock | def cmdDeleteUntilEndOfBlock(self, cmd, count):
""" C and D
"""
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) | python | def cmdDeleteUntilEndOfBlock(self, cmd, count):
""" C and D
"""
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",
")",
":",
"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",
")"
] | C and D | [
"C",
"and",
"D"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/vim.py#L1103-L1115 |
andreikop/qutepart | qutepart/indenter/python.py | IndentAlgPython._computeSmartIndent | def _computeSmartIndent(self, block, column):
"""Compute smart indent for case when cursor is on (block, column)
"""
lineStripped = block.text()[:column].strip() # empty text from invalid block is ok
spaceLen = len(block.text()) - len(block.text().lstrip())
"""Move initial search position to bracket start, if bracket was closed
l = [1,
2]|
"""
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)
"""Unindent if hanging indentation finished
func(a,
another_func(a,
b),|
"""
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)
"""Check hanging indentation
call_func(x,
y,
z
But
call_func(x,
y,
z
"""
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))
"""
for:
func(a,
b):
"""
if lineStripped.endswith(':'):
newColumn = spaceLen + len(lineStripped) - 1
prevIndent = self._computeSmartIndent(block, newColumn)
return self._increaseIndent(prevIndent)
""" Generally, when a brace is on its own at the end of a regular line
(i.e a data structure is being started), indent is wanted.
For example:
dictionary = {
'foo': 'bar',
}
"""
if lineStripped.endswith('{['):
return self._increaseIndent(self._blockIndent(block))
return self._blockIndent(block) | python | def _computeSmartIndent(self, block, column):
"""Compute smart indent for case when cursor is on (block, column)
"""
lineStripped = block.text()[:column].strip() # empty text from invalid block is ok
spaceLen = len(block.text()) - len(block.text().lstrip())
"""Move initial search position to bracket start, if bracket was closed
l = [1,
2]|
"""
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)
"""Unindent if hanging indentation finished
func(a,
another_func(a,
b),|
"""
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)
"""Check hanging indentation
call_func(x,
y,
z
But
call_func(x,
y,
z
"""
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))
"""
for:
func(a,
b):
"""
if lineStripped.endswith(':'):
newColumn = spaceLen + len(lineStripped) - 1
prevIndent = self._computeSmartIndent(block, newColumn)
return self._increaseIndent(prevIndent)
""" Generally, when a brace is on its own at the end of a regular line
(i.e a data structure is being started), indent is wanted.
For example:
dictionary = {
'foo': 'bar',
}
"""
if lineStripped.endswith('{['):
return self._increaseIndent(self._blockIndent(block))
return self._blockIndent(block) | [
"def",
"_computeSmartIndent",
"(",
"self",
",",
"block",
",",
"column",
")",
":",
"lineStripped",
"=",
"block",
".",
"text",
"(",
")",
"[",
":",
"column",
"]",
".",
"strip",
"(",
")",
"# empty text from invalid block is ok",
"spaceLen",
"=",
"len",
"(",
"block",
".",
"text",
"(",
")",
")",
"-",
"len",
"(",
"block",
".",
"text",
"(",
")",
".",
"lstrip",
"(",
")",
")",
"\"\"\"Move initial search position to bracket start, if bracket was closed\n l = [1,\n 2]|\n \"\"\"",
"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",
")",
"\"\"\"Unindent if hanging indentation finished\n func(a,\n another_func(a,\n b),|\n \"\"\"",
"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",
")",
"\"\"\"Check hanging indentation\n call_func(x,\n y,\n z\n But\n call_func(x,\n y,\n z\n \"\"\"",
"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",
")",
")",
"\"\"\"\n for:\n\n func(a,\n b):\n \"\"\"",
"if",
"lineStripped",
".",
"endswith",
"(",
"':'",
")",
":",
"newColumn",
"=",
"spaceLen",
"+",
"len",
"(",
"lineStripped",
")",
"-",
"1",
"prevIndent",
"=",
"self",
".",
"_computeSmartIndent",
"(",
"block",
",",
"newColumn",
")",
"return",
"self",
".",
"_increaseIndent",
"(",
"prevIndent",
")",
"\"\"\" Generally, when a brace is on its own at the end of a regular line\n (i.e a data structure is being started), indent is wanted.\n For example:\n dictionary = {\n 'foo': 'bar',\n }\n \"\"\"",
"if",
"lineStripped",
".",
"endswith",
"(",
"'{['",
")",
":",
"return",
"self",
".",
"_increaseIndent",
"(",
"self",
".",
"_blockIndent",
"(",
"block",
")",
")",
"return",
"self",
".",
"_blockIndent",
"(",
"block",
")"
] | Compute smart indent for case when cursor is on (block, column) | [
"Compute",
"smart",
"indent",
"for",
"case",
"when",
"cursor",
"is",
"on",
"(",
"block",
"column",
")"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/python.py#L7-L93 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.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
"""
self.text = ''
self._completer.terminate()
if self._highlighter is not None:
self._highlighter.terminate()
if self._vim is not None:
self._vim.terminate() | python | 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
"""
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",
")",
":",
"self",
".",
"text",
"=",
"''",
"self",
".",
"_completer",
".",
"terminate",
"(",
")",
"if",
"self",
".",
"_highlighter",
"is",
"not",
"None",
":",
"self",
".",
"_highlighter",
".",
"terminate",
"(",
")",
"if",
"self",
".",
"_vim",
"is",
"not",
"None",
":",
"self",
".",
"_vim",
".",
"terminate",
"(",
")"
] | 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 | [
"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"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L335-L348 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._initActions | def _initActions(self):
"""Init shortcuts for text editing
"""
def createAction(text, shortcut, slot, iconFileName=None):
"""Create QAction with given parameters and add to the widget
"""
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') | python | def _initActions(self):
"""Init shortcuts for text editing
"""
def createAction(text, shortcut, slot, iconFileName=None):
"""Create QAction with given parameters and add to the widget
"""
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",
")",
":",
"def",
"createAction",
"(",
"text",
",",
"shortcut",
",",
"slot",
",",
"iconFileName",
"=",
"None",
")",
":",
"\"\"\"Create QAction with given parameters and add to the widget\n \"\"\"",
"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'",
")"
] | Init shortcuts for text editing | [
"Init",
"shortcuts",
"for",
"text",
"editing"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L350-L416 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._updateTabStopWidth | def _updateTabStopWidth(self):
"""Update tabstop width after font or indentation changed
"""
self.setTabStopWidth(self.fontMetrics().width(' ' * self._indenter.width)) | python | def _updateTabStopWidth(self):
"""Update tabstop width after font or indentation changed
"""
self.setTabStopWidth(self.fontMetrics().width(' ' * self._indenter.width)) | [
"def",
"_updateTabStopWidth",
"(",
"self",
")",
":",
"self",
".",
"setTabStopWidth",
"(",
"self",
".",
"fontMetrics",
"(",
")",
".",
"width",
"(",
"' '",
"*",
"self",
".",
"_indenter",
".",
"width",
")",
")"
] | Update tabstop width after font or indentation changed | [
"Update",
"tabstop",
"width",
"after",
"font",
"or",
"indentation",
"changed"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L460-L463 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.textForSaving | def textForSaving(self):
"""Get text with correct EOL symbols. Use this method for saving a file to storage
"""
lines = self.text.splitlines()
if self.text.endswith('\n'): # splitlines ignores last \n
lines.append('')
return self.eol.join(lines) + self.eol | python | def textForSaving(self):
"""Get text with correct EOL symbols. Use this method for saving a file to storage
"""
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",
")",
":",
"lines",
"=",
"self",
".",
"text",
".",
"splitlines",
"(",
")",
"if",
"self",
".",
"text",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"# splitlines ignores last \\n",
"lines",
".",
"append",
"(",
"''",
")",
"return",
"self",
".",
"eol",
".",
"join",
"(",
"lines",
")",
"+",
"self",
".",
"eol"
] | Get text with correct EOL symbols. Use this method for saving a file to storage | [
"Get",
"text",
"with",
"correct",
"EOL",
"symbols",
".",
"Use",
"this",
"method",
"for",
"saving",
"a",
"file",
"to",
"storage"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L492-L498 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.resetSelection | def resetSelection(self):
"""Reset selection. Nothing will be selected.
"""
cursor = self.textCursor()
cursor.setPosition(cursor.position())
self.setTextCursor(cursor) | python | def resetSelection(self):
"""Reset selection. Nothing will be selected.
"""
cursor = self.textCursor()
cursor.setPosition(cursor.position())
self.setTextCursor(cursor) | [
"def",
"resetSelection",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"cursor",
".",
"position",
"(",
")",
")",
"self",
".",
"setTextCursor",
"(",
"cursor",
")"
] | Reset selection. Nothing will be selected. | [
"Reset",
"selection",
".",
"Nothing",
"will",
"be",
"selected",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L583-L588 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.replaceText | 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)``
"""
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) | python | 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)``
"""
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",
")",
":",
"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",
")"
] | 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)`` | [
"Replace",
"length",
"symbols",
"from",
"pos",
"with",
"new",
"text",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L715-L735 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.detectSyntax | def detectSyntax(self,
xmlFileName=None,
mimeType=None,
language=None,
sourceFilePath=None,
firstLine=None):
"""Get syntax by next parameters (fill as many, as known):
* name of XML file with syntax definition
* MIME type of source file
* Programming language name
* Source file path
* First line of source file
First parameter in the list has the hightest priority.
Old syntax is always cleared, even if failed to detect new.
Method returns ``True``, if syntax is detected, and ``False`` otherwise
"""
oldLanguage = self.language()
self.clearSyntax()
syntax = self._globalSyntaxManager.getSyntax(xmlFileName=xmlFileName,
mimeType=mimeType,
languageName=language,
sourceFilePath=sourceFilePath,
firstLine=firstLine)
if syntax is not None:
self._highlighter = SyntaxHighlighter(syntax, self)
self._indenter.setSyntax(syntax)
keywords = {kw for kwList in syntax.parser.lists.values() for kw in kwList}
self._completer.setKeywords(keywords)
newLanguage = self.language()
if oldLanguage != newLanguage:
self.languageChanged.emit(newLanguage)
return syntax is not None | python | def detectSyntax(self,
xmlFileName=None,
mimeType=None,
language=None,
sourceFilePath=None,
firstLine=None):
"""Get syntax by next parameters (fill as many, as known):
* name of XML file with syntax definition
* MIME type of source file
* Programming language name
* Source file path
* First line of source file
First parameter in the list has the hightest priority.
Old syntax is always cleared, even if failed to detect new.
Method returns ``True``, if syntax is detected, and ``False`` otherwise
"""
oldLanguage = self.language()
self.clearSyntax()
syntax = self._globalSyntaxManager.getSyntax(xmlFileName=xmlFileName,
mimeType=mimeType,
languageName=language,
sourceFilePath=sourceFilePath,
firstLine=firstLine)
if syntax is not None:
self._highlighter = SyntaxHighlighter(syntax, self)
self._indenter.setSyntax(syntax)
keywords = {kw for kwList in syntax.parser.lists.values() for kw in kwList}
self._completer.setKeywords(keywords)
newLanguage = self.language()
if oldLanguage != newLanguage:
self.languageChanged.emit(newLanguage)
return syntax is not None | [
"def",
"detectSyntax",
"(",
"self",
",",
"xmlFileName",
"=",
"None",
",",
"mimeType",
"=",
"None",
",",
"language",
"=",
"None",
",",
"sourceFilePath",
"=",
"None",
",",
"firstLine",
"=",
"None",
")",
":",
"oldLanguage",
"=",
"self",
".",
"language",
"(",
")",
"self",
".",
"clearSyntax",
"(",
")",
"syntax",
"=",
"self",
".",
"_globalSyntaxManager",
".",
"getSyntax",
"(",
"xmlFileName",
"=",
"xmlFileName",
",",
"mimeType",
"=",
"mimeType",
",",
"languageName",
"=",
"language",
",",
"sourceFilePath",
"=",
"sourceFilePath",
",",
"firstLine",
"=",
"firstLine",
")",
"if",
"syntax",
"is",
"not",
"None",
":",
"self",
".",
"_highlighter",
"=",
"SyntaxHighlighter",
"(",
"syntax",
",",
"self",
")",
"self",
".",
"_indenter",
".",
"setSyntax",
"(",
"syntax",
")",
"keywords",
"=",
"{",
"kw",
"for",
"kwList",
"in",
"syntax",
".",
"parser",
".",
"lists",
".",
"values",
"(",
")",
"for",
"kw",
"in",
"kwList",
"}",
"self",
".",
"_completer",
".",
"setKeywords",
"(",
"keywords",
")",
"newLanguage",
"=",
"self",
".",
"language",
"(",
")",
"if",
"oldLanguage",
"!=",
"newLanguage",
":",
"self",
".",
"languageChanged",
".",
"emit",
"(",
"newLanguage",
")",
"return",
"syntax",
"is",
"not",
"None"
] | Get syntax by next parameters (fill as many, as known):
* name of XML file with syntax definition
* MIME type of source file
* Programming language name
* Source file path
* First line of source file
First parameter in the list has the hightest priority.
Old syntax is always cleared, even if failed to detect new.
Method returns ``True``, if syntax is detected, and ``False`` otherwise | [
"Get",
"syntax",
"by",
"next",
"parameters",
"(",
"fill",
"as",
"many",
"as",
"known",
")",
":"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L744-L783 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.clearSyntax | def clearSyntax(self):
"""Clear syntax. Disables syntax highlighting
This method might take long time, if document is big. Don't call it if you don't have to (i.e. in destructor)
"""
if self._highlighter is not None:
self._highlighter.terminate()
self._highlighter = None
self.languageChanged.emit(None) | python | def clearSyntax(self):
"""Clear syntax. Disables syntax highlighting
This method might take long time, if document is big. Don't call it if you don't have to (i.e. in destructor)
"""
if self._highlighter is not None:
self._highlighter.terminate()
self._highlighter = None
self.languageChanged.emit(None) | [
"def",
"clearSyntax",
"(",
"self",
")",
":",
"if",
"self",
".",
"_highlighter",
"is",
"not",
"None",
":",
"self",
".",
"_highlighter",
".",
"terminate",
"(",
")",
"self",
".",
"_highlighter",
"=",
"None",
"self",
".",
"languageChanged",
".",
"emit",
"(",
"None",
")"
] | Clear syntax. Disables syntax highlighting
This method might take long time, if document is big. Don't call it if you don't have to (i.e. in destructor) | [
"Clear",
"syntax",
".",
"Disables",
"syntax",
"highlighting"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L785-L793 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.setCustomCompletions | def setCustomCompletions(self, wordSet):
"""Add a set of custom completions to the editors completions.
This set is managed independently of the set of keywords and words from
the current document, and can thus be changed at any time.
"""
if not isinstance(wordSet, set):
raise TypeError('"wordSet" is not a set: %s' % type(wordSet))
self._completer.setCustomCompletions(wordSet) | python | def setCustomCompletions(self, wordSet):
"""Add a set of custom completions to the editors completions.
This set is managed independently of the set of keywords and words from
the current document, and can thus be changed at any time.
"""
if not isinstance(wordSet, set):
raise TypeError('"wordSet" is not a set: %s' % type(wordSet))
self._completer.setCustomCompletions(wordSet) | [
"def",
"setCustomCompletions",
"(",
"self",
",",
"wordSet",
")",
":",
"if",
"not",
"isinstance",
"(",
"wordSet",
",",
"set",
")",
":",
"raise",
"TypeError",
"(",
"'\"wordSet\" is not a set: %s'",
"%",
"type",
"(",
"wordSet",
")",
")",
"self",
".",
"_completer",
".",
"setCustomCompletions",
"(",
"wordSet",
")"
] | Add a set of custom completions to the editors completions.
This set is managed independently of the set of keywords and words from
the current document, and can thus be changed at any time. | [
"Add",
"a",
"set",
"of",
"custom",
"completions",
"to",
"the",
"editors",
"completions",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L804-L813 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.isCode | def isCode(self, blockOrBlockNumber, column):
"""Check if text at given position is a code.
If language is not known, or text is not parsed yet, ``True`` is returned
"""
if isinstance(blockOrBlockNumber, QTextBlock):
block = blockOrBlockNumber
else:
block = self.document().findBlockByNumber(blockOrBlockNumber)
return self._highlighter is None or \
self._highlighter.isCode(block, column) | python | def isCode(self, blockOrBlockNumber, column):
"""Check if text at given position is a code.
If language is not known, or text is not parsed yet, ``True`` is returned
"""
if isinstance(blockOrBlockNumber, QTextBlock):
block = blockOrBlockNumber
else:
block = self.document().findBlockByNumber(blockOrBlockNumber)
return self._highlighter is None or \
self._highlighter.isCode(block, column) | [
"def",
"isCode",
"(",
"self",
",",
"blockOrBlockNumber",
",",
"column",
")",
":",
"if",
"isinstance",
"(",
"blockOrBlockNumber",
",",
"QTextBlock",
")",
":",
"block",
"=",
"blockOrBlockNumber",
"else",
":",
"block",
"=",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"blockOrBlockNumber",
")",
"return",
"self",
".",
"_highlighter",
"is",
"None",
"or",
"self",
".",
"_highlighter",
".",
"isCode",
"(",
"block",
",",
"column",
")"
] | Check if text at given position is a code.
If language is not known, or text is not parsed yet, ``True`` is returned | [
"Check",
"if",
"text",
"at",
"given",
"position",
"is",
"a",
"code",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L821-L832 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.isComment | def isComment(self, line, column):
"""Check if text at given position is a comment. Including block comments and here documents.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isComment(self.document().findBlockByNumber(line), column) | python | def isComment(self, line, column):
"""Check if text at given position is a comment. Including block comments and here documents.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isComment(self.document().findBlockByNumber(line), column) | [
"def",
"isComment",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"return",
"self",
".",
"_highlighter",
"is",
"not",
"None",
"and",
"self",
".",
"_highlighter",
".",
"isComment",
"(",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"line",
")",
",",
"column",
")"
] | Check if text at given position is a comment. Including block comments and here documents.
If language is not known, or text is not parsed yet, ``False`` is returned | [
"Check",
"if",
"text",
"at",
"given",
"position",
"is",
"a",
"comment",
".",
"Including",
"block",
"comments",
"and",
"here",
"documents",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L834-L840 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.isBlockComment | def isBlockComment(self, line, column):
"""Check if text at given position is a block comment.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isBlockComment(self.document().findBlockByNumber(line), column) | python | def isBlockComment(self, line, column):
"""Check if text at given position is a block comment.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isBlockComment(self.document().findBlockByNumber(line), column) | [
"def",
"isBlockComment",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"return",
"self",
".",
"_highlighter",
"is",
"not",
"None",
"and",
"self",
".",
"_highlighter",
".",
"isBlockComment",
"(",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"line",
")",
",",
"column",
")"
] | Check if text at given position is a block comment.
If language is not known, or text is not parsed yet, ``False`` is returned | [
"Check",
"if",
"text",
"at",
"given",
"position",
"is",
"a",
"block",
"comment",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L842-L848 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.isHereDoc | def isHereDoc(self, line, column):
"""Check if text at given position is a here document.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isHereDoc(self.document().findBlockByNumber(line), column) | python | def isHereDoc(self, line, column):
"""Check if text at given position is a here document.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isHereDoc(self.document().findBlockByNumber(line), column) | [
"def",
"isHereDoc",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"return",
"self",
".",
"_highlighter",
"is",
"not",
"None",
"and",
"self",
".",
"_highlighter",
".",
"isHereDoc",
"(",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"line",
")",
",",
"column",
")"
] | Check if text at given position is a here document.
If language is not known, or text is not parsed yet, ``False`` is returned | [
"Check",
"if",
"text",
"at",
"given",
"position",
"is",
"a",
"here",
"document",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L850-L856 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.setExtraSelections | def setExtraSelections(self, selections):
"""Set list of extra selections.
Selections are list of tuples ``(startAbsolutePosition, length)``.
Extra selections are reset on any text modification.
This is reimplemented method of QPlainTextEdit, it has different signature. Do not use QPlainTextEdit method
"""
def _makeQtExtraSelection(startAbsolutePosition, length):
selection = QTextEdit.ExtraSelection()
cursor = QTextCursor(self.document())
cursor.setPosition(startAbsolutePosition)
cursor.setPosition(startAbsolutePosition + length, QTextCursor.KeepAnchor)
selection.cursor = cursor
selection.format = self._userExtraSelectionFormat
return selection
self._userExtraSelections = [_makeQtExtraSelection(*item) for item in selections]
self._updateExtraSelections() | python | def setExtraSelections(self, selections):
"""Set list of extra selections.
Selections are list of tuples ``(startAbsolutePosition, length)``.
Extra selections are reset on any text modification.
This is reimplemented method of QPlainTextEdit, it has different signature. Do not use QPlainTextEdit method
"""
def _makeQtExtraSelection(startAbsolutePosition, length):
selection = QTextEdit.ExtraSelection()
cursor = QTextCursor(self.document())
cursor.setPosition(startAbsolutePosition)
cursor.setPosition(startAbsolutePosition + length, QTextCursor.KeepAnchor)
selection.cursor = cursor
selection.format = self._userExtraSelectionFormat
return selection
self._userExtraSelections = [_makeQtExtraSelection(*item) for item in selections]
self._updateExtraSelections() | [
"def",
"setExtraSelections",
"(",
"self",
",",
"selections",
")",
":",
"def",
"_makeQtExtraSelection",
"(",
"startAbsolutePosition",
",",
"length",
")",
":",
"selection",
"=",
"QTextEdit",
".",
"ExtraSelection",
"(",
")",
"cursor",
"=",
"QTextCursor",
"(",
"self",
".",
"document",
"(",
")",
")",
"cursor",
".",
"setPosition",
"(",
"startAbsolutePosition",
")",
"cursor",
".",
"setPosition",
"(",
"startAbsolutePosition",
"+",
"length",
",",
"QTextCursor",
".",
"KeepAnchor",
")",
"selection",
".",
"cursor",
"=",
"cursor",
"selection",
".",
"format",
"=",
"self",
".",
"_userExtraSelectionFormat",
"return",
"selection",
"self",
".",
"_userExtraSelections",
"=",
"[",
"_makeQtExtraSelection",
"(",
"*",
"item",
")",
"for",
"item",
"in",
"selections",
"]",
"self",
".",
"_updateExtraSelections",
"(",
")"
] | Set list of extra selections.
Selections are list of tuples ``(startAbsolutePosition, length)``.
Extra selections are reset on any text modification.
This is reimplemented method of QPlainTextEdit, it has different signature. Do not use QPlainTextEdit method | [
"Set",
"list",
"of",
"extra",
"selections",
".",
"Selections",
"are",
"list",
"of",
"tuples",
"(",
"startAbsolutePosition",
"length",
")",
".",
"Extra",
"selections",
"are",
"reset",
"on",
"any",
"text",
"modification",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L862-L879 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.mapToAbsPosition | def mapToAbsPosition(self, line, column):
"""Convert line and column number to absolute position
"""
block = self.document().findBlockByNumber(line)
if not block.isValid():
raise IndexError("Invalid line index %d" % line)
if column >= block.length():
raise IndexError("Invalid column index %d" % column)
return block.position() + column | python | def mapToAbsPosition(self, line, column):
"""Convert line and column number to absolute position
"""
block = self.document().findBlockByNumber(line)
if not block.isValid():
raise IndexError("Invalid line index %d" % line)
if column >= block.length():
raise IndexError("Invalid column index %d" % column)
return block.position() + column | [
"def",
"mapToAbsPosition",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"block",
"=",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"line",
")",
"if",
"not",
"block",
".",
"isValid",
"(",
")",
":",
"raise",
"IndexError",
"(",
"\"Invalid line index %d\"",
"%",
"line",
")",
"if",
"column",
">=",
"block",
".",
"length",
"(",
")",
":",
"raise",
"IndexError",
"(",
"\"Invalid column index %d\"",
"%",
"column",
")",
"return",
"block",
".",
"position",
"(",
")",
"+",
"column"
] | Convert line and column number to absolute position | [
"Convert",
"line",
"and",
"column",
"number",
"to",
"absolute",
"position"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L881-L889 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.mapToLineCol | def mapToLineCol(self, absPosition):
"""Convert absolute position to ``(line, column)``
"""
block = self.document().findBlock(absPosition)
if not block.isValid():
raise IndexError("Invalid absolute position %d" % absPosition)
return (block.blockNumber(),
absPosition - block.position()) | python | def mapToLineCol(self, absPosition):
"""Convert absolute position to ``(line, column)``
"""
block = self.document().findBlock(absPosition)
if not block.isValid():
raise IndexError("Invalid absolute position %d" % absPosition)
return (block.blockNumber(),
absPosition - block.position()) | [
"def",
"mapToLineCol",
"(",
"self",
",",
"absPosition",
")",
":",
"block",
"=",
"self",
".",
"document",
"(",
")",
".",
"findBlock",
"(",
"absPosition",
")",
"if",
"not",
"block",
".",
"isValid",
"(",
")",
":",
"raise",
"IndexError",
"(",
"\"Invalid absolute position %d\"",
"%",
"absPosition",
")",
"return",
"(",
"block",
".",
"blockNumber",
"(",
")",
",",
"absPosition",
"-",
"block",
".",
"position",
"(",
")",
")"
] | Convert absolute position to ``(line, column)`` | [
"Convert",
"absolute",
"position",
"to",
"(",
"line",
"column",
")"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L891-L899 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._setSolidEdgeGeometry | def _setSolidEdgeGeometry(self):
"""Sets the solid edge line geometry if needed"""
if self._lineLengthEdge is not None:
cr = self.contentsRect()
# contents margin usually gives 1
# cursor rectangle left edge for the very first character usually
# gives 4
x = self.fontMetrics().width('9' * self._lineLengthEdge) + \
self._totalMarginWidth + \
self.contentsMargins().left() + \
self.__cursorRect(self.firstVisibleBlock(), 0, offset=0).left()
self._solidEdgeLine.setGeometry(QRect(x, cr.top(), 1, cr.bottom())) | python | def _setSolidEdgeGeometry(self):
"""Sets the solid edge line geometry if needed"""
if self._lineLengthEdge is not None:
cr = self.contentsRect()
# contents margin usually gives 1
# cursor rectangle left edge for the very first character usually
# gives 4
x = self.fontMetrics().width('9' * self._lineLengthEdge) + \
self._totalMarginWidth + \
self.contentsMargins().left() + \
self.__cursorRect(self.firstVisibleBlock(), 0, offset=0).left()
self._solidEdgeLine.setGeometry(QRect(x, cr.top(), 1, cr.bottom())) | [
"def",
"_setSolidEdgeGeometry",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lineLengthEdge",
"is",
"not",
"None",
":",
"cr",
"=",
"self",
".",
"contentsRect",
"(",
")",
"# contents margin usually gives 1",
"# cursor rectangle left edge for the very first character usually",
"# gives 4",
"x",
"=",
"self",
".",
"fontMetrics",
"(",
")",
".",
"width",
"(",
"'9'",
"*",
"self",
".",
"_lineLengthEdge",
")",
"+",
"self",
".",
"_totalMarginWidth",
"+",
"self",
".",
"contentsMargins",
"(",
")",
".",
"left",
"(",
")",
"+",
"self",
".",
"__cursorRect",
"(",
"self",
".",
"firstVisibleBlock",
"(",
")",
",",
"0",
",",
"offset",
"=",
"0",
")",
".",
"left",
"(",
")",
"self",
".",
"_solidEdgeLine",
".",
"setGeometry",
"(",
"QRect",
"(",
"x",
",",
"cr",
".",
"top",
"(",
")",
",",
"1",
",",
"cr",
".",
"bottom",
"(",
")",
")",
")"
] | Sets the solid edge line geometry if needed | [
"Sets",
"the",
"solid",
"edge",
"line",
"geometry",
"if",
"needed"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L940-L952 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._insertNewBlock | def _insertNewBlock(self):
"""Enter pressed.
Insert properly indented block
"""
cursor = self.textCursor()
atStartOfLine = cursor.positionInBlock() == 0
with self:
cursor.insertBlock()
if not atStartOfLine: # if whole line is moved down - just leave it as is
self._indenter.autoIndentBlock(cursor.block())
self.ensureCursorVisible() | python | def _insertNewBlock(self):
"""Enter pressed.
Insert properly indented block
"""
cursor = self.textCursor()
atStartOfLine = cursor.positionInBlock() == 0
with self:
cursor.insertBlock()
if not atStartOfLine: # if whole line is moved down - just leave it as is
self._indenter.autoIndentBlock(cursor.block())
self.ensureCursorVisible() | [
"def",
"_insertNewBlock",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"atStartOfLine",
"=",
"cursor",
".",
"positionInBlock",
"(",
")",
"==",
"0",
"with",
"self",
":",
"cursor",
".",
"insertBlock",
"(",
")",
"if",
"not",
"atStartOfLine",
":",
"# if whole line is moved down - just leave it as is",
"self",
".",
"_indenter",
".",
"autoIndentBlock",
"(",
"cursor",
".",
"block",
"(",
")",
")",
"self",
".",
"ensureCursorVisible",
"(",
")"
] | Enter pressed.
Insert properly indented block | [
"Enter",
"pressed",
".",
"Insert",
"properly",
"indented",
"block"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L954-L964 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._drawIndentMarkersAndEdge | def _drawIndentMarkersAndEdge(self, paintEventRect):
"""Draw indentation markers
"""
painter = QPainter(self.viewport())
def drawWhiteSpace(block, column, char):
leftCursorRect = self.__cursorRect(block, column, 0)
rightCursorRect = self.__cursorRect(block, column + 1, 0)
if leftCursorRect.top() == rightCursorRect.top(): # if on the same visual line
middleHeight = (leftCursorRect.top() + leftCursorRect.bottom()) / 2
if char == ' ':
painter.setPen(Qt.transparent)
painter.setBrush(QBrush(Qt.gray))
xPos = (leftCursorRect.x() + rightCursorRect.x()) / 2
painter.drawRect(QRect(xPos, middleHeight, 2, 2))
else:
painter.setPen(QColor(Qt.gray).lighter(factor=120))
painter.drawLine(leftCursorRect.x() + 3, middleHeight,
rightCursorRect.x() - 3, middleHeight)
def effectiveEdgePos(text):
"""Position of edge in a block.
Defined by self._lineLengthEdge, but visible width of \t is more than 1,
therefore effective position depends on count and position of \t symbols
Return -1 if line is too short to have edge
"""
if self._lineLengthEdge is None:
return -1
tabExtraWidth = self.indentWidth - 1
fullWidth = len(text) + (text.count('\t') * tabExtraWidth)
if fullWidth <= self._lineLengthEdge:
return -1
currentWidth = 0
for pos, char in enumerate(text):
if char == '\t':
# Qt indents up to indentation level, so visible \t width depends on position
currentWidth += (self.indentWidth - (currentWidth % self.indentWidth))
else:
currentWidth += 1
if currentWidth > self._lineLengthEdge:
return pos
else: # line too narrow, probably visible \t width is small
return -1
def drawEdgeLine(block, edgePos):
painter.setPen(QPen(QBrush(self._lineLengthEdgeColor), 0))
rect = self.__cursorRect(block, edgePos, 0)
painter.drawLine(rect.topLeft(), rect.bottomLeft())
def drawIndentMarker(block, column):
painter.setPen(QColor(Qt.blue).lighter())
rect = self.__cursorRect(block, column, offset=0)
painter.drawLine(rect.topLeft(), rect.bottomLeft())
indentWidthChars = len(self._indenter.text())
cursorPos = self.cursorPosition
for block in iterateBlocksFrom(self.firstVisibleBlock()):
blockGeometry = self.blockBoundingGeometry(block).translated(self.contentOffset())
if blockGeometry.top() > paintEventRect.bottom():
break
if block.isVisible() and blockGeometry.toRect().intersects(paintEventRect):
# Draw indent markers, if good indentation is not drawn
if self._drawIndentations:
text = block.text()
if not self.drawAnyWhitespace:
column = indentWidthChars
while text.startswith(self._indenter.text()) and \
len(text) > indentWidthChars and \
text[indentWidthChars].isspace():
if column != self._lineLengthEdge and \
(block.blockNumber(), column) != cursorPos: # looks ugly, if both drawn
"""on some fonts line is drawn below the cursor, if offset is 1
Looks like Qt bug"""
drawIndentMarker(block, column)
text = text[indentWidthChars:]
column += indentWidthChars
# Draw edge, but not over a cursor
if not self._drawSolidEdge:
edgePos = effectiveEdgePos(block.text())
if edgePos != -1 and edgePos != cursorPos[1]:
drawEdgeLine(block, edgePos)
if self.drawAnyWhitespace or \
self.drawIncorrectIndentation:
text = block.text()
for column, draw in enumerate(self._chooseVisibleWhitespace(text)):
if draw:
drawWhiteSpace(block, column, text[column]) | python | def _drawIndentMarkersAndEdge(self, paintEventRect):
"""Draw indentation markers
"""
painter = QPainter(self.viewport())
def drawWhiteSpace(block, column, char):
leftCursorRect = self.__cursorRect(block, column, 0)
rightCursorRect = self.__cursorRect(block, column + 1, 0)
if leftCursorRect.top() == rightCursorRect.top(): # if on the same visual line
middleHeight = (leftCursorRect.top() + leftCursorRect.bottom()) / 2
if char == ' ':
painter.setPen(Qt.transparent)
painter.setBrush(QBrush(Qt.gray))
xPos = (leftCursorRect.x() + rightCursorRect.x()) / 2
painter.drawRect(QRect(xPos, middleHeight, 2, 2))
else:
painter.setPen(QColor(Qt.gray).lighter(factor=120))
painter.drawLine(leftCursorRect.x() + 3, middleHeight,
rightCursorRect.x() - 3, middleHeight)
def effectiveEdgePos(text):
"""Position of edge in a block.
Defined by self._lineLengthEdge, but visible width of \t is more than 1,
therefore effective position depends on count and position of \t symbols
Return -1 if line is too short to have edge
"""
if self._lineLengthEdge is None:
return -1
tabExtraWidth = self.indentWidth - 1
fullWidth = len(text) + (text.count('\t') * tabExtraWidth)
if fullWidth <= self._lineLengthEdge:
return -1
currentWidth = 0
for pos, char in enumerate(text):
if char == '\t':
# Qt indents up to indentation level, so visible \t width depends on position
currentWidth += (self.indentWidth - (currentWidth % self.indentWidth))
else:
currentWidth += 1
if currentWidth > self._lineLengthEdge:
return pos
else: # line too narrow, probably visible \t width is small
return -1
def drawEdgeLine(block, edgePos):
painter.setPen(QPen(QBrush(self._lineLengthEdgeColor), 0))
rect = self.__cursorRect(block, edgePos, 0)
painter.drawLine(rect.topLeft(), rect.bottomLeft())
def drawIndentMarker(block, column):
painter.setPen(QColor(Qt.blue).lighter())
rect = self.__cursorRect(block, column, offset=0)
painter.drawLine(rect.topLeft(), rect.bottomLeft())
indentWidthChars = len(self._indenter.text())
cursorPos = self.cursorPosition
for block in iterateBlocksFrom(self.firstVisibleBlock()):
blockGeometry = self.blockBoundingGeometry(block).translated(self.contentOffset())
if blockGeometry.top() > paintEventRect.bottom():
break
if block.isVisible() and blockGeometry.toRect().intersects(paintEventRect):
# Draw indent markers, if good indentation is not drawn
if self._drawIndentations:
text = block.text()
if not self.drawAnyWhitespace:
column = indentWidthChars
while text.startswith(self._indenter.text()) and \
len(text) > indentWidthChars and \
text[indentWidthChars].isspace():
if column != self._lineLengthEdge and \
(block.blockNumber(), column) != cursorPos: # looks ugly, if both drawn
"""on some fonts line is drawn below the cursor, if offset is 1
Looks like Qt bug"""
drawIndentMarker(block, column)
text = text[indentWidthChars:]
column += indentWidthChars
# Draw edge, but not over a cursor
if not self._drawSolidEdge:
edgePos = effectiveEdgePos(block.text())
if edgePos != -1 and edgePos != cursorPos[1]:
drawEdgeLine(block, edgePos)
if self.drawAnyWhitespace or \
self.drawIncorrectIndentation:
text = block.text()
for column, draw in enumerate(self._chooseVisibleWhitespace(text)):
if draw:
drawWhiteSpace(block, column, text[column]) | [
"def",
"_drawIndentMarkersAndEdge",
"(",
"self",
",",
"paintEventRect",
")",
":",
"painter",
"=",
"QPainter",
"(",
"self",
".",
"viewport",
"(",
")",
")",
"def",
"drawWhiteSpace",
"(",
"block",
",",
"column",
",",
"char",
")",
":",
"leftCursorRect",
"=",
"self",
".",
"__cursorRect",
"(",
"block",
",",
"column",
",",
"0",
")",
"rightCursorRect",
"=",
"self",
".",
"__cursorRect",
"(",
"block",
",",
"column",
"+",
"1",
",",
"0",
")",
"if",
"leftCursorRect",
".",
"top",
"(",
")",
"==",
"rightCursorRect",
".",
"top",
"(",
")",
":",
"# if on the same visual line",
"middleHeight",
"=",
"(",
"leftCursorRect",
".",
"top",
"(",
")",
"+",
"leftCursorRect",
".",
"bottom",
"(",
")",
")",
"/",
"2",
"if",
"char",
"==",
"' '",
":",
"painter",
".",
"setPen",
"(",
"Qt",
".",
"transparent",
")",
"painter",
".",
"setBrush",
"(",
"QBrush",
"(",
"Qt",
".",
"gray",
")",
")",
"xPos",
"=",
"(",
"leftCursorRect",
".",
"x",
"(",
")",
"+",
"rightCursorRect",
".",
"x",
"(",
")",
")",
"/",
"2",
"painter",
".",
"drawRect",
"(",
"QRect",
"(",
"xPos",
",",
"middleHeight",
",",
"2",
",",
"2",
")",
")",
"else",
":",
"painter",
".",
"setPen",
"(",
"QColor",
"(",
"Qt",
".",
"gray",
")",
".",
"lighter",
"(",
"factor",
"=",
"120",
")",
")",
"painter",
".",
"drawLine",
"(",
"leftCursorRect",
".",
"x",
"(",
")",
"+",
"3",
",",
"middleHeight",
",",
"rightCursorRect",
".",
"x",
"(",
")",
"-",
"3",
",",
"middleHeight",
")",
"def",
"effectiveEdgePos",
"(",
"text",
")",
":",
"\"\"\"Position of edge in a block.\n Defined by self._lineLengthEdge, but visible width of \\t is more than 1,\n therefore effective position depends on count and position of \\t symbols\n Return -1 if line is too short to have edge\n \"\"\"",
"if",
"self",
".",
"_lineLengthEdge",
"is",
"None",
":",
"return",
"-",
"1",
"tabExtraWidth",
"=",
"self",
".",
"indentWidth",
"-",
"1",
"fullWidth",
"=",
"len",
"(",
"text",
")",
"+",
"(",
"text",
".",
"count",
"(",
"'\\t'",
")",
"*",
"tabExtraWidth",
")",
"if",
"fullWidth",
"<=",
"self",
".",
"_lineLengthEdge",
":",
"return",
"-",
"1",
"currentWidth",
"=",
"0",
"for",
"pos",
",",
"char",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"char",
"==",
"'\\t'",
":",
"# Qt indents up to indentation level, so visible \\t width depends on position",
"currentWidth",
"+=",
"(",
"self",
".",
"indentWidth",
"-",
"(",
"currentWidth",
"%",
"self",
".",
"indentWidth",
")",
")",
"else",
":",
"currentWidth",
"+=",
"1",
"if",
"currentWidth",
">",
"self",
".",
"_lineLengthEdge",
":",
"return",
"pos",
"else",
":",
"# line too narrow, probably visible \\t width is small",
"return",
"-",
"1",
"def",
"drawEdgeLine",
"(",
"block",
",",
"edgePos",
")",
":",
"painter",
".",
"setPen",
"(",
"QPen",
"(",
"QBrush",
"(",
"self",
".",
"_lineLengthEdgeColor",
")",
",",
"0",
")",
")",
"rect",
"=",
"self",
".",
"__cursorRect",
"(",
"block",
",",
"edgePos",
",",
"0",
")",
"painter",
".",
"drawLine",
"(",
"rect",
".",
"topLeft",
"(",
")",
",",
"rect",
".",
"bottomLeft",
"(",
")",
")",
"def",
"drawIndentMarker",
"(",
"block",
",",
"column",
")",
":",
"painter",
".",
"setPen",
"(",
"QColor",
"(",
"Qt",
".",
"blue",
")",
".",
"lighter",
"(",
")",
")",
"rect",
"=",
"self",
".",
"__cursorRect",
"(",
"block",
",",
"column",
",",
"offset",
"=",
"0",
")",
"painter",
".",
"drawLine",
"(",
"rect",
".",
"topLeft",
"(",
")",
",",
"rect",
".",
"bottomLeft",
"(",
")",
")",
"indentWidthChars",
"=",
"len",
"(",
"self",
".",
"_indenter",
".",
"text",
"(",
")",
")",
"cursorPos",
"=",
"self",
".",
"cursorPosition",
"for",
"block",
"in",
"iterateBlocksFrom",
"(",
"self",
".",
"firstVisibleBlock",
"(",
")",
")",
":",
"blockGeometry",
"=",
"self",
".",
"blockBoundingGeometry",
"(",
"block",
")",
".",
"translated",
"(",
"self",
".",
"contentOffset",
"(",
")",
")",
"if",
"blockGeometry",
".",
"top",
"(",
")",
">",
"paintEventRect",
".",
"bottom",
"(",
")",
":",
"break",
"if",
"block",
".",
"isVisible",
"(",
")",
"and",
"blockGeometry",
".",
"toRect",
"(",
")",
".",
"intersects",
"(",
"paintEventRect",
")",
":",
"# Draw indent markers, if good indentation is not drawn",
"if",
"self",
".",
"_drawIndentations",
":",
"text",
"=",
"block",
".",
"text",
"(",
")",
"if",
"not",
"self",
".",
"drawAnyWhitespace",
":",
"column",
"=",
"indentWidthChars",
"while",
"text",
".",
"startswith",
"(",
"self",
".",
"_indenter",
".",
"text",
"(",
")",
")",
"and",
"len",
"(",
"text",
")",
">",
"indentWidthChars",
"and",
"text",
"[",
"indentWidthChars",
"]",
".",
"isspace",
"(",
")",
":",
"if",
"column",
"!=",
"self",
".",
"_lineLengthEdge",
"and",
"(",
"block",
".",
"blockNumber",
"(",
")",
",",
"column",
")",
"!=",
"cursorPos",
":",
"# looks ugly, if both drawn",
"\"\"\"on some fonts line is drawn below the cursor, if offset is 1\n Looks like Qt bug\"\"\"",
"drawIndentMarker",
"(",
"block",
",",
"column",
")",
"text",
"=",
"text",
"[",
"indentWidthChars",
":",
"]",
"column",
"+=",
"indentWidthChars",
"# Draw edge, but not over a cursor",
"if",
"not",
"self",
".",
"_drawSolidEdge",
":",
"edgePos",
"=",
"effectiveEdgePos",
"(",
"block",
".",
"text",
"(",
")",
")",
"if",
"edgePos",
"!=",
"-",
"1",
"and",
"edgePos",
"!=",
"cursorPos",
"[",
"1",
"]",
":",
"drawEdgeLine",
"(",
"block",
",",
"edgePos",
")",
"if",
"self",
".",
"drawAnyWhitespace",
"or",
"self",
".",
"drawIncorrectIndentation",
":",
"text",
"=",
"block",
".",
"text",
"(",
")",
"for",
"column",
",",
"draw",
"in",
"enumerate",
"(",
"self",
".",
"_chooseVisibleWhitespace",
"(",
"text",
")",
")",
":",
"if",
"draw",
":",
"drawWhiteSpace",
"(",
"block",
",",
"column",
",",
"text",
"[",
"column",
"]",
")"
] | Draw indentation markers | [
"Draw",
"indentation",
"markers"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1161-L1256 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._currentLineExtraSelections | def _currentLineExtraSelections(self):
"""QTextEdit.ExtraSelection, which highlightes current line
"""
if self._currentLineColor is None:
return []
def makeSelection(cursor):
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(self._currentLineColor)
selection.format.setProperty(QTextFormat.FullWidthSelection, True)
cursor.clearSelection()
selection.cursor = cursor
return selection
rectangularSelectionCursors = self._rectangularSelection.cursors()
if rectangularSelectionCursors:
return [makeSelection(cursor) \
for cursor in rectangularSelectionCursors]
else:
return [makeSelection(self.textCursor())] | python | def _currentLineExtraSelections(self):
"""QTextEdit.ExtraSelection, which highlightes current line
"""
if self._currentLineColor is None:
return []
def makeSelection(cursor):
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(self._currentLineColor)
selection.format.setProperty(QTextFormat.FullWidthSelection, True)
cursor.clearSelection()
selection.cursor = cursor
return selection
rectangularSelectionCursors = self._rectangularSelection.cursors()
if rectangularSelectionCursors:
return [makeSelection(cursor) \
for cursor in rectangularSelectionCursors]
else:
return [makeSelection(self.textCursor())] | [
"def",
"_currentLineExtraSelections",
"(",
"self",
")",
":",
"if",
"self",
".",
"_currentLineColor",
"is",
"None",
":",
"return",
"[",
"]",
"def",
"makeSelection",
"(",
"cursor",
")",
":",
"selection",
"=",
"QTextEdit",
".",
"ExtraSelection",
"(",
")",
"selection",
".",
"format",
".",
"setBackground",
"(",
"self",
".",
"_currentLineColor",
")",
"selection",
".",
"format",
".",
"setProperty",
"(",
"QTextFormat",
".",
"FullWidthSelection",
",",
"True",
")",
"cursor",
".",
"clearSelection",
"(",
")",
"selection",
".",
"cursor",
"=",
"cursor",
"return",
"selection",
"rectangularSelectionCursors",
"=",
"self",
".",
"_rectangularSelection",
".",
"cursors",
"(",
")",
"if",
"rectangularSelectionCursors",
":",
"return",
"[",
"makeSelection",
"(",
"cursor",
")",
"for",
"cursor",
"in",
"rectangularSelectionCursors",
"]",
"else",
":",
"return",
"[",
"makeSelection",
"(",
"self",
".",
"textCursor",
"(",
")",
")",
"]"
] | QTextEdit.ExtraSelection, which highlightes current line | [
"QTextEdit",
".",
"ExtraSelection",
"which",
"highlightes",
"current",
"line"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1266-L1285 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._updateExtraSelections | def _updateExtraSelections(self):
"""Highlight current line
"""
cursorColumnIndex = self.textCursor().positionInBlock()
bracketSelections = self._bracketHighlighter.extraSelections(self,
self.textCursor().block(),
cursorColumnIndex)
selections = self._currentLineExtraSelections() + \
self._rectangularSelection.selections() + \
bracketSelections + \
self._userExtraSelections
self._nonVimExtraSelections = selections
if self._vim is None:
allSelections = selections
else:
allSelections = selections + self._vim.extraSelections()
QPlainTextEdit.setExtraSelections(self, allSelections) | python | def _updateExtraSelections(self):
"""Highlight current line
"""
cursorColumnIndex = self.textCursor().positionInBlock()
bracketSelections = self._bracketHighlighter.extraSelections(self,
self.textCursor().block(),
cursorColumnIndex)
selections = self._currentLineExtraSelections() + \
self._rectangularSelection.selections() + \
bracketSelections + \
self._userExtraSelections
self._nonVimExtraSelections = selections
if self._vim is None:
allSelections = selections
else:
allSelections = selections + self._vim.extraSelections()
QPlainTextEdit.setExtraSelections(self, allSelections) | [
"def",
"_updateExtraSelections",
"(",
"self",
")",
":",
"cursorColumnIndex",
"=",
"self",
".",
"textCursor",
"(",
")",
".",
"positionInBlock",
"(",
")",
"bracketSelections",
"=",
"self",
".",
"_bracketHighlighter",
".",
"extraSelections",
"(",
"self",
",",
"self",
".",
"textCursor",
"(",
")",
".",
"block",
"(",
")",
",",
"cursorColumnIndex",
")",
"selections",
"=",
"self",
".",
"_currentLineExtraSelections",
"(",
")",
"+",
"self",
".",
"_rectangularSelection",
".",
"selections",
"(",
")",
"+",
"bracketSelections",
"+",
"self",
".",
"_userExtraSelections",
"self",
".",
"_nonVimExtraSelections",
"=",
"selections",
"if",
"self",
".",
"_vim",
"is",
"None",
":",
"allSelections",
"=",
"selections",
"else",
":",
"allSelections",
"=",
"selections",
"+",
"self",
".",
"_vim",
".",
"extraSelections",
"(",
")",
"QPlainTextEdit",
".",
"setExtraSelections",
"(",
"self",
",",
"allSelections",
")"
] | Highlight current line | [
"Highlight",
"current",
"line"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1287-L1308 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutScroll | def _onShortcutScroll(self, down):
"""Ctrl+Up/Down pressed, scroll viewport
"""
value = self.verticalScrollBar().value()
if down:
value += 1
else:
value -= 1
self.verticalScrollBar().setValue(value) | python | def _onShortcutScroll(self, down):
"""Ctrl+Up/Down pressed, scroll viewport
"""
value = self.verticalScrollBar().value()
if down:
value += 1
else:
value -= 1
self.verticalScrollBar().setValue(value) | [
"def",
"_onShortcutScroll",
"(",
"self",
",",
"down",
")",
":",
"value",
"=",
"self",
".",
"verticalScrollBar",
"(",
")",
".",
"value",
"(",
")",
"if",
"down",
":",
"value",
"+=",
"1",
"else",
":",
"value",
"-=",
"1",
"self",
".",
"verticalScrollBar",
"(",
")",
".",
"setValue",
"(",
"value",
")"
] | Ctrl+Up/Down pressed, scroll viewport | [
"Ctrl",
"+",
"Up",
"/",
"Down",
"pressed",
"scroll",
"viewport"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1319-L1327 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutSelectAndScroll | def _onShortcutSelectAndScroll(self, down):
"""Ctrl+Shift+Up/Down pressed.
Select line and scroll viewport
"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.Down if down else QTextCursor.Up, QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
self._onShortcutScroll(down) | python | def _onShortcutSelectAndScroll(self, down):
"""Ctrl+Shift+Up/Down pressed.
Select line and scroll viewport
"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.Down if down else QTextCursor.Up, QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
self._onShortcutScroll(down) | [
"def",
"_onShortcutSelectAndScroll",
"(",
"self",
",",
"down",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"Down",
"if",
"down",
"else",
"QTextCursor",
".",
"Up",
",",
"QTextCursor",
".",
"KeepAnchor",
")",
"self",
".",
"setTextCursor",
"(",
"cursor",
")",
"self",
".",
"_onShortcutScroll",
"(",
"down",
")"
] | Ctrl+Shift+Up/Down pressed.
Select line and scroll viewport | [
"Ctrl",
"+",
"Shift",
"+",
"Up",
"/",
"Down",
"pressed",
".",
"Select",
"line",
"and",
"scroll",
"viewport"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1329-L1336 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutHome | def _onShortcutHome(self, select):
"""Home pressed. Run a state machine:
1. Not at the line beginning. Move to the beginning of the line or
the beginning of the indent, whichever is closest to the current
cursor position.
2. At the line beginning. Move to the beginning of the indent.
3. At the beginning of the indent. Go to the beginning of the block.
4. At the beginning of the block. Go to the beginning of the indent.
"""
# Gather info for cursor state and movement.
cursor = self.textCursor()
text = cursor.block().text()
indent = len(text) - len(text.lstrip())
anchor = QTextCursor.KeepAnchor if select else QTextCursor.MoveAnchor
# Determine current state and move based on that.
if cursor.positionInBlock() == indent:
# We're at the beginning of the indent. Go to the beginning of the
# block.
cursor.movePosition(QTextCursor.StartOfBlock, anchor)
elif cursor.atBlockStart():
# We're at the beginning of the block. Go to the beginning of the
# indent.
setPositionInBlock(cursor, indent, anchor)
else:
# Neither of the above. There's no way I can find to directly
# determine if we're at the beginning of a line. So, try moving and
# see if the cursor location changes.
pos = cursor.positionInBlock()
cursor.movePosition(QTextCursor.StartOfLine, anchor)
# If we didn't move, we were already at the beginning of the line.
# So, move to the indent.
if pos == cursor.positionInBlock():
setPositionInBlock(cursor, indent, anchor)
# If we did move, check to see if the indent was closer to the
# cursor than the beginning of the indent. If so, move to the
# indent.
elif cursor.positionInBlock() < indent:
setPositionInBlock(cursor, indent, anchor)
self.setTextCursor(cursor) | python | def _onShortcutHome(self, select):
"""Home pressed. Run a state machine:
1. Not at the line beginning. Move to the beginning of the line or
the beginning of the indent, whichever is closest to the current
cursor position.
2. At the line beginning. Move to the beginning of the indent.
3. At the beginning of the indent. Go to the beginning of the block.
4. At the beginning of the block. Go to the beginning of the indent.
"""
# Gather info for cursor state and movement.
cursor = self.textCursor()
text = cursor.block().text()
indent = len(text) - len(text.lstrip())
anchor = QTextCursor.KeepAnchor if select else QTextCursor.MoveAnchor
# Determine current state and move based on that.
if cursor.positionInBlock() == indent:
# We're at the beginning of the indent. Go to the beginning of the
# block.
cursor.movePosition(QTextCursor.StartOfBlock, anchor)
elif cursor.atBlockStart():
# We're at the beginning of the block. Go to the beginning of the
# indent.
setPositionInBlock(cursor, indent, anchor)
else:
# Neither of the above. There's no way I can find to directly
# determine if we're at the beginning of a line. So, try moving and
# see if the cursor location changes.
pos = cursor.positionInBlock()
cursor.movePosition(QTextCursor.StartOfLine, anchor)
# If we didn't move, we were already at the beginning of the line.
# So, move to the indent.
if pos == cursor.positionInBlock():
setPositionInBlock(cursor, indent, anchor)
# If we did move, check to see if the indent was closer to the
# cursor than the beginning of the indent. If so, move to the
# indent.
elif cursor.positionInBlock() < indent:
setPositionInBlock(cursor, indent, anchor)
self.setTextCursor(cursor) | [
"def",
"_onShortcutHome",
"(",
"self",
",",
"select",
")",
":",
"# Gather info for cursor state and movement.",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"text",
"=",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"indent",
"=",
"len",
"(",
"text",
")",
"-",
"len",
"(",
"text",
".",
"lstrip",
"(",
")",
")",
"anchor",
"=",
"QTextCursor",
".",
"KeepAnchor",
"if",
"select",
"else",
"QTextCursor",
".",
"MoveAnchor",
"# Determine current state and move based on that.",
"if",
"cursor",
".",
"positionInBlock",
"(",
")",
"==",
"indent",
":",
"# We're at the beginning of the indent. Go to the beginning of the",
"# block.",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"StartOfBlock",
",",
"anchor",
")",
"elif",
"cursor",
".",
"atBlockStart",
"(",
")",
":",
"# We're at the beginning of the block. Go to the beginning of the",
"# indent.",
"setPositionInBlock",
"(",
"cursor",
",",
"indent",
",",
"anchor",
")",
"else",
":",
"# Neither of the above. There's no way I can find to directly",
"# determine if we're at the beginning of a line. So, try moving and",
"# see if the cursor location changes.",
"pos",
"=",
"cursor",
".",
"positionInBlock",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"StartOfLine",
",",
"anchor",
")",
"# If we didn't move, we were already at the beginning of the line.",
"# So, move to the indent.",
"if",
"pos",
"==",
"cursor",
".",
"positionInBlock",
"(",
")",
":",
"setPositionInBlock",
"(",
"cursor",
",",
"indent",
",",
"anchor",
")",
"# If we did move, check to see if the indent was closer to the",
"# cursor than the beginning of the indent. If so, move to the",
"# indent.",
"elif",
"cursor",
".",
"positionInBlock",
"(",
")",
"<",
"indent",
":",
"setPositionInBlock",
"(",
"cursor",
",",
"indent",
",",
"anchor",
")",
"self",
".",
"setTextCursor",
"(",
"cursor",
")"
] | Home pressed. Run a state machine:
1. Not at the line beginning. Move to the beginning of the line or
the beginning of the indent, whichever is closest to the current
cursor position.
2. At the line beginning. Move to the beginning of the indent.
3. At the beginning of the indent. Go to the beginning of the block.
4. At the beginning of the block. Go to the beginning of the indent. | [
"Home",
"pressed",
".",
"Run",
"a",
"state",
"machine",
":"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1338-L1379 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._selectLines | def _selectLines(self, startBlockNumber, endBlockNumber):
"""Select whole lines
"""
startBlock = self.document().findBlockByNumber(startBlockNumber)
endBlock = self.document().findBlockByNumber(endBlockNumber)
cursor = QTextCursor(startBlock)
cursor.setPosition(endBlock.position(), QTextCursor.KeepAnchor)
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
self.setTextCursor(cursor) | python | def _selectLines(self, startBlockNumber, endBlockNumber):
"""Select whole lines
"""
startBlock = self.document().findBlockByNumber(startBlockNumber)
endBlock = self.document().findBlockByNumber(endBlockNumber)
cursor = QTextCursor(startBlock)
cursor.setPosition(endBlock.position(), QTextCursor.KeepAnchor)
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
self.setTextCursor(cursor) | [
"def",
"_selectLines",
"(",
"self",
",",
"startBlockNumber",
",",
"endBlockNumber",
")",
":",
"startBlock",
"=",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"startBlockNumber",
")",
"endBlock",
"=",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"endBlockNumber",
")",
"cursor",
"=",
"QTextCursor",
"(",
"startBlock",
")",
"cursor",
".",
"setPosition",
"(",
"endBlock",
".",
"position",
"(",
")",
",",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"EndOfBlock",
",",
"QTextCursor",
".",
"KeepAnchor",
")",
"self",
".",
"setTextCursor",
"(",
"cursor",
")"
] | Select whole lines | [
"Select",
"whole",
"lines"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1381-L1389 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._selectedBlocks | def _selectedBlocks(self):
"""Return selected blocks and tuple (startBlock, endBlock)
"""
cursor = self.textCursor()
return self.document().findBlock(cursor.selectionStart()), \
self.document().findBlock(cursor.selectionEnd()) | python | def _selectedBlocks(self):
"""Return selected blocks and tuple (startBlock, endBlock)
"""
cursor = self.textCursor()
return self.document().findBlock(cursor.selectionStart()), \
self.document().findBlock(cursor.selectionEnd()) | [
"def",
"_selectedBlocks",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"return",
"self",
".",
"document",
"(",
")",
".",
"findBlock",
"(",
"cursor",
".",
"selectionStart",
"(",
")",
")",
",",
"self",
".",
"document",
"(",
")",
".",
"findBlock",
"(",
"cursor",
".",
"selectionEnd",
"(",
")",
")"
] | Return selected blocks and tuple (startBlock, endBlock) | [
"Return",
"selected",
"blocks",
"and",
"tuple",
"(",
"startBlock",
"endBlock",
")"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1391-L1396 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._selectedBlockNumbers | def _selectedBlockNumbers(self):
"""Return selected block numbers and tuple (startBlockNumber, endBlockNumber)
"""
startBlock, endBlock = self._selectedBlocks()
return startBlock.blockNumber(), endBlock.blockNumber() | python | def _selectedBlockNumbers(self):
"""Return selected block numbers and tuple (startBlockNumber, endBlockNumber)
"""
startBlock, endBlock = self._selectedBlocks()
return startBlock.blockNumber(), endBlock.blockNumber() | [
"def",
"_selectedBlockNumbers",
"(",
"self",
")",
":",
"startBlock",
",",
"endBlock",
"=",
"self",
".",
"_selectedBlocks",
"(",
")",
"return",
"startBlock",
".",
"blockNumber",
"(",
")",
",",
"endBlock",
".",
"blockNumber",
"(",
")"
] | Return selected block numbers and tuple (startBlockNumber, endBlockNumber) | [
"Return",
"selected",
"block",
"numbers",
"and",
"tuple",
"(",
"startBlockNumber",
"endBlockNumber",
")"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1398-L1402 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutMoveLine | def _onShortcutMoveLine(self, down):
"""Move line up or down
Actually, not a selected text, but next or previous block is moved
TODO keep bookmarks when moving
"""
startBlock, endBlock = self._selectedBlocks()
startBlockNumber = startBlock.blockNumber()
endBlockNumber = endBlock.blockNumber()
def _moveBlock(block, newNumber):
text = block.text()
with self:
del self.lines[block.blockNumber()]
self.lines.insert(newNumber, text)
if down: # move next block up
blockToMove = endBlock.next()
if not blockToMove.isValid():
return
# if operaiton is UnDone, marks are located incorrectly
markMargin = self.getMargin("mark_area")
if markMargin:
markMargin.clearBookmarks(startBlock, endBlock.next())
_moveBlock(blockToMove, startBlockNumber)
self._selectLines(startBlockNumber + 1, endBlockNumber + 1)
else: # move previous block down
blockToMove = startBlock.previous()
if not blockToMove.isValid():
return
# if operaiton is UnDone, marks are located incorrectly
markMargin = self.getMargin("mark_area")
if markMargin:
markMargin.clearBookmarks(startBlock, endBlock)
_moveBlock(blockToMove, endBlockNumber)
self._selectLines(startBlockNumber - 1, endBlockNumber - 1)
if markMargin:
markMargin.update() | python | def _onShortcutMoveLine(self, down):
"""Move line up or down
Actually, not a selected text, but next or previous block is moved
TODO keep bookmarks when moving
"""
startBlock, endBlock = self._selectedBlocks()
startBlockNumber = startBlock.blockNumber()
endBlockNumber = endBlock.blockNumber()
def _moveBlock(block, newNumber):
text = block.text()
with self:
del self.lines[block.blockNumber()]
self.lines.insert(newNumber, text)
if down: # move next block up
blockToMove = endBlock.next()
if not blockToMove.isValid():
return
# if operaiton is UnDone, marks are located incorrectly
markMargin = self.getMargin("mark_area")
if markMargin:
markMargin.clearBookmarks(startBlock, endBlock.next())
_moveBlock(blockToMove, startBlockNumber)
self._selectLines(startBlockNumber + 1, endBlockNumber + 1)
else: # move previous block down
blockToMove = startBlock.previous()
if not blockToMove.isValid():
return
# if operaiton is UnDone, marks are located incorrectly
markMargin = self.getMargin("mark_area")
if markMargin:
markMargin.clearBookmarks(startBlock, endBlock)
_moveBlock(blockToMove, endBlockNumber)
self._selectLines(startBlockNumber - 1, endBlockNumber - 1)
if markMargin:
markMargin.update() | [
"def",
"_onShortcutMoveLine",
"(",
"self",
",",
"down",
")",
":",
"startBlock",
",",
"endBlock",
"=",
"self",
".",
"_selectedBlocks",
"(",
")",
"startBlockNumber",
"=",
"startBlock",
".",
"blockNumber",
"(",
")",
"endBlockNumber",
"=",
"endBlock",
".",
"blockNumber",
"(",
")",
"def",
"_moveBlock",
"(",
"block",
",",
"newNumber",
")",
":",
"text",
"=",
"block",
".",
"text",
"(",
")",
"with",
"self",
":",
"del",
"self",
".",
"lines",
"[",
"block",
".",
"blockNumber",
"(",
")",
"]",
"self",
".",
"lines",
".",
"insert",
"(",
"newNumber",
",",
"text",
")",
"if",
"down",
":",
"# move next block up",
"blockToMove",
"=",
"endBlock",
".",
"next",
"(",
")",
"if",
"not",
"blockToMove",
".",
"isValid",
"(",
")",
":",
"return",
"# if operaiton is UnDone, marks are located incorrectly",
"markMargin",
"=",
"self",
".",
"getMargin",
"(",
"\"mark_area\"",
")",
"if",
"markMargin",
":",
"markMargin",
".",
"clearBookmarks",
"(",
"startBlock",
",",
"endBlock",
".",
"next",
"(",
")",
")",
"_moveBlock",
"(",
"blockToMove",
",",
"startBlockNumber",
")",
"self",
".",
"_selectLines",
"(",
"startBlockNumber",
"+",
"1",
",",
"endBlockNumber",
"+",
"1",
")",
"else",
":",
"# move previous block down",
"blockToMove",
"=",
"startBlock",
".",
"previous",
"(",
")",
"if",
"not",
"blockToMove",
".",
"isValid",
"(",
")",
":",
"return",
"# if operaiton is UnDone, marks are located incorrectly",
"markMargin",
"=",
"self",
".",
"getMargin",
"(",
"\"mark_area\"",
")",
"if",
"markMargin",
":",
"markMargin",
".",
"clearBookmarks",
"(",
"startBlock",
",",
"endBlock",
")",
"_moveBlock",
"(",
"blockToMove",
",",
"endBlockNumber",
")",
"self",
".",
"_selectLines",
"(",
"startBlockNumber",
"-",
"1",
",",
"endBlockNumber",
"-",
"1",
")",
"if",
"markMargin",
":",
"markMargin",
".",
"update",
"(",
")"
] | Move line up or down
Actually, not a selected text, but next or previous block is moved
TODO keep bookmarks when moving | [
"Move",
"line",
"up",
"or",
"down",
"Actually",
"not",
"a",
"selected",
"text",
"but",
"next",
"or",
"previous",
"block",
"is",
"moved",
"TODO",
"keep",
"bookmarks",
"when",
"moving"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1404-L1448 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutCopyLine | def _onShortcutCopyLine(self):
"""Copy selected lines to the clipboard
"""
lines = self.lines[self._selectedLinesSlice()]
text = self._eol.join(lines)
QApplication.clipboard().setText(text) | python | def _onShortcutCopyLine(self):
"""Copy selected lines to the clipboard
"""
lines = self.lines[self._selectedLinesSlice()]
text = self._eol.join(lines)
QApplication.clipboard().setText(text) | [
"def",
"_onShortcutCopyLine",
"(",
"self",
")",
":",
"lines",
"=",
"self",
".",
"lines",
"[",
"self",
".",
"_selectedLinesSlice",
"(",
")",
"]",
"text",
"=",
"self",
".",
"_eol",
".",
"join",
"(",
"lines",
")",
"QApplication",
".",
"clipboard",
"(",
")",
".",
"setText",
"(",
"text",
")"
] | Copy selected lines to the clipboard | [
"Copy",
"selected",
"lines",
"to",
"the",
"clipboard"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1461-L1466 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutPasteLine | def _onShortcutPasteLine(self):
"""Paste lines from the clipboard
"""
lines = self.lines[self._selectedLinesSlice()]
text = QApplication.clipboard().text()
if text:
with self:
if self.textCursor().hasSelection():
startBlockNumber, endBlockNumber = self._selectedBlockNumbers()
del self.lines[self._selectedLinesSlice()]
self.lines.insert(startBlockNumber, text)
else:
line, col = self.cursorPosition
if col > 0:
line = line + 1
self.lines.insert(line, text) | python | def _onShortcutPasteLine(self):
"""Paste lines from the clipboard
"""
lines = self.lines[self._selectedLinesSlice()]
text = QApplication.clipboard().text()
if text:
with self:
if self.textCursor().hasSelection():
startBlockNumber, endBlockNumber = self._selectedBlockNumbers()
del self.lines[self._selectedLinesSlice()]
self.lines.insert(startBlockNumber, text)
else:
line, col = self.cursorPosition
if col > 0:
line = line + 1
self.lines.insert(line, text) | [
"def",
"_onShortcutPasteLine",
"(",
"self",
")",
":",
"lines",
"=",
"self",
".",
"lines",
"[",
"self",
".",
"_selectedLinesSlice",
"(",
")",
"]",
"text",
"=",
"QApplication",
".",
"clipboard",
"(",
")",
".",
"text",
"(",
")",
"if",
"text",
":",
"with",
"self",
":",
"if",
"self",
".",
"textCursor",
"(",
")",
".",
"hasSelection",
"(",
")",
":",
"startBlockNumber",
",",
"endBlockNumber",
"=",
"self",
".",
"_selectedBlockNumbers",
"(",
")",
"del",
"self",
".",
"lines",
"[",
"self",
".",
"_selectedLinesSlice",
"(",
")",
"]",
"self",
".",
"lines",
".",
"insert",
"(",
"startBlockNumber",
",",
"text",
")",
"else",
":",
"line",
",",
"col",
"=",
"self",
".",
"cursorPosition",
"if",
"col",
">",
"0",
":",
"line",
"=",
"line",
"+",
"1",
"self",
".",
"lines",
".",
"insert",
"(",
"line",
",",
"text",
")"
] | Paste lines from the clipboard | [
"Paste",
"lines",
"from",
"the",
"clipboard"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1468-L1483 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutCutLine | def _onShortcutCutLine(self):
"""Cut selected lines to the clipboard
"""
lines = self.lines[self._selectedLinesSlice()]
self._onShortcutCopyLine()
self._onShortcutDeleteLine() | python | def _onShortcutCutLine(self):
"""Cut selected lines to the clipboard
"""
lines = self.lines[self._selectedLinesSlice()]
self._onShortcutCopyLine()
self._onShortcutDeleteLine() | [
"def",
"_onShortcutCutLine",
"(",
"self",
")",
":",
"lines",
"=",
"self",
".",
"lines",
"[",
"self",
".",
"_selectedLinesSlice",
"(",
")",
"]",
"self",
".",
"_onShortcutCopyLine",
"(",
")",
"self",
".",
"_onShortcutDeleteLine",
"(",
")"
] | Cut selected lines to the clipboard | [
"Cut",
"selected",
"lines",
"to",
"the",
"clipboard"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1485-L1491 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutDuplicateLine | def _onShortcutDuplicateLine(self):
"""Duplicate selected text or current line
"""
cursor = self.textCursor()
if cursor.hasSelection(): # duplicate selection
text = cursor.selectedText()
selectionStart, selectionEnd = cursor.selectionStart(), cursor.selectionEnd()
cursor.setPosition(selectionEnd)
cursor.insertText(text)
# restore selection
cursor.setPosition(selectionStart)
cursor.setPosition(selectionEnd, QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
else:
line = cursor.blockNumber()
self.lines.insert(line + 1, self.lines[line])
self.ensureCursorVisible()
self._updateExtraSelections() | python | def _onShortcutDuplicateLine(self):
"""Duplicate selected text or current line
"""
cursor = self.textCursor()
if cursor.hasSelection(): # duplicate selection
text = cursor.selectedText()
selectionStart, selectionEnd = cursor.selectionStart(), cursor.selectionEnd()
cursor.setPosition(selectionEnd)
cursor.insertText(text)
# restore selection
cursor.setPosition(selectionStart)
cursor.setPosition(selectionEnd, QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
else:
line = cursor.blockNumber()
self.lines.insert(line + 1, self.lines[line])
self.ensureCursorVisible()
self._updateExtraSelections() | [
"def",
"_onShortcutDuplicateLine",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"if",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"# duplicate selection",
"text",
"=",
"cursor",
".",
"selectedText",
"(",
")",
"selectionStart",
",",
"selectionEnd",
"=",
"cursor",
".",
"selectionStart",
"(",
")",
",",
"cursor",
".",
"selectionEnd",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"selectionEnd",
")",
"cursor",
".",
"insertText",
"(",
"text",
")",
"# restore selection",
"cursor",
".",
"setPosition",
"(",
"selectionStart",
")",
"cursor",
".",
"setPosition",
"(",
"selectionEnd",
",",
"QTextCursor",
".",
"KeepAnchor",
")",
"self",
".",
"setTextCursor",
"(",
"cursor",
")",
"else",
":",
"line",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"self",
".",
"lines",
".",
"insert",
"(",
"line",
"+",
"1",
",",
"self",
".",
"lines",
"[",
"line",
"]",
")",
"self",
".",
"ensureCursorVisible",
"(",
")",
"self",
".",
"_updateExtraSelections",
"(",
")"
] | Duplicate selected text or current line | [
"Duplicate",
"selected",
"text",
"or",
"current",
"line"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1493-L1511 |
andreikop/qutepart | qutepart/__init__.py | Qutepart._onShortcutPrint | def _onShortcutPrint(self):
"""Ctrl+P handler.
Show dialog, print file
"""
dialog = QPrintDialog(self)
if dialog.exec_() == QDialog.Accepted:
printer = dialog.printer()
self.print_(printer) | python | def _onShortcutPrint(self):
"""Ctrl+P handler.
Show dialog, print file
"""
dialog = QPrintDialog(self)
if dialog.exec_() == QDialog.Accepted:
printer = dialog.printer()
self.print_(printer) | [
"def",
"_onShortcutPrint",
"(",
"self",
")",
":",
"dialog",
"=",
"QPrintDialog",
"(",
"self",
")",
"if",
"dialog",
".",
"exec_",
"(",
")",
"==",
"QDialog",
".",
"Accepted",
":",
"printer",
"=",
"dialog",
".",
"printer",
"(",
")",
"self",
".",
"print_",
"(",
"printer",
")"
] | Ctrl+P handler.
Show dialog, print file | [
"Ctrl",
"+",
"P",
"handler",
".",
"Show",
"dialog",
"print",
"file"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1513-L1520 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.addMargin | def addMargin(self, margin, index=None):
"""Adds a new margin.
index: index in the list of margins. Default: to the end of the list
"""
if index is None:
self._margins.append(margin)
else:
self._margins.insert(index, margin)
if margin.isVisible():
self.updateViewport() | python | def addMargin(self, margin, index=None):
"""Adds a new margin.
index: index in the list of margins. Default: to the end of the list
"""
if index is None:
self._margins.append(margin)
else:
self._margins.insert(index, margin)
if margin.isVisible():
self.updateViewport() | [
"def",
"addMargin",
"(",
"self",
",",
"margin",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"self",
".",
"_margins",
".",
"append",
"(",
"margin",
")",
"else",
":",
"self",
".",
"_margins",
".",
"insert",
"(",
"index",
",",
"margin",
")",
"if",
"margin",
".",
"isVisible",
"(",
")",
":",
"self",
".",
"updateViewport",
"(",
")"
] | Adds a new margin.
index: index in the list of margins. Default: to the end of the list | [
"Adds",
"a",
"new",
"margin",
".",
"index",
":",
"index",
"in",
"the",
"list",
"of",
"margins",
".",
"Default",
":",
"to",
"the",
"end",
"of",
"the",
"list"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1539-L1548 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.getMargin | def getMargin(self, name):
"""Provides the requested margin.
Returns a reference to the margin if found and None otherwise
"""
for margin in self._margins:
if margin.getName() == name:
return margin
return None | python | def getMargin(self, name):
"""Provides the requested margin.
Returns a reference to the margin if found and None otherwise
"""
for margin in self._margins:
if margin.getName() == name:
return margin
return None | [
"def",
"getMargin",
"(",
"self",
",",
"name",
")",
":",
"for",
"margin",
"in",
"self",
".",
"_margins",
":",
"if",
"margin",
".",
"getName",
"(",
")",
"==",
"name",
":",
"return",
"margin",
"return",
"None"
] | Provides the requested margin.
Returns a reference to the margin if found and None otherwise | [
"Provides",
"the",
"requested",
"margin",
".",
"Returns",
"a",
"reference",
"to",
"the",
"margin",
"if",
"found",
"and",
"None",
"otherwise"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1550-L1557 |
andreikop/qutepart | qutepart/__init__.py | Qutepart.delMargin | def delMargin(self, name):
"""Deletes a margin.
Returns True if the margin was deleted and False otherwise.
"""
for index, margin in enumerate(self._margins):
if margin.getName() == name:
visible = margin.isVisible()
margin.clear()
margin.deleteLater()
del self._margins[index]
if visible:
self.updateViewport()
return True
return False | python | def delMargin(self, name):
"""Deletes a margin.
Returns True if the margin was deleted and False otherwise.
"""
for index, margin in enumerate(self._margins):
if margin.getName() == name:
visible = margin.isVisible()
margin.clear()
margin.deleteLater()
del self._margins[index]
if visible:
self.updateViewport()
return True
return False | [
"def",
"delMargin",
"(",
"self",
",",
"name",
")",
":",
"for",
"index",
",",
"margin",
"in",
"enumerate",
"(",
"self",
".",
"_margins",
")",
":",
"if",
"margin",
".",
"getName",
"(",
")",
"==",
"name",
":",
"visible",
"=",
"margin",
".",
"isVisible",
"(",
")",
"margin",
".",
"clear",
"(",
")",
"margin",
".",
"deleteLater",
"(",
")",
"del",
"self",
".",
"_margins",
"[",
"index",
"]",
"if",
"visible",
":",
"self",
".",
"updateViewport",
"(",
")",
"return",
"True",
"return",
"False"
] | Deletes a margin.
Returns True if the margin was deleted and False otherwise. | [
"Deletes",
"a",
"margin",
".",
"Returns",
"True",
"if",
"the",
"margin",
"was",
"deleted",
"and",
"False",
"otherwise",
"."
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1559-L1572 |
andreikop/qutepart | qutepart/sideareas.py | LineNumberArea.paintEvent | def paintEvent(self, event):
"""QWidget.paintEvent() implementation
"""
painter = QPainter(self)
painter.fillRect(event.rect(), self.palette().color(QPalette.Window))
painter.setPen(Qt.black)
block = self._qpart.firstVisibleBlock()
blockNumber = block.blockNumber()
top = int(self._qpart.blockBoundingGeometry(block).translated(self._qpart.contentOffset()).top())
bottom = top + int(self._qpart.blockBoundingRect(block).height())
singleBlockHeight = self._qpart.cursorRect().height()
boundingRect = self._qpart.blockBoundingRect(block)
availableWidth = self.__width - self._RIGHT_MARGIN - self._LEFT_MARGIN
availableHeight = self._qpart.fontMetrics().height()
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and bottom >= event.rect().top():
number = str(blockNumber + 1)
painter.drawText(self._LEFT_MARGIN, top,
availableWidth, availableHeight,
Qt.AlignRight, number)
if boundingRect.height() >= singleBlockHeight * 2: # wrapped block
painter.fillRect(1, top + singleBlockHeight,
self.__width - 2, boundingRect.height() - singleBlockHeight - 2,
Qt.darkGreen)
block = block.next()
boundingRect = self._qpart.blockBoundingRect(block)
top = bottom
bottom = top + int(boundingRect.height())
blockNumber += 1 | python | def paintEvent(self, event):
"""QWidget.paintEvent() implementation
"""
painter = QPainter(self)
painter.fillRect(event.rect(), self.palette().color(QPalette.Window))
painter.setPen(Qt.black)
block = self._qpart.firstVisibleBlock()
blockNumber = block.blockNumber()
top = int(self._qpart.blockBoundingGeometry(block).translated(self._qpart.contentOffset()).top())
bottom = top + int(self._qpart.blockBoundingRect(block).height())
singleBlockHeight = self._qpart.cursorRect().height()
boundingRect = self._qpart.blockBoundingRect(block)
availableWidth = self.__width - self._RIGHT_MARGIN - self._LEFT_MARGIN
availableHeight = self._qpart.fontMetrics().height()
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and bottom >= event.rect().top():
number = str(blockNumber + 1)
painter.drawText(self._LEFT_MARGIN, top,
availableWidth, availableHeight,
Qt.AlignRight, number)
if boundingRect.height() >= singleBlockHeight * 2: # wrapped block
painter.fillRect(1, top + singleBlockHeight,
self.__width - 2, boundingRect.height() - singleBlockHeight - 2,
Qt.darkGreen)
block = block.next()
boundingRect = self._qpart.blockBoundingRect(block)
top = bottom
bottom = top + int(boundingRect.height())
blockNumber += 1 | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"painter",
".",
"fillRect",
"(",
"event",
".",
"rect",
"(",
")",
",",
"self",
".",
"palette",
"(",
")",
".",
"color",
"(",
"QPalette",
".",
"Window",
")",
")",
"painter",
".",
"setPen",
"(",
"Qt",
".",
"black",
")",
"block",
"=",
"self",
".",
"_qpart",
".",
"firstVisibleBlock",
"(",
")",
"blockNumber",
"=",
"block",
".",
"blockNumber",
"(",
")",
"top",
"=",
"int",
"(",
"self",
".",
"_qpart",
".",
"blockBoundingGeometry",
"(",
"block",
")",
".",
"translated",
"(",
"self",
".",
"_qpart",
".",
"contentOffset",
"(",
")",
")",
".",
"top",
"(",
")",
")",
"bottom",
"=",
"top",
"+",
"int",
"(",
"self",
".",
"_qpart",
".",
"blockBoundingRect",
"(",
"block",
")",
".",
"height",
"(",
")",
")",
"singleBlockHeight",
"=",
"self",
".",
"_qpart",
".",
"cursorRect",
"(",
")",
".",
"height",
"(",
")",
"boundingRect",
"=",
"self",
".",
"_qpart",
".",
"blockBoundingRect",
"(",
"block",
")",
"availableWidth",
"=",
"self",
".",
"__width",
"-",
"self",
".",
"_RIGHT_MARGIN",
"-",
"self",
".",
"_LEFT_MARGIN",
"availableHeight",
"=",
"self",
".",
"_qpart",
".",
"fontMetrics",
"(",
")",
".",
"height",
"(",
")",
"while",
"block",
".",
"isValid",
"(",
")",
"and",
"top",
"<=",
"event",
".",
"rect",
"(",
")",
".",
"bottom",
"(",
")",
":",
"if",
"block",
".",
"isVisible",
"(",
")",
"and",
"bottom",
">=",
"event",
".",
"rect",
"(",
")",
".",
"top",
"(",
")",
":",
"number",
"=",
"str",
"(",
"blockNumber",
"+",
"1",
")",
"painter",
".",
"drawText",
"(",
"self",
".",
"_LEFT_MARGIN",
",",
"top",
",",
"availableWidth",
",",
"availableHeight",
",",
"Qt",
".",
"AlignRight",
",",
"number",
")",
"if",
"boundingRect",
".",
"height",
"(",
")",
">=",
"singleBlockHeight",
"*",
"2",
":",
"# wrapped block",
"painter",
".",
"fillRect",
"(",
"1",
",",
"top",
"+",
"singleBlockHeight",
",",
"self",
".",
"__width",
"-",
"2",
",",
"boundingRect",
".",
"height",
"(",
")",
"-",
"singleBlockHeight",
"-",
"2",
",",
"Qt",
".",
"darkGreen",
")",
"block",
"=",
"block",
".",
"next",
"(",
")",
"boundingRect",
"=",
"self",
".",
"_qpart",
".",
"blockBoundingRect",
"(",
"block",
")",
"top",
"=",
"bottom",
"bottom",
"=",
"top",
"+",
"int",
"(",
"boundingRect",
".",
"height",
"(",
")",
")",
"blockNumber",
"+=",
"1"
] | QWidget.paintEvent() implementation | [
"QWidget",
".",
"paintEvent",
"()",
"implementation"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/sideareas.py#L45-L76 |
andreikop/qutepart | qutepart/sideareas.py | MarkArea.paintEvent | def paintEvent(self, event):
"""QWidget.paintEvent() implementation
Draw markers
"""
painter = QPainter(self)
painter.fillRect(event.rect(), self.palette().color(QPalette.Window))
block = self._qpart.firstVisibleBlock()
blockBoundingGeometry = self._qpart.blockBoundingGeometry(block).translated(self._qpart.contentOffset())
top = blockBoundingGeometry.top()
bottom = top + blockBoundingGeometry.height()
for block in qutepart.iterateBlocksFrom(block):
height = self._qpart.blockBoundingGeometry(block).height()
if top > event.rect().bottom():
break
if block.isVisible() and \
bottom >= event.rect().top():
if block.blockNumber() in self._qpart.lintMarks:
msgType, msgText = self._qpart.lintMarks[block.blockNumber()]
pixMap = self._lintPixmaps[msgType]
yPos = top + ((height - pixMap.height()) / 2) # centered
painter.drawPixmap(0, yPos, pixMap)
if self.isBlockMarked(block):
yPos = top + ((height - self._bookmarkPixmap.height()) / 2) # centered
painter.drawPixmap(0, yPos, self._bookmarkPixmap)
top += height | python | def paintEvent(self, event):
"""QWidget.paintEvent() implementation
Draw markers
"""
painter = QPainter(self)
painter.fillRect(event.rect(), self.palette().color(QPalette.Window))
block = self._qpart.firstVisibleBlock()
blockBoundingGeometry = self._qpart.blockBoundingGeometry(block).translated(self._qpart.contentOffset())
top = blockBoundingGeometry.top()
bottom = top + blockBoundingGeometry.height()
for block in qutepart.iterateBlocksFrom(block):
height = self._qpart.blockBoundingGeometry(block).height()
if top > event.rect().bottom():
break
if block.isVisible() and \
bottom >= event.rect().top():
if block.blockNumber() in self._qpart.lintMarks:
msgType, msgText = self._qpart.lintMarks[block.blockNumber()]
pixMap = self._lintPixmaps[msgType]
yPos = top + ((height - pixMap.height()) / 2) # centered
painter.drawPixmap(0, yPos, pixMap)
if self.isBlockMarked(block):
yPos = top + ((height - self._bookmarkPixmap.height()) / 2) # centered
painter.drawPixmap(0, yPos, self._bookmarkPixmap)
top += height | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"painter",
".",
"fillRect",
"(",
"event",
".",
"rect",
"(",
")",
",",
"self",
".",
"palette",
"(",
")",
".",
"color",
"(",
"QPalette",
".",
"Window",
")",
")",
"block",
"=",
"self",
".",
"_qpart",
".",
"firstVisibleBlock",
"(",
")",
"blockBoundingGeometry",
"=",
"self",
".",
"_qpart",
".",
"blockBoundingGeometry",
"(",
"block",
")",
".",
"translated",
"(",
"self",
".",
"_qpart",
".",
"contentOffset",
"(",
")",
")",
"top",
"=",
"blockBoundingGeometry",
".",
"top",
"(",
")",
"bottom",
"=",
"top",
"+",
"blockBoundingGeometry",
".",
"height",
"(",
")",
"for",
"block",
"in",
"qutepart",
".",
"iterateBlocksFrom",
"(",
"block",
")",
":",
"height",
"=",
"self",
".",
"_qpart",
".",
"blockBoundingGeometry",
"(",
"block",
")",
".",
"height",
"(",
")",
"if",
"top",
">",
"event",
".",
"rect",
"(",
")",
".",
"bottom",
"(",
")",
":",
"break",
"if",
"block",
".",
"isVisible",
"(",
")",
"and",
"bottom",
">=",
"event",
".",
"rect",
"(",
")",
".",
"top",
"(",
")",
":",
"if",
"block",
".",
"blockNumber",
"(",
")",
"in",
"self",
".",
"_qpart",
".",
"lintMarks",
":",
"msgType",
",",
"msgText",
"=",
"self",
".",
"_qpart",
".",
"lintMarks",
"[",
"block",
".",
"blockNumber",
"(",
")",
"]",
"pixMap",
"=",
"self",
".",
"_lintPixmaps",
"[",
"msgType",
"]",
"yPos",
"=",
"top",
"+",
"(",
"(",
"height",
"-",
"pixMap",
".",
"height",
"(",
")",
")",
"/",
"2",
")",
"# centered",
"painter",
".",
"drawPixmap",
"(",
"0",
",",
"yPos",
",",
"pixMap",
")",
"if",
"self",
".",
"isBlockMarked",
"(",
"block",
")",
":",
"yPos",
"=",
"top",
"+",
"(",
"(",
"height",
"-",
"self",
".",
"_bookmarkPixmap",
".",
"height",
"(",
")",
")",
"/",
"2",
")",
"# centered",
"painter",
".",
"drawPixmap",
"(",
"0",
",",
"yPos",
",",
"self",
".",
"_bookmarkPixmap",
")",
"top",
"+=",
"height"
] | QWidget.paintEvent() implementation
Draw markers | [
"QWidget",
".",
"paintEvent",
"()",
"implementation",
"Draw",
"markers"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/sideareas.py#L124-L152 |
andreikop/qutepart | qutepart/completer.py | _GlobalUpdateWordSetTimer.cancel | def cancel(self, method):
"""Cancel scheduled method
Safe method, may be called with not-scheduled method"""
if method in self._scheduledMethods:
self._scheduledMethods.remove(method)
if not self._scheduledMethods:
self._timer.stop() | python | def cancel(self, method):
"""Cancel scheduled method
Safe method, may be called with not-scheduled method"""
if method in self._scheduledMethods:
self._scheduledMethods.remove(method)
if not self._scheduledMethods:
self._timer.stop() | [
"def",
"cancel",
"(",
"self",
",",
"method",
")",
":",
"if",
"method",
"in",
"self",
".",
"_scheduledMethods",
":",
"self",
".",
"_scheduledMethods",
".",
"remove",
"(",
"method",
")",
"if",
"not",
"self",
".",
"_scheduledMethods",
":",
"self",
".",
"_timer",
".",
"stop",
"(",
")"
] | Cancel scheduled method
Safe method, may be called with not-scheduled method | [
"Cancel",
"scheduled",
"method",
"Safe",
"method",
"may",
"be",
"called",
"with",
"not",
"-",
"scheduled",
"method"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L42-L49 |
andreikop/qutepart | qutepart/completer.py | _CompletionModel.setData | def setData(self, wordBeforeCursor, wholeWord):
"""Set model information
"""
self._typedText = wordBeforeCursor
self.words = self._makeListOfCompletions(wordBeforeCursor, wholeWord)
commonStart = self._commonWordStart(self.words)
self.canCompleteText = commonStart[len(wordBeforeCursor):]
self.layoutChanged.emit() | python | def setData(self, wordBeforeCursor, wholeWord):
"""Set model information
"""
self._typedText = wordBeforeCursor
self.words = self._makeListOfCompletions(wordBeforeCursor, wholeWord)
commonStart = self._commonWordStart(self.words)
self.canCompleteText = commonStart[len(wordBeforeCursor):]
self.layoutChanged.emit() | [
"def",
"setData",
"(",
"self",
",",
"wordBeforeCursor",
",",
"wholeWord",
")",
":",
"self",
".",
"_typedText",
"=",
"wordBeforeCursor",
"self",
".",
"words",
"=",
"self",
".",
"_makeListOfCompletions",
"(",
"wordBeforeCursor",
",",
"wholeWord",
")",
"commonStart",
"=",
"self",
".",
"_commonWordStart",
"(",
"self",
".",
"words",
")",
"self",
".",
"canCompleteText",
"=",
"commonStart",
"[",
"len",
"(",
"wordBeforeCursor",
")",
":",
"]",
"self",
".",
"layoutChanged",
".",
"emit",
"(",
")"
] | Set model information | [
"Set",
"model",
"information"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L69-L77 |
andreikop/qutepart | qutepart/completer.py | _CompletionModel.data | def data(self, index, role):
"""QAbstractItemModel method implementation
"""
if role == Qt.DisplayRole and \
index.row() < len(self.words):
text = self.words[index.row()]
typed = text[:len(self._typedText)]
canComplete = text[len(self._typedText):len(self._typedText) + len(self.canCompleteText)]
rest = text[len(self._typedText) + len(self.canCompleteText):]
if canComplete:
# NOTE foreground colors are hardcoded, but I can't set background color of selected item (Qt bug?)
# might look bad on some color themes
return '<html>' \
'%s' \
'<font color="#e80000">%s</font>' \
'%s' \
'</html>' % (typed, canComplete, rest)
else:
return typed + rest
else:
return None | python | def data(self, index, role):
"""QAbstractItemModel method implementation
"""
if role == Qt.DisplayRole and \
index.row() < len(self.words):
text = self.words[index.row()]
typed = text[:len(self._typedText)]
canComplete = text[len(self._typedText):len(self._typedText) + len(self.canCompleteText)]
rest = text[len(self._typedText) + len(self.canCompleteText):]
if canComplete:
# NOTE foreground colors are hardcoded, but I can't set background color of selected item (Qt bug?)
# might look bad on some color themes
return '<html>' \
'%s' \
'<font color="#e80000">%s</font>' \
'%s' \
'</html>' % (typed, canComplete, rest)
else:
return typed + rest
else:
return None | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
")",
":",
"if",
"role",
"==",
"Qt",
".",
"DisplayRole",
"and",
"index",
".",
"row",
"(",
")",
"<",
"len",
"(",
"self",
".",
"words",
")",
":",
"text",
"=",
"self",
".",
"words",
"[",
"index",
".",
"row",
"(",
")",
"]",
"typed",
"=",
"text",
"[",
":",
"len",
"(",
"self",
".",
"_typedText",
")",
"]",
"canComplete",
"=",
"text",
"[",
"len",
"(",
"self",
".",
"_typedText",
")",
":",
"len",
"(",
"self",
".",
"_typedText",
")",
"+",
"len",
"(",
"self",
".",
"canCompleteText",
")",
"]",
"rest",
"=",
"text",
"[",
"len",
"(",
"self",
".",
"_typedText",
")",
"+",
"len",
"(",
"self",
".",
"canCompleteText",
")",
":",
"]",
"if",
"canComplete",
":",
"# NOTE foreground colors are hardcoded, but I can't set background color of selected item (Qt bug?)",
"# might look bad on some color themes",
"return",
"'<html>'",
"'%s'",
"'<font color=\"#e80000\">%s</font>'",
"'%s'",
"'</html>'",
"%",
"(",
"typed",
",",
"canComplete",
",",
"rest",
")",
"else",
":",
"return",
"typed",
"+",
"rest",
"else",
":",
"return",
"None"
] | QAbstractItemModel method implementation | [
"QAbstractItemModel",
"method",
"implementation"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L85-L105 |
andreikop/qutepart | qutepart/completer.py | _CompletionModel._commonWordStart | def _commonWordStart(self, words):
"""Get common start of all words.
i.e. for ['blablaxxx', 'blablayyy', 'blazzz'] common start is 'bla'
"""
if not words:
return ''
length = 0
firstWord = words[0]
otherWords = words[1:]
for index, char in enumerate(firstWord):
if not all([word[index] == char for word in otherWords]):
break
length = index + 1
return firstWord[:length] | python | def _commonWordStart(self, words):
"""Get common start of all words.
i.e. for ['blablaxxx', 'blablayyy', 'blazzz'] common start is 'bla'
"""
if not words:
return ''
length = 0
firstWord = words[0]
otherWords = words[1:]
for index, char in enumerate(firstWord):
if not all([word[index] == char for word in otherWords]):
break
length = index + 1
return firstWord[:length] | [
"def",
"_commonWordStart",
"(",
"self",
",",
"words",
")",
":",
"if",
"not",
"words",
":",
"return",
"''",
"length",
"=",
"0",
"firstWord",
"=",
"words",
"[",
"0",
"]",
"otherWords",
"=",
"words",
"[",
"1",
":",
"]",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"firstWord",
")",
":",
"if",
"not",
"all",
"(",
"[",
"word",
"[",
"index",
"]",
"==",
"char",
"for",
"word",
"in",
"otherWords",
"]",
")",
":",
"break",
"length",
"=",
"index",
"+",
"1",
"return",
"firstWord",
"[",
":",
"length",
"]"
] | Get common start of all words.
i.e. for ['blablaxxx', 'blablayyy', 'blazzz'] common start is 'bla' | [
"Get",
"common",
"start",
"of",
"all",
"words",
".",
"i",
".",
"e",
".",
"for",
"[",
"blablaxxx",
"blablayyy",
"blazzz",
"]",
"common",
"start",
"is",
"bla"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L117-L132 |
andreikop/qutepart | qutepart/completer.py | _CompletionModel._makeListOfCompletions | def _makeListOfCompletions(self, wordBeforeCursor, wholeWord):
"""Make list of completions, which shall be shown
"""
onlySuitable = [word for word in self._wordSet \
if word.startswith(wordBeforeCursor) and \
word != wholeWord]
return sorted(onlySuitable) | python | def _makeListOfCompletions(self, wordBeforeCursor, wholeWord):
"""Make list of completions, which shall be shown
"""
onlySuitable = [word for word in self._wordSet \
if word.startswith(wordBeforeCursor) and \
word != wholeWord]
return sorted(onlySuitable) | [
"def",
"_makeListOfCompletions",
"(",
"self",
",",
"wordBeforeCursor",
",",
"wholeWord",
")",
":",
"onlySuitable",
"=",
"[",
"word",
"for",
"word",
"in",
"self",
".",
"_wordSet",
"if",
"word",
".",
"startswith",
"(",
"wordBeforeCursor",
")",
"and",
"word",
"!=",
"wholeWord",
"]",
"return",
"sorted",
"(",
"onlySuitable",
")"
] | Make list of completions, which shall be shown | [
"Make",
"list",
"of",
"completions",
"which",
"shall",
"be",
"shown"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L134-L141 |
andreikop/qutepart | qutepart/completer.py | _CompletionList.close | def close(self):
"""Explicitly called destructor.
Removes widget from the qpart
"""
self._closeIfNotUpdatedTimer.stop()
self._qpart.removeEventFilter(self)
self._qpart.cursorPositionChanged.disconnect(self._onCursorPositionChanged)
QListView.close(self) | python | def close(self):
"""Explicitly called destructor.
Removes widget from the qpart
"""
self._closeIfNotUpdatedTimer.stop()
self._qpart.removeEventFilter(self)
self._qpart.cursorPositionChanged.disconnect(self._onCursorPositionChanged)
QListView.close(self) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_closeIfNotUpdatedTimer",
".",
"stop",
"(",
")",
"self",
".",
"_qpart",
".",
"removeEventFilter",
"(",
"self",
")",
"self",
".",
"_qpart",
".",
"cursorPositionChanged",
".",
"disconnect",
"(",
"self",
".",
"_onCursorPositionChanged",
")",
"QListView",
".",
"close",
"(",
"self",
")"
] | Explicitly called destructor.
Removes widget from the qpart | [
"Explicitly",
"called",
"destructor",
".",
"Removes",
"widget",
"from",
"the",
"qpart"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L208-L216 |
andreikop/qutepart | qutepart/completer.py | _CompletionList.sizeHint | def sizeHint(self):
"""QWidget.sizeHint implementation
Automatically resizes the widget according to rows count
FIXME very bad algorithm. Remove all this margins, if you can
"""
width = max([self.fontMetrics().width(word) \
for word in self.model().words])
width = width * 1.4 # FIXME bad hack. invent better formula
width += 30 # margin
# drawn with scrollbar without +2. I don't know why
rowCount = min(self.model().rowCount(), self._MAX_VISIBLE_ROWS)
height = self.sizeHintForRow(0) * (rowCount + 0.5) # + 0.5 row margin
return QSize(width, height) | python | def sizeHint(self):
"""QWidget.sizeHint implementation
Automatically resizes the widget according to rows count
FIXME very bad algorithm. Remove all this margins, if you can
"""
width = max([self.fontMetrics().width(word) \
for word in self.model().words])
width = width * 1.4 # FIXME bad hack. invent better formula
width += 30 # margin
# drawn with scrollbar without +2. I don't know why
rowCount = min(self.model().rowCount(), self._MAX_VISIBLE_ROWS)
height = self.sizeHintForRow(0) * (rowCount + 0.5) # + 0.5 row margin
return QSize(width, height) | [
"def",
"sizeHint",
"(",
"self",
")",
":",
"width",
"=",
"max",
"(",
"[",
"self",
".",
"fontMetrics",
"(",
")",
".",
"width",
"(",
"word",
")",
"for",
"word",
"in",
"self",
".",
"model",
"(",
")",
".",
"words",
"]",
")",
"width",
"=",
"width",
"*",
"1.4",
"# FIXME bad hack. invent better formula",
"width",
"+=",
"30",
"# margin",
"# drawn with scrollbar without +2. I don't know why",
"rowCount",
"=",
"min",
"(",
"self",
".",
"model",
"(",
")",
".",
"rowCount",
"(",
")",
",",
"self",
".",
"_MAX_VISIBLE_ROWS",
")",
"height",
"=",
"self",
".",
"sizeHintForRow",
"(",
"0",
")",
"*",
"(",
"rowCount",
"+",
"0.5",
")",
"# + 0.5 row margin",
"return",
"QSize",
"(",
"width",
",",
"height",
")"
] | QWidget.sizeHint implementation
Automatically resizes the widget according to rows count
FIXME very bad algorithm. Remove all this margins, if you can | [
"QWidget",
".",
"sizeHint",
"implementation",
"Automatically",
"resizes",
"the",
"widget",
"according",
"to",
"rows",
"count"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L218-L233 |
andreikop/qutepart | qutepart/completer.py | _CompletionList._horizontalShift | def _horizontalShift(self):
"""List should be plased such way, that typed text in the list is under
typed text in the editor
"""
strangeAdjustment = 2 # I don't know why. Probably, won't work on other systems and versions
return self.fontMetrics().width(self.model().typedText()) + strangeAdjustment | python | def _horizontalShift(self):
"""List should be plased such way, that typed text in the list is under
typed text in the editor
"""
strangeAdjustment = 2 # I don't know why. Probably, won't work on other systems and versions
return self.fontMetrics().width(self.model().typedText()) + strangeAdjustment | [
"def",
"_horizontalShift",
"(",
"self",
")",
":",
"strangeAdjustment",
"=",
"2",
"# I don't know why. Probably, won't work on other systems and versions",
"return",
"self",
".",
"fontMetrics",
"(",
")",
".",
"width",
"(",
"self",
".",
"model",
"(",
")",
".",
"typedText",
"(",
")",
")",
"+",
"strangeAdjustment"
] | List should be plased such way, that typed text in the list is under
typed text in the editor | [
"List",
"should",
"be",
"plased",
"such",
"way",
"that",
"typed",
"text",
"in",
"the",
"list",
"is",
"under",
"typed",
"text",
"in",
"the",
"editor"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L240-L245 |
andreikop/qutepart | qutepart/completer.py | _CompletionList.updateGeometry | def updateGeometry(self):
"""Move widget to point under cursor
"""
WIDGET_BORDER_MARGIN = 5
SCROLLBAR_WIDTH = 30 # just a guess
sizeHint = self.sizeHint()
width = sizeHint.width()
height = sizeHint.height()
cursorRect = self._qpart.cursorRect()
parentSize = self.parentWidget().size()
spaceBelow = parentSize.height() - cursorRect.bottom() - WIDGET_BORDER_MARGIN
spaceAbove = cursorRect.top() - WIDGET_BORDER_MARGIN
if height <= spaceBelow or \
spaceBelow > spaceAbove:
yPos = cursorRect.bottom()
if height > spaceBelow and \
spaceBelow > self.minimumHeight():
height = spaceBelow
width = width + SCROLLBAR_WIDTH
else:
if height > spaceAbove and \
spaceAbove > self.minimumHeight():
height = spaceAbove
width = width + SCROLLBAR_WIDTH
yPos = max(3, cursorRect.top() - height)
xPos = cursorRect.right() - self._horizontalShift()
if xPos + width + WIDGET_BORDER_MARGIN > parentSize.width():
xPos = max(3, parentSize.width() - WIDGET_BORDER_MARGIN - width)
self.setGeometry(xPos, yPos, width, height)
self._closeIfNotUpdatedTimer.stop() | python | def updateGeometry(self):
"""Move widget to point under cursor
"""
WIDGET_BORDER_MARGIN = 5
SCROLLBAR_WIDTH = 30 # just a guess
sizeHint = self.sizeHint()
width = sizeHint.width()
height = sizeHint.height()
cursorRect = self._qpart.cursorRect()
parentSize = self.parentWidget().size()
spaceBelow = parentSize.height() - cursorRect.bottom() - WIDGET_BORDER_MARGIN
spaceAbove = cursorRect.top() - WIDGET_BORDER_MARGIN
if height <= spaceBelow or \
spaceBelow > spaceAbove:
yPos = cursorRect.bottom()
if height > spaceBelow and \
spaceBelow > self.minimumHeight():
height = spaceBelow
width = width + SCROLLBAR_WIDTH
else:
if height > spaceAbove and \
spaceAbove > self.minimumHeight():
height = spaceAbove
width = width + SCROLLBAR_WIDTH
yPos = max(3, cursorRect.top() - height)
xPos = cursorRect.right() - self._horizontalShift()
if xPos + width + WIDGET_BORDER_MARGIN > parentSize.width():
xPos = max(3, parentSize.width() - WIDGET_BORDER_MARGIN - width)
self.setGeometry(xPos, yPos, width, height)
self._closeIfNotUpdatedTimer.stop() | [
"def",
"updateGeometry",
"(",
"self",
")",
":",
"WIDGET_BORDER_MARGIN",
"=",
"5",
"SCROLLBAR_WIDTH",
"=",
"30",
"# just a guess",
"sizeHint",
"=",
"self",
".",
"sizeHint",
"(",
")",
"width",
"=",
"sizeHint",
".",
"width",
"(",
")",
"height",
"=",
"sizeHint",
".",
"height",
"(",
")",
"cursorRect",
"=",
"self",
".",
"_qpart",
".",
"cursorRect",
"(",
")",
"parentSize",
"=",
"self",
".",
"parentWidget",
"(",
")",
".",
"size",
"(",
")",
"spaceBelow",
"=",
"parentSize",
".",
"height",
"(",
")",
"-",
"cursorRect",
".",
"bottom",
"(",
")",
"-",
"WIDGET_BORDER_MARGIN",
"spaceAbove",
"=",
"cursorRect",
".",
"top",
"(",
")",
"-",
"WIDGET_BORDER_MARGIN",
"if",
"height",
"<=",
"spaceBelow",
"or",
"spaceBelow",
">",
"spaceAbove",
":",
"yPos",
"=",
"cursorRect",
".",
"bottom",
"(",
")",
"if",
"height",
">",
"spaceBelow",
"and",
"spaceBelow",
">",
"self",
".",
"minimumHeight",
"(",
")",
":",
"height",
"=",
"spaceBelow",
"width",
"=",
"width",
"+",
"SCROLLBAR_WIDTH",
"else",
":",
"if",
"height",
">",
"spaceAbove",
"and",
"spaceAbove",
">",
"self",
".",
"minimumHeight",
"(",
")",
":",
"height",
"=",
"spaceAbove",
"width",
"=",
"width",
"+",
"SCROLLBAR_WIDTH",
"yPos",
"=",
"max",
"(",
"3",
",",
"cursorRect",
".",
"top",
"(",
")",
"-",
"height",
")",
"xPos",
"=",
"cursorRect",
".",
"right",
"(",
")",
"-",
"self",
".",
"_horizontalShift",
"(",
")",
"if",
"xPos",
"+",
"width",
"+",
"WIDGET_BORDER_MARGIN",
">",
"parentSize",
".",
"width",
"(",
")",
":",
"xPos",
"=",
"max",
"(",
"3",
",",
"parentSize",
".",
"width",
"(",
")",
"-",
"WIDGET_BORDER_MARGIN",
"-",
"width",
")",
"self",
".",
"setGeometry",
"(",
"xPos",
",",
"yPos",
",",
"width",
",",
"height",
")",
"self",
".",
"_closeIfNotUpdatedTimer",
".",
"stop",
"(",
")"
] | Move widget to point under cursor | [
"Move",
"widget",
"to",
"point",
"under",
"cursor"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L247-L283 |
andreikop/qutepart | qutepart/completer.py | _CompletionList.eventFilter | def eventFilter(self, object, event):
"""Catch events from qpart
Move selection, select item, or close themselves
"""
if event.type() == QEvent.KeyPress and event.modifiers() == Qt.NoModifier:
if event.key() == Qt.Key_Escape:
self.closeMe.emit()
return True
elif event.key() == Qt.Key_Down:
if self._selectedIndex + 1 < self.model().rowCount():
self._selectItem(self._selectedIndex + 1)
return True
elif event.key() == Qt.Key_Up:
if self._selectedIndex - 1 >= 0:
self._selectItem(self._selectedIndex - 1)
return True
elif event.key() in (Qt.Key_Enter, Qt.Key_Return):
if self._selectedIndex != -1:
self.itemSelected.emit(self._selectedIndex)
return True
elif event.key() == Qt.Key_Tab:
self.tabPressed.emit()
return True
elif event.type() == QEvent.FocusOut:
self.closeMe.emit()
return False | python | def eventFilter(self, object, event):
"""Catch events from qpart
Move selection, select item, or close themselves
"""
if event.type() == QEvent.KeyPress and event.modifiers() == Qt.NoModifier:
if event.key() == Qt.Key_Escape:
self.closeMe.emit()
return True
elif event.key() == Qt.Key_Down:
if self._selectedIndex + 1 < self.model().rowCount():
self._selectItem(self._selectedIndex + 1)
return True
elif event.key() == Qt.Key_Up:
if self._selectedIndex - 1 >= 0:
self._selectItem(self._selectedIndex - 1)
return True
elif event.key() in (Qt.Key_Enter, Qt.Key_Return):
if self._selectedIndex != -1:
self.itemSelected.emit(self._selectedIndex)
return True
elif event.key() == Qt.Key_Tab:
self.tabPressed.emit()
return True
elif event.type() == QEvent.FocusOut:
self.closeMe.emit()
return False | [
"def",
"eventFilter",
"(",
"self",
",",
"object",
",",
"event",
")",
":",
"if",
"event",
".",
"type",
"(",
")",
"==",
"QEvent",
".",
"KeyPress",
"and",
"event",
".",
"modifiers",
"(",
")",
"==",
"Qt",
".",
"NoModifier",
":",
"if",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Escape",
":",
"self",
".",
"closeMe",
".",
"emit",
"(",
")",
"return",
"True",
"elif",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Down",
":",
"if",
"self",
".",
"_selectedIndex",
"+",
"1",
"<",
"self",
".",
"model",
"(",
")",
".",
"rowCount",
"(",
")",
":",
"self",
".",
"_selectItem",
"(",
"self",
".",
"_selectedIndex",
"+",
"1",
")",
"return",
"True",
"elif",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Up",
":",
"if",
"self",
".",
"_selectedIndex",
"-",
"1",
">=",
"0",
":",
"self",
".",
"_selectItem",
"(",
"self",
".",
"_selectedIndex",
"-",
"1",
")",
"return",
"True",
"elif",
"event",
".",
"key",
"(",
")",
"in",
"(",
"Qt",
".",
"Key_Enter",
",",
"Qt",
".",
"Key_Return",
")",
":",
"if",
"self",
".",
"_selectedIndex",
"!=",
"-",
"1",
":",
"self",
".",
"itemSelected",
".",
"emit",
"(",
"self",
".",
"_selectedIndex",
")",
"return",
"True",
"elif",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Tab",
":",
"self",
".",
"tabPressed",
".",
"emit",
"(",
")",
"return",
"True",
"elif",
"event",
".",
"type",
"(",
")",
"==",
"QEvent",
".",
"FocusOut",
":",
"self",
".",
"closeMe",
".",
"emit",
"(",
")",
"return",
"False"
] | Catch events from qpart
Move selection, select item, or close themselves | [
"Catch",
"events",
"from",
"qpart",
"Move",
"selection",
"select",
"item",
"or",
"close",
"themselves"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L296-L322 |
andreikop/qutepart | qutepart/completer.py | _CompletionList._selectItem | def _selectItem(self, index):
"""Select item in the list
"""
self._selectedIndex = index
self.setCurrentIndex(self.model().createIndex(index, 0)) | python | def _selectItem(self, index):
"""Select item in the list
"""
self._selectedIndex = index
self.setCurrentIndex(self.model().createIndex(index, 0)) | [
"def",
"_selectItem",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"_selectedIndex",
"=",
"index",
"self",
".",
"setCurrentIndex",
"(",
"self",
".",
"model",
"(",
")",
".",
"createIndex",
"(",
"index",
",",
"0",
")",
")"
] | Select item in the list | [
"Select",
"item",
"in",
"the",
"list"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L324-L328 |
andreikop/qutepart | qutepart/completer.py | Completer._updateWordSet | def _updateWordSet(self):
"""Make a set of words, which shall be completed, from text
"""
self._wordSet = set(self._keywords) | set(self._customCompletions)
start = time.time()
for line in self._qpart.lines:
for match in _wordRegExp.findall(line):
self._wordSet.add(match)
if time.time() - start > self._WORD_SET_UPDATE_MAX_TIME_SEC:
"""It is better to have incomplete word set, than to freeze the GUI"""
break | python | def _updateWordSet(self):
"""Make a set of words, which shall be completed, from text
"""
self._wordSet = set(self._keywords) | set(self._customCompletions)
start = time.time()
for line in self._qpart.lines:
for match in _wordRegExp.findall(line):
self._wordSet.add(match)
if time.time() - start > self._WORD_SET_UPDATE_MAX_TIME_SEC:
"""It is better to have incomplete word set, than to freeze the GUI"""
break | [
"def",
"_updateWordSet",
"(",
"self",
")",
":",
"self",
".",
"_wordSet",
"=",
"set",
"(",
"self",
".",
"_keywords",
")",
"|",
"set",
"(",
"self",
".",
"_customCompletions",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"line",
"in",
"self",
".",
"_qpart",
".",
"lines",
":",
"for",
"match",
"in",
"_wordRegExp",
".",
"findall",
"(",
"line",
")",
":",
"self",
".",
"_wordSet",
".",
"add",
"(",
"match",
")",
"if",
"time",
".",
"time",
"(",
")",
"-",
"start",
">",
"self",
".",
"_WORD_SET_UPDATE_MAX_TIME_SEC",
":",
"\"\"\"It is better to have incomplete word set, than to freeze the GUI\"\"\"",
"break"
] | Make a set of words, which shall be completed, from text | [
"Make",
"a",
"set",
"of",
"words",
"which",
"shall",
"be",
"completed",
"from",
"text"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L375-L387 |
andreikop/qutepart | qutepart/completer.py | Completer.invokeCompletionIfAvailable | def invokeCompletionIfAvailable(self, requestedByUser=False):
"""Invoke completion, if available. Called after text has been typed in qpart
Returns True, if invoked
"""
if self._qpart.completionEnabled and self._wordSet is not None:
wordBeforeCursor = self._wordBeforeCursor()
wholeWord = wordBeforeCursor + self._wordAfterCursor()
forceShow = requestedByUser or self._completionOpenedManually
if wordBeforeCursor:
if len(wordBeforeCursor) >= self._qpart.completionThreshold or forceShow:
if self._widget is None:
model = _CompletionModel(self._wordSet)
model.setData(wordBeforeCursor, wholeWord)
if self._shouldShowModel(model, forceShow):
self._createWidget(model)
return True
else:
self._widget.model().setData(wordBeforeCursor, wholeWord)
if self._shouldShowModel(self._widget.model(), forceShow):
self._widget.updateGeometry()
return True
self._closeCompletion()
return False | python | def invokeCompletionIfAvailable(self, requestedByUser=False):
"""Invoke completion, if available. Called after text has been typed in qpart
Returns True, if invoked
"""
if self._qpart.completionEnabled and self._wordSet is not None:
wordBeforeCursor = self._wordBeforeCursor()
wholeWord = wordBeforeCursor + self._wordAfterCursor()
forceShow = requestedByUser or self._completionOpenedManually
if wordBeforeCursor:
if len(wordBeforeCursor) >= self._qpart.completionThreshold or forceShow:
if self._widget is None:
model = _CompletionModel(self._wordSet)
model.setData(wordBeforeCursor, wholeWord)
if self._shouldShowModel(model, forceShow):
self._createWidget(model)
return True
else:
self._widget.model().setData(wordBeforeCursor, wholeWord)
if self._shouldShowModel(self._widget.model(), forceShow):
self._widget.updateGeometry()
return True
self._closeCompletion()
return False | [
"def",
"invokeCompletionIfAvailable",
"(",
"self",
",",
"requestedByUser",
"=",
"False",
")",
":",
"if",
"self",
".",
"_qpart",
".",
"completionEnabled",
"and",
"self",
".",
"_wordSet",
"is",
"not",
"None",
":",
"wordBeforeCursor",
"=",
"self",
".",
"_wordBeforeCursor",
"(",
")",
"wholeWord",
"=",
"wordBeforeCursor",
"+",
"self",
".",
"_wordAfterCursor",
"(",
")",
"forceShow",
"=",
"requestedByUser",
"or",
"self",
".",
"_completionOpenedManually",
"if",
"wordBeforeCursor",
":",
"if",
"len",
"(",
"wordBeforeCursor",
")",
">=",
"self",
".",
"_qpart",
".",
"completionThreshold",
"or",
"forceShow",
":",
"if",
"self",
".",
"_widget",
"is",
"None",
":",
"model",
"=",
"_CompletionModel",
"(",
"self",
".",
"_wordSet",
")",
"model",
".",
"setData",
"(",
"wordBeforeCursor",
",",
"wholeWord",
")",
"if",
"self",
".",
"_shouldShowModel",
"(",
"model",
",",
"forceShow",
")",
":",
"self",
".",
"_createWidget",
"(",
"model",
")",
"return",
"True",
"else",
":",
"self",
".",
"_widget",
".",
"model",
"(",
")",
".",
"setData",
"(",
"wordBeforeCursor",
",",
"wholeWord",
")",
"if",
"self",
".",
"_shouldShowModel",
"(",
"self",
".",
"_widget",
".",
"model",
"(",
")",
",",
"forceShow",
")",
":",
"self",
".",
"_widget",
".",
"updateGeometry",
"(",
")",
"return",
"True",
"self",
".",
"_closeCompletion",
"(",
")",
"return",
"False"
] | Invoke completion, if available. Called after text has been typed in qpart
Returns True, if invoked | [
"Invoke",
"completion",
"if",
"available",
".",
"Called",
"after",
"text",
"has",
"been",
"typed",
"in",
"qpart",
"Returns",
"True",
"if",
"invoked"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L408-L433 |
andreikop/qutepart | qutepart/completer.py | Completer._closeCompletion | def _closeCompletion(self):
"""Close completion, if visible.
Delete widget
"""
if self._widget is not None:
self._widget.close()
self._widget = None
self._completionOpenedManually = False | python | def _closeCompletion(self):
"""Close completion, if visible.
Delete widget
"""
if self._widget is not None:
self._widget.close()
self._widget = None
self._completionOpenedManually = False | [
"def",
"_closeCompletion",
"(",
"self",
")",
":",
"if",
"self",
".",
"_widget",
"is",
"not",
"None",
":",
"self",
".",
"_widget",
".",
"close",
"(",
")",
"self",
".",
"_widget",
"=",
"None",
"self",
".",
"_completionOpenedManually",
"=",
"False"
] | Close completion, if visible.
Delete widget | [
"Close",
"completion",
"if",
"visible",
".",
"Delete",
"widget"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L435-L442 |
andreikop/qutepart | qutepart/completer.py | Completer._wordBeforeCursor | def _wordBeforeCursor(self):
"""Get word, which is located before cursor
"""
cursor = self._qpart.textCursor()
textBeforeCursor = cursor.block().text()[:cursor.positionInBlock()]
match = _wordAtEndRegExp.search(textBeforeCursor)
if match:
return match.group(0)
else:
return '' | python | def _wordBeforeCursor(self):
"""Get word, which is located before cursor
"""
cursor = self._qpart.textCursor()
textBeforeCursor = cursor.block().text()[:cursor.positionInBlock()]
match = _wordAtEndRegExp.search(textBeforeCursor)
if match:
return match.group(0)
else:
return '' | [
"def",
"_wordBeforeCursor",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_qpart",
".",
"textCursor",
"(",
")",
"textBeforeCursor",
"=",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"[",
":",
"cursor",
".",
"positionInBlock",
"(",
")",
"]",
"match",
"=",
"_wordAtEndRegExp",
".",
"search",
"(",
"textBeforeCursor",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"0",
")",
"else",
":",
"return",
"''"
] | Get word, which is located before cursor | [
"Get",
"word",
"which",
"is",
"located",
"before",
"cursor"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L444-L453 |
andreikop/qutepart | qutepart/completer.py | Completer._wordAfterCursor | def _wordAfterCursor(self):
"""Get word, which is located before cursor
"""
cursor = self._qpart.textCursor()
textAfterCursor = cursor.block().text()[cursor.positionInBlock():]
match = _wordAtStartRegExp.search(textAfterCursor)
if match:
return match.group(0)
else:
return '' | python | def _wordAfterCursor(self):
"""Get word, which is located before cursor
"""
cursor = self._qpart.textCursor()
textAfterCursor = cursor.block().text()[cursor.positionInBlock():]
match = _wordAtStartRegExp.search(textAfterCursor)
if match:
return match.group(0)
else:
return '' | [
"def",
"_wordAfterCursor",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_qpart",
".",
"textCursor",
"(",
")",
"textAfterCursor",
"=",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"[",
"cursor",
".",
"positionInBlock",
"(",
")",
":",
"]",
"match",
"=",
"_wordAtStartRegExp",
".",
"search",
"(",
"textAfterCursor",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"0",
")",
"else",
":",
"return",
"''"
] | Get word, which is located before cursor | [
"Get",
"word",
"which",
"is",
"located",
"before",
"cursor"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L455-L464 |
andreikop/qutepart | qutepart/completer.py | Completer._onCompletionListItemSelected | def _onCompletionListItemSelected(self, index):
"""Item selected. Insert completion to editor
"""
model = self._widget.model()
selectedWord = model.words[index]
textToInsert = selectedWord[len(model.typedText()):]
self._qpart.textCursor().insertText(textToInsert)
self._closeCompletion() | python | def _onCompletionListItemSelected(self, index):
"""Item selected. Insert completion to editor
"""
model = self._widget.model()
selectedWord = model.words[index]
textToInsert = selectedWord[len(model.typedText()):]
self._qpart.textCursor().insertText(textToInsert)
self._closeCompletion() | [
"def",
"_onCompletionListItemSelected",
"(",
"self",
",",
"index",
")",
":",
"model",
"=",
"self",
".",
"_widget",
".",
"model",
"(",
")",
"selectedWord",
"=",
"model",
".",
"words",
"[",
"index",
"]",
"textToInsert",
"=",
"selectedWord",
"[",
"len",
"(",
"model",
".",
"typedText",
"(",
")",
")",
":",
"]",
"self",
".",
"_qpart",
".",
"textCursor",
"(",
")",
".",
"insertText",
"(",
"textToInsert",
")",
"self",
".",
"_closeCompletion",
"(",
")"
] | Item selected. Insert completion to editor | [
"Item",
"selected",
".",
"Insert",
"completion",
"to",
"editor"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L466-L473 |
andreikop/qutepart | qutepart/completer.py | Completer._onCompletionListTabPressed | def _onCompletionListTabPressed(self):
"""Tab pressed on completion list
Insert completable text, if available
"""
canCompleteText = self._widget.model().canCompleteText
if canCompleteText:
self._qpart.textCursor().insertText(canCompleteText)
self.invokeCompletionIfAvailable() | python | def _onCompletionListTabPressed(self):
"""Tab pressed on completion list
Insert completable text, if available
"""
canCompleteText = self._widget.model().canCompleteText
if canCompleteText:
self._qpart.textCursor().insertText(canCompleteText)
self.invokeCompletionIfAvailable() | [
"def",
"_onCompletionListTabPressed",
"(",
"self",
")",
":",
"canCompleteText",
"=",
"self",
".",
"_widget",
".",
"model",
"(",
")",
".",
"canCompleteText",
"if",
"canCompleteText",
":",
"self",
".",
"_qpart",
".",
"textCursor",
"(",
")",
".",
"insertText",
"(",
"canCompleteText",
")",
"self",
".",
"invokeCompletionIfAvailable",
"(",
")"
] | Tab pressed on completion list
Insert completable text, if available | [
"Tab",
"pressed",
"on",
"completion",
"list",
"Insert",
"completable",
"text",
"if",
"available"
] | train | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/completer.py#L475-L482 |
twidi/django-extended-choices | extended_choices/choices.py | create_choice | def create_choice(klass, choices, subsets, kwargs):
"""Create an instance of a ``Choices`` object.
Parameters
----------
klass : type
The class to use to recreate the object.
choices : list(tuple)
A list of choices as expected by the ``__init__`` method of ``klass``.
subsets : list(tuple)
A tuple with an entry for each subset to create. Each entry is a list with two entries:
- the name of the subsets
- a list of the constants to use for this subset
kwargs : dict
Extra parameters expected on the ``__init__`` method of ``klass``.
Returns
-------
Choices
A new instance of ``Choices`` (or other class defined in ``klass``).
"""
obj = klass(*choices, **kwargs)
for subset in subsets:
obj.add_subset(*subset)
return obj | python | def create_choice(klass, choices, subsets, kwargs):
"""Create an instance of a ``Choices`` object.
Parameters
----------
klass : type
The class to use to recreate the object.
choices : list(tuple)
A list of choices as expected by the ``__init__`` method of ``klass``.
subsets : list(tuple)
A tuple with an entry for each subset to create. Each entry is a list with two entries:
- the name of the subsets
- a list of the constants to use for this subset
kwargs : dict
Extra parameters expected on the ``__init__`` method of ``klass``.
Returns
-------
Choices
A new instance of ``Choices`` (or other class defined in ``klass``).
"""
obj = klass(*choices, **kwargs)
for subset in subsets:
obj.add_subset(*subset)
return obj | [
"def",
"create_choice",
"(",
"klass",
",",
"choices",
",",
"subsets",
",",
"kwargs",
")",
":",
"obj",
"=",
"klass",
"(",
"*",
"choices",
",",
"*",
"*",
"kwargs",
")",
"for",
"subset",
"in",
"subsets",
":",
"obj",
".",
"add_subset",
"(",
"*",
"subset",
")",
"return",
"obj"
] | Create an instance of a ``Choices`` object.
Parameters
----------
klass : type
The class to use to recreate the object.
choices : list(tuple)
A list of choices as expected by the ``__init__`` method of ``klass``.
subsets : list(tuple)
A tuple with an entry for each subset to create. Each entry is a list with two entries:
- the name of the subsets
- a list of the constants to use for this subset
kwargs : dict
Extra parameters expected on the ``__init__`` method of ``klass``.
Returns
-------
Choices
A new instance of ``Choices`` (or other class defined in ``klass``). | [
"Create",
"an",
"instance",
"of",
"a",
"Choices",
"object",
"."
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L1078-L1104 |
twidi/django-extended-choices | extended_choices/choices.py | Choices._convert_choices | def _convert_choices(self, choices):
"""Validate each choices
Parameters
----------
choices : list of tuples
The list of choices to be added
Returns
-------
list
The list of the added constants
"""
# Check that each new constant is unique.
constants = [c[0] for c in choices]
constants_doubles = [c for c in constants if constants.count(c) > 1]
if constants_doubles:
raise ValueError("You cannot declare two constants with the same constant name. "
"Problematic constants: %s " % list(set(constants_doubles)))
# Check that none of the new constants already exists.
bad_constants = set(constants).intersection(self.constants)
if bad_constants:
raise ValueError("You cannot add existing constants. "
"Existing constants: %s." % list(bad_constants))
# Check that none of the constant is an existing attributes
bad_constants = [c for c in constants if hasattr(self, c)]
if bad_constants:
raise ValueError("You cannot add constants that already exists as attributes. "
"Existing attributes: %s." % list(bad_constants))
# Check that each new value is unique.
values = [c[1] for c in choices]
values_doubles = [c for c in values if values.count(c) > 1]
if values_doubles:
raise ValueError("You cannot declare two choices with the same name."
"Problematic values: %s " % list(set(values_doubles)))
# Check that none of the new values already exists.
try:
bad_values = set(values).intersection(self.values)
except TypeError:
raise ValueError("One value cannot be used in: %s" % list(values))
else:
if bad_values:
raise ValueError("You cannot add existing values. "
"Existing values: %s." % list(bad_values))
# We can now add each choice.
for choice_tuple in choices:
# Convert the choice tuple in a ``ChoiceEntry`` instance if it's not already done.
# It allows to share choice entries between a ``Choices`` instance and its subsets.
choice_entry = choice_tuple
if not isinstance(choice_entry, self.ChoiceEntryClass):
choice_entry = self.ChoiceEntryClass(choice_entry)
# Append to the main list the choice as expected by django: (value, display name).
self.append(choice_entry.choice)
# And the ``ChoiceEntry`` instance to our own internal list.
self.entries.append(choice_entry)
# Make the value accessible via an attribute (the constant being its name).
setattr(self, choice_entry.constant, choice_entry.value)
# Fill dicts to access the ``ChoiceEntry`` instance by its constant, value or display..
self.constants[choice_entry.constant] = choice_entry
self.values[choice_entry.value] = choice_entry
self.displays[choice_entry.display] = choice_entry
return constants | python | def _convert_choices(self, choices):
"""Validate each choices
Parameters
----------
choices : list of tuples
The list of choices to be added
Returns
-------
list
The list of the added constants
"""
# Check that each new constant is unique.
constants = [c[0] for c in choices]
constants_doubles = [c for c in constants if constants.count(c) > 1]
if constants_doubles:
raise ValueError("You cannot declare two constants with the same constant name. "
"Problematic constants: %s " % list(set(constants_doubles)))
# Check that none of the new constants already exists.
bad_constants = set(constants).intersection(self.constants)
if bad_constants:
raise ValueError("You cannot add existing constants. "
"Existing constants: %s." % list(bad_constants))
# Check that none of the constant is an existing attributes
bad_constants = [c for c in constants if hasattr(self, c)]
if bad_constants:
raise ValueError("You cannot add constants that already exists as attributes. "
"Existing attributes: %s." % list(bad_constants))
# Check that each new value is unique.
values = [c[1] for c in choices]
values_doubles = [c for c in values if values.count(c) > 1]
if values_doubles:
raise ValueError("You cannot declare two choices with the same name."
"Problematic values: %s " % list(set(values_doubles)))
# Check that none of the new values already exists.
try:
bad_values = set(values).intersection(self.values)
except TypeError:
raise ValueError("One value cannot be used in: %s" % list(values))
else:
if bad_values:
raise ValueError("You cannot add existing values. "
"Existing values: %s." % list(bad_values))
# We can now add each choice.
for choice_tuple in choices:
# Convert the choice tuple in a ``ChoiceEntry`` instance if it's not already done.
# It allows to share choice entries between a ``Choices`` instance and its subsets.
choice_entry = choice_tuple
if not isinstance(choice_entry, self.ChoiceEntryClass):
choice_entry = self.ChoiceEntryClass(choice_entry)
# Append to the main list the choice as expected by django: (value, display name).
self.append(choice_entry.choice)
# And the ``ChoiceEntry`` instance to our own internal list.
self.entries.append(choice_entry)
# Make the value accessible via an attribute (the constant being its name).
setattr(self, choice_entry.constant, choice_entry.value)
# Fill dicts to access the ``ChoiceEntry`` instance by its constant, value or display..
self.constants[choice_entry.constant] = choice_entry
self.values[choice_entry.value] = choice_entry
self.displays[choice_entry.display] = choice_entry
return constants | [
"def",
"_convert_choices",
"(",
"self",
",",
"choices",
")",
":",
"# Check that each new constant is unique.",
"constants",
"=",
"[",
"c",
"[",
"0",
"]",
"for",
"c",
"in",
"choices",
"]",
"constants_doubles",
"=",
"[",
"c",
"for",
"c",
"in",
"constants",
"if",
"constants",
".",
"count",
"(",
"c",
")",
">",
"1",
"]",
"if",
"constants_doubles",
":",
"raise",
"ValueError",
"(",
"\"You cannot declare two constants with the same constant name. \"",
"\"Problematic constants: %s \"",
"%",
"list",
"(",
"set",
"(",
"constants_doubles",
")",
")",
")",
"# Check that none of the new constants already exists.",
"bad_constants",
"=",
"set",
"(",
"constants",
")",
".",
"intersection",
"(",
"self",
".",
"constants",
")",
"if",
"bad_constants",
":",
"raise",
"ValueError",
"(",
"\"You cannot add existing constants. \"",
"\"Existing constants: %s.\"",
"%",
"list",
"(",
"bad_constants",
")",
")",
"# Check that none of the constant is an existing attributes",
"bad_constants",
"=",
"[",
"c",
"for",
"c",
"in",
"constants",
"if",
"hasattr",
"(",
"self",
",",
"c",
")",
"]",
"if",
"bad_constants",
":",
"raise",
"ValueError",
"(",
"\"You cannot add constants that already exists as attributes. \"",
"\"Existing attributes: %s.\"",
"%",
"list",
"(",
"bad_constants",
")",
")",
"# Check that each new value is unique.",
"values",
"=",
"[",
"c",
"[",
"1",
"]",
"for",
"c",
"in",
"choices",
"]",
"values_doubles",
"=",
"[",
"c",
"for",
"c",
"in",
"values",
"if",
"values",
".",
"count",
"(",
"c",
")",
">",
"1",
"]",
"if",
"values_doubles",
":",
"raise",
"ValueError",
"(",
"\"You cannot declare two choices with the same name.\"",
"\"Problematic values: %s \"",
"%",
"list",
"(",
"set",
"(",
"values_doubles",
")",
")",
")",
"# Check that none of the new values already exists.",
"try",
":",
"bad_values",
"=",
"set",
"(",
"values",
")",
".",
"intersection",
"(",
"self",
".",
"values",
")",
"except",
"TypeError",
":",
"raise",
"ValueError",
"(",
"\"One value cannot be used in: %s\"",
"%",
"list",
"(",
"values",
")",
")",
"else",
":",
"if",
"bad_values",
":",
"raise",
"ValueError",
"(",
"\"You cannot add existing values. \"",
"\"Existing values: %s.\"",
"%",
"list",
"(",
"bad_values",
")",
")",
"# We can now add each choice.",
"for",
"choice_tuple",
"in",
"choices",
":",
"# Convert the choice tuple in a ``ChoiceEntry`` instance if it's not already done.",
"# It allows to share choice entries between a ``Choices`` instance and its subsets.",
"choice_entry",
"=",
"choice_tuple",
"if",
"not",
"isinstance",
"(",
"choice_entry",
",",
"self",
".",
"ChoiceEntryClass",
")",
":",
"choice_entry",
"=",
"self",
".",
"ChoiceEntryClass",
"(",
"choice_entry",
")",
"# Append to the main list the choice as expected by django: (value, display name).",
"self",
".",
"append",
"(",
"choice_entry",
".",
"choice",
")",
"# And the ``ChoiceEntry`` instance to our own internal list.",
"self",
".",
"entries",
".",
"append",
"(",
"choice_entry",
")",
"# Make the value accessible via an attribute (the constant being its name).",
"setattr",
"(",
"self",
",",
"choice_entry",
".",
"constant",
",",
"choice_entry",
".",
"value",
")",
"# Fill dicts to access the ``ChoiceEntry`` instance by its constant, value or display..",
"self",
".",
"constants",
"[",
"choice_entry",
".",
"constant",
"]",
"=",
"choice_entry",
"self",
".",
"values",
"[",
"choice_entry",
".",
"value",
"]",
"=",
"choice_entry",
"self",
".",
"displays",
"[",
"choice_entry",
".",
"display",
"]",
"=",
"choice_entry",
"return",
"constants"
] | Validate each choices
Parameters
----------
choices : list of tuples
The list of choices to be added
Returns
-------
list
The list of the added constants | [
"Validate",
"each",
"choices"
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L239-L312 |
twidi/django-extended-choices | extended_choices/choices.py | Choices.add_choices | def add_choices(self, *choices, **kwargs):
"""Add some choices to the current ``Choices`` instance.
The given choices will be added to the existing choices.
If a ``name`` attribute is passed, a new subset will be created with all the given
choices.
Note that it's not possible to add new choices to a subset.
Parameters
----------
*choices : list of tuples
It's the list of tuples to add to the ``Choices`` instance, each tuple having three
entries: the constant name, the value, the display name.
A dict could be added as a 4th entry in the tuple to allow setting arbitrary
arguments to the final ``ChoiceEntry`` created for this choice tuple.
If the first entry of ``*choices`` is a string, then it will be used as a name for a
new subset that will contain all the given choices.
**kwargs : dict
name : string
Instead of using the first entry of the ``*choices`` to pass a name of a subset to
create, you can pass it via the ``name`` named argument.
Example
-------
>>> MY_CHOICES = Choices()
>>> MY_CHOICES.add_choices(('ZERO', 0, 'zero'))
>>> MY_CHOICES
[('ZERO', 0, 'zero')]
>>> MY_CHOICES.add_choices('SMALL', ('ONE', 1, 'one'), ('TWO', 2, 'two'))
>>> MY_CHOICES
[('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two')]
>>> MY_CHOICES.SMALL
[('ONE', 1, 'one'), ('TWO', 2, 'two')]
>>> MY_CHOICES.add_choices(('THREE', 3, 'three'), ('FOUR', 4, 'four'), name='BIG')
>>> MY_CHOICES
[('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two'), ('THREE', 3, 'three'), ('FOUR', 4, 'four')]
>>> MY_CHOICES.BIG
[('THREE', 3, 'three'), ('FOUR', 4, 'four')]
Raises
------
RuntimeError
When the ``Choices`` instance is marked as not mutable, which is the case for subsets.
ValueError
* if the subset name is defined as first argument and as named argument.
* if some constants have the same name or the same value.
* if at least one constant or value already exists in the instance.
"""
# It the ``_mutable`` flag is falsy, which is the case for subsets, we refuse to add
# new choices.
if not self._mutable:
raise RuntimeError("This ``Choices`` instance cannot be updated.")
# Check for an optional subset name as the first argument (so the first entry of *choices).
subset_name = None
if choices and isinstance(choices[0], six.string_types) and choices[0] != _NO_SUBSET_NAME_:
subset_name = choices[0]
choices = choices[1:]
# Check for an optional subset name in the named arguments.
if kwargs.get('name', None):
if subset_name:
raise ValueError("The name of the subset cannot be defined as the first "
"argument and also as a named argument")
subset_name = kwargs['name']
constants = self._convert_choices(choices)
# If we have a subset name, create a new subset with all the given constants.
if subset_name:
self.add_subset(subset_name, constants) | python | def add_choices(self, *choices, **kwargs):
"""Add some choices to the current ``Choices`` instance.
The given choices will be added to the existing choices.
If a ``name`` attribute is passed, a new subset will be created with all the given
choices.
Note that it's not possible to add new choices to a subset.
Parameters
----------
*choices : list of tuples
It's the list of tuples to add to the ``Choices`` instance, each tuple having three
entries: the constant name, the value, the display name.
A dict could be added as a 4th entry in the tuple to allow setting arbitrary
arguments to the final ``ChoiceEntry`` created for this choice tuple.
If the first entry of ``*choices`` is a string, then it will be used as a name for a
new subset that will contain all the given choices.
**kwargs : dict
name : string
Instead of using the first entry of the ``*choices`` to pass a name of a subset to
create, you can pass it via the ``name`` named argument.
Example
-------
>>> MY_CHOICES = Choices()
>>> MY_CHOICES.add_choices(('ZERO', 0, 'zero'))
>>> MY_CHOICES
[('ZERO', 0, 'zero')]
>>> MY_CHOICES.add_choices('SMALL', ('ONE', 1, 'one'), ('TWO', 2, 'two'))
>>> MY_CHOICES
[('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two')]
>>> MY_CHOICES.SMALL
[('ONE', 1, 'one'), ('TWO', 2, 'two')]
>>> MY_CHOICES.add_choices(('THREE', 3, 'three'), ('FOUR', 4, 'four'), name='BIG')
>>> MY_CHOICES
[('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two'), ('THREE', 3, 'three'), ('FOUR', 4, 'four')]
>>> MY_CHOICES.BIG
[('THREE', 3, 'three'), ('FOUR', 4, 'four')]
Raises
------
RuntimeError
When the ``Choices`` instance is marked as not mutable, which is the case for subsets.
ValueError
* if the subset name is defined as first argument and as named argument.
* if some constants have the same name or the same value.
* if at least one constant or value already exists in the instance.
"""
# It the ``_mutable`` flag is falsy, which is the case for subsets, we refuse to add
# new choices.
if not self._mutable:
raise RuntimeError("This ``Choices`` instance cannot be updated.")
# Check for an optional subset name as the first argument (so the first entry of *choices).
subset_name = None
if choices and isinstance(choices[0], six.string_types) and choices[0] != _NO_SUBSET_NAME_:
subset_name = choices[0]
choices = choices[1:]
# Check for an optional subset name in the named arguments.
if kwargs.get('name', None):
if subset_name:
raise ValueError("The name of the subset cannot be defined as the first "
"argument and also as a named argument")
subset_name = kwargs['name']
constants = self._convert_choices(choices)
# If we have a subset name, create a new subset with all the given constants.
if subset_name:
self.add_subset(subset_name, constants) | [
"def",
"add_choices",
"(",
"self",
",",
"*",
"choices",
",",
"*",
"*",
"kwargs",
")",
":",
"# It the ``_mutable`` flag is falsy, which is the case for subsets, we refuse to add",
"# new choices.",
"if",
"not",
"self",
".",
"_mutable",
":",
"raise",
"RuntimeError",
"(",
"\"This ``Choices`` instance cannot be updated.\"",
")",
"# Check for an optional subset name as the first argument (so the first entry of *choices).",
"subset_name",
"=",
"None",
"if",
"choices",
"and",
"isinstance",
"(",
"choices",
"[",
"0",
"]",
",",
"six",
".",
"string_types",
")",
"and",
"choices",
"[",
"0",
"]",
"!=",
"_NO_SUBSET_NAME_",
":",
"subset_name",
"=",
"choices",
"[",
"0",
"]",
"choices",
"=",
"choices",
"[",
"1",
":",
"]",
"# Check for an optional subset name in the named arguments.",
"if",
"kwargs",
".",
"get",
"(",
"'name'",
",",
"None",
")",
":",
"if",
"subset_name",
":",
"raise",
"ValueError",
"(",
"\"The name of the subset cannot be defined as the first \"",
"\"argument and also as a named argument\"",
")",
"subset_name",
"=",
"kwargs",
"[",
"'name'",
"]",
"constants",
"=",
"self",
".",
"_convert_choices",
"(",
"choices",
")",
"# If we have a subset name, create a new subset with all the given constants.",
"if",
"subset_name",
":",
"self",
".",
"add_subset",
"(",
"subset_name",
",",
"constants",
")"
] | Add some choices to the current ``Choices`` instance.
The given choices will be added to the existing choices.
If a ``name`` attribute is passed, a new subset will be created with all the given
choices.
Note that it's not possible to add new choices to a subset.
Parameters
----------
*choices : list of tuples
It's the list of tuples to add to the ``Choices`` instance, each tuple having three
entries: the constant name, the value, the display name.
A dict could be added as a 4th entry in the tuple to allow setting arbitrary
arguments to the final ``ChoiceEntry`` created for this choice tuple.
If the first entry of ``*choices`` is a string, then it will be used as a name for a
new subset that will contain all the given choices.
**kwargs : dict
name : string
Instead of using the first entry of the ``*choices`` to pass a name of a subset to
create, you can pass it via the ``name`` named argument.
Example
-------
>>> MY_CHOICES = Choices()
>>> MY_CHOICES.add_choices(('ZERO', 0, 'zero'))
>>> MY_CHOICES
[('ZERO', 0, 'zero')]
>>> MY_CHOICES.add_choices('SMALL', ('ONE', 1, 'one'), ('TWO', 2, 'two'))
>>> MY_CHOICES
[('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two')]
>>> MY_CHOICES.SMALL
[('ONE', 1, 'one'), ('TWO', 2, 'two')]
>>> MY_CHOICES.add_choices(('THREE', 3, 'three'), ('FOUR', 4, 'four'), name='BIG')
>>> MY_CHOICES
[('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two'), ('THREE', 3, 'three'), ('FOUR', 4, 'four')]
>>> MY_CHOICES.BIG
[('THREE', 3, 'three'), ('FOUR', 4, 'four')]
Raises
------
RuntimeError
When the ``Choices`` instance is marked as not mutable, which is the case for subsets.
ValueError
* if the subset name is defined as first argument and as named argument.
* if some constants have the same name or the same value.
* if at least one constant or value already exists in the instance. | [
"Add",
"some",
"choices",
"to",
"the",
"current",
"Choices",
"instance",
"."
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L314-L392 |
twidi/django-extended-choices | extended_choices/choices.py | Choices.extract_subset | def extract_subset(self, *constants):
"""Create a subset of entries
This subset is a new ``Choices`` instance, with only the wanted constants from the
main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``)
Parameters
----------
*constants: list
The constants names of this ``Choices`` object to make available in the subset.
Returns
-------
Choices
The newly created subset, which is a ``Choices`` object
Example
-------
>>> STATES = Choices(
... ('ONLINE', 1, 'Online'),
... ('DRAFT', 2, 'Draft'),
... ('OFFLINE', 3, 'Offline'),
... )
>>> STATES
[('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> subset = STATES.extract_subset('DRAFT', 'OFFLINE')
>>> subset
[('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> subset.DRAFT
2
>>> subset.for_constant('DRAFT') is STATES.for_constant('DRAFT')
True
>>> subset.ONLINE
Traceback (most recent call last):
...
AttributeError: 'Choices' object has no attribute 'ONLINE'
Raises
------
ValueError
If a constant is not defined as a constant in the ``Choices`` instance.
"""
# Ensure that all passed constants exists as such in the list of available constants.
bad_constants = set(constants).difference(self.constants)
if bad_constants:
raise ValueError("All constants in subsets should be in parent choice. "
"Missing constants: %s." % list(bad_constants))
# Keep only entries we asked for.
choice_entries = [self.constants[c] for c in constants]
# Create a new ``Choices`` instance with the limited set of entries, and pass the other
# configuration attributes to share the same behavior as the current ``Choices``.
# Also we set ``mutable`` to False to disable the possibility to add new choices to the
# subset.
subset = self.__class__(
*choice_entries,
**{
'dict_class': self.dict_class,
'mutable': False,
}
)
return subset | python | def extract_subset(self, *constants):
"""Create a subset of entries
This subset is a new ``Choices`` instance, with only the wanted constants from the
main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``)
Parameters
----------
*constants: list
The constants names of this ``Choices`` object to make available in the subset.
Returns
-------
Choices
The newly created subset, which is a ``Choices`` object
Example
-------
>>> STATES = Choices(
... ('ONLINE', 1, 'Online'),
... ('DRAFT', 2, 'Draft'),
... ('OFFLINE', 3, 'Offline'),
... )
>>> STATES
[('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> subset = STATES.extract_subset('DRAFT', 'OFFLINE')
>>> subset
[('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> subset.DRAFT
2
>>> subset.for_constant('DRAFT') is STATES.for_constant('DRAFT')
True
>>> subset.ONLINE
Traceback (most recent call last):
...
AttributeError: 'Choices' object has no attribute 'ONLINE'
Raises
------
ValueError
If a constant is not defined as a constant in the ``Choices`` instance.
"""
# Ensure that all passed constants exists as such in the list of available constants.
bad_constants = set(constants).difference(self.constants)
if bad_constants:
raise ValueError("All constants in subsets should be in parent choice. "
"Missing constants: %s." % list(bad_constants))
# Keep only entries we asked for.
choice_entries = [self.constants[c] for c in constants]
# Create a new ``Choices`` instance with the limited set of entries, and pass the other
# configuration attributes to share the same behavior as the current ``Choices``.
# Also we set ``mutable`` to False to disable the possibility to add new choices to the
# subset.
subset = self.__class__(
*choice_entries,
**{
'dict_class': self.dict_class,
'mutable': False,
}
)
return subset | [
"def",
"extract_subset",
"(",
"self",
",",
"*",
"constants",
")",
":",
"# Ensure that all passed constants exists as such in the list of available constants.",
"bad_constants",
"=",
"set",
"(",
"constants",
")",
".",
"difference",
"(",
"self",
".",
"constants",
")",
"if",
"bad_constants",
":",
"raise",
"ValueError",
"(",
"\"All constants in subsets should be in parent choice. \"",
"\"Missing constants: %s.\"",
"%",
"list",
"(",
"bad_constants",
")",
")",
"# Keep only entries we asked for.",
"choice_entries",
"=",
"[",
"self",
".",
"constants",
"[",
"c",
"]",
"for",
"c",
"in",
"constants",
"]",
"# Create a new ``Choices`` instance with the limited set of entries, and pass the other",
"# configuration attributes to share the same behavior as the current ``Choices``.",
"# Also we set ``mutable`` to False to disable the possibility to add new choices to the",
"# subset.",
"subset",
"=",
"self",
".",
"__class__",
"(",
"*",
"choice_entries",
",",
"*",
"*",
"{",
"'dict_class'",
":",
"self",
".",
"dict_class",
",",
"'mutable'",
":",
"False",
",",
"}",
")",
"return",
"subset"
] | Create a subset of entries
This subset is a new ``Choices`` instance, with only the wanted constants from the
main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``)
Parameters
----------
*constants: list
The constants names of this ``Choices`` object to make available in the subset.
Returns
-------
Choices
The newly created subset, which is a ``Choices`` object
Example
-------
>>> STATES = Choices(
... ('ONLINE', 1, 'Online'),
... ('DRAFT', 2, 'Draft'),
... ('OFFLINE', 3, 'Offline'),
... )
>>> STATES
[('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> subset = STATES.extract_subset('DRAFT', 'OFFLINE')
>>> subset
[('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> subset.DRAFT
2
>>> subset.for_constant('DRAFT') is STATES.for_constant('DRAFT')
True
>>> subset.ONLINE
Traceback (most recent call last):
...
AttributeError: 'Choices' object has no attribute 'ONLINE'
Raises
------
ValueError
If a constant is not defined as a constant in the ``Choices`` instance. | [
"Create",
"a",
"subset",
"of",
"entries"
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L394-L462 |
twidi/django-extended-choices | extended_choices/choices.py | Choices.add_subset | def add_subset(self, name, constants):
"""Add a subset of entries under a defined name.
This allow to defined a "sub choice" if a django field need to not have the whole
choice available.
The sub-choice is a new ``Choices`` instance, with only the wanted the constant from the
main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``)
The sub-choice is accessible from the main ``Choices`` by an attribute having the given
name.
Parameters
----------
name : string
Name of the attribute that will old the new ``Choices`` instance.
constants: list or tuple
List of the constants name of this ``Choices`` object to make available in the subset.
Returns
-------
Choices
The newly created subset, which is a ``Choices`` object
Example
-------
>>> STATES = Choices(
... ('ONLINE', 1, 'Online'),
... ('DRAFT', 2, 'Draft'),
... ('OFFLINE', 3, 'Offline'),
... )
>>> STATES
[('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> STATES.add_subset('NOT_ONLINE', ('DRAFT', 'OFFLINE',))
>>> STATES.NOT_ONLINE
[('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> STATES.NOT_ONLINE.DRAFT
2
>>> STATES.NOT_ONLINE.for_constant('DRAFT') is STATES.for_constant('DRAFT')
True
>>> STATES.NOT_ONLINE.ONLINE
Traceback (most recent call last):
...
AttributeError: 'Choices' object has no attribute 'ONLINE'
Raises
------
ValueError
* If ``name`` is already an attribute of the ``Choices`` instance.
* If a constant is not defined as a constant in the ``Choices`` instance.
"""
# Ensure that the name is not already used as an attribute.
if hasattr(self, name):
raise ValueError("Cannot use '%s' as a subset name. "
"It's already an attribute." % name)
subset = self.extract_subset(*constants)
# Make the subset accessible via an attribute.
setattr(self, name, subset)
self.subsets.append(name) | python | def add_subset(self, name, constants):
"""Add a subset of entries under a defined name.
This allow to defined a "sub choice" if a django field need to not have the whole
choice available.
The sub-choice is a new ``Choices`` instance, with only the wanted the constant from the
main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``)
The sub-choice is accessible from the main ``Choices`` by an attribute having the given
name.
Parameters
----------
name : string
Name of the attribute that will old the new ``Choices`` instance.
constants: list or tuple
List of the constants name of this ``Choices`` object to make available in the subset.
Returns
-------
Choices
The newly created subset, which is a ``Choices`` object
Example
-------
>>> STATES = Choices(
... ('ONLINE', 1, 'Online'),
... ('DRAFT', 2, 'Draft'),
... ('OFFLINE', 3, 'Offline'),
... )
>>> STATES
[('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> STATES.add_subset('NOT_ONLINE', ('DRAFT', 'OFFLINE',))
>>> STATES.NOT_ONLINE
[('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> STATES.NOT_ONLINE.DRAFT
2
>>> STATES.NOT_ONLINE.for_constant('DRAFT') is STATES.for_constant('DRAFT')
True
>>> STATES.NOT_ONLINE.ONLINE
Traceback (most recent call last):
...
AttributeError: 'Choices' object has no attribute 'ONLINE'
Raises
------
ValueError
* If ``name`` is already an attribute of the ``Choices`` instance.
* If a constant is not defined as a constant in the ``Choices`` instance.
"""
# Ensure that the name is not already used as an attribute.
if hasattr(self, name):
raise ValueError("Cannot use '%s' as a subset name. "
"It's already an attribute." % name)
subset = self.extract_subset(*constants)
# Make the subset accessible via an attribute.
setattr(self, name, subset)
self.subsets.append(name) | [
"def",
"add_subset",
"(",
"self",
",",
"name",
",",
"constants",
")",
":",
"# Ensure that the name is not already used as an attribute.",
"if",
"hasattr",
"(",
"self",
",",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot use '%s' as a subset name. \"",
"\"It's already an attribute.\"",
"%",
"name",
")",
"subset",
"=",
"self",
".",
"extract_subset",
"(",
"*",
"constants",
")",
"# Make the subset accessible via an attribute.",
"setattr",
"(",
"self",
",",
"name",
",",
"subset",
")",
"self",
".",
"subsets",
".",
"append",
"(",
"name",
")"
] | Add a subset of entries under a defined name.
This allow to defined a "sub choice" if a django field need to not have the whole
choice available.
The sub-choice is a new ``Choices`` instance, with only the wanted the constant from the
main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``)
The sub-choice is accessible from the main ``Choices`` by an attribute having the given
name.
Parameters
----------
name : string
Name of the attribute that will old the new ``Choices`` instance.
constants: list or tuple
List of the constants name of this ``Choices`` object to make available in the subset.
Returns
-------
Choices
The newly created subset, which is a ``Choices`` object
Example
-------
>>> STATES = Choices(
... ('ONLINE', 1, 'Online'),
... ('DRAFT', 2, 'Draft'),
... ('OFFLINE', 3, 'Offline'),
... )
>>> STATES
[('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> STATES.add_subset('NOT_ONLINE', ('DRAFT', 'OFFLINE',))
>>> STATES.NOT_ONLINE
[('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
>>> STATES.NOT_ONLINE.DRAFT
2
>>> STATES.NOT_ONLINE.for_constant('DRAFT') is STATES.for_constant('DRAFT')
True
>>> STATES.NOT_ONLINE.ONLINE
Traceback (most recent call last):
...
AttributeError: 'Choices' object has no attribute 'ONLINE'
Raises
------
ValueError
* If ``name`` is already an attribute of the ``Choices`` instance.
* If a constant is not defined as a constant in the ``Choices`` instance. | [
"Add",
"a",
"subset",
"of",
"entries",
"under",
"a",
"defined",
"name",
"."
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L464-L530 |
twidi/django-extended-choices | extended_choices/choices.py | AutoDisplayChoices._convert_choices | def _convert_choices(self, choices):
"""Auto create display values then call super method"""
final_choices = []
for choice in choices:
if isinstance(choice, ChoiceEntry):
final_choices.append(choice)
continue
original_choice = choice
choice = list(choice)
length = len(choice)
assert 2 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,)
final_choice = []
# do we have attributes?
if length > 2 and isinstance(choice[-1], Mapping):
final_choice.append(choice.pop())
elif length == 4:
attributes = choice.pop()
assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,)
if attributes:
final_choice.append(attributes)
# the constant
final_choice.insert(0, choice.pop(0))
# the db value
final_choice.insert(1, choice.pop(0))
if len(choice):
# we were given a display value
final_choice.insert(2, choice.pop(0))
else:
# no display value, we compute it from the constant
final_choice.insert(2, self.display_transform(final_choice[0]))
final_choices.append(final_choice)
return super(AutoDisplayChoices, self)._convert_choices(final_choices) | python | def _convert_choices(self, choices):
"""Auto create display values then call super method"""
final_choices = []
for choice in choices:
if isinstance(choice, ChoiceEntry):
final_choices.append(choice)
continue
original_choice = choice
choice = list(choice)
length = len(choice)
assert 2 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,)
final_choice = []
# do we have attributes?
if length > 2 and isinstance(choice[-1], Mapping):
final_choice.append(choice.pop())
elif length == 4:
attributes = choice.pop()
assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,)
if attributes:
final_choice.append(attributes)
# the constant
final_choice.insert(0, choice.pop(0))
# the db value
final_choice.insert(1, choice.pop(0))
if len(choice):
# we were given a display value
final_choice.insert(2, choice.pop(0))
else:
# no display value, we compute it from the constant
final_choice.insert(2, self.display_transform(final_choice[0]))
final_choices.append(final_choice)
return super(AutoDisplayChoices, self)._convert_choices(final_choices) | [
"def",
"_convert_choices",
"(",
"self",
",",
"choices",
")",
":",
"final_choices",
"=",
"[",
"]",
"for",
"choice",
"in",
"choices",
":",
"if",
"isinstance",
"(",
"choice",
",",
"ChoiceEntry",
")",
":",
"final_choices",
".",
"append",
"(",
"choice",
")",
"continue",
"original_choice",
"=",
"choice",
"choice",
"=",
"list",
"(",
"choice",
")",
"length",
"=",
"len",
"(",
"choice",
")",
"assert",
"2",
"<=",
"length",
"<=",
"4",
",",
"'Invalid number of entries in %s'",
"%",
"(",
"original_choice",
",",
")",
"final_choice",
"=",
"[",
"]",
"# do we have attributes?",
"if",
"length",
">",
"2",
"and",
"isinstance",
"(",
"choice",
"[",
"-",
"1",
"]",
",",
"Mapping",
")",
":",
"final_choice",
".",
"append",
"(",
"choice",
".",
"pop",
"(",
")",
")",
"elif",
"length",
"==",
"4",
":",
"attributes",
"=",
"choice",
".",
"pop",
"(",
")",
"assert",
"attributes",
"is",
"None",
"or",
"isinstance",
"(",
"attributes",
",",
"Mapping",
")",
",",
"'Last argument must be a dict-like object in %s'",
"%",
"(",
"original_choice",
",",
")",
"if",
"attributes",
":",
"final_choice",
".",
"append",
"(",
"attributes",
")",
"# the constant",
"final_choice",
".",
"insert",
"(",
"0",
",",
"choice",
".",
"pop",
"(",
"0",
")",
")",
"# the db value",
"final_choice",
".",
"insert",
"(",
"1",
",",
"choice",
".",
"pop",
"(",
"0",
")",
")",
"if",
"len",
"(",
"choice",
")",
":",
"# we were given a display value",
"final_choice",
".",
"insert",
"(",
"2",
",",
"choice",
".",
"pop",
"(",
"0",
")",
")",
"else",
":",
"# no display value, we compute it from the constant",
"final_choice",
".",
"insert",
"(",
"2",
",",
"self",
".",
"display_transform",
"(",
"final_choice",
"[",
"0",
"]",
")",
")",
"final_choices",
".",
"append",
"(",
"final_choice",
")",
"return",
"super",
"(",
"AutoDisplayChoices",
",",
"self",
")",
".",
"_convert_choices",
"(",
"final_choices",
")"
] | Auto create display values then call super method | [
"Auto",
"create",
"display",
"values",
"then",
"call",
"super",
"method"
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L930-L972 |
twidi/django-extended-choices | extended_choices/choices.py | AutoChoices.add_choices | def add_choices(self, *choices, **kwargs):
"""Disallow super method to thing the first argument is a subset name"""
return super(AutoChoices, self).add_choices(_NO_SUBSET_NAME_, *choices, **kwargs) | python | def add_choices(self, *choices, **kwargs):
"""Disallow super method to thing the first argument is a subset name"""
return super(AutoChoices, self).add_choices(_NO_SUBSET_NAME_, *choices, **kwargs) | [
"def",
"add_choices",
"(",
"self",
",",
"*",
"choices",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AutoChoices",
",",
"self",
")",
".",
"add_choices",
"(",
"_NO_SUBSET_NAME_",
",",
"*",
"choices",
",",
"*",
"*",
"kwargs",
")"
] | Disallow super method to thing the first argument is a subset name | [
"Disallow",
"super",
"method",
"to",
"thing",
"the",
"first",
"argument",
"is",
"a",
"subset",
"name"
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L1019-L1021 |
twidi/django-extended-choices | extended_choices/choices.py | AutoChoices._convert_choices | def _convert_choices(self, choices):
"""Auto create db values then call super method"""
final_choices = []
for choice in choices:
if isinstance(choice, ChoiceEntry):
final_choices.append(choice)
continue
original_choice = choice
if isinstance(choice, six.string_types):
if choice == _NO_SUBSET_NAME_:
continue
choice = [choice, ]
else:
choice = list(choice)
length = len(choice)
assert 1 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,)
final_choice = []
# do we have attributes?
if length > 1 and isinstance(choice[-1], Mapping):
final_choice.append(choice.pop())
elif length == 4:
attributes = choice.pop()
assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,)
if attributes:
final_choice.append(attributes)
# the constant
final_choice.insert(0, choice.pop(0))
if len(choice):
# we were given a db value
final_choice.insert(1, choice.pop(0))
if len(choice):
# we were given a display value
final_choice.insert(2, choice.pop(0))
else:
# set None to compute it later
final_choice.insert(1, None)
if final_choice[1] is None:
# no db value, we compute it from the constant
final_choice[1] = self.value_transform(final_choice[0])
final_choices.append(final_choice)
return super(AutoChoices, self)._convert_choices(final_choices) | python | def _convert_choices(self, choices):
"""Auto create db values then call super method"""
final_choices = []
for choice in choices:
if isinstance(choice, ChoiceEntry):
final_choices.append(choice)
continue
original_choice = choice
if isinstance(choice, six.string_types):
if choice == _NO_SUBSET_NAME_:
continue
choice = [choice, ]
else:
choice = list(choice)
length = len(choice)
assert 1 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,)
final_choice = []
# do we have attributes?
if length > 1 and isinstance(choice[-1], Mapping):
final_choice.append(choice.pop())
elif length == 4:
attributes = choice.pop()
assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,)
if attributes:
final_choice.append(attributes)
# the constant
final_choice.insert(0, choice.pop(0))
if len(choice):
# we were given a db value
final_choice.insert(1, choice.pop(0))
if len(choice):
# we were given a display value
final_choice.insert(2, choice.pop(0))
else:
# set None to compute it later
final_choice.insert(1, None)
if final_choice[1] is None:
# no db value, we compute it from the constant
final_choice[1] = self.value_transform(final_choice[0])
final_choices.append(final_choice)
return super(AutoChoices, self)._convert_choices(final_choices) | [
"def",
"_convert_choices",
"(",
"self",
",",
"choices",
")",
":",
"final_choices",
"=",
"[",
"]",
"for",
"choice",
"in",
"choices",
":",
"if",
"isinstance",
"(",
"choice",
",",
"ChoiceEntry",
")",
":",
"final_choices",
".",
"append",
"(",
"choice",
")",
"continue",
"original_choice",
"=",
"choice",
"if",
"isinstance",
"(",
"choice",
",",
"six",
".",
"string_types",
")",
":",
"if",
"choice",
"==",
"_NO_SUBSET_NAME_",
":",
"continue",
"choice",
"=",
"[",
"choice",
",",
"]",
"else",
":",
"choice",
"=",
"list",
"(",
"choice",
")",
"length",
"=",
"len",
"(",
"choice",
")",
"assert",
"1",
"<=",
"length",
"<=",
"4",
",",
"'Invalid number of entries in %s'",
"%",
"(",
"original_choice",
",",
")",
"final_choice",
"=",
"[",
"]",
"# do we have attributes?",
"if",
"length",
">",
"1",
"and",
"isinstance",
"(",
"choice",
"[",
"-",
"1",
"]",
",",
"Mapping",
")",
":",
"final_choice",
".",
"append",
"(",
"choice",
".",
"pop",
"(",
")",
")",
"elif",
"length",
"==",
"4",
":",
"attributes",
"=",
"choice",
".",
"pop",
"(",
")",
"assert",
"attributes",
"is",
"None",
"or",
"isinstance",
"(",
"attributes",
",",
"Mapping",
")",
",",
"'Last argument must be a dict-like object in %s'",
"%",
"(",
"original_choice",
",",
")",
"if",
"attributes",
":",
"final_choice",
".",
"append",
"(",
"attributes",
")",
"# the constant",
"final_choice",
".",
"insert",
"(",
"0",
",",
"choice",
".",
"pop",
"(",
"0",
")",
")",
"if",
"len",
"(",
"choice",
")",
":",
"# we were given a db value",
"final_choice",
".",
"insert",
"(",
"1",
",",
"choice",
".",
"pop",
"(",
"0",
")",
")",
"if",
"len",
"(",
"choice",
")",
":",
"# we were given a display value",
"final_choice",
".",
"insert",
"(",
"2",
",",
"choice",
".",
"pop",
"(",
"0",
")",
")",
"else",
":",
"# set None to compute it later",
"final_choice",
".",
"insert",
"(",
"1",
",",
"None",
")",
"if",
"final_choice",
"[",
"1",
"]",
"is",
"None",
":",
"# no db value, we compute it from the constant",
"final_choice",
"[",
"1",
"]",
"=",
"self",
".",
"value_transform",
"(",
"final_choice",
"[",
"0",
"]",
")",
"final_choices",
".",
"append",
"(",
"final_choice",
")",
"return",
"super",
"(",
"AutoChoices",
",",
"self",
")",
".",
"_convert_choices",
"(",
"final_choices",
")"
] | Auto create db values then call super method | [
"Auto",
"create",
"db",
"values",
"then",
"call",
"super",
"method"
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/choices.py#L1023-L1075 |
twidi/django-extended-choices | extended_choices/fields.py | NamedExtendedChoiceFormField.to_python | def to_python(self, value):
"""Convert the constant to the real choice value."""
# ``is_required`` is already checked in ``validate``.
if value is None:
return None
# Validate the type.
if not isinstance(value, six.string_types):
raise forms.ValidationError(
"Invalid value type (should be a string).",
code='invalid-choice-type',
)
# Get the constant from the choices object, raising if it doesn't exist.
try:
final = getattr(self.choices, value)
except AttributeError:
available = '[%s]' % ', '.join(self.choices.constants)
raise forms.ValidationError(
"Invalid value (not in available choices. Available ones are: %s" % available,
code='non-existing-choice',
)
return final | python | def to_python(self, value):
"""Convert the constant to the real choice value."""
# ``is_required`` is already checked in ``validate``.
if value is None:
return None
# Validate the type.
if not isinstance(value, six.string_types):
raise forms.ValidationError(
"Invalid value type (should be a string).",
code='invalid-choice-type',
)
# Get the constant from the choices object, raising if it doesn't exist.
try:
final = getattr(self.choices, value)
except AttributeError:
available = '[%s]' % ', '.join(self.choices.constants)
raise forms.ValidationError(
"Invalid value (not in available choices. Available ones are: %s" % available,
code='non-existing-choice',
)
return final | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"# ``is_required`` is already checked in ``validate``.",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"# Validate the type.",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"\"Invalid value type (should be a string).\"",
",",
"code",
"=",
"'invalid-choice-type'",
",",
")",
"# Get the constant from the choices object, raising if it doesn't exist.",
"try",
":",
"final",
"=",
"getattr",
"(",
"self",
".",
"choices",
",",
"value",
")",
"except",
"AttributeError",
":",
"available",
"=",
"'[%s]'",
"%",
"', '",
".",
"join",
"(",
"self",
".",
"choices",
".",
"constants",
")",
"raise",
"forms",
".",
"ValidationError",
"(",
"\"Invalid value (not in available choices. Available ones are: %s\"",
"%",
"available",
",",
"code",
"=",
"'non-existing-choice'",
",",
")",
"return",
"final"
] | Convert the constant to the real choice value. | [
"Convert",
"the",
"constant",
"to",
"the",
"real",
"choice",
"value",
"."
] | train | https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/fields.py#L37-L61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.