robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1*dev.txt* Nvim 2 3 4 NVIM REFERENCE MANUAL 5 6 7Development of Nvim *development* *dev* 8 9This reference describes design constraints and guidelines, for developing 10Nvim applications or Nvim itself. See |dev-arch| for discussion of Nvim's 11architecture and internal concepts. 12 13Nvim is free and open source. Everybody is encouraged to contribute. 14 https://github.com/neovim/neovim/blob/master/CONTRIBUTING.md 15 16 Type |gO| to see the table of contents. 17 18============================================================================== 19Design goals *design-goals* 20 21Most important things come first (roughly). Some items conflict; this is 22intentional. A balance must be found. 23 24 25NVIM IS... IMPROVED *design-improved* 26 27The Neo bits of Nvim should make it a better Vim, without becoming a 28completely different editor. 29- In matters of taste, prefer Vim/Unix tradition. If there is no relevant 30 Vim/Unix tradition, consider the "common case". 31- There is no limit to the features that can be added. Select new features 32 based on (1) what users ask for, (2) how much effort it takes to implement 33 and (3) someone actually implementing it. 34- Backwards compatibility is a feature. The RPC API in particular should 35 never break. 36 37 38NVIM IS... WELL DOCUMENTED *design-documented* 39 40- A feature that isn't documented is a useless feature. A patch for a new 41 feature must include the documentation. 42- Documentation should be comprehensive and understandable. Use examples. 43- Don't make the text unnecessarily long. Less documentation means that an 44 item is easier to find. 45 46 47NVIM IS... FAST AND SMALL *design-speed-size* 48 49Keep Nvim small and fast. This directly affects versatility and usability. 50- Computers are becoming faster and bigger each year. Vim can grow too, but 51 no faster than computers are growing. Keep Vim usable on older systems. 52- Many users start Vim from a shell very often. Startup time must be short. 53- Commands must work efficiently. The time they consume must be as small as 54 possible. Useful commands may take longer. 55- Don't forget that some people use Vim over a slow connection. Minimize the 56 communication overhead. 57- Vim is a component among other components. Don't turn it into a massive 58 application, but have it work well together with other programs 59 ("composability"). 60 61 62NVIM IS... MAINTAINABLE *design-maintain* 63 64- The source code should not become a mess. It should be reliable code. 65- Use comments in a useful way! Quoting the function name and argument names 66 is NOT useful. Do explain what they are for. 67- Porting to another platform should be made easy, without having to change 68 too much platform-independent code. 69- Use the object-oriented spirit: Put data and code together. Minimize the 70 knowledge spread to other parts of the code. 71 72 73NVIM IS... NOT *design-not* 74 75Nvim is not an operating system; instead it should be composed with other 76tools or hosted as a component. Marvim once said: "Unlike Emacs, Nvim does not 77include the kitchen sink... but it's good for plumbing." 78 79 80============================================================================== 81Developer guidelines *dev-guidelines* 82 83------------------------------------------------------------------------------ 84Providers *dev-provider* 85 86A primary goal of Nvim is to allow extension of the editor without special 87knowledge in the core. Some core functions are delegated to "providers" 88implemented as external scripts. 89 90Examples: 91 921. In the Vim source code, clipboard logic accounts for more than 1k lines of 93 C source code (ui.c), to perform two tasks that are now accomplished with 94 shell commands such as xclip or pbcopy/pbpaste. 952. Python scripting support: Vim has three files dedicated to embedding the 96 Python interpreter: if_python.c, if_python3.c and if_py_both.h. Together 97 these files sum about 9.5k lines of C source code. In contrast, Nvim Python 98 scripting is performed by an external host process implemented in ~2k lines 99 of Python. 100 101The provider framework invokes Vimscript from C. It is composed of two 102functions in eval.c: 103 104- eval_call_provider({name}, {method}, {arguments}, {discard}): Calls 105 `provider#{name}#Call` with {method} and {arguments}. If {discard} is true, any 106 value returned by the provider will be discarded and empty value will be 107 returned. 108- eval_has_provider({name}): Checks the `g:loaded_{name}_provider` variable 109 which must be set to 2 by the provider script to indicate that it is 110 "enabled and working". Called by |has()| to check if features are available. 111 112For example, the Python provider is implemented by the 113"autoload/provider/python.vim" script, which sets `g:loaded_python_provider` 114to 2 only if a valid external Python host is found. Then `has("python")` 115reflects whether Python support is working. 116 117 *provider-reload* 118Sometimes a GUI or other application may want to force a provider to 119"reload". To reload a provider, undefine its "loaded" flag, then use 120|:runtime| to reload it: >vim 121 122 :unlet g:loaded_clipboard_provider 123 :runtime autoload/provider/clipboard.vim 124 125 126------------------------------------------------------------------------------ 127Documentation *dev-doc* 128 129- "Just say it". Avoid mushy, colloquial phrasing in all documentation 130 (docstrings, user manual, website materials, newsletters, …). Don't mince 131 words. Personality and flavor, used sparingly, are welcome--but in general, 132 optimize for the reader's time and energy: be "precise yet concise". 133 - Prefer the active voice: "Foo does X", not "X is done by Foo". 134 - "The words you choose are an essential part of the user experience." 135 https://developer.apple.com/design/human-interface-guidelines/writing 136 - "...without being overly colloquial or frivolous." 137 https://developers.google.com/style/tone 138- Write docstrings (as opposed to inline comments) with present tense ("Gets"), 139 not imperative ("Get"). This tends to reduce ambiguity and improve clarity 140 by describing "What" instead of "How". > 141 ✅ OK: 142 /// Gets a highlight definition. 143 ❌ NO: 144 /// Get a highlight definition. 145- Avoid starting docstrings with "The" or "A" unless needed to avoid 146 ambiguity. This is a visual aid and reduces noise. > 147 ✅ OK: 148 /// @param dirname Path fragment before `pend` 149 ❌ NO: 150 /// @param dirname The path fragment before `pend` 151- Vim differences: 152 - Do not prefix help tags with "nvim-". Use |vim_diff.txt| to catalog 153 differences from Vim; no other distinction is necessary. 154 - If a Vim feature is removed, delete its help section and move its tag to 155 |vim_diff.txt|. 156- Mention deprecated features in |deprecated.txt| and delete their old doc. 157- Use consistent language. 158 - "terminal" in a help tag always means "the embedded terminal emulator", 159 not "the user host terminal". 160 - Use "tui-" to prefix help tags related to the host terminal, and "TUI" 161 in prose if possible. 162- Rough guidelines on where Lua documentation should end up: 163 - Nvim API functions `vim.api.nvim_*` should be in `api.txt`. 164 - If the module is big and not relevant to generic and lower-level Lua 165 functionality, then it's a strong candidate for separation. Example: 166 `treesitter.txt` 167 - Otherwise, add them to `lua.txt` 168 169DOCUMENTATION FORMAT 170 171For Nvim-owned docs, use the following strict subset of "vimdoc" to ensure 172the help doc renders nicely in other formats (such as HTML: 173https://neovim.io/doc/user ). 174 175Strict "vimdoc" subset: 176 177- Use lists (like this!) prefixed with "-" or "•", for adjacent lines that you 178 don't want to auto-wrap. Lists are always rendered with "flow" layout 179 (soft-wrapped) instead of preformatted (hard-wrapped) layout common in 180 legacy :help docs. You can also use numbered lists, e.g. "1." 181- Separate blocks (paragraphs) of content by a blank line. 182- Do not use indentation in random places—that prevents the page from using 183 "flow" layout. If you need a preformatted section, put it in 184 a |help-codeblock| starting with ">". 185- Parameters and fields are documented as `{foo}`. 186- Optional parameters and fields are documented as `{foo}?`. 187 188C DOCSTRINGS 189 190Nvim API documentation lives in the source code, as docstrings (doc 191comments) on the function definitions. The |api| :help is generated 192from the docstrings defined in src/nvim/api/*.c. 193 194Docstring format: 195- Lines start with `///` 196- Special tokens start with `@` followed by the token name: 197 `@note`, `@param`, `@return` 198- Markdown is supported. 199- Tags are written as `[tag]()`. 200- References are written as `[tag]` 201- Use "```" for code samples. 202 Code samples can be annotated as `vim` or `lua` 203 204Example: the help for |nvim_open_win()| is generated from a docstring defined 205in src/nvim/api/win_config.c like this: > 206 207 /// Opens a new window. 208 /// ... 209 /// 210 /// Example (Lua): window-relative float 211 /// 212 /// ```lua 213 /// vim.api.nvim_open_win(0, false, { 214 /// relative='win', 215 /// row=3, 216 /// col=3, 217 /// width=12, 218 /// height=3, 219 /// }) 220 /// ``` 221 /// 222 /// @param buffer Buffer to display 223 /// @param enter Enter the window 224 /// @param config Map defining the window configuration. Keys: 225 /// - relative: Sets the window layout, relative to: 226 /// - "editor" The global editor grid. 227 /// - "win" Window given by the `win` field. 228 /// - "cursor" Cursor position in current window. 229 /// ... 230 /// @param[out] err Error details, if any 231 /// 232 /// @return Window handle, or 0 on error 233 234 235LUA DOCSTRINGS *dev-lua-doc* 236Lua documentation lives in the source code, as docstrings on the function 237definitions. The |lua-vim| :help is generated from the docstrings. 238 239Docstring format: 240- Use LuaCATS annotations: https://luals.github.io/wiki/annotations/ 241- Markdown is supported. 242- Tags are written as `[tag]()`. 243- References are written as `[tag]` 244- Use "```" for code samples. 245 Code samples can be annotated as `vim` or `lua` 246- Use `@since <api-level>` to note the |api-level| when the function became 247 "stable". If `<api-level>` is greater than the current stable release (or 248 0), it is marked as "experimental". 249 - See scripts/util.lua for the mapping of api-level to Nvim version. 250- Use `@deprecated` to mark deprecated functions. 251- For callable module tables, document `__call` in `setmetatable(M, { ... })`. 252- Use `@nodoc` to prevent documentation generation. 253- Use `@private` for private functions. 254 - Naming a function with an underscore prefix ("_foo", not "foo") implies 255 `@nodoc` and `@private`. 256- Use `@internal` for non-public functions shared across Nvim modules, or 257 `@class (internal)` for shared internal types. Both hide generated docs. 258- Use `@inlinedoc` to inline `@class` blocks into `@param` blocks. 259 E.g. >lua 260 --- Object with fields: 261 --- @class myOpts 262 --- @inlinedoc 263 --- 264 --- Documentation for some field 265 --- @field somefield? integer 266 267 --- @param opts? myOpts 268 function foo(opts) 269 end 270< 271 272 Will be rendered as: >vimdoc 273 274 foo({opts}) 275 276 Parameters: 277 - {opts}? (table) Object with the fields: 278 - {somefield}? (integer) Documentation 279 for some field 280< 281- Files declared as `@meta` are only used for typing and documentation 282 (similar to "*.d.ts" typescript files). 283 284Example: the help for |vim.paste()| is generated from a docstring decorating 285vim.paste in runtime/lua/vim/_core/editor.lua like this: > 286 287 --- Paste handler, invoked by |nvim_paste()| when a conforming UI 288 --- (such as the |TUI|) pastes text into the editor. 289 --- 290 --- Example: To remove ANSI color codes when pasting: 291 --- 292 --- ```lua 293 --- vim.paste = (function() 294 --- local overridden = vim.paste 295 --- ... 296 --- end)() 297 --- ``` 298 --- 299 --- @since 12 300 --- @see |paste| 301 --- 302 --- @param lines ... 303 --- @param phase ... 304 --- @returns false if client should cancel the paste. 305 306 307EXX ERROR CODES *dev-error-codes* 308 309To choose a new "EXX" error code (e.g. |E5555|), just print a message with 310a new EXX number: > 311 emsg(_("E996: Invalid thing")); 312< 313To see existing error codes: >vim 314 :exe 'help' | let g:errtags=sort(map(taglist('E\d\d\d\?\d\?'), 'v:val.name'), 'N') | new | put =g:errtags 315 316The `linterrcodes` build target checks that all "EXX" codes are unique and 317have help tags. It runs in CI, but you can also run it locally: > 318 make linterrcodes 319< 320 321------------------------------------------------------------------------------ 322Stdlib *dev-lua* 323 324GUIDANCE 325 326- Lua names generally should conform to |dev-naming|. 327- Keep the core Lua modules |lua-stdlib| simple. Avoid elaborate OOP or 328 pseudo-OOP designs. Plugin authors just want functions to call, not a big, 329 fancy inheritance hierarchy. 330- Avoid requiring or returning special objects in the Nvim stdlib. Plain 331 tables or values are easier to serialize, easier to construct from literals, 332 easier to inspect and print, and inherently compatible with all Lua plugins. 333 (This guideline doesn't apply to opaque, non-data objects like `vim.cmd`.) 334- stdlib functions should follow these common patterns: 335 - Return |lua-result-or-message| (`any|nil,nil|string`) to communicate 336 failure, or choose from |dev-error-patterns| when appropriate. 337 - Accept iterable instead of only table. 338 - Note: in some cases iterable doesn't make sense, e.g. spair() sorts the 339 input by definition, so there is no reason for it to accept an iterable, 340 because the input needs to be "reified"; it can't operate on a "stream". 341 - Return an iterable (generator) instead of table, if possible. 342 - Mimic the pairs() or ipairs() interface if the function is intended for 343 use in a |for-in| loop. 344 345ERRORS *dev-error-patterns* 346 347To communicate failure to a consumer, choose from these patterns (in order of 348preference): 3491. `retval, errmsg` 350 - When failure is normal, or when it is practical for the consumer to 351 continue (fallback) in some other way. See |lua-result-or-message|. 3522. optional result, no errormsg 353 - Special case of 1. When there is only a single case of "doesn't exist" 354 (e.g. cache lookup, dict lookup). 3553. `error("no luck")` 356 - For invalid state ("must not happen"), when failure is exceptional, or at 357 a low level where the consumers are unlikely to handle it in a meaningful 358 way. Advantage is that propagation happens for free and it's harder to 359 accidentally swallow errors. (E.g. using 360 `uv_handle/pipe:write()` without checking return values is common.) 3614. `on_error` callback 362 - For async and "visitors" traversing a graph, where many errors may be 363 collected while work continues. 3645. `nvim_echo` (consider `opts.silent` for async/visitors) 365 - High-level / application-level messages. End-user invokes these directly. 366 367 368------------------------------------------------------------------------------ 369API *dev-api* 370 371Where applicable, this section applies to both Lua stdlib and RPC API. 372 373GUIDANCE 374 375- When adding an API, check the following: 376 - What precedents did you draw from? How does your solution compare to them? 377 - Does your new API allow future expansion? How? Or why not? 378 - Is the new API similar to existing APIs? Do we need to deprecate the old ones? 379 - Did you cross-reference related concepts in the docs? 380- Avoid "mutually exclusive" parameters (via constraints or limitations, if 381 necessary). For example nvim_create_autocmd() has mutually exclusive 382 "callback" and "command" args; but the "command" arg could be eliminated by 383 simply not supporting Vimscript function names, and treating a string 384 "callback" arg as an Ex command (which can call Vimscript functions). The 385 "buffer" arg could also be eliminated by treating a number "pattern" as 386 a buffer number. 387- Avoid functions that depend on cursor position, current buffer, etc. Instead 388 the function should take a position parameter, buffer parameter, etc. 389 390WHERE THINGS GO 391 392- API (libnvim/RPC): exposes low-level internals, or fundamental things (such 393 as `nvim_exec_lua()`) needed by clients or C consumers. 394- Lua stdlib = high-level functionality that builds on top of the API. 395 396See also |dev-layout|. 397 398API PATTERNS *dev-api-patterns* 399 400- When accepting a buffer id, etc., 0 means "current buffer", nil means "all 401 buffers". Likewise for window id, tabpage id, etc. 402 - Examples: |vim.lsp.codelens.clear()| |vim.diagnostic.enable()| 403- Any function signature that accepts a callback (example: |table.foreach()|) 404 should place it as the LAST parameter (after opts), if possible (or ALWAYS 405 for |continuation|s——functions called exactly once). 406 - Improves readability by placing the less "noisy" arguments near the start. 407 - Consistent with luv. 408 - Useful for future async lib which transforms functions of the form 409 `function(<args>, cb(<ret)>))` => `function(<args>) -> <ret>`. 410 - Example: >lua 411 -- ✅ OK: 412 filter(…, opts, fn) 413 -- ❌ NO: 414 filter(…, fn, opts) 415- If the module or topic wants to support configuration: 416 - Prefer a new 'option' (or family of related options, or "xxoptions" style 417 such as 'jumpoptions'). Options get these benefits "for free": 418 - Completion: `:set a<tab>`, `:lua vim.o.a<tab>` 419 - |OptionSet| event 420 - Scopes: global/buf/win/tab (can start as global, then "graduate" later) 421 - UI: `:verbose set`, `:options`, etc. 422 - Alternatively if the editor |options| system absolutey doesn't fit: Expose 423 a `config(opts)` interface (example: |vim.diagnostic.config()|). If `opts` 424 is omitted (or `nil`) it returns the current configuration. 425- "Enable" ("toggle") interface and behavior: 426 - `enable(…, nil)` and `enable(…, {buf=nil})` are synonyms and control 427 the "global" enablement of a feature. 428 - `is_enabled(nil)` and `is_enabled({buf=nil})`, likewise, query the 429 global state of the feature. 430 - `enable(…, {buf: number})` sets a buffer-local "enable" flag. 431 - `is_enabled({buf: number})`, likewise, queries the buffer-local state of 432 the feature. 433 - See |vim.lsp.inlay_hint.enable()| and |vim.lsp.inlay_hint.is_enabled()| 434 for a reference implementation of these "best practices". 435 - NOTE: open questions: https://github.com/neovim/neovim/issues/28603 436- Transformation functions should also have "filter" functionality (when 437 appropriate): when the function returns a nil value it excludes (filters 438 out) its input, else the transformed value is used. 439 - Example: See the format() field of |vim.diagnostic.Opts.Float|. 440- Do not add "foreach" functions (e.g. |LanguageTree:for_each_tree()|). 441 Instead return an |iterable|, which is more flexible and composable: > 442 vim.iter(parser.tree_iter()):each(function() 443 ... 444 end) 445< 446 447------------------------------------------------------------------------------ 448NAMING *dev-naming* 449 450Naming is exceedingly important: the name of a thing is the primary interface 451for uses it, discusses it, searches for it, shares it... Consistent 452naming in the stdlib, API, and UI helps both users and developers discover and 453intuitively understand related concepts ("families"), and reduces cognitive 454burden. Discoverability encourages code re-use and likewise avoids redundant, 455overlapping mechanisms, which reduces code surface-area, and thereby minimizes 456bugs... 457 458In general, look for precedent when choosing a name, that is, look at existing 459(non-deprecated) functions. In particular, see below... 460 461 *dev-name-common* 462Use existing common {verb} names (actions) if possible: 463 - add: Appends or inserts into a collection 464 - attach: Listens to something to get events from it (TODO: rename to "on"?) 465 - call: Calls a function 466 - callback |continuation|: Function parameter (NOT a field) that 467 returns the result of an async function. Use the "on_…" 468 naming-convention for all other callbacks and event handlers. 469 - cancel: Cancels or dismisses an event or interaction, typically 470 user-initiated and without error. (Compare "abort", which 471 cancels and signals error/failure.) 472 - clear: Clears state but does not destroy the container 473 - close: Releases/destroys a resource. 474 - create: Creates a new (non-trivial) thing (TODO: rename to "def"?) 475 - del: Deletes a thing (or group of things) 476 - detach: Dispose attached listener (TODO: rename to "un"?) 477 - enable: Enables/disables functionality. Signature should be 478 `enable(enable?:boolean, filter?:table)`. 479 - eval: Evaluates an expression 480 - exec: Executes code, may return a result 481 - fmt: Formats 482 - get: Gets things. Two variants (overloads): 483 1. `get<T>(id: int): T` returns one item. 484 2. `get<T>(filter: dict): T[]` returns a list. 485 - has: Checks for the presence of an item, feature, etc. 486 - inspect: Presents a high-level, often interactive, view 487 - is_enabled: Checks if functionality is enabled. 488 - on_…: Handles events or async results, or registers such 489 a handler. |dev-name-events| 490 - open: Opens something (a buffer, window, …) 491 - parse: Parses something into a structured form 492 - request: Calls a remote (network, RPC) operation. 493 - send: Writes data or a message to a channel. 494 - set: Sets a thing (or group of things) 495 - start: Spin up a long-lived process. Prefer "enable" except when 496 "start" is obviously more appropriate. 497 - stop: Inverse of "start". Teardown a long-lived process. 498 - try_{verb}: Best-effort operation, failure returns null or error obj 499 500Do NOT use these deprecated verbs: 501 - contains: Prefer "has". 502 - destroy: Prefer "close". 503 - disable: Prefer `enable(enable: boolean)`. 504 - exit: Prefer "cancel" (or "stop" if appropriate). 505 - is_disabled: Prefer `!is_enabled()`. 506 - list: Redundant with "get" 507 - notify: Redundant with "print", "echo" 508 - show: Redundant with "print", "echo" 509 - toggle: Prefer `enable(not is_enabled())`. 510 511Use consistent names for {topic} in API functions: buffer is called "buf" 512everywhere, not "buffer" in some places and "buf" in others. 513 - buf: Buffer 514 - chan: |channel| 515 - cmd: Command 516 - cmdline: Command-line UI or input 517 - dir: Directory 518 - fn: Function 519 - hl: Highlight 520 - pos: Position 521 - proc: System process 522 - tabpage: Tabpage 523 - win: Window 524 525Do NOT use these deprecated nouns: 526 - buffer Use "buf" instead 527 - command Use "cmd" instead 528 - window Use "win" instead 529 530 *continuation* 531A "continuation" is implemented as a callback function that returns the result 532of an async function and is called exactly once. Often accepts `err` as the 533first parameter, to avoid erroring on the main thread. Example: > 534 foo(…, callback: fun(err, …)) 535Use the name `callback` only for a continuation. All other callbacks and event 536handlers should be named with the `on_…` convention. |dev-name-events| 537 538 *dev-namespace-name* 539Use namespace names like `nvim.foo.bar`: > 540 vim.api.nvim_create_namespace('nvim.lsp.codelens') 541< 542 543 *dev-augroup-name* 544Use autocommand group names like `nvim.foo.bar`: > 545 vim.api.nvim_create_augroup('nvim.treesitter.dev') 546< 547 *dev-name-events* 548Use the "on_" prefix to name event-handling callbacks and also the interface for 549"registering" such handlers (on_key). The dual nature is acceptable to avoid 550a confused collection of naming conventions for these related concepts. 551 552Editor |events| (autocommands) are historically named like: > 553 {Noun}{Event} 554 555RPC API events use this format: > 556 nvim_{noun}_{event}_event (example: nvim_buf_changedtick_event) 557< 558 559RPC API NAMING *dev-api-name* 560 561Use this format to name new RPC |API| functions: > 562 nvim_{topic}_{verb}_{arbitrary-qualifiers} 563 564Do not add new nvim_buf/nvim_win/nvim_tabpage APIs, unless you are certain the 565concept will NEVER be applied to more than one "scope". That is, {topic} 566should be the TOPIC ("ns", "extmark", "option", …) that acts on the scope(s) 567(buf/win/tabpage/global), it should NOT be the scope. Instead the scope should 568be a parameter (typically manifest as mutually-exclusive buf/win/… flags like 569|nvim_get_option_value()|, or less commonly as a `scope: string` field like 570|nvim_get_option_info2()|). 571 572- Example: `nvim_get_keymap('v')` operates in a global context (first 573 parameter is not a Buffer). The "get" verb indicates that it gets anything 574 matching the given filter parameter. A "list" verb is unnecessary because 575 `nvim_get_keymap('')` (empty filter) returns all items. 576- Example: `nvim_buf_del_mark` acts on a `Buffer` object (the first parameter) 577 and uses the "del" {verb}. 578 579The RPC API doesn't have "modules" so its functions are grouped by a naming 580convention. Prefer the `nvim_{topic}_{verb}_…` convention where possible. 581 582Example: > 583 584 nvim_ns_add( 585 ns_id: int, 586 filter: { 587 handle: integer (buf/win/tabpage id) 588 scope: "global" | "win" | "buf" | "tabpage" 589 } 590 ): { ok: boolean } 591 592 nvim_ns_get( 593 ns_id: int, 594 filter: { 595 handle: integer (buf/win/tabpage id) 596 scope: "global" | "win" | "buf" | "tabpage" 597 } 598 ): { ids: int[] } 599 600 nvim_ns_del( 601 ns_id: int, 602 filter: { 603 handle: integer (buf/win/tabpage id) 604 scope: "global" | "win" | "buf" | "tabpage" 605 } 606 ): { ok: boolean } 607 608 609Anti-Example: 610 611Creating separate `nvim_xx`, `nvim_buf_xx`, `nvim_win_xx`, and 612`nvim_tabpage_xx`, functions all for the same `xx` topic, requires 4x the 613amount of documentation, tests, boilerplate, and interfaces, which users must 614comprehend, maintainers must maintain, etc. Thus the following is NOT 615recommended (compare these 12(!) functions to the above 3 functions): > 616 617 nvim_add_ns(…) 618 nvim_buf_add_ns(…) 619 nvim_win_add_ns(…) 620 nvim_tabpage_add_ns(…) 621 nvim_del_ns(…) 622 nvim_buf_del_ns(…) 623 nvim_win_del_ns(…) 624 nvim_tabpage_del_ns(…) 625 nvim_get_ns(…) 626 nvim_buf_get_ns(…) 627 nvim_win_get_ns(…) 628 nvim_tabpage_get_ns(…) 629 630 631------------------------------------------------------------------------------ 632Interface patterns *dev-interface-patterns* 633 634EX COMMANDS *dev-excmd* 635 636Prefer "flat" Ex commands (`:foobar`) instead of "subcommands" (`:foo bar`). 637except when the benefits below outweigh the costs. 638 639Pros of subcommands: 640- Useful when subcommands are discovered _at runtime_ (e.g. `:checkhealth foo`). 641 Plugins can extend the dispatcher by injecting subcommands. 642- `:Foo<tab>` completes only the `Foo` subcommands, whereas completing 643 a flat name matches every command sharing the prefix (e.g. `:FooBar` and 644 `:FootballBar`). 645- Completion can vary dynamically: e.g. `:lsp <tab>` can hide `stop` if no 646 client is running. (But this can be an antifeature, because it makes the 647 behavior less predictable.) 648 649Cons of subcommands: 650- Less harmonious with fuzzy pickers. Pickers can easily list `:foobar`, 651 whereas enumerating subcommands requires special logic. And in a picker, 652 `:foo bar` is often two "steps". 653- Adds a step when tab-completing. 654- Awkward to support `[!]`, ranges, `[count]`, etc., per-subcommand. 655- Implementation cost: a dispatcher with custom completion. 656 657 658------------------------------------------------------------------------------ 659API client *dev-api-client* 660 661 *api-client* 662API clients wrap the Nvim |API| to provide idiomatic "SDKs" for their 663respective platforms (see |jargon|). You can build a new API client for your 664favorite platform or programming language. 665 666List of API clients: 667 https://github.com/neovim/neovim/wiki/Related-projects#api-clients 668 669 *node-client* *pynvim* 670These clients can be considered the "reference implementation" for API clients: 671- https://github.com/neovim/node-client 672- https://github.com/neovim/pynvim 673 674STANDARD FEATURES 675 676- API clients exist to hide msgpack-rpc details. The wrappers can be 677 automatically generated by reading the |api-metadata| from Nvim. |api-mapping| 678- Clients should call |nvim_set_client_info()| after connecting, so users and 679 plugins can detect the client by handling the |ChanInfo| event. This avoids 680 the need for special variables or other client hints. 681- Clients should handle |nvim_error_event| notifications, which will be sent 682 if an async request to nvim was rejected or caused an error. 683 684PACKAGE NAMING 685 686API client packages should NOT be named something ambiguous like "neovim" or 687"python-client". Use "nvim" as a prefix/suffix to some other identifier 688following ecosystem conventions. 689 690For example, Python packages tend to have "py" in the name, so "pynvim" is 691a good name: it's idiomatic and unambiguous. If the package is named "neovim", 692it confuses users, and complicates documentation and discussions. 693 694Examples of API-client package names: 695- ✅ OK: nvim-racket 696- ✅ OK: pynvim 697- ❌ NO: python-client 698- ❌ NO: neovim_ 699 700API CLIENT IMPLEMENTATION 701 702- Separate the transport layer from the rest of the library. |rpc-connecting| 703- Use a MessagePack library that implements at least version 5 of the 704 MessagePack spec, which supports the BIN and EXT types used by Nvim. 705- Use a single-threaded event loop library/pattern. 706- Use a fiber/coroutine library for the language being used for implementing 707 a client. These greatly simplify concurrency and allow the library to 708 expose a blocking API on top of a non-blocking event loop without the 709 complexity that comes with preemptive multitasking. 710- Don't assume anything about the order of responses to RPC requests. 711- Clients should expect requests, which must be handled immediately because 712 Nvim is blocked while waiting for the client response. 713- Clients should expect notifications, but these can be handled "ASAP" (rather 714 than immediately) because they won't block Nvim. 715- For C/C++ projects, consider libmpack instead of the msgpack.org library. 716 https://github.com/libmpack/libmpack/ 717 libmpack is small (no dependencies, can inline into your C/C++ project) and 718 efficient (no allocations). It also implements msgpack-RPC, the protocol 719 required by Nvim. 720 https://github.com/msgpack-rpc/msgpack-rpc 721 722 723------------------------------------------------------------------------------ 724External UI *dev-ui* 725 726External UIs should be aware of the |api-contract|. In particular, future 727versions of Nvim may add new items to existing events. The API is strongly 728backwards-compatible, but clients must not break if new (optional) fields are 729added to existing events. 730 731STANDARD FEATURES 732 733External UIs are expected to implement these common features: 734 735- Call |nvim_set_client_info()| after connecting, so users and plugins can 736 detect the UI by handling the |ChanInfo| event. This avoids the need for 737 special variables and UI-specific config files (gvimrc, macvimrc, …). 738- Cursor style (shape, color) should conform to the 'guicursor' properties 739 delivered with the mode_info_set UI event. 740- Send the ALT/META ("Option" on macOS) key as a |<M-| chord. 741- Send the "super" key (Windows key, Apple key) as a |<D-| chord. 742- Avoid mappings that conflict with the Nvim keymap-space; GUIs have many new 743 chords (<C-,> <C-Enter> <C-S-x> <D-x>) and patterns ("shift shift") that do 744 not potentially conflict with Nvim defaults, plugins, etc. 745- Consider the "option_set" |ui-global| event as a hint for other GUI 746 behaviors. Various UI-related options ('guifont', 'ambiwidth', …) are 747 published in this event. See also "mouse_on", "mouse_off". 748- UIs generally should NOT set |$NVIM_APPNAME| (unless explicitly requested by 749 the user). 750- Support the text decorations/attributes given by |ui-event-hl_attr_define|. 751 The "url" attr should be presented as a clickable hyperlink. 752- Handle the "restart" UI event so that |:restart| works. 753- Detect capslock and show an indicator if capslock is active. 754 755 756MULTIGRID UI *dev-ui-multigrid* 757 758- A multigrid UI should display floating windows using one of the following 759 methods, using the `win_float_pos` |ui-multigrid| event. Different methods 760 can be selected for each window as needed. 761 762 1. Let Nvim determine the position and z-order of the windows. This can be 763 achieved by using the `compindex`, `screen_row`, and `screen_col` information from 764 the `win_float_pos` UI event. To allow Nvim to automatically determine the grid, 765 the UI should call `nvim_input_mouse` with 0 as the `grid` parameter. 766 2. Use the `anchor`, `anchor_grid`, `anchor_row`, `anchor_col`, and `zindex` as 767 references for positioning the windows. If windows are outside the screen, 768 it is the UI's responsibility to reposition and/or resize them. Since Nvim 769 lacks information about actual window placement in this case, the UI must 770 call `nvim_input_mouse` with the actual grid id, factoring in `mouse_enabled`. 771 Note: Some API functions may return unexpected results for these windows due 772 to the missing information. 773- For external windows, the grid id should also be passed to `nvim_input_mouse`. 774 775 vim:tw=78:ts=8:sw=4:et:ft=help:norl: