develop.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. *develop.txt* Nvim
  2. NVIM REFERENCE MANUAL
  3. Development of Nvim *development* *dev*
  4. This reference describes design constraints and guidelines, for developing
  5. Nvim applications or Nvim itself.
  6. Architecture and internal concepts are covered in src/nvim/README.md
  7. Nvim is free and open source. Everybody is encouraged to contribute.
  8. https://github.com/neovim/neovim/blob/master/CONTRIBUTING.md
  9. Type |gO| to see the table of contents.
  10. ==============================================================================
  11. Design goals *design-goals*
  12. Most important things come first (roughly). Some items conflict; this is
  13. intentional. A balance must be found.
  14. NVIM IS... IMPROVED *design-improved*
  15. The Neo bits of Nvim should make it a better Vim, without becoming a
  16. completely different editor.
  17. - In matters of taste, prefer Vim/Unix tradition. If there is no relevant
  18. Vim/Unix tradition, consider the "common case".
  19. - A feature that people do not know about is a useless feature. Don't add
  20. obscure features, or at least add hints in documentation that they exist.
  21. - There is no limit to the features that can be added. Selecting new features
  22. is based on (1) what users ask for, (2) how much effort it takes to
  23. implement and (3) someone actually implementing it.
  24. - Backwards compatibility is a feature. The RPC API in particular should
  25. never break.
  26. NVIM IS... WELL DOCUMENTED *design-documented*
  27. - A feature that isn't documented is a useless feature. A patch for a new
  28. feature must include the documentation.
  29. - Documentation should be comprehensive and understandable. Use examples.
  30. - Don't make the text unnecessarily long. Less documentation means that an
  31. item is easier to find.
  32. NVIM IS... FAST AND SMALL *design-speed-size*
  33. Keep Nvim small and fast.
  34. - Computers are becoming faster and bigger each year. Vim can grow too, but
  35. no faster than computers are growing. Keep Vim usable on older systems.
  36. - Many users start Vim from a shell very often. Startup time must be short.
  37. - Commands must work efficiently. The time they consume must be as small as
  38. possible. Useful commands may take longer.
  39. - Don't forget that some people use Vim over a slow connection. Minimize the
  40. communication overhead.
  41. - Vim is a component among other components. Don't turn it into a massive
  42. application, but have it work well together with other programs.
  43. NVIM IS... MAINTAINABLE *design-maintain*
  44. - The source code should not become a mess. It should be reliable code.
  45. - Use comments in a useful way! Quoting the function name and argument names
  46. is NOT useful. Do explain what they are for.
  47. - Porting to another platform should be made easy, without having to change
  48. too much platform-independent code.
  49. - Use the object-oriented spirit: Put data and code together. Minimize the
  50. knowledge spread to other parts of the code.
  51. NVIM IS... NOT *design-not*
  52. Nvim is not an operating system; instead it should be composed with other
  53. tools or hosted as a component. Marvim once said: "Unlike Emacs, Nvim does not
  54. include the kitchen sink... but it's good for plumbing."
  55. ==============================================================================
  56. Developer guidelines *dev-guidelines*
  57. PROVIDERS *dev-provider*
  58. A primary goal of Nvim is to allow extension of the editor without special
  59. knowledge in the core. Some core functions are delegated to "providers"
  60. implemented as external scripts.
  61. Examples:
  62. 1. In the Vim source code, clipboard logic accounts for more than 1k lines of
  63. C source code (ui.c), to perform two tasks that are now accomplished with
  64. shell commands such as xclip or pbcopy/pbpaste.
  65. 2. Python scripting support: Vim has three files dedicated to embedding the
  66. Python interpreter: if_python.c, if_python3.c and if_py_both.h. Together
  67. these files sum about 9.5k lines of C source code. In contrast, Nvim Python
  68. scripting is performed by an external host process implemented in ~2k lines
  69. of Python.
  70. The provider framework invokes VimL from C. It is composed of two functions
  71. in eval.c:
  72. - eval_call_provider(name, method, arguments, discard): calls
  73. provider#{name}#Call with the method and arguments. If discard is true, any
  74. value returned by the provider will be discarded and empty value will be
  75. returned.
  76. - eval_has_provider(name): Checks the `g:loaded_{name}_provider` variable
  77. which must be set to 2 by the provider script to indicate that it is
  78. "enabled and working". Called by |has()| to check if features are available.
  79. For example, the Python provider is implemented by the
  80. "autoload/provider/python.vim" script, which sets `g:loaded_python_provider`
  81. to 2 only if a valid external Python host is found. Then `has("python")`
  82. reflects whether Python support is working.
  83. *provider-reload*
  84. Sometimes a GUI or other application may want to force a provider to
  85. "reload". To reload a provider, undefine its "loaded" flag, then use
  86. |:runtime| to reload it: >
  87. :unlet g:loaded_clipboard_provider
  88. :runtime autoload/provider/clipboard.vim
  89. DOCUMENTATION *dev-doc*
  90. - "Just say it". Avoid mushy, colloquial phrasing in all documentation
  91. (docstrings, user manual, website materials, newsletters, …). Don't mince
  92. words. Personality and flavor, used sparingly, are welcome--but in general,
  93. optimize for the reader's time and energy: be "precise yet concise".
  94. - See https://developers.google.com/style/tone
  95. - Prefer the active voice: "Foo does X", not "X is done by Foo".
  96. - Vim differences:
  97. - Do not prefix help tags with "nvim-". Use |vim_diff.txt| to catalog
  98. differences from Vim; no other distinction is necessary.
  99. - If a Vim feature is removed, delete its help section and move its tag to
  100. |vim_diff.txt|.
  101. - Mention deprecated features in |deprecated.txt| and delete their old doc.
  102. - Use consistent language.
  103. - "terminal" in a help tag always means "the embedded terminal emulator",
  104. not "the user host terminal".
  105. - Use "tui-" to prefix help tags related to the host terminal, and "TUI"
  106. in prose if possible.
  107. - Docstrings: do not start parameter descriptions with "The" or "A" unless it
  108. is critical to avoid ambiguity. >
  109. GOOD:
  110. /// @param dirname Path fragment before `pend`
  111. BAD:
  112. /// @param dirname The path fragment before `pend`
  113. <
  114. Documentation format ~
  115. For Nvim-owned docs, use the following strict subset of "vimdoc" to ensure
  116. the help doc renders nicely in other formats (such as HTML:
  117. https://neovim.io/doc/user ).
  118. Strict "vimdoc" subset:
  119. - Use lists (like this!) prefixed with "-", "*", or "•", for adjacent lines
  120. that you don't want auto-wrapped. Lists are always rendered with "flow"
  121. (soft-wrapped) layout instead of preformatted (hard-wrapped) layout common
  122. in legacy :help docs.
  123. - Limitation: currently the parser https://github.com/neovim/tree-sitter-vimdoc
  124. does not understand numbered listitems, so use a bullet symbol (- or •)
  125. before numbered items, e.g. "- 1." instead of "1.".
  126. - Separate blocks (paragraphs) of content by a blank line(s).
  127. - Do not use indentation in random places—that prevents the page from using
  128. "flow" layout. If you need a preformatted section, put it in
  129. a |help-codeblock| starting with ">".
  130. C docstrings ~
  131. Nvim API documentation lives in the source code, as docstrings (Doxygen
  132. comments) on the function definitions. The |api| :help is generated
  133. from the docstrings defined in src/nvim/api/*.c.
  134. Docstring format:
  135. - Lines start with `///`
  136. - Special tokens start with `@` followed by the token name:
  137. `@note`, `@param`, `@returns`
  138. - Limited markdown is supported.
  139. - List-items start with `-` (useful to nest or "indent")
  140. - Use `<pre>` for code samples.
  141. Example: the help for |nvim_open_win()| is generated from a docstring defined
  142. in src/nvim/api/win_config.c like this: >
  143. /// Opens a new window.
  144. /// ...
  145. ///
  146. /// Example (Lua): window-relative float
  147. /// <pre>
  148. /// vim.api.nvim_open_win(0, false,
  149. /// {relative='win', row=3, col=3, width=12, height=3})
  150. /// </pre>
  151. ///
  152. /// @param buffer Buffer to display
  153. /// @param enter Enter the window
  154. /// @param config Map defining the window configuration. Keys:
  155. /// - relative: Sets the window layout, relative to:
  156. /// - "editor" The global editor grid.
  157. /// - "win" Window given by the `win` field.
  158. /// - "cursor" Cursor position in current window.
  159. /// ...
  160. /// @param[out] err Error details, if any
  161. ///
  162. /// @return Window handle, or 0 on error
  163. Lua docstrings ~
  164. *dev-lua-doc*
  165. Lua documentation lives in the source code, as docstrings on the function
  166. definitions. The |lua-vim| :help is generated from the docstrings.
  167. Docstring format:
  168. - Lines in the main description start with `---`
  169. - Special tokens start with `---@` followed by the token name:
  170. `---@see`, `---@param`, `---@returns`
  171. - Limited markdown is supported.
  172. - List-items start with `-` (useful to nest or "indent")
  173. - Use `<pre>` for code samples.
  174. Example: the help for |vim.paste()| is generated from a docstring decorating
  175. vim.paste in runtime/lua/vim/_editor.lua like this: >
  176. --- Paste handler, invoked by |nvim_paste()| when a conforming UI
  177. --- (such as the |TUI|) pastes text into the editor.
  178. ---
  179. --- Example: To remove ANSI color codes when pasting:
  180. --- <pre>
  181. --- vim.paste = (function()
  182. --- local overridden = vim.paste
  183. --- ...
  184. --- end)()
  185. --- </pre>
  186. ---
  187. ---@see |paste|
  188. ---
  189. ---@param lines ...
  190. ---@param phase ...
  191. ---@returns false if client should cancel the paste.
  192. LUA *dev-lua*
  193. - Keep the core Lua modules |lua-stdlib| simple. Avoid elaborate OOP or
  194. pseudo-OOP designs. Plugin authors just want functions to call, they don't
  195. want to learn a big, fancy inheritance hierarchy. Thus avoid specialized
  196. objects; tables or values are usually better.
  197. API *dev-api*
  198. Use this format to name new RPC |API| functions:
  199. nvim_{thing}_{action}_{arbitrary-qualifiers}
  200. If the function acts on an object then {thing} is the name of that object
  201. (e.g. "buf" or "win"). If the function operates in a "global" context then
  202. {thing} is usually omitted (but consider "namespacing" your global operations
  203. with a {thing} that groups functions under a common concept).
  204. Use existing common {action} names if possible:
  205. - add Append to, or insert into, a collection
  206. - call Call a function
  207. - create Create a new (non-trivial) thing
  208. - del Delete a thing (or group of things)
  209. - eval Evaluate an expression
  210. - exec Execute code
  211. - fmt Format
  212. - get Get things (often by a query)
  213. - open Open
  214. - parse Parse something into a structured form
  215. - set Set a thing (or group of things)
  216. Do NOT use these deprecated verbs:
  217. - list Redundant with "get"
  218. Use consistent names for {thing} (nouns) in API functions: buffer is called
  219. "buf" everywhere, not "buffer" in some places and "buf" in others.
  220. - buf Buffer
  221. - chan |channel|
  222. - cmd Command
  223. - cmdline Command-line UI or input
  224. - fn Function
  225. - hl Highlight
  226. - pos Position
  227. - proc System process
  228. - tabpage Tabpage
  229. - win Window
  230. Do NOT use these deprecated nouns:
  231. - buffer
  232. - command
  233. - window
  234. Example:
  235. `nvim_get_keymap('v')` operates in a global context (first parameter is not
  236. a Buffer). The "get" {action} indicates that it gets anything matching the
  237. given filter parameter. There is no need for a "list" action because
  238. `nvim_get_keymap('')` (i.e., empty filter) returns all items.
  239. Example:
  240. `nvim_buf_del_mark` acts on a `Buffer` object (the first parameter)
  241. and uses the "del" {action}.
  242. Use this format to name new API events:
  243. nvim_{thing}_{event}_event
  244. Example:
  245. `nvim_buf_changedtick_event`
  246. API-CLIENT *dev-api-client*
  247. *api-client*
  248. API clients wrap the Nvim |API| to provide idiomatic "SDKs" for their
  249. respective platforms (see |jargon|). You can build a new API client for your
  250. favorite platform or programming language.
  251. List of API clients:
  252. https://github.com/neovim/neovim/wiki/Related-projects#api-clients
  253. *pynvim*
  254. The Python client is the reference implementation for API clients.
  255. https://github.com/neovim/pynvim
  256. Standard Features ~
  257. - API clients exist to hide msgpack-rpc details. The wrappers can be
  258. automatically generated by reading the |api-metadata| from Nvim. |api-mapping|
  259. - Clients should call |nvim_set_client_info()| after connecting, so users and
  260. plugins can detect the client by handling the |ChanInfo| event. This avoids
  261. the need for special variables or other client hints.
  262. - Clients should handle |nvim_error_event| notifications, which will be sent
  263. if an async request to nvim was rejected or caused an error.
  264. Package Naming ~
  265. API client packages should NOT be named something ambiguous like "neovim" or
  266. "python-client". Use "nvim" as a prefix/suffix to some other identifier
  267. following ecosystem conventions.
  268. For example, Python packages tend to have "py" in the name, so "pynvim" is
  269. a good name: it's idiomatic and unambiguous. If the package is named "neovim",
  270. it confuses users, and complicates documentation and discussions.
  271. Examples of API-client package names:
  272. - GOOD: nvim-racket
  273. - GOOD: pynvim
  274. - BAD: python-client
  275. - BAD: neovim
  276. API client implementation guidelines ~
  277. - Separate the transport layer from the rest of the library. |rpc-connecting|
  278. - Use a MessagePack library that implements at least version 5 of the
  279. MessagePack spec, which supports the BIN and EXT types used by Nvim.
  280. - Use a single-threaded event loop library/pattern.
  281. - Use a fiber/coroutine library for the language being used for implementing
  282. a client. These greatly simplify concurrency and allow the library to
  283. expose a blocking API on top of a non-blocking event loop without the
  284. complexity that comes with preemptive multitasking.
  285. - Don't assume anything about the order of responses to RPC requests.
  286. - Clients should expect requests, which must be handled immediately because
  287. Nvim is blocked while waiting for the client response.
  288. - Clients should expect notifications, but these can be handled "ASAP" (rather
  289. than immediately) because they won't block Nvim.
  290. - For C/C++ projects, consider libmpack instead of the msgpack.org library.
  291. https://github.com/libmpack/libmpack/
  292. libmpack is small (no dependencies, can inline into your C/C++ project) and
  293. efficient (no allocations). It also implements msgpack-RPC, the protocol
  294. required by Nvim.
  295. https://github.com/msgpack-rpc/msgpack-rpc
  296. EXTERNAL UI *dev-ui*
  297. External UIs should be aware of the |api-contract|. In particular, future
  298. versions of Nvim may add new items to existing events. The API is strongly
  299. backwards-compatible, but clients must not break if new (optional) fields are
  300. added to existing events.
  301. Standard Features ~
  302. External UIs are expected to implement these common features:
  303. - Call |nvim_set_client_info()| after connecting, so users and plugins can
  304. detect the UI by handling the |ChanInfo| event. This avoids the need for
  305. special variables and UI-specific config files (gvimrc, macvimrc, …).
  306. - Cursor style (shape, color) should conform to the 'guicursor' properties
  307. delivered with the mode_info_set UI event.
  308. - Send the ALT/META ("Option" on macOS) key as a |<M-| chord.
  309. - Send the "super" key (Windows key, Apple key) as a |<D-| chord.
  310. - Avoid mappings that conflict with the Nvim keymap-space; GUIs have many new
  311. chords (<C-,> <C-Enter> <C-S-x> <D-x>) and patterns ("shift shift") that do
  312. not potentially conflict with Nvim defaults, plugins, etc.
  313. - Consider the "option_set" |ui-global| event as a hint for other GUI
  314. behaviors. Various UI-related options ('guifont', 'ambiwidth', …) are
  315. published in this event. See also "mouse_on", "mouse_off".
  316. NAMING *dev-naming*
  317. Naming is important. Consistent naming in the API and UI helps both users and
  318. developers discover and intuitively understand related concepts ("families"),
  319. and reduces cognitive burden. Discoverability encourages code re-use and
  320. likewise avoids redundant, overlapping mechanisms, which reduces code
  321. surface-area, and thereby minimizes bugs...
  322. Naming conventions ~
  323. Use the "on_" prefix to name event handlers and also the interface for
  324. "registering" such handlers (on_key). The dual nature is acceptable to avoid
  325. a confused collection of naming conventions for these related concepts.
  326. vim:tw=78:ts=8:sw=4:et:ft=help:norl: