void () { int visibleTargetPageIndex = documentOfPagesModel.tryGetIndexOfNeededPageInList(targetVisiblePosition.pageNumber); if (visibleTargetPageIndex == -1) { return; } int offsetToFirstVisibleSymbolOfTargetVisiblePage = getSymbolOffsetToStartOfPage(visibleTargetPageIndex); int topOfTargetVisiblePage = offsetToY(offsetToFirstVisibleSymbolOfTargetVisiblePage); int topOfTargetVisibleArea = topOfTargetVisiblePage + targetVisiblePosition.verticalScrollOffset; Rectangle visibleArea = editor.getScrollingModel().getVisibleArea(); int bottomOfTargetVisibleArea = topOfTargetVisibleArea + visibleArea.height; int lastVisiblePageIndex = visibleTargetPageIndex; int offsetToEndOfLastVisiblePage = getSymbolOffsetToStartOfPage(lastVisiblePageIndex + 1); while (lastVisiblePageIndex + 1 < documentOfPagesModel.getPagesAmount() && offsetToY(offsetToEndOfLastVisiblePage) <= bottomOfTargetVisibleArea) { lastVisiblePageIndex++; offsetToEndOfLastVisiblePage = getSymbolOffsetToStartOfPage(lastVisiblePageIndex + 1); } int maxAllowedAmountOfPagesInDocumentHere = lastVisiblePageIndex + 2 + 1; // max 2 invisible pages in the end while (documentOfPagesModel.getPagesAmount() > maxAllowedAmountOfPagesInDocumentHere) { removeLastPageFromDocument(); } }