String (@NotNull Document document) { List<CharSequence> resultLines = new ArrayList<>(); for (int i = document.getLineCount() - 1; i >= 0; i--) { int lineStart = document.getLineStartOffset(i); int lineEnd = document.getLineEndOffset(i); if (document.getCharsSequence().subSequence(lineStart, lineEnd).toString().trim().isEmpty()) { continue; } if ("//".equals(document.getCharsSequence().subSequence(lineStart, lineStart + 2).toString())) { resultLines.add(document.getCharsSequence().subSequence(lineStart + 2, lineEnd)); } else { break; } } Collections.reverse(resultLines); StringBuilder result = new StringBuilder(); for (CharSequence line : resultLines) { result.append(line).append("\n"); } result.delete(result.length() - 1, result.length()); return result.toString(); }