If you want to copy some information to another buffer, and from then on let the buffers evolve independently, you can do just that.
But if you want the other buffer to reflect the original content in real time, then Emacs provides this with indirect buffers. An indirect buffer is another buffer that has the same content as the original (modifications in one buffer are reflected in the other buffer), but different settings: a different major mode, different minor modes, different local variables, a different point, different marks, a different narrowing, etc.
So you can get a view of a part of a buffer in a different major mode, while keeping track of modifications in the original buffer and reflecting modifications back to the original buffer. First make an indirect buffer with M-x clone-indirect buffer
; there's also clone-indirect-buffer-other-window
which is bound to C-x 4 c
(C-x 4
window prefix, and c
for clone). In the cloned buffer, narrow to the region you want: select the interesting part and run C-x n n
(narrow-to-region
). Change the major mode as desired.
You can automate that with a command like this for interactive use:
(defun edit-region-in-foo-mode (beg end)
(interactive "@r")
(let ((new-buffer (clone-indirect-buffer nil t)))
(narrow-to-region beg end)
(foo-mode)))
For programming use:
(defmacro with-indirect-buffer-in-foo-mode (beg end &rest body)
`(with-current-buffer (clone-indirect-buffer nil nil)
(narrow-to-region beg end)
(foo-mode)
(unwind-protect
,body
(kill-buffer (current-buffer)))))