aerial.nvim:代码大纲窗口,支持快速浏览与导航

Neovim plugin for a code outline window

Branch8Tags23
FilesLast commitLast update
5 months ago
2 years ago
1 year ago
5 months ago
5 months ago
2 years ago
5 months ago
3 years ago
3 years ago
3 years ago
1 year ago
2 years ago
3 years ago
5 months ago
6 years ago
1 year ago
5 months ago
10 months ago

aerial.nvim

用于代码浏览和快速导航的代码大纲窗口

https://user-images.githubusercontent.com/506791/122652728-18688500-d0f5-11eb-80aa-910f7e6a5f46.mp4

要求

  • Neovim 0.11 或更高版本(对于旧版本,请使用 nvim-0.x 分支)
  • 以下一项或多项:
    • 正常工作的 LSP 设置(参见 nvim-lspconfig)
    • Tree-sitter 解析器

安装

aerial 支持所有常见的插件管理器

lazy.nvim
{
  'stevearc/aerial.nvim',
  opts = {},
  -- Optional dependencies
  dependencies = {
     "nvim-treesitter/nvim-treesitter",
     "nvim-tree/nvim-web-devicons"
  },
}
Packer
require("packer").startup(function()
  use({
    "stevearc/aerial.nvim",
    config = function()
      require("aerial").setup()
    end,
  })
end)
Paq
require("paq")({
  { "stevearc/aerial.nvim" },
})
vim-plug
Plug 'stevearc/aerial.nvim'
dein
call dein#add('stevearc/aerial.nvim')
Pathogen
git clone --depth=1 https://github.com/stevearc/aerial.nvim.git ~/.vim/bundle/
Neovim 原生包
git clone --depth=1 https://github.com/stevearc/aerial.nvim.git \
  "${XDG_DATA_HOME:-$HOME/.local/share}"/nvim/site/pack/aerial/start/aerial.nvim

配置

你需要在 init.lua 中的某处调用 aerial.setup()。完整的选项列表详见下方的 选项。

require("aerial").setup({
  -- optionally use on_attach to set keymaps when aerial has attached to a buffer
  on_attach = function(bufnr)
    -- Jump forwards/backwards with '{' and '}'
    vim.keymap.set("n", "{", "<cmd>AerialPrev<CR>", { buffer = bufnr })
    vim.keymap.set("n", "}", "<cmd>AerialNext<CR>", { buffer = bufnr })
  end,
})
-- You probably also want to set a keymap to toggle aerial
vim.keymap.set("n", "<leader>a", "<cmd>AerialToggle!<CR>")

此外,你还需要安装 Treesitter 或配置一个可用的 LSP 客户端。你可以通过 backends 选项配置首选的代码分析源(参见选项)。默认设置是优先使用 Treesitter(如果可用),并在其不可用时回退到 LSP。

支持的 treesitter 语言
  • bash
  • c
  • c_sharp
  • cpp
  • css
  • cuda
  • dart
  • djot
  • editorconfig
  • elixir
  • elm
  • enforce
  • fish
  • go
  • groovy
  • hcl
  • help
  • html
  • ini
  • java
  • javascript
  • json
  • julia
  • just
  • latex
  • lua
  • make
  • markdown
  • norg
  • nu
  • objdump
  • php
  • proto
  • puppet
  • python
  • r
  • rst
  • ruby
  • rust
  • scala
  • snakemake
  • solidity
  • sql
  • ssh_config
  • starlark
  • swift
  • systemverilog
  • teal
  • terraform
  • toml
  • tsx
  • typescript
  • typst
  • usd
  • vhdl
  • vim
  • vimdoc
  • vue
  • xml
  • yaml
  • zig

这里没有你需要的语言?请求支持该语言

命令

