   (interactive "r")
   (let ((filename (sw::file-to-specware-unit-id buffer-file-name))
 	(text (buffer-substring beg end)))
-    (simulate-input-expression (concat ":swe-spec " filename))
-    (sleep-for 0.1)
+    (when (buffer-modified-p)
+      (sw:gcl-current-file)
+      (sleep-for 1))			; Give :swll a chance to finish
+    (unless (string-equal filename
+			  (sw:eval-in-lisp "cl-user::*current-swe-spec*"))
+      (simulate-input-expression (concat ":swe-spec " filename))
+      (sleep-for 0.1))
     (simulate-input-expression (concat ":swe " text))))
 
 (defun sw:set-swe-spec ()

    (simulate-input-expression (concat ":sw " filename))))

(defun sw::file-to-specware-unit-id (filename)
  (when (eq (elt filename 1) ?:)
    (setq filename (substring filename 2)))
  (let ((len (length filename)))
    (when (equal ".sw" (substring filename (- len 3)))
      (setq filename (substring filename 0 (- len 3))))
    (setq filename (sw::normalize-filename filename))
    (name-relative-to-swpath filename)))

(defun sw::normalize-filename (filename)
  (setq filename (replace-in-string filename "\\\\" "/"))

  (define-key map "\C-cp"    'sw:process-current-file)
  (define-key map "\C-c\C-p" 'sw:process-unit)
  (define-key map "\C-c\g"   'sw:generate-lisp)
  (define-key map "\C-c\C-l" ' sw:gcl-current-file)
  (define-key map "\C-c\C-e" 'sw:evaluate-region)
  (define-key map "\C-c\C-s" 'sw:set-swe-spec)
  (define-key map "\C-c\C-u" 'sw:cl-unit)
