0

Is it possible to make only parts of a buffer read-only?

Say I have set two marks or line-numbers in the buffer and I would like to make everything between those two marks or line-numbers as read-only.

The function (read-only-mode) applies to the entire buffer but not to parts of it.

Also, if possible, I would like the read-only parts of a buffer marked with a different background color say light beige.

4
(defface my-read-only '((default . (:background "beige")))
  "Face for `my-read-only-region'")

(defun my-read-only-region (begin end)
  "Make the marked region read-only.  See also `my-writeable-region'.

Read-only text is given the face `my-read-only'."
  (interactive "r")
  (let ((inhibit-read-only t))
    (with-silent-modifications
      (add-text-properties begin end '(read-only t))
      (let ((overlay (make-overlay begin end)))
        (overlay-put overlay 'my-type 'read-only)
        (overlay-put overlay 'face 'my-read-only)))))

(defun my-writeable-region (begin end)
  "Make the marked region writeable.  See also `my-read-only-region'."
  (interactive "r")
  (let ((inhibit-read-only t))
    (with-silent-modifications
      (remove-text-properties begin end '(read-only t))
      (remove-overlays begin end 'my-type 'read-only))))
  • I'm curious: why overlays and text-properties? – rpluim Nov 19 '18 at 9:55
  • AFAIU adding faces via overlays is less susceptible to font-lock conflicts than using text-properties, and it seemed to Do The Right Thing in all my tests. It's not something I use a lot, though, and I'd be happy to be shown a more unified method. I'd then have done it all with the overlay, except there's no 'read-only' overlay property; so I believe that part needs to be a text-property. – phils Nov 19 '18 at 11:01
2

@phils said how to deal with the problem programmatically.

Here is how to deal with it interactively:

  • Select the region
  • Menu Edit -> Text Properties -> Special Properties -> Read-Only

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.