class AddMethodCommand implements Runnable { private final PsiClass psiClass; private final String methodSignatureAndBody; public AddMethodCommand(PsiClass psiClass, String methodSignatureAndBody) { this.psiClass = psiClass; this.methodSignatureAndBody = methodSignatureAndBody; } public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { PsiManager psiManager = getPsiManager(); PsiMethod newMethod = psiManager.getElementFactory().createMethodFromText(methodSignatureAndBody, psiClass); PsiMethod methodAnchor = findNearestMethodAnchorInSelectedFile(); if (methodAnchor != null) { methodAnchor.getParent().addAfter(newMethod, methodAnchor); } else { psiClass.getNavigationElement().add(newMethod); } psiManager.getCodeStyleManager().reformat(newMethod); updateDocument(psiClass.getContainingFile()); newMethod = psiClass.findMethodBySignature(newMethod, false); jumpToPsiElement(newMethod); PsiWhiteSpace whiteSpace = (PsiWhiteSpace) PsiTreeUtil.getChildOfType(newMethod.getBody(), PsiWhiteSpace.class); TextRange range = whiteSpace.getTextRange(); getSelectedTextEditor().getCaretModel().moveToOffset(range.getStartOffset()); getSelectedTextEditor().getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); } catch (IncorrectOperationException e) { LOGGER.error(e); showErrorMessage("Could not add method: " + e.getMessage(), "Warning"); } } }); } private PsiMethod findNearestMethodAnchorInSelectedFile() { PsiFile psiFile = getPsiDocumentManager().getPsiFile(getSelectedTextEditor().getDocument()); int offset = getSelectedTextEditor().getCaretModel().getOffset(); PsiElement currentElement = psiFile.findElementAt(offset); if (currentElement == null) { return null; } PsiElement nearestMethod = PsiTreeUtil.getParentOfType(currentElement, PsiMethod.class); if (nearestMethod == null) { nearestMethod = PsiTreeUtil.getPrevSiblingOfType(currentElement, PsiMethod.class); } if (nearestMethod == null) { nearestMethod = PsiTreeUtil.getNextSiblingOfType(currentElement, PsiMethod.class); } return (PsiMethod) nearestMethod; } } This command is executed using the following statement: CommandProcessor.getInstance().executeCommand(project, command, name, commandID);