MAJOR: Project rename and preparation for v1.0.0

I hope I haven't missed any for the renames!
This commit is contained in:
hedy
2023-11-12 12:40:32 +08:00
parent 2746f6f423
commit 965a3842c8
23 changed files with 141 additions and 118 deletions

View File

@@ -0,0 +1,14 @@
local main = require 'outline'
local M = {}
function M.show_code_actions()
-- keep the cursor info in outline and jump back (or not jump back?)
local winnr, pos = vim.api.nvim_get_current_win(), vim.api.nvim_win_get_cursor(0)
main._goto_location(true)
vim.lsp.buf.code_action()
vim.fn.win_gotoid(winnr)
vim.api.nvim_win_set_cursor(winnr, pos)
end
return M

225
lua/outline/config.lua Normal file
View File

@@ -0,0 +1,225 @@
local vim = vim
local M = {}
M.defaults = {
guides = {
enabled = true,
markers = {
bottom = '',
middle = '',
vertical = '',
horizontal = '',
},
},
outline_items = {
show_symbol_details = true,
show_symbol_lineno = false,
highlight_hovered_item = true,
},
outline_window = {
position = 'right',
split_command = nil,
width = 25,
relative_width = true,
wrap = false,
focus_on_open = true,
auto_close = false,
auto_goto = false,
show_numbers = false,
show_relative_numbers = false,
show_cursorline = true,
hide_cursor = false,
winhl = "OutlineDetails:Comment,OutlineLineno:LineNr",
},
preview_window = {
auto_preview = false,
width = 50,
min_width = 50,
relative_width = true,
border = 'single',
open_hover_on_preview = true,
winhl = '',
winblend = 0,
},
symbol_folding = {
autofold_depth = nil,
auto_unfold_hover = true,
markers = { '', '' },
},
keymaps = {
show_help = '?',
close = { '<Esc>', 'q' },
goto_location = '<Cr>',
peek_location = 'o',
goto_and_close = '<S-Cr>',
restore_location = "<C-g>",
hover_symbol = '<C-space>',
toggle_preview = 'K',
rename_symbol = 'r',
code_actions = 'a',
fold = 'h',
fold_toggle = '<tab>',
fold_toggle_all = '<S-tab>',
unfold = 'l',
fold_all = 'W',
unfold_all = 'E',
fold_reset = 'R',
down_and_goto = '<C-j>',
up_and_goto = '<C-k>',
},
providers = {
lsp = {
blacklist_clients = {},
},
},
symbols = {
blacklist = {},
icon_source = nil,
icon_fetcher = nil,
icons = {
File = { icon = '󰈔', hl = '@text.uri' },
Module = { icon = '󰆧', hl = '@namespace' },
Namespace = { icon = '󰅪', hl = '@namespace' },
Package = { icon = '󰏗', hl = '@namespace' },
Class = { icon = '𝓒', hl = '@type' },
Method = { icon = 'ƒ', hl = '@method' },
Property = { icon = '', hl = '@method' },
Field = { icon = '󰆨', hl = '@field' },
Constructor = { icon = '', hl = '@constructor' },
Enum = { icon = '', hl = '@type' },
Interface = { icon = '󰜰', hl = '@type' },
Function = { icon = '', hl = '@function' },
Variable = { icon = '', hl = '@constant' },
Constant = { icon = '', hl = '@constant' },
String = { icon = '𝓐', hl = '@string' },
Number = { icon = '#', hl = '@number' },
Boolean = { icon = '', hl = '@boolean' },
Array = { icon = '󰅪', hl = '@constant' },
Object = { icon = '⦿', hl = '@type' },
Key = { icon = '🔐', hl = '@type' },
Null = { icon = 'NULL', hl = '@type' },
EnumMember = { icon = '', hl = '@field' },
Struct = { icon = '𝓢', hl = '@type' },
Event = { icon = '🗲', hl = '@type' },
Operator = { icon = '+', hl = '@operator' },
TypeParameter = { icon = '𝙏', hl = '@parameter' },
Component = { icon = '󰅴', hl = '@function' },
Fragment = { icon = '󰅴', hl = '@constant' },
-- ccls
TypeAlias = { icon = '', hl = '@type' },
Parameter = { icon = '', hl = '@parameter' },
StaticMethod = { icon = '', hl = '@function' },
Macro = { icon = '', hl = '@macro' },
},
},
}
M.o = {}
function M.has_numbers()
return M.o.outline_window.show_numbers or M.o.outline_window.show_relative_numbers
end
function M.get_position_navigation_direction()
if M.o.outline_window.position == 'left' then
return 'h'
else
return 'l'
end
end
function M.get_window_width()
if M.o.outline_window.relative_width then
return math.ceil(vim.o.columns * (M.o.outline_window.width / 100))
else
return M.o.outline_window.width
end
end
function M.get_preview_width()
if M.o.preview_window.relative_width then
local relative_width = math.ceil(vim.o.columns * (M.o.preview_window.width / 100))
if relative_width < M.o.preview_window.min_width then
return M.o.preview_window.min_width
else
return relative_width
end
else
return M.o.preview_window.width
end
end
function M.get_split_command()
local sc = M.o.outline_window.split_command
if sc then
return sc
end
if M.o.outline_window.position == 'left' then
return 'topleft vs'
else
return 'botright vs'
end
end
local function has_value(tab, val)
for _, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function M.is_symbol_blacklisted(kind)
if kind == nil then
return false
end
return has_value(M.o.symbols.blacklist, kind)
end
function M.is_client_blacklisted(client_id)
local client = vim.lsp.get_client_by_id(client_id)
if not client then
return false
end
return has_value(M.o.providers.lsp.blacklist_clients, client.name)
end
function M.show_help()
print 'Current keymaps:'
print(vim.inspect(M.o.keymaps))
end
function M.check_config()
if M.o.outline_window.hide_cursor and not M.o.outline_window.show_cursorline then
vim.notify("[outline.config]: hide_cursor enabled WITHOUT cursorline enabled!", vim.log.levels.ERROR)
end
end
function M.resolve_config()
local sc = M.o.outline_window.split_command
if not sc then
return
end
-- This should not be needed, nor is it failsafe. But in case user only provides
-- the, eg, "topleft", we append the ' vs'.
if not sc:find(' vs', 1, true) then
M.o.outline_window.split_command = sc..' vs'
end
end
function M.setup(options)
vim.g.symbols_outline_loaded = 1
M.o = vim.tbl_deep_extend('force', {}, M.defaults, options or {})
local guides = M.o.guides
if type(guides) == 'boolean' and guides then
M.o.guides = M.defaults.guides
end
M.check_config()
M.resolve_config()
end
return M

27
lua/outline/folding.lua Normal file
View File

@@ -0,0 +1,27 @@
local M = {}
local cfg = require 'outline.config'
M.is_foldable = function(node)
return node.children and #node.children > 0
end
local get_default_folded = function(depth)
local fold_past = cfg.o.symbol_folding.autofold_depth
if not fold_past then
return false
else
return depth >= fold_past
end
end
M.is_folded = function(node)
if node.folded ~= nil then
return node.folded
elseif node.hovered and cfg.o.symbol_folding.auto_unfold_hover then
return false
else
return get_default_folded(node.depth)
end
end
return M

48
lua/outline/hover.lua Normal file
View File

