   (with-current-buffer (find-file-noselect file)
     (let* ((start (1+ (cdr (assq 'start data))))
            (cx-start (- start (cdr (assq 'contextOffset data))))
-           (cx (cdr (assq 'context data))))
-      (if (equal (buffer-substring-no-properties cx-start (+ cx-start (length cx))) cx)
+           (cx (cdr (assq 'context data)))
+           (cx-end (+ cx-start (length cx))))
+      (if (and (<= (point-max) cx-end) (equal (buffer-substring-no-properties cx-start cx-end) cx))
           start
         (let (nearest nearest-dist)
           (save-excursion

            (push change (cdr found))))
    (loop for (file . changes) in per-file do
          (setf changes (sort changes (lambda (a b) (> (cdr (assq 'start a)) (cdr (assq 'start b))))))
          (find-file (concat (tern-project-dir) file))
          (loop for change in changes do
                (let ((start (1+ (cdr (assq 'start change))))
                      (end (1+ (cdr (assq 'end change)))))

      (return (funcall c tern-known-port)))
    (unless (buffer-file-name)
      (return (funcall c nil)))
    (let ((port-file (expand-file-name ".tern-port" (tern-project-dir))))
      (when (file-exists-p port-file)
        (let ((port (string-to-number (with-temp-buffer
                                        (insert-file-contents port-file)
