Skip to content

Instantly share code, notes, and snippets.

@myegorov
Created March 19, 2019 06:00
Show Gist options
  • Save myegorov/7c2521ea993985e1499c0390646886f5 to your computer and use it in GitHub Desktop.
Save myegorov/7c2521ea993985e1499c0390646886f5 to your computer and use it in GitHub Desktop.
edit start-middle-end of line

Editing at line start - middle - end

We frequently need to edit the beginning or end of a line. The text may also be arranged in columns. We can then resort to keyboard macros, but there's a less laborious approach.

Suppose we're editing this excerpt:

foo = 1
bar = 'a'
foobar = foo + bar

Insert at line start

First let's prepend const using Emacs' rectangular (column) editing.

  1. put cursor before foo and set mark with C-<SPC> (or use rectangular mark with C-x <SPC>).
  2. put cursor before foobar
  3. C-x r t const<space> <RET>
const foo = 1
const bar = 'a'
const foobar = foo + bar

A special case. To prepend a column of numbers, select the region and C-x r N (followed by inserting a column of dots).

1. list item
2. list item
3. list item

Swap columns

  1. We first delete a column of text with C-x r k.
  2. We then paste the column at point with C-x r y.

From

| Tables   |      Are      |  Cool |
|----------|:-------------:|------:|
| col 1 is |  left-aligned | $1600 |
| col 2 is |    centered   |   $12 |
| col 3 is | right-aligned |    $1 |

to

| Tables   |   Cool |     Are      |
|----------|:------:|-------------:|
| col 1 is |  $1600 | left-aligned |
| col 2 is |    $12 |   centered   |
| col 3 is |     $1 |right-aligned |

Align text into columns

  1. Align on whitespace: C-u M-x align
lastname	firstname	
Smith		John		33-88
Gere		Alan		24-23
Verne		Bill		12-34
  1. Align on an arbitrary regexp: M-x align-regexp <regexp>
x match {
  case 0	=> "zero"
  case 11	=> "eleven"
  case _	=> "unknown"
}

Append to end of line

This is a more general case, since the text may not be neatly aligned in columns.

Select the region, then search/replace end of line regexp with M-x replace-regexp <RET> $ <RET> <string>

const foo		= 1;
const bar		= 'a';
const foobar	= foo + bar;

Use query-replace-regexp (C-M-%) for interactive search and replace .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment