diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..926ccaa --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +doc/tags diff --git a/README.md b/README.md index a0813d2..66e8e69 100644 --- a/README.md +++ b/README.md @@ -5,79 +5,83 @@ Supports all your favourite languages.** ![demo](https://github.com/simrat39/rust-tools-demos/raw/master/symbols-demo.gif) -### Prerequisites +## Prerequisites -- `neovim 0.5+` +- `neovim 0.7+` - Properly configured Neovim LSP client -### Installation +## Installation -Using `vim-plug` - -```vim -Plug 'simrat39/symbols-outline.nvim' -``` - -### Configuration - -Define a global variable `symbols_outline` as follows: - -Only add stuff that you want to override (even in nested tables), or skip this section entirely if you -want to roll with the defaults. +Using `packer.nvim` ```lua --- init.lua -vim.g.symbols_outline = { - highlight_hovered_item = true, - show_guides = true, - auto_preview = true, - position = 'right', - relative_width = true, - width = 25, - auto_close = false, - show_numbers = false, - show_relative_numbers = false, - show_symbol_details = true, - preview_bg_highlight = 'Pmenu', - keymaps = { -- These keymaps can be a string or a table for multiple keys - close = {"", "q"}, - goto_location = "", - focus_location = "o", - hover_symbol = "", - toggle_preview = "K", - rename_symbol = "r", - code_actions = "a", - }, - lsp_blacklist = {}, - symbol_blacklist = {}, - symbols = { - File = {icon = "", hl = "TSURI"}, - Module = {icon = "", hl = "TSNamespace"}, - Namespace = {icon = "", hl = "TSNamespace"}, - Package = {icon = "", hl = "TSNamespace"}, - Class = {icon = "𝓒", hl = "TSType"}, - Method = {icon = "ƒ", hl = "TSMethod"}, - Property = {icon = "", hl = "TSMethod"}, - Field = {icon = "", hl = "TSField"}, - Constructor = {icon = "", hl = "TSConstructor"}, - Enum = {icon = "ℰ", hl = "TSType"}, - Interface = {icon = "ﰮ", hl = "TSType"}, - Function = {icon = "", hl = "TSFunction"}, - Variable = {icon = "", hl = "TSConstant"}, - Constant = {icon = "", hl = "TSConstant"}, - String = {icon = "𝓐", hl = "TSString"}, - Number = {icon = "#", hl = "TSNumber"}, - Boolean = {icon = "⊨", hl = "TSBoolean"}, - Array = {icon = "", hl = "TSConstant"}, - Object = {icon = "⦿", hl = "TSType"}, - Key = {icon = "🔐", hl = "TSType"}, - Null = {icon = "NULL", hl = "TSType"}, - EnumMember = {icon = "", hl = "TSField"}, - Struct = {icon = "𝓢", hl = "TSType"}, - Event = {icon = "🗲", hl = "TSType"}, - Operator = {icon = "+", hl = "TSOperator"}, - TypeParameter = {icon = "𝙏", hl = "TSParameter"} - } +use 'simrat39/symbols-outline.nvim' +``` + +## Setup + +Put the setup call in your init.lua or any lua file that is sourced. + +```lua +require("symbols-outline").setup() +``` + +## Configuration + +Pass a table to the setup call above with your configuration options. + +```lua +local opts = { + highlight_hovered_item = true, + show_guides = true, + auto_preview = false, + position = 'right', + relative_width = true, + width = 25, + auto_close = false, + show_numbers = false, + show_relative_numbers = false, + show_symbol_details = true, + preview_bg_highlight = 'Pmenu', + keymaps = { -- These keymaps can be a string or a table for multiple keys + close = {"", "q"}, + goto_location = "", + focus_location = "o", + hover_symbol = "", + toggle_preview = "K", + rename_symbol = "r", + code_actions = "a", + }, + lsp_blacklist = {}, + symbol_blacklist = {}, + symbols = { + File = {icon = "", hl = "TSURI"}, + Module = {icon = "", hl = "TSNamespace"}, + Namespace = {icon = "", hl = "TSNamespace"}, + Package = {icon = "", hl = "TSNamespace"}, + Class = {icon = "𝓒", hl = "TSType"}, + Method = {icon = "ƒ", hl = "TSMethod"}, + Property = {icon = "", hl = "TSMethod"}, + Field = {icon = "", hl = "TSField"}, + Constructor = {icon = "", hl = "TSConstructor"}, + Enum = {icon = "ℰ", hl = "TSType"}, + Interface = {icon = "ﰮ", hl = "TSType"}, + Function = {icon = "", hl = "TSFunction"}, + Variable = {icon = "", hl = "TSConstant"}, + Constant = {icon = "", hl = "TSConstant"}, + String = {icon = "𝓐", hl = "TSString"}, + Number = {icon = "#", hl = "TSNumber"}, + Boolean = {icon = "⊨", hl = "TSBoolean"}, + Array = {icon = "", hl = "TSConstant"}, + Object = {icon = "⦿", hl = "TSType"}, + Key = {icon = "🔐", hl = "TSType"}, + Null = {icon = "NULL", hl = "TSType"}, + EnumMember = {icon = "", hl = "TSField"}, + Struct = {icon = "𝓢", hl = "TSType"}, + Event = {icon = "🗲", hl = "TSType"}, + Operator = {icon = "+", hl = "TSOperator"}, + TypeParameter = {icon = "𝙏", hl = "TSParameter"} + } } ``` @@ -89,7 +93,7 @@ vim.g.symbols_outline = { | relative_width | Whether width of window is set relative to existing windows | boolean | true | | width | Width of window (as a % or columns based on `relative_width`) | int | 25 | | auto_close | Whether to automatically close the window after selection | boolean | false | -| auto_preview | Show a preview of the code on hover | boolean | true | +| auto_preview | Show a preview of the code on hover | boolean | false | | show_numbers | Shows numbers with the outline | boolean | false | | show_relative_numbers | Shows relative numbers with the outline | boolean | false | | show_symbol_details | Shows extra details with the symbols (lsp dependent) | boolean | true | @@ -100,7 +104,7 @@ vim.g.symbols_outline = { | lsp_blacklist | Which lsp clients to ignore | table (array) | {} | | symbol_blacklist | Which symbols to ignore ([possible values](./lua/symbols-outline/symbols.lua)) | table (array) | {} | -### Commands +## Commands | Command | Description | | ---------------------- | ---------------------- | @@ -108,7 +112,7 @@ vim.g.symbols_outline = { | `:SymbolsOutlineOpen` | Open symbols outline | | `:SymbolsOutlineClose` | Close symbols outline | -### Default keymaps +## Default keymaps | Key | Action | | ---------- | -------------------------------------------------- | @@ -121,7 +125,7 @@ vim.g.symbols_outline = { | a | Code actions | | ? | Show help message | -### Highlights +## Highlights | Highlight | Purpose | | ----------------------- | -------------------------------------- | diff --git a/lua/symbols-outline.lua b/lua/symbols-outline.lua index bf253d1..40bbe54 100644 --- a/lua/symbols-outline.lua +++ b/lua/symbols-outline.lua @@ -1,26 +1,52 @@ -local vim = vim - local parser = require 'symbols-outline.parser' local providers = require 'symbols-outline.providers.init' local ui = require 'symbols-outline.ui' local writer = require 'symbols-outline.writer' local config = require 'symbols-outline.config' local utils = require 'symbols-outline.utils.init' -local view = require 'symbols-outline.view' +local View = require 'symbols-outline.view' local M = {} local function setup_global_autocmd() if config.options.highlight_hovered_item then - vim.cmd "au CursorHold * :lua require('symbols-outline')._highlight_current_item()" + vim.api.nvim_create_autocmd('CursorHold', { + pattern = '*', + callback = function() + M._highlight_current_item(nil) + end, + }) end + + vim.api.nvim_create_autocmd({ + 'InsertLeave', + 'WinEnter', + 'BufEnter', + 'BufWinEnter', + 'TabEnter', + 'BufWritePost', + }, { + pattern = '*', + callback = M._refresh, + }) + + vim.api.nvim_create_autocmd('WinEnter', { + pattern = '*', + callback = require('symbols-outline.preview').close, + }) end local function setup_buffer_autocmd() if config.options.auto_preview then - vim.cmd "au CursorHold lua require'symbols-outline.preview'.show()" + vim.api.nvim_create_autocmd('CursorHold', { + buffer = 0, + callback = require('symbols-outline.preview').show, + }) else - vim.cmd "au CursorMoved lua require'symbols-outline.preview'.close()" + vim.api.nvim_create_autocmd('CursorMoved', { + buffer = 0, + callback = require('symbols-outline.preview').close, + }) end end @@ -29,18 +55,15 @@ end ------------------------- M.state = { outline_items = {}, - flattened_outline_items = {}, - outline_win = nil, - outline_buf = nil, code_win = 0, } local function wipe_state() - M.state = { outline_items = {}, flattened_outline_items = {}, code_win = 0 } + M.state = { outline_items = {}, code_win = 0 } end local function __refresh() - if M.state.outline_buf ~= nil then + if M.view:is_open() then local function refresh_handler(response) if response == nil or type(response) ~= 'table' then return @@ -50,9 +73,8 @@ local function __refresh() M.state.code_win = vim.api.nvim_get_current_win() M.state.outline_items = items - M.state.flattened_outline_items = parser.flatten(items) - writer.parse_and_write(M.state.outline_buf, M.state.flattened_outline_items) + writer.parse_and_write(M.view.bufnr, M.state.outline_items) end providers.request_symbols(refresh_handler) @@ -61,10 +83,13 @@ end M._refresh = utils.debounce(__refresh, 100) -function M._goto_location(change_focus) - local current_line = vim.api.nvim_win_get_cursor(M.state.outline_win)[1] - local node = M.state.flattened_outline_items[current_line] - vim.api.nvim_win_set_cursor(M.state.code_win, { node.line + 1, node.character }) +local function goto_location(change_focus) + local current_line = vim.api.nvim_win_get_cursor(M.view.winnr)[1] + local node = M.state.outline_items[current_line] + vim.api.nvim_win_set_cursor( + M.state.code_win, + { node.line + 1, node.character } + ) if change_focus then vim.fn.win_gotoid(M.state.code_win) end @@ -76,11 +101,14 @@ end function M._highlight_current_item(winnr) local has_provider = providers.has_provider() - local is_current_buffer_the_outline = M.state.outline_buf == vim.api.nvim_get_current_buf() + local is_current_buffer_the_outline = M.view.bufnr + == vim.api.nvim_get_current_buf() - local doesnt_have_outline_buf = not M.state.outline_buf + local doesnt_have_outline_buf = not M.view.bufnr - local should_exit = not has_provider or doesnt_have_outline_buf or is_current_buffer_the_outline + local should_exit = not has_provider + or doesnt_have_outline_buf + or is_current_buffer_the_outline -- Make a special case if we have a window number -- Because we might use this to manually focus so we dont want to quit this @@ -98,18 +126,25 @@ function M._highlight_current_item(winnr) local hovered_line = vim.api.nvim_win_get_cursor(win)[1] - 1 local nodes = {} - for index, value in ipairs(M.state.flattened_outline_items) do - if value.line == hovered_line or (hovered_line > value.range_start and hovered_line < value.range_end) then + for index, value in ipairs(M.state.outline_items) do + if + value.line == hovered_line + or (hovered_line > value.range_start and hovered_line < value.range_end) + then value.line_in_outline = index table.insert(nodes, value) end end -- clear old highlight - ui.clear_hover_highlight(M.state.outline_buf) + ui.clear_hover_highlight(M.view.bufnr) for _, value in ipairs(nodes) do - ui.add_hover_highlight(M.state.outline_buf, value.line_in_outline - 1, value.depth * 2) - vim.api.nvim_win_set_cursor(M.state.outline_win, { value.line_in_outline, 1 }) + ui.add_hover_highlight( + M.view.bufnr, + value.line_in_outline - 1, + value.depth * 2 + ) + vim.api.nvim_win_set_cursor(M.view.winnr, { value.line_in_outline, 1 }) end end @@ -118,21 +153,39 @@ local function setup_keymaps(bufnr) utils.nmap(bufnr, ...) end -- goto_location of symbol and focus that window - map(config.options.keymaps.goto_location, ":lua require('symbols-outline')._goto_location(true)") + map(config.options.keymaps.goto_location, function() + goto_location(true) + end) -- goto_location of symbol but stay in outline - map(config.options.keymaps.focus_location, ":lua require('symbols-outline')._goto_location(false)") + map(config.options.keymaps.focus_location, function() + goto_location(false) + end) -- hover symbol - map(config.options.keymaps.hover_symbol, ":lua require('symbols-outline.hover').show_hover()") + map( + config.options.keymaps.hover_symbol, + require('symbols-outline.hover').show_hover + ) -- preview symbol - map(config.options.keymaps.toggle_preview, ":lua require('symbols-outline.preview').toggle()") + map(config.options.keymaps.toggle_preview, require('symbols-outline.preview').toggle) -- rename symbol - map(config.options.keymaps.rename_symbol, ":lua require('symbols-outline.rename').rename()") + map( + config.options.keymaps.rename_symbol, + require('symbols-outline.rename').rename + ) -- code actions - map(config.options.keymaps.code_actions, ":lua require('symbols-outline.code_action').show_code_actions()") + map( + config.options.keymaps.code_actions, + require('symbols-outline.code_action').show_code_actions + ) -- show help - map(config.options.keymaps.show_help, ":lua require('symbols-outline.config').show_help()") + map( + config.options.keymaps.show_help, + require('symbols-outline.config').show_help + ) -- close outline - map(config.options.keymaps.close, ':bw!') + map(config.options.keymaps.close, function() + M.view:close() + end) end local function handler(response) @@ -142,49 +195,49 @@ local function handler(response) M.state.code_win = vim.api.nvim_get_current_win() - M.state.outline_buf, M.state.outline_win = view.setup_view() + M.view:setup_view() -- clear state when buffer is closed - vim.api.nvim_buf_attach(M.state.outline_buf, false, { + vim.api.nvim_buf_attach(M.view.bufnr, false, { on_detach = function(_, _) wipe_state() end, }) - setup_keymaps(M.state.outline_buf) + + setup_keymaps(M.view.bufnr) setup_buffer_autocmd() local items = parser.parse(response) M.state.outline_items = items - M.state.flattened_outline_items = parser.flatten(items) - writer.parse_and_write(M.state.outline_buf, M.state.flattened_outline_items) - ui.setup_highlights() + writer.parse_and_write(M.view.bufnr, M.state.outline_items) M._highlight_current_item(M.state.code_win) end function M.toggle_outline() - if M.state.outline_buf == nil then - M.open_outline() - else + if M.view:is_open() then M.close_outline() + else + M.open_outline() end end function M.open_outline() - if M.state.outline_buf == nil then + if not M.view:is_open() then providers.request_symbols(handler) end end function M.close_outline() - if M.state.outline_buf then - vim.api.nvim_win_close(M.state.outline_win, true) - end + M.view:close() end function M.setup(opts) config.setup(opts) + ui.setup_highlights() + + M.view = View:new() setup_global_autocmd() end diff --git a/lua/symbols-outline/code_action.lua b/lua/symbols-outline/code_action.lua index 4c7f992..72e7228 100644 --- a/lua/symbols-outline/code_action.lua +++ b/lua/symbols-outline/code_action.lua @@ -1,7 +1,6 @@ local vim = vim local main = require 'symbols-outline' -local buf_request = require('symbols-outline.utils.lsp_utils').request local M = {} @@ -21,11 +20,15 @@ end function M.show_code_actions() local current_line = vim.api.nvim_win_get_cursor(main.state.outline_win)[1] - local node = main.state.flattened_outline_items[current_line] + local node = main.state.outline_items[current_line] local params = get_action_params(node, main.state.code_win) - - buf_request(params.bufnr, 'textDocument/codeAction', params, vim.lsp.handlers['textDocument/codeAction']) + vim.lsp.buf_request( + params.bufnr, + 'textDocument/codeAction', + params, + vim.lsp.handlers['textDocument/codeAction'] + ) end return M diff --git a/lua/symbols-outline/config.lua b/lua/symbols-outline/config.lua index e61bd5e..5376b91 100644 --- a/lua/symbols-outline/config.lua +++ b/lua/symbols-outline/config.lua @@ -10,7 +10,7 @@ M.defaults = { relative_width = true, width = 25, auto_close = false, - auto_preview = true, + auto_preview = false, show_numbers = false, show_relative_numbers = false, show_symbol_details = true, diff --git a/lua/symbols-outline/hover.lua b/lua/symbols-outline/hover.lua index 52d3b34..a6e68aa 100644 --- a/lua/symbols-outline/hover.lua +++ b/lua/symbols-outline/hover.lua @@ -1,8 +1,5 @@ -local vim = vim - -local main = require 'symbols-outline' +local so = require 'symbols-outline' local util = vim.lsp.util -local buf_request = require('symbols-outline.utils.lsp_utils').request local M = {} @@ -19,24 +16,32 @@ end -- handler yoinked from the default implementation function M.show_hover() - local current_line = vim.api.nvim_win_get_cursor(main.state.outline_win)[1] - local node = main.state.flattened_outline_items[current_line] + local current_line = vim.api.nvim_win_get_cursor(so.view.winnr)[1] + local node = so.state.outline_items[current_line] - local hover_params = get_hover_params(node, main.state.code_win) + local hover_params = get_hover_params(node, so.state.code_win) - buf_request(hover_params.bufnr, 'textDocument/hover', hover_params, function(_, result, _, config) - if not (result and result.contents) then - -- return { 'No information available' } - return + vim.lsp.buf_request( + hover_params.bufnr, + 'textDocument/hover', + hover_params, +---@diagnostic disable-next-line: param-type-mismatch + function(_, result, _, config) + if not (result and result.contents) then + -- return { 'No information available' } + return + end + local markdown_lines = util.convert_input_to_markdown_lines( + result.contents + ) + markdown_lines = util.trim_empty_lines(markdown_lines) + if vim.tbl_isempty(markdown_lines) then + -- return { 'No information available' } + return + end + return util.open_floating_preview(markdown_lines, 'markdown', config) end - local markdown_lines = util.convert_input_to_markdown_lines(result.contents) - markdown_lines = util.trim_empty_lines(markdown_lines) - if vim.tbl_isempty(markdown_lines) then - -- return { 'No information available' } - return - end - return util.open_floating_preview(markdown_lines, 'markdown', config) - end) + ) end return M diff --git a/lua/symbols-outline/parser.lua b/lua/symbols-outline/parser.lua index 7b3e510..6470b9c 100644 --- a/lua/symbols-outline/parser.lua +++ b/lua/symbols-outline/parser.lua @@ -1,22 +1,14 @@ local symbols = require 'symbols-outline.symbols' local ui = require 'symbols-outline.ui' local config = require 'symbols-outline.config' +local t_utils = require 'symbols-outline.utils.table' local M = {} --- copies an array and returns it because lua usually does references -local function array_copy(t) - local ret = {} - for _, value in ipairs(t) do - table.insert(ret, value) - end - return ret -end - ---Parses result from LSP into a table of symbols ---@param result table The result from a language server. ----@param depth number The current depth of the symbol in the hierarchy. ----@param hierarchy table A table of booleans which tells if a symbols parent was the last in its group. +---@param depth number? The current depth of the symbol in the hierarchy. +---@param hierarchy table? A table of booleans which tells if a symbols parent was the last in its group. ---@return table local function parse_result(result, depth, hierarchy) local ret = {} @@ -32,10 +24,10 @@ local function parse_result(result, depth, hierarchy) -- whether this node is the last in its group local isLast = index == #result - local children = nil + local children = {} if value.children ~= nil then -- copy by value because we dont want it messing with the hir table - local child_hir = array_copy(hir) + local child_hir = t_utils.array_copy(hir) table.insert(child_hir, isLast) children = parse_result(value.children, level + 1, child_hir) end @@ -62,11 +54,15 @@ local function parse_result(result, depth, hierarchy) character = selectionRange.start.character, range_start = range.start.line, range_end = range['end'].line, - children = children, + -- children = children, depth = level, isLast = isLast, hierarchy = hir, }) + + for _, node in pairs(children) do + table.insert(ret, node) + end end end return ret @@ -131,7 +127,9 @@ function M.parse(response) end local result = client_response['result'] - if result == nil or type(result) ~= 'table' then goto continue end + if result == nil or type(result) ~= 'table' then + goto continue + end for _, value in pairs(result) do table.insert(all_results, value) @@ -142,88 +140,83 @@ function M.parse(response) local sorted = sort_result(all_results) - return parse_result(sorted) + return parse_result(sorted, nil, nil) end -function M.flatten(outline_items) - local ret = {} - for _, value in ipairs(outline_items) do - table.insert(ret, value) - if value.children ~= nil then - local inner = M.flatten(value.children) - for _, value_inner in ipairs(inner) do - table.insert(ret, value_inner) - end - end - end - return ret -end - -local function table_to_str(t) - local ret = '' - for _, value in ipairs(t) do - ret = ret .. tostring(value) - end - return ret -end - -local function str_to_table(str) - local t = {} - for i = 1, #str do - t[i] = str:sub(i, i) - end - return t -end - -function M.get_lines(flattened_outline_items) +function M.get_lines(outline_items) local lines = {} local hl_info = {} - for _, value in ipairs(flattened_outline_items) do - local line = str_to_table(string.rep(' ', value.depth)) + + for node_line, node in ipairs(outline_items) do + local line = t_utils.str_to_table(string.rep(' ', node.depth)) + local running_length = 1 + + local function add_guide_hl(from, to) + table.insert(hl_info, { + node_line, + from, + to, + 'SymbolsOutlineConnector', + }) + end if config.options.show_guides then -- makes the guides + for index, _ in ipairs(line) do -- all items start with a space (or two) if index == 1 then line[index] = ' ' - -- if index is last, add a bottom marker if current item is last, + -- i f index is last, add a bottom marker if current item is last, -- else add a middle marker elseif index == #line then - if value.isLast then + if node.isLast then line[index] = ui.markers.bottom + add_guide_hl( + running_length, + running_length + vim.fn.strlen(ui.markers.bottom) - 1 + ) else line[index] = ui.markers.middle + add_guide_hl( + running_length, + running_length + vim.fn.strlen(ui.markers.middle) - 1 + ) end -- else if the parent was not the last in its group, add a -- vertical marker because there are items under us and we need -- to point to those - elseif not value.hierarchy[index] then + elseif not node.hierarchy[index] then line[index] = ui.markers.vertical + add_guide_hl( + running_length, + running_length + vim.fn.strlen(ui.markers.vertical) - 1 + ) end + + line[index] = line[index] .. ' ' + + running_length = running_length + vim.fn.strlen(line[index]) end end - local final_prefix = {} - -- Add 1 space between the guides - for _, v in ipairs(line) do - table.insert(final_prefix, v) - table.insert(final_prefix, ' ') - end + local final_prefix = line + + local string_prefix = t_utils.table_to_str(final_prefix) + + table.insert(lines, string_prefix .. node.icon .. ' ' .. node.name) - local string_prefix = table_to_str(final_prefix) local hl_start = #string_prefix - local hl_end = #string_prefix + #value.icon - table.insert(lines, string_prefix .. value.icon .. ' ' .. value.name) - hl_type = config.options.symbols[symbols.kinds[value.kind]].hl - table.insert(hl_info, { hl_start, hl_end, hl_type }) + local hl_end = #string_prefix + #node.icon + local hl_type = config.options.symbols[symbols.kinds[node.kind]].hl + table.insert(hl_info, { node_line, hl_start, hl_end, hl_type }) end return lines, hl_info end -function M.get_details(flattened_outline_items) +function M.get_details(outline_items) local lines = {} - for _, value in ipairs(flattened_outline_items) do + for _, value in ipairs(outline_items) do table.insert(lines, value.detail or '') end return lines diff --git a/lua/symbols-outline/preview.lua b/lua/symbols-outline/preview.lua index 04302d7..92556c2 100644 --- a/lua/symbols-outline/preview.lua +++ b/lua/symbols-outline/preview.lua @@ -1,7 +1,5 @@ -local vim = vim -local main = require 'symbols-outline' +local so = require 'symbols-outline' local config = require 'symbols-outline.config' -local buf_request = require('symbols-outline.utils.lsp_utils').request local M = {} @@ -14,21 +12,21 @@ local state = { local function is_current_win_outline() local curwin = vim.api.nvim_get_current_win() - return curwin == main.state.outline_win + return curwin == so.view.winnr end local function has_code_win() - local isWinValid = vim.api.nvim_win_is_valid(main.state.code_win) + local isWinValid = vim.api.nvim_win_is_valid(so.state.code_win) if not isWinValid then return false end - local bufnr = vim.api.nvim_win_get_buf(main.state.code_win) + local bufnr = vim.api.nvim_win_get_buf(so.state.code_win) local isBufValid = vim.api.nvim_buf_is_valid(bufnr) return isBufValid end local function get_offset() - local outline_winnr = main.state.outline_win + local outline_winnr = so.view.winnr local width = 53 local height = 0 @@ -50,13 +48,13 @@ local function get_height() end local function get_hovered_node() - local hovered_line = vim.api.nvim_win_get_cursor(main.state.outline_win)[1] - local node = main.state.flattened_outline_items[hovered_line] + local hovered_line = vim.api.nvim_win_get_cursor(so.view.winnr)[1] + local node = so.state.outline_items[hovered_line] return node end local function update_preview(code_buf) - code_buf = code_buf or vim.api.nvim_win_get_buf(main.state.code_win) + code_buf = code_buf or vim.api.nvim_win_get_buf(so.state.code_win) local node = get_hovered_node() if not node then @@ -66,12 +64,15 @@ local function update_preview(code_buf) if state.preview_buf ~= nil then vim.api.nvim_buf_set_lines(state.preview_buf, 0, -1, 0, lines) - vim.api.nvim_win_set_cursor(state.preview_win, { node.line + 1, node.character }) + vim.api.nvim_win_set_cursor( + state.preview_win, + { node.line + 1, node.character } + ) end end local function setup_preview_buf() - local code_buf = vim.api.nvim_win_get_buf(main.state.code_win) + local code_buf = vim.api.nvim_win_get_buf(so.state.code_win) local ft = vim.api.nvim_buf_get_option(code_buf, 'filetype') local function treesitter_attach() @@ -111,7 +112,7 @@ local function update_hover() end local provider = _G._symbols_outline_current_provider - local params = get_hover_params(node, main.state.code_win) + local params = get_hover_params(node, so.state.code_win) provider.hover_info(params.bufnr, params, function(err, result) if err then @@ -119,14 +120,20 @@ local function update_hover() end local markdown_lines = {} if result ~= nil then - markdown_lines = vim.lsp.util.convert_input_to_markdown_lines(result.contents) + markdown_lines = vim.lsp.util.convert_input_to_markdown_lines( + result.contents + ) end markdown_lines = vim.lsp.util.trim_empty_lines(markdown_lines) if vim.tbl_isempty(markdown_lines) then markdown_lines = { '###No info available!' } end - markdown_lines = vim.lsp.util.stylize_markdown(state.hover_buf, markdown_lines, {}) + markdown_lines = vim.lsp.util.stylize_markdown( + state.hover_buf, + markdown_lines, + {} + ) if state.hover_buf ~= nil then vim.api.nvim_buf_set_lines(state.hover_buf, 0, -1, 0, markdown_lines) @@ -138,7 +145,7 @@ local function setup_hover_buf() if not has_code_win() then return end - local code_buf = vim.api.nvim_win_get_buf(main.state.code_win) + local code_buf = vim.api.nvim_win_get_buf(so.state.code_win) local ft = vim.api.nvim_buf_get_option(code_buf, 'filetype') vim.api.nvim_buf_set_option(state.hover_buf, 'syntax', ft) vim.api.nvim_buf_set_option(state.hover_buf, 'bufhidden', 'delete') @@ -219,10 +226,14 @@ end function M.close() if has_code_win() then - if state.preview_win ~= nil and vim.api.nvim_win_is_valid(state.preview_win) then + if + state.preview_win ~= nil and vim.api.nvim_win_is_valid(state.preview_win) + then vim.api.nvim_win_close(state.preview_win, true) end - if state.hover_win ~= nil and vim.api.nvim_win_is_valid(state.hover_win) then + if + state.hover_win ~= nil and vim.api.nvim_win_is_valid(state.hover_win) + then vim.api.nvim_win_close(state.hover_win, true) end end diff --git a/lua/symbols-outline/providers/coc.lua b/lua/symbols-outline/providers/coc.lua index 7bc3abc..1ff7594 100644 --- a/lua/symbols-outline/providers/coc.lua +++ b/lua/symbols-outline/providers/coc.lua @@ -15,7 +15,12 @@ function M.should_use_provider(_) end function M.hover_info(_, _, on_info) - on_info(nil, { contents = { kind = 'markdown', contents = { 'No extra information availaible!' } } }) + on_info(nil, { + contents = { + kind = 'markdown', + contents = { 'No extra information availaible!' }, + }, + }) end ---@param on_symbols function diff --git a/lua/symbols-outline/providers/jsx.lua b/lua/symbols-outline/providers/jsx.lua index 626b6ae..5ef2dd2 100644 --- a/lua/symbols-outline/providers/jsx.lua +++ b/lua/symbols-outline/providers/jsx.lua @@ -1,24 +1,33 @@ local M = {} -local parsers = require("nvim-treesitter.parsers") +local parsers = require 'nvim-treesitter.parsers' local SYMBOL_COMPONENT = 27 local SYMBOL_FRAGMENT = 28 function M.should_use_provider(bufnr) - local ft = vim.api.nvim_buf_get_option(bufnr, 'ft') + local ft = vim.api.nvim_buf_get_option(bufnr, 'ft') - return string.match(ft, 'typescriptreact') or string.match(ft, 'javascriptreact') + return string.match(ft, 'typescriptreact') + or string.match(ft, 'javascriptreact') end function M.hover_info(_, _, on_info) - on_info(nil, { contents = { kind = 'nvim-lsp-jsx', contents = { 'No extra information availaible!' } } }) + on_info( + nil, + { + contents = { + kind = 'nvim-lsp-jsx', + contents = { 'No extra information availaible!' }, + }, + } + ) end local function get_open_tag(node) - if node:type() == "jsx_element" then - for _, outer in ipairs(node:field("open_tag")) do - if outer:type() == "jsx_opening_element" then + if node:type() == 'jsx_element' then + for _, outer in ipairs(node:field 'open_tag') do + if outer:type() == 'jsx_opening_element' then return outer end end @@ -30,14 +39,21 @@ end local function jsx_node_detail(node, buf) node = get_open_tag(node) or node - local param_nodes = node:field("attribute") - if #param_nodes == 0 then return nil end + local param_nodes = node:field 'attribute' + if #param_nodes == 0 then + return nil + end - local res = '{ ' .. table.concat(vim.tbl_map(function (el) - local a, b, c, d = el:range() - local text = vim.api.nvim_buf_get_text(buf, a, b, c, d, {}) - return text[1] - end, param_nodes), ' ') .. ' }' + local res = '{ ' + .. table.concat( + vim.tbl_map(function(el) + local a, b, c, d = el:range() + local text = vim.api.nvim_buf_get_text(buf, a, b, c, d, {}) + return text[1] + end, param_nodes), + ' ' + ) + .. ' }' return res end @@ -47,7 +63,7 @@ local function jsx_node_tagname(node, buf) local identifier = nil - for _, val in ipairs(tagnode:field('name')) do + for _, val in ipairs(tagnode:field 'name') do if val:type() == 'identifier' then identifier = val end @@ -62,28 +78,37 @@ local function jsx_node_tagname(node, buf) end local function convert_ts(child, children, bufnr) - local is_frag = (child:type() == 'jsx_fragment') + local is_frag = (child:type() == 'jsx_fragment') - local a, b, c, d = child:range() - local range = { start = { line = a, character = b }, ['end'] = { line = c, character = d } } + local a, b, c, d = child:range() + local range = { + start = { line = a, character = b }, + ['end'] = { line = c, character = d }, + } - local converted = { - name = (not is_frag and (jsx_node_tagname(child, bufnr) or '')) or 'fragment', - children = (#children > 0 and children) or nil, - kind = (is_frag and SYMBOL_FRAGMENT) or SYMBOL_COMPONENT, - detail = jsx_node_detail(child, bufnr), - range = range, - selectionRange = range - } - - return converted + local converted = { + name = (not is_frag and (jsx_node_tagname(child, bufnr) or '')) + or 'fragment', + children = (#children > 0 and children) or nil, + kind = (is_frag and SYMBOL_FRAGMENT) or SYMBOL_COMPONENT, + detail = jsx_node_detail(child, bufnr), + range = range, + selectionRange = range, + } + + return converted end local function parse_ts(root, children, bufnr) children = children or {} for child in root:iter_children() do - if vim.tbl_contains({ 'jsx_element', 'jsx_self_closing_element' }, child:type()) then + if + vim.tbl_contains( + { 'jsx_element', 'jsx_self_closing_element' }, + child:type() + ) + then local new_children = {} parse_ts(child, new_children, bufnr) @@ -105,7 +130,7 @@ function M.request_symbols(on_symbols) local symbols = parse_ts(root, nil, bufnr) -- local symbols = convert_ts(ctree) - on_symbols({ [1000000] = { result = symbols }}) + on_symbols { [1000000] = { result = symbols } } end return M diff --git a/lua/symbols-outline/providers/markdown.lua b/lua/symbols-outline/providers/markdown.lua index f93fe63..1123425 100644 --- a/lua/symbols-outline/providers/markdown.lua +++ b/lua/symbols-outline/providers/markdown.lua @@ -8,7 +8,15 @@ function M.should_use_provider(bufnr) end function M.hover_info(_, _, on_info) - on_info(nil, { contents = { kind = 'markdown', contents = { 'No extra information availaible!' } } }) + on_info( + nil, + { + contents = { + kind = 'markdown', + contents = { 'No extra information availaible!' }, + }, + } + ) end ---@param on_symbols function diff --git a/lua/symbols-outline/providers/nvim-lsp.lua b/lua/symbols-outline/providers/nvim-lsp.lua index 447a8e4..cd2c544 100644 --- a/lua/symbols-outline/providers/nvim-lsp.lua +++ b/lua/symbols-outline/providers/nvim-lsp.lua @@ -23,7 +23,15 @@ function M.hover_info(bufnr, params, on_info) end if not used_client then - on_info(nil, { contents = { kind = 'markdown', content = { 'No extra information availaible!' } } }) + on_info( + nil, + { + contents = { + kind = 'markdown', + content = { 'No extra information availaible!' }, + }, + } + ) end used_client.request('textDocument/hover', params, on_info, bufnr) @@ -51,7 +59,12 @@ end ---@param on_symbols function function M.request_symbols(on_symbols) - vim.lsp.buf_request_all(0, 'textDocument/documentSymbol', getParams(), on_symbols) + vim.lsp.buf_request_all( + 0, + 'textDocument/documentSymbol', + getParams(), + on_symbols + ) end return M diff --git a/lua/symbols-outline/rename.lua b/lua/symbols-outline/rename.lua index 8bc5044..1378eee 100644 --- a/lua/symbols-outline/rename.lua +++ b/lua/symbols-outline/rename.lua @@ -1,7 +1,4 @@ -local vim = vim - -local main = require 'symbols-outline' -local buf_request = require('symbols-outline.utils.lsp_utils').request +local so = require 'symbols-outline' local M = {} @@ -17,10 +14,10 @@ local function get_rename_params(node, winnr) end function M.rename() - local current_line = vim.api.nvim_win_get_cursor(main.state.outline_win)[1] - local node = main.state.flattened_outline_items[current_line] + local current_line = vim.api.nvim_win_get_cursor(so.view.winnr)[1] + local node = so.state.outline_items[current_line] - local params = get_rename_params(node, main.state.code_win) + local params = get_rename_params(node, so.state.code_win) local new_name = vim.fn.input('New Name: ', node.name) if not new_name or new_name == '' or new_name == node.name then @@ -29,12 +26,17 @@ function M.rename() params.newName = new_name - buf_request(params.bufnr, 'textDocument/rename', params, function(_, result, ctx) - if result ~= nil then - local client = vim.lsp.get_client_by_id(ctx.client_id) - vim.lsp.util.apply_workspace_edit(result, client.offset_encoding) + vim.lsp.buf_request( + params.bufnr, + 'textDocument/rename', + params, + function(_, result, ctx) + if result ~= nil then + local client = vim.lsp.get_client_by_id(ctx.client_id) + vim.lsp.util.apply_workspace_edit(result, client.offset_encoding) + end end - end) + ) end return M diff --git a/lua/symbols-outline/ui.lua b/lua/symbols-outline/ui.lua index f46e932..325f901 100644 --- a/lua/symbols-outline/ui.lua +++ b/lua/symbols-outline/ui.lua @@ -1,6 +1,3 @@ -local vim = vim -local config = require 'symbols-outline.config' -local symbol_kinds = require('symbols-outline.symbols').kinds local M = {} M.markers = { @@ -17,38 +14,45 @@ function M.clear_hover_highlight(bufnr) end function M.add_hover_highlight(bufnr, line, col_start) - vim.api.nvim_buf_add_highlight(bufnr, M.hovered_hl_ns, 'FocusedSymbol', line, col_start, -1) -end - -local function highlight_text(name, text, hl_group) - vim.cmd(string.format('syn match %s /%s/', name, text)) - vim.cmd(string.format('hi def link %s %s', name, hl_group)) + vim.api.nvim_buf_add_highlight( + bufnr, + M.hovered_hl_ns, + 'FocusedSymbol', + line, + col_start, + -1 + ) end function M.setup_highlights() -- Setup the FocusedSymbol highlight group if it hasn't been done already by -- a theme or manually set if vim.fn.hlexists 'FocusedSymbol' == 0 then - vim.cmd 'hi FocusedSymbol term=italic,bold cterm=italic ctermbg=yellow ctermfg=darkblue gui=bold,italic guibg=yellow guifg=darkblue' + local cline_hl = vim.api.nvim_get_hl_by_name('CursorLine', true) + local string_hl = vim.api.nvim_get_hl_by_name('String', true) + + vim.api.nvim_set_hl( + 0, + 'FocusedSymbol', + { bg = cline_hl.background, fg = string_hl.foreground } + ) end -- Some colorschemes do some funky things with the comment highlight, most -- notably making them italic, which messes up the outline connector. Fix -- this by copying the foreground color from the comment hl into a new -- highlight. - local comment_fg_gui = vim.fn.synIDattr(vim.fn.synIDtrans(vim.fn.hlID 'Comment'), 'fg', 'gui') + local comment_fg_gui = vim.fn.synIDattr( + vim.fn.synIDtrans(vim.fn.hlID 'Comment'), + 'fg', + 'gui' + ) if vim.fn.hlexists 'SymbolsOutlineConnector' == 0 then - vim.cmd(string.format('hi SymbolsOutlineConnector guifg=%s', comment_fg_gui)) + vim.cmd( + string.format('hi SymbolsOutlineConnector guifg=%s', comment_fg_gui) + ) end - - local symbols = config.options.symbols - - -- markers - highlight_text('marker_middle', M.markers.middle, 'SymbolsOutlineConnector') - highlight_text('marker_vertical', M.markers.vertical, 'SymbolsOutlineConnector') - highlight_text('markers_horizontal', M.markers.horizontal, 'SymbolsOutlineConnector') - highlight_text('markers_bottom', M.markers.bottom, 'SymbolsOutlineConnector') end return M diff --git a/lua/symbols-outline/utils/init.lua b/lua/symbols-outline/utils/init.lua index 0033c8f..29465dd 100644 --- a/lua/symbols-outline/utils/init.lua +++ b/lua/symbols-outline/utils/init.lua @@ -2,14 +2,19 @@ local M = {} ---maps the table|string of keys to the action ---@param keys table|string ----@param action string +---@param action function|string function M.nmap(bufnr, keys, action) if type(keys) == 'string' then keys = { keys } end - for _, value in ipairs(keys) do - vim.api.nvim_buf_set_keymap(bufnr, 'n', value, action, { silent = true, noremap = true }) + for _, lhs in ipairs(keys) do + vim.keymap.set( + 'n', + lhs, + action, + { silent = true, noremap = true, buffer = bufnr } + ) end end diff --git a/lua/symbols-outline/utils/lsp_utils.lua b/lua/symbols-outline/utils/lsp_utils.lua index 0fc15ba..a0fe87c 100644 --- a/lua/symbols-outline/utils/lsp_utils.lua +++ b/lua/symbols-outline/utils/lsp_utils.lua @@ -1,32 +1,5 @@ -local vim = vim - local M = {} --- callback args changed in Neovim 0.5.1/0.6. See: --- https://github.com/neovim/neovim/pull/15504 -local function mk_handler(fn) - return function(...) - local config_or_client_id = select(4, ...) - local is_new = type(config_or_client_id) ~= 'number' - if is_new then - fn(...) - else - local err = select(1, ...) - local method = select(2, ...) - local result = select(3, ...) - local client_id = select(4, ...) - local bufnr = select(5, ...) - local config = select(6, ...) - fn(err, result, { method = method, client_id = client_id, bufnr = bufnr }, config) - end - end -end - --- from mfussenegger/nvim-lsp-compl@29a81f3 -function M.request(bufnr, method, params, handler) - return vim.lsp.buf_request(bufnr, method, params, mk_handler(handler)) -end - function M.is_buf_attached_to_lsp(bufnr) local clients = vim.lsp.buf_get_clients(bufnr or 0) return clients ~= nil and #clients > 0 diff --git a/lua/symbols-outline/utils/table.lua b/lua/symbols-outline/utils/table.lua new file mode 100644 index 0000000..93247d1 --- /dev/null +++ b/lua/symbols-outline/utils/table.lua @@ -0,0 +1,31 @@ +local M = {} + +function M.table_to_str(t) + local ret = '' + for _, value in ipairs(t) do + ret = ret .. tostring(value) + end + return ret +end + +function M.str_to_table(str) + local t = {} + for i = 1, #str do + t[i] = str:sub(i, i) + end + return t +end + +--- Copies an array and returns it because lua usually does references +---@generic T +---@param t T[] +---@return T[] +function M.array_copy(t) + local ret = {} + for _, value in ipairs(t) do + table.insert(ret, value) + end + return ret +end + +return M diff --git a/lua/symbols-outline/view.lua b/lua/symbols-outline/view.lua index 4d3f4a0..0202ac6 100644 --- a/lua/symbols-outline/view.lua +++ b/lua/symbols-outline/view.lua @@ -1,43 +1,57 @@ local config = require 'symbols-outline.config' -local M = {} +local View = {} + +function View:new() + return setmetatable({ bufnr = nil, winnr = nil }, { __index = View }) +end ---creates the outline window and sets it up ----@return string bufnr ----@return string bufnr -function M.setup_view() +function View:setup_view() -- create a scratch unlisted buffer - local bufnr = vim.api.nvim_create_buf(false, true) + self.bufnr = vim.api.nvim_create_buf(false, true) -- delete buffer when window is closed / buffer is hidden - vim.api.nvim_buf_set_option(bufnr, 'bufhidden', 'delete') + vim.api.nvim_buf_set_option(self.bufnr, 'bufhidden', 'delete') -- create a split vim.cmd(config.get_split_command()) -- resize to a % of the current window size vim.cmd('vertical resize ' .. config.get_window_width()) -- get current (outline) window and attach our buffer to it - local winnr = vim.api.nvim_get_current_win() - vim.api.nvim_win_set_buf(winnr, bufnr) + self.winnr = vim.api.nvim_get_current_win() + vim.api.nvim_win_set_buf(self.winnr, self.bufnr) -- window stuff - vim.api.nvim_win_set_option(winnr, 'number', false) - vim.api.nvim_win_set_option(winnr, 'relativenumber', false) - vim.api.nvim_win_set_option(winnr, 'winfixwidth', true) + vim.api.nvim_win_set_option(self.winnr, 'number', false) + vim.api.nvim_win_set_option(self.winnr, 'relativenumber', false) + vim.api.nvim_win_set_option(self.winnr, 'winfixwidth', true) + vim.api.nvim_win_set_option(self.winnr, 'list', false) -- buffer stuff - vim.api.nvim_buf_set_name(bufnr, 'OUTLINE') - vim.api.nvim_buf_set_option(bufnr, 'filetype', 'Outline') - vim.api.nvim_buf_set_option(bufnr, 'modifiable', false) + vim.api.nvim_buf_set_name(self.bufnr, 'OUTLINE') + vim.api.nvim_buf_set_option(self.bufnr, 'filetype', 'Outline') + vim.api.nvim_buf_set_option(self.bufnr, 'modifiable', false) if config.options.show_numbers or config.options.show_relative_numbers then - vim.api.nvim_win_set_option(winnr, 'nu', true) + vim.api.nvim_win_set_option(self.winnr, 'nu', true) end if config.options.show_relative_numbers then - vim.api.nvim_win_set_option(winnr, 'rnu', true) + vim.api.nvim_win_set_option(self.winnr, 'rnu', true) end - - return bufnr, winnr end -return M +function View:close() + vim.api.nvim_win_close(self.winnr, true) + self.winnr = nil + self.bufnr = nil +end + +function View:is_open() + return self.winnr + and self.bufnr + and vim.api.nvim_buf_is_valid(self.bufnr) + and vim.api.nvim_win_is_valid(self.winnr) +end + +return View diff --git a/lua/symbols-outline/writer.lua b/lua/symbols-outline/writer.lua index c9afd3a..c25c64e 100644 --- a/lua/symbols-outline/writer.lua +++ b/lua/symbols-outline/writer.lua @@ -1,5 +1,3 @@ -local vim = vim - local parser = require 'symbols-outline.parser' local config = require 'symbols-outline.config' @@ -24,9 +22,16 @@ function M.write_outline(bufnr, lines) end function M.add_highlights(bufnr, hl_info) - for line, line_hl in ipairs(hl_info) do - hl_start, hl_end, hl_type = unpack(line_hl) - vim.api.nvim_buf_add_highlight(bufnr, hlns, hl_type, line - 1, hl_start, hl_end) + for _, line_hl in ipairs(hl_info) do + local line, hl_start, hl_end, hl_type = unpack(line_hl) + vim.api.nvim_buf_add_highlight( + bufnr, + hlns, + hl_type, + line - 1, + hl_start, + hl_end + ) end end @@ -55,12 +60,12 @@ end -- runs the whole writing routine where the text is cleared, new data is parsed -- and then written -function M.parse_and_write(bufnr, flattened_outline_items) - local lines, hl_info = parser.get_lines(flattened_outline_items) +function M.parse_and_write(bufnr, outline_items) + local lines, hl_info = parser.get_lines(outline_items) M.write_outline(bufnr, lines) clear_virt_text(bufnr) - local details = parser.get_details(flattened_outline_items) + local details = parser.get_details(outline_items) M.add_highlights(bufnr, hl_info) M.write_details(bufnr, details) end diff --git a/plugin/symbols-outline.vim b/plugin/symbols-outline.vim index f8456c9..be0f1b9 100644 --- a/plugin/symbols-outline.vim +++ b/plugin/symbols-outline.vim @@ -1,17 +1,3 @@ -if exists('g:loaded_symbols_outline') - finish -endif -let g:loaded_symbols_outline = 1 - -if exists('g:symbols_outline') - call luaeval('require"symbols-outline".setup(_A[1])', [g:symbols_outline]) -else - call luaeval('require"symbols-outline".setup()') -endif - command! SymbolsOutline :lua require'symbols-outline'.toggle_outline() command! SymbolsOutlineOpen :lua require'symbols-outline'.open_outline() command! SymbolsOutlineClose :lua require'symbols-outline'.close_outline() - -au InsertLeave,WinEnter,BufEnter,BufWinEnter,TabEnter,BufWritePost * :lua require('symbols-outline')._refresh() -au WinEnter * lua require'symbols-outline.preview'.close() diff --git a/stylua.toml b/stylua.toml index 237e120..63ea177 100644 --- a/stylua.toml +++ b/stylua.toml @@ -1,4 +1,4 @@ -column_width = 120 +column_width = 80 line_endings = 'Unix' indent_type = 'Spaces' indent_width = 2