I'm trying to use the keys "n" and "p" the same way as "C-n" and "C-p" when my buffer is read-only (yes, I'm lazy).
I use this code in my .emacs file :
(when buffer-read-only (local-set-key "n" 'next-line))
(when buffer-read-only (local-set-key "p" 'previous-line))
which is working when the buffer is automatically set as read-only (i.e. like within w3m) but it seems it doesn't work when I run C-x C-q (toggle-read-only). It keeps saying
Buffer is read-only: #<buffer buffername>
and I have no idea of how this could work otherwise...
Your key definitions are evaluated during load of .emacs
, whereas you want them evaluated each time a read-only file is visited, and each time toggle-read-only
is executed. Furthermore, you want them undone whenever a buffer is made read-write again.
Instead of implementing all that, you can make use of the fact that Emacs already supports automatic activation of view-mode
in read-only buffers. All you need to do is enable that functionality, and define your keys in 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)