@@ -0,0 +1,48 @@
local so = require 'outline'
local cfg = require 'outline.config'
local util = vim.lsp.util
local M = {}
local function get_hover_params(node, winnr)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local fn = vim.uri_from_bufnr(bufnr)
return {
textDocument = { uri = fn },
position = { line = node.line, character = node.character },
bufnr = bufnr,
}
end
-- handler yoinked from the default implementation
function M.show_hover()
local current_line = vim.api.nvim_win_get_cursor(so.view.winnr)[1]
local node = so.state.flattened_outline_items[current_line]
local hover_params = get_hover_params(node, so.state.code_win)
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
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
end
-- FIXME
local bufnr, winnr = util.open_floating_preview(markdown_lines, 'markdown', config)
vim.api.nvim_win_set_option(winnr, 'winhighlight', cfg.o.preview_window.winhl)
end
)
end
return M

615
lua/outline/init.lua Normal file
View File

@@ -0,0 +1,615 @@
local parser = require 'outline.parser'
local providers = require 'outline.providers.init'
local ui = require 'outline.ui'
local writer = require 'outline.writer'
local cfg = require 'outline.config'
local utils = require 'outline.utils.init'
local View = require 'outline.view'
local folding = require 'outline.folding'
local M = {}
local function setup_global_autocmd()
if
cfg.o.outline_items.highlight_hovered_item or cfg.o.symbol_folding.auto_unfold_hover
then
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('outline.preview').close,
})
end
-------------------------
-- STATE
-------------------------
M.state = {
outline_items = {},
flattened_outline_items = {},
code_win = 0,
-- In case unhide_cursor was called before hide_cursor for _some_ reason,
-- this can still be used as a fallback
original_cursor = vim.o.guicursor,
}
local function wipe_state()
M.state = { outline_items = {}, flattened_outline_items = {}, code_win = 0, opts = {} }
end
local function _update_lines()
M.state.flattened_outline_items = parser.flatten(M.state.outline_items)
writer.parse_and_write(M.view.bufnr, M.state.flattened_outline_items)
end
local function _merge_items(items)
utils.merge_items_rec(
{ children = items },
{ children = M.state.outline_items }
)
end
local function __refresh()
local current_buffer_is_outline = M.view.bufnr
== vim.api.nvim_get_current_buf()
if M.view:is_open() and not current_buffer_is_outline then
local function refresh_handler(response)
if response == nil or type(response) ~= 'table' then
return
end
local items = parser.parse(response)
_merge_items(items)
M.state.code_win = vim.api.nvim_get_current_win()
_update_lines()
end
providers.request_symbols(refresh_handler)
end
end
M._refresh = utils.debounce(__refresh, 100)
function M._current_node()
local current_line = vim.api.nvim_win_get_cursor(M.view.winnr)[1]
return M.state.flattened_outline_items[current_line]
end
function M.__goto_location(change_focus)
local node = M._current_node()
vim.api.nvim_win_set_cursor(
M.state.code_win,
{ node.line + 1, node.character }
)
utils.flash_highlight(M.state.code_win, node.line + 1, true)
if change_focus then
vim.fn.win_gotoid(M.state.code_win)
end
end
-- Wraps __goto_location and handles auto_close
function M._goto_location(change_focus)
M.__goto_location(change_focus)
if change_focus and cfg.o.outline_window.auto_close then
M.close_outline()
end
end
function M._goto_and_close()
M.__goto_location(true)
M.close_outline()
end
function M._move_and_goto(direction)
local move = direction == 'down' and 1 or -1
local cur = vim.api.nvim_win_get_cursor(0)
cur[1] = cur[1] + move
pcall(vim.api.nvim_win_set_cursor, 0, cur)
M.__goto_location(false)
end
function M._toggle_fold(move_cursor, node_index)
local node = M.state.flattened_outline_items[node_index] or M._current_node()
local is_folded = folding.is_folded(node)
if folding.is_foldable(node) then
M._set_folded(not is_folded, move_cursor, node_index)
end
end
local function hide_cursor()
-- Set cursor color to CursorLine in normal mode
M.state.original_cursor = vim.o.guicursor
local cur = vim.o.guicursor:match("n.-:(.-)[-,]")
vim.opt.guicursor:append("n:"..cur.."-Cursorline")
end
local function unhide_cursor()
-- vim.opt doesn't seem to provide a way to remove last item, like a pop()
-- vim.o.guicursor = vim.o.guicursor:gsub(",n.-:.-$", "")
vim.o.guicursor = M.state.original_cursor
end
local function setup_buffer_autocmd()
if cfg.o.preview_window.auto_preview then
vim.api.nvim_create_autocmd('CursorMoved', {
buffer = 0,
callback = require('outline.preview').show,
})
else
vim.api.nvim_create_autocmd('CursorMoved', {
buffer = 0,
callback = require('outline.preview').close,
})
end
if cfg.o.outline_window.auto_goto then
vim.api.nvim_create_autocmd('CursorMoved', {
buffer = 0,
callback = function()
-- Don't use _goto_location because we don't want to auto-close
M.__goto_location(false)
end
})
end
if cfg.o.outline_window.hide_cursor then
-- Unfortunately guicursor is a global option, so we have to make sure to
-- set and unset when cursor leaves the outline window.
hide_cursor()
vim.api.nvim_create_autocmd('BufEnter', {
buffer = 0,
callback = hide_cursor
})
vim.api.nvim_create_autocmd('BufLeave', {
buffer = 0,
callback = unhide_cursor
})
end
end
function M._set_folded(folded, move_cursor, node_index)
local node = M.state.flattened_outline_items[node_index] or M._current_node()
local changed = (folded ~= folding.is_folded(node))
if folding.is_foldable(node) and changed then
node.folded = folded
if move_cursor then
vim.api.nvim_win_set_cursor(M.view.winnr, { node_index, 0 })
end
_update_lines()
elseif node.parent then
local parent_node =
M.state.flattened_outline_items[node.parent.line_in_outline]
if parent_node then
M._set_folded(
folded,
not parent_node.folded and folded,
parent_node.line_in_outline
)
end
end
end
function M._toggle_all_fold(nodes)
nodes = nodes or M.state.outline_items
local folded = true
for _, node in ipairs(nodes) do
if folding.is_foldable(node) and not folding.is_folded(node) then
folded = false
break
end
end
M._set_all_folded(not folded, nodes)
end
function M._set_all_folded(folded, nodes)
local stack = { nodes or M.state.outline_items }
while #stack > 0 do
local current_nodes = table.remove(stack, #stack)
for _, node in ipairs(current_nodes) do
node.folded = folded
if node.children then
stack[#stack + 1] = node.children
end
end
end
_update_lines()
end
function M._highlight_current_item(winnr)
local has_provider = M.has_provider()
local has_outline_open = M.view:is_open()
local current_buffer_is_outline = M.view.bufnr
== vim.api.nvim_get_current_buf()
if not has_provider then
return
end
if current_buffer_is_outline and not winnr then
-- Don't update cursor pos and content if they are navigating the outline.
-- Winnr may be given when user explicitly wants to restore location
-- (follow_cursor), or through the open handler.
return
end
if not has_outline_open and not winnr then
-- Outline not open and no code window given
return
end
local win = winnr or vim.api.nvim_get_current_win()
local hovered_line = vim.api.nvim_win_get_cursor(win)[1] - 1
local leaf_node = nil
local cb = function(value)
value.hovered = nil
if
value.line == hovered_line
or (hovered_line > value.range_start and hovered_line < value.range_end)
then
value.hovered = true
leaf_node = value
end
end
utils.items_dfs(cb, M.state.outline_items)
_update_lines()
if leaf_node then
for index, node in ipairs(M.state.flattened_outline_items) do
if node == leaf_node then
vim.api.nvim_win_set_cursor(M.view.winnr, { index, 1 })
break
end
end
end
end
local function setup_keymaps(bufnr)
local map = function(...)
utils.nmap(bufnr, ...)
end
-- goto_location of symbol and focus that window
map(cfg.o.keymaps.goto_location, function()
M._goto_location(true)
end)
-- goto_location of symbol but stay in outline
map(cfg.o.keymaps.peek_location, function()
M._goto_location(false)
end)
-- Navigate to corresponding outline location for current code location
map(cfg.o.keymaps.restore_location, M._map_follow_cursor)
-- Navigate to corresponding outline location for current code location
map(cfg.o.keymaps.goto_and_close, M._goto_and_close)
-- Move down/up in outline and peek that location in code
map(cfg.o.keymaps.down_and_goto, function()
M._move_and_goto('down')
end)
-- Move down/up in outline and peek that location in code
map(cfg.o.keymaps.up_and_goto, function()
M._move_and_goto('up')
end)
-- hover symbol
map(
cfg.o.keymaps.hover_symbol,
require('outline.hover').show_hover
)
-- preview symbol
map(
cfg.o.keymaps.toggle_preview,
require('outline.preview').toggle
)
-- rename symbol
map(
cfg.o.keymaps.rename_symbol,
require('outline.rename').rename
)
-- code actions
map(
cfg.o.keymaps.code_actions,
require('outline.code_action').show_code_actions
)
-- show help
map(
cfg.o.keymaps.show_help,
require('outline.config').show_help
)
-- close outline
map(cfg.o.keymaps.close, function()
M.view:close()
end)
-- toggle fold selection
map(cfg.o.keymaps.fold_toggle, M._toggle_fold)
-- fold selection
map(cfg.o.keymaps.fold, function()
M._set_folded(true)
end)
-- unfold selection
map(cfg.o.keymaps.unfold, function()
M._set_folded(false)
end)
-- toggle fold all
map(cfg.o.keymaps.fold_toggle_all, M._toggle_all_fold)
-- fold all
map(cfg.o.keymaps.fold_all, function()
M._set_all_folded(true)
end)
-- unfold all
map(cfg.o.keymaps.unfold_all, function()
M._set_all_folded(false)
end)
-- fold reset
map(cfg.o.keymaps.fold_reset, function()
M._set_all_folded(nil)
end)
end
local function handler(response, opts)
if response == nil or type(response) ~= 'table' or M.view:is_open() then
return
end
M.state.code_win = vim.api.nvim_get_current_win()
M.view:setup_view()
-- clear state when buffer is closed
vim.api.nvim_buf_attach(M.view.bufnr, false, {
on_detach = function(_, _)
wipe_state()
end,
})
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.view.bufnr, M.state.flattened_outline_items)
M._highlight_current_item(M.state.code_win)
if not cfg.o.outline_window.focus_on_open or (opts and not opts.focus_outline) then
vim.fn.win_gotoid(M.state.code_win)
end
end
---Set position of outline window to match cursor position in code, return
---whether the window is just newly opened (previously not open).
---@param opts table? Field `focus_outline` = `false` or `nil` means don't focus on outline window after following cursor. If opts is not provided, focus will be on outline window after following cursor.
---@return boolean ok Whether it was successful. If ok=false, either the outline window is not open or the code window cannot be found.
function M.follow_cursor(opts)
if not M.view:is_open() then
return false
end
if require('outline.preview').has_code_win() then
M._highlight_current_item(M.state.code_win)
else
return false
end
if not opts then
opts = { focus_outline = true }
end
if opts.focus_outline then
M.focus_outline()
end
return true
end
local function _cmd_follow_cursor(opts)
local fnopts = { focus_outline = true }
if opts.bang then
fnopts.focus_outline = false
end
M.follow_cursor(fnopts)
end
function M._map_follow_cursor()
if not M.follow_cursor({ focus_outline = true }) then
vim.notify(
"Code window no longer active. Try closing and reopening the outline.",
vim.log.levels.ERROR
)
end
end
---Toggle the outline window, and return whether the outline window is open
---after this operation.
---@param opts table? Table of options, @see open_outline
---@return boolean is_open Whether outline window is open
function M.toggle_outline(opts)
if M.view:is_open() then
M.close_outline()
return false
else
M.open_outline(opts)
return true
end
end
-- Used for Outline user command
local function _cmd_toggle_outline(opts)
if opts.bang then
M.toggle_outline({ focus_outline = false })
else
M.toggle_outline({ focus_outline = true })
end
end
---Open the outline window.
---@param opts table? Field focus_outline=false means don't focus on outline window after opening. If opts is not provided, focus will be on outline window after opening.
function M.open_outline(opts)
if not opts then
opts = { focus_outline = true }
end
if not M.view:is_open() then
local found = providers.request_symbols(handler, opts)
if not found then
vim.notify("[outline]: No providers found for current buffer", vim.log.levels.WARN)
-- else
-- print("Using provider ".._G._symbols_outline_current_provider.name.."...")
end
end
end
local function _cmd_open_outline(opts)
if opts.bang then
M.open_outline({ focus_outline = false })
else
M.open_outline({ focus_outline = true })
end
end
---Close the outline window.
function M.close_outline()
M.view:close()
end
---Set cursor to focus on the outline window, return whether the window is currently open..
---@return boolean is_open Whether the window is open
function M.focus_outline()
if M.view:is_open() then
vim.fn.win_gotoid(M.view.winnr)
return true
end
return false
end
---Set cursor to focus on the code window, return whether this operation was successful.
---@return boolean ok Whether it was successful. If unsuccessful, it might mean that the attached code window has been closed or is no longer valid.
function M.focus_code()
if require('outline.preview').has_code_win() then
vim.fn.win_gotoid(M.state.code_win)
return true
end
return false
end
---Toggle focus between outline and code window, returns whether it was successful.
---@return boolean ok Whether it was successful. If `ok=false`, either the outline window is not open or the code window is no longer valid.
function M.focus_toggle()
if M.view:is_open() and require('outline.preview').has_code_win() then
local winid = vim.fn.win_getid()
if winid == M.state.code_win then
vim.fn.win_gotoid(M.view.winnr)
else
vim.fn.win_gotoid(M.state.code_win)
end
return true
end
return false
end
---Whether the outline window is currently open.
---@return boolean is_open
function M.is_open()
return M.view:is_open()
end
---Display outline window status in the message area.
function M.show_status()
if M.has_provider() then
print("Current provider:")
print(' ' .. _G._symbols_outline_current_provider.name)
if M.view:is_open() then
print("Outline window is open.")
else
print("Outline window is not open.")
end
if require('outline.preview').has_code_win() then
print("Code window is active.")
else
print("Warning: code window is either closed or invalid. Please close and reopen the outline window.")
end
else
print("No providers")
end
end
---Whether there is currently an available provider.
---@return boolean has_provider
function M.has_provider()
local winid = vim.fn.win_getid()
if M.view:is_open() and winid == M.view.winnr then
return _G._symbols_outline_current_provider ~= nil
end
return providers.has_provider() and _G._symbols_outline_current_provider
end
local function setup_commands()
local cmd = function(n, c, o)
vim.api.nvim_create_user_command('Outline'..n, c, o)
end
cmd('', _cmd_toggle_outline, {
desc = "Toggle the outline window. \
With bang, keep focus on initial window after opening.",
nargs = 0,
bang = true,
})
cmd('Open', _cmd_open_outline, {
desc = "With bang, keep focus on initial window after opening.",
nargs = 0,
bang = true,
})
cmd('Close', M.close_outline, { nargs = 0 })
cmd('FocusOutline', M.focus_outline, { nargs = 0 })
cmd('FocusCode', M.focus_code, { nargs = 0 })
cmd('Focus', M.focus_toggle, { nargs = 0 })
cmd('Status', M.show_status, {
desc = "Show a message about the current status of the outline window.",
nargs = 0,
})
cmd('Follow', _cmd_follow_cursor, {
desc = "Update position of outline with position of cursor. \
With bang, don't switch cursor focus to outline window.",
nargs = 0,
bang = true,
})
end
---Set up configuration options for outline.
function M.setup(opts)
cfg.setup(opts)
ui.setup_highlights()
M.view = View:new()
setup_global_autocmd()
setup_commands()
end
return M

91
lua/outline/markdown.lua Normal file
View File

@@ -0,0 +1,91 @@
local M = {}
-- Parses markdown files and returns a table of SymbolInformation[] which is
-- used by the plugin to show the outline.
-- We do this because markdown does not have a LSP.
-- Note that the headings won't have any hierarchy (as of now).
---@return table
function M.handle_markdown()
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
local level_symbols = { { children = {} } }
local max_level = 1
local is_inside_code_block = false
for line, value in ipairs(lines) do
if string.find(value, '^```') then
is_inside_code_block = not is_inside_code_block
end
if is_inside_code_block then
goto nextline
end
local next_value = lines[line+1]
local is_emtpy_line = #value:gsub("^%s*(.-)%s*$", "%1") == 0
local header, title = string.match(value, '^(#+)%s+(.+)$')
if not header and next_value and not is_emtpy_line then
if string.match(next_value, '^=+%s*$') then
header = '#'
title = value
elseif string.match(next_value, '^-+%s*$') then
header = '##'
title = value
end
end
if not header or not title then
goto nextline
end
-- TODO: This is not needed and it works?
-- if #header > 6 then
-- goto nextline
-- end
local depth = #header + 1
local parent
for i = depth - 1, 1, -1 do
if level_symbols[i] ~= nil then
parent = level_symbols[i].children
break
end
end
for i = depth, max_level do
if level_symbols[i] ~= nil then
level_symbols[i].selectionRange['end'].line = line - 1
level_symbols[i].range['end'].line = line - 1
level_symbols[i] = nil
end
end
max_level = depth
local entry = {
kind = 13,
name = title,
selectionRange = {
start = { character = 1, line = line - 1 },
['end'] = { character = 1, line = line - 1 },
},
range = {
start = { character = 1, line = line - 1 },
['end'] = { character = 1, line = line - 1 },
},
children = {},
}
parent[#parent + 1] = entry
level_symbols[depth] = entry
::nextline::
end
for i = 2, max_level do
if level_symbols[i] ~= nil then
level_symbols[i].selectionRange['end'].line = #lines
level_symbols[i].range['end'].line = #lines
end
end
return level_symbols[1].children
end
return M

256
lua/outline/parser.lua Normal file
View File

@@ -0,0 +1,256 @@
local symbols = require 'outline.symbols'
local ui = require 'outline.ui'
local cfg = require 'outline.config'
local t_utils = require 'outline.utils.table'
local lsp_utils = require 'outline.utils.lsp_utils'
local folding = require 'outline.folding'
local M = {}
---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 parent table? A reference to the current symbol's parent in the function's recursion
---@return table
local function parse_result(result, depth, hierarchy, parent)
local ret = {}
for index, value in pairs(result) do
if not cfg.is_symbol_blacklisted(symbols.kinds[value.kind]) then
-- the hierarchy is basically a table of booleans which tells whether
-- the parent was the last in its group or not
local hir = hierarchy or {}
-- how many parents this node has, 1 is the lowest value because its
-- easier to work it
local level = depth or 1
-- whether this node is the last in its group
local isLast = index == #result
local selectionRange = lsp_utils.get_selection_range(value)
local range = lsp_utils.get_range(value)
local node = {
deprecated = value.deprecated,
kind = value.kind,
icon = symbols.icon_from_kind(value.kind),
name = value.name or value.text,
detail = value.detail,
line = selectionRange.start.line,
character = selectionRange.start.character,
range_start = range.start.line,
range_end = range['end'].line,
depth = level,
isLast = isLast,
hierarchy = hir,
parent = parent,
}
table.insert(ret, node)
local children = nil
if value.children ~= nil then
-- copy by value because we dont want it messing with the hir table
local child_hir = t_utils.array_copy(hir)
table.insert(child_hir, isLast)
children = parse_result(value.children, level + 1, child_hir, node)
end
node.children = children
end
end
return ret
end
---Parses the response from lsp request 'textDocument/documentSymbol' using buf_request_all
---@param response table The result from buf_request_all
---@return table outline items
function M.parse(response)
local sorted = lsp_utils.sort_symbols(response)
return parse_result(sorted, nil, nil)
end
function M.flatten(outline_items, ret, depth)
depth = depth or 1
ret = ret or {}
for _, value in ipairs(outline_items) do
table.insert(ret, value)
value.line_in_outline = #ret
if value.children ~= nil and not folding.is_folded(value) then
M.flatten(value.children, ret, depth + 1)
end
end
-- if depth == 1 then
-- for index, value in ipairs(ret) do
-- value.line_in_outline = index
-- end
-- end
return ret
end
function M.get_lines(flattened_outline_items)
local lines = {}
local hl_info = {}
local guide_hl_info = {}
local lineno_max = 0
for node_line, node in ipairs(flattened_outline_items) do
local depth = node.depth
local marker_space = (cfg.o.symbol_folding.markers and 1) or 0
local line = t_utils.str_to_table(string.rep(' ', depth + marker_space))
local running_length = 1
if node.range_start+1 > lineno_max then
lineno_max = node.range_start+1
end
local function add_guide_hl(from, to)
table.insert(guide_hl_info, {
node_line,
from,
to,
'OutlineConnector',
})
end
for index, _ in ipairs(line) do
if cfg.o.guides.enabled then
local guide_markers = cfg.o.guides.markers
if index == 1 then
line[index] = ''
-- if index is last, add a bottom marker if current item is last,
-- else add a middle marker
elseif index == #line then
-- add fold markers
local fold_markers = cfg.o.symbol_folding.markers
if fold_markers and folding.is_foldable(node) then
if folding.is_folded(node) then
line[index] = fold_markers[1]
else
line[index] = fold_markers[2]
end
add_guide_hl(
running_length,
running_length + vim.fn.strlen(line[index]) - 1
)
-- the root level has no vertical markers
elseif depth > 1 then
if node.isLast then
line[index] = guide_markers.bottom
add_guide_hl(
running_length,
running_length + vim.fn.strlen(guide_markers.bottom) - 1
)
else
line[index] = guide_markers.middle
add_guide_hl(
running_length,
running_length + vim.fn.strlen(guide_markers.middle) - 1
)
end
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 node.hierarchy[index] and depth > 1 then
line[index + marker_space] = guide_markers.vertical
add_guide_hl(
running_length - 1 + 2 * marker_space,
running_length
+ vim.fn.strlen(guide_markers.vertical)
- 1
+ 2 * marker_space
)
end
end
line[index] = line[index] .. ' '
running_length = running_length + vim.fn.strlen(line[index])
end
line[1] = ''
local final_prefix = line
local string_prefix = t_utils.table_to_str(final_prefix)
table.insert(lines, string_prefix .. node.icon .. ' ' .. node.name)
local hl_start = #string_prefix
local hl_end = #string_prefix + #node.icon
local hl_type = cfg.o.symbols.icons[symbols.kinds[node.kind]].hl
table.insert(hl_info, { node_line, hl_start, hl_end, hl_type })
node.prefix_length = #string_prefix + #node.icon + 1
end
local final_hl = {}
if cfg.o.outline_items.show_symbol_lineno then
-- Width of the highest lineno value
local max_width = #tostring(lineno_max)
-- Padded prefix to the right of lineno for better readability if linenos
-- get more than 2 digits.
local prefix = string.rep(' ', math.max(2, max_width)+1)
-- Offset to hl_info due to adding lineno on the left of each symbol line
local total_offset = #prefix
for i, node in ipairs(flattened_outline_items) do
lines[i] = prefix .. lines[i]
table.insert(final_hl, {
hl_info[i][1], -- node_line
hl_info[i][2] + total_offset, -- start
hl_info[i][3] + total_offset, -- end
hl_info[i][4] -- type
})
node.prefix_length = node.prefix_length + total_offset
end
if cfg.o.guides.enabled then
for _, hl in ipairs(guide_hl_info) do
table.insert(final_hl, {
hl[1],
hl[2] + total_offset,
hl[3] + total_offset,
hl[4]
})
end
end
else
-- Merge lists hl_info and guide_hl_info
final_hl = hl_info
if cfg.o.guides.enabled then
for _, hl in ipairs(guide_hl_info) do
table.insert(final_hl, hl)
end
end
end
return lines, final_hl
end
function M.get_details(flattened_outline_items)
local lines = {}
for _, value in ipairs(flattened_outline_items) do
table.insert(lines, value.detail or '')
end
return lines
end
function M.get_lineno(flattened_outline_items)
local lines = {}
local max = 0
for _, value in ipairs(flattened_outline_items) do
local line = value.range_start+1
if line > max then
max = line
end
-- Not padded here
table.insert(lines, tostring(line))
end
return lines, max
end
return M

163
lua/outline/preview.lua Normal file
View File

@@ -0,0 +1,163 @@
local so = require 'outline'
local cfg = require 'outline.config'
local hover = require 'outline.hover'
local M = {}
local state = {
preview_buf = nil,
preview_win = nil,
}
local function is_current_win_outline()
local curwin = vim.api.nvim_get_current_win()
return curwin == so.view.winnr
end
local function has_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(so.state.code_win)
local isBufValid = vim.api.nvim_buf_is_valid(bufnr)
return isBufValid
end
M.has_code_win = has_code_win
local function get_width_offset()
---@type integer
local outline_winnr = so.view.winnr
local width = cfg.get_preview_width() + 3
local has_numbers = vim.api.nvim_win_get_option(outline_winnr, "number")
has_numbers = has_numbers or vim.api.nvim_win_get_option(outline_winnr, "relativenumber")
if has_numbers then
width = width + 4
end
if cfg.o.outline_window.position == 'right' then
width = 0 - width
else
width = vim.api.nvim_win_get_width(outline_winnr) + 1
end
return width
end
local function get_height()
return vim.api.nvim_list_uis()[1].height
end
local function get_hovered_node()
local hovered_line = vim.api.nvim_win_get_cursor(so.view.winnr)[1]
local node = so.state.flattened_outline_items[hovered_line]
return node
end
local function update_preview(code_buf)
code_buf = code_buf or vim.api.nvim_win_get_buf(so.state.code_win)
local node = get_hovered_node()
if not node then
return
end
local lines = vim.api.nvim_buf_get_lines(code_buf, 0, -1, false)
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 }
)
end
end
local function setup_preview_buf()
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()
local ts_highlight = require 'nvim-treesitter.highlight'
ts_highlight.attach(state.preview_buf, ft)
end
-- user might not have tree sitter installed
pcall(treesitter_attach)
vim.api.nvim_buf_set_option(state.preview_buf, 'syntax', ft)
vim.api.nvim_buf_set_option(state.preview_buf, 'bufhidden', 'delete')
vim.api.nvim_win_set_option(state.preview_win, 'cursorline', true)
update_preview(code_buf)
end
local function set_bg_hl()
vim.api.nvim_win_set_option(state.preview_win, 'winhl', cfg.o.preview_window.winhl)
vim.api.nvim_win_set_option(state.preview_win, 'winblend', cfg.o.preview_window.winblend)
end
local function show_preview()
if state.preview_win == nil and state.preview_buf == nil then
state.preview_buf = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_attach(state.preview_buf, false, {
on_detach = function()
state.preview_buf = nil
state.preview_win = nil
end,
})
local height = get_height()
local winheight = math.ceil(height / 2)
state.preview_win = vim.api.nvim_open_win(state.preview_buf, false, {
relative = 'win',
height = winheight,
width = cfg.get_preview_width(),
bufpos = { 0, 0 },
col = get_width_offset(),
-- Position preview window middle-aligned vertically
row = math.floor((height - winheight) / 2) - 1,
border = cfg.o.preview_window.border,
})
setup_preview_buf()
else
update_preview()
end
end
function M.show()
if not is_current_win_outline() or #vim.api.nvim_list_wins() < 2 then
return
end
show_preview()
set_bg_hl()
if cfg.o.preview_window.open_hover_on_preview then
hover.show_hover()
end
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
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
vim.api.nvim_win_close(state.hover_win, true)
end
end
end
function M.toggle()
if state.preview_win ~= nil then
M.close()
else
M.show()
end
end
return M

