Define key when buffer is read-only

孤者浪人 提交于 2019-12-23 12:35:01

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/15768316/define-key-when-buffer-is-read-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!