TextRange (@NotNull PsiFile file, @NotNull Document document, int offset) { CharSequence text = document.getImmutableCharSequence(); if (offset <= 0 || offset >= text.length() || !isWhiteSpaceSymbol(text.charAt(offset))) { return null; } if (!isWhiteSpaceSymbol(text.charAt(offset - 1))) { return null; // no whitespaces before offset } int end = offset; for (; end < text.length(); end++) { if (text.charAt(end) == '\n') { break; // line is empty till the end } if (!isWhiteSpaceSymbol(text.charAt(end))) { return null; } } String marker = createMarker(file, offset); document.insertString(offset, marker); return new TextRange(offset, offset + marker.length()); }