public static int compareElementsByPosition(@Nullable PsiElement element1, @Nullable PsiElement element2) {
    if (element1 == null && element2 == null) return 0;
    if (element1 == null) return -1;
    if (element2 == null) return 1;
    if (element1.equals(element2)) return 0;

    PsiFile psiFile1 = element1.getContainingFile();
    PsiFile psiFile2 = element2.getContainingFile();
    if (psiFile1 == null && psiFile2 == null) return 0;
    if (psiFile1 == null) return -1;
    if (psiFile2 == null) return 1;

    if (!psiFile1.equals(psiFile2)) {
      String name1 = psiFile1.getName();
      String name2 = psiFile2.getName();
      return name1.compareToIgnoreCase(name2);
    }
    if (element1 instanceof StubBasedPsiElement && element2 instanceof StubBasedPsiElement) {
      StubElement<?> stub1 = ((StubBasedPsiElement<?>)element1).getStub();
      StubElement<?> stub2 = ((StubBasedPsiElement<?>)element2).getStub();
      if (stub1 != null && stub2 != null) {
        return compareStubPositions(stub1, stub2);
      }
    }
    TextRange textRange1 = element1.getTextRange();
    TextRange textRange2 = element2.getTextRange();
    if (textRange1 == null && textRange2 == null) return 0;
    if (textRange1 == null) return -1;
    if (textRange2 == null) return 1;
    return Segment.BY_START_OFFSET_THEN_END_OFFSET.compare(textRange1, textRange2);
  }
public static int compareElementsByPosition(@Nullable PsiElement element1, @Nullable PsiElement element2)