private int yPositionToOffset(int y, boolean beginLine) {
    if (!dimensionsAreValid) {
      recalcEditorDimensions();
    }
    int safeY = Math.max(0, y - myEditorScrollbarTop);
    int editorY;
    if (myEditorSourceHeight < myEditorTargetHeight) {
      editorY = safeY;
    }
    else {
      float fraction = Math.max(0, Math.min(1, safeY / (float)myEditorTargetHeight));
      editorY = (int)(fraction * myEditorSourceHeight);
    }
    VisualPosition visual = myEditor.xyToVisualPosition(new Point(0, editorY));
    int line = myEditor.visualToLogicalPosition(visual).line;
    Document document = myEditor.getDocument();
    if (line < 0) return 0;
    if (line >= document.getLineCount()) return document.getTextLength();

    FoldingModelEx foldingModel = myEditor.getFoldingModel();
    if (beginLine) {
      int offset = document.getLineStartOffset(line);
      FoldRegion startCollapsed = foldingModel.getCollapsedRegionAtOffset(offset);
      return startCollapsed != null ? Math.min(offset, startCollapsed.getStartOffset()) : offset;
    }
    else {
      int offset = document.getLineEndOffset(line);
      FoldRegion startCollapsed = foldingModel.getCollapsedRegionAtOffset(offset);
      return startCollapsed != null ? Math.max(offset, startCollapsed.getEndOffset()) : offset;
    }
  }
private int yPositionToOffset(int y, boolean beginLine)