├── .editorconfig
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ └── lint.yml
├── .luacheckrc
├── .stylua.toml
├── LICENSE
├── README.md
├── doc
└── nvim-treesitter-refactor.txt
├── lua
├── nvim-treesitter-refactor.lua
└── nvim-treesitter-refactor
│ ├── highlight_current_scope.lua
│ ├── highlight_definitions.lua
│ ├── navigation.lua
│ └── smart_rename.lua
├── plugin
└── nvim-treesitter-refactor.vim
└── scripts
└── style-check.sh
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 2
6 | tab_width = 8
7 | end_of_line = lf
8 | insert_final_newline = true
9 | charset = utf-8
10 |
11 | [{Makefile,**/Makefile,runtime/doc/*.txt}]
12 | indent_style = tab
13 | indent_size = 8
14 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Output of `:checkhealth nvim_treesitter`**
24 |
25 |
26 |
27 |
28 | Paste the output here
29 |
30 |
31 |
32 |
33 | **Output of `nvim --version`**
34 | ```
35 | Paste your output here
36 | ```
37 |
38 | **Additional context**
39 | Add any other context about the problem here.
40 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: Linting and style checking
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | luacheck:
7 | name: Luacheck
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v1
11 | - name: Prepare
12 | run: |
13 | sudo apt-get update
14 | sudo add-apt-repository universe
15 | sudo apt install luarocks -y
16 | sudo luarocks install luacheck
17 | - name: Run Luacheck
18 | run: bash scripts/style-check.sh
19 |
20 | stylua:
21 | name: StyLua
22 | runs-on: ubuntu-latest
23 | steps:
24 | - uses: actions/checkout@v2
25 | - name: Lint with stylua
26 | uses: JohnnyMorganz/stylua-action@v2
27 | with:
28 | token: ${{ secrets.GITHUB_TOKEN }}
29 | args: --check .
30 |
--------------------------------------------------------------------------------
/.luacheckrc:
--------------------------------------------------------------------------------
1 | -- Glorious list of warnings: https://luacheck.readthedocs.io/en/stable/warnings.html
2 | ignore = {
3 | "212", -- Unused argument, In the case of callback function, _arg_name is easier to understand than _, so this option is set to off.
4 | "411", -- Redefining a local variable.
5 | "412", -- Redefining an argument.
6 | "422", -- Shadowing an argument
7 | "122" -- Indirectly setting a readonly global
8 | }
9 |
10 | -- Global objects defined by the C code
11 | read_globals = {
12 | "vim",
13 | }
14 |
--------------------------------------------------------------------------------
/.stylua.toml:
--------------------------------------------------------------------------------
1 | indent_type = "Spaces"
2 | indent_width = 2
3 | no_call_parentheses = true
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # nvim-treesitter-refactor
2 |
3 | Refactor modules for [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter)
4 |
5 | ## Installation
6 |
7 | You can install `nvim-treesitter-refactor` with your favorite package manager,
8 | or using the default `pack` feature of Neovim!
9 |
10 | Note: This plugin requires [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter) installed.
11 |
12 | ### Using a package manager
13 |
14 | If you are using [vim-plug](https://github.com/junegunn/vim-plug), put this in your `init.vim` file:
15 |
16 | ```vim
17 | Plug 'nvim-treesitter/nvim-treesitter-refactor'
18 | ```
19 |
20 | ## Highlight definitions
21 |
22 | Highlights definition and usages of the current symbol under the cursor.
23 |
24 | ```lua
25 | lua <
6 | Yazdani Kiyan
7 | Vigouroux Thomas
8 | https://github.com/nvim-treesitter/nvim-treesitter-refactor/graphs/contributors
9 |
10 | Type |gO| to see the table of contents.
11 |
12 | ==============================================================================
13 | QUICK START *nvim-treesitter-refactor*
14 |
15 | See |nvim-treesitter-modules| on how to configure modules.
16 |
17 | ------------------------------------------------------------------------------
18 | MODULES *nvim-treesitter-refactor-modules*
19 |
20 | *nvim-treesitter-refactor-highlight-definitions*
21 | Highlight definitions~
22 |
23 | Highlights definition and usages of the current symbol under the cursor.
24 |
25 | Query files: `locals.scm`.
26 | Supported options:
27 | - enable: `true` or `false`.
28 | - disable: list of languages.
29 | - clear_on_cursor_move: `true` or `false` if highlights should be cleared
30 | when the cursor is moved. If your 'updatetime' is around `100`
31 | you can set this to false to have a less laggy experience.
32 |
33 | >
34 | lua <
58 | lua <
81 | lua <` .
113 | No default mapping
114 | - list_definitions: list all definitions from the current file.
115 | Defaults to `gnD`.
116 | - list_definitions_toc: list all definitions from the current file like a
117 | table of contents (similar to the one you see when pressing |gO| in help files).
118 | Defaults to `gO`.
119 | - goto_next_usage: go to next usage of identifier under the cursor.
120 | Defaults to ``.
121 | - goto_previous_usage: go to previous usage of identifier.
122 | Defaults to ``.
123 |
124 | >
125 | lua < lua require'nvim-treesitter-refactor.highlight_current_scope'.highlight_current_scope(%d)]],
38 | bufnr,
39 | bufnr
40 | )
41 | )
42 | cmd(
43 | string.format(
44 | [[autocmd BufLeave lua require'nvim-treesitter-refactor.highlight_current_scope'.clear_highlights(%d)]],
45 | bufnr,
46 | bufnr
47 | )
48 | )
49 | -- luacheck: pop
50 | cmd "augroup END"
51 | end
52 |
53 | function M.detach(bufnr)
54 | M.clear_highlights(bufnr)
55 | cmd(string.format("autocmd! NvimTreesitterCurrentScope_%d CursorMoved", bufnr))
56 | cmd(string.format("autocmd! NvimTreesitterCurrentScope_%d BufLeave", bufnr))
57 | end
58 |
59 | return M
60 |
--------------------------------------------------------------------------------
/lua/nvim-treesitter-refactor/highlight_definitions.lua:
--------------------------------------------------------------------------------
1 | -- This module highlights reference usages and the corresponding
2 | -- definition on cursor hold.
3 |
4 | local configs = require "nvim-treesitter.configs"
5 | local ts_utils = require "nvim-treesitter.ts_utils"
6 | local locals = require "nvim-treesitter.locals"
7 | local api = vim.api
8 | local cmd = api.nvim_command
9 |
10 | local M = {}
11 |
12 | local usage_namespace = api.nvim_create_namespace "nvim-treesitter-usages"
13 | local last_nodes = {}
14 |
15 | function M.highlight_usages(bufnr)
16 | local node_at_point = ts_utils.get_node_at_cursor()
17 | -- Don't calculate usages again if we are on the same node.
18 | if node_at_point and node_at_point == last_nodes[bufnr] and M.has_highlights(bufnr) then
19 | return
20 | else
21 | last_nodes[bufnr] = node_at_point
22 | end
23 |
24 | M.clear_usage_highlights(bufnr)
25 | if not node_at_point then
26 | return
27 | end
28 |
29 | local def_node, scope = locals.find_definition(node_at_point, bufnr)
30 | local usages = locals.find_usages(def_node, scope, bufnr)
31 |
32 | for _, usage_node in ipairs(usages) do
33 | if usage_node ~= node_at_point and usage_node ~= def_node then
34 | ts_utils.highlight_node(usage_node, bufnr, usage_namespace, "TSDefinitionUsage")
35 | end
36 | end
37 |
38 | if def_node ~= node_at_point then
39 | ts_utils.highlight_node(def_node, bufnr, usage_namespace, "TSDefinition")
40 | end
41 | end
42 |
43 | function M.has_highlights(bufnr)
44 | return #api.nvim_buf_get_extmarks(bufnr, usage_namespace, 0, -1, {}) > 0
45 | end
46 |
47 | function M.clear_usage_highlights(bufnr)
48 | api.nvim_buf_clear_namespace(bufnr, usage_namespace, 0, -1)
49 | end
50 |
51 | function M.attach(bufnr)
52 | local config = configs.get_module "refactor.highlight_definitions"
53 | cmd(string.format("augroup NvimTreesitterUsages_%d", bufnr))
54 | cmd "au!"
55 | -- luacheck: push ignore 631
56 | cmd(
57 | string.format(
58 | [[autocmd CursorHold lua require'nvim-treesitter-refactor.highlight_definitions'.highlight_usages(%d)]],
59 | bufnr,
60 | bufnr
61 | )
62 | )
63 | if config.clear_on_cursor_move then
64 | cmd(
65 | string.format(
66 | [[autocmd CursorMoved lua require'nvim-treesitter-refactor.highlight_definitions'.clear_usage_highlights(%d)]],
67 | bufnr,
68 | bufnr
69 | )
70 | )
71 | end
72 | cmd(
73 | string.format(
74 | [[autocmd InsertEnter lua require'nvim-treesitter-refactor.highlight_definitions'.clear_usage_highlights(%d)]],
75 | bufnr,
76 | bufnr
77 | )
78 | )
79 | -- luacheck: pop
80 | cmd "augroup END"
81 | end
82 |
83 | function M.detach(bufnr)
84 | M.clear_usage_highlights(bufnr)
85 | cmd(string.format("autocmd! NvimTreesitterUsages_%d CursorHold", bufnr))
86 | cmd(string.format("autocmd! NvimTreesitterUsages_%d CursorMoved", bufnr))
87 | cmd(string.format("autocmd! NvimTreesitterUsages_%d InsertEnter", bufnr))
88 | last_nodes[bufnr] = nil
89 | end
90 |
91 | return M
92 |
--------------------------------------------------------------------------------
/lua/nvim-treesitter-refactor/navigation.lua:
--------------------------------------------------------------------------------
1 | -- Definition based navigation module
2 |
3 | local ts_utils = require "nvim-treesitter.ts_utils"
4 | local locals = require "nvim-treesitter.locals"
5 | local configs = require "nvim-treesitter.configs"
6 | local api = vim.api
7 |
8 | local M = {}
9 |
10 | local function index_of(tbl, obj)
11 | for i, o in ipairs(tbl) do
12 | if o == obj then
13 | return i
14 | end
15 | end
16 | end
17 |
18 | local get_node_text = vim.treesitter.get_node_text or vim.treesitter.query.get_node_text
19 |
20 | function M.goto_definition(bufnr, fallback_function)
21 | local bufnr = bufnr or api.nvim_get_current_buf()
22 | local node_at_point = ts_utils.get_node_at_cursor()
23 |
24 | if not node_at_point then
25 | return
26 | end
27 |
28 | local definition = locals.find_definition(node_at_point, bufnr)
29 |
30 | if fallback_function and definition == node_at_point then
31 | fallback_function()
32 | else
33 | ts_utils.goto_node(definition)
34 | end
35 | end
36 |
37 | function M.goto_definition_lsp_fallback(bufnr)
38 | M.goto_definition(bufnr, vim.lsp.buf.definition)
39 | end
40 |
41 | --- Get definitions of bufnr (unique and sorted by order of appearance).
42 | local function get_definitions(bufnr)
43 | local local_nodes = locals.get_locals(bufnr)
44 |
45 | -- Make sure the nodes are unique.
46 | local nodes_set = {}
47 | for _, loc in ipairs(local_nodes) do
48 | if loc.definition then
49 | locals.recurse_local_nodes(loc.definition, function(_, node, _, match)
50 | -- lua doesn't compare tables by value,
51 | -- use the value from byte count instead.
52 | local _, _, start = node:start()
53 | nodes_set[start] = { node = node, type = match or "" }
54 | end)
55 | end
56 | end
57 |
58 | -- Sort by order of appearance.
59 | local definition_nodes = vim.tbl_values(nodes_set)
60 | table.sort(definition_nodes, function(a, b)
61 | local _, _, start_a = a.node:start()
62 | local _, _, start_b = b.node:start()
63 | return start_a < start_b
64 | end)
65 |
66 | return definition_nodes
67 | end
68 |
69 | function M.list_definitions(bufnr)
70 | local bufnr = bufnr or api.nvim_get_current_buf()
71 | local definitions = get_definitions(bufnr)
72 |
73 | if #definitions < 1 then
74 | return
75 | end
76 |
77 | local qf_list = {}
78 |
79 | for _, node in ipairs(definitions) do
80 | local lnum, col, _ = node.node:start()
81 | local type = string.upper(node.type:sub(1, 1))
82 | local text = get_node_text(node.node, bufnr) or ""
83 | table.insert(qf_list, {
84 | bufnr = bufnr,
85 | lnum = lnum + 1,
86 | col = col + 1,
87 | text = text,
88 | type = type,
89 | })
90 | end
91 |
92 | vim.fn.setqflist(qf_list, "r")
93 | api.nvim_command "copen"
94 | end
95 |
96 | function M.list_definitions_toc()
97 | local winnr = api.nvim_get_current_win()
98 | local bufnr = api.nvim_win_get_buf(winnr)
99 | local definitions = get_definitions(bufnr)
100 |
101 | if #definitions < 1 then
102 | return
103 | end
104 |
105 | local loc_list = {}
106 |
107 | -- Force some types to act like they are parents
108 | -- instead of neighbors of the next nodes.
109 | local containers = {
110 | ["function"] = true,
111 | ["type"] = true,
112 | ["method"] = true,
113 | }
114 |
115 | local parents = {}
116 |
117 | for _, def in ipairs(definitions) do
118 | -- Get indentation level by putting all parents in a stack.
119 | -- The length of the stack minus one is the current level of indentation.
120 | local n = #parents
121 | for i = 1, n do
122 | local index = n + 1 - i
123 | local parent_def = parents[index]
124 | if
125 | ts_utils.is_parent(parent_def.node, def.node)
126 | or (containers[parent_def.type] and ts_utils.is_parent(parent_def.node:parent(), def.node))
127 | then
128 | break
129 | else
130 | parents[index] = nil
131 | end
132 | end
133 | parents[#parents + 1] = def
134 |
135 | local lnum, col, _ = def.node:start()
136 | local type = string.upper(def.type:sub(1, 1))
137 | local text = get_node_text(def.node, bufnr) or ""
138 | table.insert(loc_list, {
139 | bufnr = bufnr,
140 | lnum = lnum + 1,
141 | col = col + 1,
142 | text = string.rep(" ", #parents - 1) .. text,
143 | type = type,
144 | })
145 | end
146 |
147 | vim.fn.setloclist(winnr, loc_list, "r")
148 | -- The title needs to end with `TOC`,
149 | -- so Neovim displays it like a TOC instead of an error list.
150 | vim.fn.setloclist(winnr, {}, "a", { title = "Definitions TOC" })
151 | api.nvim_command "lopen"
152 | end
153 |
154 | function M.goto_adjacent_usage(bufnr, delta)
155 | local bufnr = bufnr or api.nvim_get_current_buf()
156 | local node_at_point = ts_utils.get_node_at_cursor()
157 | if not node_at_point then
158 | return
159 | end
160 |
161 | local def_node, scope = locals.find_definition(node_at_point, bufnr)
162 | local usages = locals.find_usages(def_node, scope, bufnr)
163 |
164 | local index = index_of(usages, node_at_point)
165 | if not index then
166 | return
167 | end
168 |
169 | local target_index = (index + delta + #usages - 1) % #usages + 1
170 | ts_utils.goto_node(usages[target_index])
171 | end
172 |
173 | function M.goto_next_usage(bufnr)
174 | return M.goto_adjacent_usage(bufnr, 1)
175 | end
176 | function M.goto_previous_usage(bufnr)
177 | return M.goto_adjacent_usage(bufnr, -1)
178 | end
179 |
180 | function M.attach(bufnr)
181 | local config = configs.get_module "refactor.navigation"
182 |
183 | for fn_name, mapping in pairs(config.keymaps) do
184 | if mapping then
185 | local cmd = string.format([[:lua require'nvim-treesitter-refactor.navigation'.%s(%d)]], fn_name, bufnr)
186 | api.nvim_buf_set_keymap(bufnr, "n", mapping, cmd, { silent = true, noremap = true, desc = fn_name })
187 | end
188 | end
189 | end
190 |
191 | function M.detach(bufnr)
192 | local config = configs.get_module "refactor.navigation"
193 |
194 | for _, mapping in pairs(config.keymaps) do
195 | if mapping then
196 | api.nvim_buf_del_keymap(bufnr, "n", mapping)
197 | end
198 | end
199 | end
200 |
201 | return M
202 |
--------------------------------------------------------------------------------
/lua/nvim-treesitter-refactor/smart_rename.lua:
--------------------------------------------------------------------------------
1 | -- Binds a keybinding to smart rename definitions and usages.
2 | -- Can be used directly using the `smart_rename` function.
3 |
4 | local ts_utils = require "nvim-treesitter.ts_utils"
5 | local locals = require "nvim-treesitter.locals"
6 | local configs = require "nvim-treesitter.configs"
7 | local utils = require "nvim-treesitter.utils"
8 | local api = vim.api
9 |
10 | local get_node_text = vim.treesitter.get_node_text or vim.treesitter.query.get_node_text
11 |
12 | local M = {}
13 |
14 | function M.smart_rename(bufnr)
15 | bufnr = bufnr or api.nvim_get_current_buf()
16 | local node_at_point = ts_utils.get_node_at_cursor()
17 | local function complete_rename(new_name)
18 | -- Empty name cancels the interaction or ESC
19 | if not new_name or #new_name < 1 then
20 | return
21 | end
22 |
23 | local definition, scope = locals.find_definition(node_at_point, bufnr)
24 | local nodes_to_rename = {}
25 | nodes_to_rename[node_at_point:id()] = node_at_point
26 | nodes_to_rename[definition:id()] = definition
27 |
28 | for _, n in ipairs(locals.find_usages(definition, scope, bufnr)) do
29 | nodes_to_rename[n:id()] = n
30 | end
31 |
32 | local edits = {}
33 |
34 | for _, node in pairs(nodes_to_rename) do
35 | local lsp_range = ts_utils.node_to_lsp_range(node)
36 | local text_edit = { range = lsp_range, newText = new_name }
37 | table.insert(edits, text_edit)
38 | end
39 | vim.lsp.util.apply_text_edits(edits, bufnr, "utf-8")
40 | end
41 |
42 | if not node_at_point then
43 | utils.print_warning "No node to rename!"
44 | return
45 | end
46 |
47 | local node_text = get_node_text(node_at_point, bufnr)
48 | local input = { prompt = "New name: ", default = node_text or "" }
49 | if not vim.ui.input then
50 | local new_name = vim.fn.input(input.prompt, input.default)
51 | complete_rename(new_name)
52 | else
53 | vim.ui.input(input, complete_rename)
54 | end
55 | end
56 |
57 | function M.attach(bufnr)
58 | local config = configs.get_module "refactor.smart_rename"
59 |
60 | for fn_name, mapping in pairs(config.keymaps) do
61 | if mapping then
62 | local cmd = string.format([[:lua require'nvim-treesitter-refactor.smart_rename'.%s(%d)]], fn_name, bufnr)
63 | api.nvim_buf_set_keymap(bufnr, "n", mapping, cmd, { silent = true, noremap = true, desc = fn_name })
64 | end
65 | end
66 | end
67 |
68 | function M.detach(bufnr)
69 | local config = configs.get_module "refactor.smart_rename"
70 |
71 | for _, mapping in pairs(config.keymaps) do
72 | if mapping then
73 | api.nvim_buf_del_keymap(bufnr, "n", mapping)
74 | end
75 | end
76 | end
77 |
78 | return M
79 |
--------------------------------------------------------------------------------
/plugin/nvim-treesitter-refactor.vim:
--------------------------------------------------------------------------------
1 | lua << EOF
2 | require "nvim-treesitter-refactor".init()
3 | EOF
4 |
5 | highlight default link TSDefinitionUsage Visual
6 | highlight default link TSDefinition Search
7 | highlight default link TSCurrentScope CursorLine
8 |
--------------------------------------------------------------------------------
/scripts/style-check.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | luacheck `find -name "*.lua"` --codes
4 |
--------------------------------------------------------------------------------