The `last-command' variable in Emacs Lisp - emacs

I wrote a snippet to copy previous line to point,if I repeat the command,it copy more previous line. It's here:
(defun my-copy-line (num)
"copy lines"
(interactive "p")
(save-excursion
(move-end-of-line 1)
(push-mark)
(move-beginning-of-line num)
(kill-ring-save (point) (mark))))
(defvar copy-line-num 1)
(defun my-copy-line-here (num)
"copy line ahead here"
(interactive "p")
(if (eq this-command last-command)
(setq copy-line-num (+ copy-line-num num)) ;count num lines up
(setq copy-line-default 1))
(save-excursion
(save-excursion ;make current line blank
(move-beginning-of-line 1)
(push-mark)
(move-end-of-line 1)
(kill-region (point) (mark))) ;不用kill-line,以免删除空白行
(push-mark)
(previous-line copy-line-num)
(my-copy-line 1)
(exchange-point-and-mark)
(yank))
(setq this-command 'my-copy-line-here))
I intended to yank previous line to override current line.If I repeat my-copy-line-here,I'll yank the 2th previous line,this is accomplished by the test (if (eq this-command last-command).But it failed ,Because every time after executing my-copy-line-here,it sets the last-command to yank,instead my-copy-line-here.I just can't figure out what's going on.I need your help.

`M-y (yank-pop) works similarly, pasting previous copied lines on repeated calls. Checking its sources, I see two differences with yours:
; explicit check for yank
(if (not (eq last-command 'yank))
; setting this command
(setq this-command 'yank)
Perhaps one or both of these together can be useful. Set this-command after calling yank maybe?

Related

Command to uncomment multiple lines without selecting them

Is there a command in emacs to uncomment an entire comment block without having to mark it first?
For instance, let's say the point is inside a comment in the following code:
(setq doing-this t)
;; (progn |<--This is the point
;; (er/expand-region 1)
;; (uncomment-region (region-beginning) (region-end)))
I would like a command that turns that into this:
(setq doing-this t)
(progn
(er/expand-region 1)
(uncomment-region (region-beginning) (region-end)))
It's fairly easy to write a command that (un)comments a single line, but I've yet to find one that uncomments as many lines as possible. Is there one available?
A quick reply --- code could be improved and made more useful. You might want to extend it to other kinds of comments, besides ;;;, for instance.
(defun uncomment-these-lines ()
(interactive)
(let ((opoint (point))
beg end)
(save-excursion
(forward-line 0)
(while (looking-at "^;;; ") (forward-line -1))
(unless (= opoint (point))
(forward-line 1)
(setq beg (point)))
(goto-char opoint)
(forward-line 0)
(while (looking-at "^;;; ") (forward-line 1))
(unless (= opoint (point))
(setq end (point)))
(when (and beg end)
(comment-region beg end '(4))))))
The key is comment-region. FWIW, I bind comment-region to C-x C-;. Just use it with C-u to uncomment.
You can use Emacs' comment handling functions to make a generalised version of Drew's command.
(defun uncomment-current ()
(interactive)
(save-excursion
(goto-char (point-at-eol))
(goto-char (nth 8 (syntax-ppss)))
(uncomment-region
(progn
(forward-comment -10000)
(point))
(progn
(forward-comment 10000)
(point)))))

in org-mode, how to fold/hide footnotes?

In Emacs org-mode, is there a way to get inline footnote definitions to appear as collapsed?
So that for instance, a line like this:
This effect is due to the strength of weak ties[fn:: Newman, Mark, Albert-László Barabási, and Duncan J. Watts. 2006. The Structure and Dynamics of Networks. Princeton, NJ: Princeton University Press].
might simply appear like this:
This effect is due to the strength of weak ties[✭].
I would also need a command to show the footnotes when necessary. So maybe what is needed are two commands: org-hide-footnotes and org-show-footnotes.
I don't believe this is possible at the moment. Also using TAB as the expansion key within for it would likely cause even more overloading of the key.
On the other hand, is there any particular reason not to use a footnote section for the footnotes?
C-c C-x f will create/interact with any footnotes you have.
(org-footnote-action &optional SPECIAL)
Do the right thing for footnotes.
When at a footnote reference, jump to the definition.
When at a definition, jump to the references if they exist, offer to
create them otherwise.
When neither at definition or reference, create a new footnote,
interactively.
With prefix arg SPECIAL, offer additional commands in a menu.
The additional commands being:
s Sort the footnote definitions by reference sequence. During editing,
Org makes no effort to sort footnote definitions into a particular
sequence. If you want them sorted, use this command, which will
also move entries according to org-footnote-section. Automatic
sorting after each insertion/deletion can be configured using the
variable org-footnote-auto-adjust.
r Renumber the simple fn:N footnotes. Automatic renumbering
after each insertion/deletion can be configured using the variable
org-footnote-auto-adjust.
S Short for first r, then s action.
n Normalize the footnotes by collecting all definitions (including
inline definitions) into a special section, and then numbering them
in sequence. The references will then also be numbers. This is
meant to be the final step before finishing a document (e.g., sending
off an email). The exporters do this automatically, and so could
something like message-send-hook.
d Delete the footnote at point, and all definitions of and references
to it.
INITIAL (February 6, 2014):   First working draft.
EDIT February 18, 2014:  Revised the function lawlist-toggle-block-visibility so that it contains a proper if/then/else statement -- i.e., if the line contains the requisite beginning region regexp, then the block visibility will be toggled, else a message saying sorry . . . . Added a citation to a related thread for code folding. Revised the error message to refer to a point rather than a line.
The source code for the answer below is also stored on Github: https://github.com/lawlist/lawlist-org-block-toggle/blob/master/lawlist-org-block-toggle.el
On a related issue (i.e., to completely hide the properties drawer including the word :PROPERTIES:), please refer to the following thread: Completely hide the :PROPERTIES: drawer in org-mode
On a semi-related issue (i.e., to create a custom block to be code-folded), see also: https://tex.stackexchange.com/a/161196/26911
This solution was tested with a fairly recent version of Emacs Trunk (built on January 19, 2014), which contains org-mode version 8.2.5c. Inasmuch as the :PROPERTIES: drawer through its :END: gets folded separately from the footnotes and the html blocks, this solution contemplates that the footnote and/or html code blocks will not be anywhere inside that properties drawer. The footnote can appear anywhere in the text paragraph, but cannot have another pair of square brackets inside the footnote -- since this code looks for the first ending square bracket in order to mark the end of the folded region. This code contemplates that #+BEGIN_HTML and #+END_HTML will both be flush-left with the left-hand margin. The startup views still work the same way -- e.g., the variables org-startup-folded and org-hide-block-startup.
The modification of org-cycle-internal-local enables tab cycling for all forms of folding in org-mode. All we did was fix the pagination of the function to make it more readable, and added the following condition: ((eq org-cycle-subtree-status 'subtree) (org-show-subtree) (message "ALL") (setq org-cycle-subtree-status 'all)). The interactive function org-cycle is still used to tab cycle between all of the various folded / unfolded views. The function lawlist-block-org-cycle-internal-local is a non-interactive supporting function that is used by org-cycle. The two defalias portions of the code in this solution are needed for everything to work properly. Rather than using tab cycling, the user can also call the interactive function directly at the beginning of the headings or subheadings with: M-x org-cycle RET
To toggle visibility of the footnote or html block directly, we use the interactive function lawlist-toggle-block-visibility. Place the cursor anywhere on the line containing the beginning of the footnote or, the beginning of the html block, and type: M-x lawlist-toggle-block-visibility RET
(require 'org)
(defalias 'org-cycle-hide-drawers 'lawlist-block-org-cycle-hide-drawers)
(defun lawlist-block-org-cycle-hide-drawers (state)
"Re-hide all drawers, footnotes or html blocks after a visibility state change."
(when
(and
(derived-mode-p 'org-mode)
(not (memq state '(overview folded contents))))
(save-excursion
(let* (
(globalp (memq state '(contents all)))
(beg (if globalp (point-min) (point)))
(end
(cond
(globalp
(point-max))
((eq state 'children)
(save-excursion (outline-next-heading) (point)))
(t (org-end-of-subtree t)) )))
(goto-char beg)
(while
(re-search-forward
".*\\[fn\\|^\\#\\+BEGIN_HTML.*$\\|^[ \t]*:PROPERTIES:[ \t]*$" end t)
(lawlist-org-flag t))))))
(defalias 'org-cycle-internal-local 'lawlist-block-org-cycle-internal-local)
(defun lawlist-block-org-cycle-internal-local ()
"Do the local cycling action."
(let ((goal-column 0) eoh eol eos has-children children-skipped struct)
(save-excursion
(if (org-at-item-p)
(progn
(beginning-of-line)
(setq struct (org-list-struct))
(setq eoh (point-at-eol))
(setq eos (org-list-get-item-end-before-blank (point) struct))
(setq has-children (org-list-has-child-p (point) struct)))
(org-back-to-heading)
(setq eoh (save-excursion (outline-end-of-heading) (point)))
(setq eos (save-excursion (1- (org-end-of-subtree t t))))
(setq has-children
(or
(save-excursion
(let ((level (funcall outline-level)))
(outline-next-heading)
(and
(org-at-heading-p t)
(> (funcall outline-level) level))))
(save-excursion
(org-list-search-forward (org-item-beginning-re) eos t)))))
(beginning-of-line 2)
(if (featurep 'xemacs)
(while
(and
(not (eobp))
(get-char-property (1- (point)) 'invisible))
(beginning-of-line 2))
(while
(and
(not (eobp))
(get-char-property (1- (point)) 'invisible))
(goto-char (next-single-char-property-change (point) 'invisible))
(and
(eolp)
(beginning-of-line 2))))
(setq eol (point)))
(cond
((= eos eoh)
(unless (org-before-first-heading-p)
(run-hook-with-args 'org-pre-cycle-hook 'empty))
(org-unlogged-message "EMPTY ENTRY")
(setq org-cycle-subtree-status nil)
(save-excursion
(goto-char eos)
(outline-next-heading)
(if (outline-invisible-p)
(org-flag-heading nil))))
((and
(or
(>= eol eos)
(not (string-match "\\S-" (buffer-substring eol eos))))
(or
has-children
(not (setq children-skipped
org-cycle-skip-children-state-if-no-children))))
(unless (org-before-first-heading-p)
(run-hook-with-args 'org-pre-cycle-hook 'children))
(if (org-at-item-p)
;; then
(org-list-set-item-visibility (point-at-bol) struct 'children)
;; else
(org-show-entry)
(org-with-limited-levels (show-children))
(when (eq org-cycle-include-plain-lists 'integrate)
(save-excursion
(org-back-to-heading)
(while (org-list-search-forward (org-item-beginning-re) eos t)
(beginning-of-line 1)
(let* (
(struct (org-list-struct))
(prevs (org-list-prevs-alist struct))
(end (org-list-get-bottom-point struct)))
(mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
(org-list-get-all-items (point) struct prevs))
(goto-char (if (< end eos) end eos)))))))
(org-unlogged-message "CHILDREN")
(save-excursion
(goto-char eos)
(outline-next-heading)
(if (outline-invisible-p)
(org-flag-heading nil)))
(setq org-cycle-subtree-status 'children)
(unless (org-before-first-heading-p)
(run-hook-with-args 'org-cycle-hook 'children)))
((or
children-skipped
(and
(eq last-command this-command)
(eq org-cycle-subtree-status 'children)))
(unless (org-before-first-heading-p)
(run-hook-with-args 'org-pre-cycle-hook 'subtree))
(outline-flag-region eoh eos nil)
(org-unlogged-message
(if children-skipped
"SUBTREE (NO CHILDREN)"
"SUBTREE"))
(setq org-cycle-subtree-status 'subtree)
(unless (org-before-first-heading-p)
(run-hook-with-args 'org-cycle-hook 'subtree)))
((eq org-cycle-subtree-status 'subtree)
(org-show-subtree)
(message "ALL")
(setq org-cycle-subtree-status 'all))
(t
(run-hook-with-args 'org-pre-cycle-hook 'folded)
(outline-flag-region eoh eos t)
(org-unlogged-message "FOLDED")
(setq org-cycle-subtree-status 'folded)
(unless (org-before-first-heading-p)
(run-hook-with-args 'org-cycle-hook 'folded))))))
(defun lawlist-org-flag (flag)
"When FLAG is non-nil, hide any of the following: html code block;
footnote; or, the properties drawer. Otherwise make it visible."
(save-excursion
(beginning-of-line 1)
(cond
((looking-at ".*\\[fn")
(let* (
(begin (match-end 0))
end-footnote)
(if (re-search-forward "\\]"
(save-excursion (outline-next-heading) (point)) t)
(progn
(setq end-footnote (point))
(outline-flag-region begin end-footnote flag))
(user-error "Error beginning at point %s." begin))))
((looking-at "^\\#\\+BEGIN_HTML.*$\\|^[ \t]*:PROPERTIES:[ \t]*$")
(let* ((begin (match-end 0)))
(if (re-search-forward "^\\#\\+END_HTML.*$\\|^[ \t]*:END:"
(save-excursion (outline-next-heading) (point)) t)
(outline-flag-region begin (point-at-eol) flag)
(user-error "Error beginning at point %s." begin)))))))
(defun lawlist-toggle-block-visibility ()
"For this function to work, the cursor must be on the same line as the regexp."
(interactive)
(if
(save-excursion
(beginning-of-line 1)
(looking-at
".*\\[fn\\|^\\#\\+BEGIN_HTML.*$\\|^[ \t]*:PROPERTIES:[ \t]*$"))
(lawlist-org-flag (not (get-char-property (match-end 0) 'invisible)))
(message "Sorry, you are not on a line containing the beginning regexp.")))

Emacs - mark the word forward and backward

Basically what I am asking is the equivalent function to vim's vb(bbww...) and vw(wwbb...):
I want to bind my meta-j and meta-k to mark the word before and after current point. Simple.el provided the mark-word function, which I bind to meta-k. And I changed the mark-word function a bit to:
(defun mark-backward (&optional arg allow-extend) ;
(interactive "P\np")
(cond ((and allow-extend
(or (and (eq last-command this-command) (mark t))
(and transient-mark-mode mark-active)))
(setq arg (if arg (prefix-numeric-value arg)
(if (< (mark) (point)) -1 1)))
(set-mark
(save-excursion
(goto-char (mark))
(forward-word arg)
(point))))
(t (push-mark
(save-excursion
(backward-word (prefix-numeric-value arg))
(point)) nil t))))
(global-set-key (kbd "M-k") 'mark-word)
(global-set-key (kbd "M-j") 'mark-backward)
This kinda worked. I want to undo some marking use the other key, how can I do that? (i.e. after I marked some word with M-k, I want to use M-j to unmark some word to left. Currently, when I hit M-j, emacs continue to mark forward).
(defun my-mark-word (N)
(interactive "p")
(if (and
(not (eq last-command this-command))
(not (eq last-command 'my-mark-word-backward)))
(set-mark (point)))
(forward-word N))
(defun my-mark-word-backward (N)
(interactive "p")
(if (and
(not (eq last-command this-command))
(not (eq last-command 'my-mark-word)))
(set-mark (point)))
(backward-word N))
(local-set-key (kbd "M-k") 'my-mark-word)
(local-set-key (kbd "M-j") 'my-mark-word-backward)
This should emulate VIMs behaviour (with other keystrokes, of course).
Remark: M-j is by default bound to indent-new-comment-line which is quite handy when writing commented blocks in source code. M-k is by default bound to kill-sentence.
You should replace forward-word with backward-word in one more place.
The code, however, still have problems selecting words to the left of the point.
Ps. Please edit your post -- the code posted is barely readable.

How to execute emacs grep-find link in the same window?

When I use grep-find it opens another window (area in the frame) with a list of results that I can select. When I select one it opens the target file in a different window than grep-find is in.
How can I get the target file to open in the same window as the grep results (replacing the grep results window with what I am actually looking for).
How can I keep grep-find from opening a separate window (have it so it opens in the current window). My goal is I look for something, I find it, I go to it, all within the same window. I would like to add this to my .emacs file.
It doesn't look like there is any way to configure the compile package to do what you're asking. And there's no easy way to use advice to tweak the behavior. I think you have to resort to editing the function which actually jumps to the error, which you can do with the following addition to your .emacs (tested in Emacs 23.1):
(eval-after-load "compile"
'(defun compilation-goto-locus (msg mk end-mk)
"Jump to an error corresponding to MSG at MK.
All arguments are markers. If END-MK is non-nil, mark is set there
and overlay is highlighted between MK and END-MK."
;; Show compilation buffer in other window, scrolled to this error.
(let* ((from-compilation-buffer (eq (window-buffer (selected-window))
(marker-buffer msg)))
;; Use an existing window if it is in a visible frame.
(pre-existing (get-buffer-window (marker-buffer msg) 0))
(w (if (and from-compilation-buffer pre-existing)
;; Calling display-buffer here may end up (partly) hiding
;; the error location if the two buffers are in two
;; different frames. So don't do it if it's not necessary.
pre-existing
(let ((display-buffer-reuse-frames t)
(pop-up-windows t))
;; Pop up a window.
(display-buffer (marker-buffer msg)))))
(highlight-regexp (with-current-buffer (marker-buffer msg)
;; also do this while we change buffer
(compilation-set-window w msg)
compilation-highlight-regexp)))
;; Ideally, the window-size should be passed to `display-buffer' (via
;; something like special-display-buffer) so it's only used when
;; creating a new window.
(unless pre-existing (compilation-set-window-height w))
(switch-to-buffer (marker-buffer mk))
;; was
;; (if from-compilation-buffer
;; ;; If the compilation buffer window was selected,
;; ;; keep the compilation buffer in this window;
;; ;; display the source in another window.
;; (let ((pop-up-windows t))
;; (pop-to-buffer (marker-buffer mk) 'other-window))
;; (if (window-dedicated-p (selected-window))
;; (pop-to-buffer (marker-buffer mk))
;; (switch-to-buffer (marker-buffer mk))))
;; If narrowing gets in the way of going to the right place, widen.
(unless (eq (goto-char mk) (point))
(widen)
(goto-char mk))
(if end-mk
(push-mark end-mk t)
(if mark-active (setq mark-active)))
;; If hideshow got in the way of
;; seeing the right place, open permanently.
(dolist (ov (overlays-at (point)))
(when (eq 'hs (overlay-get ov 'invisible))
(delete-overlay ov)
(goto-char mk)))
(when highlight-regexp
(if (timerp next-error-highlight-timer)
(cancel-timer next-error-highlight-timer))
(unless compilation-highlight-overlay
(setq compilation-highlight-overlay
(make-overlay (point-min) (point-min)))
(overlay-put compilation-highlight-overlay 'face 'next-error))
(with-current-buffer (marker-buffer mk)
(save-excursion
(if end-mk (goto-char end-mk) (end-of-line))
(let ((end (point)))
(if mk (goto-char mk) (beginning-of-line))
(if (and (stringp highlight-regexp)
(re-search-forward highlight-regexp end t))
(progn
(goto-char (match-beginning 0))
(move-overlay compilation-highlight-overlay
(match-beginning 0) (match-end 0)
(current-buffer)))
(move-overlay compilation-highlight-overlay
(point) end (current-buffer)))
(if (or (eq next-error-highlight t)
(numberp next-error-highlight))
;; We want highlighting: delete overlay on next input.
(add-hook 'pre-command-hook
'compilation-goto-locus-delete-o)
;; We don't want highlighting: delete overlay now.
(delete-overlay compilation-highlight-overlay))
;; We want highlighting for a limited time:
;; set up a timer to delete it.
(when (numberp next-error-highlight)
(setq next-error-highlight-timer
(run-at-time next-error-highlight nil
'compilation-goto-locus-delete-o)))))))
(when (and (eq next-error-highlight 'fringe-arrow))
;; We want a fringe arrow (instead of highlighting).
(setq next-error-overlay-arrow-position
(copy-marker (line-beginning-position)))))))
The eval-afer-load portion just ensures that you re-define it after Emacs defined it, so that your change takes hold.
You can add a binding (e.g. Alt-m) and do the following
(define-key grep-mode-map "\M-m" (lambda()
(interactive)
(compile-goto-error)
(delete-other-windows)
(kill-buffer "*grep*")))
I didn't find a way to replace the standard "Enter" / Mouse-click binding with a custom function
There is an another approach:
(defun eab/compile-goto-error ()
(interactive)
(let ((cwc (current-window-configuration)))
(funcall
`(lambda ()
(defun eab/compile-goto-error-internal ()
(let ((cb (current-buffer))
(p (point)))
(set-window-configuration ,cwc)
(switch-to-buffer cb)
(goto-char p ))))))
(compile-goto-error)
(run-with-timer 0.01 nil 'eab/compile-goto-error-internal))
I had the same question, and found this answer over at emacs.stackexchange https://emacs.stackexchange.com/a/33908/20000
(defun my-compile-goto-error-same-window ()
(interactive)
(let ((display-buffer-overriding-action
'((display-buffer-reuse-window
display-buffer-same-window)
(inhibit-same-window . nil))))
(call-interactively #'compile-goto-error)))
(defun my-compilation-mode-hook ()
(local-set-key (kbd "o") #'my-compile-goto-error-same-window))
(add-hook 'compilation-mode-hook #'my-compilation-mode-hook)
Pressing o in the *grep* buffer will open the location and file in the same frame.
I found this an elegant solution without deleting frames or too much lisp code and just hooking into compilation-mode-hook.

Move line/region up and down in emacs

What is the easiest way to move selected region or line (if there is no selection) up or down in emacs? I'm looking for the same functionality as is in eclipse (bounded to M-up, M-down).
Update: Install the move-text package from Marmalade or MELPA to get the following code.
Here's what I use, which works on both regions and individual lines:
(defun move-text-internal (arg)
(cond
((and mark-active transient-mark-mode)
(if (> (point) (mark))
(exchange-point-and-mark))
(let ((column (current-column))
(text (delete-and-extract-region (point) (mark))))
(forward-line arg)
(move-to-column column t)
(set-mark (point))
(insert text)
(exchange-point-and-mark)
(setq deactivate-mark nil)))
(t
(let ((column (current-column)))
(beginning-of-line)
(when (or (> arg 0) (not (bobp)))
(forward-line)
(when (or (< arg 0) (not (eobp)))
(transpose-lines arg)
(when (and (eval-when-compile
'(and (>= emacs-major-version 24)
(>= emacs-minor-version 3)))
(< arg 0))
(forward-line -1)))
(forward-line -1))
(move-to-column column t)))))
(defun move-text-down (arg)
"Move region (transient-mark-mode active) or current line
arg lines down."
(interactive "*p")
(move-text-internal arg))
(defun move-text-up (arg)
"Move region (transient-mark-mode active) or current line
arg lines up."
(interactive "*p")
(move-text-internal (- arg)))
(global-set-key [M-S-up] 'move-text-up)
(global-set-key [M-S-down] 'move-text-down)
A line can be moved using transpose-lines bound to C-x C-t. I don't know about regions, though.
I found this elisp snippet that does what you want, except you need to change the bindings.
(defun move-text-internal (arg)
(cond
((and mark-active transient-mark-mode)
(if (> (point) (mark))
(exchange-point-and-mark))
(let ((column (current-column))
(text (delete-and-extract-region (point) (mark))))
(forward-line arg)
(move-to-column column t)
(set-mark (point))
(insert text)
(exchange-point-and-mark)
(setq deactivate-mark nil)))
(t
(beginning-of-line)
(when (or (> arg 0) (not (bobp)))
(forward-line)
(when (or (< arg 0) (not (eobp)))
(transpose-lines arg))
(forward-line -1)))))
(defun move-text-down (arg)
"Move region (transient-mark-mode active) or current line
arg lines down."
(interactive "*p")
(move-text-internal arg))
(defun move-text-up (arg)
"Move region (transient-mark-mode active) or current line
arg lines up."
(interactive "*p")
(move-text-internal (- arg)))
(global-set-key [\M-\S-up] 'move-text-up)
(global-set-key [\M-\S-down] 'move-text-down)
You should try drag-stuff !
It works exactly like eclipse Alt+Up/Down for single lines, as well as for selected region lines!
In addition to that it allows you to move words with Alt+Left/Right
This is exactly what you're looking for! And it is even available from the ELPA repos!
Other solutions never worked for me. Some of them were buggy(transposing lines while changing their order, wtf?) and some of them were moving exactly selected region, leaving unselected parts of the lines on their positions. But drag-stuff works exactly like in eclipse!
And even more! You can try selecting a region and using Alt+Left/Right ! This will transpose selected region by one character to the left or right. Amazing!
To enable it globally simply run this:
(drag-stuff-global-mode)
I have written a couple of interactive functions for moving lines up/down:
;; move line up
(defun move-line-up ()
(interactive)
(transpose-lines 1)
(previous-line 2))
(global-set-key [(control shift up)] 'move-line-up)
;; move line down
(defun move-line-down ()
(interactive)
(next-line 1)
(transpose-lines 1)
(previous-line 1))
(global-set-key [(control shift down)] 'move-line-down)
The keybindings are IntelliJ IDEA style, but you can use anything you want. I should probably implement some functions that operate on regions as well.
Here is my snippet to move the current line or the lines spanned by the active region. It respects cursor position and highlighted region. And it won't break lines when the region doesn't begin/end at line border(s). (It is inspired by eclipse; I found the eclipse way more convenient than 'transpose-lines'.)
;; move the line(s) spanned by the active region up/down (line transposing)
;; {{{
(defun move-lines (n)
(let ((beg) (end) (keep))
(if mark-active
(save-excursion
(setq keep t)
(setq beg (region-beginning)
end (region-end))
(goto-char beg)
(setq beg (line-beginning-position))
(goto-char end)
(setq end (line-beginning-position 2)))
(setq beg (line-beginning-position)
end (line-beginning-position 2)))
(let ((offset (if (and (mark t)
(and (>= (mark t) beg)
(< (mark t) end)))
(- (point) (mark t))))
(rewind (- end (point))))
(goto-char (if (< n 0) beg end))
(forward-line n)
(insert (delete-and-extract-region beg end))
(backward-char rewind)
(if offset (set-mark (- (point) offset))))
(if keep
(setq mark-active t
deactivate-mark nil))))
(defun move-lines-up (n)
"move the line(s) spanned by the active region up by N lines."
(interactive "*p")
(move-lines (- (or n 1))))
(defun move-lines-down (n)
"move the line(s) spanned by the active region down by N lines."
(interactive "*p")
(move-lines (or n 1)))
There is an entry in the emacs wiki just for this:
http://www.emacswiki.org/emacs/MoveLine
For moving regions:
http://www.emacswiki.org/emacs/MoveRegion
There's no built-in. You can use transpose-lines (C-x C-t) but you cannot use it repeatedly. Look at the functions on http://www.schuerig.de/michael/blog/index.php/2009/01/16/line-movement-for-emacs/.
It should be easy to adapt that to regions, too.
The transpose-paragraph function could help you.
You might also want to have a look to the transpose section in the Emacs manual.
Essentially:
C-t
Transpose two characters (transpose-chars).
M-t
Transpose two words (transpose-words).
C-M-t
Transpose two balanced expressions (transpose-sexps).
C-x C-t
Transpose two lines (transpose-lines).
I use the smart-shift package (in Melpa) for this. By default it rebinds C-C <arrow> to move a line or region. It moves horizontally by a major-mode-specific amount (e.g. c-basic-offset or python-indent-offset). Works on regions also.
;; binds C-C <arrows>
(when (require 'smart-shift nil 'noerror)
(global-smart-shift-mode 1))