Use with-current-buffer and derived-mode-p.