命令 参数 描述
AerialToggle[!] left/right/float 打开或关闭代码大纲窗口。带 ! 时光标停留在当前窗口
AerialOpen[!] left/right/float 打开代码大纲窗口。带 ! 时光标停留在当前窗口
AerialOpenAll 为每个可见窗口打开一个代码大纲窗口。
AerialClose 关闭代码大纲窗口。
AerialCloseAll 关闭所有可见的代码大纲窗口。
[count]AerialNext 向前跳转 {count} 个符号(默认为 1)。
[count]AerialPrev 向后跳转 [count] 个符号(默认为 1)。
[count]AerialGo[!] 跳转到第 [count] 个符号(默认为 1)。
AerialInfo 打印与 aerial 相关的调试信息。
AerialNavToggle 打开或关闭代码导航窗口。
AerialNavOpen 打开代码导航窗口。
AerialNavClose 关闭代码导航窗口。

选项

-- Call the setup function to change the default behavior
require("aerial").setup({
  -- Priority list of preferred backends for aerial.
  -- This can be a filetype map (see :help aerial-filetype-map)
  backends = { "treesitter", "lsp", "markdown", "asciidoc", "man" },

  layout = {
    -- These control the width of the aerial window.
    -- They can be integers or a float between 0 and 1 (e.g. 0.4 for 40%)
    -- min_width and max_width can be a list of mixed types.
    -- max_width = {40, 0.2} means "the lesser of 40 columns or 20% of total"
    max_width = { 40, 0.2 },
    width = nil,
    min_width = 10,

    -- key-value pairs of window-local options for aerial window (e.g. winhl)
    win_opts = {},

    -- Determines the default direction to open the aerial window. The 'prefer'
    -- options will open the window in the other direction *if* there is a
    -- different buffer in the way of the preferred direction
    -- Enum: prefer_right, prefer_left, right, left, float
    default_direction = "prefer_right",

    -- Determines where the aerial window will be opened
    --   edge   - open aerial at the far right/left of the editor
    --   window - open aerial to the right/left of the current window
    placement = "window",

    -- When the symbols change, resize the aerial window (within min/max constraints) to fit
    resize_to_content = true,

    -- Preserve window size equality with (:help CTRL-W_=)
    preserve_equality = false,
  },

  -- Determines how the aerial window decides which buffer to display symbols for
  --   window - aerial window will display symbols for the buffer in the window from which it was opened
  --   global - aerial window will display symbols for the current window
  attach_mode = "window",

  -- List of enum values that configure when to auto-close the aerial window
  --   unfocus       - close aerial when you leave the original source window
  --   switch_buffer - close aerial when you change buffers in the source window
  --   unsupported   - close aerial when attaching to a buffer that has no symbol source
  close_automatic_events = {},

  -- Keymaps in aerial window. Can be any value that `vim.keymap.set` accepts OR a table of keymap
  -- options with a `callback` (e.g. { callback = function() ... end, desc = "", nowait = true })
  -- Additionally, if it is a string that matches "actions.<name>",
  -- it will use the mapping at require("aerial.actions").<name>
  -- Set to `false` to remove a keymap
  keymaps = {
    ["?"] = "actions.show_help",
    ["g?"] = "actions.show_help",
    ["<CR>"] = "actions.jump",
    ["<2-LeftMouse>"] = "actions.jump",
    ["<C-v>"] = "actions.jump_vsplit",
    ["<C-s>"] = "actions.jump_split",
    ["p"] = "actions.scroll",
    ["<C-j>"] = "actions.down_and_scroll",
    ["<C-k>"] = "actions.up_and_scroll",
    ["{"] = "actions.prev",
    ["}"] = "actions.next",
    ["[["] = "actions.prev_up",
    ["]]"] = "actions.next_up",
    ["q"] = "actions.close",
    ["o"] = "actions.tree_toggle",
    ["za"] = "actions.tree_toggle",
    ["O"] = "actions.tree_toggle_recursive",
    ["zA"] = "actions.tree_toggle_recursive",
    ["l"] = "actions.tree_open",
    ["zo"] = "actions.tree_open",
    ["L"] = "actions.tree_open_recursive",
    ["zO"] = "actions.tree_open_recursive",
    ["h"] = "actions.tree_close",
    ["zc"] = "actions.tree_close",
    ["H"] = "actions.tree_close_recursive",
    ["zC"] = "actions.tree_close_recursive",
    ["zr"] = "actions.tree_increase_fold_level",
    ["zR"] = "actions.tree_open_all",
    ["zm"] = "actions.tree_decrease_fold_level",
    ["zM"] = "actions.tree_close_all",
    ["zx"] = "actions.tree_sync_folds",
    ["zX"] = "actions.tree_sync_folds",
  },

  -- When true, don't load aerial until a command or function is called
  -- Defaults to true, unless `on_attach` is provided, then it defaults to false
  lazy_load = true,

  -- Disable aerial on files with this many lines
  disable_max_lines = 10000,

  -- Disable aerial on files this size or larger (in bytes)
  disable_max_size = 2000000, -- Default 2MB

  -- A list of all symbols to display. Set to false to display all symbols.
  -- This can be a filetype map (see :help aerial-filetype-map)
  -- To see all available values, see :help SymbolKind
  filter_kind = {
    "Class",
    "Constructor",
    "Enum",
    "Function",
    "Interface",
    "Module",
    "Method",
    "Struct",
  },

  -- Determines line highlighting mode when multiple splits are visible.
  -- split_width   Each open window will have its cursor location marked in the
  --               aerial buffer. Each line will only be partially highlighted
  --               to indicate which window is at that location.
  -- full_width    Each open window will have its cursor location marked as a
  --               full-width highlight in the aerial buffer.
  -- last          Only the most-recently focused window will have its location
  --               marked in the aerial buffer.
  -- none          Do not show the cursor locations in the aerial window.
  highlight_mode = "split_width",

  -- Highlight the closest symbol if the cursor is not exactly on one.
  highlight_closest = true,

  -- Highlight the symbol in the source buffer when cursor is in the aerial win
  highlight_on_hover = false,

  -- When jumping to a symbol, highlight the line for this many ms.
  -- Set to false to disable
  highlight_on_jump = 300,

  -- Jump to symbol in source window when the cursor moves
  autojump = false,

  -- Define symbol icons. You can also specify "<Symbol>Collapsed" to change the
  -- icon when the tree is collapsed at that symbol, or "Collapsed" to specify a
  -- default collapsed icon. The default icon set is determined by the
  -- "nerd_font" option below.
  -- If you have lspkind-nvim installed, it will be the default icon set.
  -- This can be a filetype map (see :help aerial-filetype-map)
  icons = {},

  -- Control which windows and buffers aerial should ignore.
  -- Aerial will not open when these are focused, and existing aerial windows will not be updated
  ignore = {
    -- Ignore unlisted buffers. See :help buflisted
    unlisted_buffers = false,

    -- Ignore diff windows (setting to false will allow aerial in diff windows)
    diff_windows = true,

    -- List of filetypes to ignore.
    filetypes = {},

    -- Ignored buftypes.
    -- Can be one of the following:
    -- false or nil - No buftypes are ignored.
    -- "special"    - All buffers other than normal, help and man page buffers are ignored.
    -- table        - A list of buftypes to ignore. See :help buftype for the
    --                possible values.
    -- function     - A function that returns true if the buffer should be
    --                ignored or false if it should not be ignored.
    --                Takes two arguments, `bufnr` and `buftype`.
    buftypes = "special",

    -- Ignored wintypes.
    -- Can be one of the following:
    -- false or nil - No wintypes are ignored.
    -- "special"    - All windows other than normal windows are ignored.
    -- table        - A list of wintypes to ignore. See :help win_gettype() for the
    --                possible values.
    -- function     - A function that returns true if the window should be
    --                ignored or false if it should not be ignored.
    --                Takes two arguments, `winid` and `wintype`.
    wintypes = "special",
  },

  -- Use symbol tree for folding. Set to true or false to enable/disable
  -- Set to "auto" to manage folds if your previous foldmethod was 'manual'
  -- This can be a filetype map (see :help aerial-filetype-map)
  manage_folds = false,

  -- When you fold code with za, zo, or zc, update the aerial tree as well.
  -- Only works when manage_folds = true
  link_folds_to_tree = false,

  -- Fold code when you open/collapse symbols in the tree.
  -- Only works when manage_folds = true
  link_tree_to_folds = true,

  -- Set default symbol icons to use patched font icons (see https://www.nerdfonts.com/)
  -- "auto" will set it to true if nvim-web-devicons or lspkind-nvim is installed.
  nerd_font = "auto",

  -- Call this function when aerial attaches to a buffer.
  on_attach = function(bufnr) end,

  -- Call this function when aerial first sets symbols on a buffer.
  on_first_symbols = function(bufnr) end,

  -- Automatically open aerial when entering supported buffers.
  -- This can be a function (see :help aerial-open-automatic)
  open_automatic = false,

  -- Run this command after jumping to a symbol (false will disable)
  post_jump_cmd = "normal! zz",

  -- Invoked after each symbol is parsed, can be used to modify the parsed item,
  -- or to filter it by returning false.
  --
  -- bufnr: a neovim buffer number
  -- item: of type aerial.Symbol
  -- ctx: a record containing the following fields:
  --   * backend_name: treesitter, lsp, man...
  --   * lang: info about the language
  --   * symbols?: specific to the lsp backend
  --   * symbol?: specific to the lsp backend
  --   * syntax_tree?: specific to the treesitter backend
  --   * match?: specific to the treesitter backend, TS query match
  post_parse_symbol = function(bufnr, item, ctx)
    return true
  end,

  -- Invoked after all symbols have been parsed and post-processed,
  -- allows to modify the symbol structure before final display
  --
  -- bufnr: a neovim buffer number
  -- items: a collection of aerial.Symbol items, organized in a tree,
  --        with 'parent' and 'children' fields
  -- ctx: a record containing the following fields:
  --   * backend_name: treesitter, lsp, man...
  --   * lang: info about the language
  --   * symbols?: specific to the lsp backend
  --   * syntax_tree?: specific to the treesitter backend
  post_add_all_symbols = function(bufnr, items, ctx)
    return items
  end,

  -- When true, aerial will automatically close after jumping to a symbol
  close_on_select = false,

  -- The autocmds that trigger symbols update (not used for LSP backend)
  update_events = "TextChanged,InsertLeave",

  -- Show box drawing characters for the tree hierarchy
  show_guides = false,

  -- Customize the characters used when show_guides = true
  guides = {
    -- When the child item has a sibling below it
    mid_item = "├─",
    -- When the child item is the last in the list
    last_item = "└─",
    -- When there are nested child guides to the right
    nested_top = "│ ",
    -- Raw indentation
    whitespace = "  ",
  },

  -- Set this function to override the highlight groups for certain symbols
  get_highlight = function(symbol, is_icon, is_collapsed)
    -- return "MyHighlight" .. symbol.kind
  end,

  -- Options for opening aerial in a floating win
  float = {
    -- Controls border appearance. Passed to nvim_open_win
    border = "rounded",

    -- Determines location of floating window
    --   cursor - Opens float on top of the cursor
    --   editor - Opens float centered in the editor
    --   win    - Opens float centered in the window
    relative = "cursor",

    -- These control the height of the floating window.
    -- They can be integers or a float between 0 and 1 (e.g. 0.4 for 40%)
    -- min_height and max_height can be a list of mixed types.
    -- min_height = {8, 0.1} means "the greater of 8 rows or 10% of total"
    max_height = 0.9,
    height = nil,
    min_height = { 8, 0.1 },

    override = function(conf, source_winid)
      -- This is the config that will be passed to nvim_open_win.
      -- Change values here to customize the layout
      return conf
    end,
  },

  -- Options for the floating nav windows
  nav = {
    border = "rounded",
    max_height = 0.9,
    min_height = { 10, 0.1 },
    max_width = 0.5,
    min_width = { 0.2, 20 },
    win_opts = {
      cursorline = true,
      winblend = 10,
    },
    -- Jump to symbol in source window when the cursor moves
    autojump = false,
    -- Show a preview of the code in the right column, when there are no child symbols
    preview = false,
    -- Keymaps in the nav window
    keymaps = {
      ["<CR>"] = "actions.jump",
      ["<2-LeftMouse>"] = "actions.jump",
      ["<C-v>"] = "actions.jump_vsplit",
      ["<C-s>"] = "actions.jump_split",
      ["h"] = "actions.left",
      ["l"] = "actions.right",
      ["<C-c>"] = "actions.close",
    },
  },

  lsp = {
    -- If true, fetch document symbols when LSP diagnostics update.
    diagnostics_trigger_update = false,

    -- Set to false to not update the symbols when there are LSP errors
    update_when_errors = true,

    -- How long to wait (in ms) after a buffer change before updating
    -- Only used when diagnostics_trigger_update = false
    update_delay = 300,

    -- Map of LSP client name to priority. Default value is 10.
    -- Clients with higher (larger) priority will be used before those with lower priority.
    -- Set to -1 to never use the client.
    priority = {
      -- pyright = 10,
    },
  },

  treesitter = {
    -- How long to wait (in ms) after a buffer change before updating
    update_delay = 300,
  },

  markdown = {
    -- How long to wait (in ms) after a buffer change before updating
    update_delay = 300,
  },

  asciidoc = {
    -- How long to wait (in ms) after a buffer change before updating
    update_delay = 300,
  },

  man = {
    -- How long to wait (in ms) after a buffer change before updating
    update_delay = 300,
  },
})

所有可能的 SymbolKind 值可在 LSP 规范 中找到。这些值用于配置图标、高亮组和过滤。

某些可选回调中使用的 aerial.Symbol 类型如下:

{
kind: SymbolKind,
name: string,
level: number,
parent: aerial.Symbol,
lnum: number,
end_lnum: number,
col: number,
end_col: number
}

第三方集成

Snacks

如果你已安装 snacks.nvim,可以使用选择器查找并跳转到符号。

require("aerial").snacks_picker()

你可以传入一个选项表,该表将直接发送到 Snacks.picker.pick。使用此功能可自定义显示效果。

require("aerial").snacks_picker({
  layout = {
    preset = "dropdown",
    preview = false,
  }
})

Telescope

如果你已安装 telescope,则有一个用于模糊查找和跳转到符号的扩展。它的功能与内置的 lsp_document_symbols 选择器类似,主要区别在于它使用 aerial 后端作为数据源(例如 LSP、treesitter 等),并且会过滤掉一些符号(参见 filter_kind 选项)。

你可以通过 :Telescope aerial 或 :lua require("telescope").extensions.aerial.aerial() 激活该选择器。

此扩展可通过以下选项进行自定义:

require("telescope").setup({
  extensions = {
    aerial = {
      -- Set the width of the first two columns (the second
      -- is relevant only when show_columns is set to 'both')
      col1_width = 4,
      col2_width = 30,
      -- How to format the symbols
      format_symbol = function(symbol_path, filetype)
        if filetype == "json" or filetype == "yaml" then
          return table.concat(symbol_path, ".")
        else
          return symbol_path[#symbol_path]
        end
      end,
      -- Available modes: symbols, lines, both
      show_columns = "both",
    },
  },
})

如果希望命令能够自动补全,可以先加载扩展(此行必须放在上述的 setup 部分之后):

require("telescope").load_extension("aerial")

fzf-lua

如果您已安装 fzf-lua,可以使用选择器查找并跳转到符号。 它支持多选,并使用 files 选择器的默认操作(例如,使用 <C-s> 在分屏中打开符号)。

require("aerial").fzf_lua_picker()

你可以传入一个选项表,该表将直接发送给 require('fzf-lua').fzf_exec。使用此功能可自定义显示效果。

require("aerial").fzf_lua_picker({
  profile = 'ivy',
})

fzf

如果你已安装 fzf,可以通过 :call aerial#fzf() 触发模糊查找。若要创建映射:

nmap <silent> <leader>ds <cmd>call aerial#fzf()<cr>

Lualine

有一个 lualine 组件可用于显示当前光标位置的符号

require("lualine").setup({
  sections = {
    lualine_x = { "aerial" },

    -- Or you can customize it
    lualine_y = {
      {
        "aerial",
        -- The separator to be used to separate symbols in status line.
        sep = " ) ",

        -- The number of symbols to render top-down. In order to render only 'N' last
        -- symbols, negative numbers may be supplied. For instance, 'depth = -1' can
        -- be used in order to render only current symbol.
        depth = nil,

        -- When 'dense' mode is on, icons are not rendered near their symbols. Only
        -- a single icon that represents the kind of current symbol is rendered at
        -- the beginning of status line.
        dense = false,

        -- The separator to be used to separate symbols in dense mode.
        dense_sep = ".",

        -- Color the symbol icons.
        colored = true,
      },
    },
  },
})

高亮

为每个 SymbolKind 都创建了高亮组。其中一个用于符号名称(Aerial<SymbolKind>),另一个用于图标(Aerial<SymbolKind>Icon)。例如:

hi link AerialClass Type
hi link AerialClassIcon Special
hi link AerialFunction Special
hi AerialFunctionIcon guifg=#cb4b16 guibg=NONE guisp=NONE gui=NONE cterm=NONE

" There's also this group for the fallback of the text if a specific
" class highlight isn't defined
hi link AerialNormal Normal
" There's also this group for the cursor position
hi link AerialLine QuickFixLine
" If highlight_mode="split_width", you can set a separate color for the
" non-current location highlight
hi AerialLineNC guibg=Gray

" You can customize the guides (if show_guide=true)
hi link AerialGuide Comment
" You can set a different guide color for each level
hi AerialGuide1 guifg=Red
hi AerialGuide2 guifg=Blue

API

TreeSitter 查询

编写查询时,Aerial 会使用以下捕获和元数据:

  • @symbol - 用于捕获逻辑区域的必需捕获项

  • kind - 必需元数据,一个与 vim.lsp.protocol.SymbolKind 之一匹配的字符串值

  • @name - 用于从文本中提取名称的捕获项

  • @start - 匹配的起始位置,影响光标位置与代码大纲树的匹配,默认为 @symbol

  • @end - 匹配的结束位置,影响光标位置与代码大纲树的匹配,默认为 @start

  • @selection - 使用 Aerial 导航时要跳转到的位置,若未设置则回退到 @name 和 @symbol

  • @scope - 为匹配项命名作用域的节点,其文本用于为该条目生成自定义的 "Comment" 链接高亮,"public" 除外。

    文本为 "developers" 的 @scope 节点将导致其在树中的条目应用 "AerialDevelopers" 高亮。

  • scope - 与 @scope 捕获项作用相同的元数据值,会覆盖上述捕获项

注意:可以分别使用 #set! 和 #gsub! 来设置或修改捕获项的文本。

常见问题

问:我不小心在 aerial 窗口中打开了文件,导致显示异常。如何防止这种情况发生?

建议安装 stickybuf。该插件正是为解决此问题而设计的。

Introduction

NeoVim 代码大纲窗口插件【此简介由AI生成】

Customize your domain
62.36 K119Visit GitHub