private void mergeOverlappingCaretsAndSelections() {
    EditorImpl.assertIsDispatchThread();
    if (myCarets.size() > 1) {
      LinkedList<CaretImpl> carets = new LinkedList<>(myCarets);
      carets.sort(CARET_POSITION_COMPARATOR);
      ListIterator<CaretImpl> it = carets.listIterator();
      CaretImpl keepPrimary = getPrimaryCaret();
      while (it.hasNext()) {
        CaretImpl prevCaret = null;
        if (it.hasPrevious()) {
          prevCaret = it.previous();
          it.next();
        }
        CaretImpl currCaret = it.next();
        if (prevCaret != null && caretsOverlap(currCaret, prevCaret)) {
          int newSelectionStart = Math.min(currCaret.getSelectionStart(), prevCaret.getSelectionStart());
          int newSelectionEnd = Math.max(currCaret.getSelectionEnd(), prevCaret.getSelectionEnd());
          CaretImpl toRetain;
          CaretImpl toRemove;
          if (currCaret.getOffset() >= prevCaret.getSelectionStart() && currCaret.getOffset() <= prevCaret.getSelectionEnd()) {
            toRetain = prevCaret;
            toRemove = currCaret;
            it.remove();
            it.previous();
          }
          else {
            toRetain = currCaret;
            toRemove = prevCaret;
            it.previous();
            it.previous();
            it.remove();
          }
          if (toRemove == keepPrimary) {
            keepPrimary = toRetain;
          }
          removeCaret(toRemove);
          if (newSelectionStart < newSelectionEnd) {
            toRetain.setSelection(newSelectionStart, newSelectionEnd);
          }
        }
      }
      if (keepPrimary != getPrimaryCaret()) {
        synchronized (myCarets) {
          myCarets.remove(keepPrimary);
          myCarets.add(keepPrimary);
          myPrimaryCaret = keepPrimary;
        }
      }
    }
    if (myEditorSizeValidationScheduled) {
      myEditorSizeValidationScheduled = false;
      myEditor.validateSize();
    }
  }
private void mergeOverlappingCaretsAndSelections()