1

I'd like to take a buffer which looks like this:

one


two
three

four


five

And turn it into this

one

two
three

four

five

I've tried using delete-blank-line, however, it will only effect the area around the cursor, and I'd like to do the whole buffer (or at least the whole region). I've also tried various permutation of replace-regexp but I have not been able to find a regexp that works.

1
  • You might want to specify whether the "blank" lines can have whitespace chars, and if so, which ones.
    – Drew
    Aug 11 '20 at 17:53
1

Have you tried

(replace-regexp "^\n+" "\n")

Replace any number of blank lines with one blank line. This works regardless of the end-of-line style (Unix,DOS,Mac).

Interactively, you can do the same by entering the newlines as literal newline characters, i.e.

M-x query-replace-regexp ^C-qC-jC-qC-jRETC-jRET
0

Tried lots of solutions and none worked for me. After much trials and errors this is what worked for me (GNU Emacs 27.1 (build 1, x86_64-w64-mingw32) of 2020-08-22).

The idea is to match all blank lines that may or may not contain spaces at once (many solutions only match one blank line for each match), and then replace them with just one blank line. To match these blank lines use the pattern \(^ *^J\)+ where ^J is the newline character and it should be entered with quoted-insert, i.e., C-q C-j. The actual input sequence would be this:

M-x query-replace-regex RET ^ \ ( ^ SPC * C-q C-j \ ) + RET C-q C-j

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.