'Toggle comment on current line or selection'

@Slot()
def toggle_comment(self):

    cursor = self.textCursor()
    (start_pos, end_pos) = sorted([cursor.selectionStart(), cursor.selectionEnd()])
    cursor.setPosition(end_pos)
    last_line = cursor.block().blockNumber()
    if (cursor.atBlockStart() and (start_pos != end_pos)):
        last_line -= 1
    cursor.setPosition(start_pos)
    first_line = cursor.block().blockNumber()
    is_comment_or_whitespace = True
    at_least_one_comment = False
    for _line_nb in range(first_line, (last_line + 1)):
        text = to_text_string(cursor.block().text()).lstrip()
        is_comment = text.startswith(self.comment_string)
        is_whitespace = (text == '')
        is_comment_or_whitespace *= (is_comment or is_whitespace)
        if is_comment:
            at_least_one_comment = True
        cursor.movePosition(QTextCursor.NextBlock)
    if (is_comment_or_whitespace and at_least_one_comment):
        self.uncomment()
    else:
        self.comment()
