[gopls-release-branch.0.3] internal/lsp: ignore irrelevant on-disk changes

Change-Id: Ibdceadbfc822a64066d9370eefa9ff5f7988d0a2
Reviewed-on: https://go-review.googlesource.com/c/tools/+/219202
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
(cherry picked from commit 6dd6151793f7ca4e4c7e87d7f2f5363f2615a446)
Reviewed-on: https://go-review.googlesource.com/c/tools/+/219221
diff --git a/internal/lsp/cache/view.go b/internal/lsp/cache/view.go
index ee1b3e9..9dbbdf1 100644
--- a/internal/lsp/cache/view.go
+++ b/internal/lsp/cache/view.go
@@ -425,16 +425,23 @@
 }
 
 func (v *view) relevantChange(c source.FileModification) bool {
-	if v.contains(c.URI) {
-		return true
-	}
+	// If the file is known to the view, the change is relevant.
+	known := v.knownFile(c.URI)
 
-	// Check if the view is already aware of this file.
-	// If so, the change is relevant.
+	// If the file is not known to the view, and the change is only on-disk,
+	// we should not invalidate the snapshot. This is necessary because Emacs
+	// sends didChangeWatchedFiles events for temp files.
+	if !known && c.OnDisk && (c.Action == source.Change || c.Action == source.Delete) {
+		return false
+	}
+	return v.contains(c.URI) || known
+}
+
+func (v *view) knownFile(uri span.URI) bool {
 	v.mu.Lock()
 	defer v.mu.Unlock()
 
-	f, err := v.findFile(c.URI)
+	f, err := v.findFile(uri)
 	return f != nil && err == nil
 }