public void documentChanged(final DocumentEvent documentEvent) { final Project project = JiraConfigurationComponent.this.project; FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance(); FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); PsiManager psiManager = PsiManager.getInstance(project); Document selectedDocument = documentEvent.getDocument(); VirtualFile selectedFile = fileDocumentManager.getFile(selectedDocument); PsiFile psiFile = psiManager.findFile(selectedFile); // We only annotate java code if (psiFile.canContainJavaCode()) { final PsiJavaFile javaFile = (PsiJavaFile) psiFile; int offset = documentEvent.getOffset(); PsiElement context = javaFile.findElementAt(offset); if (context == null) { return; } while (!(context instanceof PsiMethod)) { context = context.getParent(); } final PsiElement method = context; final PsiElement comment = method.getFirstChild(); final PsiComment[] element = new PsiComment[] { null }; if (!(comment instanceof PsiComment)) { final PsiElementFactory elementFactory = psiManager.getElementFactory(); CommandProcessor.getInstance().executeCommand(project, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { String commentString; PsiDocumentManager pdm = PsiDocumentManager.getInstance(project); try { int textOffset = method.getTextOffset(); String issueKey = "FOO-777"; String issueDescription = "This text comes from the issue description"; //commentString = "/**\n * " + issueDescription + "\n *\n * @jira " + issueKey + "\n */"; StringBuffer comment = new StringBuffer(); comment.append("/**\n"); comment.append(" * "); comment.append(issueDescription); comment.append("\n"); comment.append(" * @jira "); comment.append(issueKey); comment.append("\n"); comment.append(" */"); commentString = comment.toString(); element[0] = elementFactory.createCommentFromText(commentString, null); } catch (IncorrectOperationException e) { LOGGER.error("Unable to create comment element.", e); } try { pdm.commitDocument(documentEvent.getDocument()); method.addBefore(element[0], comment); } catch (IncorrectOperationException e) { LOGGER.error("Unable to add the javadoc comment.", e); } finally { // make sure PSI is in sync with a certain document pdm.commitDocument(documentEvent.getDocument()); } } }); } }, "Comment", null); fileEditorManager.getSelectedTextEditor().getCaretModel().moveToOffset(offset + element[0].getLength()); } } }