| 1 | ## Moving the selection with syntax-aware motions |
| 2 | |
| 3 | `Alt-p`, `Alt-o`, `Alt-i`, and `Alt-n` (or `Alt` and arrow keys) allow you to move the |
| 4 | selection according to its location in the syntax tree. For example, many languages have the |
| 5 | following syntax for function calls: |
| 6 | |
| 7 | ```js |
| 8 | func(arg1, arg2, arg3); |
| 9 | ``` |
| 10 | |
| 11 | A function call might be parsed by tree-sitter into a tree like the following. |
| 12 | |
| 13 | ```tsq |
| 14 | (call |
| 15 | function: (identifier) ; func |
| 16 | arguments: |
| 17 | (arguments ; (arg1, arg2, arg3) |
| 18 | (identifier) ; arg1 |
| 19 | (identifier) ; arg2 |
| 20 | (identifier))) ; arg3 |
| 21 | ``` |
| 22 | |
| 23 | Use `:tree-sitter-subtree` to view the syntax tree of the primary selection. In |
| 24 | a more intuitive tree format: |
| 25 | |
| 26 | ```text |
| 27 | ┌────┐ |
| 28 | │call│ |
| 29 | ┌─────┴────┴─────┐ |
| 30 | │ │ |
| 31 | ┌─────▼────┐ ┌────▼────┐ |
| 32 | │identifier│ │arguments│ |
| 33 | │ "func" │ ┌────┴───┬─────┴───┐ |
| 34 | └──────────┘ │ │ │ |
| 35 | │ │ │ |
| 36 | ┌─────────▼┐ ┌────▼─────┐ ┌▼─────────┐ |
| 37 | │identifier│ │identifier│ │identifier│ |
| 38 | │ "arg1" │ │ "arg2" │ │ "arg3" │ |
| 39 | └──────────┘ └──────────┘ └──────────┘ |
| 40 | ``` |
| 41 | |
| 42 | If you have a selection that wraps `arg1` (see the tree above), and you use |
| 43 | `Alt-n`, it will select the next sibling in the syntax tree: `arg2`. |
| 44 | |
| 45 | ```js |
| 46 | // before |
| 47 | func([arg1], arg2, arg3) |
| 48 | // after |
| 49 | func(arg1, [arg2], arg3); |
| 50 | ``` |
| 51 | |
| 52 | Similarly, `Alt-o` will expand the selection to the parent node, in this case, the |
| 53 | arguments node. |
| 54 | |
| 55 | ```js |
| 56 | func[(arg1, arg2, arg3)]; |
| 57 | ``` |
| 58 | |
| 59 | There is also some nuanced behavior that prevents you from getting stuck on a |
| 60 | node with no sibling. When using `Alt-p` with a selection on `arg1`, the previous |
| 61 | child node will be selected. In the event that `arg1` does not have a previous |
| 62 | sibling, the selection will move up the syntax tree and select the previous |
| 63 | element. As a result, using `Alt-p` with a selection on `arg1` will move the |
| 64 | selection to the "func" `identifier`. |
| 65 | |
| 66 | [lang-support]: ./lang-support.md |