Skip to content

fix: correctly resolve array index in nested arrays#17

Open
Nikita-90 wants to merge 2 commits into
phelipetls:mainfrom
Nikita-90:fix/array-index-nested
Open

fix: correctly resolve array index in nested arrays#17
Nikita-90 wants to merge 2 commits into
phelipetls:mainfrom
Nikita-90:fix/array-index-nested

Conversation

@Nikita-90

@Nikita-90 Nikita-90 commented May 5, 2026

Copy link
Copy Markdown

Problem

When the cursor is inside a deeply nested array, the array index is shown as [] instead of the actual index (e.g. [0]).

Example: with this JSON:

{
  "users": [
    {
      "orders": [
        { "id": 1 }
      ]
    }
  ]
}

With cursor on "id", the winbar shows .users[].orders[] instead of .users[0].orders[0].

Root cause

When traversing the treesitter tree upward, the original code used current_node:parent() to find which child of an array contains the cursor. This is always the direct parent of the initial cursor node, so it only matched when the array was the immediate parent. For any outer/nested array, the comparison failed and the index stayed as []. Additionally, iterating all children with ipairs counted anonymous nodes (brackets, commas), causing an off-by-one error.

Fix

For each named child of the array, walk up from current_node to check if the cursor is inside that child. This correctly handles nested arrays at any depth.

-- before
for i, child in ipairs(get_children(node)) do
  local parent = current_node:parent()
  if parent == child then
    accessor = string.format("[%d]", i - 1)
  end
end

-- after
local index = 0
for child in node:iter_children() do
  if child:named() then
    local n = current_node
    while n and n ~= node do
      if n == child then
        accessor = string.format("[%d]", index)
        break
      end
      n = n:parent()
    end
    if accessor ~= "" then break end
    index = index + 1
  end
end

When traversing the treesitter tree upward, `current_node:parent()` is
always the direct parent of the cursor node. This means array index
detection only worked when the array was the immediate parent of the
cursor, producing `[]` for all outer/nested arrays.

Track `prev_node` across iterations so that when an `array` node is
reached, we compare against the actual direct child of that array
containing the cursor.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@Nikita-90 Nikita-90 marked this pull request as draft May 5, 2026 13:09
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@Nikita-90 Nikita-90 marked this pull request as ready for review May 7, 2026 09:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant