From a2b8d386a020f3c8c5b1befdbb6537f34af81ce4 Mon Sep 17 00:00:00 2001 From: Sanchayan Maity Date: Thu, 11 Jun 2020 11:30:15 +0530 Subject: [PATCH] nvim: lua: lsp: Add support for peek definition Signed-off-by: Sanchayan Maity --- nvim/.config/nvim/lua/lsp.lua | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/nvim/.config/nvim/lua/lsp.lua b/nvim/.config/nvim/lua/lsp.lua index 4c10832..e9590ba 100644 --- a/nvim/.config/nvim/lua/lsp.lua +++ b/nvim/.config/nvim/lua/lsp.lua @@ -1,5 +1,47 @@ local nvim_lsp = require('nvim_lsp') +-- Taken from https://www.reddit.com/r/neovim/comments/gyb077/nvimlsp_peek_defination_javascript_ttserver/ +function preview_location(location, context, before_context) + -- location may be LocationLink or Location (more useful for the former) + context = context or 10 + before_context = before_context or 5 + local uri = location.targetUri or location.uri + if uri == nil then + return + end + local bufnr = vim.uri_to_bufnr(uri) + if not vim.api.nvim_buf_is_loaded(bufnr) then + vim.fn.bufload(bufnr) + end + local range = location.targetRange or location.range + local contents = + vim.api.nvim_buf_get_lines(bufnr, range.start.line - before_context, range["end"].line + 1 + context, false) + local filetype = vim.api.nvim_buf_get_option(bufnr, "filetype") + return vim.lsp.util.open_floating_preview(contents, filetype) +end + +function preview_location_callback(_, method, result) + local context = 10 + if result == nil or vim.tbl_isempty(result) then + print("No location found: " .. method) + return nil + end + if vim.tbl_islist(result) then + floating_buf, floating_win = preview_location(result[1], context) + else + floating_buf, floating_win = preview_location(result, context) + end +end + +function peek_definition() + if vim.tbl_contains(vim.api.nvim_list_wins(), floating_win) then + vim.api.nvim_set_current_win(floating_win) + else + local params = vim.lsp.util.make_position_params() + return vim.lsp.buf_request(0, "textDocument/definition", params, preview_location_callback) + end +end + local on_attach = function(_, bufnr) vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') require'diagnostic'.on_attach() @@ -17,6 +59,7 @@ local on_attach = function(_, bufnr) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gW', 'lua vim.lsp.buf.workspace_symbol()', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'de', 'lua vim.lsp.buf.declaration()', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'rn', 'lua vim.lsp.buf.rename()', opts) + vim.api.nvim_buf_set_keymap(bufnr, 'n', 'pd', 'lua peek_definition()', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '[d', ':PrevDiagnostic', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', ']d', ':NextDiagnostic', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '[D', ':PrevDiagnosticCycle', opts)