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.
defun top-join-line ()
("Join the current line with the line beneath it."
(interactive)1))
(delete-indentation "C-^") 'top-join-line) -- add keybinding (global-set-key (kbd
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
defun join-region (beg end)
("Apply join-line over region."
"r")
(interactive if mark-active
(let ((beg (region-beginning))
(
(end (copy-marker (region-end))))
(goto-char beg)< (point) end)
(while (1)))))
(join-line "C-S-^") 'join-region) -- add keybinding (global-set-key (kbd
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:
C-x ( --start defining keyboard macro
M-h -- select paragraph
M-x join-region
M-}
C-n
C-x ) --end defining keyboard macro0 C-x e -- repeat the macro until end of file C-u