public static void addFromImportStatement(@NotNull PsiFile file,
                                            @NotNull PyFromImportStatement newImport,
                                            @Nullable ImportPriority priority,
                                            @Nullable PsiElement anchor,
                                            @Nullable PsiElement insertBefore) {
    try {
      final PyImportStatementBase parentImport = PsiTreeUtil.getParentOfType(anchor, PyImportStatementBase.class, false);
      final InjectedLanguageManager manager = InjectedLanguageManager.getInstance(file.getProject());
      final PsiLanguageInjectionHost injectionHost = manager.getInjectionHost(file);
      final boolean insideDoctest = file instanceof PyDocstringFile &&
                                    injectionHost != null &&
                                    DocStringUtil.getParentDefinitionDocString(injectionHost) == injectionHost;

      final PsiElement insertParent;
      if (insertBefore != null && insertBefore.getParent() != null) {
        insertParent = insertBefore.getParent();
      }
      else if (parentImport != null && parentImport.getContainingFile() == file) {
        insertParent = parentImport.getParent();
      }
      else if (injectionHost != null && !insideDoctest) {
        insertParent = manager.getTopLevelFile(file);
      }
      else {
        insertParent = file;
      }

      if (insideDoctest) {
        final PsiElement element = insertParent.addBefore(newImport, getInsertPosition(insertParent, anchor, newImport, priority));
        PsiElement whitespace = element.getNextSibling();
        if (!(whitespace instanceof PsiWhiteSpace)) {
          whitespace = PsiParserFacade.getInstance(file.getProject()).createWhiteSpaceFromText("  >>> ");
        }
        insertParent.addBefore(whitespace, element);
      }
      else if (anchor instanceof PyImportStatementBase) {
        insertParent.addAfter(newImport, anchor);
      }
      else {
        final PsiElement position;
        if (insertBefore == null) {
          position = getInsertPosition(insertParent, anchor, newImport, priority);
        }
        else {
          position = insertBefore;
        }
        insertParent.addBefore(newImport, position);
      }
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
public static void addFromImportStatement(@NotNull PsiFile file,
                                            @NotNull PyFromImportStatement newImport,
                                            @Nullable ImportPriority priority,
                                            @Nullable PsiElement anchor,
                                            @Nullable PsiElement insertBefore)