1

Scenario: I have Emacs open with split window. Top window contains an R script. Bottom windows has the interactive R session. I want to be able to copy a region from the interactive window to the script window, AND have the copied region be commented.

My current approach (below) does this to the region:

  1. comment-region
  2. copy to other window/buffer
  3. uncomment-region

My problem is that comment-region does not update beg/end. This causes the copy to other window to not copy the entire commented region (since the commented region is now larger).

How do I get comment-region to update beg/end ?

(defun duplicate-region-to-other-window-and-comment (beg end)
  "Duplicate the region to other window. Comment it."
  (interactive "r")
  (comment-region beg end)
  (pcase (window-list)
    (`(,w0 ,w1)
     (with-selected-window w1
       (insert-buffer-substring (window-buffer w0) beg end)))
    (_ (user-error "Only works with 2 windows"))) ;; _ is really t
  (uncomment-region beg end ) )
0

1 Answer 1

1

You could avoid this problem by commenting the text after you insert it:

(defun duplicate-region-to-other-window-and-comment (beg end)
  "Duplicate the region to other window. Comment it."
  (interactive "r")
  (let ((text (buffer-substring beg end))) ;; collect text to copy
    (pcase (window-list)
      (`(,w0 ,w1)
       (with-selected-window w1
         (let ((start (point))) ;; store beginning of inserted text
           (insert text)
           (comment-region start (point))))) ;; comment inserted region
      (_ (user-error "Only works with 2 windows")))))
2
  • Please reformat (reindent) your code. It looks like it might a result of copying TAB chars. (Before copying, M-x untabify is your friend.)
    – Drew
    Commented Nov 17, 2021 at 20:04
  • Excellent. Thanks. Commented Nov 17, 2021 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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