From b631faa26e537914b706fad6dec8fe0d7cc27fe3 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:24:00 +0100 Subject: [PATCH 01/14] chore(example): update the Podfile lock to 0.1.11 --- example/ios/Podfile.lock | 88 ++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 4ff2c28..08d3cda 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -1,7 +1,7 @@ PODS: - - Codepad (0.1.10): - - Codepad/Core (= 0.1.10) - - Codepad/TreeSitter (= 0.1.10) + - Codepad (0.1.11): + - Codepad/Core (= 0.1.11) + - Codepad/TreeSitter (= 0.1.11) - hermes-engine - NitroModules - RCTRequired @@ -25,7 +25,7 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - Codepad/Core (0.1.10): + - Codepad/Core (0.1.11): - hermes-engine - NitroModules - RCTRequired @@ -49,7 +49,7 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - Codepad/TreeSitter (0.1.10): + - Codepad/TreeSitter (0.1.11): - hermes-engine - NitroModules - RCTRequired @@ -73,45 +73,45 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - CodepadLangC (0.1.10): + - CodepadLangC (0.1.11): - Codepad - - CodepadLangCss (0.1.10): + - CodepadLangCss (0.1.11): - Codepad - - CodepadLangGo (0.1.10): + - CodepadLangGo (0.1.11): - Codepad - - CodepadLangHtml (0.1.10): + - CodepadLangHtml (0.1.11): - Codepad - - CodepadLangIni (0.1.10): + - CodepadLangIni (0.1.11): - Codepad - - CodepadLangJava (0.1.10): + - CodepadLangJava (0.1.11): - Codepad - - CodepadLangJavascript (0.1.10): + - CodepadLangJavascript (0.1.11): - Codepad - - CodepadLangJson (0.1.10): + - CodepadLangJson (0.1.11): - Codepad - - CodepadLangKotlin (0.1.10): + - CodepadLangKotlin (0.1.11): - Codepad - CodepadLangKvLite (1.0.0): - Codepad - - CodepadLangMarkdown (0.1.10): + - CodepadLangMarkdown (0.1.11): - Codepad - - CodepadLangPhp (0.1.10): + - CodepadLangPhp (0.1.11): - Codepad - - CodepadLangPython (0.1.10): + - CodepadLangPython (0.1.11): - Codepad - - CodepadLangRust (0.1.10): + - CodepadLangRust (0.1.11): - Codepad - - CodepadLangSql (0.1.10): + - CodepadLangSql (0.1.11): - Codepad - - CodepadLangSwift (0.1.10): + - CodepadLangSwift (0.1.11): - Codepad - - CodepadLangTsx (0.1.10): + - CodepadLangTsx (0.1.11): - Codepad - - CodepadLangTypescript (0.1.10): + - CodepadLangTypescript (0.1.11): - Codepad - - CodepadLangXml (0.1.10): + - CodepadLangXml (0.1.11): - Codepad - - CodepadLangYaml (0.1.10): + - CodepadLangYaml (0.1.11): - Codepad - EXConstants (57.0.22): - ExpoModulesCore @@ -2679,27 +2679,27 @@ EXTERNAL SOURCES: :path: "../node_modules/react-native/ReactCommon/yoga" SPEC CHECKSUMS: - Codepad: be9c515420bb5d080a7d97aa43a4f78488df0276 - CodepadLangC: e918e5efa94718d3072a2cfbcde5aa78d56ec5ac - CodepadLangCss: 89a9d02af97f5f89f92cc18932a315bb26a47654 - CodepadLangGo: c35773dd80d618ac404223896774957ecd849134 - CodepadLangHtml: abb387f12be8ed8aa8671bddf5eec0c4fb3d0c05 - CodepadLangIni: 303ffdea4421bfb153ed1538a1f571f2072cfd94 - CodepadLangJava: b0b86325c2325eb831ed22d949a4081da64805f7 - CodepadLangJavascript: af1f3035769f3b4938f6ef9254e8d9f547766cda - CodepadLangJson: 0723a0d9c1b5294aec9a59dae36277d52d6faa3a - CodepadLangKotlin: 3e18e799bf41571666a342f3066ffb5159d15e51 + Codepad: 1a8dc9d9ddacaca0e38d1656e688d3a8979d9c97 + CodepadLangC: f8eff5fd6f04e4503068f9c47fbae80bc9fc683e + CodepadLangCss: e9b2702687f29ab51e7ea6528622d72119a726f0 + CodepadLangGo: 0c3b1544a5f32c20e6aa454d3c869bbb319396e9 + CodepadLangHtml: a5ec238a1848dfbc37f9e5eb75b82aa1bf805b18 + CodepadLangIni: 193ddc03fc5d553274fe8bede039cb42526eb374 + CodepadLangJava: 19b2a11e10bae811e2e527c85838b50f89a11779 + CodepadLangJavascript: 0d8e542b6864d3f0421f0e19ef00ab0b4809de79 + CodepadLangJson: b74bcf918666ded7c5fb12108a0fbf4aa16aae28 + CodepadLangKotlin: ea983d03548e29da8351f7a1c6f37960936a3015 CodepadLangKvLite: 9253cabc0ae1762339d0d732631ee140a7dbd173 - CodepadLangMarkdown: 2649a34a3f98b0e456317fe9b04ecf31f8c5f999 - CodepadLangPhp: b5d9a91c6bf067dba508821ae9b922c394b0c1a4 - CodepadLangPython: 17d7787e07844c404aedb322c9e25d5263ceb9dd - CodepadLangRust: de1890b1899b57813927531820f0f7808df8952a - CodepadLangSql: 941eb8ad8b5590a0050cc10f2c9a31cc89031696 - CodepadLangSwift: d9066d58690b0cad9b7c0a80ff268160a8330c1b - CodepadLangTsx: e07c416da04dcda466c54025d433c2beb7b863d8 - CodepadLangTypescript: 2267726874223138f267a04d7231bcfc52c7cb0b - CodepadLangXml: 11131a1d0b4fd8de36144c2e3a3ea8f9c656918e - CodepadLangYaml: 969e6d3a1726343194610f7e69a850c0ca9c1b2a + CodepadLangMarkdown: ed7be832a191c01a39b4cfececf7cc8063b998b3 + CodepadLangPhp: fc9a9fe641f3bd62ac4890299a1fad73feaa0696 + CodepadLangPython: b8117e5ded6779c546b7cca3b7eb0f6ad899b9f3 + CodepadLangRust: 1d29435dda0121e00122c6b41e5f327b02e6607c + CodepadLangSql: ee9170a1513a18b721ea064fd6568f01080b3f24 + CodepadLangSwift: 3a58ea2ff88c875dd2b657de60e0b2176aed0214 + CodepadLangTsx: f11c0d268d7f741cd6a845f1612592b7b05c780d + CodepadLangTypescript: 0e7f2d9257725bb3c2b3f3fc9d6f0b234b52fbbf + CodepadLangXml: 8ab738b2632843b8b834102802973eb93dca0a3d + CodepadLangYaml: 09e462e77dcd9493795bd9fa0245b31759a8780a EXConstants: 8a0eb5e2553569c0e6710b73a8d90d1ce358c153 Expo: 83ceec8498d39a83bfcdf6ad56118bc6c5c81c72 ExpoAsset: 2581425f9b581b4fce3c83ffc9f28528d1c4ee68 From 3b7e9ead84a09917be5fb9eb5bb43f3e7a78aab0 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:45:05 +0100 Subject: [PATCH 02/14] feat: tell setSearch callers when a regex stopped at the match limit A regex that backtracks past PCRE2's match limit keeps the matches found before that point, and the count looked complete. setSearch now resolves with { count, limited }, so a search bar can show the count as partial. The worker carries the flag into the core with its matches. --- android/src/main/cpp/core_jni.cpp | 6 +- .../nitro/codepad/HybridCodeEditorView.kt | 4 +- .../me/sectiontn/codepad/core/EditorCore.kt | 6 +- .../me/sectiontn/codepad/syntax/CoreNative.kt | 3 +- .../sectiontn/codepad/view/CodeEditorView.kt | 1 + .../codepad/view/SearchController.kt | 8 +- .../me/sectiontn/codepad/core/VectorRunner.kt | 1 + .../codepad/view/SearchControllerTest.kt | 11 +++ cpp/core/include/codepad.h | 8 +- cpp/core/src/capi_editor.cpp | 7 +- cpp/core/src/editor.cpp | 4 +- cpp/core/src/editor.hpp | 3 +- cpp/core/src/search.hpp | 2 + ios/Codepad/core/EditorCore.swift | 8 +- ios/Codepad/nitro/HybridCodeEditorView.swift | 6 +- ios/Codepad/syntax/SearchController.swift | 12 ++- ios/Codepad/view/CodeEditorView.swift | 1 + .../android/c++/JHybridCodeEditorViewSpec.cpp | 12 ++- .../android/c++/JHybridCodeEditorViewSpec.hpp | 2 +- .../android/c++/JNativeSearchResult.hpp | 61 ++++++++++++ .../nitro/codepad/HybridCodeEditorViewSpec.kt | 2 +- .../nitro/codepad/NativeSearchResult.kt | 56 +++++++++++ .../ios/Codepad-Swift-Cxx-Bridge.cpp | 16 +++- .../ios/Codepad-Swift-Cxx-Bridge.hpp | 94 ++++++++++++++----- .../ios/Codepad-Swift-Cxx-Umbrella.hpp | 3 + .../ios/c++/HybridCodeEditorViewSpecSwift.hpp | 5 +- .../swift/Func_void_NativeSearchResult.swift | 46 +++++++++ .../ios/swift/HybridCodeEditorViewSpec.swift | 2 +- .../swift/HybridCodeEditorViewSpec_cxx.swift | 12 +-- .../ios/swift/NativeSearchResult.swift | 34 +++++++ .../shared/c++/HybridCodeEditorViewSpec.hpp | 5 +- .../shared/c++/NativeSearchResult.hpp | 87 +++++++++++++++++ src/CodeEditor.tsx | 4 +- src/__tests__/CodeEditor.test.tsx | 6 +- src/specs/CodeEditorView.nitro.ts | 8 +- src/types.ts | 7 +- tests/swift/SearchControllerTests.swift | 10 ++ tests/swift/VectorRunner.swift | 1 + tests/vectors/search.json | 1 + website/docs/guides/search.md | 4 +- website/docs/reference/methods.md | 2 +- 41 files changed, 493 insertions(+), 78 deletions(-) create mode 100644 nitrogen/generated/android/c++/JNativeSearchResult.hpp create mode 100644 nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/NativeSearchResult.kt create mode 100644 nitrogen/generated/ios/swift/Func_void_NativeSearchResult.swift create mode 100644 nitrogen/generated/ios/swift/NativeSearchResult.swift create mode 100644 nitrogen/generated/shared/c++/NativeSearchResult.hpp diff --git a/android/src/main/cpp/core_jni.cpp b/android/src/main/cpp/core_jni.cpp index a6a5f6c..f1754b9 100644 --- a/android/src/main/cpp/core_jni.cpp +++ b/android/src/main/cpp/core_jni.cpp @@ -502,6 +502,7 @@ FN(editorSearchActive)(JNIEnv *, jclass, jlong editor) -> jboolean { FN(editorSearchStale)(JNIEnv *, jclass, jlong editor) -> jboolean { return cp_editor_search_stale(ed(editor)) != 0; } FN(editorMatchCount)(JNIEnv *, jclass, jlong editor) -> jint { return cp_editor_match_count(ed(editor)); } +FN(editorMatchLimited)(JNIEnv *, jclass, jlong editor) -> jboolean { return cp_editor_match_limited(ed(editor)) != 0; } FN(editorMatches)(JNIEnv *e, jclass, jlong editor) -> jintArray { uint32_t n = cp_editor_matches(ed(editor), nullptr, 0); @@ -527,11 +528,12 @@ FN(editorReplaceAll)(JNIEnv *e, jclass, jlong editor, jstring text) -> jint { return cp_editor_replace_all(ed(editor), units_of(s), count_of(s)); } -FN(editorAcceptMatches)(JNIEnv *e, jclass, jlong editor, jint revision, jintArray pairs) -> jboolean { +FN(editorAcceptMatches)(JNIEnv *e, jclass, jlong editor, jint revision, jintArray pairs, jboolean limited) + -> jboolean { jsize n = e->GetArrayLength(pairs); std::vector in(static_cast(n)); if (n > 0) e->GetIntArrayRegion(pairs, 0, n, reinterpret_cast(in.data())); - return cp_editor_accept_matches(ed(editor), revision, in.data(), static_cast(n)) != 0; + return cp_editor_accept_matches(ed(editor), revision, in.data(), static_cast(n), limited ? 1 : 0) != 0; } FN(editorSearchQuery)(JNIEnv *, jclass, jlong editor) -> jlong { return handle(cp_editor_search_query(ed(editor))); } diff --git a/android/src/main/java/com/margelo/nitro/codepad/HybridCodeEditorView.kt b/android/src/main/java/com/margelo/nitro/codepad/HybridCodeEditorView.kt index 9f54790..f3c7d7d 100644 --- a/android/src/main/java/com/margelo/nitro/codepad/HybridCodeEditorView.kt +++ b/android/src/main/java/com/margelo/nitro/codepad/HybridCodeEditorView.kt @@ -358,9 +358,9 @@ class HybridCodeEditorView(val context: ThemedReactContext) : HybridCodeEditorVi override fun paste(): Promise = onMain { editor.paste(ChangeOrigin.Api) } - override fun setSearch(query: NativeSearchQuery): Promise = deferred { promise -> + override fun setSearch(query: NativeSearchQuery): Promise = deferred { promise -> editor.setSearch(SearchQuery(query.text, query.regex, query.caseSensitive, query.wholeWord)) - editor.whenSearchFresh { promise.resolve(editor.matchCount.toDouble()) } + editor.whenSearchFresh { promise.resolve(NativeSearchResult(editor.matchCount.toDouble(), editor.matchLimited)) } } override fun findNext(): Promise = deferred { promise -> diff --git a/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt b/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt index b81f742..1e59f32 100644 --- a/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt +++ b/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt @@ -159,6 +159,9 @@ class EditorCore(initialText: String = "", clock: (() -> Long)? = null) : AutoCl val matches: IntArray get() = CoreNative.editorMatches(handle()) val matchCount: Int get() = CoreNative.editorMatchCount(handle()) + /** True when a match attempt hit PCRE2's match limit, so the matches stop there. */ + val matchLimited: Boolean get() = CoreNative.editorMatchLimited(handle()) + /** True while a query is active and its matches belong to an older revision. */ val searchStale: Boolean get() = CoreNative.editorSearchStale(handle()) @@ -188,7 +191,8 @@ class EditorCore(initialText: String = "", clock: (() -> Long)? = null) : AutoCl fun textSnapshot(): Long = CoreNative.editorText(handle()) /** Stores matches computed elsewhere. False when the document moved on since [revision]. */ - fun acceptMatches(revision: Int, matches: IntArray): Boolean = CoreNative.editorAcceptMatches(handle(), revision, matches) + fun acceptMatches(revision: Int, matches: IntArray, limited: Boolean): Boolean = + CoreNative.editorAcceptMatches(handle(), revision, matches, limited) fun findNext(): SearchHit? = find(true) diff --git a/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt b/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt index 11b521c..b1a3a60 100644 --- a/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt +++ b/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt @@ -58,11 +58,12 @@ internal object CoreNative { @JvmStatic external fun editorSearchActive(editor: Long): Boolean @JvmStatic external fun editorSearchStale(editor: Long): Boolean @JvmStatic external fun editorMatchCount(editor: Long): Int + @JvmStatic external fun editorMatchLimited(editor: Long): Boolean @JvmStatic external fun editorMatches(editor: Long): IntArray @JvmStatic external fun editorFind(editor: Long, forward: Boolean, out: IntArray): Boolean @JvmStatic external fun editorReplaceCurrent(editor: Long, text: String): Boolean @JvmStatic external fun editorReplaceAll(editor: Long, text: String): Int - @JvmStatic external fun editorAcceptMatches(editor: Long, revision: Int, pairs: IntArray): Boolean + @JvmStatic external fun editorAcceptMatches(editor: Long, revision: Int, pairs: IntArray, limited: Boolean): Boolean @JvmStatic external fun editorSearchQuery(editor: Long): Long @JvmStatic external fun searchRelease(search: Long) @JvmStatic external fun editorText(editor: Long): Long diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index 2bed052..b8d42f2 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -506,6 +506,7 @@ class CodeEditorView(context: Context) : View(context) { fun whenSearchFresh(block: () -> Unit) = search?.whenFresh(block) ?: block() val matchCount: Int get() = core.matchCount + val matchLimited: Boolean get() = core.matchLimited fun findNext(): EditorCore.SearchHit? = core.findNext().also { afterSearchMove() } diff --git a/android/src/main/java/me/sectiontn/codepad/view/SearchController.kt b/android/src/main/java/me/sectiontn/codepad/view/SearchController.kt index f68c1f2..40df556 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/SearchController.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/SearchController.kt @@ -89,12 +89,12 @@ class SearchController( try { val started = System.nanoTime() val result = try { - Searcher.find(text, search) { job.cancelled }.matches + Searcher.find(text, search) { job.cancelled } } catch (e: CancellationException) { return@Runnable } val millis = (System.nanoTime() - started) / 1_000_000 - postToMain(Runnable { deliver(job, revision, result, millis) }) + postToMain(Runnable { deliver(job, revision, result.matches, result.limited, millis) }) } finally { Searcher.release(search) Searcher.releaseText(text) @@ -108,8 +108,8 @@ class SearchController( } } - private fun deliver(job: Job, revision: Int, result: IntArray, millis: Long) { - if (closed || job.generation != generation || !core.acceptMatches(revision, result)) return + private fun deliver(job: Job, revision: Int, result: IntArray, limited: Boolean, millis: Long) { + if (closed || job.generation != generation || !core.acceptMatches(revision, result, limited)) return running = null displayed = result onResult?.invoke(result.size / 2, millis) diff --git a/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt b/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt index d304826..78f8743 100644 --- a/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt +++ b/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt @@ -192,6 +192,7 @@ class VectorRunner(private val case: JSONObject) { } } if (expect.has("result")) assertEquals("result $where", expect.get("result"), lastResult) + if (expect.has("limited")) assertEquals("limited $where", expect.getBoolean("limited"), core.matchLimited) if (expect.has("brackets")) { if (expect.isNull("brackets")) assertNull("brackets $where", lastResult) else { diff --git a/android/src/test/java/me/sectiontn/codepad/view/SearchControllerTest.kt b/android/src/test/java/me/sectiontn/codepad/view/SearchControllerTest.kt index c490ada..8680d74 100644 --- a/android/src/test/java/me/sectiontn/codepad/view/SearchControllerTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/view/SearchControllerTest.kt @@ -123,4 +123,15 @@ class SearchControllerTest { controller.close() assertEquals(queued, executor.size) } + + // setSearch's result reads the limit from the core, so the worker's scan has to bring it there. + @Test + fun aWorkerScanStoppedAtTheMatchLimitReachesTheCore() { + val core = EditorCore("aa\n" + "a".repeat(40) + "b\naaa") + val controller = SearchController(core, { main.add(it) }, executor) + controller.setQuery(SearchQuery("(a+)+$", regex = true)) + settle() + assertEquals(1, core.matchCount) + assertTrue(core.matchLimited) + } } diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h index 006efd3..7560615 100644 --- a/cpp/core/include/codepad.h +++ b/cpp/core/include/codepad.h @@ -258,6 +258,8 @@ CP_API int32_t cp_editor_search_active(const cp_editor *editor); // 1 while a query is active and its matches belong to an older revision. CP_API int32_t cp_editor_search_stale(const cp_editor *editor); CP_API int32_t cp_editor_match_count(const cp_editor *editor); +// 1 when a match attempt hit PCRE2's match limit, so the matches stop there. +CP_API int32_t cp_editor_match_limited(const cp_editor *editor); // The matches as start and end pairs, computed on the calling thread when stale. Returns the ints there are. CP_API uint32_t cp_editor_matches(cp_editor *editor, int32_t *out, uint32_t cap); // Selects the next match, or the previous one when forward is 0. Returns 0 without a match. @@ -265,8 +267,10 @@ CP_API int32_t cp_editor_find(cp_editor *editor, int32_t forward, int32_t *index CP_API int32_t cp_editor_replace_current(cp_editor *editor, const cp_unit *text, uint32_t length); // Returns how many matches were replaced, as one undo step. CP_API int32_t cp_editor_replace_all(cp_editor *editor, const cp_unit *text, uint32_t length); -// Matches computed off the main thread for revision. count is in ints. Returns 0 when the document moved on. -CP_API int32_t cp_editor_accept_matches(cp_editor *editor, int32_t revision, const int32_t *pairs, uint32_t count); +// Matches computed off the main thread for revision, with the scan's limited flag. count is in ints. Returns 0 when +// the document moved on. +CP_API int32_t cp_editor_accept_matches(cp_editor *editor, int32_t revision, const int32_t *pairs, uint32_t count, + int32_t limited); // The compiled query, retained for the caller, or NULL without a search. CP_API cp_search *cp_editor_search_query(cp_editor *editor); // One scan of a query over a text, carried across cp_search_find calls. Start with next 0, or the offset to scan diff --git a/cpp/core/src/capi_editor.cpp b/cpp/core/src/capi_editor.cpp index 56e3220..9c47065 100644 --- a/cpp/core/src/capi_editor.cpp +++ b/cpp/core/src/capi_editor.cpp @@ -181,6 +181,8 @@ int32_t cp_editor_search_stale(const cp_editor *editor) { return editor->search_ int32_t cp_editor_match_count(const cp_editor *editor) { return editor->match_count(); } +int32_t cp_editor_match_limited(const cp_editor *editor) { return editor->match_limited() ? 1 : 0; } + uint32_t cp_editor_matches(cp_editor *editor, int32_t *out, uint32_t cap) { const std::vector &matches = editor->matches(); if (out != nullptr) std::copy_n(matches.begin(), std::min(matches.size(), cap), out); @@ -204,8 +206,9 @@ int32_t cp_editor_replace_all(cp_editor *editor, const cp_unit *text, uint32_t l return editor->replace_all(units(text, length)); } -int32_t cp_editor_accept_matches(cp_editor *editor, int32_t revision, const int32_t *pairs, uint32_t count) { - return editor->accept_matches(revision, pairs, count) ? 1 : 0; +int32_t cp_editor_accept_matches(cp_editor *editor, int32_t revision, const int32_t *pairs, uint32_t count, + int32_t limited) { + return editor->accept_matches(revision, pairs, count, limited != 0) ? 1 : 0; } cp_search *cp_editor_search_query(cp_editor *editor) { diff --git a/cpp/core/src/editor.cpp b/cpp/core/src/editor.cpp index 1f0182c..96d585c 100644 --- a/cpp/core/src/editor.cpp +++ b/cpp/core/src/editor.cpp @@ -395,6 +395,7 @@ void Editor::ensure_matches() { if (!search_ || search_->revision == doc.revision()) return; bool limited = false; search_->matches = search_->search->find_all(doc.text(0, doc.length()), limited); + search_->limited = limited; search_->revision = doc.revision(); } @@ -451,9 +452,10 @@ int32_t Editor::replace_all(std::u16string_view text) { return static_cast(targets.size() / 2); } -bool Editor::accept_matches(int32_t revision, const int32_t *pairs, uint32_t count) { +bool Editor::accept_matches(int32_t revision, const int32_t *pairs, uint32_t count, bool limited) { if (!search_ || revision != doc.revision()) return false; search_->matches.assign(pairs, pairs + count); + search_->limited = limited; search_->revision = revision; return true; } diff --git a/cpp/core/src/editor.hpp b/cpp/core/src/editor.hpp index 05f129c..d1095ed 100644 --- a/cpp/core/src/editor.hpp +++ b/cpp/core/src/editor.hpp @@ -65,13 +65,14 @@ class Editor { bool search_active() const { return search_.has_value(); } bool search_stale() const { return search_ && search_->revision != doc.revision(); } int32_t match_count() const { return search_ ? search_->count() : 0; } + bool match_limited() const { return search_ && search_->limited; } // The matches, computed on the calling thread when stale. const std::vector &matches(); // Selects the next match, or the previous one. False without a match. bool find(bool forward, int32_t &index, int32_t &total); bool replace_current(std::u16string_view text); int32_t replace_all(std::u16string_view text); - bool accept_matches(int32_t revision, const int32_t *pairs, uint32_t count); + bool accept_matches(int32_t revision, const int32_t *pairs, uint32_t count, bool limited); std::shared_ptr search_query() const { return search_ ? search_->search : nullptr; } private: diff --git a/cpp/core/src/search.hpp b/cpp/core/src/search.hpp index bb26e62..871a790 100644 --- a/cpp/core/src/search.hpp +++ b/cpp/core/src/search.hpp @@ -39,6 +39,8 @@ struct SearchSession { std::shared_ptr search; std::vector matches; int32_t revision = -1; + // A match attempt hit PCRE2's match limit, so the matches stop there. + bool limited = false; int32_t count() const { return static_cast(matches.size() / 2); } // The first match starting at or after offset, else count. diff --git a/ios/Codepad/core/EditorCore.swift b/ios/Codepad/core/EditorCore.swift index baa442c..7c25a83 100644 --- a/ios/Codepad/core/EditorCore.swift +++ b/ios/Codepad/core/EditorCore.swift @@ -168,6 +168,9 @@ final class EditorCore: @unchecked Sendable { var matchCount: Int { Int(cp_editor_match_count(document.handle)) } + /// True when a match attempt hit PCRE2's match limit, so the matches stop there. + var matchLimited: Bool { cp_editor_match_limited(document.handle) != 0 } + /// True while a query is active and its matches belong to an older revision. var searchStale: Bool { cp_editor_search_stale(document.handle) != 0 } @@ -209,10 +212,11 @@ final class EditorCore: @unchecked Sendable { } /// Stores matches computed elsewhere. False when the document moved on since `revision`. - func acceptMatches(revision: Int, matches: [Int]) -> Bool { + func acceptMatches(revision: Int, matches: [Int], limited: Bool) -> Bool { let pairs = matches.map { Int32(clamping: $0) } return pairs.withUnsafeBufferPointer { - cp_editor_accept_matches(document.handle, Int32(clamping: revision), $0.baseAddress, UInt32($0.count)) + cp_editor_accept_matches( + document.handle, Int32(clamping: revision), $0.baseAddress, UInt32($0.count), limited ? 1 : 0) } != 0 } diff --git a/ios/Codepad/nitro/HybridCodeEditorView.swift b/ios/Codepad/nitro/HybridCodeEditorView.swift index 2869567..6ad6620 100644 --- a/ios/Codepad/nitro/HybridCodeEditorView.swift +++ b/ios/Codepad/nitro/HybridCodeEditorView.swift @@ -350,11 +350,13 @@ final class HybridCodeEditorView: HybridCodeEditorViewSpec, @unchecked Sendable // Search methods resolve once the worker's results match the document. - func setSearch(query: NativeSearchQuery) throws -> Promise { + func setSearch(query: NativeSearchQuery) throws -> Promise { let q = SearchQuery(text: query.text, regex: query.regex, caseSensitive: query.caseSensitive, wholeWord: query.wholeWord) return deferred { editor, promise in try editor.setSearch(q) - editor.whenSearchFresh { promise.resolve(withResult: Double(editor.matchCount)) } + editor.whenSearchFresh { + promise.resolve(withResult: NativeSearchResult(count: Double(editor.matchCount), limited: editor.matchLimited)) + } } } diff --git a/ios/Codepad/syntax/SearchController.swift b/ios/Codepad/syntax/SearchController.swift index 06f5518..1c4dc4f 100644 --- a/ios/Codepad/syntax/SearchController.swift +++ b/ios/Codepad/syntax/SearchController.swift @@ -89,18 +89,22 @@ final class SearchController: @unchecked Sendable { queue.async { [self] in let started = DispatchTime.now().uptimeNanoseconds let result: [Int] + let limited: Bool do { - result = try Searcher.find(text, search) { job.cancelled }.matches + let found = try Searcher.find(text, search) { job.cancelled } + result = found.matches + limited = found.limited } catch { return } let millis = Int64((DispatchTime.now().uptimeNanoseconds - started) / 1_000_000) - postToMain { self.deliver(job, revision: revision, result: result, millis: millis) } + postToMain { self.deliver(job, revision: revision, result: result, limited: limited, millis: millis) } } } - private func deliver(_ job: Job, revision: Int, result: [Int], millis: Int64) { - if closed || job.generation != generation || !core.acceptMatches(revision: revision, matches: result) { return } + private func deliver(_ job: Job, revision: Int, result: [Int], limited: Bool, millis: Int64) { + if closed || job.generation != generation { return } + if !core.acceptMatches(revision: revision, matches: result, limited: limited) { return } running = nil displayed = result onResult?(result.count / 2, millis) diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 92c6af1..d11e0a7 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -458,6 +458,7 @@ final class CodeEditorView: UIScrollView { } var matchCount: Int { core.matchCount } + var matchLimited: Bool { core.matchLimited } func findNext() -> EditorCore.SearchHit? { let hit = core.findNext() diff --git a/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.cpp b/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.cpp index 1eaecf3..460b0d7 100644 --- a/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.cpp +++ b/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.cpp @@ -39,6 +39,8 @@ namespace margelo::nitro::codepad { struct NativeRect; } namespace margelo::nitro::codepad { struct NativePosition; } // Forward declaration of `NativeVisibleLines` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeVisibleLines; } +// Forward declaration of `NativeSearchResult` to properly resolve imports. +namespace margelo::nitro::codepad { struct NativeSearchResult; } // Forward declaration of `NativeSearchHit` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeSearchHit; } // Forward declaration of `NativeSearchQuery` to properly resolve imports. @@ -94,6 +96,8 @@ namespace margelo::nitro::codepad { enum class NativeCaretDirection; } #include #include #include +#include "NativeSearchResult.hpp" +#include "JNativeSearchResult.hpp" #include "NativeSearchHit.hpp" #include "JNativeSearchHit.hpp" #include "NativeSearchQuery.hpp" @@ -835,14 +839,14 @@ namespace margelo::nitro::codepad { return __promise; }(); } - std::shared_ptr> JHybridCodeEditorViewSpec::setSearch(const NativeSearchQuery& query) { + std::shared_ptr> JHybridCodeEditorViewSpec::setSearch(const NativeSearchQuery& query) { static const auto method = _javaPart->javaClassStatic()->getMethod(jni::alias_ref /* query */)>("setSearch"); auto __result = method(_javaPart, JNativeSearchQuery::fromCpp(query)); return [&]() { - auto __promise = Promise::create(); + auto __promise = Promise::create(); __result->cthis()->addOnResolvedListener([=](const jni::alias_ref& __boxedResult) { - auto __result = jni::static_ref_cast(__boxedResult); - __promise->resolve(__result->value()); + auto __result = jni::static_ref_cast(__boxedResult); + __promise->resolve(__result->toCpp()); }); __result->cthis()->addOnRejectedListener([=](const jni::alias_ref& __throwable) { jni::JniException __jniError(__throwable); diff --git a/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.hpp b/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.hpp index 5e970b8..7a766bb 100644 --- a/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.hpp +++ b/nitrogen/generated/android/c++/JHybridCodeEditorViewSpec.hpp @@ -150,7 +150,7 @@ namespace margelo::nitro::codepad { std::shared_ptr> paste() override; std::shared_ptr> focus() override; std::shared_ptr> blur() override; - std::shared_ptr> setSearch(const NativeSearchQuery& query) override; + std::shared_ptr> setSearch(const NativeSearchQuery& query) override; std::shared_ptr> findNext() override; std::shared_ptr> findPrevious() override; std::shared_ptr> replaceCurrent(const std::string& text) override; diff --git a/nitrogen/generated/android/c++/JNativeSearchResult.hpp b/nitrogen/generated/android/c++/JNativeSearchResult.hpp new file mode 100644 index 0000000..ab1db42 --- /dev/null +++ b/nitrogen/generated/android/c++/JNativeSearchResult.hpp @@ -0,0 +1,61 @@ +/// +/// JNativeSearchResult.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include "NativeSearchResult.hpp" + + + +namespace margelo::nitro::codepad { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ struct "NativeSearchResult" and the Kotlin data class "NativeSearchResult". + */ + struct JNativeSearchResult final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/codepad/NativeSearchResult;"; + + public: + /** + * Convert this Java/Kotlin-based struct to the C++ struct NativeSearchResult by copying all values to C++. + */ + [[maybe_unused]] + [[nodiscard]] + NativeSearchResult toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldCount = clazz->getField("count"); + double count = this->getFieldValue(fieldCount); + static const auto fieldLimited = clazz->getField("limited"); + jboolean limited = this->getFieldValue(fieldLimited); + return NativeSearchResult( + count, + static_cast(limited) + ); + } + + public: + /** + * Create a Java/Kotlin-based struct by copying all values from the given C++ struct to Java. + */ + [[maybe_unused]] + static jni::local_ref fromCpp(const NativeSearchResult& value) { + using JSignature = JNativeSearchResult(double, jboolean); + static const auto clazz = javaClassStatic(); + static const auto create = clazz->getStaticMethod("fromCpp"); + return create( + clazz, + value.count, + value.limited + ); + } + }; + +} // namespace margelo::nitro::codepad diff --git a/nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/HybridCodeEditorViewSpec.kt b/nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/HybridCodeEditorViewSpec.kt index 1a21053..9859775 100644 --- a/nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/HybridCodeEditorViewSpec.kt +++ b/nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/HybridCodeEditorViewSpec.kt @@ -425,7 +425,7 @@ abstract class HybridCodeEditorViewSpec: HybridView() { @DoNotStrip @Keep - abstract fun setSearch(query: NativeSearchQuery): Promise + abstract fun setSearch(query: NativeSearchQuery): Promise @DoNotStrip @Keep diff --git a/nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/NativeSearchResult.kt b/nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/NativeSearchResult.kt new file mode 100644 index 0000000..e39a8a2 --- /dev/null +++ b/nitrogen/generated/android/kotlin/com/margelo/nitro/codepad/NativeSearchResult.kt @@ -0,0 +1,56 @@ +/// +/// NativeSearchResult.kt +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +package com.margelo.nitro.codepad + +import androidx.annotation.Keep +import com.facebook.proguard.annotations.DoNotStrip +import java.util.Objects + + +/** + * Represents the JavaScript object/struct "NativeSearchResult". + */ +@DoNotStrip +@Keep +data class NativeSearchResult( + @DoNotStrip + @Keep + val count: Double, + @DoNotStrip + @Keep + val limited: Boolean +) { + /* primary constructor */ + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is NativeSearchResult) return false + return Objects.deepEquals(this.count, other.count) + && Objects.deepEquals(this.limited, other.limited) + } + + override fun hashCode(): Int { + return arrayOf( + count, + limited + ).contentDeepHashCode() + } + + companion object { + /** + * Constructor called from C++ + */ + @DoNotStrip + @Keep + @Suppress("unused") + @JvmStatic + private fun fromCpp(count: Double, limited: Boolean): NativeSearchResult { + return NativeSearchResult(count, limited) + } + } +} diff --git a/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.cpp b/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.cpp index d4b3dc8..c1cffe7 100644 --- a/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.cpp +++ b/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.cpp @@ -79,10 +79,10 @@ namespace margelo::nitro::codepad::bridge::swift { }; } - // pragma MARK: std::function - Func_void_double create_Func_void_double(void* NON_NULL swiftClosureWrapper) noexcept { - auto swiftClosure = Codepad::Func_void_double::fromUnsafe(swiftClosureWrapper); - return [swiftClosure = std::move(swiftClosure)](double result) mutable -> void { + // pragma MARK: std::function + Func_void_NativeSearchResult create_Func_void_NativeSearchResult(void* NON_NULL swiftClosureWrapper) noexcept { + auto swiftClosure = Codepad::Func_void_NativeSearchResult::fromUnsafe(swiftClosureWrapper); + return [swiftClosure = std::move(swiftClosure)](const NativeSearchResult& result) mutable -> void { swiftClosure.call(result); }; } @@ -103,6 +103,14 @@ namespace margelo::nitro::codepad::bridge::swift { }; } + // pragma MARK: std::function + Func_void_double create_Func_void_double(void* NON_NULL swiftClosureWrapper) noexcept { + auto swiftClosure = Codepad::Func_void_double::fromUnsafe(swiftClosureWrapper); + return [swiftClosure = std::move(swiftClosure)](double result) mutable -> void { + swiftClosure.call(result); + }; + } + // pragma MARK: std::shared_ptr std::shared_ptr create_std__shared_ptr_HybridCodeEditorViewSpec_(void* NON_NULL swiftUnsafePointer) noexcept { Codepad::HybridCodeEditorViewSpec_cxx swiftPart = Codepad::HybridCodeEditorViewSpec_cxx::fromUnsafe(swiftUnsafePointer); diff --git a/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.hpp b/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.hpp index 704b952..6e3c1c3 100644 --- a/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.hpp +++ b/nitrogen/generated/ios/Codepad-Swift-Cxx-Bridge.hpp @@ -34,6 +34,8 @@ namespace margelo::nitro::codepad { struct NativeRect; } namespace margelo::nitro::codepad { struct NativeScrollEvent; } // Forward declaration of `NativeSearchHit` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeSearchHit; } +// Forward declaration of `NativeSearchResult` to properly resolve imports. +namespace margelo::nitro::codepad { struct NativeSearchResult; } // Forward declaration of `NativeSelection` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeSelection; } // Forward declaration of `NativeSuggestions` to properly resolve imports. @@ -67,6 +69,7 @@ namespace Codepad { class HybridCodepadSpec_cxx; } #include "NativeRect.hpp" #include "NativeScrollEvent.hpp" #include "NativeSearchHit.hpp" +#include "NativeSearchResult.hpp" #include "NativeSelection.hpp" #include "NativeSuggestions.hpp" #include "NativeTheme.hpp" @@ -550,38 +553,38 @@ namespace margelo::nitro::codepad::bridge::swift { return Func_void_std__exception_ptr_Wrapper(std::move(value)); } - // pragma MARK: std::shared_ptr> + // pragma MARK: std::shared_ptr> /** - * Specialized version of `std::shared_ptr>`. + * Specialized version of `std::shared_ptr>`. */ - using std__shared_ptr_Promise_double__ = std::shared_ptr>; - inline std::shared_ptr> create_std__shared_ptr_Promise_double__() noexcept { - return Promise::create(); + using std__shared_ptr_Promise_NativeSearchResult__ = std::shared_ptr>; + inline std::shared_ptr> create_std__shared_ptr_Promise_NativeSearchResult__() noexcept { + return Promise::create(); } - inline PromiseHolder wrap_std__shared_ptr_Promise_double__(std::shared_ptr> promise) noexcept { - return PromiseHolder(std::move(promise)); + inline PromiseHolder wrap_std__shared_ptr_Promise_NativeSearchResult__(std::shared_ptr> promise) noexcept { + return PromiseHolder(std::move(promise)); } - // pragma MARK: std::function + // pragma MARK: std::function /** - * Specialized version of `std::function`. + * Specialized version of `std::function`. */ - using Func_void_double = std::function; + using Func_void_NativeSearchResult = std::function; /** - * Wrapper class for a `std::function`, this can be used from Swift. + * Wrapper class for a `std::function`, this can be used from Swift. */ - class Func_void_double_Wrapper final { + class Func_void_NativeSearchResult_Wrapper final { public: - explicit Func_void_double_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} - inline void call(double result) const noexcept { + explicit Func_void_NativeSearchResult_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} + inline void call(NativeSearchResult result) const noexcept { _function->operator()(result); } private: - std::unique_ptr> _function; + std::unique_ptr> _function; } SWIFT_NONCOPYABLE; - Func_void_double create_Func_void_double(void* NON_NULL swiftClosureWrapper) noexcept; - inline Func_void_double_Wrapper wrap_Func_void_double(Func_void_double value) noexcept { - return Func_void_double_Wrapper(std::move(value)); + Func_void_NativeSearchResult create_Func_void_NativeSearchResult(void* NON_NULL swiftClosureWrapper) noexcept; + inline Func_void_NativeSearchResult_Wrapper wrap_Func_void_NativeSearchResult(Func_void_NativeSearchResult value) noexcept { + return Func_void_NativeSearchResult_Wrapper(std::move(value)); } // pragma MARK: std::shared_ptr> @@ -652,6 +655,40 @@ namespace margelo::nitro::codepad::bridge::swift { return Func_void_bool_Wrapper(std::move(value)); } + // pragma MARK: std::shared_ptr> + /** + * Specialized version of `std::shared_ptr>`. + */ + using std__shared_ptr_Promise_double__ = std::shared_ptr>; + inline std::shared_ptr> create_std__shared_ptr_Promise_double__() noexcept { + return Promise::create(); + } + inline PromiseHolder wrap_std__shared_ptr_Promise_double__(std::shared_ptr> promise) noexcept { + return PromiseHolder(std::move(promise)); + } + + // pragma MARK: std::function + /** + * Specialized version of `std::function`. + */ + using Func_void_double = std::function; + /** + * Wrapper class for a `std::function`, this can be used from Swift. + */ + class Func_void_double_Wrapper final { + public: + explicit Func_void_double_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} + inline void call(double result) const noexcept { + _function->operator()(result); + } + private: + std::unique_ptr> _function; + } SWIFT_NONCOPYABLE; + Func_void_double create_Func_void_double(void* NON_NULL swiftClosureWrapper) noexcept; + inline Func_void_double_Wrapper wrap_Func_void_double(Func_void_double value) noexcept { + return Func_void_double_Wrapper(std::move(value)); + } + // pragma MARK: std::shared_ptr /** * Specialized version of `std::shared_ptr`. @@ -736,13 +773,13 @@ namespace margelo::nitro::codepad::bridge::swift { return Result>>::withError(error); } - // pragma MARK: Result>> - using Result_std__shared_ptr_Promise_double___ = Result>>; - inline Result_std__shared_ptr_Promise_double___ create_Result_std__shared_ptr_Promise_double___(const std::shared_ptr>& value) noexcept { - return Result>>::withValue(value); + // pragma MARK: Result>> + using Result_std__shared_ptr_Promise_NativeSearchResult___ = Result>>; + inline Result_std__shared_ptr_Promise_NativeSearchResult___ create_Result_std__shared_ptr_Promise_NativeSearchResult___(const std::shared_ptr>& value) noexcept { + return Result>>::withValue(value); } - inline Result_std__shared_ptr_Promise_double___ create_Result_std__shared_ptr_Promise_double___(const std::exception_ptr& error) noexcept { - return Result>>::withError(error); + inline Result_std__shared_ptr_Promise_NativeSearchResult___ create_Result_std__shared_ptr_Promise_NativeSearchResult___(const std::exception_ptr& error) noexcept { + return Result>>::withError(error); } // pragma MARK: Result>> @@ -763,6 +800,15 @@ namespace margelo::nitro::codepad::bridge::swift { return Result>>::withError(error); } + // pragma MARK: Result>> + using Result_std__shared_ptr_Promise_double___ = Result>>; + inline Result_std__shared_ptr_Promise_double___ create_Result_std__shared_ptr_Promise_double___(const std::shared_ptr>& value) noexcept { + return Result>>::withValue(value); + } + inline Result_std__shared_ptr_Promise_double___ create_Result_std__shared_ptr_Promise_double___(const std::exception_ptr& error) noexcept { + return Result>>::withError(error); + } + // pragma MARK: std::vector /** * Specialized version of `std::vector`. diff --git a/nitrogen/generated/ios/Codepad-Swift-Cxx-Umbrella.hpp b/nitrogen/generated/ios/Codepad-Swift-Cxx-Umbrella.hpp index 2822ad3..efbfd72 100644 --- a/nitrogen/generated/ios/Codepad-Swift-Cxx-Umbrella.hpp +++ b/nitrogen/generated/ios/Codepad-Swift-Cxx-Umbrella.hpp @@ -38,6 +38,8 @@ namespace margelo::nitro::codepad { struct NativeScrollEvent; } namespace margelo::nitro::codepad { struct NativeSearchHit; } // Forward declaration of `NativeSearchQuery` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeSearchQuery; } +// Forward declaration of `NativeSearchResult` to properly resolve imports. +namespace margelo::nitro::codepad { struct NativeSearchResult; } // Forward declaration of `NativeSelection` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeSelection; } // Forward declaration of `NativeSuggestions` to properly resolve imports. @@ -67,6 +69,7 @@ namespace margelo::nitro::codepad { struct NativeVisibleLines; } #include "NativeScrollEvent.hpp" #include "NativeSearchHit.hpp" #include "NativeSearchQuery.hpp" +#include "NativeSearchResult.hpp" #include "NativeSelection.hpp" #include "NativeSuggestions.hpp" #include "NativeTheme.hpp" diff --git a/nitrogen/generated/ios/c++/HybridCodeEditorViewSpecSwift.hpp b/nitrogen/generated/ios/c++/HybridCodeEditorViewSpecSwift.hpp index 482470f..4b547cd 100644 --- a/nitrogen/generated/ios/c++/HybridCodeEditorViewSpecSwift.hpp +++ b/nitrogen/generated/ios/c++/HybridCodeEditorViewSpecSwift.hpp @@ -44,6 +44,8 @@ namespace margelo::nitro::codepad { struct NativeRect; } namespace margelo::nitro::codepad { struct NativePosition; } // Forward declaration of `NativeVisibleLines` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeVisibleLines; } +// Forward declaration of `NativeSearchResult` to properly resolve imports. +namespace margelo::nitro::codepad { struct NativeSearchResult; } // Forward declaration of `NativeSearchQuery` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeSearchQuery; } // Forward declaration of `NativeSearchHit` to properly resolve imports. @@ -73,6 +75,7 @@ namespace margelo::nitro::codepad { enum class NativeCaretDirection; } #include "NativePosition.hpp" #include "NativeVisibleLines.hpp" #include +#include "NativeSearchResult.hpp" #include "NativeSearchQuery.hpp" #include "NativeSearchHit.hpp" #include "NativeCaretDirection.hpp" @@ -605,7 +608,7 @@ namespace margelo::nitro::codepad { auto __value = std::move(__result.value()); return __value; } - inline std::shared_ptr> setSearch(const NativeSearchQuery& query) override { + inline std::shared_ptr> setSearch(const NativeSearchQuery& query) override { auto __result = _swiftPart.setSearch(std::forward(query)); if (__result.hasError()) [[unlikely]] { std::rethrow_exception(__result.error()); diff --git a/nitrogen/generated/ios/swift/Func_void_NativeSearchResult.swift b/nitrogen/generated/ios/swift/Func_void_NativeSearchResult.swift new file mode 100644 index 0000000..ea5c3ee --- /dev/null +++ b/nitrogen/generated/ios/swift/Func_void_NativeSearchResult.swift @@ -0,0 +1,46 @@ +/// +/// Func_void_NativeSearchResult.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +/** + * Wraps a Swift `(_ value: NativeSearchResult) -> Void` as a class. + * This class can be used from C++, e.g. to wrap the Swift closure as a `std::function`. + */ +public final class Func_void_NativeSearchResult { + public typealias bridge = margelo.nitro.codepad.bridge.swift + + private let closure: (_ value: NativeSearchResult) -> Void + + public init(_ closure: @escaping (_ value: NativeSearchResult) -> Void) { + self.closure = closure + } + + @inline(__always) + public func call(value: NativeSearchResult) -> Void { + self.closure(value) + } + + /** + * Casts this instance to a retained unsafe raw pointer. + * This acquires one additional strong reference on the object! + */ + @inline(__always) + public func toUnsafe() -> UnsafeMutableRawPointer { + return Unmanaged.passRetained(self).toOpaque() + } + + /** + * Casts an unsafe pointer to a `Func_void_NativeSearchResult`. + * The pointer has to be a retained opaque `Unmanaged`. + * This removes one strong reference from the object! + */ + @inline(__always) + public static func fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> Func_void_NativeSearchResult { + return Unmanaged.fromOpaque(pointer).takeRetainedValue() + } +} diff --git a/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec.swift b/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec.swift index 5698d2c..f33501c 100644 --- a/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec.swift +++ b/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec.swift @@ -76,7 +76,7 @@ public protocol HybridCodeEditorViewSpec_protocol: HybridObject, HybridView { func paste() throws -> Promise func focus() throws -> Promise func blur() throws -> Promise - func setSearch(query: NativeSearchQuery) throws -> Promise + func setSearch(query: NativeSearchQuery) throws -> Promise func findNext() throws -> Promise func findPrevious() throws -> Promise func replaceCurrent(text: String) throws -> Promise diff --git a/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec_cxx.swift b/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec_cxx.swift index d6c4dbc..056f21e 100644 --- a/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec_cxx.swift +++ b/nitrogen/generated/ios/swift/HybridCodeEditorViewSpec_cxx.swift @@ -1474,21 +1474,21 @@ open class HybridCodeEditorViewSpec_cxx { } @inline(__always) - public final func setSearch(query: NativeSearchQuery) -> bridge.Result_std__shared_ptr_Promise_double___ { + public final func setSearch(query: NativeSearchQuery) -> bridge.Result_std__shared_ptr_Promise_NativeSearchResult___ { do { let __result = try self.__implementation.setSearch(query: query) - let __resultCpp = { () -> bridge.std__shared_ptr_Promise_double__ in - let __promise = bridge.create_std__shared_ptr_Promise_double__() - let __promiseHolder = bridge.wrap_std__shared_ptr_Promise_double__(__promise) + let __resultCpp = { () -> bridge.std__shared_ptr_Promise_NativeSearchResult__ in + let __promise = bridge.create_std__shared_ptr_Promise_NativeSearchResult__() + let __promiseHolder = bridge.wrap_std__shared_ptr_Promise_NativeSearchResult__(__promise) __result .then({ __result in __promiseHolder.resolve(__result) }) .catch({ __error in __promiseHolder.reject(__error.toCpp()) }) return __promise }() - return bridge.create_Result_std__shared_ptr_Promise_double___(__resultCpp) + return bridge.create_Result_std__shared_ptr_Promise_NativeSearchResult___(__resultCpp) } catch (let __error) { let __exceptionPtr = __error.toCpp() - return bridge.create_Result_std__shared_ptr_Promise_double___(__exceptionPtr) + return bridge.create_Result_std__shared_ptr_Promise_NativeSearchResult___(__exceptionPtr) } } diff --git a/nitrogen/generated/ios/swift/NativeSearchResult.swift b/nitrogen/generated/ios/swift/NativeSearchResult.swift new file mode 100644 index 0000000..16ce99b --- /dev/null +++ b/nitrogen/generated/ios/swift/NativeSearchResult.swift @@ -0,0 +1,34 @@ +/// +/// NativeSearchResult.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +/** + * Represents an instance of `NativeSearchResult`, backed by a C++ struct. + */ +public typealias NativeSearchResult = margelo.nitro.codepad.NativeSearchResult + +public extension NativeSearchResult { + private typealias bridge = margelo.nitro.codepad.bridge.swift + + /** + * Create a new instance of `NativeSearchResult`. + */ + init(count: Double, limited: Bool) { + self.init(count, limited) + } + + @inline(__always) + var count: Double { + return self.__count + } + + @inline(__always) + var limited: Bool { + return self.__limited + } +} diff --git a/nitrogen/generated/shared/c++/HybridCodeEditorViewSpec.hpp b/nitrogen/generated/shared/c++/HybridCodeEditorViewSpec.hpp index 05865e9..01e8af5 100644 --- a/nitrogen/generated/shared/c++/HybridCodeEditorViewSpec.hpp +++ b/nitrogen/generated/shared/c++/HybridCodeEditorViewSpec.hpp @@ -37,6 +37,8 @@ namespace margelo::nitro::codepad { struct NativePosition; } namespace margelo::nitro::codepad { struct NativeRect; } // Forward declaration of `NativeVisibleLines` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeVisibleLines; } +// Forward declaration of `NativeSearchResult` to properly resolve imports. +namespace margelo::nitro::codepad { struct NativeSearchResult; } // Forward declaration of `NativeSearchQuery` to properly resolve imports. namespace margelo::nitro::codepad { struct NativeSearchQuery; } // Forward declaration of `NativeSearchHit` to properly resolve imports. @@ -61,6 +63,7 @@ namespace margelo::nitro::codepad { enum class NativeCaretDirection; } #include "NativeRect.hpp" #include "NativeVisibleLines.hpp" #include +#include "NativeSearchResult.hpp" #include "NativeSearchQuery.hpp" #include "NativeSearchHit.hpp" #include "NativeCaretDirection.hpp" @@ -192,7 +195,7 @@ namespace margelo::nitro::codepad { virtual std::shared_ptr> paste() = 0; virtual std::shared_ptr> focus() = 0; virtual std::shared_ptr> blur() = 0; - virtual std::shared_ptr> setSearch(const NativeSearchQuery& query) = 0; + virtual std::shared_ptr> setSearch(const NativeSearchQuery& query) = 0; virtual std::shared_ptr> findNext() = 0; virtual std::shared_ptr> findPrevious() = 0; virtual std::shared_ptr> replaceCurrent(const std::string& text) = 0; diff --git a/nitrogen/generated/shared/c++/NativeSearchResult.hpp b/nitrogen/generated/shared/c++/NativeSearchResult.hpp new file mode 100644 index 0000000..0f792ef --- /dev/null +++ b/nitrogen/generated/shared/c++/NativeSearchResult.hpp @@ -0,0 +1,87 @@ +/// +/// NativeSearchResult.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + + + + + +namespace margelo::nitro::codepad { + + /** + * A struct which can be represented as a JavaScript object (NativeSearchResult). + */ + struct NativeSearchResult final { + public: + double count SWIFT_PRIVATE; + bool limited SWIFT_PRIVATE; + + public: + NativeSearchResult() = default; + explicit NativeSearchResult(double count, bool limited): count(count), limited(limited) {} + + public: + friend bool operator==(const NativeSearchResult& lhs, const NativeSearchResult& rhs) = default; + }; + +} // namespace margelo::nitro::codepad + +namespace margelo::nitro { + + // C++ NativeSearchResult <> JS NativeSearchResult (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::codepad::NativeSearchResult fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::codepad::NativeSearchResult( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "count"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "limited"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::codepad::NativeSearchResult& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "count"), JSIConverter::toJSI(runtime, arg.count)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "limited"), JSIConverter::toJSI(runtime, arg.limited)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "count")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "limited")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/src/CodeEditor.tsx b/src/CodeEditor.tsx index 21c3064..c5c2aa9 100644 --- a/src/CodeEditor.tsx +++ b/src/CodeEditor.tsx @@ -231,13 +231,13 @@ export const CodeEditor = forwardRef(function Co focus: () => native.current?.focus() ?? Promise.resolve(), blur: () => native.current?.blur() ?? Promise.resolve(), setSearch: async (query) => { - const count = await native.current?.setSearch({ + const result = await native.current?.setSearch({ text: query.text, regex: query.regex ?? false, caseSensitive: query.caseSensitive ?? false, wholeWord: query.wholeWord ?? false, }); - return { count: count ?? 0 }; + return { count: result?.count ?? 0, limited: result?.limited ?? false }; }, findNext: () => native.current?.findNext().then(toHit) ?? Promise.resolve(null), findPrevious: () => native.current?.findPrevious().then(toHit) ?? Promise.resolve(null), diff --git a/src/__tests__/CodeEditor.test.tsx b/src/__tests__/CodeEditor.test.tsx index 069459d..1456d79 100644 --- a/src/__tests__/CodeEditor.test.tsx +++ b/src/__tests__/CodeEditor.test.tsx @@ -257,14 +257,14 @@ describe('CodeEditor', () => { it('maps the search methods onto the native object', async () => { const ref = createRef(); const props = host(await render()); - expect(await ref.current?.setSearch({ text: 'ab' })).toEqual({ count: 0 }); + expect(await ref.current?.setSearch({ text: 'ab' })).toEqual({ count: 0, limited: false }); expect(await ref.current?.findNext()).toBeNull(); expect(await ref.current?.findPrevious()).toBeNull(); expect(await ref.current?.replaceCurrent('x')).toBe(false); expect(await ref.current?.replaceAll('x')).toBe(0); await ref.current?.clearSearch(); const native = { - setSearch: jest.fn(() => Promise.resolve(3)), + setSearch: jest.fn(() => Promise.resolve({ count: 3, limited: true })), findNext: jest.fn(() => Promise.resolve({ index: -1, total: 0 })), findPrevious: jest.fn(() => Promise.resolve({ index: 1, total: 3 })), replaceCurrent: jest.fn(() => Promise.resolve(true)), @@ -272,7 +272,7 @@ describe('CodeEditor', () => { clearSearch: jest.fn(() => Promise.resolve()), }; props.hybridRef.f(native); - expect(await ref.current?.setSearch({ text: 'ab' })).toEqual({ count: 3 }); + expect(await ref.current?.setSearch({ text: 'ab' })).toEqual({ count: 3, limited: true }); expect(native.setSearch).toHaveBeenCalledWith({ text: 'ab', regex: false, diff --git a/src/specs/CodeEditorView.nitro.ts b/src/specs/CodeEditorView.nitro.ts index 22ee33d..1c6c1ef 100644 --- a/src/specs/CodeEditorView.nitro.ts +++ b/src/specs/CodeEditorView.nitro.ts @@ -103,6 +103,12 @@ export interface NativeSearchHit { total: number; } +// limited: a regex hit PCRE2's match limit, so the count stops there. +export interface NativeSearchResult { + count: number; + limited: boolean; +} + export type NativeDecorationKind = 'underline' | 'gap' | 'lineBackground'; export type NativeUnderlineStyle = 'solid' | 'wavy'; @@ -195,7 +201,7 @@ export interface CodeEditorViewMethods extends HybridViewMethods { paste(): Promise; focus(): Promise; blur(): Promise; - setSearch(query: NativeSearchQuery): Promise; + setSearch(query: NativeSearchQuery): Promise; findNext(): Promise; findPrevious(): Promise; replaceCurrent(text: string): Promise; diff --git a/src/types.ts b/src/types.ts index 6b3d2fa..2002326 100644 --- a/src/types.ts +++ b/src/types.ts @@ -210,8 +210,11 @@ export interface CodeEditorRef { paste(): Promise; focus(): Promise; blur(): Promise; - /** Rejects when a regex query does not compile. */ - setSearch(query: SearchQuery): Promise<{ count: number }>; + /** + * Rejects when a regex query does not compile. `limited` is true when the regex hit PCRE2's + * match limit, so `count` stops there. + */ + setSearch(query: SearchQuery): Promise<{ count: number; limited: boolean }>; findNext(): Promise; findPrevious(): Promise; /** Replaces the selected match and selects the next one; false when the selection is not a match. */ diff --git a/tests/swift/SearchControllerTests.swift b/tests/swift/SearchControllerTests.swift index eab6db6..2557833 100644 --- a/tests/swift/SearchControllerTests.swift +++ b/tests/swift/SearchControllerTests.swift @@ -100,4 +100,14 @@ final class SearchControllerTests: XCTestCase { XCTAssertThrowsError(try controller.setQuery(SearchQuery(text: "(", regex: true))) XCTAssertFalse(controller.active) } + + /// setSearch's result reads the limit from the core, so the worker's scan has to bring it there. + func testAWorkerScanStoppedAtTheMatchLimitReachesTheCore() throws { + let core = EditorCore("aa\n" + String(repeating: "a", count: 40) + "b\naaa") + let controller = SearchController(core: core, queue: queue, postToMain: { [main] in main.post($0) }) + try controller.setQuery(SearchQuery(text: "(a+)+$", regex: true)) + settle() + XCTAssertEqual(core.matchCount, 1) + XCTAssertTrue(core.matchLimited) + } } diff --git a/tests/swift/VectorRunner.swift b/tests/swift/VectorRunner.swift index b799f28..559ff47 100644 --- a/tests/swift/VectorRunner.swift +++ b/tests/swift/VectorRunner.swift @@ -207,6 +207,7 @@ final class VectorRunner { } } if let v = expect["result"] { checkResult(v, at) } + if let v = expect["limited"] as? Bool { XCTAssertEqual(core.matchLimited, v, "limited \(at)") } if expect.keys.contains("brackets") { if expect["brackets"] is NSNull { XCTAssertNil(lastResult, "brackets \(at)") diff --git a/tests/vectors/search.json b/tests/vectors/search.json index d2b767d..7ca73d9 100644 --- a/tests/vectors/search.json +++ b/tests/vectors/search.json @@ -8,6 +8,7 @@ { "name": "regex anchors are per line", "text": "x\nx", "ops": [{ "op": "search", "text": "^x", "regex": true, "expect": { "matches": [[0, 1], [2, 3]] } }] }, { "name": "plain search escapes regex characters", "text": "a.b axb", "ops": [{ "op": "search", "text": "a.b", "expect": { "matches": [[0, 3]] } }] }, { "name": "invalid regex reports an error and clears matches", "text": "abc", "ops": [{ "op": "search", "text": "a", "expect": { "matches": [[0, 1]] } }, { "op": "search", "text": "(", "regex": true, "expect": { "error": true, "matches": [] } }] }, + { "name": "a regex past PCRE2's match limit keeps the matches before it and marks them limited", "text": "aa\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab\naaa", "ops": [{ "op": "search", "text": "(a+)+$", "regex": true, "expect": { "result": 1, "matches": [[0, 2]], "limited": true } }, { "op": "search", "text": "a", "expect": { "result": 45, "limited": false } }] }, { "name": "findNext starts at the first match at or after the caret and wraps", "text": "ab ab ab", "ops": [ { "op": "setSelection", "anchor": 4, "head": 4 }, { "op": "search", "text": "ab" }, diff --git a/website/docs/guides/search.md b/website/docs/guides/search.md index 0993b46..f5b68b4 100644 --- a/website/docs/guides/search.md +++ b/website/docs/guides/search.md @@ -9,7 +9,7 @@ Search runs in the native engine. You set a query, the editor paints every match ## Query ```ts -const { count } = await editor.current.setSearch({ +const { count, limited } = await editor.current.setSearch({ text: 'readFile', regex: false, caseSensitive: false, @@ -19,7 +19,7 @@ const { count } = await editor.current.setSearch({ `setSearch` resolves with the match count once the matches are painted. -- `regex` uses PCRE2 on both platforms, built into the shared core, so Unicode `\w` and `\b`, lookahead, bounded lookbehind and named groups behave the same. A pattern that does not compile rejects the promise and clears the search, so your bar can show the error while the user keeps typing. When a pattern backtracks too much, such as `(a+)+$` over a long run of `a`, the search stops at PCRE2's match limit and keeps the matches it found before that point. +- `regex` uses PCRE2 on both platforms, built into the shared core, so Unicode `\w` and `\b`, lookahead, bounded lookbehind and named groups behave the same. A pattern that does not compile rejects the promise and clears the search, so your bar can show the error while the user keeps typing. When a pattern backtracks too much, such as `(a+)+$` over a long run of `a`, the search stops at PCRE2's match limit and keeps the matches it found before that point. The promise then resolves with `limited: true`, so your bar can show the count as incomplete. - `caseSensitive` is off by default. - `wholeWord` wants identifier boundaries (`[A-Za-z0-9_]`) on both ends. diff --git a/website/docs/reference/methods.md b/website/docs/reference/methods.md index ecbc08e..0d2eedc 100644 --- a/website/docs/reference/methods.md +++ b/website/docs/reference/methods.md @@ -58,7 +58,7 @@ Native keeps the query and paints the matches. See the [search guide](/guides/se | Method | Notes | | --- | --- | -| `setSearch(query)` | Sets a `SearchQuery` and resolves with the match count. Rejects when a regex does not compile. | +| `setSearch(query)` | Sets a `SearchQuery` and resolves with `{ count, limited }`. `limited` is `true` when a regex stopped at PCRE2's match limit, so `count` covers only the matches found before it. Rejects when a regex does not compile. | | `findNext()`, `findPrevious()` | Select the next or previous match, wrapping around, and reveal it. Resolve with a `SearchHit`, or `null` without a query or matches. | | `replaceCurrent(text)` | Replaces the selected match and selects the next one. Resolves with `false` when the selection is not a match. | | `replaceAll(text)` | Replaces every match in one undo group and resolves with the number of replacements. | From 449e1492ae9790df1a0be874fd8452e3cb928204 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:47:33 +0100 Subject: [PATCH 03/14] fix(android): extend a word drag by the words a long press selects The drag used a Kotlin word finder whose white space differs from the core's (U+0085 and U+001C-001F), so a drag could stop inside a word the long press had selected whole. --- android/src/main/cpp/core_jni.cpp | 8 +++-- .../me/sectiontn/codepad/core/EditorCore.kt | 6 ++++ .../me/sectiontn/codepad/core/TextMovement.kt | 35 ------------------- .../me/sectiontn/codepad/syntax/CoreNative.kt | 2 +- .../sectiontn/codepad/view/CodeEditorView.kt | 2 +- .../sectiontn/codepad/core/WordRangeTest.kt | 17 +++++++++ cpp/core/include/codepad.h | 2 ++ cpp/core/src/capi_editor.cpp | 6 ++++ 8 files changed, 39 insertions(+), 39 deletions(-) create mode 100644 android/src/test/java/me/sectiontn/codepad/core/WordRangeTest.kt diff --git a/android/src/main/cpp/core_jni.cpp b/android/src/main/cpp/core_jni.cpp index f1754b9..9fa5661 100644 --- a/android/src/main/cpp/core_jni.cpp +++ b/android/src/main/cpp/core_jni.cpp @@ -389,8 +389,12 @@ FN(docOffset)(JNIEnv *, jclass, jlong editor, jint line, jint column) -> jint { return static_cast(cp_doc_offset(ed(editor), line, column)); } -FN(docGrapheme)(JNIEnv *, jclass, jlong editor, jint offset, jboolean forward) -> jint { - return static_cast(cp_doc_grapheme(ed(editor), at(offset), forward ? 1 : 0)); +// start in the high 32 bits, end in the low ones. +FN(docWordAt)(JNIEnv *, jclass, jlong editor, jint offset) -> jlong { + uint32_t start = 0; + uint32_t end = 0; + cp_doc_word_at(ed(editor), at(offset), &start, &end); + return static_cast(start) << 32 | end; } FN(editorSettings)(JNIEnv *, jclass, jlong editor, jint tab, jboolean spaces, jboolean indent, jboolean close) diff --git a/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt b/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt index 1e59f32..5b1929b 100644 --- a/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt +++ b/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt @@ -142,6 +142,12 @@ class EditorCore(initialText: String = "", clock: (() -> Long)? = null) : AutoCl fun selectWordAt(offset: Int) = mutate { CoreNative.editorSelectWordAt(it, offset) } + /** The word [selectWordAt] would select, without moving the selection. */ + fun wordRangeAt(offset: Int): Range { + val packed = CoreNative.docWordAt(handle(), offset) + return Range((packed ushr 32).toInt(), packed.toInt()) + } + /** True when a backspace at [caret] removes an auto closed pair. */ fun deletesPair(caret: Int): Boolean = CoreNative.editorDeletesPair(handle(), caret) diff --git a/android/src/main/java/me/sectiontn/codepad/core/TextMovement.kt b/android/src/main/java/me/sectiontn/codepad/core/TextMovement.kt index dd4fdc3..55ba39f 100644 --- a/android/src/main/java/me/sectiontn/codepad/core/TextMovement.kt +++ b/android/src/main/java/me/sectiontn/codepad/core/TextMovement.kt @@ -1,41 +1,6 @@ package me.sectiontn.codepad.core -import me.sectiontn.codepad.syntax.CoreNative - object TextMovement { /** Ordinals match CP_MOVE_*. */ enum class Unit { Char, Word, LineStart, LineEnd, DocStart, DocEnd } - - fun isWordChar(c: Char): Boolean = c == '_' || c in 'a'..'z' || c in 'A'..'Z' || c in '0'..'9' - - fun nextGrapheme(doc: Document, offset: Int): Int = CoreNative.docGrapheme(doc.handle, offset, true) - - fun prevGrapheme(doc: Document, offset: Int): Int = CoreNative.docGrapheme(doc.handle, offset, false) - - /** Double tap target: an identifier run, a whitespace run, or a single punctuation grapheme. */ - fun wordRangeAt(doc: Document, offset: Int): Range { - val o = offset.coerceIn(0, doc.length) - val line = doc.lineAt(o) - val start = doc.lineStart(line) - val text = doc.line(line) - if (text.isEmpty()) return Range(start, start) - var col = (o - start).coerceIn(0, text.length) - if (col == text.length) col-- - val c = text[col] - val cls: ((Char) -> Boolean)? = when { - isWordChar(c) -> { ch -> isWordChar(ch) } - c.isWhitespace() -> { ch -> ch.isWhitespace() } - else -> null - } - if (cls != null) { - var a = col - var b = col + 1 - while (a > 0 && cls(text[a - 1])) a-- - while (b < text.length && cls(text[b])) b++ - return Range(start + a, start + b) - } - // A punctuation grapheme is its own word, so "a.b" splits in three. - val end = nextGrapheme(doc, start + col) - return Range(prevGrapheme(doc, end), end) - } } diff --git a/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt b/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt index b1a3a60..c52bc25 100644 --- a/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt +++ b/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt @@ -31,7 +31,7 @@ internal object CoreNative { @JvmStatic external fun docText(editor: Long, start: Int, end: Int): String @JvmStatic external fun docPosition(editor: Long, offset: Int): Long @JvmStatic external fun docOffset(editor: Long, line: Int, column: Int): Int - @JvmStatic external fun docGrapheme(editor: Long, offset: Int, forward: Boolean): Int + @JvmStatic external fun docWordAt(editor: Long, offset: Int): Long @JvmStatic external fun editorSettings(editor: Long, tabSize: Int, spaces: Boolean, indent: Boolean, close: Boolean) @JvmStatic external fun editorReplace(editor: Long, start: Int, end: Int, text: String, origin: Int, typing: Boolean, caretAfter: Boolean) @JvmStatic external fun editorSetText(editor: Long, text: String, keepHistory: Boolean) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index b8d42f2..2b35e59 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -979,7 +979,7 @@ class CodeEditorView(context: Context) : View(context) { // The word under the long press stays selected and the far end follows the finger by words. override fun extendWords(offset: Int) { - val word = TextMovement.wordRangeAt(core.document, offset) + val word = core.wordRangeAt(offset) if (offset >= wordAnchor.start) { core.setSelection(wordAnchor.start, maxOf(word.end, wordAnchor.end)) } else { diff --git a/android/src/test/java/me/sectiontn/codepad/core/WordRangeTest.kt b/android/src/test/java/me/sectiontn/codepad/core/WordRangeTest.kt new file mode 100644 index 0000000..72f2ffa --- /dev/null +++ b/android/src/test/java/me/sectiontn/codepad/core/WordRangeTest.kt @@ -0,0 +1,17 @@ +package me.sectiontn.codepad.core + +import org.junit.Assert.assertEquals +import org.junit.Test + +class WordRangeTest { + // A drag after a long press extends by the words the long press selects, so both use the core's classes: + // U+0085 is Unicode white space and U+001C to U+001F are not. + @Test + fun theDragWordIsTheLongPressWord() { + val core = EditorCore("a\u0085\u0085b c\u001C\u001Dd") + for (offset in 0..core.document.length) { + core.selectWordAt(offset) + assertEquals("offset $offset", core.selection.range, core.wordRangeAt(offset)) + } + } +} diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h index 7560615..7a14e4a 100644 --- a/cpp/core/include/codepad.h +++ b/cpp/core/include/codepad.h @@ -94,6 +94,8 @@ CP_API cp_point cp_doc_position(const cp_editor *editor, uint32_t offset); CP_API uint32_t cp_doc_offset(const cp_editor *editor, int32_t line, int32_t column); // The grapheme boundary after offset, or before it when forward is 0. A line break is a grapheme of its own. CP_API uint32_t cp_doc_grapheme(const cp_editor *editor, uint32_t offset, int32_t forward); +// The word cp_editor_select_word_at selects at offset, without moving the selection. +CP_API void cp_doc_word_at(const cp_editor *editor, uint32_t offset, uint32_t *start, uint32_t *end); // The current text, retained for the caller. CP_API cp_text *cp_editor_text(cp_editor *editor); diff --git a/cpp/core/src/capi_editor.cpp b/cpp/core/src/capi_editor.cpp index 9c47065..743991d 100644 --- a/cpp/core/src/capi_editor.cpp +++ b/cpp/core/src/capi_editor.cpp @@ -86,6 +86,12 @@ uint32_t cp_doc_grapheme(const cp_editor *editor, uint32_t offset, int32_t forwa : codepad::movement::prev_grapheme(editor->doc, offset); } +void cp_doc_word_at(const cp_editor *editor, uint32_t offset, uint32_t *start, uint32_t *end) { + codepad::movement::Range r = codepad::movement::word_range_at(editor->doc, offset); + *start = r.start; + *end = r.end; +} + cp_text *cp_editor_text(cp_editor *editor) { return new cp_text{editor->doc.view()}; } void cp_editor_set_settings(cp_editor *editor, const cp_settings *s) { From 0ac9566935cbbbcec7086469df5a69924c9c9c72 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:50:11 +0100 Subject: [PATCH 04/14] fix(android): stop at a failed JNI allocation instead of using the null A failed NewString, NewIntArray or GetStringUTFChars leaves an OutOfMemoryError pending. The binding kept going, passing the null on or making the next JNI call with the error pending. It now returns at once so the error reaches Kotlin. --- android/src/main/cpp/core_jni.cpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/android/src/main/cpp/core_jni.cpp b/android/src/main/cpp/core_jni.cpp index 9fa5661..2074a17 100644 --- a/android/src/main/cpp/core_jni.cpp +++ b/android/src/main/cpp/core_jni.cpp @@ -86,6 +86,10 @@ int64_t now_micros(void *) { const cp_language *resolve(void *ctx, const char *id) { JNIEnv *e = env(); jstring name = java_string(e, id); + if (name == nullptr) { + clear(e); + return nullptr; + } jlong handle = e->CallLongMethod(static_cast(ctx)->host, resolve_id, name); e->DeleteLocalRef(name); if (e->ExceptionCheck()) { @@ -136,7 +140,7 @@ jint fill(JNIEnv *e, jintArray out, Call call) { FN(abiRange)(JNIEnv *e, jclass) -> jintArray { jintArray out = e->NewIntArray(2); jint v[2] = {cp_abi_min(), cp_abi_max()}; - e->SetIntArrayRegion(out, 0, 2, v); + if (out != nullptr) e->SetIntArrayRegion(out, 0, 2, v); return out; } @@ -144,6 +148,7 @@ FN(abiRange)(JNIEnv *e, jclass) -> jintArray { FN(languageLoad)(JNIEnv *e, jclass, jstring jid, jlong pointer, jbyteArray highlights, jbyteArray injections, jobjectArray error) -> jlong { const char *id = e->GetStringUTFChars(jid, nullptr); + if (id == nullptr) return 0; jsize hn = e->GetArrayLength(highlights); jsize in = injections ? e->GetArrayLength(injections) : 0; std::vector h(static_cast(hn)); @@ -154,12 +159,14 @@ FN(languageLoad)(JNIEnv *e, jclass, jstring jid, jlong pointer, jbyteArray highl cp_language *language = cp_language_load(id, ptr(pointer), h.data(), static_cast(hn), i.data(), static_cast(in), message, sizeof(message)); e->ReleaseStringUTFChars(jid, id); - if (message[0] && error) e->SetObjectArrayElement(error, 0, java_string(e, message)); + jstring m = message[0] && error ? java_string(e, message) : nullptr; + if (m != nullptr) e->SetObjectArrayElement(error, 0, m); return handle(language); } FN(styleId)(JNIEnv *e, jclass, jstring jname) -> jint { const char *name = e->GetStringUTFChars(jname, nullptr); + if (name == nullptr) return 0; jint id = cp_style_id(name); e->ReleaseStringUTFChars(jname, name); return id; @@ -219,7 +226,7 @@ FN(snapshotChanged)(JNIEnv *e, jclass, jlong snapshot) -> jintArray { cp_snapshot_info info{}; cp_snapshot_info_get(ptr(snapshot), &info); jintArray out = e->NewIntArray(static_cast(info.changed_len)); - if (info.changed_len) { + if (out != nullptr && info.changed_len) { e->SetIntArrayRegion(out, 0, static_cast(info.changed_len), reinterpret_cast(cp_snapshot_changed(ptr(snapshot)))); } @@ -322,7 +329,9 @@ jstring copy_text(JNIEnv *e, const cp_editor *editor, uint32_t start, uint32_t e jintArray int_array(JNIEnv *e, const int32_t *values, uint32_t n) { jintArray out = e->NewIntArray(static_cast(n)); - if (n > 0) e->SetIntArrayRegion(out, 0, static_cast(n), reinterpret_cast(values)); + if (out != nullptr && n > 0) { + e->SetIntArrayRegion(out, 0, static_cast(n), reinterpret_cast(values)); + } return out; } @@ -493,6 +502,7 @@ FN(editorSetSearch)(JNIEnv *e, jclass, jlong editor, jstring query, jint flags, char message[512] = {0}; if (cp_editor_set_search(ed(editor), units_of(q), count_of(q), flags, message, sizeof(message)) != 0) return JNI_TRUE; jstring m = java_string(e, message); + if (m == nullptr) return JNI_FALSE; e->SetObjectArrayElement(error, 0, m); e->DeleteLocalRef(m); return JNI_FALSE; From 7b3d9e785ef05d462b2948475232261fc12030cc Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:53:31 +0100 Subject: [PATCH 05/14] fix: free a snapshot that lands after the engine closed A parse posted just before close reached the host after it. On Android the view kept it after an unmount and nothing freed it. The engine now drops a snapshot that lands once it is shut. --- .../codepad/syntax/SyntaxEngineTest.kt | 22 +++++++++++++++++++ cpp/core/src/engine.cpp | 5 +++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/android/src/test/java/me/sectiontn/codepad/syntax/SyntaxEngineTest.kt b/android/src/test/java/me/sectiontn/codepad/syntax/SyntaxEngineTest.kt index a3b6589..f0fe29c 100644 --- a/android/src/test/java/me/sectiontn/codepad/syntax/SyntaxEngineTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/syntax/SyntaxEngineTest.kt @@ -314,4 +314,26 @@ class SyntaxEngineTest { snapshot.close() engine.close() } + + // A parse posted just before close lands after it, when the view that would free it is gone. + @Test + fun aSnapshotPostedBeforeCloseNeverReachesTheHost() { + val main = LinkedBlockingQueue() + val core = EditorCore("let a = 1;") + val engine = SyntaxEngine(postToMain = { main.add(it) }, onSnapshot = { snapshots.add(it) }) + engine.setLanguage("javascript") + engine.attach(core) + while (snapshots.none { it.length > 0 }) checkNotNull(main.poll(5, TimeUnit.SECONDS)).run() + while (true) (main.poll(300, TimeUnit.MILLISECONDS) ?: break).run() + snapshots.forEach { it.close() } + snapshots.clear() + core.replace(4, 5, "value") + val late = checkNotNull(main.poll(5, TimeUnit.SECONDS)) + engine.close() + late.run() + val reached = snapshots.size + snapshots.forEach { it.close() } + checkNotNull(main.poll(5, TimeUnit.SECONDS)).run() + assertEquals(0, reached) + } } diff --git a/cpp/core/src/engine.cpp b/cpp/core/src/engine.cpp index ed3d98e..a10c6ce 100644 --- a/cpp/core/src/engine.cpp +++ b/cpp/core/src/engine.cpp @@ -178,8 +178,9 @@ struct Engine : std::enable_shared_from_this { static void run_post(void *arg) { std::unique_ptr post(static_cast(arg)); Engine &engine = *post->engine; - // Parsed before the latest attach: its revision can equal the new document's, so the host must never see it. - if (post->snapshot && post->snapshot->epoch != engine.epoch.load()) { + // Parsed before the latest attach, whose revision can equal the new document's, or landing after close, when the + // host that would free it is gone. The host never sees either. + if (post->snapshot && (engine.shut || post->snapshot->epoch != engine.epoch.load())) { engine.release(post->snapshot); return; } From 6715fd30cd783bc1a43ecccc4217c0489e2743a2 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:55:56 +0100 Subject: [PATCH 06/14] chore(ios): read C buffers without the deprecated String(cString:) --- ios/Codepad/syntax/LanguageRegistry.swift | 2 +- ios/Codepad/syntax/StyleTable.swift | 2 +- tests/swift/CoreHighlightTests.swift | 2 +- tests/swift/CoreLanguageTests.swift | 11 ++++++++--- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/ios/Codepad/syntax/LanguageRegistry.swift b/ios/Codepad/syntax/LanguageRegistry.swift index 1d23bda..f36e1ec 100644 --- a/ios/Codepad/syntax/LanguageRegistry.swift +++ b/ios/Codepad/syntax/LanguageRegistry.swift @@ -103,7 +103,7 @@ enum LanguageRegistry { } } } - let message = String(cString: error) + let message = String(decoding: error.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) guard let handle else { log.warning("\(message, privacy: .public)") return nil diff --git a/ios/Codepad/syntax/StyleTable.swift b/ios/Codepad/syntax/StyleTable.swift index 2f5093b..a5def7e 100644 --- a/ios/Codepad/syntax/StyleTable.swift +++ b/ios/Codepad/syntax/StyleTable.swift @@ -23,7 +23,7 @@ enum StyleTable { buffer = [CChar](repeating: 0, count: length + 1) _ = cp_style_name(Int32(id), &buffer, UInt32(length + 1)) } - let name = String(cString: buffer) + let name = String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) names.lock.withLock { names.byId[id] = name } return name } diff --git a/tests/swift/CoreHighlightTests.swift b/tests/swift/CoreHighlightTests.swift index 826256a..51a234e 100644 --- a/tests/swift/CoreHighlightTests.swift +++ b/tests/swift/CoreHighlightTests.swift @@ -73,7 +73,7 @@ final class CoreHighlightTests: XCTestCase { private func name(_ style: Int32) -> String { var buffer = [CChar](repeating: 0, count: 128) _ = cp_style_name(style, &buffer, 128) - return String(cString: buffer) + return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) } /// Renders cp_highlight lines as the golden files do, from the given line on. diff --git a/tests/swift/CoreLanguageTests.swift b/tests/swift/CoreLanguageTests.swift index 49a042c..666e4bb 100644 --- a/tests/swift/CoreLanguageTests.swift +++ b/tests/swift/CoreLanguageTests.swift @@ -21,7 +21,7 @@ final class CoreLanguageTests: XCTestCase { } } } - return (language, String(cString: error)) + return (language, text(error)) } private func javascript() throws -> OpaquePointer { @@ -40,7 +40,7 @@ final class CoreLanguageTests: XCTestCase { cp_test_predicate(lang, qc.baseAddress, UInt32(qc.count), s, UInt32(s.count), &message, 512) } } - XCTAssertGreaterThanOrEqual(count, 0, String(cString: message)) + XCTAssertGreaterThanOrEqual(count, 0, text(message)) return count } @@ -89,7 +89,7 @@ final class CoreLanguageTests: XCTestCase { XCTAssertEqual(cp_style_id("keyword.function"), id) var name = [CChar](repeating: 0, count: 64) XCTAssertEqual(cp_style_name(id, &name, 64), UInt32("keyword.function".utf8.count)) - XCTAssertEqual(String(cString: name), "keyword.function") + XCTAssertEqual(text(name), "keyword.function") var short = [CChar](repeating: 0, count: 4) XCTAssertEqual(cp_style_name(id, &short, 4), UInt32("keyword.function".utf8.count)) } @@ -136,3 +136,8 @@ final class CoreLanguageTests: XCTestCase { XCTAssertEqual(try accepted("((template_string) @t (#match? @t \"^.a.b.$\"))", "`a-b`;"), 1) } } + +/// The text of a NUL-terminated C buffer. +private func text(_ buffer: [CChar]) -> String { + String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) +} From ebd41e7016025227e3e8121752b3dfad6a3012cf Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:57:10 +0100 Subject: [PATCH 07/14] test: pin the scroll in range after setText drops the gaps --- tests/vectors/layout.json | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/vectors/layout.json b/tests/vectors/layout.json index b5831af..21e6ffa 100644 --- a/tests/vectors/layout.json +++ b/tests/vectors/layout.json @@ -9,6 +9,7 @@ { "name": "gap rows sit beside wrap rows", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 3, "rows": 2 }] }, { "op": "measure", "pairs": [[3, 2]] }], "expect": { "rowStart": { "3": 3, "4": 7 }, "isGapRow": { "3": false, "4": false, "5": true, "6": true, "7": false }, "totalRows": 23 } }, { "name": "a new decoration set replaces the gaps", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 2, "rows": 2 }], "expect": { "totalRows": 22 } }, { "op": "decorate", "items": [{ "kind": "gap", "line": 5, "rows": 1 }] }], "expect": { "totalRows": 21, "rowStart": { "3": 3, "6": 7 }, "isGapRow": { "3": false, "6": true } } }, { "name": "deleting a gap's line at the end and undoing keeps the rows in range", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 19, "rows": 2 }] }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "scroll": [0, 170], "totalRows": 22 } }, { "op": "replace", "start": 29, "end": 39, "text": "", "expect": { "lineCount": 15, "gapRows": {}, "totalRows": 15, "scroll": [0, 100], "isGapRow": { "14": false, "15": false } } }, { "op": "undo" }], "expect": { "lineCount": 20, "gapRows": {}, "totalRows": 20, "scroll": [0, 100], "maxScroll": [0, 150] } }, + { "name": "setText drops the gaps and keeps the scroll in range", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 0, "rows": 2 }] }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "scroll": [0, 170], "totalRows": 22 } }, { "op": "setText", "text": "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny" }], "expect": { "lineCount": 20, "gapRows": {}, "totalRows": 20, "scroll": [0, 150], "maxScroll": [0, 150] } }, { "name": "an edit makes fresh one-row lines and moves gap lines with their text", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 10, "rows": 2 }] }, { "op": "measure", "pairs": [[5, 3], [12, 2]] }, { "op": "replace", "start": 10, "end": 10, "text": "y\ny\n" }], "expect": { "lineCount": 22, "gapRows": { "12": 2 }, "rowStart": { "5": 5, "8": 8, "12": 12, "13": 15, "14": 16, "15": 18 }, "totalRows": 25 } }, { "name": "rows map to the view through the insets", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [8, 4, 6, 2], "gutter": 10, "padding": 3, "wrap": false, "expect": { "content": [82, 200], "maxScroll": [0, 162], "lineTop": { "0": 8, "3": 38 }, "visible": [0, 3] } }, { "op": "scrollTo", "x": 0, "y": 25 }], "expect": { "lineTop": { "3": 13 }, "visible": [2, 6] } }, { "name": "layout reports only a text area width change", "text": "x\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }, { "op": "layout", "rowHeight": 10, "width": 100, "height": 80, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": false } }, { "op": "layout", "rowHeight": 10, "width": 100, "height": 80, "insets": [0, 0, 4, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }, { "op": "layout", "rowHeight": 10, "width": 120, "height": 80, "insets": [0, 0, 4, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }] }, From d3b72c9c1bc81d13b6ecddddcb3f75c01a754067 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 01:58:25 +0100 Subject: [PATCH 08/14] test(android): check the draw budget in the draw helper, without the debug switch The decoration test relied on the app's check, which throws only with the debug switch on. The draw helper now checks every draw's single layout calls, like the iOS suite. A dropped view test is renamed to what it checks: keyboard edits until the view leaves the window. --- .../java/codepad/example/DecorationPaintTest.kt | 2 +- .../java/codepad/example/InputConnectionTest.kt | 6 +++--- .../src/androidTest/java/codepad/example/ScrollTest.kt | 5 +---- .../src/androidTest/java/codepad/example/Support.kt | 10 ++++++++++ 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt b/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt index b51792d..b5d195f 100644 --- a/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt @@ -39,7 +39,7 @@ class DecorationPaintTest { } // A checker marks lines all over a file. Each one below the window would cost a layout call per draw, and the - // debug switch the suite runs with throws past eight of them. + // draw helper fails past eight of them. @Test fun decorationsBelowTheWindowCostNoLayoutCall() { launch().use { s -> diff --git a/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt b/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt index 8024180..9eb191d 100644 --- a/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt @@ -110,10 +110,10 @@ class InputConnectionTest { } } - // The layout lives as long as the core. A dropped view still in the window relays out on a keyboard edit that - // widens the gutter, and draws, until it leaves. + // A dropped view still in the window keeps its core and layout: a keyboard edit that widens the gutter works and + // a draw call does not crash. Once the view leaves the window, keyboard calls do nothing. @Test - fun aDroppedViewStillDrawsUntilItLeavesTheWindow() { + fun aDroppedViewTakesKeyboardEditsUntilItLeavesTheWindow() { launch().use { s -> val editor = s.editor() onMain { diff --git a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt index b82aaa2..cbb247a 100644 --- a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt @@ -3,8 +3,6 @@ package codepad.example import android.os.SystemClock import android.view.KeyEvent import androidx.test.ext.junit.runners.AndroidJUnit4 -import me.sectiontn.codepad.layout.Viewport -import me.sectiontn.codepad.view.CodeEditorView import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test @@ -42,8 +40,7 @@ class ScrollTest { editor.setInitialText((0 until 100).joinToString("\n") { "line $it" }) layout(editor) draw(editor) - val viewport = CodeEditorView::class.java.getDeclaredField("viewport").apply { isAccessible = true } - .get(editor) as Viewport + val viewport = viewportOf(editor) viewport.measured(98, 30) viewport.measured(99, 30) viewport.scrollTo(0, viewport.maxScrollY) diff --git a/example/android/app/src/androidTest/java/codepad/example/Support.kt b/example/android/app/src/androidTest/java/codepad/example/Support.kt index e6358d5..d59b7a0 100644 --- a/example/android/app/src/androidTest/java/codepad/example/Support.kt +++ b/example/android/app/src/androidTest/java/codepad/example/Support.kt @@ -5,7 +5,9 @@ import android.graphics.Canvas import android.view.View import androidx.test.core.app.ActivityScenario import androidx.test.platform.app.InstrumentationRegistry +import me.sectiontn.codepad.layout.Viewport import me.sectiontn.codepad.view.CodeEditorView +import org.junit.Assert.assertTrue internal fun launch(): ActivityScenario = ActivityScenario.launch(TestActivity::class.java) @@ -33,9 +35,17 @@ internal fun layout(view: View, width: Int = 600, height: Int = 400) { internal fun draw(view: View): Bitmap { val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) view.draw(Canvas(bitmap)) + // The app's check needs the debug switch, so the suite checks the draw's single layout calls here. + if (view is CodeEditorView) { + val calls = viewportOf(view).drawCalls + assertTrue("$calls single layout calls in one draw", calls <= Viewport.DRAW_CALL_LIMIT) + } return bitmap } +internal fun viewportOf(editor: CodeEditorView): Viewport = + CodeEditorView::class.java.getDeclaredField("viewport").apply { isAccessible = true }.get(editor) as Viewport + /** Pixels painted in a theme's pure red over the first [rows] pixel rows of the bitmap. */ internal fun redPixels(bitmap: Bitmap, rows: Int): Int { var n = 0 From 6501d4e5ad4044f3c4dc1b2100c848ec5e15d87f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 02:00:02 +0100 Subject: [PATCH 09/14] test: add a golden for an XML document with an internal DTD subset --- .../codepad/syntax/HighlightGoldenTest.kt | 10 ++- tests/highlight/xml.internal-subset.spans | 73 +++++++++++++++++++ tests/highlight/xml.internal-subset.txt | 11 +++ tests/swift/CoreHighlightTests.swift | 4 +- 4 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 tests/highlight/xml.internal-subset.spans create mode 100644 tests/highlight/xml.internal-subset.txt diff --git a/android/src/test/java/me/sectiontn/codepad/syntax/HighlightGoldenTest.kt b/android/src/test/java/me/sectiontn/codepad/syntax/HighlightGoldenTest.kt index 433b8e1..2551806 100644 --- a/android/src/test/java/me/sectiontn/codepad/syntax/HighlightGoldenTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/syntax/HighlightGoldenTest.kt @@ -11,7 +11,10 @@ import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized -/** Every sample's spans against tests/highlight/.spans; CODEPAD_RECORD_HIGHLIGHT=1 rewrites them. */ +/** + * Every sample's spans against tests/highlight/.spans, in the language before the first dot of the name. + * CODEPAD_RECORD_HIGHLIGHT=1 rewrites them. + */ @RunWith(Parameterized::class) class HighlightGoldenTest(private val id: String) { companion object { @@ -48,7 +51,8 @@ class HighlightGoldenTest(private val id: String) { val text = dir.resolve("$id.txt").readText() val snapshots = LinkedBlockingQueue() val engine = SyntaxEngine(postToMain = { it.run() }, onSnapshot = { snapshots.add(it) }) - engine.setLanguage(id) + val language = id.substringBefore('.') + engine.setLanguage(language) val core = EditorCore(text) engine.attach(core) // setLanguage can publish an empty document snapshot first; wait for the whole text. @@ -59,7 +63,7 @@ class HighlightGoldenTest(private val id: String) { snapshot.close() } val doc = core.document - val lang = checkNotNull(LanguageRegistry.resolve(id)) + val lang = checkNotNull(LanguageRegistry.resolve(language)) val actual = render(doc, Highlighter(lang).spans(snapshot, doc, 0, doc.lineCount - 1)) snapshot.close() engine.close() diff --git a/tests/highlight/xml.internal-subset.spans b/tests/highlight/xml.internal-subset.spans new file mode 100644 index 0000000..6ee1093 --- /dev/null +++ b/tests/highlight/xml.internal-subset.spans @@ -0,0 +1,73 @@ +0 0 2 tag.delimiter +0 2 5 keyword.directive +0 6 13 tag.attribute +0 13 14 operator +0 14 15 punctuation.delimiter +0 15 18 number +0 18 19 punctuation.delimiter +0 20 28 tag.attribute +0 28 29 operator +0 29 30 punctuation.delimiter +0 30 35 string.special +0 35 36 punctuation.delimiter +0 36 38 tag.delimiter +1 0 2 tag.delimiter +1 2 9 keyword.directive.define +1 10 14 type.definition +1 15 16 punctuation.bracket +2 2 4 tag.delimiter +2 4 11 keyword.directive.define +2 12 16 tag +2 17 18 punctuation.bracket +2 18 20 tag.attribute +2 20 21 operator +2 22 26 tag.attribute +2 26 27 punctuation.bracket +2 27 28 tag.delimiter +3 2 4 tag.delimiter +3 4 11 keyword.directive.define +3 12 14 tag +3 15 16 punctuation.bracket +3 16 23 type.builtin +3 23 24 punctuation.bracket +3 24 25 tag.delimiter +4 2 4 tag.delimiter +4 4 11 keyword.directive.define +4 12 16 tag +4 17 19 tag.attribute +4 20 22 type.builtin +4 23 32 attribute +4 32 33 tag.delimiter +5 2 4 tag.delimiter +5 4 10 keyword.directive.define +5 11 15 constant +5 16 17 punctuation.delimiter +5 17 33 string +5 33 34 punctuation.delimiter +5 34 35 tag.delimiter +6 0 1 punctuation.bracket +6 1 2 tag.delimiter +7 0 1 tag.delimiter +7 1 5 tag +7 6 8 tag.attribute +7 8 9 operator +7 9 10 punctuation.delimiter +7 10 12 string +7 12 13 punctuation.delimiter +7 13 14 tag.delimiter +8 2 3 tag.delimiter +8 3 5 tag +8 5 6 tag.delimiter +8 9 11 tag.delimiter +8 11 13 tag +8 13 14 tag.delimiter +9 2 3 tag.delimiter +9 3 7 tag +9 7 8 tag.delimiter +9 20 26 constant +9 26 28 tag.delimiter +9 28 32 tag +9 32 33 tag.delimiter +10 0 2 tag.delimiter +10 2 6 tag +10 6 7 tag.delimiter diff --git a/tests/highlight/xml.internal-subset.txt b/tests/highlight/xml.internal-subset.txt new file mode 100644 index 0000000..a22dca3 --- /dev/null +++ b/tests/highlight/xml.internal-subset.txt @@ -0,0 +1,11 @@ + + + + + +]> + + Ada + Thanks from &team; + diff --git a/tests/swift/CoreHighlightTests.swift b/tests/swift/CoreHighlightTests.swift index 51a234e..814ed80 100644 --- a/tests/swift/CoreHighlightTests.swift +++ b/tests/swift/CoreHighlightTests.swift @@ -93,11 +93,11 @@ final class CoreHighlightTests: XCTestCase { func testEverySampleMatchesItsGolden() throws { let files = try FileManager.default.contentsOfDirectory(atPath: Self.highlightDir.path).filter { $0.hasSuffix(".txt") }.sorted() - XCTAssertEqual(files.count, 22) + XCTAssertEqual(files.count, 23) for file in files { let id = String(file.dropLast(4)) let text = try String(contentsOf: Self.highlightDir.appendingPathComponent(file), encoding: .utf8) - let s = snapshot(id, text) + let s = snapshot(String(id.prefix { $0 != "." }), text) let lines = text.split(separator: "\n", omittingEmptySubsequences: false).count let ints = fill { cp_highlight(s, 0, Int32(lines - 1), 0, $0, $1) } let expected = try String(contentsOf: Self.highlightDir.appendingPathComponent("\(id).spans"), encoding: .utf8) From 2b1d1e7dd3f32ed124d44f306d33587baa34f304 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 12:46:38 +0100 Subject: [PATCH 10/14] fix(ios): end an animated scrollToLine on the line when wrap is on The animation aimed at an offset that counted unmeasured lines as one row, and the wrapped lines it passed took their rows on the way, so Go to line 1500 stopped near line 743. It now runs on a display link that reads the line's row start on every frame. scrollToLine also stops a deceleration or an animated offset first, as Android aborts its scroller, so UIKit no longer moves the view after it. --- example/ios/CodepadTests/ScrollTests.swift | 33 ++++++++++++++ ios/Codepad/view/CodeEditorView.swift | 51 ++++++++++++++++++++-- 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index 4f9931c..eb9907f 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -107,4 +107,37 @@ final class ScrollTests: XCTestCase { XCTAssertEqual(heard, CGFloat(editor.viewport.scrollY), "keeping \(keep) lines") } } + + // The lines an animated scroll passes get their wrapped heights on the way, which moves the target line down. + // The scroll still ends with that line at the top. + func testAnAnimatedScrollToLineWithWrapEndsAtTheLine() { + let editor = launch() + editor.setSoftWrap(true) + editor.setInitialText((0..<600).map { "line \($0) " + String(repeating: "word ", count: 20) }.joined(separator: "\n")) + layout(editor) + draw(editor) + editor.scrollToLine(400, animated: true) + XCTAssertLessThan(editor.contentOffset.y, CGFloat(editor.viewport.rowHeight), "the scroll is animating") + // The rows the passed lines would get from the draws on the way. + for line in 1..<400 { editor.viewport.measured(line, 3) } + spin(until: { false }, timeout: 1) + draw(editor) + XCTAssertEqual(editor.viewport.firstVisibleLine(), 400) + XCTAssertEqual(editor.viewport.scrollY, editor.viewport.rowStart(400) * editor.viewport.rowHeight) + } + + // A scroll UIKit animates (a deceleration, an animated offset) stops when scrollToLine starts. + func testAScrollToLineTakesOverAScrollInFlight() { + for animated in [false, true] { + let editor = launch() + editor.setInitialText((0..<600).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + editor.setContentOffset(CGPoint(x: 0, y: 400 * editor.viewport.rowHeight), animated: true) + editor.scrollToLine(50, animated: animated) + spin(until: { false }, timeout: 1) + draw(editor) + XCTAssertEqual(editor.viewport.firstVisibleLine(), 50, "animated \(animated)") + } + } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index d11e0a7..d26dedd 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -63,6 +63,16 @@ final class CodeEditorView: UIScrollView { static let defaultTextPadding: CGFloat = 8 static let gutterPadding: CGFloat = 8 static let caretWidth: CGFloat = 2 + /// Android's SCROLL_DURATION_MS. + static let scrollDuration: CFTimeInterval = 0.25 + + /// An animated scrollToLine in flight. + private struct LineScroll { + let line: Int + let startY: Int + let start: CFTimeInterval + let link: CADisplayLink + } // The JS thread reads the core, the last frame and the focus through these locks. private let coreLock: OSAllocatedUnfairLock @@ -132,6 +142,7 @@ final class CodeEditorView: UIScrollView { private(set) var keyboardTracker: KeyboardInsetTracker? private var ready = false private var scrollDirty = false + private var lineScroll: LineScroll? private var selectionDirty = false private var selectionViewsDirty = false private var contentDirty = false @@ -338,6 +349,7 @@ final class CodeEditorView: UIScrollView { private(set) var scrollsVertically = true func setScrollEnabled(_ enabled: Bool) { + stopLineScroll() scrollsVertically = enabled alwaysBounceVertical = enabled // A second scroll-to-top view in the window turns off the page's status bar tap. @@ -509,17 +521,49 @@ final class CodeEditorView: UIScrollView { } func scrollToLine(_ line: Int, animated: Bool) { - let target = viewport.rowStart(max(0, min(line, core.document.lineCount - 1))) * viewport.rowHeight + stopLineScroll() + // Ends a deceleration or an animated offset, as Android aborts its scroller. + setContentOffset(contentOffset, animated: false) if animated { - setContentOffset(CGPoint(x: viewport.scrollX, y: min(target, viewport.maxScrollY)), animated: true) - } else if viewport.scrollTo(viewport.scrollX, target) { + let link = CADisplayLink(target: self, selector: #selector(stepLineScroll)) + link.add(to: .main, forMode: .common) + lineScroll = LineScroll(line: line, startY: Int(contentOffset.y.rounded()), start: CACurrentMediaTime(), link: link) + } else if viewport.scrollTo(viewport.scrollX, lineTop(line)) { pushScroll() onScrolled() } } + private func lineTop(_ line: Int) -> Int { + viewport.rowStart(max(0, min(line, core.document.lineCount - 1))) * viewport.rowHeight + } + + /// Aims at the line again every frame: the wrapped lines the scroll passes take their rows on the way. + @objc private func stepLineScroll() { + guard let scroll = lineScroll else { return } + if isTracking { + stopLineScroll() + return + } + let t = min(1, (CACurrentMediaTime() - scroll.start) / Self.scrollDuration) + let eased = 1 - pow(1 - t, 3) + let target = min(lineTop(scroll.line), viewport.maxScrollY) + let y = Double(scroll.startY) + Double(target - scroll.startY) * eased + if t >= 1 { stopLineScroll() } + if viewport.scrollTo(viewport.scrollX, Int(y.rounded())) { + pushScroll() + onScrolled() + } + } + + private func stopLineScroll() { + lineScroll?.link.invalidate() + lineScroll = nil + } + /// Scrolls the least amount that shows the caret with the text padding around it. func revealSelection() { + stopLineScroll() let m = rowMetrics() let doc = core.document let head = core.selection.head @@ -627,6 +671,7 @@ final class CodeEditorView: UIScrollView { override func didMoveToWindow() { super.didMoveToWindow() if window == nil { + stopLineScroll() textInput.menu.hide() textInput.endLoupe() search?.close() From 77982b7db1bf3f90eb626d51b52c1b816feda76e Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 12:58:20 +0100 Subject: [PATCH 11/14] fix(android): end an animated scrollToLine on the line when wrap is on The scroller aimed at an offset that counted unmeasured lines as one row, and the wrapped lines it passed took their rows on the way, so a jump to line 400 of a wrapped document ended near line 99. The animation now reads the line's row start on every frame, as on iOS. --- .../sectiontn/codepad/view/CodeEditorView.kt | 7 ++-- .../codepad/view/ScrollController.kt | 40 +++++++++++++++---- .../java/codepad/example/ScrollTest.kt | 26 ++++++++++++ 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index 2b35e59..75f4729 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -447,16 +447,17 @@ class CodeEditorView(context: Context) : View(context) { } fun scrollToLine(line: Int, animated: Boolean) { - val target = viewport.rowStart(line.coerceIn(0, core.document.lineCount - 1)) * viewport.rowHeight scroller.abort() val s = viewport.scroll() if (animated) { - scroller.animateTo(s.x, s.y, s.x, target.coerceIn(0, s.maxY)) - } else if (viewport.scrollTo(s.x, target)) { + scroller.animateTo(s.x, s.y) { lineTop(line).coerceAtMost(viewport.maxScrollY) } + } else if (viewport.scrollTo(s.x, lineTop(line))) { onScrolled() } } + private fun lineTop(line: Int): Int = viewport.rowStart(line.coerceIn(0, core.document.lineCount - 1)) * viewport.rowHeight + /** Scrolls the least amount that shows the caret with the text padding around it. */ fun revealSelection() { val m = rowMetrics() diff --git a/android/src/main/java/me/sectiontn/codepad/view/ScrollController.kt b/android/src/main/java/me/sectiontn/codepad/view/ScrollController.kt index b3af9b6..27e8771 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/ScrollController.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/ScrollController.kt @@ -3,8 +3,10 @@ package me.sectiontn.codepad.view import android.content.Context import android.graphics.Canvas import android.view.View +import android.view.animation.AnimationUtils import android.widget.EdgeEffect import android.widget.OverScroller +import kotlin.math.roundToInt /** Fling physics and the four edge glows. The view keeps the scroll position, this only animates it. */ class ScrollController(context: Context, private val view: View) { @@ -14,9 +16,17 @@ class ScrollController(context: Context, private val view: View) { private val left = EdgeEffect(context) private val right = EdgeEffect(context) - val isFinished: Boolean get() = scroller.isFinished - val currX: Int get() = scroller.currX - val currY: Int get() = scroller.currY + // The animateTo target, read again every frame. + private var target: (() -> Int)? = null + private var aimed = false + private var aimX = 0 + private var aimY = 0 + private var fromY = 0 + private var started = 0L + + val isFinished: Boolean get() = target == null && scroller.isFinished + val currX: Int get() = if (aimed) aimX else scroller.currX + val currY: Int get() = if (aimed) aimY else scroller.currY val currVelocity: Float get() = scroller.currVelocity /** True between fling() and the next abort() or animateTo(), so only flings light the edges up. */ @@ -38,24 +48,40 @@ class ScrollController(context: Context, private val view: View) { } fun fling(startX: Int, startY: Int, velocityX: Int, velocityY: Int, maxX: Int, maxY: Int) { + abort() flinging = true scroller.fling(startX, startY, velocityX, velocityY, 0, maxX, 0, maxY) view.postInvalidateOnAnimation() } - fun animateTo(startX: Int, startY: Int, x: Int, y: Int) { - flinging = false - scroller.startScroll(startX, startY, x - startX, y - startY, SCROLL_DURATION_MS) + /** Scrolls vertically to [y], which can move while the scroll runs: wrapped lines take their rows on the way. */ + fun animateTo(startX: Int, startY: Int, y: () -> Int) { + abort() + target = y + aimed = true + aimX = startX + aimY = startY + fromY = startY + started = AnimationUtils.currentAnimationTimeMillis() view.postInvalidateOnAnimation() } fun abort() { flinging = false scroller.abortAnimation() + target = null + aimed = false } /** Advances a running animation. False once it is finished. */ - fun step(): Boolean = scroller.computeScrollOffset() + fun step(): Boolean { + val y = target ?: return scroller.computeScrollOffset() + val t = ((AnimationUtils.currentAnimationTimeMillis() - started).toFloat() / SCROLL_DURATION_MS).coerceAtMost(1f) + val eased = 1 - (1 - t) * (1 - t) * (1 - t) + aimY = fromY + ((y() - fromY) * eased).roundToInt() + if (t >= 1f) target = null + return true + } /** A drag went past an edge by (dx, dy) px with the finger at (x, y). */ fun pull(dx: Float, dy: Float, x: Float, y: Float, width: Int, height: Int) { diff --git a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt index cbb247a..b2edd4b 100644 --- a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt @@ -78,4 +78,30 @@ class ScrollTest { } } } + + // The lines an animated scroll passes get their wrapped heights on the way, which moves the target line down. + // The scroll still ends with that line at the top. + @Test + fun anAnimatedScrollToLineWithWrapEndsAtTheLine() { + launch().use { s -> + val editor = s.editor() + onMain { + editor.setSoftWrap(true) + editor.setInitialText((0 until 600).joinToString("\n") { "line $it " + "word ".repeat(20) }) + layout(editor) + draw(editor) + editor.scrollToLine(400, true) + assertTrue("the scroll is animating", viewportOf(editor).scrollY < viewportOf(editor).rowHeight) + // The rows the passed lines would get from the draws on the way. + for (line in 1 until 400) viewportOf(editor).measured(line, 3) + } + SystemClock.sleep(1000) + onMain { + draw(editor) + val viewport = viewportOf(editor) + assertEquals(400, viewport.firstVisibleLine()) + assertEquals(viewport.rowStart(400) * viewport.rowHeight, viewport.scrollY) + } + } + } } From 136aa34d7109bd5fed3d872277e90b060e04a0a2 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 13:19:23 +0100 Subject: [PATCH 12/14] test(ios): read the golden's language from its name in the engine test The XML internal subset golden is named xml.internal-subset, and the Swift engine test passed the whole name as the language, so that document never parsed. It now takes the part before the first dot, like the Kotlin test and the core test already do. --- tests/swift/HighlightGoldenTests.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/swift/HighlightGoldenTests.swift b/tests/swift/HighlightGoldenTests.swift index c990451..3ede7ef 100644 --- a/tests/swift/HighlightGoldenTests.swift +++ b/tests/swift/HighlightGoldenTests.swift @@ -3,7 +3,8 @@ import XCTest @testable import Codepad -/// Every sample's spans against tests/highlight/.spans, recorded from the Kotlin engine. +/// Every sample's spans against tests/highlight/.spans, recorded from the Kotlin engine, in the language before +/// the first dot of the name. final class HighlightGoldenTests: XCTestCase { private static let dir = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("highlight") @@ -30,11 +31,12 @@ final class HighlightGoldenTests: XCTestCase { XCTAssertFalse(files.isEmpty) for file in files { let id = String(file.dropLast(4)) + let language = String(id.prefix { $0 != "." }) let text = try String(contentsOf: Self.dir.appendingPathComponent(file), encoding: .utf8) let snapshots = SnapshotQueue() let core = EditorCore(text) let engine = SyntaxEngine(postToMain: { $0() }, onSnapshot: { snapshots.add($0) }) - engine.setLanguage(id) + engine.setLanguage(language) engine.attach(core) var snapshot: Snapshot? while let s = snapshots.take(10) { @@ -45,7 +47,7 @@ final class HighlightGoldenTests: XCTestCase { } let parsed = try XCTUnwrap(snapshot, "\(id) never parsed") let doc = core.document - let lang = try XCTUnwrap(LanguageRegistry.resolve(id)) + let lang = try XCTUnwrap(LanguageRegistry.resolve(language)) let actual = render(Highlighter(language: lang).spans(snapshot: parsed, doc: doc, firstLine: 0, lastLine: doc.lineCount - 1)) engine.close() let expected = try String(contentsOf: Self.dir.appendingPathComponent("\(id).spans"), encoding: .utf8) From 78d27cd57d8fa33604f7ef451a5cd5e9099ab4db Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 13:36:43 +0100 Subject: [PATCH 13/14] fix(ios): stop an animated scrollToLine when the document is replaced setText and setInitialText put the view at the top, but the display link kept aiming at the old line and scrolled the new text down to offset 8800. Both now stop the line scroll first. --- example/ios/CodepadTests/ScrollTests.swift | 23 ++++++++++++++++++++++ ios/Codepad/view/CodeEditorView.swift | 2 ++ 2 files changed, 25 insertions(+) diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index eb9907f..962b7cc 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -140,4 +140,27 @@ final class ScrollTests: XCTestCase { XCTAssertEqual(editor.viewport.firstVisibleLine(), 50, "animated \(animated)") } } + + // A document replaced during an animated scrollToLine stays at the top. + func testReplacingTheDocumentStopsAnAnimatedScrollToLine() { + let long = (0..<600).map { "line \($0)" }.joined(separator: "\n") + let replacements: [(String, (CodeEditorView) -> Void)] = [ + ("setText", { $0.setText(long, keepHistory: false) }), + ("setInitialText", { $0.setInitialText(long) }), + ] + for (name, replace) in replacements { + let editor = launch() + editor.setInitialText(long) + layout(editor) + draw(editor) + editor.scrollToLine(400, animated: true) + spin(until: { editor.contentOffset.y > 0 }, timeout: 1) + let target = CGFloat(editor.viewport.rowStart(400) * editor.viewport.rowHeight) + XCTAssertTrue(editor.contentOffset.y > 0 && editor.contentOffset.y < target, "\(name): the scroll is animating") + replace(editor) + spin(until: { false }, timeout: 1) + draw(editor) + XCTAssertEqual(editor.viewport.scrollY, 0, name) + } + } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index d26dedd..d95bcf1 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -204,6 +204,7 @@ final class CodeEditorView: UIScrollView { func setText(_ text: String, keepHistory: Bool) { textInput.session.reset() core.setText(text, keepHistory: keepHistory) + stopLineScroll() viewport.scrollTo(0, 0) pushScroll() setNeedsLayout() @@ -863,6 +864,7 @@ final class CodeEditorView: UIScrollView { cache.clear() viewport.widestLine = 0 updateGutter() + stopLineScroll() viewport.scrollTo(0, 0) pushScroll() selectionViewsDirty = true From 650c2d43d824ce01ad2b3d3e69cd53313585daf1 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 13:39:28 +0100 Subject: [PATCH 14/14] fix(android): stop an animated scrollToLine when the document is replaced setText and setInitialText put the view at the top, but the scroller kept running toward the old line and moved the new text to offset 23600. Both now abort it first. --- .../sectiontn/codepad/view/CodeEditorView.kt | 2 ++ .../java/codepad/example/ScrollTest.kt | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index 75f4729..adb8523 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -271,6 +271,7 @@ class CodeEditorView(context: Context) : View(context) { fun setText(text: String, keepHistory: Boolean) { ime.reset() core.setText(text, keepHistory) + scroller.abort() viewport.scrollTo(0, 0) restartInput() invalidate() @@ -598,6 +599,7 @@ class CodeEditorView(context: Context) : View(context) { cache.clear() viewport.widestLine = 0 updateGutter() + scroller.abort() viewport.scrollTo(0, 0) invalidate() } diff --git a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt index b2edd4b..8a81570 100644 --- a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt @@ -3,6 +3,7 @@ package codepad.example import android.os.SystemClock import android.view.KeyEvent import androidx.test.ext.junit.runners.AndroidJUnit4 +import me.sectiontn.codepad.view.CodeEditorView import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test @@ -104,4 +105,38 @@ class ScrollTest { } } } + + // A document replaced during an animated scrollToLine stays at the top. + @Test + fun replacingTheDocumentStopsAnAnimatedScrollToLine() { + val long = (0 until 600).joinToString("\n") { "line $it" } + val replacements = listOf Unit>>( + "setText" to { it.setText(long, false) }, + "setInitialText" to { it.setInitialText(long) }, + ) + for ((name, replace) in replacements) { + launch().use { s -> + val editor = s.editor() + onMain { + editor.setInitialText(long) + layout(editor) + draw(editor) + editor.scrollToLine(400, true) + } + val deadline = SystemClock.uptimeMillis() + 500 + while (onMain { viewportOf(editor).scrollY } == 0 && SystemClock.uptimeMillis() < deadline) SystemClock.sleep(8) + onMain { + val viewport = viewportOf(editor) + val target = viewport.rowStart(400) * viewport.rowHeight + assertTrue("$name: the scroll is animating", viewport.scrollY in 1 until target) + replace(editor) + } + SystemClock.sleep(1000) + onMain { + draw(editor) + assertEquals(name, 0, viewportOf(editor).scrollY) + } + } + } + } }