Join multiple lines in Emacs

Posted on May 3, 2020 by Abhinav

Last weekend my wife came up to me and asked if there was a way to join lines of a paragraph in a poorly formated text file.

The text file looked something like this:

1. this is a 
really 
poorly formatted 
paragraph. 


2. the shitty formating 
continues on 
like this for the rest
of this document. Spanning over
several paragraphs.

...
...

Sure enough that was an easy task in Vim, Select the paragraph using Shift+v, press } to select till end of that paragraph and press j voila all the lines in selected region gets joined. Use the dot command to repeat it for the entire file.

But since I am now learning and getting deep into Emacs land(while I am still improving my vim skills). I wanted to see if this was as easily achiveable in Emacs as well. Well, obviously Emacs has the functionality to join lines using M-^ but you had to do it slightly differently.

Let me try to explain:

line 1 
line 2 
line 3 

To join line 1 to line 2 my brain is trained in such a way(because of vim maybe) that you would run the join command on line 1 and it would combine it with line 2 (join current line with next line) But in Emacs to join line 1 and line 2 you would have to be on line 2 and press M-^ to get line 1 line 2 as output(join current line with previous line).

The fun thing with Emacs and also the reason why many Emacs user love it is, it is easy enough to change/program the behavior of anything in emacs to your liking(La power of Elisp).

I found a snippet online1 that does exactly what I wanted, joinig current line with next line as opposed to the original behavior of joinig current line with previous line.

The above snippet works fine for just few lines but it doesn’t work when a region is selected is selected for which you need

Coming back to the problem in hand, joining all the lines in the paragraphs. I created a macro in Emacs to select paragraph, run the join-region function, move to the next line. And ran the macro for the entire file.

Which translates into something like this in Emacs Land:


  1. Emacsredux