By Emacs, how to join two lines into one?

Viewed 24923

I am new to Emacs. I have googled this but no good answer there. One of them is Ctrl-n Ctrl-a Backspace This works but is stupid. Is there a quick and simple way to join a block of lines into a single line?

Actually, I can use Esc-q to auto-fill a paragraph now, but how could I get it to revert without UNDO?

15 Answers

Place point anywhere on the last line of the group of lines that need joining and call

M-^

repeatedly until all the lines are merged.

Note: It leaves one space between all of the now joined lines.

M-x join-line will join two lines. Just bind it to a convenient keystroke.

Just replace newlines with nothing.

You could define a new command for this, temporarily adjusting the fill width before using the the Esc-q command:

;; -- define a new command to join multiple lines together --
(defun join-lines () (interactive)
 (setq fill-column 100000)
 (fill-paragraph nil)
 (setq fill-column 78)
)

Obviously this only works, if your paragraph has less than 100000 characters.

Because join-line will left one space between two lines, also it only support join two lines. In case of you want to join plenty of lines without one space left, you can use "search-replace" mode to solve, as follows:

  1. C-%
  2. Query: input C-q C-j Enter
  3. Replace: Enter
  4. Run the replacement. Enter

Done.

Two ways come to mind:

  1. Once you think of it, the most obvious (or at least easiest to remember) way is to use M-q format-paragraph with a long line length C-x-f 1000.

  2. There is also a built-in tool M-^ join-line. More usefully, if you select a region then it will combine them all into one line.

A basic join of 2 lines:

(delete-indentation)

I like to line below to be joined to the current without moving the cursor:

("C-j" .
  (lambda (iPoint)
    "Join next line onto current line"
    (interactive "d")
    (next-line)
    (delete-indentation)
    (goto-char iPoint)))

This one behaves like in vscode. So it add space only if join line consisted something else than whitespace. And I bind it to alt+shift+j.

Shorter version based on crux-top-join-line:

(global-set-key (kbd "M-J") (lambda () (interactive) (delete-indentation 1)))

Longer version based on https://stackoverflow.com/a/33005183/588759.

;; https://stackoverflow.com/questions/1072662/by-emacs-how-to-join-two-lines-into-one/68685485#68685485
(defun join-lines ()
  (interactive)
  (next-line)
  (join-line)
  (delete-horizontal-space)
  (unless (looking-at-p "\n") (insert " ")))

(global-set-key (kbd "M-J") 'join-lines)
Related