Runnable () { final Set<String> simplyImportedClasses = new LinkedHashSet<>(); final Set<String> staticallyImportedMembers = new LinkedHashSet<>(); final Set<GrImportStatement> usedImports = new HashSet<>(); final Set<GrImportStatement> unresolvedOnDemandImports = new HashSet<>(); final Set<String> implicitlyImportedClasses = new LinkedHashSet<>(); final Set<String> innerClasses = new HashSet<>(); final Map<String, String> aliasImported = new HashMap<>(); final Map<String, String> annotatedImports = new HashMap<>(); GroovyImportUtil.processFile(myFile, simplyImportedClasses, staticallyImportedMembers, usedImports, unresolvedOnDemandImports, implicitlyImportedClasses, innerClasses, aliasImported, annotatedImports); final List<GrImportStatement> oldImports = PsiUtil.getValidImportStatements(myFile); // Add new import statements GrImportStatement[] newImports = prepare(usedImports, simplyImportedClasses, staticallyImportedMembers, implicitlyImportedClasses, innerClasses, aliasImported, annotatedImports, unresolvedOnDemandImports); if (oldImports.isEmpty() && newImports.length == 0 && aliasImported.isEmpty()) return EmptyRunnable.getInstance(); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myFile.getProject()); final GroovyFile tempFile = factory.createGroovyFile("", false, null); tempFile.putUserData(PsiFileFactory.ORIGINAL_FILE, myFile); for (GrImportStatement newImport : newImports) { tempFile.addImport(newImport); } if (!oldImports.isEmpty()) { final int startOffset = oldImports.get(0).getTextRange().getStartOffset(); final int endOffset = oldImports.get(oldImports.size() - 1).getTextRange().getEndOffset(); String oldText = myFile.getText().substring(startOffset, endOffset); if (tempFile.getText().trim().equals(oldText)) return EmptyRunnable.getInstance(); } return () -> { final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myFile.getProject()); final Document document = documentManager.getDocument(myFile); if (document != null) documentManager.commitDocument(document); List<GrImportStatement> existingImports = PsiUtil.getValidImportStatements(myFile); for (GrImportStatement statement : tempFile.getImportStatements()) { myFile.addImport(statement); } for (GrImportStatement importStatement : existingImports) { myFile.removeImport(importStatement); } }; }