diff --git a/src/search.c b/src/search.c index bb8ed059..490306a5 100644 --- a/src/search.c +++ b/src/search.c @@ -28,6 +28,7 @@ SEXP find_unbalanced_bracket(SEXP content, SEXP _row, SEXP _col, SEXP _skip_el) stack pos; stack codept_pos; int nbracket = 0; + int ncurrentunbalanced = 0; int nunbalanced = 0; char brac[2] = " \x00"; @@ -47,6 +48,7 @@ SEXP find_unbalanced_bracket(SEXP content, SEXP _row, SEXP _col, SEXP _skip_el) fsm_initialize(&state); stack_initialize(&pos); stack_initialize(&codept_pos); + ncurrentunbalanced = 0; while (j < n && (i < row || k <= col)) { cj = c[j]; if (0x80 <= cj && cj <= 0xbf) { @@ -66,7 +68,7 @@ SEXP find_unbalanced_bracket(SEXP content, SEXP _row, SEXP _col, SEXP _skip_el) stack_pop(&pos); stack_pop(&codept_pos); } else { - nunbalanced += 1; + ncurrentunbalanced += 1; } } } @@ -80,6 +82,7 @@ SEXP find_unbalanced_bracket(SEXP content, SEXP _row, SEXP _col, SEXP _skip_el) nunbalanced -= 1; nbracket -= 1; } + nunbalanced += ncurrentunbalanced; j = stack_pop(&pos); k = stack_pop(&codept_pos); stack_clear(&pos); diff --git a/tests/testthat/test-search.R b/tests/testthat/test-search.R index 4a2f3c34..86b43498 100644 --- a/tests/testthat/test-search.R +++ b/tests/testthat/test-search.R @@ -64,6 +64,10 @@ test_that("find_unbalanced_bracket works as expected", { expect_equal(bsearch(c("foo({ ", "}, xyz"), 1, 3)[[1]], c(0, 3)) expect_equal(bsearch(c("foo(( ", "), xyz"), 1, 3)[[1]], c(0, 3)) + # issue #530 + expect_equal(bsearch(c("if (sum()) ", "xyz"), 0, 7)[[1]], c(0, 7)) + expect_equal(bsearch(c("} if (sum()) ", "xyz"), 0, 9)[[1]], c(0, 9)) += # other brackets expect_equal(bsearch("foo[xy", 0, 5), list(c(0, 3), "[")) expect_equal(bsearch("foo{xy", 0, 5), list(c(0, 3), "{"))