2008-01-02

Locking a section of text in emacs

Today, I was talking to a friend about things that would be useful for text editors. One feature that we thought was missing was the ability to select a region of text, and lock it so as to prevent accidental editing without unlocking it.

This was rather trivial to add to emacs:


(defun lock ()
"Make a section of text read-only, and add an overlay so
it's apparent"
(interactive)
(let ((start (region-beginning))
(end (region-end)))
(overlay-put (make-overlay start (+ 1 end)) 'face
'(:background "light slate gray"))
(put-text-property start end 'read-only t)))

(defun unlock ()
"Unlock a region of text, and remove its overlay"
(interactive)
(let ((inhibit-read-only t)
(start (region-beginning))
(end (region-end)))
(remove-overlays start (+ 1 end))
(remove-text-properties start end '(read-only))))


Just bind lock and unlock to some keys, and there you go - makes a region of text uneditable, and adds an overlay to it.

2 comments:

  1. The unlock function should read "remove its overlay" instead of "remove it's overlay"; the latter is the same thing as "remove it is overlay," which obviously makes no sense ;-)

    ReplyDelete