diff options
Diffstat (limited to 'runtime/doc/lua.txt')
-rw-r--r-- | runtime/doc/lua.txt | 475 |
1 files changed, 181 insertions, 294 deletions
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 60c7a60d25..334bb33c1e 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -9,7 +9,7 @@ Lua engine *lua* *Lua* Type |gO| to see the table of contents. ============================================================================== -Introduction *lua-intro* +INTRODUCTION *lua-intro* The Lua 5.1 language is builtin and always available. Try this command to get an idea of what lurks beneath: > @@ -30,7 +30,7 @@ finds and loads Lua modules. The conventions are similar to VimL plugins, with some extra features. See |lua-require-example| for a walkthrough. ============================================================================== -Importing Lua modules *lua-require* +IMPORTING LUA MODULES *lua-require* *lua-package-path* Nvim automatically adjusts `package.path` and `package.cpath` according to @@ -233,7 +233,7 @@ lua/charblob.lua: > } ============================================================================== -Commands *lua-commands* +COMMANDS *lua-commands* These commands execute a Lua chunk from either the command line (:lua, :luado) or a file (:luafile) on the given line [range]. As always in Lua, each chunk @@ -456,7 +456,7 @@ management. Try this command to see available functions: > :lua print(vim.inspect(vim.loop)) -Reference: http://docs.libuv.org +Reference: https://github.com/luvit/luv/blob/master/docs.md Examples: https://github.com/luvit/luv/tree/master/examples *E5560* *lua-loop-callbacks* @@ -551,223 +551,6 @@ Example: TCP echo-server *tcp-server* print('TCP echo-server listening on port: '..server:getsockname().port) ------------------------------------------------------------------------------ -VIM.TREESITTER *lua-treesitter* - -Nvim integrates the tree-sitter library for incremental parsing of buffers. - -Currently Nvim does not provide the tree-sitter parsers, instead these must -be built separately, for instance using the tree-sitter utility. The only -exception is a C parser being included in official builds for testing -purposes. Parsers are searched for as `parser/{lang}.*` in any 'runtimepath' -directory. A parser can also be loaded manually using a full path: > - - vim.treesitter.require_language("python", "/path/to/python.so") - -<Create a parser for a buffer and a given language (if another plugin uses the -same buffer/language combination, it will be safely reused). Use > - - parser = vim.treesitter.get_parser(bufnr, lang) - -<`bufnr=0` can be used for current buffer. `lang` will default to 'filetype' (this -doesn't work yet for some filetypes like "cpp") Currently, the parser will be -retained for the lifetime of a buffer but this is subject to change. A plugin -should keep a reference to the parser object as long as it wants incremental -updates. - -Parser methods *lua-treesitter-parser* - -tsparser:parse() *tsparser:parse()* -Whenever you need to access the current syntax tree, parse the buffer: > - - tstree = parser:parse() - -<This will return an immutable tree that represents the current state of the -buffer. When the plugin wants to access the state after a (possible) edit -it should call `parse()` again. If the buffer wasn't edited, the same tree will -be returned again without extra work. If the buffer was parsed before, -incremental parsing will be done of the changed parts. - -NB: to use the parser directly inside a |nvim_buf_attach| Lua callback, you must -call `get_parser()` before you register your callback. But preferably parsing -shouldn't be done directly in the change callback anyway as they will be very -frequent. Rather a plugin that does any kind of analysis on a tree should use -a timer to throttle too frequent updates. - -tsparser:set_included_ranges(ranges) *tsparser:set_included_ranges()* - Changes the ranges the parser should consider. This is used for - language injection. `ranges` should be of the form (all zero-based): > - { - {start_node, end_node}, - ... - } -< - NOTE: `start_node` and `end_node` are both inclusive. - -Tree methods *lua-treesitter-tree* - -tstree:root() *tstree:root()* - Return the root node of this tree. - - -Node methods *lua-treesitter-node* - -tsnode:parent() *tsnode:parent()* - Get the node's immediate parent. - -tsnode:child_count() *tsnode:child_count()* - Get the node's number of children. - -tsnode:child(N) *tsnode:child()* - Get the node's child at the given index, where zero represents the - first child. - -tsnode:named_child_count() *tsnode:named_child_count()* - Get the node's number of named children. - -tsnode:named_child(N) *tsnode:named_child()* - Get the node's named child at the given index, where zero represents - the first named child. - -tsnode:start() *tsnode:start()* - Get the node's start position. Return three values: the row, column - and total byte count (all zero-based). - -tsnode:end_() *tsnode:end_()* - Get the node's end position. Return three values: the row, column - and total byte count (all zero-based). - -tsnode:range() *tsnode:range()* - Get the range of the node. Return four values: the row, column - of the start position, then the row, column of the end position. - -tsnode:type() *tsnode:type()* - Get the node's type as a string. - -tsnode:symbol() *tsnode:symbol()* - Get the node's type as a numerical id. - -tsnode:named() *tsnode:named()* - Check if the node is named. Named nodes correspond to named rules in - the grammar, whereas anonymous nodes correspond to string literals - in the grammar. - -tsnode:missing() *tsnode:missing()* - Check if the node is missing. Missing nodes are inserted by the - parser in order to recover from certain kinds of syntax errors. - -tsnode:has_error() *tsnode:has_error()* - Check if the node is a syntax error or contains any syntax errors. - -tsnode:sexpr() *tsnode:sexpr()* - Get an S-expression representing the node as a string. - -tsnode:descendant_for_range(start_row, start_col, end_row, end_col) - *tsnode:descendant_for_range()* - Get the smallest node within this node that spans the given range of - (row, column) positions - -tsnode:named_descendant_for_range(start_row, start_col, end_row, end_col) - *tsnode:named_descendant_for_range()* - Get the smallest named node within this node that spans the given - range of (row, column) positions - -Query methods *lua-treesitter-query* - -Tree-sitter queries are supported, with some limitations. Currently, the only -supported match predicate is `eq?` (both comparing a capture against a string -and two captures against each other). - -vim.treesitter.parse_query(lang, query) - *vim.treesitter.parse_query(()* - Parse the query as a string. (If the query is in a file, the caller - should read the contents into a string before calling). - -query:iter_captures(node, bufnr, start_row, end_row) - *query:iter_captures()* - Iterate over all captures from all matches inside a `node`. - `bufnr` is needed if the query contains predicates, then the caller - must ensure to use a freshly parsed tree consistent with the current - text of the buffer. `start_row` and `end_row` can be used to limit - matches inside a row range (this is typically used with root node - as the node, i e to get syntax highlight matches in the current - viewport) - - The iterator returns two values, a numeric id identifying the capture - and the captured node. The following example shows how to get captures - by name: -> - for id, node in query:iter_captures(tree:root(), bufnr, first, last) do - local name = query.captures[id] -- name of the capture in the query - -- typically useful info about the node: - local type = node:type() -- type of the captured node - local row1, col1, row2, col2 = node:range() -- range of the capture - ... use the info here ... - end -< -query:iter_matches(node, bufnr, start_row, end_row) - *query:iter_matches()* - Iterate over all matches within a node. The arguments are the same as - for |query:iter_captures()| but the iterated values are different: - an (1-based) index of the pattern in the query, and a table mapping - capture indices to nodes. If the query has more than one pattern - the capture table might be sparse, and e.g. `pairs` should be used and not - `ipairs`. Here an example iterating over all captures in - every match: -> - for pattern, match in cquery:iter_matches(tree:root(), bufnr, first, last) do - for id,node in pairs(match) do - local name = query.captures[id] - -- `node` was captured by the `name` capture in the match - ... use the info here ... - end - end -> -Treesitter syntax highlighting (WIP) *lua-treesitter-highlight* - -NOTE: This is a partially implemented feature, and not usable as a default -solution yet. What is documented here is a temporary interface indented -for those who want to experiment with this feature and contribute to -its development. - -Highlights are defined in the same query format as in the tree-sitter highlight -crate, which some limitations and additions. Set a highlight query for a -buffer with this code: > - - local query = [[ - "for" @keyword - "if" @keyword - "return" @keyword - - (string_literal) @string - (number_literal) @number - (comment) @comment - - (preproc_function_def name: (identifier) @function) - - ; ... more definitions - ]] - - highlighter = vim.treesitter.TSHighlighter.new(query, bufnr, lang) - -- alternatively, to use the current buffer and its filetype: - -- highlighter = vim.treesitter.TSHighlighter.new(query) - - -- Don't recreate the highlighter for the same buffer, instead - -- modify the query like this: - local query2 = [[ ... ]] - highlighter:set_query(query2) - -As mentioned above the supported predicate is currently only `eq?`. `match?` -predicates behave like matching always fails. As an addition a capture which -begin with an upper-case letter like `@WarningMsg` will map directly to this -highlight group, if defined. Also if the predicate begins with upper-case and -contains a dot only the part before the first will be interpreted as the -highlight group. As an example, this warns of a binary expression with two -identical identifiers, highlighting both as |hl-WarningMsg|: > - - ((binary_expression left: (identifier) @WarningMsg.left right: (identifier) @WarningMsg.right) - (eq? @WarningMsg.left @WarningMsg.right)) - ------------------------------------------------------------------------------- VIM.HIGHLIGHT *lua-highlight* Nvim includes a function for highlighting a selection on yank (see for example @@ -839,11 +622,6 @@ vim.api.{func}({...}) *vim.api* Example: call the "nvim_get_current_line()" API function: > print(tostring(vim.api.nvim_get_current_line())) -vim.call({func}, {...}) *vim.call()* - Invokes |vim-function| or |user-function| {func} with arguments {...}. - See also |vim.fn|. Equivalent to: > - vim.fn[func]({...}) - vim.in_fast_event() *vim.in_fast_event()* Returns true if the code is executing as part of a "fast" event handler, where most of the API is disabled. These are low-level events @@ -876,6 +654,34 @@ vim.region({bufnr}, {pos1}, {pos2}, {type}, {inclusive}) *vim.region()* whether the selection is inclusive or not, into a zero-indexed table of linewise selections of the form `{linenr = {startcol, endcol}}` . + *vim.register_keystroke_callback()* +vim.register_keystroke_callback({fn}, {ns_id}) + Register a lua {fn} with an {ns_id} to be run after every keystroke. + + Parameters: ~ + {fn}: (function): Function to call on keystroke. + It should take one argument, which is a string. + The string will contain the literal keys typed. + See |i_CTRL-V| + + If {fn} is `nil`, it removes the callback for the + associated {ns_id}. + + {ns_id}: (number) Namespace ID. If not passed or 0, will generate + and return a new namespace ID from |nvim_create_namespace()| + + Return: ~ + (number) Namespace ID associated with {fn} + + NOTE: {fn} will be automatically removed if an error occurs while + calling. This is to prevent the annoying situation of every keystroke + erroring while trying to remove a broken callback. + + NOTE: {fn} will receive the keystrokes after mappings have been + evaluated + + NOTE: {fn} will *NOT* be cleared from |nvim_buf_clear_namespace()| + vim.rpcnotify({channel}, {method}[, {args}...]) *vim.rpcnotify()* Sends {event} to {channel} via |RPC| and returns immediately. If {channel} is 0, the event is broadcast to all channels. @@ -931,13 +737,20 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn* Returns: ~ |vim.loop|.new_timer() object -vim.wait({time}, {callback} [, {interval}]) *vim.wait()* +vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* Wait for {time} in milliseconds until {callback} returns `true`. Executes {callback} immediately and at approximately {interval} milliseconds (default 200). Nvim still processes other events during this time. + Parameters: ~ + {time} Number of milliseconds to wait + {callback} Optional callback. Waits until {callback} returns true + {interval} (Approximate) number of milliseconds to wait between polls + {fast_only} If true, only |api-fast| events will be processed. + If called from while in an |api-fast| event, will + automatically be set to `true`. Returns: ~ If {callback} returns `true` during the {time}: @@ -975,22 +788,6 @@ vim.wait({time}, {callback} [, {interval}]) *vim.wait()* end < -vim.fn.{func}({...}) *vim.fn* - Invokes |vim-function| or |user-function| {func} with arguments {...}. - To call autoload functions, use the syntax: > - vim.fn['some#function']({...}) -< - Unlike vim.api.|nvim_call_function| this converts directly between Vim - objects and Lua objects. If the Vim function returns a float, it will - be represented directly as a Lua number. Empty lists and dictionaries - both are represented by an empty table. - - Note: |v:null| values as part of the return value is represented as - |vim.NIL| special value - - Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only - enumerates functions that were called at least once. - vim.type_idx *vim.type_idx* Type index for use in |lua-special-tbl|. Specifying one of the values from |vim.types| allows typing the empty table (it is @@ -1026,64 +823,103 @@ vim.types *vim.types* `vim.types.dictionary` will not change or that `vim.types` table will only contain values for these three types. -============================================================================== -Vim Internal Variables *lua-vim-internal-variables* - -Built-in Vim dictionaries can be accessed and set idiomatically in Lua by each -of the following tables. - -To set a value: > - - vim.g.my_global_variable = 5 -< +------------------------------------------------------------------------------ +LUA-VIMSCRIPT BRIDGE *lua-vimscript* -To read a value: > +Nvim Lua provides an interface to Vimscript variables and functions, and +editor commands and options. - print(vim.g.my_global_variable) -< +vim.call({func}, {...}) *vim.call()* + Invokes |vim-function| or |user-function| {func} with arguments {...}. + See also |vim.fn|. + Equivalent to: > + vim.fn[func]({...}) -To delete a value: > +vim.cmd({cmd}) *vim.cmd()* + Invokes an Ex command (the ":" commands, Vimscript statements). + See also |ex-cmd-index|. + Example: > + vim.cmd('echo 42') - vim.g.my_global_variable = nil +vim.fn.{func}({...}) *vim.fn* + Invokes |vim-function| or |user-function| {func} with arguments {...}. + To call autoload functions, use the syntax: > + vim.fn['some#function']({...}) < + Unlike vim.api.|nvim_call_function| this converts directly between Vim + objects and Lua objects. If the Vim function returns a float, it will + be represented directly as a Lua number. Empty lists and dictionaries + both are represented by an empty table. -vim.g *vim.g* - Table with values from |g:| - Keys with no values set will result in `nil`. - -vim.b *vim.b* - Gets a buffer-scoped (b:) variable for the current buffer. - Keys with no values set will result in `nil`. - -vim.w *vim.w* - Gets a window-scoped (w:) variable for the current window. - Keys with no values set will result in `nil`. + Note: |v:null| values as part of the return value is represented as + |vim.NIL| special value -vim.t *vim.t* - Gets a tabpage-scoped (t:) variable for the current table. - Keys with no values set will result in `nil`. + Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only + enumerates functions that were called at least once. -vim.v *vim.v* - Gets a v: variable. - Keys with no values set will result in `nil`. + *lua-vim-variables* +The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed +from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables +described below. In this way you can easily read and modify global Vimscript +variables from Lua. -Vim Internal Options *lua-vim-internal-options* +Example: > -Read, set and clear vim |options| in Lua by each of the following tables. + vim.g.foo = 5 -- Set the g:foo Vimscript variable. + print(vim.g.foo) -- Get and print the g:foo Vimscript variable. + vim.g.foo = nil -- Delete (:unlet) the Vimscript variable. + +vim.g *vim.g* + Global (|g:|) editor variables. + Key with no value returns `nil`. + +vim.b *vim.b* + Buffer-scoped (|b:|) variables for the current buffer. + Invalid or unset key returns `nil`. + +vim.w *vim.w* + Window-scoped (|w:|) variables for the current window. + Invalid or unset key returns `nil`. + +vim.t *vim.t* + Tabpage-scoped (|t:|) variables for the current tabpage. + Invalid or unset key returns `nil`. + +vim.v *vim.v* + |v:| variables. + Invalid or unset key returns `nil`. + +vim.env *vim.env* + Environment variables defined in the editor session. + See |expand-env| and |:let-environment| for the Vimscript behavior. + Invalid or unset key returns `nil`. + Example: > + vim.env.FOO = 'bar' + print(vim.env.TERM) +< + *lua-vim-options* +From Lua you can work with editor |options| by reading and setting items in +these Lua tables: -vim.o *vim.o* - Table with values from |options| - Invalid keys will result in an error. +vim.o *vim.o* + Get or set editor options, like |:set|. Invalid key is an error. + Example: > + vim.o.cmdheight = 4 + print(vim.o.columns) -vim.bo *vim.bo* - Gets a buffer-scoped option for the current buffer. - Invalid keys will result in an error. +vim.bo *vim.bo* + Get or set buffer-scoped |local-options|. Invalid key is an error. + Example: > + vim.bo.buflisted = true + print(vim.bo.comments) -vim.wo *vim.wo* - Gets a window-scoped option for the current window. - Invalid keys will result in an error. +vim.wo *vim.wo* + Get or set window-scoped |local-options|. Invalid key is an error. + Example: > + vim.wo.cursorcolumn = true + print(vim.wo.foldmarker) ============================================================================== @@ -1195,6 +1031,9 @@ is_callable({f}) *vim.is_callable()* Return: ~ true if `f` is callable, else false +is_valid({opt}) *vim.is_valid()* + TODO: Documentation + list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()* Extends a list-like table with the values of another list-like table. @@ -1339,17 +1178,21 @@ tbl_flatten({t}) *vim.tbl_flatten()* Fromhttps://github.com/premake/premake-core/blob/master/src/base/table.lua tbl_isempty({t}) *vim.tbl_isempty()* + Checks if a table is empty. + + Parameters: ~ + {t} Table to check + See also: ~ - Fromhttps://github.com/premake/premake-core/blob/master/src/base/table.lua@paramt Table to check + https://github.com/premake/premake-core/blob/master/src/base/table.lua tbl_islist({t}) *vim.tbl_islist()* - Determine whether a Lua table can be treated as an array. + Tests if a Lua table can be treated as an array. - An empty table `{}` will default to being treated as an array. - Use `vim.emtpy_dict()` to create a table treated as an empty - dict. Empty tables returned by `rpcrequest()` and `vim.fn` - functions can be checked using this function whether they - represent empty API arrays and vimL lists. + Empty table `{}` is assumed to be an array, unless it was + created by |vim.empty_dict()| or returned as a dict-like |API| + or Vimscript result, for example from |rpcrequest()| or + |vim.fn|. Parameters: ~ {t} Table @@ -1446,8 +1289,52 @@ validate({opt}) *vim.validate()* • arg_value: argument value • fn: any function accepting one argument, returns true if and only if the argument is - valid + valid. Can optionally return an additional + informative error message as the second + returned value. • msg: (optional) error string if validation fails + +============================================================================== +Lua module: uri *lua-uri* + +uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()* + Get a URI from a bufnr + + Parameters: ~ + {bufnr} (number): Buffer number + + Return: ~ + URI + +uri_from_fname({path}) *vim.uri_from_fname()* + Get a URI from a file path. + + Parameters: ~ + {path} (string): Path to file + + Return: ~ + URI + +uri_to_bufnr({uri}) *vim.uri_to_bufnr()* + Return or create a buffer for a uri. + + Parameters: ~ + {uri} (string): The URI + + Return: ~ + bufnr. + Note: + Creates buffer but does not load it + +uri_to_fname({uri}) *vim.uri_to_fname()* + Get a filename from a URI + + Parameters: ~ + {uri} (string): The URI + + Return: ~ + Filename + vim:tw=78:ts=8:ft=help:norl: |