tags:

views:

96

answers:

1

Is it possible to do inbuffer calculation in emacs.

For example, if my file has the following numbers

10
11
12

(A) I would like to convert these numbers to hex (either in place or paste it next to that),

10 A
11 B
12 C

(B) I would like to sum those numbers.

10
11
12

33

(C) I would like to increment the count (sth like an index)

10
11
12
13
14

+6  A: 

You can use the inbuilt calculator and/or the fact that \, in the replacement string for commands like replace-regexp will evaluate an arbitrary elisp expression.

More-or-less of the top of my head you can do:

A.

  1. Mark the region containing the numbers.
  2. Execute M-x replace-regexp
    • For the matching regexp, use \([[:digit:]]+\).
    • For the replacement, use \,(format "%X" (string-to-number \1)).

B.

  1. Mark the region containing the numbers.
  2. Type C-x * g.
  3. Type V R +.
  4. Type y to insert the sum, or C-u y to replace.

C.

Same as for A, but mark just the last number, and use a replacement function of \,(format "%s\n%d" \1 (1+ (string-to-number \1))).

You can put these in macros or functions which take care of moving point around to the right place.

Cirno de Bergerac
Good Answer. Need upcase "G" for grabbing region: "C-x * G"
Jürgen Hötzel
case doesn't matter for calc commands.
Cirno de Bergerac
No need for (format "%s\n%d" \1 (1+ (string-to-number \1))), a short (+ x \#1) would do the job as "#1" automatically converts the match into a number
polyglot