calc-embed.el 49.3 KB
Newer Older
1 2
;;; calc-embed.el --- embed Calc in a buffer

Jay Belanger's avatar
Jay Belanger committed
3
;; Copyright (C) 1990, 1991, 1992, 1993, 2001, 2002, 2003, 2004,
Glenn Morris's avatar
Glenn Morris committed
4
;;   2005, 2006, 2007 Free Software Foundation, Inc.
5 6

;; Author: David Gillespie <daveg@synaptics.com>
Jay Belanger's avatar
Jay Belanger committed
7
;; Maintainer: Jay Belanger <jay.p.belanger@gmail.com>
Eli Zaretskii's avatar
Eli Zaretskii committed
8 9 10

;; This file is part of GNU Emacs.

11 12 13 14 15
;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

Eli Zaretskii's avatar
Eli Zaretskii committed
16
;; GNU Emacs is distributed in the hope that it will be useful,
17 18 19 20 21 22 23 24
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
Eli Zaretskii's avatar
Eli Zaretskii committed
25

26
;;; Commentary:
Eli Zaretskii's avatar
Eli Zaretskii committed
27

28
;;; Code:
Eli Zaretskii's avatar
Eli Zaretskii committed
29 30 31

;; This file is autoloaded from calc-ext.el.

Jay Belanger's avatar
Jay Belanger committed
32
(require 'calc-ext)
Eli Zaretskii's avatar
Eli Zaretskii committed
33 34 35 36 37 38 39
(require 'calc-macs)

(defun calc-show-plain (n)
  (interactive "P")
  (calc-wrapper
   (calc-set-command-flag 'renum-stack)
   (message (if (calc-change-mode 'calc-show-plain n nil t)
40 41
		"Including \"plain\" formulas in Calc Embedded mode"
	      "Omitting \"plain\" formulas in Calc Embedded mode"))))
Eli Zaretskii's avatar
Eli Zaretskii committed
42 43 44 45 46


(defvar calc-embedded-modes nil)
(defvar calc-embedded-globals nil)
(defvar calc-embedded-active nil)
47
(defvar calc-embedded-all-active nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
48
(make-variable-buffer-local 'calc-embedded-all-active)
49
(defvar calc-embedded-some-active nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
50 51
(make-variable-buffer-local 'calc-embedded-some-active)

Jay Belanger's avatar
Jay Belanger committed
52 53 54 55 56 57 58 59 60 61 62 63
;; The following variables are customizable and defined in calc.el.
(defvar calc-embedded-announce-formula)
(defvar calc-embedded-open-formula)
(defvar calc-embedded-close-formula)
(defvar calc-embedded-open-word)
(defvar calc-embedded-close-word)
(defvar calc-embedded-open-plain)
(defvar calc-embedded-close-plain)
(defvar calc-embedded-open-new-formula)
(defvar calc-embedded-close-new-formula)
(defvar calc-embedded-open-mode)
(defvar calc-embedded-close-mode)
Eli Zaretskii's avatar
Eli Zaretskii committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

(defconst calc-embedded-mode-vars '(("precision" . calc-internal-prec)
				    ("word-size" . calc-word-size)
				    ("angles" . calc-angle-mode)
				    ("symbolic" . calc-symbolic-mode)
				    ("matrix" . calc-matrix-mode)
				    ("fractions" . calc-prefer-frac)
				    ("complex" . calc-complex-mode)
				    ("simplify" . calc-simplify-mode)
				    ("language" . the-language)
				    ("plain" . calc-show-plain)
				    ("break" . calc-line-breaking)
				    ("justify" . the-display-just)
				    ("left-label" . calc-left-label)
				    ("right-label" . calc-right-label)
				    ("radix" . calc-number-radix)
				    ("leading-zeros" . calc-leading-zeros)
				    ("grouping" . calc-group-digits)
				    ("group-char" . calc-group-char)
				    ("point-char" . calc-point-char)
				    ("frac-format" . calc-frac-format)
				    ("float-format" . calc-float-format)
				    ("complex-format" . calc-complex-format)
				    ("hms-format" . calc-hms-format)
				    ("date-format" . calc-date-format)
				    ("matrix-justify" . calc-matrix-just)
				    ("full-vectors" . calc-full-vectors)
				    ("break-vectors" . calc-break-vectors)
				    ("vector-commas" . calc-vector-commas)
				    ("vector-brackets" . calc-vector-brackets)
				    ("matrix-brackets" . calc-matrix-brackets)
				    ("strings" . calc-display-strings)
))


;;; Format of calc-embedded-info vector:
;;;    0   Editing buffer.
;;;    1   Calculator buffer.
;;;    2   Top of current formula (marker).
;;;    3   Bottom of current formula (marker).
;;;    4   Top of current formula's delimiters (marker).
;;;    5   Bottom of current formula's delimiters (marker).
;;;    6   String representation of current formula.
;;;    7   Non-nil if formula is embedded within a single line.
;;;    8   Internal representation of current formula.
;;;    9   Variable assigned by this formula, or nil.
;;;   10   List of variables upon which this formula depends.
;;;   11   Evaluated value of the formula, or nil.
;;;   12   Mode settings for current formula.
;;;   13   Local mode settings for current formula.
;;;   14   Permanent mode settings for current formula.
;;;   15   Global mode settings for editing buffer.


;;; calc-embedded-active is an a-list keyed on buffers; each cdr is a
;;; sorted list of calc-embedded-infos in that buffer.  We do this
;;; rather than using buffer-local variables because the latter are
;;; thrown away when a buffer changes major modes.

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
(defvar calc-embedded-original-modes nil
  "The mode settings for Calc buffer when put in embedded mode.")

(defun calc-embedded-save-original-modes ()
  "Save the current Calc modes when entereding embedded mode."
  (let ((calcbuf (save-excursion
                   (calc-create-buffer)
                   (current-buffer)))
        lang modes)
    (if calcbuf
        (with-current-buffer calcbuf
          (setq lang
                (cons calc-language calc-language-option))
          (setq modes
                (list (cons 'calc-display-just
                            calc-display-just)
                      (cons 'calc-display-origin
                            calc-display-origin)))
          (let ((v calc-embedded-mode-vars))
            (while v
              (let ((var (cdr (car v))))
                (unless (memq var '(the-language the-display-just))
                  (setq modes
                        (cons (cons var (symbol-value var)) 
                              modes))))
              (setq v (cdr v))))
          (setq calc-embedded-original-modes (cons lang modes)))
      (setq calc-embedded-original-modes nil))))

152 153 154 155 156 157 158 159 160
(defun calc-embedded-preserve-modes ()
  "Preserve the current modes when leaving embedded mode."
  (interactive)
  (if calc-embedded-info
      (progn
        (calc-embedded-save-original-modes)
        (message "Current modes will be preserved when leaving embedded mode."))
    (message "Not in embedded mode.")))

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
(defun calc-embedded-restore-original-modes ()
  "Restore the original Calc modes when leaving embedded mode."
  (let ((calcbuf (get-buffer "*Calculator*"))
        (changed nil)
        (lang (car calc-embedded-original-modes))
        (modes (cdr calc-embedded-original-modes)))
    (if (and calcbuf calc-embedded-original-modes)
        (with-current-buffer calcbuf
          (unless (and
                   (equal calc-language (car lang))
                   (equal calc-language-option (cdr lang)))
            (calc-set-language (car lang) (cdr lang))
            (setq changed t))
          (while modes
            (let ((mode (car modes)))
              (unless (equal (symbol-value (car mode)) (cdr mode))
                (set (car mode) (cdr mode))
                (setq changed t)))
            (setq modes (cdr modes)))
          (when changed
            (calc-refresh)
            (calc-set-mode-line))))
    (setq calc-embedded-original-modes nil)))

185 186 187 188 189 190 191 192 193 194
;; The variables calc-embed-outer-top, calc-embed-outer-bot, 
;; calc-embed-top and calc-embed-bot are
;; local to calc-do-embedded, calc-embedded-mark-formula,
;; calc-embedded-duplicate, calc-embedded-new-formula and
;; calc-embedded-make-info, but are used by calc-embedded-find-bounds,
;; which is called (directly or indirectly) by the above functions.
(defvar calc-embed-outer-top)
(defvar calc-embed-outer-bot)
(defvar calc-embed-top)
(defvar calc-embed-bot)
Eli Zaretskii's avatar
Eli Zaretskii committed
195

Jay Belanger's avatar
Jay Belanger committed
196 197 198 199 200 201 202
;; The variable calc-embed-arg is local to calc-do-embedded,
;; calc-embedded-update-formula, calc-embedded-edit and
;; calc-do-embedded-activate, but is used by 
;; calc-embedded-make-info, which is called by the above
;; functions.
(defvar calc-embed-arg)

203
(defvar calc-embedded-quiet nil)
204 205 206 207 208

(defvar calc-embedded-firsttime)
(defvar calc-embedded-firsttime-buf)
(defvar calc-embedded-firsttime-formula)

209 210 211 212 213 214 215 216 217 218 219 220
;; The following is to take care of any minor modes which override
;; a Calc command.
(defvar calc-override-minor-modes-map 
  (make-sparse-keymap)
  "A list of keybindings that might be overwritten by minor modes.")

;; Add any keys that might be overwritten here.
(define-key calc-override-minor-modes-map "`" 'calc-edit)

(defvar calc-override-minor-modes 
  (cons t calc-override-minor-modes-map))

Jay Belanger's avatar
Jay Belanger committed
221
(defun calc-do-embedded (calc-embed-arg end obeg oend)
Eli Zaretskii's avatar
Eli Zaretskii committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  (if calc-embedded-info

      ;; Turn embedded mode off or switch to a new buffer.
      (cond ((eq (current-buffer) (aref calc-embedded-info 1))
	     (let ((calcbuf (current-buffer))
		   (buf (aref calc-embedded-info 0)))
	       (calc-embedded-original-buffer t)
	       (calc-embedded nil)
	       (switch-to-buffer calcbuf)))

	    ((eq (current-buffer) (aref calc-embedded-info 0))
	     (let* ((info calc-embedded-info)
		    (mode calc-embedded-modes))
	       (save-excursion
		 (set-buffer (aref info 1))
		 (if (and (> (calc-stack-size) 0)
			  (equal (calc-top 1 'full) (aref info 8)))
		     (let ((calc-no-refresh-evaltos t))
		       (if (calc-top 1 'sel)
			   (calc-unselect 1))
		       (calc-embedded-set-modes
			(aref info 15) (aref info 12) (aref info 14))
		       (let ((calc-embedded-info nil))
			 (calc-wrapper (calc-pop-stack))))
		   (calc-set-mode-line)))
	       (setq calc-embedded-info nil
		     mode-line-buffer-identification (car mode)
		     truncate-lines (nth 2 mode)
		     buffer-read-only nil)
	       (use-local-map (nth 1 mode))
252 253
               (setq minor-mode-overriding-map-alist
                     (remq calc-override-minor-modes minor-mode-overriding-map-alist))
Eli Zaretskii's avatar
Eli Zaretskii committed
254
	       (set-buffer-modified-p (buffer-modified-p))
255
               (calc-embedded-restore-original-modes)
Eli Zaretskii's avatar
Eli Zaretskii committed
256
	       (or calc-embedded-quiet
257
		   (message "Back to %s mode" mode-name))))
Eli Zaretskii's avatar
Eli Zaretskii committed
258 259 260 261 262

	    (t
	     (if (buffer-name (aref calc-embedded-info 0))
		 (save-excursion
		   (set-buffer (aref calc-embedded-info 0))
263 264
		   (or (y-or-n-p (format "Cancel Calc Embedded mode in buffer %s? "
					 (buffer-name)))
Eli Zaretskii's avatar
Eli Zaretskii committed
265 266
		       (keyboard-quit))
		   (calc-embedded nil)))
Jay Belanger's avatar
Jay Belanger committed
267
	     (calc-embedded calc-embed-arg end obeg oend)))
Eli Zaretskii's avatar
Eli Zaretskii committed
268 269 270 271 272 273

    ;; Turn embedded mode on.
    (calc-plain-buffer-only)
    (let ((modes (list mode-line-buffer-identification
		       (current-local-map)
		       truncate-lines))
274 275 276
          (calc-embedded-firsttime (not calc-embedded-active))
          (calc-embedded-firsttime-buf nil)
          (calc-embedded-firsttime-formula nil)
277
	  calc-embed-top calc-embed-bot calc-embed-outer-top calc-embed-outer-bot
Eli Zaretskii's avatar
Eli Zaretskii committed
278 279
	  info chg ident)
      (barf-if-buffer-read-only)
280
      (calc-embedded-save-original-modes)
Eli Zaretskii's avatar
Eli Zaretskii committed
281 282
      (or calc-embedded-globals
	  (calc-find-globals))
Jay Belanger's avatar
Jay Belanger committed
283 284
      (setq info 
            (calc-embedded-make-info (point) nil t calc-embed-arg end obeg oend))
Eli Zaretskii's avatar
Eli Zaretskii committed
285 286
      (if (eq (car-safe (aref info 8)) 'error)
	  (progn
287
            (setq calc-embedded-original-modes nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
288 289 290 291 292 293 294 295 296
	    (goto-char (nth 1 (aref info 8)))
	    (error (nth 2 (aref info 8)))))
      (let ((mode-line-buffer-identification mode-line-buffer-identification)
	    (calc-embedded-info info)
	    (calc-embedded-no-reselect t))
	(calc-wrapper
	 (let* ((okay nil)
		(calc-no-refresh-evaltos t))
	   (if (aref info 8)
Jay Belanger's avatar
Jay Belanger committed
297 298 299 300 301 302
               (progn
                 (calc-push (calc-normalize (aref info 8)))
                 (setq chg (calc-embedded-set-modes
                            (aref info 15) (aref info 12) (aref info 13))))
             (setq chg (calc-embedded-set-modes
                        (aref info 15) (aref info 12) (aref info 13)))
Eli Zaretskii's avatar
Eli Zaretskii committed
303 304 305 306 307 308 309 310 311 312 313
	     (calc-alg-entry)))
	 (setq calc-undo-list nil
	       calc-redo-list nil
	       ident mode-line-buffer-identification)))
      (setq calc-embedded-info info
	    calc-embedded-modes modes
	    mode-line-buffer-identification ident
	    truncate-lines t
	    buffer-read-only t)
      (set-buffer-modified-p (buffer-modified-p))
      (use-local-map calc-mode-map)
314 315 316
      (setq minor-mode-overriding-map-alist
            (cons calc-override-minor-modes
                  minor-mode-overriding-map-alist))
Eli Zaretskii's avatar
Eli Zaretskii committed
317 318
      (setq calc-no-refresh-evaltos nil)
      (and chg calc-any-evaltos (calc-wrapper (calc-refresh-evaltos)))
319 320 321 322 323 324 325
      (let (str)
        (save-excursion
          (calc-select-buffer)
          (setq str mode-line-buffer-identification))
        (unless (equal str mode-line-buffer-identification)
          (setq mode-line-buffer-identification str)
          (set-buffer-modified-p (buffer-modified-p))))
326 327 328 329 330 331
      (if calc-embedded-firsttime
          (run-hooks 'calc-embedded-mode-hook))
      (if calc-embedded-firsttime-buf
          (run-hooks 'calc-embedded-new-buffer-hook))
      (if calc-embedded-firsttime-formula
          (run-hooks 'calc-embedded-new-formula-hook))
Eli Zaretskii's avatar
Eli Zaretskii committed
332
      (or (eq calc-embedded-quiet t)
333
	  (message "Embedded Calc mode enabled; %s to return to normal"
Eli Zaretskii's avatar
Eli Zaretskii committed
334
		   (if calc-embedded-quiet
335
		       "Type `C-x * x'"
Eli Zaretskii's avatar
Eli Zaretskii committed
336
		     "Give this command again")))))
337
  (scroll-down 0))    ; fix a bug which occurs when truncate-lines is changed.
Eli Zaretskii's avatar
Eli Zaretskii committed
338 339 340 341 342 343 344 345 346 347 348 349 350


(defun calc-embedded-select (arg)
  (interactive "P")
  (calc-embedded arg)
  (and calc-embedded-info
       (eq (car-safe (aref calc-embedded-info 8)) 'calcFunc-evalto)
       (calc-select-part 1))
  (and calc-embedded-info
       (or (eq (car-safe (aref calc-embedded-info 8)) 'calcFunc-assign)
	   (and (eq (car-safe (aref calc-embedded-info 8)) 'calcFunc-evalto)
		(eq (car-safe (nth 1 (aref calc-embedded-info 8)))
		    'calcFunc-assign)))
351
       (calc-select-part 2)))
Eli Zaretskii's avatar
Eli Zaretskii committed
352 353


Jay Belanger's avatar
Jay Belanger committed
354
(defun calc-embedded-update-formula (calc-embed-arg)
Eli Zaretskii's avatar
Eli Zaretskii committed
355
  (interactive "P")
Jay Belanger's avatar
Jay Belanger committed
356
  (if calc-embed-arg
Eli Zaretskii's avatar
Eli Zaretskii committed
357 358 359
      (let ((entry (assq (current-buffer) calc-embedded-active)))
	(while (setq entry (cdr entry))
	  (and (eq (car-safe (aref (car entry) 8)) 'calcFunc-evalto)
Jay Belanger's avatar
Jay Belanger committed
360
	       (or (not (consp calc-embed-arg))
Eli Zaretskii's avatar
Eli Zaretskii committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
		   (and (<= (aref (car entry) 2) (region-beginning))
			(>= (aref (car entry) 3) (region-end))))
	       (save-excursion
		 (calc-embedded-update (car entry) 14 t t)))))
    (if (and calc-embedded-info
	     (eq (current-buffer) (aref calc-embedded-info 0))
	     (>= (point) (aref calc-embedded-info 4))
	     (<= (point) (aref calc-embedded-info 5)))
	(calc-evaluate 1)
      (let* ((opt (point))
	     (info (calc-embedded-make-info (point) nil t))
	     (pt (- opt (aref info 4))))
	(or (eq (car-safe (aref info 8)) 'error)
	    (progn
	      (save-excursion
		(calc-embedded-update info 14 'eval t))
377
	      (goto-char (+ (aref info 4) pt))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
378 379


Jay Belanger's avatar
Jay Belanger committed
380
(defun calc-embedded-edit (calc-embed-arg)
Eli Zaretskii's avatar
Eli Zaretskii committed
381
  (interactive "P")
Jay Belanger's avatar
Jay Belanger committed
382
  (let ((info (calc-embedded-make-info (point) nil t calc-embed-arg))
Eli Zaretskii's avatar
Eli Zaretskii committed
383 384 385 386 387 388 389
	str)
    (if (eq (car-safe (aref info 8)) 'error)
	(progn
	  (goto-char (nth 1 (aref info 8)))
	  (error (nth 2 (aref info 8)))))
    (calc-wrapper
     (setq str (math-showing-full-precision
390
		(math-format-nice-expr (aref info 8) (frame-width))))
Eli Zaretskii's avatar
Eli Zaretskii committed
391 392
     (calc-edit-mode (list 'calc-embedded-finish-edit info))
     (insert str "\n")))
393
  (calc-show-edit-buffer))
Eli Zaretskii's avatar
Eli Zaretskii committed
394

395
(defvar calc-original-buffer)
396
(defvar calc-edit-top)
Eli Zaretskii's avatar
Eli Zaretskii committed
397 398
(defun calc-embedded-finish-edit (info)
  (let ((buf (current-buffer))
399
	(str (buffer-substring calc-edit-top (point-max)))
Eli Zaretskii's avatar
Eli Zaretskii committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
	(start (point))
	pos)
    (switch-to-buffer calc-original-buffer)
    (let ((val (save-excursion
		 (set-buffer (aref info 1))
		 (let ((calc-language nil)
		       (math-expr-opers math-standard-opers))
		   (math-read-expr str)))))
      (if (eq (car-safe val) 'error)
	  (progn
	    (switch-to-buffer buf)
	    (goto-char (+ start (nth 1 val)))
	    (error (nth 2 val))))
      (calc-embedded-original-buffer t info)
      (aset info 8 val)
415
      (calc-embedded-update info 14 t t))))
Eli Zaretskii's avatar
Eli Zaretskii committed
416

Jay Belanger's avatar
Jay Belanger committed
417
(defun calc-do-embedded-activate (calc-embed-arg cbuf)
Eli Zaretskii's avatar
Eli Zaretskii committed
418
  (calc-plain-buffer-only)
Jay Belanger's avatar
Jay Belanger committed
419
  (if calc-embed-arg
Eli Zaretskii's avatar
Eli Zaretskii committed
420 421
      (calc-embedded-forget))
  (calc-find-globals)
Jay Belanger's avatar
Jay Belanger committed
422
  (if (< (prefix-numeric-value calc-embed-arg) 0)
423
      (message "Deactivating %s for Calc Embedded mode" (buffer-name))
Eli Zaretskii's avatar
Eli Zaretskii committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437
    (message "Activating %s for Calc Embedded mode..." (buffer-name))
    (save-excursion
      (let* ((active (assq (current-buffer) calc-embedded-active))
	     (info active)
	     (pat " := \\| \\\\gets \\| => \\| \\\\evalto "))
	(if calc-embedded-announce-formula
	    (setq pat (format "%s\\|\\(%s\\)"
			      pat calc-embedded-announce-formula)))
	(while (setq info (cdr info))
	  (or (equal (buffer-substring (aref (car info) 2) (aref (car info) 3))
		     (aref (car info) 6))
	      (setcdr active (delq (car info) (cdr active)))))
	(goto-char (point-min))
	(while (re-search-forward pat nil t)
438 439
;;;	  (if (looking-at calc-embedded-open-formula)
;;;	      (goto-char (match-end 1)))
Eli Zaretskii's avatar
Eli Zaretskii committed
440 441 442 443
	  (setq info (calc-embedded-make-info (point) cbuf nil))
	  (or (eq (car-safe (aref info 8)) 'error)
	      (goto-char (aref info 5))))))
    (message "Activating %s for Calc Embedded mode...done" (buffer-name)))
444
  (calc-embedded-active-state t))
Eli Zaretskii's avatar
Eli Zaretskii committed
445 446 447

(defun calc-plain-buffer-only ()
  (if (memq major-mode '(calc-mode calc-trail-mode calc-edit-mode))
448
      (error "This command should be used in a normal editing buffer")))
Eli Zaretskii's avatar
Eli Zaretskii committed
449 450 451 452 453 454 455 456 457 458 459 460 461

(defun calc-embedded-active-state (state)
  (or (assq 'calc-embedded-all-active minor-mode-alist)
      (setq minor-mode-alist
	    (cons '(calc-embedded-all-active " Active")
		  (cons '(calc-embedded-some-active " ~Active")
			minor-mode-alist))))
  (let ((active (assq (current-buffer) calc-embedded-active)))
    (or (cdr active)
	(setq state nil)))
  (and (eq state 'more) calc-embedded-all-active (setq state t))
  (setq calc-embedded-all-active (eq state t)
	calc-embedded-some-active (not (memq state '(nil t))))
462
  (set-buffer-modified-p (buffer-modified-p)))
Eli Zaretskii's avatar
Eli Zaretskii committed
463 464 465 466 467 468 469 470


(defun calc-embedded-original-buffer (switch &optional info)
  (or info (setq info calc-embedded-info))
  (or (buffer-name (aref info 0))
      (progn
	(error "Calc embedded mode: Original buffer has been killed")))
  (if switch
471
      (set-buffer (aref info 0))))
Eli Zaretskii's avatar
Eli Zaretskii committed
472 473 474

(defun calc-embedded-word ()
  (interactive)
475
  (calc-embedded '(t)))
Eli Zaretskii's avatar
Eli Zaretskii committed
476 477 478 479 480 481 482 483

(defun calc-embedded-mark-formula (&optional body-only)
  "Put point at the beginning of this Calc formula, mark at the end.
This normally marks the whole formula, including surrounding delimiters.
With any prefix argument, marks only the formula itself."
  (interactive "P")
  (and (eq major-mode 'calc-mode)
       (error "This command should be used in a normal editing buffer"))
484
  (let (calc-embed-top calc-embed-bot calc-embed-outer-top calc-embed-outer-bot)
Eli Zaretskii's avatar
Eli Zaretskii committed
485 486
    (save-excursion
      (calc-embedded-find-bounds body-only))
487 488
    (push-mark (if body-only calc-embed-bot calc-embed-outer-bot) t)
    (goto-char (if body-only calc-embed-top calc-embed-outer-top))))
Eli Zaretskii's avatar
Eli Zaretskii committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502

(defun calc-embedded-find-bounds (&optional plain)
  ;; (while (and (bolp) (eq (following-char) ?\n))
  ;;  (forward-char 1))
  (and (eolp) (bolp) (not (eq (char-after (- (point) 2)) ?\n))
       (forward-char -1))
  (let ((home (point)))
    (or (and (looking-at calc-embedded-open-formula)
	     (not (looking-at calc-embedded-close-formula)))
	(re-search-backward calc-embedded-open-formula nil t)
	(error "Can't find start of formula"))
    (and (eq (preceding-char) ?\$)  ; backward search for \$\$? won't back
	 (eq (following-char) ?\$)  ; up over a second $, so do it by hand.
	 (forward-char -1))
503
    (setq calc-embed-outer-top (point))
Eli Zaretskii's avatar
Eli Zaretskii committed
504
    (goto-char (match-end 0))
505 506
    (if (looking-at "[ \t]*$")
        (end-of-line))
Eli Zaretskii's avatar
Eli Zaretskii committed
507 508 509 510 511 512 513 514 515 516
    (if (eq (following-char) ?\n)
	(forward-char 1))
    (or (bolp)
	(while (eq (following-char) ?\ )
	  (forward-char 1)))
    (or (eq plain 'plain)
	(if (looking-at (regexp-quote calc-embedded-open-plain))
	    (progn
	      (goto-char (match-end 0))
	      (search-forward calc-embedded-close-plain))))
517
    (setq calc-embed-top (point))
Eli Zaretskii's avatar
Eli Zaretskii committed
518 519 520 521 522 523
    (or (re-search-forward calc-embedded-close-formula nil t)
	(error "Can't find end of formula"))
    (if (< (point) home)
	(error "Not inside a formula"))
    (and (eq (following-char) ?\n) (not (bolp))
	 (forward-char 1))
524
    (setq calc-embed-outer-bot (point))
Eli Zaretskii's avatar
Eli Zaretskii committed
525 526 527 528 529 530
    (goto-char (match-beginning 0))
    (if (eq (preceding-char) ?\n)
	(backward-char 1))
    (or (eolp)
	(while (eq (preceding-char) ?\ )
	  (backward-char 1)))
531
    (setq calc-embed-bot (point))))
Eli Zaretskii's avatar
Eli Zaretskii committed
532 533 534 535 536 537 538 539 540 541 542

(defun calc-embedded-kill-formula ()
  "Kill the formula surrounding point.
If Calc Embedded mode was active, this deactivates it.
The formula (including its surrounding delimiters) is saved in the kill ring.
The command \\[yank] can retrieve it from there."
  (interactive)
  (and calc-embedded-info
       (calc-embedded nil))
  (calc-embedded-mark-formula)
  (kill-region (point) (mark))
543
  (pop-mark))
Eli Zaretskii's avatar
Eli Zaretskii committed
544 545 546 547 548 549 550

(defun calc-embedded-copy-formula-as-kill ()
  "Save the formula surrounding point as if killed, but don't kill it."
  (interactive)
  (save-excursion
    (calc-embedded-mark-formula)
    (copy-region-as-kill (point) (mark))
551
    (pop-mark)))
Eli Zaretskii's avatar
Eli Zaretskii committed
552 553 554 555

(defun calc-embedded-duplicate ()
  (interactive)
  (let ((already calc-embedded-info)
556
	calc-embed-top calc-embed-bot calc-embed-outer-top calc-embed-outer-bot new-top)
Eli Zaretskii's avatar
Eli Zaretskii committed
557 558
    (if calc-embedded-info
	(progn
559 560 561 562
	  (setq calc-embed-top (+ (aref calc-embedded-info 2))
		calc-embed-bot (+ (aref calc-embedded-info 3))
		calc-embed-outer-top (+ (aref calc-embedded-info 4))
		calc-embed-outer-bot (+ (aref calc-embedded-info 5)))
Eli Zaretskii's avatar
Eli Zaretskii committed
563 564
	  (calc-embedded nil))
      (calc-embedded-find-bounds))
565
    (goto-char calc-embed-outer-bot)
Eli Zaretskii's avatar
Eli Zaretskii committed
566 567
    (insert "\n")
    (setq new-top (point))
568 569 570
    (insert-buffer-substring (current-buffer) 
                             calc-embed-outer-top calc-embed-outer-bot)
    (goto-char (+ new-top (- calc-embed-top calc-embed-outer-top)))
Eli Zaretskii's avatar
Eli Zaretskii committed
571
    (let ((calc-embedded-quiet (if already t 'x)))
572 573
      (calc-embedded (+ new-top (- calc-embed-top calc-embed-outer-top))
		     (+ new-top (- calc-embed-bot calc-embed-outer-top))
Eli Zaretskii's avatar
Eli Zaretskii committed
574
		     new-top
575
		     (+ new-top (- calc-embed-outer-bot calc-embed-outer-top))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

(defun calc-embedded-next (arg)
  (interactive "P")
  (setq arg (prefix-numeric-value arg))
  (let* ((active (cdr (assq (current-buffer) calc-embedded-active)))
	 (p active)
	 (num (length active)))
    (or active
	(error "No active formulas in buffer"))
    (cond ((= arg 0))
	  ((= arg -1)
	   (if (<= (point) (aref (car active) 3))
	       (goto-char (aref (nth (1- num) active) 2))
	     (while (and (cdr p)
			 (> (point) (aref (nth 1 p) 3)))
	       (setq p (cdr p)))
	     (goto-char (aref (car p) 2))))
	  ((< arg -1)
	   (calc-embedded-next -1)
	   (calc-embedded-next (+ (* num 1000) arg 1)))
	  (t
	   (setq arg (1+ (% (1- arg) num)))
	   (while (and p (>= (point) (aref (car p) 2)))
	     (setq p (cdr p)))
	   (while (> (setq arg (1- arg)) 0)
	     (setq p (if p (cdr p) (cdr active))))
602
	   (goto-char (aref (car (or p active)) 2))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
603 604 605

(defun calc-embedded-previous (arg)
  (interactive "p")
606
  (calc-embedded-next (- (prefix-numeric-value arg))))
Eli Zaretskii's avatar
Eli Zaretskii committed
607 608 609 610 611 612 613

(defun calc-embedded-new-formula ()
  (interactive)
  (and (eq major-mode 'calc-mode)
       (error "This command should be used in a normal editing buffer"))
  (if calc-embedded-info
      (calc-embedded nil))
614
  (let (calc-embed-top calc-embed-bot calc-embed-outer-top calc-embed-outer-bot)
Eli Zaretskii's avatar
Eli Zaretskii committed
615 616 617
    (if (and (eq (preceding-char) ?\n)
	     (string-match "\\`\n" calc-embedded-open-new-formula))
	(progn
618
	  (setq calc-embed-outer-top (1- (point)))
Eli Zaretskii's avatar
Eli Zaretskii committed
619 620
	  (forward-char -1)
	  (insert (substring calc-embedded-open-new-formula 1)))
621
      (setq calc-embed-outer-top (point))
Eli Zaretskii's avatar
Eli Zaretskii committed
622
      (insert calc-embedded-open-new-formula))
623
    (setq calc-embed-top (point))
Eli Zaretskii's avatar
Eli Zaretskii committed
624
    (insert " ")
625
    (setq calc-embed-bot (point))
Eli Zaretskii's avatar
Eli Zaretskii committed
626 627 628 629
    (insert calc-embedded-close-new-formula)
    (if (and (eq (following-char) ?\n)
	     (string-match "\n\\'" calc-embedded-close-new-formula))
	(delete-char 1))
630 631
    (setq calc-embed-outer-bot (point))
    (goto-char calc-embed-top)
Eli Zaretskii's avatar
Eli Zaretskii committed
632
    (let ((calc-embedded-quiet 'x))
633
      (calc-embedded calc-embed-top calc-embed-bot calc-embed-outer-top calc-embed-outer-bot))))
Eli Zaretskii's avatar
Eli Zaretskii committed
634 635 636 637 638

(defun calc-embedded-forget ()
  (interactive)
  (setq calc-embedded-active (delq (assq (current-buffer) calc-embedded-active)
				   calc-embedded-active))
639
  (calc-embedded-active-state nil))
Eli Zaretskii's avatar
Eli Zaretskii committed
640

641 642 643
;; The variables calc-embed-prev-modes is local to calc-embedded-update,
;; but is used by calc-embedded-set-modes.
(defvar calc-embed-prev-modes)
Eli Zaretskii's avatar
Eli Zaretskii committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

(defun calc-embedded-set-modes (gmodes modes local-modes &optional temp)
  (let ((the-language (calc-embedded-language))
	(the-display-just (calc-embedded-justify))
	(v gmodes)
	(changed nil)
	found value)
    (while v
      (or (symbolp (car v))
	  (and (setq found (assq (car (car v)) modes))
	       (not (eq (cdr found) 'default)))
	  (and (setq found (assq (car (car v)) local-modes))
	       (not (eq (cdr found) 'default)))
	  (progn
	    (if (eq (setq value (cdr (car v))) 'default)
659
		(setq value (list (nth 1 (assq (car (car v)) calc-mode-var-list)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
660 661 662
	    (equal (symbol-value (car (car v))) value))
	  (progn
	    (setq changed t)
663 664 665 666
	    (if temp (setq calc-embed-prev-modes 
                           (cons (cons (car (car v))
                                       (symbol-value (car (car v))))
                                 calc-embed-prev-modes)))
Eli Zaretskii's avatar
Eli Zaretskii committed
667 668 669 670 671 672 673 674 675 676
	    (set (car (car v)) value)))
      (setq v (cdr v)))
    (setq v modes)
    (while v
      (or (and (setq found (assq (car (car v)) local-modes))
	       (not (eq (cdr found) 'default)))
	  (eq (setq value (cdr (car v))) 'default)
	  (equal (symbol-value (car (car v))) value)
	  (progn
	    (setq changed t)
677
	    (if temp (setq calc-embed-prev-modes (cons (cons (car (car v))
Eli Zaretskii's avatar
Eli Zaretskii committed
678
						  (symbol-value (car (car v))))
679
					    calc-embed-prev-modes)))
Eli Zaretskii's avatar
Eli Zaretskii committed
680 681 682 683 684 685 686 687
	    (set (car (car v)) value)))
      (setq v (cdr v)))
    (setq v local-modes)
    (while v
      (or (eq (setq value (cdr (car v))) 'default)
	  (equal (symbol-value (car (car v))) value)
	  (progn
	    (setq changed t)
688
	    (if temp (setq calc-embed-prev-modes (cons (cons (car (car v))
Eli Zaretskii's avatar
Eli Zaretskii committed
689
						  (symbol-value (car (car v))))
690
					    calc-embed-prev-modes)))
Eli Zaretskii's avatar
Eli Zaretskii committed
691 692 693 694 695 696 697 698 699 700 701 702 703 704
	    (set (car (car v)) value)))
      (setq v (cdr v)))
    (and changed (not (eq temp t))
	 (progn
	   (calc-embedded-set-justify the-display-just)
	   (calc-embedded-set-language the-language)))
    (and changed (not temp)
	 (progn
	   (setq calc-full-float-format (list (if (eq (car calc-float-format)
						      'fix)
						  'float
						(car calc-float-format))
					      0))
	   (calc-refresh)))
705
    changed))
Eli Zaretskii's avatar
Eli Zaretskii committed
706 707 708 709

(defun calc-embedded-language ()
  (if calc-language-option
      (list calc-language calc-language-option)
710
    calc-language))
Eli Zaretskii's avatar
Eli Zaretskii committed
711 712 713 714 715 716 717 718

(defun calc-embedded-set-language (lang)
  (let ((option nil))
    (if (consp lang)
	(setq option (nth 1 lang)
	      lang (car lang)))
    (or (and (eq lang calc-language)
	     (equal option calc-language-option))
719
	(calc-set-language lang option t))))
Eli Zaretskii's avatar
Eli Zaretskii committed
720 721 722 723

(defun calc-embedded-justify ()
  (if calc-display-origin
      (list calc-display-just calc-display-origin)
724
    calc-display-just))
Eli Zaretskii's avatar
Eli Zaretskii committed
725 726 727 728 729 730

(defun calc-embedded-set-justify (just)
  (if (consp just)
      (setq calc-display-origin (nth 1 just)
	    calc-display-just (car just))
    (setq calc-display-just just
731
	  calc-display-origin nil)))
Eli Zaretskii's avatar
Eli Zaretskii committed
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755


(defun calc-find-globals ()
  (interactive)
  (and (eq major-mode 'calc-mode)
       (error "This command should be used in a normal editing buffer"))
  (make-local-variable 'calc-embedded-globals)
  (let ((case-fold-search nil)
	(modes nil)
	(save-pt (point))
	found value)
    (goto-char (point-min))
    (while (re-search-forward "\\[calc-global-mode: *\\([-a-z]+\\): *\\(\"\\([^\"\n\\]\\|\\\\.\\)*\"\\|[- ()a-zA-Z0-9]+\\)\\]" nil t)
      (and (setq found (assoc (buffer-substring (match-beginning 1)
						(match-end 1))
			      calc-embedded-mode-vars))
	   (or (assq (cdr found) modes)
	       (setq modes (cons (cons (cdr found)
				       (car (read-from-string
					     (buffer-substring
					      (match-beginning 2)
					      (match-end 2)))))
				 modes)))))
    (setq calc-embedded-globals (cons t modes))
756
    (goto-char save-pt)))
Eli Zaretskii's avatar
Eli Zaretskii committed
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804

(defun calc-embedded-find-modes ()
  (let ((case-fold-search nil)
	(save-pt (point))
	(no-defaults t)
	(modes nil)
	(emodes nil)
	(pmodes nil)
	found value)
    (while (and no-defaults (search-backward "[calc-" nil t))
      (forward-char 6)
      (or (and (looking-at "mode: *\\([-a-z]+\\): *\\(\"\\([^\"\n\\]\\|\\\\.\\)*\"\\|[- ()a-zA-Z0-9]+\\)]")
	       (setq found (assoc (buffer-substring (match-beginning 1)
						    (match-end 1))
				  calc-embedded-mode-vars))
	       (or (assq (cdr found) modes)
		   (setq modes (cons (cons (cdr found)
					   (car (read-from-string
						 (buffer-substring
						  (match-beginning 2)
						  (match-end 2)))))
				     modes))))
	  (and (looking-at "perm-mode: *\\([-a-z]+\\): *\\(\"\\([^\"\n\\]\\|\\\\.\\)*\"\\|[- ()a-zA-Z0-9]+\\)]")
	       (setq found (assoc (buffer-substring (match-beginning 1)
						    (match-end 1))
				  calc-embedded-mode-vars))
	       (or (assq (cdr found) pmodes)
		   (setq pmodes (cons (cons (cdr found)
					    (car (read-from-string
						  (buffer-substring
						   (match-beginning 2)
						   (match-end 2)))))
				      pmodes))))
	  (and (looking-at "edit-mode: *\\([-a-z]+\\): *\\(\"\\([^\"\n\\]\\|\\\\.\\)*\"\\|[- ()a-zA-Z0-9]+\\)]")
	       (setq found (assoc (buffer-substring (match-beginning 1)
						    (match-end 1))
				  calc-embedded-mode-vars))
	       (or (assq (cdr found) emodes)
		   (setq emodes (cons (cons (cdr found)
					    (car (read-from-string
						  (buffer-substring
						   (match-beginning 2)
						   (match-end 2)))))
				      emodes))))
	  (and (looking-at "defaults]")
	       (setq no-defaults nil)))
      (backward-char 6))
    (goto-char save-pt)
805
    (unless (assq 'the-language modes)
806
      (let ((lang (assoc major-mode calc-language-alist)))
807 808 809
        (if lang
            (setq modes (cons (cons 'the-language (cdr lang))
                              modes)))))
810
    (list modes emodes pmodes)))
Eli Zaretskii's avatar
Eli Zaretskii committed
811

812 813 814 815
;; The variable calc-embed-vars-used is local to calc-embedded-make-info,
;; calc-embedded-evaluate-expr and calc-embedded-update, but is 
;; used by calc-embedded-find-vars, which is called by the above functions.
(defvar calc-embed-vars-used)
Eli Zaretskii's avatar
Eli Zaretskii committed
816 817

(defun calc-embedded-make-info (point cbuf fresh &optional
818 819
				      calc-embed-top calc-embed-bot 
                                      calc-embed-outer-top calc-embed-outer-bot)
Eli Zaretskii's avatar
Eli Zaretskii committed
820 821
  (let* ((bufentry (assq (current-buffer) calc-embedded-active))
	 (found bufentry)
822 823
	 (force (and fresh calc-embed-top))
	 (fixed calc-embed-top)
Eli Zaretskii's avatar
Eli Zaretskii committed
824 825 826
	 (new-info nil)
	 info str)
    (or found
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
        (and
         (setq found (list (current-buffer))
               calc-embedded-active (cons found calc-embedded-active)
               calc-embedded-firsttime-buf t)
         (let ((newann (assoc major-mode calc-embedded-announce-formula-alist))
               (newform (assoc major-mode calc-embedded-open-close-formula-alist))
               (newword (assoc major-mode calc-embedded-open-close-word-alist))
               (newplain (assoc major-mode calc-embedded-open-close-plain-alist))
               (newnewform 
                (assoc major-mode calc-embedded-open-close-new-formula-alist))
               (newmode (assoc major-mode calc-embedded-open-close-mode-alist)))
           (when newann
             (make-local-variable 'calc-embedded-announce-formula)
             (setq calc-embedded-announce-formula (cdr newann)))
           (when newform
             (make-local-variable 'calc-embedded-open-formula)
             (make-local-variable 'calc-embedded-close-formula)
             (setq calc-embedded-open-formula (nth 0 (cdr newform)))
             (setq calc-embedded-close-formula (nth 1 (cdr newform))))
           (when newword
             (make-local-variable 'calc-embedded-open-word)
             (make-local-variable 'calc-embedded-close-word)
             (setq calc-embedded-open-word (nth 0 (cdr newword)))
             (setq calc-embedded-close-word (nth 1 (cdr newword))))
           (when newplain
             (make-local-variable 'calc-embedded-open-plain)
             (make-local-variable 'calc-embedded-close-plain)
             (setq calc-embedded-open-plain (nth 0 (cdr newplain)))
             (setq calc-embedded-close-plain (nth 1 (cdr newplain))))
           (when newnewform
             (make-local-variable 'calc-embedded-open-new-formula)
             (make-local-variable 'calc-embedded-close-new-formula)
             (setq calc-embedded-open-new-formula (nth 0 (cdr newnewform)))
             (setq calc-embedded-close-new-formula (nth 1 (cdr newnewform))))
           (when newmode
             (make-local-variable 'calc-embedded-open-mode)
             (make-local-variable 'calc-embedded-close-mode)
             (setq calc-embedded-open-mode (nth 0 (cdr newmode)))
             (setq calc-embedded-close-mode (nth 1 (cdr newmode)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
866 867 868 869 870
    (while (and (cdr found)
		(> point (aref (car (cdr found)) 3)))
      (setq found (cdr found)))
    (if (and (cdr found)
	     (>= point (aref (nth 1 found) 2)))
871 872
        (setq info (nth 1 found))
      (setq calc-embedded-firsttime-formula t)
Eli Zaretskii's avatar
Eli Zaretskii committed
873 874 875 876 877 878 879
      (setq info (make-vector 16 nil)
	    new-info t
	    fresh t)
      (aset info 0 (current-buffer))
      (aset info 1 (or cbuf (save-excursion
			      (calc-create-buffer)
			      (current-buffer)))))
880 881 882
    (if (and 
         (or (integerp calc-embed-top) (equal calc-embed-top '(4)))
         (not calc-embed-bot))  
883
                                        ; started with a user-supplied argument
Eli Zaretskii's avatar
Eli Zaretskii committed
884
	(progn
885 886 887 888 889
          (if (equal calc-embed-top '(4))
              (progn
                (aset info 2 (copy-marker (line-beginning-position)))
                (aset info 3 (copy-marker (line-end-position))))
            (if (= (setq calc-embed-arg (prefix-numeric-value calc-embed-arg)) 0)
890
                (progn
891 892 893 894 895 896 897 898 899
                  (aset info 2 (copy-marker (region-beginning)))
                  (aset info 3 (copy-marker (region-end))))
              (aset info (if (> calc-embed-arg 0) 2 3) (point-marker))
              (if (> calc-embed-arg 0)
                  (progn
                    (forward-line (1- calc-embed-arg))
                    (end-of-line))
                (forward-line (1+ calc-embed-arg)))
              (aset info (if (> calc-embed-arg 0) 3 2) (point-marker))))
Eli Zaretskii's avatar
Eli Zaretskii committed
900 901 902
	  (aset info 4 (copy-marker (aref info 2)))
	  (aset info 5 (copy-marker (aref info 3))))
      (if (aref info 4)
903 904 905
	  (setq calc-embed-top (aref info 2)
		fixed calc-embed-top)
	(if (consp calc-embed-top)
Eli Zaretskii's avatar
Eli Zaretskii committed
906 907 908
	    (let ((calc-embedded-open-formula calc-embedded-open-word)
		  (calc-embedded-close-formula calc-embedded-close-word))
	      (calc-embedded-find-bounds 'plain))
909
	  (or calc-embed-top
Eli Zaretskii's avatar
Eli Zaretskii committed
910
	      (calc-embedded-find-bounds 'plain)))
911 912 913 914
	(aset info 2 (copy-marker (min calc-embed-top calc-embed-bot)))
	(aset info 3 (copy-marker (max calc-embed-top calc-embed-bot)))
	(aset info 4 (copy-marker (or calc-embed-outer-top (aref info 2))))
	(aset info 5 (copy-marker (or calc-embed-outer-bot (aref info 3))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
    (goto-char (aref info 2))
    (if new-info
	(progn
	  (or (bolp) (aset info 7 t))
	  (goto-char (aref info 3))
	  (or (bolp) (eolp) (aset info 7 t))))
    (if fresh
	(let ((modes (calc-embedded-find-modes)))
	  (aset info 12 (car modes))
	  (aset info 13 (nth 1 modes))
	  (aset info 14 (nth 2 modes))))
    (aset info 15 calc-embedded-globals)
    (setq str (buffer-substring (aref info 2) (aref info 3)))
    (if (or force
	    (not (equal str (aref info 6))))
	(if (and fixed (aref info 6))
	    (progn
	      (aset info 4 nil)
	      (calc-embedded-make-info point cbuf nil)
	      (setq new-info nil))
	  (let* ((open-plain calc-embedded-open-plain)
		 (close-plain calc-embedded-close-plain)
		 (pref-len (length open-plain))
938
		 (calc-embed-vars-used nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
939 940 941 942 943 944 945 946 947 948 949 950 951
		 suff-pos val temp)
	    (save-excursion
	      (set-buffer (aref info 1))
	      (calc-embedded-set-modes (aref info 15)
				       (aref info 12) (aref info 14))
	      (if (and (> (length str) pref-len)
		       (equal (substring str 0 pref-len) open-plain)
		       (setq suff-pos (string-match (regexp-quote close-plain)
						    str pref-len)))
		  (setq val (math-read-plain-expr
			     (substring str pref-len suff-pos)))
		(if (string-match "[^ \t\n]" str)
		    (setq pref-len 0
952 953 954
			  val (condition-case nil
                                  (math-read-big-expr str)
                                (error (math-read-expr str))))
Eli Zaretskii's avatar
Eli Zaretskii committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
		  (setq val nil))))
	    (if (eq (car-safe val) 'error)
		(setq val (list 'error
				(+ (aref info 2) pref-len (nth 1 val))
				(nth 2 val))))
	    (aset info 6 str)
	    (aset info 8 val)
	    (setq temp val)
	    (if (eq (car-safe temp) 'calcFunc-evalto)
		(setq temp (nth 1 temp))
	      (if (eq (car-safe temp) 'error)
		  (if new-info
		      (setq new-info nil)
		    (setcdr found (delq info (cdr found)))
		    (calc-embedded-active-state 'less))))
	    (aset info 9 (and (eq (car-safe temp) 'calcFunc-assign)
			      (nth 1 temp)))
	    (if (memq (car-safe val) '(calcFunc-evalto calcFunc-assign))
		(calc-embedded-find-vars val))
974
	    (aset info 10 calc-embed-vars-used)
Eli Zaretskii's avatar
Eli Zaretskii committed
975 976 977 978 979
	    (aset info 11 nil))))
    (if new-info
	(progn
	  (setcdr found (cons info (cdr found)))
	  (calc-embedded-active-state 'more)))
980
    info))
Eli Zaretskii's avatar
Eli Zaretskii committed
981 982 983 984

(defun calc-embedded-find-vars (x)
  (cond ((Math-primp x)
	 (and (eq (car-safe x) 'var)
985 986
	      (not (assoc x calc-embed-vars-used))
	      (setq calc-embed-vars-used (cons (list x) calc-embed-vars-used))))
Eli Zaretskii's avatar
Eli Zaretskii committed
987 988 989 990 991 992 993 994
	((eq (car x) 'calcFunc-evalto)
	 (calc-embedded-find-vars (nth 1 x)))
	((eq (car x) 'calcFunc-assign)
	 (calc-embedded-find-vars (nth 2 x)))
	(t
	 (and (eq (car x) 'calcFunc-subscr)
	      (eq (car-safe (nth 1 x)) 'var)
	      (Math-primp (nth 2 x))
995 996
	      (not (assoc x calc-embed-vars-used))
	      (setq calc-embed-vars-used (cons (list x) calc-embed-vars-used)))
Eli Zaretskii's avatar
Eli Zaretskii committed
997
	 (while (setq x (cdr x))
998
	   (calc-embedded-find-vars (car x))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
999

Jay Belanger's avatar
Jay Belanger committed
1000
(defvar math-ms-args)
Eli Zaretskii's avatar
Eli Zaretskii committed
1001
(defun calc-embedded-evaluate-expr (x)
1002 1003 1004
  (let ((calc-embed-vars-used (aref calc-embedded-info 10)))
    (or calc-embed-vars-used (calc-embedded-find-vars x))
    (if calc-embed-vars-used
Eli Zaretskii's avatar
Eli Zaretskii committed
1005
	(let ((active (assq (aref calc-embedded-info 0) calc-embedded-active))
Jay Belanger's avatar
Jay Belanger committed
1006
	      (math-ms-args nil))
Eli Zaretskii's avatar
Eli Zaretskii committed
1007 1008 1009 1010 1011 1012 1013
	  (save-excursion
	    (calc-embedded-original-buffer t)
	    (or active
		(progn
		  (calc-embedded-activate)
		  (setq active (assq (aref calc-embedded-info 0)
				     calc-embedded-active))))
1014 1015 1016
	    (while calc-embed-vars-used
	      (calc-embedded-eval-get-var (car (car calc-embed-vars-used)) active)
	      (setq calc-embed-vars-used (cdr calc-embed-vars-used))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1017
	  (calc-embedded-subst x))
1018
      (calc-normalize (math-evaluate-expr-rec x)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

(defun calc-embedded-subst (x)
  (if (and (eq (car-safe x) 'calcFunc-evalto) (cdr x))
      (let ((rhs (calc-embedded-subst (nth 1 x))))
	(list 'calcFunc-evalto
	      (nth 1 x)
	      (if (eq (car-safe rhs) 'calcFunc-assign) (nth 2 rhs) rhs)))
    (if (and (eq (car-safe x) 'calcFunc-assign) (= (length x) 3))
	(list 'calcFunc-assign
	      (nth 1 x)
	      (calc-embedded-subst (nth 2 x)))
Jay Belanger's avatar
Jay Belanger committed
1030
      (calc-normalize (math-evaluate-expr-rec (math-multi-subst-rec x))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

(defun calc-embedded-eval-get-var (var base)
  (let ((entry base)
	(point (aref calc-embedded-info 2))
	(last nil)
	val)
    (while (and (setq entry (cdr entry))
		(or (not (equal var (aref (car entry) 9)))
		    (and (> point (aref (car entry) 3))
			 (setq last entry)))))
    (if last
	(setq entry last))
    (if entry
	(progn
	  (setq entry (car entry))
	  (if (equal (buffer-substring (aref entry 2) (aref entry 3))
		     (aref entry 6))
	      (progn
		(or (aref entry 11)
		    (save-excursion
		      (calc-embedded-update entry 14 t nil)))
		(setq val (aref entry 11))
		(if (eq (car-safe val) 'calcFunc-evalto)
		    (setq val (nth 2 val)))
		(if (eq (car-safe val) 'calcFunc-assign)
		    (setq val (nth 2 val)))
Jay Belanger's avatar
Jay Belanger committed
1057
		(setq math-ms-args (cons (cons var val) math-ms-args)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1058
	    (calc-embedded-activate)
1059
	    (calc-embedded-eval-get-var var base))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1060 1061 1062 1063


(defun calc-embedded-update (info which need-eval need-display
				  &optional str entry old-val)
1064
  (let* ((calc-embed-prev-modes nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
1065 1066
	 (open-plain calc-embedded-open-plain)
	 (close-plain calc-embedded-close-plain)
1067
	 (calc-embed-vars-used nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
	 (evalled nil)
	 (val (aref info 8))
	 (old-eval (aref info 11)))
    (or old-val (setq old-val val))
    (if (eq (car-safe val) 'calcFunc-evalto)
	(setq need-display t))
    (unwind-protect
	(progn
	  (set-buffer (aref info 1))
	  (and which
	       (calc-embedded-set-modes (aref info 15) (aref info 12)
					(aref info which)
					(if need-display 'full t)))
	  (if (memq (car-safe val) '(calcFunc-evalto calcFunc-assign))
	      (calc-embedded-find-vars val))
	  (if need-eval
	      (let ((calc-embedded-info info))
		(setq val (math-evaluate-expr val)
		      evalled val)))
	  (if (or (eq need-eval 'eval) (eq (car-safe val) 'calcFunc-evalto))
	      (aset info 8 val))
	  (aset info 9 nil)
1090
	  (aset info 10 calc-embed-vars-used)
Eli Zaretskii's avatar
Eli Zaretskii committed
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
	  (aset info 11 nil)
	  (if (or need-display (eq (car-safe val) 'calcFunc-evalto))
	      (let ((extra (if (eq calc-language 'big) 1 0)))
		(or entry (setq entry (list val 1 nil)))
		(or str (progn
			  (setq str (let ((calc-line-numbering nil))
				      (math-format-stack-value entry)))
			  (if (eq calc-language 'big)
			      (setq str (substring str 0 -1)))))
		(and calc-show-plain
		     (setq str (concat open-plain
				       (math-showing-full-precision
					(math-format-flat-expr val 0))
				       close-plain
				       str)))
		(save-excursion
		  (calc-embedded-original-buffer t info)
		  (or (equal str (aref info 6))
		      (let ((delta (- (aref info 5) (aref info 3)))
1110
                            (adjbot 0)
Eli Zaretskii's avatar
Eli Zaretskii committed
1111 1112 1113 1114 1115 1116 1117
			    (buffer-read-only nil))
			(goto-char (aref info 2))
			(delete-region (point) (aref info 3))
			(and (> (nth 1 entry) (1+ extra))
			     (aref info 7)
			     (progn
			       (delete-horizontal-space)
1118 1119 1120 1121 1122 1123 1124 1125
                               (if (looking-at "\n")
                                   ;; If there's a newline there, don't add one
                                   (insert "\n")
                                 (insert "\n\n")
                                 (delete-horizontal-space)
                                 (setq adjbot 1)
;                               (setq delta (1+ delta))
                                 (backward-char 1))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1126
			(insert str)
1127
			(set-marker (aref info 3) (+ (point) adjbot))
Eli Zaretskii's avatar
Eli Zaretskii committed
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
			(set-marker (aref info 5) (+ (point) delta))
			(aset info 6 str))))))
	  (if (eq (car-safe val) 'calcFunc-evalto)
	      (progn
		(setq evalled (nth 2 val)
		      val (nth 1 val))))
	  (if (eq (car-safe val) 'calcFunc-assign)
	      (progn
		(aset info 9 (nth 1 val))
		(aset info 11 (or evalled
				  (let ((calc-embedded-info info))
				    (math-evaluate-expr (nth 2 val)))))
		(or (equal old-eval (aref info 11))
		    (calc-embedded-var-change (nth 1 val) (aref info 0))))
	    (if (eq (car-safe old-val) 'calcFunc-evalto)
		(setq old-val (nth 1 old-val)))
	    (if (eq (car-safe old-val) 'calcFunc-assign)
		(calc-embedded-var-change (nth 1 old-val) (aref info 0)))))
      (set-buffer (aref info 1))
1147 1148
      (while calc-embed-prev-modes
	(cond ((eq (car (car calc-embed-prev-modes)) 'the-language)
Eli Zaretskii's avatar
Eli Zaretskii committed
1149
	       (if need-display
1150 1151
		   (calc-embedded-set-language (cdr (car calc-embed-prev-modes)))))
	      ((eq (car (car calc-embed-prev-modes)) 'the-display-just)
Eli Zaretskii's avatar
Eli Zaretskii committed
1152
	       (if need-display
1153
		   (calc-embedded-set-justify (cdr (car calc-embed-prev-modes)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1154
	      (t
1155 1156
	       (set (car (car calc-embed-prev-modes)) 
                    (cdr (car calc-embed-prev-modes)))))
1157
	(setq calc-embed-prev-modes (cdr calc-embed-prev-modes))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1158 1159 1160 1161 1162 1163




;;; These are hooks called by the main part of Calc.

1164
(defvar calc-embedded-no-reselect nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
(defun calc-embedded-select-buffer ()
  (if (eq (current-buffer) (aref calc-embedded-info 0))
      (let ((info calc-embedded-info)
	    horiz vert)
	(if (and (or (< (point) (aref info 4))
		     (> (point) (aref info 5)))
		 (not calc-embedded-no-reselect))
	    (let ((calc-embedded-quiet t))
	      (message "(Switching Calc Embedded mode to new formula.)")
	      (calc-embedded nil)
	      (calc-embedded nil)))
	(setq horiz (max (min (current-column) (- (point) (aref info 2))) 0)
	      vert (if (<= (aref info 2) (point))
		       (- (count-lines (aref info 2) (point))
			  (if (bolp) 0 1))
		     0))
	(set-buffer (aref info 1))
	(if calc-show-plain
	    (if (= vert 0)
		(setq horiz 0)
	      (setq vert (1- vert))))
	(calc-cursor-stack-index 1)
	(if calc-line-numbering
	    (setq horiz (+ horiz 4)))
	(if (> vert 0)
	    (forward-line vert))
	(forward-char (min horiz
			   (- (point-max) (point)))))
1193
    (calc-select-buffer)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

(defun calc-embedded-finish-command ()
  (let ((buf (current-buffer))
	horiz vert)
    (save-excursion
      (set-buffer (aref calc-embedded-info 1))
      (if (> (calc-stack-size) 0)
	  (let ((pt (point))
		(col (current-column))
		(bol (bolp)))
	    (calc-cursor-stack-index 0)
	    (if (< pt (point))
		(progn
		  (calc-cursor-stack-index 1)
		  (if (>= pt (point))
		      (progn
			(setq horiz (- col (if calc-line-numbering 4 0))
			      vert (- (count-lines (point) pt)
				      (if bol 0 1)))
			(if calc-show-plain
			    (setq vert (max 1 (1+ vert))))))))
	    (goto-char pt))))
    (if horiz
	(progn
	  (set-buffer (aref calc-embedded-info 0))
	  (goto-char (aref calc-embedded-info 2))
	  (if (> vert 0)
	      (forward-line vert))
	  (forward-char (max horiz 0))
1223
	  (set-buffer buf)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254

(defun calc-embedded-stack-change ()
  (or calc-executing-macro
      (save-excursion
	(set-buffer (aref calc-embedded-info 1))
	(let* ((info calc-embedded-info)
	       (extra-line (if (eq calc-language 'big) 1 0))
	       (the-point (point))
	       (empty (= (calc-stack-size) 0))
	       (entry (if empty
			  (list '(var empty var-empty) 1 nil)
			(calc-top 1 'entry)))
	       (old-val (aref info 8))
	       top bot str)
	  (if empty
	      (setq str "empty")
	    (save-excursion
	      (calc-cursor-stack-index 1)
	      (setq top (point))
	      (calc-cursor-stack-index 0)
	      (setq bot (- (point) extra-line))
	      (setq str (buffer-substring top (- bot 1))))
	    (if calc-line-numbering
		(let ((pos 0))
		  (setq str (substring str 4))
		  (while (setq pos (string-match "\n...." str pos))
		    (setq str (concat (substring str 0 (1+ pos))
				      (substring str (+ pos 5)))
			  pos (1+ pos))))))
	  (calc-embedded-original-buffer t)
	  (aset info 8 (car entry))
1255
	  (calc-embedded-update info 13 nil t str entry old-val)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1256 1257 1258 1259 1260 1261

(defun calc-embedded-mode-line-change ()
  (let ((str mode-line-buffer-identification))
    (save-excursion
      (calc-embedded-original-buffer t)
      (setq mode-line-buffer-identification str)
1262
      (set-buffer-modified-p (buffer-modified-p)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

(defun calc-embedded-modes-change (vars)
  (if (eq (car vars) 'calc-language) (setq vars '(the-language)))
  (if (eq (car vars) 'calc-display-just) (setq vars '(the-display-just)))
  (while (and vars
	      (not (rassq (car vars) calc-embedded-mode-vars)))
    (setq vars (cdr vars)))
  (if (and vars calc-mode-save-mode (not (eq calc-mode-save-mode 'save)))
      (save-excursion
	(let* ((save-mode calc-mode-save-mode)
	       (header (if (eq save-mode 'local)
			   "calc-mode:"
			 (format "calc-%s-mode:" save-mode)))
	       (the-language (calc-embedded-language))
	       (the-display-just (calc-embedded-justify))
	       (values (mapcar 'symbol-value vars))
	       (num (cond ((eq save-mode 'local) 12)
			  ((eq save-mode 'edit) 13)
			  ((eq save-mode 'perm) 14)
			  (t nil)))
	       base limit mname mlist)
	  (calc-embedded-original-buffer t)
	  (save-excursion
	    (if (eq save-mode 'global)
		(setq base (point-max)
		      limit (point-min)
		      mlist calc-embedded-globals)
	      (goto-char (aref calc-embedded-info 4))
	      (beginning-of-line)
	      (setq base (point)
		    limit (max (- (point) 1000) (point-min))
		    mlist (and num (aref calc-embedded-info num)))
	      (and (re-search-backward
		    (format "\\(%s\\)[^\001]*\\(%s\\)\\|\\[calc-defaults]"
			    calc-embedded-open-formula
			    calc-embedded-close-formula) limit t)
		   (setq limit (point))))
	    (while vars
	      (goto-char base)
	      (if (setq mname (car (rassq (car vars)
					  calc-embedded-mode-vars)))
		  (let ((buffer-read-only nil)
			(found (assq (car vars) mlist)))
		    (if found
			(setcdr found (car values))
		      (setq mlist (cons (cons (car vars) (car values)) mlist))
		      (if num
			  (aset calc-embedded-info num mlist)
			(if (eq save-mode 'global)
			    (setq calc-embedded-globals mlist))))
		    (if (re-search-backward
			 (format "\\[%s *%s: *\\(\"\\([^\"\n\\]\\|\\\\.\\)*\"\\|[- ()a-zA-Z0-9]+\\)]"
				 header mname)
			 limit t)
			(progn
			  (goto-char (match-beginning 1))
			  (delete-region (point) (match-end 1))
			  (insert (prin1-to-string (car values))))
		      (goto-char base)
		      (insert-before-markers
		       calc-embedded-open-mode
		       "[" header " " mname ": "
		       (prin1-to-string (car values)) "]"
		       calc-embedded-close-mode))))
	      (setq vars (cdr vars)
1328
		    values (cdr values))))))
1329 1330
    (when (and vars (eq calc-mode-save-mode 'save))
      (calc-embedded-save-original-modes))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369

(defun calc-embedded-var-change (var &optional buf)
  (if (symbolp var)
      (setq var (list 'var
		      (if (string-match "\\`var-.+\\'"
					(symbol-name var))
			  (intern (substring (symbol-name var) 4))
			var)
		      var)))
  (save-excursion
    (let ((manual (not calc-auto-recompute))
	  (bp calc-embedded-active)
	  (first t))
      (if buf (setq bp (memq (assq buf bp) bp)))
      (while bp
	(let ((calc-embedded-no-reselect t)
	      (p (and (buffer-name (car (car bp)))
		      (cdr (car bp)))))
	  (while p
	    (if (assoc var (aref (car p) 10))
		(if manual
		    (if (aref (car p) 11)
			(progn
			  (aset (car p) 11 nil)
			  (if (aref (car p) 9)
			      (calc-embedded-var-change (aref (car p) 9)))))
		  (set-buffer (aref (car p) 0))
		  (if (equal (buffer-substring (aref (car p) 2)
					       (aref (car p) 3))
			     (aref (car p) 6))
		      (let ((calc-embedded-info nil))
			(or calc-embedded-quiet
			    (message "Recomputing..."))
			(setq first nil)
			(calc-wrapper
			 (set-buffer (aref (car p) 0))
			 (calc-embedded-update (car p) 14 t nil)))
		    (setcdr (car bp) (delq (car p) (cdr (car bp))))
		    (message
1370
		     "(Tried to recompute but formula was changed or missing)"))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1371 1372
	    (setq p (cdr p))))
	(setq bp (if buf nil (cdr bp))))
1373
      (or first calc-embedded-quiet (message "")))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1374

Jay Belanger's avatar
Jay Belanger committed
1375 1376
(provide 'calc-embed)

Miles Bader's avatar
Miles Bader committed
1377
;;; arch-tag: 1b8f311e-fba1-40d3-b8c3-1d6f68fd26fc
1378
;;; calc-embed.el ends here