 
 (defun tern-find-definition ()
   (interactive)
-  (tern-run-request (lambda (data _offset)
+  (tern-run-query (lambda (data _offset)
                       (push (cons (buffer-file-name) (point)) tern-find-definition-stack)
                       (let ((too-long (nthcdr 20 tern-find-definition-stack)))
                         (when too-long (setf (cdr too-long) nil)))

    (when files (push `(files . ,(apply #'vector files)) doc))
    (push `(file . ,file-name) (cdr (assq 'query doc)))
    (push `(end . ,(1- pos)) (cdr (assq 'query doc)))
    (setf callback
          (lambda (port)
            (if port
                (tern-req port doc runner)
              (message "Could not find a Tern server"))))
    (setf runner
          (lambda (err data)
            (when (< tern-activity-since-command generation)
              (with-current-buffer buffer
                (cond ((not err)
                       (dolist (file files)
                         (when (equal (cdr (assq 'type file)) "full")
                           (with-current-buffer (find-file-noselect (concat tern-project-dir (cdr (assq 'name file))))
                             (setf tern-buffer-is-dirty nil))))
                       (funcall f data offset))
                      ((and (eq (cadar err) 'connection-failed) (not retrying))
                       (setf retrying t)
                       (let ((old-port tern-known-port))
                         (setf tern-known-port nil)
                         (tern-find-server callback old-port)))
                      ((not (eq mode :silent)) (message "Request failed: %s" (cdr err))))))))
    (tern-find-server callback)))

;; Completion

(defun tern-completion-at-point ()
  (or (tern-completion-matches-last)
      (lambda ()
        (tern-run-request #'tern-do-complete "completions" (point)))))

(defun tern-do-complete (data offset)
  (let ((cs (loop for elt across (cdr (assq 'completions data)) collect elt))

  (set (make-local-variable 'tern-buffer-is-dirty) (buffer-modified-p))
  (make-local-variable 'completion-at-point-functions)
  (push 'tern-completion-at-point completion-at-point-functions)
  (add-hook 'after-change-functions 'tern-after-change nil t)
  (add-hook 'post-command-hook 'tern-post-command nil t)
  (add-hook 'buffer-list-update-hook 'tern-left-buffer nil t))

(defun tern-mode-disable ()
  (setf completion-at-point-functions
        (remove 'tern-completion-at-point completion-at-point-functions))
  (remove-hook 'after-change-functions 'tern-after-change t)
  (remove-hook 'post-command-hook 'tern-post-command t)
  (remove-hook 'buffer-list-update-hook 'tern-left-buffer t))

(provide 'tern)
