tags:

views:

506

answers:

3

In my .emacs i have the following function that transposes a line

(defun move-line (n)
   "Move the current line up or down by N lines."
   (interactive "p")
   (let ((col (current-column))
         start
         end)
     (beginning-of-line)
     (setq start (point))
     (end-of-line)
     (forward-char)
     (setq end (point))
     (let ((line-text (delete-and-extract-region start end)))
       (forward-line n)
       (insert line-text)
       ;; restore point to original column in moved line
       (forward-line -1)
       (forward-char col))))

And I bind a key to it like this

(global-set-key (kbd "M-<down>") 'move-line)
;; this is the same as M-x global-set-key <return>

However, I want to bind M-up to move-line (-1) But I cant seem to be able to do it correctly:

;; M-- M-1 M-x global-set-key <return>

How do I define the above using global-set-key to call move-line -1?

+2  A: 

Not minutes after asking the question I figured it out by copy+pasting code. However I have no clue how it works.

(global-set-key (kbd "M-<up>") (lambda () (interactive) (move-line -1)))
You create a anomynous function (`lambda`) which is only a wrapper for your function called with the argument `-1`. Search the internet or emacs info for `lambda` if you want to get more information.
danielpoe
+3  A: 

global-set-key only takes 2 arguments: the key sequence and the command you want to bind to it. So

(global-set-key (kbd "M-<down>") 'move-line)

works fine. But if you want to use move-line with an argument you need to wrap it in an anonymous (aka lamba) function so that it presents itself to global-set-key as one value.

Martin Redmond
A: 

You might want to check out the "transpose-lines" built-in function.