View File

@@ -0,0 +1,96 @@
local M = {}
function M.should_use_provider(_)
local not_coc_installed = vim.fn.exists '*CocActionAsync' == 0
local not_coc_service_initialized = vim.g.coc_service_initialized == 0
if not_coc_installed or not_coc_service_initialized then
return
end
local coc_attached = vim.fn.call('CocAction', { 'ensureDocument' })
local has_symbols = vim.fn.call('CocHasProvider', { 'documentSymbol' })
return coc_attached and has_symbols
end
function M.hover_info(_, _, on_info)
on_info(nil, {
contents = {
kind = 'markdown',
contents = { 'No extra information availaible!' },
},
})
end
---@param result table
local function convert_symbols(result)
local s = {}
local kinds_index = {}
-- create a inverse indexing of symbols.kind
local symbols = require("outline.symbols")
for k, v in pairs(symbols.kinds) do
kinds_index[v] = k
end
-- rebuild coc.nvim symbol list hierarchy according to the 'level' key
for _, value in pairs(result) do
value.children = {}
value.kind = kinds_index[value.kind]
if #s == 0 then
table.insert(s, value)
goto continue
end
if value.level == s[#s].level then
if value.level == 0 then
table.insert(s, value)
goto continue
end
local tmp = s[#s]
table.remove(s)
table.insert(s[#s].children, tmp)
table.insert(s, value)
elseif value.level == s[#s].level + 1 then
table.insert(s[#s].children, value)
elseif value.level == s[#s].level + 2 then
local tmp = s[#s].children[#(s[#s].children)]
table.remove(s[#s].children)
table.insert(s, tmp)
table.insert(s[#s].children, value)
elseif value.level < s[#s].level then
while value.level < s[#s].level do
local tmp = s[#s]
table.remove(s)
table.insert(s[#s].children, tmp)
end
if s[#s].level ~= 0 then
local tmp = s[#s]
table.remove(s)
table.insert(s[#s].children, tmp)
table.insert(s, value)
else
table.insert(s, value)
end
end
::continue::
end
local top = s[#s]
while top.level ~= 0 do
table.remove(s)
table.insert(s[#s].children, top)
top = s[#s]
end
return s
end
---@param on_symbols function
---@param opts table
function M.request_symbols(on_symbols, opts)
vim.fn.call('CocActionAsync', {
'documentSymbols',
function(_, symbols)
on_symbols({ [1000000] = { result = convert_symbols(symbols) } }, opts)
end,
})
end
return M

View File

@@ -0,0 +1,38 @@
local M = {}
local providers = {
'outline/providers/nvim-lsp',
'outline/providers/coc',
'outline/providers/markdown',
}
_G._symbols_outline_current_provider = nil
function M.has_provider()
local ret = false
for _, value in ipairs(providers) do
local provider = require(value)
if provider.should_use_provider(0) then
ret = true
break
end
end
return ret
end
---@param on_symbols function
---@return boolean found_provider
function M.request_symbols(on_symbols, opts)
for _, value in ipairs(providers) do
local provider = require(value)
if provider.should_use_provider(0) then
_G._symbols_outline_current_provider = provider
_G._symbols_outline_current_provider.name = value
provider.request_symbols(on_symbols, opts)
return true
end
end
return false
end
return M

View File

@@ -0,0 +1,25 @@
local md_parser = require 'outline.markdown'
local M = {}
-- probably change this
function M.should_use_provider(bufnr)
return string.match(vim.api.nvim_buf_get_option(bufnr, 'ft'), 'markdown')
end
function M.hover_info(_, _, on_info)
on_info(nil, {
contents = {
kind = 'markdown',
contents = { 'No extra information availaible!' },
},
})
end
---@param on_symbols function
---@param opts table
function M.request_symbols(on_symbols, opts)
on_symbols(md_parser.handle_markdown(), opts)
end
return M

View File

@@ -0,0 +1,84 @@
local config = require 'outline.config'
local lsp_utils = require 'outline.utils.lsp_utils'
local jsx = require 'outline.utils.jsx'
local M = {}
local function getParams()
return { textDocument = vim.lsp.util.make_text_document_params() }
end
function M.hover_info(bufnr, params, on_info)
local clients = vim.lsp.buf_get_clients(bufnr)
local used_client
for id, client in pairs(clients) do
if config.is_client_blacklisted(id) then
goto continue
else
if client.server_capabilities.hoverProvider then
used_client = client
break
end
end
::continue::
end
if not used_client then
on_info(nil, {
contents = {
kind = 'markdown',
content = { 'No extra information availaible!' },
},
})
end
used_client.request('textDocument/hover', params, on_info, bufnr)
end
-- probably change this
function M.should_use_provider(bufnr)
local clients = vim.lsp.buf_get_clients(bufnr)
local ret = false
for id, client in pairs(clients) do
if config.is_client_blacklisted(id) then
goto continue
else
if client.server_capabilities.documentSymbolProvider then
ret = true
break
end
end
::continue::
end
return ret
end
function M.postprocess_symbols(response)
local symbols = lsp_utils.flatten_response(response)
local jsx_symbols = jsx.get_symbols()
if #jsx_symbols > 0 then
return lsp_utils.merge_symbols(symbols, jsx_symbols)
else
return symbols
end
end
---@param on_symbols function
function M.request_symbols(on_symbols, opts)
vim.lsp.buf_request_all(
0,
'textDocument/documentSymbol',
getParams(),
function (response)
response = M.postprocess_symbols(response)
on_symbols(response, opts)
end
)
end
return M

42
lua/outline/rename.lua Normal file
View File

@@ -0,0 +1,42 @@
local so = require 'outline'
local M = {}
local function get_rename_params(node, winnr)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local fn = 'file://' .. vim.api.nvim_buf_get_name(bufnr)
return {
textDocument = { uri = fn },
position = { line = node.line, character = node.character },
bufnr = bufnr,
}
end
function M.rename()
local current_line = vim.api.nvim_win_get_cursor(so.view.winnr)[1]
local node = so.state.flattened_outline_items[current_line]
local params = get_rename_params(node, so.state.code_win)
local new_name = vim.fn.input({ prompt = 'New Name: ', default = node.name })
if not new_name or new_name == '' or new_name == node.name then
return
end
params.newName = new_name
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
return M

74
lua/outline/symbols.lua Normal file
View File

@@ -0,0 +1,74 @@
local cfg = require 'outline.config'
local M = {}
M.kinds = {
[1] = 'File',
[2] = 'Module',
[3] = 'Namespace',
[4] = 'Package',
[5] = 'Class',
[6] = 'Method',
[7] = 'Property',
[8] = 'Field',
[9] = 'Constructor',
[10] = 'Enum',
[11] = 'Interface',
[12] = 'Function',
[13] = 'Variable',
[14] = 'Constant',
[15] = 'String',
[16] = 'Number',
[17] = 'Boolean',
[18] = 'Array',
[19] = 'Object',
[20] = 'Key',
[21] = 'Null',
[22] = 'EnumMember',
[23] = 'Struct',
[24] = 'Event',
[25] = 'Operator',
[26] = 'TypeParameter',
[27] = 'Component',
[28] = 'Fragment',
-- ccls
[252] = 'TypeAlias',
[253] = 'Parameter',
[254] = 'StaticMethod',
[255] = 'Macro',
}
---@param kind string|integer
function M.icon_from_kind(kind)
local kindstr = kind
if type(kind) ~= 'string' then
kindstr = M.kinds[kind]
end
if not kindstr then
kindstr = 'Object'
end
if type(cfg.o.symbols.icon_fetcher) == 'function' then
local icon = cfg.o.symbols.icon_fetcher(kindstr)
if icon and icon ~= "" then
return icon
end
end
if cfg.o.symbols.icon_source == 'lspkind' then
local has_lspkind, lspkind = pcall(require, 'lspkind')
if not has_lspkind then
vim.notify("[outline]: icon_source set to lspkind but failed to require lspkind!", vim.log.levels.ERROR)
else
local icon = lspkind.symbolic(kindstr, { with_text = false })
if icon and icon ~= "" then
return icon
end
end
end
return cfg.o.symbols.icons[kindstr].icon
end
return M

51
lua/outline/ui.lua Normal file
View File

@@ -0,0 +1,51 @@
local M = {}
M.hovered_hl_ns = vim.api.nvim_create_namespace 'hovered_item'
function M.clear_hover_highlight(bufnr)
vim.api.nvim_buf_clear_namespace(bufnr, M.hovered_hl_ns, 0, -1)
end
function M.add_hover_highlight(bufnr, line, col_start)
vim.api.nvim_buf_add_highlight(
bufnr,
M.hovered_hl_ns,
'OutlineCurrent',
line,
col_start,
-1
)
end
function M.setup_highlights()
-- Setup the OutlineCurrent highlight group if it hasn't been done already by
-- a theme or manually set
if vim.fn.hlexists 'OutlineCurrent' == 0 then
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,
'OutlineCurrent',
{ 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'
)
if vim.fn.hlexists 'OutlineConnector' == 0 then
vim.cmd(
string.format('hi OutlineConnector guifg=%s', comment_fg_gui)
)
end
end
return M

126
lua/outline/utils/init.lua Normal file
View File

@@ -0,0 +1,126 @@
local M = {}
---maps the table|string of keys to the action
---@param keys table|string
---@param action function|string
function M.nmap(bufnr, keys, action)
if type(keys) == 'string' then
keys = { keys }
end
for _, lhs in ipairs(keys) do
vim.keymap.set(
'n',
lhs,
action,
{ silent = true, noremap = true, buffer = bufnr }
)
end
end
--- @param f function
--- @param delay number
--- @return function
function M.debounce(f, delay)
local timer = vim.loop.new_timer()
return function(...)
local args = { ... }
timer:start(
delay,
0,
vim.schedule_wrap(function()
timer:stop()
f(unpack(args))
end)
)
end
end
function M.items_dfs(callback, children)
for _, val in ipairs(children) do
callback(val)
if val.children then
M.items_dfs(callback, val.children)
end
end
end
---Merges a symbol tree recursively, only replacing nodes
---which have changed. This will maintain the folding
---status of any unchanged nodes.
---@param new_node table New node
---@param old_node table Old node
---@param index? number Index of old_item in parent
---@param parent? table Parent of old_item
M.merge_items_rec = function(new_node, old_node, index, parent)
local failed = false
if not new_node or not old_node then
failed = true
else
for key, _ in pairs(new_node) do
if
vim.tbl_contains({
'parent',
'children',
'folded',
'hovered',
'line_in_outline',
'hierarchy',
}, key)
then
goto continue
end
if key == 'name' then
-- in the case of a rename, just rename the existing node
old_node['name'] = new_node['name']
else
if not vim.deep_equal(new_node[key], old_node[key]) then
failed = true
break
end
end
::continue::
end
end
if failed then
if parent and index then
parent[index] = new_node
end
else
local next_new_item = new_node.children or {}
-- in case new children are created on a node which
-- previously had no children
if #next_new_item > 0 and not old_node.children then
old_node.children = {}
end
local next_old_item = old_node.children or {}
for i = 1, math.max(#next_new_item, #next_old_item) do
M.merge_items_rec(next_new_item[i], next_old_item[i], i, next_old_item)
end
end
end
M.flash_highlight = function(winnr, lnum, durationMs, hl_group)
hl_group = hl_group or "Visual"
if durationMs == true or durationMs == 1 then
durationMs = 300
end
local bufnr = vim.api.nvim_win_get_buf(winnr)
local ns = vim.api.nvim_buf_add_highlight(bufnr, 0, hl_group, lnum - 1, 0, -1)
local remove_highlight = function()
pcall(vim.api.nvim_buf_clear_namespace, bufnr, ns, 0, -1)
end
vim.defer_fn(remove_highlight, durationMs)
end
return M

128
lua/outline/utils/jsx.lua Normal file
View File

@@ -0,0 +1,128 @@
local M = {}
local SYMBOL_COMPONENT = 27
local SYMBOL_FRAGMENT = 28
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
return outer
end
end
end
return nil
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 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
local function jsx_node_tagname(node, buf)
local tagnode = get_open_tag(node) or node
local identifier = nil
for _, val in ipairs(tagnode:field 'name') do
if val:type() == 'identifier' then
identifier = val
end
end
if identifier then
local a, b, c, d = identifier:range()
local text = vim.api.nvim_buf_get_text(buf, a, b, c, d, {})
local name = table.concat(text)
return name
end
end
local function convert_ts(child, children, bufnr)
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 converted = {
name = (not is_frag and (jsx_node_tagname(child, bufnr) or '<unknown>'))
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
function M.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
local new_children = {}
M.parse_ts(child, new_children, bufnr)
table.insert(children, convert_ts(child, new_children, bufnr))
else
M.parse_ts(child, children, bufnr)
end
end
return children
end
function M.get_symbols()
local status, parsers = pcall(require, 'nvim-treesitter.parsers')
if not status then
return {}
end
local bufnr = 0
local parser = parsers.get_parser(bufnr)
if parser == nil then
return {}
end
local root = parser:parse()[1]:root()
if root == nil then
return {}
end
return M.parse_ts(root, nil, bufnr)
end
return M

View File

@@ -0,0 +1,185 @@
local config = require 'outline.config'
local tbl_utils = require 'outline.utils.table'
local M = {}
function M.is_buf_attached_to_lsp(bufnr)
local clients = vim.lsp.buf_get_clients(bufnr or 0)
return clients ~= nil and #clients > 0
end
function M.is_buf_markdown(bufnr)
return vim.api.nvim_buf_get_option(bufnr, 'ft') == 'markdown'
end
--- Merge all client token lists in an LSP response
function M.flatten_response(response)
local all_results = {}
-- flatten results to one giant table of symbols
for client_id, client_response in pairs(response) do
if config.is_client_blacklisted(client_id) then
print('skipping client ' .. client_id)
goto continue
end
local result = client_response['result']
if result == nil or type(result) ~= 'table' then
goto continue
end
for _, value in pairs(result) do
table.insert(all_results, value)
end
::continue::
end
return all_results
end
function M.get_selection_range(token)
-- support symbolinformation[]
-- https://microsoft.github.io/language-server-protocol/specification#textdocument_documentsymbol
if token.selectionRange == nil then
return token.location.range
end
return token.selectionRange
end
function M.get_range(token)
if token == nil then
return {
start={ line=math.huge, character=math.huge },
['end']={ line=-math.huge, character=-math.huge },
}
end
-- support symbolinformation[]
-- https://microsoft.github.io/language-server-protocol/specification#textdocument_documentsymbol
if token.range == nil then
return token.location.range
end
return token.range
end
--- lexicographically strict compare Ranges, line first
--- https://microsoft.github.io/language-server-protocol/specification/#range
local function range_compare(a, b)
if a == nil and b == nil then
return true
end
if a == nil then
return true
end
if b == nil then
return false
end
return (a.line < b.line) or (a.line == b.line and a.character < b.character)
end
--- Sorts the result from LSP by where the symbols start.
function M.sort_symbols(symbols)
table.sort(symbols, function(a, b)
return range_compare(
M.get_range(a).start,
M.get_range(b).start
)
end)
for _, child in ipairs(symbols) do
if child.children ~= nil then
M.sort_symbols(child.children)
end
end
return symbols
end
--- Preorder DFS iterator on the symbol tree
function M.symbol_preorder_iter(symbols)
local stk = {}
local function push_stk(symbols_list)
for i = #symbols_list, 1, -1 do
table.insert(stk, symbols_list[i])
end
end
push_stk(symbols)
local function is_empty()
return #stk == 0
end
local function next()
if not is_empty() then
local top = table.remove(stk)
push_stk(top and top.children or {})
return top
end
end
local function peek()
return stk[#stk]
end
return { next=next, is_empty=is_empty, peek=peek }
end
local function merge_symbols_rec(iter1, iter2, ub)
local res = {}
while not (iter1.is_empty() and iter2.is_empty()) do
local bv1 = ((not iter1.is_empty()) and M.get_range(iter1.peek()).start) or { line=math.huge, character=math.huge }
local bv2 = ((not iter2.is_empty()) and M.get_range(iter2.peek()).start) or { line=math.huge, character=math.huge }
local iter = (range_compare(bv1, bv2) and iter1) or iter2
if ub ~= nil and range_compare(ub, M.get_range(iter.peek()).start) then
break
end
local node = iter.next()
node.new_children = merge_symbols_rec(iter1, iter2, M.get_range(node)['end'])
table.insert(res, node)
end
return res
end
--- Merge symbols from two symbol trees
--- NOTE: Symbols are mutated!
function M.merge_symbols(symbols1, symbols2)
M.sort_symbols(symbols1)
M.sort_symbols(symbols2)
local iter1 = M.symbol_preorder_iter(symbols1)
local iter2 = M.symbol_preorder_iter(symbols2)
local symbols = merge_symbols_rec(iter1, iter2)
local function dfs(nodes)
for _, node in ipairs(nodes) do
dfs(node.new_children or {})
node.children = node.new_children
node.new_children = nil
end
end
dfs(symbols)
return symbols
end
return M

View File

@@ -0,0 +1,49 @@
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
--- Deep copy a table, deeply excluding certain keys
function M.deepcopy_excluding(t, keys)
local res = {}
for key, value in pairs(t) do
if not vim.tbl_contains(keys, key) then
if type(value) == "table" then
res[key] = M.deepcopy_excluding(value, keys)
else
res[key] = value
end
end
end
return res
end
return M

75
lua/outline/view.lua Normal file
View File

@@ -0,0 +1,75 @@
local cfg = require('outline.config')
local View = {}
function View:new()
return setmetatable({ bufnr = nil, winnr = nil }, { __index = View })
end
---creates the outline window and sets it up
function View:setup_view()
-- create a scratch unlisted buffer
self.bufnr = vim.api.nvim_create_buf(false, true)
-- delete buffer when window is closed / buffer is hidden
vim.api.nvim_buf_set_option(self.bufnr, 'bufhidden', 'delete')
-- create a split
vim.cmd(cfg.get_split_command())
-- resize to a % of the current window size
vim.cmd('vertical resize ' .. cfg.get_window_width())
-- get current (outline) window and attach our buffer to it
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(self.winnr, 'spell', false)
vim.api.nvim_win_set_option(self.winnr, 'signcolumn', 'no')
vim.api.nvim_win_set_option(self.winnr, 'foldcolumn', '0')
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)
vim.api.nvim_win_set_option(self.winnr, 'wrap', cfg.o.outline_window.wrap)
vim.api.nvim_win_set_option(self.winnr, 'winhl', cfg.o.outline_window.winhl)
vim.api.nvim_win_set_option(self.winnr, 'linebreak', true) -- only has effect when wrap=true
vim.api.nvim_win_set_option(self.winnr, 'breakindent', true) -- only has effect when wrap=true
-- Would be nice to use guides.markers.vertical as part of showbreak to keep
-- continuity of the tree UI, but there's currently no way to style the
-- color, apart from globally overriding hl-NonText, which will potentially
-- mess with other theme/user settings. So just use empty spaces for now.
vim.api.nvim_win_set_option(self.winnr, 'showbreak', ' ') -- only has effect when wrap=true.
-- buffer stuff
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 cfg.o.outline_window.show_numbers or cfg.o.outline_window.show_relative_numbers then
vim.api.nvim_win_set_option(self.winnr, 'nu', true)
end
if cfg.o.outline_window.show_relative_numbers then
vim.api.nvim_win_set_option(self.winnr, 'rnu', true)
end
if cfg.o.outline_window.show_cursorline then
vim.api.nvim_win_set_option(self.winnr, 'cursorline', true)
end
end
function View:close()
if self.winnr then
vim.api.nvim_win_close(self.winnr, true)
self.winnr = nil
self.bufnr = nil
end
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

130
lua/outline/writer.lua Normal file
View File

@@ -0,0 +1,130 @@
local parser = require 'outline.parser'
local cfg = require('outline.config')
local ui = require 'outline.ui'
local M = {}
local function is_buffer_outline(bufnr)
if not vim.api.nvim_buf_is_valid(bufnr) then
return false
end
local name = vim.api.nvim_buf_get_name(bufnr)
local ft = vim.api.nvim_buf_get_option(bufnr, 'filetype')
return string.match(name, 'OUTLINE') ~= nil and ft == 'Outline'
end
local hlns = vim.api.nvim_create_namespace 'outline-icon-highlight'
function M.write_outline(bufnr, lines)
if not is_buffer_outline(bufnr) then
return
end
lines = vim.tbl_map(function(line)
lines, _ = string.gsub(line, "\n", " ")
return lines
end, lines)
vim.api.nvim_buf_set_option(bufnr, 'modifiable', true)
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
vim.api.nvim_buf_set_option(bufnr, 'modifiable', false)
end
function M.add_highlights(bufnr, hl_info, nodes)
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
M.add_hover_highlights(bufnr, nodes)
end
local ns = vim.api.nvim_create_namespace 'outline-virt-text'
function M.write_details(bufnr, lines)
if not is_buffer_outline(bufnr) then
return
end
if not cfg.o.outline_items.show_symbol_details then
return
end
for index, value in ipairs(lines) do
vim.api.nvim_buf_set_extmark(bufnr, ns, index - 1, -1, {
virt_text = { { value, 'OutlineDetails' } },
virt_text_pos = 'eol',
hl_mode = 'combine',
})
end
end
function M.write_lineno(bufnr, lines, max)
if not is_buffer_outline(bufnr) then
return
end
if not cfg.o.outline_items.show_symbol_lineno then
return
end
local maxwidth = #tostring(max)
for index, value in ipairs(lines) do
local leftpad = string.rep(' ', maxwidth-#value)
vim.api.nvim_buf_set_extmark(bufnr, ns, index - 1, -1, {
virt_text = { {leftpad..value, 'OutlineLineno' } },
virt_text_pos = 'overlay',
virt_text_win_col = 0,
hl_mode = 'combine',
})
end
end
local function clear_virt_text(bufnr)
vim.api.nvim_buf_clear_namespace(bufnr, -1, 0, -1)
end
M.add_hover_highlights = function(bufnr, nodes)
if not cfg.o.outline_items.highlight_hovered_item then
return
end
-- clear old highlight
ui.clear_hover_highlight(bufnr)
for _, node in ipairs(nodes) do
if not node.hovered then
goto continue
end
local marker_fac = (cfg.o.symbol_folding.markers and 1) or 0
if node.prefix_length then
ui.add_hover_highlight(
bufnr,
node.line_in_outline - 1,
node.prefix_length
)
end
::continue::
end
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)
M.write_outline(bufnr, lines)
clear_virt_text(bufnr)
local details = parser.get_details(flattened_outline_items)
local lineno, lineno_max = parser.get_lineno(flattened_outline_items)
M.add_highlights(bufnr, hl_info, flattened_outline_items)
M.write_details(bufnr, details)
M.write_lineno(bufnr, lineno, lineno_max)
end
return M