Git Product home page Git Product logo

legendary.nvim's Introduction

Define your keymaps, commands, and autocommands as simple Lua tables, building a legend at the same time (like VS Code's Command Palette).

demo gif
Theme used in recording is onedarkpro.nvim. The finder UI is handled by telescope.nvim via dressing.nvim. See Prerequisites for details.

Table of Contents

Features

  • Define your keymaps, commands, augroup/autocmds, and even arbitrary Lua functions to run on the fly, as simple Lua tables, then bind them with legendary.nvim
  • Integration with which-key.nvim, use your existing which-key.nvim tables with legendary.nvim (see extensions)
  • Integration with lazy.nvim, automatically load keymaps defined via lazy.nvim's keys property on plugin specs (see extensions)
  • Execute normal, insert, and visual mode keymaps, commands, autocommands, and Lua functions when you select them
  • Show your most recently executed items at the top when triggered via legendary.nvim (can be disabled via config)
  • Uses vim.ui.select() so it can be hooked up to a fuzzy finder using something like dressing.nvim for a VS Code command palette like interface
  • Buffer-local keymaps, commands, functions and autocmds only appear in the finder for the current buffer
  • Help execute commands that take arguments by prefilling the command line instead of executing immediately
  • Search built-in keymaps and commands along with your user-defined keymaps and commands (may be disabled in config). Notice some missing? Comment on this discussion or submit a PR!
  • A legendary.toolbox module to help create lazily-evaluated keymaps and commands, and item filter. Have an idea for a new helper? Comment on this discussion or submit a PR!
  • Sort by frecency, a combined measure of how frequently and how recently you've used an item from the picker
  • A parser to convert Vimscript keymap commands (e.g. vnoremap <silent> <leader>f :SomeCommand<CR>) to legendary.nvim keymap tables (see Converting Keymaps From Vimscript)
  • Anonymous mappings; show mappings/commands in the finder without having legendary.nvim handle creating them
  • Extensions to automatically load keymaps and commands from other plugins

Prerequisites

Installation

This project uses git tags to adhere to Semantic Versioning. To check the latest version, see the git tag list.

With lazy.nvim:

-- to use a version
{
  'mrjones2014/legendary.nvim',
  version = 'v2.13.9',
  -- since legendary.nvim handles all your keymaps/commands,
  -- its recommended to load legendary.nvim before other plugins
  priority = 10000,
  lazy = false,
  -- sqlite is only needed if you want to use frecency sorting
  -- dependencies = { 'kkharji/sqlite.lua' }
}
-- or, to get rolling updates
{
  'mrjones2014/legendary.nvim',
  -- since legendary.nvim handles all your keymaps/commands,
  -- its recommended to load legendary.nvim before other plugins
  priority = 10000,
  lazy = false,
  -- sqlite is only needed if you want to use frecency sorting
  -- dependencies = { 'kkharji/sqlite.lua' }
}

With vim-plug:

" if you want to use frecency sorting, sqlite is also needed
Plug "kkharji/sqlite.lua"

" to use a version
Plug "mrjones2014/legendary.nvim", { 'tag': 'v2.1.0' }
" or, to get rolling updates
Plug "mrjones2014/legendary.nvim"

Quickstart

If you use lazy.nvim for your plugin manager, legendary.nvim can automatically register keymaps defined via the keys property of lazy.nvim plugin specs. This lets you keep your plugin-specific keymaps where you define the plugin, and legendary.nvim automatically detects them. For example:

-- in a plugin spec:
{
  'folke/flash.nvim',
  keys = {
    {
      's',
      function()
        require('flash').jump()
      end,
      mode = { 'n', 'x', 'o' },
      desc = 'Jump forwards',
    },
    {
      'S',
      function()
        require('flash').jump({ search = { forward = false } })
      end,
      mode = { 'n', 'x', 'o' },
      desc = 'Jump backwards',
    },
  },
}

-- where you set up legendary.nvim
-- now the keymaps from the `flash.nvim` plugin spec will be automatically loaded
require('legendary').setup({ extensions = { lazy_nvim = true } })

Otherwise, register keymaps, commands, autocmds, and functions through setup, including opting into extensions which can automatically load keymaps and commands from other plugins:

require('legendary').setup({
  keymaps = {
    -- map keys to a command
    { '<leader>ff', ':Telescope find_files', description = 'Find files' },
    -- map keys to a function
    {
      '<leader>h',
      function()
        print('hello world!')
      end,
      description = 'Say hello',
    },
    -- Set options used during keymap creation
    { '<leader>s', ':SomeCommand<CR>', description = 'Non-silent keymap', opts = { silent = true } },
    -- create keymaps with different implementations per-mode
    {
      '<leader>c',
      { n = ':LinewiseCommentToggle<CR>', x = ":'<,'>BlockwiseCommentToggle<CR>" },
      description = 'Toggle comment',
    },
    -- create item groups to create sub-menus in the finder
    -- note that only keymaps, commands, and functions
    -- can be added to item groups
    {
      -- groups with same itemgroup will be merged
      itemgroup = 'short ID',
      description = 'A submenu of items...',
      icon = '',
      keymaps = {
        -- more keymaps here
      },
    },
    -- in-place filters, see :h legendary-tables or ./doc/table_structures/README.md
    { '<leader>m', description = 'Preview markdown', filters = { ft = 'markdown' } },
  },
  commands = {
    -- easily create user commands
    {
      ':SayHello',
      function()
        print('hello world!')
      end,
      description = 'Say hello as a command',
    },
    {
      -- groups with same itemgroup will be merged
      itemgroup = 'short ID',
      -- don't need to copy the other group data because
      -- it will be merged with the one from the keymaps table
      commands = {
        -- more commands here
      },
    },
    -- in-place filters, see :h legendary-tables or ./doc/table_structures/README.md
    { ':Glow', description = 'Preview markdown', filters = { ft = 'markdown' } },
  },
  funcs = {
    -- Make arbitrary Lua functions that can be executed via the item finder
    {
      function()
        doSomeStuff()
      end,
      description = 'Do some stuff with a Lua function!',
    },
    {
      -- groups with same itemgroup will be merged
      itemgroup = 'short ID',
      -- don't need to copy the other group data because
      -- it will be merged with the one from the keymaps table
      funcs = {
        -- more funcs here
      },
    },
  },
  autocmds = {
    -- Create autocmds and augroups
    { 'BufWritePre', vim.lsp.buf.format, description = 'Format on save' },
    {
      name = 'MyAugroup',
      clear = true,
      -- autocmds here
    },
  },
  -- load extensions
  extensions = {
    -- automatically load keymaps from lazy.nvim's `keys` option
    lazy_nvim = true,
    -- load keymaps and commands from nvim-tree.lua
    nvim_tree = true,
    -- load commands from smart-splits.nvim
    -- and create keymaps, see :h legendary-extensions-smart-splits.nvim
    smart_splits = {
      directions = { 'h', 'j', 'k', 'l' },
      mods = {
        move = '<C>',
        resize = '<M>',
      },
    },
    -- load commands from op.nvim
    op_nvim = true,
    -- load keymaps from diffview.nvim
    diffview = true,
  },
})

For more mapping features and more complicated setups see Table Structures.

To trigger the finder for your configured keymaps, commands, augroup/autocmds, and Lua functions:

Commands:

" search keymaps, commands, and autocmds
:Legendary

" search keymaps
:Legendary keymaps

" search commands
:Legendary commands

" search functions
:Legendary functions

" search autocmds
:Legendary autocmds

" repeat the last item executed via legendary.nvim's finder;
" by default, only executes if the last set of item filters used still returns `true`
:LegendaryRepeat

" repeat the last item executed via legendary.nvim's finder, ignoring the filters used
:LegendaryRepeat!

Lua API:

The require('legendary').find() function takes an opts table with the following fields (all optional):

{
  -- pass a list of filter functions or a single filter function with
  -- the signature `function(item, context): boolean`
  -- (see below for `context` definition)
  -- several filter functions are provided for convenience
  -- see ./doc/FILTERS.md for a list
  filters = {},
  -- pass a function with the signature `function(item, mode): string[]`
  -- returning a list of strings where each string is one column
  -- use this to override the configured formatter for just one call
  formatter = nil,
  -- pass a string, or a function that returns a string
  -- to customize the select prompt for the current call
  select_prompt = nil,
}

The context table passed to filters contains the following properties:

{
  buf = number, -- buffer ID
  buftype = string,
  filetype = string,
  mode = string, -- the mode that the UI was triggered from
  cursor_pos = table, -- { row, col }
  marks = table, -- visual mode marks, if applicable; { line, col, line, col }
}

See USAGE_EXAMPLES.md for some advanced usage examples.

Configuration

Default configuration is shown below. For a detailed explanation of the structure for keymap, command, and augroup/autocmd tables, see doc/table_structures/README.md.

require('legendary').setup({
  -- Initial keymaps to bind, can also be a function that returns the list
  keymaps = {},
  -- Initial commands to bind, can also be a function that returns the list
  commands = {},
  -- Initial augroups/autocmds to bind, can also be a function that returns the list
  autocmds = {},
  -- Initial functions to bind, can also be a function that returns the list
  funcs = {},
  -- Initial item groups to bind,
  -- note that item groups can also
  -- be under keymaps, commands, autocmds, or funcs;
  -- can also be a function that returns the list
  itemgroups = {},
  -- default opts to merge with the `opts` table
  -- of each individual item
  default_opts = {
    -- for example, { silent = true, remap = false }
    keymaps = {},
    -- for example, { args = '?', bang = true }
    commands = {},
    -- for example, { buf = 0, once = true }
    autocmds = {},
  },
  -- Customize the prompt that appears on your vim.ui.select() handler
  -- Can be a string or a function that returns a string.
  select_prompt = ' legendary.nvim ',
  -- Character to use to separate columns in the UI
  col_separator_char = '',
  -- Optionally pass a custom formatter function. This function
  -- receives the item as a parameter and the mode that legendary
  -- was triggered from (e.g. `function(item, mode): string[]`)
  -- and must return a table of non-nil string values for display.
  -- It must return the same number of values for each item to work correctly.
  -- The values will be used as column values when formatted.
  -- See function `default_format(item)` in
  -- `lua/legendary/ui/format.lua` to see default implementation.
  default_item_formatter = nil,
  -- Customize icons used by the default item formatter
  icons = {
    -- keymap items list the modes in which the keymap applies
    -- by default, you can show an icon instead by setting this to
    -- a non-nil icon
    keymap = nil,
    command = '',
    fn = '󰡱',
    itemgroup = '',
  },
  -- Include builtins by default, set to false to disable
  include_builtin = true,
  -- Include the commands that legendary.nvim creates itself
  -- in the legend by default, set to false to disable
  include_legendary_cmds = true,
  -- Options for list sorting. Note that fuzzy-finders will still
  -- do their own sorting. For telescope.nvim, you can set it to use
  -- `require('telescope.sorters').fuzzy_with_index_bias({})` when
  -- triggered via `legendary.nvim`. Example config for `dressing.nvim`:
  --
  -- require('dressing').setup({
  --  select = {
  --    get_config = function(opts)
  --      if opts.kind == 'legendary.nvim' then
  --        return {
  --          telescope = {
  --            sorter = require('telescope.sorters').fuzzy_with_index_bias({})
  --          }
  --        }
  --      else
  --        return {}
  --      end
  --    end
  --  }
  -- })
  sort = {
    -- put most recently selected item first, this works
    -- both within global and item group lists
    most_recent_first = true,
    -- sort user-defined items before built-in items
    user_items_first = true,
    -- sort the specified item type before other item types,
    -- value must be one of: 'keymap', 'command', 'autocmd', 'group', nil
    item_type_bias = nil,
    -- settings for frecency sorting.
    -- https://en.wikipedia.org/wiki/Frecency
    -- Set `frecency = false` to disable.
    -- this feature requires sqlite.lua (https://github.com/kkharji/sqlite.lua)
    -- and will be automatically disabled if sqlite is not available.
    -- NOTE: THIS TAKES PRECEDENCE OVER OTHER SORT OPTIONS!
    frecency = {
      -- the directory to store the database in
      db_root = string.format('%s/legendary/', vim.fn.stdpath('data')),
      -- the maximum number of timestamps for a single item
      -- to store in the database
      max_timestamps = 10,
    },
  },
  lazy_nvim = {
    -- Automatically register keymaps that are defined on lazy.nvim plugin specs
    -- using the `keys = {}` property.
    auto_register = false,
  },
  which_key = {
    -- Automatically add which-key tables to legendary
    -- see ./doc/WHICH_KEY.md for more details
    auto_register = false,
    -- you can put which-key.nvim tables here,
    -- or alternatively have them auto-register,
    -- see ./doc/WHICH_KEY.md
    mappings = {},
    opts = {},
    -- controls whether legendary.nvim actually binds they keymaps,
    -- or if you want to let which-key.nvim handle the bindings.
    -- if not passed, true by default
    do_binding = true,
    -- controls whether to use legendary.nvim item groups
    -- matching your which-key.nvim groups; if false, all keymaps
    -- are added at toplevel instead of in a group.
    use_groups = true,
  },
  -- Which extensions to load; no extensions are loaded by default.
  -- Setting the plugin name to `false` disables loading the extension.
  -- Setting it to any other value will attempt to load the extension,
  -- and pass the value as an argument to the extension, which should
  -- be a single function. Extensions are modules under `legendary.extensions.*`
  -- which return a single function, which is responsible for loading and
  -- initializing the extension.
  extensions = {
    nvim_tree = false,
    smart_splits = false,
    op_nvim = false,
    diffview = false,
  },
  scratchpad = {
    -- How to open the scratchpad buffer,
    -- 'current' for current window, 'float'
    -- for floating window
    view = 'float',
    -- How to show the results of evaluated Lua code.
    -- 'print' for `print(result)`, 'float' for a floating window.
    results_view = 'float',
    -- Border style for floating windows related to the scratchpad
    float_border = 'rounded',
    -- Whether to restore scratchpad contents from a cache file
    keep_contents = true,
  },
  -- Directory used for caches
  cache_path = string.format('%s/legendary/', vim.fn.stdpath('cache')),
  -- Log level, one of 'trace', 'debug', 'info', 'warn', 'error', 'fatal'
  log_level = 'info',
})

Troubleshooting Frecency Sort

If you get an error along the lines of the following, and frecency sorting does not work:

Failed to open database at /Users/mat/.local/share/nvim/legendary/legendary_frecency.sqlite3: ...at/.local/share/nvim/lazy/sqlite.lua/lua/sqlite/defs.lua:56: dlopen(lib.dylib, 0x0005): tried: 'lib.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlib.dylib' (no such file), '/nix/store/092zx4zf4fmj0jyk32jl1ihix6q4bmw4-apple-framework-CoreFoundation-11.0.0/Library/Frameworks/lib.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/nix/store/092zx4zf4fmj0jyk32jl1ihix6q4bmw4-apple-framework-CoreFoundation-11.0.0/Library/Frameworks/lib.dylib' (no such file), '/nix/store/092zx4zf4fmj0jyk32jl1ihix6q4bmw4-apple-framework-CoreFoundation-11.0.0/Library/Frameworks/lib.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/nix/store/092zx4zf4fmj0jyk32jl1ihix6q4bmw4-apple-framework-CoreFoundation-11.0.0/Library/Frameworks/lib.dylib' (no such file), '/usr/lib/lib.dylib' (no such file, not in dyld cache), 'lib.dylib' (no such file), '/usr/local/lib/lib.dylib' (no such file), '/usr/lib/lib.dylib' (no such file, not in dyld cache)

This means that the sqlite.lua Lua library was unable to find the libsqlite3.dylib shared library file. This could be the case for a few reasons. To fix this, you can either set vim.g.sqlite_clib_path in your Neovim config, or the LIBSQLITE environment variable to the full path to libsqlite3.dylib. If you are using Nix with home-manager, this can be done like so:

{
  home.sessionVariables = {
    LIBSQLITE = "${pkgs.sqlite.out}/lib/libsqlite3.dylib";
  };
}

If you are not using Nix, you can locate the libsqlite3.dylib on macOS by running:

otool -L $(which sqlite3) | grep "sqlite3.dylib"

Additional documentation can be found under doc/.

legendary.nvim's People

Contributors

figsoda avatar hinell avatar lmburns avatar lvimuser avatar mracos avatar mrjones2014 avatar nifoc avatar olimorris avatar simon123h avatar smjonas avatar songww avatar tsyroid avatar tversteeg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

legendary.nvim's Issues

[Bug]: Can't run commands without specifying an empty opts table

Similar Issues

  • Before filing, I have searched for similar issues.

Neovim Version

NVIM v0.7.0-dev+nightly
Build type: Debug
LuaJIT 2.1.0-beta3
Compilation: /Library/Developer/CommandLineTools/usr/bin/cc -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -DNVIM_TS_HAS_SET_MATCH_LIMIT -DNVIM_TS_HAS_SET_ALLOCATOR -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wdouble-promotion -Wmissing-noreturn -Wmissing-format-attribute -Wmissing-prototypes -Wimplicit-fallthrough -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=always -DINCLUDE_GENERATED_DECLARATIONS -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -DMIN_LOG_LEVEL=1 -I/Users/Oli/.neovim/1649746983/build/config -I/Users/Oli/.neovim/1649746983/src -I/Users/Oli/.neovim/1649746983/.deps/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -I/opt/homebrew/opt/gettext/include -I/Users/Oli/.neovim/1649746983/build/src/nvim/auto -I/Users/Oli/.neovim/1649746983/build/include
Compiled by Oli@Oli

Features: +acl +iconv +tui
See ":help feature-compile"

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/usr/local/share/nvim"

Expected Behavior

I should be able to run a command from legendary without having to add opts = {} to all of my existing commands.

Actual Behavior

I get an error:

Error executing vim.schedule lua callback: ...k/packer/start/legendary.nvim/lua/legendary/executor.lua:45: attempt to index local 'opts' (a nil value)
stack traceback:
        ...k/packer/start/legendary.nvim/lua/legendary/executor.lua:45: in function 'exec'
        ...k/packer/start/legendary.nvim/lua/legendary/executor.lua:84: in function 'try_execute'
        ...k/packer/start/legendary.nvim/lua/legendary/bindings.lua:267: in function <...k/packer/start/legendary.nvim/lua/legendary/bindings.lua:266>

Minimal Configuration to Reproduce

-- legendary.lua
local M = {}
function M.setup()
  local ok, legendary = om.safe_require("legendary")
  if not ok then
    return
  end

  legendary.setup({
    include_builtin = false,
    keymaps = require(config_namespace .. ".core.mappings").default_keymaps(),
    commands = require(config_namespace .. ".core.commands").default_commands(),
    autocmds = require(config_namespace .. ".core.autocmds").default_autocmds(),
    auto_register_which_key = false,
  })
end
return M

-- commands.lua
local M = {}
function M.default_commands()
  return {
    {
      "LineNumbers",
      function()
        om.ToggleLineNumbers()
      end,
      description = "Toggle line numbers",
    },
  }
end
return M

Additional Details and/or Screenshots

The problem is solved if you add an empty opts table. Like:

{
  "LineNumbers",
  function()
    om.ToggleLineNumbers()
  end,
  description = "Toggle line numbers",
  opts = {}
},

Check here for breaking changes

Neovim changed nvim_add_user_command to nvim_create_user_command, update to latest Neovim if you run into an error relating to this.

Revamped documentation

The README.md is getting quite big. We should break it down into either separate files or better organized sections.

We should have a section explaining in detail the required table structures for each type:

  • keymaps
  • commands
  • augroups
  • autocmds

And then a section on the Lua API functions, how/when to use them vs. using require('legendary').setup() etc.

[Bug]: `Error detected while processing VimEnter Autocommands for "*":`

Similar Issues

  • Before filing, I have searched for similar issues.

Neovim Version

NVIM v0.7.0-dev+1437-g356cff78e
Build type: Release
LuaJIT 2.1.0-beta3
Compiled by bennyp@iMac

Features: +acl +iconv +tui
See ":help feature-compile"

system vimrc file: "$VIM/sysinit.vim"
fall-back for $VIM: "/usr/local/Cellar/neovim/HEAD-356cff7/share/nvim"

Run :checkhealth for more info

Expected Behavior

as per README

Actual Behavior

I can launch the command palette, but which-key no longer displays prompts for registered bindings

Minimal Configuration to Reproduce

working on it... TBD

Additional Details and/or Screenshots

Error when launching nvim:

Error detected while processing VimEnter Autocommands for "*":
E5108: Error executing lua .../start/legendary.nvim/lua/legendary/compat/which-key.lua:31: attempt to get length of a boolean value
stack traceback:
        .../start/legendary.nvim/lua/legendary/compat/which-key.lua:31: in function <.../start/legendary.nvim/lua/legendary/compat/which-key.lua:27
>
        vim/shared.lua: in function 'tbl_map'
        .../start/legendary.nvim/lua/legendary/compat/which-key.lua:27: in function 'parse_whichkey'
        .../start/legendary.nvim/lua/legendary/compat/which-key.lua:46: in function 'bind_whichkey'
        .../start/legendary.nvim/lua/legendary/compat/which-key.lua:56: in function 'register'
        ...rt/which-key.nvim/lua/which-key/plugins/presets/misc.lua:86: in function 'setup'
        ...rt/which-key.nvim/lua/which-key/plugins/presets/init.lua:86: in function 'setup'
        ...cker/start/which-key.nvim/lua/which-key/plugins/init.lua:37: in function '_setup'
        ...cker/start/which-key.nvim/lua/which-key/plugins/init.lua:19: in function 'setup'
        .../pack/packer/start/which-key.nvim/lua/which-key/init.lua:87: in function 'load'
        [string ":lua"]:1: in main chunk
        ```

[Feature]: opts for visual and normal modes?

Similar Issues

  • Before filing, I have searched for similar issues.

Description

With the brilliant new feature added yesterday, enabling us to do this:

{ '<LocalLeader>"', { n = [[ciw"<c-r>""<esc>]], v = [[c"<c-r>""<esc>]] }, description = "Wrap in quotes" },

I quickly began trying to consolidate my keymaps. I have a very advanced multiple cursors mapping based on this excellent article:

vim.g.mc = vim.api.nvim_replace_termcodes([[y/\V<C-r>=escape(@", '/')<CR><CR>]], true, true, true)

{ "cn", "*``cgN", description = "Multiple cursors (backwards)" }
{ "cn", [[g:mc . "``cgn"]], description = "Multiple cursors", mode = { "x" }, opts = { expr = true } }

Unfortunately I can't consolidate them with the new feature as expr = true needs to be present for the x mode and not for the n mode.

If this is too much work, then forget it. It just saves a line and an extra row in my legendary popup. Thought it may be an interesting feature though.

Unit tests!

This plugin is growing in surface area. It would be great to get a decent set of unit tests in place.

[Bug]: Legendary thinks all `which-key` mappings are in normal mode

Similar Issues

  • Before filing, I have searched for similar issues.

Neovim Version

NVIM v0.7.0-dev+1443-gdbd5242d8
Build type: RelWithDebInfo
LuaJIT 2.1.0-beta3
Compilation: /usr/bin/gcc-11 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -DNVIM_TS_HAS_SET_MATCH_LIMIT -DNVIM_TS_HAS_SET_ALLOCATOR -O2 -g -Og -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wdouble-promotion -Wmissing-noreturn -Wmissing-format-attribute -Wmissing-prototypes -Wimplicit-fallthrough -Wsuggest-attribute=pure -Wsuggest-attribute=const -Wsuggest-attribute=malloc -Wsuggest-attribute=cold -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=always -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -DMIN_LOG_LEVEL=3 -I/home/runner/work/neovim/neovim/build/config -I/home/runner/work/neovim/neovim/src -I/home/runner/work/neovim/neovim/.deps/usr/include -I/usr/include -I/home/runner/work/neovim/neovim/build/src/nvim/auto -I/home/runner/work/neovim/neovim/build/include
Compiled by runner@fv-az32-353

Features: +acl +iconv +tui
See ":help feature-compile"

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/share/nvim"

Run :checkhealth for more info

Expected Behavior

I would expect for a mapping created in which-key, which has a mode other than n, would be picked up by legendary as that same mode.

Actual Behavior

legendary thinks that all which-key bindings are in normal mode.

Minimal Configuration to Reproduce

An example of a which-key binding that is not in normal mode is the following example.

require('which-key").register(
    {
        ["d"] = {[["_d]], "Delete (blackhole)"},
    },
    {mode = "v"}
)

When looking in legendary I see the following line:

n       │ d                       │ Delete (blackhole)   

Whenever creating a binding with legendary that species a mode, like the following example, everything is fine.

require("legendary").bind_keymap(
    {
        "<C-,>",
        "<Cmd>Legendary keymaps<CR>",
        description = "Show Legendary keymaps",
        mode = {"n", "i", "x"}
    }
)

When looking in legendary I see the following line:

n, i, x │ <C-,>                   │ Show Legendary keymaps  

Additional Details and/or Screenshots

No response

Commands don't seem to work when they contain a pipe `|`

require('legendary').bind_command({ ':TestCommand', ':echo "test" | echo "test2"', description = 'Test command' })

The :TestCommand command when run manually prints the messages but not when pressing enter on it from the finder.

[Docs]: Improve documentation for possible table structures

Similar Issues

  • Before filing, I have searched for similar issues.

Description

There's a few different table structures that are accepted now. In particular, keymaps accept several different structures. They're all documented, but not super well. I see two main problems.

  1. The documentation that is there is too wordy. We need cold hard API documentation, with types. Honestly I'm considering rewriting parts in Teal so I can add static types and use a documentation generator for this.

  2. There needs to be a brief overview of the power of what you can do with legendary.nvim closer to the top of the README.md

@tsyroid @olimorris thoughts and input always appreciated.

Interactive command editor

There could be a cool interactive command editor here.

Maybe something like a buffer as a Lua REPL, then once you confirm what you want the implementation to be, it prompts you for the command name or keymap string. Then it would generate the Lua table and copy it to the clipboard or something?

[Feature]: Option to lazy-load key maps with an autocmd

Similar Issues

  • Before filing, I have searched for similar issues.

Description

I’m imaging an API like defining the keymap like so:

{
  ‘<leader>p’,
  require(‘legendary.helpers’).lazy(some_func, some_arg),
  description =something”,
  opts = {
    lazy = {
      event = { ‘FileType’ },
      pattern = { “rust” }
    }
  }
}

The above keymap definition would only be created when you enter a Rust file.

Executing a command which requires the word under the cursor

Hey Mr Jones.

I have 75% converted all of my keymaps, commands and autocmds over to legendary now and I couldn't be happier. I've noticed a bit of an edge case regarding some complex mappings I have so thought I'd share as I couldn't find anything in the readme.

I have a nifty keymap which replaces the word under the cursor, across the whole of a buffer:

vim.api.nvim_set_keymap("n", "<LocalLeader>[", [[:%s/\<<C-r>=expand("<cword>")<CR>\>/]], {})

However when I try to incorporate into legendary, like so:

{ "<LocalLeader>[", [[:%s/\<<C-r>=expand("<cword>")<CR>\>/]], description = "Replace cursor words in file"},

I get the following error:

Error executing vim.schedule lua callback: ...k/packer/start/legendary.nvim/lua/legendary/executor.lua:44: Vim(substitute):E486: Pattern not found: \<^A8=expand("<cword>")^K\>
stack traceback:
    [C]: in function 'cmd'
    ...k/packer/start/legendary.nvim/lua/legendary/executor.lua:44: in function 'exec'
    ...k/packer/start/legendary.nvim/lua/legendary/executor.lua:74: in function 'try_execute'
    ...k/packer/start/legendary.nvim/lua/legendary/bindings.lua:264: in function  <...k/packer/start/legendary.nvim/lua/legendary/bindings.lua:263>

I'm guessing that as the cursor has focussed to legendary.nvim then executing cword yields nothing.

Sort by mapping/command

It would be nice to have a way to sort the list. Is the sort controlled by Legendary or the configured select function? I'm using Telescope via dressing right now.

Custom entry format

Config option, function that takes the entry table and returns a table of values. Will add more details tomorrow

Add CONTRIBUTING.md

All PRs should pass CI, which runs luacheck and stylua, as well as the unit tests.

Should also include notes about updating the documentation in the README.md if you're changing public APIs.

Create a parser to convert Vimscript keymaps into legendary tables

Theoretically we should be able to parse a Vimscript keymap in the form:

vnoremap <leader>t :DoSomethingWithLeaderT<CR>

and convert that into the equivalent legendary keymap table:

{
  '<leader>t',
  ':DoSomethingWithLeaderT<CR>',
  mode = 'v',
  opts = {
    noremap = true,
  },
}

We would need to take into consideration all the different options and types of mapping commands in order to set all the right options on the table.

Implement "groups" of keymaps/commands

which-key has a concept of "groups" of commands.

it would be cool to support something similar, where selecting a "group" then re-triggers legendary.nvim and searches keymaps/commands within that group.

Figure out how to support executing visual mode commands

Right now we can only execute normal and visual mode commands, because I haven't found a way to programmatically enter visual mode.

As a last resort we could do something like:

vim.cmd('stopinsert')
vim.api.nvim_feedkeys('v', 't', true)

but hopefully there's a better, more stable way.

Integration with 'personal' keymaps

Meaning, my efforts at integrating legendary with my mappings-ng.lua file.

I've achieved this by using the :require('legendary').bind_whichkey(wk_tbls, wk_opts) (thanks to mat) command from the vim comandline. All good. But when I tried to integrate this into my config (by using the above 'require' in place of my 'require('legendary').setup()' line everything blew up (nvim init failed).

My current (working) config is attached for reference.

Seems to me this solution is rather 'inelegant'. Looking for a cleaner solution.

/tom

paste.md

Allow `select_prompt` config to be either a string or a function

We should allow select_prompt to be a function, and if it's a function, pass it the type currently being searched, e.g. the kind that is passed to vim.ui.select.

This way, we could make it so that, if you're only searching keymaps, for example, we can make the prompt title "Legendary Keymaps" instead of just "Legendary"

[Feature]: Allow separate descriptions per mode

Similar Issues

  • Before filing, I have searched for similar issues.

Description

Currently description is only read from the outermost table. When per-mode mappings are used, you should be able to specify a separate description for each.

[Enhancement] Recently used maps or commands

Firstly, thanks for such an amazing plugin. Our correspondence on Reddit last night convinced me to try this out. Totally revolutionising how I use Neovim.

One thing I thought would be a great, low priority enhancement, would be to open legendary and see my most commonly used commands at the top of the window.

Appreciate this would be an additional dependency (likely on sqlite.lua) so this should be an optional add in for people.

[Bug]: Description column in UI is misaligned if keymap contains specialchar

Similar Issues

  • Before filing, I have searched for similar issues.

Neovim Version

NVIM v0.7.0-dev+nightly
Build type: Debug
LuaJIT 2.1.0-beta3
Compilation: /Library/Developer/CommandLineTools/usr/bin/cc -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -DNVIM_TS_HAS_SET_MATCH_LIMIT -DNVIM_TS_HAS_SET_ALLOCATOR -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wimplicit-fallthrough -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=always -DINCLUDE_GENERATED_DECLARATIONS -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -DMIN_LOG_LEVEL=1 -I/Users/Oli/.neovim/1647624272/build/config -I/Users/Oli/.neovim/1647624272/src -I/Users/Oli/.neovim/1647624272/.deps/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/usr/include -I/opt/homebrew/opt/gettext/include -I/Users/Oli/.neovim/1647624272/build/src/nvim/auto -I/Users/Oli/.neovim/1647624272/build/include
Compiled by Oli@Oli

Features: +acl +iconv +tui
See ":help feature-compile"

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/usr/local/share/nvim"

Run :checkhealth for more info

Expected Behavior

The three columns in the legendary UI should always be aligned

Actual Behavior

The special chars I have in four of my keymaps cause a weird misalignment in the columns:

Screen Shot 2022-03-21 at 07 57 00@2x

Minimal Configuration to Reproduce

local maps = {
  { "", "<cmd>move+<CR>==", description = "Move line down" },
  { "˚", "<cmd>move-2<CR>==", description = "Move line up" },
  { "", ":move'>+<CR>='[gv", description = "Move line down", mode = { "v" } },
  { "˚", ":move-2<CR>='[gv", description = "Move line up", mode = { "v" } },
}
require("legendary").bind_keymaps(maps)

Additional Details and/or Screenshots

No response

Integration with Which-Key

Plugin looks great! Would love it if I could plug in my which_key tables to the fuzzy finder here - a real replacement for atom command palette. Which key and legendary could really complement each other perfectly

It's two different tasks: "I remember the leader key category but can't remember what's under it" (which key) vs "I remember the description but not the command or binding" (legendary)

In Atom, there's the command palette for the latter and the keybinding resolver for the former

Longer term, we can imagine a pseudo-standard way to document and describe bindings and commands that any UI could consume and display

Remove the hard requirement for a description

We could just show "No description provided" as a default description.

This would make the migration path a lot easier. We could even set up an interceptor for calls to vim.keymap.set and load them into legendary, similar to how we're intercepting which-key.nvim mappings.

One consideration would be, maybe we still require descriptions for autocmds to appear in the finder, since I think these should not appear by default. I feel like most autocmds should be pretty transparent, I don't think I ever actually used :doautocmd to manually trigger an autocmd.

Keymapping & Command Helpers

PRs are more than welcome to add new helpers for making keymaps and commands (see lua/helpers.lua)!

Please link your PR to this issue if you're adding helpers there.

Better way to show results from `:LegendaryScratchpad`

Right now it just uses vim.epi.nvim_err_writeln and vim.api.nvim_out_write, for errors vs. normal output, respectively.

That's fine, but there's probably better ways.

Maybe show it in a new scratch buffer in a floating window?

Maybe make this behavior configurable?

Missing Builtins?

Noticed a missing built-in keymap or command? Comment on this issue, or better yet, submit a Pull Request to add it!

Unexpected results from "first time" install

Attempting to install/configure legendary to mimic the same behaviour I experienced running it under your nvim configuration (https://github.com/mrjones2014/dotfiles/tree/master/.config/nvim).

At the time I opened this issue (reference note: commit a62b717 in my current nvim-dev tree):

  • it installs fine
  • it loads fine (that is, I can access all the legendary commands from the command line and they work as advertised)
  • I have no errors arising relating to legendary
  • I have been through your README multiple times
  • I have triple checked my config for all the obvious (it also loads and works without error or incident)
  • My nvim install, overall, is behaving as it should -- no errors or issues

What I expect:
When I key-press (in my install; was l in your example) I should be a popup dialogue with a list of the maps and commands listed in my config file. Instead I get a list of all available nvim commands.
Screenshot attached.
Config file attached

Screen Shot 2022-03-02 at 09 29 17

[legendary.txt](https://github.com/mrjones2014/legendary.nvim/files/8171772/legendary.txt) .

Improved validation of types

Currently everything works great as long as your tables are structured properly.

However, if they aren't, the error messages sometimes aren't super useful.

We can probably make the error messages better and validate really nicely using vim.validate. See :h vim.validate.

Implement an API to auto-load commands, autocmds, and keymaps from the nvim API

Say you already have keymaps being set up another way, you just want them to be searchable with legendary.nvim.

We could load the commands, autocmds, and keymaps through the nvim APIs, as long as they have the desc key set.

Although I'm not sure how to do this effectively because right now, the API functions use the same table field definition for the description, or if no description is set, it's just the implementation, which we wouldn't wanna show as a description.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.