Detect key when buffer is read-only

I try to use the keys "n" and "p" in the same way as "Cn" and "Cp" when my buffer is read-only (yes, I'm lazy).

I use this code in the .emacs file:

(when buffer-read-only (local-set-key "n" 'next-line)) (when buffer-read-only (local-set-key "p" 'previous-line)) 

which works when the buffer is automatically set as read-only (i.e. like in w3m), but it does not seem to work when I run Cx Cq (read-only). He keeps talking

 Buffer is read-only: #<buffer buffername> 

and I don’t know how it could work otherwise ...

+4
source share
1 answer

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) 
+6
source

All Articles