diff --git a/src/backend/tsearch/wparser_def.c b/src/backend/tsearch/wparser_def.c
index aa4271a..2f84259 100644
--- a/src/backend/tsearch/wparser_def.c
+++ b/src/backend/tsearch/wparser_def.c
@@ -2319,11 +2319,12 @@ mark_hl_words(HeadlineParsedText *prs, TSQuery query, int highlight,
 	int			bestb = -1,
 				beste = -1;
 	int			bestlen = -1;
+	bool		bestcover = false;
 	int			pose,
 				posb,
 				poslen,
 				curlen;
-
+	bool		poscover;
 	int			i;
 
 	if (highlight == 0)
@@ -2413,18 +2414,27 @@ mark_hl_words(HeadlineParsedText *prs, TSQuery query, int highlight,
 			}
 
 			/*
-			 * Adopt this headline if it's the first, or if it has more
-			 * interesting words and isn't ending at a bad endpoint, or if it
-			 * replaces a bad endpoint with a good one (XXX even if it has
-			 * fewer interesting words?  Really?)
+			 * Check whether the proposed headline includes the original
+			 * cover; it might not if we trimmed it due to max_words.
+			 */
+			poscover = (posb <= p && pose >= q);
+
+			/*
+			 * Adopt this headline if it's better than the last one, giving
+			 * highest priority to headlines including the cover, then to
+			 * headlines with more interesting words, then to headlines with
+			 * good stopping points.  (Since bestlen is initially -1, we will
+			 * certainly adopt the first headline.)
 			 */
-			if (bestlen < 0 ||
-				(poslen > bestlen && !BADENDPOINT(pose)) ||
-				(!BADENDPOINT(pose) && BADENDPOINT(beste)))
+			if (poscover > bestcover ||
+				(poscover == bestcover && poslen > bestlen) ||
+				(poscover == bestcover && poslen == bestlen &&
+				 !BADENDPOINT(pose) && BADENDPOINT(beste)))
 			{
 				bestb = posb;
 				beste = pose;
 				bestlen = poslen;
+				bestcover = poscover;
 			}
 
 			p++;
