Function: treesit-node-first-child-for-pos

treesit-node-first-child-for-pos is a function defined in treesit.c.

Signature

(treesit-node-first-child-for-pos NODE POS &optional NAMED)

Documentation

Return the first child of NODE for buffer position POS.

Specifically, return the first child that extends beyond POS. Return nil if there is no such child. If NAMED is non-nil, look for named children only. NAMED defaults to nil. Note that this function returns an immediate child, not the smallest
(grand)child. If NODE is nil, return nil.

Other relevant functions are documented in the treesit group.

View in manual

Shortdoc

;; treesit
(treesit-node-first-child-for-pos node 1)
    e.g. => #<treesit-node (primitive_type) in 1-4>

Source Code

// Defined in /usr/src/emacs/src/treesit.c
{
  if (NILP (node))
    return Qnil;
  treesit_check_node (node);

  struct buffer *buf = XBUFFER (XTS_PARSER (XTS_NODE (node)->parser)->buffer);
  ptrdiff_t visible_beg = XTS_PARSER (XTS_NODE (node)->parser)->visible_beg;

  treesit_check_position (pos, buf);
  treesit_initialize ();

  ptrdiff_t byte_pos = buf_charpos_to_bytepos (buf, XFIXNUM (pos));
  TSNode treesit_node = XTS_NODE (node)->node;

  TSTreeCursor cursor = ts_tree_cursor_new (treesit_node);
  ptrdiff_t treesit_pos = byte_pos - visible_beg;
  bool success;
  success = treesit_cursor_first_child_for_byte (&cursor, treesit_pos,
						 !NILP (named));
  TSNode child = ts_tree_cursor_current_node (&cursor);
  ts_tree_cursor_delete (&cursor);

  if (!success)
    return Qnil;
  return make_treesit_node (XTS_NODE (node)->parser, child);
}