How to remove all newlines from selected region in Emacs?

  1. M-x replace-string
  2. C-q C-j
  3. RET
  4. RET

The trick is to quote the C-j with C-q, but otherwise replacing newlines is like replacing anything else.


With my key bindings, which I think are standard, on windows:

Select region

shift-alt-%

ctrl-Q ctrl-J

return

return

!

Or to put it another way, query replace region, ctrl-q to get extended characters, ctrl-j to put in a newline, replace with nothing, all of them.


If you want to create a function to do this (and bind it to F8) you could try:

(defun remove-newlines-in-region ()
  "Removes all newlines in the region."
  (interactive)
  (save-restriction
    (narrow-to-region (point) (mark))
    (goto-char (point-min))
    (while (search-forward "\n" nil t) (replace-match "" nil t))))

(global-set-key [f8] 'remove-newlines-in-region)

That's based on an example I that I found here.