Emacs: make portion of buffer readonly

emacs

I sometimes edit files in emacs where portions of the file are
documentation or something else that shouldn't be edited, and another
portions are "play areas" where I'm free to edit and create new text.

Question: can I make a portion of an emacs buffer readonly?

The simplest example would be making lines 1-100 readonly (for
example). A more complex example (similar to emacs bookmarks) would be
to make all text between [readonly] and [/readonly] uneditable.

I googled this, but couldn't find anything useful.

Best Answer

Yes, you can make a portion of a buffer read-only using text properties. The code below defines two new commands make-region-read-only and make-region-read-write that affect the region between point and mark. Put the code in your .emacs file to make the commands available via Meta-x.

(defun make-region-read-only (start end)
  (interactive "*r")
  (let ((inhibit-read-only t))
    (put-text-property start end 'read-only t)))

(defun make-region-read-write (start end)
  (interactive "*r")
  (let ((inhibit-read-only t))
    (put-text-property start end 'read-only nil)))