Accessing a capture's name #2793
-
IssueI am using
but I cannot seem to find a way to access this particular name. It's not in the fields of How can that be accessed? ContextTo prevent an XY problem, I'll give context I am encountering this issue in. I'm totally happy to change approach if the current one is dumb. In the playground, input this TypeScript: let x: string = `Hello ${world}`; I am trying to separate the literal part of the string from the to-be-interpolated variable. This query:
works: Ultimately, I am trying to get the bytes ranges of The only way I can currently see is running two queries, one for all strings, one only for If a capture's name could be accessed, we could iterate over all matches once, then simply drop anything captures as |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I also tried |
Beta Was this translation helpful? Give feedback.
-
Hi! I see two solutions here, the first is to match the To more directly address your question for associating captures with their names, I believe you can use fn main() {
let text = "let x: string = `Hello ${world}`";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(tree_sitter_typescript::language_typescript())
.unwrap();
let tree = parser.parse(text, None).unwrap();
let mut cursor = tree_sitter::QueryCursor::new();
let query = tree_sitter::Query::new(
tree_sitter_typescript::language_typescript(),
r#"(template_string (template_substitution) @interpol) @whole"#,
)
.unwrap();
let whole_idx = query.capture_index_for_name("whole").unwrap();
let interpol_idx = query.capture_index_for_name("interpol").unwrap();
let query_capture = cursor
.captures(&query, tree.root_node(), text.as_bytes())
.next()
.unwrap();
let whole_node = query_capture
.0
.nodes_for_capture_index(whole_idx)
.next()
.unwrap();
let interpol_node = query_capture
.0
.nodes_for_capture_index(interpol_idx)
.next()
.unwrap();
let whole_text = whole_node.utf8_text(text.as_bytes()).unwrap().to_owned();
let interpol_text = interpol_node.utf8_text(text.as_bytes()).unwrap().to_owned();
println!("@whole: {:#?}, text: {}\n", whole_node, whole_text);
println!("@interpol: {:#?}, text: {}", interpol_node, interpol_text);
} I also tried using the built-in function
but wasn't able to see any changes. Hope this helps! :) |
Beta Was this translation helpful? Give feedback.
Hi! I see two solutions here, the first is to match the
string_fragment
field:To more directly address your question for associating captures with their names, I believe you can use
capture_idx_for_name()
along withnodes_for_capture_index()
. You mentioned using the Rust bindings, so I threw together a quick program to make sure this works as expected.