int (final Editor editor, final int tailOffset) { final Document document = editor.getDocument(); if (tailOffset >= document.getTextLength()) return -1; final CharSequence charsSequence = document.getCharsSequence(); EditorHighlighter highlighter = editor.getHighlighter(); int existingRParenthOffset = -1; for(HighlighterIterator iterator = highlighter.createIterator(tailOffset); !iterator.atEnd(); iterator.advance()){ final IElementType tokenType = iterator.getTokenType(); if ((!(tokenType instanceof IJavaElementType) || !ElementType.JAVA_COMMENT_OR_WHITESPACE_BIT_SET.contains(tokenType)) && tokenType != TokenType.WHITE_SPACE) { final int start = iterator.getStart(); if (iterator.getEnd() == start + 1 && ')' == charsSequence.charAt(start)) { existingRParenthOffset = start; } break; } } if (existingRParenthOffset >= 0){ final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(editor.getProject()); psiDocumentManager.commitDocument(document); TextRange range = getRangeToCheckParensBalance(psiDocumentManager.getPsiFile(document), document, editor.getCaretModel().getOffset()); int balance = calcParensBalance(document, highlighter, range.getStartOffset(), range.getEndOffset()); if (balance > 0){ return -1; } } return existingRParenthOffset; }