6

How can I automatically move selected to the other window? Trying to streamline my split-window workflow.

Here's what I have so far. Doesn't work yet.

(defun move-region-to-other-window (start end)
  "Move selected text to other window"
  (interactive "r")
  (if (use-region-p) 
      (let ((count (count-words-region start end)))
        (save-excursion
          (kill-region start end)
          (other-window)          
          (yank)
          (newline))
        (other-window)         
        (message "Moved %s words" count))
    (message "No region selected")))

Attribution: Code above is based on danielsz's excellent package Palimpsest Mode.

incandescentman
  • 4,111
  • 16
  • 53
  • 3
    I suppose people can just copy and evaluate your code and try it out to see what "doesn't work yet" means, but it would be nice nevertheless if you could provide this info right away. – paprika Nov 20 '14 at 09:01
  • Seems like `append-to-buffer` does what you want, except for killing the region afterward. – glucas Nov 21 '14 at 03:58

1 Answers1

7

Your code is alright except that it is missing the mandatory arguments to the other-window command.

From the function documentation (C-h f other-window RET),

(other-window COUNT &optional ALL-FRAMES)

Select another window in cyclic ordering of windows. COUNT specifies the number of windows to skip, starting with the selected window, before making the selection. If COUNT is positive, skip COUNT windows forwards. If COUNT is negative, skip -COUNT windows backwards. COUNT zero means do not skip any window, so select the selected window. In an interactive call, COUNT is the numeric prefix argument. Return nil.

Fixed code

(defun move-region-to-other-window (start end)
  "Move selected text to other window"
  (interactive "r")
  (if (use-region-p) 
      (let ((count (count-words-region start end)))
        (save-excursion
          (kill-region start end)
          (other-window 1)   
          (yank)
          (newline))
        (other-window -1)     
        (message "Moved %s words" count))
    (message "No region selected")))
Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179
  • 2
    @PeterSalazar: This is the core problem: the function works if you change `(other-window)` to `(other-window 1)`. However, it will insert the text wherever point happens to be: maybe consider adding something like `(goto-char (point-max))` right before the `(yank)` if you want it added to the *end* of the buffer. – Dan Nov 20 '14 at 04:50
  • 2
    @Dan: I guess what the OP might actually *want* could be adding text at point. – mbork Nov 20 '14 at 10:00
  • Yes, adding text at point is in fact the desired behavior, allows more precision. – incandescentman Nov 20 '14 at 18:34