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...
To change the read-only status of a buffer, use C-x C-q (toggle read-only-mode ). To change file permissions, you can run dired on the file's directory ( C-x d ), search for the file by C-s and use M to change its mode.
A buffer visiting a write-protected file is normally read-only. Here, the purpose is to inform the user that editing the buffer with the aim of saving it in the file may be futile or undesirable. The user who wants to change the buffer text despite this can do so after clearing the read-only flag with C-x C-q .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With