emacs - working with lines
Emacs keep or remove lines matching regex
You can use keep-lines
to get what you want, copy them, and then undo.
For the opposite, there is also flush-lines
to get rid of lines you don’t want.
Joining lines in emacs
How to join lines into one in emacs?
There are several ways to do this.
-
~Meta ^~
Either visually select and call Meta ^ to join the visually selected lines. Or place the point anywhere on the last line of the group of lines that need joining and call Meta ^ repeatedly until all the lines are merged. It leaves one space between all of the now joined lines.
-
~Meta join-line~
: This will join two lines. Bind it to a convenient keystroke. -
Select paragraph/lines by
~Meta h~
or~Ctrl SPC~
. Press~Meta q~
-
Multiple Cursors combined with
~Meta ^~
will collapse all selected lines into one with all extraneous white-space removed.For example to select an entire buffer, invoke multiple cursors mode, collapse into one line, and then disable multiple cursors mode:
C-x h M-x mc/edit-lines M-^ C-g
Sorting lines alphabetically
Imagine you’re working in emacs. You come across this code:
gem 'clearance', '1.0.0.rc4'
gem 'neat'
gem 'stripe'
gem 'pg'
gem 'thin'
gem 'rails', '3.2.11'
gem 'bourbon'
gem 'simple_form'
gem 'strong_parameters'
If you want to sort the list alphabetically, select the lines visually and run: M-x sort-lines
That will result in this:
gem 'bourbon'
gem 'clearance', '1.0.0.rc4'
gem 'neat'
gem 'pg'
gem 'rails', '3.2.11'
gem 'simple_form'
gem 'stripe'
gem 'strong_parameters'
gem 'thin'
Delete duplicate lines
M-x delete-duplicate-lines
- this works on a region, not a buffer, so select the desired text first
- it maintains the relative order of the originals, killing the duplicates
Delete empty lines
To do it in a region or on the whole buffer.
M-x flush-lines (delete lines containing matches for REGEXP)
For regex for empty lines, enter this: ^$
^
represents the beginning text of the line
$
represents the ending text of the line
Clean up empty lines specifically where you want it but not on a region or not on the whole buffer
C-x C-o