Intelligently select a node in Emacs with tree-sitter
Sometimes it's annoying having to manually select a variable name and copy it, especially when you deal with multiple languages.
Apart from manually selecting the text you want, you try to use mark-sexp
, which works fine but fails in the following python example when the cursor is at the character "p".
report_prefix = "report name"
In the above example, only prefix
will be selected with mark-sexp
.
There are many ways to solve this problem (e.g. use ivy-thing-at-point
).
However I found using tree-sitter and emacs-tree-sitter to be the fastest and most accurate solution.
Here's the function I wrote that implements this.
(require 'tree-sitter) (defun mark-node () "Mark the current node under cursor using tree-sitter." (interactive) (let* ((node (tree-sitter-node-at-pos)) (start-pos (tsc-node-start-position node)) (end-pos (tsc-node-end-position node))) (goto-char start-pos) (push-mark end-pos) (setq mark-active t)))
Now if you run mark-node
when your cursor is under the character "p", it'll still select report_prefix
as expected.
What's better is you can even use this to select "report name"
wherever your cursor is at, as long as it's within the quotes. All because tree-sitter recognises that it is a string in python.
report_prefix = "report name"