user797257
user797257

Reputation:

M-x align-regexp removes text?

Here's an example text I'm trying to format:

(9 12 19 38 0 -39 -20 -13 -10)
(7 9 14 29 0 -30 -15 -10 -8)
(4 6 9 19 0 -20 -10 -7 -5)
(2 3 4 9 0 -10 -5 -4 -3)
(0 0 0 0 0 0 0 0 0)
(-3 -4 -5 -10 0 9 4 3 2)
(-5 -7 -10 -20 0 19 9 6 4)
(-8 -10 -15 -30 0 29 14 9 7)
(-10 -13 -20 -39 0 38 19 12 9)

I would like each column to align on digits, (i.e. if there's a minus sign, add extra space).

If I do it like so: C-uM-xalign-regexpRET\([[:digit:]]+\)RETRETRETy

I get this:

(9  12 19 38 0 -3 -2 -1 -1)
(7  9  14 29 0 -3 -1 -1 -8)
(4  6  9  19 0 -2 -1 -7 -5)
(2  3  4  9  0 -1 -5 -4 -3)
(0  0  0  0  0 0  0  0  0 )
(-3 -4 -5 -1 0 9  4  3  2 )
(-5 -7 -1 -2 0 19 9  6  4 )
(-8 -1 -1 -3 0 29 14 9  7 )
(-1 -1 -2 -3 0 38 19 12 9 )

which is very close, but not what I want.

And if I try to modify the expression to include the minus sign, like so: \(-?[[:digit:]]+\)

Then I get this:

(9 1 1 3 0 - - - -)
(7 9 1 2 0 - - - -)
(4 6 9 1 0 - - - -)
(2 3 4 9 0 - - - -)
(0 0 0 0 0 0 0 0 0)
(- - - - 0 9 4 3 2)
(- - - - 0 1 9 6 4)
(- - - - 0 2 1 9 7)
(- - - - 0 3 1 1 9)

Is this a bug, or is there something I don't know?

Upvotes: 5

Views: 129

Answers (1)

Sean
Sean

Reputation: 29790

The text matched by the designated group (usually group 1) is expanded or shrunk, so non-whitespace characters in the group are subject to deletion, as you saw. Unless, that is, justification is enabled, which is indicated by supplying a negative group number to align-regexp:

C-uM-xalign-regexpRET\(\s-*-?\)[0-9]+RET-1RETRETy

If you want, you can align the columns on the ones digits of each number by including the digits in the match group:

C-uM-xalign-regexpRET\(\s-*-?[0-9]+\)RET-1RETRETy

In either case, an extra space will be inserted after each opening parenthesis. I don't see any way to keep align-regexp from doing this, but if you do it often you could wrap it in a command that does the align-regexp, then replaces the regexp "^( " with "(" everywhere in the original region.

Upvotes: 3

Related Questions