How to remove all newlines from selected region in Emacs?

EmacsReplaceNewline

Emacs Problem Overview


How to remove all newlines from selected region in Emacs?

Emacs Solutions


Solution 1 - 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.

Solution 2 - Emacs

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.

Solution 3 - Emacs

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.

Solution 4 - Emacs

You might also consider the old standby delete-blank-lines, typically bound to C-x C-o.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSławoszView Question on Stackoverflow
Solution 1 - EmacsBruce StephensView Answer on Stackoverflow
Solution 2 - EmacsPete View Answer on Stackoverflow
Solution 3 - EmacsMark LongairView Answer on Stackoverflow
Solution 4 - EmacsJoseph GayView Answer on Stackoverflow