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
kytos/python-openflow
pyof/foundation/network_types.py
IPv4._update_checksum
def _update_checksum(self): """Update the packet checksum to enable integrity check.""" source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8) + source_list[1] source_lower = (source_list[2] << 8) + source_list[3] destination_upper = (destination_list[0] << 8) + destination_list[1] destination_lower = (destination_list[2] << 8) + destination_list[3] block_sum = ((self._version_ihl << 8 | self._dscp_ecn) + self.length + self.identification + self._flags_offset + (self.ttl << 8 | self.protocol) + source_upper + source_lower + destination_upper + destination_lower) while block_sum > 65535: carry = block_sum >> 16 block_sum = (block_sum & 65535) + carry self.checksum = ~block_sum & 65535
python
def _update_checksum(self): """Update the packet checksum to enable integrity check.""" source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8) + source_list[1] source_lower = (source_list[2] << 8) + source_list[3] destination_upper = (destination_list[0] << 8) + destination_list[1] destination_lower = (destination_list[2] << 8) + destination_list[3] block_sum = ((self._version_ihl << 8 | self._dscp_ecn) + self.length + self.identification + self._flags_offset + (self.ttl << 8 | self.protocol) + source_upper + source_lower + destination_upper + destination_lower) while block_sum > 65535: carry = block_sum >> 16 block_sum = (block_sum & 65535) + carry self.checksum = ~block_sum & 65535
[ "def", "_update_checksum", "(", "self", ")", ":", "source_list", "=", "[", "int", "(", "octet", ")", "for", "octet", "in", "self", ".", "source", ".", "split", "(", "\".\"", ")", "]", "destination_list", "=", "[", "int", "(", "octet", ")", "for", "octet", "in", "self", ".", "destination", ".", "split", "(", "\".\"", ")", "]", "source_upper", "=", "(", "source_list", "[", "0", "]", "<<", "8", ")", "+", "source_list", "[", "1", "]", "source_lower", "=", "(", "source_list", "[", "2", "]", "<<", "8", ")", "+", "source_list", "[", "3", "]", "destination_upper", "=", "(", "destination_list", "[", "0", "]", "<<", "8", ")", "+", "destination_list", "[", "1", "]", "destination_lower", "=", "(", "destination_list", "[", "2", "]", "<<", "8", ")", "+", "destination_list", "[", "3", "]", "block_sum", "=", "(", "(", "self", ".", "_version_ihl", "<<", "8", "|", "self", ".", "_dscp_ecn", ")", "+", "self", ".", "length", "+", "self", ".", "identification", "+", "self", ".", "_flags_offset", "+", "(", "self", ".", "ttl", "<<", "8", "|", "self", ".", "protocol", ")", "+", "source_upper", "+", "source_lower", "+", "destination_upper", "+", "destination_lower", ")", "while", "block_sum", ">", "65535", ":", "carry", "=", "block_sum", ">>", "16", "block_sum", "=", "(", "block_sum", "&", "65535", ")", "+", "carry", "self", ".", "checksum", "=", "~", "block_sum", "&", "65535" ]
Update the packet checksum to enable integrity check.
[ "Update", "the", "packet", "checksum", "to", "enable", "integrity", "check", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L534-L553
kytos/python-openflow
pyof/foundation/network_types.py
IPv4.pack
def pack(self, value=None): """Pack the struct in a binary representation. Merge some fields to ensure correct packing. Returns: bytes: Binary representation of this instance. """ # Set the correct IHL based on options size if self.options: self.ihl += int(len(self.options) / 4) # Set the correct packet length based on header length and data self.length = int(self.ihl * 4 + len(self.data)) self._version_ihl = self.version << 4 | self.ihl self._dscp_ecn = self.dscp << 2 | self.ecn self._flags_offset = self.flags << 13 | self.offset # Set the checksum field before packing self._update_checksum() return super().pack()
python
def pack(self, value=None): """Pack the struct in a binary representation. Merge some fields to ensure correct packing. Returns: bytes: Binary representation of this instance. """ # Set the correct IHL based on options size if self.options: self.ihl += int(len(self.options) / 4) # Set the correct packet length based on header length and data self.length = int(self.ihl * 4 + len(self.data)) self._version_ihl = self.version << 4 | self.ihl self._dscp_ecn = self.dscp << 2 | self.ecn self._flags_offset = self.flags << 13 | self.offset # Set the checksum field before packing self._update_checksum() return super().pack()
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "# Set the correct IHL based on options size", "if", "self", ".", "options", ":", "self", ".", "ihl", "+=", "int", "(", "len", "(", "self", ".", "options", ")", "/", "4", ")", "# Set the correct packet length based on header length and data", "self", ".", "length", "=", "int", "(", "self", ".", "ihl", "*", "4", "+", "len", "(", "self", ".", "data", ")", ")", "self", ".", "_version_ihl", "=", "self", ".", "version", "<<", "4", "|", "self", ".", "ihl", "self", ".", "_dscp_ecn", "=", "self", ".", "dscp", "<<", "2", "|", "self", ".", "ecn", "self", ".", "_flags_offset", "=", "self", ".", "flags", "<<", "13", "|", "self", ".", "offset", "# Set the checksum field before packing", "self", ".", "_update_checksum", "(", ")", "return", "super", "(", ")", ".", "pack", "(", ")" ]
Pack the struct in a binary representation. Merge some fields to ensure correct packing. Returns: bytes: Binary representation of this instance.
[ "Pack", "the", "struct", "in", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L555-L578
kytos/python-openflow
pyof/foundation/network_types.py
IPv4.unpack
def unpack(self, buff, offset=0): """Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails. """ super().unpack(buff, offset) self.version = self._version_ihl.value >> 4 self.ihl = self._version_ihl.value & 15 self.dscp = self._dscp_ecn.value >> 2 self.ecn = self._dscp_ecn.value & 3 self.length = self.length.value self.identification = self.identification.value self.flags = self._flags_offset.value >> 13 self.offset = self._flags_offset.value & 8191 self.ttl = self.ttl.value self.protocol = self.protocol.value self.checksum = self.checksum.value self.source = self.source.value self.destination = self.destination.value if self.ihl > 5: options_size = (self.ihl - 5) * 4 self.data = self.options.value[options_size:] self.options = self.options.value[:options_size] else: self.data = self.options.value self.options = b''
python
def unpack(self, buff, offset=0): """Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails. """ super().unpack(buff, offset) self.version = self._version_ihl.value >> 4 self.ihl = self._version_ihl.value & 15 self.dscp = self._dscp_ecn.value >> 2 self.ecn = self._dscp_ecn.value & 3 self.length = self.length.value self.identification = self.identification.value self.flags = self._flags_offset.value >> 13 self.offset = self._flags_offset.value & 8191 self.ttl = self.ttl.value self.protocol = self.protocol.value self.checksum = self.checksum.value self.source = self.source.value self.destination = self.destination.value if self.ihl > 5: options_size = (self.ihl - 5) * 4 self.data = self.options.value[options_size:] self.options = self.options.value[:options_size] else: self.data = self.options.value self.options = b''
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ",", "offset", ")", "self", ".", "version", "=", "self", ".", "_version_ihl", ".", "value", ">>", "4", "self", ".", "ihl", "=", "self", ".", "_version_ihl", ".", "value", "&", "15", "self", ".", "dscp", "=", "self", ".", "_dscp_ecn", ".", "value", ">>", "2", "self", ".", "ecn", "=", "self", ".", "_dscp_ecn", ".", "value", "&", "3", "self", ".", "length", "=", "self", ".", "length", ".", "value", "self", ".", "identification", "=", "self", ".", "identification", ".", "value", "self", ".", "flags", "=", "self", ".", "_flags_offset", ".", "value", ">>", "13", "self", ".", "offset", "=", "self", ".", "_flags_offset", ".", "value", "&", "8191", "self", ".", "ttl", "=", "self", ".", "ttl", ".", "value", "self", ".", "protocol", "=", "self", ".", "protocol", ".", "value", "self", ".", "checksum", "=", "self", ".", "checksum", ".", "value", "self", ".", "source", "=", "self", ".", "source", ".", "value", "self", ".", "destination", "=", "self", ".", "destination", ".", "value", "if", "self", ".", "ihl", ">", "5", ":", "options_size", "=", "(", "self", ".", "ihl", "-", "5", ")", "*", "4", "self", ".", "data", "=", "self", ".", "options", ".", "value", "[", "options_size", ":", "]", "self", ".", "options", "=", "self", ".", "options", ".", "value", "[", ":", "options_size", "]", "else", ":", "self", ".", "data", "=", "self", ".", "options", ".", "value", "self", ".", "options", "=", "b''" ]
Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails.
[ "Unpack", "a", "binary", "struct", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L580-L615
kytos/python-openflow
pyof/foundation/network_types.py
TLVWithSubType.value
def value(self): """Return sub type and sub value as binary data. Returns: :class:`~pyof.foundation.basic_types.BinaryData`: BinaryData calculated. """ binary = UBInt8(self.sub_type).pack() + self.sub_value.pack() return BinaryData(binary)
python
def value(self): """Return sub type and sub value as binary data. Returns: :class:`~pyof.foundation.basic_types.BinaryData`: BinaryData calculated. """ binary = UBInt8(self.sub_type).pack() + self.sub_value.pack() return BinaryData(binary)
[ "def", "value", "(", "self", ")", ":", "binary", "=", "UBInt8", "(", "self", ".", "sub_type", ")", ".", "pack", "(", ")", "+", "self", ".", "sub_value", ".", "pack", "(", ")", "return", "BinaryData", "(", "binary", ")" ]
Return sub type and sub value as binary data. Returns: :class:`~pyof.foundation.basic_types.BinaryData`: BinaryData calculated.
[ "Return", "sub", "type", "and", "sub", "value", "as", "binary", "data", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L640-L649
kytos/python-openflow
pyof/foundation/network_types.py
TLVWithSubType.unpack
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exception: If there is a struct unpacking error. """ header = UBInt16() header.unpack(buff[offset:offset+2]) self.tlv_type = header.value >> 9 length = header.value & 511 begin, end = offset + 2, offset + 2 + length sub_type = UBInt8() sub_type.unpack(buff[begin:begin+1]) self.sub_type = sub_type.value self.sub_value = BinaryData(buff[begin+1:end])
python
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exception: If there is a struct unpacking error. """ header = UBInt16() header.unpack(buff[offset:offset+2]) self.tlv_type = header.value >> 9 length = header.value & 511 begin, end = offset + 2, offset + 2 + length sub_type = UBInt8() sub_type.unpack(buff[begin:begin+1]) self.sub_type = sub_type.value self.sub_value = BinaryData(buff[begin+1:end])
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "header", "=", "UBInt16", "(", ")", "header", ".", "unpack", "(", "buff", "[", "offset", ":", "offset", "+", "2", "]", ")", "self", ".", "tlv_type", "=", "header", ".", "value", ">>", "9", "length", "=", "header", ".", "value", "&", "511", "begin", ",", "end", "=", "offset", "+", "2", ",", "offset", "+", "2", "+", "length", "sub_type", "=", "UBInt8", "(", ")", "sub_type", ".", "unpack", "(", "buff", "[", "begin", ":", "begin", "+", "1", "]", ")", "self", ".", "sub_type", "=", "sub_type", ".", "value", "self", ".", "sub_value", "=", "BinaryData", "(", "buff", "[", "begin", "+", "1", ":", "end", "]", ")" ]
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exception: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L651-L673
kytos/python-openflow
pyof/utils.py
validate_packet
def validate_packet(packet): """Check if packet is valid OF packet. Raises: UnpackException: If the packet is invalid. """ if not isinstance(packet, bytes): raise UnpackException('invalid packet') packet_length = len(packet) if packet_length < 8 or packet_length > 2**16: raise UnpackException('invalid packet') if packet_length != int.from_bytes(packet[2:4], byteorder='big'): raise UnpackException('invalid packet') version = packet[0] if version == 0 or version >= 128: raise UnpackException('invalid packet')
python
def validate_packet(packet): """Check if packet is valid OF packet. Raises: UnpackException: If the packet is invalid. """ if not isinstance(packet, bytes): raise UnpackException('invalid packet') packet_length = len(packet) if packet_length < 8 or packet_length > 2**16: raise UnpackException('invalid packet') if packet_length != int.from_bytes(packet[2:4], byteorder='big'): raise UnpackException('invalid packet') version = packet[0] if version == 0 or version >= 128: raise UnpackException('invalid packet')
[ "def", "validate_packet", "(", "packet", ")", ":", "if", "not", "isinstance", "(", "packet", ",", "bytes", ")", ":", "raise", "UnpackException", "(", "'invalid packet'", ")", "packet_length", "=", "len", "(", "packet", ")", "if", "packet_length", "<", "8", "or", "packet_length", ">", "2", "**", "16", ":", "raise", "UnpackException", "(", "'invalid packet'", ")", "if", "packet_length", "!=", "int", ".", "from_bytes", "(", "packet", "[", "2", ":", "4", "]", ",", "byteorder", "=", "'big'", ")", ":", "raise", "UnpackException", "(", "'invalid packet'", ")", "version", "=", "packet", "[", "0", "]", "if", "version", "==", "0", "or", "version", ">=", "128", ":", "raise", "UnpackException", "(", "'invalid packet'", ")" ]
Check if packet is valid OF packet. Raises: UnpackException: If the packet is invalid.
[ "Check", "if", "packet", "is", "valid", "OF", "packet", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/utils.py#L15-L35
kytos/python-openflow
pyof/utils.py
unpack
def unpack(packet): """Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked. """ validate_packet(packet) version = packet[0] try: pyof_lib = PYOF_VERSION_LIBS[version] except KeyError: raise UnpackException('Version not supported') try: message = pyof_lib.common.utils.unpack_message(packet) return message except (UnpackException, ValueError) as exception: raise UnpackException(exception)
python
def unpack(packet): """Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked. """ validate_packet(packet) version = packet[0] try: pyof_lib = PYOF_VERSION_LIBS[version] except KeyError: raise UnpackException('Version not supported') try: message = pyof_lib.common.utils.unpack_message(packet) return message except (UnpackException, ValueError) as exception: raise UnpackException(exception)
[ "def", "unpack", "(", "packet", ")", ":", "validate_packet", "(", "packet", ")", "version", "=", "packet", "[", "0", "]", "try", ":", "pyof_lib", "=", "PYOF_VERSION_LIBS", "[", "version", "]", "except", "KeyError", ":", "raise", "UnpackException", "(", "'Version not supported'", ")", "try", ":", "message", "=", "pyof_lib", ".", "common", ".", "utils", ".", "unpack_message", "(", "packet", ")", "return", "message", "except", "(", "UnpackException", ",", "ValueError", ")", "as", "exception", ":", "raise", "UnpackException", "(", "exception", ")" ]
Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked.
[ "Unpack", "the", "OpenFlow", "Packet", "and", "returns", "a", "message", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/utils.py#L38-L63
kytos/python-openflow
pyof/v0x04/asynchronous/error_msg.py
ErrorType.get_class
def get_class(self): """Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type. """ classes = {'OFPET_HELLO_FAILED': HelloFailedCode, 'OFPET_BAD_REQUEST': BadRequestCode, 'OFPET_BAD_ACTION': BadActionCode, 'OFPET_BAD_INSTRUCTION': BadInstructionCode, 'OFPET_BAD_MATCH': BadMatchCode, 'OFPET_FLOW_MOD_FAILED': FlowModFailedCode, 'OFPET_GROUP_MOD_FAILED': GroupModFailedCode, 'OFPET_PORT_MOD_FAILED': PortModFailedCode, 'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode, 'OFPET_SWITCH_CONFIG_FAILED': SwitchConfigFailedCode, 'OFPET_ROLE_REQUEST_FAILED': RoleRequestFailedCode, 'OFPET_METER_MOD_FAILED': MeterModFailedCode, 'OFPET_TABLE_MOD_FAILED': TableModFailedCode, 'OFPET_TABLE_FEATURES_FAILED': TableFeaturesFailedCode} return classes.get(self.name, GenericFailedCode)
python
def get_class(self): """Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type. """ classes = {'OFPET_HELLO_FAILED': HelloFailedCode, 'OFPET_BAD_REQUEST': BadRequestCode, 'OFPET_BAD_ACTION': BadActionCode, 'OFPET_BAD_INSTRUCTION': BadInstructionCode, 'OFPET_BAD_MATCH': BadMatchCode, 'OFPET_FLOW_MOD_FAILED': FlowModFailedCode, 'OFPET_GROUP_MOD_FAILED': GroupModFailedCode, 'OFPET_PORT_MOD_FAILED': PortModFailedCode, 'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode, 'OFPET_SWITCH_CONFIG_FAILED': SwitchConfigFailedCode, 'OFPET_ROLE_REQUEST_FAILED': RoleRequestFailedCode, 'OFPET_METER_MOD_FAILED': MeterModFailedCode, 'OFPET_TABLE_MOD_FAILED': TableModFailedCode, 'OFPET_TABLE_FEATURES_FAILED': TableFeaturesFailedCode} return classes.get(self.name, GenericFailedCode)
[ "def", "get_class", "(", "self", ")", ":", "classes", "=", "{", "'OFPET_HELLO_FAILED'", ":", "HelloFailedCode", ",", "'OFPET_BAD_REQUEST'", ":", "BadRequestCode", ",", "'OFPET_BAD_ACTION'", ":", "BadActionCode", ",", "'OFPET_BAD_INSTRUCTION'", ":", "BadInstructionCode", ",", "'OFPET_BAD_MATCH'", ":", "BadMatchCode", ",", "'OFPET_FLOW_MOD_FAILED'", ":", "FlowModFailedCode", ",", "'OFPET_GROUP_MOD_FAILED'", ":", "GroupModFailedCode", ",", "'OFPET_PORT_MOD_FAILED'", ":", "PortModFailedCode", ",", "'OFPET_QUEUE_OP_FAILED'", ":", "QueueOpFailedCode", ",", "'OFPET_SWITCH_CONFIG_FAILED'", ":", "SwitchConfigFailedCode", ",", "'OFPET_ROLE_REQUEST_FAILED'", ":", "RoleRequestFailedCode", ",", "'OFPET_METER_MOD_FAILED'", ":", "MeterModFailedCode", ",", "'OFPET_TABLE_MOD_FAILED'", ":", "TableModFailedCode", ",", "'OFPET_TABLE_FEATURES_FAILED'", ":", "TableFeaturesFailedCode", "}", "return", "classes", ".", "get", "(", "self", ".", "name", ",", "GenericFailedCode", ")" ]
Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type.
[ "Return", "a", "Code", "class", "based", "on", "current", "ErrorType", "value", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/asynchronous/error_msg.py#L211-L232
kytos/python-openflow
pyof/v0x04/asynchronous/error_msg.py
ErrorMsg.unpack
def unpack(self, buff, offset=0): """Unpack binary data into python object.""" super().unpack(buff, offset) code_class = ErrorType(self.error_type).get_class() self.code = code_class(self.code)
python
def unpack(self, buff, offset=0): """Unpack binary data into python object.""" super().unpack(buff, offset) code_class = ErrorType(self.error_type).get_class() self.code = code_class(self.code)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ",", "offset", ")", "code_class", "=", "ErrorType", "(", "self", ".", "error_type", ")", ".", "get_class", "(", ")", "self", ".", "code", "=", "code_class", "(", "self", ".", "code", ")" ]
Unpack binary data into python object.
[ "Unpack", "binary", "data", "into", "python", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/asynchronous/error_msg.py#L474-L478
kytos/python-openflow
pyof/v0x01/asynchronous/error_msg.py
ErrorType.get_class
def get_class(self): """Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type. """ classes = {'OFPET_HELLO_FAILED': HelloFailedCode, 'OFPET_BAD_REQUEST': BadRequestCode, 'OFPET_BAD_ACTION': BadActionCode, 'OFPET_FLOW_MOD_FAILED': FlowModFailedCode, 'OFPET_PORT_MOD_FAILED': PortModFailedCode, 'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode} return classes.get(self.name, GenericFailedCode)
python
def get_class(self): """Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type. """ classes = {'OFPET_HELLO_FAILED': HelloFailedCode, 'OFPET_BAD_REQUEST': BadRequestCode, 'OFPET_BAD_ACTION': BadActionCode, 'OFPET_FLOW_MOD_FAILED': FlowModFailedCode, 'OFPET_PORT_MOD_FAILED': PortModFailedCode, 'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode} return classes.get(self.name, GenericFailedCode)
[ "def", "get_class", "(", "self", ")", ":", "classes", "=", "{", "'OFPET_HELLO_FAILED'", ":", "HelloFailedCode", ",", "'OFPET_BAD_REQUEST'", ":", "BadRequestCode", ",", "'OFPET_BAD_ACTION'", ":", "BadActionCode", ",", "'OFPET_FLOW_MOD_FAILED'", ":", "FlowModFailedCode", ",", "'OFPET_PORT_MOD_FAILED'", ":", "PortModFailedCode", ",", "'OFPET_QUEUE_OP_FAILED'", ":", "QueueOpFailedCode", "}", "return", "classes", ".", "get", "(", "self", ".", "name", ",", "GenericFailedCode", ")" ]
Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type.
[ "Return", "a", "Code", "class", "based", "on", "current", "ErrorType", "value", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/asynchronous/error_msg.py#L39-L52
kytos/python-openflow
pyof/v0x01/asynchronous/error_msg.py
ErrorMsg.pack
def pack(self, value=None): """Pack the value as a binary representation. :attr:`data` is packed before the calling :meth:`.GenericMessage.pack`. After that, :attr:`data`'s value is restored. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.PackException`: If pack fails. """ if value is None: data_backup = None if self.data is not None and not isinstance(self.data, bytes): data_backup = self.data self.data = self.data.pack() packed = super().pack() if data_backup is not None: self.data = data_backup return packed elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
python
def pack(self, value=None): """Pack the value as a binary representation. :attr:`data` is packed before the calling :meth:`.GenericMessage.pack`. After that, :attr:`data`'s value is restored. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.PackException`: If pack fails. """ if value is None: data_backup = None if self.data is not None and not isinstance(self.data, bytes): data_backup = self.data self.data = self.data.pack() packed = super().pack() if data_backup is not None: self.data = data_backup return packed elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "data_backup", "=", "None", "if", "self", ".", "data", "is", "not", "None", "and", "not", "isinstance", "(", "self", ".", "data", ",", "bytes", ")", ":", "data_backup", "=", "self", ".", "data", "self", ".", "data", "=", "self", ".", "data", ".", "pack", "(", ")", "packed", "=", "super", "(", ")", ".", "pack", "(", ")", "if", "data_backup", "is", "not", "None", ":", "self", ".", "data", "=", "data_backup", "return", "packed", "elif", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "pack", "(", ")", "else", ":", "msg", "=", "\"{} is not an instance of {}\"", ".", "format", "(", "value", ",", "type", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
Pack the value as a binary representation. :attr:`data` is packed before the calling :meth:`.GenericMessage.pack`. After that, :attr:`data`'s value is restored. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.PackException`: If pack fails.
[ "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/asynchronous/error_msg.py#L204-L231
andreikop/qutepart
qutepart/bookmarks.py
Bookmarks._createAction
def _createAction(self, widget, iconFileName, text, shortcut, slot): """Create QAction with given parameters and add to the widget """ icon = qutepart.getIcon(iconFileName) action = QAction(icon, text, widget) action.setShortcut(QKeySequence(shortcut)) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(slot) widget.addAction(action) return action
python
def _createAction(self, widget, iconFileName, text, shortcut, slot): """Create QAction with given parameters and add to the widget """ icon = qutepart.getIcon(iconFileName) action = QAction(icon, text, widget) action.setShortcut(QKeySequence(shortcut)) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(slot) widget.addAction(action) return action
[ "def", "_createAction", "(", "self", ",", "widget", ",", "iconFileName", ",", "text", ",", "shortcut", ",", "slot", ")", ":", "icon", "=", "qutepart", ".", "getIcon", "(", "iconFileName", ")", "action", "=", "QAction", "(", "icon", ",", "text", ",", "widget", ")", "action", ".", "setShortcut", "(", "QKeySequence", "(", "shortcut", ")", ")", "action", ".", "setShortcutContext", "(", "Qt", ".", "WidgetShortcut", ")", "action", ".", "triggered", ".", "connect", "(", "slot", ")", "widget", ".", "addAction", "(", "action", ")", "return", "action" ]
Create QAction with given parameters and add to the widget
[ "Create", "QAction", "with", "given", "parameters", "and", "add", "to", "the", "widget" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/bookmarks.py#L25-L36
andreikop/qutepart
qutepart/bookmarks.py
Bookmarks.clear
def clear(self, startBlock, endBlock): """Clear bookmarks on block range including start and end """ for block in qutepart.iterateBlocksFrom(startBlock): self._setBlockMarked(block, False) if block == endBlock: break
python
def clear(self, startBlock, endBlock): """Clear bookmarks on block range including start and end """ for block in qutepart.iterateBlocksFrom(startBlock): self._setBlockMarked(block, False) if block == endBlock: break
[ "def", "clear", "(", "self", ",", "startBlock", ",", "endBlock", ")", ":", "for", "block", "in", "qutepart", ".", "iterateBlocksFrom", "(", "startBlock", ")", ":", "self", ".", "_setBlockMarked", "(", "block", ",", "False", ")", "if", "block", "==", "endBlock", ":", "break" ]
Clear bookmarks on block range including start and end
[ "Clear", "bookmarks", "on", "block", "range", "including", "start", "and", "end" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/bookmarks.py#L46-L52
andreikop/qutepart
qutepart/bookmarks.py
Bookmarks._onPrevBookmark
def _onPrevBookmark(self): """Previous Bookmark action triggered. Move cursor """ for block in qutepart.iterateBlocksBackFrom(self._qpart.textCursor().block().previous()): if self.isBlockMarked(block): self._qpart.setTextCursor(QTextCursor(block)) return
python
def _onPrevBookmark(self): """Previous Bookmark action triggered. Move cursor """ for block in qutepart.iterateBlocksBackFrom(self._qpart.textCursor().block().previous()): if self.isBlockMarked(block): self._qpart.setTextCursor(QTextCursor(block)) return
[ "def", "_onPrevBookmark", "(", "self", ")", ":", "for", "block", "in", "qutepart", ".", "iterateBlocksBackFrom", "(", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "previous", "(", ")", ")", ":", "if", "self", ".", "isBlockMarked", "(", "block", ")", ":", "self", ".", "_qpart", ".", "setTextCursor", "(", "QTextCursor", "(", "block", ")", ")", "return" ]
Previous Bookmark action triggered. Move cursor
[ "Previous", "Bookmark", "action", "triggered", ".", "Move", "cursor" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/bookmarks.py#L73-L79
andreikop/qutepart
qutepart/bookmarks.py
Bookmarks._onNextBookmark
def _onNextBookmark(self): """Previous Bookmark action triggered. Move cursor """ for block in qutepart.iterateBlocksFrom(self._qpart.textCursor().block().next()): if self.isBlockMarked(block): self._qpart.setTextCursor(QTextCursor(block)) return
python
def _onNextBookmark(self): """Previous Bookmark action triggered. Move cursor """ for block in qutepart.iterateBlocksFrom(self._qpart.textCursor().block().next()): if self.isBlockMarked(block): self._qpart.setTextCursor(QTextCursor(block)) return
[ "def", "_onNextBookmark", "(", "self", ")", ":", "for", "block", "in", "qutepart", ".", "iterateBlocksFrom", "(", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "next", "(", ")", ")", ":", "if", "self", ".", "isBlockMarked", "(", "block", ")", ":", "self", ".", "_qpart", ".", "setTextCursor", "(", "QTextCursor", "(", "block", ")", ")", "return" ]
Previous Bookmark action triggered. Move cursor
[ "Previous", "Bookmark", "action", "triggered", ".", "Move", "cursor" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/bookmarks.py#L81-L87
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter._iterateDocumentCharsForward
def _iterateDocumentCharsForward(self, block, startColumnIndex): """Traverse document forward. Yield (block, columnIndex, char) Raise _TimeoutException if time is over """ # Chars in the start line endTime = time.time() + self._MAX_SEARCH_TIME_SEC 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 if time.time() > endTime: raise _TimeoutException('Time is over') 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 endTime = time.time() + self._MAX_SEARCH_TIME_SEC 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 if time.time() > endTime: raise _TimeoutException('Time is over') block = block.next()
[ "def", "_iterateDocumentCharsForward", "(", "self", ",", "block", ",", "startColumnIndex", ")", ":", "# Chars in the start line", "endTime", "=", "time", ".", "time", "(", ")", "+", "self", ".", "_MAX_SEARCH_TIME_SEC", "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", "if", "time", ".", "time", "(", ")", ">", "endTime", ":", "raise", "_TimeoutException", "(", "'Time is over'", ")", "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/brackethlighter.py#L35-L53
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter._iterateDocumentCharsBackward
def _iterateDocumentCharsBackward(self, block, startColumnIndex): """Traverse document forward. Yield (block, columnIndex, char) Raise _TimeoutException if time is over """ # Chars in the start line endTime = time.time() + self._MAX_SEARCH_TIME_SEC 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 if time.time() > endTime: raise _TimeoutException('Time is over') 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 endTime = time.time() + self._MAX_SEARCH_TIME_SEC 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 if time.time() > endTime: raise _TimeoutException('Time is over') block = block.previous()
[ "def", "_iterateDocumentCharsBackward", "(", "self", ",", "block", ",", "startColumnIndex", ")", ":", "# Chars in the start line", "endTime", "=", "time", ".", "time", "(", ")", "+", "self", ".", "_MAX_SEARCH_TIME_SEC", "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", "if", "time", ".", "time", "(", ")", ">", "endTime", ":", "raise", "_TimeoutException", "(", "'Time is over'", ")", "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/brackethlighter.py#L55-L73
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter._findMatchingBracket
def _findMatchingBracket(self, bracket, qpart, block, columnIndex): """Find matching bracket for the bracket. Return (block, columnIndex) or (None, None) Raise _TimeoutException, if time is over """ if bracket in self._START_BRACKETS: charsGenerator = self._iterateDocumentCharsForward(block, columnIndex + 1) else: charsGenerator = self._iterateDocumentCharsBackward(block, columnIndex) depth = 1 oposite = self._OPOSITE_BRACKET[bracket] for block, columnIndex, char in charsGenerator: if qpart.isCode(block, columnIndex): if char == oposite: depth -= 1 if depth == 0: return block, columnIndex elif char == bracket: depth += 1 else: return None, None
python
def _findMatchingBracket(self, bracket, qpart, block, columnIndex): """Find matching bracket for the bracket. Return (block, columnIndex) or (None, None) Raise _TimeoutException, if time is over """ if bracket in self._START_BRACKETS: charsGenerator = self._iterateDocumentCharsForward(block, columnIndex + 1) else: charsGenerator = self._iterateDocumentCharsBackward(block, columnIndex) depth = 1 oposite = self._OPOSITE_BRACKET[bracket] for block, columnIndex, char in charsGenerator: if qpart.isCode(block, columnIndex): if char == oposite: depth -= 1 if depth == 0: return block, columnIndex elif char == bracket: depth += 1 else: return None, None
[ "def", "_findMatchingBracket", "(", "self", ",", "bracket", ",", "qpart", ",", "block", ",", "columnIndex", ")", ":", "if", "bracket", "in", "self", ".", "_START_BRACKETS", ":", "charsGenerator", "=", "self", ".", "_iterateDocumentCharsForward", "(", "block", ",", "columnIndex", "+", "1", ")", "else", ":", "charsGenerator", "=", "self", ".", "_iterateDocumentCharsBackward", "(", "block", ",", "columnIndex", ")", "depth", "=", "1", "oposite", "=", "self", ".", "_OPOSITE_BRACKET", "[", "bracket", "]", "for", "block", ",", "columnIndex", ",", "char", "in", "charsGenerator", ":", "if", "qpart", ".", "isCode", "(", "block", ",", "columnIndex", ")", ":", "if", "char", "==", "oposite", ":", "depth", "-=", "1", "if", "depth", "==", "0", ":", "return", "block", ",", "columnIndex", "elif", "char", "==", "bracket", ":", "depth", "+=", "1", "else", ":", "return", "None", ",", "None" ]
Find matching bracket for the bracket. Return (block, columnIndex) or (None, None) Raise _TimeoutException, if time is over
[ "Find", "matching", "bracket", "for", "the", "bracket", ".", "Return", "(", "block", "columnIndex", ")", "or", "(", "None", "None", ")", "Raise", "_TimeoutException", "if", "time", "is", "over" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/brackethlighter.py#L75-L96
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter._makeMatchSelection
def _makeMatchSelection(self, block, columnIndex, matched): """Make matched or unmatched QTextEdit.ExtraSelection """ selection = QTextEdit.ExtraSelection() if matched: bgColor = Qt.green else: bgColor = Qt.red selection.format.setBackground(bgColor) selection.cursor = QTextCursor(block) selection.cursor.setPosition(block.position() + columnIndex) selection.cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) return selection
python
def _makeMatchSelection(self, block, columnIndex, matched): """Make matched or unmatched QTextEdit.ExtraSelection """ selection = QTextEdit.ExtraSelection() if matched: bgColor = Qt.green else: bgColor = Qt.red selection.format.setBackground(bgColor) selection.cursor = QTextCursor(block) selection.cursor.setPosition(block.position() + columnIndex) selection.cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) return selection
[ "def", "_makeMatchSelection", "(", "self", ",", "block", ",", "columnIndex", ",", "matched", ")", ":", "selection", "=", "QTextEdit", ".", "ExtraSelection", "(", ")", "if", "matched", ":", "bgColor", "=", "Qt", ".", "green", "else", ":", "bgColor", "=", "Qt", ".", "red", "selection", ".", "format", ".", "setBackground", "(", "bgColor", ")", "selection", ".", "cursor", "=", "QTextCursor", "(", "block", ")", "selection", ".", "cursor", ".", "setPosition", "(", "block", ".", "position", "(", ")", "+", "columnIndex", ")", "selection", ".", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "Right", ",", "QTextCursor", ".", "KeepAnchor", ")", "return", "selection" ]
Make matched or unmatched QTextEdit.ExtraSelection
[ "Make", "matched", "or", "unmatched", "QTextEdit", ".", "ExtraSelection" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/brackethlighter.py#L98-L113
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter._highlightBracket
def _highlightBracket(self, bracket, qpart, block, columnIndex): """Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's """ try: matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex) except _TimeoutException: # not found, time is over return[] # highlight nothing if matchedBlock is not None: self.currentMatchedBrackets = ((block, columnIndex), (matchedBlock, matchedColumnIndex)) return [self._makeMatchSelection(block, columnIndex, True), self._makeMatchSelection(matchedBlock, matchedColumnIndex, True)] else: self.currentMatchedBrackets = None return [self._makeMatchSelection(block, columnIndex, False)]
python
def _highlightBracket(self, bracket, qpart, block, columnIndex): """Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's """ try: matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex) except _TimeoutException: # not found, time is over return[] # highlight nothing if matchedBlock is not None: self.currentMatchedBrackets = ((block, columnIndex), (matchedBlock, matchedColumnIndex)) return [self._makeMatchSelection(block, columnIndex, True), self._makeMatchSelection(matchedBlock, matchedColumnIndex, True)] else: self.currentMatchedBrackets = None return [self._makeMatchSelection(block, columnIndex, False)]
[ "def", "_highlightBracket", "(", "self", ",", "bracket", ",", "qpart", ",", "block", ",", "columnIndex", ")", ":", "try", ":", "matchedBlock", ",", "matchedColumnIndex", "=", "self", ".", "_findMatchingBracket", "(", "bracket", ",", "qpart", ",", "block", ",", "columnIndex", ")", "except", "_TimeoutException", ":", "# not found, time is over", "return", "[", "]", "# highlight nothing", "if", "matchedBlock", "is", "not", "None", ":", "self", ".", "currentMatchedBrackets", "=", "(", "(", "block", ",", "columnIndex", ")", ",", "(", "matchedBlock", ",", "matchedColumnIndex", ")", ")", "return", "[", "self", ".", "_makeMatchSelection", "(", "block", ",", "columnIndex", ",", "True", ")", ",", "self", ".", "_makeMatchSelection", "(", "matchedBlock", ",", "matchedColumnIndex", ",", "True", ")", "]", "else", ":", "self", ".", "currentMatchedBrackets", "=", "None", "return", "[", "self", ".", "_makeMatchSelection", "(", "block", ",", "columnIndex", ",", "False", ")", "]" ]
Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's
[ "Highlight", "bracket", "and", "matching", "bracket", "Return", "tuple", "of", "QTextEdit", ".", "ExtraSelection", "s" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/brackethlighter.py#L115-L130
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter.extraSelections
def extraSelections(self, qpart, block, columnIndex): """List of QTextEdit.ExtraSelection's, which highlighte brackets """ blockText = block.text() if columnIndex < len(blockText) and \ blockText[columnIndex] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex): return self._highlightBracket(blockText[columnIndex], qpart, block, columnIndex) elif columnIndex > 0 and \ blockText[columnIndex - 1] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex - 1): return self._highlightBracket(blockText[columnIndex - 1], qpart, block, columnIndex - 1) else: self.currentMatchedBrackets = None return []
python
def extraSelections(self, qpart, block, columnIndex): """List of QTextEdit.ExtraSelection's, which highlighte brackets """ blockText = block.text() if columnIndex < len(blockText) and \ blockText[columnIndex] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex): return self._highlightBracket(blockText[columnIndex], qpart, block, columnIndex) elif columnIndex > 0 and \ blockText[columnIndex - 1] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex - 1): return self._highlightBracket(blockText[columnIndex - 1], qpart, block, columnIndex - 1) else: self.currentMatchedBrackets = None return []
[ "def", "extraSelections", "(", "self", ",", "qpart", ",", "block", ",", "columnIndex", ")", ":", "blockText", "=", "block", ".", "text", "(", ")", "if", "columnIndex", "<", "len", "(", "blockText", ")", "and", "blockText", "[", "columnIndex", "]", "in", "self", ".", "_ALL_BRACKETS", "and", "qpart", ".", "isCode", "(", "block", ",", "columnIndex", ")", ":", "return", "self", ".", "_highlightBracket", "(", "blockText", "[", "columnIndex", "]", ",", "qpart", ",", "block", ",", "columnIndex", ")", "elif", "columnIndex", ">", "0", "and", "blockText", "[", "columnIndex", "-", "1", "]", "in", "self", ".", "_ALL_BRACKETS", "and", "qpart", ".", "isCode", "(", "block", ",", "columnIndex", "-", "1", ")", ":", "return", "self", ".", "_highlightBracket", "(", "blockText", "[", "columnIndex", "-", "1", "]", ",", "qpart", ",", "block", ",", "columnIndex", "-", "1", ")", "else", ":", "self", ".", "currentMatchedBrackets", "=", "None", "return", "[", "]" ]
List of QTextEdit.ExtraSelection's, which highlighte brackets
[ "List", "of", "QTextEdit", ".", "ExtraSelection", "s", "which", "highlighte", "brackets" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/brackethlighter.py#L132-L147
andreikop/qutepart
qutepart/syntaxhlighter.py
_cmpFormatRanges
def _cmpFormatRanges(a, b): """PyQt does not define proper comparison for QTextLayout.FormatRange Define it to check correctly, if formats has changed. It is important for the performance """ if a.format == b.format and \ a.start == b.start and \ a.length == b.length: return 0 else: return cmp(id(a), id(b))
python
def _cmpFormatRanges(a, b): """PyQt does not define proper comparison for QTextLayout.FormatRange Define it to check correctly, if formats has changed. It is important for the performance """ if a.format == b.format and \ a.start == b.start and \ a.length == b.length: return 0 else: return cmp(id(a), id(b))
[ "def", "_cmpFormatRanges", "(", "a", ",", "b", ")", ":", "if", "a", ".", "format", "==", "b", ".", "format", "and", "a", ".", "start", "==", "b", ".", "start", "and", "a", ".", "length", "==", "b", ".", "length", ":", "return", "0", "else", ":", "return", "cmp", "(", "id", "(", "a", ")", ",", "id", "(", "b", ")", ")" ]
PyQt does not define proper comparison for QTextLayout.FormatRange Define it to check correctly, if formats has changed. It is important for the performance
[ "PyQt", "does", "not", "define", "proper", "comparison", "for", "QTextLayout", ".", "FormatRange", "Define", "it", "to", "check", "correctly", "if", "formats", "has", "changed", ".", "It", "is", "important", "for", "the", "performance" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L14-L24
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isCode
def isCode(self, block, column): """Check if character at column is a a code """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isCode(data, column)
python
def isCode(self, block, column): """Check if character at column is a a code """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isCode(data, column)
[ "def", "isCode", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isCode", "(", "data", ",", "column", ")" ]
Check if character at column is a a code
[ "Check", "if", "character", "at", "column", "is", "a", "a", "code" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L143-L148
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isComment
def isComment(self, block, column): """Check if character at column is a comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isComment(data, column)
python
def isComment(self, block, column): """Check if character at column is a comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isComment(data, column)
[ "def", "isComment", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isComment", "(", "data", ",", "column", ")" ]
Check if character at column is a comment
[ "Check", "if", "character", "at", "column", "is", "a", "comment" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L150-L155
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isBlockComment
def isBlockComment(self, block, column): """Check if character at column is a block comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isBlockComment(data, column)
python
def isBlockComment(self, block, column): """Check if character at column is a block comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isBlockComment(data, column)
[ "def", "isBlockComment", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isBlockComment", "(", "data", ",", "column", ")" ]
Check if character at column is a block comment
[ "Check", "if", "character", "at", "column", "is", "a", "block", "comment" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L157-L162
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isHereDoc
def isHereDoc(self, block, column): """Check if character at column is a here document """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isHereDoc(data, column)
python
def isHereDoc(self, block, column): """Check if character at column is a here document """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isHereDoc(data, column)
[ "def", "isHereDoc", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isHereDoc", "(", "data", ",", "column", ")" ]
Check if character at column is a here document
[ "Check", "if", "character", "at", "column", "is", "a", "here", "document" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L164-L169
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter._highlighBlocks
def _highlighBlocks(self, fromBlock, atLeastUntilBlock, timeout): endTime = time.time() + timeout block = fromBlock lineData = self._lineData(block.previous()) while block.isValid() and block != atLeastUntilBlock: if time.time() >= endTime: # time is over, schedule parsing later and release event loop self._pendingBlockNumber = block.blockNumber() self._pendingAtLeastUntilBlockNumber = atLeastUntilBlock.blockNumber() self._globalTimer.scheduleCallback(self._onContinueHighlighting) return contextStack = lineData[0] if lineData is not None else None if block.length() < 4096: lineData, highlightedSegments = self._syntax.highlightBlock(block.text(), contextStack) else: """Parser freezes for a long time, if line is too long invalid parsing results are still better, than freeze """ lineData, highlightedSegments = None, [] if lineData is not None: block.setUserData(_TextBlockUserData(lineData)) else: block.setUserData(None) self._applyHighlightedSegments(block, highlightedSegments) block = block.next() # reached atLeastUntilBlock, now parse next only while data changed prevLineData = self._lineData(block) while block.isValid(): if time.time() >= endTime: # time is over, schedule parsing later and release event loop self._pendingBlockNumber = block.blockNumber() self._pendingAtLeastUntilBlockNumber = atLeastUntilBlock.blockNumber() self._globalTimer.scheduleCallback(self._onContinueHighlighting) return contextStack = lineData[0] if lineData is not None else None lineData, highlightedSegments = self._syntax.highlightBlock(block.text(), contextStack) if lineData is not None: block.setUserData(_TextBlockUserData(lineData)) else: block.setUserData(None) self._applyHighlightedSegments(block, highlightedSegments) if prevLineData == lineData: break block = block.next() prevLineData = self._lineData(block) # sucessfully finished, reset pending tasks self._pendingBlockNumber = None self._pendingAtLeastUntilBlockNumber = None """Emit sizeChanged when highlighting finished, because document size might change. See andreikop/enki issue #191 """ documentLayout = self._textEdit.document().documentLayout() documentLayout.documentSizeChanged.emit(documentLayout.documentSize())
python
def _highlighBlocks(self, fromBlock, atLeastUntilBlock, timeout): endTime = time.time() + timeout block = fromBlock lineData = self._lineData(block.previous()) while block.isValid() and block != atLeastUntilBlock: if time.time() >= endTime: # time is over, schedule parsing later and release event loop self._pendingBlockNumber = block.blockNumber() self._pendingAtLeastUntilBlockNumber = atLeastUntilBlock.blockNumber() self._globalTimer.scheduleCallback(self._onContinueHighlighting) return contextStack = lineData[0] if lineData is not None else None if block.length() < 4096: lineData, highlightedSegments = self._syntax.highlightBlock(block.text(), contextStack) else: """Parser freezes for a long time, if line is too long invalid parsing results are still better, than freeze """ lineData, highlightedSegments = None, [] if lineData is not None: block.setUserData(_TextBlockUserData(lineData)) else: block.setUserData(None) self._applyHighlightedSegments(block, highlightedSegments) block = block.next() # reached atLeastUntilBlock, now parse next only while data changed prevLineData = self._lineData(block) while block.isValid(): if time.time() >= endTime: # time is over, schedule parsing later and release event loop self._pendingBlockNumber = block.blockNumber() self._pendingAtLeastUntilBlockNumber = atLeastUntilBlock.blockNumber() self._globalTimer.scheduleCallback(self._onContinueHighlighting) return contextStack = lineData[0] if lineData is not None else None lineData, highlightedSegments = self._syntax.highlightBlock(block.text(), contextStack) if lineData is not None: block.setUserData(_TextBlockUserData(lineData)) else: block.setUserData(None) self._applyHighlightedSegments(block, highlightedSegments) if prevLineData == lineData: break block = block.next() prevLineData = self._lineData(block) # sucessfully finished, reset pending tasks self._pendingBlockNumber = None self._pendingAtLeastUntilBlockNumber = None """Emit sizeChanged when highlighting finished, because document size might change. See andreikop/enki issue #191 """ documentLayout = self._textEdit.document().documentLayout() documentLayout.documentSizeChanged.emit(documentLayout.documentSize())
[ "def", "_highlighBlocks", "(", "self", ",", "fromBlock", ",", "atLeastUntilBlock", ",", "timeout", ")", ":", "endTime", "=", "time", ".", "time", "(", ")", "+", "timeout", "block", "=", "fromBlock", "lineData", "=", "self", ".", "_lineData", "(", "block", ".", "previous", "(", ")", ")", "while", "block", ".", "isValid", "(", ")", "and", "block", "!=", "atLeastUntilBlock", ":", "if", "time", ".", "time", "(", ")", ">=", "endTime", ":", "# time is over, schedule parsing later and release event loop", "self", ".", "_pendingBlockNumber", "=", "block", ".", "blockNumber", "(", ")", "self", ".", "_pendingAtLeastUntilBlockNumber", "=", "atLeastUntilBlock", ".", "blockNumber", "(", ")", "self", ".", "_globalTimer", ".", "scheduleCallback", "(", "self", ".", "_onContinueHighlighting", ")", "return", "contextStack", "=", "lineData", "[", "0", "]", "if", "lineData", "is", "not", "None", "else", "None", "if", "block", ".", "length", "(", ")", "<", "4096", ":", "lineData", ",", "highlightedSegments", "=", "self", ".", "_syntax", ".", "highlightBlock", "(", "block", ".", "text", "(", ")", ",", "contextStack", ")", "else", ":", "\"\"\"Parser freezes for a long time, if line is too long\n invalid parsing results are still better, than freeze\n \"\"\"", "lineData", ",", "highlightedSegments", "=", "None", ",", "[", "]", "if", "lineData", "is", "not", "None", ":", "block", ".", "setUserData", "(", "_TextBlockUserData", "(", "lineData", ")", ")", "else", ":", "block", ".", "setUserData", "(", "None", ")", "self", ".", "_applyHighlightedSegments", "(", "block", ",", "highlightedSegments", ")", "block", "=", "block", ".", "next", "(", ")", "# reached atLeastUntilBlock, now parse next only while data changed", "prevLineData", "=", "self", ".", "_lineData", "(", "block", ")", "while", "block", ".", "isValid", "(", ")", ":", "if", "time", ".", "time", "(", ")", ">=", "endTime", ":", "# time is over, schedule parsing later and release event loop", "self", ".", "_pendingBlockNumber", "=", "block", ".", "blockNumber", "(", ")", "self", ".", "_pendingAtLeastUntilBlockNumber", "=", "atLeastUntilBlock", ".", "blockNumber", "(", ")", "self", ".", "_globalTimer", ".", "scheduleCallback", "(", "self", ".", "_onContinueHighlighting", ")", "return", "contextStack", "=", "lineData", "[", "0", "]", "if", "lineData", "is", "not", "None", "else", "None", "lineData", ",", "highlightedSegments", "=", "self", ".", "_syntax", ".", "highlightBlock", "(", "block", ".", "text", "(", ")", ",", "contextStack", ")", "if", "lineData", "is", "not", "None", ":", "block", ".", "setUserData", "(", "_TextBlockUserData", "(", "lineData", ")", ")", "else", ":", "block", ".", "setUserData", "(", "None", ")", "self", ".", "_applyHighlightedSegments", "(", "block", ",", "highlightedSegments", ")", "if", "prevLineData", "==", "lineData", ":", "break", "block", "=", "block", ".", "next", "(", ")", "prevLineData", "=", "self", ".", "_lineData", "(", "block", ")", "# sucessfully finished, reset pending tasks", "self", ".", "_pendingBlockNumber", "=", "None", "self", ".", "_pendingAtLeastUntilBlockNumber", "=", "None", "documentLayout", "=", "self", ".", "_textEdit", ".", "document", "(", ")", ".", "documentLayout", "(", ")", "documentLayout", ".", "documentSizeChanged", ".", "emit", "(", "documentLayout", ".", "documentSize", "(", ")", ")" ]
Emit sizeChanged when highlighting finished, because document size might change. See andreikop/enki issue #191
[ "Emit", "sizeChanged", "when", "highlighting", "finished", "because", "document", "size", "might", "change", ".", "See", "andreikop", "/", "enki", "issue", "#191" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L219-L278
andreikop/qutepart
qutepart/indenter/lisp.py
IndentAlgLisp.computeSmartIndent
def computeSmartIndent(self, block, ch): """special rules: ;;; -> indent 0 ;; -> align with next line, if possible ; -> usually on the same line as code -> ignore """ if re.search(r'^\s*;;;', block.text()): return '' elif re.search(r'^\s*;;', block.text()): #try to align with the next line nextBlock = self._nextNonEmptyBlock(block) if nextBlock.isValid(): return self._blockIndent(nextBlock) try: foundBlock, foundColumn = self.findBracketBackward(block, 0, '(') except ValueError: return '' else: return self._increaseIndent(self._blockIndent(foundBlock))
python
def computeSmartIndent(self, block, ch): """special rules: ;;; -> indent 0 ;; -> align with next line, if possible ; -> usually on the same line as code -> ignore """ if re.search(r'^\s*;;;', block.text()): return '' elif re.search(r'^\s*;;', block.text()): #try to align with the next line nextBlock = self._nextNonEmptyBlock(block) if nextBlock.isValid(): return self._blockIndent(nextBlock) try: foundBlock, foundColumn = self.findBracketBackward(block, 0, '(') except ValueError: return '' else: return self._increaseIndent(self._blockIndent(foundBlock))
[ "def", "computeSmartIndent", "(", "self", ",", "block", ",", "ch", ")", ":", "if", "re", ".", "search", "(", "r'^\\s*;;;'", ",", "block", ".", "text", "(", ")", ")", ":", "return", "''", "elif", "re", ".", "search", "(", "r'^\\s*;;'", ",", "block", ".", "text", "(", ")", ")", ":", "#try to align with the next line", "nextBlock", "=", "self", ".", "_nextNonEmptyBlock", "(", "block", ")", "if", "nextBlock", ".", "isValid", "(", ")", ":", "return", "self", ".", "_blockIndent", "(", "nextBlock", ")", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "findBracketBackward", "(", "block", ",", "0", ",", "'('", ")", "except", "ValueError", ":", "return", "''", "else", ":", "return", "self", ".", "_increaseIndent", "(", "self", ".", "_blockIndent", "(", "foundBlock", ")", ")" ]
special rules: ;;; -> indent 0 ;; -> align with next line, if possible ; -> usually on the same line as code -> ignore
[ "special", "rules", ":", ";;;", "-", ">", "indent", "0", ";;", "-", ">", "align", "with", "next", "line", "if", "possible", ";", "-", ">", "usually", "on", "the", "same", "line", "as", "code", "-", ">", "ignore" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/lisp.py#L8-L26
andreikop/qutepart
qutepart/lines.py
Lines._atomicModification
def _atomicModification(func): """Decorator Make document modification atomic """ def wrapper(*args, **kwargs): self = args[0] with self._qpart: func(*args, **kwargs) return wrapper
python
def _atomicModification(func): """Decorator Make document modification atomic """ def wrapper(*args, **kwargs): self = args[0] with self._qpart: func(*args, **kwargs) return wrapper
[ "def", "_atomicModification", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "with", "self", ".", "_qpart", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Decorator Make document modification atomic
[ "Decorator", "Make", "document", "modification", "atomic" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L21-L29
andreikop/qutepart
qutepart/lines.py
Lines._checkAndConvertIndex
def _checkAndConvertIndex(self, index): """Check integer index, convert from less than zero notation """ if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
python
def _checkAndConvertIndex(self, index): """Check integer index, convert from less than zero notation """ if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
[ "def", "_checkAndConvertIndex", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", ":", "index", "=", "len", "(", "self", ")", "+", "index", "if", "index", "<", "0", "or", "index", ">=", "self", ".", "_doc", ".", "blockCount", "(", ")", ":", "raise", "IndexError", "(", "'Invalid block index'", ",", "index", ")", "return", "index" ]
Check integer index, convert from less than zero notation
[ "Check", "integer", "index", "convert", "from", "less", "than", "zero", "notation" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L47-L54
andreikop/qutepart
qutepart/lines.py
Lines.append
def append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
python
def append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
[ "def", "append", "(", "self", ",", "text", ")", ":", "cursor", "=", "QTextCursor", "(", "self", ".", "_doc", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "End", ")", "cursor", ".", "insertBlock", "(", ")", "cursor", ".", "insertText", "(", "text", ")" ]
Append line to the end
[ "Append", "line", "to", "the", "end" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L153-L159
andreikop/qutepart
qutepart/lines.py
Lines.insert
def insert(self, index, text): """Insert line to the document """ if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(text) cursor.insertBlock() elif index != self._doc.blockCount(): # not the last cursor = QTextCursor(self._doc.findBlockByNumber(index).previous()) cursor.movePosition(QTextCursor.EndOfBlock) cursor.insertBlock() cursor.insertText(text) else: # last append to the end self.append(text)
python
def insert(self, index, text): """Insert line to the document """ if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(text) cursor.insertBlock() elif index != self._doc.blockCount(): # not the last cursor = QTextCursor(self._doc.findBlockByNumber(index).previous()) cursor.movePosition(QTextCursor.EndOfBlock) cursor.insertBlock() cursor.insertText(text) else: # last append to the end self.append(text)
[ "def", "insert", "(", "self", ",", "index", ",", "text", ")", ":", "if", "index", "<", "0", "or", "index", ">", "self", ".", "_doc", ".", "blockCount", "(", ")", ":", "raise", "IndexError", "(", "'Invalid block index'", ",", "index", ")", "if", "index", "==", "0", ":", "# first", "cursor", "=", "QTextCursor", "(", "self", ".", "_doc", ".", "firstBlock", "(", ")", ")", "cursor", ".", "insertText", "(", "text", ")", "cursor", ".", "insertBlock", "(", ")", "elif", "index", "!=", "self", ".", "_doc", ".", "blockCount", "(", ")", ":", "# not the last", "cursor", "=", "QTextCursor", "(", "self", ".", "_doc", ".", "findBlockByNumber", "(", "index", ")", ".", "previous", "(", ")", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "EndOfBlock", ")", "cursor", ".", "insertBlock", "(", ")", "cursor", ".", "insertText", "(", "text", ")", "else", ":", "# last append to the end", "self", ".", "append", "(", "text", ")" ]
Insert line to the document
[ "Insert", "line", "to", "the", "document" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L162-L178
andreikop/qutepart
qutepart/indenter/xmlindent.py
IndentAlgXml.computeSmartIndent
def computeSmartIndent(self, block, char): """Compute indent for the block """ lineText = block.text() prevLineText = self._prevNonEmptyBlock(block).text() alignOnly = char == '' if alignOnly: # XML might be all in one line, in which case we want to break that up. tokens = re.split(r'>\s*<', lineText) if len(tokens) > 1: prevIndent = self._lineIndent(prevLineText) for index, newLine in enumerate(tokens): if index > 0: newLine = '<' + newLine if index < len(tokens) - 1: newLine = newLine + '>' if re.match(r'^\s*</', newLine): char = '/' elif re.match(r'\\>[^<>]*$', newLine): char = '>' else: char = '\n' indentation = self.processChar(newLine, prevLineText, char) newLine = indentation + newLine tokens[index] = newLine prevLineText = newLine; self._qpart.lines[block.blockNumber()] = '\n'.join(tokens) return None else: # no tokens, do not split line, just compute indent if re.search(r'^\s*</', lineText): char = '/' elif re.search(r'>[^<>]*', lineText): char = '>' else: char = '\n' return self.processChar(lineText, prevLineText, char)
python
def computeSmartIndent(self, block, char): """Compute indent for the block """ lineText = block.text() prevLineText = self._prevNonEmptyBlock(block).text() alignOnly = char == '' if alignOnly: # XML might be all in one line, in which case we want to break that up. tokens = re.split(r'>\s*<', lineText) if len(tokens) > 1: prevIndent = self._lineIndent(prevLineText) for index, newLine in enumerate(tokens): if index > 0: newLine = '<' + newLine if index < len(tokens) - 1: newLine = newLine + '>' if re.match(r'^\s*</', newLine): char = '/' elif re.match(r'\\>[^<>]*$', newLine): char = '>' else: char = '\n' indentation = self.processChar(newLine, prevLineText, char) newLine = indentation + newLine tokens[index] = newLine prevLineText = newLine; self._qpart.lines[block.blockNumber()] = '\n'.join(tokens) return None else: # no tokens, do not split line, just compute indent if re.search(r'^\s*</', lineText): char = '/' elif re.search(r'>[^<>]*', lineText): char = '>' else: char = '\n' return self.processChar(lineText, prevLineText, char)
[ "def", "computeSmartIndent", "(", "self", ",", "block", ",", "char", ")", ":", "lineText", "=", "block", ".", "text", "(", ")", "prevLineText", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", ".", "text", "(", ")", "alignOnly", "=", "char", "==", "''", "if", "alignOnly", ":", "# XML might be all in one line, in which case we want to break that up.", "tokens", "=", "re", ".", "split", "(", "r'>\\s*<'", ",", "lineText", ")", "if", "len", "(", "tokens", ")", ">", "1", ":", "prevIndent", "=", "self", ".", "_lineIndent", "(", "prevLineText", ")", "for", "index", ",", "newLine", "in", "enumerate", "(", "tokens", ")", ":", "if", "index", ">", "0", ":", "newLine", "=", "'<'", "+", "newLine", "if", "index", "<", "len", "(", "tokens", ")", "-", "1", ":", "newLine", "=", "newLine", "+", "'>'", "if", "re", ".", "match", "(", "r'^\\s*</'", ",", "newLine", ")", ":", "char", "=", "'/'", "elif", "re", ".", "match", "(", "r'\\\\>[^<>]*$'", ",", "newLine", ")", ":", "char", "=", "'>'", "else", ":", "char", "=", "'\\n'", "indentation", "=", "self", ".", "processChar", "(", "newLine", ",", "prevLineText", ",", "char", ")", "newLine", "=", "indentation", "+", "newLine", "tokens", "[", "index", "]", "=", "newLine", "prevLineText", "=", "newLine", "self", ".", "_qpart", ".", "lines", "[", "block", ".", "blockNumber", "(", ")", "]", "=", "'\\n'", ".", "join", "(", "tokens", ")", "return", "None", "else", ":", "# no tokens, do not split line, just compute indent", "if", "re", ".", "search", "(", "r'^\\s*</'", ",", "lineText", ")", ":", "char", "=", "'/'", "elif", "re", ".", "search", "(", "r'>[^<>]*'", ",", "lineText", ")", ":", "char", "=", "'>'", "else", ":", "char", "=", "'\\n'", "return", "self", ".", "processChar", "(", "lineText", ",", "prevLineText", ",", "char", ")" ]
Compute indent for the block
[ "Compute", "indent", "for", "the", "block" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/xmlindent.py#L10-L55
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby._prevNonCommentBlock
def _prevNonCommentBlock(self, block): """Return the closest non-empty line, ignoring comments (result <= line). Return -1 if the document """ block = self._prevNonEmptyBlock(block) while block.isValid() and self._isCommentBlock(block): block = self._prevNonEmptyBlock(block) return block
python
def _prevNonCommentBlock(self, block): """Return the closest non-empty line, ignoring comments (result <= line). Return -1 if the document """ block = self._prevNonEmptyBlock(block) while block.isValid() and self._isCommentBlock(block): block = self._prevNonEmptyBlock(block) return block
[ "def", "_prevNonCommentBlock", "(", "self", ",", "block", ")", ":", "block", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", "while", "block", ".", "isValid", "(", ")", "and", "self", ".", "_isCommentBlock", "(", "block", ")", ":", "block", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", "return", "block" ]
Return the closest non-empty line, ignoring comments (result <= line). Return -1 if the document
[ "Return", "the", "closest", "non", "-", "empty", "line", "ignoring", "comments", "(", "result", "<", "=", "line", ")", ".", "Return", "-", "1", "if", "the", "document" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L77-L84
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby._isLastCodeColumn
def _isLastCodeColumn(self, block, column): """Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment. """ return column >= self._lastColumn(block) or \ self._isComment(block, self._nextNonSpaceColumn(block, column + 1))
python
def _isLastCodeColumn(self, block, column): """Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment. """ return column >= self._lastColumn(block) or \ self._isComment(block, self._nextNonSpaceColumn(block, column + 1))
[ "def", "_isLastCodeColumn", "(", "self", ",", "block", ",", "column", ")", ":", "return", "column", ">=", "self", ".", "_lastColumn", "(", "block", ")", "or", "self", ".", "_isComment", "(", "block", ",", "self", ".", "_nextNonSpaceColumn", "(", "block", ",", "column", "+", "1", ")", ")" ]
Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment.
[ "Return", "true", "if", "the", "given", "column", "is", "at", "least", "equal", "to", "the", "column", "that", "contains", "the", "last", "non", "-", "whitespace", "character", "at", "the", "given", "line", "or", "if", "the", "rest", "of", "the", "line", "is", "a", "comment", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L90-L96
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby.lastAnchor
def lastAnchor(self, block, column): """Find the last open bracket before the current line. Return (block, column, char) or (None, None, None) """ currentPos = -1 currentBlock = None currentColumn = None currentChar = None for char in '({[': try: foundBlock, foundColumn = self.findBracketBackward(block, column, char) except ValueError: continue else: pos = foundBlock.position() + foundColumn if pos > currentPos: currentBlock = foundBlock currentColumn = foundColumn currentChar = char currentPos = pos return currentBlock, currentColumn, currentChar
python
def lastAnchor(self, block, column): """Find the last open bracket before the current line. Return (block, column, char) or (None, None, None) """ currentPos = -1 currentBlock = None currentColumn = None currentChar = None for char in '({[': try: foundBlock, foundColumn = self.findBracketBackward(block, column, char) except ValueError: continue else: pos = foundBlock.position() + foundColumn if pos > currentPos: currentBlock = foundBlock currentColumn = foundColumn currentChar = char currentPos = pos return currentBlock, currentColumn, currentChar
[ "def", "lastAnchor", "(", "self", ",", "block", ",", "column", ")", ":", "currentPos", "=", "-", "1", "currentBlock", "=", "None", "currentColumn", "=", "None", "currentChar", "=", "None", "for", "char", "in", "'({['", ":", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "findBracketBackward", "(", "block", ",", "column", ",", "char", ")", "except", "ValueError", ":", "continue", "else", ":", "pos", "=", "foundBlock", ".", "position", "(", ")", "+", "foundColumn", "if", "pos", ">", "currentPos", ":", "currentBlock", "=", "foundBlock", "currentColumn", "=", "foundColumn", "currentChar", "=", "char", "currentPos", "=", "pos", "return", "currentBlock", ",", "currentColumn", ",", "currentChar" ]
Find the last open bracket before the current line. Return (block, column, char) or (None, None, None)
[ "Find", "the", "last", "open", "bracket", "before", "the", "current", "line", ".", "Return", "(", "block", "column", "char", ")", "or", "(", "None", "None", "None", ")" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L119-L140
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby.findStmtStart
def findStmtStart(self, block): """Return the first line that is not preceded by a "continuing" line. Return currBlock if currBlock <= 0 """ prevBlock = self._prevNonCommentBlock(block) while prevBlock.isValid() and \ (((prevBlock == block.previous()) and self._isBlockContinuing(prevBlock)) or \ self.isStmtContinuing(prevBlock)): block = prevBlock prevBlock = self._prevNonCommentBlock(block) return block
python
def findStmtStart(self, block): """Return the first line that is not preceded by a "continuing" line. Return currBlock if currBlock <= 0 """ prevBlock = self._prevNonCommentBlock(block) while prevBlock.isValid() and \ (((prevBlock == block.previous()) and self._isBlockContinuing(prevBlock)) or \ self.isStmtContinuing(prevBlock)): block = prevBlock prevBlock = self._prevNonCommentBlock(block) return block
[ "def", "findStmtStart", "(", "self", ",", "block", ")", ":", "prevBlock", "=", "self", ".", "_prevNonCommentBlock", "(", "block", ")", "while", "prevBlock", ".", "isValid", "(", ")", "and", "(", "(", "(", "prevBlock", "==", "block", ".", "previous", "(", ")", ")", "and", "self", ".", "_isBlockContinuing", "(", "prevBlock", ")", ")", "or", "self", ".", "isStmtContinuing", "(", "prevBlock", ")", ")", ":", "block", "=", "prevBlock", "prevBlock", "=", "self", ".", "_prevNonCommentBlock", "(", "block", ")", "return", "block" ]
Return the first line that is not preceded by a "continuing" line. Return currBlock if currBlock <= 0
[ "Return", "the", "first", "line", "that", "is", "not", "preceded", "by", "a", "continuing", "line", ".", "Return", "currBlock", "if", "currBlock", "<", "=", "0" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L153-L163
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby._isValidTrigger
def _isValidTrigger(block, ch): """check if the trigger characters are in the right context, otherwise running the indenter might be annoying to the user """ if ch == "" or ch == "\n": return True # Explicit align or new line match = rxUnindent.match(block.text()) return match is not None and \ match.group(3) == ""
python
def _isValidTrigger(block, ch): """check if the trigger characters are in the right context, otherwise running the indenter might be annoying to the user """ if ch == "" or ch == "\n": return True # Explicit align or new line match = rxUnindent.match(block.text()) return match is not None and \ match.group(3) == ""
[ "def", "_isValidTrigger", "(", "block", ",", "ch", ")", ":", "if", "ch", "==", "\"\"", "or", "ch", "==", "\"\\n\"", ":", "return", "True", "# Explicit align or new line", "match", "=", "rxUnindent", ".", "match", "(", "block", ".", "text", "(", ")", ")", "return", "match", "is", "not", "None", "and", "match", ".", "group", "(", "3", ")", "==", "\"\"" ]
check if the trigger characters are in the right context, otherwise running the indenter might be annoying to the user
[ "check", "if", "the", "trigger", "characters", "are", "in", "the", "right", "context", "otherwise", "running", "the", "indenter", "might", "be", "annoying", "to", "the", "user" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L166-L175
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby.findPrevStmt
def findPrevStmt(self, block): """Returns a tuple that contains the first and last line of the previous statement before line. """ stmtEnd = self._prevNonCommentBlock(block) stmtStart = self.findStmtStart(stmtEnd) return Statement(self._qpart, stmtStart, stmtEnd)
python
def findPrevStmt(self, block): """Returns a tuple that contains the first and last line of the previous statement before line. """ stmtEnd = self._prevNonCommentBlock(block) stmtStart = self.findStmtStart(stmtEnd) return Statement(self._qpart, stmtStart, stmtEnd)
[ "def", "findPrevStmt", "(", "self", ",", "block", ")", ":", "stmtEnd", "=", "self", ".", "_prevNonCommentBlock", "(", "block", ")", "stmtStart", "=", "self", ".", "findStmtStart", "(", "stmtEnd", ")", "return", "Statement", "(", "self", ".", "_qpart", ",", "stmtStart", ",", "stmtEnd", ")" ]
Returns a tuple that contains the first and last line of the previous statement before line.
[ "Returns", "a", "tuple", "that", "contains", "the", "first", "and", "last", "line", "of", "the", "previous", "statement", "before", "line", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L177-L183
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby.computeSmartIndent
def computeSmartIndent(self, block, ch): """indent gets three arguments: line, indentWidth in spaces, typed character indent """ if not self._isValidTrigger(block, ch): return None prevStmt = self.findPrevStmt(block) if not prevStmt.endBlock.isValid(): return None # Can't indent the first line prevBlock = self._prevNonEmptyBlock(block) # HACK Detect here documents if self._qpart.isHereDoc(prevBlock.blockNumber(), prevBlock.length() - 2): return None # HACK Detect embedded comments if self._qpart.isBlockComment(prevBlock.blockNumber(), prevBlock.length() - 2): return None prevStmtCnt = prevStmt.content() prevStmtInd = prevStmt.indent() # Are we inside a parameter list, array or hash? foundBlock, foundColumn, foundChar = self.lastAnchor(block, 0) if foundBlock is not None: shouldIndent = foundBlock == prevStmt.endBlock or \ self.testAtEnd(prevStmt, re.compile(',\s*')) if (not self._isLastCodeColumn(foundBlock, foundColumn)) or \ self.lastAnchor(foundBlock, foundColumn)[0] is not None: # TODO This is alignment, should force using spaces instead of tabs: if shouldIndent: foundColumn += 1 nextCol = self._nextNonSpaceColumn(foundBlock, foundColumn) if nextCol > 0 and \ (not self._isComment(foundBlock, nextCol)): foundColumn = nextCol # Keep indent of previous statement, while aligning to the anchor column if len(prevStmtInd) > foundColumn: return prevStmtInd else: return self._makeIndentAsColumn(foundBlock, foundColumn) else: indent = self._blockIndent(foundBlock) if shouldIndent: indent = self._increaseIndent(indent) return indent # Handle indenting of multiline statements. if (prevStmt.endBlock == block.previous() and \ self._isBlockContinuing(prevStmt.endBlock)) or \ self.isStmtContinuing(prevStmt.endBlock): if prevStmt.startBlock == prevStmt.endBlock: if ch == '' and \ len(self._blockIndent(block)) > len(self._blockIndent(prevStmt.endBlock)): return None # Don't force a specific indent level when aligning manually return self._increaseIndent(self._increaseIndent(prevStmtInd)) else: return self._blockIndent(prevStmt.endBlock) if rxUnindent.match(block.text()): startStmt = self.findBlockStart(block) if startStmt.startBlock.isValid(): return startStmt.indent() else: return None if self.isBlockStart(prevStmt) and not rxBlockEnd.search(prevStmt.content()): return self._increaseIndent(prevStmtInd) elif re.search(r'[\[\{]\s*$', prevStmtCnt) is not None: return self._increaseIndent(prevStmtInd) # Keep current return prevStmtInd
python
def computeSmartIndent(self, block, ch): """indent gets three arguments: line, indentWidth in spaces, typed character indent """ if not self._isValidTrigger(block, ch): return None prevStmt = self.findPrevStmt(block) if not prevStmt.endBlock.isValid(): return None # Can't indent the first line prevBlock = self._prevNonEmptyBlock(block) # HACK Detect here documents if self._qpart.isHereDoc(prevBlock.blockNumber(), prevBlock.length() - 2): return None # HACK Detect embedded comments if self._qpart.isBlockComment(prevBlock.blockNumber(), prevBlock.length() - 2): return None prevStmtCnt = prevStmt.content() prevStmtInd = prevStmt.indent() # Are we inside a parameter list, array or hash? foundBlock, foundColumn, foundChar = self.lastAnchor(block, 0) if foundBlock is not None: shouldIndent = foundBlock == prevStmt.endBlock or \ self.testAtEnd(prevStmt, re.compile(',\s*')) if (not self._isLastCodeColumn(foundBlock, foundColumn)) or \ self.lastAnchor(foundBlock, foundColumn)[0] is not None: # TODO This is alignment, should force using spaces instead of tabs: if shouldIndent: foundColumn += 1 nextCol = self._nextNonSpaceColumn(foundBlock, foundColumn) if nextCol > 0 and \ (not self._isComment(foundBlock, nextCol)): foundColumn = nextCol # Keep indent of previous statement, while aligning to the anchor column if len(prevStmtInd) > foundColumn: return prevStmtInd else: return self._makeIndentAsColumn(foundBlock, foundColumn) else: indent = self._blockIndent(foundBlock) if shouldIndent: indent = self._increaseIndent(indent) return indent # Handle indenting of multiline statements. if (prevStmt.endBlock == block.previous() and \ self._isBlockContinuing(prevStmt.endBlock)) or \ self.isStmtContinuing(prevStmt.endBlock): if prevStmt.startBlock == prevStmt.endBlock: if ch == '' and \ len(self._blockIndent(block)) > len(self._blockIndent(prevStmt.endBlock)): return None # Don't force a specific indent level when aligning manually return self._increaseIndent(self._increaseIndent(prevStmtInd)) else: return self._blockIndent(prevStmt.endBlock) if rxUnindent.match(block.text()): startStmt = self.findBlockStart(block) if startStmt.startBlock.isValid(): return startStmt.indent() else: return None if self.isBlockStart(prevStmt) and not rxBlockEnd.search(prevStmt.content()): return self._increaseIndent(prevStmtInd) elif re.search(r'[\[\{]\s*$', prevStmtCnt) is not None: return self._increaseIndent(prevStmtInd) # Keep current return prevStmtInd
[ "def", "computeSmartIndent", "(", "self", ",", "block", ",", "ch", ")", ":", "if", "not", "self", ".", "_isValidTrigger", "(", "block", ",", "ch", ")", ":", "return", "None", "prevStmt", "=", "self", ".", "findPrevStmt", "(", "block", ")", "if", "not", "prevStmt", ".", "endBlock", ".", "isValid", "(", ")", ":", "return", "None", "# Can't indent the first line", "prevBlock", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", "# HACK Detect here documents", "if", "self", ".", "_qpart", ".", "isHereDoc", "(", "prevBlock", ".", "blockNumber", "(", ")", ",", "prevBlock", ".", "length", "(", ")", "-", "2", ")", ":", "return", "None", "# HACK Detect embedded comments", "if", "self", ".", "_qpart", ".", "isBlockComment", "(", "prevBlock", ".", "blockNumber", "(", ")", ",", "prevBlock", ".", "length", "(", ")", "-", "2", ")", ":", "return", "None", "prevStmtCnt", "=", "prevStmt", ".", "content", "(", ")", "prevStmtInd", "=", "prevStmt", ".", "indent", "(", ")", "# Are we inside a parameter list, array or hash?", "foundBlock", ",", "foundColumn", ",", "foundChar", "=", "self", ".", "lastAnchor", "(", "block", ",", "0", ")", "if", "foundBlock", "is", "not", "None", ":", "shouldIndent", "=", "foundBlock", "==", "prevStmt", ".", "endBlock", "or", "self", ".", "testAtEnd", "(", "prevStmt", ",", "re", ".", "compile", "(", "',\\s*'", ")", ")", "if", "(", "not", "self", ".", "_isLastCodeColumn", "(", "foundBlock", ",", "foundColumn", ")", ")", "or", "self", ".", "lastAnchor", "(", "foundBlock", ",", "foundColumn", ")", "[", "0", "]", "is", "not", "None", ":", "# TODO This is alignment, should force using spaces instead of tabs:", "if", "shouldIndent", ":", "foundColumn", "+=", "1", "nextCol", "=", "self", ".", "_nextNonSpaceColumn", "(", "foundBlock", ",", "foundColumn", ")", "if", "nextCol", ">", "0", "and", "(", "not", "self", ".", "_isComment", "(", "foundBlock", ",", "nextCol", ")", ")", ":", "foundColumn", "=", "nextCol", "# Keep indent of previous statement, while aligning to the anchor column", "if", "len", "(", "prevStmtInd", ")", ">", "foundColumn", ":", "return", "prevStmtInd", "else", ":", "return", "self", ".", "_makeIndentAsColumn", "(", "foundBlock", ",", "foundColumn", ")", "else", ":", "indent", "=", "self", ".", "_blockIndent", "(", "foundBlock", ")", "if", "shouldIndent", ":", "indent", "=", "self", ".", "_increaseIndent", "(", "indent", ")", "return", "indent", "# Handle indenting of multiline statements.", "if", "(", "prevStmt", ".", "endBlock", "==", "block", ".", "previous", "(", ")", "and", "self", ".", "_isBlockContinuing", "(", "prevStmt", ".", "endBlock", ")", ")", "or", "self", ".", "isStmtContinuing", "(", "prevStmt", ".", "endBlock", ")", ":", "if", "prevStmt", ".", "startBlock", "==", "prevStmt", ".", "endBlock", ":", "if", "ch", "==", "''", "and", "len", "(", "self", ".", "_blockIndent", "(", "block", ")", ")", ">", "len", "(", "self", ".", "_blockIndent", "(", "prevStmt", ".", "endBlock", ")", ")", ":", "return", "None", "# Don't force a specific indent level when aligning manually", "return", "self", ".", "_increaseIndent", "(", "self", ".", "_increaseIndent", "(", "prevStmtInd", ")", ")", "else", ":", "return", "self", ".", "_blockIndent", "(", "prevStmt", ".", "endBlock", ")", "if", "rxUnindent", ".", "match", "(", "block", ".", "text", "(", ")", ")", ":", "startStmt", "=", "self", ".", "findBlockStart", "(", "block", ")", "if", "startStmt", ".", "startBlock", ".", "isValid", "(", ")", ":", "return", "startStmt", ".", "indent", "(", ")", "else", ":", "return", "None", "if", "self", ".", "isBlockStart", "(", "prevStmt", ")", "and", "not", "rxBlockEnd", ".", "search", "(", "prevStmt", ".", "content", "(", ")", ")", ":", "return", "self", ".", "_increaseIndent", "(", "prevStmtInd", ")", "elif", "re", ".", "search", "(", "r'[\\[\\{]\\s*$'", ",", "prevStmtCnt", ")", "is", "not", "None", ":", "return", "self", ".", "_increaseIndent", "(", "prevStmtInd", ")", "# Keep current", "return", "prevStmtInd" ]
indent gets three arguments: line, indentWidth in spaces, typed character indent
[ "indent", "gets", "three", "arguments", ":", "line", "indentWidth", "in", "spaces", "typed", "character", "indent" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L213-L288
andreikop/qutepart
qutepart/htmldelegate.py
HTMLDelegate.paint
def paint(self, painter, option, index): """QStyledItemDelegate.paint implementation """ option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItem(option) self.initStyleOption(options,index) style = QApplication.style() if options.widget is None else options.widget.style() doc = QTextDocument() doc.setDocumentMargin(1) doc.setHtml(options.text) if options.widget is not None: doc.setDefaultFont(options.widget.font()) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter); ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) """Original example contained line painter.setClipRect(textRect.translated(-textRect.topLeft())) but text is drawn clipped with it on kubuntu 12.04 """ doc.documentLayout().draw(painter, ctx) painter.restore()
python
def paint(self, painter, option, index): """QStyledItemDelegate.paint implementation """ option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItem(option) self.initStyleOption(options,index) style = QApplication.style() if options.widget is None else options.widget.style() doc = QTextDocument() doc.setDocumentMargin(1) doc.setHtml(options.text) if options.widget is not None: doc.setDefaultFont(options.widget.font()) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter); ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) """Original example contained line painter.setClipRect(textRect.translated(-textRect.topLeft())) but text is drawn clipped with it on kubuntu 12.04 """ doc.documentLayout().draw(painter, ctx) painter.restore()
[ "def", "paint", "(", "self", ",", "painter", ",", "option", ",", "index", ")", ":", "option", ".", "state", "&=", "~", "QStyle", ".", "State_HasFocus", "# never draw focus rect", "options", "=", "QStyleOptionViewItem", "(", "option", ")", "self", ".", "initStyleOption", "(", "options", ",", "index", ")", "style", "=", "QApplication", ".", "style", "(", ")", "if", "options", ".", "widget", "is", "None", "else", "options", ".", "widget", ".", "style", "(", ")", "doc", "=", "QTextDocument", "(", ")", "doc", ".", "setDocumentMargin", "(", "1", ")", "doc", ".", "setHtml", "(", "options", ".", "text", ")", "if", "options", ".", "widget", "is", "not", "None", ":", "doc", ".", "setDefaultFont", "(", "options", ".", "widget", ".", "font", "(", ")", ")", "# bad long (multiline) strings processing doc.setTextWidth(options.rect.width())", "options", ".", "text", "=", "\"\"", "style", ".", "drawControl", "(", "QStyle", ".", "CE_ItemViewItem", ",", "options", ",", "painter", ")", "ctx", "=", "QAbstractTextDocumentLayout", ".", "PaintContext", "(", ")", "# Highlighting text if item is selected", "if", "option", ".", "state", "&", "QStyle", ".", "State_Selected", ":", "ctx", ".", "palette", ".", "setColor", "(", "QPalette", ".", "Text", ",", "option", ".", "palette", ".", "color", "(", "QPalette", ".", "Active", ",", "QPalette", ".", "HighlightedText", ")", ")", "textRect", "=", "style", ".", "subElementRect", "(", "QStyle", ".", "SE_ItemViewItemText", ",", "options", ")", "painter", ".", "save", "(", ")", "painter", ".", "translate", "(", "textRect", ".", "topLeft", "(", ")", ")", "\"\"\"Original example contained line\n painter.setClipRect(textRect.translated(-textRect.topLeft()))\n but text is drawn clipped with it on kubuntu 12.04\n \"\"\"", "doc", ".", "documentLayout", "(", ")", ".", "draw", "(", "painter", ",", "ctx", ")", "painter", ".", "restore", "(", ")" ]
QStyledItemDelegate.paint implementation
[ "QStyledItemDelegate", ".", "paint", "implementation" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/htmldelegate.py#L36-L71
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.isDeleteKeyEvent
def isDeleteKeyEvent(self, keyEvent): """Check if key event should be handled as Delete command""" return self._start is not None and \ (keyEvent.matches(QKeySequence.Delete) or \ (keyEvent.key() == Qt.Key_Backspace and keyEvent.modifiers() == Qt.NoModifier))
python
def isDeleteKeyEvent(self, keyEvent): """Check if key event should be handled as Delete command""" return self._start is not None and \ (keyEvent.matches(QKeySequence.Delete) or \ (keyEvent.key() == Qt.Key_Backspace and keyEvent.modifiers() == Qt.NoModifier))
[ "def", "isDeleteKeyEvent", "(", "self", ",", "keyEvent", ")", ":", "return", "self", ".", "_start", "is", "not", "None", "and", "(", "keyEvent", ".", "matches", "(", "QKeySequence", ".", "Delete", ")", "or", "(", "keyEvent", ".", "key", "(", ")", "==", "Qt", ".", "Key_Backspace", "and", "keyEvent", ".", "modifiers", "(", ")", "==", "Qt", ".", "NoModifier", ")", ")" ]
Check if key event should be handled as Delete command
[ "Check", "if", "key", "event", "should", "be", "handled", "as", "Delete", "command" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L35-L39
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.delete
def delete(self): """Del or Backspace pressed. Delete selection""" with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
python
def delete(self): """Del or Backspace pressed. Delete selection""" with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
[ "def", "delete", "(", "self", ")", ":", "with", "self", ".", "_qpart", ":", "for", "cursor", "in", "self", ".", "cursors", "(", ")", ":", "if", "cursor", ".", "hasSelection", "(", ")", ":", "cursor", ".", "deleteChar", "(", ")" ]
Del or Backspace pressed. Delete selection
[ "Del", "or", "Backspace", "pressed", ".", "Delete", "selection" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L41-L46
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.isExpandKeyEvent
def isExpandKeyEvent(self, keyEvent): """Check if key event should expand rectangular selection""" return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, Qt.Key_PageUp, Qt.Key_PageDown, Qt.Key_Home, Qt.Key_End)
python
def isExpandKeyEvent(self, keyEvent): """Check if key event should expand rectangular selection""" return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, Qt.Key_PageUp, Qt.Key_PageDown, Qt.Key_Home, Qt.Key_End)
[ "def", "isExpandKeyEvent", "(", "self", ",", "keyEvent", ")", ":", "return", "keyEvent", ".", "modifiers", "(", ")", "&", "Qt", ".", "ShiftModifier", "and", "keyEvent", ".", "modifiers", "(", ")", "&", "Qt", ".", "AltModifier", "and", "keyEvent", ".", "key", "(", ")", "in", "(", "Qt", ".", "Key_Left", ",", "Qt", ".", "Key_Right", ",", "Qt", ".", "Key_Down", ",", "Qt", ".", "Key_Up", ",", "Qt", ".", "Key_PageUp", ",", "Qt", ".", "Key_PageDown", ",", "Qt", ".", "Key_Home", ",", "Qt", ".", "Key_End", ")" ]
Check if key event should expand rectangular selection
[ "Check", "if", "key", "event", "should", "expand", "rectangular", "selection" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L48-L53
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.onExpandKeyEvent
def onExpandKeyEvent(self, keyEvent): """One of expand selection key events""" if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn(currentBlockText, self._qpart.cursorPosition[1]) self._start = (line, visibleColumn) modifiersWithoutAltShift = keyEvent.modifiers() & ( ~ (Qt.AltModifier | Qt.ShiftModifier)) newEvent = QKeyEvent(keyEvent.type(), keyEvent.key(), modifiersWithoutAltShift, keyEvent.text(), keyEvent.isAutoRepeat(), keyEvent.count()) self._qpart.cursorPositionChanged.disconnect(self._reset) self._qpart.selectionChanged.disconnect(self._reset) super(self._qpart.__class__, self._qpart).keyPressEvent(newEvent) self._qpart.cursorPositionChanged.connect(self._reset) self._qpart.selectionChanged.connect(self._reset)
python
def onExpandKeyEvent(self, keyEvent): """One of expand selection key events""" if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn(currentBlockText, self._qpart.cursorPosition[1]) self._start = (line, visibleColumn) modifiersWithoutAltShift = keyEvent.modifiers() & ( ~ (Qt.AltModifier | Qt.ShiftModifier)) newEvent = QKeyEvent(keyEvent.type(), keyEvent.key(), modifiersWithoutAltShift, keyEvent.text(), keyEvent.isAutoRepeat(), keyEvent.count()) self._qpart.cursorPositionChanged.disconnect(self._reset) self._qpart.selectionChanged.disconnect(self._reset) super(self._qpart.__class__, self._qpart).keyPressEvent(newEvent) self._qpart.cursorPositionChanged.connect(self._reset) self._qpart.selectionChanged.connect(self._reset)
[ "def", "onExpandKeyEvent", "(", "self", ",", "keyEvent", ")", ":", "if", "self", ".", "_start", "is", "None", ":", "currentBlockText", "=", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "text", "(", ")", "line", "=", "self", ".", "_qpart", ".", "cursorPosition", "[", "0", "]", "visibleColumn", "=", "self", ".", "_realToVisibleColumn", "(", "currentBlockText", ",", "self", ".", "_qpart", ".", "cursorPosition", "[", "1", "]", ")", "self", ".", "_start", "=", "(", "line", ",", "visibleColumn", ")", "modifiersWithoutAltShift", "=", "keyEvent", ".", "modifiers", "(", ")", "&", "(", "~", "(", "Qt", ".", "AltModifier", "|", "Qt", ".", "ShiftModifier", ")", ")", "newEvent", "=", "QKeyEvent", "(", "keyEvent", ".", "type", "(", ")", ",", "keyEvent", ".", "key", "(", ")", ",", "modifiersWithoutAltShift", ",", "keyEvent", ".", "text", "(", ")", ",", "keyEvent", ".", "isAutoRepeat", "(", ")", ",", "keyEvent", ".", "count", "(", ")", ")", "self", ".", "_qpart", ".", "cursorPositionChanged", ".", "disconnect", "(", "self", ".", "_reset", ")", "self", ".", "_qpart", ".", "selectionChanged", ".", "disconnect", "(", "self", ".", "_reset", ")", "super", "(", "self", ".", "_qpart", ".", "__class__", ",", "self", ".", "_qpart", ")", ".", "keyPressEvent", "(", "newEvent", ")", "self", ".", "_qpart", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "_reset", ")", "self", ".", "_qpart", ".", "selectionChanged", ".", "connect", "(", "self", ".", "_reset", ")" ]
One of expand selection key events
[ "One", "of", "expand", "selection", "key", "events" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L55-L74
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection._realToVisibleColumn
def _realToVisibleColumn(self, text, realColumn): """If \t is used, real position of symbol in block and visible position differs This function converts real to visible """ generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(generator) val = next(generator) return val
python
def _realToVisibleColumn(self, text, realColumn): """If \t is used, real position of symbol in block and visible position differs This function converts real to visible """ generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(generator) val = next(generator) return val
[ "def", "_realToVisibleColumn", "(", "self", ",", "text", ",", "realColumn", ")", ":", "generator", "=", "self", ".", "_visibleCharPositionGenerator", "(", "text", ")", "for", "i", "in", "range", "(", "realColumn", ")", ":", "val", "=", "next", "(", "generator", ")", "val", "=", "next", "(", "generator", ")", "return", "val" ]
If \t is used, real position of symbol in block and visible position differs This function converts real to visible
[ "If", "\\", "t", "is", "used", "real", "position", "of", "symbol", "in", "block", "and", "visible", "position", "differs", "This", "function", "converts", "real", "to", "visible" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L90-L98
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection._visibleToRealColumn
def _visibleToRealColumn(self, text, visiblePos): """If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short """ if visiblePos == 0: return 0 elif not '\t' in text: return visiblePos else: currentIndex = 1 for currentVisiblePos in self._visibleCharPositionGenerator(text): if currentVisiblePos >= visiblePos: return currentIndex - 1 currentIndex += 1 return None
python
def _visibleToRealColumn(self, text, visiblePos): """If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short """ if visiblePos == 0: return 0 elif not '\t' in text: return visiblePos else: currentIndex = 1 for currentVisiblePos in self._visibleCharPositionGenerator(text): if currentVisiblePos >= visiblePos: return currentIndex - 1 currentIndex += 1 return None
[ "def", "_visibleToRealColumn", "(", "self", ",", "text", ",", "visiblePos", ")", ":", "if", "visiblePos", "==", "0", ":", "return", "0", "elif", "not", "'\\t'", "in", "text", ":", "return", "visiblePos", "else", ":", "currentIndex", "=", "1", "for", "currentVisiblePos", "in", "self", ".", "_visibleCharPositionGenerator", "(", "text", ")", ":", "if", "currentVisiblePos", ">=", "visiblePos", ":", "return", "currentIndex", "-", "1", "currentIndex", "+=", "1", "return", "None" ]
If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short
[ "If", "\\", "t", "is", "used", "real", "position", "of", "symbol", "in", "block", "and", "visible", "position", "differs", "This", "function", "converts", "visible", "to", "real", ".", "Bigger", "value", "is", "returned", "if", "visiblePos", "is", "in", "the", "middle", "of", "\\", "t", "None", "if", "text", "is", "too", "short" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L100-L116
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.cursors
def cursors(self): """Cursors for rectangular selection. 1 cursor for every line """ cursors = [] if self._start is not None: startLine, startVisibleCol = self._start currentLine, currentCol = self._qpart.cursorPosition if abs(startLine - currentLine) > self._MAX_SIZE or \ abs(startVisibleCol - currentCol) > self._MAX_SIZE: # Too big rectangular selection freezes the GUI self._qpart.userWarning.emit('Rectangular selection area is too big') self._start = None return [] currentBlockText = self._qpart.textCursor().block().text() currentVisibleCol = self._realToVisibleColumn(currentBlockText, currentCol) for lineNumber in range(min(startLine, currentLine), max(startLine, currentLine) + 1): block = self._qpart.document().findBlockByNumber(lineNumber) cursor = QTextCursor(block) realStartCol = self._visibleToRealColumn(block.text(), startVisibleCol) realCurrentCol = self._visibleToRealColumn(block.text(), currentVisibleCol) if realStartCol is None: realStartCol = block.length() # out of range value if realCurrentCol is None: realCurrentCol = block.length() # out of range value cursor.setPosition(cursor.block().position() + min(realStartCol, block.length() - 1)) cursor.setPosition(cursor.block().position() + min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor) cursors.append(cursor) return cursors
python
def cursors(self): """Cursors for rectangular selection. 1 cursor for every line """ cursors = [] if self._start is not None: startLine, startVisibleCol = self._start currentLine, currentCol = self._qpart.cursorPosition if abs(startLine - currentLine) > self._MAX_SIZE or \ abs(startVisibleCol - currentCol) > self._MAX_SIZE: # Too big rectangular selection freezes the GUI self._qpart.userWarning.emit('Rectangular selection area is too big') self._start = None return [] currentBlockText = self._qpart.textCursor().block().text() currentVisibleCol = self._realToVisibleColumn(currentBlockText, currentCol) for lineNumber in range(min(startLine, currentLine), max(startLine, currentLine) + 1): block = self._qpart.document().findBlockByNumber(lineNumber) cursor = QTextCursor(block) realStartCol = self._visibleToRealColumn(block.text(), startVisibleCol) realCurrentCol = self._visibleToRealColumn(block.text(), currentVisibleCol) if realStartCol is None: realStartCol = block.length() # out of range value if realCurrentCol is None: realCurrentCol = block.length() # out of range value cursor.setPosition(cursor.block().position() + min(realStartCol, block.length() - 1)) cursor.setPosition(cursor.block().position() + min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor) cursors.append(cursor) return cursors
[ "def", "cursors", "(", "self", ")", ":", "cursors", "=", "[", "]", "if", "self", ".", "_start", "is", "not", "None", ":", "startLine", ",", "startVisibleCol", "=", "self", ".", "_start", "currentLine", ",", "currentCol", "=", "self", ".", "_qpart", ".", "cursorPosition", "if", "abs", "(", "startLine", "-", "currentLine", ")", ">", "self", ".", "_MAX_SIZE", "or", "abs", "(", "startVisibleCol", "-", "currentCol", ")", ">", "self", ".", "_MAX_SIZE", ":", "# Too big rectangular selection freezes the GUI", "self", ".", "_qpart", ".", "userWarning", ".", "emit", "(", "'Rectangular selection area is too big'", ")", "self", ".", "_start", "=", "None", "return", "[", "]", "currentBlockText", "=", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "text", "(", ")", "currentVisibleCol", "=", "self", ".", "_realToVisibleColumn", "(", "currentBlockText", ",", "currentCol", ")", "for", "lineNumber", "in", "range", "(", "min", "(", "startLine", ",", "currentLine", ")", ",", "max", "(", "startLine", ",", "currentLine", ")", "+", "1", ")", ":", "block", "=", "self", ".", "_qpart", ".", "document", "(", ")", ".", "findBlockByNumber", "(", "lineNumber", ")", "cursor", "=", "QTextCursor", "(", "block", ")", "realStartCol", "=", "self", ".", "_visibleToRealColumn", "(", "block", ".", "text", "(", ")", ",", "startVisibleCol", ")", "realCurrentCol", "=", "self", ".", "_visibleToRealColumn", "(", "block", ".", "text", "(", ")", ",", "currentVisibleCol", ")", "if", "realStartCol", "is", "None", ":", "realStartCol", "=", "block", ".", "length", "(", ")", "# out of range value", "if", "realCurrentCol", "is", "None", ":", "realCurrentCol", "=", "block", ".", "length", "(", ")", "# out of range value", "cursor", ".", "setPosition", "(", "cursor", ".", "block", "(", ")", ".", "position", "(", ")", "+", "min", "(", "realStartCol", ",", "block", ".", "length", "(", ")", "-", "1", ")", ")", "cursor", ".", "setPosition", "(", "cursor", ".", "block", "(", ")", ".", "position", "(", ")", "+", "min", "(", "realCurrentCol", ",", "block", ".", "length", "(", ")", "-", "1", ")", ",", "QTextCursor", ".", "KeepAnchor", ")", "cursors", ".", "append", "(", "cursor", ")", "return", "cursors" ]
Cursors for rectangular selection. 1 cursor for every line
[ "Cursors", "for", "rectangular", "selection", ".", "1", "cursor", "for", "every", "line" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L118-L152
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.selections
def selections(self): """Build list of extra selections for rectangular selection""" selections = [] cursors = self.cursors() if cursors: background = self._qpart.palette().color(QPalette.Highlight) foreground = self._qpart.palette().color(QPalette.HighlightedText) for cursor in cursors: selection = QTextEdit.ExtraSelection() selection.format.setBackground(background) selection.format.setForeground(foreground) selection.cursor = cursor selections.append(selection) return selections
python
def selections(self): """Build list of extra selections for rectangular selection""" selections = [] cursors = self.cursors() if cursors: background = self._qpart.palette().color(QPalette.Highlight) foreground = self._qpart.palette().color(QPalette.HighlightedText) for cursor in cursors: selection = QTextEdit.ExtraSelection() selection.format.setBackground(background) selection.format.setForeground(foreground) selection.cursor = cursor selections.append(selection) return selections
[ "def", "selections", "(", "self", ")", ":", "selections", "=", "[", "]", "cursors", "=", "self", ".", "cursors", "(", ")", "if", "cursors", ":", "background", "=", "self", ".", "_qpart", ".", "palette", "(", ")", ".", "color", "(", "QPalette", ".", "Highlight", ")", "foreground", "=", "self", ".", "_qpart", ".", "palette", "(", ")", ".", "color", "(", "QPalette", ".", "HighlightedText", ")", "for", "cursor", "in", "cursors", ":", "selection", "=", "QTextEdit", ".", "ExtraSelection", "(", ")", "selection", ".", "format", ".", "setBackground", "(", "background", ")", "selection", ".", "format", ".", "setForeground", "(", "foreground", ")", "selection", ".", "cursor", "=", "cursor", "selections", ".", "append", "(", "selection", ")", "return", "selections" ]
Build list of extra selections for rectangular selection
[ "Build", "list", "of", "extra", "selections", "for", "rectangular", "selection" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L154-L169
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.copy
def copy(self): """Copy to the clipboard""" data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
python
def copy(self): """Copy to the clipboard""" data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
[ "def", "copy", "(", "self", ")", ":", "data", "=", "QMimeData", "(", ")", "text", "=", "'\\n'", ".", "join", "(", "[", "cursor", ".", "selectedText", "(", ")", "for", "cursor", "in", "self", ".", "cursors", "(", ")", "]", ")", "data", ".", "setText", "(", "text", ")", "data", ".", "setData", "(", "self", ".", "MIME_TYPE", ",", "text", ".", "encode", "(", "'utf8'", ")", ")", "QApplication", ".", "clipboard", "(", ")", ".", "setMimeData", "(", "data", ")" ]
Copy to the clipboard
[ "Copy", "to", "the", "clipboard" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L175-L182
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.cut
def cut(self): """Cut action. Copy and delete """ cursorPos = self._qpart.cursorPosition topLeft = (min(self._start[0], cursorPos[0]), min(self._start[1], cursorPos[1])) self.copy() self.delete() """Move cursor to top-left corner of the selection, so that if text gets pasted again, original text will be restored""" self._qpart.cursorPosition = topLeft
python
def cut(self): """Cut action. Copy and delete """ cursorPos = self._qpart.cursorPosition topLeft = (min(self._start[0], cursorPos[0]), min(self._start[1], cursorPos[1])) self.copy() self.delete() """Move cursor to top-left corner of the selection, so that if text gets pasted again, original text will be restored""" self._qpart.cursorPosition = topLeft
[ "def", "cut", "(", "self", ")", ":", "cursorPos", "=", "self", ".", "_qpart", ".", "cursorPosition", "topLeft", "=", "(", "min", "(", "self", ".", "_start", "[", "0", "]", ",", "cursorPos", "[", "0", "]", ")", ",", "min", "(", "self", ".", "_start", "[", "1", "]", ",", "cursorPos", "[", "1", "]", ")", ")", "self", ".", "copy", "(", ")", "self", ".", "delete", "(", ")", "\"\"\"Move cursor to top-left corner of the selection,\n so that if text gets pasted again, original text will be restored\"\"\"", "self", ".", "_qpart", ".", "cursorPosition", "=", "topLeft" ]
Cut action. Copy and delete
[ "Cut", "action", ".", "Copy", "and", "delete" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L184-L195
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection._indentUpTo
def _indentUpTo(self, text, width): """Add space to text, so text width will be at least width. Return text, which must be added """ visibleTextWidth = self._realToVisibleColumn(text, len(text)) diff = width - visibleTextWidth if diff <= 0: return '' elif self._qpart.indentUseTabs and \ all([char == '\t' for char in text]): # if using tabs and only tabs in text return '\t' * (diff // self._qpart.indentWidth) + \ ' ' * (diff % self._qpart.indentWidth) else: return ' ' * int(diff)
python
def _indentUpTo(self, text, width): """Add space to text, so text width will be at least width. Return text, which must be added """ visibleTextWidth = self._realToVisibleColumn(text, len(text)) diff = width - visibleTextWidth if diff <= 0: return '' elif self._qpart.indentUseTabs and \ all([char == '\t' for char in text]): # if using tabs and only tabs in text return '\t' * (diff // self._qpart.indentWidth) + \ ' ' * (diff % self._qpart.indentWidth) else: return ' ' * int(diff)
[ "def", "_indentUpTo", "(", "self", ",", "text", ",", "width", ")", ":", "visibleTextWidth", "=", "self", ".", "_realToVisibleColumn", "(", "text", ",", "len", "(", "text", ")", ")", "diff", "=", "width", "-", "visibleTextWidth", "if", "diff", "<=", "0", ":", "return", "''", "elif", "self", ".", "_qpart", ".", "indentUseTabs", "and", "all", "(", "[", "char", "==", "'\\t'", "for", "char", "in", "text", "]", ")", ":", "# if using tabs and only tabs in text", "return", "'\\t'", "*", "(", "diff", "//", "self", ".", "_qpart", ".", "indentWidth", ")", "+", "' '", "*", "(", "diff", "%", "self", ".", "_qpart", ".", "indentWidth", ")", "else", ":", "return", "' '", "*", "int", "(", "diff", ")" ]
Add space to text, so text width will be at least width. Return text, which must be added
[ "Add", "space", "to", "text", "so", "text", "width", "will", "be", "at", "least", "width", ".", "Return", "text", "which", "must", "be", "added" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L197-L210
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.paste
def paste(self, mimeData): """Paste recrangular selection. Add space at the beginning of line, if necessary """ if self.isActive(): self.delete() elif self._qpart.textCursor().hasSelection(): self._qpart.textCursor().deleteChar() text = bytes(mimeData.data(self.MIME_TYPE)).decode('utf8') lines = text.splitlines() cursorLine, cursorCol = self._qpart.cursorPosition if cursorLine + len(lines) > len(self._qpart.lines): for i in range(cursorLine + len(lines) - len(self._qpart.lines)): self._qpart.lines.append('') with self._qpart: for index, line in enumerate(lines): currentLine = self._qpart.lines[cursorLine + index] newLine = currentLine[:cursorCol] + \ self._indentUpTo(currentLine, cursorCol) + \ line + \ currentLine[cursorCol:] self._qpart.lines[cursorLine + index] = newLine self._qpart.cursorPosition = cursorLine, cursorCol
python
def paste(self, mimeData): """Paste recrangular selection. Add space at the beginning of line, if necessary """ if self.isActive(): self.delete() elif self._qpart.textCursor().hasSelection(): self._qpart.textCursor().deleteChar() text = bytes(mimeData.data(self.MIME_TYPE)).decode('utf8') lines = text.splitlines() cursorLine, cursorCol = self._qpart.cursorPosition if cursorLine + len(lines) > len(self._qpart.lines): for i in range(cursorLine + len(lines) - len(self._qpart.lines)): self._qpart.lines.append('') with self._qpart: for index, line in enumerate(lines): currentLine = self._qpart.lines[cursorLine + index] newLine = currentLine[:cursorCol] + \ self._indentUpTo(currentLine, cursorCol) + \ line + \ currentLine[cursorCol:] self._qpart.lines[cursorLine + index] = newLine self._qpart.cursorPosition = cursorLine, cursorCol
[ "def", "paste", "(", "self", ",", "mimeData", ")", ":", "if", "self", ".", "isActive", "(", ")", ":", "self", ".", "delete", "(", ")", "elif", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "hasSelection", "(", ")", ":", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "deleteChar", "(", ")", "text", "=", "bytes", "(", "mimeData", ".", "data", "(", "self", ".", "MIME_TYPE", ")", ")", ".", "decode", "(", "'utf8'", ")", "lines", "=", "text", ".", "splitlines", "(", ")", "cursorLine", ",", "cursorCol", "=", "self", ".", "_qpart", ".", "cursorPosition", "if", "cursorLine", "+", "len", "(", "lines", ")", ">", "len", "(", "self", ".", "_qpart", ".", "lines", ")", ":", "for", "i", "in", "range", "(", "cursorLine", "+", "len", "(", "lines", ")", "-", "len", "(", "self", ".", "_qpart", ".", "lines", ")", ")", ":", "self", ".", "_qpart", ".", "lines", ".", "append", "(", "''", ")", "with", "self", ".", "_qpart", ":", "for", "index", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "currentLine", "=", "self", ".", "_qpart", ".", "lines", "[", "cursorLine", "+", "index", "]", "newLine", "=", "currentLine", "[", ":", "cursorCol", "]", "+", "self", ".", "_indentUpTo", "(", "currentLine", ",", "cursorCol", ")", "+", "line", "+", "currentLine", "[", "cursorCol", ":", "]", "self", ".", "_qpart", ".", "lines", "[", "cursorLine", "+", "index", "]", "=", "newLine", "self", ".", "_qpart", ".", "cursorPosition", "=", "cursorLine", ",", "cursorCol" ]
Paste recrangular selection. Add space at the beginning of line, if necessary
[ "Paste", "recrangular", "selection", ".", "Add", "space", "at", "the", "beginning", "of", "line", "if", "necessary" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L212-L236
andreikop/qutepart
qutepart/margins.py
MarginBase.__allocateBits
def __allocateBits(self): """Allocates the bit range depending on the required bit count """ if self._bit_count < 0: raise Exception( "A margin cannot request negative number of bits" ) if self._bit_count == 0: return # Build a list of occupied ranges margins = self._qpart.getMargins() occupiedRanges = [] for margin in margins: bitRange = margin.getBitRange() if bitRange is not None: # pick the right position added = False for index in range( len( occupiedRanges ) ): r = occupiedRanges[ index ] if bitRange[ 1 ] < r[ 0 ]: occupiedRanges.insert(index, bitRange) added = True break if not added: occupiedRanges.append(bitRange) vacant = 0 for r in occupiedRanges: if r[ 0 ] - vacant >= self._bit_count: self._bitRange = (vacant, vacant + self._bit_count - 1) return vacant = r[ 1 ] + 1 # Not allocated, i.e. grab the tail bits self._bitRange = (vacant, vacant + self._bit_count - 1)
python
def __allocateBits(self): """Allocates the bit range depending on the required bit count """ if self._bit_count < 0: raise Exception( "A margin cannot request negative number of bits" ) if self._bit_count == 0: return # Build a list of occupied ranges margins = self._qpart.getMargins() occupiedRanges = [] for margin in margins: bitRange = margin.getBitRange() if bitRange is not None: # pick the right position added = False for index in range( len( occupiedRanges ) ): r = occupiedRanges[ index ] if bitRange[ 1 ] < r[ 0 ]: occupiedRanges.insert(index, bitRange) added = True break if not added: occupiedRanges.append(bitRange) vacant = 0 for r in occupiedRanges: if r[ 0 ] - vacant >= self._bit_count: self._bitRange = (vacant, vacant + self._bit_count - 1) return vacant = r[ 1 ] + 1 # Not allocated, i.e. grab the tail bits self._bitRange = (vacant, vacant + self._bit_count - 1)
[ "def", "__allocateBits", "(", "self", ")", ":", "if", "self", ".", "_bit_count", "<", "0", ":", "raise", "Exception", "(", "\"A margin cannot request negative number of bits\"", ")", "if", "self", ".", "_bit_count", "==", "0", ":", "return", "# Build a list of occupied ranges", "margins", "=", "self", ".", "_qpart", ".", "getMargins", "(", ")", "occupiedRanges", "=", "[", "]", "for", "margin", "in", "margins", ":", "bitRange", "=", "margin", ".", "getBitRange", "(", ")", "if", "bitRange", "is", "not", "None", ":", "# pick the right position", "added", "=", "False", "for", "index", "in", "range", "(", "len", "(", "occupiedRanges", ")", ")", ":", "r", "=", "occupiedRanges", "[", "index", "]", "if", "bitRange", "[", "1", "]", "<", "r", "[", "0", "]", ":", "occupiedRanges", ".", "insert", "(", "index", ",", "bitRange", ")", "added", "=", "True", "break", "if", "not", "added", ":", "occupiedRanges", ".", "append", "(", "bitRange", ")", "vacant", "=", "0", "for", "r", "in", "occupiedRanges", ":", "if", "r", "[", "0", "]", "-", "vacant", ">=", "self", ".", "_bit_count", ":", "self", ".", "_bitRange", "=", "(", "vacant", ",", "vacant", "+", "self", ".", "_bit_count", "-", "1", ")", "return", "vacant", "=", "r", "[", "1", "]", "+", "1", "# Not allocated, i.e. grab the tail bits", "self", ".", "_bitRange", "=", "(", "vacant", ",", "vacant", "+", "self", ".", "_bit_count", "-", "1", ")" ]
Allocates the bit range depending on the required bit count
[ "Allocates", "the", "bit", "range", "depending", "on", "the", "required", "bit", "count" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L32-L65
andreikop/qutepart
qutepart/margins.py
MarginBase.__updateRequest
def __updateRequest(self, rect, dy): """Repaint line number area if necessary """ if dy: self.scroll(0, dy) elif self._countCache[0] != self._qpart.blockCount() or \ self._countCache[1] != self._qpart.textCursor().block().lineCount(): # if block height not added to rect, last line number sometimes is not drawn blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock()).height() self.update(0, rect.y(), self.width(), rect.height() + blockHeight) self._countCache = (self._qpart.blockCount(), self._qpart.textCursor().block().lineCount()) if rect.contains(self._qpart.viewport().rect()): self._qpart.updateViewportMargins()
python
def __updateRequest(self, rect, dy): """Repaint line number area if necessary """ if dy: self.scroll(0, dy) elif self._countCache[0] != self._qpart.blockCount() or \ self._countCache[1] != self._qpart.textCursor().block().lineCount(): # if block height not added to rect, last line number sometimes is not drawn blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock()).height() self.update(0, rect.y(), self.width(), rect.height() + blockHeight) self._countCache = (self._qpart.blockCount(), self._qpart.textCursor().block().lineCount()) if rect.contains(self._qpart.viewport().rect()): self._qpart.updateViewportMargins()
[ "def", "__updateRequest", "(", "self", ",", "rect", ",", "dy", ")", ":", "if", "dy", ":", "self", ".", "scroll", "(", "0", ",", "dy", ")", "elif", "self", ".", "_countCache", "[", "0", "]", "!=", "self", ".", "_qpart", ".", "blockCount", "(", ")", "or", "self", ".", "_countCache", "[", "1", "]", "!=", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "lineCount", "(", ")", ":", "# if block height not added to rect, last line number sometimes is not drawn", "blockHeight", "=", "self", ".", "_qpart", ".", "blockBoundingRect", "(", "self", ".", "_qpart", ".", "firstVisibleBlock", "(", ")", ")", ".", "height", "(", ")", "self", ".", "update", "(", "0", ",", "rect", ".", "y", "(", ")", ",", "self", ".", "width", "(", ")", ",", "rect", ".", "height", "(", ")", "+", "blockHeight", ")", "self", ".", "_countCache", "=", "(", "self", ".", "_qpart", ".", "blockCount", "(", ")", ",", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "lineCount", "(", ")", ")", "if", "rect", ".", "contains", "(", "self", ".", "_qpart", ".", "viewport", "(", ")", ".", "rect", "(", ")", ")", ":", "self", ".", "_qpart", ".", "updateViewportMargins", "(", ")" ]
Repaint line number area if necessary
[ "Repaint", "line", "number", "area", "if", "necessary" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L67-L82
andreikop/qutepart
qutepart/margins.py
MarginBase.setBlockValue
def setBlockValue(self, block, value): """Sets the required value to the block without damaging the other bits """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") if value < 0: raise Exception( "The margin '" + self._name + "' must be a positive integer" ) if value >= 2 ** self._bit_count: raise Exception( "The margin '" + self._name + "' value exceeds the allocated bit range" ) newMarginValue = value << self._bitRange[ 0 ] currentUserState = block.userState() if currentUserState in [ 0, -1 ]: block.setUserState(newMarginValue) else: marginMask = 2 ** self._bit_count - 1 otherMarginsValue = currentUserState & ~marginMask block.setUserState(newMarginValue | otherMarginsValue)
python
def setBlockValue(self, block, value): """Sets the required value to the block without damaging the other bits """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") if value < 0: raise Exception( "The margin '" + self._name + "' must be a positive integer" ) if value >= 2 ** self._bit_count: raise Exception( "The margin '" + self._name + "' value exceeds the allocated bit range" ) newMarginValue = value << self._bitRange[ 0 ] currentUserState = block.userState() if currentUserState in [ 0, -1 ]: block.setUserState(newMarginValue) else: marginMask = 2 ** self._bit_count - 1 otherMarginsValue = currentUserState & ~marginMask block.setUserState(newMarginValue | otherMarginsValue)
[ "def", "setBlockValue", "(", "self", ",", "block", ",", "value", ")", ":", "if", "self", ".", "_bit_count", "==", "0", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' did not allocate any bits for the values\"", ")", "if", "value", "<", "0", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' must be a positive integer\"", ")", "if", "value", ">=", "2", "**", "self", ".", "_bit_count", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' value exceeds the allocated bit range\"", ")", "newMarginValue", "=", "value", "<<", "self", ".", "_bitRange", "[", "0", "]", "currentUserState", "=", "block", ".", "userState", "(", ")", "if", "currentUserState", "in", "[", "0", ",", "-", "1", "]", ":", "block", ".", "setUserState", "(", "newMarginValue", ")", "else", ":", "marginMask", "=", "2", "**", "self", ".", "_bit_count", "-", "1", "otherMarginsValue", "=", "currentUserState", "&", "~", "marginMask", "block", ".", "setUserState", "(", "newMarginValue", "|", "otherMarginsValue", ")" ]
Sets the required value to the block without damaging the other bits
[ "Sets", "the", "required", "value", "to", "the", "block", "without", "damaging", "the", "other", "bits" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L95-L117
andreikop/qutepart
qutepart/margins.py
MarginBase.getBlockValue
def getBlockValue(self, block): """Provides the previously set block value respecting the bits range. 0 value and not marked block are treated the same way and 0 is provided. """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") val = block.userState() if val in [ 0, -1 ]: return 0 # Shift the value to the right val >>= self._bitRange[ 0 ] # Apply the mask to the value mask = 2 ** self._bit_count - 1 val &= mask return val
python
def getBlockValue(self, block): """Provides the previously set block value respecting the bits range. 0 value and not marked block are treated the same way and 0 is provided. """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") val = block.userState() if val in [ 0, -1 ]: return 0 # Shift the value to the right val >>= self._bitRange[ 0 ] # Apply the mask to the value mask = 2 ** self._bit_count - 1 val &= mask return val
[ "def", "getBlockValue", "(", "self", ",", "block", ")", ":", "if", "self", ".", "_bit_count", "==", "0", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' did not allocate any bits for the values\"", ")", "val", "=", "block", ".", "userState", "(", ")", "if", "val", "in", "[", "0", ",", "-", "1", "]", ":", "return", "0", "# Shift the value to the right", "val", ">>=", "self", ".", "_bitRange", "[", "0", "]", "# Apply the mask to the value", "mask", "=", "2", "**", "self", ".", "_bit_count", "-", "1", "val", "&=", "mask", "return", "val" ]
Provides the previously set block value respecting the bits range. 0 value and not marked block are treated the same way and 0 is provided.
[ "Provides", "the", "previously", "set", "block", "value", "respecting", "the", "bits", "range", ".", "0", "value", "and", "not", "marked", "block", "are", "treated", "the", "same", "way", "and", "0", "is", "provided", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L119-L137
andreikop/qutepart
qutepart/margins.py
MarginBase.hide
def hide(self): """Override the QWidget::hide() method to properly recalculate the editor viewport. """ if not self.isHidden(): QWidget.hide(self) self._qpart.updateViewport()
python
def hide(self): """Override the QWidget::hide() method to properly recalculate the editor viewport. """ if not self.isHidden(): QWidget.hide(self) self._qpart.updateViewport()
[ "def", "hide", "(", "self", ")", ":", "if", "not", "self", ".", "isHidden", "(", ")", ":", "QWidget", ".", "hide", "(", "self", ")", "self", ".", "_qpart", ".", "updateViewport", "(", ")" ]
Override the QWidget::hide() method to properly recalculate the editor viewport.
[ "Override", "the", "QWidget", "::", "hide", "()", "method", "to", "properly", "recalculate", "the", "editor", "viewport", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L139-L145
andreikop/qutepart
qutepart/margins.py
MarginBase.show
def show(self): """Override the QWidget::show() method to properly recalculate the editor viewport. """ if self.isHidden(): QWidget.show(self) self._qpart.updateViewport()
python
def show(self): """Override the QWidget::show() method to properly recalculate the editor viewport. """ if self.isHidden(): QWidget.show(self) self._qpart.updateViewport()
[ "def", "show", "(", "self", ")", ":", "if", "self", ".", "isHidden", "(", ")", ":", "QWidget", ".", "show", "(", "self", ")", "self", ".", "_qpart", ".", "updateViewport", "(", ")" ]
Override the QWidget::show() method to properly recalculate the editor viewport.
[ "Override", "the", "QWidget", "::", "show", "()", "method", "to", "properly", "recalculate", "the", "editor", "viewport", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L147-L153
andreikop/qutepart
qutepart/margins.py
MarginBase.setVisible
def setVisible(self, val): """Override the QWidget::setVisible(bool) method to properly recalculate the editor viewport. """ if val != self.isVisible(): if val: QWidget.setVisible(self, True) else: QWidget.setVisible(self, False) self._qpart.updateViewport()
python
def setVisible(self, val): """Override the QWidget::setVisible(bool) method to properly recalculate the editor viewport. """ if val != self.isVisible(): if val: QWidget.setVisible(self, True) else: QWidget.setVisible(self, False) self._qpart.updateViewport()
[ "def", "setVisible", "(", "self", ",", "val", ")", ":", "if", "val", "!=", "self", ".", "isVisible", "(", ")", ":", "if", "val", ":", "QWidget", ".", "setVisible", "(", "self", ",", "True", ")", "else", ":", "QWidget", ".", "setVisible", "(", "self", ",", "False", ")", "self", ".", "_qpart", ".", "updateViewport", "(", ")" ]
Override the QWidget::setVisible(bool) method to properly recalculate the editor viewport.
[ "Override", "the", "QWidget", "::", "setVisible", "(", "bool", ")", "method", "to", "properly", "recalculate", "the", "editor", "viewport", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L155-L164
andreikop/qutepart
qutepart/margins.py
MarginBase.clear
def clear(self): """Convenience method to reset all the block values to 0 """ if self._bit_count == 0: return block = self._qpart.document().begin() while block.isValid(): if self.getBlockValue(block): self.setBlockValue(block, 0) block = block.next()
python
def clear(self): """Convenience method to reset all the block values to 0 """ if self._bit_count == 0: return block = self._qpart.document().begin() while block.isValid(): if self.getBlockValue(block): self.setBlockValue(block, 0) block = block.next()
[ "def", "clear", "(", "self", ")", ":", "if", "self", ".", "_bit_count", "==", "0", ":", "return", "block", "=", "self", ".", "_qpart", ".", "document", "(", ")", ".", "begin", "(", ")", "while", "block", ".", "isValid", "(", ")", ":", "if", "self", ".", "getBlockValue", "(", "block", ")", ":", "self", ".", "setBlockValue", "(", "block", ",", "0", ")", "block", "=", "block", ".", "next", "(", ")" ]
Convenience method to reset all the block values to 0
[ "Convenience", "method", "to", "reset", "all", "the", "block", "values", "to", "0" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L175-L185
andreikop/qutepart
qutepart/syntax/__init__.py
Syntax._getTextType
def _getTextType(self, lineData, column): """Get text type (letter) """ if lineData is None: return ' ' # default is code textTypeMap = lineData[1] if column >= len(textTypeMap): # probably, not actual data, not updated yet return ' ' return textTypeMap[column]
python
def _getTextType(self, lineData, column): """Get text type (letter) """ if lineData is None: return ' ' # default is code textTypeMap = lineData[1] if column >= len(textTypeMap): # probably, not actual data, not updated yet return ' ' return textTypeMap[column]
[ "def", "_getTextType", "(", "self", ",", "lineData", ",", "column", ")", ":", "if", "lineData", "is", "None", ":", "return", "' '", "# default is code", "textTypeMap", "=", "lineData", "[", "1", "]", "if", "column", ">=", "len", "(", "textTypeMap", ")", ":", "# probably, not actual data, not updated yet", "return", "' '", "return", "textTypeMap", "[", "column", "]" ]
Get text type (letter)
[ "Get", "text", "type", "(", "letter", ")" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L117-L127
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxByXmlFileName
def _getSyntaxByXmlFileName(self, xmlFileName): """Get syntax by its xml file name """ import qutepart.syntax.loader # delayed import for avoid cross-imports problem with self._loadedSyntaxesLock: if not xmlFileName in self._loadedSyntaxes: xmlFilePath = os.path.join(os.path.dirname(__file__), "data", "xml", xmlFileName) syntax = Syntax(self) self._loadedSyntaxes[xmlFileName] = syntax qutepart.syntax.loader.loadSyntax(syntax, xmlFilePath) return self._loadedSyntaxes[xmlFileName]
python
def _getSyntaxByXmlFileName(self, xmlFileName): """Get syntax by its xml file name """ import qutepart.syntax.loader # delayed import for avoid cross-imports problem with self._loadedSyntaxesLock: if not xmlFileName in self._loadedSyntaxes: xmlFilePath = os.path.join(os.path.dirname(__file__), "data", "xml", xmlFileName) syntax = Syntax(self) self._loadedSyntaxes[xmlFileName] = syntax qutepart.syntax.loader.loadSyntax(syntax, xmlFilePath) return self._loadedSyntaxes[xmlFileName]
[ "def", "_getSyntaxByXmlFileName", "(", "self", ",", "xmlFileName", ")", ":", "import", "qutepart", ".", "syntax", ".", "loader", "# delayed import for avoid cross-imports problem", "with", "self", ".", "_loadedSyntaxesLock", ":", "if", "not", "xmlFileName", "in", "self", ".", "_loadedSyntaxes", ":", "xmlFilePath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"data\"", ",", "\"xml\"", ",", "xmlFileName", ")", "syntax", "=", "Syntax", "(", "self", ")", "self", ".", "_loadedSyntaxes", "[", "xmlFileName", "]", "=", "syntax", "qutepart", ".", "syntax", ".", "loader", ".", "loadSyntax", "(", "syntax", ",", "xmlFilePath", ")", "return", "self", ".", "_loadedSyntaxes", "[", "xmlFileName", "]" ]
Get syntax by its xml file name
[ "Get", "syntax", "by", "its", "xml", "file", "name" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L170-L182
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxByLanguageName
def _getSyntaxByLanguageName(self, syntaxName): """Get syntax by its name. Name is defined in the xml file """ xmlFileName = self._syntaxNameToXmlFileName[syntaxName] return self._getSyntaxByXmlFileName(xmlFileName)
python
def _getSyntaxByLanguageName(self, syntaxName): """Get syntax by its name. Name is defined in the xml file """ xmlFileName = self._syntaxNameToXmlFileName[syntaxName] return self._getSyntaxByXmlFileName(xmlFileName)
[ "def", "_getSyntaxByLanguageName", "(", "self", ",", "syntaxName", ")", ":", "xmlFileName", "=", "self", ".", "_syntaxNameToXmlFileName", "[", "syntaxName", "]", "return", "self", ".", "_getSyntaxByXmlFileName", "(", "xmlFileName", ")" ]
Get syntax by its name. Name is defined in the xml file
[ "Get", "syntax", "by", "its", "name", ".", "Name", "is", "defined", "in", "the", "xml", "file" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L184-L188
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxBySourceFileName
def _getSyntaxBySourceFileName(self, name): """Get syntax by source name of file, which is going to be highlighted """ for regExp, xmlFileName in self._extensionToXmlFileName.items(): if regExp.match(name): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + name)
python
def _getSyntaxBySourceFileName(self, name): """Get syntax by source name of file, which is going to be highlighted """ for regExp, xmlFileName in self._extensionToXmlFileName.items(): if regExp.match(name): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + name)
[ "def", "_getSyntaxBySourceFileName", "(", "self", ",", "name", ")", ":", "for", "regExp", ",", "xmlFileName", "in", "self", ".", "_extensionToXmlFileName", ".", "items", "(", ")", ":", "if", "regExp", ".", "match", "(", "name", ")", ":", "return", "self", ".", "_getSyntaxByXmlFileName", "(", "xmlFileName", ")", "else", ":", "raise", "KeyError", "(", "\"No syntax for \"", "+", "name", ")" ]
Get syntax by source name of file, which is going to be highlighted
[ "Get", "syntax", "by", "source", "name", "of", "file", "which", "is", "going", "to", "be", "highlighted" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L190-L197
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxByMimeType
def _getSyntaxByMimeType(self, mimeType): """Get syntax by first line of the file """ xmlFileName = self._mimeTypeToXmlFileName[mimeType] return self._getSyntaxByXmlFileName(xmlFileName)
python
def _getSyntaxByMimeType(self, mimeType): """Get syntax by first line of the file """ xmlFileName = self._mimeTypeToXmlFileName[mimeType] return self._getSyntaxByXmlFileName(xmlFileName)
[ "def", "_getSyntaxByMimeType", "(", "self", ",", "mimeType", ")", ":", "xmlFileName", "=", "self", ".", "_mimeTypeToXmlFileName", "[", "mimeType", "]", "return", "self", ".", "_getSyntaxByXmlFileName", "(", "xmlFileName", ")" ]
Get syntax by first line of the file
[ "Get", "syntax", "by", "first", "line", "of", "the", "file" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L199-L203
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxByFirstLine
def _getSyntaxByFirstLine(self, firstLine): """Get syntax by first line of the file """ for pattern, xmlFileName in self._firstLineToXmlFileName.items(): if fnmatch.fnmatch(firstLine, pattern): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + firstLine)
python
def _getSyntaxByFirstLine(self, firstLine): """Get syntax by first line of the file """ for pattern, xmlFileName in self._firstLineToXmlFileName.items(): if fnmatch.fnmatch(firstLine, pattern): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + firstLine)
[ "def", "_getSyntaxByFirstLine", "(", "self", ",", "firstLine", ")", ":", "for", "pattern", ",", "xmlFileName", "in", "self", ".", "_firstLineToXmlFileName", ".", "items", "(", ")", ":", "if", "fnmatch", ".", "fnmatch", "(", "firstLine", ",", "pattern", ")", ":", "return", "self", ".", "_getSyntaxByXmlFileName", "(", "xmlFileName", ")", "else", ":", "raise", "KeyError", "(", "\"No syntax for \"", "+", "firstLine", ")" ]
Get syntax by first line of the file
[ "Get", "syntax", "by", "first", "line", "of", "the", "file" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L205-L212
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager.getSyntax
def getSyntax(self, xmlFileName=None, mimeType=None, languageName=None, sourceFilePath=None, firstLine=None): """Get syntax by one of parameters: * xmlFileName * mimeType * languageName * sourceFilePath First parameter in the list has biggest priority """ syntax = None if syntax is None and xmlFileName is not None: try: syntax = self._getSyntaxByXmlFileName(xmlFileName) except KeyError: _logger.warning('No xml definition %s' % xmlFileName) if syntax is None and mimeType is not None: try: syntax = self._getSyntaxByMimeType(mimeType) except KeyError: _logger.warning('No syntax for mime type %s' % mimeType) if syntax is None and languageName is not None: try: syntax = self._getSyntaxByLanguageName(languageName) except KeyError: _logger.warning('No syntax for language %s' % languageName) if syntax is None and sourceFilePath is not None: baseName = os.path.basename(sourceFilePath) try: syntax = self._getSyntaxBySourceFileName(baseName) except KeyError: pass if syntax is None and firstLine is not None: try: syntax = self._getSyntaxByFirstLine(firstLine) except KeyError: pass return syntax
python
def getSyntax(self, xmlFileName=None, mimeType=None, languageName=None, sourceFilePath=None, firstLine=None): """Get syntax by one of parameters: * xmlFileName * mimeType * languageName * sourceFilePath First parameter in the list has biggest priority """ syntax = None if syntax is None and xmlFileName is not None: try: syntax = self._getSyntaxByXmlFileName(xmlFileName) except KeyError: _logger.warning('No xml definition %s' % xmlFileName) if syntax is None and mimeType is not None: try: syntax = self._getSyntaxByMimeType(mimeType) except KeyError: _logger.warning('No syntax for mime type %s' % mimeType) if syntax is None and languageName is not None: try: syntax = self._getSyntaxByLanguageName(languageName) except KeyError: _logger.warning('No syntax for language %s' % languageName) if syntax is None and sourceFilePath is not None: baseName = os.path.basename(sourceFilePath) try: syntax = self._getSyntaxBySourceFileName(baseName) except KeyError: pass if syntax is None and firstLine is not None: try: syntax = self._getSyntaxByFirstLine(firstLine) except KeyError: pass return syntax
[ "def", "getSyntax", "(", "self", ",", "xmlFileName", "=", "None", ",", "mimeType", "=", "None", ",", "languageName", "=", "None", ",", "sourceFilePath", "=", "None", ",", "firstLine", "=", "None", ")", ":", "syntax", "=", "None", "if", "syntax", "is", "None", "and", "xmlFileName", "is", "not", "None", ":", "try", ":", "syntax", "=", "self", ".", "_getSyntaxByXmlFileName", "(", "xmlFileName", ")", "except", "KeyError", ":", "_logger", ".", "warning", "(", "'No xml definition %s'", "%", "xmlFileName", ")", "if", "syntax", "is", "None", "and", "mimeType", "is", "not", "None", ":", "try", ":", "syntax", "=", "self", ".", "_getSyntaxByMimeType", "(", "mimeType", ")", "except", "KeyError", ":", "_logger", ".", "warning", "(", "'No syntax for mime type %s'", "%", "mimeType", ")", "if", "syntax", "is", "None", "and", "languageName", "is", "not", "None", ":", "try", ":", "syntax", "=", "self", ".", "_getSyntaxByLanguageName", "(", "languageName", ")", "except", "KeyError", ":", "_logger", ".", "warning", "(", "'No syntax for language %s'", "%", "languageName", ")", "if", "syntax", "is", "None", "and", "sourceFilePath", "is", "not", "None", ":", "baseName", "=", "os", ".", "path", ".", "basename", "(", "sourceFilePath", ")", "try", ":", "syntax", "=", "self", ".", "_getSyntaxBySourceFileName", "(", "baseName", ")", "except", "KeyError", ":", "pass", "if", "syntax", "is", "None", "and", "firstLine", "is", "not", "None", ":", "try", ":", "syntax", "=", "self", ".", "_getSyntaxByFirstLine", "(", "firstLine", ")", "except", "KeyError", ":", "pass", "return", "syntax" ]
Get syntax by one of parameters: * xmlFileName * mimeType * languageName * sourceFilePath First parameter in the list has biggest priority
[ "Get", "syntax", "by", "one", "of", "parameters", ":", "*", "xmlFileName", "*", "mimeType", "*", "languageName", "*", "sourceFilePath", "First", "parameter", "in", "the", "list", "has", "biggest", "priority" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L214-L260
andreikop/qutepart
qutepart/syntax/parser.py
ContextStack.pop
def pop(self, count): """Returns new context stack, which doesn't contain few levels """ if len(self._contexts) - 1 < count: _logger.error("#pop value is too big %d", len(self._contexts)) if len(self._contexts) > 1: return ContextStack(self._contexts[:1], self._data[:1]) else: return self return ContextStack(self._contexts[:-count], self._data[:-count])
python
def pop(self, count): """Returns new context stack, which doesn't contain few levels """ if len(self._contexts) - 1 < count: _logger.error("#pop value is too big %d", len(self._contexts)) if len(self._contexts) > 1: return ContextStack(self._contexts[:1], self._data[:1]) else: return self return ContextStack(self._contexts[:-count], self._data[:-count])
[ "def", "pop", "(", "self", ",", "count", ")", ":", "if", "len", "(", "self", ".", "_contexts", ")", "-", "1", "<", "count", ":", "_logger", ".", "error", "(", "\"#pop value is too big %d\"", ",", "len", "(", "self", ".", "_contexts", ")", ")", "if", "len", "(", "self", ".", "_contexts", ")", ">", "1", ":", "return", "ContextStack", "(", "self", ".", "_contexts", "[", ":", "1", "]", ",", "self", ".", "_data", "[", ":", "1", "]", ")", "else", ":", "return", "self", "return", "ContextStack", "(", "self", ".", "_contexts", "[", ":", "-", "count", "]", ",", "self", ".", "_data", "[", ":", "-", "count", "]", ")" ]
Returns new context stack, which doesn't contain few levels
[ "Returns", "new", "context", "stack", "which", "doesn", "t", "contain", "few", "levels" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L32-L42
andreikop/qutepart
qutepart/syntax/parser.py
ContextStack.append
def append(self, context, data): """Returns new context, which contains current stack and new frame """ return ContextStack(self._contexts + [context], self._data + [data])
python
def append(self, context, data): """Returns new context, which contains current stack and new frame """ return ContextStack(self._contexts + [context], self._data + [data])
[ "def", "append", "(", "self", ",", "context", ",", "data", ")", ":", "return", "ContextStack", "(", "self", ".", "_contexts", "+", "[", "context", "]", ",", "self", ".", "_data", "+", "[", "data", "]", ")" ]
Returns new context, which contains current stack and new frame
[ "Returns", "new", "context", "which", "contains", "current", "stack", "and", "new", "frame" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L44-L47
andreikop/qutepart
qutepart/syntax/parser.py
ContextSwitcher.getNextContextStack
def getNextContextStack(self, contextStack, data=None): """Apply modification to the contextStack. This method never modifies input parameter list """ if self._popsCount: contextStack = contextStack.pop(self._popsCount) if self._contextToSwitch is not None: if not self._contextToSwitch.dynamic: data = None contextStack = contextStack.append(self._contextToSwitch, data) return contextStack
python
def getNextContextStack(self, contextStack, data=None): """Apply modification to the contextStack. This method never modifies input parameter list """ if self._popsCount: contextStack = contextStack.pop(self._popsCount) if self._contextToSwitch is not None: if not self._contextToSwitch.dynamic: data = None contextStack = contextStack.append(self._contextToSwitch, data) return contextStack
[ "def", "getNextContextStack", "(", "self", ",", "contextStack", ",", "data", "=", "None", ")", ":", "if", "self", ".", "_popsCount", ":", "contextStack", "=", "contextStack", ".", "pop", "(", "self", ".", "_popsCount", ")", "if", "self", ".", "_contextToSwitch", "is", "not", "None", ":", "if", "not", "self", ".", "_contextToSwitch", ".", "dynamic", ":", "data", "=", "None", "contextStack", "=", "contextStack", ".", "append", "(", "self", ".", "_contextToSwitch", ",", "data", ")", "return", "contextStack" ]
Apply modification to the contextStack. This method never modifies input parameter list
[ "Apply", "modification", "to", "the", "contextStack", ".", "This", "method", "never", "modifies", "input", "parameter", "list" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L72-L84
andreikop/qutepart
qutepart/syntax/parser.py
AbstractRule.tryMatch
def tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (contextStack, count, matchedRule) or (contextStack, None, None) if doesn't match """ # Skip if column doesn't match if self.column != -1 and \ self.column != textToMatchObject.currentColumnIndex: return None if self.firstNonSpace and \ (not textToMatchObject.firstNonSpace): return None return self._tryMatch(textToMatchObject)
python
def tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (contextStack, count, matchedRule) or (contextStack, None, None) if doesn't match """ # Skip if column doesn't match if self.column != -1 and \ self.column != textToMatchObject.currentColumnIndex: return None if self.firstNonSpace and \ (not textToMatchObject.firstNonSpace): return None return self._tryMatch(textToMatchObject)
[ "def", "tryMatch", "(", "self", ",", "textToMatchObject", ")", ":", "# Skip if column doesn't match", "if", "self", ".", "column", "!=", "-", "1", "and", "self", ".", "column", "!=", "textToMatchObject", ".", "currentColumnIndex", ":", "return", "None", "if", "self", ".", "firstNonSpace", "and", "(", "not", "textToMatchObject", ".", "firstNonSpace", ")", ":", "return", "None", "return", "self", ".", "_tryMatch", "(", "textToMatchObject", ")" ]
Try to find themselves in the text. Returns (contextStack, count, matchedRule) or (contextStack, None, None) if doesn't match
[ "Try", "to", "find", "themselves", "in", "the", "text", ".", "Returns", "(", "contextStack", "count", "matchedRule", ")", "or", "(", "contextStack", "None", "None", ")", "if", "doesn", "t", "match" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L186-L199
andreikop/qutepart
qutepart/syntax/parser.py
StringDetect._makeDynamicSubsctitutions
def _makeDynamicSubsctitutions(string, contextData): """For dynamic rules, replace %d patterns with actual strings Python function, which is used by C extension. """ def _replaceFunc(escapeMatchObject): stringIndex = escapeMatchObject.group(0)[1] index = int(stringIndex) if index < len(contextData): return contextData[index] else: return escapeMatchObject.group(0) # no any replacements, return original value return _numSeqReplacer.sub(_replaceFunc, string)
python
def _makeDynamicSubsctitutions(string, contextData): """For dynamic rules, replace %d patterns with actual strings Python function, which is used by C extension. """ def _replaceFunc(escapeMatchObject): stringIndex = escapeMatchObject.group(0)[1] index = int(stringIndex) if index < len(contextData): return contextData[index] else: return escapeMatchObject.group(0) # no any replacements, return original value return _numSeqReplacer.sub(_replaceFunc, string)
[ "def", "_makeDynamicSubsctitutions", "(", "string", ",", "contextData", ")", ":", "def", "_replaceFunc", "(", "escapeMatchObject", ")", ":", "stringIndex", "=", "escapeMatchObject", ".", "group", "(", "0", ")", "[", "1", "]", "index", "=", "int", "(", "stringIndex", ")", "if", "index", "<", "len", "(", "contextData", ")", ":", "return", "contextData", "[", "index", "]", "else", ":", "return", "escapeMatchObject", ".", "group", "(", "0", ")", "# no any replacements, return original value", "return", "_numSeqReplacer", ".", "sub", "(", "_replaceFunc", ",", "string", ")" ]
For dynamic rules, replace %d patterns with actual strings Python function, which is used by C extension.
[ "For", "dynamic", "rules", "replace", "%d", "patterns", "with", "actual", "strings", "Python", "function", "which", "is", "used", "by", "C", "extension", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L304-L316
andreikop/qutepart
qutepart/syntax/parser.py
RegExpr._tryMatch
def _tryMatch(self, textToMatchObject): """Tries to parse text. If matched - saves data for dynamic context """ # Special case. if pattern starts with \b, we have to check it manually, # because string is passed to .match(..) without beginning if self.wordStart and \ (not textToMatchObject.isWordStart): return None #Special case. If pattern starts with ^ - check column number manually if self.lineStart and \ textToMatchObject.currentColumnIndex > 0: return None if self.dynamic: string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData) regExp = self._compileRegExp(string, self.insensitive, self.minimal) else: regExp = self.regExp if regExp is None: return None wholeMatch, groups = self._matchPattern(regExp, textToMatchObject.text) if wholeMatch is not None: count = len(wholeMatch) return RuleTryMatchResult(self, count, groups) else: return None
python
def _tryMatch(self, textToMatchObject): """Tries to parse text. If matched - saves data for dynamic context """ # Special case. if pattern starts with \b, we have to check it manually, # because string is passed to .match(..) without beginning if self.wordStart and \ (not textToMatchObject.isWordStart): return None #Special case. If pattern starts with ^ - check column number manually if self.lineStart and \ textToMatchObject.currentColumnIndex > 0: return None if self.dynamic: string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData) regExp = self._compileRegExp(string, self.insensitive, self.minimal) else: regExp = self.regExp if regExp is None: return None wholeMatch, groups = self._matchPattern(regExp, textToMatchObject.text) if wholeMatch is not None: count = len(wholeMatch) return RuleTryMatchResult(self, count, groups) else: return None
[ "def", "_tryMatch", "(", "self", ",", "textToMatchObject", ")", ":", "# Special case. if pattern starts with \\b, we have to check it manually,", "# because string is passed to .match(..) without beginning", "if", "self", ".", "wordStart", "and", "(", "not", "textToMatchObject", ".", "isWordStart", ")", ":", "return", "None", "#Special case. If pattern starts with ^ - check column number manually", "if", "self", ".", "lineStart", "and", "textToMatchObject", ".", "currentColumnIndex", ">", "0", ":", "return", "None", "if", "self", ".", "dynamic", ":", "string", "=", "self", ".", "_makeDynamicSubsctitutions", "(", "self", ".", "string", ",", "textToMatchObject", ".", "contextData", ")", "regExp", "=", "self", ".", "_compileRegExp", "(", "string", ",", "self", ".", "insensitive", ",", "self", ".", "minimal", ")", "else", ":", "regExp", "=", "self", ".", "regExp", "if", "regExp", "is", "None", ":", "return", "None", "wholeMatch", ",", "groups", "=", "self", ".", "_matchPattern", "(", "regExp", ",", "textToMatchObject", ".", "text", ")", "if", "wholeMatch", "is", "not", "None", ":", "count", "=", "len", "(", "wholeMatch", ")", "return", "RuleTryMatchResult", "(", "self", ",", "count", ",", "groups", ")", "else", ":", "return", "None" ]
Tries to parse text. If matched - saves data for dynamic context
[ "Tries", "to", "parse", "text", ".", "If", "matched", "-", "saves", "data", "for", "dynamic", "context" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L400-L428
andreikop/qutepart
qutepart/syntax/parser.py
RegExpr._compileRegExp
def _compileRegExp(string, insensitive, minimal): """Compile regular expression. Python function, used by C code NOTE minimal flag is not supported here, but supported on PCRE """ flags = 0 if insensitive: flags = re.IGNORECASE string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser string = string.replace('[:digit:]', '\\d') string = string.replace('[:blank:]', '\\s') try: return re.compile(string, flags) except (re.error, AssertionError) as ex: _logger.warning("Invalid pattern '%s': %s", string, str(ex)) return None
python
def _compileRegExp(string, insensitive, minimal): """Compile regular expression. Python function, used by C code NOTE minimal flag is not supported here, but supported on PCRE """ flags = 0 if insensitive: flags = re.IGNORECASE string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser string = string.replace('[:digit:]', '\\d') string = string.replace('[:blank:]', '\\s') try: return re.compile(string, flags) except (re.error, AssertionError) as ex: _logger.warning("Invalid pattern '%s': %s", string, str(ex)) return None
[ "def", "_compileRegExp", "(", "string", ",", "insensitive", ",", "minimal", ")", ":", "flags", "=", "0", "if", "insensitive", ":", "flags", "=", "re", ".", "IGNORECASE", "string", "=", "string", ".", "replace", "(", "'[_[:alnum:]]'", ",", "'[\\\\w\\\\d]'", ")", "# ad-hoc fix for C++ parser", "string", "=", "string", ".", "replace", "(", "'[:digit:]'", ",", "'\\\\d'", ")", "string", "=", "string", ".", "replace", "(", "'[:blank:]'", ",", "'\\\\s'", ")", "try", ":", "return", "re", ".", "compile", "(", "string", ",", "flags", ")", "except", "(", "re", ".", "error", ",", "AssertionError", ")", "as", "ex", ":", "_logger", ".", "warning", "(", "\"Invalid pattern '%s': %s\"", ",", "string", ",", "str", "(", "ex", ")", ")", "return", "None" ]
Compile regular expression. Python function, used by C code NOTE minimal flag is not supported here, but supported on PCRE
[ "Compile", "regular", "expression", ".", "Python", "function", "used", "by", "C", "code" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L447-L465
andreikop/qutepart
qutepart/syntax/parser.py
RegExpr._matchPattern
def _matchPattern(regExp, string): """Try to match pattern. Returns tuple (whole match, groups) or (None, None) Python function, used by C code """ match = regExp.match(string) if match is not None and match.group(0): return match.group(0), (match.group(0), ) + match.groups() else: return None, None
python
def _matchPattern(regExp, string): """Try to match pattern. Returns tuple (whole match, groups) or (None, None) Python function, used by C code """ match = regExp.match(string) if match is not None and match.group(0): return match.group(0), (match.group(0), ) + match.groups() else: return None, None
[ "def", "_matchPattern", "(", "regExp", ",", "string", ")", ":", "match", "=", "regExp", ".", "match", "(", "string", ")", "if", "match", "is", "not", "None", "and", "match", ".", "group", "(", "0", ")", ":", "return", "match", ".", "group", "(", "0", ")", ",", "(", "match", ".", "group", "(", "0", ")", ",", ")", "+", "match", ".", "groups", "(", ")", "else", ":", "return", "None", ",", "None" ]
Try to match pattern. Returns tuple (whole match, groups) or (None, None) Python function, used by C code
[ "Try", "to", "match", "pattern", ".", "Returns", "tuple", "(", "whole", "match", "groups", ")", "or", "(", "None", "None", ")", "Python", "function", "used", "by", "C", "code" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L468-L477
andreikop/qutepart
qutepart/syntax/parser.py
AbstractNumberRule._tryMatch
def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match """ # andreikop: This check is not described in kate docs, and I haven't found it in the code if not textToMatchObject.isWordStart: return None index = self._tryMatchText(textToMatchObject.text) if index is None: return None if textToMatchObject.currentColumnIndex + index < len(textToMatchObject.wholeLineText): newTextToMatchObject = TextToMatchObject(textToMatchObject.currentColumnIndex + index, textToMatchObject.wholeLineText, self.parentContext.parser.deliminatorSet, textToMatchObject.contextData) for rule in self.childRules: ruleTryMatchResult = rule.tryMatch(newTextToMatchObject) if ruleTryMatchResult is not None: index += ruleTryMatchResult.length break # child rule context and attribute ignored return RuleTryMatchResult(self, index)
python
def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match """ # andreikop: This check is not described in kate docs, and I haven't found it in the code if not textToMatchObject.isWordStart: return None index = self._tryMatchText(textToMatchObject.text) if index is None: return None if textToMatchObject.currentColumnIndex + index < len(textToMatchObject.wholeLineText): newTextToMatchObject = TextToMatchObject(textToMatchObject.currentColumnIndex + index, textToMatchObject.wholeLineText, self.parentContext.parser.deliminatorSet, textToMatchObject.contextData) for rule in self.childRules: ruleTryMatchResult = rule.tryMatch(newTextToMatchObject) if ruleTryMatchResult is not None: index += ruleTryMatchResult.length break # child rule context and attribute ignored return RuleTryMatchResult(self, index)
[ "def", "_tryMatch", "(", "self", ",", "textToMatchObject", ")", ":", "# andreikop: This check is not described in kate docs, and I haven't found it in the code", "if", "not", "textToMatchObject", ".", "isWordStart", ":", "return", "None", "index", "=", "self", ".", "_tryMatchText", "(", "textToMatchObject", ".", "text", ")", "if", "index", "is", "None", ":", "return", "None", "if", "textToMatchObject", ".", "currentColumnIndex", "+", "index", "<", "len", "(", "textToMatchObject", ".", "wholeLineText", ")", ":", "newTextToMatchObject", "=", "TextToMatchObject", "(", "textToMatchObject", ".", "currentColumnIndex", "+", "index", ",", "textToMatchObject", ".", "wholeLineText", ",", "self", ".", "parentContext", ".", "parser", ".", "deliminatorSet", ",", "textToMatchObject", ".", "contextData", ")", "for", "rule", "in", "self", ".", "childRules", ":", "ruleTryMatchResult", "=", "rule", ".", "tryMatch", "(", "newTextToMatchObject", ")", "if", "ruleTryMatchResult", "is", "not", "None", ":", "index", "+=", "ruleTryMatchResult", ".", "length", "break", "# child rule context and attribute ignored", "return", "RuleTryMatchResult", "(", "self", ",", "index", ")" ]
Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match
[ "Try", "to", "find", "themselves", "in", "the", "text", ".", "Returns", "(", "count", "matchedRule", ")", "or", "(", "None", "None", ")", "if", "doesn", "t", "match" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L491-L516
andreikop/qutepart
qutepart/syntax/parser.py
AbstractNumberRule._countDigits
def _countDigits(self, text): """Count digits at start of text """ index = 0 while index < len(text): if not text[index].isdigit(): break index += 1 return index
python
def _countDigits(self, text): """Count digits at start of text """ index = 0 while index < len(text): if not text[index].isdigit(): break index += 1 return index
[ "def", "_countDigits", "(", "self", ",", "text", ")", ":", "index", "=", "0", "while", "index", "<", "len", "(", "text", ")", ":", "if", "not", "text", "[", "index", "]", ".", "isdigit", "(", ")", ":", "break", "index", "+=", "1", "return", "index" ]
Count digits at start of text
[ "Count", "digits", "at", "start", "of", "text" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L518-L526
andreikop/qutepart
qutepart/syntax/parser.py
IncludeRules._tryMatch
def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match """ for rule in self.context.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None: _logger.debug('\tmatched rule %s at %d in included context %s/%s', rule.shortId(), textToMatchObject.currentColumnIndex, self.context.parser.syntax.name, self.context.name) return ruleTryMatchResult else: return None
python
def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match """ for rule in self.context.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None: _logger.debug('\tmatched rule %s at %d in included context %s/%s', rule.shortId(), textToMatchObject.currentColumnIndex, self.context.parser.syntax.name, self.context.name) return ruleTryMatchResult else: return None
[ "def", "_tryMatch", "(", "self", ",", "textToMatchObject", ")", ":", "for", "rule", "in", "self", ".", "context", ".", "rules", ":", "ruleTryMatchResult", "=", "rule", ".", "tryMatch", "(", "textToMatchObject", ")", "if", "ruleTryMatchResult", "is", "not", "None", ":", "_logger", ".", "debug", "(", "'\\tmatched rule %s at %d in included context %s/%s'", ",", "rule", ".", "shortId", "(", ")", ",", "textToMatchObject", ".", "currentColumnIndex", ",", "self", ".", "context", ".", "parser", ".", "syntax", ".", "name", ",", "self", ".", "context", ".", "name", ")", "return", "ruleTryMatchResult", "else", ":", "return", "None" ]
Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match
[ "Try", "to", "find", "themselves", "in", "the", "text", ".", "Returns", "(", "count", "matchedRule", ")", "or", "(", "None", "None", ")", "if", "doesn", "t", "match" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L742-L756
andreikop/qutepart
qutepart/syntax/parser.py
Context.parseBlock
def parseBlock(self, contextStack, currentColumnIndex, text): """Parse block Exits, when reached end of the text, or when context is switched Returns (length, newContextStack, highlightedSegments, lineContinue) """ startColumnIndex = currentColumnIndex countOfNotMatchedSymbols = 0 highlightedSegments = [] textTypeMap = [] ruleTryMatchResult = None while currentColumnIndex < len(text): textToMatchObject = TextToMatchObject(currentColumnIndex, text, self.parser.deliminatorSet, contextStack.currentData()) for rule in self.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None: # if something matched _logger.debug('\tmatched rule %s at %d', rule.shortId(), currentColumnIndex) if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] countOfNotMatchedSymbols = 0 if ruleTryMatchResult.rule.context is not None: newContextStack = ruleTryMatchResult.rule.context.getNextContextStack(contextStack, ruleTryMatchResult.data) else: newContextStack = contextStack format = ruleTryMatchResult.rule.format if ruleTryMatchResult.rule.attribute else newContextStack.currentContext().format textType = ruleTryMatchResult.rule.textType or newContextStack.currentContext().textType highlightedSegments.append((ruleTryMatchResult.length, format)) textTypeMap += textType * ruleTryMatchResult.length currentColumnIndex += ruleTryMatchResult.length if newContextStack != contextStack: lineContinue = isinstance(ruleTryMatchResult.rule, LineContinue) return currentColumnIndex - startColumnIndex, newContextStack, highlightedSegments, textTypeMap, lineContinue break # for loop else: # no matched rules if self.fallthroughContext is not None: newContextStack = self.fallthroughContext.getNextContextStack(contextStack) if newContextStack != contextStack: if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] return (currentColumnIndex - startColumnIndex, newContextStack, highlightedSegments, textTypeMap, False) currentColumnIndex += 1 countOfNotMatchedSymbols += 1 if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] lineContinue = ruleTryMatchResult is not None and \ isinstance(ruleTryMatchResult.rule, LineContinue) return currentColumnIndex - startColumnIndex, contextStack, highlightedSegments, textTypeMap, lineContinue
python
def parseBlock(self, contextStack, currentColumnIndex, text): """Parse block Exits, when reached end of the text, or when context is switched Returns (length, newContextStack, highlightedSegments, lineContinue) """ startColumnIndex = currentColumnIndex countOfNotMatchedSymbols = 0 highlightedSegments = [] textTypeMap = [] ruleTryMatchResult = None while currentColumnIndex < len(text): textToMatchObject = TextToMatchObject(currentColumnIndex, text, self.parser.deliminatorSet, contextStack.currentData()) for rule in self.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None: # if something matched _logger.debug('\tmatched rule %s at %d', rule.shortId(), currentColumnIndex) if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] countOfNotMatchedSymbols = 0 if ruleTryMatchResult.rule.context is not None: newContextStack = ruleTryMatchResult.rule.context.getNextContextStack(contextStack, ruleTryMatchResult.data) else: newContextStack = contextStack format = ruleTryMatchResult.rule.format if ruleTryMatchResult.rule.attribute else newContextStack.currentContext().format textType = ruleTryMatchResult.rule.textType or newContextStack.currentContext().textType highlightedSegments.append((ruleTryMatchResult.length, format)) textTypeMap += textType * ruleTryMatchResult.length currentColumnIndex += ruleTryMatchResult.length if newContextStack != contextStack: lineContinue = isinstance(ruleTryMatchResult.rule, LineContinue) return currentColumnIndex - startColumnIndex, newContextStack, highlightedSegments, textTypeMap, lineContinue break # for loop else: # no matched rules if self.fallthroughContext is not None: newContextStack = self.fallthroughContext.getNextContextStack(contextStack) if newContextStack != contextStack: if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] return (currentColumnIndex - startColumnIndex, newContextStack, highlightedSegments, textTypeMap, False) currentColumnIndex += 1 countOfNotMatchedSymbols += 1 if countOfNotMatchedSymbols > 0: highlightedSegments.append((countOfNotMatchedSymbols, self.format)) textTypeMap += [self.textType for i in range(countOfNotMatchedSymbols)] lineContinue = ruleTryMatchResult is not None and \ isinstance(ruleTryMatchResult.rule, LineContinue) return currentColumnIndex - startColumnIndex, contextStack, highlightedSegments, textTypeMap, lineContinue
[ "def", "parseBlock", "(", "self", ",", "contextStack", ",", "currentColumnIndex", ",", "text", ")", ":", "startColumnIndex", "=", "currentColumnIndex", "countOfNotMatchedSymbols", "=", "0", "highlightedSegments", "=", "[", "]", "textTypeMap", "=", "[", "]", "ruleTryMatchResult", "=", "None", "while", "currentColumnIndex", "<", "len", "(", "text", ")", ":", "textToMatchObject", "=", "TextToMatchObject", "(", "currentColumnIndex", ",", "text", ",", "self", ".", "parser", ".", "deliminatorSet", ",", "contextStack", ".", "currentData", "(", ")", ")", "for", "rule", "in", "self", ".", "rules", ":", "ruleTryMatchResult", "=", "rule", ".", "tryMatch", "(", "textToMatchObject", ")", "if", "ruleTryMatchResult", "is", "not", "None", ":", "# if something matched", "_logger", ".", "debug", "(", "'\\tmatched rule %s at %d'", ",", "rule", ".", "shortId", "(", ")", ",", "currentColumnIndex", ")", "if", "countOfNotMatchedSymbols", ">", "0", ":", "highlightedSegments", ".", "append", "(", "(", "countOfNotMatchedSymbols", ",", "self", ".", "format", ")", ")", "textTypeMap", "+=", "[", "self", ".", "textType", "for", "i", "in", "range", "(", "countOfNotMatchedSymbols", ")", "]", "countOfNotMatchedSymbols", "=", "0", "if", "ruleTryMatchResult", ".", "rule", ".", "context", "is", "not", "None", ":", "newContextStack", "=", "ruleTryMatchResult", ".", "rule", ".", "context", ".", "getNextContextStack", "(", "contextStack", ",", "ruleTryMatchResult", ".", "data", ")", "else", ":", "newContextStack", "=", "contextStack", "format", "=", "ruleTryMatchResult", ".", "rule", ".", "format", "if", "ruleTryMatchResult", ".", "rule", ".", "attribute", "else", "newContextStack", ".", "currentContext", "(", ")", ".", "format", "textType", "=", "ruleTryMatchResult", ".", "rule", ".", "textType", "or", "newContextStack", ".", "currentContext", "(", ")", ".", "textType", "highlightedSegments", ".", "append", "(", "(", "ruleTryMatchResult", ".", "length", ",", "format", ")", ")", "textTypeMap", "+=", "textType", "*", "ruleTryMatchResult", ".", "length", "currentColumnIndex", "+=", "ruleTryMatchResult", ".", "length", "if", "newContextStack", "!=", "contextStack", ":", "lineContinue", "=", "isinstance", "(", "ruleTryMatchResult", ".", "rule", ",", "LineContinue", ")", "return", "currentColumnIndex", "-", "startColumnIndex", ",", "newContextStack", ",", "highlightedSegments", ",", "textTypeMap", ",", "lineContinue", "break", "# for loop", "else", ":", "# no matched rules", "if", "self", ".", "fallthroughContext", "is", "not", "None", ":", "newContextStack", "=", "self", ".", "fallthroughContext", ".", "getNextContextStack", "(", "contextStack", ")", "if", "newContextStack", "!=", "contextStack", ":", "if", "countOfNotMatchedSymbols", ">", "0", ":", "highlightedSegments", ".", "append", "(", "(", "countOfNotMatchedSymbols", ",", "self", ".", "format", ")", ")", "textTypeMap", "+=", "[", "self", ".", "textType", "for", "i", "in", "range", "(", "countOfNotMatchedSymbols", ")", "]", "return", "(", "currentColumnIndex", "-", "startColumnIndex", ",", "newContextStack", ",", "highlightedSegments", ",", "textTypeMap", ",", "False", ")", "currentColumnIndex", "+=", "1", "countOfNotMatchedSymbols", "+=", "1", "if", "countOfNotMatchedSymbols", ">", "0", ":", "highlightedSegments", ".", "append", "(", "(", "countOfNotMatchedSymbols", ",", "self", ".", "format", ")", ")", "textTypeMap", "+=", "[", "self", ".", "textType", "for", "i", "in", "range", "(", "countOfNotMatchedSymbols", ")", "]", "lineContinue", "=", "ruleTryMatchResult", "is", "not", "None", "and", "isinstance", "(", "ruleTryMatchResult", ".", "rule", ",", "LineContinue", ")", "return", "currentColumnIndex", "-", "startColumnIndex", ",", "contextStack", ",", "highlightedSegments", ",", "textTypeMap", ",", "lineContinue" ]
Parse block Exits, when reached end of the text, or when context is switched Returns (length, newContextStack, highlightedSegments, lineContinue)
[ "Parse", "block", "Exits", "when", "reached", "end", "of", "the", "text", "or", "when", "context", "is", "switched", "Returns", "(", "length", "newContextStack", "highlightedSegments", "lineContinue", ")" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L831-L897
andreikop/qutepart
qutepart/syntax/parser.py
Parser.highlightBlock
def highlightBlock(self, text, prevContextStack): """Parse block and return ParseBlockFullResult return (lineData, highlightedSegments) where lineData is (contextStack, textTypeMap) where textTypeMap is a string of textType characters """ if prevContextStack is not None: contextStack = prevContextStack else: contextStack = self._defaultContextStack highlightedSegments = [] lineContinue = False currentColumnIndex = 0 textTypeMap = [] if len(text) > 0: while currentColumnIndex < len(text): _logger.debug('In context %s', contextStack.currentContext().name) length, newContextStack, segments, textTypeMapPart, lineContinue = \ contextStack.currentContext().parseBlock(contextStack, currentColumnIndex, text) highlightedSegments += segments contextStack = newContextStack textTypeMap += textTypeMapPart currentColumnIndex += length if not lineContinue: while contextStack.currentContext().lineEndContext is not None: oldStack = contextStack contextStack = contextStack.currentContext().lineEndContext.getNextContextStack(contextStack) if oldStack == contextStack: # avoid infinite while loop if nothing to switch break # this code is not tested, because lineBeginContext is not defined by any xml file if contextStack.currentContext().lineBeginContext is not None: contextStack = contextStack.currentContext().lineBeginContext.getNextContextStack(contextStack) elif contextStack.currentContext().lineEmptyContext is not None: contextStack = contextStack.currentContext().lineEmptyContext.getNextContextStack(contextStack) lineData = (contextStack, textTypeMap) return lineData, highlightedSegments
python
def highlightBlock(self, text, prevContextStack): """Parse block and return ParseBlockFullResult return (lineData, highlightedSegments) where lineData is (contextStack, textTypeMap) where textTypeMap is a string of textType characters """ if prevContextStack is not None: contextStack = prevContextStack else: contextStack = self._defaultContextStack highlightedSegments = [] lineContinue = False currentColumnIndex = 0 textTypeMap = [] if len(text) > 0: while currentColumnIndex < len(text): _logger.debug('In context %s', contextStack.currentContext().name) length, newContextStack, segments, textTypeMapPart, lineContinue = \ contextStack.currentContext().parseBlock(contextStack, currentColumnIndex, text) highlightedSegments += segments contextStack = newContextStack textTypeMap += textTypeMapPart currentColumnIndex += length if not lineContinue: while contextStack.currentContext().lineEndContext is not None: oldStack = contextStack contextStack = contextStack.currentContext().lineEndContext.getNextContextStack(contextStack) if oldStack == contextStack: # avoid infinite while loop if nothing to switch break # this code is not tested, because lineBeginContext is not defined by any xml file if contextStack.currentContext().lineBeginContext is not None: contextStack = contextStack.currentContext().lineBeginContext.getNextContextStack(contextStack) elif contextStack.currentContext().lineEmptyContext is not None: contextStack = contextStack.currentContext().lineEmptyContext.getNextContextStack(contextStack) lineData = (contextStack, textTypeMap) return lineData, highlightedSegments
[ "def", "highlightBlock", "(", "self", ",", "text", ",", "prevContextStack", ")", ":", "if", "prevContextStack", "is", "not", "None", ":", "contextStack", "=", "prevContextStack", "else", ":", "contextStack", "=", "self", ".", "_defaultContextStack", "highlightedSegments", "=", "[", "]", "lineContinue", "=", "False", "currentColumnIndex", "=", "0", "textTypeMap", "=", "[", "]", "if", "len", "(", "text", ")", ">", "0", ":", "while", "currentColumnIndex", "<", "len", "(", "text", ")", ":", "_logger", ".", "debug", "(", "'In context %s'", ",", "contextStack", ".", "currentContext", "(", ")", ".", "name", ")", "length", ",", "newContextStack", ",", "segments", ",", "textTypeMapPart", ",", "lineContinue", "=", "contextStack", ".", "currentContext", "(", ")", ".", "parseBlock", "(", "contextStack", ",", "currentColumnIndex", ",", "text", ")", "highlightedSegments", "+=", "segments", "contextStack", "=", "newContextStack", "textTypeMap", "+=", "textTypeMapPart", "currentColumnIndex", "+=", "length", "if", "not", "lineContinue", ":", "while", "contextStack", ".", "currentContext", "(", ")", ".", "lineEndContext", "is", "not", "None", ":", "oldStack", "=", "contextStack", "contextStack", "=", "contextStack", ".", "currentContext", "(", ")", ".", "lineEndContext", ".", "getNextContextStack", "(", "contextStack", ")", "if", "oldStack", "==", "contextStack", ":", "# avoid infinite while loop if nothing to switch", "break", "# this code is not tested, because lineBeginContext is not defined by any xml file", "if", "contextStack", ".", "currentContext", "(", ")", ".", "lineBeginContext", "is", "not", "None", ":", "contextStack", "=", "contextStack", ".", "currentContext", "(", ")", ".", "lineBeginContext", ".", "getNextContextStack", "(", "contextStack", ")", "elif", "contextStack", ".", "currentContext", "(", ")", ".", "lineEmptyContext", "is", "not", "None", ":", "contextStack", "=", "contextStack", ".", "currentContext", "(", ")", ".", "lineEmptyContext", ".", "getNextContextStack", "(", "contextStack", ")", "lineData", "=", "(", "contextStack", ",", "textTypeMap", ")", "return", "lineData", ",", "highlightedSegments" ]
Parse block and return ParseBlockFullResult return (lineData, highlightedSegments) where lineData is (contextStack, textTypeMap) where textTypeMap is a string of textType characters
[ "Parse", "block", "and", "return", "ParseBlockFullResult" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L948-L991
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.findTextBackward
def findTextBackward(self, block, column, needle): """Search for a needle and return (block, column) Raise ValueError, if not found """ if column is not None: index = block.text()[:column].rfind(needle) else: index = block.text().rfind(needle) if index != -1: return block, index for block in self.iterateBlocksBackFrom(block.previous()): column = block.text().rfind(needle) if column != -1: return block, column raise ValueError('Not found')
python
def findTextBackward(self, block, column, needle): """Search for a needle and return (block, column) Raise ValueError, if not found """ if column is not None: index = block.text()[:column].rfind(needle) else: index = block.text().rfind(needle) if index != -1: return block, index for block in self.iterateBlocksBackFrom(block.previous()): column = block.text().rfind(needle) if column != -1: return block, column raise ValueError('Not found')
[ "def", "findTextBackward", "(", "self", ",", "block", ",", "column", ",", "needle", ")", ":", "if", "column", "is", "not", "None", ":", "index", "=", "block", ".", "text", "(", ")", "[", ":", "column", "]", ".", "rfind", "(", "needle", ")", "else", ":", "index", "=", "block", ".", "text", "(", ")", ".", "rfind", "(", "needle", ")", "if", "index", "!=", "-", "1", ":", "return", "block", ",", "index", "for", "block", "in", "self", ".", "iterateBlocksBackFrom", "(", "block", ".", "previous", "(", ")", ")", ":", "column", "=", "block", ".", "text", "(", ")", ".", "rfind", "(", "needle", ")", "if", "column", "!=", "-", "1", ":", "return", "block", ",", "column", "raise", "ValueError", "(", "'Not found'", ")" ]
Search for a needle and return (block, column) Raise ValueError, if not found
[ "Search", "for", "a", "needle", "and", "return", "(", "block", "column", ")", "Raise", "ValueError", "if", "not", "found" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L47-L64
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.findLeftBrace
def findLeftBrace(self, block, column): """Search for a corresponding '{' and return its indentation If not found return None """ block, column = self.findBracketBackward(block, column, '{') # raise ValueError if not found try: block, column = self.tryParenthesisBeforeBrace(block, column) except ValueError: pass # leave previous values return self._blockIndent(block)
python
def findLeftBrace(self, block, column): """Search for a corresponding '{' and return its indentation If not found return None """ block, column = self.findBracketBackward(block, column, '{') # raise ValueError if not found try: block, column = self.tryParenthesisBeforeBrace(block, column) except ValueError: pass # leave previous values return self._blockIndent(block)
[ "def", "findLeftBrace", "(", "self", ",", "block", ",", "column", ")", ":", "block", ",", "column", "=", "self", ".", "findBracketBackward", "(", "block", ",", "column", ",", "'{'", ")", "# raise ValueError if not found", "try", ":", "block", ",", "column", "=", "self", ".", "tryParenthesisBeforeBrace", "(", "block", ",", "column", ")", "except", "ValueError", ":", "pass", "# leave previous values", "return", "self", ".", "_blockIndent", "(", "block", ")" ]
Search for a corresponding '{' and return its indentation If not found return None
[ "Search", "for", "a", "corresponding", "{", "and", "return", "its", "indentation", "If", "not", "found", "return", "None" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L66-L76
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryParenthesisBeforeBrace
def tryParenthesisBeforeBrace(self, block, column): """ Character at (block, column) has to be a '{'. Now try to find the right line for indentation for constructs like: if (a == b and c == d) { <- check for ')', and find '(', then return its indentation Returns input params, if no success, otherwise block and column of '(' """ text = block.text()[:column - 1].rstrip() if not text.endswith(')'): raise ValueError() return self.findBracketBackward(block, len(text) - 1, '(')
python
def tryParenthesisBeforeBrace(self, block, column): """ Character at (block, column) has to be a '{'. Now try to find the right line for indentation for constructs like: if (a == b and c == d) { <- check for ')', and find '(', then return its indentation Returns input params, if no success, otherwise block and column of '(' """ text = block.text()[:column - 1].rstrip() if not text.endswith(')'): raise ValueError() return self.findBracketBackward(block, len(text) - 1, '(')
[ "def", "tryParenthesisBeforeBrace", "(", "self", ",", "block", ",", "column", ")", ":", "text", "=", "block", ".", "text", "(", ")", "[", ":", "column", "-", "1", "]", ".", "rstrip", "(", ")", "if", "not", "text", ".", "endswith", "(", "')'", ")", ":", "raise", "ValueError", "(", ")", "return", "self", ".", "findBracketBackward", "(", "block", ",", "len", "(", "text", ")", "-", "1", ",", "'('", ")" ]
Character at (block, column) has to be a '{'. Now try to find the right line for indentation for constructs like: if (a == b and c == d) { <- check for ')', and find '(', then return its indentation Returns input params, if no success, otherwise block and column of '('
[ "Character", "at", "(", "block", "column", ")", "has", "to", "be", "a", "{", ".", "Now", "try", "to", "find", "the", "right", "line", "for", "indentation", "for", "constructs", "like", ":", "if", "(", "a", "==", "b", "and", "c", "==", "d", ")", "{", "<", "-", "check", "for", ")", "and", "find", "(", "then", "return", "its", "indentation", "Returns", "input", "params", "if", "no", "success", "otherwise", "block", "and", "column", "of", "(" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L78-L88
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.trySwitchStatement
def trySwitchStatement(self, block): """Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found. """ if not re.match(r'^\s*(default\s*|case\b.*):', block.text()): return None for block in self.iterateBlocksBackFrom(block.previous()): text = block.text() if re.match(r"^\s*(default\s*|case\b.*):", text): dbg("trySwitchStatement: success in line %d" % block.blockNumber()) return self._lineIndent(text) elif re.match(r"^\s*switch\b", text): if CFG_INDENT_CASE: return self._increaseIndent(self._lineIndent(text)) else: return self._lineIndent(text) return None
python
def trySwitchStatement(self, block): """Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found. """ if not re.match(r'^\s*(default\s*|case\b.*):', block.text()): return None for block in self.iterateBlocksBackFrom(block.previous()): text = block.text() if re.match(r"^\s*(default\s*|case\b.*):", text): dbg("trySwitchStatement: success in line %d" % block.blockNumber()) return self._lineIndent(text) elif re.match(r"^\s*switch\b", text): if CFG_INDENT_CASE: return self._increaseIndent(self._lineIndent(text)) else: return self._lineIndent(text) return None
[ "def", "trySwitchStatement", "(", "self", ",", "block", ")", ":", "if", "not", "re", ".", "match", "(", "r'^\\s*(default\\s*|case\\b.*):'", ",", "block", ".", "text", "(", ")", ")", ":", "return", "None", "for", "block", "in", "self", ".", "iterateBlocksBackFrom", "(", "block", ".", "previous", "(", ")", ")", ":", "text", "=", "block", ".", "text", "(", ")", "if", "re", ".", "match", "(", "r\"^\\s*(default\\s*|case\\b.*):\"", ",", "text", ")", ":", "dbg", "(", "\"trySwitchStatement: success in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "self", ".", "_lineIndent", "(", "text", ")", "elif", "re", ".", "match", "(", "r\"^\\s*switch\\b\"", ",", "text", ")", ":", "if", "CFG_INDENT_CASE", ":", "return", "self", ".", "_increaseIndent", "(", "self", ".", "_lineIndent", "(", "text", ")", ")", "else", ":", "return", "self", ".", "_lineIndent", "(", "text", ")", "return", "None" ]
Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found.
[ "Check", "for", "default", "and", "case", "keywords", "and", "assume", "we", "are", "in", "a", "switch", "statement", ".", "Try", "to", "find", "a", "previous", "default", "case", "or", "switch", "and", "return", "its", "indentation", "or", "None", "if", "not", "found", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L90-L109
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryAccessModifiers
def tryAccessModifiers(self, block): """Check for private, protected, public, signals etc... and assume we are in a class definition. Try to find a previous private/protected/private... or class and return its indentation or null if not found. """ if CFG_ACCESS_MODIFIERS < 0: return None if not re.match(r'^\s*((public|protected|private)\s*(slots|Q_SLOTS)?|(signals|Q_SIGNALS)\s*):\s*$', block.text()): return None try: block, notUsedColumn = self.findBracketBackward(block, 0, '{') except ValueError: return None indentation = self._blockIndent(block) for i in range(CFG_ACCESS_MODIFIERS): indentation = self._increaseIndent(indentation) dbg("tryAccessModifiers: success in line %d" % block.blockNumber()) return indentation
python
def tryAccessModifiers(self, block): """Check for private, protected, public, signals etc... and assume we are in a class definition. Try to find a previous private/protected/private... or class and return its indentation or null if not found. """ if CFG_ACCESS_MODIFIERS < 0: return None if not re.match(r'^\s*((public|protected|private)\s*(slots|Q_SLOTS)?|(signals|Q_SIGNALS)\s*):\s*$', block.text()): return None try: block, notUsedColumn = self.findBracketBackward(block, 0, '{') except ValueError: return None indentation = self._blockIndent(block) for i in range(CFG_ACCESS_MODIFIERS): indentation = self._increaseIndent(indentation) dbg("tryAccessModifiers: success in line %d" % block.blockNumber()) return indentation
[ "def", "tryAccessModifiers", "(", "self", ",", "block", ")", ":", "if", "CFG_ACCESS_MODIFIERS", "<", "0", ":", "return", "None", "if", "not", "re", ".", "match", "(", "r'^\\s*((public|protected|private)\\s*(slots|Q_SLOTS)?|(signals|Q_SIGNALS)\\s*):\\s*$'", ",", "block", ".", "text", "(", ")", ")", ":", "return", "None", "try", ":", "block", ",", "notUsedColumn", "=", "self", ".", "findBracketBackward", "(", "block", ",", "0", ",", "'{'", ")", "except", "ValueError", ":", "return", "None", "indentation", "=", "self", ".", "_blockIndent", "(", "block", ")", "for", "i", "in", "range", "(", "CFG_ACCESS_MODIFIERS", ")", ":", "indentation", "=", "self", ".", "_increaseIndent", "(", "indentation", ")", "dbg", "(", "\"tryAccessModifiers: success in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "indentation" ]
Check for private, protected, public, signals etc... and assume we are in a class definition. Try to find a previous private/protected/private... or class and return its indentation or null if not found.
[ "Check", "for", "private", "protected", "public", "signals", "etc", "...", "and", "assume", "we", "are", "in", "a", "class", "definition", ".", "Try", "to", "find", "a", "previous", "private", "/", "protected", "/", "private", "...", "or", "class", "and", "return", "its", "indentation", "or", "null", "if", "not", "found", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L111-L133
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryCComment
def tryCComment(self, block): """C comment checking. If the previous line begins with a "/*" or a "* ", then return its leading white spaces + ' *' + the white spaces after the * return: filler string or null, if not in a C comment """ indentation = None prevNonEmptyBlock = self._prevNonEmptyBlock(block) if not prevNonEmptyBlock.isValid(): return None prevNonEmptyBlockText = prevNonEmptyBlock.text() if prevNonEmptyBlockText.endswith('*/'): try: foundBlock, notUsedColumn = self.findTextBackward(prevNonEmptyBlock, prevNonEmptyBlock.length(), '/*') except ValueError: foundBlock = None if foundBlock is not None: dbg("tryCComment: success (1) in line %d" % foundBlock.blockNumber()) return self._lineIndent(foundBlock.text()) if prevNonEmptyBlock != block.previous(): # inbetween was an empty line, so do not copy the "*" character return None blockTextStripped = block.text().strip() prevBlockTextStripped = prevNonEmptyBlockText.strip() if prevBlockTextStripped.startswith('/*') and not '*/' in prevBlockTextStripped: indentation = self._blockIndent(prevNonEmptyBlock) if CFG_AUTO_INSERT_STAR: # only add '*', if there is none yet. indentation += ' ' if not blockTextStripped.endswith('*'): indentation += '*' secondCharIsSpace = len(blockTextStripped) > 1 and blockTextStripped[1].isspace() if not secondCharIsSpace and \ not blockTextStripped.endswith("*/"): indentation += ' ' dbg("tryCComment: success (2) in line %d" % block.blockNumber()) return indentation elif prevBlockTextStripped.startswith('*') and \ (len(prevBlockTextStripped) == 1 or prevBlockTextStripped[1].isspace()): # in theory, we could search for opening /*, and use its indentation # and then one alignment character. Let's not do this for now, though. indentation = self._lineIndent(prevNonEmptyBlockText) # only add '*', if there is none yet. if CFG_AUTO_INSERT_STAR and not blockTextStripped.startswith('*'): indentation += '*' if len(blockTextStripped) < 2 or not blockTextStripped[1].isspace(): indentation += ' ' dbg("tryCComment: success (2) in line %d" % block.blockNumber()) return indentation return None
python
def tryCComment(self, block): """C comment checking. If the previous line begins with a "/*" or a "* ", then return its leading white spaces + ' *' + the white spaces after the * return: filler string or null, if not in a C comment """ indentation = None prevNonEmptyBlock = self._prevNonEmptyBlock(block) if not prevNonEmptyBlock.isValid(): return None prevNonEmptyBlockText = prevNonEmptyBlock.text() if prevNonEmptyBlockText.endswith('*/'): try: foundBlock, notUsedColumn = self.findTextBackward(prevNonEmptyBlock, prevNonEmptyBlock.length(), '/*') except ValueError: foundBlock = None if foundBlock is not None: dbg("tryCComment: success (1) in line %d" % foundBlock.blockNumber()) return self._lineIndent(foundBlock.text()) if prevNonEmptyBlock != block.previous(): # inbetween was an empty line, so do not copy the "*" character return None blockTextStripped = block.text().strip() prevBlockTextStripped = prevNonEmptyBlockText.strip() if prevBlockTextStripped.startswith('/*') and not '*/' in prevBlockTextStripped: indentation = self._blockIndent(prevNonEmptyBlock) if CFG_AUTO_INSERT_STAR: # only add '*', if there is none yet. indentation += ' ' if not blockTextStripped.endswith('*'): indentation += '*' secondCharIsSpace = len(blockTextStripped) > 1 and blockTextStripped[1].isspace() if not secondCharIsSpace and \ not blockTextStripped.endswith("*/"): indentation += ' ' dbg("tryCComment: success (2) in line %d" % block.blockNumber()) return indentation elif prevBlockTextStripped.startswith('*') and \ (len(prevBlockTextStripped) == 1 or prevBlockTextStripped[1].isspace()): # in theory, we could search for opening /*, and use its indentation # and then one alignment character. Let's not do this for now, though. indentation = self._lineIndent(prevNonEmptyBlockText) # only add '*', if there is none yet. if CFG_AUTO_INSERT_STAR and not blockTextStripped.startswith('*'): indentation += '*' if len(blockTextStripped) < 2 or not blockTextStripped[1].isspace(): indentation += ' ' dbg("tryCComment: success (2) in line %d" % block.blockNumber()) return indentation return None
[ "def", "tryCComment", "(", "self", ",", "block", ")", ":", "indentation", "=", "None", "prevNonEmptyBlock", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", "if", "not", "prevNonEmptyBlock", ".", "isValid", "(", ")", ":", "return", "None", "prevNonEmptyBlockText", "=", "prevNonEmptyBlock", ".", "text", "(", ")", "if", "prevNonEmptyBlockText", ".", "endswith", "(", "'*/'", ")", ":", "try", ":", "foundBlock", ",", "notUsedColumn", "=", "self", ".", "findTextBackward", "(", "prevNonEmptyBlock", ",", "prevNonEmptyBlock", ".", "length", "(", ")", ",", "'/*'", ")", "except", "ValueError", ":", "foundBlock", "=", "None", "if", "foundBlock", "is", "not", "None", ":", "dbg", "(", "\"tryCComment: success (1) in line %d\"", "%", "foundBlock", ".", "blockNumber", "(", ")", ")", "return", "self", ".", "_lineIndent", "(", "foundBlock", ".", "text", "(", ")", ")", "if", "prevNonEmptyBlock", "!=", "block", ".", "previous", "(", ")", ":", "# inbetween was an empty line, so do not copy the \"*\" character", "return", "None", "blockTextStripped", "=", "block", ".", "text", "(", ")", ".", "strip", "(", ")", "prevBlockTextStripped", "=", "prevNonEmptyBlockText", ".", "strip", "(", ")", "if", "prevBlockTextStripped", ".", "startswith", "(", "'/*'", ")", "and", "not", "'*/'", "in", "prevBlockTextStripped", ":", "indentation", "=", "self", ".", "_blockIndent", "(", "prevNonEmptyBlock", ")", "if", "CFG_AUTO_INSERT_STAR", ":", "# only add '*', if there is none yet.", "indentation", "+=", "' '", "if", "not", "blockTextStripped", ".", "endswith", "(", "'*'", ")", ":", "indentation", "+=", "'*'", "secondCharIsSpace", "=", "len", "(", "blockTextStripped", ")", ">", "1", "and", "blockTextStripped", "[", "1", "]", ".", "isspace", "(", ")", "if", "not", "secondCharIsSpace", "and", "not", "blockTextStripped", ".", "endswith", "(", "\"*/\"", ")", ":", "indentation", "+=", "' '", "dbg", "(", "\"tryCComment: success (2) in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "indentation", "elif", "prevBlockTextStripped", ".", "startswith", "(", "'*'", ")", "and", "(", "len", "(", "prevBlockTextStripped", ")", "==", "1", "or", "prevBlockTextStripped", "[", "1", "]", ".", "isspace", "(", ")", ")", ":", "# in theory, we could search for opening /*, and use its indentation", "# and then one alignment character. Let's not do this for now, though.", "indentation", "=", "self", ".", "_lineIndent", "(", "prevNonEmptyBlockText", ")", "# only add '*', if there is none yet.", "if", "CFG_AUTO_INSERT_STAR", "and", "not", "blockTextStripped", ".", "startswith", "(", "'*'", ")", ":", "indentation", "+=", "'*'", "if", "len", "(", "blockTextStripped", ")", "<", "2", "or", "not", "blockTextStripped", "[", "1", "]", ".", "isspace", "(", ")", ":", "indentation", "+=", "' '", "dbg", "(", "\"tryCComment: success (2) in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "indentation", "return", "None" ]
C comment checking. If the previous line begins with a "/*" or a "* ", then return its leading white spaces + ' *' + the white spaces after the * return: filler string or null, if not in a C comment
[ "C", "comment", "checking", ".", "If", "the", "previous", "line", "begins", "with", "a", "/", "*", "or", "a", "*", "then", "return", "its", "leading", "white", "spaces", "+", "*", "+", "the", "white", "spaces", "after", "the", "*", "return", ":", "filler", "string", "or", "null", "if", "not", "in", "a", "C", "comment" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L135-L194
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryCppComment
def tryCppComment(self, block): """C++ comment checking. when we want to insert slashes: #, #/, #! #/<, #!< and ##... return: filler string or null, if not in a star comment NOTE: otherwise comments get skipped generally and we use the last code-line """ if not block.previous().isValid() or \ not CFG_AUTO_INSERT_SLACHES: return None prevLineText = block.previous().text() indentation = None comment = prevLineText.lstrip().startswith('#') # allowed are: #, #/, #! #/<, #!< and ##... if comment: prevLineText = block.previous().text() lstrippedText = block.previous().text().lstrip() if len(lstrippedText) >= 4: char3 = lstrippedText[2] char4 = lstrippedText[3] indentation = self._lineIndent(prevLineText) if CFG_AUTO_INSERT_SLACHES: if prevLineText[2:4] == '//': # match ##... and replace by only two: # match = re.match(r'^\s*(\/\/)', prevLineText) elif (char3 == '/' or char3 == '!'): # match #/, #!, #/< and #! match = re.match(r'^\s*(\/\/[\/!][<]?\s*)', prevLineText) else: # only #, nothing else: match = re.match(r'^\s*(\/\/\s*)', prevLineText) if match is not None: self._qpart.insertText((block.blockNumber(), 0), match.group(1)) if indentation is not None: dbg("tryCppComment: success in line %d" % block.previous().blockNumber()) return indentation
python
def tryCppComment(self, block): """C++ comment checking. when we want to insert slashes: #, #/, #! #/<, #!< and ##... return: filler string or null, if not in a star comment NOTE: otherwise comments get skipped generally and we use the last code-line """ if not block.previous().isValid() or \ not CFG_AUTO_INSERT_SLACHES: return None prevLineText = block.previous().text() indentation = None comment = prevLineText.lstrip().startswith('#') # allowed are: #, #/, #! #/<, #!< and ##... if comment: prevLineText = block.previous().text() lstrippedText = block.previous().text().lstrip() if len(lstrippedText) >= 4: char3 = lstrippedText[2] char4 = lstrippedText[3] indentation = self._lineIndent(prevLineText) if CFG_AUTO_INSERT_SLACHES: if prevLineText[2:4] == '//': # match ##... and replace by only two: # match = re.match(r'^\s*(\/\/)', prevLineText) elif (char3 == '/' or char3 == '!'): # match #/, #!, #/< and #! match = re.match(r'^\s*(\/\/[\/!][<]?\s*)', prevLineText) else: # only #, nothing else: match = re.match(r'^\s*(\/\/\s*)', prevLineText) if match is not None: self._qpart.insertText((block.blockNumber(), 0), match.group(1)) if indentation is not None: dbg("tryCppComment: success in line %d" % block.previous().blockNumber()) return indentation
[ "def", "tryCppComment", "(", "self", ",", "block", ")", ":", "if", "not", "block", ".", "previous", "(", ")", ".", "isValid", "(", ")", "or", "not", "CFG_AUTO_INSERT_SLACHES", ":", "return", "None", "prevLineText", "=", "block", ".", "previous", "(", ")", ".", "text", "(", ")", "indentation", "=", "None", "comment", "=", "prevLineText", ".", "lstrip", "(", ")", ".", "startswith", "(", "'#'", ")", "# allowed are: #, #/, #! #/<, #!< and ##...", "if", "comment", ":", "prevLineText", "=", "block", ".", "previous", "(", ")", ".", "text", "(", ")", "lstrippedText", "=", "block", ".", "previous", "(", ")", ".", "text", "(", ")", ".", "lstrip", "(", ")", "if", "len", "(", "lstrippedText", ")", ">=", "4", ":", "char3", "=", "lstrippedText", "[", "2", "]", "char4", "=", "lstrippedText", "[", "3", "]", "indentation", "=", "self", ".", "_lineIndent", "(", "prevLineText", ")", "if", "CFG_AUTO_INSERT_SLACHES", ":", "if", "prevLineText", "[", "2", ":", "4", "]", "==", "'//'", ":", "# match ##... and replace by only two: #", "match", "=", "re", ".", "match", "(", "r'^\\s*(\\/\\/)'", ",", "prevLineText", ")", "elif", "(", "char3", "==", "'/'", "or", "char3", "==", "'!'", ")", ":", "# match #/, #!, #/< and #!", "match", "=", "re", ".", "match", "(", "r'^\\s*(\\/\\/[\\/!][<]?\\s*)'", ",", "prevLineText", ")", "else", ":", "# only #, nothing else:", "match", "=", "re", ".", "match", "(", "r'^\\s*(\\/\\/\\s*)'", ",", "prevLineText", ")", "if", "match", "is", "not", "None", ":", "self", ".", "_qpart", ".", "insertText", "(", "(", "block", ".", "blockNumber", "(", ")", ",", "0", ")", ",", "match", ".", "group", "(", "1", ")", ")", "if", "indentation", "is", "not", "None", ":", "dbg", "(", "\"tryCppComment: success in line %d\"", "%", "block", ".", "previous", "(", ")", ".", "blockNumber", "(", ")", ")", "return", "indentation" ]
C++ comment checking. when we want to insert slashes: #, #/, #! #/<, #!< and ##... return: filler string or null, if not in a star comment NOTE: otherwise comments get skipped generally and we use the last code-line
[ "C", "++", "comment", "checking", ".", "when", "we", "want", "to", "insert", "slashes", ":", "#", "#", "/", "#!", "#", "/", "<", "#!<", "and", "##", "...", "return", ":", "filler", "string", "or", "null", "if", "not", "in", "a", "star", "comment", "NOTE", ":", "otherwise", "comments", "get", "skipped", "generally", "and", "we", "use", "the", "last", "code", "-", "line" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L196-L238
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryCKeywords
def tryCKeywords(self, block, isBrace): """ Check for if, else, while, do, switch, private, public, protected, signals, default, case etc... keywords, as we want to indent then. If is non-null/True, then indentation is not increased. Note: The code is written to be called *after* tryCComment and tryCppComment! """ currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None # if line ends with ')', find the '(' and check this line then. if currentBlock.text().rstrip().endswith(')'): try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(currentBlock.text()), '(') except ValueError: pass else: currentBlock = foundBlock # found non-empty line currentBlockText = currentBlock.text() if re.match(r'^\s*(if\b|for|do\b|while|switch|[}]?\s*else|((private|public|protected|case|default|signals|Q_SIGNALS).*:))', currentBlockText) is None: return None indentation = None # ignore trailing comments see: https:#bugs.kde.org/show_bug.cgi?id=189339 try: index = currentBlockText.index('//') except ValueError: pass else: currentBlockText = currentBlockText[:index] # try to ignore lines like: if (a) b; or if (a) { b; } if not currentBlockText.endswith(';') and \ not currentBlockText.endswith('}'): # take its indentation and add one indentation level indentation = self._lineIndent(currentBlockText) if not isBrace: indentation = self._increaseIndent(indentation) elif currentBlockText.endswith(';'): # stuff like: # for(int b; # b < 10; # --b) try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, None, '(') except ValueError: pass else: dbg("tryCKeywords: success 1 in line %d" % block.blockNumber()) return self._makeIndentAsColumn(foundBlock, foundColumn, 1) if indentation is not None: dbg("tryCKeywords: success in line %d" % block.blockNumber()) return indentation
python
def tryCKeywords(self, block, isBrace): """ Check for if, else, while, do, switch, private, public, protected, signals, default, case etc... keywords, as we want to indent then. If is non-null/True, then indentation is not increased. Note: The code is written to be called *after* tryCComment and tryCppComment! """ currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None # if line ends with ')', find the '(' and check this line then. if currentBlock.text().rstrip().endswith(')'): try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(currentBlock.text()), '(') except ValueError: pass else: currentBlock = foundBlock # found non-empty line currentBlockText = currentBlock.text() if re.match(r'^\s*(if\b|for|do\b|while|switch|[}]?\s*else|((private|public|protected|case|default|signals|Q_SIGNALS).*:))', currentBlockText) is None: return None indentation = None # ignore trailing comments see: https:#bugs.kde.org/show_bug.cgi?id=189339 try: index = currentBlockText.index('//') except ValueError: pass else: currentBlockText = currentBlockText[:index] # try to ignore lines like: if (a) b; or if (a) { b; } if not currentBlockText.endswith(';') and \ not currentBlockText.endswith('}'): # take its indentation and add one indentation level indentation = self._lineIndent(currentBlockText) if not isBrace: indentation = self._increaseIndent(indentation) elif currentBlockText.endswith(';'): # stuff like: # for(int b; # b < 10; # --b) try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, None, '(') except ValueError: pass else: dbg("tryCKeywords: success 1 in line %d" % block.blockNumber()) return self._makeIndentAsColumn(foundBlock, foundColumn, 1) if indentation is not None: dbg("tryCKeywords: success in line %d" % block.blockNumber()) return indentation
[ "def", "tryCKeywords", "(", "self", ",", "block", ",", "isBrace", ")", ":", "currentBlock", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", "if", "not", "currentBlock", ".", "isValid", "(", ")", ":", "return", "None", "# if line ends with ')', find the '(' and check this line then.", "if", "currentBlock", ".", "text", "(", ")", ".", "rstrip", "(", ")", ".", "endswith", "(", "')'", ")", ":", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "findBracketBackward", "(", "currentBlock", ",", "len", "(", "currentBlock", ".", "text", "(", ")", ")", ",", "'('", ")", "except", "ValueError", ":", "pass", "else", ":", "currentBlock", "=", "foundBlock", "# found non-empty line", "currentBlockText", "=", "currentBlock", ".", "text", "(", ")", "if", "re", ".", "match", "(", "r'^\\s*(if\\b|for|do\\b|while|switch|[}]?\\s*else|((private|public|protected|case|default|signals|Q_SIGNALS).*:))'", ",", "currentBlockText", ")", "is", "None", ":", "return", "None", "indentation", "=", "None", "# ignore trailing comments see: https:#bugs.kde.org/show_bug.cgi?id=189339", "try", ":", "index", "=", "currentBlockText", ".", "index", "(", "'//'", ")", "except", "ValueError", ":", "pass", "else", ":", "currentBlockText", "=", "currentBlockText", "[", ":", "index", "]", "# try to ignore lines like: if (a) b; or if (a) { b; }", "if", "not", "currentBlockText", ".", "endswith", "(", "';'", ")", "and", "not", "currentBlockText", ".", "endswith", "(", "'}'", ")", ":", "# take its indentation and add one indentation level", "indentation", "=", "self", ".", "_lineIndent", "(", "currentBlockText", ")", "if", "not", "isBrace", ":", "indentation", "=", "self", ".", "_increaseIndent", "(", "indentation", ")", "elif", "currentBlockText", ".", "endswith", "(", "';'", ")", ":", "# stuff like:", "# for(int b;", "# b < 10;", "# --b)", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "findBracketBackward", "(", "currentBlock", ",", "None", ",", "'('", ")", "except", "ValueError", ":", "pass", "else", ":", "dbg", "(", "\"tryCKeywords: success 1 in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "self", ".", "_makeIndentAsColumn", "(", "foundBlock", ",", "foundColumn", ",", "1", ")", "if", "indentation", "is", "not", "None", ":", "dbg", "(", "\"tryCKeywords: success in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "indentation" ]
Check for if, else, while, do, switch, private, public, protected, signals, default, case etc... keywords, as we want to indent then. If is non-null/True, then indentation is not increased. Note: The code is written to be called *after* tryCComment and tryCppComment!
[ "Check", "for", "if", "else", "while", "do", "switch", "private", "public", "protected", "signals", "default", "case", "etc", "...", "keywords", "as", "we", "want", "to", "indent", "then", ".", "If", "is", "non", "-", "null", "/", "True", "then", "indentation", "is", "not", "increased", ".", "Note", ":", "The", "code", "is", "written", "to", "be", "called", "*", "after", "*", "tryCComment", "and", "tryCppComment!" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L269-L327
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryCondition
def tryCondition(self, block): """ Search for if, do, while, for, ... as we want to indent then. Return null, if nothing useful found. Note: The code is written to be called *after* tryCComment and tryCppComment! """ currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None # found non-empty line currentText = currentBlock.text() if currentText.rstrip().endswith(';') and \ re.search(r'^\s*(if\b|[}]?\s*else|do\b|while\b|for)', currentText) is None: # idea: we had something like: # if/while/for (expression) # statement(); <-- we catch this trailing ';' # Now, look for a line that starts with if/for/while, that has one # indent level less. currentIndentation = self._lineIndent(currentText) if not currentIndentation: return None for block in self.iterateBlocksBackFrom(currentBlock.previous()): if block.text().strip(): # not empty indentation = self._blockIndent(block) if len(indentation) < len(currentIndentation): if re.search(r'^\s*(if\b|[}]?\s*else|do\b|while\b|for)[^{]*$', block.text()) is not None: dbg("tryCondition: success in line %d" % block.blockNumber()) return indentation break return None
python
def tryCondition(self, block): """ Search for if, do, while, for, ... as we want to indent then. Return null, if nothing useful found. Note: The code is written to be called *after* tryCComment and tryCppComment! """ currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None # found non-empty line currentText = currentBlock.text() if currentText.rstrip().endswith(';') and \ re.search(r'^\s*(if\b|[}]?\s*else|do\b|while\b|for)', currentText) is None: # idea: we had something like: # if/while/for (expression) # statement(); <-- we catch this trailing ';' # Now, look for a line that starts with if/for/while, that has one # indent level less. currentIndentation = self._lineIndent(currentText) if not currentIndentation: return None for block in self.iterateBlocksBackFrom(currentBlock.previous()): if block.text().strip(): # not empty indentation = self._blockIndent(block) if len(indentation) < len(currentIndentation): if re.search(r'^\s*(if\b|[}]?\s*else|do\b|while\b|for)[^{]*$', block.text()) is not None: dbg("tryCondition: success in line %d" % block.blockNumber()) return indentation break return None
[ "def", "tryCondition", "(", "self", ",", "block", ")", ":", "currentBlock", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", "if", "not", "currentBlock", ".", "isValid", "(", ")", ":", "return", "None", "# found non-empty line", "currentText", "=", "currentBlock", ".", "text", "(", ")", "if", "currentText", ".", "rstrip", "(", ")", ".", "endswith", "(", "';'", ")", "and", "re", ".", "search", "(", "r'^\\s*(if\\b|[}]?\\s*else|do\\b|while\\b|for)'", ",", "currentText", ")", "is", "None", ":", "# idea: we had something like:", "# if/while/for (expression)", "# statement(); <-- we catch this trailing ';'", "# Now, look for a line that starts with if/for/while, that has one", "# indent level less.", "currentIndentation", "=", "self", ".", "_lineIndent", "(", "currentText", ")", "if", "not", "currentIndentation", ":", "return", "None", "for", "block", "in", "self", ".", "iterateBlocksBackFrom", "(", "currentBlock", ".", "previous", "(", ")", ")", ":", "if", "block", ".", "text", "(", ")", ".", "strip", "(", ")", ":", "# not empty", "indentation", "=", "self", ".", "_blockIndent", "(", "block", ")", "if", "len", "(", "indentation", ")", "<", "len", "(", "currentIndentation", ")", ":", "if", "re", ".", "search", "(", "r'^\\s*(if\\b|[}]?\\s*else|do\\b|while\\b|for)[^{]*$'", ",", "block", ".", "text", "(", ")", ")", "is", "not", "None", ":", "dbg", "(", "\"tryCondition: success in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "indentation", "break", "return", "None" ]
Search for if, do, while, for, ... as we want to indent then. Return null, if nothing useful found. Note: The code is written to be called *after* tryCComment and tryCppComment!
[ "Search", "for", "if", "do", "while", "for", "...", "as", "we", "want", "to", "indent", "then", ".", "Return", "null", "if", "nothing", "useful", "found", ".", "Note", ":", "The", "code", "is", "written", "to", "be", "called", "*", "after", "*", "tryCComment", "and", "tryCppComment!" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L329-L361
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryStatement
def tryStatement(self, block): """ If the non-empty line ends with ); or ',', then search for '(' and return its indentation; also try to ignore trailing comments. """ currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None indentation = None currentBlockText = currentBlock.text() if currentBlockText.endswith('('): # increase indent level dbg("tryStatement: success 1 in line %d" % block.blockNumber()) return self._increaseIndent(self._lineIndent(currentBlockText)) alignOnSingleQuote = self._qpart.language() in ('PHP/PHP', 'JavaScript') # align on strings "..."\n => below the opening quote # multi-language support: [\.+] for javascript or php pattern = '^(.*)' # any group 1 pattern += '([,"\'\\)])' # one of [ , " ' ) group 2 pattern += '(;?)' # optional ; group 3 pattern += '\s*[\.+]?\s*' # optional spaces optional . or + optional spaces pattern += '(//.*|/\\*.*\\*/\s*)?$' # optional(//any or /*any*/spaces) group 4 match = re.match(pattern, currentBlockText) if match is not None: alignOnAnchor = len(match.group(3)) == 0 and match.group(2) != ')' # search for opening ", ' or ( if match.group(2) == '"' or (alignOnSingleQuote and match.group(2) == "'"): startIndex = len(match.group(1)) while True: # start from matched closing ' or " # find string opener for i in range(startIndex - 1, 0, -1): # make sure it's not commented out if currentBlockText[i] == match.group(2) and (i == 0 or currentBlockText[i - 1] != '\\'): # also make sure that this is not a line like '#include "..."' <-- we don't want to indent here if re.match(r'^#include', currentBlockText): dbg("tryStatement: success 2 in line %d" % block.blockNumber()) return indentation break if not alignOnAnchor and currentBlock.previous().isValid(): # when we finished the statement (;) we need to get the first line and use it's indentation # i.e.: $foo = "asdf"; -> align on $ i -= 1 # skip " or ' # skip whitespaces and stuff like + or . (for PHP, JavaScript, ...) for i in range(i, 0, -1): if currentBlockText[i] in (' ', '\t', '.', '+'): continue else: break if i > 0: # there's something in this line, use it's indentation break else: # go to previous line currentBlock = currentBlock.previous() currentBlockText = currentBlock.text() startIndex = len(currentBlockText) else: break elif match.group(2) == ',' and not '(' in currentBlockText: # assume a function call: check for '(' brace # - if not found, use previous indentation # - if found, compare the indentation depth of current line and open brace line # - if current indentation depth is smaller, use that # - otherwise, use the '(' indentation + following white spaces currentIndentation = self._blockIndent(currentBlock) try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(match.group(1)), '(') except ValueError: indentation = currentIndentation else: indentWidth = foundColumn + 1 text = foundBlock.text() while indentWidth < len(text) and text[indentWidth].isspace(): indentWidth += 1 indentation = self._makeIndentAsColumn(foundBlock, indentWidth) else: try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(match.group(1)), '(') except ValueError: pass else: if alignOnAnchor: if not match.group(2) in ('"', "'"): foundColumn += 1 foundBlockText = foundBlock.text() while foundColumn < len(foundBlockText) and \ foundBlockText[foundColumn].isspace(): foundColumn += 1 indentation = self._makeIndentAsColumn(foundBlock, foundColumn) else: currentBlock = foundBlock indentation = self._blockIndent(currentBlock) elif currentBlockText.rstrip().endswith(';'): indentation = self._blockIndent(currentBlock) if indentation is not None: dbg("tryStatement: success in line %d" % currentBlock.blockNumber()) return indentation
python
def tryStatement(self, block): """ If the non-empty line ends with ); or ',', then search for '(' and return its indentation; also try to ignore trailing comments. """ currentBlock = self._prevNonEmptyBlock(block) if not currentBlock.isValid(): return None indentation = None currentBlockText = currentBlock.text() if currentBlockText.endswith('('): # increase indent level dbg("tryStatement: success 1 in line %d" % block.blockNumber()) return self._increaseIndent(self._lineIndent(currentBlockText)) alignOnSingleQuote = self._qpart.language() in ('PHP/PHP', 'JavaScript') # align on strings "..."\n => below the opening quote # multi-language support: [\.+] for javascript or php pattern = '^(.*)' # any group 1 pattern += '([,"\'\\)])' # one of [ , " ' ) group 2 pattern += '(;?)' # optional ; group 3 pattern += '\s*[\.+]?\s*' # optional spaces optional . or + optional spaces pattern += '(//.*|/\\*.*\\*/\s*)?$' # optional(//any or /*any*/spaces) group 4 match = re.match(pattern, currentBlockText) if match is not None: alignOnAnchor = len(match.group(3)) == 0 and match.group(2) != ')' # search for opening ", ' or ( if match.group(2) == '"' or (alignOnSingleQuote and match.group(2) == "'"): startIndex = len(match.group(1)) while True: # start from matched closing ' or " # find string opener for i in range(startIndex - 1, 0, -1): # make sure it's not commented out if currentBlockText[i] == match.group(2) and (i == 0 or currentBlockText[i - 1] != '\\'): # also make sure that this is not a line like '#include "..."' <-- we don't want to indent here if re.match(r'^#include', currentBlockText): dbg("tryStatement: success 2 in line %d" % block.blockNumber()) return indentation break if not alignOnAnchor and currentBlock.previous().isValid(): # when we finished the statement (;) we need to get the first line and use it's indentation # i.e.: $foo = "asdf"; -> align on $ i -= 1 # skip " or ' # skip whitespaces and stuff like + or . (for PHP, JavaScript, ...) for i in range(i, 0, -1): if currentBlockText[i] in (' ', '\t', '.', '+'): continue else: break if i > 0: # there's something in this line, use it's indentation break else: # go to previous line currentBlock = currentBlock.previous() currentBlockText = currentBlock.text() startIndex = len(currentBlockText) else: break elif match.group(2) == ',' and not '(' in currentBlockText: # assume a function call: check for '(' brace # - if not found, use previous indentation # - if found, compare the indentation depth of current line and open brace line # - if current indentation depth is smaller, use that # - otherwise, use the '(' indentation + following white spaces currentIndentation = self._blockIndent(currentBlock) try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(match.group(1)), '(') except ValueError: indentation = currentIndentation else: indentWidth = foundColumn + 1 text = foundBlock.text() while indentWidth < len(text) and text[indentWidth].isspace(): indentWidth += 1 indentation = self._makeIndentAsColumn(foundBlock, indentWidth) else: try: foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(match.group(1)), '(') except ValueError: pass else: if alignOnAnchor: if not match.group(2) in ('"', "'"): foundColumn += 1 foundBlockText = foundBlock.text() while foundColumn < len(foundBlockText) and \ foundBlockText[foundColumn].isspace(): foundColumn += 1 indentation = self._makeIndentAsColumn(foundBlock, foundColumn) else: currentBlock = foundBlock indentation = self._blockIndent(currentBlock) elif currentBlockText.rstrip().endswith(';'): indentation = self._blockIndent(currentBlock) if indentation is not None: dbg("tryStatement: success in line %d" % currentBlock.blockNumber()) return indentation
[ "def", "tryStatement", "(", "self", ",", "block", ")", ":", "currentBlock", "=", "self", ".", "_prevNonEmptyBlock", "(", "block", ")", "if", "not", "currentBlock", ".", "isValid", "(", ")", ":", "return", "None", "indentation", "=", "None", "currentBlockText", "=", "currentBlock", ".", "text", "(", ")", "if", "currentBlockText", ".", "endswith", "(", "'('", ")", ":", "# increase indent level", "dbg", "(", "\"tryStatement: success 1 in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "self", ".", "_increaseIndent", "(", "self", ".", "_lineIndent", "(", "currentBlockText", ")", ")", "alignOnSingleQuote", "=", "self", ".", "_qpart", ".", "language", "(", ")", "in", "(", "'PHP/PHP'", ",", "'JavaScript'", ")", "# align on strings \"...\"\\n => below the opening quote", "# multi-language support: [\\.+] for javascript or php", "pattern", "=", "'^(.*)'", "# any group 1", "pattern", "+=", "'([,\"\\'\\\\)])'", "# one of [ , \" ' ) group 2", "pattern", "+=", "'(;?)'", "# optional ; group 3", "pattern", "+=", "'\\s*[\\.+]?\\s*'", "# optional spaces optional . or + optional spaces", "pattern", "+=", "'(//.*|/\\\\*.*\\\\*/\\s*)?$'", "# optional(//any or /*any*/spaces) group 4", "match", "=", "re", ".", "match", "(", "pattern", ",", "currentBlockText", ")", "if", "match", "is", "not", "None", ":", "alignOnAnchor", "=", "len", "(", "match", ".", "group", "(", "3", ")", ")", "==", "0", "and", "match", ".", "group", "(", "2", ")", "!=", "')'", "# search for opening \", ' or (", "if", "match", ".", "group", "(", "2", ")", "==", "'\"'", "or", "(", "alignOnSingleQuote", "and", "match", ".", "group", "(", "2", ")", "==", "\"'\"", ")", ":", "startIndex", "=", "len", "(", "match", ".", "group", "(", "1", ")", ")", "while", "True", ":", "# start from matched closing ' or \"", "# find string opener", "for", "i", "in", "range", "(", "startIndex", "-", "1", ",", "0", ",", "-", "1", ")", ":", "# make sure it's not commented out", "if", "currentBlockText", "[", "i", "]", "==", "match", ".", "group", "(", "2", ")", "and", "(", "i", "==", "0", "or", "currentBlockText", "[", "i", "-", "1", "]", "!=", "'\\\\'", ")", ":", "# also make sure that this is not a line like '#include \"...\"' <-- we don't want to indent here", "if", "re", ".", "match", "(", "r'^#include'", ",", "currentBlockText", ")", ":", "dbg", "(", "\"tryStatement: success 2 in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "indentation", "break", "if", "not", "alignOnAnchor", "and", "currentBlock", ".", "previous", "(", ")", ".", "isValid", "(", ")", ":", "# when we finished the statement (;) we need to get the first line and use it's indentation", "# i.e.: $foo = \"asdf\"; -> align on $", "i", "-=", "1", "# skip \" or '", "# skip whitespaces and stuff like + or . (for PHP, JavaScript, ...)", "for", "i", "in", "range", "(", "i", ",", "0", ",", "-", "1", ")", ":", "if", "currentBlockText", "[", "i", "]", "in", "(", "' '", ",", "'\\t'", ",", "'.'", ",", "'+'", ")", ":", "continue", "else", ":", "break", "if", "i", ">", "0", ":", "# there's something in this line, use it's indentation", "break", "else", ":", "# go to previous line", "currentBlock", "=", "currentBlock", ".", "previous", "(", ")", "currentBlockText", "=", "currentBlock", ".", "text", "(", ")", "startIndex", "=", "len", "(", "currentBlockText", ")", "else", ":", "break", "elif", "match", ".", "group", "(", "2", ")", "==", "','", "and", "not", "'('", "in", "currentBlockText", ":", "# assume a function call: check for '(' brace", "# - if not found, use previous indentation", "# - if found, compare the indentation depth of current line and open brace line", "# - if current indentation depth is smaller, use that", "# - otherwise, use the '(' indentation + following white spaces", "currentIndentation", "=", "self", ".", "_blockIndent", "(", "currentBlock", ")", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "findBracketBackward", "(", "currentBlock", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ",", "'('", ")", "except", "ValueError", ":", "indentation", "=", "currentIndentation", "else", ":", "indentWidth", "=", "foundColumn", "+", "1", "text", "=", "foundBlock", ".", "text", "(", ")", "while", "indentWidth", "<", "len", "(", "text", ")", "and", "text", "[", "indentWidth", "]", ".", "isspace", "(", ")", ":", "indentWidth", "+=", "1", "indentation", "=", "self", ".", "_makeIndentAsColumn", "(", "foundBlock", ",", "indentWidth", ")", "else", ":", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "findBracketBackward", "(", "currentBlock", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ",", "'('", ")", "except", "ValueError", ":", "pass", "else", ":", "if", "alignOnAnchor", ":", "if", "not", "match", ".", "group", "(", "2", ")", "in", "(", "'\"'", ",", "\"'\"", ")", ":", "foundColumn", "+=", "1", "foundBlockText", "=", "foundBlock", ".", "text", "(", ")", "while", "foundColumn", "<", "len", "(", "foundBlockText", ")", "and", "foundBlockText", "[", "foundColumn", "]", ".", "isspace", "(", ")", ":", "foundColumn", "+=", "1", "indentation", "=", "self", ".", "_makeIndentAsColumn", "(", "foundBlock", ",", "foundColumn", ")", "else", ":", "currentBlock", "=", "foundBlock", "indentation", "=", "self", ".", "_blockIndent", "(", "currentBlock", ")", "elif", "currentBlockText", ".", "rstrip", "(", ")", ".", "endswith", "(", "';'", ")", ":", "indentation", "=", "self", ".", "_blockIndent", "(", "currentBlock", ")", "if", "indentation", "is", "not", "None", ":", "dbg", "(", "\"tryStatement: success in line %d\"", "%", "currentBlock", ".", "blockNumber", "(", ")", ")", "return", "indentation" ]
If the non-empty line ends with ); or ',', then search for '(' and return its indentation; also try to ignore trailing comments.
[ "If", "the", "non", "-", "empty", "line", "ends", "with", ")", ";", "or", "then", "search", "for", "(", "and", "return", "its", "indentation", ";", "also", "try", "to", "ignore", "trailing", "comments", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L363-L469
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.tryMatchedAnchor
def tryMatchedAnchor(self, block, autoIndent): """ find out whether we pressed return in something like {} or () or [] and indent properly: {} becomes: { | } """ oposite = { ')': '(', '}': '{', ']': '['} char = self._firstNonSpaceChar(block) if not char in oposite.keys(): return None # we pressed enter in e.g. () try: foundBlock, foundColumn = self.findBracketBackward(block, 0, oposite[char]) except ValueError: return None if autoIndent: # when aligning only, don't be too smart and just take the indent level of the open anchor return self._blockIndent(foundBlock) lastChar = self._lastNonSpaceChar(block.previous()) charsMatch = ( lastChar == '(' and char == ')' ) or \ ( lastChar == '{' and char == '}' ) or \ ( lastChar == '[' and char == ']' ) indentation = None if (not charsMatch) and char != '}': # otherwise check whether the last line has the expected # indentation, if not use it instead and place the closing # anchor on the level of the opening anchor expectedIndentation = self._increaseIndent(self._blockIndent(foundBlock)) actualIndentation = self._increaseIndent(self._blockIndent(block.previous())) indentation = None if len(expectedIndentation) <= len(actualIndentation): if lastChar == ',': # use indentation of last line instead and place closing anchor # in same column of the opening anchor self._qpart.insertText((block.blockNumber(), self._firstNonSpaceColumn(block.text())), '\n') self._qpart.cursorPosition = (block.blockNumber(), len(actualIndentation)) # indent closing anchor self._setBlockIndent(block.next(), self._makeIndentAsColumn(foundBlock, foundColumn)) indentation = actualIndentation elif expectedIndentation == self._blockIndent(block.previous()): # otherwise don't add a new line, just use indentation of closing anchor line indentation = self._blockIndent(foundBlock) else: # otherwise don't add a new line, just align on closing anchor indentation = self._makeIndentAsColumn(foundBlock, foundColumn) dbg("tryMatchedAnchor: success in line %d" % foundBlock.blockNumber()) return indentation # otherwise we i.e. pressed enter between (), [] or when we enter before curly brace # increase indentation and place closing anchor on the next line indentation = self._blockIndent(foundBlock) self._qpart.replaceText((block.blockNumber(), 0), len(self._blockIndent(block)), "\n") self._qpart.cursorPosition = (block.blockNumber(), len(indentation)) # indent closing brace self._setBlockIndent(block.next(), indentation) dbg("tryMatchedAnchor: success in line %d" % foundBlock.blockNumber()) return self._increaseIndent(indentation)
python
def tryMatchedAnchor(self, block, autoIndent): """ find out whether we pressed return in something like {} or () or [] and indent properly: {} becomes: { | } """ oposite = { ')': '(', '}': '{', ']': '['} char = self._firstNonSpaceChar(block) if not char in oposite.keys(): return None # we pressed enter in e.g. () try: foundBlock, foundColumn = self.findBracketBackward(block, 0, oposite[char]) except ValueError: return None if autoIndent: # when aligning only, don't be too smart and just take the indent level of the open anchor return self._blockIndent(foundBlock) lastChar = self._lastNonSpaceChar(block.previous()) charsMatch = ( lastChar == '(' and char == ')' ) or \ ( lastChar == '{' and char == '}' ) or \ ( lastChar == '[' and char == ']' ) indentation = None if (not charsMatch) and char != '}': # otherwise check whether the last line has the expected # indentation, if not use it instead and place the closing # anchor on the level of the opening anchor expectedIndentation = self._increaseIndent(self._blockIndent(foundBlock)) actualIndentation = self._increaseIndent(self._blockIndent(block.previous())) indentation = None if len(expectedIndentation) <= len(actualIndentation): if lastChar == ',': # use indentation of last line instead and place closing anchor # in same column of the opening anchor self._qpart.insertText((block.blockNumber(), self._firstNonSpaceColumn(block.text())), '\n') self._qpart.cursorPosition = (block.blockNumber(), len(actualIndentation)) # indent closing anchor self._setBlockIndent(block.next(), self._makeIndentAsColumn(foundBlock, foundColumn)) indentation = actualIndentation elif expectedIndentation == self._blockIndent(block.previous()): # otherwise don't add a new line, just use indentation of closing anchor line indentation = self._blockIndent(foundBlock) else: # otherwise don't add a new line, just align on closing anchor indentation = self._makeIndentAsColumn(foundBlock, foundColumn) dbg("tryMatchedAnchor: success in line %d" % foundBlock.blockNumber()) return indentation # otherwise we i.e. pressed enter between (), [] or when we enter before curly brace # increase indentation and place closing anchor on the next line indentation = self._blockIndent(foundBlock) self._qpart.replaceText((block.blockNumber(), 0), len(self._blockIndent(block)), "\n") self._qpart.cursorPosition = (block.blockNumber(), len(indentation)) # indent closing brace self._setBlockIndent(block.next(), indentation) dbg("tryMatchedAnchor: success in line %d" % foundBlock.blockNumber()) return self._increaseIndent(indentation)
[ "def", "tryMatchedAnchor", "(", "self", ",", "block", ",", "autoIndent", ")", ":", "oposite", "=", "{", "')'", ":", "'('", ",", "'}'", ":", "'{'", ",", "']'", ":", "'['", "}", "char", "=", "self", ".", "_firstNonSpaceChar", "(", "block", ")", "if", "not", "char", "in", "oposite", ".", "keys", "(", ")", ":", "return", "None", "# we pressed enter in e.g. ()", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "findBracketBackward", "(", "block", ",", "0", ",", "oposite", "[", "char", "]", ")", "except", "ValueError", ":", "return", "None", "if", "autoIndent", ":", "# when aligning only, don't be too smart and just take the indent level of the open anchor", "return", "self", ".", "_blockIndent", "(", "foundBlock", ")", "lastChar", "=", "self", ".", "_lastNonSpaceChar", "(", "block", ".", "previous", "(", ")", ")", "charsMatch", "=", "(", "lastChar", "==", "'('", "and", "char", "==", "')'", ")", "or", "(", "lastChar", "==", "'{'", "and", "char", "==", "'}'", ")", "or", "(", "lastChar", "==", "'['", "and", "char", "==", "']'", ")", "indentation", "=", "None", "if", "(", "not", "charsMatch", ")", "and", "char", "!=", "'}'", ":", "# otherwise check whether the last line has the expected", "# indentation, if not use it instead and place the closing", "# anchor on the level of the opening anchor", "expectedIndentation", "=", "self", ".", "_increaseIndent", "(", "self", ".", "_blockIndent", "(", "foundBlock", ")", ")", "actualIndentation", "=", "self", ".", "_increaseIndent", "(", "self", ".", "_blockIndent", "(", "block", ".", "previous", "(", ")", ")", ")", "indentation", "=", "None", "if", "len", "(", "expectedIndentation", ")", "<=", "len", "(", "actualIndentation", ")", ":", "if", "lastChar", "==", "','", ":", "# use indentation of last line instead and place closing anchor", "# in same column of the opening anchor", "self", ".", "_qpart", ".", "insertText", "(", "(", "block", ".", "blockNumber", "(", ")", ",", "self", ".", "_firstNonSpaceColumn", "(", "block", ".", "text", "(", ")", ")", ")", ",", "'\\n'", ")", "self", ".", "_qpart", ".", "cursorPosition", "=", "(", "block", ".", "blockNumber", "(", ")", ",", "len", "(", "actualIndentation", ")", ")", "# indent closing anchor", "self", ".", "_setBlockIndent", "(", "block", ".", "next", "(", ")", ",", "self", ".", "_makeIndentAsColumn", "(", "foundBlock", ",", "foundColumn", ")", ")", "indentation", "=", "actualIndentation", "elif", "expectedIndentation", "==", "self", ".", "_blockIndent", "(", "block", ".", "previous", "(", ")", ")", ":", "# otherwise don't add a new line, just use indentation of closing anchor line", "indentation", "=", "self", ".", "_blockIndent", "(", "foundBlock", ")", "else", ":", "# otherwise don't add a new line, just align on closing anchor", "indentation", "=", "self", ".", "_makeIndentAsColumn", "(", "foundBlock", ",", "foundColumn", ")", "dbg", "(", "\"tryMatchedAnchor: success in line %d\"", "%", "foundBlock", ".", "blockNumber", "(", ")", ")", "return", "indentation", "# otherwise we i.e. pressed enter between (), [] or when we enter before curly brace", "# increase indentation and place closing anchor on the next line", "indentation", "=", "self", ".", "_blockIndent", "(", "foundBlock", ")", "self", ".", "_qpart", ".", "replaceText", "(", "(", "block", ".", "blockNumber", "(", ")", ",", "0", ")", ",", "len", "(", "self", ".", "_blockIndent", "(", "block", ")", ")", ",", "\"\\n\"", ")", "self", ".", "_qpart", ".", "cursorPosition", "=", "(", "block", ".", "blockNumber", "(", ")", ",", "len", "(", "indentation", ")", ")", "# indent closing brace", "self", ".", "_setBlockIndent", "(", "block", ".", "next", "(", ")", ",", "indentation", ")", "dbg", "(", "\"tryMatchedAnchor: success in line %d\"", "%", "foundBlock", ".", "blockNumber", "(", ")", ")", "return", "self", ".", "_increaseIndent", "(", "indentation", ")" ]
find out whether we pressed return in something like {} or () or [] and indent properly: {} becomes: { | }
[ "find", "out", "whether", "we", "pressed", "return", "in", "something", "like", "{}", "or", "()", "or", "[]", "and", "indent", "properly", ":", "{}", "becomes", ":", "{", "|", "}" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L471-L538
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.indentLine
def indentLine(self, block, autoIndent): """ Indent line. Return filler or null. """ indent = None if indent is None: indent = self.tryMatchedAnchor(block, autoIndent) if indent is None: indent = self.tryCComment(block) if indent is None and not autoIndent: indent = self.tryCppComment(block) if indent is None: indent = self.trySwitchStatement(block) if indent is None: indent = self.tryAccessModifiers(block) if indent is None: indent = self.tryBrace(block) if indent is None: indent = self.tryCKeywords(block, block.text().lstrip().startswith('{')) if indent is None: indent = self.tryCondition(block) if indent is None: indent = self.tryStatement(block) if indent is not None: return indent else: dbg("Nothing matched") return self._prevNonEmptyBlockIndent(block)
python
def indentLine(self, block, autoIndent): """ Indent line. Return filler or null. """ indent = None if indent is None: indent = self.tryMatchedAnchor(block, autoIndent) if indent is None: indent = self.tryCComment(block) if indent is None and not autoIndent: indent = self.tryCppComment(block) if indent is None: indent = self.trySwitchStatement(block) if indent is None: indent = self.tryAccessModifiers(block) if indent is None: indent = self.tryBrace(block) if indent is None: indent = self.tryCKeywords(block, block.text().lstrip().startswith('{')) if indent is None: indent = self.tryCondition(block) if indent is None: indent = self.tryStatement(block) if indent is not None: return indent else: dbg("Nothing matched") return self._prevNonEmptyBlockIndent(block)
[ "def", "indentLine", "(", "self", ",", "block", ",", "autoIndent", ")", ":", "indent", "=", "None", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryMatchedAnchor", "(", "block", ",", "autoIndent", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryCComment", "(", "block", ")", "if", "indent", "is", "None", "and", "not", "autoIndent", ":", "indent", "=", "self", ".", "tryCppComment", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "trySwitchStatement", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryAccessModifiers", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryBrace", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryCKeywords", "(", "block", ",", "block", ".", "text", "(", ")", ".", "lstrip", "(", ")", ".", "startswith", "(", "'{'", ")", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryCondition", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryStatement", "(", "block", ")", "if", "indent", "is", "not", "None", ":", "return", "indent", "else", ":", "dbg", "(", "\"Nothing matched\"", ")", "return", "self", ".", "_prevNonEmptyBlockIndent", "(", "block", ")" ]
Indent line. Return filler or null.
[ "Indent", "line", ".", "Return", "filler", "or", "null", "." ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L540-L568
andreikop/qutepart
qutepart/indenter/scheme.py
IndentAlgScheme._findExpressionEnd
def _findExpressionEnd(self, block): """Find end of the last expression """ while block.isValid(): column = self._lastColumn(block) if column > 0: return block, column block = block.previous() raise UserWarning()
python
def _findExpressionEnd(self, block): """Find end of the last expression """ while block.isValid(): column = self._lastColumn(block) if column > 0: return block, column block = block.previous() raise UserWarning()
[ "def", "_findExpressionEnd", "(", "self", ",", "block", ")", ":", "while", "block", ".", "isValid", "(", ")", ":", "column", "=", "self", ".", "_lastColumn", "(", "block", ")", "if", "column", ">", "0", ":", "return", "block", ",", "column", "block", "=", "block", ".", "previous", "(", ")", "raise", "UserWarning", "(", ")" ]
Find end of the last expression
[ "Find", "end", "of", "the", "last", "expression" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/scheme.py#L15-L23
andreikop/qutepart
qutepart/indenter/scheme.py
IndentAlgScheme._lastWord
def _lastWord(self, text): """Move backward to the start of the word at the end of a string. Return the word """ for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: return text
python
def _lastWord(self, text): """Move backward to the start of the word at the end of a string. Return the word """ for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: return text
[ "def", "_lastWord", "(", "self", ",", "text", ")", ":", "for", "index", ",", "char", "in", "enumerate", "(", "text", "[", ":", ":", "-", "1", "]", ")", ":", "if", "char", ".", "isspace", "(", ")", "or", "char", "in", "(", "'('", ",", "')'", ")", ":", "return", "text", "[", "len", "(", "text", ")", "-", "index", ":", "]", "else", ":", "return", "text" ]
Move backward to the start of the word at the end of a string. Return the word
[ "Move", "backward", "to", "the", "start", "of", "the", "word", "at", "the", "end", "of", "a", "string", ".", "Return", "the", "word" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/scheme.py#L25-L34
andreikop/qutepart
qutepart/indenter/scheme.py
IndentAlgScheme._findExpressionStart
def _findExpressionStart(self, block): """Find start of not finished expression Raise UserWarning, if not found """ # raise expession on next level, if not found expEndBlock, expEndColumn = self._findExpressionEnd(block) text = expEndBlock.text()[:expEndColumn + 1] if text.endswith(')'): try: return self.findBracketBackward(expEndBlock, expEndColumn, '(') except ValueError: raise UserWarning() else: return expEndBlock, len(text) - len(self._lastWord(text))
python
def _findExpressionStart(self, block): """Find start of not finished expression Raise UserWarning, if not found """ # raise expession on next level, if not found expEndBlock, expEndColumn = self._findExpressionEnd(block) text = expEndBlock.text()[:expEndColumn + 1] if text.endswith(')'): try: return self.findBracketBackward(expEndBlock, expEndColumn, '(') except ValueError: raise UserWarning() else: return expEndBlock, len(text) - len(self._lastWord(text))
[ "def", "_findExpressionStart", "(", "self", ",", "block", ")", ":", "# raise expession on next level, if not found", "expEndBlock", ",", "expEndColumn", "=", "self", ".", "_findExpressionEnd", "(", "block", ")", "text", "=", "expEndBlock", ".", "text", "(", ")", "[", ":", "expEndColumn", "+", "1", "]", "if", "text", ".", "endswith", "(", "')'", ")", ":", "try", ":", "return", "self", ".", "findBracketBackward", "(", "expEndBlock", ",", "expEndColumn", ",", "'('", ")", "except", "ValueError", ":", "raise", "UserWarning", "(", ")", "else", ":", "return", "expEndBlock", ",", "len", "(", "text", ")", "-", "len", "(", "self", ".", "_lastWord", "(", "text", ")", ")" ]
Find start of not finished expression Raise UserWarning, if not found
[ "Find", "start", "of", "not", "finished", "expression", "Raise", "UserWarning", "if", "not", "found" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/scheme.py#L36-L51
andreikop/qutepart
qutepart/indenter/scheme.py
IndentAlgScheme.computeSmartIndent
def computeSmartIndent(self, block, char): """Compute indent for the block """ try: foundBlock, foundColumn = self._findExpressionStart(block.previous()) except UserWarning: return '' expression = foundBlock.text()[foundColumn:].rstrip() beforeExpression = foundBlock.text()[:foundColumn].strip() if beforeExpression.startswith('(module'): # special case return '' elif beforeExpression.endswith('define'): # special case return ' ' * (len(beforeExpression) - len('define') + 1) elif beforeExpression.endswith('let'): # special case return ' ' * (len(beforeExpression) - len('let') + 1) else: return ' ' * foundColumn
python
def computeSmartIndent(self, block, char): """Compute indent for the block """ try: foundBlock, foundColumn = self._findExpressionStart(block.previous()) except UserWarning: return '' expression = foundBlock.text()[foundColumn:].rstrip() beforeExpression = foundBlock.text()[:foundColumn].strip() if beforeExpression.startswith('(module'): # special case return '' elif beforeExpression.endswith('define'): # special case return ' ' * (len(beforeExpression) - len('define') + 1) elif beforeExpression.endswith('let'): # special case return ' ' * (len(beforeExpression) - len('let') + 1) else: return ' ' * foundColumn
[ "def", "computeSmartIndent", "(", "self", ",", "block", ",", "char", ")", ":", "try", ":", "foundBlock", ",", "foundColumn", "=", "self", ".", "_findExpressionStart", "(", "block", ".", "previous", "(", ")", ")", "except", "UserWarning", ":", "return", "''", "expression", "=", "foundBlock", ".", "text", "(", ")", "[", "foundColumn", ":", "]", ".", "rstrip", "(", ")", "beforeExpression", "=", "foundBlock", ".", "text", "(", ")", "[", ":", "foundColumn", "]", ".", "strip", "(", ")", "if", "beforeExpression", ".", "startswith", "(", "'(module'", ")", ":", "# special case", "return", "''", "elif", "beforeExpression", ".", "endswith", "(", "'define'", ")", ":", "# special case", "return", "' '", "*", "(", "len", "(", "beforeExpression", ")", "-", "len", "(", "'define'", ")", "+", "1", ")", "elif", "beforeExpression", ".", "endswith", "(", "'let'", ")", ":", "# special case", "return", "' '", "*", "(", "len", "(", "beforeExpression", ")", "-", "len", "(", "'let'", ")", "+", "1", ")", "else", ":", "return", "' '", "*", "foundColumn" ]
Compute indent for the block
[ "Compute", "indent", "for", "the", "block" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/scheme.py#L53-L70
andreikop/qutepart
qutepart/indenter/__init__.py
_getSmartIndenter
def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols """ indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter)
python
def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols """ indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter)
[ "def", "_getSmartIndenter", "(", "indenterName", ",", "qpart", ",", "indenter", ")", ":", "indenterName", "=", "indenterName", ".", "lower", "(", ")", "if", "indenterName", "in", "(", "'haskell'", ",", "'lilypond'", ")", ":", "# not supported yet", "logger", ".", "warning", "(", "'Smart indentation for %s not supported yet. But you could be a hero who implemented it'", "%", "indenterName", ")", "from", "qutepart", ".", "indenter", ".", "base", "import", "IndentAlgNormal", "as", "indenterClass", "elif", "'none'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "base", "import", "IndentAlgBase", "as", "indenterClass", "elif", "'normal'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "base", "import", "IndentAlgNormal", "as", "indenterClass", "elif", "'cstyle'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "cstyle", "import", "IndentAlgCStyle", "as", "indenterClass", "elif", "'python'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "python", "import", "IndentAlgPython", "as", "indenterClass", "elif", "'ruby'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "ruby", "import", "IndentAlgRuby", "as", "indenterClass", "elif", "'xml'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "xmlindent", "import", "IndentAlgXml", "as", "indenterClass", "elif", "'haskell'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "haskell", "import", "IndenterHaskell", "as", "indenterClass", "elif", "'lilypond'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "lilypond", "import", "IndenterLilypond", "as", "indenterClass", "elif", "'lisp'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "lisp", "import", "IndentAlgLisp", "as", "indenterClass", "elif", "'scheme'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "scheme", "import", "IndentAlgScheme", "as", "indenterClass", "else", ":", "raise", "KeyError", "(", "\"Indenter %s not found\"", "%", "indenterName", ")", "return", "indenterClass", "(", "qpart", ",", "indenter", ")" ]
Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols
[ "Get", "indenter", "by", "name", ".", "Available", "indenters", "are", "none", "normal", "cstyle", "haskell", "lilypond", "lisp", "python", "ruby", "xml", "Indenter", "name", "is", "not", "case", "sensitive", "Raise", "KeyError", "if", "not", "found", "indentText", "is", "indentation", "which", "shall", "be", "used", ".", "i", ".", "e", ".", "\\", "t", "for", "tabs", "for", "4", "space", "symbols" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L13-L48
andreikop/qutepart
qutepart/indenter/__init__.py
Indenter.autoIndentBlock
def autoIndentBlock(self, block, char='\n'): """Indent block after Enter pressed or trigger character typed """ currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent)
python
def autoIndentBlock(self, block, char='\n'): """Indent block after Enter pressed or trigger character typed """ currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent)
[ "def", "autoIndentBlock", "(", "self", ",", "block", ",", "char", "=", "'\\n'", ")", ":", "currentText", "=", "block", ".", "text", "(", ")", "spaceAtStartLen", "=", "len", "(", "currentText", ")", "-", "len", "(", "currentText", ".", "lstrip", "(", ")", ")", "currentIndent", "=", "currentText", "[", ":", "spaceAtStartLen", "]", "indent", "=", "self", ".", "_smartIndenter", ".", "computeIndent", "(", "block", ",", "char", ")", "if", "indent", "is", "not", "None", "and", "indent", "!=", "currentIndent", ":", "self", ".", "_qpart", ".", "replaceText", "(", "block", ".", "position", "(", ")", ",", "spaceAtStartLen", ",", "indent", ")" ]
Indent block after Enter pressed or trigger character typed
[ "Indent", "block", "after", "Enter", "pressed", "or", "trigger", "character", "typed" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L85-L93
andreikop/qutepart
qutepart/indenter/__init__.py
Indenter.onChangeSelectedBlocksIndent
def onChangeSelectedBlocksIndent(self, increase, withSpace=False): """Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks """ def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith(self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if(cursor.selectionStart() != cursor.selectionEnd() and endBlock.position() == cursor.selectionEnd() and endBlock.previous().isValid()): endBlock = endBlock.previous() # do not indent not selected line if indenting multiple lines indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock)
python
def onChangeSelectedBlocksIndent(self, increase, withSpace=False): """Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks """ def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith(self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if(cursor.selectionStart() != cursor.selectionEnd() and endBlock.position() == cursor.selectionEnd() and endBlock.previous().isValid()): endBlock = endBlock.previous() # do not indent not selected line if indenting multiple lines indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock)
[ "def", "onChangeSelectedBlocksIndent", "(", "self", ",", "increase", ",", "withSpace", "=", "False", ")", ":", "def", "blockIndentation", "(", "block", ")", ":", "text", "=", "block", ".", "text", "(", ")", "return", "text", "[", ":", "len", "(", "text", ")", "-", "len", "(", "text", ".", "lstrip", "(", ")", ")", "]", "def", "cursorAtSpaceEnd", "(", "block", ")", ":", "cursor", "=", "QTextCursor", "(", "block", ")", "cursor", ".", "setPosition", "(", "block", ".", "position", "(", ")", "+", "len", "(", "blockIndentation", "(", "block", ")", ")", ")", "return", "cursor", "def", "indentBlock", "(", "block", ")", ":", "cursor", "=", "cursorAtSpaceEnd", "(", "block", ")", "cursor", ".", "insertText", "(", "' '", "if", "withSpace", "else", "self", ".", "text", "(", ")", ")", "def", "spacesCount", "(", "text", ")", ":", "return", "len", "(", "text", ")", "-", "len", "(", "text", ".", "rstrip", "(", "' '", ")", ")", "def", "unIndentBlock", "(", "block", ")", ":", "currentIndent", "=", "blockIndentation", "(", "block", ")", "if", "currentIndent", ".", "endswith", "(", "'\\t'", ")", ":", "charsToRemove", "=", "1", "elif", "withSpace", ":", "charsToRemove", "=", "1", "if", "currentIndent", "else", "0", "else", ":", "if", "self", ".", "useTabs", ":", "charsToRemove", "=", "min", "(", "spacesCount", "(", "currentIndent", ")", ",", "self", ".", "width", ")", "else", ":", "# spaces", "if", "currentIndent", ".", "endswith", "(", "self", ".", "text", "(", ")", ")", ":", "# remove indent level", "charsToRemove", "=", "self", ".", "width", "else", ":", "# remove all spaces", "charsToRemove", "=", "min", "(", "spacesCount", "(", "currentIndent", ")", ",", "self", ".", "width", ")", "if", "charsToRemove", ":", "cursor", "=", "cursorAtSpaceEnd", "(", "block", ")", "cursor", ".", "setPosition", "(", "cursor", ".", "position", "(", ")", "-", "charsToRemove", ",", "QTextCursor", ".", "KeepAnchor", ")", "cursor", ".", "removeSelectedText", "(", ")", "cursor", "=", "self", ".", "_qpart", ".", "textCursor", "(", ")", "startBlock", "=", "self", ".", "_qpart", ".", "document", "(", ")", ".", "findBlock", "(", "cursor", ".", "selectionStart", "(", ")", ")", "endBlock", "=", "self", ".", "_qpart", ".", "document", "(", ")", ".", "findBlock", "(", "cursor", ".", "selectionEnd", "(", ")", ")", "if", "(", "cursor", ".", "selectionStart", "(", ")", "!=", "cursor", ".", "selectionEnd", "(", ")", "and", "endBlock", ".", "position", "(", ")", "==", "cursor", ".", "selectionEnd", "(", ")", "and", "endBlock", ".", "previous", "(", ")", ".", "isValid", "(", ")", ")", ":", "endBlock", "=", "endBlock", ".", "previous", "(", ")", "# do not indent not selected line if indenting multiple lines", "indentFunc", "=", "indentBlock", "if", "increase", "else", "unIndentBlock", "if", "startBlock", "!=", "endBlock", ":", "# indent multiply lines", "stopBlock", "=", "endBlock", ".", "next", "(", ")", "block", "=", "startBlock", "with", "self", ".", "_qpart", ":", "while", "block", "!=", "stopBlock", ":", "indentFunc", "(", "block", ")", "block", "=", "block", ".", "next", "(", ")", "newCursor", "=", "QTextCursor", "(", "startBlock", ")", "newCursor", ".", "setPosition", "(", "endBlock", ".", "position", "(", ")", "+", "len", "(", "endBlock", ".", "text", "(", ")", ")", ",", "QTextCursor", ".", "KeepAnchor", ")", "self", ".", "_qpart", ".", "setTextCursor", "(", "newCursor", ")", "else", ":", "# indent 1 line", "indentFunc", "(", "startBlock", ")" ]
Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks
[ "Tab", "or", "Space", "pressed", "and", "few", "blocks", "are", "selected", "or", "Shift", "+", "Tab", "pressed", "Insert", "or", "remove", "text", "from", "the", "beginning", "of", "blocks" ]
train
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L95-L161