robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesdocs: bufadd(), fnameescape() guidance #403788e3b216d0b

master
13.9 KiB360 linesraw
1*lua-plugin.txt*                     Nvim
2
3                            NVIM REFERENCE MANUAL
4
5                   Guide to developing Lua plugins for Nvim
6
7
8                                       Type |gO| to see the table of contents.
9
10==============================================================================
11Introduction                                                       *lua-plugin*
12
13This document provides guidance for developing Nvim Lua plugins.
14
15- See |lua-guide| for guidance on using Lua to configure and operate Nvim.
16- See |luaref| and |lua-concepts| for details on the Lua programming language.
17
18==============================================================================
19Creating your first plugin                                    *lua-plugin-new*
20
21Any Vimscript or Lua code file that lives in the right directory,
22automatically is a "plugin". There's no manifest or "registration" step.
23
24You can try it right now:
25
261. Visit your config directory: >
27    :exe 'edit' stdpath('config')
282. Create a `plugin/foo.lua` file in there.
293. Add something to it, like: >lua
30    vim.print('Hello World')
314. Start `nvim` and notice that it prints "Hello World" in the messages area.
32   Check `:messages` if you don't see it.
33
34Besides `plugin/foo.lua`, which is always run at startup, you can define Lua
35modules in the `lua/` directory. Those modules aren't loaded until your
36`plugin/foo.lua`, or the user, calls `require(…)`.
37
38==============================================================================
39Type safety                                            *lua-plugin-type-safety*
40
41Lua, as a dynamically typed language, is great for configuration. It provides
42virtually immediate feedback.
43But for larger projects, this can be a double-edged sword, leaving your plugin
44susceptible to unexpected bugs at the wrong time.
45
46You can leverage LuaCATS or "emmylua" annotations https://luals.github.io/wiki/annotations/
47along with lua-language-server ("LuaLS") https://luals.github.io/ to catch
48potential bugs in your CI before your plugin's users do. The Nvim codebase
49uses these annotations extensively.
50
51TOOLS
52
53- lua-typecheck-action https://github.com/marketplace/actions/lua-typecheck-action
54- lua-language-server https://luals.github.io
55
56==============================================================================
57Keymaps                                                   *lua-plugin-keymaps*
58
59Avoid creating excessive keymaps automatically. Doing so can conflict with
60user |mapping|s.
61
62NOTE: An example for uncontroversial keymaps are buffer-local |mapping|s for
63      specific file types or floating windows, or <Plug> mappings.
64
65A common approach to allow keymap configuration is to define a declarative DSL
66https://en.wikipedia.org/wiki/Domain-specific_language via a `setup` function.
67
68However, doing so means that
69
70- You will have to implement and document it yourself.
71- Users will likely face inconsistencies if another plugin has a slightly
72  different DSL.
73- |init.lua| scripts that call such a `setup` function may throw an error if
74  the plugin is not installed or disabled.
75
76As an alternative, you can provide |<Plug>| mappings to allow users to define
77their own keymaps with |vim.keymap.set()|.
78
79- This requires one line of code in user configs.
80- Even if your plugin is not installed or disabled, creating the keymap won't
81  throw an error.
82
83Another option is to simply expose a Lua function or |user-commands|.
84
85Some benefits of |<Plug>| mappings are that you can
86
87- Enforce options like `expr = true`.
88- Use |vim.keymap|'s built-in mode handling to expose functionality only for
89  specific |map-modes|.
90- Handle different |map-modes| differently with a single mapping, without
91  adding mode checks to the underlying implementation.
92- Detect user-defined mappings through |hasmapto()| before creating defaults.
93
94Some benefits of exposing a Lua function are:
95
96- Extensibility, if the function takes an options table as an argument.
97- A cleaner UX, if there are many options and enumerating all combinations
98  of options would result in a lot of |<Plug>| mappings.
99
100NOTE: If your function takes an options table, users may still benefit
101      from |<Plug>| mappings for the most common combinations.
102
103KEYMAP EXAMPLE
104
105In your plugin:
106>lua
107    vim.keymap.set('n', '<Plug>(SayHello)', function()
108        print('Hello from normal mode')
109    end)
110
111    vim.keymap.set('v', '<Plug>(SayHello)', function()
112        print('Hello from visual mode')
113    end)
114<
115In the user's config:
116>lua
117    vim.keymap.set({'n', 'v'}, '<leader>h', '<Plug>(SayHello)')
118<
119==============================================================================
120Initialization                                               *lua-plugin-init*
121
122Strictly separated configuration and smart initialization allow your plugin to
123work out of the box. Common approaches are:
124
125- A Lua function, e.g. `setup(opts)` or `configure(opts)`, which only overrides the
126  default configuration and does not contain any initialization logic.
127- A Vimscript compatible table (e.g. in the |vim.g| or |vim.b| namespace) that your
128  plugin reads from and validates at initialization time.
129  See also |lua-vim-variables|.
130
131Typically, automatic initialization logic is done in a |plugin| or |ftplugin|
132script. See also 'runtimepath'.
133
134On the other hand, a single `setup(opts)` that combines configuration and
135initialization may be useful in specific cases:
136
137- Customizing complex initialization, where there is a significant risk of
138  misconfiguration.
139- Requiring users to opt in for plugin functionality that should not be
140  initialized automatically.
141
142Keep in mind that this approach requires users to call `setup` in order to
143use your plugin, even if the default configuration is enough for them.
144Consider carefully whether your plugin benefits from combined `setup()` pattern
145before adopting it. This article chronicles the history and tradeoffs of
146`setup()`: https://mrcjkb.dev/posts/2023-08-22-setup.html
147
148NOTE: A well designed plugin has minimal impact on startup time. See also
149|lua-plugin-lazy|.
150
151==============================================================================
152Lazy loading                                                 *lua-plugin-lazy*
153
154Some users like to micro-manage "lazy loading" of plugins by explicitly
155configuring which commands and key mappings load the plugin.
156
157Your plugin should not depend on every user micro-managing their configuration
158in such a way. Nvim has a mechanism for every plugin to do its own implicit
159lazy-loading, via |autoload| (Vimscript) and `lua/` (Lua).
160
161Plugin authors can provide "lazy loading" by providing a `plugin/<name>.lua`
162file which defines their commands and keymappings. This file should be small,
163and should not eagerly `require()` the rest of your plugin. Commands and
164mappings should do the `require()`.
165
166Guidance:
167
168- Plugins should arrange their "lazy" behavior once, instead of expecting
169  every user to micromanage it.
170- Keep `plugin/<name>.lua` small, avoid eagerly calling `require()` on modules
171  until a command or mapping is actually used.
172
173------------------------------------------------------------------------------
174Defer require() calls                               *lua-plugin-defer-require*
175
176`plugin/<name>.lua` scripts (|plugin|) are eagerly run at startup; this is
177intentional, so that plugins can setup the (minimal) commands and keymappings
178that users will use to invoke the plugin. This also means these "plugin/"
179files should NOT eagerly `require` Lua modules.
180
181For example, instead of:
182>lua
183    local foo = require('foo')
184    vim.api.nvim_create_user_command('MyCommand', function()
185        foo.do_something()
186    end, {
187      -- ...
188    })
189<
190which calls `require('foo')` as soon as the module is loaded, you can
191lazy-load it by moving the `require` into the command's implementation:
192>lua
193    vim.api.nvim_create_user_command('MyCommand', function()
194        local foo = require('foo')
195        foo.do_something()
196    end, {
197      -- ...
198    })
199<
200Likewise, if a plugin uses a Lua module as an entrypoint, it should
201defer `require` calls too.
202
203NOTE: For a Vimscript alternative to `require`, see |autoload|.
204
205NOTE: If you are worried about eagerly creating user commands, autocommands or
206keymaps at startup: Plugin managers that provide abstractions for lazy-loading
207plugins on such events do the same amount of work. There is no performance
208benefit for users to define lazy-loading entrypoints in their configuration
209instead of plugins defining it in `plugin/<name>.lua`.
210
211NOTE: You can use |--startuptime| to |profile| the impact a plugin has on
212startup time.
213
214------------------------------------------------------------------------------
215Filetype-specific functionality                          *lua-plugin-filetype*
216
217Consider making use of 'filetype' for any functionality that is specific to
218a filetype, by putting the initialization logic in a `ftplugin/{filetype}.lua`
219script.
220
221For buffers owned by your plugin (often used to show a custom UI or view),
222typically your plugin will set a custom 'filetype'. In that case, it's useful
223to set the 'filetype' "as late as possible", so that users can override
224buffer-local settings after your plugin has (re)initialized the buffer.
225
226FILETYPE EXAMPLE
227
228A plugin tailored to Rust development might have initialization in
229`ftplugin/rust.lua`:
230>lua
231    if not vim.g.loaded_my_rust_plugin then
232        -- Initialize
233    end
234    -- NOTE: Using `vim.g.loaded_` prevents the plugin from initializing twice
235    -- and allows users to prevent plugins from loading
236    -- (in both Lua and Vimscript).
237    vim.g.loaded_my_rust_plugin = true
238
239    local bufnr = vim.api.nvim_get_current_buf()
240    -- do something specific to this buffer,
241    -- e.g. add a |<Plug>| mapping or create a command
242    vim.keymap.set('n', '<Plug>(MyPluginBufferAction)', function()
243        print('Hello')
244    end, { buf = bufnr })
245<
246==============================================================================
247Opening files                                           *lua-plugin-open-file*
248
249To robustly open a file, see |open-file|.
250
251==============================================================================
252Configuration                                              *lua-plugin-config*
253
254To allow users to override buffer-local configuration for filetypes owned by
255your plugin, publish a |FileType| event, "as late as possible".
256|lua-plugin-filetype|
257
258Once you have merged the default configuration with the user's config, you
259should validate configs.
260
261Validations could include:
262
263- Correct types, see |vim.validate()|
264- Unknown fields in the user config (e.g. due to typos).
265  This can be tricky to implement, and may be better suited for a |health|
266  check, to reduce overhead.
267
268==============================================================================
269UI                                                           *lua-plugin-ui*
270
271Some plugins have their own "UI" which they present in a buffer that the
272plugin "owns". In that buffer typically you will want to provide custom
273actions.
274
275Besides creating |<Plug>| mappings, you may want to consider providing actions
276by defining an in-process LSP server. Offering actions as code-actions
277|vim.lsp.buf.code_action()| means the user can see all available actions using
278the default |gra| mapping to view the code-actions menu. They can even define
279mappings to a specific action by invoking `vim.lsp.buf.code_action()` with the
280`filter` + `apply` parameters: >lua
281
282    vim.lsp.buf.code_action({
283        apply = true,
284        filter = function(a)
285            return a.title == 'Do something'
286        end,
287    })
288<
289
290Example: See `runtime/lua/vim/pack/_lsp.lua` for how vim.pack defines an
291in-process LSP server to provide interactive features in its
292`nvim-pack://confirm` buffer.
293
294==============================================================================
295Troubleshooting                                   *lua-plugin-troubleshooting*
296
297While developing a plugin, you can use the |:restart| command to see the
298result of code changes in your plugin.
299
300HEALTH
301
302Nvim's "health" framework gives plugins a simple way to report status checks
303to users. See |health-dev| for an example.
304
305Basically, this just means your plugin will have a `lua/{plugin}/health.lua`
306file. |:checkhealth| will automatically find this file when it runs.
307
308Some things to validate:
309
310- User configuration
311- Proper initialization
312- Presence of Lua dependencies (e.g. other plugins)
313- Presence of external dependencies
314
315MINIMAL CONFIG TEMPLATE
316
317It can be useful to provide a template for a minimal configuration, along with
318a guide on how to use it to reproduce issues.
319
320==============================================================================
321Versioning and releases                                *lua-plugin-versioning*
322
323Consider:
324
325- Use |vim.deprecate()| or a `---@deprecate` annotation when you need to
326  communicate a (future) breaking change or discouraged practice.
327- Using SemVer https://semver.org/ tags and releases to properly communicate
328  bug fixes, new features, and breaking changes.
329- Automating versioning and releases in CI.
330- Publishing to luarocks https://luarocks.org, especially if your plugin
331  has dependencies or components that need to be built; or if it could be a
332  dependency for another plugin.
333
334FURTHER READING
335
336- Luarocks ❤️ Nvim https://github.com/nvim-neorocks/sample-luarocks-plugin
337
338VERSIONING TOOLS
339
340- luarocks-tag-release
341  https://github.com/marketplace/actions/luarocks-tag-release
342- release-please-action
343  https://github.com/marketplace/actions/release-please-action
344- semantic-release
345  https://github.com/semantic-release/semantic-release
346
347==============================================================================
348Documentation                                                 *lua-plugin-doc*
349
350Provide vimdoc (see |help-writing|), so that users can read your plugin's
351documentation in Nvim, by entering `:h {plugin}` in |command-mode|. The
352help-tags (the right-aligned "search keywords" in the help documents) are
353regenerated using the |:helptags| command.
354
355DOCUMENTATION TOOLS
356
357- panvimdoc https://github.com/kdheepak/panvimdoc
358
359
360vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: