     (when (and (not isStar)
                (not isComment)
                (member wordAtLineBeginning zomp-indent-keywords)
-               (not endAtNextLine)
-               (not nextLineMoreIndented)
+               (not (and endAtNextLine (>= nextLineIndentDiff 0)))
+               (<= nextLineIndentDiff 0)
                isAtEnd)
       (insert "end")
       (indent-according-to-mode)

        (wordAtLineBeginning "")
        (endAtNextLine nil)
        (endQuotationAtNextLine nil)
        (nextLineMoreIndented nil))

    (setq isAtEnd (looking-at " *$"))


    (save-excursion
      (let ((thisLineIndent (zomp-current-line-indent)))
        (next-line)
        (setq nextLineIndentDiff (- (zomp-current-line-indent) thisLineIndent))))

    (save-excursion
      (back-to-indentation)
