├── .github
└── FUNDING.yml
├── .gitignore
├── .vscode-test.mjs
├── .vscode
├── extensions.json
├── launch.json
├── settings.json
└── tasks.json
├── .vscodeignore
├── CHANGELOG.md
├── README.md
├── docs
└── demo.gif
├── esbuild.js
├── eslint.config.mjs
├── images
├── icon.png
├── icon_new.png
└── support.png
├── license.md
├── package-lock.json
├── package.json
├── parsers
├── tree-sitter-c.wasm
├── tree-sitter-c_sharp.wasm
├── tree-sitter-cpp.wasm
├── tree-sitter-go.wasm
├── tree-sitter-java.wasm
├── tree-sitter-javascript.wasm
├── tree-sitter-json.wasm
├── tree-sitter-lua.wasm
├── tree-sitter-php.wasm
├── tree-sitter-python.wasm
├── tree-sitter-rust.wasm
├── tree-sitter-toml.wasm
├── tree-sitter-tree-sitter.wasm
├── tree-sitter-tsx.wasm
├── tree-sitter-typescript.wasm
└── tree-sitter-yaml.wasm
├── src
├── config.ts
├── configurations
│ ├── configGeneration.ts
│ ├── generateKeybindings.ts
│ ├── generateVimKeybinds.ts
│ └── migrateVimPositionals.ts
├── context
│ └── context.ts
├── editor
│ ├── editor.ts
│ └── editorContext.ts
├── extension.ts
├── motions
│ ├── commandFunctions.ts
│ ├── commands.ts
│ ├── modifiers.ts
│ └── queries
│ │ ├── Array.ts
│ │ ├── Conditional.ts
│ │ ├── Function.ts
│ │ ├── Lhs.ts
│ │ ├── Loop.ts
│ │ ├── Node.ts
│ │ ├── Object.ts
│ │ ├── Params.ts
│ │ ├── Rhs.ts
│ │ ├── String.ts
│ │ ├── Type.ts
│ │ ├── Variables.ts
│ │ ├── call.ts
│ │ ├── class.ts
│ │ ├── comment.ts
│ │ ├── innerArray.ts
│ │ ├── innerCall.ts
│ │ ├── innerClass.ts
│ │ ├── innerConditional.ts
│ │ ├── innerFunction.ts
│ │ ├── innerLhs.ts
│ │ ├── innerLoop.ts
│ │ ├── innerNode.ts
│ │ ├── innerObject.ts
│ │ ├── innerParams.ts
│ │ ├── innerRhs.ts
│ │ ├── innerString.ts
│ │ ├── innerType.ts
│ │ └── innercomment.ts
├── parsing
│ ├── nodes.ts
│ ├── parser.ts
│ └── position.ts
├── playgrounds
│ ├── playground.c
│ ├── playground.cpp
│ ├── playground.cproj
│ ├── playground.cs
│ ├── playground.css
│ ├── playground.go
│ ├── playground.java
│ ├── playground.js
│ ├── playground.json
│ ├── playground.jsonc
│ ├── playground.jsx
│ ├── playground.lua
│ ├── playground.php
│ ├── playground.py
│ ├── playground.rs
│ ├── playground.toml
│ ├── playground.ts
│ ├── playground.tsx
│ └── playground.yaml
├── state
│ └── updates
│ │ └── new_keybindings.ts
├── test
│ └── extension.test.ts
├── types
│ └── global.d.ts
└── utils.ts
└── tsconfig.json
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: rodrigoscola
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12 | polar: # Replace with a single Polar username
13 | buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
14 | thanks_dev: # Replace with a single thanks.dev username
15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
3 | .vscode-test
4 | .idea
5 |
6 | dist
7 | out
8 | bugs
9 |
10 | .vscode-test
11 | .vscode/settings.json
12 |
13 | commands.json
14 | keybinds.json
15 | vim_keybinds.json
16 | vscode-text-objects.sln
17 |
18 | support_readme.md
19 |
20 | retrospective.md
21 | **/*.vsix
22 | *.vsix
23 |
24 | things.md
25 |
--------------------------------------------------------------------------------
/.vscode-test.mjs:
--------------------------------------------------------------------------------
1 | import { defineConfig } from '@vscode/test-cli';
2 |
3 | export default defineConfig({
4 | files: 'dist/test/**/*.test.js',
5 | mocha: {
6 | timeout:5000
7 | },
8 | });
9 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | // See http://go.microsoft.com/fwlink/?LinkId=827846
3 | // for the documentation about the extensions.json format
4 | "recommendations": [
5 | "dbaeumer.vscode-eslint",
6 | "connor4312.esbuild-problem-matchers",
7 | "ms-vscode.extension-test-runner",
8 | "rodrigoscola.vscode-textobjects"
9 | ]
10 | }
11 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "Run Extension",
6 | "type": "extensionHost",
7 | "request": "launch",
8 | "args": [
9 | "--extensionDevelopmentPath=${workspaceFolder}",
10 | "${workspaceFolder}/src/playgrounds/playground.php"
11 | ],
12 | "outFiles": ["${workspaceFolder}/dist/**/*.js"],
13 | "preLaunchTask": "${defaultBuildTask}"
14 | }
15 | ]
16 | }
17 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {}
2 |
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | // See https://go.microsoft.com/fwlink/?LinkId=733558
2 | // for the documentation about the tasks.json format
3 | {
4 | "version": "2.0.0",
5 | "tasks": [
6 | {
7 | "label": "watch",
8 | "dependsOn": ["npm: watch:tsc", "npm: watch:esbuild"],
9 | "presentation": {
10 | "reveal": "always"
11 | },
12 | "group": {
13 | "kind": "build",
14 | "isDefault": true
15 | }
16 | },
17 | {
18 | "type": "npm",
19 | "script": "watch:esbuild",
20 | "group": "build",
21 | "problemMatcher": "$esbuild-watch",
22 | "isBackground": true,
23 | "label": "npm: watch:esbuild",
24 | "presentation": {
25 | "group": "watch",
26 | "reveal": "always"
27 | }
28 | },
29 | {
30 | "type": "npm",
31 | "script": "watch:tsc",
32 | "group": "build",
33 | "problemMatcher": "$tsc-watch",
34 | "isBackground": true,
35 | "label": "npm: watch:tsc",
36 | "presentation": {
37 | "group": "watch",
38 | "reveal": "always"
39 | }
40 | },
41 | {
42 | "type": "npm",
43 | "script": "watch-tests",
44 | "problemMatcher": "$tsc-watch",
45 | "isBackground": true,
46 | "presentation": {
47 | "reveal": "always",
48 | "group": "watchers"
49 | },
50 | "group": "build"
51 | },
52 |
53 | ]
54 | }
55 |
--------------------------------------------------------------------------------
/.vscodeignore:
--------------------------------------------------------------------------------
1 | .vscode/**
2 | .vscode-test/**
3 | out/**
4 | node_modules/**
5 | src/**
6 | .gitignore
7 | .yarnrc
8 | esbuild.js
9 | vsc-extension-quickstart.md
10 | **/tsconfig.json
11 | **/eslint.config.mjs
12 | **/*.map
13 | **/*.ts
14 | **/.vscode-test.*
15 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 |
3 | ## [0.2.4]
4 |
5 | - Added a new Language: PHP!
6 |
7 | ## [0.2.2]
8 |
9 | After some bugs on the vim keybind generation and position migration.
10 |
11 | - changed the `vimGenerateKeybinds` commands to show a new editor window, instead of automatically changing it (it deleted some comments)
12 |
13 | - Added a comment on the `migratePositionals` command to warn about comment removal on auto upgrade
14 |
15 | thanks to [Josh](https://github.com/JoshPaulie) and [nv-pipo](https://github.com/nv-pipo) for discovering this.
16 |
17 | ## [0.2.0]
18 |
19 | This is a big one 🎊🎊🎊! We added a new motion specification, new way to configure and generate your keybindings and migration to the new model!
20 |
21 | ## New motion specification: Position
22 |
23 | This was a big thing that was missing in the initial release. A way for you to explicitelly go to the end of an object, either forwards or backwards.
24 |
25 | For now only the `go to` motion has this hability, but if theres a community want for this, we can add it to all the other ones.
26 |
27 | To migrate your old configuration to the new configuration, either accept the migration prompt, or execute the command `vscode-textobjects.migrateVimPositionals`.
28 |
29 | ## A New way to configure and generate your keybindings
30 |
31 | There was a lot to improve in the keybinds and configuration department. If you wanted to change a motion key you had to update all the motions to update the one keystroke. Now you can update your settings with commands!
32 |
33 | to change a specific key, use the `vscode-textobjects.keybindings`. Then if you are not using the `vim` extension, use the command `Generate Keybindings`. It will open a new window with all your new keybindings for you to paste in your keyboard json config. To see that configuration, press CTRL+SHIFT+P and type `Preferences: Open Keyboard shortcuts (JSON)`.
34 |
35 | if you are using the [Vim extension](https://marketplace.visualstudio.com/items?itemName=vscodevim.vim). Alter your keys in `vscode-textobjects.vimKeybindings`, then use the command `Generate Vim Keybinds`. It will now update your keybinds and they will be stored in `normalModeKeybindings`
36 |
37 | ## Contribute
38 |
39 | If you enjoy how the extension has been coming along, please consider contributing! I love developing tools and this helps me a ton!
40 |
41 | [Donate Here!](https://ko-fi.com/rodrigoscola)
42 |
43 | ---
44 |
45 | ## [0.1.33]
46 |
47 | In the continuation to make `Vscode-Text-Objects` a seemless integration with vscode and the vim extension. We've done some updates to how we handle the configuration and keybinds.
48 |
49 | The biggest change is that some keybinds overwrote vim default motions, we've updated the default keybindings. Some of you might be affected if you use the `parameters`, `strings` and `type` motions. If you want the previous keybinds, i suggest you to change it on te configuration file or in the `shortcuts` tab.
50 |
51 | - Non obstructive vim keybindings. (#3; Thanks to [Josh](https://github.com/JoshPaulie))
52 |
53 | - Added a `getting_started.md` guide for vim users.
54 |
55 | - Updated vim keybindings were clauses that were covered by the vim extension by default
56 |
57 | - Added a [support me page](https://ko-fi.com/rodrigoscola) (#2; Thanks to [Rob](https://github.com/RobPruzan))
58 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Vscode Text Objects
4 |
5 | With Vscode Text Objects you can select, delete, copy and go to text in a more fluid way than you have ever experienced.
6 |
7 |
8 |
9 | 
10 |
11 | ## Getting started
12 |
13 | To change your keybinds, you need to update your `vscode-textobjects.keybindings` to the shortcut you want. Then execute the command `vscode-textobjects.generateKeybinds`. Copy and paste the output on your vscode keybinds (`Preferences: Open Keyboard shortcuts (JSON)`).
14 |
15 | ### The Vim way
16 |
17 | To enable Vim integration, wich adds the commands to select, delete, copy and change as motions that you can activate using the vim motions syntax!
18 |
19 | To enable the deletion, copying and changing motions to go to your register instead of your clipboard. Go to your `settings.json` and paste this:
20 |
21 | ```json
22 | "vscode-textobjects.vimEnabled": true,
23 | ```
24 |
25 | #### Changing the keybinds
26 |
27 | If you are using the [Vim extension](https://marketplace.visualstudio.com/items?itemName=vscodevim.vim), you need to change the shortcuts in `vscode-textobjects.vimKeybinds` to the key that you want, then use the command `Generate Vim Keybinds`. It will show you a new window with your new keybinds that you need to paste on your `settings.json`
28 |
29 | ## Supported Languages
30 |
31 | You can use it in a variety of languages such as:
32 |
33 | - Javascript and JSX
34 | - Typescript and TSX
35 | - Python
36 | - RUST
37 | - Golang
38 | - C#
39 | - C++
40 | - C
41 | - PHP
42 | - Java
43 | - Lua
44 | - Toml
45 | - Yaml
46 | - JSON
47 |
48 |
49 |
50 | If you enjoy this extension, consider supporting it. You can donate it on ko-fi or paypal directly. It will encourage me to make more extensions and make them better and better!
51 |
52 |
53 |
54 |
55 |
56 |
57 | ## VIM Integration
58 |
59 | Example:
60 |
61 | To select a function, just press:
62 |
63 | v a f
64 |
65 | To select the inner of a function, just press:
66 |
67 | v i f
68 |
69 | to go to a function, just press:
70 |
71 | [ f
72 |
73 | to go to the inside of a function, just press:
74 |
75 | [ F
76 |
77 | to go to back a function, just press:
78 |
79 | ] f
80 |
81 | to go back to the inside of a function, just press:
82 |
83 | ] F
84 |
85 | ### Nodes Support
86 |
87 | The current Fully supported nodes are:
88 |
89 | - Functions
90 | - Loops
91 | - Objects
92 | - Arrays
93 | - Function calls
94 | - Classes
95 | - Comments
96 | - Parameters
97 | - If and else statements, switches, ternaries, conditionals in generals
98 | - Strings
99 | - Types
100 | - Nodes
101 | - Variables
102 | - Right Hand Variable Assignment
103 | - Left Hand Variable Assignment
104 |
105 | ### Misc
106 |
107 | - remove the console logs - DONE
108 | - make sure keybinds and vim are okay - DONE
109 | - do a nice landing page - DONE
110 |
111 | - Make an icon, revamp the name?
112 | - LAUNCH (add tags and releases)
113 |
114 | # Keybinds
115 |
116 | The current keybinds for all the nodes are:
117 |
118 | - f - Functions
119 | - l - Loops
120 | - o - Objects
121 | - a - Arrays
122 | - m - Function calls
123 | - k - Classes
124 | - c - Comments
125 | - p - Parameters
126 | - i - If and else statements, switches, ternaries, conditionals in generals
127 | - s - Strings
128 | - t - Types
129 | - n - Nodes
130 | - v - Variables
131 | - r - Right Hand Variable Assignment
132 | - h - Left Hand Variable Assignment
133 |
134 | # Huge Thanks
135 |
136 | Thank you [nvim-treesitter-textobjects](https://github.com/nvim-treesitter/nvim-treesitter-textobjects) for the huge inspiration. You were the reason that i wanted to make this extension in vscode and the thing i miss about [neovim](https://github.com/neovim/neovim/) the most.
137 |
138 | ## Disclaimer
139 |
140 | Although i like this extension, I am uncertain about the development past my needs. Since extension development is not my career (at least not for now). I dont intend to have a lot going on for this extension.
141 |
142 | # Update material
143 |
144 | - add an start and end so we can goto start and goto end of a node
145 |
--------------------------------------------------------------------------------
/docs/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/docs/demo.gif
--------------------------------------------------------------------------------
/esbuild.js:
--------------------------------------------------------------------------------
1 | const esbuild = require('esbuild');
2 |
3 | const production = process.argv.includes('--production');
4 | const watch = process.argv.includes('--watch');
5 |
6 | /**
7 | * @type {import('esbuild').Plugin}
8 | */
9 | const esbuildProblemMatcherPlugin = {
10 | name: 'esbuild-problem-matcher',
11 |
12 | setup(build) {
13 | build.onStart(() => {
14 | console.log('[watch] build started');
15 | });
16 | build.onEnd((result) => {
17 | result.errors.forEach(({ text, location }) => {
18 | console.error(`✘ [ERROR] ${text}`);
19 | console.error(` ${location.file}:${location.line}:${location.column}:`);
20 | });
21 | console.log('[watch] build finished');
22 | });
23 | },
24 | };
25 |
26 | async function main() {
27 | const ctx = await esbuild.context({
28 | entryPoints: ['src/extension.ts'],
29 | bundle: true,
30 | format: 'cjs',
31 | minify: production,
32 | sourcemap: !production,
33 | sourcesContent: false,
34 | platform: 'node',
35 | outfile: 'dist/extension.js',
36 | external: ['vscode'],
37 | logLevel: 'silent',
38 | plugins: [
39 | /* add to the end of plugins array */
40 | esbuildProblemMatcherPlugin,
41 | ],
42 | });
43 | if (watch) {
44 | await ctx.watch();
45 | } else {
46 | await ctx.rebuild();
47 | await ctx.dispose();
48 | }
49 | }
50 |
51 | main().catch((e) => {
52 | console.error(e);
53 | process.exit(1);
54 | });
55 |
--------------------------------------------------------------------------------
/eslint.config.mjs:
--------------------------------------------------------------------------------
1 | import typescriptEslint from '@typescript-eslint/eslint-plugin';
2 | import tsParser from '@typescript-eslint/parser';
3 |
4 | export default [
5 | {
6 | files: ['**/*.ts'],
7 | },
8 | {
9 | plugins: {
10 | '@typescript-eslint': typescriptEslint,
11 | },
12 |
13 | languageOptions: {
14 | parser: tsParser,
15 | ecmaVersion: 2022,
16 | sourceType: 'module',
17 | },
18 |
19 | rules: {
20 | '@typescript-eslint/naming-convention': [
21 | 'warn',
22 | {
23 | selector: 'import',
24 | format: ['camelCase', 'PascalCase'],
25 | },
26 | ],
27 |
28 | curly: 'warn',
29 | eqeqeq: 'warn',
30 | 'no-throw-literal': 'warn',
31 | semi: 'warn',
32 | '@typescript-eslint/explicit-function-return-type': [
33 | 'warn',
34 | {
35 | allowExpressions: false,
36 | allowTypedFunctionExpressions: true,
37 | allowHigherOrderFunctions: true,
38 | allowDirectConstAssertionInArrowFunctions: true,
39 | allowConciseArrowFunctionExpressionsStartingWithVoid: true,
40 | },
41 | ],
42 | },
43 | },
44 | ];
45 |
--------------------------------------------------------------------------------
/images/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/images/icon.png
--------------------------------------------------------------------------------
/images/icon_new.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/images/icon_new.png
--------------------------------------------------------------------------------
/images/support.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/images/support.png
--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) [year] [fullname]
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/parsers/tree-sitter-c.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-c.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-c_sharp.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-c_sharp.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-cpp.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-cpp.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-go.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-go.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-java.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-java.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-javascript.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-javascript.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-json.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-json.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-lua.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-lua.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-php.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-php.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-python.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-python.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-rust.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-rust.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-toml.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-toml.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-tree-sitter.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-tree-sitter.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-tsx.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-tsx.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-typescript.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-typescript.wasm
--------------------------------------------------------------------------------
/parsers/tree-sitter-yaml.wasm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RodrigoScola/vscode-text-objects/cf39a66055c2dcdd0a8b56bdb19da77eb3f7d351/parsers/tree-sitter-yaml.wasm
--------------------------------------------------------------------------------
/src/config.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import * as vscode from 'vscode';
3 | import { WorkspaceConfiguration } from 'vscode';
4 |
5 | export class Config {
6 | private config: WorkspaceConfiguration;
7 | constructor(configuration: WorkspaceConfiguration) {
8 | this.config = configuration;
9 | }
10 |
11 | vimActive(): boolean {
12 | assert(this.config, ' config has not been setup');
13 |
14 | const value = this.config.get('vimEnabled');
15 |
16 | assert(typeof value !== 'undefined' && value !== null, 'value was not found');
17 |
18 | return Boolean(value);
19 | }
20 | vimkeybindingConfig(): VimKeyboardConfig {
21 | assert(this.config, ' config has not been setup');
22 |
23 | const value = this.config.get('vimKeybindings');
24 |
25 | assert(typeof value !== 'undefined' && value !== null, 'value was not found');
26 | return value as VimKeyboardConfig;
27 | }
28 | keybindingConfig(): DefaultKeyboardConfig {
29 | assert(this.config, ' config has not been setup');
30 |
31 | const value = this.config.get('keybindings');
32 |
33 | assert(typeof value !== 'undefined' && value !== null, 'value was not found');
34 |
35 | return value as DefaultKeyboardConfig;
36 | }
37 |
38 | copyOnDelete(): boolean {
39 | assert(this.config, ' config has not been setup');
40 |
41 | const value = this.config.get('copyOnDelete');
42 |
43 | assert(typeof value !== 'undefined' && value !== null, 'value was not found');
44 | return Boolean(value);
45 | }
46 | }
47 | export function getConfig(): Config {
48 | return new Config(vscode.workspace.getConfiguration('vscode-textobjects'));
49 | }
50 |
--------------------------------------------------------------------------------
/src/configurations/configGeneration.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 |
3 | import fs from 'fs';
4 | import path from 'path';
5 | import { getCommandName, getCommandNameWithoutPosition } from '../motions/commands';
6 | import { getConfig } from '../config';
7 |
8 | /**
9 | * this is not supposed to be pretty, this is just so i can generate the keybinds, vim integration or the commands automatically
10 | *
11 | */
12 | export function makeName(str: string): string {
13 | return `vscode-textobjects.${str}`;
14 | }
15 |
16 | export function formatKeybindCommands(commands: Command[]): Record[] {
17 | const keybindCommands: Record> = {};
18 |
19 | for (const command of commands) {
20 | let actionName: string = command.action;
21 |
22 | if (command.action === 'goTo') {
23 | actionName = 'Go To';
24 | } else {
25 | actionName = actionName[0].toUpperCase() + actionName.slice(1);
26 | }
27 | if (command.action === 'yank') {
28 | actionName = 'Copy';
29 | }
30 |
31 | const node: Record = {
32 | command: makeName(getCommandName(command)),
33 | title: `${actionName} ${command.direction} ${command.scope} ${command.name} ${command.position}`,
34 | when: `editorTextFocus `,
35 | };
36 |
37 | //remove this in a future patch
38 | if (command.action === 'goTo') {
39 | const nodeWithoutPosition = {
40 | command: makeName(getCommandNameWithoutPosition(command)),
41 | title: `${actionName} ${command.direction} ${command.scope} ${command.name}`,
42 | when: `editorTextFocus `,
43 | };
44 |
45 | keybindCommands[nodeWithoutPosition.command] = nodeWithoutPosition;
46 | }
47 |
48 | keybindCommands[node.command] = node;
49 | }
50 | return Object.values(keybindCommands);
51 | }
52 |
53 | export function saveCommands(commands: Record[]): void {
54 | fs.writeFileSync(
55 | path.join(__dirname, '..', 'commands.json'),
56 |
57 | JSON.stringify(commands, null, 2)
58 | );
59 | }
60 |
61 | //todo: if this becomes a bigger thing, see if the values still need to be hardcoded, they could be in the user config and we get the defaults or the user preffered keybind from there
62 | function getkeyForCommandName(name: CommandNames, config: KeyboardConfig): string {
63 | if (!(name in config)) {
64 | throw new Error(`invalid keybinding for ${name}`);
65 | }
66 | return config[name];
67 | }
68 |
69 | function getKeyForCommand(command: Command, config: KeyboardMotionConfig): string {
70 | if (command.action === 'goTo' && command.position === 'start') {
71 | return config['go to start'];
72 | } else if (command.action === 'goTo' && command.position === 'end') {
73 | return config['go to end'];
74 | } else if (command.action === 'select' && command.scope === 'inner') {
75 | return config['select inner'];
76 | } else if (command.action === 'select' && command.scope === 'outer') {
77 | return config['select outer'];
78 | } else if (command.action === 'delete' && command.scope === 'outer') {
79 | return config['delete outer'];
80 | } else if (command.action === 'delete' && command.scope === 'inner') {
81 | return config['delete inner'];
82 | } else if (command.action === 'yank' && command.scope === 'outer') {
83 | return config['yank outer'];
84 | }
85 | throw new Error('did not implement: ' + getCommandName(command));
86 | }
87 |
88 | export function getKeyboardKeybinds(commands: Command[], config: DefaultKeyboardConfig): KeyboardKeybind[] {
89 | const total: KeyboardKeybind[] = [];
90 | for (const command of commands) {
91 | if (
92 | command.action === 'change' ||
93 | (command.action === 'yank' && command.scope === 'inner') ||
94 | (command.action === 'goTo' && command.scope === 'inner')
95 | ) {
96 | //actions that are only with vim integration
97 | continue;
98 | }
99 | let winActivation = ['ctrl+alt'];
100 | let macActivation = ['cmd+alt'];
101 |
102 | const node: {
103 | command: string;
104 | when: string;
105 | mac?: string;
106 | key?: string;
107 | } = {
108 | command: `${makeName(getCommandName(command))}`,
109 | when: 'editorTextFocus',
110 | };
111 |
112 | let winKey = ['ctrl+alt'];
113 | let macKey = ['cmd+alt'];
114 |
115 | if (command.direction === 'previous') {
116 | winActivation.push('shift');
117 | macActivation.push('shift');
118 | winActivation.push(getKeyForCommand(command, config).toUpperCase());
119 | macActivation.push(getKeyForCommand(command, config).toUpperCase());
120 |
121 | winKey.push('shift');
122 | macKey.push('shift');
123 | winKey.push(getkeyForCommandName(command.name, config).toUpperCase());
124 | macKey.push(getkeyForCommandName(command.name, config).toUpperCase());
125 | } else {
126 | winActivation.push(getKeyForCommand(command, config));
127 | macActivation.push(getKeyForCommand(command, config));
128 |
129 | winKey.push(getkeyForCommandName(command.name, config));
130 | macKey.push(getkeyForCommandName(command.name, config));
131 | }
132 |
133 | node.key = [winActivation.join('+'), winKey.join('+')].join(' ');
134 | node.mac = [macActivation.join('+'), macKey.join('+')].join(' ');
135 |
136 | total.push(node);
137 | }
138 | return total;
139 | }
140 |
141 | export function saveKeybinds(commands: Command[]): void {
142 | const keyboardConfig = getConfig().keybindingConfig();
143 | const total = getKeyboardKeybinds(commands, keyboardConfig);
144 |
145 | fs.writeFileSync(
146 | path.join(__dirname, '..', 'keybinds.json'),
147 |
148 | JSON.stringify(total, null, 2)
149 | );
150 | }
151 |
152 | function getVimKeyForCommandAction(action: CommandAction, config: VimMotionConfig): string {
153 | if (action === 'change') {
154 | return config.change;
155 | } else if (action === 'delete') {
156 | return config.delete;
157 | } else if (action === 'select') {
158 | return config.select;
159 | } else if (action === 'yank') {
160 | return config.yank;
161 | }
162 | throw new Error('forgot to implement: ' + action);
163 | }
164 |
165 | function getKeyForCommandScope(scope: CommandScope, config: ScopeConfig): string {
166 | if (scope === 'inner') {
167 | return config.inner;
168 | } else if (scope === 'outer') {
169 | return config.outer;
170 | }
171 |
172 | throw new Error('forgot to implement: ' + scope);
173 | }
174 |
175 | function getGoToKeyForDirectionAndPosition(dir: CommandDirection, pos: CommandPosition): string[] {
176 | const config = getConfig().vimkeybindingConfig();
177 |
178 | if (dir === 'next' && pos === 'start') {
179 | return config['go to next start'].split(' ');
180 | } else if (dir === 'previous' && pos === 'start') {
181 | return config['go to previous start'].split(' ');
182 | } else if (dir === 'next' && pos === 'end') {
183 | return config['go to next end'].split(' ');
184 | } else if (dir === 'previous' && pos === 'end') {
185 | return config['go to previous end'].split(' ');
186 | }
187 | throw new Error('forgot to implement:' + dir);
188 | }
189 |
190 | export function GetVimKeybindings(commands: Command[]): VimKeybinding[] {
191 | const keybindings: VimKeybinding[] = [];
192 |
193 | const keybindConfig = getConfig().vimkeybindingConfig();
194 |
195 | for (const command of commands) {
196 | let key: string[] = [];
197 |
198 | if (command.action === 'goTo') {
199 | let dirKey = getkeyForCommandName(command.name, keybindConfig);
200 |
201 | if (command.scope === 'inner') {
202 | dirKey = dirKey.toUpperCase();
203 | }
204 |
205 | key = getGoToKeyForDirectionAndPosition(command.direction, command.position).concat(dirKey);
206 | } else {
207 | key = [
208 | getVimKeyForCommandAction(command.action, keybindConfig),
209 | getKeyForCommandScope(command.scope, keybindConfig),
210 | command.direction === 'next'
211 | ? getkeyForCommandName(command.name, keybindConfig)
212 | : getkeyForCommandName(command.name, keybindConfig).toUpperCase(),
213 | ];
214 | }
215 |
216 | const node: VimKeybinding = {
217 | before: key,
218 | commands: [makeName(getCommandName(command))],
219 | };
220 |
221 | keybindings.push(node);
222 | }
223 | return keybindings;
224 | }
225 |
226 | export function saveVimKeybinds(commands: Command[]): void {
227 | const total = GetVimKeybindings(commands);
228 |
229 | assert.equal(total.length, commands.length);
230 |
231 | fs.writeFileSync(
232 | path.join(__dirname, '..', 'vim_keybinds.json'),
233 |
234 | JSON.stringify(total, null, 1)
235 | );
236 | }
237 |
--------------------------------------------------------------------------------
/src/configurations/generateKeybindings.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import { getKeyboardKeybinds } from './configGeneration';
3 | import { commands } from '../motions/commands';
4 | import { getConfig } from '../config';
5 | export async function GenerateKeyboardKeybindings(): Promise {
6 | const keyboardConfig = getConfig().keybindingConfig();
7 | const total = getKeyboardKeybinds(commands, keyboardConfig);
8 |
9 | const doc = await vscode.workspace.openTextDocument({
10 | language: 'jsonc',
11 | content: JSON.stringify(total, null, 1),
12 | });
13 |
14 | await vscode.window.showTextDocument(doc, { preview: true });
15 |
16 | try {
17 | vscode.commands.executeCommand('editor.action.formatDocument');
18 | } catch (err) {}
19 | }
20 |
--------------------------------------------------------------------------------
/src/configurations/generateVimKeybinds.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import { GetVimKeybindings, makeName } from './configGeneration';
3 | import { commands } from '../motions/commands';
4 |
5 | export async function GenerateVimKeybinds(): Promise {
6 | const doc = await vscode.workspace.openTextDocument({
7 | language: 'jsonc',
8 | content: JSON.stringify(GetVimKeybindings(commands), null, 1),
9 | });
10 |
11 | await vscode.window.showTextDocument(doc);
12 |
13 | try {
14 | vscode.commands.executeCommand('editor.action.formatDocument');
15 | } catch (err) {}
16 | }
17 |
18 | // export async function GenerateVimKeybinds(): Promise {
19 | // const keybinds = GetVimKeybindings(commands);
20 |
21 | // const config = vscode.workspace.getConfiguration('vim');
22 |
23 | // if (!config) {
24 | // return;
25 | // }
26 |
27 | // const keybind = config.inspect('normalModeKeyBindings');
28 |
29 | // if (!keybind) {
30 | // return;
31 | // }
32 |
33 | // let keybindValues: VimKeybinding[] = (keybind.globalValue as VimKeybinding[]) || [];
34 |
35 | // const previousKeybinds: VimKeybinding[] = [];
36 | // const nameToCommand: Record = {};
37 |
38 | // for (const keybind of keybindValues) {
39 | // if (
40 | // !('commands' in keybind) ||
41 | // !Array.isArray(keybind.commands) ||
42 | // keybind.commands.length !== 1 ||
43 | // !keybind.commands[0] ||
44 | // !keybind.commands[0].includes(makeName(''))
45 | // ) {
46 | // previousKeybinds.push(keybind);
47 | // continue;
48 | // }
49 |
50 | // nameToCommand[keybind.commands[0]] = keybind;
51 | // }
52 |
53 | // for (const keybind of keybinds) {
54 | // if (
55 | // !(keybind.commands[0] in nameToCommand) ||
56 | // ('before' in keybind &&
57 | // keybind.before.join(',') !== nameToCommand[keybind.commands[0]].before.join(','))
58 | // ) {
59 | // nameToCommand[keybind.commands[0]] = keybind;
60 | // }
61 | // }
62 |
63 | // config
64 | // .update('normalModeKeyBindings', previousKeybinds.concat(Object.values(nameToCommand)), true)
65 | // .then(() => {
66 | // vscode.window.showInformationMessage('Keybinds updated in normalModeKeybindings');
67 | // });
68 | // }
69 |
--------------------------------------------------------------------------------
/src/configurations/migrateVimPositionals.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import assert from 'assert';
3 | import { getContext } from '../context/context';
4 | import { EditorScope, ProcessFlow } from '../editor/editorContext';
5 | import { commands, getCommandName, getCommandNameWithoutPosition } from '../motions/commands';
6 | import { makeName } from './configGeneration';
7 |
8 | export function automaticProcess(): void {
9 | checkVimPositionals();
10 | }
11 | export function getVimSettingsNames(): string[] {
12 | return [
13 | 'insertModeKeyBindingsNonRecursive',
14 | 'insertModeKeyBindings',
15 | 'normalModeKeyBindings',
16 | 'normalModeKeyBindingsNonRecursive',
17 | 'visualModeKeyBindingsNonRecursive',
18 | 'visualModeKeyBindings',
19 | 'operatorPendingModeKeyBindingsNonRecursive',
20 | 'operatorPendingModeKeyBindings',
21 | ];
22 | }
23 |
24 | function checkVimPositionals(): void {
25 | const ctx = getContext();
26 |
27 | const config = vscode.workspace.getConfiguration('vim');
28 | if (!config) {
29 | return;
30 | }
31 |
32 | assert(ctx.extensionContext, 'extension started but no vscode extension context?');
33 |
34 | const shouldCheck = ctx.extensionContext.getState('check_vim_positional_commands', EditorScope.global);
35 |
36 | if (Boolean(shouldCheck) && shouldCheck === ProcessFlow.DONT_ASK) {
37 | return;
38 | }
39 |
40 | if (!hasInvalidVimPositionals(config)) {
41 | return;
42 | }
43 |
44 | vscode.window
45 | .showWarningMessage(
46 | 'You have an invalid command. do you want to migrate changes? If there are comments inside your vim settings, they will get removed. To circumvent that, use the command "generateVimKeybinds" and copy-paste your new keybinds on your vim settings. ',
47 | 'Yes',
48 | 'Dont ask me again'
49 | )
50 | .then((r) => {
51 | if (!r) {
52 | return;
53 | }
54 |
55 | if (r === 'Dont ask me again') {
56 | ctx.extensionContext?.updateState(
57 | 'check_vim_positional_commands',
58 | ProcessFlow.DONT_ASK,
59 | EditorScope.global
60 | );
61 | return;
62 | }
63 |
64 | MigratePositionalCommand(config);
65 |
66 | ctx.extensionContext?.updateState(
67 | 'check_vim_positional_commands',
68 | ProcessFlow.EXECUTED,
69 | EditorScope.global
70 | );
71 | });
72 | }
73 |
74 | export function MigratePositionalCommand(config: vscode.WorkspaceConfiguration): void {
75 | if (!config) {
76 | return;
77 | }
78 | const settings = getVimSettingsNames();
79 | for (let i = 0; i < settings.length; i++) {
80 | const settingName = settings[i];
81 |
82 | const conf = config.inspect(settingName);
83 | if (!conf) {
84 | continue;
85 | }
86 |
87 | if (isConfig(conf.globalValue)) {
88 | config.update(settingName, migratePositionals(conf.globalValue), true);
89 | }
90 |
91 | if (isConfig(conf.workspaceValue)) {
92 | config.update(settingName, migratePositionals(conf.workspaceValue), false);
93 | }
94 |
95 | if (isConfig(conf.workspaceFolderValue)) {
96 | config.update(settingName, migratePositionals(conf.workspaceFolderValue), null);
97 | }
98 | }
99 | }
100 |
101 | function isConfig(conf: unknown): conf is { commands: string[] }[] {
102 | return (typeof conf === 'object' && conf && Array.isArray(conf)) as boolean;
103 | }
104 |
105 | function migratePositionals(conf: { commands: string[] }[]): { commands: string[] }[] {
106 | const names: Record = commands.reduce((all: Record, item) => {
107 | if (item.action === 'goTo' && item.position === 'end') {
108 | return all;
109 | }
110 | all[makeName(getCommandNameWithoutPosition(item))] = item;
111 | return all;
112 | }, {});
113 |
114 | for (const command of conf) {
115 | if (!('commands' in command) || !Array.isArray(command.commands)) {
116 | continue;
117 | }
118 |
119 | for (let i = 0; i < command.commands.length; i++) {
120 | const name = command.commands[i];
121 |
122 | if (name in names) {
123 | command.commands[i] = makeName(getCommandName(names[name]));
124 | }
125 | }
126 | }
127 | return conf;
128 | }
129 |
130 | function hasMissingPositional(conf: { commands: string[] }[]): boolean {
131 | const names = new Set(commands.map((c) => makeName(getCommandNameWithoutPosition(c))));
132 |
133 | for (const command of conf) {
134 | if (!('commands' in command) || !Array.isArray(command.commands)) {
135 | continue;
136 | }
137 |
138 | for (const name of command.commands) {
139 | if (names.has(name)) {
140 | return true;
141 | }
142 | }
143 | }
144 | return false;
145 | }
146 |
147 | function hasInvalidVimPositionals(config: vscode.WorkspaceConfiguration): boolean {
148 | let hasInvalid = false;
149 | const settings = getVimSettingsNames();
150 | for (let i = 0; i < settings.length; i++) {
151 | const settingName = settings[i];
152 |
153 | const conf = config.inspect(settingName);
154 | if (!conf) {
155 | continue;
156 | }
157 |
158 | if (isConfig(conf.globalValue)) {
159 | hasInvalid ||= hasMissingPositional(conf.globalValue);
160 | }
161 |
162 | if (isConfig(conf.workspaceValue)) {
163 | hasInvalid ||= hasMissingPositional(conf.workspaceValue);
164 | }
165 |
166 | if (isConfig(conf.workspaceFolderValue)) {
167 | hasInvalid ||= hasMissingPositional(conf.workspaceFolderValue);
168 | }
169 |
170 | if (hasInvalid === true) {
171 | return true;
172 | }
173 | }
174 | return hasInvalid;
175 | }
176 |
--------------------------------------------------------------------------------
/src/context/context.ts:
--------------------------------------------------------------------------------
1 | import { ExtensionContext } from 'vscode';
2 | import assert from 'assert';
3 | import { Editor } from '../editor/editor';
4 | import { EditorContext } from '../editor/editorContext';
5 |
6 | let context: Context = getDefaultContext();
7 |
8 | export function getContext(): Context {
9 | assert(context, ' context is not defined');
10 | return context;
11 | }
12 |
13 | export function updateContext(ctx: Context): Context {
14 | context = ctx;
15 | return context;
16 | }
17 | export function updateCommand(cmd: Command): void {
18 | context.command = cmd;
19 | context.command.currentSelector = undefined;
20 | }
21 |
22 | export function getDefaultContext(): Context {
23 | return {
24 | editor: new Editor(),
25 | command: null,
26 | parsing: {
27 | parser: undefined,
28 | },
29 | extensionContext: null,
30 | };
31 | }
32 |
33 | export function setExtensionContext(c: ExtensionContext): void {
34 | context.extensionContext = new EditorContext(c);
35 | }
36 |
--------------------------------------------------------------------------------
/src/editor/editor.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import * as vscode from 'vscode';
3 | export class Editor {
4 | private editor: vscode.TextEditor | undefined;
5 |
6 | constructor() {
7 | // cursor: new vscode.Position(0, 0),
8 | // language: 'tree-sitter',
9 | // text: '',
10 | }
11 |
12 | cursor(): vscode.Position {
13 | assert(this.editor, 'editor is undefined');
14 | return this.editor.selection.active;
15 | }
16 |
17 | getText() {
18 | assert(this.editor, 'editor is not defined');
19 | return this.editor.document.getText();
20 | }
21 | getRange(startLine: number, startChar: number, endLine: number, endChar: number) {
22 | assert(this.editor, 'editor is not defined');
23 | return this.editor.document.getText(
24 | new vscode.Range(new vscode.Position(startLine, startChar), new vscode.Position(endLine, endChar))
25 | );
26 | }
27 | language(): string {
28 | assert(this.editor, 'editor is not defined');
29 | return this.editor.document.languageId;
30 | }
31 |
32 | getEditor(): vscode.TextEditor {
33 | assert(this.editor, 'editor has not been setup yet');
34 | return this.editor;
35 | }
36 | setEditor(editor: vscode.TextEditor) {
37 | assert(editor, 'invalid editor');
38 | this.editor = editor;
39 | }
40 |
41 | goTo(_: Context, pos: vscode.Position): void {
42 | assert(this.editor, 'editor is not defined');
43 | if (!pos) {
44 | return;
45 | }
46 |
47 | this.editor.selection = new vscode.Selection(pos, pos);
48 | const that = this;
49 | // there HAS to be a way
50 | setTimeout(function () {
51 | assert(that.editor, 'editor is now undefined???');
52 | that.editor!.revealRange(
53 | new vscode.Range(pos, pos),
54 | vscode.TextEditorRevealType.InCenterIfOutsideViewport
55 | );
56 | }, 2);
57 | }
58 | selectRange(_: Context, range: vscode.Range | undefined): void {
59 | assert(this.editor, 'editor is not defined');
60 | if (!range) {
61 | return;
62 | }
63 |
64 | this.editor.selection = new vscode.Selection(range.start, range.end);
65 |
66 | const ref = this;
67 |
68 | // there HAS to be a way
69 | setTimeout(function () {
70 | assert(ref.editor, 'editor is now undefined???');
71 | ref.editor.revealRange(range, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
72 | }, 2);
73 | }
74 | exec(command: string, ...rest: any[]) {
75 | return vscode.commands.executeCommand(command, rest);
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/editor/editorContext.ts:
--------------------------------------------------------------------------------
1 | import { ExtensionContext, Memento } from 'vscode';
2 |
3 | export enum ProcessFlow {
4 | DONT_ASK = 0,
5 | EXECUTED = 1,
6 | SHOULD_ASK = 2,
7 | }
8 |
9 | export enum EditorScope {
10 | global = 1,
11 | workspace = 2,
12 | }
13 |
14 | const keys = {
15 | check_vim_positional_commands: ProcessFlow.DONT_ASK as ProcessFlow,
16 | showed_new_positionals_and_migrations: ProcessFlow.SHOULD_ASK as ProcessFlow,
17 | } as const;
18 |
19 | export class EditorContext {
20 | private ctx: ExtensionContext;
21 | constructor(c: ExtensionContext) {
22 | this.ctx = c;
23 | }
24 |
25 | private getEditorState(scope: EditorScope): Memento {
26 | if (scope === EditorScope.global) {
27 | return this.ctx.globalState;
28 | } else if (scope === EditorScope.workspace) {
29 | return this.ctx.workspaceState;
30 | }
31 |
32 | throw new Error(`invalid state ${scope}`);
33 | }
34 |
35 | getState(
36 | key: T,
37 | scope: EditorScope
38 | ): K | undefined {
39 | const config = this.getEditorState(scope);
40 |
41 | return config.get(key);
42 | }
43 |
44 | updateState(
45 | key: T,
46 | v: K,
47 | scope: EditorScope
48 | ): Thenable {
49 | const config = this.getEditorState(scope);
50 |
51 | return config.update(key, v);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/extension.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import { init, deactivate as quit } from './motions/commands';
3 | import { LanguageParser } from './parsing/parser';
4 | import { setExtensionContext } from './context/context';
5 |
6 | export async function activate(context: vscode.ExtensionContext): Promise {
7 | setExtensionContext(context);
8 | await Promise.all([LanguageParser.init(), init()]);
9 | }
10 |
11 | export function deactivate(): void {
12 | quit();
13 | }
14 |
--------------------------------------------------------------------------------
/src/motions/commands.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import { QueryOptions } from 'web-tree-sitter';
3 | import { makeName, formatKeybindCommands } from '../configurations/configGeneration';
4 | import * as vscode from 'vscode';
5 | import { LanguageParser } from '../parsing/parser';
6 | import {
7 | getChangePreviousCommands,
8 | getChangenextCommands,
9 | getDeleteNextCommands,
10 | getDeletePreviousCommands,
11 | getGoToNextEndCommands,
12 | getGoToPreviousCommands,
13 | getGoToPreviousEndCommands,
14 | getGotoNextStartCommands,
15 | getSelectNextCommands,
16 | getSelectPreviousCommands,
17 | getYankNextCommands,
18 | getYankPreviousCommands,
19 | } from './commandFunctions';
20 |
21 | import { getContext, getDefaultContext, updateCommand, updateContext } from '../context/context';
22 | import { pointPool, toNodes as toPoint, toRange } from '../parsing/nodes';
23 | import {
24 | automaticProcess,
25 | getVimSettingsNames,
26 | MigratePositionalCommand,
27 | } from '../configurations/migrateVimPositionals';
28 | import { format } from 'path';
29 | import { GenerateVimKeybinds } from '../configurations/generateVimKeybinds';
30 | import { GenerateKeyboardKeybindings } from '../configurations/generateKeybindings';
31 | import { showUpdateKeybindingsWelcomeScreen } from '../state/updates/new_keybindings';
32 |
33 | function addSelector(command: Command, selector: Selector): void {
34 | command.selectors[selector.language] = selector;
35 | }
36 |
37 | export function getCommandName(command: Command): string {
38 | return `${command.action}.${command.direction}.${command.scope}.${command.name}.${command.position}`;
39 | }
40 | export function getCommandNameWithoutPosition(command: Command): string {
41 | return `${command.action}.${command.direction}.${command.scope}.${command.name}`;
42 | }
43 |
44 | //make a better name
45 |
46 | function assertSelector(ctx: Context, selector: Selector | undefined): asserts selector {
47 | const command = ctx.command;
48 | assert(command, 'invalid command?');
49 |
50 | assert(selector, `invalid selector for ${getCommandName(ctx.command!)}`);
51 |
52 | assert(selector.language === ctx.editor.language(), 'they are different languages');
53 | }
54 |
55 | function getOptions(ctx: Context): QueryOptions {
56 | assert(ctx.command, 'getting command options with an empty command');
57 |
58 | const opts: QueryOptions = {
59 | //could revise this but if hitting this is common. could say more about you than about this extension
60 | matchLimit: Math.max(300, ctx.editor.getEditor().document.lineCount * 3),
61 | };
62 |
63 | const cursor = ctx.editor.cursor();
64 | if (ctx.command.action === 'goTo' && ctx.command.direction === 'next') {
65 | opts.startPosition = {
66 | row: cursor.line,
67 | column: cursor.character,
68 | };
69 | } else if (ctx.command.action === 'goTo' && ctx.command.direction === 'previous') {
70 | opts.endPosition = {
71 | row: cursor.line,
72 | column: cursor.character,
73 | };
74 | }
75 |
76 | return opts;
77 | }
78 |
79 | function executeCommand(ctx: Context): void {
80 | assert(ctx.parsing.parser, 'parser is not defined?');
81 |
82 | const command = ctx.command;
83 | // console.group('inside');
84 | assert(command, 'COMMAND IS NOT DEFINED?');
85 |
86 | const language = ctx.editor.language();
87 |
88 | const parser = ctx.parsing.parser;
89 | assert(parser, `could not init parser for ${language}`);
90 |
91 | const tree = parser.parser.parse(ctx.editor.getText());
92 |
93 | const selector = command.selectors[language as SupportedLanguages];
94 | assertSelector(ctx, selector);
95 | command.currentSelector = selector;
96 |
97 | const query = parser.language.query(selector.query);
98 | assert(query, 'invalid query came out???');
99 |
100 | let matches = query.matches(tree.rootNode, getOptions(ctx)).filter((c) => c.captures.length > 0);
101 |
102 | if (command.onMatch) {
103 | assert(typeof command.onMatch === 'function', 'match function is function');
104 | matches = command.onMatch(ctx, matches);
105 | }
106 |
107 | const points = toPoint(matches);
108 | const ranges = toRange(points);
109 |
110 | pointPool.retrieveAll(points);
111 |
112 | const pos = command.pos(ranges, ctx.editor.cursor());
113 |
114 | if (pos) {
115 | assert(pos.start.isBeforeOrEqual(pos.end), 'start needs to be first');
116 | }
117 |
118 | command.end(ctx, pos);
119 | }
120 |
121 | export function addSelectors(command: Command, funcs: Record Selector>): Command {
122 | for (const func of Object.values(funcs)) {
123 | addSelector(command, func());
124 | }
125 |
126 | return command;
127 | }
128 |
129 | export const commands: Command[] = getSelectNextCommands()
130 | .concat(getGotoNextStartCommands())
131 | .concat(getGoToNextEndCommands())
132 | .concat(getGoToPreviousCommands())
133 | .concat(getGoToPreviousEndCommands())
134 | .concat(getSelectPreviousCommands())
135 | .concat(getDeleteNextCommands())
136 | .concat(getDeletePreviousCommands())
137 | .concat(getYankNextCommands())
138 | .concat(getYankPreviousCommands())
139 | .concat(getChangenextCommands())
140 | .concat(getChangePreviousCommands());
141 |
142 | export async function setupCommand(command: Command): Promise {
143 | const currentEditor = vscode.window.activeTextEditor;
144 | if (!currentEditor) {
145 | return;
146 | }
147 |
148 | const ctx = getContext();
149 |
150 | ctx.editor.setEditor(currentEditor);
151 |
152 | const language = ctx.editor.language();
153 | assert(language.length > 0, 'language came empty');
154 |
155 | const parser = await LanguageParser.get(language);
156 | assert(parser, `could not find parser for ${language}`);
157 |
158 | ctx.parsing.parser = parser;
159 | updateCommand(command);
160 |
161 | executeCommand(ctx);
162 | }
163 |
164 | function createEditorCommand(name: string, title: string, f: () => void): EditorCommand {
165 | return {
166 | title: title,
167 | when: '',
168 | command: name,
169 | f,
170 | };
171 | }
172 |
173 | const editorCommands: EditorCommand[] = [
174 | createEditorCommand(makeName('migrateVimPositionals'), 'Migrate vim positionals', () => {
175 | MigratePositionalCommand(vscode.workspace.getConfiguration('vim'));
176 | }),
177 |
178 | createEditorCommand(makeName('generateVimKeybinds'), 'Generate vim keybinds', () => {
179 | GenerateVimKeybinds();
180 | }),
181 |
182 | createEditorCommand(makeName('generateKeybinds'), 'Generate keybinds', () => {
183 | GenerateKeyboardKeybindings();
184 | }),
185 | ];
186 | //doing this because the vscode.commands.getCommands() returns a promise, so this is to not slow down the start times
187 | const installedCommands: Record = {};
188 |
189 | export function init(): void {
190 | automaticProcess();
191 |
192 | // saveKeybinds(commands);
193 | // saveCommands(formatKeybindCommands(commands).concat(editorCommands as any as Record[]));
194 | // saveVimKeybinds(commands);
195 |
196 | showUpdateKeybindingsWelcomeScreen();
197 |
198 | for (const editorCommand of editorCommands) {
199 | installedCommands[makeName('migratePositionals')] = vscode.commands.registerCommand(
200 | editorCommand.command,
201 | editorCommand.f
202 | );
203 | }
204 |
205 | for (const command of commands) {
206 | const name = makeName(getCommandName(command));
207 | const nameWithoutPosition = makeName(getCommandNameWithoutPosition(command));
208 |
209 | if (command.action === 'goTo' && !(nameWithoutPosition in installedCommands)) {
210 | const dis = vscode.commands.registerCommand(nameWithoutPosition, async () => {
211 | vscode.window.showWarningMessage(
212 | `${nameWithoutPosition} is now outdated and will be removed in a future version, please update to [${name}] or update your configuration in https://github.com/RodrigoScola/vscode-text-objects/blob/main/vim_integration.md`
213 | );
214 |
215 | setupCommand(command);
216 | });
217 |
218 | installedCommands[nameWithoutPosition] = dis;
219 | }
220 |
221 | const disposable = vscode.commands.registerCommand(name, async () => {
222 | setupCommand(command);
223 | });
224 |
225 | installedCommands[name] = disposable;
226 | }
227 | }
228 |
229 | export function deactivate(): void {
230 | for (const command of Object.values(installedCommands)) {
231 | command.dispose();
232 | }
233 | }
234 |
--------------------------------------------------------------------------------
/src/motions/queries/Array.ts:
--------------------------------------------------------------------------------
1 | function selectC(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(initializer_list) @array`].join('\n'),
5 | };
6 | }
7 |
8 | function selectCPP(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: ['(initializer_list ) @array'].join('\n'),
12 | };
13 | }
14 | function selectCSharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [` (initializer_expression) @array `].join('\n'),
18 | };
19 | }
20 | function selectGo(): Selector {
21 | return {
22 | language: 'go',
23 | query: [
24 | ` (composite_literal type: (array_type)) @array`,
25 | ` (composite_literal type: (slice_type)) @array`,
26 | ` (var_declaration (var_spec type : (array_type))) @array `,
27 | ` (var_declaration (var_spec type : (slice_type))) @array `,
28 | ].join('\n'),
29 | };
30 | }
31 | function selectJava(): Selector {
32 | return {
33 | language: 'java',
34 | query: ['(array_initializer) @array'].join('\n'),
35 | };
36 | }
37 |
38 | function selectJson(): Selector {
39 | return {
40 | language: 'json',
41 | query: ['(array) @array'].join('\n'),
42 | };
43 | }
44 |
45 | function selectJsonC(): Selector {
46 | return {
47 | language: 'jsonc',
48 | query: selectJson().query,
49 | };
50 | }
51 | function selectLua(): Selector {
52 | return {
53 | language: 'lua',
54 | query: [`(field_list) @array`, ,].join('\n'),
55 | };
56 | }
57 |
58 | function selectPython(): Selector {
59 | return {
60 | language: 'python',
61 | query: [' (list) @array', `(list_comprehension) @array`].join('\n'),
62 | };
63 | }
64 | function selectRust(): Selector {
65 | return {
66 | language: 'rust',
67 | query: [`(array_expression ) @array`].join('\n'),
68 | };
69 | }
70 |
71 | function selectToml(): Selector {
72 | return {
73 | language: 'toml',
74 | query: ['(array) @array'].join('\n'),
75 | };
76 | }
77 |
78 | function selectJavascript(): Selector {
79 | return {
80 | language: 'javascript',
81 | query: ['(array) @array'].join('\n'),
82 | };
83 | }
84 | function selectTypescript(): Selector {
85 | return {
86 | language: 'typescript',
87 | query: ['(array) @array'].join('\n'),
88 | };
89 | }
90 | function selectTypescriptReact(): Selector {
91 | return {
92 | language: 'typescriptreact',
93 | query: ['(array) @array'].join('\n'),
94 | };
95 | }
96 |
97 | function selectjavascriptReact(): Selector {
98 | return {
99 | language: 'javascriptreact',
100 | query: ['(array) @array'].join('\n'),
101 | };
102 | }
103 |
104 | function selectYaml(): Selector {
105 | return {
106 | language: 'yaml',
107 | query: [` (block_sequence) @array `].join('\n'),
108 | };
109 | }
110 | function selectPhp(): Selector {
111 | return {
112 | language: 'php',
113 | query: [` (array_creation_expression) @array `].join('\n'),
114 | };
115 | }
116 |
117 | export const select = {
118 | C: selectC,
119 | cpp: selectCPP,
120 | csharp: selectCSharp,
121 | go: selectGo,
122 | java: selectJava,
123 | yaml: selectYaml,
124 | javascript: selectJavascript,
125 | json: selectJson,
126 | jsonc: selectJsonC,
127 | toml: selectToml,
128 | lua: selectLua,
129 | python: selectPython,
130 | rust: selectRust,
131 | typescript: selectTypescript,
132 | typescriptreact: selectTypescriptReact,
133 | javascriptreact: selectjavascriptReact,
134 | php: selectPhp,
135 | };
136 |
137 | export const goTo = select;
138 |
--------------------------------------------------------------------------------
/src/motions/queries/Conditional.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | ` (switch_statement) @conditional `,
6 | ` (conditional_expression )@conditional `,
7 | ` (if_statement) @conditional `,
8 | ].join('\n'),
9 | };
10 | }
11 |
12 | function cpp(): Selector {
13 | return {
14 | language: 'cpp',
15 | query: [
16 | `(if_statement) @conditional`,
17 |
18 | ` (switch_statement ) @conditional `,
19 | `(conditional_expression) @conditional`,
20 | ].join('\n'),
21 | };
22 | }
23 | function csharp(): Selector {
24 | return {
25 | language: 'csharp',
26 | query: [
27 | ` (conditional_expression ) @conditional`,
28 | ` (if_statement) @conditional `,
29 | ` (switch_statement) @conditional `,
30 | ].join('\n'),
31 | };
32 | }
33 | function go(): Selector {
34 | return {
35 | language: 'go',
36 | query: [` (if_statement ) @conditional `, `(expression_switch_statement) @conditional`].join('\n'),
37 | };
38 | }
39 | function java(): Selector {
40 | return {
41 | language: 'java',
42 | query: [
43 | ` (if_statement) @conditional `,
44 | ` (ternary_expression ) @conditional`,
45 | ` (ternary_expression ) @conditional`,
46 | ` (switch_block_statement_group) @conditional `,
47 | ].join('\n'),
48 | };
49 | }
50 |
51 | function lua(): Selector {
52 | return {
53 | language: 'lua',
54 | query: ['(if_statement) @conditional'].join('\n'),
55 | };
56 | }
57 |
58 | function python(): Selector {
59 | return {
60 | language: 'python',
61 | query: [` (if_statement) @conditional `, ` (conditional_expression) @conditional `].join('\n'),
62 | };
63 | }
64 | function rust(): Selector {
65 | return {
66 | language: 'rust',
67 | query: [
68 | `(if_expression) @conditional `,
69 | `(match_expression body: (match_block) @conditional) `,
70 | `(let_declaration value: (if_expression) @conditional) `,
71 | ].join('\n'),
72 | };
73 | }
74 |
75 | const jsSelector = [
76 | ` (if_statement) @conditional `,
77 | ` (ternary_expression) @conditional `,
78 | ` (switch_case) @conditional `,
79 | ];
80 | function typescript(): Selector {
81 | return {
82 | language: 'typescript',
83 | query: jsSelector.join('\n'),
84 | };
85 | }
86 |
87 | function typescriptreact(): Selector {
88 | return {
89 | language: 'typescriptreact',
90 | query: jsSelector.join('\n'),
91 | };
92 | }
93 | function javascriptreact(): Selector {
94 | return {
95 | language: 'javascriptreact',
96 | query: jsSelector.join('\n'),
97 | };
98 | }
99 | function javascript(): Selector {
100 | return {
101 | language: 'javascript',
102 | query: jsSelector.join('\n'),
103 | };
104 | }
105 | function php(): Selector {
106 | return {
107 | language: 'php',
108 | query: [
109 | `(if_statement) @conditional`,
110 | `(conditional_expression) @conditional`,
111 | `(switch_statement) @conditional`,
112 | `(match_expression) @conditional`,
113 | ].join('\n'),
114 | };
115 | }
116 |
117 | export default {
118 | C,
119 | cpp,
120 | csharp,
121 | go,
122 | java,
123 | javascript,
124 | lua,
125 | python,
126 | rust,
127 | typescript,
128 | typescriptreact,
129 | javascriptreact,
130 | php,
131 | };
132 |
--------------------------------------------------------------------------------
/src/motions/queries/Function.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(function_definition) @function`,
6 | `(declaration declarator: (function_declarator)) @function`,
7 | ].join('\n'),
8 | };
9 | }
10 |
11 | function cpp(): Selector {
12 | return {
13 | language: 'cpp',
14 | query: [
15 | ` (function_definition) @function `,
16 | `(template_declaration (function_definition)) @function`,
17 | ` (declaration (init_declarator value: (lambda_expression declarator: (abstract_function_declarator)) )) @function `,
18 | ` (lambda_expression declarator: (abstract_function_declarator)) @function `,
19 | ].join('\n'),
20 | };
21 | }
22 |
23 | function csharp(): Selector {
24 | return {
25 | language: 'csharp',
26 | query: [
27 | `(local_function_statement) @function`,
28 | `(method_declaration) @function`,
29 | ` (lambda_expression) @function `,
30 | ].join('\n'),
31 | };
32 | }
33 | function go(): Selector {
34 | return {
35 | language: 'go',
36 | query: [
37 | `
38 | (go_statement
39 | (call_expression
40 | function:(parenthesized_expression
41 | (func_literal)))) @function
42 | `,
43 | `
44 | (var_declaration
45 | (var_spec
46 | value:(expression_list
47 | (func_literal)))) @function
48 | `,
49 | `(function_declaration) @function`,
50 | ` (func_literal) @function `,
51 | `(method_declaration) @function`,
52 | ].join('\n'),
53 | };
54 | }
55 | function java(): Selector {
56 | return {
57 | language: 'java',
58 | query: [
59 | `(method_declaration) @function`,
60 | `(local_variable_declaration
61 | declarator:(variable_declarator
62 | value:(lambda_expression))) @function`,
63 | ].join('\n'),
64 | };
65 | }
66 | function javascript(): Selector {
67 | return {
68 | language: 'javascript',
69 | query: [
70 | `(export_statement (_ (_ (function_expression) @function ))) @export `,
71 | `(_ (_ (function_expression) @function )) @declaration `,
72 | `(method_definition) @function`,
73 | `(arguments (function_expression) @function ) @arguments `,
74 | `(arrow_function ) @function `,
75 | `(export_statement (function_declaration) @function ) @export `,
76 | `(function_declaration) @function `,
77 | `(export_statement (_ (arrow_function) @function )) @export `,
78 | `(export_statement (_ (_ value: (arrow_function) @function )) ) @export `,
79 | `(_ arguments:(_ (arrow_function) @function )) `,
80 | ].join('\n'),
81 | };
82 | }
83 | function lua(): Selector {
84 | return {
85 | language: 'lua',
86 | query: [
87 | ` (function_definition_statement) @function `,
88 | ` (local_function_definition_statement) @function `,
89 | ` (local_variable_declaration
90 | (expression_list value:(function_definition))) @function `,
91 | `(variable_assignment
92 | (expression_list value:(function_definition))) @function `,
93 | `(field value:(function_definition)) @function`,
94 | ].join('\n'),
95 | };
96 | }
97 |
98 | function python(): Selector {
99 | return {
100 | language: 'python',
101 | query: [` (function_definition) @function `].join('\n'),
102 | };
103 | }
104 | function rust(): Selector {
105 | return {
106 | language: 'rust',
107 | query: [
108 | `(let_declaration pattern: (identifier) (_) ) @anonymous_function`,
109 | `(function_item ) @function.declaration`,
110 | `(function_signature_item) @function.declaration`,
111 | ].join('\n'),
112 | };
113 | }
114 | function typescript(): Selector {
115 | return {
116 | language: 'typescript',
117 | query: javascript().query,
118 | };
119 | }
120 |
121 | function typescriptreact(): Selector {
122 | return {
123 | language: 'typescriptreact',
124 | query: javascript().query,
125 | };
126 | }
127 | function javascriptreact(): Selector {
128 | return {
129 | language: 'javascriptreact',
130 | query: javascript().query,
131 | };
132 | }
133 | function php(): Selector {
134 | return {
135 | language: 'php',
136 | query: [
137 | ` (function_definition) @function `,
138 | ` (anonymous_function_creation_expression) @function `,
139 | ` (arrow_function) @function `,
140 | ` (method_declaration) @function `,
141 | ].join('\n'),
142 | };
143 | }
144 |
145 | export default {
146 | C,
147 | cpp,
148 | csharp,
149 | go,
150 | java,
151 | javascript,
152 | lua,
153 | python,
154 | rust,
155 | typescript,
156 | typescriptreact,
157 | javascriptreact,
158 | php,
159 | };
160 |
--------------------------------------------------------------------------------
/src/motions/queries/Lhs.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(assignment_expression left:(_) @lhs) `,
6 | `(declaration type:(_) @lhs declarator:(_ declarator:(_) @lhs)) `,
7 | `(declaration (_) @lhs type:(_) @lhs declarator:(_ declarator:(_) @lhs))`,
8 | ].join('\n'),
9 | };
10 | }
11 |
12 | function cpp(): Selector {
13 | return {
14 | language: 'cpp',
15 | query: [
16 | ` (declaration type:(_) @lhs declarator:(init_declarator declarator:(_) @lhs) ) `,
17 | ` (assignment_expression left:(_) @lhs) `,
18 | ].join('\n'),
19 | };
20 | }
21 | function csharp(): Selector {
22 | return {
23 | language: 'csharp',
24 | query: [` (variable_declaration (variable_declarator (_) @lhs)) `].join('\n'),
25 | };
26 | }
27 | function go(): Selector {
28 | return {
29 | language: 'go',
30 | query: [
31 | ` (short_var_declaration left : (_) @variable ) `,
32 | ` (var_declaration (var_spec name:(identifier) @variable type:(_)* @variable )) `,
33 | ` (const_declaration (const_spec name:(identifier) @variable type:(_)* @variable )) `,
34 | ].join('\n'),
35 | };
36 | }
37 | function java(): Selector {
38 | return {
39 | language: 'java',
40 | query: [
41 | ` (local_variable_declaration type:(_) @lhs declarator:(variable_declarator name:(identifier) @lhs)) `,
42 | ` (assignment_expression left:(_) @lhs ) `,
43 | ].join('\n'),
44 | };
45 | }
46 | function javascript(): Selector {
47 | return {
48 | language: 'javascript',
49 | query: [` (variable_declarator name:(_) @lhs) `].join('\n'),
50 | };
51 | }
52 | function jsonc(): Selector {
53 | return {
54 | language: 'jsonc',
55 | query: [`(pair key :(_) @key)`].join('\n'),
56 | };
57 | }
58 | function json(): Selector {
59 | return {
60 | language: 'json',
61 | query: [`(pair key :(_) @key)`].join('\n'),
62 | };
63 | }
64 |
65 | function lua(): Selector {
66 | return {
67 | language: 'lua',
68 | query: [` (variable_list (variable name:(identifier) @val)) `].join('\n'),
69 | };
70 | }
71 |
72 | function python(): Selector {
73 | return {
74 | language: 'python',
75 | query: [` (assignment left: (_) @lhs) `].join('\n'),
76 | };
77 | }
78 | function rust(): Selector {
79 | return {
80 | language: 'rust',
81 | query: [
82 | ` (let_declaration pattern:(_) @lhs)`,
83 | ` (static_item name:(_) @lhs type:(_)+ @lhs)`,
84 | ` (let_declaration (mutable_specifier) @lhs pattern:(identifier) @lhs )`,
85 | ` (const_item name:(_) @lhs type:(_)+ @lhs)`,
86 | ].join('\n'),
87 | };
88 | }
89 | function toml(): Selector {
90 | return {
91 | language: 'toml',
92 | query: [`(pair (bare_key) @lhs) `].join('\n'),
93 | };
94 | }
95 |
96 | function typescript(): Selector {
97 | return {
98 | language: 'typescript',
99 | query: [` (variable_declarator name:(_) @lhs) `].join('\n'),
100 | };
101 | }
102 |
103 | function yaml(): Selector {
104 | return {
105 | language: 'yaml',
106 | query: [` (block_mapping_pair key:(_) @lhs value:(flow_node (_))) `].join('\n'),
107 | };
108 | }
109 | function typescriptreact(): Selector {
110 | return {
111 | language: 'typescriptreact',
112 | query: [
113 | `(variable_declarator value: (_) @rhs)`,
114 | `( assignment_expression (_) @rhs) `,
115 | ` (type_alias_declaration value: (_) @type ) `,
116 | // `( public_field_definition
117 | // value: (_) @rhs
118 | // )`,
119 | ].join('\n'),
120 | };
121 | }
122 | function javascriptreact(): Selector {
123 | return {
124 | language: 'javascriptreact',
125 | query: [
126 | `(variable_declarator value: (_) @rhs)`,
127 | `( assignment_expression (_) @rhs) `,
128 | // `( public_field_definition
129 | // value: (_) @rhs
130 | // )`,
131 | ].join('\n'),
132 | };
133 | }
134 | function php(): Selector {
135 | return {
136 | language: 'php',
137 | query: [
138 | ` (assignment_expression left:(variable_name ) @variable ) `,
139 | ` (assignment_expression left:(list_literal ) @variable ) `,
140 | ].join('\n'),
141 | };
142 | }
143 | export default {
144 | C,
145 | cpp,
146 | csharp,
147 | go,
148 | java,
149 | javascript,
150 | json,
151 | jsonc,
152 | toml,
153 | lua,
154 | python,
155 | rust,
156 | typescript,
157 | yaml,
158 | typescriptreact,
159 | javascriptreact,
160 | php,
161 | };
162 |
--------------------------------------------------------------------------------
/src/motions/queries/Loop.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(for_statement) @loops`, `(while_statement) @loops`, `(do_statement) @loops`].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [` (for_range_loop) @loop `, ` (for_statement) @loop `].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [
18 | `(for_statement ) @loop `,
19 | `(for_each_statement ) @loop `,
20 | `(while_statement ) @loop `,
21 | `(do_statement ) @loop`,
22 | ].join('\n'),
23 | };
24 | }
25 | function go(): Selector {
26 | return {
27 | language: 'go',
28 | query: [` (for_statement) @loop `].join('\n'),
29 | };
30 | }
31 | function java(): Selector {
32 | return {
33 | language: 'java',
34 | query: [
35 | ` (for_statement body:(block (_) @loop)) `,
36 | ` (enhanced_for_statement body:(block (_) @loop)) `,
37 | ` (while_statement body:(block (_) @loop)) `,
38 | ` (do_statement body:(block (_) @loop)) `,
39 | ].join('\n'),
40 | };
41 | }
42 | function javascript(): Selector {
43 | return {
44 | language: 'javascript',
45 | query: [` (for_statement) @loop (for_in_statement) @loop `].join('\n'),
46 | };
47 | }
48 | function lua(): Selector {
49 | return {
50 | language: 'lua',
51 | query: [
52 | `(while_statement) @loop`,
53 | `(repeat_statement) @loop`,
54 | `(for_numeric_statement) @loop`,
55 | `(for_generic_statement) @loop`,
56 | ].join('\n'),
57 | };
58 | }
59 |
60 | function python(): Selector {
61 | return {
62 | language: 'python',
63 | query: [
64 | ` (for_in_clause) @loop `,
65 | ` (for_statement) @loop `,
66 | `(while_statement) @loop`,
67 | `(list_comprehension) @loop`,
68 | ].join('\n'),
69 | };
70 | }
71 | function rust(): Selector {
72 | return {
73 | language: 'rust',
74 | query: [`(loop_expression) @loop`, `(while_expression) @loop`, `(for_expression) @loop`].join('\n'),
75 | };
76 | }
77 | function typescript(): Selector {
78 | return {
79 | language: 'typescript',
80 | query: javascript().query,
81 | };
82 | }
83 | function typescriptreact(): Selector {
84 | return {
85 | language: 'typescriptreact',
86 | query: javascript().query,
87 | };
88 | }
89 | function javascriptreact(): Selector {
90 | return {
91 | language: 'javascriptreact',
92 | query: javascript().query,
93 | };
94 | }
95 | function php(): Selector {
96 | return {
97 | language: 'php',
98 | query: [
99 | ` (for_statement ) @loop `,
100 | ` (foreach_statement ) @loop `,
101 | ` (while_statement ) @loop `,
102 | ` (do_statement ) @loop `,
103 | ].join('\n'),
104 | };
105 | }
106 | export default {
107 | C,
108 | cpp,
109 | csharp,
110 | go,
111 | java,
112 | javascript,
113 | lua,
114 | python,
115 | rust,
116 | typescript,
117 | typescriptreact,
118 | javascriptreact,
119 | php,
120 | };
121 |
--------------------------------------------------------------------------------
/src/motions/queries/Node.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | const query = [
3 | `(for_statement) @node`,
4 | `(while_statement) @node`,
5 | `(do_statement) @node`,
6 | `(type_definition type:(struct_specifier) @node ) @outer `,
7 | `(struct_specifier) @node `,
8 | `(enum_specifier ) @node `,
9 | `(union_specifier ) @node `,
10 | `(function_definition) @node`,
11 | `(declaration declarator: (function_declarator)) @node`,
12 | `(switch_statement) @node`,
13 | `(conditional_expression )@node`,
14 | `(if_statement) @node`,
15 | `(declaration declarator: (init_declarator)) @node`,
16 | ];
17 |
18 | return {
19 | language: 'c',
20 | query: query.join('\n'),
21 | };
22 | }
23 |
24 | function cpp(): Selector {
25 | const query = [
26 | `(for_range_loop) @node `,
27 | `(for_statement) @node `,
28 | '(class_specifier) @node',
29 | `(function_definition) @node `,
30 | `(template_declaration (function_definition)) @node`,
31 | `(declaration (init_declarator value: (lambda_expression declarator: (abstract_function_declarator)) )) @node `,
32 | `(lambda_expression declarator: (abstract_function_declarator)) @node `,
33 | `(if_statement) @node`,
34 | `(switch_statement ) @node `,
35 | `(conditional_expression) @node`,
36 | `(declaration) @node `,
37 | `(field_declaration) @node `,
38 | ];
39 |
40 | return {
41 | language: 'cpp',
42 | query: query.join('\n'),
43 | };
44 | }
45 | function csharp(): Selector {
46 | const query = [
47 | `(for_statement body: (block (_)+ @node)) `,
48 | `(for_each_statement (block (_)+ @node)) `,
49 | `(while_statement (block (_)+ @node)) `,
50 | `(do_statement (block (_)+ @node))`,
51 | `(class_declaration) @node`,
52 | `(local_function_statement) @node`,
53 | `(method_declaration) @node`,
54 | `(lambda_expression) @node `,
55 | `(conditional_expression ) @node`,
56 | `(if_statement) @node `,
57 | `(switch_statement) @node `,
58 | `(variable_declaration) @node`,
59 | ];
60 |
61 | return {
62 | language: 'csharp',
63 | query: query.join('\n'),
64 | };
65 | }
66 | function go(): Selector {
67 | const query = [
68 | `(for_statement) @node`,
69 | '(type_declaration (type_spec type: (struct_type) )) @node ',
70 | `(go_statement (_ (_ (func_literal)))) @node `,
71 | `(var_declaration (_ (_ (func_literal)))) @node `,
72 | `(function_declaration) @node`,
73 | `(func_literal) @node `,
74 | `(method_declaration) @node`,
75 | `(if_statement ) @node `,
76 | `(expression_switch_statement) @node`,
77 | `(short_var_declaration) @node `,
78 | `(var_declaration) @node `,
79 | `(const_declaration) @node `,
80 | `(const_spec) @node `,
81 | ].join('\n');
82 |
83 | return {
84 | language: 'go',
85 | query: query,
86 | };
87 | }
88 | function java(): Selector {
89 | const query = [
90 | `(for_statement body:(block (_) @node)) `,
91 | `(enhanced_for_statement body:(block (_) @node)) `,
92 | `(while_statement body:(block (_) @node)) `,
93 | `(do_statement body:(block (_) @node)) `,
94 | '(class_declaration) @node',
95 | `(method_declaration) @node`,
96 | `(local_variable_declaration declarator:(variable_declarator value:(lambda_expression))) @node`,
97 | `(local_variable_declaration) @node `,
98 | `(expression_statement (assignment_expression)) @node`,
99 | `(if_statement) @node `,
100 | `(ternary_expression ) @node`,
101 | `(ternary_expression ) @node`,
102 | `(switch_block_statement_group) @node `,
103 | ].join('\n');
104 |
105 | return {
106 | language: 'java',
107 | query: query,
108 | };
109 | }
110 |
111 | function javascript(): Selector {
112 | const selector = [
113 | // selects functions
114 | `(method_definition) @node`,
115 | `(export_statement (_ (_ (function_expression) @function ))) @export `,
116 | `(_ (_ (function_expression) @function )) @declaration `,
117 | `(method_definition) @function`,
118 | `(arguments (function_expression) @function ) @arguments `,
119 | `(arrow_function ) @function `,
120 | `(export_statement (function_declaration) @function ) @export `,
121 | `(function_declaration) @function `,
122 | `(_ (_ (arrow_function) @function )) @export `,
123 | `(export_statement (_ (_ value: (arrow_function) @function )) ) @export `,
124 | //--
125 |
126 | `(_ arguments:(_ (arrow_function) @function )) `,
127 | `(for_statement) @node (for_in_statement) @node `,
128 | `( class_declaration ) @node`,
129 | `(export_statement declaration: ( class_declaration ) @node ) @export `,
130 | `(if_statement) @node `,
131 | `(switch_case) @node`,
132 | `(export_statement (lexical_declaration) @node ) @export `,
133 | `(lexical_declaration ) @node`,
134 | `(try_statement) @node `,
135 | ].join('\n');
136 |
137 | return {
138 | language: 'javascript',
139 | query: selector,
140 | };
141 | }
142 |
143 | function python(): Selector {
144 | const query = [
145 | `(expression_statement) @node`,
146 | `(if_statement) @node `,
147 | `(conditional_expression) @node `,
148 | `(function_definition) @node `,
149 | '(class_definition) @node ',
150 | `(for_statement) @node `,
151 | `(while_statement) @node`,
152 | `(list_comprehension) @node`,
153 | ];
154 |
155 | return {
156 | language: 'python',
157 | query: query.join('\n'),
158 | };
159 | }
160 |
161 | function rust(): Selector {
162 | const query = [
163 | `(struct_item) @node`,
164 | `(impl_item) @node`,
165 | `(trait_item) @node`,
166 | `(enum_item) @node`,
167 | `(loop_expression) @node`,
168 | `(while_expression) @node`,
169 | `(for_expression) @node`,
170 | `(let_declaration pattern: (identifier) (_) ) @node`,
171 | `(function_item ) @node`,
172 | `(function_signature_item) @node`,
173 | `(if_expression) @node `,
174 | `(match_expression body: (match_block) @node) `,
175 | `(let_declaration value: (if_expression) @node) `,
176 | `(let_declaration) @node`,
177 | `(const_item) @node`,
178 | `(static_item) @node`,
179 | ];
180 |
181 | return {
182 | language: 'rust',
183 | query: query.join('\n'),
184 | };
185 | }
186 |
187 | function toml(): Selector {
188 | const query = ['(pair)* @node'];
189 |
190 | return {
191 | language: 'toml',
192 | query: query.join('\n'),
193 | };
194 | }
195 |
196 | function typescript(): Selector {
197 | return {
198 | language: 'typescript',
199 | query: javascript().query,
200 | };
201 | }
202 | function typescriptreact(): Selector {
203 | return {
204 | language: 'typescriptreact',
205 | query: javascript().query,
206 | };
207 | }
208 | function javascriptreact(): Selector {
209 | return {
210 | language: 'javascriptreact',
211 | query: javascript().query,
212 | };
213 | }
214 |
215 | function lua(): Selector {
216 | const query = [
217 | `(field_list) @node`,
218 |
219 | `(while_statement) @node`,
220 | `(repeat_statement) @node`,
221 | `(for_numeric_statement) @node`,
222 | `(for_generic_statement) @node`,
223 | '(table) @node',
224 | `(variable_assignment) @node`,
225 | `(local_variable_declaration) @node`,
226 | ` (function_definition_statement) @node `,
227 | ` (local_function_definition_statement) @node `,
228 | ` (local_variable_declaration
229 | (expression_list value:(function_definition))) @node `,
230 | `(variable_assignment
231 | (expression_list value:(function_definition))) @node `,
232 | `(field value:(function_definition)) @node`,
233 | '(if_statement) @node',
234 | '(call arguments: (argument_list) @node)',
235 | ];
236 |
237 | return {
238 | language: 'lua',
239 | query: query.join('\n'),
240 | };
241 | }
242 | function yaml(): Selector {
243 | const query = [` (block_mapping_pair) @node`];
244 |
245 | return {
246 | language: 'yaml',
247 | query: query.join('\n'),
248 | };
249 | }
250 |
251 | export default {
252 | C,
253 | cpp,
254 | java,
255 | csharp,
256 | go,
257 | javascript,
258 | python,
259 | lua,
260 | rust,
261 | toml,
262 | javascriptreact,
263 | typescript,
264 | yaml,
265 | typescriptreact,
266 | };
267 |
--------------------------------------------------------------------------------
/src/motions/queries/Object.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | ` (type_definition type:(struct_specifier) @object ) @outer `,
6 | `(struct_specifier) @object `,
7 | `(enum_specifier ) @object `,
8 | `(union_specifier ) @object `,
9 | ].join('\n'),
10 | };
11 | }
12 |
13 | function cpp(): Selector {
14 | return {
15 | language: 'cpp',
16 | query: [
17 | ` (class_specifier body:(field_declaration_list (_) @class))`,
18 | `(struct_specifier body : (field_declaration_list (_)@object) ) `,
19 | `(declaration
20 | declarator:(init_declarator
21 | value:(initializer_list (_) @object))) `,
22 | `(type_definition type:(struct_specifier body:(field_declaration_list (_) @object ))) `,
23 | ].join('\n'),
24 | };
25 | }
26 | function csharp(): Selector {
27 | return {
28 | language: 'csharp',
29 | query: [
30 | `(class_declaration) @object `,
31 | `(enum_declaration) @object `,
32 | `(struct_declaration) @object `,
33 | `(record_declaration) @object `,
34 | `(anonymous_object_creation_expression) @object`,
35 | `(tuple_expression) @object`,
36 | ].join('\n'),
37 | };
38 | }
39 | function go(): Selector {
40 | return {
41 | language: 'go',
42 | query: [
43 | `(type_declaration (type_spec type: (struct_type))) @struct`,
44 | ` (expression_list (composite_literal (_) ) ) @struct`,
45 | ].join('\n'),
46 | };
47 | }
48 | function java(): Selector {
49 | return {
50 | language: 'java',
51 | query: [
52 | '(class_declaration) @class',
53 | ` (local_variable_declaration
54 | declarator:(variable_declarator
55 | value:(object_creation_expression))) @object `,
56 | ].join('\n'),
57 | };
58 | }
59 | function javascript(): Selector {
60 | return {
61 | language: 'javascript',
62 | query: ['(object) @object'].join('\n'),
63 | };
64 | }
65 |
66 | function json(): Selector {
67 | return {
68 | language: 'json',
69 | query: javascript().query,
70 | };
71 | }
72 |
73 | function jsonc(): Selector {
74 | return {
75 | language: 'jsonc',
76 | query: javascript().query,
77 | };
78 | }
79 |
80 | function lua(): Selector {
81 | return {
82 | language: 'lua',
83 | query: ['(table) @object'].join('\n'),
84 | };
85 | }
86 |
87 | function python(): Selector {
88 | return {
89 | language: 'python',
90 | query: ['(dictionary) @object'].join('\n'),
91 | };
92 | }
93 | function rust(): Selector {
94 | return {
95 | language: 'rust',
96 | query: [`(struct_item) @object`, `(struct_expression) @object`, `(enum_item) @object`].join('\n'),
97 | };
98 | }
99 |
100 | function toml(): Selector {
101 | return {
102 | language: 'toml',
103 | query: ['(table) @object', `(inline_table) @object`].join('\n'),
104 | };
105 | }
106 |
107 | function typescript(): Selector {
108 | return {
109 | language: 'typescript',
110 | query: javascript().query,
111 | };
112 | }
113 | function yaml(): Selector {
114 | return {
115 | language: 'yaml',
116 | query: [
117 | ` (block_mapping_pair value:(block_node (block_mapping (block_mapping_pair key:(_) value:(flow_node (_))) )@object )) `,
118 | ].join('\n'),
119 | };
120 | }
121 | function typescriptreact(): Selector {
122 | return {
123 | language: 'typescriptreact',
124 | query: javascript().query,
125 | };
126 | }
127 |
128 | function javascriptreact(): Selector {
129 | return {
130 | language: 'javascriptreact',
131 | query: javascript().query,
132 | };
133 | }
134 | function php(): Selector {
135 | return {
136 | language: 'php',
137 | query: [` (array_creation_expression (array_element_initializer (_)+ ) @object) `].join('\n'),
138 | };
139 | }
140 | export default {
141 | C,
142 | cpp,
143 | csharp,
144 | go,
145 | java,
146 | javascript,
147 | json,
148 | jsonc,
149 | toml,
150 | lua,
151 | python,
152 | rust,
153 | typescript,
154 | yaml,
155 | typescriptreact,
156 | javascriptreact,
157 | php,
158 | };
159 |
--------------------------------------------------------------------------------
/src/motions/queries/Params.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: ['(parameter_list (_) @params ) '].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [` (parameter_list (_) @params) `].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [`(parameter_list (_) @params ) `].join('\n'),
18 | };
19 | }
20 | function go(): Selector {
21 | return {
22 | language: 'go',
23 | query: [`(parameter_list (_) @params ) `].join('\n'),
24 | };
25 | }
26 | function java(): Selector {
27 | return {
28 | language: 'java',
29 | query: [` (formal_parameters (_) @params ) `].join('\n'),
30 | };
31 | }
32 | function javascript(): Selector {
33 | return {
34 | language: 'javascript',
35 | query: [`(formal_parameters (_) @params ) `].join('\n'),
36 | };
37 | }
38 |
39 | function lua(): Selector {
40 | return {
41 | language: 'lua',
42 | query: ['(parameter_list (_) @params ) '].join('\n'),
43 | };
44 | }
45 |
46 | function python(): Selector {
47 | return {
48 | language: 'python',
49 | query: ['(parameters (_) @params ) '].join('\n'),
50 | };
51 | }
52 | function rust(): Selector {
53 | return {
54 | language: 'rust',
55 | query: ['(parameters (_) @params ) '].join('\n'),
56 | };
57 | }
58 |
59 | function typescript(): Selector {
60 | return {
61 | language: 'typescript',
62 | query: javascript().query,
63 | };
64 | }
65 | function typescriptreact(): Selector {
66 | return {
67 | language: 'typescriptreact',
68 | query: javascript().query,
69 | };
70 | }
71 | function javascriptreact(): Selector {
72 | return {
73 | language: 'javascriptreact',
74 | query: javascript().query,
75 | };
76 | }
77 | function php(): Selector {
78 | return {
79 | language: 'php',
80 | query: [`(formal_parameters (_) @params ) `].join('\n'),
81 | };
82 | }
83 | export const select: Record Selector> = {
84 | C,
85 | cpp,
86 | csharp,
87 | go,
88 | java,
89 | javascript,
90 | lua,
91 | python,
92 | rust,
93 | typescript,
94 | typescriptreact,
95 | javascriptreact,
96 | php,
97 | };
98 |
99 | function selectC(): Selector {
100 | return {
101 | language: 'c',
102 | query: ['(parameter_list )@params '].join('\n'),
103 | };
104 | }
105 |
106 | function selectCpp(): Selector {
107 | return {
108 | language: 'cpp',
109 | query: [` (parameter_list) @params `].join('\n'),
110 | };
111 | }
112 | function selectCsharp(): Selector {
113 | return {
114 | language: 'csharp',
115 | query: [`(parameter_list) @parameters `].join('\n'),
116 | };
117 | }
118 | function selectGo(): Selector {
119 | return {
120 | language: 'go',
121 | query: [`(parameter_list )@parameters `].join('\n'),
122 | };
123 | }
124 | function selectJava(): Selector {
125 | return {
126 | language: 'java',
127 | query: [` (formal_parameters) @parameters `].join('\n'),
128 | };
129 | }
130 | function selectJavascript(): Selector {
131 | return {
132 | language: 'javascript',
133 | query: [`(formal_parameters) @parameter`].join('\n'),
134 | };
135 | }
136 |
137 | function selectLua(): Selector {
138 | return {
139 | language: 'lua',
140 | query: ['(parameter_list) @params'].join('\n'),
141 | };
142 | }
143 |
144 | function selectPython(): Selector {
145 | return {
146 | language: 'python',
147 | query: ['(parameters) @parameters'].join('\n'),
148 | };
149 | }
150 | function selectRust(): Selector {
151 | return {
152 | language: 'rust',
153 | query: ['(parameters) @parameters'].join('\n'),
154 | };
155 | }
156 |
157 | function selectTypescript(): Selector {
158 | return {
159 | language: 'typescript',
160 | query: javascript().query,
161 | };
162 | }
163 | function selectTypescriptReact(): Selector {
164 | return {
165 | language: 'typescriptreact',
166 | query: javascript().query,
167 | };
168 | }
169 | function selectjavascriptReact(): Selector {
170 | return {
171 | language: 'javascriptreact',
172 | query: javascript().query,
173 | };
174 | }
175 | function selectPhp(): Selector {
176 | return {
177 | language: 'php',
178 | query: [`(formal_parameters ) @params`].join('\n'),
179 | };
180 | }
181 |
182 | export const goTo: Record Selector> = {
183 | C: selectC,
184 | cpp: selectCpp,
185 | csharp: selectCsharp,
186 | go: selectGo,
187 | java: selectJava,
188 | javascript: selectJavascript,
189 | lua: selectLua,
190 | python: selectPython,
191 | rust: selectRust,
192 | typescript: selectTypescript,
193 | typescriptreact: selectTypescriptReact,
194 | javascriptreact: selectjavascriptReact,
195 | php: selectPhp,
196 | };
197 |
--------------------------------------------------------------------------------
/src/motions/queries/Rhs.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(assignment_expression right:(_) @lhs)`, `(init_declarator value: (_) @rhs ) `].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [
12 | ` (init_declarator value:(_) @variable ) `,
13 | ` (field_declaration default_value:(_) @variable)`,
14 | ` (assignment_expression right:(_) @rhs) `,
15 | ].join('\n'),
16 | };
17 | }
18 | function csharp(): Selector {
19 | return {
20 | language: 'csharp',
21 | query: [` (equals_value_clause (_) @rhs )`, ` (assignment_expression right:(_) @rhs )`].join('\n'),
22 | };
23 | }
24 | function go(): Selector {
25 | return {
26 | language: 'go',
27 | query: [
28 | `(short_var_declaration right: (_) @rhs)`,
29 | `(assignment_statement right:(_)+ @rhs)`,
30 | `(var_spec value:(expression_list (_) @rhs ))`,
31 | `(const_spec value:(expression_list (_) @rhs))`,
32 | ].join('\n'),
33 | };
34 | }
35 | function java(): Selector {
36 | return {
37 | language: 'java',
38 | query: [
39 | `(assignment_expression left:(identifier) right:(_) @rhs) `,
40 | `(variable_declarator value:(_) @rhs) `,
41 | ].join('\n'),
42 | };
43 | }
44 | function javascript(): Selector {
45 | return {
46 | language: 'javascript',
47 | query: [
48 | `(variable_declarator value: (_) @rhs)`,
49 | `(assignment_expression right:(_) @rhs) `,
50 | `(field_definition value:(_) @rhs) `,
51 | ` (object (pair key:(property_identifier) value:(_) @rhs ) ) `,
52 | ].join('\n'),
53 | };
54 | }
55 |
56 | function jsonc(): Selector {
57 | return {
58 | language: 'jsonc',
59 | query: [`(pair value: (_) @rhs)`].join('\n'),
60 | };
61 | }
62 | function json(): Selector {
63 | return {
64 | language: 'json',
65 | query: [`(pair value: (_) @rhs)`].join('\n'),
66 | };
67 | }
68 |
69 | function lua(): Selector {
70 | return {
71 | language: 'lua',
72 | query: [
73 | ` (local_variable_declaration (expression_list value:(_) @rhs)) `,
74 | ` (variable_assignment (expression_list value:(_) @rhs )) `,
75 | ].join('\n'),
76 | };
77 | }
78 |
79 | function python(): Selector {
80 | return {
81 | language: 'python',
82 | query: [` (assignment right:(_) @rhs)`].join('\n'),
83 | };
84 | }
85 | function rust(): Selector {
86 | return {
87 | language: 'rust',
88 | query: [` (let_declaration value:(_) @rhs) `, ` (assignment_expression right:(_) @rhs) `].join('\n'),
89 | };
90 | }
91 |
92 | function toml(): Selector {
93 | return {
94 | language: 'toml',
95 | query: [`(pair (bare_key) (_) @rhs)`].join('\n'),
96 | };
97 | }
98 |
99 | function typescript(): Selector {
100 | return {
101 | language: 'typescript',
102 | //todo revise the selectors
103 | query: [
104 | `(variable_declarator value: (_) @rhs)`,
105 | `(assignment_expression right:(_) @rhs) `,
106 | ` (class_declaration body:(class_body (public_field_definition value:(_) @rhs ))) `,
107 |
108 | ` (object (pair key:(property_identifier) value:(_) @rhs ) ) `,
109 | ].join('\n'),
110 | };
111 | }
112 | function yaml(): Selector {
113 | return {
114 | language: 'yaml',
115 | //todo revise the selectors
116 | query: [` (block_mapping_pair value:(_) @rhs) `].join('\n'),
117 | };
118 | }
119 | function typescriptreact(): Selector {
120 | return {
121 | language: 'typescriptreact',
122 | //todo revise the selectors
123 | query: [
124 | `(variable_declarator value: (_) @rhs)`,
125 | `(assignment_expression right:(_) @rhs) `,
126 | ` (class_declaration body:(class_body (public_field_definition value:(_) @rhs ))) `,
127 |
128 | ` (object (pair key:(property_identifier) value:(_) @rhs ) ) `,
129 | ].join('\n'),
130 | };
131 | }
132 | function javascriptreact(): Selector {
133 | return {
134 | language: 'javascriptreact',
135 | //todo revise the selectors
136 | query: [
137 | `(variable_declarator value: (_) @rhs)`,
138 | `(assignment_expression right:(_) @rhs) `,
139 | `(field_definition value:(_) @rhs) `,
140 | `(object (pair key:(property_identifier) value:(_) @rhs ) ) `,
141 | ].join('\n'),
142 | };
143 | }
144 | function php(): Selector {
145 | return {
146 | language: 'php',
147 | query: [
148 | ` (assignment_expression right:(_) @rhs ) `,
149 | // ` (assignment_expression right:(_ (_) @rhs )) `,
150 | ].join('\n'),
151 | };
152 | }
153 |
154 | export default {
155 | C,
156 | cpp,
157 | csharp,
158 | go,
159 | java,
160 | javascript,
161 | json,
162 | jsonc,
163 | toml,
164 | lua,
165 | python,
166 | rust,
167 | typescript,
168 | yaml,
169 | typescriptreact,
170 | javascriptreact,
171 | php,
172 | };
173 |
--------------------------------------------------------------------------------
/src/motions/queries/String.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: ['(string_literal) @string', '(char_literal) @string'].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [`(string_literal) @string`, `(raw_string_literal) @string`].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [
18 | ` (string_literal) @string `,
19 | `(interpolated_string_expression) @string`,
20 | `(character_literal) @string`,
21 | ].join('\n'),
22 | };
23 | }
24 | function go(): Selector {
25 | return {
26 | language: 'go',
27 | query: [`(raw_string_literal) @string`, `(interpreted_string_literal) @string`].join('\n'),
28 | };
29 | }
30 | function java(): Selector {
31 | return {
32 | language: 'java',
33 | query: [`(string_literal) @string`, `(character_literal) @string`].join('\n'),
34 | };
35 | }
36 | function javascript(): Selector {
37 | return {
38 | language: 'javascript',
39 | query: [`( string ) @string`, `( template_string ) @string`].join('\n'),
40 | };
41 | }
42 |
43 | function jsonc(): Selector {
44 | return {
45 | language: 'jsonc',
46 | query: [`(string) @string`].join('\n'),
47 | };
48 | }
49 | function json(): Selector {
50 | return {
51 | language: 'json',
52 | query: [`(string) @string`].join('\n'),
53 | };
54 | }
55 |
56 | function lua(): Selector {
57 | return {
58 | language: 'lua',
59 | query: ['(string) @string'].join('\n'),
60 | };
61 | }
62 |
63 | function python(): Selector {
64 | return {
65 | language: 'python',
66 | query: [` (string) @string `].join('\n'),
67 | };
68 | }
69 | function rust(): Selector {
70 | return {
71 | language: 'rust',
72 | query: [`(string_literal) @string`, `(char_literal) @string`].join('\n'),
73 | };
74 | }
75 |
76 | function toml(): Selector {
77 | return {
78 | language: 'toml',
79 | query: [`(string) @string`].join('\n'),
80 | };
81 | }
82 |
83 | function typescript(): Selector {
84 | return {
85 | language: 'typescript',
86 | query: javascript().query,
87 | };
88 | }
89 | function yaml(): Selector {
90 | return {
91 | language: 'yaml',
92 | query: [
93 | `(single_quote_scalar) @string`,
94 | `(double_quote_scalar) @string`,
95 | `
96 | (block_mapping_pair value:(block_node (block_scalar) @string))
97 | `,
98 | ].join('\n'),
99 | };
100 | }
101 | function typescriptreact(): Selector {
102 | return {
103 | language: 'typescriptreact',
104 | query: javascript().query,
105 | };
106 | }
107 | function javascriptreact(): Selector {
108 | return {
109 | language: 'javascriptreact',
110 | query: javascript().query,
111 | };
112 | }
113 |
114 | function php(): Selector {
115 | return {
116 | language: 'php',
117 | query: [
118 | `(encapsed_string) @string`,
119 | `(string) @string`,
120 | ` (heredoc_body (string_content)) @string `,
121 | ` (nowdoc_body (nowdoc_string)) @string `,
122 | ].join('\n'),
123 | };
124 | }
125 |
126 | export default {
127 | C,
128 | cpp,
129 | csharp,
130 | go,
131 | java,
132 | javascript,
133 | json,
134 | jsonc,
135 | toml,
136 | lua,
137 | python,
138 | rust,
139 | typescript,
140 | yaml,
141 | typescriptreact,
142 | javascriptreact,
143 | php,
144 | };
145 |
--------------------------------------------------------------------------------
/src/motions/queries/Type.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(declaration (type_qualifier) @types type: (primitive_type) @types ) `,
6 | `(declaration type: (union_specifier) @types ) `,
7 | `(declaration (storage_class_specifier) @types type: (primitive_type) @types ) `,
8 | `(primitive_type) @types`,
9 | `(struct_specifier) @types`,
10 |
11 | `(union_specifier ) @type`,
12 | ].join('\n'),
13 | };
14 | }
15 |
16 | function cpp(): Selector {
17 | return {
18 | language: 'cpp',
19 | query: [
20 | `(declaration (type_qualifier) @types type: (primitive_type) @types ) `,
21 | `(declaration type: (union_specifier) @types ) `,
22 | `(declaration (storage_class_specifier) @types type: (primitive_type) @types ) `,
23 | `(primitive_type) @types`,
24 | `(struct_specifier) @types`,
25 | `(union_specifier ) @type`,
26 | ].join('\n'),
27 | };
28 | }
29 | function csharp(): Selector {
30 | return {
31 | language: 'csharp',
32 | query: [
33 | ` (variable_declaration type: (_) @type) `,
34 | `(parameter type: (_) @type)`,
35 | `(predefined_type) @type`,
36 | `(void_keyword) @type`,
37 | `(type_parameter) @type`,
38 | `(array_type ) @type`,
39 | `(struct_declaration ) @type `,
40 | ].join('\n'),
41 | };
42 | }
43 | function go(): Selector {
44 | return {
45 | language: 'go',
46 | query: [
47 | `(parameter_list (parameter_declaration)) @types`,
48 | `(type_declaration) @types`,
49 | `(pointer_type) @types `,
50 | `(type_identifier) @types`,
51 | `(interface_type) @types `,
52 | `(qualified_type ) @types `,
53 | ].join('\n'),
54 | };
55 | }
56 | function java(): Selector {
57 | return {
58 | language: 'java',
59 | query: [
60 | ` (interface_declaration) @types `,
61 | ` (method_declaration type:(void_type) @types) `,
62 | `(type_identifier) @types`,
63 | `(void_type) @types`,
64 | `(array_type) @types`,
65 | `(integral_type) @types`,
66 | `(catch_type) @types`,
67 | ].join('\n'),
68 | };
69 | }
70 |
71 | function rust(): Selector {
72 | return {
73 | language: 'rust',
74 | query: [`(type_identifier) @type`, `(primitive_type) @type`, `(struct_item) @class`].join('\n'),
75 | };
76 | }
77 |
78 | function typescript(): Selector {
79 | return {
80 | language: 'typescript',
81 | query: [
82 | ` (export_statement (type_alias_declaration)) @type `,
83 | ` (type_alias_declaration) @type `,
84 | ` (export_statement (interface_declaration)) @type `,
85 | ` (interface_declaration) @type `,
86 | `(type_annotation (_) @type)`,
87 | ].join('\n'),
88 | };
89 | }
90 | function typescriptreact(): Selector {
91 | return {
92 | language: 'typescriptreact',
93 | query: [
94 | ` (export_statement (type_alias_declaration)) @type `,
95 | ` (type_alias_declaration) @type `,
96 | ` (export_statement (interface_declaration)) @type `,
97 | ` (interface_declaration) @type `,
98 | `(type_annotation (_) @type)`,
99 | ].join('\n'),
100 | };
101 | }
102 | function php(): Selector {
103 | return {
104 | language: 'php',
105 | query: [
106 | `(primitive_type) @type`,
107 | ` (union_type) @type `,
108 | ` (intersection_type) @type `,
109 | `(optional_type) @type`,
110 | ].join('\n'),
111 | };
112 | }
113 |
114 | export default {
115 | C,
116 | cpp,
117 | csharp,
118 | go,
119 | java,
120 | rust,
121 | typescript,
122 | typescriptreact,
123 | php,
124 | };
125 |
--------------------------------------------------------------------------------
/src/motions/queries/Variables.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(declaration declarator: (init_declarator)) @variable`].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [` (declaration) @variable `, ` (field_declaration) @variable `].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [`(variable_declaration) @variable`].join('\n'),
18 | };
19 | }
20 | function go(): Selector {
21 | return {
22 | language: 'go',
23 | query: [
24 | ` (short_var_declaration) @variable `,
25 | ` (var_declaration) @variable `,
26 | ` (const_declaration) @variable `,
27 | ` (const_spec) @variable `,
28 | ].join('\n'),
29 | };
30 | }
31 | function java(): Selector {
32 | return {
33 | language: 'java',
34 | query: [
35 | ` (local_variable_declaration) @variable `,
36 | `(expression_statement (assignment_expression)) @variable`,
37 | ].join('\n'),
38 | };
39 | }
40 | function javascript(): Selector {
41 | return {
42 | language: 'javascript',
43 | query: [
44 | ` (field_definition) @variable`,
45 | ` (export_statement (lexical_declaration (variable_declarator) @variable) @declaration ) @export `,
46 | ` (lexical_declaration (variable_declarator ) @variable ) @declaration `,
47 | ].join('\n'),
48 | };
49 | }
50 |
51 | function jsonc(): Selector {
52 | return {
53 | language: 'jsonc',
54 | query: [`(pair) @variable`].join('\n'),
55 | };
56 | }
57 | function json(): Selector {
58 | return {
59 | language: 'json',
60 | query: [`(pair) @variable`].join('\n'),
61 | };
62 | }
63 |
64 | function lua(): Selector {
65 | return {
66 | language: 'lua',
67 | query: [`(variable_assignment) @variable`, `(local_variable_declaration) @variable`].join('\n'),
68 | };
69 | }
70 |
71 | function python(): Selector {
72 | return {
73 | language: 'python',
74 | query: [` (expression_statement (assignment)) @variable `].join('\n'),
75 | };
76 | }
77 | function rust(): Selector {
78 | return {
79 | language: 'rust',
80 | query: [`(let_declaration) @variable`, `(const_item) @variable`, `(static_item) @variable`].join('\n'),
81 | };
82 | }
83 |
84 | function toml(): Selector {
85 | return {
86 | language: 'toml',
87 | query: ['(pair) @variable'].join('\n'),
88 | };
89 | }
90 |
91 | function typescript(): Selector {
92 | const tsSelector = [
93 | ` (export_statement (lexical_declaration (variable_declarator) @variable) @declaration ) @export `,
94 | ` (lexical_declaration (variable_declarator ) @variable ) @declaration `,
95 | `(assignment_expression) @variable `,
96 | `(type_alias_declaration) @type`,
97 | ` (public_field_definition ) @variable `,
98 | ].join('\n');
99 | return {
100 | language: 'typescript',
101 | query: tsSelector,
102 | };
103 | }
104 |
105 | function yaml(): Selector {
106 | return {
107 | language: 'yaml',
108 | query: [` (block_mapping_pair) @variable `].join('\n'),
109 | };
110 | }
111 | function typescriptreact(): Selector {
112 | const tsSelector = typescript().query + '\n' + `(type_alias_declaration) @type`;
113 | return {
114 | language: 'typescriptreact',
115 | query: tsSelector,
116 | };
117 | }
118 | function javascriptreact(): Selector {
119 | return {
120 | language: 'javascriptreact',
121 | query: javascript().query,
122 | };
123 | }
124 | function php(): Selector {
125 | return {
126 | language: 'php',
127 | query: [` (assignment_expression left:(variable_name) ) @variable `].join('\n'),
128 | };
129 | }
130 | export default {
131 | C,
132 | cpp,
133 | csharp,
134 | go,
135 | java,
136 | javascript,
137 | json,
138 | jsonc,
139 | toml,
140 | lua,
141 | python,
142 | rust,
143 | typescript,
144 | yaml,
145 | typescriptreact,
146 | javascriptreact,
147 | php,
148 | };
149 |
--------------------------------------------------------------------------------
/src/motions/queries/call.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: ['(call_expression) @call'].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [` (call_expression) @call `].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [` (invocation_expression) @call`].join('\n'),
18 | };
19 | }
20 | function go(): Selector {
21 | return {
22 | language: 'go',
23 | query: [` (call_expression) @call`].join('\n'),
24 | };
25 | }
26 | function java(): Selector {
27 | return {
28 | language: 'java',
29 | query: [` (method_invocation ) @call `].join('\n'),
30 | };
31 | }
32 | function javascript(): Selector {
33 | return {
34 | language: 'javascript',
35 | query: [`(call_expression ) @call `].join('\n'),
36 | };
37 | }
38 |
39 | function lua(): Selector {
40 | return {
41 | language: 'lua',
42 |
43 | query: ['(call arguments: (argument_list) @call)'].join('\n'),
44 | };
45 | }
46 |
47 | function python(): Selector {
48 | return {
49 | language: 'python',
50 | query: ['(call) @call'].join('\n'),
51 | };
52 | }
53 | function rust(): Selector {
54 | return {
55 | language: 'rust',
56 | query: [`(call_expression) @call`].join('\n'),
57 | };
58 | }
59 |
60 | function toml(): Selector {
61 | return {
62 | language: 'toml',
63 | query: [`(pair (bare_key) (_) @rhs)`].join('\n'),
64 | };
65 | }
66 |
67 | function typescript(): Selector {
68 | return {
69 | language: 'typescript',
70 | query: javascript().query,
71 | };
72 | }
73 |
74 | function typescriptreact(): Selector {
75 | return {
76 | language: 'typescriptreact',
77 | query: javascript().query,
78 | };
79 | }
80 |
81 | function javascriptreact(): Selector {
82 | return {
83 | language: 'javascriptreact',
84 | query: javascript().query,
85 | };
86 | }
87 | function yaml(): Selector {
88 | return {
89 | language: 'yaml',
90 | query: [` (alias) @call `].join('\n'),
91 | };
92 | }
93 |
94 | function php(): Selector {
95 | return {
96 | language: 'php',
97 | query: [` (function_call_expression) @call `].join('\n'),
98 | };
99 | }
100 |
101 | export default {
102 | C,
103 | cpp,
104 | csharp,
105 | yaml,
106 | go,
107 | java,
108 | javascript,
109 | toml,
110 | lua,
111 | python,
112 | rust,
113 | typescript,
114 | typescriptreact,
115 | javascriptreact,
116 | php,
117 | };
118 |
--------------------------------------------------------------------------------
/src/motions/queries/class.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(union_specifier name:(_ ) body:(_) ) @class `,
6 | `(enum_specifier name:(type_identifier) body:(_)) @class`,
7 | `(type_definition type:(struct_specifier) @class declarator:(type_identifier)) @outer`,
8 | // this also selects some variable definitions
9 | `(struct_specifier name:(_) body: (_) ) @class `,
10 | ].join('\n'),
11 | };
12 | }
13 |
14 | function cpp(): Selector {
15 | return {
16 | language: 'cpp',
17 | query: ['(class_specifier) @class'].join('\n'),
18 | };
19 | }
20 | function csharp(): Selector {
21 | return {
22 | language: 'csharp',
23 | query: [`(class_declaration) @class`].join('\n'),
24 | };
25 | }
26 | function go(): Selector {
27 | return {
28 | language: 'go',
29 | query: ['(type_declaration (type_spec type: (struct_type) )) @struct '].join('\n'),
30 | };
31 | }
32 | function java(): Selector {
33 | return {
34 | language: 'java',
35 | query: ['(class_declaration) @class'].join('\n'),
36 | };
37 | }
38 | function javascript(): Selector {
39 | return {
40 | language: 'javascript',
41 | query: [
42 | ` ( class_declaration ) @class `,
43 | ` (export_statement declaration: ( class_declaration ) @class ) @export `,
44 | ].join('\n'),
45 | };
46 | }
47 |
48 | function python(): Selector {
49 | return {
50 | language: 'python',
51 | query: [' (class_definition) @class '].join('\n'),
52 | };
53 | }
54 | function rust(): Selector {
55 | return {
56 | language: 'rust',
57 | query: [`(struct_item) @class`, `(impl_item) @class`, `(trait_item) @class`, `(enum_item) @class`].join(
58 | '\n'
59 | ),
60 | };
61 | }
62 |
63 | function toml(): Selector {
64 | return {
65 | language: 'toml',
66 | query: [`(pair (bare_key) (_) @rhs)`].join('\n'),
67 | };
68 | }
69 |
70 | function typescript(): Selector {
71 | return {
72 | language: 'typescript',
73 | query: javascript().query,
74 | };
75 | }
76 | function typescriptreact(): Selector {
77 | return {
78 | language: 'typescriptreact',
79 | query: javascript().query,
80 | };
81 | }
82 | function javascriptreact(): Selector {
83 | return {
84 | language: 'javascriptreact',
85 | query: javascript().query,
86 | };
87 | }
88 | function yaml(): Selector {
89 | return {
90 | language: 'yaml',
91 | query: [
92 | ` (block_mapping_pair key:(flow_node (plain_scalar)) value:(block_node (anchor)+ @class (_)+ @class )) `,
93 | ].join('\n'),
94 | };
95 | }
96 | function php(): Selector {
97 | return {
98 | language: 'php',
99 | query: [
100 | `(class_declaration) @class`,
101 |
102 | `
103 |
104 | (object_creation_expression
105 | (declaration_list
106 | (method_declaration)*)) @class
107 | `,
108 | ].join('\n'),
109 | };
110 | }
111 |
112 | export default {
113 | C,
114 | cpp,
115 | csharp,
116 | go,
117 | java,
118 | javascript,
119 | toml,
120 | python,
121 | rust,
122 | typescript,
123 | yaml,
124 | typescriptreact,
125 | javascriptreact,
126 | php,
127 | };
128 |
--------------------------------------------------------------------------------
/src/motions/queries/comment.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(comment)* @comment`].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: ['(comment)+ @comment'].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [`(comment)+ @comment`].join('\n'),
18 | };
19 | }
20 | function go(): Selector {
21 | return {
22 | language: 'go',
23 | query: ['(comment)+ @comment'].join('\n'),
24 | };
25 | }
26 | function java(): Selector {
27 | return {
28 | language: 'java',
29 | query: [`(line_comment)+ @comment`, `(block_comment)+ @comment`].join('\n'),
30 | };
31 | }
32 | function javascript(): Selector {
33 | return {
34 | language: 'javascript',
35 | query: ['(comment)+ @comment'].join('\n'),
36 | };
37 | }
38 |
39 | function jsonc(): Selector {
40 | return {
41 | language: 'jsonc',
42 | query: javascript().query,
43 | };
44 | }
45 |
46 | function lua(): Selector {
47 | return {
48 | language: 'lua',
49 | query: ['(comment)+ @comment'].join('\n'),
50 | };
51 | }
52 |
53 | function python(): Selector {
54 | return {
55 | language: 'python',
56 | query: [` (comment)+ @comment `].join('\n'),
57 | };
58 | }
59 | function rust(): Selector {
60 | return {
61 | language: 'rust',
62 | query: [` (line_comment)+ @comment `, ` (block_comment)+ @comment `].join('\n'),
63 | };
64 | }
65 |
66 | function toml(): Selector {
67 | return {
68 | language: 'toml',
69 | query: ['(comment)+ @comment'].join('\n'),
70 | };
71 | }
72 |
73 | function typescript(): Selector {
74 | return {
75 | language: 'typescript',
76 | query: javascript().query,
77 | };
78 | }
79 | function typescriptreact(): Selector {
80 | return {
81 | language: 'typescriptreact',
82 | query: javascript().query,
83 | };
84 | }
85 | function javascriptreact(): Selector {
86 | return {
87 | language: 'javascriptreact',
88 | query: javascript().query,
89 | };
90 | }
91 | function yaml(): Selector {
92 | return {
93 | language: 'yaml',
94 | query: [`(comment)+ @comment`].join('\n'),
95 | };
96 | }
97 |
98 | function php(): Selector {
99 | return {
100 | language: 'php',
101 | query: [`(comment)+ @comment`].join('\n'),
102 | };
103 | }
104 |
105 | export default {
106 | C,
107 | cpp,
108 | csharp,
109 | go,
110 | java,
111 | javascript,
112 | jsonc,
113 | toml,
114 | lua,
115 | python,
116 | rust,
117 | typescript,
118 | yaml,
119 | typescriptreact,
120 | javascriptreact,
121 | php,
122 | };
123 |
--------------------------------------------------------------------------------
/src/motions/queries/innerArray.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(init_declarator
6 | declarator:(array_declarator)
7 | value:(initializer_list (_) @array ) )`,
8 | ].join('\n'),
9 | };
10 | }
11 |
12 | function cpp(): Selector {
13 | return {
14 | language: 'cpp',
15 | query: ['(initializer_list (_) @array ) '].join('\n'),
16 | };
17 | }
18 | function csharp(): Selector {
19 | return {
20 | language: 'csharp',
21 | query: [` (initializer_expression (_) @array ) `].join('\n'),
22 | };
23 | }
24 | function go(): Selector {
25 | return {
26 | language: 'go',
27 | query: [
28 | ` (composite_literal type: (array_type) body: (literal_value (_) @array)) `,
29 | ` (composite_literal type: (slice_type) body: (literal_value (_) @array)) `,
30 | ` (var_declaration (var_spec type : (array_type))) @array `,
31 | ].join('\n'),
32 | };
33 | }
34 | function java(): Selector {
35 | return {
36 | language: 'java',
37 | query: [`(array_initializer (_) @array )`].join('\n'),
38 | };
39 | }
40 | function javascript(): Selector {
41 | return {
42 | language: 'javascript',
43 | query: ['(array (_) @array) '].join('\n'),
44 | };
45 | }
46 |
47 | function json(): Selector {
48 | return {
49 | language: 'json',
50 | query: javascript().query,
51 | };
52 | }
53 | function jsonc(): Selector {
54 | return {
55 | language: 'jsonc',
56 | query: javascript().query,
57 | };
58 | }
59 |
60 | function lua(): Selector {
61 | return {
62 | language: 'lua',
63 | query: [` (expression_list value:(table (field_list (_) @array )) )`].join('\n'),
64 | };
65 | }
66 |
67 | function python(): Selector {
68 | return {
69 | language: 'python',
70 | query: [`(list (_) @array )`].join('\n'),
71 | };
72 | }
73 | function rust(): Selector {
74 | return {
75 | language: 'rust',
76 | query: [`(array_expression (_) @array ) `].join('\n'),
77 | };
78 | }
79 |
80 | function toml(): Selector {
81 | return {
82 | language: 'toml',
83 | query: ['(array (_) @array ) '].join('\n'),
84 | };
85 | }
86 |
87 | function typescript(): Selector {
88 | return {
89 | language: 'typescript',
90 | query: javascript().query,
91 | };
92 | }
93 | function yaml(): Selector {
94 | return {
95 | language: 'yaml',
96 | query: [` (block_sequence (_) @array ) `].join('\n'),
97 | };
98 | }
99 | function typescriptreact(): Selector {
100 | return {
101 | language: 'typescriptreact',
102 | query: javascript().query,
103 | };
104 | }
105 | function javascriptreact(): Selector {
106 | return {
107 | language: 'javascriptreact',
108 | query: javascript().query,
109 | };
110 | }
111 | function php(): Selector {
112 | return {
113 | language: 'php',
114 | query: [` (array_creation_expression (array_element_initializer) @array ) `].join('\n'),
115 | };
116 | }
117 | export default {
118 | C,
119 | cpp,
120 | csharp,
121 | go,
122 | java,
123 | javascript,
124 | json,
125 | jsonc,
126 | toml,
127 | lua,
128 | python,
129 | rust,
130 | typescript,
131 | yaml,
132 | typescriptreact,
133 | javascriptreact,
134 | php,
135 | };
136 |
--------------------------------------------------------------------------------
/src/motions/queries/innerCall.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: ['(call_expression arguments: (argument_list (_) @call )) '].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [
12 | `
13 | (call_expression
14 | arguments: (
15 | argument_list (_)+ @call))
16 | `,
17 | ].join('\n'),
18 | };
19 | }
20 | function csharp(): Selector {
21 | return {
22 | language: 'csharp',
23 | query: [` (invocation_expression arguments:(argument_list (_) @call)) `].join('\n'),
24 | };
25 | }
26 | function go(): Selector {
27 | return {
28 | language: 'go',
29 | query: [` (call_expression arguments:(argument_list (_) @call )) `].join('\n'),
30 | };
31 | }
32 | function java(): Selector {
33 | return {
34 | language: 'java',
35 | query: [` (expression_statement (method_invocation arguments:(argument_list (_) @call))) `].join('\n'),
36 | };
37 | }
38 | function javascript(): Selector {
39 | return {
40 | language: 'javascript',
41 | query: [`(call_expression arguments: (arguments (_) @call) ) `].join('\n'),
42 | };
43 | }
44 |
45 | function lua(): Selector {
46 | return {
47 | language: 'lua',
48 | query: ['(call arguments: (argument_list (_)@call )) '].join('\n'),
49 | };
50 | }
51 |
52 | function python(): Selector {
53 | return {
54 | language: 'python',
55 | query: ['(call arguments: (argument_list (_) @call) )'].join('\n'),
56 | };
57 | }
58 | function rust(): Selector {
59 | return {
60 | language: 'rust',
61 | query: [`(call_expression arguments: (arguments ) @call)`].join('\n'),
62 | };
63 | }
64 |
65 | function typescript(): Selector {
66 | return {
67 | language: 'typescript',
68 | query: javascript().query,
69 | };
70 | }
71 | function typescriptreact(): Selector {
72 | return {
73 | language: 'typescriptreact',
74 | query: javascript().query,
75 | };
76 | }
77 | function javascriptreact(): Selector {
78 | return {
79 | language: 'javascriptreact',
80 | query: javascript().query,
81 | };
82 | }
83 | function yaml(): Selector {
84 | return {
85 | language: 'yaml',
86 | query: [` (alias (_) @call) `].join('\n'),
87 | };
88 | }
89 |
90 | function php(): Selector {
91 | return {
92 | language: 'php',
93 | query: [` (function_call_expression arguments:(arguments (argument) @call ) ) `].join('\n'),
94 | };
95 | }
96 |
97 | export default {
98 | C,
99 | cpp,
100 | csharp,
101 | go,
102 | java,
103 | javascript,
104 | lua,
105 | python,
106 | rust,
107 | typescript,
108 | yaml,
109 | typescriptreact,
110 | javascriptreact,
111 | php,
112 | };
113 |
--------------------------------------------------------------------------------
/src/motions/queries/innerClass.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(struct_specifier body: (field_declaration_list (_)+ @class ))`].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [
12 | `
13 | (class_specifier
14 | body:(field_declaration_list
15 | (access_specifier)
16 | (_)+ @class) )
17 |
18 | `,
19 | ].join(`\n`),
20 | };
21 | }
22 | function csharp(): Selector {
23 | return {
24 | language: 'csharp',
25 | query: [` (class_declaration body: (declaration_list (_)+ @body)) `].join('\n'),
26 | };
27 | }
28 | function go(): Selector {
29 | return {
30 | language: 'go',
31 | query: [` (struct_type (field_declaration_list (_)+ @struct) ) `].join('\n'),
32 | };
33 | }
34 | function java(): Selector {
35 | return {
36 | language: 'java',
37 | query: ['(class_declaration body: (class_body (_) @class))'].join('\n'),
38 | };
39 | }
40 | function javascript(): Selector {
41 | return {
42 | language: 'javascript',
43 | query: [` (class_body (_)* @class.body) `].join('\n'),
44 | };
45 | }
46 |
47 | function python(): Selector {
48 | return {
49 | language: 'python',
50 | query: [' (class_definition body: (_) @class )'].join('\n'),
51 | };
52 | }
53 | function rust(): Selector {
54 | return {
55 | language: 'rust',
56 | query: [
57 | `(struct_item body: (field_declaration_list (_)+ @class )) `,
58 | `(impl_item body: (declaration_list (_)+ @class )) `,
59 | `(trait_item body: (declaration_list (_)+ @class)) `,
60 | `(enum_item body: (enum_variant_list (_)+ @class )) `,
61 | ].join('\n'),
62 | };
63 | }
64 |
65 | function typescript(): Selector {
66 | return {
67 | language: 'typescript',
68 | query: javascript().query,
69 | };
70 | }
71 | function yaml(): Selector {
72 | return {
73 | language: 'yaml',
74 | query: [
75 | ` (block_mapping_pair key:(flow_node (plain_scalar)) value:(block_node (anchor) (_)+ @class )) `,
76 | ].join('\n'),
77 | };
78 | }
79 | function typescriptreact(): Selector {
80 | return {
81 | language: 'typescriptreact',
82 | query: javascript().query,
83 | };
84 | }
85 | function javascriptreact(): Selector {
86 | return {
87 | language: 'javascriptreact',
88 | query: javascript().query,
89 | };
90 | }
91 | function php(): Selector {
92 | return {
93 | language: 'php',
94 | query: [
95 | `
96 | (class_declaration
97 | body:(declaration_list
98 | (_)+ @class ))
99 | `,
100 | ].join('\n'),
101 | };
102 | }
103 | export default {
104 | C,
105 | cpp,
106 | csharp,
107 | go,
108 | java,
109 | javascript,
110 | python,
111 | rust,
112 | typescript,
113 | yaml,
114 | typescriptreact,
115 | javascriptreact,
116 | php,
117 | };
118 |
--------------------------------------------------------------------------------
/src/motions/queries/innerConditional.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | ` (case_statement value:(_) (expression_statement (_)+ @conditional) (break_statement)* @conditional ) `,
6 | ` (conditional_expression consequence:(_)+ @conditional) `,
7 | ` (conditional_expression alternative:(_)+ @conditional ) `,
8 |
9 | ` (if_statement consequence:(compound_statement
10 | (_)+ @conditional))
11 |
12 | `,
13 | `(else_clause (compound_statement (_)+ @conditional))`,
14 | `(else_clause (expression_statement (_)+ @conditional))`,
15 |
16 | ` (if_statement consequence:(expression_statement (_)+ @conditional )) `,
17 |
18 | ,
19 | ].join('\n'),
20 | };
21 | }
22 |
23 | function cpp(): Selector {
24 | return {
25 | language: 'cpp',
26 | query: [
27 | ` (case_statement value:(_) (expression_statement (_) @conditional) (break_statement) @conditional) `,
28 | ` (conditional_expression consequence:(_)+ @conditional) `,
29 | ` (conditional_expression alternative:(_)+ @conditional ) `,
30 | ` (if_statement consequence:(compound_statement
31 | (_)+ @conditional)) `,
32 | `(else_clause (compound_statement (_)+ @conditional))`,
33 | ` (if_statement consequence:(expression_statement (_)+ @conditional )) `,
34 | ,
35 | ].join('\n'),
36 | };
37 | }
38 | function csharp(): Selector {
39 | return {
40 | language: 'csharp',
41 | query: [
42 | ` (conditional_expression consequence:(_)+ @conditional) `,
43 | ` (conditional_expression alternative:(_)+ @conditional ) `,
44 |
45 | ` (if_statement consequence:(block
46 | (_)+ @conditional)) `,
47 | ` (switch_statement body: (switch_body (_) @conditional)) `,
48 | `(if_statement alternative: (block (_)+ @conditional))`,
49 |
50 | ` (if_statement consequence:(expression_statement (_)+ @conditional )) `,
51 |
52 | ,
53 | ].join('\n'),
54 | };
55 | }
56 | function go(): Selector {
57 | return {
58 | language: 'go',
59 | query: [
60 | `
61 | (if_statement
62 | consequence: (block (_) @consequence)
63 | )
64 |
65 | `,
66 | `(if_statement consequence: (block (_)* @conditional) )`,
67 | `(if_statement alternative: (block (_)* @conditional))`,
68 |
69 | `(expression_switch_statement (expression_case (_) @conditional ))`,
70 | ].join('\n'),
71 | };
72 | }
73 |
74 | function java(): Selector {
75 | return {
76 | language: 'java',
77 | query: [
78 | ` (if_statement consequence:(block (_)+ @conditional )) `,
79 | ` (if_statement consequence:(expression_statement (_)+ @conditional)) `,
80 | ` (if_statement alternative:(expression_statement (_)+ @conditional)) `,
81 | ` (if_statement alternative:(block (_)+ @conditional )) `,
82 | ` (ternary_expression consequence:(_) @conditional) `,
83 | ` (ternary_expression alternative:(_) @conditional) `,
84 |
85 | /**
86 | * maybe todo? there is a bug where
87 | * case value1:
88 | * case value2:
89 | * rest of the code
90 | *
91 | * can select the line of value1 if you are on the top
92 | *
93 | * and if you are on the bottom it selects
94 | *
95 | * value2:
96 | * rest of the code
97 | */
98 | `
99 | (switch_block_statement_group
100 | (switch_label)*
101 | (_)+ @conditional
102 | (break_statement)? @conditional) `,
103 | ].join('\n'),
104 | };
105 | }
106 |
107 | function lua(): Selector {
108 | return {
109 | language: 'lua',
110 | query: [
111 | '(if_statement consequence: (_) @conditional )',
112 | '(if_statement consequence: (_) @conditional (comment) @comment )',
113 | '(if_statement alternative: (else_clause (_) @conditional ) )',
114 | ].join('\n'),
115 | };
116 | }
117 |
118 | function python(): Selector {
119 | return {
120 | language: 'python',
121 | query: [
122 | ` (if_statement consequence: (_) @conditional) `,
123 | ` (elif_clause consequence:(block (_)+ @conditional)) `,
124 | ` (else_clause body:(block (_)+ @conditional)) `,
125 |
126 | ` (conditional_expression (_)+ @conditional ) `,
127 | //ternaries, kinda crazy
128 | ` (conditional_expression (_) (comparison_operator (_) ) (_)+ @conditional) `,
129 | ].join('\n'),
130 | };
131 | }
132 | function rust(): Selector {
133 | return {
134 | language: 'rust',
135 | query: [
136 | `(if_expression consequence: (block (_)+ @conditional )) `,
137 | `(match_expression body: (match_block (_)+ @conditional )) `,
138 | `(let_declaration value: (if_expression consequence: (block (_)+ @conditional))) `,
139 | ` (else_clause (block (_)+ @conditional )) `,
140 | ].join('\n'),
141 | };
142 | }
143 |
144 | function javascript(): Selector {
145 | return {
146 | language: 'javascript',
147 | query: [
148 | ` (if_statement consequence: (statement_block (_)+ @inner_statement)) `,
149 | ` (else_clause (statement_block (_)+ @conditional)) `,
150 | ` (if_statement consequence: (expression_statement (_)+ @inner_statement)) `,
151 | ` (else_clause (expression_statement (_)+ @inner_statement)) `,
152 | ` (ternary_expression consequence:(_) @conditional ) `,
153 | ` (ternary_expression alternative:(_) @conditional ) `,
154 | ` (switch_case (comment)* @conditional )`,
155 | ` (switch_case (comment)* @conditional body:(_)* @conditional ) `,
156 | ].join('\n'),
157 | };
158 | }
159 |
160 | function typescript(): Selector {
161 | return {
162 | language: 'typescript',
163 | query: javascript().query,
164 | };
165 | }
166 | function typescriptreact(): Selector {
167 | return {
168 | language: 'typescriptreact',
169 | query: javascript().query,
170 | };
171 | }
172 | function javascriptreact(): Selector {
173 | return {
174 | language: 'javascriptreact',
175 | query: javascript().query,
176 | };
177 | }
178 |
179 | function php(): Selector {
180 | return {
181 | language: 'php',
182 | query: [
183 | `(if_statement body:(compound_statement (_)+ @conditional )) `,
184 | `(if_statement alternative:(else_clause body:(compound_statement (_)+ @conditional))) `,
185 | `(if_statement alternative:(else_clause body:((_)+ @conditional))) `,
186 | `(conditional_expression body: (_) @conditional) `,
187 | `(conditional_expression alternative: (_) @conditional) `,
188 | ].join('\n'),
189 | };
190 | }
191 | export default {
192 | C,
193 | cpp,
194 | csharp,
195 | go,
196 | java,
197 | javascript,
198 | lua,
199 | python,
200 | rust,
201 | typescript,
202 | typescriptreact,
203 | javascriptreact,
204 | php,
205 | };
206 |
--------------------------------------------------------------------------------
/src/motions/queries/innerFunction.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(function_definition body: (compound_statement (_)+ @function)) `].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [
12 | ` (function_definition body: (
13 | (compound_statement (_)+ @function))) `,
14 | `
15 | (lambda_expression
16 | declarator: (abstract_function_declarator)
17 | body: (compound_statement (_)+ @function))
18 | `,
19 | ].join('\n'),
20 | };
21 | }
22 | function csharp(): Selector {
23 | return {
24 | language: 'csharp',
25 | query: [
26 | ` (method_declaration body:(block (_)+ @function )) `,
27 | ` (local_function_statement body:(block (_)+ @function )) `,
28 | ` (lambda_expression body:(_)+ @function )`,
29 | ].join('\n'),
30 | };
31 | }
32 | function go(): Selector {
33 | return {
34 | language: 'go',
35 | query: [
36 | ` (function_declaration body:(block (_) @function )) `,
37 | ` (method_declaration body:(block (_) @function )) `,
38 | ].join('\n'),
39 | };
40 | }
41 | function java(): Selector {
42 | return {
43 | language: 'java',
44 | query: [
45 | ` (method_declaration body:(block (_)+ @function)) `,
46 | ` (variable_declarator value:(lambda_expression body:(block (_)+ @function)))`,
47 | ].join('\n'),
48 | };
49 | }
50 | function javascript(): Selector {
51 | return {
52 | language: 'javascript',
53 | query: [
54 | `((function_declaration body: (statement_block (_)* @function_body)))`,
55 | `(function_expression body: (statement_block (_)* @function.body)) `,
56 | `(arrow_function body: (statement_block (_)* @function_body)) `,
57 | `(method_definition body: (statement_block (_)* @function.body)) `,
58 | ].join('\n'),
59 | };
60 | }
61 | function lua(): Selector {
62 | return {
63 | language: 'lua',
64 | query: [
65 | `(function_definition_statement body: (block (_)+ @function )) `,
66 | `(local_function_definition_statement body: (block (_)+ @function )) `,
67 | `(local_variable_declaration (expression_list value:(function_definition body: (block (_)+ @function )))) `,
68 | `(variable_assignment (expression_list value:(function_definition body: (block (_)+ @function )))) `,
69 | `(field value:(function_definition body: (block (_)+ @function))) `,
70 | ].join('\n'),
71 | };
72 | }
73 |
74 | function python(): Selector {
75 | return {
76 | language: 'python',
77 | query: ['(function_definition body: (_)+ @function)'].join('\n'),
78 | };
79 | }
80 | function rust(): Selector {
81 | return {
82 | language: 'rust',
83 | query: [
84 | `(_ (closure_expression body:(_ (_)* @function ))) `,
85 | `(function_item body: (_)* @function ) `,
86 | `(function_signature_item ) @function `,
87 | ].join('\n'),
88 | };
89 | }
90 | function typescript(): Selector {
91 | return {
92 | language: 'typescript',
93 | query: javascript().query,
94 | };
95 | }
96 | function typescriptreact(): Selector {
97 | return {
98 | language: 'typescriptreact',
99 | query: javascript().query,
100 | };
101 | }
102 | function javascriptreact(): Selector {
103 | return {
104 | language: 'javascriptreact',
105 | query: javascript().query,
106 | };
107 | }
108 | function php(): Selector {
109 | return {
110 | language: 'php',
111 | query: [
112 | `(function_definition body:(compound_statement (_) @function )) `,
113 | `(anonymous_function_creation_expression body:(compound_statement (_) @function )) `,
114 | `(arrow_function body:(_) @function ) `,
115 | `(method_declaration body:(compound_statement (_) @function )) `,
116 | ].join('\n'),
117 | };
118 | }
119 | export default {
120 | C,
121 | cpp,
122 | csharp,
123 | go,
124 | java,
125 | javascript,
126 | lua,
127 | python,
128 | rust,
129 | typescript,
130 | typescriptreact,
131 | javascriptreact,
132 | php,
133 | };
134 |
--------------------------------------------------------------------------------
/src/motions/queries/innerLhs.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(field_expression field:(_) @lhs ) `,
6 | `(init_declarator declarator:(_) @lhs)`,
7 | `(assignment_expression left:(_) @lhs) `,
8 | ].join('\n'),
9 | };
10 | }
11 |
12 | function cpp(): Selector {
13 | return {
14 | language: 'cpp',
15 | query: [` (declaration declarator:(init_declarator (_ (_) @lhs) )) `].join('\n'),
16 | };
17 | }
18 | function csharp(): Selector {
19 | return {
20 | language: 'csharp',
21 | query: [
22 | ` (variable_declaration type:(predefined_type) @lhs (variable_declarator)) @lhs `,
23 | ` (assignment_expression left:(_) @lhs) `,
24 | ].join('\n'),
25 | };
26 | }
27 | function go(): Selector {
28 | return {
29 | language: 'go',
30 | query: [
31 | ` (var_declaration (var_spec value:(expression_list (_) @variable ) )) `,
32 | ` (const_declaration (const_spec value:(expression_list (_) @variable ) )) `,
33 | ` (short_var_declaration left:(expression_list (_) @variable )) `,
34 | ].join('\n'),
35 | };
36 | }
37 | function java(): Selector {
38 | return {
39 | language: 'java',
40 | query: [`(local_variable_declaration declarator:(variable_declarator name:(identifier) @lhs)) `].join(
41 | '\n'
42 | ),
43 | };
44 | }
45 | function javascript(): Selector {
46 | return {
47 | language: 'javascript',
48 | query: [`(variable_declarator name:(_) @lhs) `, `(assignment_expression left:(identifier) @lhs)`].join(
49 | '\n'
50 | ),
51 | };
52 | }
53 |
54 | function json(): Selector {
55 | return {
56 | language: 'json',
57 | query: [`(pair key : (string (_) @key))`].join('\n'),
58 | };
59 | }
60 | function jsonc(): Selector {
61 | return {
62 | language: 'jsonc',
63 | query: [`(pair key : (string (_) @key))`].join('\n'),
64 | };
65 | }
66 |
67 | function lua(): Selector {
68 | return {
69 | language: 'lua',
70 | query: [` (variable_list (variable name:(identifier) @val)) `].join('\n'),
71 | };
72 | }
73 |
74 | function python(): Selector {
75 | return {
76 | language: 'python',
77 | query: [`(assignment left:(_ attribute: (_)@lhs))`].join('\n'),
78 | };
79 | }
80 | function rust(): Selector {
81 | return {
82 | language: 'rust',
83 | query: [
84 | ` (let_declaration pattern:(tuple_pattern (_) @lhs)) `,
85 | ` (static_item name:(_) @lhs )`,
86 | ` (let_declaration pattern:(identifier) @lhs )`,
87 | ` (const_item name:(_) @lhs )`,
88 | ].join('\n'),
89 | };
90 | }
91 |
92 | function toml(): Selector {
93 | return {
94 | language: 'toml',
95 | query: [`(pair (bare_key) @lhs) `].join('\n'),
96 | };
97 | }
98 |
99 | function typescript(): Selector {
100 | return {
101 | language: 'typescript',
102 | query: javascript().query,
103 | };
104 | }
105 | function yaml(): Selector {
106 | return {
107 | language: 'yaml',
108 | query: [`(block_mapping_pair key : (flow_node (_) @lhs ))`].join('\n'),
109 | };
110 | }
111 | function typescriptreact(): Selector {
112 | return {
113 | language: 'typescriptreact',
114 | query: typescript().query,
115 | };
116 | }
117 | function javascriptreact(): Selector {
118 | return {
119 | language: 'javascriptreact',
120 | query: javascript().query,
121 | };
122 | }
123 | function php(): Selector {
124 | return {
125 | language: 'php',
126 | query: [
127 | `(assignment_expression left:(variable_name (_) @variable ) ) `,
128 | `(assignment_expression left:(list_literal (_) @variable ) ) `,
129 | ].join('\n'),
130 | };
131 | }
132 | export default {
133 | C,
134 | cpp,
135 | csharp,
136 | go,
137 | java,
138 | javascript,
139 | json,
140 | jsonc,
141 | toml,
142 | lua,
143 | python,
144 | rust,
145 | typescript,
146 | yaml,
147 | typescriptreact,
148 | javascriptreact,
149 | php,
150 | };
151 |
--------------------------------------------------------------------------------
/src/motions/queries/innerLoop.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(for_statement body: (compound_statement (_)+ @loops)) `,
6 | `(while_statement body: (compound_statement (_)+ @loops)) `,
7 | `(do_statement body: (compound_statement (_)+ @loops)) `,
8 | ].join('\n'),
9 | };
10 | }
11 |
12 | function cpp(): Selector {
13 | return {
14 | language: 'cpp',
15 | query: [
16 | ` (for_range_loop body: (compound_statement (_)+ @loop) ) `,
17 | ` (for_statement body: (compound_statement (_)+ @loop)) `,
18 | ].join('\n'),
19 | };
20 | }
21 | function csharp(): Selector {
22 | return {
23 | language: 'csharp',
24 | query: [
25 | `(for_statement body: (block (_)+ @loop)) `,
26 | `(for_each_statement (block (_)+ @loop)) `,
27 | `(while_statement (block (_)+ @loop)) `,
28 | `(do_statement (block (_)+ @loop))`,
29 | ].join('\n'),
30 | };
31 | }
32 | function go(): Selector {
33 | return {
34 | language: 'go',
35 | query: [`(for_statement body: (block (_) @loop)*) `].join('\n'),
36 | };
37 | }
38 | function java(): Selector {
39 | return {
40 | language: 'java',
41 | query: [
42 | ` (for_statement body:(block (_) @loop)) `,
43 | ` (enhanced_for_statement body:(block (_) @loop)) `,
44 | ` (while_statement body:(block (_) @loop)) `,
45 | ` (do_statement body:(block (_) @loop)) `,
46 | ].join('\n'),
47 | };
48 | }
49 | function javascript(): Selector {
50 | return {
51 | language: 'javascript',
52 | query: [
53 | `
54 | (for_statement
55 | body: (statement_block
56 | (_)* @loop_body))
57 |
58 | (for_in_statement
59 | body: (statement_block
60 | (_)* @loop_body))
61 | `,
62 | ].join('\n'),
63 | };
64 | }
65 | function lua(): Selector {
66 | return {
67 | language: 'lua',
68 | query: [
69 | `(while_statement body: (block (_)+ @loop )) `,
70 | `(repeat_statement body: (block (_)+ @loop )) `,
71 | `(for_numeric_statement body: (block (_)+ @loop )) `,
72 | `(for_generic_statement body: (block (_)+ @loop )) `,
73 | ].join('\n'),
74 | };
75 | }
76 |
77 | function python(): Selector {
78 | return {
79 | language: 'python',
80 | query: [
81 | `(list_comprehension body: (_)+ @loop )`,
82 | `(for_in_clause right:(_) @loop )`,
83 | `(for_statement body: (block (_)+ @loop)) `,
84 | ].join('\n'),
85 | };
86 | }
87 | function rust(): Selector {
88 | return {
89 | language: 'rust',
90 | query: [` (for_expression body: (block (_)+ @loop)) `].join('\n'),
91 | };
92 | }
93 | function typescript(): Selector {
94 | return {
95 | language: 'typescript',
96 | query: javascript().query,
97 | };
98 | }
99 | function typescriptreact(): Selector {
100 | return {
101 | language: 'typescriptreact',
102 | query: javascript().query,
103 | };
104 | }
105 | function javascriptreact(): Selector {
106 | return {
107 | language: 'javascriptreact',
108 | query: javascript().query,
109 | };
110 | }
111 |
112 | function php(): Selector {
113 | return {
114 | language: 'php',
115 | query: [
116 | ` (for_statement body:(compound_statement (_) @loop )) `,
117 | ` (foreach_statement body:(compound_statement (_) @loop)) `,
118 | ` (while_statement body:(compound_statement (_) @loop )) `,
119 | ` (do_statement body:(compound_statement (_) @loop ) ) `,
120 | ].join('\n'),
121 | };
122 | }
123 | export default {
124 | C,
125 | cpp,
126 | csharp,
127 | go,
128 | java,
129 | javascript,
130 | lua,
131 | python,
132 | rust,
133 | typescript,
134 | typescriptreact,
135 | javascriptreact,
136 | php,
137 | };
138 |
--------------------------------------------------------------------------------
/src/motions/queries/innerObject.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(struct_specifier body: (field_declaration_list (_) @object) ) `,
6 | `(enum_specifier body: (enumerator_list (_) @object )) `,
7 | `
8 | (union_specifier body:(field_declaration_list (_)+ @object) )
9 |
10 | `,
11 | ].join('\n'),
12 | };
13 | }
14 |
15 | function cpp(): Selector {
16 | return {
17 | language: 'cpp',
18 | query: [
19 | `(class_specifier) @object`,
20 | `(struct_specifier) @object`,
21 | `(declaration
22 | declarator:(init_declarator
23 | value:(initializer_list))) @object`,
24 | `(type_definition
25 | type:(struct_specifier)
26 | ) @object`,
27 | ].join('\n'),
28 | };
29 | }
30 | function csharp(): Selector {
31 | return {
32 | language: 'csharp',
33 | query: [
34 | `(class_declaration body:(declaration_list (_)@object)) `,
35 | `(enum_declaration body:(enum_member_declaration_list (_)@object)) `,
36 | `(struct_declaration body:(declaration_list (_) @object)) `,
37 | `(record_declaration parameters: (parameter_list (_)@parameter)) @object `,
38 | `(anonymous_object_creation_expression (_) @object) `,
39 | `(tuple_expression (_) @object ) `,
40 | ].join('\n'),
41 | };
42 | }
43 | function go(): Selector {
44 | return {
45 | language: 'go',
46 | query: [
47 | `(type_declaration (type_spec type: (struct_type))) @struct`,
48 | ` (expression_list (composite_literal (_) ) ) @struct`,
49 | ].join('\n'),
50 | };
51 | }
52 | function java(): Selector {
53 | return {
54 | language: 'java',
55 | query: [
56 | '(class_declaration body: (class_body (_) @class) ) ',
57 | ` (local_variable_declaration
58 | declarator:(variable_declarator
59 | value:(object_creation_expression) @object )) `,
60 | ].join('\n'),
61 | };
62 | }
63 | function javascript(): Selector {
64 | return {
65 | language: 'javascript',
66 | query: ['(object (_) @object ) '].join('\n'),
67 | };
68 | }
69 | function jsonc(): Selector {
70 | return {
71 | language: 'jsonc',
72 | query: javascript().query,
73 | };
74 | }
75 | function json(): Selector {
76 | return {
77 | language: 'json',
78 | query: javascript().query,
79 | };
80 | }
81 |
82 | function lua(): Selector {
83 | return {
84 | language: 'lua',
85 | query: [`(table (field_list (_) @object )) `].join('\n'),
86 | };
87 | }
88 |
89 | function python(): Selector {
90 | return {
91 | language: 'python',
92 | query: ['(dictionary (_) @object) '].join('\n'),
93 | };
94 | }
95 | function rust(): Selector {
96 | return {
97 | language: 'rust',
98 | query: [
99 | `(struct_item body: (field_declaration_list (_) @object)) `,
100 | `(struct_expression body: (field_initializer_list (_) @object)) `,
101 | `(enum_item body: (enum_variant_list (_) @object)) `,
102 | ].join('\n'),
103 | };
104 | }
105 |
106 | function toml(): Selector {
107 | return {
108 | language: 'toml',
109 | query: ['(table (_) @object ) ', `(inline_table (_) @object) `].join('\n'),
110 | };
111 | }
112 |
113 | function typescript(): Selector {
114 | return {
115 | language: 'typescript',
116 | query: javascript().query,
117 | };
118 | }
119 | function typescriptreact(): Selector {
120 | return {
121 | language: 'typescriptreact',
122 | query: javascript().query,
123 | };
124 | }
125 | function javascriptreact(): Selector {
126 | return {
127 | language: 'javascriptreact',
128 | query: javascript().query,
129 | };
130 | }
131 | function yaml(): Selector {
132 | return {
133 | language: 'yaml',
134 | query: [
135 | ` (block_mapping_pair value:(block_node (block_mapping (block_mapping_pair key:(_) value:(flow_node (_))) @object ))) `,
136 | ].join('\n'),
137 | };
138 | }
139 | function php(): Selector {
140 | return {
141 | language: 'php',
142 | query: [` (array_creation_expression (array_element_initializer (encapsed_string ) @object )) `].join(
143 | '\n'
144 | ),
145 | };
146 | }
147 |
148 | export default {
149 | C,
150 | cpp,
151 | csharp,
152 | go,
153 | java,
154 | javascript,
155 | json,
156 | jsonc,
157 | toml,
158 | lua,
159 | python,
160 | rust,
161 | typescript,
162 | yaml,
163 | typescriptreact,
164 | javascriptreact,
165 | php,
166 | };
167 |
--------------------------------------------------------------------------------
/src/motions/queries/innerParams.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: ['(parameter_list (_) @parameters) '].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [` (parameter_list (_) @params ) `].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [` (parameter_list (_) @parameters) `].join('\n'),
18 | };
19 | }
20 | function go(): Selector {
21 | return {
22 | language: 'go',
23 | query: [`(parameter_list (_) @parameters)`].join('\n'),
24 | };
25 | }
26 | function java(): Selector {
27 | return {
28 | language: 'java',
29 | query: [` (method_declaration parameters:(formal_parameters (_) @parameters) ) `].join('\n'),
30 | };
31 | }
32 | function javascript(): Selector {
33 | return {
34 | language: 'javascript',
35 | query: [`(formal_parameters (_) @parameter )`].join('\n'),
36 | };
37 | }
38 |
39 | function lua(): Selector {
40 | return {
41 | language: 'lua',
42 | query: ['(parameter_list (_) @params) '].join('\n'),
43 | };
44 | }
45 |
46 | function python(): Selector {
47 | return {
48 | language: 'python',
49 | query: ['(parameters (_) @parameters )'].join('\n'),
50 | };
51 | }
52 | function rust(): Selector {
53 | return {
54 | language: 'rust',
55 | query: ['(parameters) @parameters'].join('\n'),
56 | };
57 | }
58 |
59 | function typescript(): Selector {
60 | return {
61 | language: 'typescript',
62 | query: javascript().query,
63 | };
64 | }
65 | function typescriptreact(): Selector {
66 | return {
67 | language: 'typescriptreact',
68 | query: javascript().query,
69 | };
70 | }
71 | function javascriptreact(): Selector {
72 | return {
73 | language: 'javascriptreact',
74 | query: javascript().query,
75 | };
76 | }
77 | function php(): Selector {
78 | return {
79 | language: 'php',
80 | query: [
81 | `
82 | (formal_parameters (_) @parameter)
83 | `,
84 | ].join('\n'),
85 | };
86 | }
87 |
88 | export default {
89 | C,
90 | cpp,
91 | csharp,
92 | go,
93 | java,
94 | javascript,
95 | lua,
96 | python,
97 | rust,
98 | typescript,
99 | typescriptreact,
100 | javascriptreact,
101 | php,
102 | };
103 |
--------------------------------------------------------------------------------
/src/motions/queries/innerRhs.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `( field_expression field:(field_identifier) @rhs ) `,
6 | ` (init_declarator value:(initializer_list (_) @rhs))`,
7 | ].join('\n'),
8 | };
9 | }
10 |
11 | function cpp(): Selector {
12 | return {
13 | language: 'cpp',
14 | query: [
15 | // lambda_expression
16 | `(init_declarator value:(_ body:(_ (_)+ @rhs ))) `,
17 | `(init_declarator value:(_ value: (_(_)@rhs ))) `,
18 | `(init_declarator value:(_ arguments:(argument_list (lambda_expression body:(_ (_) @rhs ))))) `,
19 | `(init_declarator value:(_ arguments:(_ (_) @rhs))) `,
20 | ].join('\n'),
21 | };
22 | }
23 | function csharp(): Selector {
24 | return {
25 | language: 'csharp',
26 | query: [` (equals_value_clause (_ (_)@rhs) )`, ` (assignment_expression right:(_ (_) @rhs) )`].join(
27 | '\n'
28 | ),
29 | };
30 | }
31 | function go(): Selector {
32 | return {
33 | language: 'go',
34 | query: [
35 | ` (expression_list (_ body:(_ (_) @rhs ))) `,
36 | ` (expression_list (_ function:(_ body:(_ (_)+ @rhs )))) `,
37 | ` (expression_list (_ arguments:(_ (_) @rhs))) `,
38 | ].join('\n'),
39 | };
40 | }
41 | function java(): Selector {
42 | return {
43 | language: 'java',
44 | query: [
45 | ` (_ declarator:(_ value:(object_creation_expression (_ (_) @rhs )))) `,
46 | ` (_ value:(array_initializer (_)@rhs)) `,
47 | ` (_ declarator:(_ value:(_ arguments:(_ (_) @rhs)))) `,
48 | ].join('\n'),
49 | };
50 | }
51 | function javascript(): Selector {
52 | return {
53 | language: 'javascript',
54 | query: [
55 | ` (variable_declarator value:(object (_) @rhs))`,
56 | ` (assignment_expression right:(_ (_)@rhs )) `,
57 | ` (variable_declarator value:(_ body:(_ (_)+ @rhs ))) `,
58 | ` (variable_declarator value:(_ arguments:(_ (_) @rhs))) `,
59 | ].join('\n'),
60 | };
61 | }
62 | function jsonc(): Selector {
63 | return {
64 | language: 'jsonc',
65 | query: ['(pair value : (_ (_) @rhs))'].join('\n'),
66 | };
67 | }
68 | function json(): Selector {
69 | return {
70 | language: 'json',
71 | query: ['(pair value : (_ (_) @rhs))'].join('\n'),
72 | };
73 | }
74 |
75 | function lua(): Selector {
76 | return {
77 | language: 'lua',
78 | // maybe do generic?
79 | // call doesnt work when just replacing things with just _
80 | query: [
81 | ` (local_variable_declaration (expression_list value:(call arguments:(_ (_) @rhs )))) `,
82 | ` (local_variable_declaration (expression_list value:(table (field_list (_) @rhs )))) `,
83 | ` (local_variable_declaration (expression_list value:(function_definition body:(block (_)+ @rhs )))) `,
84 | ].join('\n'),
85 | };
86 | }
87 |
88 | function python(): Selector {
89 | return {
90 | language: 'python',
91 | query: [
92 | ` (assignment right:(lambda body:(binary_operator (_) @rhs))) `,
93 | ` (assignment right:(list (_) @rhs )) `,
94 | ` (assignment right:(call arguments:(argument_list (lambda body:(_) @rhs )))) `,
95 | ` (assignment right:(call arguments:(argument_list (_) @rhs ))) `,
96 | ` (assignment right:(lambda body:(_) @rhs)) `,
97 | ` (assignment right:(dictionary (_) @rhs )) `,
98 | ` (assignment right:(list_comprehension (_) @rhs)) `,
99 | ].join('\n'),
100 | };
101 | }
102 | function rust(): Selector {
103 | return {
104 | language: 'rust',
105 | query: [
106 | //clojure
107 | ` (let_declaration value:(closure_expression body:(_) @rhs)) `,
108 | ` (static_item value:(closure_expression body:(_) @rhs)) `,
109 | ` (const_item value:(closure_expression body:(_) @rhs)) `,
110 |
111 | //tuples
112 | ` (let_declaration value:(tuple_expression (_) @rhs)) `,
113 | ` (static_item value:(tuple_expression (_) @rhs)) `,
114 | ` (const_item value:(tuple_expression (_) @rhs)) `,
115 |
116 | //arrays
117 | ` (let_declaration value:(array_expression (_) @rhs)) `,
118 | ` (static_item value:(array_expression (_) @rhs)) `,
119 | ` (const_item value:(array_expression (_) @rhs)) `,
120 |
121 | //match
122 | ` (let_declaration value:(match_expression body:(match_block (_) @rhs ))) `,
123 | ` (static_item value:(match_expression body:(match_block (_) @rhs ))) `,
124 | ` (const_item value:(match_expression body:(match_block (_) @rhs ))) `,
125 |
126 | //struct
127 | ` (let_declaration value:(struct_expression body:( field_initializer_list (_) @rhs))) `,
128 | ` (static_item value:(struct_expression body:( field_initializer_list (_) @rhs))) `,
129 | ` (const_item value:(struct_expression body:( field_initializer_list (_) @rhs))) `,
130 |
131 | //variants?
132 | ` (let_declaration value:(call_expression arguments:(arguments (_) @rhs ))) `,
133 | ` (static_item value:(call_expression arguments:(arguments (_) @rhs ))) `,
134 | ` (const_item value:(call_expression arguments:(arguments (_) @rhs ))) `,
135 |
136 | //macro
137 | ` (let_declaration value:(macro_invocation (_ (_) @rhs ))) `,
138 | ` (const_item value:(macro_invocation (_ (_) @rhs ))) `,
139 | ` (static_item value:(macro_invocation (_ (_) @rhs ))) `,
140 |
141 | ` (let_declaration value:(if_expression consequence:(block (_) @rhs ) alternative:(else_clause (_ (_) @rhs )))) `,
142 | ` (static_item value:(if_expression consequence:(block (_) @rhs ) alternative:(else_clause (_ (_) @rhs )))) `,
143 | ` (const_item value:(if_expression consequence:(block (_) @rhs ) alternative:(else_clause (_ (_) @rhs )))) `,
144 | ].join('\n'),
145 | };
146 | }
147 |
148 | function toml(): Selector {
149 | return {
150 | language: 'toml',
151 | query: [`(pair (bare_key) (_ (_) @rhs) )`].join('\n'),
152 | };
153 | }
154 |
155 | function typescript(): Selector {
156 | return {
157 | language: 'typescript',
158 | query: javascript().query,
159 | };
160 | }
161 | function yaml(): Selector {
162 | return {
163 | language: 'yaml',
164 | query: [
165 | `
166 | (block_mapping_pair
167 | key:(flow_node
168 | (plain_scalar))
169 | value:(block_node (_ (_) @rhs )))
170 | `,
171 | ].join('\n'),
172 | };
173 | }
174 | function typescriptreact(): Selector {
175 | return {
176 | language: 'typescriptreact',
177 | query: javascript().query,
178 | };
179 | }
180 | function javascriptreact(): Selector {
181 | return {
182 | language: 'javascriptreact',
183 | query: javascript().query,
184 | };
185 | }
186 | function php(): Selector {
187 | return {
188 | language: 'php',
189 | query: [` (assignment_expression right:(_ (_) @rhs )) `].join('\n'),
190 | };
191 | }
192 |
193 | export default {
194 | C,
195 | cpp,
196 | csharp,
197 | go,
198 | java,
199 | javascript,
200 | json,
201 | jsonc,
202 | toml,
203 | lua,
204 | python,
205 | rust,
206 | typescript,
207 | yaml,
208 | typescriptreact,
209 | javascriptreact,
210 | php,
211 | };
212 |
--------------------------------------------------------------------------------
/src/motions/queries/innerString.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: ['(string_content) @string', '(character) @string'].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: [` (string_content) @string `].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [
18 | ` (string_literal) @string `,
19 | `(interpolated_string_expression) @string`,
20 | `(character_literal) @string`,
21 | ].join('\n'),
22 | };
23 | }
24 | function go(): Selector {
25 | return {
26 | language: 'go',
27 | query: [`(raw_string_literal) @string`, `(interpreted_string_literal) @string`].join('\n'),
28 | };
29 | }
30 | function java(): Selector {
31 | return {
32 | language: 'java',
33 | query: ['(string_fragment) @string', `(multiline_string_fragment) @string`].join('\n'),
34 | };
35 | }
36 | function javascript(): Selector {
37 | return {
38 | language: 'javascript',
39 | query: [`(string (_)* @string) `, `(template_string (_)* @string) `].join('\n'),
40 | };
41 | }
42 | function jsonc(): Selector {
43 | return {
44 | language: 'jsonc',
45 | query: [`(string_content) @string`].join('\n'),
46 | };
47 | }
48 | function json(): Selector {
49 | return {
50 | language: 'json',
51 | query: [`(string_content) @string`].join('\n'),
52 | };
53 | }
54 |
55 | function lua(): Selector {
56 | return {
57 | language: 'lua',
58 | query: ['(string) @string'].join('\n'),
59 | };
60 | }
61 |
62 | function python(): Selector {
63 | return {
64 | language: 'python',
65 | query: [` (string_content) @string `].join('\n'),
66 | };
67 | }
68 | function rust(): Selector {
69 | return {
70 | language: 'rust',
71 | query: [`(string_literal) @string`, `(char_literal) @string`].join('\n'),
72 | };
73 | }
74 |
75 | function toml(): Selector {
76 | return {
77 | language: 'toml',
78 | query: [`(string) @string`].join('\n'),
79 | };
80 | }
81 |
82 | function typescript(): Selector {
83 | return {
84 | language: 'typescript',
85 | query: javascript().query,
86 | };
87 | }
88 |
89 | function yaml(): Selector {
90 | return {
91 | language: 'yaml',
92 | query: [
93 | `(single_quote_scalar) @string`,
94 | ` (block_mapping_pair value:(block_node (block_scalar) @string)) `,
95 | ` (block_mapping_pair value:(flow_node (double_quote_scalar) @string )) `,
96 | ].join('\n'),
97 | };
98 | }
99 | function typescriptreact(): Selector {
100 | return {
101 | language: 'typescriptreact',
102 | query: javascript().query,
103 | };
104 | }
105 | function javascriptreact(): Selector {
106 | return {
107 | language: 'javascriptreact',
108 | query: javascript().query,
109 | };
110 | }
111 |
112 | function php(): Selector {
113 | return {
114 | language: 'php',
115 | query: [`(string_content) @string`, `(nowdoc_string) @string `].join('\n'),
116 | };
117 | }
118 |
119 | export default {
120 | C,
121 | cpp,
122 | csharp,
123 | go,
124 | java,
125 | javascript,
126 | json,
127 | jsonc,
128 | toml,
129 | lua,
130 | python,
131 | rust,
132 | typescript,
133 | yaml,
134 | typescriptreact,
135 | javascriptreact,
136 | php,
137 | };
138 |
--------------------------------------------------------------------------------
/src/motions/queries/innerType.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [
5 | `(struct_specifier body: (field_declaration_list (_)+ @types ))`,
6 | `(union_specifier body:(field_declaration_list (_)+ @object) )`,
7 | ].join('\n'),
8 | };
9 | }
10 |
11 | function cpp(): Selector {
12 | //todo: add the types
13 | return {
14 | language: 'cpp',
15 | query: [`(primitive_type) @type`].join('\n'),
16 | };
17 | }
18 | function csharp(): Selector {
19 | return {
20 | language: 'csharp',
21 | query: [
22 | // `(predefined_type) @type`,
23 | // `(void_keyword) @type`,
24 | // `(type_parameter) @type`,
25 | `(array_type (_)* @type)`,
26 |
27 | ` (struct_declaration body:(_ (_)* @type)) `,
28 | ].join('\n'),
29 | };
30 | }
31 | function go(): Selector {
32 | return {
33 | language: 'go',
34 | query: [
35 | `(pointer_type (_) @types ) `,
36 | `(interface_type (_) @types)`,
37 | `(struct_type (field_declaration_list (_)+ @types))`,
38 | `(qualified_type (_) @types ) `,
39 | ].join('\n'),
40 | };
41 | }
42 | function java(): Selector {
43 | return {
44 | language: 'java',
45 | query: [`(interface_declaration body:(interface_body (_) @type))`].join('\n'),
46 | };
47 | }
48 |
49 | function rust(): Selector {
50 | return {
51 | language: 'rust',
52 | query: ['(struct_item body: (field_declaration_list (_) @types ))'].join('\n'),
53 | };
54 | }
55 |
56 | function typescript(): Selector {
57 | return {
58 | language: 'typescript',
59 | //todo addtypes
60 | query: [
61 | `(interface_declaration body:(_ (_)* @type )) `,
62 | `(type_alias_declaration value:(object_type (_)* @type )) `,
63 | `(enum_declaration body:(enum_body (_)* @type )) `,
64 | ` (required_parameter type:(_) @type ) `,
65 | ].join('\n'),
66 | };
67 | }
68 | function typescriptreact(): Selector {
69 | return {
70 | language: 'typescriptreact',
71 | query: typescript().query,
72 | };
73 | }
74 | function php(): Selector {
75 | return {
76 | language: 'php',
77 | query: [`(primitive_type) @type`].join('\n'),
78 | };
79 | }
80 |
81 | export default {
82 | C,
83 | cpp,
84 | csharp,
85 | go,
86 | java,
87 | rust,
88 | typescript,
89 | typescriptreact,
90 | php,
91 | };
92 |
--------------------------------------------------------------------------------
/src/motions/queries/innercomment.ts:
--------------------------------------------------------------------------------
1 | function C(): Selector {
2 | return {
3 | language: 'c',
4 | query: [`(comment) @comment`].join('\n'),
5 | };
6 | }
7 |
8 | function cpp(): Selector {
9 | return {
10 | language: 'cpp',
11 | query: ['(comment) @comment'].join('\n'),
12 | };
13 | }
14 | function csharp(): Selector {
15 | return {
16 | language: 'csharp',
17 | query: [`(comment) @comment`].join('\n'),
18 | };
19 | }
20 | function go(): Selector {
21 | return {
22 | language: 'go',
23 | query: ['(comment) @comment'].join('\n'),
24 | };
25 | }
26 | function java(): Selector {
27 | return {
28 | language: 'java',
29 | query: [`(line_comment) @comment`, `(block_comment) @comment`].join('\n'),
30 | };
31 | }
32 | function javascript(): Selector {
33 | return {
34 | language: 'javascript',
35 | query: ['(comment) @comment'].join('\n'),
36 | };
37 | }
38 |
39 | function json(): Selector {
40 | return {
41 | language: 'json',
42 | query: javascript().query,
43 | };
44 | }
45 | function jsonc(): Selector {
46 | return {
47 | language: 'jsonc',
48 | query: javascript().query,
49 | };
50 | }
51 |
52 | function lua(): Selector {
53 | return {
54 | language: 'lua',
55 | query: ['(comment) @comment'].join('\n'),
56 | };
57 | }
58 |
59 | function python(): Selector {
60 | return {
61 | language: 'python',
62 | query: [` (comment) @comment `].join('\n'),
63 | };
64 | }
65 | function rust(): Selector {
66 | return {
67 | language: 'rust',
68 | query: [` (line_comment) @comment `, ` (block_comment) @comment `].join('\n'),
69 | };
70 | }
71 |
72 | function toml(): Selector {
73 | return {
74 | language: 'toml',
75 | query: ['(comment) @comment'].join('\n'),
76 | };
77 | }
78 |
79 | function typescript(): Selector {
80 | return {
81 | language: 'typescript',
82 | query: javascript().query,
83 | };
84 | }
85 | function typescriptreact(): Selector {
86 | return {
87 | language: 'typescriptreact',
88 | query: javascript().query,
89 | };
90 | }
91 | function javascriptreact(): Selector {
92 | return {
93 | language: 'javascriptreact',
94 | query: javascript().query,
95 | };
96 | }
97 | function yaml(): Selector {
98 | return {
99 | language: 'yaml',
100 | query: ['(comment) @comment'].join('\n'),
101 | };
102 | }
103 | function php(): Selector {
104 | return {
105 | language: 'php',
106 | query: ['(comment) @comment'].join('\n'),
107 | };
108 | }
109 |
110 | export default {
111 | C,
112 | cpp,
113 | csharp,
114 | go,
115 | java,
116 | javascript,
117 | json,
118 | jsonc,
119 | toml,
120 | lua,
121 | python,
122 | rust,
123 | typescript,
124 | yaml,
125 | typescriptreact,
126 | javascriptreact,
127 | php,
128 | };
129 |
--------------------------------------------------------------------------------
/src/parsing/nodes.ts:
--------------------------------------------------------------------------------
1 | import * as parser from 'web-tree-sitter';
2 |
3 | import assert from 'assert';
4 | import { Position, Range } from 'vscode';
5 | import { QueryMatch } from 'web-tree-sitter';
6 | import { NodePool } from '../utils';
7 |
8 | const matchSelector = new Map();
9 | export function filterDuplicates(matches: QueryMatch[], selector: string | string[]): QueryMatch[] {
10 | matchSelector.clear();
11 |
12 | for (const match of matches) {
13 | if (match.captures.length === 0) {
14 | continue;
15 | }
16 | if (!match.captures.some((capture) => capture.name === selector)) {
17 | const first = match.captures[0];
18 | assert(first, 'first node came undefined?');
19 |
20 | matchSelector.set(first.node.text, match);
21 | continue;
22 | }
23 |
24 | for (const capture of match.captures) {
25 | if (selector.includes(capture.name) && !matchSelector.has(capture.node.text)) {
26 | matchSelector.set(capture.node.text, match);
27 | break;
28 | }
29 | }
30 | }
31 |
32 | return Array.from(matchSelector.values());
33 | }
34 |
35 | export const pointPool = new NodePool(function (): JoinedPoint {
36 | return {
37 | end: { column: 0, row: 0 },
38 | start: { column: 0, row: 0 },
39 | };
40 | });
41 |
42 | function before(a: parser.Point, b: parser.Point): parser.Point {
43 | if (a.row < b.row) {
44 | return a;
45 | } else if (a.row === b.row) {
46 | return a.column < b.column ? a : b;
47 | }
48 | return b;
49 | }
50 | function after(a: parser.Point, b: parser.Point): parser.Point {
51 | if (a.row < b.row) {
52 | return b;
53 | } else if (a.row === b.row) {
54 | return a.column < b.column ? b : a;
55 | }
56 | return a;
57 | }
58 |
59 | export function toNodes(matches: parser.QueryMatch[]): JoinedPoint[] {
60 | const nodes: JoinedPoint[] = new Array(matches.length);
61 | let len = 0;
62 |
63 | for (const match of matches) {
64 | if (match.captures.length === 0) {
65 | continue;
66 | }
67 |
68 | // match.captures.sort((a, b) => a.node.startIndex - b.node.startIndex);
69 | const first = match.captures.at(0)?.node;
70 | const last = match.captures.at(-1)?.node;
71 |
72 | assert(first && last, 'undefined first and last nodes');
73 | assert(first.startIndex <= last.startIndex, 'last needs to be after than first');
74 |
75 | let node = pointPool.get();
76 | assert(node, 'point node came undefined?');
77 |
78 | const top = before(
79 | before(first.startPosition, first.endPosition),
80 | before(last.startPosition, last.endPosition)
81 | );
82 |
83 | const bottom = after(
84 | after(first.startPosition, first.endPosition),
85 | after(last.startPosition, last.endPosition)
86 | );
87 |
88 | assert(top.row <= bottom.row, 'top needs to come first on line:' + top.row + ' ' + bottom.row);
89 | if (top.row === bottom.row) {
90 | assert(top.column <= bottom.column, 'top needs to come before bottom on character');
91 | }
92 | assert(
93 | top.column >= 0 && top.row >= 0 && bottom.column >= 0 && bottom.row >= 0,
94 | 'invalid node positions'
95 | );
96 | assert(node.start, 'trying to create start gives an errror?');
97 |
98 | node.start = top;
99 | node.end = bottom;
100 |
101 | nodes[len] = node;
102 | len++;
103 | }
104 |
105 | assert(nodes.length === matches.length, 'is there a mismatch of things?');
106 | assert(nodes.every((n) => n !== null || n !== undefined, 'idk what happened'));
107 |
108 | return nodes;
109 | }
110 |
111 | export function toRange(nodes: JoinedPoint[]): Range[] {
112 | if (nodes.length === 0) {
113 | return [];
114 | }
115 | const arr: Range[] = new Array(nodes.length).fill(undefined);
116 |
117 | for (let i = 0; i < arr.length; i++) {
118 | const node = nodes[i];
119 | assert(node, 'trying to make range from undefined node');
120 |
121 | assert(node.start.column >= 0, 'cannot be less than 0, received: ' + node.start.column);
122 |
123 | arr[i] = new Range(
124 | new Position(node.start.row, node.start.column),
125 | new Position(node.end.row, node.end.column)
126 | );
127 | }
128 |
129 | //idk also doing another function outside seems too much now
130 | return arr.sort(function (a, b) {
131 | return a.start.isAfter(b.start) ? 1 : -1;
132 | });
133 | }
134 |
--------------------------------------------------------------------------------
/src/parsing/parser.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import path from 'path';
3 | import { Language, default as Parser, default as parser } from 'web-tree-sitter';
4 |
5 | export const Languages = {
6 | 'tree-sitter': {
7 | module: 'tree-sitter',
8 | },
9 | javascript: {
10 | module: 'javascript',
11 | },
12 | javascriptreact: {
13 | module: 'javascript',
14 | },
15 | //need to add parser for this but for now lets do javascript
16 | typescript: {
17 | module: 'typescript',
18 | },
19 |
20 | typescriptreact: {
21 | module: 'tsx',
22 | },
23 | go: {
24 | module: 'go',
25 | },
26 |
27 | json: {
28 | module: 'json',
29 | },
30 | jsonc: {
31 | module: 'json',
32 | },
33 | python: {
34 | module: 'python',
35 | },
36 | cpp: {
37 | module: 'cpp',
38 | },
39 |
40 | csharp: {
41 | module: 'c_sharp',
42 | },
43 | rust: {
44 | module: 'rust',
45 | },
46 | c: {
47 | module: 'c',
48 | },
49 | css: {
50 | module: 'css',
51 | },
52 | yaml: {
53 | module: 'yaml',
54 | },
55 | lua: {
56 | module: 'lua',
57 | },
58 | java: {
59 | module: 'java',
60 | },
61 | toml: {
62 | module: 'toml',
63 | },
64 | php: {
65 | module: 'php',
66 | },
67 | };
68 |
69 | export const SupportedLanguages = Object.keys(Languages);
70 |
71 | export class LanguageParser {
72 | private static hasStarted: boolean = false;
73 | private static initedLanguages: Partial> = {};
74 | static init(): Promise {
75 | if (LanguageParser.hasStarted) {
76 | return Promise.resolve();
77 | }
78 | const wasmPath = LanguageParser.path('tree-sitter');
79 | LanguageParser.hasStarted = true;
80 |
81 | return parser.init({
82 | locateFile: () => wasmPath,
83 | });
84 | }
85 | static path(name: string): string {
86 | return path.join(__dirname, '..', 'parsers', `tree-sitter-${name}.wasm`); // Adjust the path if necessary
87 | }
88 |
89 | static async get(langname: string) {
90 | if (langname in LanguageParser.initedLanguages) {
91 | return LanguageParser.initedLanguages[langname as keyof typeof Languages];
92 | }
93 |
94 | let lang: Language | undefined;
95 | await LanguageParser.init();
96 | try {
97 | const parseName = Languages[langname as keyof typeof Languages];
98 |
99 | assert(parseName, 'could not find parser for ' + langname);
100 | lang = await parser.Language.load(this.path(parseName.module));
101 | } catch (err) {
102 | console.error('could not set language', err);
103 | return undefined;
104 | }
105 | assert(lang, 'could not set language');
106 | const p = new Parser();
107 | p.setLanguage(lang);
108 | LanguageParser.initedLanguages[langname as keyof typeof Languages] = {
109 | language: lang,
110 | module: langname,
111 | parser: p,
112 | };
113 | return LanguageParser.initedLanguages[langname as keyof typeof Languages];
114 | }
115 |
116 | // static async get(langname: string): Promise {
117 | // if (langname in LanguageParser.initedLanguages) {
118 | // return LanguageParser.initedLanguages[langname as keyof typeof Languages];
119 | // }
120 |
121 | // let lang: Language | undefined;
122 | // assert(LanguageParser.hasStarted === true, 'the default language parser has not started');
123 | // // if (!LanguageParser.hasStarted) {
124 | // // await LanguageParser.init()
125 | // // }
126 |
127 | // const parseName = Languages[langname as keyof typeof Languages];
128 |
129 | // assert(parseName, 'could not find parser for ' + langname);
130 | // const modulePath = this.path(parseName.module);
131 |
132 | // if (!(langname in LanguageParser.initedLanguages)) {
133 | // try {
134 | // lang = await parser.Language.load(modulePath);
135 | // } catch (err) {
136 | // // could send an notification alert
137 | // console.error('could not set language:', err);
138 | // }
139 | // } else {
140 | // //@ts-ignore
141 | // lang = LanguageParser.initedLanguages[langname];
142 | // }
143 | // assert(lang, `could not set language ${langname}`);
144 | // const p = new Parser();
145 | // p.setLanguage(lang);
146 | // LanguageParser.initedLanguages[langname as keyof typeof Languages] = {
147 | // language: lang,
148 | // module: langname,
149 | // parser: p,
150 | // };
151 | // return LanguageParser.initedLanguages[langname as keyof typeof Languages];
152 | // }
153 | }
154 |
--------------------------------------------------------------------------------
/src/parsing/position.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import { Position, Range } from 'vscode';
3 | import { QueryMatch } from 'web-tree-sitter';
4 |
5 | export function nextPositionEnd(nodes: Range[], index: Position): Range | undefined {
6 | let closestRange: Range | undefined;
7 |
8 | for (let i = 0; i < nodes.length; i++) {
9 | const range = nodes[i];
10 |
11 | if (index.isAfterOrEqual(range.end)) {
12 | continue;
13 | }
14 |
15 | if (!closestRange || closestRange.end.isAfter(range.end)) {
16 | closestRange = range;
17 | }
18 | }
19 |
20 | return closestRange;
21 | }
22 | export function nextPosition(nodes: Range[], index: Position): Range | undefined {
23 | let closestRange: Range | undefined;
24 |
25 | for (let i = 0; i < nodes.length; i++) {
26 | const range = nodes[i];
27 |
28 | if (index.isAfterOrEqual(range.start)) {
29 | continue;
30 | }
31 |
32 | if (!closestRange || closestRange.start.isAfter(range.start)) {
33 | closestRange = range;
34 | }
35 | }
36 |
37 | return closestRange;
38 | }
39 |
40 | export function previousPositionEnd(nodes: Range[], index: Position): Range | undefined {
41 | let closestRange: Range | undefined;
42 |
43 | for (let i = 0; i < nodes.length; i++) {
44 | const range = nodes[i];
45 |
46 | if (index.isBeforeOrEqual(range.end)) {
47 | continue;
48 | }
49 |
50 | if (!closestRange || closestRange.start.isBefore(range.end)) {
51 | closestRange = range;
52 | }
53 | }
54 |
55 | return closestRange;
56 | }
57 |
58 | export function previousPosition(nodes: Range[], index: Position): Range | undefined {
59 | let closestRange: Range | undefined;
60 |
61 | for (let i = 0; i < nodes.length; i++) {
62 | const range = nodes[i];
63 |
64 | if (index.isBeforeOrEqual(range.start)) {
65 | continue;
66 | }
67 |
68 | if (!closestRange || closestRange.end.isBefore(range.start)) {
69 | closestRange = range;
70 | }
71 | }
72 |
73 | return closestRange;
74 | }
75 | function line(range: Range, pos: Position): boolean {
76 | let truth = false;
77 | if (range.isSingleLine) {
78 | truth = range.start.line === pos.line;
79 | } else {
80 | truth = range.contains(pos);
81 | }
82 |
83 | return truth;
84 | }
85 |
86 | export function closestPos(nodes: Range[], index: Position): Range | undefined {
87 | if (nodes.length === 0) {
88 | return undefined;
89 | }
90 |
91 | let closestRange: Range | undefined;
92 |
93 | for (let i = 0; i < nodes.length; i++) {
94 | const range = nodes[i];
95 |
96 | let startDelta = range.start.isBefore(index);
97 | let endDelta = range.end.isBefore(index);
98 |
99 | if (startDelta && endDelta) {
100 | continue;
101 | }
102 | if (!closestRange) {
103 | closestRange = range;
104 | continue;
105 | }
106 |
107 | const sameLine = line(range, index);
108 |
109 | if (
110 | (closestRange.start.isAfter(range.start) && closestRange.end.isAfter(range.start)) ||
111 | (sameLine && closestRange.contains(range))
112 | ) {
113 | closestRange = range;
114 | }
115 | }
116 |
117 | return closestRange;
118 | }
119 |
120 | // there is a better way, could make a state class with all the current state of the extension
121 | // just trying to prove the idea for now
122 | export function groupMatches(_: Context, matches: QueryMatch[]): QueryMatch[] {
123 | const captureParents = new Map();
124 |
125 | for (const match of matches) {
126 | for (const capture of match.captures) {
127 | const node = capture.node;
128 | assert(node.parent, 'i should worry about this now');
129 |
130 | const parentId = node.parent.id;
131 | const parentNode = captureParents.get(parentId);
132 | if (!parentNode) {
133 | captureParents.set(parentId, match);
134 | continue;
135 | }
136 |
137 | if (!parentNode.captures.some((s) => s.node.id === capture.node.id)) {
138 | parentNode.captures.push(capture);
139 | }
140 | captureParents.set(parentId, parentNode);
141 | }
142 | }
143 |
144 | return Array.from(captureParents.values());
145 | }
146 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.c:
--------------------------------------------------------------------------------
1 | // Function with no return value and no parameters
2 | // Function with no return value and no parameters
3 | // Function with no return value and no parameters
4 | // Function with no return value and no parameters
5 | void functionName(int param1, float param2)
6 | {
7 | // function body
8 | }
9 |
10 | // Function declaration (prototype)
11 | void functionName(int param1, float param2);
12 |
13 | // Function pointer
14 | void (*functionPointer)(int, float);
15 |
16 | // Inline function
17 | inline int functionName(int param1, float param2)
18 | {
19 | // function body
20 | return param1;
21 | }
22 |
23 | functionName();
24 |
25 | // Calling a function with parameters
26 | functionName(param1, param2);
27 |
28 | // Calling a function and using its return value
29 | int result = functionName(param1, param2);
30 |
31 | // Calling a function through a function pointer
32 | functionPointer(param1, param2);
33 |
34 | // Calling a function within another function
35 | void anotherFunction()
36 | {
37 | functionName(param1, param2);
38 | }
39 |
40 | int arr2[5] = {1, 2, 3, 4, 5};
41 |
42 | // Define a struct
43 | struct Point
44 | {
45 | int x;
46 | int y;
47 | };
48 |
49 | // Create a struct variable
50 | struct Point p1;
51 |
52 | typedef struct
53 | {
54 | int x;
55 | int y;
56 | } Point2;
57 |
58 | const result = condition ? valueIfTrue : valueIfFalse;
59 |
60 | // Simple if statement
61 | if (condition)
62 | {
63 | // code to execute if condition is true
64 | }
65 | else
66 | {
67 | result += 1;
68 | }
69 |
70 | if (condition)
71 | result += 1;
72 | else
73 | result -= 1;
74 |
75 | // Standard for loop
76 | for (int i = 0; i < 10; i++)
77 | {
78 | // code to execute
79 | }
80 |
81 | // For loop with multiple variables
82 |
83 | // For loop with no initialization
84 | // Standard for loop
85 | for (int i = 0; i < 10; i++)
86 | {
87 | // code to execute
88 | }
89 |
90 | // here
91 | // For loop with multiple variables
92 | for (int i = 0, j = 10; i < j; i++, j--)
93 | {
94 | // code to execute
95 | }
96 |
97 | // For loop with no initialization
98 | for (int i = 0; i < 10; i++)
99 | {
100 | // code to execute
101 | }
102 |
103 | // For loop with no condition (infinite loop)
104 | for (int i = 0;; i++)
105 | {
106 | // code to execute
107 | if (i >= 10)
108 | break; // exit condition
109 | }
110 |
111 | // For loop with no increment
112 | for (int i = 0; i < 10;)
113 | {
114 | // code to execute
115 | i++; // manual increment
116 | }
117 |
118 | // For loop with all parts omitted (infinite loop)
119 | for (;;)
120 | {
121 | // code to execute
122 | break; // exit condition
123 | }
124 |
125 | // Nested for loop
126 | for (int i = 0; i < 5; i++)
127 | {
128 | for (int j = 0; j < 5; j++)
129 | {
130 | // code to execute
131 | }
132 | }
133 |
134 | // For loop with array
135 | int arr[5] = {1, 2, 3, 4, 5};
136 | for (int i = 0; i < 5; i++)
137 | {
138 | // code to execute with arr[i]
139 | }
140 | for (; i < 10; i++)
141 | {
142 | // code to execute
143 | while (;;)
144 | {
145 | }
146 | }
147 |
148 | // For loop with no condition (infinite loop)
149 | for (int i = 0;; i++)
150 | {
151 | // code to execute
152 | if (i >= 10)
153 | break; // exit condition
154 | }
155 |
156 | // For loop with no increment
157 | for (int i = 0; i < 10;)
158 | {
159 | // code to execute
160 | i++; // manual increment
161 | }
162 |
163 | // For loop with all parts omitted (infinite loop)
164 | for (;;)
165 | {
166 | // code to execute
167 | break; // exit condition
168 | }
169 |
170 | // Nested for loop
171 | for (int i = 0; i < 5; i++)
172 | {
173 | for (int j = 0; j < 5; j++)
174 | {
175 | // code to execute
176 | }
177 | }
178 |
179 | // For loop with array
180 | int arr[5] = ;
181 | for (int i = 0; i < 5; i++)
182 | {
183 | // code to execute with arr[i]
184 | }
185 |
186 | // Standard while loop
187 | int i = 0;
188 | while (i < 10)
189 | {
190 | // code to execute
191 | i++;
192 | }
193 |
194 | // Infinite while loop
195 | while (1)
196 | {
197 | // code to execute
198 | break; // exit condition
199 | }
200 |
201 | // while loop with complex condition
202 | int a = 0, b = 10;
203 | while (a < b && b > 0)
204 | {
205 | // code to execute
206 | a++;
207 | b--;
208 | }
209 |
210 | // Nested while loops
211 | int x = 0;
212 | while (x < 5)
213 | {
214 | int y = 0;
215 | while (y < 5)
216 | {
217 | // code to execute
218 | y++;
219 | }
220 | x++;
221 | }
222 |
223 | // do-while loop (executes at least once)
224 | int j = 0;
225 | do
226 | {
227 | // code to execute
228 | j++;
229 | } while (j < 10);
230 |
231 | #include
232 | #include
233 | #include
234 |
235 | // String as a character array
236 | char str1[] = "Hello, World!";
237 |
238 | str1 = "other hello";
239 |
240 | // // String as a pointer to a constant string
241 | const char *str2 = "Hello, World!";
242 |
243 | // // Dynamic string allocation using malloc
244 | char *str3 = (char *)malloc(50 * sizeof(char));
245 | strcpy(str3, "Hello, World!");
246 |
247 | // Dynamic string allocation using calloc (initializes all elements to zero)
248 | char *str4 = (char *)calloc(50, sizeof(char));
249 | strcpy(str4, "Hello, World!");
250 |
251 | // String using a character array with manual initialization
252 | char str5[13] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'};
253 |
254 | // String using a character array with partial initialization (remaining elements are zero)
255 | char str6[50] = "Hello, World!";
256 |
257 | // String using a pointer and manual memory allocation
258 | char *str7 = (char *)malloc(50 * sizeof(char));
259 | sprintf(str7, "Hello, World!");
260 |
261 | // String using snprintf for safe formatting
262 | char str8[50];
263 | snprintf(str8, sizeof(str8), "Hello, World!");
264 |
265 | // Basic data types
266 | int a = 10;
267 | float b = 3.14;
268 | double c = 3.14159;
269 | char d = 'A';
270 |
271 | // Unsigned types
272 | unsigned int e = 20;
273 | unsigned char f = 'B';
274 |
275 | // Short and long types
276 | short g = 5;
277 | long h = 100000L;
278 | long long i = 10000000000LL;
279 |
280 | // Boolean type (requires stdbool.h)
281 | #include
282 | bool j = true;
283 |
284 | // Pointer variables
285 | int *k = &a;
286 | float *l = &b;
287 |
288 | // Array variables
289 | int m[5] = {1, 2, 3, 4, 5};
290 | char n[6] = "Hello";
291 |
292 | // Struct variables
293 | struct Point
294 | {
295 | int x;
296 | int y;
297 | };
298 | struct Point p1 = {10, 20};
299 |
300 | // Typedef struct variables
301 | typedef struct
302 | {
303 | int x;
304 | int y;
305 | } Point2;
306 | Point2 p2 = {30, 40};
307 |
308 | // Enum variables
309 | enum Color
310 | {
311 | RED,
312 | GREEN,
313 | BLUE
314 | };
315 | enum Color color = RED;
316 |
317 | // Union variables
318 | union Data
319 | {
320 | int intValue;
321 | float floatValue;
322 | char charValue;
323 | };
324 |
325 | union Data data;
326 | data.intValue = 10;
327 |
328 | // Volatile variables
329 | volatile int o = 0;
330 |
331 | // Static variables
332 | static int p = data.intValue;
333 |
334 | extern int q;
335 |
336 | // Single-line comment
337 | int a = 10; // This is a single-line comment
338 |
339 | /*
340 | Multi-line comment
341 | This comment spans multiple lines
342 | */
343 | int b = 20;
344 |
345 | /*
346 | * Multi-line comment with asterisks
347 | * This is another style for multi-line comments
348 | */
349 | int c = 30;
350 |
351 | #include
352 |
353 | int main()
354 | {
355 | int number = 2;
356 |
357 | switch (number)
358 | {
359 | case 1:
360 | printf("Number is 1\n");
361 | break;
362 | case 2:
363 | printf("Number is 2\n");
364 | break;
365 | case 3:
366 | printf("Number is 3\n");
367 | break;
368 | default:
369 | printf("Number is not 1, 2, or 3\n");
370 | break;
371 | }
372 |
373 | return 0;
374 | }
--------------------------------------------------------------------------------
/src/playgrounds/playground.cproj:
--------------------------------------------------------------------------------
1 | // Method 1: Regular method
2 | public void MyMethod()
3 | {
4 | // Method body
5 | }
6 |
7 | // Method 2: Static method
8 | public static void MyStaticMethod()
9 | {
10 | // Method body
11 | }
12 |
13 | // Method 3: Method with parameters
14 | public void MyMethodWithParameters(int param1, string param2)
15 | {
16 | // Method body
17 | }
18 |
19 |
20 | // Method 5: Expression-bodied method
21 | public int MyExpressionBodiedMethod() => 42;
22 |
23 | // Method 6: Local function
24 | void MyLocalFunction()
25 | {
26 | // Method body
27 | }
--------------------------------------------------------------------------------
/src/playgrounds/playground.css:
--------------------------------------------------------------------------------
1 | :root {
2 | --base-size: 16px;
3 | }
4 |
5 | .element {
6 | font-size: calc(var(--base-size) * 2);
7 | transition-duration: 0.5s;
8 | image-resolution: 300dpi;
9 | animation-timing-function: steps(4, end);
10 | transform: rotate(45deg);
11 | width: 50%;
12 | width: calc(100% - 50px);
13 | color: var(--main-color);
14 | content: attr(data-content);
15 | display: none;
16 | position: absolute;
17 | background-image: url('path/to/image.jpg');
18 | color: #ff0000;
19 | background-color: rgb(255, 0, 0);
20 | border-color: rgba(255, 0, 0, 0.5);
21 | color: hsl(0, 100%, 50%);
22 | color: hsla(0, 100%, 50%, 0.5);
23 | width: 100px;
24 | font-size: 1.5em;
25 | margin: 10%;
26 | opacity: 0.75;
27 | z-index: 10;
28 | content: 'Hello, World!';
29 | }
30 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.go:
--------------------------------------------------------------------------------
1 | // this is a comment
2 | // this is a comment
3 | // this is a comment
4 | // this is a comment
5 | // this is a comment
6 |
7 | package main
8 |
9 | import (
10 | "fmt"
11 | )
12 |
13 | const h = 3
14 |
15 | var (
16 | e = 3
17 | fdg int = 3
18 | )
19 |
20 | var f int = 3
21 |
22 | const fl int = 3
23 |
24 | type St struct {
25 | A int
26 | }
27 |
28 | func main() {
29 | c := St{
30 | A: 4,
31 | }
32 |
33 | b, err := func() (int, error) {
34 | return 3, nil
35 | }()
36 |
37 | _ = "this is an string to make testing easier"
38 |
39 | f := func() {
40 |
41 | }
42 | _ = f
43 | fmt.Errorf("err: %v", err)
44 |
45 | fd := retA(5)
46 |
47 | fn := retFunc(func() any {
48 | return 3
49 | })
50 |
51 | _ = b
52 | _ = fn
53 | _ = fd
54 | _ = c
55 | }
56 |
57 | func callOther() string {
58 | fmt.Printf("hellot")
59 | fmt.Printf("hellot")
60 | fmt.Printf("hellot")
61 | fmt.Printf("hellot")
62 | fmt.Printf("hellot")
63 | fmt.Printf("hellot")
64 | return ""
65 | }
66 |
67 | type b struct {
68 | In int
69 | Out string
70 | }
71 |
72 | func (f *b) Call(a int) string {
73 | e = 4
74 |
75 | g := []int{1, 2, 3}
76 | g = []int{1, 2, 3}
77 | _ = g
78 |
79 | if a == 3 {
80 | fmt.Printf("Hello i")
81 | fmt.Printf("alskjdfklsjdf")
82 | fmt.Printf("Hello ii")
83 | fmt.Printf("Hello ")
84 | } else if a == 4 {
85 |
86 | fmt.Printf("Hello there")
87 | fmt.Printf("Hello there")
88 | //this is a cmment
89 | } else {
90 |
91 | //comment
92 | }
93 |
94 | fmt.Printf("%d", a)
95 | for i := range 10 {
96 | fmt.Println(i, i, i)
97 | fmt.Println(i)
98 | fmt.Println(i)
99 | }
100 |
101 | switch a {
102 | case 4:
103 | fmt.Println("he")
104 | break
105 | case 5:
106 | fmt.Println("he")
107 | break
108 |
109 | }
110 |
111 | asdf := retA(4)
112 | _ = asdf
113 | return "this is a full line to help with testing"
114 | }
115 |
116 | func retFunc(f func() any) func() any {
117 | return f
118 | }
119 |
120 | func retA(b int) int {
121 | return 3
122 | }
123 |
124 | func checkParam(s string, c []byte) {
125 | }
126 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.java:
--------------------------------------------------------------------------------
1 | // // 1. Regular method
2 | // public void myFunction() {
3 | // // code
4 | // }
5 |
6 | // //this is a type
7 | // public interface MyInterface {
8 | // void myInterfaceMethod();
9 | // }
10 |
11 | // // 8. Anonymous class method
12 | // Runnable runnable = new Runnable() {
13 | // @Override
14 | // public void run() {
15 | // // code
16 | // // code
17 | // }
18 | // };
19 |
20 | // // 9. Lambda expression (Java 8+)
21 | // Runnable lambda = () -> {
22 | // // code
23 | // // code
24 | // };
25 |
26 | // // 10. Method reference (Java 8+)
27 | // public abstract class MyClass {
28 | // public static void myMethod() {
29 | // // code
30 | // }
31 | // }
32 |
33 | // Runnable methodRef = MyClass::myMethod;
34 |
35 |
36 | // import java.io.IOException;
37 | // import java.util.Optional;
38 |
39 |
40 |
41 |
42 | // if (othercondition) System.out.println();
43 |
44 |
45 |
46 | // if (condition){ System.out.println("hello world"); }
47 |
48 | // else if (condition) {System.out.println("hello world");}
49 | // else {System.out.println("hello world");}
50 |
51 |
52 | // switch (variable) {
53 | // case value1:
54 | // case value2:
55 | // // code to be executed if variable equals value2
56 | // break;
57 | // // you can have any number of case statements
58 | // default:
59 | // // code to be executed if variable doesn't match any case
60 | // }
61 |
62 | // variable = (condition) ? valueIfTrue : valueIfFalse;
63 |
64 | // String multiLineTextBlock = """
65 | // t Hello,
66 | // World!
67 | // This is a multiline string.
68 | // """;
69 |
70 | // multiLineTextBlock = """hello"""
71 |
72 | // char myChar = 'A';
73 |
74 |
75 | // // This is a single-line comment
76 |
77 | // /*
78 | // * This is a multi-line comment
79 | // * that spans multiple lines.
80 | // */
81 |
82 | // /**
83 | // * This is a Javadoc comment.
84 | // * It is used to describe the class, method, or field.
85 | // *
86 | // * @param paramName Description of the parameter
87 | // * @return Description of the return value
88 | // */
89 | // public class Example {
90 | // // Single-line comment inside a method
91 | // public int method() {
92 | // /* Multi-line comment inside a method */
93 | // return 4;
94 |
95 | // }
96 | // }
97 |
98 |
99 | // for (int i = 0; i < 5; i++) {
100 | // System.out.println(i);
101 | // }
102 |
103 | // int[] arr = {1, 2, 3, 4, 5};
104 | // for (int num : arr) {
105 | // System.out.println(num);
106 | // }
107 |
108 | // int i = 0;
109 | // while (i < 5) {
110 | // System.out.println(i);
111 | // i++;
112 | // }
113 |
114 | // Example ex = new Example();
115 |
116 | // int e = ex.method();
117 |
118 | // int i = 0;
119 | // do {
120 | // System.out.println(i);
121 | // i++;
122 | // } while (i < 5);
123 |
124 |
125 | // import java.util.*;
126 |
127 | // import java.util.Arrays;
128 |
129 | // int[] arr = {1, 2, 3, 4, 5};
130 |
131 |
132 | // Arrays.stream(arr) .forEach(System.out::println);
133 |
134 |
135 | // MyClass obj = new MyClass() {
136 | // void display() {
137 | // System.out.println("Anonymous class object");
138 | // }
139 | // };
140 |
141 | // class MyClassOter implements Serializable {
142 | // transient int transientVar = 100; // Transient variable
143 | // }
144 |
145 |
146 | // public class Main {
147 | // // public static int func(IntSupplier fn) {
148 | // // return fn.get();
149 | // // }
150 |
151 | // public static void main(String[] args) {
152 | // // Using a lambda expression
153 | // IntSupplier lambda = () -> 42;
154 |
155 | // int d = func(lambda);
156 |
157 |
158 | // System.out.println("Result from lambda: " + func(lambda)); // Output: Result from lambda: 42
159 |
160 |
161 | // // Using a method reference
162 | // IntSupplier methodRef = Main::exampleFunction;
163 | // // System.out.println("Result from method reference: " + func(methodRef)); // Output: Result from method reference: 100
164 |
165 | // // Using an anonymous class
166 | // IntSupplier anonymousClass = new IntSupplier() {
167 | // @Override
168 | // public int get() {
169 | // return 84;
170 | // }
171 | // };
172 | // // System.out.println("Result from anonymous class: " + func(anonymousClass)); // Output: Result from anonymous class: 84
173 | // }
174 |
175 | // public static int exampleFunction() {
176 | // try {
177 | // } catch(err Exception) {
178 | // }
179 |
180 | // return 100;
181 | // }
182 | // }
183 |
184 | public class Count {
185 | public boolean has(int[] haystack, int needle, int count) {
186 | if (count >= haystack.length ){
187 | return false;
188 | } else if (haystack[count] === needle) {
189 | return true
190 | } else {
191 | return has(haystack, needle, count++);
192 | }
193 | }
194 |
195 | public int count(int[] haystack, int needle, int count ) {
196 | if (!has(haystack, needle, count) || count >= haystack.length) {
197 | return 0;
198 | }
199 | int c= 0;
200 | if (array[count] == needle) {
201 | c++;
202 | }
203 | c += count(haystack, needle, count);
204 | return c;
205 | }
206 |
207 | }
208 | public static void main (String[] args) {
209 | int[] haystack = {2,3,5,6,9,7,8,8,9};
210 | Count co = new Count();
211 | System.out.println(co.count(haystack,5,0));
212 | }
213 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.js:
--------------------------------------------------------------------------------
1 | export function a(b, c) {
2 | console.log(b);
3 | function d() {
4 | console.log(b);
5 | function e() {
6 | console.log(c);
7 | }
8 | }
9 | console.log('this');
10 | }
11 |
12 | export const d = function () {};
13 |
14 | let g = {
15 | db: 3,
16 | };
17 |
18 | g = {
19 | db: 5,
20 | };
21 |
22 | function b() {
23 | console.log('');
24 | }
25 |
26 | function c() {}
27 |
28 | a(3, 'asdfadf');
29 |
30 | export class M {
31 | static asopidfj = 34;
32 | }
33 |
34 | import assert from 'assert';
35 | import * as vscode from 'vscode';
36 | import { closestPos, nextPosition, previousPosition } from '../parsing/position';
37 | import { getConfig } from '../config';
38 |
39 | const strRegex = /['"`]/;
40 |
41 | export function withInnerStringModifier(command) {
42 | const next = command.end;
43 |
44 | command.end = function (context, range) {
45 | if (!range) {
46 | return;
47 | }
48 | const start = range.start;
49 | const end = range.end;
50 | const line = context.editor.getRange(start.line, start.character, end.line, end.character);
51 |
52 | if (line.match(strRegex)) {
53 | range = new vscode.Range(
54 | new vscode.Position(range.start.line, range.start.character + 1),
55 | new vscode.Position(range.end.line, range.end.character - 1)
56 | );
57 | }
58 |
59 | assert(context.editor, 'editor is undefined');
60 | assert(
61 | typeof context.editor.selectRange === 'function',
62 | 'range selection is not a function, received:' + typeof context.editor.selectRange
63 | );
64 |
65 | next(context, range);
66 | };
67 | return command;
68 | }
69 | export function withMatchFunc(command, func) {
70 | command.onMatch = func;
71 | return command;
72 | }
73 |
74 | export function createSelectNext(scope, name) {
75 | return {
76 | name,
77 | scope,
78 | direction: 'next',
79 | selectors: {},
80 | currentSelector: undefined,
81 | action: 'select',
82 | pos: closestPos,
83 | end: (ctx, range) => {
84 | assert(ctx.editor && typeof ctx.editor.selectRange === 'function', 'is this running another way');
85 | ctx.editor.selectRange(ctx, range);
86 | },
87 | };
88 | }
89 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.json:
--------------------------------------------------------------------------------
1 | {
2 | "outerarray": ["one", "two"],
3 | "innerarray": ["one", "two"],
4 | "outerstr": "string",
5 | "obj": {
6 | "outerarray": ["one", "two"],
7 | "innerarray": ["one", "two"],
8 | "outerstr": "string"
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.jsonc:
--------------------------------------------------------------------------------
1 | {
2 | "outerarray": ["one", "two"],
3 | "innerarray": ["one", "two"],
4 | "outerstr": "string",
5 | "obj": {
6 | "outerarray": ["one", "two"],
7 | "innerarray": ["one", "two"],
8 | "outerstr": "string"
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.jsx:
--------------------------------------------------------------------------------
1 | const b = 3;
2 |
3 | const s = 'ao;sidjfaoijdf';
4 |
5 | (() => {})();
6 |
7 | console.log('asdofjasodifj');
8 |
9 | function a() {}
10 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.lua:
--------------------------------------------------------------------------------
1 |
2 | -- Function declaration using the function keyword
3 | -- Function declaration using the function keyword
4 | -- Function declaration using the function keyword
5 | function myFunction()
6 | print("Hello, World!")
7 | end
8 |
9 |
10 | -- Function declaration with local scope
11 | local function myLocalFunction()
12 | print("Hello, Local World!")
13 | end
14 |
15 | -- Anonymous function assigned to a variable
16 | myanonymousfunction = function()
17 | print("hello, anonymous world!")
18 | end
19 |
20 | -- Function as a table field
21 | myTable = {
22 | myTableFunction = function()
23 | print("Hello, Table World!")
24 | end
25 | }
26 |
27 | myTable.myTableFunction = function()
28 |
29 | end
30 | -- Function with parameterlocal
31 | function myFunctionWithParams(param1, param2)
32 | print(param1, param2)
33 | end
34 |
35 | -- Function with return value
36 | function myFunctionWithReturn()
37 | return "Hello, Return World!"
38 | end
39 |
40 | function MyClass(value)
41 | local self = {}
42 | self = {}
43 | local privateValue = value
44 |
45 | function self:getValue()
46 | return privateValue
47 | end
48 |
49 | return self
50 | end
51 |
52 | local condition = true
53 |
54 |
55 |
56 | local inte = 3
57 |
58 | if inte ==1 then
59 | -- hello
60 | print("hello there")
61 | else
62 | print("hello there")
63 | -- hello
64 | end
65 |
66 |
67 | if inte == 1 then
68 | print("hello")
69 |
70 | elseif inte == 2 then
71 | print("bye")
72 | end
73 |
74 | while condition do
75 | inte = 2
76 | inte = 4
77 | -- code to execute as long as condition is true
78 | end
79 |
80 | repeat
81 |
82 | inte = 2
83 | inte = 4
84 | -- code to execute at least once and then repeatedly until condition is true
85 | until condition
86 |
87 | for i = 1, 10, 1 do
88 | print(i)
89 | end
90 |
91 | for key, value in pairs(table) do
92 | -- code to execute for each key-value pair in the table
93 | end
94 |
95 | local i = 1
96 | while i <= 10 do
97 | print(i)
98 | i = i + 1
99 | end
100 |
101 |
102 | local x = 10
103 |
104 | local yy = 20
105 |
106 | local key = function ()
107 | print('content')
108 | end
109 |
110 | local t = {
111 |
112 | b = function ()
113 | print("hello worlld")
114 | end
115 | }
116 |
117 | local function add(a, b)
118 | return a + b
119 | end
120 |
121 | local result = add(5, 7)
122 | print(result) -- Output: 12
123 |
124 | local array = {1, 2, 3, 4, 5}
125 | array = {1, 2, 3, 4, 5}
126 | local array2 = {
127 | thing1 = 'other'
128 | }
129 | array2 = {
130 | thing1 = 'other'
131 | }
132 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.php:
--------------------------------------------------------------------------------
1 |
12 |
16 | //function calls
17 | ?>
18 |
21 | greet($name, $age);
22 |
23 | ?>
24 |
25 |
49 |
50 |
69 |
70 | = 18) {
74 | // echo "Adult";
75 | // }
76 |
77 | if ($age >= 18) {
78 | echo "Adult";
79 | } else
80 | echo "Minor";
81 |
82 | ?>
83 | = 18) ? "Adult" : "Minort";
85 | ?>
86 | = 18):
104 | echo "Adult";
105 | else:
106 | echo "Minor";
107 | endif;
108 |
109 | $username = $inputUsername ?: "Guest";
110 |
111 | ?>
112 | = 90 => 'A',
116 | $score >= 75 => 'B',
117 | $score >= 60 => 'C',
118 | default => 'F',
119 | };
120 |
121 | ?>
122 |
123 |
128 |
135 |
141 |
148 | "Hello, $name";
150 | ?>
151 |
166 |
167 |
172 | $fruit) {
181 | echo "$index: $fruit";
182 | }
183 |
184 |
185 | ?>
186 |
194 |
195 |
203 |
204 | "Rodrigo", "age" => 30]; ?>
205 |
206 |
214 |
220 |
221 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.py:
--------------------------------------------------------------------------------
1 | def f(param1, two):
2 | print("second")
3 |
4 | def second():
5 | print("second")
6 |
7 |
8 | add = lambda x, y: x + y
9 |
10 |
11 | class MyClass:
12 | def my_method(self):
13 | print("This is a method inside a class.")
14 |
15 |
16 | class OtherClass:
17 | @staticmethod
18 | def my_static_method():
19 | print("This is a static method.")
20 |
21 |
22 | class MyClass2:
23 | @classmethod
24 | def my_class_method(cls):
25 | print("This is a class method.")
26 |
27 |
28 | name = "Josh"
29 |
30 | def my_generator():
31 | yield 1
32 |
33 | yield c2
34 | yield 3
35 |
36 |
37 | async def my_async_function():
38 | print("Async function completed")
39 |
40 |
41 | i = 1
42 | i = 2
43 |
44 |
45 | # htis is a comment
46 | # this is anoterh
47 |
48 | """
49 | this is a docstring for python
50 | """
51 |
52 |
53 | str = "3"
54 |
55 |
56 | fruits = ["on1", "tw2", "thr3", "fou4"]
57 |
58 | count = 0
59 |
60 | while count < 5:
61 | if count == 3:
62 | print("the count is 4")
63 | print("the count is 4")
64 | elif count == 4:
65 | print("the count is 4")
66 | else:
67 | print("the count is 4")
68 | count += 1
69 |
70 |
71 | my_dict = {"a": 1, "b": 2, "c": 3}
72 |
73 |
74 | result = "x is less than 5" if my_dict["c"] < 5 else "x is 5 or greater"
75 | x = 4
76 |
77 | result = {"x is less than 5"} if x < 5 else {"x is 5 or greater"}
78 |
79 |
80 | my_dict.a = 3
81 | for key, value in my_dict.items():
82 | print(f"Key: {key}, Value: {value}")
83 |
84 | squares = [x**2 for x in range(10)]
85 |
86 |
87 | arrr = [1, 2, 3, 4]
88 |
89 | d = {"name": "hogh"}
90 |
91 |
92 | def func(fn):
93 | return fn()
94 |
95 |
96 | # Example function to be passed as an argument
97 | def example_function():
98 | return 42
99 |
100 |
101 | # Using a lambda function
102 | lambda_function = lambda: 100
103 |
104 | # Using the func function with example_function
105 | result = func(example_function)
106 | print(
107 | "Result from example_function:", result
108 | ) # Output: Result from example_function: 42
109 |
110 | # Using the func function with a lambda function
111 | lambda_result = func(lambda_function)
112 | print(
113 | "Result from lambda_function:", lambda_result
114 | ) # Output: Result from lambda_function: 100
115 |
116 | # Using the func function with an anonymous lambda function directly
117 | anonymous_lambda_result = func(lambda: 84)
118 | print(
119 | "Result from anonymous lambda:", anonymous_lambda_result
120 | ) # Output: Result from anonymous lambda: 84
121 |
122 | # Complex nested syntax example
123 | result = (
124 | lambda x: (
125 | (lambda a, b: a(b))(
126 | lambda y: [z for z in y if z % 2 == 0],
127 | (
128 | lambda q: sorted(
129 | [w**2 for w in q if w > 10], key=lambda n: -1 * (n % 5)
130 | )
131 | )(list(range(x))),
132 | )
133 | )
134 | )(50)
135 |
136 | # A highly nested data structure with mixed types
137 | data_structure = {
138 | "key1": [
139 | [1, 2, {"inner_key": [100, 200, 300]}],
140 | [4, 5, 6],
141 | ],
142 | "key2": {
143 | "subkey1": [{"id": idx, "value": (lambda x: x**2)(idx)} for idx in range(5)],
144 | "subkey2": tuple((lambda y: y + (lambda z: z / 2)(y))(i) for i in range(1, 4)),
145 | },
146 | }
147 |
148 | # Obscure generator chained into a dictionary comprehension
149 | gen_chain = {
150 | f"item_{i}": sum(y for y in (x**2 for x in range(i * 2)) if y % 3 == 0)
151 | for i in range(1, 5)
152 | }
153 |
154 |
155 | def perform_extremely_complex_operations_no_comprehensions(input_data):
156 | data = []
157 | sorted_input = sorted(set(input_data), key=lambda x: -x)
158 | for item in sorted_input:
159 | transformed = []
160 | for k, v in enumerate([x**2 for x in range(item) if x % 3 == 0]):
161 | value = 0
162 | transformed.append({"key": k, "value": value})
163 |
164 | for i in range(v):
165 | if i % 2 == 0 and len(str(i)) % 2 == 0:
166 | value += i**2
167 | data.append({"original": item, "transformed": transformed})
168 |
169 | final_result = []
170 | for data in data:
171 | if "transformed" in data:
172 | if isinstance(data["transformed"], list):
173 | for entry in data["transformed"]:
174 | if entry["value"] % 5 == 0:
175 | extra_value = entry["value"]
176 | if extra_value % 7 != 0:
177 | extra_value *= 2
178 | final_result.append(
179 | {
180 | "key": entry["key"],
181 | "value": entry["value"] ** 0.5,
182 | "original": data["original"],
183 | "extra": extra_value,
184 | }
185 | )
186 |
187 | summary = {}
188 | for i in range(len(input_data)):
189 | values = []
190 | for entry in final_result:
191 | if entry["key"] == i:
192 | values.append(entry["value"])
193 | if isinstance(values, list):
194 | if values:
195 | summary[str(i)] = values[0] + sum(values[1:])
196 | else:
197 | summary[str(i)] = -1
198 | else:
199 | summary[str(i)] = -1
200 |
201 | nested_transformations = []
202 | for entry in final_result:
203 | extra = entry["extra"]
204 | if isinstance(extra, int):
205 | range_list = list(range(extra))
206 | else:
207 | range_list = [1, 2, 3]
208 | for v in range_list:
209 | if v % 2 == 0:
210 | nested_transformations.append(v**2)
211 | else:
212 | nested_transformations.append(v**3)
213 |
214 | return {
215 | "processed_data": data,
216 | "final_result": final_result,
217 | "summary": summary,
218 | "nested_transformations": nested_transformations,
219 | }
220 |
221 | def transform( itea):
222 | transformed = []
223 | for k, v in enumerate([x**2 for x in range(item) if x % 3 == 0]):
224 | value = 0
225 |
226 | transformed.append({"key": k, "value": value})
227 |
228 | for i in range(v):
229 | if i % 2 == 0 and len(str(i)) % 2 == 0:
230 | value += i**2
231 | return {"original": item, "transformed": transformed}
232 |
233 |
234 |
235 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.toml:
--------------------------------------------------------------------------------
1 | names = ["Alice", "Bob", "Charlie"]
2 |
3 | basic_string = "Hello, World!"
4 |
5 | multiline_basic_string = """This is a
6 | multiline string."""
7 |
8 | literal_string = 'This is a literal string with special characters like \n and \t but they are not escaped.'
9 |
10 | multiline_literal_string = '''This is a
11 | multiline literal string.'''
12 |
13 | escaped_string = "This string contains a newline character:\nAnd a tab character:\tTab"
14 |
15 |
16 | [person]
17 | name = "Alice"
18 | age = 30
19 | is_student = false
20 |
21 |
22 | person = { name = "Alice", age = 30, is_student = false }
23 |
24 |
25 |
26 | othername= "Alice"
27 | greeting = 'Hello, World!'
28 | multiline_string = """This is a
29 | multiline string."""
30 | multiline_literal_string = '''This is a
31 | multiline literal string.'''
32 | ageo = 30
33 | price = 19.99
34 | date = 2024-10-20
35 | time = 13:45:30
36 | iois_student = false
37 |
38 | datetime = 2024-10-20T13:45:30
39 | datetime_offset = 2024-10-20T13:45:30Z
40 | numbers = [1, 2, 3, 4, 5]
41 |
42 | # This is a multi-line comment
43 | # that explains the following
44 | # configuration settings.
45 |
--------------------------------------------------------------------------------
/src/playgrounds/playground.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const b = 3
4 |
5 | function c(param: object) {
6 | }
7 |
8 | export const Function = (other: object) => {
9 | return (
10 |
11 | {
12 | ((param) => {
13 | return 1
14 | })({
15 | s: () => {
16 | }
17 |
18 | }) === 1 ? (
) : (
)
19 |
20 |
21 | }
22 | {1 === Math.random() ? (
23 |
24 | ) : (
25 | <>>
26 | )}
27 |
28 | );
29 | };
--------------------------------------------------------------------------------
/src/playgrounds/playground.yaml:
--------------------------------------------------------------------------------
1 | # Basic strin
2 | name: 'John Doe'
3 |
4 | # Multi-line string
5 | description: |
6 | This is a multi-line string.
7 | It can span multiple lines.
8 |
9 | # Number
10 | age: 30
11 |
12 | # Boolean
13 | is_active: true
14 |
15 | # Null value
16 | nickname: null
17 |
18 | # Array
19 | skills:
20 | - Python
21 | - JavaScript
22 | - DevOps
23 |
24 | # Object
25 | address:
26 | street: '123 Main St'
27 | city: 'Anytown'
28 | state: 'CA'
29 | zip: '12345'
30 |
31 | # Nested objects
32 | company:
33 | name: 'Tech Corp'
34 | location:
35 | city: 'San Francisco'
36 | state: 'CA'
37 |
38 | # Array of objects
39 | projects:
40 | - name: 'Project Alpha'
41 | status: 'Completed'
42 | - name: 'Project Beta'
43 | status: 'In Progress'
44 |
45 | # Variables (using anchors and aliases)
46 | defaults: &dede
47 | country: 'USA'
48 | language: 'English'
49 |
50 | # Variables (using anchors and aliases)
51 | user1:
52 | <<: *defaults
53 | name: 'Alice'
54 |
55 | user2:
56 | <<: *defaults
57 | name: 'Bob'
58 | language: 'Spanish'
59 |
60 | b: "dou"
61 |
62 | # Complex keys
63 | !!str 'complex key': 'value'
64 |
65 | # Timestamps
66 | created_at: 2023-10-01T12:00:00Z
67 |
68 |
--------------------------------------------------------------------------------
/src/state/updates/new_keybindings.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import { getContext } from '../../context/context';
3 | import { EditorScope, ProcessFlow } from '../../editor/editorContext';
4 |
5 | export function showUpdateKeybindingsWelcomeScreen(): void {
6 | try {
7 | const ctx = getContext().extensionContext;
8 | if (!ctx) {
9 | return;
10 | }
11 | const state = ctx.getState('showed_new_positionals_and_migrations', EditorScope.global);
12 |
13 | if (state === ProcessFlow.EXECUTED) {
14 | return;
15 | }
16 |
17 | ctx.updateState('showed_new_positionals_and_migrations', ProcessFlow.EXECUTED, EditorScope.global).then(
18 | () => {
19 | const panel = vscode.window.createWebviewPanel(
20 | 'Version 0.2.0 is Live!',
21 | 'Version 0.2.0 is Live!',
22 | vscode.ViewColumn.One,
23 | {}
24 | );
25 |
26 | panel.webview.html = getHTML();
27 | }
28 | );
29 | } catch (err) {
30 | console.error(err);
31 | }
32 | }
33 |
34 | function getHTML(): string {
35 | return `
36 |
37 |
38 | Welcome
39 |
40 |
41 | Version 0.2.0 is Live
42 |
43 |
44 | This is a big one 🎊🎊🎊! We added a new motion specification, new way to configure and generate your keybindings and migration to the new model!
45 |
46 |
47 | New motion specification: Position
48 |
49 | This was a big thing that was missing in the initial release. A way for you to explicitelly go to the end of an object, either forwards or backwards.
50 |
51 | For now only the go to motion has this hability, but if theres a community want for this, we can add it to all the other ones.
52 |
53 | To migrate your old configuration to the new configuration, either accept the migration prompt, or execute the command vscode-textobjects.migrateVimPositionals.
54 |
55 | A New way to configure and generate your keybindings
56 |
57 | There was a lot to improve in the keybinds and configuration department. If you wanted to change a motion key you had to update all the motions to update the one keystroke. Now you can update your settings with commands!
58 |
59 | to change a specific key, use the vscode-textobjects.keybindings. Then if you are not using the vim extension, use the command Generate Keybindings. It will open a new window with all your new keybindings for you to paste in your keyboard json config. To see that configuration, press CTRL+SHIFT+P and type Preferences: Open Keyboard shortcuts (JSON).
60 |
61 | if you are using the Vim extension. Alter your keys in vscode-textobjects.vimKeybindings, then use the command Generate Vim Keybinds. It will now show a window with your new keybindings that you can paste in your vim settings
62 |
63 | Contribute
64 |
65 | If you enjoy how the extension has been coming along, please consider contributing! I love developing tools and this helps me a ton!
66 |
67 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 | `;
77 | }
78 |
--------------------------------------------------------------------------------
/src/types/global.d.ts:
--------------------------------------------------------------------------------
1 | import { Position, Range } from 'vscode';
2 | import Parser, { Language, QueryMatch } from 'web-tree-sitter';
3 | import { Editor } from '../editor/editor';
4 | import { Languages } from '../parsing/parser';
5 | import { EditorContext } from '../editor/editorContext';
6 |
7 | export {};
8 |
9 | declare global {
10 | export type SupportedLanguages = keyof typeof Languages;
11 | export type CommandNames =
12 | | 'function'
13 | | 'comment'
14 | | 'type'
15 | | 'call'
16 | | 'parameters'
17 | | 'loop'
18 | | 'conditional'
19 | | 'variable'
20 | | 'rhs'
21 | | 'lhs'
22 | | 'class'
23 | | 'array'
24 | | 'object'
25 | | 'node'
26 | | 'string';
27 |
28 | export type CommandScope = 'inner' | 'outer';
29 | export type CommandDirection = 'next' | 'previous';
30 | export type CommandAction = 'select' | 'goTo' | 'delete' | 'yank' | 'change';
31 |
32 | export type Context = {
33 | editor: Editor;
34 | parsing: {
35 | parser: Parsing | undefined;
36 | };
37 | command: Command | null;
38 | extensionContext: EditorContext | null;
39 | };
40 |
41 | export type Parsing = {
42 | module: string;
43 | language: Language;
44 | parser: Parser;
45 | };
46 | export type CommandPosition = 'start' | 'end';
47 |
48 | export type Command = {
49 | selectors: Partial>;
50 | currentSelector: Selector | undefined;
51 | name: CommandNames;
52 | scope: CommandScope;
53 | direction: CommandDirection;
54 | position: CommandPosition;
55 | action: CommandAction;
56 | onMatch?: OnMatchFunc;
57 | end: OnFinish;
58 | pos: GetPositionFunc;
59 | };
60 |
61 | export interface Selector {
62 | language: SupportedLanguages;
63 | query: string;
64 | }
65 |
66 | export type OnMatchFunc = (ctx: Context, matches: QueryMatch[]) => QueryMatch[];
67 | export type GetPositionFunc = (points: Range[], index: Position) => Range | undefined;
68 |
69 | export type OnFinish = (Ctx: Context, range: Range | undefined) => unknown;
70 |
71 | export type JoinedPoint = {
72 | start: Parser.Point;
73 | end: Parser.Point;
74 | };
75 |
76 | export type EditorCommand = {
77 | command: string;
78 | title: string;
79 | when: string;
80 | f: () => void;
81 | };
82 |
83 | type KeyboardConfig = {
84 | array: string;
85 | call: string;
86 | class: string;
87 | comment: string;
88 | conditional: string;
89 | function: string;
90 | lhs: string;
91 | loop: string;
92 | node: string;
93 | object: string;
94 | rhs: string;
95 | parameters: string;
96 | string: string;
97 | type: string;
98 | variable: string;
99 | };
100 |
101 | type VimMotionConfig = {
102 | select: string;
103 | change: string;
104 | delete: string;
105 | yank: string;
106 | };
107 |
108 | type ScopeConfig = {
109 | inner: string;
110 | outer: string;
111 | };
112 |
113 | type VimKeyboardConfig = {
114 | 'go to next start': string;
115 | 'go to next end': string;
116 | 'go to previous start': string;
117 | 'go to previous end': string;
118 | } & KeyboardConfig &
119 | VimMotionConfig &
120 | ScopeConfig;
121 |
122 | type KeyboardMotionConfig = {
123 | 'go to start': 'f';
124 | 'go to end': 't';
125 | 'select inner': 'n';
126 | 'select outer': 's';
127 | 'delete outer': 'd';
128 | 'delete inner': 'x';
129 | 'yank outer': 'y';
130 | };
131 |
132 | type DefaultKeyboardConfig = KeyboardMotionConfig & KeyboardConfig;
133 |
134 | export type KeyboardKeybind = {
135 | command: string;
136 | when: string;
137 | mac?: string;
138 | key?: string;
139 | };
140 |
141 | export type VimKeybinding = { before: string[]; commands: string[] };
142 | }
143 |
--------------------------------------------------------------------------------
/src/utils.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import * as vscode from 'vscode';
3 | import { getContext } from './context/context';
4 |
5 | export function visualize(start: vscode.Range): void {
6 | assert(start, 'start needs to be defined');
7 |
8 | const ctx = getContext();
9 | assert(ctx, 'context is not defined');
10 |
11 | const editor = ctx.editor.getEditor();
12 | assert(editor, 'editor is not present');
13 |
14 | editor.revealRange(start);
15 | editor.selection = new vscode.Selection(start.start, start.end); // Move cursor to that position
16 | }
17 |
18 | export class NodePool {
19 | size: number;
20 | private nodes: T[];
21 | private createFunc: () => T;
22 | constructor(createFunc: () => T) {
23 | this.nodes = new Array();
24 | this.size = 0;
25 | this.createFunc = createFunc;
26 | }
27 | get(): T {
28 | const node = this.nodes.pop();
29 |
30 | if (!node) {
31 | this.size++;
32 | return this.createFunc();
33 | }
34 | this.size--;
35 | return node;
36 | }
37 | retrieveAll(point: T[]) {
38 | while (point.length > 0) {
39 | this.nodes[this.size] = point.pop()!;
40 | this.size++;
41 | }
42 | }
43 | retrieve(point: T) {
44 | this.nodes[this.size] = point;
45 | this.size++;
46 | }
47 | }
48 |
49 | export function closerToZero(a: number, b: number) {
50 | if (Math.abs(a) < Math.abs(b)) {
51 | return a;
52 | } else if (Math.abs(b) < Math.abs(a)) {
53 | return b;
54 | } else {
55 | return a; // or return b, since they are equally close to zero
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "Node16",
4 | "target": "ES2022",
5 | "lib": ["ES2022"],
6 | "sourceMap": true,
7 | "rootDir": "src",
8 | "strict": true /* enable all strict type-checking options */,
9 | // "noEmit": true,
10 | "alwaysStrict": true,
11 |
12 | "noImplicitReturns": true,
13 | "noUnusedParameters": true /* Report errors on unused parameters. */
14 | /* Additional Checks */
15 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
16 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
17 | }
18 | }
19 |
--------------------------------------------------------------------------------