List<TextRange> (Document document) { ArrayList<TextRange> result = new ArrayList<>(); int offset = 0; int startPos; while ((startPos = document.getText().indexOf('[', offset)) != -1) { int finalStartPos = startPos; WriteCommandAction.runWriteCommandAction(getProject(), () -> document.deleteString(finalStartPos, finalStartPos + 1)); int endPos = document.getText().indexOf(']', startPos); if (endPos == -1) break; WriteCommandAction.runWriteCommandAction(getProject(), () -> document.deleteString(endPos, endPos + 1)); result.add(new TextRange(startPos, endPos)); } return result; }