def select_current_cell(self, cursor=None): """ Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected """ if cursor is None: cursor = self.textCursor() if self.current_cell: current_cell, cell_full_file = self.current_cell cell_start_pos = current_cell.selectionStart() cell_end_position = current_cell.selectionEnd() # Check if the saved current cell is still valid if cell_start_pos <= cursor.position() < cell_end_position: return current_cell, cell_full_file else: self.current_cell = None block = cursor.block() try: if is_cell_header(block): header = block.userData().oedata else: header = next( document_cells(block, forward=False, cell_list=self.get_cell_list())) cell_start_pos = header.block.position() cell_at_file_start = False cursor.setPosition(cell_start_pos) except StopIteration: # This cell has no header, so it is the first cell. cell_at_file_start = True cursor.movePosition(QTextCursor.Start) try: footer = next( document_cells(block, forward=True, cell_list=self.get_cell_list())) cell_end_position = footer.block.position() cell_at_file_end = False cursor.setPosition(cell_end_position, QTextCursor.KeepAnchor) except StopIteration: # This cell has no next header, so it is the last cell. cell_at_file_end = True cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) cell_full_file = cell_at_file_start and cell_at_file_end self.current_cell = (cursor, cell_full_file) return cursor, cell_full_file
def go_to_previous_cell(self): """Go to the previous cell of lines""" cursor = self.textCursor() block = cursor.block() if is_cell_header(block): block = block.previous() try: header = next(document_cells( block, forward=False, cell_list=self.get_cell_list())) cursor.setPosition(header.block.position()) except StopIteration: return self.setTextCursor(cursor)
def get_cell_as_executable_code(self, cursor=None): """Return cell contents as executable code.""" if cursor is None: cursor = self.textCursor() ls = self.get_line_separator() cursor, whole_file_selected = self.select_current_cell(cursor) line_from, line_to = self.get_selection_bounds(cursor) # Get the block for the first cell line start = cursor.selectionStart() block = self.document().findBlock(start) if not is_cell_header(block) and start > 0: block = self.document().findBlock(start - 1) # Get text text = self.get_selection_as_executable_code(cursor) if text is not None: text = ls * line_from + text return text, block