From b1ebcb0f9507e6bb623724ea37982445dd5c9295 Mon Sep 17 00:00:00 2001
From: Alcor <alcor@tilde.club>
Date: Sun, 17 May 2026 22:57:34 +0200
Subject: [PATCH 15/19] optimize reflow() with binary search

---
 window.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)

diff --git a/window.c b/window.c
index 3182a47..afea0be 100644
--- a/window.c
+++ b/window.c
@@ -395,12 +395,22 @@ static void reflow(struct Window *window) {
 		window->thresh, window->unreadSoft
 	);
 	if (!window->scroll || !num) return;
-	for (size_t i = 0; i < BufferCap; ++i) {
-		line = bufferHard(window->buffer, i);
-		if (!line || line->num != num) continue;
-		scrollTo(window, BufferCap - i);
-		break;
+	/* binary search for num */
+	int low = 0;
+	int high = BufferCap;
+	int i = -1;
+	while (low < high) {
+		int mid = low + (high - low) / 2;
+		const struct Line *line = bufferHard(window->buffer, mid);
+		if (!line || line->num < num) {
+			low = mid + 1;
+		} else if (line->num > num) {
+			high = mid;
+		} else {
+			i = high = mid;
+		}
 	}
+	if (i >= 0) scrollTo(window, BufferCap - i);
 }
 
 void windowResize(void) {
-- 
2.47.3

