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: Seweryn Kokot
Subject: Re: How modify numbers in a region by a multiplier?
Date: Thu, 1 Jul 2010 20:36:05 +0000 (UTC)
User-agent: Loom/3.14 (http://gmane.org/)

Juanma Barranquero <lekktu <at> gmail.com> writes:

> Qiang Guo is right, though, in pointing that you're using a fixed
> `end' but the buffer or region length is potentially changing with
> every replace.

Is there a canonical solution to this problem, since it seems that it should
happen frequently when using the following structure: 
(while (re-search-forward "\\([0-9.]+\\)" end t)
(replace-match (format "%.2f" (* (string-to-number (match-string 1))
multiplier))))

I tried this in a buffer with just "1 4 5 5 4 5 4" and specifying 
the multiplier of 0.001 gives
Debugger entered--Lisp error: (error "Invalid search 
bound (wrong side of point)")
  re-search-forward("\\([0-9.]+\\)" 14 t) ...

or modifies only a part of the buffer if the content of 
the buffer is "1 4 5 5 4 5 4 " (just adding one space). 
Then using my function gives

0.00 0.00 0.01 5 4 5 4 

P.S. The function now is as follows:

(defun my-multiply-numbers-in-region-or-buffer (multiplier)
  (interactive "nSpecify a multiplier (default is 0.001): ")
;; if nil - RET multiplier is 0.001
  (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)))
        (unless multiplier
          (setq multiplier 0.001))
        (goto-char beg)
        (while (re-search-forward "\\([0-9.]+\\)" end t)
          (replace-match (format "%.2f" (* (string-to-number (match-string 1))
multiplier))))
        (message "Numbers in %s modified by multiplier %s." object multiplier)))




reply via email to

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