Keyword definitions are evaluated at the time of loading .emacs , whereas you want them to be evaluated each time you visit only a toggle-read-only file and toggle-read-only is executed each time. In addition, you want them to be canceled whenever the buffer is read and written again.
Instead of embedding all of this, you can use the fact that Emacs already supports the automatic activation of view-mode in read-only buffers. All you have to do is enable this functionality and define your keys in the view-mode-map :
(setq view-read-only t) ; enter view-mode for read-only files (define-key view-mode-map "n" 'next-line) (define-key view-mode-map "p" 'previous-line)
source share