public BufferCell[,] GetBufferContents(Rectangle rectangle) { BufferCell[,] bufferCells = new BufferCell[(rectangle.Top - rectangle.Bottom), (rectangle.Right - rectangle.Left)]; try { var cur = (int) ((Next.ElementEnd.GetCharacterRect(LogicalDirection.Backward).Bottom + ScrollViewer.ContentVerticalOffset) / (double.IsNaN(Document.LineHeight) ? Document.FontSize : Document.LineHeight)); int count; var nextContextPosition = Next.ElementEnd.GetNextContextPosition(LogicalDirection.Backward); var start = nextContextPosition?.GetLineStartPosition(rectangle.Bottom - cur, out count); if (start != null) { // for each line for (var ln = 0; ln <= rectangle.Top - rectangle.Bottom; ln++) { // Resharper is being stupid here, these can't actually be null: Debug.Assert(start != null, "start != null"); var next = start.GetLineStartPosition(1); start = start.GetPositionAtOffset(rectangle.Left); // Resharper is being stupid here, these can't actually be null: Debug.Assert(start != null, "start != null"); Debug.Assert(next != null, "next != null"); // if there's text on this line after that char, there's no output if (start.GetOffsetToPosition(next) <= 0) { continue; } var end = start.GetPositionAtOffset(1); Debug.Assert(end != null, "end != null"); // for each character in the line int c = 0, width = rectangle.Right - rectangle.Left; while (end.GetOffsetToPosition(next) <= 0 && c < width) { var range = new TextRange(start, end); bufferCells[ln, c++] = new BufferCell( range.Text[0], range.GetBackgroundAsConsoleColor(), range.GetForegroundAsConsoleColor(), BufferCellType.Complete); end = end.GetPositionAtOffset(1); } // for the whitespace ta the end of the line for (; c < width; c++) { bufferCells[ln, c] = new BufferCell(' ', ForegroundColor, BackgroundColor, BufferCellType.Complete); } start = next; } } } catch (Exception ex) { Write(ConsoleBrushes.ErrorForeground, ConsoleBrushes.ErrorBackground, ex.Message); } return bufferCells; }