Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define key when buffer is read-only

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...

like image 928
user1775326 Avatar asked Apr 02 '13 15:04

user1775326


People also ask

How do I change a buffer from read-only?

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.

Why is buffer read-only Emacs?

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 .


1 Answers

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)
like image 123
user4815162342 Avatar answered Sep 29 '22 05:09

user4815162342