public class Finders {
public static Optional<PsiElement> findFirstElementAtLine(@NotNull final PsiFile file, Integer line) {
if (line == null) return Optional.absent();
int ijLine = line - 1;
final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
Optional<PsiElement> element = Optional.absent();
try {
if (document != null) {
final int offset = document.getLineStartOffset(ijLine);
element = fromNullable(file.getViewProvider().findElementAt(offset));
if (element.isPresent() && document.getLineNumber(element.get().getTextOffset()) != ijLine) {
element = fromNullable(element.get().getNextSibling());
}
}
} catch (@NotNull final IndexOutOfBoundsException ignore) {
// Ignore this exception
}
while (element.isPresent() && element.get().getTextLength() == 0) {
element = fromNullable(element.get().getNextSibling());
}
if (document != null && element.isPresent() && document.getLineNumber(element.get().getTextOffset()) != ijLine) {
element = Optional.absent();
}
return element;
}