Saturday, March 08, 2008

coping emacs #1

After having written a lot of erlang code with emacs(uhhm ... no, erlide, the erlang eclipse plugin, is not yet a viable alternative...), I decided to start (back-)porting eclipse features to emacs. Yeahhhh! I am now among those 1337 |-|4><025 that have their own ".emacs" in ~.

Well one feature, that I can't live without, is moving the current line with Alt - up/down, this is really usefull together with anotherthe other feature: duplicating the current line(Ctrl-Alt-up/down).

Below is the elisp code that provides these features and binds them to the keys these are bound to in eclipse. Note: In contrast to the eclipse version of this feature, this implementation does not(yet) work with regions, but with lines only.

Ok, put this in your ~/.emacs

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Written by Sven Heyll in 2008
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun sh-wind-col (thunk)
(let ((col (- (point) (line-beginning-position))))
(apply thunk '())
(beginning-of-line)
(forward-char col)))

(defun sh-with-current-line (func)
(let ((cline (buffer-substring (line-beginning-position) (line-end-position))))
(apply func `(,cline))))

(defun sh-dup-line-down ()
(interactive)
(sh-wind-col
(lambda ()
(sh-with-current-line
(lambda (cline)
(end-of-line)
(insert ?\n)
(insert cline))))))

(defun sh-dup-line-up ()
(interactive)
(sh-wind-col
(lambda ()
(sh-with-current-line
(lambda (cline)
(beginning-of-line)
(insert cline)
(insert ?\n)
(forward-line -1))))))

(global-set-key [C-M-down] 'sh-dup-line-down)
(global-set-key [C-M-up] 'sh-dup-line-up)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun sh-move-line (dir)
(defun extract-a-line (dir)
(let ((line-start (line-beginning-position (+ 1 dir)))
(line-end (line-end-position (+ 1 dir))))
(setq res (delete-and-extract-region line-start line-end))
(delete-region line-start (+ 1 line-start))
res))
(if (not
(or
(and (< dir 0) (= (line-beginning-position) (point-min)))
(and (> dir 0) (= (line-end-position) (- (point-max) 1)))))
(let
((col (- (point) (line-beginning-position)))
(line (extract-a-line dir)))
(if (< dir 0)
(progn
(end-of-line)
(insert ?\n)
(insert line))
(progn
(beginning-of-line)
(insert line)
(insert ?\n)))
(beginning-of-line (truncate (+ 0.5 (* 0.5 dir))))
(forward-char col))))

(defun sh-line-down ()
(interactive)
(sh-move-line 1))

(defun sh-line-up ()
(interactive)
(sh-move-line -1))

(global-set-key [M-down] 'sh-line-down)
(global-set-key [M-up] 'sh-line-up)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

No comments: