Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inbuffer emacs calculation

Tags:

emacs

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

like image 556
iobelix Avatar asked Jan 21 '23 16:01

iobelix


1 Answers

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.

like image 66
Nietzche-jou Avatar answered Jan 29 '23 16:01

Nietzche-jou