From a8930997f03445f9277444df63ddd61172b35424 Mon Sep 17 00:00:00 2001 From: Ben Wiederhake Date: Fri, 15 Oct 2021 00:05:19 +0200 Subject: [PATCH] LibGUI: Make Ctrl-Right at the end of a span work There used to be the silly bug that when the cursor was already at the end of a span (e.g. because the user just pressed Ctrl-Right), then Ctrl-Right had no effect. This bug does not appear with Ctrl-Left because due to the order in which the spans are iterated, the effective result is always correct. This patch also makes it more apparent that the algorithm is unnecessarily inefficient. --- Userland/Libraries/LibGUI/TextDocument.cpp | 26 +++++++++++++++------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/Userland/Libraries/LibGUI/TextDocument.cpp b/Userland/Libraries/LibGUI/TextDocument.cpp index c5fd0d79e9..832220a172 100644 --- a/Userland/Libraries/LibGUI/TextDocument.cpp +++ b/Userland/Libraries/LibGUI/TextDocument.cpp @@ -616,15 +616,25 @@ Optional TextDocument::first_non_skippable_span_before(const T Optional TextDocument::first_non_skippable_span_after(const TextPosition& position) const { - for (size_t i = 0; i < m_spans.size(); ++i) { - if (!m_spans[i].range.contains(position)) - continue; - while ((i + 1) < m_spans.size() && m_spans[i + 1].is_skippable) - ++i; - if (i >= (m_spans.size() - 1)) - return {}; - return m_spans[i + 1]; + size_t i = 0; + // Find the first span containing the cursor + for (; i < m_spans.size(); ++i) { + if (m_spans[i].range.contains(position)) + break; } + // Find the first span *after* the cursor + // TODO: For a large number of spans, binary search would be faster. + for (; i < m_spans.size(); ++i) { + if (!m_spans[i].range.contains(position)) + break; + } + // Skip skippable spans + for (; i < m_spans.size(); ++i) { + if (m_spans[i].is_skippable) + break; + } + if (i < m_spans.size()) + return m_spans[i + 1]; return {}; }