Emacs: read-only copy of current buffer

Very often I split the emacs frame into two windows with the same buffer in both. For example on the left side I have a class definition and on the right side I implement it (so that part of the buffer is below the definition). While this works like a charm, sometimes I stumble upon an obstacle: if I want to change the class definition for testing, I cannot see the old definition for comparision. It has changed after all.

So I wrote this function which creates a copy of the current buffer, names it appropriately, makes it read-only, splits the current window and places the read-only copy on the right. Now I can see the old implementation while changing the current one, I can copy parts of the old stuff back into the current (because UNDO might remove some of the new things I want to keep) and so on. I bound this to C-c C-p, which you might want to change.

Here's the code. Put into .emacs to try it out:

;; ** Make a read-only copy of the current buffer
;;
I just create a new read-only buffer and copy the contents of the
;; current one into it, which can be used as backup
(defvar copy-counter 0)

(defun get-copy-buffer-name() “return unique copy buffer name” (let ( (name (concat "*COPY “ (buffer-name (current-buffer)) ” (RO)")) ) (if (not (get-buffer name)) (progn (setq copy-counter (1+ copy-counter)) (concat name "<" (number-to-string copy-counter) ">") ) (concat name) )))

(defun copy-buffer-read-only() “Create a read-only copy of the current buffer” (interactive) (let ( (old-buffer (current-buffer)) (new-buffer-name (get-copy-buffer-name)) ) (progn (delete-other-windows) (split-window-horizontally) (other-window 1) (if (not (eq (get-buffer new-buffer-name) nil)) (kill-buffer (get-buffer new-buffer-name)) ) (set-buffer (get-buffer-create new-buffer-name)) (insert-buffer-substring old-buffer) (read-only-mode) (switch-to-buffer new-buffer-name) (other-window 1) )))

(defaliascp ‘copy-buffer-read-only)

(global-set-key (kbd “C-c C-p”) ‘copy-buffer-read-only)

There's even a screenshot (the read-only copy can be seen on the right):

#emacs

↷ 27.05.2016