How to remove all newlines from selected region in Emacs?
EmacsReplaceNewlineEmacs Problem Overview
How to remove all newlines from selected region in Emacs?
Emacs Solutions
Solution 1 - Emacs
M-x replace-string
C-q C-j
RET
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.