help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How modify numbers in a region by a multiplier?


From: Marc Mientki
Subject: Re: How modify numbers in a region by a multiplier?
Date: Wed, 08 Dec 2010 15:16:46 -0000
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.10) Gecko/20100512 Thunderbird/3.0.5

Am 01.07.2010 15:55, schrieb Seweryn Kokot:
> Hi,
>
> I would like to modify numbers in a region/buffer by a given multiplier.
>
> Imagine that I have some numbers
>
> 33.444 3333 4433.4443 3344 .34234
>
> and I want them multiplied for example by 0.1
>
> to receive
>
> 3.3444 333.3 443.34443 334.4 .034234
>
> I tried with this function I wrote, but it doesn't work properly.
> Any idea why?
>
> (defun my-multiply-numbers-in-region-or-buffer (multiplier)
>    (interactive "nGive multiplier: ")
>    (let (beg end object)
>    (if (use-region-p)
>          (progn
>            (setq object "region")
>            (setq beg (region-beginning))
>            (setq end (region-end)))
>        (setq object "buffer")
>        (setq beg (point-min))
>        (setq end (point-max)))
>    (goto-char beg)
>    (while (re-search-forward "\\([0-9]*\\.?[0-9]*\\)" end t)
>      (replace-match (format "%.3f" (* (string-to-number (match-string 1))
> multiplier))))
>    (message "Numbers in %s modified by multiplier %s." object
> multiplier)))
>
>

I use for such purposes macro-math.el from Nikolaj Schumacher
(http://nschum.de/src/emacs/macro-math/) and bind so:

(global-set-key "\C-x~" 'macro-math-eval-and-round-region)
(global-set-key "\C-x=" 'macro-math-eval-region)

The next step is to write macro where you search begin of the numer and
set there mark at this position, then go to the end of the number (don't
worry that mark disapear - it is still there) and type mathematical
operation - in your case *0.1 - and call macro-math-eval-region with
C-x= which replace all marked text (original number and '*0.1') with the
results of the operation. When you don't wish to replace text call
macro-math-eval-region with C-u prefix. In this case the result will be
written to kill-ring and yiu can yank it on other place.

This is a very simple example of macro for your task:
(fset 'mult-by-0.1
   [?\C-  ?\C-s ?  ?\C-m left ?* ?0 ?. ?1 ?\C-x ?= ?\C-f])


HTH
regards
Marc





reply via email to

[Prev in Thread] Current Thread [Next in Thread]