├── .gitignore ├── lua ├── health │ └── goto-preview.lua ├── vim │ └── health │ │ └── goto-preview.lua ├── telescope │ └── _extensions │ │ └── gotopreview.lua ├── goto-preview │ ├── health.lua │ └── lib.lua └── goto-preview.lua ├── .stylua.toml ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /lua/health/goto-preview.lua: -------------------------------------------------------------------------------- 1 | return require "goto-preview.health" 2 | -------------------------------------------------------------------------------- /lua/vim/health/goto-preview.lua: -------------------------------------------------------------------------------- 1 | return require "goto-preview.health" 2 | -------------------------------------------------------------------------------- /.stylua.toml: -------------------------------------------------------------------------------- 1 | column_width = 160 2 | line_endings = "Unix" 3 | indent_type = "Spaces" 4 | indent_width = 2 5 | quote_style = "AutoPreferDouble" 6 | no_call_parentheses = true 7 | call_parentheses = "Input" 8 | collapse_simple_statement = "Never" 9 | 10 | -------------------------------------------------------------------------------- /lua/telescope/_extensions/gotopreview.lua: -------------------------------------------------------------------------------- 1 | local has_telescope, telescope = pcall(require, "telescope") 2 | local GotoPreview = require "goto-preview" 3 | local lib = require "goto-preview.lib" 4 | 5 | if not has_telescope then 6 | lib.logger.debug "Telescope.nvim not found. (https://github.com/nvim-telescope/telescope.nvim)" 7 | end 8 | 9 | return telescope.register_extension { 10 | setup = GotoPreview.setup, 11 | exports = { 12 | references = GotoPreview.goto_preview_references, 13 | }, 14 | } 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[FEATURE]" 5 | labels: enhancement 6 | assignees: rmagatti 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 | 22 | **Note:** This plugin requires Neovim >= 0.10. Please ensure your feature request is compatible with this requirement. 23 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: rmagatti 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 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Baseline (please complete the following information):** 27 | - OS. e.g `uname -a`: 28 | - Neovim version `nvim --version` (⚠️ **REQUIRED: Neovim >= 0.10**) 29 | - URL to your current config (if public) 30 | 31 | **⚠️ IMPORTANT:** This plugin requires Neovim >= 0.10. If you're using an older version, please upgrade before reporting issues. 32 | 33 | **Additional context** 34 | Add any other context about the problem here. 35 | -------------------------------------------------------------------------------- /lua/goto-preview/health.lua: -------------------------------------------------------------------------------- 1 | local M = {} 2 | 3 | function M.check() 4 | -- Use vim.health in Neovim 0.8+ or health in older versions if available 5 | local health 6 | if vim.fn.has "nvim-0.8" == 1 then 7 | health = vim.health 8 | else 9 | health = require "health" 10 | end 11 | 12 | -- Start the health check report 13 | health.start "goto-preview" 14 | 15 | -- Check Neovim version requirement 16 | if vim.fn.has "nvim-0.10" == 1 then 17 | health.ok "Neovim version is >= 0.10 (required)" 18 | else 19 | health.error("Neovim version is < 0.10", { 20 | "goto-preview requires Neovim >= 0.10", 21 | "Current version: " .. vim.version().major .. "." .. vim.version().minor .. "." .. vim.version().patch, 22 | "Please upgrade Neovim to version 0.10 or later", 23 | }) 24 | end 25 | 26 | -- Check if logger.nvim is installed 27 | local has_logger, _ = pcall(require, "logger") 28 | if has_logger then 29 | health.ok "logger.nvim is installed" 30 | else 31 | health.warn("logger.nvim is not installed", { 32 | "Some advanced logging features will be limited", 33 | "Consider installing 'logger.nvim' for enhanced logging capabilities", 34 | "To do so, add `dependencies = 'rmagatti/logger.nvim'` to the plugin install object", 35 | }) 36 | end 37 | 38 | -- Check if the plugin is properly loaded 39 | local has_goto_preview = pcall(require, "goto-preview") 40 | if has_goto_preview then 41 | health.ok "goto-preview is properly loaded" 42 | else 43 | health.error "goto-preview is not properly loaded" 44 | end 45 | 46 | -- Check for other providers 47 | health.info "Checking available reference providers" 48 | 49 | -- Telescope 50 | local has_telescope = pcall(require, "telescope") 51 | if has_telescope then 52 | health.ok "Telescope is available for references provider" 53 | else 54 | health.info "Telescope is not installed (optional for 'telescope' references provider)" 55 | end 56 | 57 | -- fzf-lua 58 | local has_fzf = pcall(require, "fzf-lua") 59 | if has_fzf then 60 | health.ok "fzf-lua is available for references provider" 61 | else 62 | health.info "fzf-lua is not installed (optional for 'fzf_lua' references provider)" 63 | end 64 | 65 | -- mini.pick 66 | local has_mini_pick = pcall(require, "mini.pick") 67 | if has_mini_pick then 68 | health.ok "mini.pick is available for references provider" 69 | else 70 | health.info "mini.pick is not installed (optional for 'mini_pick' references provider)" 71 | end 72 | 73 | -- snacks 74 | local has_snacks = pcall(require, "snacks") 75 | if has_snacks then 76 | health.ok "snacks is available for references provider" 77 | else 78 | health.info "snacks is not installed (optional for 'snacks' references provider)" 79 | end 80 | end 81 | 82 | return M 83 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## ⭐ Goto Preview 2 | A small Neovim plugin for previewing native LSP's goto definition, type definition, implementation, declaration and references calls in floating windows. 3 | 4 | ### 🚀 Showcase 5 | 6 | 7 | #### 🔗 References 8 | 9 | 10 | #### ⌨️ vim.ui.input 11 | 12 | 13 | ### ⚠️ IMPORTANT REQUIREMENTS 14 | **Minimum Neovim Version:** This plugin requires Neovim **≥ 0.10**. 15 | 16 | #### Migration Note for Older Neovim Versions 17 | If you are using Neovim < 0.10, please upgrade to continue using this plugin. The plugin now uses simplified LSP handler expectations that are only available in Neovim 0.10 and later. 18 | 19 | **For users on older Neovim releases:** Consider using an older version of this plugin that supports your Neovim version, or upgrade your Neovim installation. 20 | 21 | ### 📦 Installation 22 | [Lazy.nvim](https://github.com/folke/lazy.nvim) 23 | ```lua 24 | { 25 | "rmagatti/goto-preview", 26 | dependencies = { "rmagatti/logger.nvim" }, 27 | event = "BufEnter", 28 | config = true, -- necessary as per https://github.com/rmagatti/goto-preview/issues/88 29 | } 30 | ``` 31 | 32 | After installation it is recommended you run `:checkhealth goto-preview` to check if everything is in order. 33 | Note: the plugin has to be loaded for the checkhealth to run. 34 | 35 | ### ⚙️ Configuration 36 | 37 | **Default** 38 | ```lua 39 | require('goto-preview').setup { 40 | width = 120, -- Width of the floating window 41 | height = 15, -- Height of the floating window 42 | border = {"↖", "─" ,"┐", "│", "┘", "─", "└", "│"}, -- Border characters of the floating window 43 | default_mappings = false, -- Bind default mappings 44 | debug = false, -- Print debug information 45 | opacity = nil, -- 0-100 opacity level of the floating window where 100 is fully transparent. 46 | resizing_mappings = false, -- Binds arrow keys to resizing the floating window. 47 | post_open_hook = nil, -- A function taking two arguments, a buffer and a window to be ran as a hook. 48 | post_close_hook = nil, -- A function taking two arguments, a buffer and a window to be ran as a hook. 49 | references = { -- Configure the telescope UI for slowing the references cycling window. 50 | provider = "telescope", -- telescope|fzf_lua|snacks|mini_pick|default 51 | telescope = require("telescope.themes").get_dropdown({ hide_preview = false }) 52 | }, 53 | -- These two configs can also be passed down to the goto-preview definition and implementation calls for one off "peak" functionality. 54 | focus_on_open = true, -- Focus the floating window when opening it. 55 | dismiss_on_move = false, -- Dismiss the floating window when moving the cursor. 56 | force_close = true, -- passed into vim.api.nvim_win_close's second argument. See :h nvim_win_close 57 | bufhidden = "wipe", -- the bufhidden option to set on the floating window. See :h bufhidden 58 | stack_floating_preview_windows = true, -- Whether to nest floating windows 59 | same_file_float_preview = true, -- Whether to open a new floating window for a reference within the current file 60 | preview_window_title = { enable = true, position = "left" }, -- Whether to set the preview window title as the filename 61 | zindex = 1, -- Starting zindex for the stack of floating windows 62 | vim_ui_input = true, -- Whether to override vim.ui.input with a goto-preview floating window 63 | 64 | } 65 | ``` 66 | 67 | The `post_open_hook` function gets called right before setting the cursor position in the new floating window. 68 | One can use this to set custom key bindings or really anything else they want to do when a new preview window opens. 69 | 70 | The `post_close_hook` function gets called right before closing the preview window. This can be used to undo any 71 | custom key bindings when you leave the preview window. 72 | 73 | ### ⌨️ Mappings 74 | There are no mappings by default, you can set `default_mappings = true` in the config to make use of the mappings I use or define your own. 75 | 76 | **Default** 77 | ```viml 78 | nnoremap gpd lua require('goto-preview').goto_preview_definition() 79 | nnoremap gpt lua require('goto-preview').goto_preview_type_definition() 80 | nnoremap gpi lua require('goto-preview').goto_preview_implementation() 81 | nnoremap gpD lua require('goto-preview').goto_preview_declaration() 82 | nnoremap gP lua require('goto-preview').close_all_win() 83 | nnoremap gpr lua require('goto-preview').goto_preview_references() 84 | ``` 85 | 86 | **Custom example** 87 | ```lua 88 | vim.keymap.set("n", "gp", "lua require('goto-preview').goto_preview_definition()", {noremap=true}) 89 | ``` 90 | 91 | ### 📚 Custom Options 92 | 93 | The `close_all_win` function takes an optional table as an argument. 94 | 95 | Example usage: 96 | ```lua 97 | require("goto-preview").close_all_win { skip_curr_window = true } 98 | ``` 99 | 100 | ### 🔍 LSP Capability Detection 101 | 102 | Goto Preview uses a conservative approach for LSP capability detection to handle multiple language servers gracefully: 103 | 104 | 1. **Primary Strategy**: Uses language servers that explicitly advertise support for specific LSP methods (like `textDocument/definition`) 105 | 2. **Fallback Strategy**: If no servers advertise the capability, attempts the request with all attached language servers 106 | 3. **Result Selection**: Uses the first valid response from the preferred client set 107 | 108 | This approach ensures compatibility with language servers like jdtls that support definition requests but don't advertise the `definitionProvider` capability, while maintaining predictable behavior when multiple language servers are attached to the same buffer. 109 | 110 | ### Window manipulation 111 | One can manipulate floating windows with the regular Vim window moving commands. See `:h window-moving`. 112 | Example: 113 | 114 | 115 | ### Supported languages 116 | Goto Preview should work with LSP responses for most languages now! If something doesn't work as expected, drop an issue and I'll be happy to check it out! 117 | 118 | **Note:** different language servers have potentially different shapes for the result of the `textDocument/definition`, `textDocument/typeDefinition`, `textDocument/implementation` and `textDocument/declaration` calls. 119 | 120 | #### Simplified Handler Expectations 121 | Starting with Neovim 0.10, this plugin uses simplified LSP handler expectations. The handlers now expect a consistent 4-parameter signature: `(err, result, ctx, config)` instead of the legacy 3-parameter signature. 122 | 123 | **Custom LSP Response Handling:** You can customize LSP response processing through the `lsp_configs.get_config` function. This function should return two values: 124 | - `target (string)`: The URI or file path to open 125 | - `cursor_position ({line_num, col_num})`: The position to navigate to 126 | 127 | The `data` parameter passed to `get_config` is the first element of the LSP result or the result itself if it's not an array. 128 | 129 | 130 | ### Tested with 131 | ``` 132 | NVIM v0.11.0-dev-5068+g7371abf755-Homebrew 133 | Build type: Release 134 | LuaJIT 2.1.1736781742 135 | ``` 136 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /lua/goto-preview.lua: -------------------------------------------------------------------------------- 1 | local lib = require "goto-preview.lib" 2 | 3 | local function get_offset_encoding() 4 | local client = vim.lsp.get_clients({ bufnr = 0 })[1] 5 | return client and client.offset_encoding or "utf-16" 6 | end 7 | 8 | local M = { 9 | conf = { 10 | width = 120, -- Width of the floating window 11 | height = 15, -- Height of the floating window 12 | border = { "↖", "─", "┐", "│", "┘", "─", "└", "│" }, -- Border characters of the floating window 13 | default_mappings = false, -- Bind default mappings 14 | resizing_mappings = false, -- Binds arrow keys to resizing the floating window. 15 | debug = false, -- Print debug information 16 | opacity = nil, -- 0-100 opacity level of the floating window where 100 is fully transparent. 17 | lsp_configs = { 18 | -- Lsp result configs 19 | get_config = function(data) 20 | lib.logger.debug("data from the lsp", vim.inspect(data)) 21 | 22 | local uri = data.targetUri or data.uri 23 | local range = data.targetRange or data.range 24 | 25 | if range == nil then 26 | vim.notify("Warning: Range is nil, returning default configuration.", vim.log.levels.WARN) 27 | return uri, { 1, 0 } -- default safe values 28 | end 29 | 30 | return uri, { range.start.line + 1, range.start.character } 31 | end, 32 | }, 33 | post_open_hook = nil, -- A function taking two arguments, a buffer and a window to be ran as a hook. 34 | post_close_hook = nil, -- A function taking two arguments, a buffer and a window to be ran as a hook. 35 | references = { 36 | provider = "telescope", -- telescope|fzf_lua|snacks|mini_pick|default 37 | telescope = nil, 38 | }, 39 | focus_on_open = true, -- Focus the floating window when opening it. 40 | dismiss_on_move = false, -- Dismiss the floating window when moving the cursor. 41 | force_close = true, -- passed into vim.api.nvim_win_close's second argument. See :h nvim_win_close 42 | bufhidden = "wipe", -- the bufhidden option to set on the floating window. See :h bufhidden 43 | stack_floating_preview_windows = true, -- Whether to nest floating windows 44 | same_file_float_preview = true, -- Whether to open a new floating window for a reference within the current file 45 | preview_window_title = { enable = true, position = "left" }, -- Preview window title configuration 46 | zindex = 1, -- Starting zindex for the stack of floating windows 47 | vim_ui_input = false, -- Whether to override vim.ui.input with our custom implementation 48 | }, 49 | } 50 | 51 | M.setup = function(conf) 52 | conf = conf or {} 53 | M.conf = vim.tbl_deep_extend("force", M.conf, conf) 54 | lib.setup_lib(M.conf) 55 | lib.logger.debug("non-lib:", vim.inspect(M.conf)) 56 | lib.setup_aucmds() 57 | 58 | if M.conf.default_mappings then 59 | M.apply_default_mappings() 60 | end 61 | if M.conf.resizing_mappings then 62 | M.apply_resizing_mappings() 63 | end 64 | 65 | -- Setup custom input UI if enabled 66 | if M.conf.vim_ui_input then 67 | lib.setup_custom_input() 68 | end 69 | end 70 | 71 | local function print_lsp_error(lsp_call) 72 | print("goto-preview: Error calling LSP " .. lsp_call .. ". The current language lsp might not support it.") 73 | end 74 | 75 | --- Preview definition. 76 | --- @param opts table: Custom config 77 | --- • focus_on_open boolean: Focus the floating window when opening it. 78 | --- • dismiss_on_move boolean: Dismiss the floating window when moving the cursor. 79 | --- @see require("goto-preview").setup() 80 | -- Helper function to get LSP clients that support a specific method 81 | local function get_capable_clients(bufnr, method) 82 | local clients = vim.lsp.get_clients({ bufnr = bufnr }) 83 | local capable_clients = {} 84 | 85 | -- Map LSP methods to their capability paths 86 | local capability_map = { 87 | ["textDocument/definition"] = "definitionProvider", 88 | ["textDocument/typeDefinition"] = "typeDefinitionProvider", 89 | ["textDocument/implementation"] = "implementationProvider", 90 | ["textDocument/declaration"] = "declarationProvider", 91 | ["textDocument/references"] = "referencesProvider", 92 | } 93 | 94 | local capability_key = capability_map[method] 95 | if not capability_key then 96 | lib.logger.debug("Unknown method:", method) 97 | return clients -- fallback to all clients 98 | end 99 | 100 | for _, client in ipairs(clients) do 101 | if client.supports_method(method) then 102 | table.insert(capable_clients, client) 103 | lib.logger.debug("Client supports", method, ":", client.name) 104 | else 105 | lib.logger.debug("Client does NOT support", method, ":", client.name) 106 | end 107 | end 108 | 109 | return capable_clients 110 | end 111 | 112 | M.lsp_request_definition = function(opts) 113 | local params = vim.lsp.util.make_position_params(nil, get_offset_encoding()) 114 | local lsp_call = "textDocument/definition" 115 | 116 | -- Get clients that support definition requests 117 | local capable_clients = get_capable_clients(0, lsp_call) 118 | local all_clients = vim.lsp.get_clients({ bufnr = 0 }) 119 | 120 | lib.logger.debug("Found", #capable_clients, "capable clients for", lsp_call, "out of", #all_clients, "total clients") 121 | 122 | -- Strategy: prefer capable clients, but fallback to all clients if none capable 123 | local clients_to_try = #capable_clients > 0 and capable_clients or all_clients 124 | 125 | if #capable_clients == 0 and #all_clients > 0 then 126 | lib.logger.debug("No capable clients found, attempting fallback with all", #all_clients, "clients") 127 | elseif #all_clients == 0 then 128 | lib.logger.debug("No LSP clients attached to buffer") 129 | print_lsp_error(lsp_call) 130 | return 131 | end 132 | 133 | -- Create a map for easier lookup during result processing 134 | local client_ids_to_try = {} 135 | for _, client in ipairs(clients_to_try) do 136 | client_ids_to_try[client.id] = true 137 | end 138 | 139 | -- Use buf_request_all but only process results from our target clients 140 | local success, request_id = pcall(vim.lsp.buf_request_all, 0, lsp_call, params, function(results) 141 | lib.logger.debug("buf_request_all results:", vim.inspect(results)) 142 | 143 | -- Process results only from clients we intended to query 144 | for client_id, result in pairs(results) do 145 | if result.result and not vim.tbl_isempty(result.result) and client_ids_to_try[client_id] then 146 | lib.logger.debug("Using result from client_id:", client_id) 147 | local handler = lib.get_handler(lsp_call, opts) 148 | handler(nil, result.result, nil, nil) 149 | return -- Only process the first valid result 150 | end 151 | end 152 | 153 | lib.logger.debug("No valid results found from target clients") 154 | print_lsp_error(lsp_call) 155 | end) 156 | 157 | lib.logger.debug("lsp_request_definition", success, "request_id:", request_id) 158 | if not success then 159 | print_lsp_error(lsp_call) 160 | end 161 | end 162 | 163 | --- Preview type definition. 164 | --- @param opts table: Custom config 165 | --- • focus_on_open boolean: Focus the floating window when opening it. 166 | --- • dismiss_on_move boolean: Dismiss the floating window when moving the cursor. 167 | --- @see require("goto-preview").setup() 168 | M.lsp_request_type_definition = function(opts) 169 | local params = vim.lsp.util.make_position_params(nil, get_offset_encoding()) 170 | local lsp_call = "textDocument/typeDefinition" 171 | local success, _ = pcall(vim.lsp.buf_request, 0, lsp_call, params, lib.get_handler(lsp_call, opts)) 172 | lib.logger.debug("lsp_request_type_definition", success) 173 | if not success then 174 | print_lsp_error(lsp_call) 175 | end 176 | end 177 | 178 | --- Preview implementation. 179 | --- @param opts table: Custom config 180 | --- • focus_on_open boolean: Focus the floating window when opening it. 181 | --- • dismiss_on_move boolean: Dismiss the floating window when moving the cursor. 182 | --- @see require("goto-preview").setup() 183 | M.lsp_request_implementation = function(opts) 184 | local params = vim.lsp.util.make_position_params(nil, get_offset_encoding()) 185 | local lsp_call = "textDocument/implementation" 186 | local success, _ = pcall(vim.lsp.buf_request, 0, lsp_call, params, lib.get_handler(lsp_call, opts)) 187 | lib.logger.debug("lsp_request_implementation", success) 188 | if not success then 189 | print_lsp_error(lsp_call) 190 | end 191 | end 192 | 193 | --- Preview declaration. 194 | --- @param opts table: Custom config 195 | --- • focus_on_open boolean: Focus the floating window when opening it. 196 | --- • dismiss_on_move boolean: Dismiss the floating window when moving the cursor. 197 | --- @see require("goto-preview").setup() 198 | M.lsp_request_declaration = function(opts) 199 | local params = vim.lsp.util.make_position_params(nil, get_offset_encoding()) 200 | local lsp_call = "textDocument/declaration" 201 | local success, _ = pcall(vim.lsp.buf_request, 0, lsp_call, params, lib.get_handler(lsp_call, opts)) 202 | lib.logger.debug("lsp_request_declaration", success) 203 | if not success then 204 | print_lsp_error(lsp_call) 205 | end 206 | end 207 | 208 | M.lsp_request_references = function(opts) 209 | local params = vim.lsp.util.make_position_params(nil, get_offset_encoding()) 210 | 211 | lib.logger.debug("params pre manipulation", vim.inspect(params)) 212 | if not params.context then 213 | params.context = { 214 | includeDeclaration = true, 215 | } 216 | end 217 | lib.logger.debug("params post manipulation", vim.inspect(params)) 218 | 219 | local lsp_call = "textDocument/references" 220 | local success, _ = pcall(vim.lsp.buf_request, 0, lsp_call, params, lib.get_handler(lsp_call, opts)) 221 | if not success then 222 | print_lsp_error(lsp_call) 223 | end 224 | end 225 | 226 | M.close_all_win = function(options) 227 | local windows = vim.api.nvim_tabpage_list_wins(0) 228 | 229 | for _, win in pairs(windows) do 230 | local index = lib.tablefind(lib.windows, win) 231 | table.remove(lib.windows, index) 232 | 233 | if options and options.skip_curr_window then 234 | if win ~= vim.api.nvim_get_current_win() then 235 | pcall(lib.close_if_is_goto_preview, win) 236 | end 237 | else 238 | pcall(lib.close_if_is_goto_preview, win) 239 | end 240 | end 241 | end 242 | 243 | M.remove_win = lib.remove_win 244 | M.buffer_entered = lib.buffer_entered 245 | M.buffer_left = lib.buffer_left 246 | M.dismiss_preview = lib.dismiss_preview 247 | M.goto_preview_definition = M.lsp_request_definition 248 | M.goto_preview_type_definition = M.lsp_request_type_definition 249 | M.goto_preview_implementation = M.lsp_request_implementation 250 | M.goto_preview_declaration = M.lsp_request_declaration 251 | M.goto_preview_references = M.lsp_request_references 252 | -- Mappings 253 | 254 | M.apply_default_mappings = function() 255 | if M.conf.default_mappings then 256 | vim.keymap.set("n", "gpd", require("goto-preview").goto_preview_definition, { desc = "Preview definition" }) 257 | vim.keymap.set("n", "gpt", require("goto-preview").goto_preview_type_definition, { desc = "Preview type definition" }) 258 | vim.keymap.set("n", "gpi", require("goto-preview").goto_preview_implementation, { 259 | desc = "Preview implementation", 260 | }) 261 | vim.keymap.set("n", "gpD", require("goto-preview").goto_preview_declaration, { 262 | desc = "Preview declaration", 263 | }) 264 | vim.keymap.set("n", "gpr", require("goto-preview").goto_preview_references, { desc = "Preview references" }) 265 | vim.keymap.set("n", "gP", require("goto-preview").close_all_win, { desc = "Close preview windows" }) 266 | end 267 | end 268 | 269 | M.apply_resizing_mappings = function() 270 | if M.conf.resizing_mappings then 271 | vim.keymap.set("n", "", "<", { noremap = true }) 272 | vim.keymap.set("n", "", ">", { noremap = true }) 273 | vim.keymap.set("n", "", "-", { noremap = true }) 274 | vim.keymap.set("n", "", "+", { noremap = true }) 275 | end 276 | end 277 | 278 | return M 279 | -------------------------------------------------------------------------------- /lua/goto-preview/lib.lua: -------------------------------------------------------------------------------- 1 | local M = { 2 | conf = {}, 3 | } 4 | 5 | local logger = nil 6 | 7 | -- Simple logger implementation for fallback 8 | local function create_simple_logger(options) 9 | local log_level = options and options.log_level or "info" 10 | local prefix = options and options.prefix or "" 11 | local levels = { debug = 1, info = 2, warn = 3, error = 4 } 12 | local current_level = levels[log_level] or 2 13 | 14 | local function log(level, ...) 15 | if levels[level] >= current_level then 16 | local args = { ... } 17 | local msg = "" 18 | ---@diagnostic disable-next-line: unused-local 19 | for _, v in ipairs(args) do 20 | msg = msg .. tostring(v) .. " " 21 | end 22 | local formatted_msg = string.format("[%s][FALLBACK LOGGER - missing logger.nvim dependency] %s: %s", prefix, 23 | level:upper(), msg) 24 | 25 | -- Use vim.notify for user-visible notifications 26 | vim.notify(formatted_msg, vim.log.levels[level:upper()]) 27 | 28 | -- Also log to messages for persistence 29 | print(formatted_msg) 30 | end 31 | end 32 | 33 | return { 34 | debug = function(...) 35 | log("debug", ...) 36 | end, 37 | info = function(...) 38 | log("info", ...) 39 | end, 40 | warn = function(...) 41 | log("warn", ...) 42 | end, 43 | error = function(...) 44 | log("error", ...) 45 | end, 46 | new = function(opts) 47 | return create_simple_logger(opts) 48 | end, 49 | } 50 | end 51 | 52 | M.setup_lib = function(conf) 53 | M.conf = vim.tbl_deep_extend("force", M.conf, conf) 54 | 55 | -- Try to require the logger module, fall back to simple implementation if not available 56 | local ok, logger_module = pcall(require, "logger") 57 | if ok then 58 | logger = logger_module:new { log_level = M.conf.debug and "debug" or "info", prefix = "goto-preview" } 59 | else 60 | -- Use the simple logger implementation 61 | logger = create_simple_logger { log_level = M.conf.debug and "debug" or "info", prefix = "goto-preview" } 62 | end 63 | 64 | M.logger = logger 65 | logger.debug("lib:", vim.inspect(M.conf)) 66 | end 67 | 68 | local function is_floating(window_id) 69 | return vim.api.nvim_win_get_config(window_id).relative ~= "" 70 | end 71 | 72 | local function is_curr_buf(buffer) 73 | return vim.api.nvim_get_current_buf() == buffer 74 | end 75 | 76 | local run_post_open_hook_function = function(buffer, new_window) 77 | local success, result = pcall(M.conf.post_open_hook, buffer, new_window) 78 | logger.debug("post_open_hook call success:", success, result) 79 | end 80 | 81 | local run_post_close_hook_function = function(buffer, new_window) 82 | local success, result = pcall(M.conf.post_close_hook, buffer, new_window) 83 | logger.debug("post_close_hook call success:", success, result) 84 | end 85 | 86 | function M.tablefind(tab, el) 87 | for index, value in pairs(tab) do 88 | if value == el then 89 | return index 90 | end 91 | end 92 | end 93 | 94 | --- Setup the custom UI input functionality 95 | M.setup_custom_input = function() 96 | -- Store the original vim.ui.input 97 | M._original_input = vim.ui.input 98 | 99 | -- Replace with our custom implementation 100 | vim.ui.input = function(opts, on_confirm) 101 | -- Create a new buffer for the input field 102 | local buf = vim.api.nvim_create_buf(false, true) 103 | 104 | -- Pre-populate with default text if provided 105 | local initial_text = opts.default or "" 106 | vim.api.nvim_buf_set_lines(buf, 0, -1, false, { initial_text }) 107 | 108 | -- Calculate appropriate width based on content + padding 109 | local content_width = #initial_text 110 | local min_width = 20 -- Minimum width for small inputs 111 | local max_width = 120 -- Maximum width to prevent too wide windows 112 | local padding = 16 -- Extra space for cursor, line numbers, and comfort 113 | local width = math.min(max_width, math.max(min_width, content_width + padding)) 114 | 115 | -- Open the floating window using our existing function 116 | local win = M.open_floating_win(buf, { 1, 0 }, { 117 | focus_on_open = true, 118 | dismiss_on_move = false, 119 | -- Override some settings specific to input windows 120 | same_file_float_preview = true, 121 | width = width, 122 | height = 1, -- Only one line for input 123 | }) 124 | 125 | -- Move cursor to the end of any default text 126 | vim.api.nvim_win_set_cursor(win, { 1, #initial_text }) 127 | 128 | -- Set window title if we have a prompt 129 | if vim.fn.has "nvim-0.9.0" == 1 and opts.prompt then 130 | vim.api.nvim_win_set_config(win, { 131 | title = opts.prompt, 132 | title_pos = "left", 133 | }) 134 | end 135 | 136 | -- Function to handle result and clean up 137 | local function handle_result(result) 138 | -- Remove from windows table 139 | local index = M.tablefind(M.windows, win) 140 | if index then 141 | table.remove(M.windows, index) 142 | end 143 | 144 | -- Run post close hook if defined 145 | if M.conf.post_close_hook then 146 | run_post_close_hook_function(buf, win) 147 | end 148 | 149 | -- Close the window 150 | pcall(vim.api.nvim_win_close, win, true) 151 | 152 | -- Call the callback 153 | if on_confirm then 154 | on_confirm(result) 155 | end 156 | end 157 | 158 | -- Set keymaps for the input window 159 | local keymaps = { 160 | -- Normal mode mappings 161 | n = { 162 | [""] = function() 163 | local result = vim.api.nvim_buf_get_lines(buf, 0, 1, false)[1] 164 | handle_result(result) 165 | end, 166 | [""] = function() 167 | handle_result(nil) 168 | end, 169 | ["i"] = function() 170 | vim.cmd "startinsert" 171 | end, 172 | ["a"] = function() 173 | vim.cmd "startinsert" 174 | end, 175 | }, 176 | 177 | -- Insert mode mappings 178 | i = { 179 | [""] = function() 180 | local result = vim.api.nvim_buf_get_lines(buf, 0, 1, false)[1] 181 | handle_result(result) 182 | end, 183 | }, 184 | } 185 | 186 | -- Apply all keymaps 187 | for mode, maps in pairs(keymaps) do 188 | for key, func in pairs(maps) do 189 | vim.keymap.set(mode, key, func, { buffer = buf, nowait = true }) 190 | end 191 | end 192 | 193 | -- Start in normal mode by default 194 | vim.cmd "stopinsert" 195 | vim.notify("Press to confirm, to cancel", "info") 196 | end 197 | end 198 | 199 | M.remove_win = function(win) 200 | local curr_buf = vim.api.nvim_get_current_buf() 201 | local curr_win = vim.api.nvim_get_current_win() 202 | 203 | local success, result = pcall(vim.api.nvim_win_get_var, curr_win, "is-goto-preview-window") 204 | 205 | if success and result == 1 then 206 | run_post_close_hook_function(curr_buf, curr_win) 207 | end 208 | 209 | local index = M.tablefind(M.windows, win or vim.api.nvim_get_current_win()) 210 | if index then 211 | table.remove(M.windows, index) 212 | -- Focus the previous preview if there is one 213 | if index > 1 then 214 | local prev_win = M.windows[index - 1] 215 | vim.api.nvim_set_current_win(prev_win) 216 | end 217 | end 218 | end 219 | 220 | M.windows = {} 221 | 222 | M.setup_aucmds = function() 223 | vim.cmd [[ 224 | augroup goto-preview 225 | au! 226 | au WinClosed * lua require('goto-preview').remove_win() 227 | au BufEnter * lua require('goto-preview').buffer_entered() 228 | au BufLeave * lua require('goto-preview').buffer_left() 229 | augroup end 230 | ]] 231 | end 232 | 233 | M.dismiss_preview = function(winnr) 234 | logger.debug("dismiss_preview", winnr) 235 | if winnr then 236 | logger.debug("attempting to close ", winnr) 237 | pcall(vim.api.nvim_win_close, winnr, true) 238 | else 239 | logger.debug "attempting to all preview windows" 240 | for _, win in ipairs(M.windows) do 241 | M.close_if_is_goto_preview(win) 242 | end 243 | end 244 | end 245 | 246 | M.close_if_is_goto_preview = function(win_handle) 247 | local curr_buf = vim.api.nvim_get_current_buf() 248 | local curr_win = vim.api.nvim_get_current_win() 249 | 250 | local success, result = pcall(vim.api.nvim_win_get_var, win_handle, "is-goto-preview-window") 251 | if success and result == 1 then 252 | run_post_close_hook_function(curr_buf, curr_win) 253 | vim.api.nvim_win_close(win_handle, M.conf.force_close) 254 | end 255 | end 256 | 257 | local function set_title(buffer) 258 | if vim.fn.has "nvim-0.9.0" == 0 then 259 | logger.debug "title not supported in this version of neovim" 260 | return nil 261 | end 262 | 263 | local rel_filepath = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(buffer), ":.") 264 | return M.conf.preview_window_title.enable and rel_filepath or nil 265 | end 266 | 267 | local function set_title_pos() 268 | if vim.fn.has "nvim-0.9.0" == 0 then 269 | logger.debug "title_pos not supported in this version of neovim" 270 | return nil 271 | end 272 | 273 | return M.conf.preview_window_title.enable and M.conf.preview_window_title.position or nil 274 | end 275 | 276 | local function create_preview_win(buffer, bufpos, zindex, opts) 277 | local enter = function() 278 | return opts.focus_on_open or M.conf.focus_on_open or false 279 | end 280 | 281 | local stack_floating_preview_windows = function() 282 | return opts.stack_floating_preview_windows or M.conf.stack_floating_preview_windows or false 283 | end 284 | 285 | local same_file_float_preview = function() 286 | return opts.same_file_float_preview or M.conf.same_file_float_preview or false 287 | end 288 | 289 | logger.debug("focus_on_open", enter()) 290 | logger.debug("stack_floating_preview_windows", stack_floating_preview_windows()) 291 | logger.debug("width" .. vim.inspect(opts.width or M.conf.width), "info") 292 | logger.debug("height" .. vim.inspect(opts.height or M.conf.height), "info") 293 | 294 | local preview_window 295 | local curr_win = vim.api.nvim_get_current_win() 296 | local success, result = pcall(vim.api.nvim_win_get_var, curr_win, "is-goto-preview-window") 297 | 298 | if is_curr_buf(buffer) and not same_file_float_preview() then 299 | return curr_win 300 | end 301 | 302 | if not stack_floating_preview_windows() and is_floating(curr_win) and success and result == 1 then 303 | preview_window = curr_win 304 | vim.api.nvim_win_set_config(preview_window, { 305 | width = opts.width or M.conf.width, 306 | height = opts.height or M.conf.height, 307 | border = M.conf.border, 308 | }) 309 | vim.api.nvim_win_set_buf(preview_window, buffer) 310 | else 311 | preview_window = vim.api.nvim_open_win(buffer, enter(), { 312 | relative = "win", 313 | width = opts.width or M.conf.width, 314 | height = opts.height or M.conf.height, 315 | border = M.conf.border, 316 | bufpos = bufpos, 317 | zindex = zindex, 318 | win = vim.api.nvim_get_current_win(), 319 | title = set_title(buffer), 320 | title_pos = set_title_pos(), 321 | }) 322 | 323 | table.insert(M.windows, preview_window) 324 | end 325 | 326 | return preview_window 327 | end 328 | 329 | M.open_floating_win = function(target, position, opts) 330 | local buffer = type(target) == "string" and vim.uri_to_bufnr(target) or target 331 | local bufpos = { vim.fn.line "." - 1, vim.fn.col "." } -- FOR relative='win' 332 | local zindex = M.conf.zindex + (vim.tbl_isempty(M.windows) and 0 or #M.windows) 333 | 334 | opts = opts or {} 335 | 336 | local preview_window = create_preview_win(buffer, bufpos, zindex, opts) 337 | 338 | if M.conf.opacity then 339 | vim.api.nvim_set_option_value("winblend", M.conf.opacity, { win = preview_window }) 340 | end 341 | if not is_curr_buf(buffer) then 342 | vim.api.nvim_set_option_value("bufhidden", M.conf.bufhidden, { buf = buffer }) 343 | end 344 | vim.api.nvim_win_set_var(preview_window, "is-goto-preview-window", 1) 345 | 346 | logger.debug(vim.inspect { 347 | curr_window = vim.api.nvim_get_current_win(), 348 | preview_window = preview_window, 349 | bufpos = bufpos, 350 | get_config = vim.api.nvim_win_get_config(preview_window), 351 | get_current_line = vim.api.nvim_get_current_line(), 352 | windows = M.windows, 353 | }) 354 | 355 | local dismiss = function() 356 | if opts.dismiss_on_move ~= nil then 357 | return opts.dismiss_on_move 358 | else 359 | return M.conf.dismiss_on_move 360 | end 361 | end 362 | 363 | logger.debug("dismiss_on_move", dismiss()) 364 | if dismiss() then 365 | vim.api.nvim_command(string.format( 366 | "autocmd CursorMoved ++once lua require('goto-preview').dismiss_preview(%d)", preview_window)) 367 | end 368 | 369 | -- Set position of the preview buffer equal to the target position so that correct preview position shows 370 | vim.api.nvim_win_set_cursor(preview_window, position) 371 | 372 | run_post_open_hook_function(buffer, preview_window) 373 | 374 | return preview_window 375 | end 376 | 377 | M.buffer_entered = function() 378 | local curr_buf = vim.api.nvim_get_current_buf() 379 | local curr_win = vim.api.nvim_get_current_win() 380 | 381 | local success, result = pcall(vim.api.nvim_win_get_var, curr_win, "is-goto-preview-window") 382 | 383 | if success and result == 1 then 384 | logger.debug "buffer_entered was called and will run hook function" 385 | run_post_open_hook_function(curr_buf, curr_win) 386 | end 387 | end 388 | 389 | M.buffer_left = function() 390 | local curr_buf = vim.api.nvim_get_current_buf() 391 | local curr_win = vim.api.nvim_get_current_win() 392 | 393 | local success, result = pcall(vim.api.nvim_win_get_var, curr_win, "is-goto-preview-window") 394 | 395 | if success and result == 1 then 396 | logger.debug "buffer_left was called and will run hook function" 397 | run_post_close_hook_function(curr_buf, curr_win) 398 | end 399 | end 400 | 401 | local function _open_references_window(filename, pos) 402 | M.open_floating_win(vim.uri_from_fname(filename), pos) 403 | end 404 | 405 | local function _format_item_entry(item) 406 | -- Format text to the following standard 407 | -- some/path/to/file:20:1 | text in the file 408 | -- some/longer/path/to/f...| text in the file 409 | local filename_width = 30 410 | 411 | -- This sets up the correct field for mini.pick 412 | item.path = item.filename 413 | local rel_path = vim.fn.fnamemodify(item.filename, ":.") 414 | local display_path = string.format("%s:%d:%d", rel_path, item.lnum or 1, item.col or 1) 415 | 416 | if #display_path > filename_width then 417 | display_path = display_path:sub(1, filename_width - 3) .. "..." 418 | else 419 | display_path = display_path .. string.rep(" ", filename_width - #display_path) 420 | end 421 | 422 | -- Remove leading and trailing spaces 423 | local trimmed = string.gsub(item.text, "^%s*(.-)%s*$", "%1") 424 | 425 | item.text = display_path .. "| " .. trimmed 426 | return item.text 427 | end 428 | 429 | local providers = { 430 | snacks = function(_, _) 431 | local ok, snacks = pcall(require, "snacks") 432 | if not ok then 433 | error "Snacks not installed" 434 | end 435 | 436 | snacks.picker.pick { 437 | source = "lsp_references", 438 | confirm = function(picker) 439 | local selection = picker:current() 440 | picker:close() 441 | 442 | if selection ~= nil then 443 | _open_references_window(selection.file, selection.pos) 444 | end 445 | end, 446 | } 447 | end, 448 | 449 | fzf_lua = function(_, _) 450 | local ok, fzf = pcall(require, "fzf-lua") 451 | if not ok then 452 | error "fzf-lua not installed" 453 | end 454 | 455 | fzf.lsp_references { 456 | actions = { 457 | ["default"] = function(selected, opts) 458 | local selection = fzf.path.entry_to_file(selected[1], opts) 459 | 460 | _open_references_window(selection.path, { selection.line, selection.col }) 461 | end, 462 | }, 463 | } 464 | end, 465 | 466 | telescope = function(prompt_title, items) 467 | local ok, _ = pcall(require, "telescope") 468 | if not ok then 469 | error "Telescope not installed" 470 | end 471 | 472 | local pickers = require "telescope.pickers" 473 | local make_entry = require "telescope.make_entry" 474 | local telescope_conf = require("telescope.config").values 475 | local finders = require "telescope.finders" 476 | local actions = require "telescope.actions" 477 | local action_state = require "telescope.actions.state" 478 | local themes = require "telescope.themes" 479 | 480 | local opts = M.conf.references.telescope or themes.get_dropdown { hide_preview = false } 481 | local entry_maker = make_entry.gen_from_quickfix(opts) 482 | local previewer = nil 483 | 484 | if not opts.hide_preview then 485 | previewer = telescope_conf.qflist_previewer(opts) 486 | end 487 | 488 | pickers 489 | .new(opts, { 490 | prompt_title = prompt_title, 491 | finder = finders.new_table { 492 | results = items, 493 | entry_maker = entry_maker, 494 | }, 495 | previewer = previewer, 496 | sorter = telescope_conf.generic_sorter(opts), 497 | attach_mappings = function(prompt_bufnr) 498 | actions.select_default:replace(function() 499 | local selection = action_state.get_selected_entry() 500 | actions.close(prompt_bufnr) 501 | 502 | _open_references_window(selection.value.filename, { 503 | selection.value.lnum, 504 | selection.value.col, 505 | }) 506 | end) 507 | 508 | return true 509 | end, 510 | }) 511 | :find() 512 | end, 513 | 514 | mini_pick = function(prompt_title, items) 515 | local ok, mini_pick = pcall(require, "mini.pick") 516 | if not ok then 517 | error "MiniPick not installed" 518 | end 519 | 520 | for _, item in ipairs(items) do 521 | _format_item_entry(item) 522 | end 523 | 524 | mini_pick.start { 525 | source = { 526 | name = prompt_title, 527 | items = items, 528 | show = function(buf_id, items_to_show, query) 529 | mini_pick.default_show(buf_id, items_to_show, query, { 530 | show_icons = true, 531 | }) 532 | end, 533 | choose = function(item) 534 | _open_references_window(item.filename, { 535 | item.lnum, 536 | item.col, 537 | }) 538 | end, 539 | }, 540 | preview = function(buf_id, item) 541 | mini_pick.default_preview(buf_id, item, nil) 542 | end, 543 | } 544 | end, 545 | 546 | default = function(prompt_title, items) 547 | vim.ui.select(items, { 548 | prompt = prompt_title, 549 | format_item = function(item) 550 | if item ~= nil then 551 | return _format_item_entry(item) 552 | end 553 | end, 554 | }, function(choice) 555 | if choice ~= nil then 556 | _open_references_window(choice.filename, { 557 | choice.lnum, 558 | choice.col, 559 | }) 560 | end 561 | end) 562 | end, 563 | } 564 | 565 | local function open_references_previewer(prompt_title, items) 566 | if #items == 1 then 567 | local item = items[1] 568 | _open_references_window(item.filename, { item.lnum, item.col }) 569 | return true 570 | end 571 | 572 | local provider = M.conf.references.provider 573 | local provider_fn = providers[provider] 574 | 575 | -- Try selected provider first 576 | if provider_fn then 577 | local ok, err = pcall(provider_fn, prompt_title, items) 578 | if ok then 579 | return 580 | end 581 | -- Log the error and fall through to default 582 | logger.debug("Provider", provider, "failed:", err) 583 | end 584 | 585 | -- Fall back to default provider 586 | providers.default(prompt_title, items) 587 | end 588 | 589 | local handle = function(result, opts) 590 | logger.debug("handle called with result:", vim.inspect(result)) 591 | logger.debug("current windows before processing:", vim.inspect(M.windows)) 592 | 593 | if not result then 594 | logger.debug "handle: result is nil, returning" 595 | return 596 | end 597 | 598 | local data = result[1] or result 599 | logger.debug("extracted data:", vim.inspect(data)) 600 | 601 | if vim.tbl_isempty(data) then 602 | logger.debug "The LSP returned no results. No preview to display." 603 | return 604 | end 605 | 606 | local target, cursor_position = M.conf.lsp_configs.get_config(data) 607 | logger.debug("opening window for target:", target, "at position:", vim.inspect(cursor_position)) 608 | 609 | -- opts: focus_on_open, dismiss_on_move, etc. 610 | M.open_floating_win(target, cursor_position, opts) 611 | 612 | logger.debug("current windows after processing:", vim.inspect(M.windows)) 613 | end 614 | 615 | local handle_references = function(result) 616 | if not result then 617 | return 618 | end 619 | local items = {} 620 | 621 | vim.list_extend(items, vim.lsp.util.locations_to_items(result, "utf-8") or {}) 622 | 623 | open_references_previewer("References", items) 624 | end 625 | 626 | local legacy_handler = function(lsp_call, opts) 627 | return function(_, _, result) 628 | if lsp_call ~= nil and lsp_call == "textDocument/references" then 629 | logger.debug("raw result", vim.inspect(result)) 630 | handle_references(result) 631 | else 632 | handle(result, opts) 633 | end 634 | end 635 | end 636 | 637 | local handler = function(lsp_call, opts) 638 | return function(_, result, _, _) 639 | if lsp_call ~= nil and lsp_call == "textDocument/references" then 640 | logger.debug("raw result", vim.inspect(result)) 641 | handle_references(result) 642 | else 643 | handle(result, opts) 644 | end 645 | end 646 | end 647 | 648 | M.get_handler = function(lsp_call, opts) 649 | -- Only really need to check one of the handlers 650 | for k, v in pairs(vim.lsp.handlers) do 651 | if string.find(k, "textDocument") and type(v) == "function" and debug.getinfo(v).isvararg == false then 652 | if debug.getinfo(v).nparams == 4 then 653 | logger.debug "calling new handler" 654 | return handler(lsp_call, opts) 655 | else 656 | logger.debug "calling legacy handler" 657 | return legacy_handler(lsp_call, opts) 658 | end 659 | end 660 | end 661 | end 662 | 663 | return M 664 | --------------------------------------------------------------------------------