   (setf tern-last-file-name (buffer-file-name))
   tern-project-dir)
 
+(defun tern-known-port ()
+  ;; Invalidate the port when the project directory changes, since a new
+  ;; directory may yield a new .tern-port file.
+  (if (equal tern-last-project-dir (tern-project-dir))
+      tern-known-port
+    (setf tern-last-project-dir (tern-project-dir)
+          tern-known-port nil)))
+
 (defun tern-find-server (c &optional ignore-port)
   (cl-block nil
-    (when tern-known-port
-      (cl-return (if (consp tern-known-port)
-                     (funcall c nil (cdr tern-known-port))
-                   (funcall c tern-known-port nil))))
+    (when (tern-known-port)
+      (cl-return (if (consp (tern-known-port))
+                     (funcall c nil (cdr (tern-known-port)))
+                   (funcall c (tern-known-port) nil))))
     (if tern-explicit-port
         (funcall c tern-explicit-port nil)
       (unless (buffer-file-name)

                                 (run-at-time "30 sec" nil
                                              (lambda (buf)
                                                (with-current-buffer buf
                                                  (when (consp tern-known-port) (setf tern-known-port nil))))
                                              (current-buffer))
                                 (funcall c nil tern-known-port)))
    (set-process-filter proc (lambda (proc output)
                               (if (not (string-match "Listening on port \\([0-9][0-9]*\\)" output))
                                   (setf all-output (concat all-output output))

  (set (make-local-variable 'tern-explicit-port) nil)
  (set (make-local-variable 'tern-project-dir) nil)
  (set (make-local-variable 'tern-last-file-name) nil)
  (set (make-local-variable 'tern-last-project-dir) nil)
  (set (make-local-variable 'tern-last-point-pos) nil)
  (set (make-local-variable 'tern-last-completions) nil)
  (set (make-local-variable 'tern-last-argument-hints) nil)
