Search code examples
org-modetreesitter

treesitter get deeply nested child


I'm making a little script using treesitter that will extract all code blocks inside an ORG file, but only if they're under an headline with a specific property (:TANGLE:).

I was able to make this query, which works, but only finds code blocks that are immediate children of the headline:

(section
    (property_drawer
        (property
            name: (expr) @prop_name (#eq? @prop_name "TANGLE")
            value: (value) @file
        )
    )
    (body
        (block
            contents: (contents) @code
        )
    )
)

It works with this org file:

* Headline
  :PROPERTIES:
  :TANGLE: file.lua
  :END:
  
  #+begin_src lua
  print("test")
  #+end_src

But not with this one, because the code block is not directly inside "Headline 1":

* Headline 1
  :PROPERTIES:
  :TANGLE: file.lua
  :END:

** Headline 2
   
   #+begin_src lua
   print("test")
   #+end_src

Is there a way using treesitter queries to get nodes nested at any depth inside the headline?


Solution

  • I couldn't find any way to do that, so in the end, I decided to do a deep search recursively.

    This was a script for neovim, so I used these functions:

    tsnode:iter_children() -- used in a for loop
    tsnode:type() -- Check the node type
    ts_utils.get_node_text() -- To get the text content of a node
    

    I hope this could be helpful for others too.