diff --git a/src/expand.cpp b/src/expand.cpp index cfa83b2e6..44b8a4e50 100644 --- a/src/expand.cpp +++ b/src/expand.cpp @@ -219,21 +219,24 @@ static size_t parse_slice(const wchar_t *in, wchar_t **end_ptr, std::vector -1 ? tmp1 : size + tmp1 + 1; - // Clamp to array size, but only when doing a range, - // and only when just one is too high. + // Skip sequences that are entirely outside. + // This means "17..18" expands to nothing if there are less than 17 elements. if (i1 > size && i2 > size) { continue; } - i1 = i1 < size ? i1 : size; - i2 = i2 < size ? i2 : size; - // debug( 0, L"Push range idx %d %d", i1, i2 ); short direction = i2 < i1 ? -1 : 1; // If only the beginning is negative, always go reverse. // If only the end, always go forward. // Prevents `[x..-1]` from going reverse if less than x elements are there. if (tmp1 > -1 != tmp > -1) { direction = tmp1 > -1 ? -1 : 1; + } else { + // Clamp to array size when not forcing direction + // - otherwise "2..-1" clamps both to 1 and then becomes "1..1". + i1 = i1 < size ? i1 : size; + i2 = i2 < size ? i2 : size; } + // debug( 0, L"Push range idx %d %d", i1, i2 ); for (long jjj = i1; jjj * direction <= i2 * direction; jjj += direction) { // debug(0, L"Expand range [subst]: %i\n", jjj); idx.push_back(jjj); diff --git a/tests/expansion.in b/tests/expansion.in index 2510ac1cf..f175ff7f7 100644 --- a/tests/expansion.in +++ b/tests/expansion.in @@ -71,7 +71,9 @@ expansion $foo[-10..-5] expansion (printf '%s\n' $foo)[-5..2] expansion (printf '%s\n' $foo)[-2..-1] expansion (printf '%s\n' $foo)[-10..-5] +expansion (echo one)[2..-1] +echo "# foo = " set -l foo expansion "$foo[1]" expansion $foo[1] @@ -83,11 +85,15 @@ expansion "$foo[1 2]" expansion $foo[1 2] expansion "$foo[2 1]" expansion $foo[2 1] +echo "# foo = a b c" set -l foo a b c expansion $foo[17] expansion $foo[-17] expansion $foo[17..18] expansion $foo[4..-2] +echo "# foo = a" +set -l foo a +expansion $foo[2..-1] echo "$foo[d]" echo $foo[d] diff --git a/tests/expansion.out b/tests/expansion.out index 6b8ab0743..82f3b9ee7 100644 --- a/tests/expansion.out +++ b/tests/expansion.out @@ -42,6 +42,8 @@ 0 2 fooest 0 +0 +# foo = 1 0 1 @@ -52,10 +54,13 @@ 0 1 0 +# foo = a b c 0 0 0 0 +# foo = a +0 ####################