www.delorie.com/gnu/docs/calc/calc_354.html   search  
Buy the book!

GNU Emacs Calc 2.02 Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Example

Here is a sample Emacs command that uses calc-eval. Suppose you have a document with lots of references to temperatures on the Fahrenheit scale, say "98.6 F", and you wish to convert these references to Centigrade. The following command does this conversion. Place the Emacs cursor right after the letter "F" and invoke the command to change "98.6 F" to "37 C". Or, if the temperature is already in Centigrade form, the command changes it back to Fahrenheit.

(defun convert-temp ()
    (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
    (let* ((top1 (match-beginning 1))
           (bot1 (match-end 1))
           (number (buffer-substring top1 bot1))
           (top2 (match-beginning 2))
           (bot2 (match-end 2))
           (type (buffer-substring top2 bot2)))
      (if (equal type "F")
          (setq type "C"
                number (calc-eval "($ - 32)*5/9" nil number))
        (setq type "F"
              number (calc-eval "$*9/5 + 32" nil number)))
      (goto-char top2)
      (delete-region top2 bot2)
      (insert-before-markers type)
      (goto-char top1)
      (delete-region top1 bot1)
      (if (string-match "\\.$" number)   ; change "37." to "37"
          (setq number (substring number 0 -1)))
      (insert number))))

Note the use of insert-before-markers when changing between "F" and "C", so that the character winds up before the cursor instead of after it.

  webmaster   donations   bookstore     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003