diff options
author | Josh Rahm <joshuarahm@gmail.com> | 2023-01-25 18:31:31 +0000 |
---|---|---|
committer | Josh Rahm <joshuarahm@gmail.com> | 2023-01-25 18:31:31 +0000 |
commit | 9243becbedbb6a1592208051f8fa2b090dcc5e7d (patch) | |
tree | 607c2a862ec3f4399b8766383f6f8e04c4aa43b4 /runtime/doc | |
parent | 9e40b6e9e1bc67f2d856adb837ee64dd0e25b717 (diff) | |
parent | 3c48d3c83fc21dbc0841f9210f04bdb073d73cd1 (diff) | |
download | rneovim-usermarks.tar.gz rneovim-usermarks.tar.bz2 rneovim-usermarks.zip |
Merge remote-tracking branch 'upstream/master' into usermarksusermarks
Diffstat (limited to 'runtime/doc')
104 files changed, 7683 insertions, 7414 deletions
diff --git a/runtime/doc/Makefile b/runtime/doc/Makefile deleted file mode 100644 index 18d32c0820..0000000000 --- a/runtime/doc/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -# -# Makefile for the Vim documentation on Unix -# -# If you get "don't know how to make scratch", first run make in the source -# directory. Or remove the include below. - -AWK = awk - -DOCS = $(wildcard *.txt) -HTMLS = $(DOCS:.txt=.html) - -.SUFFIXES: -.SUFFIXES: .c .o .txt .html - -# Awk version of .txt to .html conversion. -html: noerrors vimindex.html $(HTMLS) - @if test -f errors.log; then cat errors.log; fi - -noerrors: - -rm -f errors.log - -$(HTMLS): tags.ref - -.txt.html: - $(AWK) -f makehtml.awk $< >$@ - -# index.html is the starting point for HTML, but for the help files it is -# help.txt. Therefore use vimindex.html for index.txt. -index.html: help.txt - $(AWK) -f makehtml.awk help.txt >index.html - -vimindex.html: index.txt - $(AWK) -f makehtml.awk index.txt >vimindex.html - -tags.ref tags.html: tags - $(AWK) -f maketags.awk tags >tags.html - -clean: - -rm -f *.html tags.ref $(HTMLS) errors.log tags - diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index a388592981..0e1cc3c28c 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -51,7 +51,7 @@ Connecting to the socket is the easiest way a programmer can test the API, which can be done through any msgpack-rpc client library or full-featured |api-client|. Here's a Ruby script that prints "hello world!" in the current Nvim instance: -> +>ruby #!/usr/bin/env ruby # Requires msgpack-rpc: gem install msgpack-rpc # @@ -79,10 +79,11 @@ functions can be called interactively: < You can also embed Nvim via |jobstart()|, and communicate using |rpcrequest()| and |rpcnotify()|: -> +>vim let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true}) echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"') call jobstop(nvim) +< ============================================================================== API Definitions *api-definitions* @@ -92,7 +93,7 @@ The Nvim C API defines custom types for all function parameters. Some are just typedefs around C99 standard types, others are Nvim-defined data structures. Basic types ~ - +> API Type C type ------------------------------------------------------------------------ Nil @@ -103,7 +104,7 @@ Basic types ~ Array Dictionary (msgpack: map) Object - +< Note: empty Array is accepted as a valid argument for Dictionary parameter. Special types (msgpack EXT) ~ @@ -115,13 +116,13 @@ Special types (msgpack EXT) ~ The EXT object data is the (integer) object handle. The EXT type codes given in the |api-metadata| `types` key are stable: they will not change and are thus forward-compatible. - +> EXT Type C type Data ------------------------------------------------------------------------ Buffer enum value kObjectTypeBuffer |bufnr()| Window enum value kObjectTypeWindow |window-ID| Tabpage enum value kObjectTypeTabpage internal handle - +< *api-indexing* Most of the API uses 0-based indices, and ranges are end-exclusive. For the @@ -130,19 +131,19 @@ end of a range, -1 denotes the last line/column. Exception: the following API functions use "mark-like" indexing (1-based lines, 0-based columns): - |nvim_get_mark()| - |nvim_buf_get_mark()| - |nvim_buf_set_mark()| - |nvim_win_get_cursor()| - |nvim_win_set_cursor()| +- |nvim_get_mark()| +- |nvim_buf_get_mark()| +- |nvim_buf_set_mark()| +- |nvim_win_get_cursor()| +- |nvim_win_set_cursor()| Exception: the following API functions use |extmarks| indexing (0-based indices, end-inclusive): - |nvim_buf_del_extmark()| - |nvim_buf_get_extmark_by_id()| - |nvim_buf_get_extmarks()| - |nvim_buf_set_extmark()| +- |nvim_buf_del_extmark()| +- |nvim_buf_get_extmark_by_id()| +- |nvim_buf_get_extmarks()| +- |nvim_buf_set_extmark()| *api-fast* Most API functions are "deferred": they are queued on the main loop and @@ -162,19 +163,19 @@ and return values. Nvim exposes its API metadata as a Dictionary with these items: -version Nvim version, API level/compatibility -version.api_level API version integer *api-level* -version.api_compatible API is backwards-compatible with this level -version.api_prerelease Declares the API as unstable/unreleased > - (version.api_prerelease && fn.since == version.api_level) -functions API function signatures, containing |api-types| info - describing the return value and parameters. -ui_events |UI| event signatures -ui_options Supported |ui-option|s -{fn}.since API level where function {fn} was introduced -{fn}.deprecated_since API level where function {fn} was deprecated -types Custom handle types defined by Nvim -error_types Possible error types returned by API functions +- version Nvim version, API level/compatibility +- version.api_level API version integer *api-level* +- version.api_compatible API is backwards-compatible with this level +- version.api_prerelease Declares the API as unstable/unreleased + `(version.api_prerelease && fn.since == version.api_level)` +- functions API function signatures, containing |api-types| info + describing the return value and parameters. +- ui_events |UI| event signatures +- ui_options Supported |ui-option|s +- {fn}.since API level where function {fn} was introduced +- {fn}.deprecated_since API level where function {fn} was deprecated +- types Custom handle types defined by Nvim +- error_types Possible error types returned by API functions About the `functions` map: @@ -200,9 +201,9 @@ any of these approaches: Example (requires Python "pyyaml" and "msgpack-python" modules): > nvim --api-info | python -c 'import msgpack, sys, yaml; yaml.dump(msgpack.unpackb(sys.stdin.buffer.read()), sys.stdout)' < - 3. Use the |api_info()| Vimscript function. > + 3. Use the |api_info()| Vimscript function. >vim :lua print(vim.inspect(vim.fn.api_info())) -< Example using |filter()| to exclude non-deprecated API functions: > +< Example using |filter()| to exclude non-deprecated API functions: >vim :new|put =map(filter(api_info().functions, '!has_key(v:val,''deprecated_since'')'), 'v:val.name') ============================================================================== @@ -230,6 +231,15 @@ As Nvim evolves the API may change in compliance with this CONTRACT: - Existing items will not be removed (after release). - Deprecated functions will not be removed until Nvim version 2.0 +"Private" interfaces are NOT covered by this contract: + +- Undocumented (not in :help) functions or events of any kind +- nvim__x ("double underscore") functions + +The idea is "versionless evolution", in the words of Rich Hickey: +- Relaxing a requirement should be a compatible change. +- Strengthening a promise should be a compatible change. + ============================================================================== Global events *api-global-events* @@ -345,16 +355,16 @@ LUA ~ In-process Lua plugins can receive buffer updates in the form of Lua callbacks. These callbacks are called frequently in various contexts; |textlock| prevents changing buffer contents and window layout (use -|vim.schedule| to defer such operations to the main loop instead). +|vim.schedule()| to defer such operations to the main loop instead). |nvim_buf_attach()| will take keyword args for the callbacks. "on_lines" will receive parameters ("lines", {buf}, {changedtick}, {firstline}, {lastline}, {new_lastline}, {old_byte_size} [, {old_utf32_size}, {old_utf16_size}]). Unlike remote channel events the text contents are not passed. The new text can -be accessed inside the callback as - - `vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true)` +be accessed inside the callback as >lua + vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true) +< {old_byte_size} is the total size of the replaced region {firstline} to {lastline} in bytes, including the final newline after {lastline}. if `utf_sizes` is set to true in |nvim_buf_attach()| keyword args, then the @@ -390,7 +400,7 @@ performance can be improved by calling |nvim_buf_add_highlight()| as an asynchronous notification, after first (synchronously) requesting a source id. Example using the Python API client (|pynvim|): -> +>python src = vim.new_highlight_source() buf = vim.current.buffer for i in range(5): @@ -404,7 +414,7 @@ clear highlights from a specific source, in a specific line range or the entire buffer by passing in the line range 0, -1 (the latter is the default in python as used above). -Example using the API from Vimscript: > +Example using the API from Vimscript: >vim call nvim_buf_set_lines(0, 0, 0, v:true, ["test text"]) let src = nvim_buf_add_highlight(0, 0, "String", 1, 0, 4) @@ -428,12 +438,12 @@ Two ways to create a floating window: To close it use |nvim_win_close()| or a command such as |:close|. To check whether a window is floating, check whether the `relative` option in -its config is non-empty: > +its config is non-empty: >lua if vim.api.nvim_win_get_config(window_id).relative ~= '' then -- window with this window_id is floating end -> +< Buffer text can be highlighted by typical mechanisms (syntax highlighting, |api-highlights|). The |hl-NormalFloat| group highlights normal text; @@ -446,7 +456,7 @@ Currently, floating windows don't support some widgets like scrollbar. The output of |:mksession| does not include commands for restoring floating windows. -Example: create a float with scratch buffer: > +Example: create a float with scratch buffer: >vim let buf = nvim_create_buf(v:false, v:true) call nvim_buf_set_lines(buf, 0, -1, v:true, ["test", "text"]) @@ -455,10 +465,10 @@ Example: create a float with scratch buffer: > let win = nvim_open_win(buf, 0, opts) " optional: change highlight, otherwise Pmenu is used call nvim_win_set_option(win, 'winhl', 'Normal:MyHighlight') -> +< ============================================================================== -Extended marks *api-extended-marks* *extmarks* +Extended marks *api-extended-marks* *extmarks* *extmark* Extended marks (extmarks) represent buffer annotations that track text changes in the buffer. They can represent cursors, folds, misspelled words, anything @@ -499,30 +509,32 @@ Let's set an extmark at the first row (row=0) and third column (column=2). 01 2345678 0 ex|ample.. -< ^ extmark position -> + ^ extmark position +< +>vim let g:mark_ns = nvim_create_namespace('myplugin') let g:mark_id = nvim_buf_set_extmark(0, g:mark_ns, 0, 2, {}) < -We can get the mark by its id: > +We can get the mark by its id: >vim echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {}) - => [0, 2] + " => [0, 2] -We can get all marks in a buffer by |namespace| (or by a range): > +We can get all marks in a buffer by |namespace| (or by a range): >vim echo nvim_buf_get_extmarks(0, g:mark_ns, 0, -1, {}) - => [[1, 0, 2]] + " => [[1, 0, 2]] Deleting all surrounding text does NOT remove an extmark! To remove extmarks use |nvim_buf_del_extmark()|. Deleting "x" in our example: > 0 12345678 0 e|ample.. -< ^ extmark position -> + ^ extmark position +< +>vim echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {}) - => [0, 1] + " => [0, 1] < Note: Extmark "gravity" decides how it will shift after a text edit. See |nvim_buf_set_extmark()| @@ -544,9 +556,9 @@ nvim__get_runtime({pat}, {all}, {*opts}) *nvim__get_runtime()* |api-fast| Parameters: ~ - {pat} pattern of files to search for - {all} whether to return all matches or only the first - {opts} is_lua: only search lua subdirs + • {pat} pattern of files to search for + • {all} whether to return all matches or only the first + • {opts} is_lua: only search lua subdirs Return: ~ list of absolute paths to the found files @@ -558,7 +570,7 @@ nvim__id({obj}) *nvim__id()* in plugins. Parameters: ~ - {obj} Object to return. + • {obj} Object to return. Return: ~ its argument. @@ -570,7 +582,7 @@ nvim__id_array({arr}) *nvim__id_array()* in plugins. Parameters: ~ - {arr} Array to return. + • {arr} Array to return. Return: ~ its argument. @@ -582,7 +594,7 @@ nvim__id_dictionary({dct}) *nvim__id_dictionary()* in plugins. Parameters: ~ - {dct} Dictionary to return. + • {dct} Dictionary to return. Return: ~ its argument. @@ -594,7 +606,7 @@ nvim__id_float({flt}) *nvim__id_float()* in plugins. Parameters: ~ - {flt} Value to return. + • {flt} Value to return. Return: ~ its argument. @@ -624,7 +636,7 @@ nvim_call_atomic({calls}) *nvim_call_atomic()* |RPC| only Parameters: ~ - {calls} an array of calls, where each call is described by an array + • {calls} an array of calls, where each call is described by an array with two elements: the request name, and an array of arguments. @@ -648,18 +660,18 @@ nvim_chan_send({chan}, {data}) *nvim_chan_send()* Attributes: ~ |RPC| only - |vim.api| only + Lua |vim.api| only Parameters: ~ - {chan} id of the channel - {data} data to write. 8-bit clean: can contain NUL bytes. + • {chan} id of the channel + • {data} data to write. 8-bit clean: can contain NUL bytes. nvim_create_buf({listed}, {scratch}) *nvim_create_buf()* Creates a new, empty, unnamed buffer. Parameters: ~ - {listed} Sets 'buflisted' - {scratch} Creates a "throwaway" |scratch-buffer| for temporary work + • {listed} Sets 'buflisted' + • {scratch} Creates a "throwaway" |scratch-buffer| for temporary work (always 'nomodified'). Also sets 'nomodeline' on the buffer. @@ -690,7 +702,7 @@ nvim_del_mark({name}) *nvim_del_mark()* fails with error if a lowercase or buffer local named mark is used. Parameters: ~ - {name} Mark name + • {name} Mark name Return: ~ true if the mark was deleted, else false. @@ -703,31 +715,35 @@ nvim_del_var({name}) *nvim_del_var()* Removes a global (g:) variable. Parameters: ~ - {name} Variable name + • {name} Variable name -nvim_echo({chunks}, {history}, {opts}) *nvim_echo()* +nvim_echo({chunks}, {history}, {*opts}) *nvim_echo()* Echo a message. Parameters: ~ - {chunks} A list of [text, hl_group] arrays, each representing a text + • {chunks} A list of [text, hl_group] arrays, each representing a text chunk with specified highlight. `hl_group` element can be omitted for no highlight. - {history} if true, add to |message-history|. - {opts} Optional parameters. Reserved for future use. + • {history} if true, add to |message-history|. + • {opts} Optional parameters. + • verbose: Message was printed as a result of 'verbose' + option if Nvim was invoked with -V3log_file, the message + will be redirected to the log_file and suppressed from + direct output. nvim_err_write({str}) *nvim_err_write()* Writes a message to the Vim error buffer. Does not append "\n", the message is buffered (won't display) until a linefeed is written. Parameters: ~ - {str} Message + • {str} Message nvim_err_writeln({str}) *nvim_err_writeln()* Writes a message to the Vim error buffer. Appends "\n", so the buffer is flushed (and displayed). Parameters: ~ - {str} Message + • {str} Message See also: ~ nvim_err_write() @@ -739,8 +755,8 @@ nvim_eval_statusline({str}, {*opts}) *nvim_eval_statusline()* |api-fast| Parameters: ~ - {str} Statusline string (see 'statusline'). - {opts} Optional parameters. + • {str} Statusline string (see 'statusline'). + • {opts} Optional parameters. • winid: (number) |window-ID| of the window to use as context for statusline. • maxwidth: (number) Maximum width of statusline. @@ -750,7 +766,7 @@ nvim_eval_statusline({str}, {*opts}) *nvim_eval_statusline()* • highlights: (boolean) Return highlight information. • use_winbar: (boolean) Evaluate winbar instead of statusline. • use_tabline: (boolean) Evaluate tabline instead of - statusline. When |TRUE|, {winid} is ignored. Mutually + statusline. When true, {winid} is ignored. Mutually exclusive with {use_winbar}. Return: ~ @@ -759,7 +775,7 @@ nvim_eval_statusline({str}, {*opts}) *nvim_eval_statusline()* • width: (number) Display width of the statusline. • highlights: Array containing highlight information of the statusline. Only included when the "highlights" key in {opts} is - |TRUE|. Each element of the array is a |Dictionary| with these keys: + true. Each element of the array is a |Dictionary| with these keys: • start: (number) Byte index (0-based) of first character that uses the highlight. • group: (string) Name of highlight group. @@ -775,8 +791,8 @@ nvim_exec_lua({code}, {args}) *nvim_exec_lua()* |RPC| only Parameters: ~ - {code} Lua code to execute - {args} Arguments to the code + • {code} Lua code to execute + • {args} Arguments to the code Return: ~ Return value of Lua code if present or NIL. @@ -791,15 +807,15 @@ nvim_feedkeys({keys}, {mode}, {escape_ks}) *nvim_feedkeys()* with escape_ks=false) to replace |keycodes|, then pass the result to nvim_feedkeys(). - Example: > + Example: >vim :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true) :call nvim_feedkeys(key, 'n', v:false) < Parameters: ~ - {keys} to be typed - {mode} behavior flags, see |feedkeys()| - {escape_ks} If true, escape K_SPECIAL bytes in `keys` This should be + • {keys} to be typed + • {mode} behavior flags, see |feedkeys()| + • {escape_ks} If true, escape K_SPECIAL bytes in `keys`. This should be false if you already used |nvim_replace_termcodes()|, and true otherwise. @@ -847,13 +863,13 @@ nvim_get_color_by_name({name}) *nvim_get_color_by_name()* Returns the 24-bit RGB value of a |nvim_get_color_map()| color name or "#rrggbb" hexadecimal string. - Example: > + Example: >vim :echo nvim_get_color_by_name("Pink") :echo nvim_get_color_by_name("#cbcbcb") < Parameters: ~ - {name} Color name or "#rrggbb" string + • {name} Color name or "#rrggbb" string Return: ~ 24-bit RGB value, or -1 for invalid argument. @@ -871,7 +887,7 @@ nvim_get_context({*opts}) *nvim_get_context()* Gets a map of the current editor state. Parameters: ~ - {opts} Optional parameters. + • {opts} Optional parameters. • types: List of |context-types| ("regs", "jumps", "bufs", "gvars", …) to gather, or empty for "all". @@ -906,8 +922,8 @@ nvim_get_hl_by_id({hl_id}, {rgb}) *nvim_get_hl_by_id()* Gets a highlight definition by id. |hlID()| Parameters: ~ - {hl_id} Highlight id as returned by |hlID()| - {rgb} Export RGB colors + • {hl_id} Highlight id as returned by |hlID()| + • {rgb} Export RGB colors Return: ~ Highlight definition map @@ -919,8 +935,8 @@ nvim_get_hl_by_name({name}, {rgb}) *nvim_get_hl_by_name()* Gets a highlight definition by name. Parameters: ~ - {name} Highlight group name - {rgb} Export RGB colors + • {name} Highlight group name + • {rgb} Export RGB colors Return: ~ Highlight definition map @@ -937,7 +953,7 @@ nvim_get_keymap({mode}) *nvim_get_keymap()* Gets a list of global (non-buffer-local) |mapping| definitions. Parameters: ~ - {mode} Mode short-name ("n", "i", "v", ...) + • {mode} Mode short-name ("n", "i", "v", ...) Return: ~ Array of |maparg()|-like dictionaries describing mappings. The @@ -953,8 +969,8 @@ nvim_get_mark({name}, {opts}) *nvim_get_mark()* fails with error if a lowercase or buffer local named mark is used. Parameters: ~ - {name} Mark name - {opts} Optional parameters. Reserved for future use. + • {name} Mark name + • {opts} Optional parameters. Reserved for future use. Return: ~ 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if the mark is @@ -989,7 +1005,7 @@ nvim_get_proc_children({pid}) *nvim_get_proc_children()* nvim_get_runtime_file({name}, {all}) *nvim_get_runtime_file()* Find files in runtime directories - 'name' can contain wildcards. For example + "name" can contain wildcards. For example nvim_get_runtime_file("colors/*.vim", true) will return all color scheme files. Always use forward slashes (/) in the search pattern for subdirectories regardless of platform. @@ -1000,8 +1016,8 @@ nvim_get_runtime_file({name}, {all}) *nvim_get_runtime_file()* |api-fast| Parameters: ~ - {name} pattern of files to search for - {all} whether to return all matches or only the first + • {name} pattern of files to search for + • {all} whether to return all matches or only the first Return: ~ list of absolute paths to the found files @@ -1010,7 +1026,7 @@ nvim_get_var({name}) *nvim_get_var()* Gets a global (g:) variable. Parameters: ~ - {name} Variable name + • {name} Variable name Return: ~ Variable value @@ -1019,7 +1035,7 @@ nvim_get_vvar({name}) *nvim_get_vvar()* Gets a v: variable. Parameters: ~ - {name} Variable name + • {name} Variable name Return: ~ Variable value @@ -1043,7 +1059,7 @@ nvim_input({keys}) *nvim_input()* |api-fast| Parameters: ~ - {keys} to be typed + • {keys} to be typed Return: ~ Number of bytes actually written (can be fewer than requested if the @@ -1067,16 +1083,18 @@ nvim_input_mouse({button}, {action}, {modifier}, {grid}, {row}, {col}) |api-fast| Parameters: ~ - {button} Mouse button: one of "left", "right", "middle", "wheel". - {action} For ordinary buttons, one of "press", "drag", "release". + • {button} Mouse button: one of "left", "right", "middle", "wheel", + "move". + • {action} For ordinary buttons, one of "press", "drag", "release". For the wheel, one of "up", "down", "left", "right". - {modifier} String of modifiers each represented by a single char. The + Ignored for "move". + • {modifier} String of modifiers each represented by a single char. The same specifiers are used as for a key press, except that the "-" separator is optional, so "C-A-", "c-a" and "CA" can all be used to specify Ctrl+Alt+click. - {grid} Grid number if the client uses |ui-multigrid|, else 0. - {row} Mouse row-position (zero-based, like redraw events) - {col} Mouse column-position (zero-based, like redraw events) + • {grid} Grid number if the client uses |ui-multigrid|, else 0. + • {row} Mouse row-position (zero-based, like redraw events) + • {col} Mouse column-position (zero-based, like redraw events) nvim_list_bufs() *nvim_list_bufs()* Gets the current list of buffer handles @@ -1115,7 +1133,7 @@ nvim_list_uis() *nvim_list_uis()* • "width" Requested width of the UI • "rgb" true if the UI uses RGB colors (false implies |cterm-colors|) • "ext_..." Requested UI extensions, see |ui-option| - • "chan" Channel id of remote UI (not present for TUI) + • "chan" |channel-id| of remote UI nvim_list_wins() *nvim_list_wins()* Gets the current list of window handles. @@ -1127,7 +1145,7 @@ nvim_load_context({dict}) *nvim_load_context()* Sets the current editor state from the given |context| map. Parameters: ~ - {dict} |Context| map. + • {dict} |Context| map. nvim_notify({msg}, {log_level}, {opts}) *nvim_notify()* Notify the user with a message @@ -1136,9 +1154,9 @@ nvim_notify({msg}, {log_level}, {opts}) *nvim_notify()* echo area but can be overridden to trigger desktop notifications. Parameters: ~ - {msg} Message to display to the user - {log_level} The log level - {opts} Reserved for future use. + • {msg} Message to display to the user + • {log_level} The log level + • {opts} Reserved for future use. nvim_open_term({buffer}, {opts}) *nvim_open_term()* Open a terminal instance in a buffer @@ -1156,13 +1174,13 @@ nvim_open_term({buffer}, {opts}) *nvim_open_term()* virtual terminal having the intended size. Parameters: ~ - {buffer} the buffer to use (expected to be empty) - {opts} Optional parameters. + • {buffer} the buffer to use (expected to be empty) + • {opts} Optional parameters. • on_input: lua callback for input sent, i e keypresses in terminal mode. Note: keypresses are sent raw as they would be to the pty master end. For instance, a carriage return is sent as a "\r", not as a "\n". |textlock| applies. It - is possible to call |nvim_chan_send| directly in the + is possible to call |nvim_chan_send()| directly in the callback however. ["input", term, bufnr, data] Return: ~ @@ -1173,7 +1191,7 @@ nvim_out_write({str}) *nvim_out_write()* message is buffered (won't display) until a linefeed is written. Parameters: ~ - {str} Message + • {str} Message nvim_paste({data}, {crlf}, {phase}) *nvim_paste()* Pastes at cursor, in any mode. @@ -1190,9 +1208,9 @@ nvim_paste({data}, {crlf}, {phase}) *nvim_paste()* not allowed when |textlock| is active Parameters: ~ - {data} Multiline input. May be binary (containing NUL bytes). - {crlf} Also break lines at CR and CRLF. - {phase} -1: paste in a single call (i.e. without streaming). To + • {data} Multiline input. May be binary (containing NUL bytes). + • {crlf} Also break lines at CR and CRLF. + • {phase} -1: paste in a single call (i.e. without streaming). To "stream" a paste, call `nvim_paste` sequentially with these `phase` values: • 1: starts the paste (exactly once) • 2: continues the paste (zero or more times) @@ -1212,15 +1230,15 @@ nvim_put({lines}, {type}, {after}, {follow}) *nvim_put()* not allowed when |textlock| is active Parameters: ~ - {lines} |readfile()|-style list of lines. |channel-lines| - {type} Edit behavior: any |getregtype()| result, or: + • {lines} |readfile()|-style list of lines. |channel-lines| + • {type} Edit behavior: any |getregtype()| result, or: • "b" |blockwise-visual| mode (may include width, e.g. "b3") • "c" |charwise| mode • "l" |linewise| mode • "" guess by contents, see |setreg()| - {after} If true insert after cursor (like |p|), or before (like + • {after} If true insert after cursor (like |p|), or before (like |P|). - {follow} If true place cursor at end of inserted text. + • {follow} If true place cursor at end of inserted text. *nvim_replace_termcodes()* nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special}) @@ -1228,10 +1246,10 @@ nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special}) the internal representation. Parameters: ~ - {str} String to be converted. - {from_part} Legacy Vim parameter. Usually true. - {do_lt} Also translate <lt>. Ignored if `special` is false. - {special} Replace |keycodes|, e.g. <CR> becomes a "\r" char. + • {str} String to be converted. + • {from_part} Legacy Vim parameter. Usually true. + • {do_lt} Also translate <lt>. Ignored if `special` is false. + • {special} Replace |keycodes|, e.g. <CR> becomes a "\r" char. See also: ~ replace_termcodes @@ -1239,20 +1257,22 @@ nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special}) *nvim_select_popupmenu_item()* nvim_select_popupmenu_item({item}, {insert}, {finish}, {opts}) - Selects an item in the completion popupmenu. + Selects an item in the completion popup menu. - If |ins-completion| is not active this API call is silently ignored. - Useful for an external UI using |ui-popupmenu| to control the popupmenu - with the mouse. Can also be used in a mapping; use <cmd> |:map-cmd| to - ensure the mapping doesn't end completion mode. + If neither |ins-completion| nor |cmdline-completion| popup menu is active + this API call is silently ignored. Useful for an external UI using + |ui-popupmenu| to control the popup menu with the mouse. Can also be used + in a mapping; use <Cmd> |:map-cmd| or a Lua mapping to ensure the mapping + doesn't end completion mode. Parameters: ~ - {item} Index (zero-based) of the item to select. Value of -1 + • {item} Index (zero-based) of the item to select. Value of -1 selects nothing and restores the original text. - {insert} Whether the selection should be inserted in the buffer. - {finish} Finish the completion and dismiss the popupmenu. Implies - `insert`. - {opts} Optional parameters. Reserved for future use. + • {insert} For |ins-completion|, whether the selection should be + inserted in the buffer. Ignored for |cmdline-completion|. + • {finish} Finish the completion and dismiss the popup menu. Implies + {insert}. + • {opts} Optional parameters. Reserved for future use. *nvim_set_client_info()* nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) @@ -1274,8 +1294,8 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) |RPC| only Parameters: ~ - {name} Short name for the connected client - {version} Dictionary describing the version, with these (optional) + • {name} Short name for the connected client + • {version} Dictionary describing the version, with these (optional) keys: • "major" major version (defaults to 0 if not set, for no release yet) @@ -1284,7 +1304,7 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) • "prerelease" string describing a prerelease, like "dev" or "beta1" • "commit" hash or similar identifier of commit - {type} Must be one of the following values. Client libraries + • {type} Must be one of the following values. Client libraries should default to "remote" unless overridden by the user. • "remote" remote client connected to Nvim. @@ -1293,7 +1313,7 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) example, IDE/editor implementing a vim mode). • "host" plugin host, typically started by nvim • "plugin" single plugin, started by nvim - {methods} Builtin methods in the client. For a host, this does not + • {methods} Builtin methods in the client. For a host, this does not include plugin methods which will be discovered later. The key should be the method name, the values are dicts with these (optional) keys (more keys may be added in @@ -1305,7 +1325,7 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) • "nargs" Number of arguments. Could be a single integer or an array of two integers, minimum and maximum inclusive. - {attributes} Arbitrary string:string map of informal client + • {attributes} Arbitrary string:string map of informal client properties. Suggested keys: • "website": Client homepage URL (e.g. GitHub repository) @@ -1321,13 +1341,13 @@ nvim_set_current_buf({buffer}) *nvim_set_current_buf()* not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer handle + • {buffer} Buffer handle nvim_set_current_dir({dir}) *nvim_set_current_dir()* Changes the global working directory. Parameters: ~ - {dir} Directory path + • {dir} Directory path nvim_set_current_line({line}) *nvim_set_current_line()* Sets the current line. @@ -1336,7 +1356,7 @@ nvim_set_current_line({line}) *nvim_set_current_line()* not allowed when |textlock| is active Parameters: ~ - {line} Line contents + • {line} Line contents nvim_set_current_tabpage({tabpage}) *nvim_set_current_tabpage()* Sets the current tabpage. @@ -1345,7 +1365,7 @@ nvim_set_current_tabpage({tabpage}) *nvim_set_current_tabpage()* not allowed when |textlock| is active Parameters: ~ - {tabpage} Tabpage handle + • {tabpage} Tabpage handle nvim_set_current_win({window}) *nvim_set_current_win()* Sets the current window. @@ -1354,7 +1374,7 @@ nvim_set_current_win({window}) *nvim_set_current_win()* not allowed when |textlock| is active Parameters: ~ - {window} Window handle + • {window} Window handle nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* Sets a highlight group. @@ -1372,10 +1392,10 @@ nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* using these values results in an error. Parameters: ~ - {ns_id} Namespace id for this highlight |nvim_create_namespace()|. + • {ns_id} Namespace id for this highlight |nvim_create_namespace()|. Use 0 to set a highlight group globally |:highlight|. - {name} Highlight group name, e.g. "ErrorMsg" - {val} Highlight definition map, accepts the following keys: + • {name} Highlight group name, e.g. "ErrorMsg" + • {val} Highlight definition map, accepts the following keys: • fg (or foreground): color name or "#RRGGBB", see note. • bg (or background): color name or "#RRGGBB", see note. • sp (or special): color name or "#RRGGBB" @@ -1394,31 +1414,31 @@ nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* • link: name of another highlight group to link to, see |:hi-link|. • default: Don't override existing definition |:hi-default| - • ctermfg: Sets foreground of cterm color |highlight-ctermfg| - • ctermbg: Sets background of cterm color |highlight-ctermbg| + • ctermfg: Sets foreground of cterm color |ctermfg| + • ctermbg: Sets background of cterm color |ctermbg| • cterm: cterm attribute map, like |highlight-args|. If not set, cterm attributes will match those from the attribute map documented above. nvim_set_hl_ns({ns_id}) *nvim_set_hl_ns()* Set active namespace for highlights. This can be set for a single window, - see |nvim_win_set_hl_ns|. + see |nvim_win_set_hl_ns()|. Parameters: ~ - {ns_id} the namespace to use + • {ns_id} the namespace to use nvim_set_hl_ns_fast({ns_id}) *nvim_set_hl_ns_fast()* Set active namespace for highlights while redrawing. This function meant to be called while redrawing, primarily from - |nvim_set_decoration_provider| on_win and on_line callbacks, which are + |nvim_set_decoration_provider()| on_win and on_line callbacks, which are allowed to change the namespace during a redraw cycle. Attributes: ~ |api-fast| Parameters: ~ - {ns_id} the namespace to activate + • {ns_id} the namespace to activate nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()* Sets a global |mapping| for the given mode. @@ -1428,22 +1448,22 @@ nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()* Unlike |:map|, leading/trailing whitespace is accepted as part of the {lhs} or {rhs}. Empty {rhs} is |<Nop>|. |keycodes| are replaced as usual. - Example: > + Example: >vim call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) < - is equivalent to: > + is equivalent to: >vim nmap <nowait> <Space><NL> <Nop> < Parameters: ~ - {mode} Mode short-name (map command prefix: "n", "i", "v", "x", …) or + • {mode} Mode short-name (map command prefix: "n", "i", "v", "x", …) or "!" for |:map!|, or empty string for |:map|. - {lhs} Left-hand-side |{lhs}| of the mapping. - {rhs} Right-hand-side |{rhs}| of the mapping. - {opts} Optional parameters map: keys are |:map-arguments|, values are + • {lhs} Left-hand-side |{lhs}| of the mapping. + • {rhs} Right-hand-side |{rhs}| of the mapping. + • {opts} Optional parameters map: keys are |:map-arguments|, values are booleans (default false). Accepts all |:map-arguments| as keys - excluding |<buffer>| but including |noremap| and "desc". + excluding |<buffer>| but including |:noremap| and "desc". Unknown key is an error. "desc" can be used to give a description to the mapping. When called from Lua, also accepts a "callback" key that takes a Lua function to call when the @@ -1456,22 +1476,22 @@ nvim_set_var({name}, {value}) *nvim_set_var()* Sets a global (g:) variable. Parameters: ~ - {name} Variable name - {value} Variable value + • {name} Variable name + • {value} Variable value nvim_set_vvar({name}, {value}) *nvim_set_vvar()* Sets a v: variable, if it is not readonly. Parameters: ~ - {name} Variable name - {value} Variable value + • {name} Variable name + • {value} Variable value nvim_strwidth({text}) *nvim_strwidth()* Calculates the number of display cells occupied by `text`. Control characters including <Tab> count as one cell. Parameters: ~ - {text} Some text + • {text} Some text Return: ~ Number of cells @@ -1483,7 +1503,7 @@ nvim_subscribe({event}) *nvim_subscribe()* |RPC| only Parameters: ~ - {event} Event type string + • {event} Event type string nvim_unsubscribe({event}) *nvim_unsubscribe()* Unsubscribes to event broadcasts. @@ -1492,7 +1512,7 @@ nvim_unsubscribe({event}) *nvim_unsubscribe()* |RPC| only Parameters: ~ - {event} Event type string + • {event} Event type string ============================================================================== @@ -1505,9 +1525,9 @@ nvim_call_dict_function({dict}, {fn}, {args}) On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {dict} Dictionary, or String evaluating to a VimL |self| dict - {fn} Name of the function defined on the VimL dict - {args} Function arguments packed in an Array + • {dict} Dictionary, or String evaluating to a VimL |self| dict + • {fn} Name of the function defined on the VimL dict + • {args} Function arguments packed in an Array Return: ~ Result of the function call @@ -1518,8 +1538,8 @@ nvim_call_function({fn}, {args}) *nvim_call_function()* On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {fn} Function to call - {args} Function arguments packed in an Array + • {fn} Function to call + • {args} Function arguments packed in an Array Return: ~ Result of the function call @@ -1536,7 +1556,7 @@ nvim_command({command}) *nvim_command()* |nvim_parse_cmd()| in conjunction with |nvim_cmd()|. Parameters: ~ - {command} Ex command string + • {command} Ex command string nvim_eval({expr}) *nvim_eval()* Evaluates a VimL |expression|. Dictionaries and Lists are recursively @@ -1545,7 +1565,7 @@ nvim_eval({expr}) *nvim_eval()* On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {expr} VimL expression string + • {expr} VimL expression string Return: ~ Evaluation result or expanded object @@ -1560,8 +1580,8 @@ nvim_exec({src}, {output}) *nvim_exec()* On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {src} Vimscript code - {output} Capture and return all (non-error, non-shell |:!|) output + • {src} Vimscript code + • {output} Capture and return all (non-error, non-shell |:!|) output Return: ~ Output (non-error, non-shell |:!|) if `output` is true, else empty @@ -1580,8 +1600,8 @@ nvim_parse_expression({expr}, {flags}, {highlight}) |api-fast| Parameters: ~ - {expr} Expression to parse. Always treated as a single line. - {flags} Flags: + • {expr} Expression to parse. Always treated as a single line. + • {flags} Flags: • "m" if multiple expressions in a row are allowed (only the first one will be parsed), • "E" if EOC tokens are not allowed (determines whether @@ -1593,7 +1613,7 @@ nvim_parse_expression({expr}, {flags}, {highlight}) • "E" to parse like for "<C-r>=". • empty string for ":call". • "lm" to parse for ":let". - {highlight} If true, return value will also include "highlight" key + • {highlight} If true, return value will also include "highlight" key containing array of 4-tuples (arrays) (Integer, Integer, Integer, String), where first three numbers define the highlighted region and represent line, starting column @@ -1661,7 +1681,7 @@ nvim_buf_create_user_command({buffer}, {name}, {command}, {*opts}) Create a new user command |user-commands| in the given buffer. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer. + • {buffer} Buffer handle, or 0 for current buffer. See also: ~ nvim_create_user_command @@ -1674,15 +1694,15 @@ nvim_buf_del_user_command({buffer}, {name}) |nvim_buf_create_user_command()| can be deleted with this function. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer. - {name} Name of the command to delete. + • {buffer} Buffer handle, or 0 for current buffer. + • {name} Name of the command to delete. nvim_buf_get_commands({buffer}, {*opts}) *nvim_buf_get_commands()* Gets a map of buffer-local |user-commands|. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {opts} Optional parameters. Currently not used. + • {buffer} Buffer handle, or 0 for current buffer + • {opts} Optional parameters. Currently not used. Return: ~ Map of maps describing commands. @@ -1694,16 +1714,22 @@ nvim_cmd({*cmd}, {*opts}) *nvim_cmd()* of a String. This allows for easier construction and manipulation of an Ex command. This also allows for things such as having spaces inside a command argument, expanding filenames in a command that otherwise doesn't - expand filenames, etc. + expand filenames, etc. Command arguments may also be Number, Boolean or + String. + + The first argument may also be used instead of count for commands that + support it in order to make their usage simpler with |vim.cmd()|. For + example, instead of `vim.cmd.bdelete{ count = 2 }`, you may do + `vim.cmd.bdelete(2)`. On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {cmd} Command to execute. Must be a Dictionary that can contain the + • {cmd} Command to execute. Must be a Dictionary that can contain the same values as the return value of |nvim_parse_cmd()| except "addr", "nargs" and "nextcmd" which are ignored if provided. All values except for "cmd" are optional. - {opts} Optional parameters. + • {opts} Optional parameters. • output: (boolean, default false) Whether to return command output. @@ -1724,19 +1750,20 @@ nvim_create_user_command({name}, {command}, {*opts}) {command} is the replacement text or Lua function to execute. - Example: > + Example: >vim :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {}) :SayHello Hello world! < Parameters: ~ - {name} Name of the new user command. Must begin with an uppercase + • {name} Name of the new user command. Must begin with an uppercase letter. - {command} Replacement command to execute when this user command is + • {command} Replacement command to execute when this user command is executed. When called from Lua, the command can also be a Lua function. The function is called with a single table argument that contains the following keys: + • name: (string) Command name • args: (string) The args passed to the command, if any |<args>| • fargs: (table) The args split by unescaped whitespace @@ -1756,7 +1783,7 @@ nvim_create_user_command({name}, {command}, {*opts}) • smods: (table) Command modifiers in a structured format. Has the same structure as the "mods" key of |nvim_parse_cmd()|. - {opts} Optional command attributes. See |command-attributes| for + • {opts} Optional command attributes. See |command-attributes| for more details. To use boolean attributes (such as |:command-bang| or |:command-bar|) set the value to "true". In addition to the string options listed in @@ -1774,7 +1801,7 @@ nvim_del_user_command({name}) *nvim_del_user_command()* Delete a user-defined command. Parameters: ~ - {name} Name of the command to delete. + • {name} Name of the command to delete. nvim_get_commands({*opts}) *nvim_get_commands()* Gets a map of global (non-buffer-local) Ex commands. @@ -1782,7 +1809,7 @@ nvim_get_commands({*opts}) *nvim_get_commands()* Currently only |user-commands| are supported, not builtin Ex commands. Parameters: ~ - {opts} Optional parameters. Currently only supports {"builtin":false} + • {opts} Optional parameters. Currently only supports {"builtin":false} Return: ~ Map of maps describing commands. @@ -1796,24 +1823,25 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* |api-fast| Parameters: ~ - {str} Command line string to parse. Cannot contain "\n". - {opts} Optional parameters. Reserved for future use. + • {str} Command line string to parse. Cannot contain "\n". + • {opts} Optional parameters. Reserved for future use. Return: ~ Dictionary containing command information, with these keys: • cmd: (string) Command name. - • range: (array) Command <range>. Can have 0-2 elements depending on - how many items the range contains. Has no elements if command - doesn't accept a range or if no range was specified, one element if - only a single range item was specified and two elements if both - range items were specified. - • count: (number) Any |<count>| that was supplied to the command. -1 - if command cannot take a count. - • reg: (number) The optional command |<register>|, if specified. Empty - string if not specified or if command cannot take a register. + • range: (array) (optional) Command range (|<line1>| |<line2>|). + Omitted if command doesn't accept a range. Otherwise, has no + elements if no range was specified, one element if only a single + range item was specified, or two elements if both range items were + specified. + • count: (number) (optional) Command |<count>|. Omitted if command + cannot take a count. + • reg: (string) (optional) Command |<register>|. Omitted if command + cannot take a register. • bang: (boolean) Whether command contains a |<bang>| (!) modifier. • args: (array) Command arguments. - • addr: (string) Value of |:command-addr|. Uses short name. + • addr: (string) Value of |:command-addr|. Uses short name or "line" + for -addr=lines. • nargs: (string) Value of |:command-nargs|. • nextcmd: (string) Next command if there are multiple commands separated by a |:bar|. Empty if there isn't a next command. @@ -1839,13 +1867,14 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* • browse: (boolean) |:browse|. • confirm: (boolean) |:confirm|. • hide: (boolean) |:hide|. + • horizontal: (boolean) |:horizontal|. • keepalt: (boolean) |:keepalt|. • keepjumps: (boolean) |:keepjumps|. • keepmarks: (boolean) |:keepmarks|. • keeppatterns: (boolean) |:keeppatterns|. • lockmarks: (boolean) |:lockmarks|. • noswapfile: (boolean) |:noswapfile|. - • tab: (integer) |:tab|. + • tab: (integer) |:tab|. -1 when omitted. • verbose: (integer) |:verbose|. -1 when omitted. • vertical: (boolean) |:vertical|. • split: (string) Split modifier string, is an empty string when @@ -1864,8 +1893,8 @@ nvim_buf_get_option({buffer}, {name}) *nvim_buf_get_option()* Gets a buffer option value Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Option name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Option name Return: ~ Option value @@ -1875,15 +1904,15 @@ nvim_buf_set_option({buffer}, {name}, {value}) *nvim_buf_set_option()* (only works if there's a global fallback) Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Option name - {value} Option value + • {buffer} Buffer handle, or 0 for current buffer + • {name} Option name + • {value} Option value nvim_get_all_options_info() *nvim_get_all_options_info()* Gets the option information for all options. The dictionary has the full option names as keys and option metadata - dictionaries as detailed at |nvim_get_option_info|. + dictionaries as detailed at |nvim_get_option_info()|. Return: ~ dictionary of all options @@ -1892,7 +1921,7 @@ nvim_get_option({name}) *nvim_get_option()* Gets the global value of an option. Parameters: ~ - {name} Option name + • {name} Option name Return: ~ Option value (global) @@ -1915,7 +1944,7 @@ nvim_get_option_info({name}) *nvim_get_option_info()* • flaglist: List of single char flags Parameters: ~ - {name} Option name + • {name} Option name Return: ~ Option Information @@ -1927,8 +1956,8 @@ nvim_get_option_value({name}, {*opts}) *nvim_get_option_value()* current buffer or window, unless "buf" or "win" is set in {opts}. Parameters: ~ - {name} Option name - {opts} Optional parameters + • {name} Option name + • {opts} Optional parameters • scope: One of "global" or "local". Analogous to |:setglobal| and |:setlocal|, respectively. • win: |window-ID|. Used for getting window local options. @@ -1942,8 +1971,8 @@ nvim_set_option({name}, {value}) *nvim_set_option()* Sets the global value of an option. Parameters: ~ - {name} Option name - {value} New option value + • {name} Option name + • {value} New option value *nvim_set_option_value()* nvim_set_option_value({name}, {value}, {*opts}) @@ -1954,10 +1983,10 @@ nvim_set_option_value({name}, {value}, {*opts}) Note the options {win} and {buf} cannot be used together. Parameters: ~ - {name} Option name - {value} New option value - {opts} Optional parameters - • scope: One of 'global' or 'local'. Analogous to + • {name} Option name + • {value} New option value + • {opts} Optional parameters + • scope: One of "global" or "local". Analogous to |:setglobal| and |:setlocal|, respectively. • win: |window-ID|. Used for setting window local option. • buf: Buffer number. Used for setting buffer local option. @@ -1966,8 +1995,8 @@ nvim_win_get_option({window}, {name}) *nvim_win_get_option()* Gets a window option value Parameters: ~ - {window} Window handle, or 0 for current window - {name} Option name + • {window} Window handle, or 0 for current window + • {name} Option name Return: ~ Option value @@ -1977,9 +2006,9 @@ nvim_win_set_option({window}, {name}, {value}) *nvim_win_set_option()* (only works if there's a global fallback) Parameters: ~ - {window} Window handle, or 0 for current window - {name} Option name - {value} Option value + • {window} Window handle, or 0 for current window + • {name} Option name + • {value} Option value ============================================================================== @@ -2003,20 +2032,20 @@ whether a buffer is loaded. nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()* Activates buffer-update events on a channel, or as Lua callbacks. - Example (Lua): capture buffer updates in a global `events` variable (use "print(vim.inspect(events))" to see its contents): > + Example (Lua): capture buffer updates in a global `events` variable (use "print(vim.inspect(events))" to see its contents): >lua events = {} vim.api.nvim_buf_attach(0, false, { on_lines=function(...) table.insert(events, {...}) end}) < Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {send_buffer} True if the initial notification should contain the + • {buffer} Buffer handle, or 0 for current buffer + • {send_buffer} True if the initial notification should contain the whole buffer: first notification will be `nvim_buf_lines_event`. Else the first notification will be `nvim_buf_changedtick_event`. Not for Lua callbacks. - {opts} Optional parameters. + • {opts} Optional parameters. • on_lines: Lua callback invoked on change. Return `true` to detach. Args: • the string "lines" • buffer handle @@ -2087,11 +2116,11 @@ nvim_buf_call({buffer}, {fun}) *nvim_buf_call()* buffer/window currently, like |termopen()|. Attributes: ~ - |vim.api| only + Lua |vim.api| only Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {fun} Function to call inside the buffer (currently lua callable + • {buffer} Buffer handle, or 0 for current buffer + • {fun} Function to call inside the buffer (currently lua callable only) Return: ~ @@ -2102,7 +2131,7 @@ nvim_buf_del_keymap({buffer}, {mode}, {lhs}) *nvim_buf_del_keymap()* Unmaps a buffer-local |mapping| for the given mode. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer See also: ~ |nvim_del_keymap()| @@ -2115,8 +2144,8 @@ nvim_buf_del_mark({buffer}, {name}) *nvim_buf_del_mark()* buffer it will return false. Parameters: ~ - {buffer} Buffer to set the mark on - {name} Mark name + • {buffer} Buffer to set the mark on + • {name} Mark name Return: ~ true if the mark was deleted, else false. @@ -2129,8 +2158,8 @@ nvim_buf_del_var({buffer}, {name}) *nvim_buf_del_var()* Removes a buffer-scoped (b:) variable Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Variable name nvim_buf_delete({buffer}, {opts}) *nvim_buf_delete()* Deletes the buffer. See |:bwipeout| @@ -2139,8 +2168,8 @@ nvim_buf_delete({buffer}, {opts}) *nvim_buf_delete()* not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {opts} Optional parameters. Keys: + • {buffer} Buffer handle, or 0 for current buffer + • {opts} Optional parameters. Keys: • force: Force deletion and ignore unsaved changes. • unload: Unloaded only, do not delete. See |:bunload| @@ -2151,7 +2180,7 @@ nvim_buf_detach({buffer}) *nvim_buf_detach()* |RPC| only Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ False if detach failed (because the buffer isn't loaded); otherwise @@ -2165,7 +2194,7 @@ nvim_buf_get_changedtick({buffer}) *nvim_buf_get_changedtick()* Gets a changed tick of a buffer Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ `b:changedtick` value. @@ -2174,8 +2203,8 @@ nvim_buf_get_keymap({buffer}, {mode}) *nvim_buf_get_keymap()* Gets a list of buffer-local |mapping| definitions. Parameters: ~ - {mode} Mode short-name ("n", "i", "v", ...) - {buffer} Buffer handle, or 0 for current buffer + • {mode} Mode short-name ("n", "i", "v", ...) + • {buffer} Buffer handle, or 0 for current buffer Return: ~ Array of |maparg()|-like dictionaries describing mappings. The @@ -2193,10 +2222,10 @@ nvim_buf_get_lines({buffer}, {start}, {end}, {strict_indexing}) `strict_indexing` is set. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start} First line index - {end} Last line index, exclusive - {strict_indexing} Whether out-of-bounds should be an error. + • {buffer} Buffer handle, or 0 for current buffer + • {start} First line index + • {end} Last line index, exclusive + • {strict_indexing} Whether out-of-bounds should be an error. Return: ~ Array of lines, or empty array for unloaded buffer. @@ -2208,8 +2237,8 @@ nvim_buf_get_mark({buffer}, {name}) *nvim_buf_get_mark()* Marks are (1,0)-indexed. |api-indexing| Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Mark name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Mark name Return: ~ (row, col) tuple, (0, 0) if the mark is not set, or is an @@ -2223,7 +2252,7 @@ nvim_buf_get_name({buffer}) *nvim_buf_get_name()* Gets the full file name for the buffer Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ Buffer name @@ -2240,8 +2269,8 @@ nvim_buf_get_offset({buffer}, {index}) *nvim_buf_get_offset()* for unloaded buffer. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {index} Line index + • {buffer} Buffer handle, or 0 for current buffer + • {index} Line index Return: ~ Integer byte offset, or -1 for unloaded buffer. @@ -2260,12 +2289,12 @@ nvim_buf_get_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, Prefer |nvim_buf_get_lines()| when retrieving entire lines. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start_row} First line index - {start_col} Starting column (byte offset) on first line - {end_row} Last line index, inclusive - {end_col} Ending column (byte offset) on last line, exclusive - {opts} Optional parameters. Currently unused. + • {buffer} Buffer handle, or 0 for current buffer + • {start_row} First line index + • {start_col} Starting column (byte offset) on first line + • {end_row} Last line index, inclusive + • {end_col} Ending column (byte offset) on last line, exclusive + • {opts} Optional parameters. Currently unused. Return: ~ Array of lines, or empty array for unloaded buffer. @@ -2274,8 +2303,8 @@ nvim_buf_get_var({buffer}, {name}) *nvim_buf_get_var()* Gets a buffer-scoped (b:) variable. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Variable name Return: ~ Variable value @@ -2285,7 +2314,7 @@ nvim_buf_is_loaded({buffer}) *nvim_buf_is_loaded()* about unloaded buffers. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ true if the buffer is valid and loaded, false otherwise. @@ -2298,7 +2327,7 @@ nvim_buf_is_valid({buffer}) *nvim_buf_is_valid()* for more info about unloaded buffers. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ true if the buffer is valid, false otherwise. @@ -2307,7 +2336,7 @@ nvim_buf_line_count({buffer}) *nvim_buf_line_count()* Returns the number of lines in the given buffer. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ Line count, or 0 for unloaded buffer. |api-buffer| @@ -2317,7 +2346,7 @@ nvim_buf_set_keymap({buffer}, {mode}, {lhs}, {rhs}, {*opts}) Sets a buffer-local |mapping| for the given mode. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer See also: ~ |nvim_set_keymap()| @@ -2340,11 +2369,14 @@ nvim_buf_set_lines({buffer}, {start}, {end}, {strict_indexing}, {replacement}) not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start} First line index - {end} Last line index, exclusive - {strict_indexing} Whether out-of-bounds should be an error. - {replacement} Array of lines to use as replacement + • {buffer} Buffer handle, or 0 for current buffer + • {start} First line index + • {end} Last line index, exclusive + • {strict_indexing} Whether out-of-bounds should be an error. + • {replacement} Array of lines to use as replacement + + See also: ~ + |nvim_buf_set_text()| *nvim_buf_set_mark()* nvim_buf_set_mark({buffer}, {name}, {line}, {col}, {opts}) @@ -2357,11 +2389,11 @@ nvim_buf_set_mark({buffer}, {name}, {line}, {col}, {opts}) Passing 0 as line deletes the mark Parameters: ~ - {buffer} Buffer to set the mark on - {name} Mark name - {line} Line number - {col} Column/row number - {opts} Optional parameters. Reserved for future use. + • {buffer} Buffer to set the mark on + • {name} Mark name + • {line} Line number + • {col} Column/row number + • {opts} Optional parameters. Reserved for future use. Return: ~ true if the mark was set, else false. @@ -2374,8 +2406,8 @@ nvim_buf_set_name({buffer}, {name}) *nvim_buf_set_name()* Sets the full file name for a buffer Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Buffer name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Buffer name *nvim_buf_set_text()* nvim_buf_set_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, @@ -2397,20 +2429,23 @@ nvim_buf_set_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, lines. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start_row} First line index - {start_col} Starting column (byte offset) on first line - {end_row} Last line index, inclusive - {end_col} Ending column (byte offset) on last line, exclusive - {replacement} Array of lines to use as replacement + • {buffer} Buffer handle, or 0 for current buffer + • {start_row} First line index + • {start_col} Starting column (byte offset) on first line + • {end_row} Last line index, inclusive + • {end_col} Ending column (byte offset) on last line, exclusive + • {replacement} Array of lines to use as replacement + + See also: ~ + |nvim_buf_set_lines()| nvim_buf_set_var({buffer}, {name}, {value}) *nvim_buf_set_var()* Sets a buffer-scoped (b:) variable Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name - {value} Variable value + • {buffer} Buffer handle, or 0 for current buffer + • {name} Variable name + • {value} Variable value ============================================================================== @@ -2441,12 +2476,12 @@ nvim_buf_add_highlight({buffer}, {ns_id}, {hl_group}, {line}, {col_start}, |nvim_create_namespace()| to create a new empty namespace. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} namespace to use or -1 for ungrouped highlight - {hl_group} Name of the highlight group to use - {line} Line to highlight (zero-indexed) - {col_start} Start of (byte-indexed) column range to highlight - {col_end} End of (byte-indexed) column range to highlight, or -1 to + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} namespace to use or -1 for ungrouped highlight + • {hl_group} Name of the highlight group to use + • {line} Line to highlight (zero-indexed) + • {col_start} Start of (byte-indexed) column range to highlight + • {col_end} End of (byte-indexed) column range to highlight, or -1 to highlight to end of line Return: ~ @@ -2454,39 +2489,39 @@ nvim_buf_add_highlight({buffer}, {ns_id}, {hl_group}, {line}, {col_start}, *nvim_buf_clear_namespace()* nvim_buf_clear_namespace({buffer}, {ns_id}, {line_start}, {line_end}) - Clears namespaced objects (highlights, extmarks, virtual text) from a + Clears |namespace|d objects (highlights, |extmarks|, virtual text) from a region. Lines are 0-indexed. |api-indexing| To clear the namespace in the entire buffer, specify line_start=0 and line_end=-1. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace to clear, or -1 to clear all namespaces. - {line_start} Start of range of lines to clear - {line_end} End of range of lines to clear (exclusive) or -1 to + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace to clear, or -1 to clear all namespaces. + • {line_start} Start of range of lines to clear + • {line_end} End of range of lines to clear (exclusive) or -1 to clear to end of buffer. nvim_buf_del_extmark({buffer}, {ns_id}, {id}) *nvim_buf_del_extmark()* - Removes an extmark. + Removes an |extmark|. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {id} Extmark id + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {id} Extmark id Return: ~ true if the extmark was found, else false *nvim_buf_get_extmark_by_id()* nvim_buf_get_extmark_by_id({buffer}, {ns_id}, {id}, {opts}) - Gets the position (0-indexed) of an extmark. + Gets the position (0-indexed) of an |extmark|. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {id} Extmark id - {opts} Optional parameters. Keys: + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {id} Extmark id + • {opts} Optional parameters. Keys: • details: Whether to include the details dict Return: ~ @@ -2494,45 +2529,43 @@ nvim_buf_get_extmark_by_id({buffer}, {ns_id}, {id}, {opts}) *nvim_buf_get_extmarks()* nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) - Gets extmarks in "traversal order" from a |charwise| region defined by + Gets |extmarks| in "traversal order" from a |charwise| region defined by buffer positions (inclusive, 0-indexed |api-indexing|). Region can be given as (row,col) tuples, or valid extmark ids (whose positions define the bounds). 0 and -1 are understood as (0,0) and (-1,-1) - respectively, thus the following are equivalent: -> - nvim_buf_get_extmarks(0, my_ns, 0, -1, {}) - nvim_buf_get_extmarks(0, my_ns, [0,0], [-1,-1], {}) + respectively, thus the following are equivalent: >lua + vim.api.nvim_buf_get_extmarks(0, my_ns, 0, -1, {}) + vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) < If `end` is less than `start`, traversal works backwards. (Useful with `limit`, to get the first marks prior to a given position.) - Example: -> - local a = vim.api - local pos = a.nvim_win_get_cursor(0) - local ns = a.nvim_create_namespace('my-plugin') - -- Create new extmark at line 1, column 1. - local m1 = a.nvim_buf_set_extmark(0, ns, 0, 0, {}) - -- Create new extmark at line 3, column 1. - local m2 = a.nvim_buf_set_extmark(0, ns, 0, 2, {}) - -- Get extmarks only from line 3. - local ms = a.nvim_buf_get_extmarks(0, ns, {2,0}, {2,0}, {}) - -- Get all marks in this buffer + namespace. - local all = a.nvim_buf_get_extmarks(0, ns, 0, -1, {}) - print(vim.inspect(ms)) + Example: >lua + local a = vim.api + local pos = a.nvim_win_get_cursor(0) + local ns = a.nvim_create_namespace('my-plugin') + -- Create new extmark at line 1, column 1. + local m1 = a.nvim_buf_set_extmark(0, ns, 0, 0, {}) + -- Create new extmark at line 3, column 1. + local m2 = a.nvim_buf_set_extmark(0, ns, 2, 0, {}) + -- Get extmarks only from line 3. + local ms = a.nvim_buf_get_extmarks(0, ns, {2,0}, {2,0}, {}) + -- Get all marks in this buffer + namespace. + local all = a.nvim_buf_get_extmarks(0, ns, 0, -1, {}) + print(vim.inspect(ms)) < Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {start} Start of range: a 0-indexed (row, col) or valid extmark id + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {start} Start of range: a 0-indexed (row, col) or valid extmark id (whose position defines the bound). |api-indexing| - {end} End of range (inclusive): a 0-indexed (row, col) or valid + • {end} End of range (inclusive): a 0-indexed (row, col) or valid extmark id (whose position defines the bound). |api-indexing| - {opts} Optional parameters. Keys: + • {opts} Optional parameters. Keys: • limit: Maximum number of marks to return • details Whether to include the details dict @@ -2541,7 +2574,7 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) *nvim_buf_set_extmark()* nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) - Creates or updates an extmark. + Creates or updates an |extmark|. By default a new extmark is created when no id is passed in, but it is also possible to create a new mark by passing in a previously unused id or @@ -2553,11 +2586,11 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) range of text, and also to associate virtual text to the mark. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {line} Line where to place the mark, 0-based. |api-indexing| - {col} Column where to place the mark, 0-based. |api-indexing| - {opts} Optional parameters. + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {line} Line where to place the mark, 0-based. |api-indexing| + • {col} Column where to place the mark, 0-based. |api-indexing| + • {opts} Optional parameters. • id : id of the extmark to edit. • end_row : ending line of the mark, 0-based inclusive. • end_col : ending col of the mark, 0-based exclusive. @@ -2569,11 +2602,11 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) • virt_text : virtual text to link to this mark. A list of [text, highlight] tuples, each representing a text chunk with specified highlight. `highlight` element can either - be a a single highlight group, or an array of multiple + be a single highlight group, or an array of multiple highlight groups that will be stacked (highest priority last). A highlight group can be supplied either as a string or as an integer, the latter which can be obtained - using |nvim_get_hl_id_by_name|. + using |nvim_get_hl_id_by_name()|. • virt_text_pos : position of virtual text. Possible values: • "eol": right after eol character (default) • "overlay": display over the specified column, without @@ -2605,7 +2638,7 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) • virt_lines_above: place virtual lines above instead. • virt_lines_leftcol: Place extmarks in the leftmost column of the window, bypassing sign and number columns. - • ephemeral : for use with |nvim_set_decoration_provider| + • ephemeral : for use with |nvim_set_decoration_provider()| callbacks. The mark will only be used for the current redraw cycle, and not be permantently stored in the buffer. @@ -2643,6 +2676,8 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) When a character is supplied it is used as |:syn-cchar|. "hl_group" is used as highlight for the cchar if provided, otherwise it defaults to |hl-Conceal|. + • spell: boolean indicating that spell checking should be + performed within this extmark • ui_watched: boolean that indicates the mark should be drawn by a UI. When set, the UI will receive win_extmark events. Note: the mark is positioned by virt_text @@ -2652,7 +2687,7 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) Id of the created/updated extmark nvim_create_namespace({name}) *nvim_create_namespace()* - Creates a new *namespace* or gets an existing one. + Creates a new namespace or gets an existing one. *namespace* Namespaces are used for buffer highlights and virtual text, see |nvim_buf_add_highlight()| and |nvim_buf_set_extmark()|. @@ -2662,26 +2697,26 @@ nvim_create_namespace({name}) *nvim_create_namespace()* new, anonymous namespace is created. Parameters: ~ - {name} Namespace name or empty string + • {name} Namespace name or empty string Return: ~ Namespace id nvim_get_namespaces() *nvim_get_namespaces()* - Gets existing, non-anonymous namespaces. + Gets existing, non-anonymous |namespace|s. Return: ~ dict that maps from names to namespace ids. *nvim_set_decoration_provider()* -nvim_set_decoration_provider({ns_id}, {opts}) - Set or change decoration provider for a namespace +nvim_set_decoration_provider({ns_id}, {*opts}) + Set or change decoration provider for a |namespace| This is a very general purpose interface for having lua callbacks being triggered during the redraw code. - The expected usage is to set extmarks for the currently redrawn buffer. - |nvim_buf_set_extmark| can be called to add marks on a per-window or + The expected usage is to set |extmarks| for the currently redrawn buffer. + |nvim_buf_set_extmark()| can be called to add marks on a per-window or per-lines basis. Use the `ephemeral` key to only use the mark for the current screen redraw (the callback will be called again for the next redraw ). @@ -2702,11 +2737,11 @@ nvim_set_decoration_provider({ns_id}, {opts}) quite dubious for the moment. Attributes: ~ - |vim.api| only + Lua |vim.api| only Parameters: ~ - {ns_id} Namespace id from |nvim_create_namespace()| - {opts} Callbacks invoked during redraw: + • {ns_id} Namespace id from |nvim_create_namespace()| + • {opts} Table of callbacks: • on_start: called first on each screen redraw ["start", tick] • on_buf: called for each buffer being redrawn (before window @@ -2726,11 +2761,11 @@ nvim_win_call({window}, {fun}) *nvim_win_call()* Calls a function with window as temporary current window. Attributes: ~ - |vim.api| only + Lua |vim.api| only Parameters: ~ - {window} Window handle, or 0 for current window - {fun} Function to call inside the window (currently lua callable + • {window} Window handle, or 0 for current window + • {fun} Function to call inside the window (currently lua callable only) Return: ~ @@ -2748,8 +2783,8 @@ nvim_win_close({window}, {force}) *nvim_win_close()* not allowed when |textlock| is active Parameters: ~ - {window} Window handle, or 0 for current window - {force} Behave like `:close!` The last window of a buffer with + • {window} Window handle, or 0 for current window + • {force} Behave like `:close!` The last window of a buffer with unwritten changes can be closed. The buffer will become hidden, even if 'hidden' is not set. @@ -2757,23 +2792,25 @@ nvim_win_del_var({window}, {name}) *nvim_win_del_var()* Removes a window-scoped (w:) variable Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name + • {window} Window handle, or 0 for current window + • {name} Variable name nvim_win_get_buf({window}) *nvim_win_get_buf()* Gets the current buffer in a window Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Buffer handle nvim_win_get_cursor({window}) *nvim_win_get_cursor()* - Gets the (1,0)-indexed cursor position in the window. |api-indexing| + Gets the (1,0)-indexed, buffer-relative cursor position for a given window + (different windows showing the same buffer have independent cursor + positions). |api-indexing| Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ (row, col) tuple @@ -2782,7 +2819,7 @@ nvim_win_get_height({window}) *nvim_win_get_height()* Gets the window height Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Height as a count of rows @@ -2791,7 +2828,7 @@ nvim_win_get_number({window}) *nvim_win_get_number()* Gets the window number Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Window number @@ -2800,7 +2837,7 @@ nvim_win_get_position({window}) *nvim_win_get_position()* Gets the window position in display cells. First position is zero. Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ (row, col) tuple with the window position @@ -2809,7 +2846,7 @@ nvim_win_get_tabpage({window}) *nvim_win_get_tabpage()* Gets the window tabpage Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Tabpage that contains the window @@ -2818,8 +2855,8 @@ nvim_win_get_var({window}, {name}) *nvim_win_get_var()* Gets a window-scoped (w:) variable Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name + • {window} Window handle, or 0 for current window + • {name} Variable name Return: ~ Variable value @@ -2828,7 +2865,7 @@ nvim_win_get_width({window}) *nvim_win_get_width()* Gets the window width Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Width as a count of columns @@ -2839,19 +2876,19 @@ nvim_win_hide({window}) *nvim_win_hide()* Like |:hide| the buffer becomes hidden unless another window is editing it, or 'bufhidden' is `unload`, `delete` or `wipe` as opposed to |:close| - or |nvim_win_close|, which will close the buffer. + or |nvim_win_close()|, which will close the buffer. Attributes: ~ not allowed when |textlock| is active Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window nvim_win_is_valid({window}) *nvim_win_is_valid()* Checks if a window is valid Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ true if the window is valid, false otherwise @@ -2863,48 +2900,48 @@ nvim_win_set_buf({window}, {buffer}) *nvim_win_set_buf()* not allowed when |textlock| is active Parameters: ~ - {window} Window handle, or 0 for current window - {buffer} Buffer handle + • {window} Window handle, or 0 for current window + • {buffer} Buffer handle nvim_win_set_cursor({window}, {pos}) *nvim_win_set_cursor()* Sets the (1,0)-indexed cursor position in the window. |api-indexing| This scrolls the window even if it is not the current one. Parameters: ~ - {window} Window handle, or 0 for current window - {pos} (row, col) tuple representing the new position + • {window} Window handle, or 0 for current window + • {pos} (row, col) tuple representing the new position nvim_win_set_height({window}, {height}) *nvim_win_set_height()* Sets the window height. Parameters: ~ - {window} Window handle, or 0 for current window - {height} Height as a count of rows + • {window} Window handle, or 0 for current window + • {height} Height as a count of rows nvim_win_set_hl_ns({window}, {ns_id}) *nvim_win_set_hl_ns()* Set highlight namespace for a window. This will use highlights defined in this namespace, but fall back to global highlights (ns=0) when missing. - This takes predecence over the 'winhighlight' option. + This takes precedence over the 'winhighlight' option. Parameters: ~ - {ns_id} the namespace to use + • {ns_id} the namespace to use nvim_win_set_var({window}, {name}, {value}) *nvim_win_set_var()* Sets a window-scoped (w:) variable Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name - {value} Variable value + • {window} Window handle, or 0 for current window + • {name} Variable name + • {value} Variable value nvim_win_set_width({window}, {width}) *nvim_win_set_width()* Sets the window width. This will only succeed if the screen is split vertically. Parameters: ~ - {window} Window handle, or 0 for current window - {width} Width as a count of columns + • {window} Window handle, or 0 for current window + • {width} Width as a count of columns ============================================================================== @@ -2935,12 +2972,12 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* could let floats hover outside of the main window like a tooltip, but this should not be used to specify arbitrary WM screen positions. - Example (Lua): window-relative float > + Example (Lua): window-relative float >lua vim.api.nvim_open_win(0, false, {relative='win', row=3, col=3, width=12, height=3}) < - Example (Lua): buffer-relative float (travels as buffer is scrolled) > + Example (Lua): buffer-relative float (travels as buffer is scrolled) >lua vim.api.nvim_open_win(0, false, {relative='win', width=12, height=3, bufpos={100,10}}) < @@ -2949,15 +2986,16 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer to display, or 0 for current buffer - {enter} Enter the window (make it the current window) - {config} Map defining the window configuration. Keys: + • {buffer} Buffer to display, or 0 for current buffer + • {enter} Enter the window (make it the current window) + • {config} Map defining the window configuration. Keys: • relative: Sets the window layout to "floating", placed at (row,col) coordinates relative to: • "editor" The global editor grid • "win" Window given by the `win` field, or current window. • "cursor" Cursor position in current window. + • "mouse" Mouse position • win: |window-ID| for relative="win". • anchor: Decides which corner of the float to place at @@ -3005,10 +3043,10 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* Disables 'number', 'relativenumber', 'cursorline', 'cursorcolumn', 'foldcolumn', 'spell' and 'list' options. 'signcolumn' is changed to `auto` and - 'colorcolumn' is cleared. The end-of-buffer region is - hidden by setting `eob` flag of 'fillchars' to a space - char, and clearing the |EndOfBuffer| region in - 'winhighlight'. + 'colorcolumn' is cleared. 'statuscolumn' is changed to + empty. The end-of-buffer region is hidden by setting + `eob` flag of 'fillchars' to a space char, and clearing + the |hl-EndOfBuffer| region in 'winhighlight'. • border: Style of (optional) window border. This can either be a string or an array. The string values are @@ -3034,9 +3072,14 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* borders but not horizontal ones. By default, `FloatBorder` highlight is used, which links to `WinSeparator` when not defined. It could also be - specified by character: [ {"+", "MyCorner"}, {"x", - "MyBorder"} ]. - + specified by character: [ ["+", "MyCorner"], ["x", + "MyBorder"] ]. + + • title: Title (optional) in window border, String or list. + List is [text, highlight] tuples. if is string the default + highlight group is `FloatTitle`. + • title_pos: Title position must set with title option. + value can be of `left` `center` `right` default is left. • noautocmd: If true then no buffer-related autocommand events such as |BufEnter|, |BufLeave| or |BufWinEnter| may fire from calling this function. @@ -3052,7 +3095,7 @@ nvim_win_get_config({window}) *nvim_win_get_config()* `relative` is empty for normal windows. Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Map defining the window configuration, see |nvim_open_win()| @@ -3065,8 +3108,8 @@ nvim_win_set_config({window}, {*config}) *nvim_win_set_config()* changed. `row`/`col` and `relative` must be reconfigured together. Parameters: ~ - {window} Window handle, or 0 for current window - {config} Map defining the window configuration, see |nvim_open_win()| + • {window} Window handle, or 0 for current window + • {config} Map defining the window configuration, see |nvim_open_win()| See also: ~ |nvim_open_win()| @@ -3079,14 +3122,14 @@ nvim_tabpage_del_var({tabpage}, {name}) *nvim_tabpage_del_var()* Removes a tab-scoped (t:) variable Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name + • {tabpage} Tabpage handle, or 0 for current tabpage + • {name} Variable name nvim_tabpage_get_number({tabpage}) *nvim_tabpage_get_number()* Gets the tabpage number Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ Tabpage number @@ -3095,8 +3138,8 @@ nvim_tabpage_get_var({tabpage}, {name}) *nvim_tabpage_get_var()* Gets a tab-scoped (t:) variable Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name + • {tabpage} Tabpage handle, or 0 for current tabpage + • {name} Variable name Return: ~ Variable value @@ -3105,7 +3148,7 @@ nvim_tabpage_get_win({tabpage}) *nvim_tabpage_get_win()* Gets the current window in a tabpage Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ Window handle @@ -3114,7 +3157,7 @@ nvim_tabpage_is_valid({tabpage}) *nvim_tabpage_is_valid()* Checks if a tabpage is valid Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ true if the tabpage is valid, false otherwise @@ -3123,7 +3166,7 @@ nvim_tabpage_list_wins({tabpage}) *nvim_tabpage_list_wins()* Gets the windows in a tabpage Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ List of windows in `tabpage` @@ -3133,9 +3176,9 @@ nvim_tabpage_set_var({tabpage}, {name}, {value}) Sets a tab-scoped (t:) variable Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name - {value} Variable value + • {tabpage} Tabpage handle, or 0 for current tabpage + • {name} Variable name + • {value} Variable value ============================================================================== @@ -3143,10 +3186,10 @@ Autocmd Functions *api-autocmd* nvim_clear_autocmds({*opts}) *nvim_clear_autocmds()* Clear all autocommands that match the corresponding {opts}. To delete a - particular autocmd, see |nvim_del_autocmd|. + particular autocmd, see |nvim_del_autocmd()|. Parameters: ~ - {opts} Parameters + • {opts} Parameters • event: (string|table) Examples: • event: "pat1" • event: { "pat1" } @@ -3171,15 +3214,15 @@ nvim_clear_autocmds({*opts}) *nvim_clear_autocmds()* nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* Create or get an autocommand group |autocmd-groups|. - To get an existing group id, do: > + To get an existing group id, do: >lua local id = vim.api.nvim_create_augroup("MyGroup", { clear = false }) < Parameters: ~ - {name} String: The name of the group - {opts} Dictionary Parameters + • {name} String: The name of the group + • {opts} Dictionary Parameters • clear (bool) optional: defaults to true. Clear existing commands if the group already exists |autocmd-groups|. @@ -3190,84 +3233,54 @@ nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* |autocmd-groups| nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* - Create an |autocommand| - - The API allows for two (mutually exclusive) types of actions to be - executed when the autocommand triggers: a callback function (Lua or - Vimscript), or a command (like regular autocommands). - - Example using callback: > - -- Lua function - local myluafun = function() print("This buffer enters") end - - -- Vimscript function name (as a string) - local myvimfun = "g:MyVimFunction" + Creates an |autocommand| event handler, defined by `callback` (Lua function or Vimscript function name string) or `command` (Ex command string). + Example using Lua callback: >lua vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { pattern = {"*.c", "*.h"}, - callback = myluafun, -- Or myvimfun + callback = function(ev) + print(string.format('event fired: s', vim.inspect(ev))) + end }) < - Lua functions receive a table with information about the autocmd event as - an argument. To use a function which itself accepts another (optional) - parameter, wrap the function in a lambda: -> - -- Lua function with an optional parameter. - -- The autocmd callback would pass a table as argument but this - -- function expects number|nil - local myluafun = function(bufnr) bufnr = bufnr or vim.api.nvim_get_current_buf() end - - vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { - pattern = {"*.c", "*.h"}, - callback = function() myluafun() end, - }) -< - - Example using command: > + Example using an Ex command as the handler: >lua vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { pattern = {"*.c", "*.h"}, command = "echo 'Entering a C or C++ file'", }) < - Example values for pattern: > - pattern = "*.py" - pattern = { "*.py", "*.pyi" } -< - - Example values for event: > - "BufWritePre" - {"CursorHold", "BufWritePre", "BufWritePost"} + Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|), thus names like + "$HOME" and "~" must be expanded explicitly: >lua + pattern = vim.fn.expand("~") .. "/some/path/*.py" < Parameters: ~ - {event} (string|array) The event or events to register this - autocommand - {opts} Dictionary of autocommand options: - • group (string|integer) optional: the autocommand group name - or id to match against. - • pattern (string|array) optional: pattern or patterns to - match against |autocmd-pattern|. - • buffer (integer) optional: buffer number for buffer local + • {event} (string|array) Event(s) that will trigger the handler + (`callback` or `command`). + • {opts} Options dict: + • group (string|integer) optional: autocommand group name or + id to match against. + • pattern (string|array) optional: pattern(s) to match + literally |autocmd-pattern|. + • buffer (integer) optional: buffer number for buffer-local autocommands |autocmd-buflocal|. Cannot be used with {pattern}. - • desc (string) optional: description of the autocommand. - • callback (function|string) optional: if a string, the name - of a Vimscript function to call when this autocommand is - triggered. Otherwise, a Lua function which is called when - this autocommand is triggered. Cannot be used with - {command}. Lua callbacks can return true to delete the - autocommand; in addition, they accept a single table - argument with the following keys: - • id: (number) the autocommand id - • event: (string) the name of the event that triggered the - autocommand |autocmd-events| - • group: (number|nil) the autocommand group id, if it - exists - • match: (string) the expanded value of |<amatch>| - • buf: (number) the expanded value of |<abuf>| - • file: (string) the expanded value of |<afile>| + • desc (string) optional: description (for documentation and + troubleshooting). + • callback (function|string) optional: Lua function (or + Vimscript function name, if string) called when the + event(s) is triggered. Lua callback can return true to + delete the autocommand, and receives a table argument with + these keys: + • id: (number) autocommand id + • event: (string) name of the triggered event + |autocmd-events| + • group: (number|nil) autocommand group id, if any + • match: (string) expanded value of |<amatch>| + • buf: (number) expanded value of |<abuf>| + • file: (string) expanded value of |<afile>| • data: (any) arbitrary data passed to |nvim_exec_autocmds()| @@ -3279,7 +3292,7 @@ nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* autocommands |autocmd-nested|. Return: ~ - Integer id of the created autocommand. + Autocommand id (number) See also: ~ |autocommand| @@ -3290,12 +3303,12 @@ nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()* To get a group id one can use |nvim_get_autocmds()|. - NOTE: behavior differs from |augroup-delete|. When deleting a group, + NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in this group will also be deleted and cleared. This group will no longer exist. Parameters: ~ - {id} Integer The id of the group. + • {id} Integer The id of the group. See also: ~ |nvim_del_augroup_by_name()| @@ -3304,15 +3317,15 @@ nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()* nvim_del_augroup_by_name({name}) *nvim_del_augroup_by_name()* Delete an autocommand group by name. - NOTE: behavior differs from |augroup-delete|. When deleting a group, + NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in this group will also be deleted and cleared. This group will no longer exist. Parameters: ~ - {name} String The name of the group. + • {name} String The name of the group. See also: ~ - |autocommand-groups| + |autocmd-groups| nvim_del_autocmd({id}) *nvim_del_autocmd()* Delete an autocommand by id. @@ -3320,7 +3333,7 @@ nvim_del_autocmd({id}) *nvim_del_autocmd()* NOTE: Only autocommands created via the API have an id. Parameters: ~ - {id} Integer The id returned by nvim_create_autocmd + • {id} Integer The id returned by nvim_create_autocmd See also: ~ |nvim_create_autocmd()| @@ -3330,8 +3343,8 @@ nvim_exec_autocmds({event}, {*opts}) *nvim_exec_autocmds()* |autocmd-execute|. Parameters: ~ - {event} (String|Array) The event or events to execute - {opts} Dictionary of autocommand options: + • {event} (String|Array) The event or events to execute + • {opts} Dictionary of autocommand options: • group (string|integer) optional: the autocommand group name or id to match against. |autocmd-groups|. • pattern (string|array) optional: defaults to "*" @@ -3349,7 +3362,7 @@ nvim_exec_autocmds({event}, {*opts}) *nvim_exec_autocmds()* nvim_get_autocmds({*opts}) *nvim_get_autocmds()* Get all autocommands that match the corresponding {opts}. - These examples will get autocommands matching ALL the given criteria: > + These examples will get autocommands matching ALL the given criteria: >lua -- Matches all criteria autocommands = vim.api.nvim_get_autocmds({ group = "MyGroup", @@ -3367,13 +3380,16 @@ nvim_get_autocmds({*opts}) *nvim_get_autocmds()* autocommands that match any combination of them. Parameters: ~ - {opts} Dictionary with at least one of the following: + • {opts} Dictionary with at least one of the following: • group (string|integer): the autocommand group name or id to match against. • event (string|array): event or events to match against |autocmd-events|. • pattern (string|array): pattern or patterns to match against - |autocmd-pattern|. + |autocmd-pattern|. Cannot be used with {buffer} + • buffer: Buffer number or list of buffer numbers for buffer + local autocommands |autocmd-buflocal|. Cannot be used with + {pattern} Return: ~ Array of autocommands matching the criteria, with each item containing @@ -3413,9 +3429,9 @@ nvim_ui_attach({width}, {height}, {options}) *nvim_ui_attach()* |RPC| only Parameters: ~ - {width} Requested screen columns - {height} Requested screen rows - {options} |ui-option| map + • {width} Requested screen columns + • {height} Requested screen rows + • {options} |ui-option| map nvim_ui_detach() *nvim_ui_detach()* Deactivates UI events on the channel. @@ -3427,8 +3443,8 @@ nvim_ui_detach() *nvim_ui_detach()* *nvim_ui_pum_set_bounds()* nvim_ui_pum_set_bounds({width}, {height}, {row}, {col}) - Tells Nvim the geometry of the popumenu, to align floating windows with an - external popup menu. + Tells Nvim the geometry of the popupmenu, to align floating windows with + an external popup menu. Note that this method is not to be confused with |nvim_ui_pum_set_height()|, which sets the number of visible items in the @@ -3441,20 +3457,26 @@ nvim_ui_pum_set_bounds({width}, {height}, {row}, {col}) |RPC| only Parameters: ~ - {width} Popupmenu width. - {height} Popupmenu height. - {row} Popupmenu row. - {col} Popupmenu height. + • {width} Popupmenu width. + • {height} Popupmenu height. + • {row} Popupmenu row. + • {col} Popupmenu height. nvim_ui_pum_set_height({height}) *nvim_ui_pum_set_height()* - Tells Nvim the number of elements displaying in the popumenu, to decide + Tells Nvim the number of elements displaying in the popupmenu, to decide <PageUp> and <PageDown> movement. Attributes: ~ |RPC| only Parameters: ~ - {height} Popupmenu height, must be greater than zero. + • {height} Popupmenu height, must be greater than zero. + +nvim_ui_set_focus({gained}) *nvim_ui_set_focus()* + Tells the nvim server if focus was gained or lost by the GUI. + + Attributes: ~ + |RPC| only nvim_ui_set_option({name}, {value}) *nvim_ui_set_option()* TODO: Documentation @@ -3479,8 +3501,8 @@ nvim_ui_try_resize_grid({grid}, {width}, {height}) |RPC| only Parameters: ~ - {grid} The handle of the grid to be changed. - {width} The new requested width. - {height} The new requested height. + • {grid} The handle of the grid to be changed. + • {width} The new requested width. + • {height} The new requested height. vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/arabic.txt b/runtime/doc/arabic.txt index 0df861111c..0a80edb981 100644 --- a/runtime/doc/arabic.txt +++ b/runtime/doc/arabic.txt @@ -14,8 +14,9 @@ It is best to view this file with these settings within VIM's GUI: > :set arabicshape +------------------------------------------------------------------------------ Introduction ------------- + Arabic is a rather demanding language in which a number of special features are required. Characters are right-to-left oriented and ought to appear as such on the screen (i.e. from right to left). @@ -34,8 +35,9 @@ The commands, prompts and help files are not in Arabic, therefore the user interface remains the standard Vi interface. +------------------------------------------------------------------------------ Highlights ----------- + o Editing left-to-right files as in the original Vim hasn't changed. o Viewing and editing files in right-to-left windows. File @@ -64,8 +66,8 @@ o Proper Bidirectional functionality is possible given Vim is started within a Bidi capable terminal emulator. +------------------------------------------------------------------------------ Arabic Fonts *arabicfonts* ------------- Vim requires monospaced fonts of which there are many out there. Arabic requires ISO-8859-6 as well as Presentation Form-B fonts @@ -75,8 +77,8 @@ Do an Internet search or check www.arabeyes.org for further info on where to obtain the necessary Arabic fonts. +------------------------------------------------------------------------------ Font Installation ------------------ o Installation of fonts for X Window systems (Unix/Linux) @@ -88,8 +90,9 @@ o Installation of fonts for X Window systems (Unix/Linux) % xset +fp path_name_of_arabic_fonts_directory +------------------------------------------------------------------------------ Usage ------ + Prior to the actual usage of Arabic within Vim, a number of settings need to be accounted for and invoked. @@ -259,8 +262,8 @@ o Enable Arabic settings [short-cut] ':set arabicshape' to your vimrc file. +------------------------------------------------------------------------------ Keymap/Keyboard *arabickeymap* ---------------- The character/letter encoding used in Vim is the standard UTF-8. It is widely discouraged that any other encoding be used or even @@ -276,7 +279,7 @@ o Keyboard + CTRL-^ in insert/replace mode toggles between Arabic/Latin mode + Keyboard mapping is based on the Microsoft's Arabic keymap (the - de facto standard in the Arab world): + de facto standard in the Arab world): > +---------------------------------------------------------------------+ |! |@ |# |$ |% |^ |& |* |( |) |_ |+ || |~ ّ | @@ -291,17 +294,18 @@ o Keyboard |Z ~ |X ْ |C { |V } |B لآ |N آ |M ' |< , |> . |? ؟ | |z ئ |x ء |c ؤ |v ر |b لا |n ى |m ة |, و |. ز |/ ظ | +-------------------------------------------------+ +< +------------------------------------------------------------------------------ Restrictions ------------- o Vim in its GUI form does not currently support Bi-directionality (i.e. the ability to see both Arabic and Latin intermixed within the same line). +------------------------------------------------------------------------------ Known Bugs ----------- There is one known minor bug, diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt index 63226fe701..8cc4754880 100644 --- a/runtime/doc/autocmd.txt +++ b/runtime/doc/autocmd.txt @@ -57,7 +57,7 @@ The special pattern <buffer> or <buffer=N> defines a buffer-local autocommand. See |autocmd-buflocal|. Note: The ":autocmd" command can only be followed by another command when the -'|' appears where the pattern is expected. This works: > +"|" appears where the pattern is expected. This works: > :augroup mine | au! BufRead | augroup END But this sees "augroup" as part of the defined command: > :augroup mine | au! BufRead * | augroup END @@ -412,6 +412,8 @@ CmdwinLeave Before leaving the command-line window. |cmdwin-char| *ColorScheme* ColorScheme After loading a color scheme. |:colorscheme| + Not triggered if the color scheme is not + found. The pattern is matched against the colorscheme name. <afile> can be used for the name of the actual file where this option was @@ -588,6 +590,7 @@ FileChangedShell When Vim notices that the modification time of - executing a shell command - |:checktime| - |FocusGained| + Not used when 'autoread' is set and the buffer was not changed. If a FileChangedShell autocommand exists the warning message and @@ -678,16 +681,12 @@ FuncUndefined When a user function is used but it isn't UIEnter After a UI connects via |nvim_ui_attach()|, or after builtin TUI is started, after |VimEnter|. Sets these |v:event| keys: - chan: 0 for builtin TUI - 1 for |--embed| - |channel-id| of the UI otherwise + chan: |channel-id| of the UI *UILeave* UILeave After a UI disconnects from Nvim, or after builtin TUI is stopped, after |VimLeave|. Sets these |v:event| keys: - chan: 0 for builtin TUI - 1 for |--embed| - |channel-id| of the UI otherwise + chan: |channel-id| of the UI *InsertChange* InsertChange When typing <Insert> while in Insert or Replace mode. The |v:insertmode| variable @@ -803,7 +802,7 @@ OptionSet After setting an option (except during QuickFixCmdPre Before a quickfix command is run (|:make|, |:lmake|, |:grep|, |:lgrep|, |:grepadd|, |:lgrepadd|, |:vimgrep|, |:lvimgrep|, - |:vimgrepadd|, |:lvimgrepadd|, |:cscope|, + |:vimgrepadd|, |:lvimgrepadd|, |:cfile|, |:cgetfile|, |:caddfile|, |:lfile|, |:lgetfile|, |:laddfile|, |:helpgrep|, |:lhelpgrep|, |:cexpr|, |:cgetexpr|, @@ -820,8 +819,8 @@ QuickFixCmdPre Before a quickfix command is run (|:make|, QuickFixCmdPost Like QuickFixCmdPre, but after a quickfix command is run, before jumping to the first location. For |:cfile| and |:lfile| commands - it is run after error file is read and before - moving to the first error. + it is run after the error file is read and + before moving to the first error. See |QuickFixCmdPost-example|. *QuitPre* QuitPre When using `:quit`, `:wq` or `:qall`, before @@ -833,13 +832,13 @@ QuitPre When using `:quit`, `:wq` or `:qall`, before See also |ExitPre|, |WinClosed|. *RemoteReply* RemoteReply When a reply from a Vim that functions as - server was received |server2client()|. The + server was received server2client(). The pattern is matched against the {serverid}. <amatch> is equal to the {serverid} from which the reply was sent, and <afile> is the actual reply string. Note that even if an autocommand is defined, - the reply should be read with |remote_read()| + the reply should be read with remote_read() to consume it. *SearchWrapped* SearchWrapped After making a search with |n| or |N| if the @@ -993,6 +992,10 @@ TextChangedP After a change was made to the text in the current buffer in Insert mode, only when the popup menu is visible. Otherwise the same as TextChanged. + *TextChangedT* +TextChangedT After a change was made to the text in the + current buffer in |Terminal-mode|. Otherwise + the same as TextChanged. *TextYankPost* TextYankPost Just after a |yank| or |deleting| command, but not if the black hole register |quote_| is used nor @@ -1058,8 +1061,9 @@ VimResume After Nvim resumes from |suspend| state. *VimSuspend* VimSuspend Before Nvim enters |suspend| state. *WinClosed* -WinClosed After closing a window. The pattern is - matched against the |window-ID|. Both +WinClosed When closing a window, just before it is + removed from the window layout. The pattern + is matched against the |window-ID|. Both <amatch> and <afile> are set to the |window-ID|. After WinLeave. Non-recursive (event cannot trigger itself). @@ -1088,23 +1092,48 @@ WinNew When a new window was created. Not done for Before WinEnter. *WinScrolled* -WinScrolled After scrolling the content of a window or - resizing a window. - The pattern is matched against the - |window-ID|. Both <amatch> and <afile> are - set to the |window-ID|. - Non-recursive (the event cannot trigger - itself). However, if the command causes the - window to scroll or change size another +WinScrolled After any window in the current tab page + scrolled the text (horizontally or vertically) + or changed width or height. See + |win-scrolled-resized|. + + The pattern is matched against the |window-ID| + of the first window that scrolled or resized. + Both <amatch> and <afile> are set to the + |window-ID|. + + |v:event| is set with information about size + and scroll changes. |WinScrolled-event| + + Only starts triggering after startup finished + and the first screen redraw was done. + Does not trigger when defining the first + WinScrolled or WinResized event, but may + trigger when adding more. + + Non-recursive: the event will not trigger + while executing commands for the WinScrolled + event. However, if the command causes a + window to scroll or change size, then another WinScrolled event will be triggered later. - Does not trigger when the command is added, - only after the first scroll or resize. + + + *WinResized* +WinResized After a window in the current tab page changed + width or height. + See |win-scrolled-resized|. + + |v:event| is set with information about size + changes. |WinResized-event| + + Same behavior as |WinScrolled| for the + pattern, triggering and recursiveness. ============================================================================== 6. Patterns *autocmd-pattern* *{aupat}* -The {aupat} argument of `:autocmd` can be a comma-separated list. This works -as if the command was given with each pattern separately. Thus this command: > +The {aupat} argument of `:autocmd` can be a comma-separated list. This works as +if the command was given with each pattern separately. Thus this command: > :autocmd BufRead *.txt,*.info set et Is equivalent to: > :autocmd BufRead *.txt set et @@ -1204,7 +1233,7 @@ still executed. ============================================================================== 7. Buffer-local autocommands *autocmd-buflocal* *autocmd-buffer-local* - *<buffer=N>* *<buffer=abuf>* *E680* + *<buffer>* *<buffer=N>* *<buffer=abuf>* *E680* Buffer-local autocommands are attached to a specific buffer. They are useful if the buffer does not have a name and when the name does not match a specific diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 0be9e9b9d1..4d2c85b134 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -4,11 +4,11 @@ VIM REFERENCE MANUAL by Bram Moolenaar -Builtin functions *builtin-functions* +Builtin functions *vimscript-functions* *builtin-functions* -1. Overview |builtin-function-list| -2. Details |builtin-function-details| -3. Matching a pattern in a String |string-match| +For functions grouped by what they are used for see |function-list|. + + Type |gO| to see the table of contents. ============================================================================== 1. Overview *builtin-function-list* @@ -68,8 +68,8 @@ bufnr([{expr} [, {create}]]) Number Number of the buffer {expr} bufwinid({expr}) Number |window-ID| of buffer {expr} bufwinnr({expr}) Number window number of buffer {expr} byte2line({byte}) Number line number at byte count {byte} -byteidx({expr}, {nr}) Number byte index of {nr}'th char in {expr} -byteidxcomp({expr}, {nr}) Number byte index of {nr}'th char in {expr} +byteidx({expr}, {nr}) Number byte index of {nr}th char in {expr} +byteidxcomp({expr}, {nr}) Number byte index of {nr}th char in {expr} call({func}, {arglist} [, {dict}]) any call {func} with arguments {arglist} ceil({expr}) Float round {expr} up @@ -78,13 +78,13 @@ chanclose({id} [, {stream}]) Number Closes a channel or one of its streams chansend({id}, {data}) Number Writes {data} to channel char2nr({expr} [, {utf8}]) Number ASCII/UTF-8 value of first char in {expr} charclass({string}) Number character class of {string} -charcol({expr}) Number column number of cursor or mark +charcol({expr} [, {winid}]) Number column number of cursor or mark charidx({string}, {idx} [, {countcc}]) Number char index of byte {idx} in {string} chdir({dir}) String change current working directory cindent({lnum}) Number C indent for line {lnum} clearmatches([{win}]) none clear all matches -col({expr}) Number column byte index of cursor or mark +col({expr} [, {winid}]) Number column byte index of cursor or mark complete({startcol}, {matches}) none set Insert mode completion complete_add({expr}) Number add completion match complete_check() Number check for key typed during completion @@ -96,8 +96,6 @@ cos({expr}) Float cosine of {expr} cosh({expr}) Float hyperbolic cosine of {expr} count({comp}, {expr} [, {ic} [, {start}]]) Number count how many {expr} are in {comp} -cscope_connection([{num}, {dbpath} [, {prepend}]]) - Number checks existence of cscope connection ctxget([{index}]) Dict return the |context| dict at {index} ctxpop() none pop and restore |context| from the |context-stack| @@ -136,7 +134,8 @@ exists({expr}) Number |TRUE| if {expr} exists exp({expr}) Float exponential of {expr} expand({expr} [, {nosuf} [, {list}]]) any expand special keywords in {expr} -expandcmd({expr}) String expand {expr} like with `:edit` +expandcmd({string} [, {options}]) + String expand {string} like with `:edit` extend({expr1}, {expr2} [, {expr3}]) List/Dict insert items of {expr2} into {expr1} feedkeys({string} [, {mode}]) Number add key sequence to typeahead buffer @@ -171,8 +170,10 @@ get({func}, {what}) any get property of funcref/partial {func} getbufinfo([{buf}]) List information about buffers getbufline({buf}, {lnum} [, {end}]) List lines {lnum} to {end} of buffer {buf} +getbufoneline({buf}, {lnum}) String line {lnum} of buffer {buf} getbufvar({buf}, {varname} [, {def}]) any variable {varname} in buffer {buf} +getcellwidths() List get character cell width overrides getchangelist([{buf}]) List list of change list items getchar([expr]) Number or String get one character from the user @@ -222,6 +223,7 @@ gettabvar({nr}, {varname} [, {def}]) gettabwinvar({tabnr}, {winnr}, {name} [, {def}]) any {name} in {winnr} in tab page {tabnr} gettagstack([{nr}]) Dict get the tag stack of window {nr} +gettext({text}) String lookup translation of {text} getwininfo([{winid}]) List list of info about each window getwinpos([{timeout}]) List X and Y coord in pixels of the Vim window getwinposx() Number X coord in pixels of Vim window @@ -279,6 +281,8 @@ join({list} [, {sep}]) String join {list} items into one String json_decode({expr}) any Convert {expr} from JSON json_encode({expr}) String Convert {expr} to JSON keys({dict}) List keys in {dict} +keytrans({string}) String translate internal keycodes to a form + that can be used by |:map| len({expr}) Number the length of {expr} libcall({lib}, {func}, {arg}) String call {func} in library {lib} with {arg} libcallnr({lib}, {func}, {arg}) Number idem, but return a Number @@ -315,9 +319,9 @@ matchfuzzypos({list}, {str} [, {dict}]) matchlist({expr}, {pat} [, {start} [, {count}]]) List match and submatches of {pat} in {expr} matchstr({expr}, {pat} [, {start} [, {count}]]) - String {count}'th match of {pat} in {expr} + String {count}th match of {pat} in {expr} matchstrpos({expr}, {pat} [, {start} [, {count}]]) - List {count}'th match of {pat} in {expr} + List {count}th match of {pat} in {expr} max({expr}) Number maximum value of items in {expr} menu_get({path} [, {modes}]) List description of |menus| matched by {path} menu_info({name} [, {mode}]) Dict get menu item information @@ -348,6 +352,7 @@ pyxeval({expr}) any evaluate |python_x| expression rand([{expr}]) Number get pseudo-random number range({expr} [, {max} [, {stride}]]) List items from {expr} to {max} +readblob({fname}) Blob read a |Blob| from {fname} readdir({dir} [, {expr}]) List file names in {dir} selected by {expr} readfile({fname} [, {type} [, {max}]]) List get list of lines from file {fname} @@ -400,6 +405,7 @@ setbufvar({buf}, {varname}, {val}) set {varname} in buffer {buf} to {val} setcellwidths({list}) none set character cell width overrides setcharpos({expr}, {list}) Number set the {expr} position to {list} setcharsearch({dict}) Dict set character search from {dict} +setcmdline({str} [, {pos}]) Number set command-line setcmdpos({pos}) Number set cursor position in command-line setcursorcharpos({list}) Number move cursor to position in {list} setenv({name}, {val}) none set environment variable @@ -463,10 +469,11 @@ str2list({expr} [, {utf8}]) List convert each character of {expr} to ASCII/UTF-8 value str2nr({expr} [, {base} [, {quoted}]]) Number convert String to Number +strcharlen({expr}) Number character length of the String {expr} strcharpart({str}, {start} [, {len}]) String {len} characters of {str} at character {start} -strchars({expr} [, {skipcc}]) Number character length of the String {expr} +strchars({expr} [, {skipcc}]) Number character count of the String {expr} strdisplaywidth({expr} [, {col}]) Number display length of the String {expr} strftime({format} [, {time}]) String format time with a specified format strgetchar({str}, {index}) Number get char {index} from {str} @@ -527,6 +534,8 @@ uniq({list} [, {func} [, {dict}]]) List remove adjacent duplicates from a list values({dict}) List values in {dict} virtcol({expr}) Number screen column of cursor or mark +virtcol2col({winid}, {lnum}, {col}) + Number byte index of a character on screen visualmode([expr]) String last visual mode used wait({timeout}, {condition} [, {interval}]) Number Wait until {condition} is satisfied @@ -631,6 +640,7 @@ append({lnum}, {text}) *append()* text line below line {lnum} in the current buffer. Otherwise append {text} as one text line below line {lnum} in the current buffer. + Any type of item is accepted and converted to a String. {lnum} can be zero to insert a line before the first one. {lnum} is used like with |getline()|. Returns 1 for failure ({lnum} out of range or out of memory), @@ -649,9 +659,10 @@ appendbufline({buf}, {lnum}, {text}) *appendbufline()* For the use of {buf}, see |bufname()|. - {lnum} is used like with |append()|. Note that using |line()| - would use the current buffer, not the one appending to. - Use "$" to append at the end of the buffer. + {lnum} is the line number to append below. Note that using + |line()| would use the current buffer, not the one appending + to. Use "$" to append at the end of the buffer. Other string + values are not supported. On success 0 is returned, on failure 1 is returned. @@ -784,7 +795,8 @@ browsedir({title}, {initdir}) browsing is not possible, an empty string is returned. bufadd({name}) *bufadd()* - Add a buffer to the buffer list with String {name}. + Add a buffer to the buffer list with name {name} (must be a + String). If a buffer for file {name} already exists, return that buffer number. Otherwise return the buffer number of the newly created buffer. When {name} is an empty string then a new @@ -835,7 +847,8 @@ bufload({buf}) *bufload()* Ensure the buffer {buf} is loaded. When the buffer name refers to an existing file then the file is read. Otherwise the buffer will be empty. If the buffer was already loaded - then there is no change. + then there is no change. If the buffer is not related to a + file the no file is read (e.g., when 'buftype' is "nofile"). If there is an existing swap file for the file of the buffer, there will be no dialog, the buffer will be loaded anyway. The {buf} argument is used like with |bufexists()|. @@ -910,7 +923,8 @@ bufwinid({buf}) *bufwinid()* echo "A window containing buffer 1 is " .. (bufwinid(1)) < - Only deals with the current tab page. + Only deals with the current tab page. See |win_findbuf()| for + finding more. Can also be used as a |method|: > FindBuffer()->bufwinid() @@ -943,7 +957,7 @@ byte2line({byte}) *byte2line()* GetOffset()->byte2line() byteidx({expr}, {nr}) *byteidx()* - Return byte index of the {nr}'th character in the String + Return byte index of the {nr}th character in the String {expr}. Use zero for the first character, it then returns zero. If there are no multibyte characters the returned value is @@ -1027,7 +1041,7 @@ chanclose({id} [, {stream}]) *chanclose()* are closed. If the channel is a pty, this will then close the pty master, sending SIGHUP to the job process. For a socket, there is only one stream, and {stream} should be - ommited. + omitted. chansend({id}, {data}) *chansend()* Send data to channel {id}. For a job, it writes it to the @@ -1078,8 +1092,8 @@ charclass({string}) *charclass()* Returns 0 if {string} is not a |String|. - *charcol()* -charcol({expr}) Same as |col()| but returns the character index of the column +charcol({expr} [, {winid}]) *charcol()* + Same as |col()| but returns the character index of the column position given with {expr} instead of the byte position. Example: @@ -1126,16 +1140,20 @@ chdir({dir}) *chdir()* directory (|:tcd|) then changes the tabpage local directory. - Otherwise, changes the global directory. + {dir} must be a String. If successful, returns the previous working directory. Pass this to another chdir() to restore the directory. On failure, returns an empty string. Example: > let save_dir = chdir(newdir) - if save_dir + if save_dir != "" " ... do some work call chdir(save_dir) endif + +< Can also be used as a |method|: > + GetDir()->chdir() < cindent({lnum}) *cindent()* Get the amount of indent for line {lnum} according the C @@ -1157,8 +1175,8 @@ clearmatches([{win}]) *clearmatches()* Can also be used as a |method|: > GetWin()->clearmatches() < - *col()* -col({expr}) The result is a Number, which is the byte index of the column +col({expr} [, {winid}) *col()* + The result is a Number, which is the byte index of the column position given with {expr}. The accepted positions are: . the cursor position $ the end of the cursor line (the result is the @@ -1173,6 +1191,8 @@ col({expr}) The result is a Number, which is the byte index of the column and column number. Most useful when the column is "$", to get the last column of a specific line. When "lnum" or "col" is out of range then col() returns zero. + With the optional {winid} argument the values are obtained for + that window instead of the current window. To get the line number use |line()|. To get both use |getpos()|. For the screen column position use |virtcol()|. For the @@ -1183,16 +1203,15 @@ col({expr}) The result is a Number, which is the byte index of the column col("$") length of cursor line plus one col("'t") column of mark t col("'" .. markname) column of mark markname -< The first column is 1. Returns 0 if {expr} is invalid. +< The first column is 1. Returns 0 if {expr} is invalid or when + the window with ID {winid} is not found. For an uppercase mark the column may actually be in another buffer. For the cursor position, when 'virtualedit' is active, the column is one higher if the cursor is after the end of the - line. This can be used to obtain the column in Insert mode: > - :imap <F2> <C-O>:let save_ve = &ve<CR> - \<C-O>:set ve=all<CR> - \<C-O>:echo col(".") .. "\n" <Bar> - \let &ve = save_ve<CR> + line. Also, when using a <Cmd> mapping the cursor isn't + moved, this can be used to obtain the column in Insert mode: > + :imap <F2> <Cmd>echo col(".").."\n"<CR> < Can also be used as a |method|: > GetPos()->col() @@ -1270,7 +1289,7 @@ complete_info([{what}]) *complete_info()* typed text only, or the last completion after no item is selected when using the <Up> or <Down> keys) - inserted Inserted string. [NOT IMPLEMENT YET] + inserted Inserted string. [NOT IMPLEMENTED YET] *complete_info_mode* mode values are: @@ -1425,47 +1444,6 @@ count({comp}, {expr} [, {ic} [, {start}]]) *count()* Can also be used as a |method|: > mylist->count(val) < - *cscope_connection()* -cscope_connection([{num} , {dbpath} [, {prepend}]]) - Checks for the existence of a |cscope| connection. If no - parameters are specified, then the function returns: - 0, if there are no cscope connections; - 1, if there is at least one cscope connection. - - If parameters are specified, then the value of {num} - determines how existence of a cscope connection is checked: - - {num} Description of existence check - ----- ------------------------------ - 0 Same as no parameters (e.g., "cscope_connection()"). - 1 Ignore {prepend}, and use partial string matches for - {dbpath}. - 2 Ignore {prepend}, and use exact string matches for - {dbpath}. - 3 Use {prepend}, use partial string matches for both - {dbpath} and {prepend}. - 4 Use {prepend}, use exact string matches for both - {dbpath} and {prepend}. - - Note: All string comparisons are case sensitive! - - Examples. Suppose we had the following (from ":cs show"): > - - # pid database name prepend path - 0 27664 cscope.out /usr/local -< - Invocation Return Val ~ - ---------- ---------- > - cscope_connection() 1 - cscope_connection(1, "out") 1 - cscope_connection(2, "out") 0 - cscope_connection(3, "out") 0 - cscope_connection(3, "out", "local") 1 - cscope_connection(4, "out") 0 - cscope_connection(4, "out", "local") 0 - cscope_connection(4, "cscope.out", "/usr/local") 1 -< - ctxget([{index}]) *ctxget()* Returns a |Dictionary| representing the |context| at {index} from the top of the |context-stack| (see |context-dict|). @@ -1508,9 +1486,10 @@ cursor({list}) |setcursorcharpos()|. Does not change the jumplist. + {lnum} is used like with |getline()|, except that if {lnum} is + zero, the cursor will stay in the current line. If {lnum} is greater than the number of lines in the buffer, the cursor will be positioned at the last line in the buffer. - If {lnum} is zero, the cursor will stay in the current line. If {col} is greater than the number of bytes in the line, the cursor will be positioned at the last character in the line. @@ -1526,6 +1505,18 @@ cursor({list}) Can also be used as a |method|: > GetCursorPos()->cursor() +debugbreak({pid}) *debugbreak()* + Specifically used to interrupt a program being debugged. It + will cause process {pid} to get a SIGTRAP. Behavior for other + processes is undefined. See |terminal-debug|. + (Sends a SIGINT to a process {pid} other than MS-Windows) + + Returns |TRUE| if successfully interrupted the program. + Otherwise returns |FALSE|. + + Can also be used as a |method|: > + GetPid()->debugbreak() + deepcopy({expr} [, {noref}]) *deepcopy()* *E698* Make a copy of {expr}. For Numbers and Strings this isn't different from using {expr} directly. @@ -1607,9 +1598,9 @@ dictwatcheradd({dict}, {pattern}, {callback}) *dictwatcheradd()* call dictwatcheradd(g:, '*', 'OnDictChanged') < For now {pattern} only accepts very simple patterns that can - contain a '*' at the end of the string, in which case it will - match every key that begins with the substring before the '*'. - That means if '*' is not the last character of {pattern}, only + contain a "*" at the end of the string, in which case it will + match every key that begins with the substring before the "*". + That means if "*" is not the last character of {pattern}, only keys that are exactly equal as {pattern} will be matched. The {callback} receives three arguments: @@ -1967,18 +1958,6 @@ exp({expr}) *exp()* Can also be used as a |method|: > Compute()->exp() -debugbreak({pid}) *debugbreak()* - Specifically used to interrupt a program being debugged. It - will cause process {pid} to get a SIGTRAP. Behavior for other - processes is undefined. See |terminal-debugger|. - {Sends a SIGINT to a process {pid} other than MS-Windows} - - Returns |TRUE| if successfully interrupted the program. - Otherwise returns |FALSE|. - - Can also be used as a |method|: > - GetPid()->debugbreak() - expand({string} [, {nosuf} [, {list}]]) *expand()* Expand wildcards and the following special keywords in {string}. 'wildignorecase' applies. @@ -2010,6 +1989,8 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* a function <SID> "<SNR>123_" where "123" is the current script ID |<SID>| + <script> sourced script file, or script file + where the current function was defined <stack> call stack <cword> word under the cursor <cWORD> WORD under the cursor @@ -2043,6 +2024,9 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* is not defined, an empty string is used. Using "%:p" in a buffer with no name, results in the current directory, with a '/' added. + When 'verbose' is set then expanding '%', '#' and <> items + will result in an error message if the argument cannot be + expanded. When {string} does not start with '%', '#' or '<', it is expanded like a file name is expanded on the command line. @@ -2068,18 +2052,27 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* Can also be used as a |method|: > Getpattern()->expand() -expandcmd({string}) *expandcmd()* +expandcmd({string} [, {options}]) *expandcmd()* Expand special items in String {string} like what is done for an Ex command such as `:edit`. This expands special keywords, like with |expand()|, and environment variables, anywhere in {string}. "~user" and "~/path" are only expanded at the start. + + The following items are supported in the {options} Dict + argument: + errmsg If set to TRUE, error messages are displayed + if an error is encountered during expansion. + By default, error messages are not displayed. + Returns the expanded string. If an error is encountered during expansion, the unmodified {string} is returned. + Example: > :echo expandcmd('make %<.o') -< make /path/runtime/doc/builtin.o ~ - + make /path/runtime/doc/builtin.o + :echo expandcmd('make %<.o', {'errmsg': v:true}) +< Can also be used as a |method|: > GetCommand()->expandcmd() < @@ -2305,7 +2298,7 @@ flatten({list} [, {maxdepth}]) *flatten()* float2nr({expr}) *float2nr()* Convert {expr} to a Number by omitting the part after the decimal point. - {expr} must evaluate to a |Float| or a Number. + {expr} must evaluate to a |Float| or a |Number|. Returns 0 if {expr} is not a |Float| or a |Number|. When the value of {expr} is out of range for a |Number| the result is truncated to 0x7fffffff or -0x7fffffff (or when @@ -2496,10 +2489,11 @@ funcref({name} [, {arglist}] [, {dict}]) Can also be used as a |method|: > GetFuncname()->funcref([arg]) < - *function()* *E700* *E922* *E923* + *function()* *partial* *E700* *E922* *E923* function({name} [, {arglist}] [, {dict}]) Return a |Funcref| variable that refers to function {name}. - {name} can be a user defined function or an internal function. + {name} can be the name of a user defined function or an + internal function. {name} can also be a Funcref or a partial. When it is a partial the dict stored in it will be used and the {dict} @@ -2518,30 +2512,56 @@ function({name} [, {arglist}] [, {dict}]) The arguments are passed to the function in front of other arguments, but after any argument from |method|. Example: > func Callback(arg1, arg2, name) - ... + "... let Partial = function('Callback', ['one', 'two']) - ... + "... call Partial('name') < Invokes the function as with: > call Callback('one', 'two', 'name') +< With a |method|: > + func Callback(one, two, three) + "... + let Partial = function('Callback', ['two']) + "... + eval 'one'->Partial('three') +< Invokes the function as with: > + call Callback('one', 'two', 'three') + +< The function() call can be nested to add more arguments to the + Funcref. The extra arguments are appended to the list of + arguments. Example: > + func Callback(arg1, arg2, name) + "... + let Func = function('Callback', ['one']) + let Func2 = function(Func, ['two']) + "... + call Func2('name') +< Invokes the function as with: > + call Callback('one', 'two', 'name') + < The Dictionary is only useful when calling a "dict" function. In that case the {dict} is passed in as "self". Example: > function Callback() dict echo "called for " .. self.name endfunction - ... + "... let context = {"name": "example"} let Func = function('Callback', context) - ... + "... call Func() " will echo: called for example +< The use of function() is not needed when there are no extra + arguments, these two are equivalent, if Callback() is defined + as context.Callback(): > + let Func = function('Callback', context) + let Func = context.Callback < The argument list and the Dictionary can be combined: > function Callback(arg1, count) dict - ... + "... let context = {"name": "example"} let Func = function('Callback', ['one'], context) - ... + "... call Func(500) < Invokes the function as with: > call context.Callback('one', 500) @@ -2587,7 +2607,7 @@ get({dict}, {key} [, {default}]) {default} is omitted. Useful example: > let val = get(g:, 'var_name', 'default') < This gets the value of g:var_name if it exists, and uses - 'default' when it does not exist. + "default" when it does not exist. get({func}, {what}) Get item {what} from Funcref {func}. Possible values for {what} are: @@ -2667,11 +2687,13 @@ getbufinfo([{dict}]) Can also be used as a |method|: > GetBufnr()->getbufinfo() < + *getbufline()* getbufline({buf}, {lnum} [, {end}]) Return a |List| with the lines starting from {lnum} to {end} (inclusive) in the buffer {buf}. If {end} is omitted, a - |List| with only the line {lnum} is returned. + |List| with only the line {lnum} is returned. See + `getbufoneline()` for only getting the line. For the use of {buf}, see |bufname()| above. @@ -2694,6 +2716,11 @@ getbufline({buf}, {lnum} [, {end}]) < Can also be used as a |method|: > GetBufnr()->getbufline(lnum) +< + *getbufoneline()* +getbufoneline({buf}, {lnum}) + Just like `getbufline()` but only get one line and return it + as a string. getbufvar({buf}, {varname} [, {def}]) *getbufvar()* The result is the value of option or local buffer variable @@ -2719,6 +2746,13 @@ getbufvar({buf}, {varname} [, {def}]) *getbufvar()* < Can also be used as a |method|: > GetBufnr()->getbufvar(varname) < +getcellwidths() *getcellwidths()* + Returns a |List| of cell widths of character ranges overridden + by |setcellwidths()|. The format is equal to the argument of + |setcellwidths()|. If no character ranges have their cell + widths overridden, an empty List is returned. + + getchangelist([{buf}]) *getchangelist()* Returns the |changelist| for the buffer {buf}. For the use of {buf}, see |bufname()| above. If buffer {buf} doesn't @@ -2870,7 +2904,8 @@ getcmdcompltype() *getcmdcompltype()* Only works when the command line is being edited, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=|. See |:command-completion| for the return string. - Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|. + Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. Returns an empty string when completion is not defined. getcmdline() *getcmdline()* @@ -2879,7 +2914,8 @@ getcmdline() *getcmdline()* |c_CTRL-R_=|. Example: > :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR> -< Also see |getcmdtype()|, |getcmdpos()| and |setcmdpos()|. +< Also see |getcmdtype()|, |getcmdpos()|, |setcmdpos()| and + |setcmdline()|. Returns an empty string when entering a password or using |inputsecret()|. @@ -2889,7 +2925,8 @@ getcmdpos() *getcmdpos()* Only works when editing the command line, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. Returns 0 otherwise. - Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|. + Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. getcmdscreenpos() *getcmdscreenpos()* Return the screen position of the cursor in the command line @@ -2898,7 +2935,8 @@ getcmdscreenpos() *getcmdscreenpos()* Only works when editing the command line, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. Returns 0 otherwise. - Also see |getcmdpos()|, |setcmdpos()|. + Also see |getcmdpos()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. getcmdtype() *getcmdtype()* Return the current command-line type. Possible return values @@ -2928,12 +2966,12 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* arglist file names in argument list augroup autocmd groups buffer buffer names - behave :behave suboptions + behave |:behave| suboptions + breakpoint |:breakadd| and |:breakdel| suboptions cmdline |cmdline-completion| result color color schemes command Ex command compiler compilers - cscope |:cscope| suboptions diff_buffer |:diffget| and |:diffput| completion dir directory names environment environment variable names @@ -2945,7 +2983,7 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* function function name help help subjects highlight highlight groups - history :history suboptions + history |:history| suboptions locale locale names (as output of locale -a) mapclear buffer argument mapping mapping name @@ -2953,6 +2991,7 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* messages |:messages| suboptions option options packadd optional package |pack-add| names + scriptnames sourced script names |:scriptnames| shellcmd Shell command sign |:sign| suboptions syntax syntax file names |'syntax'| @@ -2970,6 +3009,13 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* is applied to filter the results. Otherwise all the matches are returned. The 'wildignorecase' option always applies. + If the 'wildoptions' option contains "fuzzy", then fuzzy + matching is used to get the completion matches. Otherwise + regular expression matching is used. Thus this function + follows the user preference, what happens on the command line. + If you do not want this you can make 'wildoptions' empty + before calling getcompletion() and restore it afterwards. + If {type} is "cmdline", then the |cmdline-completion| result is returned. For example, to complete the possible values after a ":call" command: > @@ -2990,7 +3036,7 @@ getcurpos([{winid}]) cursor vertically. Also see |getcursorcharpos()| and |getpos()|. The first "bufnum" item is always zero. The byte position of - the cursor is returned in 'col'. To get the character + the cursor is returned in "col". To get the character position, use |getcursorcharpos()|. The optional {winid} argument can specify the window. It can @@ -3178,7 +3224,8 @@ getline({lnum} [, {end}]) < Can also be used as a |method|: > ComputeLnum()->getline() -< To get lines from another buffer see |getbufline()| +< To get lines from another buffer see |getbufline()| and + |getbufoneline()| getloclist({nr} [, {what}]) *getloclist()* Returns a |List| with all the entries in the location list for @@ -3196,7 +3243,7 @@ getloclist({nr} [, {what}]) *getloclist()* In addition to the items supported by |getqflist()| in {what}, the following item is supported by |getloclist()|: - filewinid id of the window used to display files + filewinid id of the window used to display files from the location list. This field is applicable only when called from a location list window. See @@ -3245,18 +3292,18 @@ getmatches([{win}]) *getmatches()* an empty list is returned. Example: > :echo getmatches() -< [{'group': 'MyGroup1', 'pattern': 'TODO', - 'priority': 10, 'id': 1}, {'group': 'MyGroup2', - 'pattern': 'FIXME', 'priority': 10, 'id': 2}] > +< [{"group": "MyGroup1", "pattern": "TODO", + "priority": 10, "id": 1}, {"group": "MyGroup2", + "pattern": "FIXME", "priority": 10, "id": 2}] > :let m = getmatches() :call clearmatches() :echo getmatches() < [] > :call setmatches(m) :echo getmatches() -< [{'group': 'MyGroup1', 'pattern': 'TODO', - 'priority': 10, 'id': 1}, {'group': 'MyGroup2', - 'pattern': 'FIXME', 'priority': 10, 'id': 2}] > +< [{"group": "MyGroup1", "pattern": "TODO", + "priority": 10, "id": 1}, {"group": "MyGroup2", + "pattern": "FIXME", "priority": 10, "id": 2}] > :unlet m < getmousepos() *getmousepos()* @@ -3369,7 +3416,7 @@ getqflist([{what}]) *getqflist()* |quickfix-ID|; zero means the id for the current list or the list specified by "nr" idx get information for the quickfix entry at this - index in the list specified by 'id' or 'nr'. + index in the list specified by "id" or "nr". If set to zero, then uses the current entry. See |quickfix-index| items quickfix list entries @@ -3455,7 +3502,7 @@ getreginfo([{regname}]) *getreginfo()* Dictionary with the following entries: regcontents List of lines contained in register {regname}, like - |getreg|({regname}, 1, 1). + getreg({regname}, 1, 1). regtype the type of register {regname}, as in |getregtype()|. isunnamed Boolean flag, v:true if this register @@ -3580,6 +3627,19 @@ gettagstack([{winnr}]) *gettagstack()* Can also be used as a |method|: > GetWinnr()->gettagstack() + +gettext({text}) *gettext()* + Translate String {text} if possible. + This is mainly for use in the distributed Vim scripts. When + generating message translations the {text} is extracted by + xgettext, the translator can add the translated message in the + .po file and Vim will lookup the translation when gettext() is + called. + For {text} double quoted strings are preferred, because + xgettext does not understand escaping in single quoted + strings. + + getwininfo([{winid}]) *getwininfo()* Returns information about windows as a |List| with Dictionaries. @@ -3759,15 +3819,15 @@ has({feature}) Returns 1 if {feature} is supported, 0 otherwise. The {feature} argument is a feature name like "nvim-0.2.1" or "win32", see below. See also |exists()|. - If the code has a syntax error, then Nvim may skip the rest - of the line and miss |:endif|. > - if has('feature') | let x = this->breaks->without->the->feature | endif -< - Put |:if| and |:endif| on separate lines to avoid the - syntax error. > - if has('feature') - let x = this->breaks->without->the->feature - endif + To get the system name use |vim.loop|.os_uname() in Lua: > + :lua print(vim.loop.os_uname().sysname) + +< If the code has a syntax error then Vimscript may skip the + rest of the line. Put |:if| and |:endif| on separate lines to + avoid the syntax error: > + if has('feature') + let x = this->breaks->without->the->feature + endif < Vim's compile-time feature-names (prefixed with "+") are not recognized because Nvim is always compiled with all possible @@ -4371,7 +4431,7 @@ jobstart({cmd} [, {opts}]) *jobstart()* killed when Nvim exits. If the process exits before Nvim, `on_exit` will be invoked. env: (dict) Map of environment variable name:value - pairs extending (or replacing with |clear_env|) + pairs extending (or replace with "clear_env") the current environment. |jobstart-env| height: (number) Height of the `pty` terminal. |on_exit|: (function) Callback invoked when the job exits. @@ -4495,6 +4555,16 @@ keys({dict}) *keys()* Can also be used as a |method|: > mydict->keys() +keytrans({string}) *keytrans()* + Turn the internal byte representation of keys into a form that + can be used for |:map|. E.g. > + :let xx = "\<C-Home>" + :echo keytrans(xx) +< <C-Home> + + Can also be used as a |method|: > + "\<C-Home>"->keytrans() + < *len()* *E701* len({expr}) The result is a Number, which is the length of the argument. When {expr} is a String or a Number the length in bytes is @@ -4903,7 +4973,7 @@ match({expr}, {pat} [, {start} [, {count}]]) *match()* If {start} is out of range ({start} > strlen({expr}) for a String or {start} > len({expr}) for a |List|) -1 is returned. - When {count} is given use the {count}'th match. When a match + When {count} is given use the {count}th match. When a match is found in a String the search for the next one starts one character further. Thus this example results in 1: > echo match("testing", "..", 0, 2) @@ -4955,7 +5025,7 @@ matchadd({group}, {pattern} [, {priority} [, {id} [, {dict}]]]) respectively. 3 is reserved for use by the |matchparen| plugin. If the {id} argument is not specified or -1, |matchadd()| - automatically chooses a free ID. + automatically chooses a free ID, which is at least 1000. The optional {dict} argument allows for further custom values. Currently this is used to specify a match specific @@ -4963,7 +5033,7 @@ matchadd({group}, {pattern} [, {priority} [, {id} [, {dict}]]]) highlighted matches. The dict can have the following members: conceal Special character to show instead of the - match (only for |hl-Conceal| highlighed + match (only for |hl-Conceal| highlighted matches, see |:syn-cchar|) window Instead of the current window use the window with this number or window ID. @@ -5013,8 +5083,6 @@ matchaddpos({group}, {pos} [, {priority} [, {id} [, {dict}]]]) ignored, as well as entries with negative column numbers and lengths. - The maximum number of positions in {pos} is 8. - Returns -1 on error. Example: > @@ -5135,7 +5203,7 @@ matchfuzzy({list}, {str} [, {dict}]) *matchfuzzy()* :let l = readfile("buffer.c")->matchfuzzy("str") < results in a list of lines in "buffer.c" fuzzy matching "str". > :echo ['one two', 'two one']->matchfuzzy('two one') -< results in ['two one', 'one two']. > +< results in `['two one', 'one two']` . > :echo ['one two', 'two one']->matchfuzzy('two one', \ {'matchseq': 1}) < results in ['two one']. @@ -5155,12 +5223,12 @@ matchfuzzypos({list}, {str} [, {dict}]) *matchfuzzypos()* Example: > :echo matchfuzzypos(['testing'], 'tsg') -< results in [['testing'], [[0, 2, 6]], [99]] > +< results in [["testing"], [[0, 2, 6]], [99]] > :echo matchfuzzypos(['clay', 'lacy'], 'la') -< results in [['lacy', 'clay'], [[0, 1], [1, 2]], [153, 133]] > +< results in [["lacy", "clay"], [[0, 1], [1, 2]], [153, 133]] > :echo [{'text': 'hello', 'id' : 10}] \ ->matchfuzzypos('ll', {'key' : 'text'}) -< results in [[{'id': 10, 'text': 'hello'}], [[2, 3]], [127]] +< results in [[{"id": 10, "text": "hello"}], [[2, 3]], [127]] matchlist({expr}, {pat} [, {start} [, {count}]]) *matchlist()* Same as |match()|, but return a |List|. The first item in the @@ -5580,12 +5648,19 @@ nvim_...({...}) *E5555* *nvim_...()* *eval-api* or({expr}, {expr}) *or()* Bitwise OR on the two arguments. The arguments are converted to a number. A List, Dict or Float argument causes an error. + Also see `and()` and `xor()`. Example: > :let bits = or(bits, 0x80) < Can also be used as a |method|: > :let bits = bits->or(0x80) -pathshorten({expr} [, {len}]) *pathshorten()* +< Rationale: The reason this is a function and not using the "|" + character like many languages, is that Vi has always used "|" + to separate commands. In many places it would not be clear if + "|" is an operator or a command separator. + + +pathshorten({path} [, {len}]) *pathshorten()* Shorten directory names in the path {path} and return the result. The tail, the file name, is kept as-is. The other components in the path are reduced to {len} letters in length. @@ -6005,9 +6080,19 @@ rand([{expr}]) *rand()* Can also be used as a |method|: > seed->rand() < + +readblob({fname}) *readblob()* + Read file {fname} in binary mode and return a |Blob|. + When the file can't be opened an error message is given and + the result is an empty |Blob|. + Also see |readfile()| and |writefile()|. + + *readdir()* readdir({directory} [, {expr}]) Return a list with file and directory names in {directory}. + You can also use |glob()| if you don't need to do complicated + things, such as limiting the number of matches. When {expr} is omitted all entries are included. When {expr} is given, it is evaluated to check what to do: @@ -6037,6 +6122,7 @@ readdir({directory} [, {expr}]) Can also be used as a |method|: > GetDirName()->readdir() < + *readfile()* readfile({fname} [, {type} [, {max}]]) Read file {fname} and return a |List|, each line of the file @@ -6048,8 +6134,6 @@ readfile({fname} [, {type} [, {max}]]) - When the last line ends in a NL an extra empty list item is added. - No CR characters are removed. - When {type} contains "B" a |Blob| is returned with the binary - data of the file unmodified. Otherwise: - CR characters that appear before a NL are removed. - Whether the last line ends in a NL or not does not matter. @@ -6066,6 +6150,9 @@ readfile({fname} [, {type} [, {max}]]) Note that without {max} the whole file is read into memory. Also note that there is no recognition of encoding. Read a file into a buffer if you need to. + Deprecated (use |readblob()| instead): When {type} contains + "B" a |Blob| is returned with the binary data of the file + unmodified. When the file can't be opened an error message is given and the result is an empty list. Also see |writefile()|. @@ -6106,7 +6193,9 @@ reg_recording() *reg_recording()* Returns the single letter name of the register being recorded. Returns an empty string when not recording. See |q|. -reltime([{start} [, {end}]]) *reltime()* +reltime() +reltime({start}) +reltime({start}, {end}) *reltime()* Return an item that represents a time value. The item is a list with items that depend on the system. The item can be passed to |reltimestr()| to convert it to a @@ -6160,7 +6249,8 @@ reltimestr({time}) *reltimestr()* Can also be used as a |method|: > reltime(start)->reltimestr() < -remove({list}, {idx} [, {end}]) *remove()* +remove({list}, {idx}) +remove({list}, {idx}, {end}) *remove()* Without {end}: Remove the item at {idx} from |List| {list} and return the item. With {end}: Remove items from {idx} to {end} (inclusive) and @@ -6178,7 +6268,8 @@ remove({list}, {idx} [, {end}]) *remove()* Can also be used as a |method|: > mylist->remove(idx) -remove({blob}, {idx} [, {end}]) +remove({blob}, {idx}) +remove({blob}, {idx}, {end}) Without {end}: Remove the byte at {idx} from |Blob| {blob} and return the byte. With {end}: Remove bytes from {idx} to {end} (inclusive) and @@ -6417,8 +6508,10 @@ search({pattern} [, {flags} [, {stopline} [, {timeout} [, {skip}]]]]) starts in column zero and then matches before the cursor are skipped. When the 'c' flag is present in 'cpo' the next search starts after the match. Without the 'c' flag the next - search starts one column further. This matters for - overlapping matches. + search starts one column after the start of the match. This + matters for overlapping matches. See |cpo-c|. You can also + insert "\ze" to change where the match ends, see |/\ze|. + When searching backwards and the 'z' flag is given then the search starts in column zero, thus no match in the current line will be found (unless wrapping around the end of the @@ -6607,7 +6700,7 @@ searchcount([{options}]) *searchcount()* pos |List| `[lnum, col, off]` value when recomputing the result. this changes "current" result - value. see |cursor()|, |getpos() + value. see |cursor()|, |getpos()| (default: cursor's position) Can also be used as a |method|: > @@ -6763,18 +6856,24 @@ serverstart([{address}]) *serverstart()* |RPC| messages. Clients can send |API| commands to the returned address to control Nvim. - Returns the address string (may differ from the requested - {address}). - - - If {address} contains a colon ":" it is interpreted as - a TCP/IPv4/IPv6 address where the last ":" separates host - and port (empty or zero assigns a random port). - - Else it is interpreted as a named pipe or Unix domain socket - path. If there are no slashes it is treated as a name and - appended to a generated path. - - If {address} is empty it generates a path. - - Example named pipe: > + Returns the address string (which may differ from the + {address} argument, see below). + + - If {address} has a colon (":") it is a TCP/IPv4/IPv6 address + where the last ":" separates host and port (empty or zero + assigns a random port). + - Else {address} is the path to a named pipe (except on Windows). + - If {address} has no slashes ("/") it is treated as the + "name" part of a generated path in this format: > + stdpath("run").."/{name}.{pid}.{counter}" +< - If {address} is omitted the name is "nvim". > + :echo serverstart() + => /tmp/nvim.bram/oknANW/nvim.15430.5 + +< Example bash command to list all Nvim servers: > + ls ${XDG_RUNTIME_DIR:-${TMPDIR}nvim.${USER}}/*/nvim.*.0 + +< Example named pipe: > if has('win32') echo serverstart('\\.\pipe\nvim-pipe-1234') else @@ -6839,29 +6938,38 @@ setbufvar({buf}, {varname}, {val}) *setbufvar()* setcellwidths({list}) *setcellwidths()* Specify overrides for cell widths of character ranges. This - tells Vim how wide characters are, counted in screen cells. - This overrides 'ambiwidth'. Example: > - setcellwidths([[0xad, 0xad, 1], - \ [0x2194, 0x2199, 2]]) - -< *E1109* *E1110* *E1111* *E1112* *E1113* *E1114* - The {list} argument is a list of lists with each three - numbers. These three numbers are [low, high, width]. "low" - and "high" can be the same, in which case this refers to one - character. Otherwise it is the range of characters from "low" - to "high" (inclusive). "width" is either 1 or 2, indicating - the character width in screen cells. + tells Vim how wide characters are when displayed in the + terminal, counted in screen cells. The values override + 'ambiwidth'. Example: > + call setcellwidths([ + \ [0x111, 0x111, 1], + \ [0x2194, 0x2199, 2], + \ ]) + +< The {list} argument is a List of Lists with each three + numbers: [{low}, {high}, {width}]. *E1109* *E1110* + {low} and {high} can be the same, in which case this refers to + one character. Otherwise it is the range of characters from + {low} to {high} (inclusive). *E1111* *E1114* + Only characters with value 0x80 and higher can be used. + + {width} must be either 1 or 2, indicating the character width + in screen cells. *E1112* An error is given if the argument is invalid, also when a - range overlaps with another. - Only characters with value 0x100 and higher can be used. + range overlaps with another. *E1113* If the new value causes 'fillchars' or 'listchars' to become invalid it is rejected and an error is given. - To clear the overrides pass an empty list: > - setcellwidths([]); + To clear the overrides pass an empty {list}: > + call setcellwidths([]) + < You can use the script $VIMRUNTIME/tools/emoji_list.vim to see - the effect for known emoji characters. + the effect for known emoji characters. Move the cursor + through the text to check if the cell widths of your terminal + match with what Vim knows about each emoji. If it doesn't + look right you need to adjust the {list} argument. + setcharpos({expr}, {list}) *setcharpos()* Same as |setpos()| but uses the specified column number as the @@ -6900,6 +7008,16 @@ setcharsearch({dict}) *setcharsearch()* Can also be used as a |method|: > SavedSearch()->setcharsearch() +setcmdline({str} [, {pos}]) *setcmdline()* + Set the command line to {str} and set the cursor position to + {pos}. + If {pos} is omitted, the cursor is positioned after the text. + Returns 0 when successful, 1 when not editing the command + line. + + Can also be used as a |method|: > + GetText()->setcmdline() + setcmdpos({pos}) *setcmdpos()* Set the cursor position in the command line to byte position {pos}. The first position is 1. @@ -6912,8 +7030,8 @@ setcmdpos({pos}) *setcmdpos()* before inserting the resulting text. When the number is too big the cursor is put at the end of the line. A number smaller than one has undefined results. - Returns FALSE when successful, TRUE when not editing the - command line. + Returns 0 when successful, 1 when not editing the command + line. Can also be used as a |method|: > GetPos()->setcmdpos() @@ -6972,6 +7090,8 @@ setline({lnum}, {text}) *setline()* {lnum} is used like with |getline()|. When {lnum} is just below the last line the {text} will be added below the last line. + {text} can be any type or a List of any type, each item is + converted to a String. If this succeeds, FALSE is returned. If this fails (most likely because {lnum} is invalid) TRUE is returned. @@ -7014,8 +7134,8 @@ setloclist({nr}, {list} [, {action} [, {what}]]) *setloclist()* GetLoclist()->setloclist(winnr) setmatches({list} [, {win}]) *setmatches()* - Restores a list of matches saved by |getmatches() for the - current window|. Returns 0 if successful, otherwise -1. All + Restores a list of matches saved by |getmatches()| for the + current window. Returns 0 if successful, otherwise -1. All current matches are cleared before the list is restored. See example for |getmatches()|. If {win} is specified, use the window with this number or @@ -7150,7 +7270,7 @@ setqflist({list} [, {action} [, {what}]]) *setqflist()* See |quickfix-parse| id quickfix list identifier |quickfix-ID| idx index of the current entry in the quickfix - list specified by 'id' or 'nr'. If set to '$', + list specified by "id" or "nr". If set to '$', then the last entry in the list is set as the current entry. See |quickfix-index| items list of quickfix entries. Same as the {list} @@ -7195,6 +7315,7 @@ setqflist({list} [, {action} [, {what}]]) *setqflist()* *setreg()* setreg({regname}, {value} [, {options}]) Set the register {regname} to {value}. + If {regname} is "" or "@", the unnamed register '"' is used. The {regname} argument is a string. {value} may be any value returned by |getreg()| or @@ -7642,7 +7763,7 @@ sqrt({expr}) *sqrt()* :echo sqrt(100) < 10.0 > :echo sqrt(-4.01) -< str2float('nan') +< str2float("nan") NaN may be different, it depends on system libraries. Can also be used as a |method|: > @@ -7697,14 +7818,13 @@ stdpath({what}) *stdpath()* *E6100* config String User configuration directory. |init.vim| is stored here. config_dirs List Other configuration directories. - data String User data directory. The |shada-file| - is stored here. + data String User data directory. data_dirs List Other data directories. log String Logs directory (for use by plugins too). run String Run directory: temporary, local storage for sockets, named pipes, etc. state String Session state directory: storage for file - drafts, undo, shada, etc. + drafts, swap, undo, |shada|. Example: > :echo stdpath("config") @@ -7769,6 +7889,21 @@ str2nr({string} [, {base}]) *str2nr()* Can also be used as a |method|: > GetText()->str2nr() + +strcharlen({string}) *strcharlen()* + The result is a Number, which is the number of characters + in String {string}. Composing characters are ignored. + |strchars()| can count the number of characters, counting + composing characters separately. + + Returns 0 if {string} is empty or on error. + + Also see |strlen()|, |strdisplaywidth()| and |strwidth()|. + + Can also be used as a |method|: > + GetText()->strcharlen() + + strcharpart({src}, {start} [, {len}]) *strcharpart()* Like |strpart()| but using character index and length instead of byte index and length. Composing characters are counted @@ -7783,12 +7918,14 @@ strcharpart({src}, {start} [, {len}]) *strcharpart()* Can also be used as a |method|: > GetText()->strcharpart(5) + strchars({string} [, {skipcc}]) *strchars()* The result is a Number, which is the number of characters in String {string}. When {skipcc} is omitted or zero, composing characters are counted separately. When {skipcc} set to 1, Composing characters are ignored. + |strcharlen()| always does this. Returns zero on error. @@ -7883,7 +8020,7 @@ stridx({haystack}, {needle} [, {start}]) *stridx()* Can also be used as a |method|: > GetHaystack()->stridx(needle) - +< *string()* string({expr}) Return {expr} converted to a String. If {expr} is a Number, Float, String, Blob or a composition of them, then the result @@ -8027,7 +8164,7 @@ strwidth({string}) *strwidth()* submatch({nr} [, {list}]) *submatch()* *E935* Only for an expression in a |:substitute| command or substitute() function. - Returns the {nr}'th submatch of the matched text. When {nr} + Returns the {nr}th submatch of the matched text. When {nr} is 0 the whole matched text is returned. Note that a NL in the string can stand for a line break of a multi-line match or a NUL character in the text. @@ -8175,7 +8312,7 @@ synIDattr({synID}, {what} [, {mode}]) *synIDattr()* "bg" background color (as with "fg") "font" font name (only available in the GUI) |highlight-font| - "sp" special color (as with "fg") |highlight-guisp| + "sp" special color (as with "fg") |guisp| "fg#" like "fg", but for the GUI and the GUI is running the name in "#RRGGBB" form "bg#" like "fg#" for "bg" @@ -8191,6 +8328,7 @@ synIDattr({synID}, {what} [, {mode}]) *synIDattr()* "underdotted" "1" if dotted underlined "underdashed" "1" if dashed underlined "strikethrough" "1" if struckthrough + "altfont" "1" if alternative font "nocombine" "1" if nocombine Returns an empty string on error. @@ -8231,12 +8369,12 @@ synconcealed({lnum}, {col}) *synconcealed()* the text is "123456" and both "23" and "45" are concealed and replaced by the character "X", then: call returns ~ - synconcealed(lnum, 1) [0, '', 0] - synconcealed(lnum, 2) [1, 'X', 1] - synconcealed(lnum, 3) [1, 'X', 1] - synconcealed(lnum, 4) [1, 'X', 2] - synconcealed(lnum, 5) [1, 'X', 2] - synconcealed(lnum, 6) [0, '', 0] + synconcealed(lnum, 1) [0, '', 0] + synconcealed(lnum, 2) [1, 'X', 1] + synconcealed(lnum, 3) [1, 'X', 1] + synconcealed(lnum, 4) [1, 'X', 2] + synconcealed(lnum, 5) [1, 'X', 2] + synconcealed(lnum, 6) [0, '', 0] synstack({lnum}, {col}) *synstack()* @@ -8780,6 +8918,26 @@ virtcol({expr}) *virtcol()* < Can also be used as a |method|: > GetPos()->virtcol() +virtcol2col({winid}, {lnum}, {col}) *virtcol2col()* + The result is a Number, which is the byte index of the + character in window {winid} at buffer line {lnum} and virtual + column {col}. + + If {col} is greater than the last virtual column in line + {lnum}, then the byte index of the character at the last + virtual column is returned. + + The {winid} argument can be the window number or the + |window-ID|. If this is zero, then the current window is used. + + Returns -1 if the window {winid} doesn't exist or the buffer + line {lnum} or virtual column {col} is invalid. + + See also |screenpos()|, |virtcol()| and |col()|. + + Can also be used as a |method|: > + GetWinid()->virtcol2col(lnum, col) + visualmode([{expr}]) *visualmode()* The result is a String, which describes the last Visual mode used in the current buffer. Initially it returns an empty @@ -8833,7 +8991,12 @@ win_execute({id}, {command} [, {silent}]) *win_execute()* have unexpected side effects. Use |:noautocmd| if needed. Example: > call win_execute(winid, 'syntax enable') -< +< Doing the same with `setwinvar()` would not trigger + autocommands and not actually show syntax highlighting. + + When window {id} does not exist then no error is given and + an empty string is returned. + Can also be used as a |method|, the base is passed as the second argument: > GetCommand()->win_execute(winid) @@ -8914,6 +9077,7 @@ win_move_separator({nr}, {offset}) *win_move_separator()* FALSE otherwise. This will fail for the rightmost window and a full-width window, since it has no separator on the right. + Only works for the current tab page. *E1308* Can also be used as a |method|: > GetWinnr()->win_move_separator(offset) @@ -8928,6 +9092,7 @@ win_move_statusline({nr}, {offset}) *win_move_statusline()* movement may be smaller than specified (e.g., as a consequence of maintaining 'winminheight'). Returns TRUE if the window can be found and FALSE otherwise. + Only works for the current tab page. Can also be used as a |method|: > GetWinnr()->win_move_statusline(offset) @@ -9014,12 +9179,12 @@ winlayout([{tabnr}]) *winlayout()* returns an empty list. For a leaf window, it returns: - ['leaf', {winid}] + ["leaf", {winid}] For horizontally split windows, which form a column, it returns: - ['col', [{nested list of windows}]] + ["col", [{nested list of windows}]] For vertically split windows, which form a row, it returns: - ['row', [{nested list of windows}]] + ["row", [{nested list of windows}]] Example: > " Only one window in the tab page @@ -9211,6 +9376,7 @@ writefile({object}, {fname} [, {flags}]) xor({expr}, {expr}) *xor()* Bitwise XOR on the two arguments. The arguments are converted to a number. A List, Dict or Float argument causes an error. + Also see `and()` and `or()`. Example: > :let bits = xor(bits, 0x80) < diff --git a/runtime/doc/change.txt b/runtime/doc/change.txt index a4ff4474e6..990ba3d8fd 100644 --- a/runtime/doc/change.txt +++ b/runtime/doc/change.txt @@ -204,7 +204,6 @@ gR Enter Virtual Replace mode: Each character you type *v_S* {Visual}["x]S Delete the highlighted lines [into register x] and start insert (for {Visual} see |Visual-mode|). - *v_R* {Visual}["x]R Currently just like {Visual}["x]S. In a next version it might work differently. @@ -441,13 +440,13 @@ steps to make a numbered list. SHIFTING LINES LEFT OR RIGHT *shift-left-right* *<* -<{motion} Shift {motion} lines one 'shiftwidth' leftwards. + <{motion} Shift {motion} lines one 'shiftwidth' leftwards. If the 'shiftwidth' option is set to zero, the amount of indent is calculated at the first non-blank character in the line. *<<* -<< Shift [count] lines one 'shiftwidth' leftwards. + << Shift [count] lines one 'shiftwidth' leftwards. *v_<* {Visual}[count]< Shift the highlighted lines [count] 'shiftwidth' @@ -1130,11 +1129,20 @@ used. If you do need it you can use |p| with another register. E.g., yank the text to copy, Visually select the text to replace and use "0p . You can repeat this as many times as you like, and the unnamed register will be changed each time. - -When you use a blockwise Visual mode command and yank only a single line into -a register, a paste on a visual selected area will paste that single line on -each of the selected lines (thus replacing the blockwise selected region by a -block of the pasted line). + *blockwise-put* +When a register contains text from one line (characterwise), using a +blockwise Visual selection, putting that register will paste that text +repeatedly in each of the selected lines, thus replacing the blockwise +selected region by multiple copies of the register text. For example: + - yank the word "TEXT" into a register with `yw` + - select a visual block, marked with "v" in this text: + aaavvaaa + bbbvvbbb + cccvvccc + - press `p`, results in: + aaaTEXTaaa + bbbTEXTbbb + cccTEXTccc *blockwise-register* If you use a blockwise Visual mode command to get the text into the register, diff --git a/runtime/doc/channel.txt b/runtime/doc/channel.txt index d4bed7a5f2..1c52b2d692 100644 --- a/runtime/doc/channel.txt +++ b/runtime/doc/channel.txt @@ -48,21 +48,22 @@ a job channel using RPC, bytes can still be read over its stderr. Similarly, only bytes can be written to Nvim's own stderr. *channel-callback* -on_stdout({chan-id}, {data}, {name}) *on_stdout* -on_stderr({chan-id}, {data}, {name}) *on_stderr* -on_stdin({chan-id}, {data}, {name}) *on_stdin* -on_data({chan-id}, {data}, {name}) *on_data* +- on_stdout({chan-id}, {data}, {name}) *on_stdout* +- on_stderr({chan-id}, {data}, {name}) *on_stderr* +- on_stdin({chan-id}, {data}, {name}) *on_stdin* +- on_data({chan-id}, {data}, {name}) *on_data* + Scripts can react to channel activity (received data) via callback functions assigned to the `on_stdout`, `on_stderr`, `on_stdin`, or `on_data` option keys. Callbacks should be fast: avoid potentially slow/expensive work. Parameters: ~ - {chan-id} Channel handle. |channel-id| - {data} Raw data (|readfile()|-style list of strings) read from + - {chan-id} Channel handle. |channel-id| + - {data} Raw data (|readfile()|-style list of strings) read from the channel. EOF is a single-item list: `['']`. First and last items may be partial lines! |channel-lines| - {name} Stream name (string) like "stdout", so the same function + - {name} Stream name (string) like "stdout", so the same function can handle multiple streams. Event names depend on how the channel was opened and in what mode/protocol. @@ -83,13 +84,14 @@ on_data({chan-id}, {data}, {name}) *on_data* the final `['']` emitted at EOF): - `foobar` may arrive as `['fo'], ['obar']` - `foo\nbar` may arrive as - `['foo','bar']` - or `['foo',''], ['bar']` - or `['foo'], ['','bar']` - or `['fo'], ['o','bar']` + - `['foo','bar']` + - or `['foo',''], ['bar']` + - or `['foo'], ['','bar']` + - or `['fo'], ['o','bar']` + There are two ways to deal with this: - 1. To wait for the entire output, use |channel-buffered| mode. - 2. To read line-by-line, use the following code: > + - 1. To wait for the entire output, use |channel-buffered| mode. + - 2. To read line-by-line, use the following code: >vim let s:lines = [''] func! s:on_event(job_id, data, event) dict let eof = (a:data == ['']) @@ -106,7 +108,7 @@ callbacks. Data can be sent to the channel using the |chansend()| function. Here is a simple example, echoing some data through a cat-process: -> +>vim function! s:OnEvent(id, data, event) dict let str = join(a:data, "\n") echomsg str @@ -117,7 +119,7 @@ simple example, echoing some data through a cat-process: Here is a example of setting a buffer to the result of grep, but only after all data has been processed: -> +>vim function! s:OnEvent(id, data, event) dict call nvim_buf_set_lines(2, 0, -1, v:true, a:data) endfunction @@ -140,7 +142,7 @@ However, change of PTY size can be signaled to the slave using |jobresize()|. See also |terminal-emulator|. Terminal characteristics (termios) for |:terminal| and PTY channels are copied -from the host TTY, or if Nvim is |--headless| it uses default values: > +from the host TTY, or if Nvim is |--headless| it uses default values: >vim :echo system('nvim --headless +"te stty -a" +"sleep 1" +"1,/^$/print" +q') ============================================================================== @@ -161,7 +163,7 @@ used as a channel. See also |--embed|. Call |stdioopen()| during |startup| to open the stdio channel as |channel-id| 1. Nvim's stderr is always available as |v:stderr|, a write-only bytes channel. -Example: > +Example: >vim func! OnEvent(id, data, event) if a:data == [""] quit @@ -170,7 +172,7 @@ Example: > endfunc call stdioopen({'on_stdin': 'OnEvent'}) < -Put this in `uppercase.vim` and run: > +Put this in `uppercase.vim` and run: >bash nvim --headless --cmd "source uppercase.vim" ============================================================================== @@ -221,7 +223,7 @@ start of the line. Here is an example for Unix. It starts a shell in the background and prompts for the next shell command. Output from the shell is displayed above the -prompt. > +prompt. >vim " Function handling a line of text that has been typed. func TextEntered(text) diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt index 29eff75bfa..b4923b0d70 100644 --- a/runtime/doc/cmdline.txt +++ b/runtime/doc/cmdline.txt @@ -524,7 +524,6 @@ that see the '"' as part of their argument: :cexpr (and the like) :cdo (and the like) :command - :cscope (and the like) :debug :display :echo (and the like) @@ -566,7 +565,6 @@ followed by another Vim command: :cdo :cfdo :command - :cscope :debug :eval :folddoopen @@ -575,7 +573,6 @@ followed by another Vim command: :global :help :helpgrep - :lcscope :ldo :lfdo :lhelpgrep @@ -586,7 +583,6 @@ followed by another Vim command: :python :registers :read ! - :scscope :sign :terminal :vglobal @@ -694,7 +690,9 @@ Line numbers may be specified with: *:range* *{address}* 'T position of mark T (uppercase); when the mark is in another file it cannot be used in a range /{pattern}[/] the next line where {pattern} matches *:/* + also see |:range-pattern| below ?{pattern}[?] the previous line where {pattern} matches *:?* + also see |:range-pattern| below \/ the next line where the previously used search pattern matches \? the previous line where the previously used search @@ -702,11 +700,49 @@ Line numbers may be specified with: *:range* *{address}* \& the next line where the previously used substitute pattern matches + *:range-offset* Each may be followed (several times) by '+' or '-' and an optional number. This number is added or subtracted from the preceding line number. If the number is omitted, 1 is used. If there is nothing before the '+' or '-' then the current line is used. - + *:range-closed-fold* +When a line number after the comma is in a closed fold it is adjusted to the +last line of the fold, thus the whole fold is included. + +When a number is added this is done after the adjustment to the last line of +the fold. This means these lines are additionally included in the range. For +example: > + :3,4+2print +On this text: + 1 one ~ + 2 two ~ + 3 three ~ + 4 four FOLDED ~ + 5 five FOLDED ~ + 6 six ~ + 7 seven ~ + 8 eight ~ +Where lines four and five are a closed fold, ends up printing lines 3 to 7. +The 7 comes from the "4" in the range, which is adjusted to the end of the +closed fold, which is 5, and then the offset 2 is added. + +An example for subtracting (which isn't very useful): > + :2,4-1print +On this text: + 1 one ~ + 2 two ~ + 3 three FOLDED~ + 4 four FOLDED ~ + 5 five FOLDED ~ + 6 six FOLDED ~ + 7 seven ~ + 8 eight ~ +Where lines three to six are a closed fold, ends up printing lines 2 to 6. +The 6 comes from the "4" in the range, which is adjusted to the end of the +closed fold, which is 6, and then 1 is subtracted, then this is still in the +closed fold and the last line of that fold is used, which is 6. + + *:range-pattern* The "/" and "?" after {pattern} are required to separate the pattern from anything that follows. @@ -762,9 +798,9 @@ always be swapped then. Count and Range *N:* -When giving a count before entering ":", this is translated into: +When giving a count before entering ":", this is translated into: > :.,.+(count - 1) -In words: The 'count' lines at and after the cursor. Example: To delete +In words: The "count" lines at and after the cursor. Example: To delete three lines: > 3:d<CR> is translated into: .,.+2d<CR> < @@ -881,7 +917,7 @@ Note: these are typed literally, they are not special keys! file name of the sourced file. *E498* When executing a function, is replaced with the call stack, as with <stack> (this is for backwards compatibility, using - <stack> is preferred). + <stack> or <script> is preferred). Note that filename-modifiers are useless when <sfile> is not used inside a script. *:<stack>* *<stack>* @@ -891,6 +927,12 @@ Note: these are typed literally, they are not special keys! ".." in between items. E.g.: "function {function-name1}[{lnum}]..{function-name2}[{lnum}]" If there is no call stack you get error *E489* . + *:<script>* *<script>* + <script> When executing a `:source` command, is replaced with the file + name of the sourced file. When executing a function, is + replaced with the file name of the script where it is + defined. + If the file name cannot be determined you get error *E1274* . *:<slnum>* *<slnum>* <slnum> When executing a `:source` command, is replaced with the line number. *E842* diff --git a/runtime/doc/deprecated.txt b/runtime/doc/deprecated.txt index eb6d9b6dc9..1bdd13ac0c 100644 --- a/runtime/doc/deprecated.txt +++ b/runtime/doc/deprecated.txt @@ -10,150 +10,144 @@ The items listed below are deprecated: they will be removed in the future. They should not be used in new scripts, and old scripts should be updated. ============================================================================== - -API ~ -*nvim_buf_clear_highlight()* Use |nvim_buf_clear_namespace()| instead. -*nvim_buf_set_virtual_text()* Use |nvim_buf_set_extmark()| instead. -*nvim_command_output()* Use |nvim_exec()| instead. -*nvim_execute_lua()* Use |nvim_exec_lua()| instead. - -Commands ~ -*:rv* -*:rviminfo* Deprecated alias to |:rshada| command. -*:wv* -*:wviminfo* Deprecated alias to |:wshada| command. - -Environment Variables ~ -*$NVIM_LISTEN_ADDRESS* Deprecated way to - * set the server name (use |--listen| instead) - * get the server name (use |v:servername| instead) - * detect a parent Nvim (use |$NVIM| instead) - Unset by |terminal| and |jobstart()| (unless explicitly - given by the "env" option). Ignored if --listen is given. - -Events ~ -*BufCreate* Use |BufAdd| instead. -*EncodingChanged* Never fired; 'encoding' is always "utf-8". -*FileEncoding* Never fired; equivalent to |EncodingChanged|. -*GUIEnter* Never fired; use |UIEnter| instead. -*GUIFailed* Never fired. - -Keycodes ~ -*<MouseDown>* Use <ScrollWheelUp> instead. -*<MouseUp>* Use <ScrollWheelDown> instead. - -Functions ~ -*buffer_exists()* Obsolete name for |bufexists()|. -*buffer_name()* Obsolete name for |bufname()|. -*buffer_number()* Obsolete name for |bufnr()|. -*file_readable()* Obsolete name for |filereadable()|. -*highlight_exists()* Obsolete name for |hlexists()|. -*highlightID()* Obsolete name for |hlID()|. -*inputdialog()* Use |input()| instead. -*jobclose()* Obsolete name for |chanclose()| -*jobsend()* Obsolete name for |chansend()| -*last_buffer_nr()* Obsolete name for bufnr("$"). -*rpcstop()* Deprecated. Instead use |jobstop()| to stop any job, - or chanclose(id, "rpc") to close RPC communication +Deprecated features + +API +- *nvim_buf_clear_highlight()* Use |nvim_buf_clear_namespace()| instead. +- *nvim_buf_set_virtual_text()* Use |nvim_buf_set_extmark()| instead. +- *nvim_command_output()* Use |nvim_exec()| instead. +- *nvim_execute_lua()* Use |nvim_exec_lua()| instead. + +COMMANDS +- *:rv* *:rviminfo* Deprecated alias to |:rshada| command. +- *:wv* *:wviminfo* Deprecated alias to |:wshada| command. + +ENVIRONMENT VARIABLES +- *$NVIM_LISTEN_ADDRESS* + - Deprecated way to: + - set the server name (use |--listen| or |serverstart()| instead) + - get the server name (use |v:servername| instead) + - detect a parent Nvim (use |$NVIM| instead) + - Ignored if --listen is given. + - Unset by |terminal| and |jobstart()| unless explicitly given by the "env" + option. Example: >vim + call jobstart(['foo'], { 'env': { 'NVIM_LISTEN_ADDRESS': v:servername } }) +< + +EVENTS +- *BufCreate* Use |BufAdd| instead. +- *EncodingChanged* Never fired; 'encoding' is always "utf-8". +- *FileEncoding* Never fired; equivalent to |EncodingChanged|. +- *GUIEnter* Never fired; use |UIEnter| instead. +- *GUIFailed* Never fired. + +KEYCODES +- *<MouseDown>* Use <ScrollWheelUp> instead. +- *<MouseUp>* Use <ScrollWheelDown> instead. + +FUNCTIONS +- *buffer_exists()* Obsolete name for |bufexists()|. +- *buffer_name()* Obsolete name for |bufname()|. +- *buffer_number()* Obsolete name for |bufnr()|. +- *file_readable()* Obsolete name for |filereadable()|. +- *health#report_error* Use Lua |vim.health.report_error()| instead. +- *health#report_info* Use Lua |vim.health.report_info()| instead. +- *health#report_ok* Use Lua |vim.health.report_ok()| instead. +- *health#report_start* Use Lua |vim.health.report_start()| instead. +- *health#report_warn* Use Lua |vim.health.report_warn()| instead. +- *highlight_exists()* Obsolete name for |hlexists()|. +- *highlightID()* Obsolete name for |hlID()|. +- *inputdialog()* Use |input()| instead. +- *jobclose()* Obsolete name for |chanclose()| +- *jobsend()* Obsolete name for |chansend()| +- *last_buffer_nr()* Obsolete name for bufnr("$"). +- *rpcstop()* Use |jobstop()| instead to stop any job, or + `chanclose(id, "rpc")` to close RPC communication without stopping the job. Use chanclose(id) to close any socket. -Highlights ~ - -*hl-VertSplit* Use |hl-WinSeparator| instead. - -LSP Diagnostics ~ +HIGHLIGHTS +- *hl-VertSplit* Use |hl-WinSeparator| instead. +LSP DIAGNOSTICS For each of the functions below, use the corresponding function in |vim.diagnostic| instead (unless otherwise noted). For example, use |vim.diagnostic.get()| instead of |vim.lsp.diagnostic.get()|. -*vim.lsp.diagnostic.clear()* Use |vim.diagnostic.hide()| instead. -*vim.lsp.diagnostic.disable()* -*vim.lsp.diagnostic.display()* Use |vim.diagnostic.show()| instead. -*vim.lsp.diagnostic.enable()* -*vim.lsp.diagnostic.get()* -*vim.lsp.diagnostic.get_all()* Use |vim.diagnostic.get()| instead. -*vim.lsp.diagnostic.get_count()* Use |vim.diagnostic.get()| instead. -*vim.lsp.diagnostic.get_line_diagnostics()* - Use |vim.diagnostic.get()| instead. -*vim.lsp.diagnostic.get_next()* -*vim.lsp.diagnostic.get_next_pos()* -*vim.lsp.diagnostic.get_prev()* -*vim.lsp.diagnostic.get_prev_pos()* -*vim.lsp.diagnostic.get_virtual_text_chunks_for_line()* - No replacement. Use options provided by - |vim.diagnostic.config()| to customize - virtual text. -*vim.lsp.diagnostic.goto_next()* -*vim.lsp.diagnostic.goto_prev()* -*vim.lsp.diagnostic.redraw()* Use |vim.diagnostic.show()| instead. -*vim.lsp.diagnostic.reset()* -*vim.lsp.diagnostic.save()* Use |vim.diagnostic.set()| instead. -*vim.lsp.diagnostic.set_loclist()* Use |vim.diagnostic.setloclist()| instead. -*vim.lsp.diagnostic.set_qflist()* Use |vim.diagnostic.setqflist()| instead. - -The following have been replaced by |vim.diagnostic.open_float()|. - -*vim.lsp.diagnostic.show_line_diagnostics()* -*vim.lsp.diagnostic.show_position_diagnostics()* +- *vim.lsp.diagnostic.clear()* Use |vim.diagnostic.hide()| instead. +- *vim.lsp.diagnostic.disable()* +- *vim.lsp.diagnostic.display()* Use |vim.diagnostic.show()| instead. +- *vim.lsp.diagnostic.enable()* +- *vim.lsp.diagnostic.get()* +- *vim.lsp.diagnostic.get_all()* Use |vim.diagnostic.get()| instead. +- *vim.lsp.diagnostic.get_count()* Use |vim.diagnostic.get()| instead. +- *vim.lsp.diagnostic.get_line_diagnostics()* Use |vim.diagnostic.get()| instead. +- *vim.lsp.diagnostic.get_next()* +- *vim.lsp.diagnostic.get_next_pos()* +- *vim.lsp.diagnostic.get_prev()* +- *vim.lsp.diagnostic.get_prev_pos()* +- *vim.lsp.diagnostic.get_virtual_text_chunks_for_line()* No replacement. Use + options provided by |vim.diagnostic.config()| to customize virtual text. +- *vim.lsp.diagnostic.goto_next()* +- *vim.lsp.diagnostic.goto_prev()* +- *vim.lsp.diagnostic.redraw()* Use |vim.diagnostic.show()| instead. +- *vim.lsp.diagnostic.reset()* +- *vim.lsp.diagnostic.save()* Use |vim.diagnostic.set()| instead. +- *vim.lsp.diagnostic.set_loclist()* Use |vim.diagnostic.setloclist()| instead. +- *vim.lsp.diagnostic.set_qflist()* Use |vim.diagnostic.setqflist()| instead. +- *vim.lsp.diagnostic.show_line_diagnostics()* Use |vim.diagnostic.open_float()| instead. +- *vim.lsp.diagnostic.show_position_diagnostics()* Use |vim.diagnostic.open_float()| instead. The following are deprecated without replacement. These functions are moved internally and are no longer exposed as part of the API. Instead, use |vim.diagnostic.config()| and |vim.diagnostic.show()|. -*vim.lsp.diagnostic.set_signs()* -*vim.lsp.diagnostic.set_underline()* -*vim.lsp.diagnostic.set_virtual_text()* - -LSP Functions ~ - -*vim.lsp.util.diagnostics_to_items()* Use |vim.diagnostic.toqflist()| instead. -*vim.lsp.util.set_qflist()* Use |setqflist()| instead. -*vim.lsp.util.set_loclist()* Use |setloclist()| instead. -*vim.lsp.buf_get_clients()* Use |vim.lsp.get_active_clients()| with +- *vim.lsp.diagnostic.set_signs()* +- *vim.lsp.diagnostic.set_underline()* +- *vim.lsp.diagnostic.set_virtual_text()* + +LSP FUNCTIONS +- *vim.lsp.buf.range_code_action()* Use |vim.lsp.buf.code_action()| with + the `range` parameter. +- *vim.lsp.util.diagnostics_to_items()* Use |vim.diagnostic.toqflist()| instead. +- *vim.lsp.util.set_qflist()* Use |setqflist()| instead. +- *vim.lsp.util.set_loclist()* Use |setloclist()| instead. +- *vim.lsp.buf_get_clients()* Use |vim.lsp.get_active_clients()| with {buffer = bufnr} instead. - -Lua ~ -*vim.register_keystroke_callback()* Use |vim.on_key()| instead. - -Modifiers ~ -*cpo-<* -*:menu-<special>* -*:menu-special* <> notation is always enabled. -*:map-<special>* -*:map-special* <> notation is always enabled. - -Normal commands ~ -*]f* -*[f* Same as "gf". - -Options ~ -*'cscopeverbose'* Enabled by default. Use |:silent| instead. -*'exrc'* *'ex'* Security risk: downloaded files could include - a malicious .nvimrc or .exrc file. See 'secure'. - Recommended alternative: define an autocommand in your - |vimrc| to set options for a matching directory. -'gd' -'gdefault' Enables the |:substitute| flag 'g' by default. -*'fe'* 'fenc'+'enc' before Vim 6.0; no longer used. -*'highlight'* *'hl'* Names of builtin |highlight-groups| cannot be changed. -*'langnoremap'* Deprecated alias to 'nolangremap'. -'sessionoptions' Flags "unix", "slash" are ignored and always enabled. -*'vi'* -'viewoptions' Flags "unix", "slash" are ignored and always enabled. -*'viminfo'* Deprecated alias to 'shada' option. -*'viminfofile'* Deprecated alias to 'shadafile' option. - -UI extensions~ -*ui-wildmenu* Use |ui-cmdline| with |ui-popupmenu| instead. Enabled +- *vim.lsp.buf.formatting()* Use |vim.lsp.buf.format()| with + {async = true} instead. +- *vim.lsp.buf.range_formatting()* Use |vim.lsp.formatexpr()| + or |vim.lsp.buf.format()| instead. + +LUA +- *vim.register_keystroke_callback()* Use |vim.on_key()| instead. + +NORMAL COMMANDS +- *]f* *[f* Same as "gf". + +OPTIONS +- *cpo-<* *:menu-<special>* *:menu-special* *:map-<special>* *:map-special* + `<>` notation is always enabled. +- 'gdefault' Enables the |:substitute| flag 'g' by default. +- *'fe'* 'fenc'+'enc' before Vim 6.0; no longer used. +- *'highlight'* *'hl'* Names of builtin |highlight-groups| cannot be changed. +- *'langnoremap'* Deprecated alias to 'nolangremap'. +- 'sessionoptions' Flags "unix", "slash" are ignored and always enabled. +- *'vi'* +- 'viewoptions' Flags "unix", "slash" are ignored and always enabled. +- *'viminfo'* Deprecated alias to 'shada' option. +- *'viminfofile'* Deprecated alias to 'shadafile' option. + +UI EXTENSIONS +- *ui-wildmenu* Use |ui-cmdline| with |ui-popupmenu| instead. Enabled by the `ext_wildmenu` |ui-option|. Emits these events: - ["wildmenu_show", items] - ["wildmenu_select", selected] - ["wildmenu_hide"] + - `["wildmenu_show", items]` + - `["wildmenu_select", selected]` + - `["wildmenu_hide"]` -Variables~ -*b:terminal_job_pid* PID of the top-level process in a |:terminal|. +VARIABLES +- *b:terminal_job_pid* PID of the top-level process in a |:terminal|. Use `jobpid(&channel)` instead. + vim:noet:tw=78:ts=8:ft=help:norl: diff --git a/runtime/doc/dev_style.txt b/runtime/doc/dev_style.txt index 77253e7831..b96b01dbff 100644 --- a/runtime/doc/dev_style.txt +++ b/runtime/doc/dev_style.txt @@ -8,7 +8,7 @@ Nvim style guide *dev-style* This is style guide for developers working on Nvim's source code. -License: CC-By 3.0 http://creativecommons.org/licenses/by/3.0/ +License: CC-By 3.0 https://creativecommons.org/licenses/by/3.0/ Type |gO| to see the table of contents. @@ -38,7 +38,7 @@ All header files should have `#define` guards to prevent multiple inclusion. The format of the symbol name should be `NVIM_<DIRECTORY>_<FILE>_H`. In foo/bar.h: -> +>c #ifndef NVIM_FOO_BAR_H #define NVIM_FOO_BAR_H @@ -71,7 +71,7 @@ C99 allows you to declare variables anywhere in a function. Declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization -should be used instead of declaration and assignment, e.g. > +should be used instead of declaration and assignment, e.g. >c int i; i = f(); // BAD: initialization separate from declaration. @@ -110,7 +110,7 @@ Variable-length arrays can cause hard to detect stack overflows. Postincrement and Postdecrement ~ -Use postfix form (`i++`) in statements. > +Use postfix form (`i++`) in statements. >c for (int i = 0; i < 3; i++) { } int j = ++i; // OK: ++i is used as an expression. @@ -136,7 +136,7 @@ Use `const` pointers whenever possible. Avoid `const` on non-pointer parameter d before the "noun" (`int`). That said, while we encourage putting `const` first, we do not require it. - But be consistent with the code around you! > + But be consistent with the code around you! >c void foo(const char *p, int i); } @@ -176,21 +176,14 @@ Type unsigned signed Booleans ~ -Use `bool` to represent boolean values. > +Use `bool` to represent boolean values. >c int loaded = 1; // BAD: loaded should have type bool. -Variable declarations ~ - -Declare only one variable per line. > - - int i, j = 1 - - Conditions ~ -Don't use "yoda-conditions". Use at most one assignment per condition. > +Don't use "yoda-conditions". Use at most one assignment per condition. >c if (1 == x) { @@ -203,7 +196,7 @@ Function declarations ~ Every function must not have a separate declaration. -Function declarations are created by the gendeclarations.lua script. > +Function declarations are created by the gendeclarations.lua script. >c static void f(void); @@ -216,7 +209,7 @@ Function declarations are created by the gendeclarations.lua script. > General translation unit layout ~ The definitions of public functions precede the definitions of static -functions. > +functions. >c <HEADER> @@ -237,7 +230,7 @@ if .c file does not contain any static functions. Included file name consists of the .c file name without extension, preceded by the directory name relative to src/nvim. Name of the file containing static functions declarations ends with `.c.generated.h`, `*.h.generated.h` files -contain only non-static function declarations. > +contain only non-static function declarations. >c // src/nvim/foo.c file #include <stddef.h> @@ -281,7 +274,7 @@ comparisons, and structure alignment. `#pragma pack()` and `__declspec(align())`. - Use the `LL` or `ULL` suffixes as needed to create 64-bit constants. For - example: > + example: >c int64_t my_value = 0x123456789LL; uint64_t my_mask = 3ULL << 48; @@ -295,7 +288,7 @@ Use `sizeof(varname)` when you take the size of a particular variable. `sizeof(varname)` will update appropriately if someone changes the variable type either now or later. You may use `sizeof(type)` for code unrelated to any particular variable, such as code that manages an external or internal data -format where a variable of an appropriate C type is not convenient. > +format where a variable of an appropriate C type is not convenient. >c Struct data; memset(&data, 0, sizeof(data)); @@ -331,7 +324,7 @@ Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate -by deleting letters within a word. > +by deleting letters within a word. >c int price_count_reader; // No abbreviation. int num_errors; // "num" is a widespread convention. @@ -368,7 +361,7 @@ Typedef-ed structs and enums start with a capital letter and have a capital letter for each new word, with no underscores: `MyExcitingStruct`. Non-Typedef-ed structs and enums are all lowercase with underscores between -words: `struct my_exciting_struct` . > +words: `struct my_exciting_struct` . >c struct my_struct { ... @@ -383,7 +376,7 @@ instance: `my_exciting_local_variable`. Common Variable names ~ - For example: > + For example: >c string table_name; // OK: uses underscore. string tablename; // OK: all lowercase. @@ -393,7 +386,7 @@ instance: `my_exciting_local_variable`. Struct Variables ~ - Data members in structs should be named like regular variables. > + Data members in structs should be named like regular variables. >c struct url_table_properties { string name; @@ -413,7 +406,7 @@ Use a `k` followed by mixed case: `kDaysInAWeek`. All compile-time constants, whether they are declared locally or globally, follow a slightly different naming convention from other variables. Use a `k` -followed by words with uppercase first letters: > +followed by words with uppercase first letters: >c const int kDaysInAWeek = 7; @@ -423,7 +416,7 @@ Function names are all lowercase, with underscores between words. For instance: `my_exceptional_function()`. All functions in the same header file should have a common prefix. -In `os_unix.h`: > +In `os_unix.h`: >c void unix_open(const char *path); void unix_user_id(void); @@ -436,7 +429,7 @@ normal operation. Enumerator Names ~ -Enumerators should be named like constants: `kEnumName`. > +Enumerators should be named like constants: `kEnumName`. >c enum url_table_errors { kOK = 0, @@ -447,7 +440,7 @@ Enumerators should be named like constants: `kEnumName`. > Macro Names ~ -They're like this: `MY_MACRO_THAT_SCARES_CPP_DEVELOPERS`. > +They're like this: `MY_MACRO_THAT_SCARES_CPP_DEVELOPERS`. >c #define ROUND(x) ... #define PI_ROUNDED 5.0 @@ -468,7 +461,7 @@ Nvim uses Doxygen comments. Comment Style ~ -Use the `//`-style syntax only. > +Use the `//`-style syntax only. >c // This is a comment spanning // multiple lines @@ -496,7 +489,7 @@ Start each file with a description of its contents. mention in the `.c` that the documentation is in the `.h` file. Do not duplicate comments in both the `.h` and the `.c`. Duplicated - comments diverge. > + comments diverge. >c /// A brief description of this file. /// @@ -507,7 +500,7 @@ Start each file with a description of its contents. Struct Comments ~ Every struct definition should have accompanying comments that describes what -it is for and how it should be used. > +it is for and how it should be used. >c /// Window info stored with a buffer. /// @@ -529,7 +522,7 @@ it is for and how it should be used. > }; If the field comments are short, you can also put them next to the field. But -be consistent within one struct, and follow the necessary doxygen style. > +be consistent within one struct, and follow the necessary doxygen style. >c struct wininfo_S { WinInfo *wi_next; ///< Next entry or NULL for last entry. @@ -567,8 +560,7 @@ of a function describe operation. - If the function allocates memory that the caller must free. - Whether any of the arguments can be a null pointer. - If there are any performance implications of how a function is used. - - If the function is re-entrant. What are its synchronization assumptions? - > + - If the function is re-entrant. What are its synchronization assumptions? >c /// Brief description of the function. /// /// Detailed description. @@ -596,7 +588,7 @@ of a function describe operation. Note you should not just repeat the comments given with the function declaration, in the `.h` file or wherever. It's okay to recapitulate briefly what the function does, but the focus of the comments should be on - how it does it. > + how it does it. >c // Note that we don't use Doxygen comments here. Iterator *get_iterator(void *arg1, void *arg2) @@ -614,7 +606,7 @@ comments are required. Global Variables ~ All global variables should have a comment describing what they are and - what they are used for. For example: > + what they are used for. For example: >c /// The total number of tests cases that we run /// through in this regression test. @@ -630,7 +622,7 @@ interesting, or important parts of your code. Also, lines that are non-obvious should get a comment at the end of the line. These end-of-line comments should be separated from the code by 2 - spaces. Example: > + spaces. Example: >c // If we have enough memory, mmap the data portion too. mmap_budget = max<int64>(0, mmap_budget - index_->length()); @@ -643,7 +635,7 @@ interesting, or important parts of your code. function returns. If you have several comments on subsequent lines, it can often be more - readable to line them up: > + readable to line them up: >c do_something(); // Comment here so the comments line up. do_something_else_that_is_longer(); // Comment here so there are two spaces between @@ -659,7 +651,7 @@ interesting, or important parts of your code. When you pass in a null pointer, boolean, or literal integer values to functions, you should consider adding a comment about what they are, or make your code self-documenting by using constants. For example, compare: - > + >c bool success = calculate_something(interesting_value, 10, @@ -667,7 +659,7 @@ interesting, or important parts of your code. NULL); // What are these arguments?? < - versus: > + versus: >c bool success = calculate_something(interesting_value, 10, // Default base value. @@ -675,7 +667,7 @@ interesting, or important parts of your code. NULL); // No callback. < - Or alternatively, constants or self-describing variables: > + Or alternatively, constants or self-describing variables: >c const int kDefaultBaseValue = 10; const bool kFirstTimeCalling = false; @@ -690,7 +682,7 @@ interesting, or important parts of your code. Note that you should never describe the code itself. Assume that the person reading the code knows C better than you do, even though he or she - does not know what you are trying to do: > + does not know what you are trying to do: >c // Now go through the b array and make sure that if i occurs, // the next element is i+1. @@ -725,7 +717,7 @@ about the problem referenced by the `TODO`. The main purpose is to have a consistent `TODO` format that can be searched to find the person who can provide more details upon request. A `TODO` is not a commitment that the person referenced will fix the problem. Thus when you create a `TODO`, it is -almost always your name that is given. > +almost always your name that is given. >c // TODO(kl@gmail.com): Use a "*" here for concatenation operator. // TODO(Zeke): change this to use relations. @@ -789,72 +781,23 @@ example, `"\uFEFF"`, is the Unicode zero-width no-break space character, which would be invisible if included in the source as straight UTF-8. -Function Declarations and Definitions ~ - -Return type on the same line as function name, parameters on the same line if -they fit. - -Functions look like this: > - - ReturnType function_name(Type par_name1, Type par_name2) - { - do_something(); - ... - } - -If you have too much text to fit on one line: > - - ReturnType really_long_function_name(Type par_name1, Type par_name2, - Type par_name3) - { - do_something(); - ... - } - -or if you cannot fit even the first parameter (but only then): > - - ReturnType really_really_really_long_function_name( - Type par_name1, // 4 space indent - Type par_name2, - Type par_name3) - { - do_something(); // 2 space indent - ... - } - -Some points to note: - -- The open parenthesis is always on the same line as the function name. -- There is never a space between the function name and the open parenthesis. -- There is never a space between the parentheses and the parameters. -- The open curly brace is always on the next line. -- The close curly brace is always on the last line by itself. -- There should be a space between the close parenthesis and the open curly - brace. -- All parameters should be named, with identical names in the declaration and - implementation. -- All parameters should be aligned if possible. -- Default indentation is 2 spaces. -- Wrapped parameters have a 4 space indent. - - Function Calls ~ On one line if it fits; otherwise, wrap arguments at the parenthesis. -Function calls have the following format: > +Function calls have the following format: >c bool retval = do_something(argument1, argument2, argument3); If the arguments do not all fit on one line, they should be broken up onto multiple lines, with each subsequent line aligned with the first argument. Do -not add spaces after the open paren or before the close paren: > +not add spaces after the open paren or before the close paren: >c bool retval = do_something(averyveryveryverylongargument1, argument2, argument3); If the function has many arguments, consider having one per line if this makes -the code more readable: > +the code more readable: >c bool retval = do_something(argument1, argument2, @@ -862,7 +805,7 @@ the code more readable: > argument4); Arguments may optionally all be placed on subsequent lines, with one line per -argument: > +argument: >c if (...) { ... @@ -886,7 +829,7 @@ place but with one space after the `{` and one space before the `}` If the braced list follows a name (e.g. a type or variable name), format as if the `{}` were the parentheses of a function call with that name. If there is -no name, assume a zero-length name. > +no name, assume a zero-length name. >c struct my_struct m = { // Here, you could also break before {. superlongvariablename1, @@ -896,18 +839,6 @@ no name, assume a zero-length name. > interiorwrappinglist2 } }; -Conditionals ~ - -Don't use spaces inside parentheses. > - - if (condition) { // no spaces inside parentheses - ... // 2 space indent. - } else if (...) { // The else goes on the same line as the closing brace. - ... - } else { - ... - } - Loops and Switch Statements ~ Annotate non-trivial fall-through between cases. @@ -915,7 +846,7 @@ Annotate non-trivial fall-through between cases. If not conditional on an enumerated value, switch statements should always have a `default` case (in the case of an enumerated value, the compiler will warn you if any values are not handled). If the default case should never -execute, simply `assert`: > +execute, simply `assert`: >c switch (var) { case 0: @@ -928,45 +859,12 @@ execute, simply `assert`: > assert(false); } -Pointer Expressions ~ - -No spaces around period or arrow. Pointer operators do not have trailing -spaces. - -The following are examples of correctly-formatted pointer and reference -expressions: > - - x = *p; - p = &x; - x = r.y; - x = r->y; - -Note that: - - - There are no spaces around the period or arrow when accessing a member. - - Pointer operators have no space after the * or &. - -Boolean Expressions ~ - -When you have a boolean expression that is longer than the standard line -length, keep operators at the start of the line. > - - if (this_one_thing > this_other_thing - && a_third_thing == a_fourth_thing - && yet_another && last_one) { - ... - } - -Also note that you should always use the punctuation operators, such as `&&` -and `~`, rather than the word operators, such as `and` and `compl`. - - Return Values ~ Do not needlessly surround the `return` expression with parentheses. Use parentheses in `return expr`; only where you would use them in `x = -expr;`. > +expr;`. >c return result; return (some_long_condition && another_condition); @@ -980,12 +878,12 @@ Horizontal Whitespace ~ Use of horizontal whitespace depends on location. General ~ -> +>c int x[] = { 0 }; // Spaces inside braces for braced-init-list. < Variables ~ -> +>c int long_variable = 0; // Don't align assignments. int i = 1; @@ -1002,14 +900,12 @@ Use of horizontal whitespace depends on location. Operators ~ -> +>c x = 0; // Assignment operators always have spaces around // them. x = -5; // No spaces separating unary operators and their x++; // arguments. if (x && !y) - ... - i = (int)d; // No spaces after a cast operator. < Vertical Whitespace ~ diff --git a/runtime/doc/develop.txt b/runtime/doc/develop.txt index b31ac47bda..ff48ae3e26 100644 --- a/runtime/doc/develop.txt +++ b/runtime/doc/develop.txt @@ -28,11 +28,9 @@ The Neo bits of Nvim should make it a better Vim, without becoming a completely different editor. - In matters of taste, prefer Vim/Unix tradition. If there is no relevant Vim/Unix tradition, consider the "common case". -- A feature that people do not know about is a useless feature. Don't add - obscure features, or at least add hints in documentation that they exist. -- There is no limit to the features that can be added. Selecting new features - is based on (1) what users ask for, (2) how much effort it takes to - implement and (3) someone actually implementing it. +- There is no limit to the features that can be added. Select new features + based on (1) what users ask for, (2) how much effort it takes to implement + and (3) someone actually implementing it. - Backwards compatibility is a feature. The RPC API in particular should never break. @@ -48,7 +46,7 @@ NVIM IS... WELL DOCUMENTED *design-documented* NVIM IS... FAST AND SMALL *design-speed-size* -Keep Nvim small and fast. +Keep Nvim small and fast. This directly affects versatility and usability. - Computers are becoming faster and bigger each year. Vim can grow too, but no faster than computers are growing. Keep Vim usable on older systems. - Many users start Vim from a shell very often. Startup time must be short. @@ -57,7 +55,8 @@ Keep Nvim small and fast. - Don't forget that some people use Vim over a slow connection. Minimize the communication overhead. - Vim is a component among other components. Don't turn it into a massive - application, but have it work well together with other programs. + application, but have it work well together with other programs + ("composability"). NVIM IS... MAINTAINABLE *design-maintain* @@ -119,7 +118,7 @@ reflects whether Python support is working. *provider-reload* Sometimes a GUI or other application may want to force a provider to "reload". To reload a provider, undefine its "loaded" flag, then use -|:runtime| to reload it: > +|:runtime| to reload it: >vim :unlet g:loaded_clipboard_provider :runtime autoload/provider/clipboard.vim @@ -131,6 +130,7 @@ DOCUMENTATION *dev-doc* (docstrings, user manual, website materials, newsletters, …). Don't mince words. Personality and flavor, used sparingly, are welcome--but in general, optimize for the reader's time and energy: be "precise yet concise". + - See https://developers.google.com/style/tone - Prefer the active voice: "Foo does X", not "X is done by Foo". - Vim differences: - Do not prefix help tags with "nvim-". Use |vim_diff.txt| to catalog @@ -144,13 +144,33 @@ DOCUMENTATION *dev-doc* - Use "tui-" to prefix help tags related to the host terminal, and "TUI" in prose if possible. - Docstrings: do not start parameter descriptions with "The" or "A" unless it - is critical to avoid ambiguity. - GOOD: > - /// @param dirname Path fragment before `pend` -< BAD: > - /// @param dirname The path fragment before `pend` + is critical to avoid ambiguity. > + GOOD: + /// @param dirname Path fragment before `pend` + BAD: + /// @param dirname The path fragment before `pend` < +Documentation format ~ + +For Nvim-owned docs, use the following strict subset of "vimdoc" to ensure +the help doc renders nicely in other formats (such as HTML: +https://neovim.io/doc/user ). + +Strict "vimdoc" subset: + +- Use lists (like this!) prefixed with "-", "*", or "•", for adjacent lines + that you don't want auto-wrapped. Lists are always rendered with "flow" + (soft-wrapped) layout instead of preformatted (hard-wrapped) layout common + in legacy :help docs. + - Limitation: currently the parser https://github.com/neovim/tree-sitter-vimdoc + does not understand numbered listitems, so use a bullet symbol (- or •) + before numbered items, e.g. "- 1." instead of "1.". +- Separate blocks (paragraphs) of content by a blank line(s). +- Do not use indentation in random places—that prevents the page from using + "flow" layout. If you need a preformatted section, put it in + a |help-codeblock| starting with ">". + C docstrings ~ Nvim API documentation lives in the source code, as docstrings (Doxygen @@ -163,7 +183,8 @@ Docstring format: `@note`, `@param`, `@returns` - Limited markdown is supported. - List-items start with `-` (useful to nest or "indent") -- Use `<pre>` for code samples. +- Use `<pre>` for code samples. + Code samples can be annotated as `vim` or `lua` Example: the help for |nvim_open_win()| is generated from a docstring defined in src/nvim/api/win_config.c like this: > @@ -172,7 +193,7 @@ in src/nvim/api/win_config.c like this: > /// ... /// /// Example (Lua): window-relative float - /// <pre> + /// <pre>lua /// vim.api.nvim_open_win(0, false, /// {relative='win', row=3, col=3, width=12, height=3}) /// </pre> @@ -201,7 +222,8 @@ Docstring format: `---@see`, `---@param`, `---@returns` - Limited markdown is supported. - List-items start with `-` (useful to nest or "indent") -- Use `<pre>` for code samples. +- Use `<pre>` for code samples. + Code samples can be annotated as `vim` or `lua` Example: the help for |vim.paste()| is generated from a docstring decorating vim.paste in runtime/lua/vim/_editor.lua like this: > @@ -210,7 +232,7 @@ vim.paste in runtime/lua/vim/_editor.lua like this: > --- (such as the |TUI|) pastes text into the editor. --- --- Example: To remove ANSI color codes when pasting: - --- <pre> + --- <pre>lua --- vim.paste = (function() --- local overridden = vim.paste --- ... @@ -227,14 +249,27 @@ vim.paste in runtime/lua/vim/_editor.lua like this: > LUA *dev-lua* - Keep the core Lua modules |lua-stdlib| simple. Avoid elaborate OOP or - pseudo-OOP designs. Plugin authors just want functions to call, they don't - want to learn a big, fancy inheritance hierarchy. Thus avoid specialized - objects; tables or values are usually better. + pseudo-OOP designs. Plugin authors just want functions to call, not a big, + fancy inheritance hierarchy. +- Avoid requiring or returning special objects in the Nvim stdlib. Plain + tables or values are easier to serialize, easier to construct from literals, + easier to inspect and print, and inherently compatible with all Lua plugins. + (This guideline doesn't apply to opaque, non-data objects like `vim.cmd`.) API *dev-api* -Use this template to name new RPC |API| functions: +- Avoid "mutually exclusive" parameters--via constraints or limitations, if + necessary. For example nvim_create_autocmd() has mutually exclusive + "callback" and "command" args; but the "command" arg could be eliminated by + simply not supporting Vimscript function names, and treating a string + "callback" arg as an Ex command (which can call Vimscript functions). The + "buffer" arg could also be eliminated by treating a number "pattern" as + a buffer number. + + *dev-api-naming* +Use this format to name new RPC |API| functions: + nvim_{thing}_{action}_{arbitrary-qualifiers} If the function acts on an object then {thing} is the name of that object @@ -243,31 +278,50 @@ If the function acts on an object then {thing} is the name of that object with a {thing} that groups functions under a common concept). Use existing common {action} names if possible: - add Append to, or insert into, a collection - create Create a new thing - del Delete a thing (or group of things) - exec Execute code - get Get a thing (or group of things by query) - list Get all things - set Set a thing (or group of things) - -Use consistent names for {thing} in all API functions. E.g. a buffer is called + - add Append to, or insert into, a collection + - call Call a function + - create Create a new (non-trivial) thing + - del Delete a thing (or group of things) + - eval Evaluate an expression + - exec Execute code + - fmt Format + - get Get things (often by a query) + - open Open + - parse Parse something into a structured form + - set Set a thing (or group of things) + +Do NOT use these deprecated verbs: + - list Redundant with "get" + +Use consistent names for {thing} (nouns) in API functions: buffer is called "buf" everywhere, not "buffer" in some places and "buf" in others. + - buf Buffer + - chan |channel| + - cmd Command + - cmdline Command-line UI or input + - fn Function + - hl Highlight + - pos Position + - proc System process + - tabpage Tabpage + - win Window + +Do NOT use these deprecated nouns: + - buffer + - command + - window Example: - `nvim_get_current_line` acts on the global editor state; the common - {action} "get" is used but {thing} is omitted. - -Example: - `nvim_buf_add_highlight` acts on a `Buffer` object (the first parameter) - and uses the common {action} "add". + `nvim_get_keymap('v')` operates in a global context (first parameter is not + a Buffer). The "get" {action} indicates that it gets anything matching the + given filter parameter. There is no need for a "list" action because + `nvim_get_keymap('')` (i.e., empty filter) returns all items. Example: - `nvim_list_bufs` operates in a global context (first parameter is not - a Buffer). The common {action} "list" indicates that it lists all bufs - (plural) in the global context. + `nvim_buf_del_mark` acts on a `Buffer` object (the first parameter) + and uses the "del" {action}. -Use this template to name new API events: +Use this format to name new API events: nvim_{thing}_{event}_event Example: @@ -309,10 +363,10 @@ a good name: it's idiomatic and unambiguous. If the package is named "neovim", it confuses users, and complicates documentation and discussions. Examples of API-client package names: - GOOD: nvim-racket - GOOD: pynvim - BAD: python-client - BAD: neovim +- GOOD: nvim-racket +- GOOD: pynvim +- BAD: python-client +- BAD: neovim API client implementation guidelines ~ @@ -378,4 +432,4 @@ Use the "on_" prefix to name event handlers and also the interface for a confused collection of naming conventions for these related concepts. - vim:tw=78:ts=8:noet:ft=help:norl: + vim:tw=78:ts=8:sw=4:et:ft=help:norl: diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt index e1b52746be..7066a3739a 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -68,11 +68,11 @@ The "severity" key in a diagnostic is one of the values defined in Functions that take a severity as an optional parameter (e.g. |vim.diagnostic.get()|) accept one of two forms: -1. A single |vim.diagnostic.severity| value: > +1. A single |vim.diagnostic.severity| value: >lua vim.diagnostic.get(0, { severity = vim.diagnostic.severity.WARN }) -2. A table with a "min" or "max" key (or both): > +2. A table with a "min" or "max" key (or both): >lua vim.diagnostic.get(0, { severity = { min = vim.diagnostic.severity.WARN } }) @@ -107,7 +107,7 @@ Nvim provides these handlers by default: "virtual_text", "signs", and *diagnostic-handlers-example* The example below creates a new handler that notifies the user of diagnostics -with |vim.notify()|: > +with |vim.notify()|: >lua -- It's good practice to namespace custom handlers to avoid collisions vim.diagnostic.handlers["my/notify"] = { @@ -135,7 +135,7 @@ In this example, there is nothing to do when diagnostics are hidden, so we omit the "hide" function. Existing handlers can be overridden. For example, use the following to only -show a sign for the highest severity diagnostic on a given line: > +show a sign for the highest severity diagnostic on a given line: >lua -- Create a custom namespace. This will aggregate signs from all other -- namespaces and only show the one with the highest severity on a @@ -185,7 +185,7 @@ own default highlight groups. For example, the default highlighting for |hl-DiagnosticSignError| is linked to |hl-DiagnosticError|. To change the default (and therefore the linked -highlights), use the |:highlight| command: > +highlights), use the |:highlight| command: >vim highlight DiagnosticError guifg="BrightRed" < @@ -209,6 +209,11 @@ DiagnosticHint Used as the base highlight group. Other Diagnostic highlights link to this by default (except Underline) + *hl-DiagnosticOk* +DiagnosticOk + Used as the base highlight group. + Other Diagnostic highlights link to this by default (except Underline) + *hl-DiagnosticVirtualTextError* DiagnosticVirtualTextError Used for "Error" diagnostic virtual text. @@ -225,6 +230,10 @@ DiagnosticVirtualTextInfo DiagnosticVirtualTextHint Used for "Hint" diagnostic virtual text. + *hl-DiagnosticVirtualTextOk* +DiagnosticVirtualTextOk + Used for "Ok" diagnostic virtual text. + *hl-DiagnosticUnderlineError* DiagnosticUnderlineError Used to underline "Error" diagnostics. @@ -241,6 +250,10 @@ DiagnosticUnderlineInfo DiagnosticUnderlineHint Used to underline "Hint" diagnostics. + *hl-DiagnosticUnderlineOk* +DiagnosticUnderlineOk + Used to underline "Ok" diagnostics. + *hl-DiagnosticFloatingError* DiagnosticFloatingError Used to color "Error" diagnostic messages in diagnostics float. @@ -258,6 +271,10 @@ DiagnosticFloatingInfo DiagnosticFloatingHint Used to color "Hint" diagnostic messages in diagnostics float. + *hl-DiagnosticFloatingOk* +DiagnosticFloatingOk + Used to color "Ok" diagnostic messages in diagnostics float. + *hl-DiagnosticSignError* DiagnosticSignError Used for "Error" signs in sign column. @@ -274,12 +291,16 @@ DiagnosticSignInfo DiagnosticSignHint Used for "Hint" signs in sign column. + *hl-DiagnosticSignOk* +DiagnosticSignOk + Used for "Ok" signs in sign column. + ============================================================================== SIGNS *diagnostic-signs* Signs are defined for each diagnostic severity. The default text for each sign is the first letter of the severity name (for example, "E" for ERROR). Signs -can be customized using the following: > +can be customized using the following: >vim sign define DiagnosticSignError text=E texthl=DiagnosticSignError linehl= numhl= sign define DiagnosticSignWarn text=W texthl=DiagnosticSignWarn linehl= numhl= @@ -295,10 +316,18 @@ option in the "signs" table of |vim.diagnostic.config()| or 10 if unset). EVENTS *diagnostic-events* *DiagnosticChanged* -DiagnosticChanged After diagnostics have changed. +DiagnosticChanged After diagnostics have changed. When used from Lua, + the new diagnostics are passed to the autocmd + callback in the "data" table. + +Example: >lua -Example: > - autocmd DiagnosticChanged * lua vim.diagnostic.setqflist({ open = false }) + vim.api.nvim_create_autocmd('DiagnosticChanged', { + callback = function(args) + local diagnostics = args.data.diagnostics + vim.pretty_print(diagnostics) + end, + }) < ============================================================================== Lua module: vim.diagnostic *diagnostic-api* @@ -312,12 +341,12 @@ config({opts}, {namespace}) *vim.diagnostic.config()* |vim.diagnostic.show()|). Ephemeral configuration has highest priority, followed by namespace configuration, and finally global configuration. - For example, if a user enables virtual text globally with > + For example, if a user enables virtual text globally with >lua vim.diagnostic.config({ virtual_text = true }) < - and a diagnostic producer sets diagnostics with > + and a diagnostic producer sets diagnostics with >lua vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) < @@ -334,7 +363,7 @@ config({opts}, {namespace}) *vim.diagnostic.config()* any of the above. Parameters: ~ - {opts} (table|nil) When omitted or "nil", retrieve the current + • {opts} (table|nil) When omitted or "nil", retrieve the current configuration. Otherwise, a configuration table with the following keys: • underline: (default true) Use underline for @@ -357,16 +386,21 @@ config({opts}, {namespace}) *vim.diagnostic.config()* the beginning of the virtual text. • prefix: (string) Prepend diagnostic message with prefix. + • suffix: (string or function) Append diagnostic + message with suffix. If a function, it must have the + signature (diagnostic) -> string, where {diagnostic} + is of type |diagnostic-structure|. This can be used + to render an LSP diagnostic error code. • format: (function) A function that takes a diagnostic as input and returns a string. The return value is - the text used to display the diagnostic. Example: > + the text used to display the diagnostic. Example: >lua - function(diagnostic) - if diagnostic.severity == vim.diagnostic.severity.ERROR then - return string.format("E: %s", diagnostic.message) + function(diagnostic) + if diagnostic.severity == vim.diagnostic.severity.ERROR then + return string.format("E: %s", diagnostic.message) + end + return diagnostic.message end - return diagnostic.message - end < • signs: (default true) Use signs for diagnostics. @@ -389,57 +423,57 @@ config({opts}, {namespace}) *vim.diagnostic.config()* severities are displayed before lower severities (e.g. ERROR is displayed before WARN). Options: • reverse: (boolean) Reverse sort order - {namespace} (number|nil) Update the options for the given namespace. + • {namespace} (number|nil) Update the options for the given namespace. When omitted, update the global diagnostic options. disable({bufnr}, {namespace}) *vim.diagnostic.disable()* Disable diagnostics in the given buffer. Parameters: ~ - {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, disable diagnostics in all buffers. - {namespace} (number|nil) Only disable diagnostics for the given + • {namespace} (number|nil) Only disable diagnostics for the given namespace. enable({bufnr}, {namespace}) *vim.diagnostic.enable()* Enable diagnostics in the given buffer. Parameters: ~ - {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, enable diagnostics in all buffers. - {namespace} (number|nil) Only enable diagnostics for the given + • {namespace} (number|nil) Only enable diagnostics for the given namespace. fromqflist({list}) *vim.diagnostic.fromqflist()* Convert a list of quickfix items to a list of diagnostics. Parameters: ~ - {list} (table) A list of quickfix items from |getqflist()| or + • {list} (table) A list of quickfix items from |getqflist()| or |getloclist()|. Return: ~ - array of diagnostics |diagnostic-structure| + Diagnostic [] array of |diagnostic-structure| get({bufnr}, {opts}) *vim.diagnostic.get()* Get current diagnostics. Parameters: ~ - {bufnr} (number|nil) Buffer number to get diagnostics from. Use 0 for + • {bufnr} (number|nil) Buffer number to get diagnostics from. Use 0 for current buffer or nil for all buffers. - {opts} (table|nil) A table with the following keys: + • {opts} (table|nil) A table with the following keys: • namespace: (number) Limit diagnostics to the given namespace. • lnum: (number) Limit diagnostics to the given line number. • severity: See |diagnostic-severity|. Return: ~ - (table) A list of diagnostic items |diagnostic-structure|. + Diagnostic [] table A list of diagnostic items |diagnostic-structure|. get_namespace({namespace}) *vim.diagnostic.get_namespace()* Get namespace metadata. Parameters: ~ - {namespace} (number) Diagnostic namespace + • {namespace} (number) Diagnostic namespace Return: ~ (table) Namespace metadata @@ -454,43 +488,45 @@ get_next({opts}) *vim.diagnostic.get_next()* Get the next diagnostic closest to the cursor position. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table|nil) See |vim.diagnostic.goto_next()| Return: ~ - (table) Next diagnostic + Diagnostic|nil Next diagnostic get_next_pos({opts}) *vim.diagnostic.get_next_pos()* Return the position of the next diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table|nil) See |vim.diagnostic.goto_next()| Return: ~ - (table) Next diagnostic position as a (row, col) tuple. + table|false Next diagnostic position as a (row, col) tuple or false if + no next diagnostic. get_prev({opts}) *vim.diagnostic.get_prev()* Get the previous diagnostic closest to the cursor position. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} nil|table See |vim.diagnostic.goto_next()| Return: ~ - (table) Previous diagnostic + Diagnostic|nil Previous diagnostic get_prev_pos({opts}) *vim.diagnostic.get_prev_pos()* Return the position of the previous diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table|nil) See |vim.diagnostic.goto_next()| Return: ~ - (table) Previous diagnostic position as a (row, col) tuple. + table|false Previous diagnostic position as a (row, col) tuple or + false if there is no prior diagnostic goto_next({opts}) *vim.diagnostic.goto_next()* Move to the next diagnostic. Parameters: ~ - {opts} (table|nil) Configuration table with the following keys: + • {opts} (table|nil) Configuration table with the following keys: • namespace: (number) Only consider diagnostics from the given namespace. • cursor_position: (cursor position) Cursor position as a @@ -511,7 +547,7 @@ goto_prev({opts}) *vim.diagnostic.goto_prev()* Move to the previous diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table|nil) See |vim.diagnostic.goto_next()| hide({namespace}, {bufnr}) *vim.diagnostic.hide()* Hide currently displayed diagnostics. @@ -524,11 +560,23 @@ hide({namespace}, {bufnr}) *vim.diagnostic.hide()* |vim.diagnostic.disable()|. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, hide - diagnostics from all namespaces. - {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + • {namespace} (number|nil) Diagnostic namespace. When omitted, hide diagnostics from all + namespaces. + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, hide diagnostics in all buffers. +is_disabled({bufnr}, {namespace}) *vim.diagnostic.is_disabled()* + Check whether diagnostics are disabled in a given buffer. + + Parameters: ~ + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. + • {namespace} (number|nil) Diagnostic namespace. When omitted, checks if all diagnostics are + disabled in {bufnr}. Otherwise, only checks if + diagnostics from {namespace} are disabled. + + Return: ~ + (boolean) + *vim.diagnostic.match()* match({str}, {pat}, {groups}, {severity_map}, {defaults}) Parse a diagnostic from a string. @@ -538,34 +586,34 @@ match({str}, {pat}, {groups}, {severity_map}, {defaults}) WARNING filename:27:3: Variable 'foo' does not exist < - This can be parsed into a diagnostic |diagnostic-structure| with: > + This can be parsed into a diagnostic |diagnostic-structure| with: >lua - local s = "WARNING filename:27:3: Variable 'foo' does not exist" - local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" - local groups = { "severity", "lnum", "col", "message" } - vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) + local s = "WARNING filename:27:3: Variable 'foo' does not exist" + local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" + local groups = { "severity", "lnum", "col", "message" } + vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) < Parameters: ~ - {str} (string) String to parse diagnostics from. - {pat} (string) Lua pattern with capture groups. - {groups} (table) List of fields in a |diagnostic-structure| to + • {str} (string) String to parse diagnostics from. + • {pat} (string) Lua pattern with capture groups. + • {groups} (table) List of fields in a |diagnostic-structure| to associate with captures from {pat}. - {severity_map} (table) A table mapping the severity field from + • {severity_map} (table) A table mapping the severity field from {groups} with an item from |vim.diagnostic.severity|. - {defaults} (table|nil) Table of default values for any fields not + • {defaults} (table|nil) Table of default values for any fields not listed in {groups}. When omitted, numeric values default to 0 and "severity" defaults to ERROR. Return: ~ - diagnostic |diagnostic-structure| or `nil` if {pat} fails to match - {str}. + Diagnostic|nil: |diagnostic-structure| or `nil` if {pat} fails to + match {str}. open_float({opts}, {...}) *vim.diagnostic.open_float()* Show diagnostics in a floating window. Parameters: ~ - {opts} (table|nil) Configuration table with the same keys as + • {opts} (table|nil) Configuration table with the same keys as |vim.lsp.util.open_floating_preview()| in addition to the following: • bufnr: (number) Buffer number to show diagnostics from. @@ -610,9 +658,12 @@ open_float({opts}, {...}) *vim.diagnostic.open_float()* {prefix} is a string, it is prepended to each diagnostic in the window with no highlight. Overrides the setting from |vim.diagnostic.config()|. + • suffix: Same as {prefix}, but appends the text to the + diagnostic instead of prepending it. Overrides the setting + from |vim.diagnostic.config()|. Return: ~ - tuple ({float_bufnr}, {win_id}) + number|nil, number|nil: ({float_bufnr}, {win_id}) reset({namespace}, {bufnr}) *vim.diagnostic.reset()* Remove all diagnostics from the given namespace. @@ -623,27 +674,27 @@ reset({namespace}, {bufnr}) *vim.diagnostic.reset()* re-displayed, use |vim.diagnostic.hide()|. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, remove - diagnostics from all namespaces. - {bufnr} (number|nil) Remove diagnostics for the given buffer. + • {namespace} (number|nil) Diagnostic namespace. When omitted, remove diagnostics from all + namespaces. + • {bufnr} (number|nil) Remove diagnostics for the given buffer. When omitted, diagnostics are removed for all buffers. set({namespace}, {bufnr}, {diagnostics}, {opts}) *vim.diagnostic.set()* Set diagnostics for the given namespace and buffer. Parameters: ~ - {namespace} (number) The diagnostic namespace - {bufnr} (number) Buffer number - {diagnostics} (table) A list of diagnostic items + • {namespace} (number) The diagnostic namespace + • {bufnr} (number) Buffer number + • {diagnostics} (table) A list of diagnostic items |diagnostic-structure| - {opts} (table|nil) Display options to pass to + • {opts} (table|nil) Display options to pass to |vim.diagnostic.show()| setloclist({opts}) *vim.diagnostic.setloclist()* Add buffer diagnostics to the location list. Parameters: ~ - {opts} (table|nil) Configuration table with the following keys: + • {opts} (table|nil) Configuration table with the following keys: • namespace: (number) Only add diagnostics from the given namespace. • winnr: (number, default 0) Window number to set location @@ -658,7 +709,7 @@ setqflist({opts}) *vim.diagnostic.setqflist()* Add all diagnostics to the quickfix list. Parameters: ~ - {opts} (table|nil) Configuration table with the following keys: + • {opts} (table|nil) Configuration table with the following keys: • namespace: (number) Only add diagnostics from the given namespace. • open: (boolean, default true) Open quickfix list after @@ -672,17 +723,17 @@ show({namespace}, {bufnr}, {diagnostics}, {opts}) Display diagnostics for the given namespace and buffer. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, show - diagnostics from all namespaces. - {bufnr} (number|nil) Buffer number, or 0 for current buffer. + • {namespace} (number|nil) Diagnostic namespace. When omitted, show diagnostics from all + namespaces. + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, show diagnostics in all buffers. - {diagnostics} (table|nil) The diagnostics to display. When omitted, + • {diagnostics} (table|nil) The diagnostics to display. When omitted, use the saved diagnostics for the given namespace and buffer. This can be used to display a list of diagnostics without saving them or to display only a subset of diagnostics. May not be used when {namespace} or {bufnr} is nil. - {opts} (table|nil) Display options. See + • {opts} (table|nil) Display options. See |vim.diagnostic.config()|. toqflist({diagnostics}) *vim.diagnostic.toqflist()* @@ -690,9 +741,9 @@ toqflist({diagnostics}) *vim.diagnostic.toqflist()* passed to |setqflist()| or |setloclist()|. Parameters: ~ - {diagnostics} (table) List of diagnostics |diagnostic-structure|. + • {diagnostics} (table) List of diagnostics |diagnostic-structure|. Return: ~ - array of quickfix list items |setqflist-what| + table[] of quickfix list items |setqflist-what| vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/diff.txt b/runtime/doc/diff.txt index 9c5792dd43..382d025d3c 100644 --- a/runtime/doc/diff.txt +++ b/runtime/doc/diff.txt @@ -137,6 +137,10 @@ Otherwise they are set to their default value: 'foldmethod' "manual" 'foldcolumn' 0 +'foldenable' will most-likely be reset to off. That is when 'foldmethod' is +restored to "manual". The folds themselves are not cleared but they should +not show up, resetting 'foldenable' is the best way to do that. + ============================================================================== 2. Viewing diffs *view-diffs* @@ -388,6 +392,11 @@ mode, so that a CTRL-Z doesn't end the text on DOS. The `redraw!` command may not be needed, depending on whether executing a shell command shows something on the display or not. +If the 'diffexpr' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Example: > + set diffexpr=s:MyDiffExpr() + set diffexpr=<SID>SomeDiffExpr() +< *E810* *E97* Vim will do a test if the diff output looks alright. If it doesn't, you will get an error message. Possible causes: @@ -401,7 +410,7 @@ to see more messages. The self-installing Vim for MS-Windows includes a diff program. If you don't have it you might want to download a diff.exe. For example from -http://gnuwin32.sourceforge.net/packages/diffutils.htm. +https://gnuwin32.sourceforge.net/packages/diffutils.htm. USING PATCHES *diff-patchexpr* @@ -439,4 +448,9 @@ evaluating 'patchexpr'. This hopefully avoids that files in the current directory are accidentally patched. Vim will also delete files starting with v:fname_in and ending in ".rej" and ".orig". +If the 'patchexpr' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Example: > + set patchexpr=s:MyPatchExpr() + set patchexpr=<SID>SomePatchExpr() +< vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/digraph.txt b/runtime/doc/digraph.txt index eb3de0111f..ce0a929bc1 100644 --- a/runtime/doc/digraph.txt +++ b/runtime/doc/digraph.txt @@ -156,7 +156,7 @@ These are the RFC1345 digraphs for the one-byte characters. See the output of ":digraphs" for the others. EURO - + *euro* *euro-digraph* Exception: RFC1345 doesn't specify the euro sign. In Vim the digraph =e was added for this. Note the difference between latin1, where the digraph Cu is used for the currency sign, and latin9 (iso-8859-15), where the digraph =e is diff --git a/runtime/doc/editing.txt b/runtime/doc/editing.txt index dcb0bf8a2e..f77db5fab3 100644 --- a/runtime/doc/editing.txt +++ b/runtime/doc/editing.txt @@ -345,9 +345,9 @@ escaped with a backslash. Wildcards in {file} are expanded, but as with file completion, 'wildignore' and 'suffixes' apply. Which wildcards are supported depends on the system. These are the common ones: - ? matches one character - * matches anything, including nothing - ** matches anything, including nothing, recurses into directories + `?` matches one character + `*` matches anything, including nothing + `**` matches anything, including nothing, recurses into directories [abc] match 'a', 'b' or 'c' To avoid the special meaning of the wildcards prepend a backslash. However, @@ -406,7 +406,7 @@ external command, by putting an equal sign right after the first backtick, e.g.: > :e `=tempname()` The expression can contain just about anything, thus this can also be used to -avoid the special meaning of '"', '|', '%' and '#'. However, 'wildignore' +avoid the special meaning of '"', "|", '%' and '#'. However, 'wildignore' does apply like to other wildcards. Environment variables in the expression are expanded when evaluating the @@ -423,9 +423,8 @@ Note that such expressions are only supported in places where a filename is expected as an argument to an Ex-command. *++opt* *[++opt]* -The [++opt] argument can be used to force the value of 'fileformat', -'fileencoding' or 'binary' to a value for one command, and to specify the -behavior for bad characters. The form is: > +The [++opt] argument can be used to set some options for one command, and to +specify the behavior for bad characters. The form is: > ++{optname} Or: > ++{optname}={value} @@ -436,11 +435,11 @@ Where {optname} is one of: *++ff* *++enc* *++bin* *++nobin* *++edit* bin or binary sets 'binary' nobin or nobinary resets 'binary' bad specifies behavior for bad characters - edit for |:read| only: keep option values as if editing - a file + edit for |:read|: keeps options as if editing a file + p for |:write|: creates the file's parent directory -{value} cannot contain white space. It can be any valid value for these -options. Examples: > +{value} cannot contain whitespace. It can be any valid value for the options. +Examples: > :e ++ff=unix This edits the same file again with 'fileformat' set to "unix". > @@ -450,9 +449,24 @@ This writes the current buffer to "newfile" in latin1 format. The message given when writing a file will show "[converted]" when 'fileencoding' or the value specified with ++enc differs from 'encoding'. -There may be several ++opt arguments, separated by white space. They must all +There may be several ++opt arguments, separated by whitespace. They must all appear before any |+cmd| argument. + *++p* +The "++p" flag creates the parent directory of the file if it does not exist. +For example if you edit "foo/bar/file.txt", the ":write ++p" command creates +"foo/bar/" if necessary before writing the file. > + + :edit foo/bar/file.txt + :write ++p + +If you want :write (without "++p") to always create missing parent +directories, add this autocmd to your config: > + + " Auto-create parent directories (except for URIs "://"). + au BufWritePre,FileWritePre * if @% !~# '\(://\)' | call mkdir(expand('<afile>:p:h'), 'p') | endif +< + *++bad* The argument of "++bad=" specifies what happens with characters that can't be converted and illegal bytes. It can be one of three things: @@ -545,6 +559,44 @@ Before editing binary, executable or Vim script files you should set the option. This will avoid the use of 'fileformat'. Without this you risk that single <NL> characters are unexpectedly replaced with <CR><NL>. +END OF LINE AND END OF FILE *eol-and-eof* + +Vim has several options to control the file format: + 'fileformat' the <EOL> style: Unix, DOS, Mac + 'endofline' whether the last line ends with a <EOL> + 'endoffile' whether the file ends with a CTRL-Z + 'fixendofline' whether to fix eol and eof + +The first three values are normally detected automatically when reading the +file and are used when writing the text to a file. While editing the buffer +it looks like every line has a line ending and the CTRL-Z isn't there (an +exception is when 'binary' is set, it works differently then). + +The 'fixendofline' option can be used to choose what to write. You can also +change the option values to write the file differently than how it was read. + +Here are some examples how to use them. + +If you want files in Unix format (every line NL terminated): > + setl ff=unix fixeol +You should probably do this on any Unix-like system. Also modern MS-Windows +systems tend to work well with this. It is recommended to always use this +format for Vim scripts. + +If you want to use an old MS-DOS file in a modern environment, fixing line +endings and dropping CTRL-Z, but keeping the <CR><NL> style <EOL>: > + setl ff=dos fixeol +This is useful for many MS-Windows programs, they regularly expect the +<CR><NL> line endings. + +If you want to drop the final <EOL> and add a final CTRL-Z (e.g. for an old +system like CP/M): > + setl ff=dos nofixeol noeol eof + +If you want to preserve the fileformat exactly as-is, including any final +<EOL> and final CTRL-Z: > + setl nofixeol + ============================================================================== 3. The argument list *argument-list* *arglist* @@ -842,7 +894,7 @@ changed. This is done for all *.c files. Example: > :args *.[ch] :argdo %s/\<my_foo\>/My_Foo/ge | update -This changes the word "my_foo" to "My_Foo" in all *.c and *.h files. The "e" +This changes the word "my_foo" to "My_Foo" in all "*.c" and "*.h" files. The "e" flag is used for the ":substitute" command to avoid an error for files where "my_foo" isn't used. ":update" writes the file only if changes were made. @@ -855,11 +907,13 @@ Note: When the 'write' option is off, you are not able to write any file. *E502* *E503* *E504* *E505* *E512* *E514* *E667* *E949* :w[rite] [++opt] Write the whole buffer to the current file. This is - the normal way to save changes to a file. It fails - when the 'readonly' option is set or when there is - another reason why the file can't be written. - For ++opt see |++opt|, but only ++bin, ++nobin, ++ff - and ++enc are effective. + the normal way to save changes to a file. Fails when + 'readonly' is set or when there is another reason why + the file can't be written, such as when the parent + directory doesn't exist (use |++p| to avoid that). + For ++opt see |++opt|, but only ++p, ++bin, ++nobin, + ++ff and ++enc are effective. + :w[rite]! [++opt] Like ":write", but forcefully write when 'readonly' is set or there is another reason why writing was @@ -941,7 +995,7 @@ WRITING WITH MULTIPLE BUFFERS *buffer-write* Vim will warn you if you try to overwrite a file that has been changed -elsewhere. See |timestamp|. +elsewhere (unless "!" was used). See |timestamp|. *backup* *E207* *E506* *E507* *E508* *E509* *E510* If you write to an existing file (but do not append) while the 'backup', @@ -1222,8 +1276,8 @@ unmodified. For MS-Windows you can modify the filters that are used in the browse dialog. By setting the g:browsefilter or b:browsefilter variables, you can change the filters globally or locally to the buffer. The variable is set to -a string in the format "{filter label}\t{pattern};{pattern}\n" where {filter -label} is the text that appears in the "Files of Type" comboBox, and {pattern} +a string in the format "{filter label}\t{pattern};{pattern}\n" where "{filter +label}" is the text that appears in the "Files of Type" comboBox, and {pattern} is the pattern which filters the filenames. Several patterns can be given, separated by ';'. @@ -1271,6 +1325,7 @@ exist, the next-higher scope in the hierarchy applies. :cd[!] {path} Change the current directory to {path}. If {path} is relative, it is searched for in the directories listed in |'cdpath'|. + Clear any window-local directory. Does not change the meaning of an already opened file, because its full path name is remembered. Files from the |arglist| may change though! @@ -1481,8 +1536,8 @@ doing something there and closing it should be OK (if there are no side effects from other autocommands). Closing unrelated windows and buffers will get you into trouble. -Before writing a file the timestamp is checked. If it has changed, Vim will -ask if you really want to overwrite the file: +Before writing a file, the timestamp is checked (unless "!" was used). +If it has changed, Vim will ask if you really want to overwrite the file: WARNING: The file has been changed since reading it!!! Do you really want to write to it (y/n)? @@ -1521,8 +1576,8 @@ which is slightly different. There are three different types of searching: 1) Downward search: *starstar* - Downward search uses the wildcards '*', '**' and possibly others - supported by your operating system. '*' and '**' are handled inside Vim, + Downward search uses the wildcards "*", "**" and possibly others + supported by your operating system. "*" and "**" are handled inside Vim, so they work on all operating systems. Note that "**" only acts as a special wildcard when it is at the start of a name. @@ -1530,12 +1585,12 @@ There are three different types of searching: search pattern this would be ".*". Note that the "." is not used for file searching. - '**' is more sophisticated: + "**" is more sophisticated: - It ONLY matches directories. - It matches up to 30 directories deep by default, so you can use it to search an entire directory tree - The maximum number of levels matched can be given by appending a number - to '**'. + to "**". Thus '/usr/**2' can match: > /usr /usr/include @@ -1546,14 +1601,14 @@ There are three different types of searching: .... < It does NOT match '/usr/include/g++/std' as this would be three levels. - The allowed number range is 0 ('**0' is removed) to 100 + The allowed number range is 0 ("**0" is removed) to 100 If the given number is smaller than 0 it defaults to 30, if it's bigger than 100 then 100 is used. The system also has a limit on the path length, usually 256 or 1024 bytes. - - '**' can only be at the end of the path or be followed by a path + - "**" can only be at the end of the path or be followed by a path separator or by a number and a path separator. - You can combine '*' and '**' in any order: > + You can combine "*" and "**" in any order: > /usr/**/sys/* /usr/*tory/sys/** /usr/**2/sys/* @@ -1610,4 +1665,32 @@ There are three different types of searching: currently work with 'path' items that contain a URL or use the double star with depth limiter (/usr/**2) or upward search (;) notations. +============================================================================== +12. Trusted Files *trust* + +Nvim has the ability to execute arbitrary code through the 'exrc' option. In +order to prevent executing code from untrusted sources, Nvim has the concept of +"trusted files". An untrusted file will not be executed without the user's +consent, and a user can permanently mark a file as trusted or untrusted using +the |:trust| command or the |vim.secure.read()| function. + + *:trust* *E5570* +:trust [++deny] [++remove] [{file}] + + Manage files in the trust database. Without any options + or arguments, :trust adds the file associated with the + current buffer to the trust database, along with the + SHA256 hash of its contents. + + [++deny] marks the file associated with the current + buffer (or {file}, if given) as denied; no prompts will + be displayed to the user and the file will never be + executed. + + [++remove] removes the file associated with the current + buffer (or {file}, if given) from the trust database. + Future attempts to read the file in a secure setting + (i.e. with 'exrc' or |vim.secure.read()|) will prompt + the user if the file is trusted. + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/editorconfig.txt b/runtime/doc/editorconfig.txt new file mode 100644 index 0000000000..04a057e5ff --- /dev/null +++ b/runtime/doc/editorconfig.txt @@ -0,0 +1,91 @@ +*editorconfig.txt* Nvim + + + NVIM REFERENCE MANUAL + + +EditorConfig integration *editorconfig* + +Nvim natively supports EditorConfig. When a file is opened, Nvim searches +upward through all of the parent directories of that file looking for +".editorconfig" files. Each of these is parsed and any properties that match +the opened file are applied. + +For more information on EditorConfig, see https://editorconfig.org/. + + *g:editorconfig* *b:editorconfig* +EditorConfig integration can be disabled globally by adding >lua + + vim.g.editorconfig = false +< +to the user's |init.lua| file (or the Vimscript equivalent to |init.vim|). It +can also be disabled per-buffer by setting the |b:editorconfig| buffer-local +variable to `false`. + +When Nvim finds a valid .editorconfig file it will store the applied +properties in the buffer variable |b:editorconfig| if it was not already set to +`false` by the user. + + *editorconfig-properties* +The following properties are supported by default: + + *editorconfig_root* +root If "true", then stop searching for .editorconfig files + in parent directories. This property must be at the + top-level of the .editorconfig file (i.e. it must not + be within a glob section). + + *editorconfig_charset* +charset One of "utf-8", "utf-8-bom", "latin1", "utf-16be", or + "utf-16le". Sets the 'fileencoding' and 'bomb' + options. + + *editorconfig_end_of_line* +end_of_line One of "lf", "crlf", or "cr". These correspond to + setting 'fileformat' to "unix", "dos", or "mac", + respectively. + + *editorconfig_indent_style* +indent_style One of "tab" or "space". Sets the 'expandtab' option. + + *editorconfig_indent_size* +indent_size A number indicating the size of a single indent. + Alternatively, use the value "tab" to use the value of + the tab_width property. Sets the 'shiftwidth' and + 'softtabstop'. + + *editorconfig_insert_final_newline* +insert_final_newline "true" or "false" to ensure the file always has a + trailing newline as its last byte. Sets the + 'fixendofline' and 'endofline' options. + + *editorconfig_max_line_length* +max_line_length A number indicating the maximum length of a single + line. Sets the 'textwidth' option. + + *editorconfig_tab_width* +tab_width The display size of a single tab character. Sets the + 'tabstop' option. + + *editorconfig_trim_trailing_whitespace* +trim_trailing_whitespace + When "true", trailing whitespace is automatically + removed when the buffer is written. + + *editorconfig-custom-properties* +New properties can be added by adding a new entry to the "properties" table. +The table key is a property name and the value is a callback function which +accepts the number of the buffer to be modified, the value of the property +in the .editorconfig file, and (optionally) a table containing all of the +other properties and their values (useful for properties which depend on other +properties). The value is always a string and must be coerced if necessary. +Example: >lua + + require('editorconfig').properties.foo = function(bufnr, val, opts) + if opts.charset and opts.charset ~= "utf-8" then + error("foo can only be set when charset is utf-8", 0) + end + vim.b[bufnr].foo = val + end +< + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index 376adfec7f..58759a6053 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -4,7 +4,7 @@ VIM REFERENCE MANUAL by Bram Moolenaar -Expression evaluation *expression* *expr* *E15* *eval* +Expression evaluation *vimscript* *expression* *expr* *E15* *eval* Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|. @@ -40,7 +40,7 @@ List An ordered sequence of items, see |List| for details. Dictionary An associative, unordered array: Each entry has a key and a value. |Dictionary| Examples: - {'blue': "#0000ff", 'red': "#ff0000"} + {"blue": "#0000ff", "red": "#ff0000"} #{blue: "#0000ff", red: "#ff0000"} Blob Binary Large Object. Stores any sequence of bytes. See |Blob| @@ -229,13 +229,13 @@ is not available it returns zero or the default value you specify: > List concatenation ~ - + *list-concatenation* Two lists can be concatenated with the "+" operator: > :let longlist = mylist + [5, 6] :let mylist += [7, 8] -To prepend or append an item turn the item into a list by putting [] around -it. To change a list in-place see |list-modification| below. +To prepend or append an item, turn the item into a list by putting [] around +it. To change a list in-place, refer to |list-modification| below. Sublist ~ @@ -457,7 +457,7 @@ String automatically. Thus the String '4' and the number 4 will find the same entry. Note that the String '04' and the Number 04 are different, since the Number will be converted to the String '4', leading zeros are dropped. The empty string can also be used as a key. - *literal-Dict* + *literal-Dict* *#{}* To avoid having to put quotes around every key the #{} form can be used. This does require the key to consist only of ASCII letters, digits, '-' and '_'. Example: > @@ -681,7 +681,7 @@ similar to -1. > :let shortblob = myblob[2:2] " Blob with one byte: 0z22 :let otherblob = myblob[:] " make a copy of the Blob -If the first index is beyond the last byte of the Blob or the second byte is +If the first index is beyond the last byte of the Blob or the second index is before the first index, the result is an empty Blob. There is no error message. @@ -704,8 +704,8 @@ The length of the replaced bytes must be exactly the same as the value provided. *E972* To change part of a blob you can specify the first and last byte to be -modified. The value must at least have the number of bytes in the range: > - :let blob[3:5] = [3, 4, 5] +modified. The value must have the same number of bytes in the range: > + :let blob[3:5] = 0z334455 You can also use the functions |add()|, |remove()| and |insert()|. @@ -840,8 +840,8 @@ Example: > All expressions within one level are parsed from left to right. +------------------------------------------------------------------------------ expr1 *expr1* *ternary* *E109* ------ expr2 ? expr1 : expr1 @@ -867,8 +867,8 @@ You should always put a space before the ':', otherwise it can be mistaken for use in a variable such as "a:1". +------------------------------------------------------------------------------ expr2 and expr3 *expr2* *expr3* ---------------- expr3 || expr3 .. logical OR *expr-barbar* expr4 && expr4 .. logical AND *expr-&&* @@ -906,8 +906,8 @@ This is valid whether "b" has been defined or not. The second clause will only be evaluated if "b" has been defined. +------------------------------------------------------------------------------ expr4 *expr4* ------ expr5 {cmp} expr5 @@ -1010,8 +1010,9 @@ can be matched like an ordinary character. Examples: "foo\nbar" =~ "\\n" evaluates to 0 +------------------------------------------------------------------------------ expr5 and expr6 *expr5* *expr6* ---------------- + expr6 + expr6 Number addition, |List| or |Blob| concatenation *expr-+* expr6 - expr6 Number subtraction *expr--* expr6 . expr6 String concatenation *expr-.* @@ -1064,8 +1065,9 @@ None of these work for |Funcref|s. . and % do not work for Float. *E804* +------------------------------------------------------------------------------ expr7 *expr7* ------ + ! expr7 logical NOT *expr-!* - expr7 unary minus *expr-unary--* + expr7 unary plus *expr-unary-+* @@ -1082,8 +1084,9 @@ These three can be repeated and mixed. Examples: --9 == 9 +------------------------------------------------------------------------------ expr8 *expr8* ------ + This expression is either |expr9| or a sequence of the alternatives below, in any order. E.g., these are all possible: expr8[expr1].name @@ -1228,11 +1231,15 @@ And NOT: > \ ->map(mapexpr) \ ->sort() \ ->join() -< + +When using the lambda form there must be no white space between the } and the +(. + *expr9* +------------------------------------------------------------------------------ number ------- + number number constant *expr-number* *0x* *hex-number* *0o* *octal-number* *binary-number* @@ -1294,9 +1301,9 @@ function. Example: > < 7.853981633974483e-01 - +------------------------------------------------------------------------------ string *string* *String* *expr-string* *E114* ------- + "string" string constant *expr-quote* Note that double quotes are used. @@ -1335,16 +1342,17 @@ encodings. Use "\u00ff" to store character 255 correctly as UTF-8. Note that "\000" and "\x00" force the end of the string. +------------------------------------------------------------------------------ blob-literal *blob-literal* *E973* ------------- Hexadecimal starting with 0z or 0Z, with an arbitrary number of bytes. The sequence must be an even number of hex characters. Example: > :let b = 0zFF00ED015DAF +------------------------------------------------------------------------------ literal-string *literal-string* *E115* ---------------- + 'string' string constant *expr-'* Note that single quotes are used. @@ -1358,8 +1366,9 @@ to be doubled. These two commands are equivalent: > if a =~ '\s*' +------------------------------------------------------------------------------ option *expr-option* *E112* *E113* ------- + &option option value, local value if possible &g:option global option value &l:option local option value @@ -1373,8 +1382,9 @@ and there is no buffer-local or window-local value, the global value is used anyway. +------------------------------------------------------------------------------ register *expr-register* *@r* --------- + @r contents of register 'r' The result is the contents of the named register, as a single string. @@ -1391,8 +1401,9 @@ nesting *expr-nesting* *E110* (expr1) nested expression +------------------------------------------------------------------------------ environment variable *expr-env* --------------------- + $VAR environment variable The String value of any environment variable. When it is not defined, the @@ -1417,20 +1428,23 @@ The first one probably doesn't echo anything, the second echoes the $shell variable (if your shell supports it). +------------------------------------------------------------------------------ internal variable *expr-variable* ------------------ + variable internal variable See below |internal-variables|. +------------------------------------------------------------------------------ function call *expr-function* *E116* *E118* *E119* *E120* -------------- + function(expr1, ...) function call See below |functions|. +------------------------------------------------------------------------------ lambda expression *expr-lambda* *lambda* ------------------ + {args -> expr1} lambda expression A lambda expression creates a new unnamed function which returns the result of @@ -1521,7 +1535,7 @@ specified by what is prepended: |tabpage-variable| t: Local to the current tab page. |global-variable| g: Global. |local-variable| l: Local to a function. -|script-variable| s: Local to a |:source|'ed Vim script. +|script-variable| s: Local to a |:source|d Vim script. |function-argument| a: Function argument (only inside a function). |vim-variable| v: Global, predefined by Vim. @@ -1704,17 +1718,13 @@ v:charconvert_to Only valid while evaluating the 'charconvert' option. *v:cmdarg* *cmdarg-variable* -v:cmdarg This variable is used for two purposes: - 1. The extra arguments given to a file read/write command. - Currently these are "++enc=" and "++ff=". This variable is - set before an autocommand event for a file read/write - command is triggered. There is a leading space to make it - possible to append this variable directly after the - read/write command. Note: The "+cmd" argument isn't - included here, because it will be executed anyway. - 2. When printing a PostScript file with ":hardcopy" this is - the argument for the ":hardcopy" command. This can be used - in 'printexpr'. +v:cmdarg + The extra arguments ("++p", "++enc=", "++ff=") given to a file + read/write command. This is set before an autocommand event + for a file read/write command is triggered. There is a + leading space to make it possible to append this variable + directly after the read/write command. Note: "+cmd" isn't + included here, because it will be executed anyway. *v:collate* *collate-variable* v:collate The current locale setting for collation order of the runtime @@ -1777,7 +1787,7 @@ v:exiting Exit code, or |v:null| before invoking the |VimLeavePre| and |VimLeave| autocmds. See |:q|, |:x| and |:cquit|. Example: > :au VimLeave * echo "Exit value is " .. v:exiting - +< *v:echospace* *echospace-variable* v:echospace Number of screen cells that can be used for an `:echo` message in the last screen line before causing the |hit-enter-prompt|. @@ -1912,17 +1922,16 @@ v:fname_in The name of the input file. Valid while evaluating: 'charconvert' file to be converted 'diffexpr' original file 'patchexpr' original file - 'printexpr' file to be printed And set to the swap file name for |SwapExists|. *v:fname_out* *fname_out-variable* v:fname_out The name of the output file. Only valid while evaluating: option used for ~ - 'charconvert' resulting converted file (*) + 'charconvert' resulting converted file [1] 'diffexpr' output of diff 'patchexpr' resulting patched file - (*) When doing conversion for a write command (e.g., ":w + [1] When doing conversion for a write command (e.g., ":w file") it will be equal to v:fname_in. When doing conversion for a read command (e.g., ":e file") it will be a temporary file and different from v:fname_in. @@ -1992,10 +2001,10 @@ v:lc_time The current locale setting for time messages of the runtime command. See |multi-lang|. *v:lnum* *lnum-variable* -v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr' and - 'indentexpr' expressions, tab page number for 'guitablabel' - and 'guitabtooltip'. Only valid while one of these - expressions is being evaluated. Read-only when in the +v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr', + 'indentexpr' and 'statuscolumn' expressions, tab page number + for 'guitablabel' and 'guitabtooltip'. Only valid while one of + these expressions is being evaluated. Read-only when in the |sandbox|. *v:lua* *lua-variable* @@ -2129,6 +2138,10 @@ v:register The name of the register in effect for the current normal mode '*' or '+'. Also see |getreg()| and |setreg()| + *v:relnum* *relnum-variable* +v:relnum Relative line number for the 'statuscolumn' expression. + Read-only. + *v:scrollstart* *scrollstart-variable* v:scrollstart String describing the script or function that caused the screen to scroll up. It's only set when it is empty, thus the @@ -2138,9 +2151,11 @@ v:scrollstart String describing the script or function that caused the hit-enter prompt. *v:servername* *servername-variable* -v:servername Primary listen-address of the current Nvim instance, the first - item returned by |serverlist()|. Can be set by |--listen| or - |$NVIM_LISTEN_ADDRESS| (deprecated) at startup. +v:servername Primary listen-address of Nvim, the first item returned by + |serverlist()|. Usually this is the named pipe created by Nvim + at |startup| or given by |--listen| (or the deprecated + |$NVIM_LISTEN_ADDRESS| env var). + See also |serverstart()| |serverstop()|. Read-only. @@ -2280,6 +2295,13 @@ v:version Vim version number: major version times 100 plus minor :if has("nvim-0.2.1") < + *v:virtnum* *virtnum-variable* +v:virtnum Virtual line number for the 'statuscolumn' expression. + Negative when drawing the status column for virtual lines, zero + when drawing an actual buffer line, and positive when drawing + the wrapped part of a buffer line. + Read-only. + *v:vim_did_enter* *vim_did_enter-variable* v:vim_did_enter 0 during startup, 1 just before |VimEnter|. Read-only. @@ -2309,397 +2331,10 @@ help file: |builtin-functions|. 5. Defining functions *user-function* New functions can be defined. These can be called just like builtin -functions. The function executes a sequence of Ex commands. Normal mode -commands can be executed with the |:normal| command. - -The function name must start with an uppercase letter, to avoid confusion with -builtin functions. To prevent from using the same name in different scripts -avoid obvious, short names. A good habit is to start the function name with -the name of the script, e.g., "HTMLcolor()". - -It's also possible to use curly braces, see |curly-braces-names|. And the -|autoload| facility is useful to define a function only when it's called. - - *local-function* -A function local to a script must start with "s:". A local script function -can only be called from within the script and from functions, user commands -and autocommands defined in the script. It is also possible to call the -function from a mapping defined in the script, but then |<SID>| must be used -instead of "s:" when the mapping is expanded outside of the script. -There are only script-local functions, no buffer-local or window-local -functions. - - *:fu* *:function* *E128* *E129* *E123* -:fu[nction] List all functions and their arguments. - -:fu[nction][!] {name} List function {name}, annotated with line numbers - unless "!" is given. - {name} may be a |Dictionary| |Funcref| entry: > - :function dict.init - -:fu[nction] /{pattern} List functions with a name matching {pattern}. - Example that lists all functions ending with "File": > - :function /File$ -< - *:function-verbose* -When 'verbose' is non-zero, listing a function will also display where it was -last defined. Example: > +functions. The function takes arguments, executes a sequence of Ex commands +and can return a value. - :verbose function SetFileTypeSH - function SetFileTypeSH(name) - Last set from /usr/share/vim/vim-7.0/filetype.vim -< -See |:verbose-cmd| for more information. - - *E124* *E125* *E853* *E884* -:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure] - Define a new function by the name {name}. The body of - the function follows in the next lines, until the - matching |:endfunction|. - - The name must be made of alphanumeric characters and - '_', and must start with a capital or "s:" (see - above). Note that using "b:" or "g:" is not allowed. - (since patch 7.4.260 E884 is given if the function - name has a colon in the name, e.g. for "foo:bar()". - Before that patch no error was given). - - {name} can also be a |Dictionary| entry that is a - |Funcref|: > - :function dict.init(arg) -< "dict" must be an existing dictionary. The entry - "init" is added if it didn't exist yet. Otherwise [!] - is required to overwrite an existing function. The - result is a |Funcref| to a numbered function. The - function can only be used with a |Funcref| and will be - deleted if there are no more references to it. - *E127* *E122* - When a function by this name already exists and [!] is - not used an error message is given. There is one - exception: When sourcing a script again, a function - that was previously defined in that script will be - silently replaced. - When [!] is used, an existing function is silently - replaced. Unless it is currently being executed, that - is an error. - NOTE: Use ! wisely. If used without care it can cause - an existing function to be replaced unexpectedly, - which is hard to debug. - - For the {arguments} see |function-argument|. - - *:func-range* *a:firstline* *a:lastline* - When the [range] argument is added, the function is - expected to take care of a range itself. The range is - passed as "a:firstline" and "a:lastline". If [range] - is excluded, ":{range}call" will call the function for - each line in the range, with the cursor on the start - of each line. See |function-range-example|. - The cursor is still moved to the first line of the - range, as is the case with all Ex commands. - *:func-abort* - When the [abort] argument is added, the function will - abort as soon as an error is detected. - *:func-dict* - When the [dict] argument is added, the function must - be invoked through an entry in a |Dictionary|. The - local variable "self" will then be set to the - dictionary. See |Dictionary-function|. - *:func-closure* *E932* - When the [closure] argument is added, the function - can access variables and arguments from the outer - scope. This is usually called a closure. In this - example Bar() uses "x" from the scope of Foo(). It - remains referenced even after Foo() returns: > - :function! Foo() - : let x = 0 - : function! Bar() closure - : let x += 1 - : return x - : endfunction - : return funcref('Bar') - :endfunction - - :let F = Foo() - :echo F() -< 1 > - :echo F() -< 2 > - :echo F() -< 3 - - *function-search-undo* - The last used search pattern and the redo command "." - will not be changed by the function. This also - implies that the effect of |:nohlsearch| is undone - when the function returns. - - *:endf* *:endfunction* *E126* *E193* *W22* -:endf[unction] [argument] - The end of a function definition. Best is to put it - on a line by its own, without [argument]. - - [argument] can be: - | command command to execute next - \n command command to execute next - " comment always ignored - anything else ignored, warning given when - 'verbose' is non-zero - The support for a following command was added in Vim - 8.0.0654, before that any argument was silently - ignored. - - To be able to define a function inside an `:execute` - command, use line breaks instead of |:bar|: > - :exe "func Foo()\necho 'foo'\nendfunc" -< - *:delf* *:delfunction* *E131* *E933* -:delf[unction][!] {name} - Delete function {name}. - {name} can also be a |Dictionary| entry that is a - |Funcref|: > - :delfunc dict.init -< This will remove the "init" entry from "dict". The - function is deleted if there are no more references to - it. - With the ! there is no error if the function does not - exist. - *:retu* *:return* *E133* -:retu[rn] [expr] Return from a function. When "[expr]" is given, it is - evaluated and returned as the result of the function. - If "[expr]" is not given, the number 0 is returned. - When a function ends without an explicit ":return", - the number 0 is returned. - Note that there is no check for unreachable lines, - thus there is no warning if commands follow ":return". - - If the ":return" is used after a |:try| but before the - matching |:finally| (if present), the commands - following the ":finally" up to the matching |:endtry| - are executed first. This process applies to all - nested ":try"s inside the function. The function - returns at the outermost ":endtry". - - *function-argument* *a:var* -An argument can be defined by giving its name. In the function this can then -be used as "a:name" ("a:" for argument). - *a:0* *a:1* *a:000* *E740* *...* -Up to 20 arguments can be given, separated by commas. After the named -arguments an argument "..." can be specified, which means that more arguments -may optionally be following. In the function the extra arguments can be used -as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which -can be 0). "a:000" is set to a |List| that contains these arguments. Note -that "a:1" is the same as "a:000[0]". - *E742* -The a: scope and the variables in it cannot be changed, they are fixed. -However, if a composite type is used, such as |List| or |Dictionary| , you can -change their contents. Thus you can pass a |List| to a function and have the -function add an item to it. If you want to make sure the function cannot -change a |List| or |Dictionary| use |:lockvar|. - -It is also possible to define a function without any arguments. You must -still supply the () then. - -It is allowed to define another function inside a function body. - - *optional-function-argument* -You can provide default values for positional named arguments. This makes -them optional for function calls. When a positional argument is not -specified at a call, the default expression is used to initialize it. -This only works for functions declared with |function|, not for -lambda expressions |expr-lambda|. - -Example: > - function Something(key, value = 10) - echo a:key .. ": " .. a:value - endfunction - call Something('empty') "empty: 10" - call Something('key', 20) "key: 20" - -The argument default expressions are evaluated at the time of the function -call, not definition. Thus it is possible to use an expression which is -invalid the moment the function is defined. The expressions are also only -evaluated when arguments are not specified during a call. - - *E989* -Optional arguments with default expressions must occur after any mandatory -arguments. You can use "..." after all optional named arguments. - -It is possible for later argument defaults to refer to prior arguments, -but not the other way around. They must be prefixed with "a:", as with all -arguments. - -Example that works: > - :function Okay(mandatory, optional = a:mandatory) - :endfunction -Example that does NOT work: > - :function NoGood(first = a:second, second = 10) - :endfunction -< -When not using "...", the number of arguments in a function call must be at -least equal to the number of mandatory named arguments. When using "...", the -number of arguments may be larger than the total of mandatory and optional -arguments. - - *local-variables* -Inside a function local variables can be used. These will disappear when the -function returns. Global variables need to be accessed with "g:". - -Example: > - :function Table(title, ...) - : echohl Title - : echo a:title - : echohl None - : echo a:0 .. " items:" - : for s in a:000 - : echon ' ' .. s - : endfor - :endfunction - -This function can then be called with: > - call Table("Table", "line1", "line2") - call Table("Empty Table") - -To return more than one value, return a |List|: > - :function Compute(n1, n2) - : if a:n2 == 0 - : return ["fail", 0] - : endif - : return ["ok", a:n1 / a:n2] - :endfunction - -This function can then be called with: > - :let [success, div] = Compute(102, 6) - :if success == "ok" - : echo div - :endif -< - *:cal* *:call* *E107* *E117* -:[range]cal[l] {name}([arguments]) - Call a function. The name of the function and its arguments - are as specified with `:function`. Up to 20 arguments can be - used. The returned value is discarded. - Without a range and for functions that accept a range, the - function is called once. When a range is given the cursor is - positioned at the start of the first line before executing the - function. - When a range is given and the function doesn't handle it - itself, the function is executed for each line in the range, - with the cursor in the first column of that line. The cursor - is left at the last line (possibly moved by the last function - call). The arguments are re-evaluated for each line. Thus - this works: - *function-range-example* > - :function Mynumber(arg) - : echo line(".") .. " " .. a:arg - :endfunction - :1,5call Mynumber(getline(".")) -< - The "a:firstline" and "a:lastline" are defined anyway, they - can be used to do something different at the start or end of - the range. - - Example of a function that handles the range itself: > - - :function Cont() range - : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ ' - :endfunction - :4,8call Cont() -< - This function inserts the continuation character "\" in front - of all the lines in the range, except the first one. - - When the function returns a composite value it can be further - dereferenced, but the range will not be used then. Example: > - :4,8call GetDict().method() -< Here GetDict() gets the range but method() does not. - - *E132* -The recursiveness of user functions is restricted with the |'maxfuncdepth'| -option. - -It is also possible to use `:eval`. It does not support a range, but does -allow for method chaining, e.g.: > - eval GetList()->Filter()->append('$') - - -AUTOMATICALLY LOADING FUNCTIONS ~ - *autoload-functions* -When using many or large functions, it's possible to automatically define them -only when they are used. There are two methods: with an autocommand and with -the "autoload" directory in 'runtimepath'. - - -Using an autocommand ~ - -This is introduced in the user manual, section |41.14|. - -The autocommand is useful if you have a plugin that is a long Vim script file. -You can define the autocommand and quickly quit the script with `:finish`. -That makes Vim startup faster. The autocommand should then load the same file -again, setting a variable to skip the `:finish` command. - -Use the FuncUndefined autocommand event with a pattern that matches the -function(s) to be defined. Example: > - - :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim - -The file "~/vim/bufnetfuncs.vim" should then define functions that start with -"BufNet". Also see |FuncUndefined|. - - -Using an autoload script ~ - *autoload* *E746* -This is introduced in the user manual, section |41.15|. - -Using a script in the "autoload" directory is simpler, but requires using -exactly the right file name. A function that can be autoloaded has a name -like this: > - - :call filename#funcname() - -When such a function is called, and it is not defined yet, Vim will search the -"autoload" directories in 'runtimepath' for a script file called -"filename.vim". For example "~/.config/nvim/autoload/filename.vim". That -file should then define the function like this: > - - function filename#funcname() - echo "Done!" - endfunction - -The file name and the name used before the # in the function must match -exactly, and the defined function must have the name exactly as it will be -called. - -It is possible to use subdirectories. Every # in the function name works like -a path separator. Thus when calling a function: > - - :call foo#bar#func() - -Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'. - -This also works when reading a variable that has not been set yet: > - - :let l = foo#bar#lvar - -However, when the autoload script was already loaded it won't be loaded again -for an unknown variable. - -When assigning a value to such a variable nothing special happens. This can -be used to pass settings to the autoload script before it's loaded: > - - :let foo#bar#toggle = 1 - :call foo#bar#func() - -Note that when you make a mistake and call a function that is supposed to be -defined in an autoload script, but the script doesn't actually define the -function, you will get an error message for the missing function. If you fix -the autoload script it won't be automatically loaded again. Either restart -Vim or manually source the script. - -Also note that if you have two script files, and one calls a function in the -other and vice versa, before the used function is defined, it won't work. -Avoid using the autoload functionality at the toplevel. +You can find most information about defining functions in |userfunc.txt|. ============================================================================== 6. Curly braces names *curly-braces-names* @@ -2915,7 +2550,7 @@ text... echo 'done' endif END -< Results in: ["if ok", " echo 'done'", "endif"] +< Results in: `["if ok", " echo 'done'", "endif"]` The marker must line up with "let" and the indentation of the first line is removed from all the text lines. Specifically: all the leading indentation exactly @@ -3046,6 +2681,8 @@ text... [depth] is relevant when locking a |List| or |Dictionary|. It specifies how deep the locking goes: + 0 Lock the variable {name} but not its + value. 1 Lock the |List| or |Dictionary| itself, cannot add or remove items, but can still change their values. @@ -3059,7 +2696,14 @@ text... |Dictionary|, one level deeper. The default [depth] is 2, thus when {name} is a |List| or |Dictionary| the values cannot be changed. - *E743* + + Example with [depth] 0: > + let mylist = [1, 2, 3] + lockvar 0 mylist + let mylist[0] = 77 " OK + call add(mylist, 4] " OK + let mylist = [7, 8, 9] " Error! +< *E743* For unlimited depth use [!] and omit [depth]. However, there is a maximum depth of 100 to catch loops. @@ -3080,6 +2724,8 @@ text... Unlock the internal variable {name}. Does the opposite of |:lockvar|. + No error is given if {name} does not exist. + :if {expr1} *:if* *:end* *:endif* *:en* *E171* *E579* *E580* :en[dif] Execute the commands until the next matching `:else` or `:endif` if {expr1} evaluates to non-zero. @@ -3167,6 +2813,9 @@ text... iterate over. Unlike with |List|, modifying the |Blob| does not affect the iteration. + When {object} is a |String| each item is a string with + one character, plus any combining characters. + :for [{var1}, {var2}, ...] in {listlist} :endfo[r] Like `:for` above, but each item in {listlist} must be @@ -3556,7 +3205,7 @@ this pending exception or command is discarded. For examples see |throw-catch| and |try-finally|. -NESTING OF TRY CONDITIONALS *try-nesting* +NESTING OF TRY CONDITIONALS *try-nesting* Try conditionals can be nested arbitrarily. That is, a complete try conditional can be put into the try block, a catch clause, or the finally @@ -4500,7 +4149,7 @@ This example sorts lines with a specific compare function. > As a one-liner: > :call setline(1, sort(getline(1, '$'), function("Strcmp"))) - +< scanf() replacement ~ *sscanf* diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 7fff74a963..a53c287d48 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -148,6 +148,7 @@ variables can be used to overrule the filetype used for certain extensions: *.fs g:filetype_fs |ft-forth-syntax| *.i g:filetype_i |ft-progress-syntax| *.inc g:filetype_inc + *.lsl g:filetype_lsl *.m g:filetype_m |ft-mathematica-syntax| *.mod g:filetype_mod *.p g:filetype_p |ft-pascal-syntax| @@ -175,15 +176,13 @@ This means that the contents of compressed files are not inspected. *new-filetype* If a file type that you want to use is not detected yet, there are a few ways -to add it. In any way, it's better not to modify the $VIMRUNTIME/filetype.lua -or $VIMRUNTIME/filetype.vim files. They will be overwritten when installing a -new version of Nvim. The following explains the legacy Vim mechanism (enabled -if |do_legacy_filetype| is set). For Nvim's default mechanism, see -|vim.filetype.add()|. +to add it. The recommended way is to use |vim.filetype.add()| to add it to +Nvim's builtin filetype detection mechanism. If you want to handle the +detection manually, proceed as follows: A. If you want to overrule all default file type checks. This works by writing one file for each filetype. The disadvantage is that - there can be many files. The advantage is that you can simply drop this + there can be many files. The advantage is that you can simply drop this file in the right directory to make it work. *ftdetect* 1. Create your user runtime directory. You would normally use the first @@ -273,28 +272,14 @@ D. If your filetype can only be detected by inspecting the contents of the means that your rules override the default rules in $VIMRUNTIME/scripts.vim. - *remove-filetype* -If a file type is detected that is wrong for you, install a filetype.lua, -filetype.vim or scripts.vim to catch it (see above). You can set 'filetype' to -a non-existing name to avoid that it will be set later anyway: > - :set filetype=ignored - -If you are setting up a system with many users, and you don't want each user -to add/remove the same filetypes, consider writing the filetype.vim and -scripts.vim files in a runtime directory that is used for everybody. Check -the 'runtimepath' for a directory to use. If there isn't one, set -'runtimepath' in the |system-vimrc|. Be careful to keep the default -directories! - - *g:do_legacy_filetype* -To disable Nvim's default filetype detection and revert to Vim's legacy -filetype detection, add the following to your |init.vim|: > - let g:do_legacy_filetype = 1 -< *g:did_load_filetypes* + *remove-filetype* +If a file type is detected that is wrong for you, you can set 'filetype' to +a non-existing name such as `ignored` to avoid that it will be set later anyway. + + *g:did_load_filetypes* The builtin filetype detection provided by Nvim can be disabled by setting -the `did_load_filetypes` global variable. If this variable exists, neither -the default `$VIMRUNTIME/filetype.lua` nor the legacy `$VIMRUNTIME/filetype.vim` -will run. +the `did_load_filetypes` global variable. If this variable exists, the default +`$VIMRUNTIME/filetype.lua` will not run. *plugin-details* The "plugin" directory can be in any of the directories in the 'runtimepath' @@ -549,7 +534,7 @@ used. For example, to set the dialect to a default of "fblite" but still allow for any #lang directive overrides, use the following command: > - let g:freebasic_lang = "fblite" + let g:freebasic_lang = "fblite" GIT COMMIT *ft-gitcommit-plugin* @@ -586,12 +571,12 @@ Local mappings: to the end of the file in Normal mode. This means "> " is inserted in each line. -MAN *ft-man-plugin* *:Man* *man.vim* +MAN *ft-man-plugin* *:Man* *man.lua* View manpages in Nvim. Supports highlighting, completion, locales, and navigation. Also see |find-manpage|. -man.vim will always attempt to reuse the closest man window (above/left) but +man.lua will always attempt to reuse the closest man window (above/left) but otherwise create a split. The case sensitivity of completion is controlled by 'fileignorecase'. diff --git a/runtime/doc/fold.txt b/runtime/doc/fold.txt index 9e3d78faff..35a3be35fb 100644 --- a/runtime/doc/fold.txt +++ b/runtime/doc/fold.txt @@ -116,6 +116,11 @@ method can be very slow! Try to avoid the "=", "a" and "s" return values, since Vim often has to search backwards for a line for which the fold level is defined. This can be slow. +If the 'foldexpr' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Examples: > + set foldexpr=s:MyFoldExpr() + set foldexpr=<SID>SomeFoldExpr() +< An example of using "a1" and "s1": For a multi-line C comment, a line containing "/*" would return "a1" to start a fold, and a line containing "*/" would return "s1" to end the fold after that line: > @@ -491,7 +496,7 @@ is evaluated to obtain the text displayed for a closed fold. Example: > This shows the first line of the fold, with "/*", "*/" and "{{{" removed. Note the use of backslashes to avoid some characters to be interpreted by the -":set" command. It's simpler to define a function and call that: > +":set" command. It is much simpler to define a function and call it: > :set foldtext=MyFoldText() :function MyFoldText() @@ -521,6 +526,11 @@ The resulting line is truncated to fit in the window, it never wraps. When there is room after the text, it is filled with the character specified by 'fillchars'. +If the 'foldtext' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Examples: > + set foldtext=s:MyFoldText() + set foldtext=<SID>SomeFoldText() +< Note that backslashes need to be used for characters that the ":set" command handles differently: Space, backslash and double-quote. |option-backslash| @@ -576,6 +586,11 @@ line is folded, it cannot be displayed there. Many movement commands handle a sequence of folded lines like an empty line. For example, the "w" command stops once in the first column. +When starting a search in a closed fold it will not find a match in the +current fold. It's like a forward search always starts from the end of the +closed fold, while a backwards search starts from the start of the closed +fold. + When in Insert mode, the cursor line is never folded. That allows you to see what you type! diff --git a/runtime/doc/ft_ada.txt b/runtime/doc/ft_ada.txt index f6dfa708fb..3321228009 100644 --- a/runtime/doc/ft_ada.txt +++ b/runtime/doc/ft_ada.txt @@ -51,7 +51,7 @@ for a complete list. To enable them, assign a value to the option. For example, to turn one on: > > let g:ada_standard_types = 1 -> + To disable them use ":unlet". Example: > > unlet g:ada_standard_types @@ -288,7 +288,7 @@ g:ada_rainbow_color bool (true when exists) rainbow_parenthesis for this to work. *g:ada_folding* -g:ada_folding set ('sigpft') +g:ada_folding set ("sigpft") Use folding for Ada sources. 's': activate syntax folding on load 'p': fold packages @@ -296,10 +296,10 @@ g:ada_folding set ('sigpft') 't': fold types 'c': fold conditionals 'g': activate gnat pretty print folding on load - 'i': lone 'is' folded with line above - 'b': lone 'begin' folded with line above - 'p': lone 'private' folded with line above - 'x': lone 'exception' folded with line above + 'i': lone "is" folded with line above + 'b': lone "begin" folded with line above + 'p': lone "private" folded with line above + 'x': lone "exception" folded with line above 'i': activate indent folding on load Note: Syntax folding is in an early (unusable) stage and @@ -334,10 +334,10 @@ g:ada_omni_with_keywords completion (|i_CTRL-X_CTRL-U|). *g:ada_extended_tagging* -g:ada_extended_tagging enum ('jump', 'list') +g:ada_extended_tagging enum ("jump", "list") use extended tagging, two options are available - 'jump': use tjump to jump. - 'list': add tags quick fix list. + "jump": use tjump to jump. + "list": add tags quick fix list. Normal tagging does not support function or operator overloading as these features are not available in C and tagging was originally developed for C. @@ -359,8 +359,8 @@ g:ada_with_gnat_project_files bool (true when exists) *g:ada_default_compiler* g:ada_default_compiler string - set default compiler. Currently supported are 'gnat' and - 'decada'. + set default compiler. Currently supported are "gnat" and + "decada". An "exists" type is a boolean considered true when the variable is defined and false when the variable is undefined. The value to which the variable is set @@ -406,14 +406,14 @@ makes no difference. g:gnat object Control object which manages GNAT compiles. The object is created when the first Ada source code is loaded provided - that |g:ada_default_compiler| is set to 'gnat'. See + that |g:ada_default_compiler| is set to "gnat". See |gnat_members| for details. *g:decada* g:decada object Control object which manages Dec Ada compiles. The object is created when the first Ada source code is loaded provided - that |g:ada_default_compiler| is set to 'decada'. See + that |g:ada_default_compiler| is set to "decada". See |decada_members| for details. ------------------------------------------------------------------------------ @@ -459,11 +459,11 @@ ada#List_Tag([{line}, {col}]) *ada#Listtags()* ada#Jump_Tag ({ident}, {mode}) *ada#Jump_Tag()* List all occurrences of the Ada entity under the cursor (or at given line/column) in the tag jump list. Mode can either be - 'tjump' or 'stjump'. + "tjump" or "stjump". ada#Create_Tags ({option}) *ada#Create_Tags()* - Creates tag file using Ctags. The option can either be 'file' - for the current file, 'dir' for the directory of the current + Creates tag file using Ctags. The option can either be "file" + for the current file, "dir" for the directory of the current file or a file name. gnat#Insert_Tags_Header() *gnat#Insert_Tags_Header()* @@ -486,25 +486,25 @@ You can optionally install the following extra plug-ins. They work well with Ada and enhance the ability of the Ada mode: backup.vim - http://www.vim.org/scripts/script.php?script_id=1537 + https://www.vim.org/scripts/script.php?script_id=1537 Keeps as many backups as you like so you don't have to. -rainbow_parenthsis.vim - http://www.vim.org/scripts/script.php?script_id=1561 +rainbow_parenthesis.vim + https://www.vim.org/scripts/script.php?script_id=1561 Very helpful since Ada uses only '(' and ')'. nerd_comments.vim - http://www.vim.org/scripts/script.php?script_id=1218 + https://www.vim.org/scripts/script.php?script_id=1218 Excellent commenting and uncommenting support for almost any programming language. matchit.vim - http://www.vim.org/scripts/script.php?script_id=39 + https://www.vim.org/scripts/script.php?script_id=39 '%' jumping for any language. The normal '%' jump only works for '{}' style languages. The Ada mode will set the needed search patterns. taglist.vim - http://www.vim.org/scripts/script.php?script_id=273 + https://www.vim.org/scripts/script.php?script_id=273 Source code explorer sidebar. There is a patch for Ada available. The GNU Ada Project distribution (http://gnuada.sourceforge.net) of Vim diff --git a/runtime/doc/ft_rust.txt b/runtime/doc/ft_rust.txt index 5c8782ec7a..a5d5b558dc 100644 --- a/runtime/doc/ft_rust.txt +++ b/runtime/doc/ft_rust.txt @@ -1,70 +1,70 @@ -*ft_rust.txt* For Vim version 8.1. Last change: 2017 Nov 02 +*ft_rust.txt* Nvim This is documentation for the Rust filetype plugin. ============================================================================== -CONTENTS *rust* +CONTENTS *rust* -1. Introduction |rust-intro| -2. Settings |rust-settings| -3. Commands |rust-commands| -4. Mappings |rust-mappings| +1. Introduction |rust-intro| +2. Settings |rust-settings| +3. Commands |rust-commands| +4. Mappings |rust-mappings| ============================================================================== -INTRODUCTION *rust-intro* +INTRODUCTION *rust-intro* This plugin provides syntax and supporting functionality for the Rust filetype. ============================================================================== -SETTINGS *rust-settings* +SETTINGS *rust-settings* This plugin has a few variables you can define in your vimrc that change the behavior of the plugin. - *g:rustc_path* + *g:rustc_path* g:rustc_path~ Set this option to the path to rustc for use in the |:RustRun| and |:RustExpand| commands. If unset, "rustc" will be located in $PATH: > let g:rustc_path = $HOME .. "/bin/rustc" < - *g:rustc_makeprg_no_percent* + *g:rustc_makeprg_no_percent* g:rustc_makeprg_no_percent~ Set this option to 1 to have 'makeprg' default to "rustc" instead of "rustc %": > let g:rustc_makeprg_no_percent = 1 < - *g:rust_conceal* + *g:rust_conceal* g:rust_conceal~ Set this option to turn on the basic |conceal| support: > let g:rust_conceal = 1 < - *g:rust_conceal_mod_path* + *g:rust_conceal_mod_path* g:rust_conceal_mod_path~ Set this option to turn on |conceal| for the path connecting token "::": > let g:rust_conceal_mod_path = 1 < - *g:rust_conceal_pub* + *g:rust_conceal_pub* g:rust_conceal_pub~ Set this option to turn on |conceal| for the "pub" token: > let g:rust_conceal_pub = 1 < - *g:rust_recommended_style* + *g:rust_recommended_style* g:rust_recommended_style~ - Set this option to enable vim indentation and textwidth settings to - conform to style conventions of the rust standard library (i.e. use 4 - spaces for indents and sets 'textwidth' to 99). This option is enabled + Set this option to enable vim indentation and textwidth settings to + conform to style conventions of the rust standard library (i.e. use 4 + spaces for indents and sets 'textwidth' to 99). This option is enabled by default. To disable it: > let g:rust_recommended_style = 0 < - *g:rust_fold* + *g:rust_fold* g:rust_fold~ Set this option to turn on |folding|: > let g:rust_fold = 1 @@ -76,53 +76,53 @@ g:rust_fold~ 2 Braced blocks are folded. 'foldlevel' is left at the global value (all folds are closed by default). - *g:rust_bang_comment_leader* + *g:rust_bang_comment_leader* g:rust_bang_comment_leader~ Set this option to 1 to preserve the leader on multi-line doc comments using the /*! syntax: > let g:rust_bang_comment_leader = 1 < - *g:ftplugin_rust_source_path* + *g:ftplugin_rust_source_path* g:ftplugin_rust_source_path~ Set this option to a path that should be prepended to 'path' for Rust source files: > let g:ftplugin_rust_source_path = $HOME .. '/dev/rust' < - *g:rustfmt_command* + *g:rustfmt_command* g:rustfmt_command~ - Set this option to the name of the 'rustfmt' executable in your $PATH. If - not specified it defaults to 'rustfmt' : > + Set this option to the name of the "rustfmt" executable in your $PATH. If + not specified it defaults to "rustfmt" : > let g:rustfmt_command = 'rustfmt' < - *g:rustfmt_autosave* + *g:rustfmt_autosave* g:rustfmt_autosave~ Set this option to 1 to run |:RustFmt| automatically when saving a buffer. If not specified it defaults to 0 : > let g:rustfmt_autosave = 0 < - *g:rustfmt_fail_silently* + *g:rustfmt_fail_silently* g:rustfmt_fail_silently~ - Set this option to 1 to prevent 'rustfmt' from populating the + Set this option to 1 to prevent "rustfmt" from populating the |location-list| with errors. If not specified it defaults to 0: > let g:rustfmt_fail_silently = 0 < - *g:rustfmt_options* + *g:rustfmt_options* g:rustfmt_options~ - Set this option to a string of options to pass to 'rustfmt'. The - write-mode is already set to 'overwrite'. If not specified it + Set this option to a string of options to pass to "rustfmt". The + write-mode is already set to "overwrite". If not specified it defaults to '' : > let g:rustfmt_options = '' < - *g:rust_playpen_url* + *g:rust_playpen_url* g:rust_playpen_url~ Set this option to override the URL for the playpen to use: > let g:rust_playpen_url = 'https://play.rust-lang.org/' < - *g:rust_shortener_url* + *g:rust_shortener_url* g:rust_shortener_url~ Set this option to override the URL for the URL shortener: > let g:rust_shortener_url = 'https://is.gd/' @@ -130,9 +130,9 @@ g:rust_shortener_url~ ============================================================================== -COMMANDS *rust-commands* +COMMANDS *rust-commands* -:RustRun [args] *:RustRun* +:RustRun [args] *:RustRun* :RustRun! [rustc-args] [--] [args] Compiles and runs the current file. If it has unsaved changes, it will be saved first using |:update|. If the current file is @@ -150,7 +150,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustExpand [args] *:RustExpand* +:RustExpand [args] *:RustExpand* :RustExpand! [TYPE] [args] Expands the current file using --pretty and displays the results in a new split. If the current file has unsaved @@ -169,7 +169,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustEmitIr [args] *:RustEmitIr* +:RustEmitIr [args] *:RustEmitIr* Compiles the current file to LLVM IR and displays the results in a new split. If the current file has unsaved changes, it will be saved first using |:update|. If the current file is an @@ -180,7 +180,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustEmitAsm [args] *:RustEmitAsm* +:RustEmitAsm [args] *:RustEmitAsm* Compiles the current file to assembly and displays the results in a new split. If the current file has unsaved changes, it will be saved first using |:update|. If the current file is an @@ -191,7 +191,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustPlay *:RustPlay* +:RustPlay *:RustPlay* This command will only work if you have web-api.vim installed (available at https://github.com/mattn/webapi-vim). It sends the current selection, or if nothing is selected, the entirety of the @@ -204,7 +204,7 @@ COMMANDS *rust-commands* |g:rust_shortener_url| is the base URL for the shortener, by default "https://is.gd/" -:RustFmt *:RustFmt* +:RustFmt *:RustFmt* Runs |g:rustfmt_command| on the current buffer. If |g:rustfmt_options| is set then those will be passed to the executable. @@ -214,12 +214,12 @@ COMMANDS *rust-commands* |g:rustfmt_command|. If |g:rustfmt_fail_silently| is set to 1 then it will not populate the |location-list|. -:RustFmtRange *:RustFmtRange* +:RustFmtRange *:RustFmtRange* Runs |g:rustfmt_command| with selected range. See |:RustFmt| for any other information. ============================================================================== -MAPPINGS *rust-mappings* +MAPPINGS *rust-mappings* This plugin defines mappings for |[[| and |]]| to support hanging indents. diff --git a/runtime/doc/ft_sql.txt b/runtime/doc/ft_sql.txt index 335faf266e..21a244e67a 100644 --- a/runtime/doc/ft_sql.txt +++ b/runtime/doc/ft_sql.txt @@ -37,9 +37,10 @@ The SQL ftplugin provides a number of options to assist with file navigation. +------------------------------------------------------------------------------ 1.1 Matchit *sql-matchit* ------------ -The matchit plugin (http://www.vim.org/scripts/script.php?script_id=39) + +The matchit plugin (https://www.vim.org/scripts/script.php?script_id=39) provides many additional features and can be customized for different languages. The matchit plugin is configured by defining a local buffer variable, b:match_words. Pressing the % key while on various @@ -85,8 +86,9 @@ The following keywords are supported: > returns +------------------------------------------------------------------------------ 1.2 Text Object Motions *sql-object-motions* ------------------------ + Vim has a number of predefined keys for working with text |object-motions|. This filetype plugin attempts to translate these keys to maps which make sense for the SQL language. @@ -99,8 +101,9 @@ file): > [] move backwards to the previous 'end' +------------------------------------------------------------------------------ 1.3 Predefined Object Motions *sql-predefined-objects* ------------------------------ + Most relational databases support various standard features, tables, indices, triggers and stored procedures. Each vendor also has a variety of proprietary objects. The next set of maps have been created to help move between these @@ -166,8 +169,9 @@ with comments: > +------------------------------------------------------------------------------ 1.4 Macros *sql-macros* ----------- + Vim's feature to find macro definitions, |'define'|, is supported using this regular expression: > \c\<\(VARIABLE\|DECLARE\|IN\|OUT\|INOUT\)\> @@ -230,8 +234,9 @@ The majority of people work with only one vendor's database product, it would be nice to specify a default in your |init.vim|. +------------------------------------------------------------------------------ 2.1 SQLSetType *sqlsettype* *SQLSetType* --------------- + For the people that work with many different databases, it is nice to be able to flip between the various vendors rules (indent, syntax) on a per buffer basis, at any time. The ftplugin/sql.vim file defines this function: > @@ -244,7 +249,7 @@ key to complete the optional parameter. After typing the function name and a space, you can use the completion to supply a parameter. The function takes the name of the Vim script you want to source. Using the |cmdline-completion| feature, the SQLSetType function will -search the |'runtimepath'| for all Vim scripts with a name containing 'sql'. +search the |'runtimepath'| for all Vim scripts with a name containing "sql". This takes the guess work out of the spelling of the names. The following are examples: > :SQLSetType @@ -259,8 +264,9 @@ of available Vim script names: > :SQL<Tab><space><Tab> +------------------------------------------------------------------------------ 2.2 SQLGetType *sqlgettype* *SQLGetType* --------------- + At anytime you can determine which SQL dialect you are using by calling the SQLGetType command. The ftplugin/sql.vim file defines this function: > SQLGetType @@ -269,8 +275,9 @@ This will echo: > Current SQL dialect in use:sqlanywhere +------------------------------------------------------------------------------ 2.3 SQL Dialect Default *sql-type-default* ------------------------ + As mentioned earlier, the default syntax rules for Vim is based on Oracle (PL/SQL). You can override this default by placing one of the following in your |init.vim|: > @@ -296,7 +303,7 @@ exist. 3. Adding new SQL Dialects *sql-adding-dialects* If you begin working with a SQL dialect which does not have any customizations -available with the default Vim distribution you can check http://www.vim.org +available with the default Vim distribution you can check https://www.vim.org to see if any customization currently exist. If not, you can begin by cloning an existing script. Read |filetype-plugins| for more details. @@ -325,8 +332,9 @@ highlight rules. The dynamic mode populates the popups with data retrieved directly from a database. This includes, table lists, column lists, procedures names and more. +------------------------------------------------------------------------------ 4.1 Static Mode *sql-completion-static* ---------------- + The static popups created contain items defined by the active syntax rules while editing a file with a filetype of SQL. The plugin defines (by default) various maps to help the user refine the list of items to be displayed. @@ -399,11 +407,12 @@ Here are some examples of the entries which are pulled from the syntax files: > - Integer, Char, Varchar, Date, DateTime, Timestamp, ... +------------------------------------------------------------------------------ 4.2 Dynamic Mode *sql-completion-dynamic* ----------------- + Dynamic mode populates the popups with data directly from a database. In order for the dynamic feature to be enabled you must have the dbext.vim -plugin installed, (http://vim.sourceforge.net/script.php?script_id=356). +plugin installed, (https://vim.sourceforge.net/script.php?script_id=356). Dynamic mode is used by several features of the SQL completion plugin. After installing the dbext plugin see the dbext-tutorial for additional @@ -448,8 +457,8 @@ necessary to clear the plugins cache. The default map for this is: > imap <buffer> <C-C>R <C-\><C-O>:call sqlcomplete#Map('ResetCache')<CR><C-X><C-O> +------------------------------------------------------------------------------ 4.3 SQL Tutorial *sql-completion-tutorial* ----------------- This tutorial is designed to take you through the common features of the SQL completion plugin so that: > @@ -462,8 +471,8 @@ First, create a new buffer: > :e tutorial.sql -Static features ---------------- +Static features ~ + To take you through the various lists, simply enter insert mode, hit: <C-C>s (show SQL statements) At this point, you can page down through the list until you find "select". @@ -484,10 +493,10 @@ depending on the syntax file you are using. The SQL Anywhere syntax file DECLARE customer_id <C-C>T <-- Choose a type from the list -Dynamic features ----------------- +Dynamic features ~ + To take advantage of the dynamic features you must first install the -dbext.vim plugin (http://vim.sourceforge.net/script.php?script_id=356). It +dbext.vim plugin (https://vim.sourceforge.net/script.php?script_id=356). It also comes with a tutorial. From the SQL completion plugin's perspective, the main feature dbext provides is a connection to a database. dbext connection profiles are the most efficient mechanism to define connection @@ -597,8 +606,8 @@ Similar to the table list, <C-C>v, will display a list of views in the database. +------------------------------------------------------------------------------ 4.4 Completion Customization *sql-completion-customization* ----------------------------- The SQL completion plugin can be customized through various options set in your |init.vim|: > @@ -657,14 +666,14 @@ your |init.vim|: > option. > +------------------------------------------------------------------------------ 4.5 SQL Maps *sql-completion-maps* ------------- The default SQL maps have been described in other sections of this document in greater detail. Here is a list of the maps with a brief description of each. -Static Maps ------------ +Static Maps ~ + These are maps which use populate the completion list using Vim's syntax highlighting rules. > <C-C>a @@ -680,8 +689,8 @@ highlighting rules. > <C-C>s < - Displays all SQL syntax items defined as 'sqlStatement'. > -Dynamic Maps ------------- +Dynamic Maps ~ + These are maps which use populate the completion list using the dbext.vim plugin. > <C-C>t @@ -713,8 +722,8 @@ plugin. > < - This maps removes all cached items and forces the SQL completion to regenerate the list of items. -Customizing Maps ----------------- +Customizing Maps ~ + You can create as many additional key maps as you like. Generally, the maps will be specifying different syntax highlight groups. @@ -733,8 +742,8 @@ chosen since it will work on both Windows and *nix platforms. On the windows platform you can also use <C-Space> or ALT keys. +------------------------------------------------------------------------------ 4.6 Using with other filetypes *sql-completion-filetypes* ------------------------------- Many times SQL can be used with different filetypes. For example Perl, Java, PHP, Javascript can all interact with a database. Often you need both the SQL @@ -746,8 +755,8 @@ This can be enabled easily with the following steps (assuming a Perl file): > 2. :set filetype=sql 3. :set ft=perl -Step 1 ------- +Step 1 ~ + Begins by editing a Perl file. Vim automatically sets the filetype to "perl". By default, Vim runs the appropriate filetype file ftplugin/perl.vim. If you are using the syntax completion plugin by following @@ -755,9 +764,9 @@ the directions at |ft-syntax-omni| then the |'omnifunc'| option has been set to "syntax#Complete". Pressing <C-X><C-O> will display the omni popup containing the syntax items for Perl. -Step 2 ------- -Manually setting the filetype to 'sql' will also fire the appropriate filetype +Step 2 ~ + +Manually setting the filetype to "sql" will also fire the appropriate filetype files ftplugin/sql.vim. This file will define a number of buffer specific maps for SQL completion, see |sql-completion-maps|. Now these maps have been created and the SQL completion plugin has been initialized. All SQL @@ -767,8 +776,8 @@ begin with <C-C>, the maps will toggle the |'omnifunc'| when in use. So you can use <C-X><C-O> to continue using the completion for Perl (using the syntax completion plugin) and <C-C> to use the SQL completion features. -Step 3 ------- +Step 3 ~ + Setting the filetype back to Perl sets all the usual "perl" related items back as they were. diff --git a/runtime/doc/gui.txt b/runtime/doc/gui.txt index 8f09e5225f..1fce9fa491 100644 --- a/runtime/doc/gui.txt +++ b/runtime/doc/gui.txt @@ -44,8 +44,8 @@ Scrollbars *gui-scrollbars* There are vertical scrollbars and a horizontal scrollbar. You may configure which ones appear with the 'guioptions' option. -The interface looks like this (with ":set guioptions=mlrb"): - +The interface looks like this (with `:set guioptions=mlrb`): +> +------------------------------+ ` | File Edit Help | <- Menu bar (m) ` +-+--------------------------+-+ ` @@ -66,7 +66,7 @@ The interface looks like this (with ":set guioptions=mlrb"): +-+--------------------------+-+ ` | |< #### >| | <- Bottom ` +-+--------------------------+-+ scrollbar (b) ` - +< Any of the scrollbar or menu components may be turned off by not putting the appropriate letter in the 'guioptions' string. The bottom scrollbar is only useful when 'nowrap' is set. @@ -123,7 +123,7 @@ message). Keep Shift pressed to change to the directory instead. If Vim happens to be editing a command line, the names of the dropped files and directories will be inserted at the cursor. This allows you to use these names with any Ex command. Special characters (space, tab, double quote and -'|'; backslash on non-MS-Windows systems) will be escaped. +"|"; backslash on non-MS-Windows systems) will be escaped. ============================================================================== Menus *menus* @@ -450,8 +450,8 @@ The default "PopUp" menu is: > anoremenu PopUp.Paste "+gP vnoremenu PopUp.Paste "+P vnoremenu PopUp.Delete "_x - nnoremenu PopUp.Select\ All> ggVG - vnoremenu PopUp.Select\ All> gg0oG$ + nnoremenu PopUp.Select\ All ggVG + vnoremenu PopUp.Select\ All gg0oG$ inoremenu PopUp.Select\ All <C-Home><C-O>VG anoremenu PopUp.-1- <Nop> anoremenu PopUp.How-to\ disable\ mouse <Cmd>help disable-mouse<CR> @@ -569,14 +569,14 @@ Tooltips & Menu tips See section |42.4| in the user manual. *:tmenu* -:tm[enu] {menupath} {rhs} Define a tip for a menu or tool. {only in - X11 and Win32 GUI} +:tm[enu] {menupath} {rhs} Define a tip for a menu or tool. (only in + X11 and Win32 GUI) -:tm[enu] [menupath] List menu tips. {only in X11 and Win32 GUI} +:tm[enu] [menupath] List menu tips. (only in X11 and Win32 GUI) *:tunmenu* :tu[nmenu] {menupath} Remove a tip for a menu or tool. - {only in X11 and Win32 GUI} + (only in X11 and Win32 GUI) Note: To create menus for terminal mode, use |:tlmenu| instead. diff --git a/runtime/doc/hebrew.txt b/runtime/doc/hebrew.txt index 2f4b137bd3..76266d777f 100644 --- a/runtime/doc/hebrew.txt +++ b/runtime/doc/hebrew.txt @@ -11,8 +11,9 @@ Lottem. <alottem at gmail dot com> Ron Aaron <ron at ronware dot org> is currently helping support these features. +------------------------------------------------------------------------------ Introduction ------------- + Hebrew-specific options are 'hkmap', 'hkmapp' 'keymap'=hebrew and 'aleph'. Hebrew-useful options are 'delcombine', 'allowrevins', 'revins', 'rightleft' and 'rightleftcmd'. @@ -22,8 +23,9 @@ from right to left instead of the usual left to right. This is useful primarily when editing Hebrew or other Middle-Eastern languages. See |rileft.txt| for further details. +------------------------------------------------------------------------------ Details --------------- + + Options: + 'rightleft' ('rl') sets window orientation to right-to-left. This means that the logical text 'ABC' will be displayed as 'CBA', and will start @@ -31,7 +33,7 @@ Details + 'hkmap' ('hk') sets keyboard mapping to Hebrew, in insert/replace modes. + 'aleph' ('al'), numeric, holds the decimal code of Aleph, for keyboard mapping. - + 'hkmapp' ('hkp') sets keyboard mapping to 'phonetic hebrew' + + 'hkmapp' ('hkp') sets keyboard mapping to "phonetic hebrew" NOTE: these three ('hkmap', 'hkmapp' and 'aleph') are obsolete. You should use ":set keymap=hebrewp" instead. @@ -51,7 +53,7 @@ Details ('deco' does nothing if UTF8 encoding is not active). + Vim arguments: - + 'vim -H file' starts editing a Hebrew file, i.e. 'rightleft' and 'hkmap' + + `vim -H file` starts editing a Hebrew file, i.e. 'rightleft' and 'hkmap' are set. + Keyboard: @@ -116,8 +118,9 @@ when exiting 'revins' via CTRL-_, the cursor moves to the end of the typed text (if possible). +------------------------------------------------------------------------------ Pasting when in a rightleft window ----------------------------------- + When cutting text with the mouse and pasting it in a rightleft window the text will be reversed, because the characters come from the cut buffer from the left to the right, while inserted in the file from the right to @@ -125,8 +128,9 @@ the left. In order to avoid it, toggle 'revins' (by typing CTRL-? or CTRL-_) before pasting. +------------------------------------------------------------------------------ Hebrew characters and the 'isprint' variable --------------------------------------------- + Sometimes Hebrew character codes are in the non-printable range defined by the 'isprint' variable. For example in the Linux console, the Hebrew font encoding starts from 128, while the default 'isprint' variable is @,161-255. diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index 04e31e0680..07f898f99c 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -1,6 +1,6 @@ *help.txt* Nvim - VIM - main help file + NVIM - help k Move around: Use the cursor keys, or "h" to go left, h l "j" to go down, "k" to go up, "l" to go right. j @@ -37,169 +37,149 @@ Get specific help: It is possible to go directly to whatever you want help Vim stands for Vi IMproved. Most of Vim was made by Bram Moolenaar, but only through the help of many others. See |credits|. + +============================================================================== +NVIM DOCUMENTATION + +------------------------------------------------------------------------------ +ABOUT NVIM *reference_toc* *doc-file-list* *Q_ct* + +|news| News since the previous release +|nvim| Transitioning from Vim +|vim-differences| Nvim compared to Vim +|user-manual| User manual: How to accomplish editing tasks. +|quickref| Overview of common commands +|tutor| 30-minute interactive course for beginners +|copying| About copyrights +|iccf| Helping poor children in Uganda +|sponsor| Sponsor Vim development, become a registered Vim user +|www| Vim on the World Wide Web +|bugs| Where to send bug reports +|support| Supported platforms + +------------------------------------------------------------------------------ +GENERAL + +|intro| Introduction to Vim; notation used in help files +|helphelp| Using the :help files +|index| Index of all commands +|tips| Various tips on using Vim +|message.txt| (Error) messages and explanations +|uganda.txt| Vim distribution and what to do with your money + +------------------------------------------------------------------------------ +BASIC EDITING + +|starting| Starting Vim, Vim command arguments, initialisation +|edit-files| Editing and writing files +|motion.txt| Commands for moving around +|scrolling| Scrolling the text in the window +|insert.txt| Insert and Replace mode +|change.txt| Deleting and replacing text +|undo-redo| Undo and Redo +|repeat.txt| Repeating commands, Vim scripts and debugging +|visual-mode| Using Visual mode (selecting text) +|various| Various other commands +|crash-recovery| Recovering from a crash + +------------------------------------------------------------------------------ +ADVANCED EDITING + +|cmdline| Command-line editing +|options| Description of all options +|pattern-searches| Vim regexp patterns and search commands +|key-mapping| Key mapping (shortcuts), abbreviations +|tags| Tags and special searches +|windows| Commands for using windows and buffers +|tabpage| Commands for using tabpages +|spell| Spell checking +|diff| Comparing files +|folding| Hide (fold) ranges of lines +|terminal| Embedded terminal emulator + +------------------------------------------------------------------------------ +API (EXTENSIBILITY/SCRIPTING/PLUGINS) + +|api| Nvim API via RPC, Lua and VimL +|ui| Nvim UI protocol +|lua-guide| Nvim Lua guide +|lua| Lua API +|luaref| Lua reference manual +|luvref| Luv (|vim.loop|) reference manual +|autocmd| Event handlers +|job-control| Spawn and control multiple processes +|channel| Nvim asynchronous IO +|vimscript| Vimscript reference +|vimscript-functions| Vimscript functions +|testing.txt| Vimscript testing functions +|remote-plugin| Nvim remote plugins + +------------------------------------------------------------------------------ +PROGRAMMING LANGUAGE SUPPORT + +|lsp| Language Server Protocol (LSP) +|diagnostic-api| Diagnostic framework +|treesitter| Incremental syntax parsing +|indent.txt| automatic indenting for C and other languages +|syntax| syntax highlighting +|filetype| Settings for specific types of files +|quickfix| Commands for a quick edit-compile-fix cycle +|ft_ada.txt| Ada filetype plugin +|ft_ps1.txt| PowerShell filetype plugin +|ft_raku.txt| Raku filetype plugin +|ft_rust.txt| Rust filetype plugin +|ft_sql.txt| SQL filetype plugin + +------------------------------------------------------------------------------ +UI + +|tui| Builtin UI +|gui| External (graphical) UIs +|signs| Signs displayed as window decorations (the "gutter") + +------------------------------------------------------------------------------ +LANGUAGE SUPPORT + +|digraph| List of available digraphs +|mbyte.txt| Multibyte text support +|mlang.txt| Non-English language support +|rileft.txt| Right-to-left editing mode +|arabic.txt| Arabic language support and editing +|hebrew.txt| Hebrew language support and editing +|russian.txt| Russian language support and editing + ------------------------------------------------------------------------------ - *doc-file-list* *Q_ct* -BASIC: -|quickref| Overview of the most common commands you will use -|tutor| 30-minute interactive course for beginners -|copying| About copyrights -|iccf| Helping poor children in Uganda -|sponsor| Sponsor Vim development, become a registered Vim user -|www| Vim on the World Wide Web -|bugs| Where to send bug reports - -USER MANUAL: These files explain how to accomplish an editing task. - -|usr_toc.txt| Table Of Contents - -Getting Started ~ -|usr_01.txt| About the manuals -|usr_02.txt| The first steps in Vim -|usr_03.txt| Moving around -|usr_04.txt| Making small changes -|usr_05.txt| Set your settings -|usr_06.txt| Using syntax highlighting -|usr_07.txt| Editing more than one file -|usr_08.txt| Splitting windows -|usr_09.txt| Using the GUI -|usr_10.txt| Making big changes -|usr_11.txt| Recovering from a crash -|usr_12.txt| Clever tricks - -Editing Effectively ~ -|usr_20.txt| Typing command-line commands quickly -|usr_21.txt| Go away and come back -|usr_22.txt| Finding the file to edit -|usr_23.txt| Editing other files -|usr_24.txt| Inserting quickly -|usr_25.txt| Editing formatted text -|usr_26.txt| Repeating -|usr_27.txt| Search commands and patterns -|usr_28.txt| Folding -|usr_29.txt| Moving through programs -|usr_30.txt| Editing programs -|usr_31.txt| Exploiting the GUI -|usr_32.txt| The undo tree - -Tuning Vim ~ -|usr_40.txt| Make new commands -|usr_41.txt| Write a Vim script -|usr_42.txt| Add new menus -|usr_43.txt| Using filetypes -|usr_44.txt| Your own syntax highlighted -|usr_45.txt| Select your language - - -REFERENCE MANUAL: These files explain every detail of Vim. *reference_toc* - -General subjects ~ -|intro.txt| general introduction to Vim; notation used in help files -|nvim.txt| Transitioning from Vim -|help.txt| overview and quick reference (this file) -|helphelp.txt| about using the help files -|index.txt| alphabetical index of all commands -|help-tags| all the tags you can jump to (index of tags) -|tips.txt| various tips on using Vim -|message.txt| (error) messages and explanations -|develop.txt| development of Nvim -|debug.txt| debugging Vim itself -|uganda.txt| Vim distribution conditions and what to do with your money - -Basic editing ~ -|starting.txt| starting Vim, Vim command arguments, initialisation -|editing.txt| editing and writing files -|motion.txt| commands for moving around -|scroll.txt| scrolling the text in the window -|insert.txt| Insert and Replace mode -|change.txt| deleting and replacing text -|undo.txt| Undo and Redo -|repeat.txt| repeating commands, Vim scripts and debugging -|visual.txt| using the Visual mode (selecting a text area) -|various.txt| various remaining commands -|recover.txt| recovering from a crash - -Advanced editing ~ -|cmdline.txt| Command-line editing -|options.txt| description of all options -|pattern.txt| regexp patterns and search commands -|map.txt| key mapping and abbreviations -|tagsrch.txt| tags and special searches -|windows.txt| commands for using multiple windows and buffers -|tabpage.txt| commands for using multiple tab pages -|spell.txt| spell checking -|diff.txt| working with two to eight versions of the same file -|autocmd.txt| automatically executing commands on an event -|eval.txt| expression evaluation, conditional commands -|builtin.txt| builtin functions -|fold.txt| hide (fold) ranges of lines -|lua.txt| Lua API -|api.txt| Nvim API via RPC, Lua and VimL - -Special issues ~ -|testing.txt| testing Vim and Vim scripts -|print.txt| printing -|remote_plugin.txt| Nvim support for remote plugins - -Programming language support ~ -|indent.txt| automatic indenting for C and other languages -|lsp.txt| Language Server Protocol (LSP) -|treesitter.txt| tree-sitter library for incremental parsing of buffers -|diagnostic.txt| Diagnostic framework -|syntax.txt| syntax highlighting -|filetype.txt| settings done specifically for a type of file -|quickfix.txt| commands for a quick edit-compile-fix cycle -|provider.txt| Built-in remote plugin hosts -|ft_ada.txt| Ada (the programming language) support -|ft_ps1.txt| Filetype plugin for Windows PowerShell -|ft_raku.txt| Filetype plugin for Raku -|ft_rust.txt| Filetype plugin for Rust -|ft_sql.txt| about the SQL filetype plugin - -Language support ~ -|digraph.txt| list of available digraphs -|mbyte.txt| multibyte text support -|mlang.txt| non-English language support -|rileft.txt| right-to-left editing mode -|arabic.txt| Arabic language support and editing -|hebrew.txt| Hebrew language support and editing -|russian.txt| Russian language support and editing - -GUI ~ -|gui.txt| Graphical User Interface (GUI) - -Interfaces ~ -|if_cscop.txt| using Cscope with Vim -|if_perl.txt| Perl interface -|if_pyth.txt| Python interface -|if_ruby.txt| Ruby interface -|sign.txt| debugging signs - -Versions ~ -|vim_diff.txt| Main differences between Nvim and Vim -|vi_diff.txt| Main differences between Vim and Vi -|deprecated.txt| Deprecated items that have been or will be removed - -Other ~ -|terminal_emulator.txt| Terminal buffers -|term.txt| Terminal UI -|ui.txt| Nvim UI protocol -|channel.txt| Nvim asynchronous IO -|dev_style.txt| Nvim style guide -|job_control.txt| Spawn and control multiple processes -|luaref.txt| Lua reference manual -|luvref.txt| Luv (|vim.loop|) reference manual +INTEROP + +|provider| Builtin remote plugin hosts +|if_perl| Perl interface +|if_pyth| Python interface +|if_ruby| Ruby interface + +------------------------------------------------------------------------------ +VERSIONS + +|deprecated| Deprecated features that will be removed +|vi-differences| Differences between Vim and Vi + +------------------------------------------------------------------------------ +DEVELOPING NVIM + +|dev| Development of Nvim +|dev-style| Development style guidelines +|debug.txt| Debugging Vim itself *standard-plugin-list* Standard plugins ~ -|matchit.txt| Extended |%| matching -|pi_gzip.txt| Reading and writing compressed files -|pi_health.txt| Healthcheck framework -|pi_msgpack.txt| msgpack utilities -|pi_netrw.txt| Reading and writing files over a network -|pi_paren.txt| Highlight matching parens -|pi_spec.txt| Filetype plugin to work with rpm spec files -|pi_tar.txt| Tar file explorer -|pi_zip.txt| Zip archive explorer +|matchit.txt| Extended |%| matching +|pi_gzip.txt| Reading and writing compressed files +|pi_health.txt| Healthcheck framework +|pi_msgpack.txt| msgpack utilities +|pi_netrw.txt| Reading and writing files over a network +|pi_paren.txt| Highlight matching parens +|pi_spec.txt| Filetype plugin to work with rpm spec files +|pi_tar.txt| Tar file explorer +|pi_zip.txt| Zip archive explorer LOCAL ADDITIONS: *local-additions* @@ -212,8 +192,8 @@ CTRL-T, CTRL-O, g<RightMouse>, or <C-RightMouse> to go back to where you were. Note that tags are within | characters, but when highlighting is enabled these characters are hidden. That makes it easier to read a command. -Anyway, you can use CTRL-] on any word, also when it is not within |, and Vim -will try to find help for it. Especially for options in single quotes, e.g. +You can use CTRL-] on any word (even if it is not within "|") and Nvim will +try to find help for it. Especially for options in single quotes, e.g. 'hlsearch'. ------------------------------------------------------------------------------ diff --git a/runtime/doc/helphelp.txt b/runtime/doc/helphelp.txt index 569995d319..da307dd241 100644 --- a/runtime/doc/helphelp.txt +++ b/runtime/doc/helphelp.txt @@ -212,12 +212,6 @@ This is done when viewing the file in Vim, the file itself is not changed. It is done by going through all help files and obtaining the first line of each file. The files in $VIMRUNTIME/doc are skipped. - *help-xterm-window* -If you want to have the help in another xterm window, you could use this -command: > - :!xterm -e vim +help & -< - *:helpt* *:helptags* *E150* *E151* *E152* *E153* *E154* *E670* *E856* :helpt[ags] [++t] {dir} @@ -257,7 +251,7 @@ At this moment translations are available for: Japanese - multiple authors Polish - translated by Mikolaj Machowski Russian - translated by Vassily Ragosin -See the Vim website to find them: http://www.vim.org/translations.php +See the Vim website to find them: https://www.vim.org/translations.php A set of translated help files consists of these files: @@ -348,7 +342,7 @@ should begin with the name of the Vim plugin. The tag name is usually right aligned on a line. When referring to an existing help tag and to create a hot-link, place the -name between two bars (|) eg. |help-writing|. +name between two bars ("|") eg. |help-writing|. When referring to a Vim command and to create a hot-link, place the name between two backticks, eg. inside `:filetype`. You will see this is @@ -372,6 +366,7 @@ To separate sections in a help file, place a series of '=' characters in a line starting from the first column. The section separator line is highlighted differently. + *help-codeblock* To quote a block of ex-commands verbatim, place a greater than (>) character at the end of the line before the block and a less than (<) character as the first non-blank on a line following the block. Any line starting in column 1 diff --git a/runtime/doc/if_cscop.txt b/runtime/doc/if_cscop.txt deleted file mode 100644 index 8947aefc1b..0000000000 --- a/runtime/doc/if_cscop.txt +++ /dev/null @@ -1,374 +0,0 @@ -*if_cscop.txt* Nvim - - - VIM REFERENCE MANUAL by Andy Kahn - - *cscope* *Cscope* -Cscope is a "code intelligence" tool that helps you navigate C programs. It -can also perform some refactoring tasks, such as renaming a global variable in -all source files. Think of it as "ctags on steroids". - -See |cscope-usage| for a quickstart. - - Type |gO| to see the table of contents. - -============================================================================== -Cscope introduction *cscope-intro* - - -Cscope is designed to answer questions like: - Where is this symbol used? - Where is it defined? - Where did this variable get its value? - What is this global symbol's definition? - Where is this function in the source files? - What functions call this function? - What functions are called by this function? - Where does the message "out of space" come from? - Where is this source file in the directory structure? - What files include this header file? - -Cscope answers these questions from a symbol database that it builds the first -time it is used on the source files. On a subsequent call, cscope rebuilds -the database only if a source file has changed or the list of source files is -different. When the database is rebuilt the data for the unchanged files is -copied from the old database, which makes rebuilding much faster than the -initial build. - -See |cscope-usage| to get started. - -============================================================================== -Cscope commands *cscope-commands* - - *:cscope* *:cs* *:scs* *:scscope* *E259* *E262* *E560* *E561* -All cscope commands are accessed through suboptions to the cscope commands. - `:cscope` or `:cs` is the main command - `:scscope` or `:scs` does the same and splits the window - `:lcscope` or `:lcs` uses the location list, see |:lcscope| - -The available subcommands are: - - *E563* *E564* *E566* *E568* *E622* *E623* *E625* - *E626* *E609* - add : Add a new cscope database/connection. - - USAGE :cs add {file|dir} [pre-path] [flags] - - [pre-path] is the pathname used with the -P command to cscope. - - [flags] are any additional flags you want to pass to cscope. - - EXAMPLES > - :cscope add /usr/local/cdb/cscope.out - :cscope add /projects/vim/cscope.out /usr/local/vim - :cscope add cscope.out /usr/local/vim -C -< - *cscope-find* *cs-find* *E567* - find : Query cscope. All cscope query options are available - except option #5 ("Change this grep pattern"). - - USAGE :cs find {querytype} {name} - - {querytype} corresponds to the actual cscope line - interface numbers as well as default nvi commands: - - 0 or s: Find this C symbol - 1 or g: Find this definition - 2 or d: Find functions called by this function - 3 or c: Find functions calling this function - 4 or t: Find this text string - 6 or e: Find this egrep pattern - 7 or f: Find this file - 8 or i: Find files #including this file - 9 or a: Find places where this symbol is assigned a value - - For all types, except 4 and 6, leading white space for {name} is - removed. For 4 and 6 there is exactly one space between {querytype} - and {name}. Further white space is included in {name}. - - EXAMPLES > - :cscope find c vim_free - :cscope find 3 vim_free -< - These two examples perform the same query: functions calling - "vim_free". > - - :cscope find t initOnce - :cscope find t initOnce -< - The first one searches for the text "initOnce", the second one for - " initOnce". > - - :cscope find 0 DEFAULT_TERM -< - Executing this example on the source code for Vim 5.1 produces the - following output: - - Cscope tag: DEFAULT_TERM - # line filename / context / line - 1 1009 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"amiga" - 2 1013 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"win32" - 3 1017 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"pcterm" - 4 1021 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"ansi" - 5 1025 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"vt52" - 6 1029 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"os2ansi" - 7 1033 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"ansi" - 8 1037 vim-5.1-gtk/src/term.c <<GLOBAL>> - # undef DEFAULT_TERM - 9 1038 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"beos-ansi" - 10 1042 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"mac-ansi" - 11 1335 vim-5.1-gtk/src/term.c <<set_termname>> - term = DEFAULT_TERM; - 12 1459 vim-5.1-gtk/src/term.c <<set_termname>> - if (STRCMP(term, DEFAULT_TERM)) - 13 1826 vim-5.1-gtk/src/term.c <<termcapinit>> - term = DEFAULT_TERM; - 14 1833 vim-5.1-gtk/src/term.c <<termcapinit>> - term = DEFAULT_TERM; - 15 3635 vim-5.1-gtk/src/term.c <<update_tcap>> - p = find_builtin_term(DEFAULT_TERM); - Enter nr of choice (<CR> to abort): - - The output shows several pieces of information: - 1. The tag number (there are 15 in this example). - 2. The line number where the tag occurs. - 3. The filename where the tag occurs. - 4. The context of the tag (e.g., global, or the function name). - 5. The line from the file itself. - - help : Show a brief synopsis. - - USAGE :cs help - - *E261* - kill : Kill a cscope connection (or kill all cscope connections). - - USAGE :cs kill {num|partial_name} - - To kill a cscope connection, the connection number or a partial - name must be specified. The partial name is simply any part of - the pathname of the cscope database. Kill a cscope connection - using the partial name with caution! - - If the specified connection number is -1, then _ALL_ cscope - connections will be killed. - - reset : Reinit all cscope connections. - - USAGE :cs reset - - show : Show cscope connections. - - USAGE :cs show - - *:lcscope* *:lcs* -This command is same as the ":cscope" command, except when the -'cscopequickfix' option is set, the location list for the current window is -used instead of the quickfix list to show the cscope results. - - *:cstag* *E257* *E562* -If you use cscope as well as ctags, |:cstag| allows you to search one or -the other before making a jump. For example, you can choose to first -search your cscope database(s) for a match, and if one is not found, then -your tags file(s) will be searched. The order in which this happens -is determined by the value of |csto|. See |cscope-options| for more -details. - -|:cstag| performs the equivalent of ":cs find g" on the identifier when -searching through the cscope database(s). - -|:cstag| performs the equivalent of |:tjump| on the identifier when searching -through your tags file(s). - - -============================================================================== -Cscope options *cscope-options* - -Use the |:set| command to set all cscope options. Ideally, you would do -this in one of your startup files (e.g., vimrc). Some cscope related -variables are only valid within |init.vim|. Setting them after vim has -started will have no effect! - - *cscopeprg* *csprg* -'cscopeprg' specifies the command to execute cscope. The default is -"cscope". For example: > - :set csprg=/usr/local/bin/cscope -< - *cscopequickfix* *csqf* *E469* -'cscopequickfix' specifies whether to use quickfix window to show cscope -results. This is a list of comma-separated values. Each item consists of -|cscope-find| command (s, g, d, c, t, e, f, i or a) and flag (+, - or 0). -'+' indicates that results must be appended to quickfix window, -'-' implies previous results clearance, '0' or command absence - don't use -quickfix. Search is performed from start until first command occurrence. -The default value is "" (don't use quickfix anyway). The following value -seems to be useful: > - :set cscopequickfix=s-,c-,d-,i-,t-,e-,a- -< - *cscopetag* *cst* -If 'cscopetag' is set, the commands ":tag" and CTRL-] as well as "vim -t" -will always use |:cstag| instead of the default :tag behavior. Effectively, -by setting 'cst', you will always search your cscope databases as well as -your tag files. The default is off. - - *cscoperelative* *csre* -If 'cscoperelative' is set, then in absence of a prefix given to cscope -(prefix is the argument of -P option of cscope), basename of cscope.out -location (usually the project root directory) will be used as the prefix -to construct an absolute path. The default is off. Note: This option is -only effective when cscope (cscopeprg) is initialized without a prefix -path (-P). - - *cscopetagorder* *csto* -The value of 'csto' determines the order in which |:cstag| performs a search. -If 'csto' is set to zero, cscope database(s) are searched first, followed -by tag file(s) if cscope did not return any matches. If 'csto' is set to -one, tag file(s) are searched before cscope database(s). The default is zero. - - *cscopepathcomp* *cspc* -'cscopepathcomp' determines how many components of a file's path to display. -With the default value of zero the entire path will be displayed. -The value one will display only the filename with no path. Other values -display that many components. For example: > - :set cscopepathcomp=3 -will display the last 3 components of the file's path, including the file -name itself. - -============================================================================== -Using cscope in Nvim *cscope-usage* *cscope-howtouse* - -To get started, build the cscope database in your project root directory: > - cscope -bcqR - -See the cscope manpage for details: > - :Man cscope - -By default the cscope database file is named "cscope.out". After building the -database, connect to it from Nvim: > - :cscope add cscope.out - -That establishes a cscope connection for Nvim to use. You can check the -result with ":cs show". It will show something like: - - # pid database name prepend path - 0 28806 cscope.out <none> - -Once a cscope connection is established, you can make queries to cscope and -the results will be printed. Queries are made using the command ":cs find". -For example: > - :cs find g ALIGN_SIZE - -To make this easier you can configure mappings, see |cscope-suggestions|. - -If the results return only one match, you will automatically be taken to it. -If there is more than one match, you will be given a selection screen to pick -the match you want to go to. After you have jumped to the new location, -simply hit Ctrl-T to get back to the previous one. - - -============================================================================== -Limitations *cscope-limitations* - -Hard-coded limitation: doing a |:tjump| when |:cstag| searches the tag files -is not configurable (e.g., you can't do a tselect instead). - - -============================================================================== -Sample config *cscope-suggestions* - -Copy this into your init.vim (adjust paths for your system): > - - if has("cscope") - set csprg=/usr/local/bin/cscope - set csto=0 - set cst - " add any database in current directory - if filereadable("cscope.out") - silent cs add cscope.out - " else add database pointed to by environment - elseif $CSCOPE_DB != "" - silent cs add $CSCOPE_DB - endif - endif - -By setting 'cscopetag', we have effectively replaced all instances of the :tag -command with :cstag. This includes :tag, Ctrl-], and "vim -t". In doing -this, the regular tag command not only searches your ctags generated tag -files, but your cscope databases as well. - -Some users may want to keep the regular tag behavior and have a different -shortcut to access :cstag. For example, one could map Ctrl-_ (underscore) -to :cstag with the following command: > - - map <C-_> :cstag <C-R>=expand("<cword>")<CR><CR> - -A couple of very commonly used cscope queries (using ":cs find") is to -find all functions calling a certain function and to find all occurrences -of a particular C symbol. To do this, you can use these mappings as an -example: > - - map g<C-]> :cs find 3 <C-R>=expand("<cword>")<CR><CR> - map g<C-\> :cs find 0 <C-R>=expand("<cword>")<CR><CR> - -These mappings for Ctrl-] (right bracket) and Ctrl-\ (backslash) allow you to -place your cursor over the function name or C symbol and quickly query cscope -for any matches. - -Or you may use the following scheme, inspired by Vim/Cscope tutorial from -Cscope Home Page (http://cscope.sourceforge.net/): > - - nmap <C-_>s :cs find s <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>g :cs find g <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>c :cs find c <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>t :cs find t <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>e :cs find e <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>f :cs find f <C-R>=expand("<cfile>")<CR><CR> - nmap <C-_>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR> - nmap <C-_>d :cs find d <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>a :cs find a <C-R>=expand("<cword>")<CR><CR> - - " Using 'CTRL-spacebar' then a search type makes the vim window - " split horizontally, with search result displayed in - " the new window. - - nmap <C-Space>s :scs find s <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>g :scs find g <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>c :scs find c <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>t :scs find t <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>e :scs find e <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>f :scs find f <C-R>=expand("<cfile>")<CR><CR> - nmap <C-Space>i :scs find i ^<C-R>=expand("<cfile>")<CR>$<CR> - nmap <C-Space>d :scs find d <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>a :scs find a <C-R>=expand("<cword>")<CR><CR> - - " Hitting CTRL-space *twice* before the search type does a vertical - " split instead of a horizontal one - - nmap <C-Space><C-Space>s - \:vert scs find s <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>g - \:vert scs find g <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>c - \:vert scs find c <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>t - \:vert scs find t <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>e - \:vert scs find e <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>i - \:vert scs find i ^<C-R>=expand("<cfile>")<CR>$<CR> - nmap <C-Space><C-Space>d - \:vert scs find d <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>a - \:vert scs find a <C-R>=expand("<cword>")<CR><CR> -< - - vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/if_pyth.txt b/runtime/doc/if_pyth.txt index 9b434e61d7..4c184ddf94 100644 --- a/runtime/doc/if_pyth.txt +++ b/runtime/doc/if_pyth.txt @@ -16,7 +16,7 @@ Commands *python-commands* *:python* *:py* *E263* *E264* *E887* :[range]py[thon] {stmt} Execute Python statement {stmt}. A simple check if - the `:python` command is working: > + the `:python` command is working: >vim :python print "Hello" :[range]py[thon] << [endmarker] @@ -31,7 +31,7 @@ The {endmarker} below the {script} must NOT be preceded by any white space. If [endmarker] is omitted from after the "<<", a dot '.' must be used after {script}, like for the |:append| and |:insert| commands. -Example: > +Example: >vim function! IcecreamInitialize() python << EOF class StrawberryIcecream: @@ -40,7 +40,7 @@ Example: > EOF endfunction -To see what version of Python you have: > +To see what version of Python you have: >vim :python print(sys.version) There is no need to "import sys", it's done by default. @@ -64,12 +64,12 @@ Note: Python is very sensitive to indenting. Make sure the "class" line and is the whole file: "1,$". Examples: -> +>vim :pydo return "%s\t%d" % (line[::-1], len(line)) :pydo if line: return "%4d: %s" % (linenr, line) < One can use `:pydo` in possible conjunction with `:py` to filter a range using -python. For example: > +python. For example: >vim :py3 << EOF needle = vim.eval('@a') @@ -94,12 +94,13 @@ In the case of :pyfile, the code to execute is the contents of the given file. Python commands cannot be used in the |sandbox|. -To pass arguments you need to set sys.argv[] explicitly. Example: > +To pass arguments you need to set sys.argv[] explicitly. Example: >vim :python sys.argv = ["foo", "bar"] :pyfile myscript.py -Here are some examples *python-examples* > +Here are some examples *python-examples* +>vim :python from vim import * :python from string import upper @@ -113,7 +114,7 @@ to the next, just like the Python REPL. *script-here* When using a script language in-line, you might want to skip this when the language isn't supported. Note that this mechanism doesn't work: -> +>vim if has('python') python << EOF this will NOT work! @@ -121,7 +122,7 @@ language isn't supported. Note that this mechanism doesn't work: endif Instead, put the Python command in a function and call that function: -> +>vim if has('python') function DefPython() python << EOF @@ -139,10 +140,10 @@ The vim module *python-vim* Python code gets all of its access to vim (with one exception - see |python-output| below) via the "vim" module. The vim module implements two methods, three constants, and one error object. You need to import the vim -module before using it: > +module before using it: >vim :python import vim -Overview > +Overview >vim :py print "Hello" # displays a message :py vim.command(cmd) # execute an Ex command :py w = vim.windows[n] # gets window "n" @@ -166,10 +167,10 @@ Methods of the "vim" module vim.command(str) *python-command* Executes the vim (ex-mode) command str. Returns None. - Examples: > + Examples: >vim :py vim.command("set tw=72") :py vim.command("%s/aaa/bbb/g") -< The following definition executes Normal mode commands: > +< The following definition executes Normal mode commands: >python def normal(str): vim.command("normal "+str) # Note the use of single quotes to delimit a string containing @@ -177,7 +178,7 @@ vim.command(str) *python-command* normal('"a2dd"aP') < *E659* The ":python" command cannot be used recursively with Python 2.2 and - older. This only works with Python 2.3 and later: > + older. This only works with Python 2.3 and later: >vim :py vim.command("python print 'Hello again Python'") vim.eval(str) *python-eval* @@ -187,7 +188,7 @@ vim.eval(str) *python-eval* - a list if the Vim expression evaluates to a Vim list - a dictionary if the Vim expression evaluates to a Vim dictionary Dictionaries and lists are recursively expanded. - Examples: > + Examples: >vim :py text_width = vim.eval("&tw") :py str = vim.eval("12+12") # NB result is a string! Use # string.atoi() to convert to @@ -215,7 +216,7 @@ Error object of the "vim" module vim.error *python-error* Upon encountering a Vim error, Python raises an exception of type vim.error. - Example: > + Example: >python try: vim.command("put a") except vim.error: @@ -229,7 +230,7 @@ Constants of the "vim" module vim.buffers *python-buffers* A mapping object providing access to the list of vim buffers. The - object supports the following operations: > + object supports the following operations: >vim :py b = vim.buffers[i] # Indexing (read-only) :py b in vim.buffers # Membership test :py n = len(vim.buffers) # Number of elements @@ -237,7 +238,7 @@ vim.buffers *python-buffers* < vim.windows *python-windows* A sequence object providing access to the list of vim windows. The - object supports the following operations: > + object supports the following operations: >vim :py w = vim.windows[i] # Indexing (read-only) :py w in vim.windows # Membership test :py n = len(vim.windows) # Number of elements @@ -251,7 +252,7 @@ vim.windows *python-windows* vim.tabpages *python-tabpages* A sequence object providing access to the list of vim tab pages. The - object supports the following operations: > + object supports the following operations: >vim :py t = vim.tabpages[i] # Indexing (read-only) :py t in vim.tabpages # Membership test :py n = len(vim.tabpages) # Number of elements @@ -277,7 +278,7 @@ vim.current *python-current* switching to given buffer, window or tab page. It is the only way to switch UI objects in python: you can't assign to |python-tabpage|.window attribute. To switch without triggering - autocommands use > + autocommands use >vim py << EOF saved_eventignore = vim.options['eventignore'] vim.options['eventignore'] = 'all' @@ -330,7 +331,7 @@ the list of paths found in 'runtimepath': with this directory in sys.path and vim.path_hooks in sys.path_hooks python will try to load module from {rtp}/python3 and {rtp}/pythonx for each {rtp} found in 'runtimepath'. -Implementation is similar to the following, but written in C: > +Implementation is similar to the following, but written in C: >python from imp import find_module, load_module import vim @@ -461,12 +462,12 @@ The buffer object methods are: numbers s and e |inclusive|. Note that when adding a line it must not contain a line break character '\n'. -A trailing '\n' is allowed and ignored, so that you can do: > +A trailing '\n' is allowed and ignored, so that you can do: >vim :py b.append(f.readlines()) Buffer object type is available using "Buffer" attribute of vim module. -Examples (assume b is the current buffer) > +Examples (assume b is the current buffer) >vim :py print b.name # write the buffer file name :py b[0] = "hello!!!" # replace the top line :py b[:] = None # delete the whole buffer @@ -605,10 +606,10 @@ variants explicitly if Python 3 is required. {script} {endmarker} The `:py3` and `:python3` commands work similar to `:python`. A - simple check if the `:py3` command is working: > + simple check if the `:py3` command is working: >vim :py3 print("Hello") < - To see what version of Python you have: > + To see what version of Python you have: >vim :py3 import sys :py3 print(sys.version) < *:py3file* @@ -619,11 +620,12 @@ variants explicitly if Python 3 is required. The `:py3do` command works similar to `:pydo`. *E880* -Raising SystemExit exception in python isn't endorsed way to quit vim, use: > +Raising SystemExit exception in python isn't endorsed way to quit vim, use: +>vim :py vim.command("qall!") < *has-python* -You can test if Python is available with: > +You can test if Python is available with: >vim if has('pythonx') echo 'there is Python' endif @@ -642,10 +644,10 @@ works with Python 2.6+ and Python 3. As Nvim only supports Python 3, all these commands are now synonymous to their "python3" equivalents. *:pyx* *:pythonx* -`:pyx` and `:pythonx` work the same as `:python3`. To check if `:pyx` works: > +`:pyx` and `:pythonx` work the same as `:python3`. To check if `:pyx` works: >vim :pyx print("Hello") -To see what version of Python is being used: > +To see what version of Python is being used: >vim :pyx import sys :pyx print(sys.version) < @@ -656,7 +658,7 @@ To see what version of Python is being used: > `:pyxdo` works the same as `:py3do`. *has-pythonx* -To check if `pyx*` functions and commands are available: > +To check if `pyx*` functions and commands are available: >vim if has('pythonx') echo 'pyx* commands are available. (Python ' .. &pyx .. ')' endif diff --git a/runtime/doc/if_ruby.txt b/runtime/doc/if_ruby.txt index 47305c65fb..d88f59eb73 100644 --- a/runtime/doc/if_ruby.txt +++ b/runtime/doc/if_ruby.txt @@ -7,7 +7,7 @@ The Ruby Interface to Vim *if_ruby* *ruby* *Ruby* *E266* *E267* *E268* *E269* *E270* *E271* *E272* *E273* -The home page for ruby is http://www.ruby-lang.org/. You can find links for +The home page for ruby is https://www.ruby-lang.org/. You can find links for downloading Ruby there. Type |gO| to see the table of contents. diff --git a/runtime/doc/indent.txt b/runtime/doc/indent.txt index 1a1d8e30b0..f3e196b426 100644 --- a/runtime/doc/indent.txt +++ b/runtime/doc/indent.txt @@ -35,7 +35,7 @@ The rest of this section describes the 'cindent' option. Note that 'cindent' indenting does not work for every code scenario. Vim is not a C compiler: it does not recognize all syntax. One requirement is -that toplevel functions have a '{' in the first column. Otherwise they are +that toplevel functions have a "{" in the first column. Otherwise they are easily confused with declarations. These five options control C program indenting: @@ -60,12 +60,12 @@ used instead. The format of 'cinkeys' and 'indentkeys' is equal. The default is "0{,0},0),0],:,0#,!^F,o,O,e" which specifies that indenting occurs as follows: - "0{" if you type '{' as the first character in a line - "0}" if you type '}' as the first character in a line - "0)" if you type ')' as the first character in a line - "0]" if you type ']' as the first character in a line - ":" if you type ':' after a label or case statement - "0#" if you type '#' as the first character in a line + "0{" if you type "{" as the first character in a line + "0}" if you type "}" as the first character in a line + "0)" if you type ")" as the first character in a line + "0]" if you type "]" as the first character in a line + ":" if you type ":" after a label or case statement + "0#" if you type "#" as the first character in a line "!^F" if you type CTRL-F (which is not inserted) "o" if you type a <CR> anywhere or use the "o" command (not in insert mode!) @@ -74,21 +74,21 @@ occurs as follows: line Characters that can precede each key: *i_CTRL-F* -! When a '!' precedes the key, Vim will not insert the key but will +! When a "!" precedes the key, Vim will not insert the key but will instead reindent the current line. This allows you to define a command key for reindenting the current line. CTRL-F is the default key for this. Be careful if you define CTRL-I for this because CTRL-I is the ASCII code for <Tab>. -* When a '*' precedes the key, Vim will reindent the line before +* When a "*" precedes the key, Vim will reindent the line before inserting the key. If 'cinkeys' contains "*<Return>", Vim reindents the current line before opening a new line. -0 When a zero precedes the key (but appears after '!' or '*') Vim will +0 When a zero precedes the key (but appears after "!" or "*") Vim will reindent the line only if the key is the first character you type in the line. When used before "=" Vim will only reindent the line if there is only white space before the word. -When neither '!' nor '*' precedes the key, Vim reindents the line after you -type the key. So ';' sets the indentation of a line which includes the ';'. +When neither "!" nor "*" precedes the key, Vim reindents the line after you +type the key. So ";" sets the indentation of a line which includes the ";". Special key names: <> Angle brackets mean spelled-out names of keys. For example: "<Up>", @@ -154,8 +154,8 @@ The examples below assume a 'shiftwidth' of 4. eN Add N to the prevailing indent inside a set of braces if the opening brace at the End of the line (more precise: is not the first character in a line). This is useful if you want a - different indent when the '{' is at the start of the line from - when '{' is at the end of the line. (default 0). + different indent when the "{" is at the start of the line from + when "{" is at the end of the line. (default 0). cino= cino=e2 cino=e-2 > if (cond) { if (cond) { if (cond) { @@ -169,8 +169,8 @@ The examples below assume a 'shiftwidth' of 4. *cino-n* nN Add N to the prevailing indent for a statement after an "if", "while", etc., if it is NOT inside a set of braces. This is - useful if you want a different indent when there is no '{' - before the statement from when there is a '{' before it. + useful if you want a different indent when there is no "{" + before the statement from when there is a "{" before it. (default 0). cino= cino=n2 cino=n-2 > @@ -193,7 +193,7 @@ The examples below assume a 'shiftwidth' of 4. int foo; int foo; int foo; < *cino-{* - {N Place opening braces N characters from the prevailing indent. + `{N` Place opening braces N characters from the prevailing indent. This applies only for opening braces that are inside other braces. (default 0). @@ -203,7 +203,7 @@ The examples below assume a 'shiftwidth' of 4. foo; foo; foo; < *cino-}* - }N Place closing braces N characters from the matching opening + `}N` Place closing braces N characters from the matching opening brace. (default 0). cino= cino={2,}-0.5s cino=}2 > @@ -724,7 +724,7 @@ Fortran with (possibly multiple) loops ending on a labelled executable statement of almost arbitrary type. Correct indentation requires compiler-quality parsing. Old code with do loops ending on labelled statements of arbitrary type can be indented with elaborate programs such as Tidy -(http://www.unb.ca/chem/ajit/f_tidy.htm). Structured do/continue loops are +(https://www.unb.ca/chem/ajit/f_tidy.htm). Structured do/continue loops are also left unindented because continue statements are also used for purposes other than ending a do loop. Programs such as Tidy can convert structured do/continue loops to the do/enddo form. Do loops of the do/enddo variety can @@ -846,7 +846,7 @@ own 'formatoptions'): > Else, 't' will be removed from the 'formatoptions' string and "qrowcb" will be added, see |fo-table| for more information. -------------- + *PHP_outdentSLComments* To add extra indentation to single-line comments: > @@ -858,7 +858,7 @@ Only single-line comments will be affected such as: > # Comment // Comment /* Comment */ -------------- +< *PHP_default_indenting* To add extra indentation to every PHP lines with N being the number of @@ -878,18 +878,17 @@ For example, with N = 1, this will give: $command_hist = TRUE; ?> (Notice the extra indentation between the PHP container markers and the code) -------------- *PHP_outdentphpescape* To indent PHP escape tags as the surrounding non-PHP code (only affects the PHP escape tags): > :let g:PHP_outdentphpescape = 0 -------------- +< *PHP_removeCRwhenUnix* To automatically remove '\r' characters when the 'fileformat' is set to Unix: > :let g:PHP_removeCRwhenUnix = 1 -------------- +< *PHP_BracesAtCodeLevel* To indent braces at the same level than the code they contain: > @@ -908,7 +907,6 @@ Instead of: > NOTE: Indenting will be a bit slower if this option is used because some optimizations won't be available. -------------- *PHP_vintage_case_default_indent* To indent 'case:' and 'default:' statements in switch() blocks: > @@ -918,7 +916,6 @@ In PHP braces are not required inside 'case/default' blocks therefore 'case:' and 'default:' are indented at the same level than the 'switch()' to avoid meaningless indentation. You can use the above option to return to the traditional way. -------------- *PHP_noArrowMatching* By default the indent script will indent multi-line chained calls by matching @@ -927,17 +924,16 @@ the position of the '->': > $user_name_very_long->name() ->age() ->info(); - +< You can revert to the classic way of indenting by setting this option to 1: > :let g:PHP_noArrowMatching = 1 - +< You will obtain the following result: > $user_name_very_long->name() ->age() ->info(); - -------------- +< *PHP_IndentFunctionCallParameters* Extra indentation levels to add to parameters in multi-line function calls. > @@ -954,14 +950,13 @@ Function call arguments will indent 1 extra level. For two-space indentation: > $and_that ); } - -------------- +< *PHP_IndentFunctionDeclarationParameters* Extra indentation levels to add to arguments in multi-line function definitions. > let g:PHP_IndentFunctionDeclarationParameters = 1 - +< Function arguments in declarations will indent 1 extra level. For two-space indentation: > @@ -974,30 +969,46 @@ indentation: > $and_that ); } - +< PYTHON *ft-python-indent* -The amount of indent can be set for the following situations. The examples -given are the defaults. Note that the variables are set to an expression, so -that you can change the value of 'shiftwidth' later. +The amount of indent can be set with the `g:python_indent` |Dictionary|, which +needs to be created before adding the items: > + let g:python_indent = {} +The examples given are the defaults. Note that the dictionary values are set +to an expression, so that you can change the value of 'shiftwidth' later +without having to update these values. Indent after an open paren: > - let g:pyindent_open_paren = 'shiftwidth() * 2' + let g:python_indent.open_paren = 'shiftwidth() * 2' Indent after a nested paren: > - let g:pyindent_nested_paren = 'shiftwidth()' + let g:python_indent.nested_paren = 'shiftwidth()' Indent for a continuation line: > - let g:pyindent_continue = 'shiftwidth() * 2' + let g:python_indent.continue = 'shiftwidth() * 2' + +By default, the closing paren on a multiline construct lines up under the first +non-whitespace character of the previous line. +If you prefer that it's lined up under the first character of the line that +starts the multiline construct, reset this key: > + let g:python_indent.closed_paren_align_last_line = v:false The method uses |searchpair()| to look back for unclosed parentheses. This can sometimes be slow, thus it timeouts after 150 msec. If you notice the indenting isn't correct, you can set a larger timeout in msec: > - let g:pyindent_searchpair_timeout = 500 + let g:python_indent.searchpair_timeout = 500 If looking back for unclosed parenthesis is still too slow, especially during a copy-paste operation, or if you don't need indenting inside multi-line parentheses, you can completely disable this feature: > - let g:pyindent_disable_parentheses_indenting = 1 + let g:python_indent.disable_parentheses_indenting = 1 + +For backward compatibility, these variables are also supported: > + g:pyindent_open_paren + g:pyindent_nested_paren + g:pyindent_continue + g:pyindent_searchpair_timeout + g:pyindent_disable_parentheses_indenting R *ft-r-indent* @@ -1129,7 +1140,6 @@ to the vimrc file, which causes the previous alignment example to change: > ); END ENTITY sync; ----------------------------------------- Alignment of right-hand side assignment "<=" statements are performed by default. This causes the following alignment example: > @@ -1148,7 +1158,6 @@ to the vimrc file, which causes the previous alignment example to change: > (sig_b OR sig_c)) OR (bus_a(0) AND sig_d); ----------------------------------------- Full-line comments (lines that begin with "--") are indented to be aligned with the very previous line's comment, PROVIDED that a whitespace follows after diff --git a/runtime/doc/index.txt b/runtime/doc/index.txt index 7f3ef20762..a6aa036b55 100644 --- a/runtime/doc/index.txt +++ b/runtime/doc/index.txt @@ -13,7 +13,6 @@ to look for deleting something, use: "/delete". For an overview of options see |option-list|. For an overview of built-in functions see |functions|. For a list of Vim variables see |vim-variable|. -For a complete listing of all help items see |help-tags|. Type |gO| to see the table of contents. @@ -21,7 +20,7 @@ For a complete listing of all help items see |help-tags|. 1. Insert mode *insert-index* tag char action in Insert mode ~ ------------------------------------------------------------------------ +------------------------------------------------------------------------------ ~ |i_CTRL-@| CTRL-@ insert previously inserted text and stop insert |i_CTRL-A| CTRL-A insert previously inserted text @@ -61,7 +60,7 @@ tag char action in Insert mode ~ |i_CTRL-Q| CTRL-Q same as CTRL-V, unless used for terminal control flow |i_CTRL-SHIFT-Q| CTRL-SHIFT-Q {char} - like CTRL-Q unless |modifyOtherKeys| is active + like CTRL-Q unless |tui-modifyOtherKeys| is active |i_CTRL-R| CTRL-R {register} insert the contents of a register |i_CTRL-R_CTRL-R| CTRL-R CTRL-R {register} @@ -79,7 +78,7 @@ tag char action in Insert mode ~ line |i_CTRL-V| CTRL-V {char} insert next non-digit literally |i_CTRL-SHIFT-V| CTRL-SHIFT-V {char} - like CTRL-V unless |modifyOtherKeys| is active + like CTRL-V unless |tui-modifyOtherKeys| is active |i_CTRL-V_digit| CTRL-V {number} insert three digit decimal number as a single byte. |i_CTRL-W| CTRL-W delete word before the cursor @@ -184,7 +183,7 @@ SECTION a section that possibly starts with '}' instead of '{' note: 1 = cursor movement command; 2 = can be undone/redone tag char note action in Normal mode ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ CTRL-@ not used |CTRL-A| CTRL-A 2 add N to number at/after cursor |CTRL-B| CTRL-B 1 scroll N screens Backwards @@ -454,14 +453,14 @@ tag char note action in Normal mode ~ |<S-Up>| <S-Up> 1 same as CTRL-B |<Undo>| <Undo> 2 same as "u" |<Up>| <Up> 1 same as "k" -|<ScrollWheelDown>| <ScrollWheelDown> move window three lines down -|<S-ScrollWheelDown>| <S-ScrollWheelDown> move window one page down -|<ScrollWheelUp>| <ScrollWheelUp> move window three lines up -|<S-ScrollWheelUp>| <S-ScrollWheelUp> move window one page up -|<ScrollWheelLeft>| <ScrollWheelLeft> move window six columns left -|<S-ScrollWheelLeft>| <S-ScrollWheelLeft> move window one page left -|<ScrollWheelRight>| <ScrollWheelRight> move window six columns right -|<S-ScrollWheelRight>| <S-ScrollWheelRight> move window one page right +*<ScrollWheelDown>* <ScrollWheelDown> move window three lines down +*<S-ScrollWheelDown>* <S-ScrollWheelDown> move window one page down +*<ScrollWheelUp>* <ScrollWheelUp> move window three lines up +*<S-ScrollWheelUp>* <S-ScrollWheelUp> move window one page up +*<ScrollWheelLeft>* <ScrollWheelLeft> move window six columns left +*<S-ScrollWheelLeft>* <S-ScrollWheelLeft> move window one page left +*<ScrollWheelRight>* <ScrollWheelRight> move window six columns right +*<S-ScrollWheelRight>* <S-ScrollWheelRight> move window one page right ============================================================================== 2.1 Text objects *objects* @@ -469,7 +468,7 @@ tag char note action in Normal mode ~ These can be used after an operator or in Visual mode to select an object. tag command action in op-pending and Visual mode ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ |v_aquote| a" double quoted string |v_a'| a' single quoted string |v_a(| a( same as ab @@ -511,7 +510,7 @@ tag command action in op-pending and Visual mode ~ 2.2 Window commands *CTRL-W* tag command action in Normal mode ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ |CTRL-W_CTRL-B| CTRL-W CTRL-B same as "CTRL-W b" |CTRL-W_CTRL-C| CTRL-W CTRL-C same as "CTRL-W c" |CTRL-W_CTRL-D| CTRL-W CTRL-D same as "CTRL-W d" @@ -609,7 +608,7 @@ tag command action in Normal mode ~ 2.3 Square bracket commands *[* *]* tag char note action in Normal mode ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ |[_CTRL-D| [ CTRL-D jump to first #define found in current and included files matching the word under the cursor, start searching at beginning of @@ -699,8 +698,8 @@ tag char note action in Normal mode ~ 2.4 Commands starting with 'g' *g* tag char note action in Normal mode ~ ------------------------------------------------------------------------------- -|g_CTRL-A| g CTRL-A dump a memory profile +------------------------------------------------------------------------------ ~ +g_CTRL-A g CTRL-A dump a memory profile |g_CTRL-G| g CTRL-G show information about current cursor position |g_CTRL-H| g CTRL-H start Select block mode @@ -802,7 +801,7 @@ tag char note action in Normal mode ~ 2.5 Commands starting with 'z' *z* tag char note action in Normal mode ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ |z<CR>| z<CR> redraw, cursor line to top of window, cursor on first non-blank |zN<CR>| z{height}<CR> redraw, make window {height} lines high @@ -876,7 +875,7 @@ tag char note action in Normal mode ~ These can be used after an operator, but before a {motion} has been entered. tag char action in Operator-pending mode ~ ------------------------------------------------------------------------ +------------------------------------------------------------------------------ ~ |o_v| v force operator to work charwise |o_V| V force operator to work linewise |o_CTRL-V| CTRL-V force operator to work blockwise @@ -888,7 +887,7 @@ Most commands in Visual mode are the same as in Normal mode. The ones listed here are those that are different. tag command note action in Visual mode ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ |v_CTRL-\_CTRL-N| CTRL-\ CTRL-N stop Visual mode |v_CTRL-\_CTRL-G| CTRL-\ CTRL-G go to Normal mode |v_CTRL-A| CTRL-A 2 add N to number in highlighted text @@ -1008,7 +1007,7 @@ Normal characters are inserted at the current cursor position. file names, tags, commands etc. as appropriate. tag command action in Command-line editing mode ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ CTRL-@ not used |c_CTRL-A| CTRL-A do completion on the pattern in front of the cursor and insert all matches @@ -1111,23 +1110,23 @@ to terminal mode. You found it, Arthur! *holy-grail* ============================================================================== -6. EX commands *ex-cmd-index* *:index* +6. EX commands *ex-commands* *ex-cmd-index* *:index* This is a brief but complete listing of all the ":" commands, without mentioning any arguments. The optional part of the command name is inside []. The commands are sorted on the non-optional part of their name. tag command action ~ ------------------------------------------------------------------------------- +------------------------------------------------------------------------------ ~ |:| : nothing |:range| :{range} go to last line in {range} |:!| :! filter lines or execute an external command |:!!| :!! repeat last ":!" command |:#| :# same as ":number" |:&| :& repeat last ":substitute" -|:star| :* execute contents of a register +|:star| :* use the last Visual area, like :'<,'> |:<| :< shift lines one 'shiftwidth' left -|:=| := print the cursor line number +|:=| := print the last line number |:>| :> shift lines one 'shiftwidth' right |:@| :@ execute contents of a register |:@@| :@@ repeat the previous ":@" @@ -1209,8 +1208,8 @@ tag command action ~ |:cgetfile| :cg[etfile] read file with error messages |:changes| :changes print the change list |:chdir| :chd[ir] change directory -|:checkhealth| :checkh[ealth] run healthchecks -|:checkpath| :che[ckpath] list included files +|:checkhealth| :che[ckhealth] run healthchecks +|:checkpath| :checkp[ath] list included files |:checktime| :checkt[ime] check timestamp of loaded buffers |:chistory| :chi[story] list the error lists |:clast| :cla[st] go to the specified error, default last one @@ -1240,8 +1239,6 @@ tag command action ~ |:cpfile| :cpf[ile] go to last error in previous file |:cquit| :cq[uit] quit Vim with an error code |:crewind| :cr[ewind] go to the specified error, default first one -|:cscope| :cs[cope] execute cscope command -|:cstag| :cst[ag] use cscope to jump to a tag |:cunmap| :cu[nmap] like ":unmap" but for Command-line mode |:cunabbrev| :cuna[bbrev] like ":unabbrev" but for Command-line mode |:cunmenu| :cunme[nu] remove menu for Command-line mode @@ -1313,7 +1310,6 @@ tag command action ~ |:grepadd| :grepa[dd] like :grep, but append to current list |:gui| :gu[i] start the GUI |:gvim| :gv[im] start the GUI -|:hardcopy| :ha[rdcopy] send text to the printer |:help| :h[elp] open a help window |:helpclose| :helpc[lose] close one help window |:helpgrep| :helpg[rep] like ":grep" but searches help files @@ -1321,6 +1317,7 @@ tag command action ~ |:highlight| :hi[ghlight] specify highlighting methods |:hide| :hid[e] hide current buffer for a command |:history| :his[tory] print a history list +|:horizontal| :hor[izontal] following window command work horizontally |:insert| :i[nsert] insert text |:iabbrev| :ia[bbrev] like ":abbrev" but for Insert mode |:iabclear| :iabc[lear] like ":abclear" but for Insert mode @@ -1365,7 +1362,6 @@ tag command action ~ |:lcd| :lc[d] change directory locally |:lchdir| :lch[dir] change directory locally |:lclose| :lcl[ose] close location window -|:lcscope| :lcs[cope] like ":cscope" but uses location list |:ldo| :ld[o] execute command in valid location list entries |:lfdo| :lfd[o] execute command in each file in location list |:left| :le[ft] left align lines @@ -1546,7 +1542,6 @@ tag command action ~ buffer list |:scriptnames| :scr[iptnames] list names of all sourced Vim scripts |:scriptencoding| :scripte[ncoding] encoding used in sourced Vim script -|:scscope| :scs[cope] split window and execute cscope command |:set| :se[t] show or set options |:setfiletype| :setf[iletype] set 'filetype', unless it was set already |:setglobal| :setg[lobal] show global values of options @@ -1637,6 +1632,7 @@ tag command action ~ |:topleft| :to[pleft] make split window appear at top or far left |:tprevious| :tp[revious] jump to previous matching tag |:trewind| :tr[ewind] jump to first matching tag +|:trust| :trust add or remove file from trust database |:try| :try execute commands, abort on error or exception |:tselect| :ts[elect] list matching tags and select one |:tunmap| :tunma[p] like ":unmap" but for |Terminal-mode| diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt index 6b0899334b..e608b431f2 100644 --- a/runtime/doc/insert.txt +++ b/runtime/doc/insert.txt @@ -257,8 +257,8 @@ CTRL-] Trigger abbreviation, without inserting a character. *i_<Insert>* <Insert> Toggle between Insert and Replace mode. ------------------------------------------------------------------------ +----------------------------------------------------------------------- *i_backspacing* The effect of the <BS>, CTRL-W, and CTRL-U depend on the 'backspace' option (unless 'revins' is set). This is a comma-separated list of items: @@ -378,6 +378,7 @@ CTRL-G u close undo sequence, start new change *i_CTRL-G_u* CTRL-G U don't start a new undo block with the next *i_CTRL-G_U* left/right cursor movement, if the cursor stays within the same line + ----------------------------------------------------------------------- The CTRL-O command sometimes has a side effect: If the cursor was beyond the @@ -650,9 +651,9 @@ When the popup menu is displayed there are a few more special keys, see |popupmenu-keys|. Note: The keys that are valid in CTRL-X mode are not mapped. This allows for -":map ^F ^X^F" to work (where ^F is CTRL-F and ^X is CTRL-X). The key that -ends CTRL-X mode (any key that is not a valid CTRL-X mode command) is mapped. -Also, when doing completion with 'complete' mappings apply as usual. +`:map <C-F> <C-X><C-F>` to work. The key that ends CTRL-X mode (any key that +is not a valid CTRL-X mode command) is mapped. Also, when doing completion +with 'complete' mappings apply as usual. *E565* Note: While completion is active Insert mode can't be used recursively and @@ -661,10 +662,10 @@ will generate an E565 error. The following mappings are suggested to make typing the completion commands a bit easier (although they will hide other commands): > - :inoremap ^] ^X^] - :inoremap ^F ^X^F - :inoremap ^D ^X^D - :inoremap ^L ^X^L + :inoremap <C-]> <C-X><C-]> + :inoremap <C-F> <C-X><C-F> + :inoremap <C-D> <C-X><C-D> + :inoremap <C-L> <C-X><C-L> As a special case, typing CTRL-R to perform register insertion (see |i_CTRL-R|) will not exit CTRL-X mode. This is primarily to allow the use of @@ -857,29 +858,27 @@ invoked and what it should return. Here is an example that uses the "aiksaurus" command (provided by Magnus Groß): > - func Thesaur(findstart, base) - if a:findstart - let line = getline('.') - let start = col('.') - 1 - while start > 0 && line[start - 1] =~ '\a' - let start -= 1 - endwhile - return start - else - let res = [] - let h = '' - for l in split(system('aiksaurus ' .. shellescape(a:base)), '\n') - if l[:3] == '=== ' - let h = substitute(l[4:], ' =*$', '', '') - elseif l[0] =~ '\a' - call extend(res, map(split(l, ', '), {_, val -> {'word': val, 'menu': '('.h.')'}})) - endif - endfor - return res - endif - endfunc - - set thesaurusfunc=Thesaur + func Thesaur(findstart, base) + if a:findstart + return searchpos('\<', 'bnW', line('.'))[1] - 1 + endif + let res = [] + let h = '' + for l in systemlist('aiksaurus ' .. shellescape(a:base)) + if l[:3] == '=== ' + let h = '(' .. substitute(l[4:], ' =*$', ')', '') + elseif l ==# 'Alphabetically similar known words are: ' + let h = "\U0001f52e" + elseif l[0] =~ '\a' || (h ==# "\U0001f52e" && l[0] ==# "\t") + call extend(res, map(split(substitute(l, '^\t', '', ''), ', '), {_, val -> {'word': val, 'menu': h}})) + endif + endfor + return res + endfunc + + if exists('+thesaurusfunc') + set thesaurusfunc=Thesaur + endif Completing keywords in the current and included files *compl-keyword* @@ -1126,7 +1125,8 @@ that contains the List. The Dict can have these items: leading text is changed. Other items are ignored. -For acting upon end of completion, see the |CompleteDone| autocommand event. +For acting upon end of completion, see the |CompleteDonePre| and +|CompleteDone| autocommand event. For example, the function can contain this: > let matches = ... list of words ... @@ -1349,16 +1349,8 @@ Completion of C code requires a tags file. You should use Universal/ Exuberant ctags, because it adds extra information that is needed for completion. You can find it here: Universal Ctags: https://ctags.io - Exuberant Ctags: http://ctags.sourceforge.net - -Universal Ctags is preferred, Exuberant Ctags is no longer being developed. -For Exuberant ctags, version 5.6 or later is recommended. For version 5.5.4 -you should add a patch that adds the "typename:" field: - ftp://ftp.vim.org/pub/vim/unstable/patches/ctags-5.5.4.patch -A compiled .exe for MS-Windows can be found at: - http://ctags.sourceforge.net/ - https://github.com/universal-ctags/ctags-win32 +Universal Ctags is preferred, Exuberant Ctags is no longer maintained. If you want to complete system functions you can do something like this. Use ctags to generate a tags file for all the system header files: > @@ -1458,14 +1450,14 @@ DOM compatibility At the moment (beginning of 2006) there are two main browsers - MS Internet Explorer and Mozilla Firefox. These two applications are covering over 90% of market. Theoretically standards are created by W3C organisation -(http://www.w3c.org) but they are not always followed/implemented. - +(https://www.w3.org/) but they are not always followed/implemented. +> IE FF W3C Omni completion ~ +/- +/- + + ~ + + - + ~ + - - - ~ - + - - ~ - +< Regardless from state of implementation in browsers but if element is defined in standards, completion plugin will place element in suggestion list. When both major engines implemented element, even if this is not in standards it @@ -1479,7 +1471,6 @@ external files and for class aware completion. You should use Universal/ Exuberant ctags version 5.5.4 or newer. You can find it here: Universal Ctags: https://ctags.io - Exuberant Ctags: http://ctags.sourceforge.net Script completes: @@ -1519,7 +1510,7 @@ RUBY *ft-ruby-omni* NOTE: |compl-omni| for Ruby code requires |provider-ruby| to be installed. Ruby completion will parse your buffer on demand in order to provide a list of -completions. These completions will be drawn from modules loaded by 'require' +completions. These completions will be drawn from modules loaded by "require" and modules defined in the current buffer. The completions provided by CTRL-X CTRL-O are sensitive to the context: @@ -1533,7 +1524,7 @@ The completions provided by CTRL-X CTRL-O are sensitive to the context: 3. After '.', '::' or ':' Methods applicable to the object being dereferenced - 4. After ':' or ':foo' Symbol name (beginning with 'foo') + 4. After ':' or ':foo' Symbol name (beginning with "foo") Notes: - Vim will load/evaluate code in order to provide completions. This may @@ -1759,7 +1750,7 @@ In the example four special elements are visible: dialect. 2. If the list containing possible values of attributes has one element and this element is equal to the name of the attribute this attribute will be - treated as boolean and inserted as 'attrname' and not as 'attrname="' + treated as boolean and inserted as "attrname" and not as 'attrname="' 3. "vimxmltaginfo" - a special key with a Dictionary containing tag names as keys and two element List as values, for additional menu info and the long description. @@ -1778,12 +1769,12 @@ DTD -> Vim *dtd2vim* On |www| is the script |dtd2vim| which parses DTD and creates an XML data file for Vim XML omni completion. - dtd2vim: http://www.vim.org/scripts/script.php?script_id=1462 + dtd2vim: https://www.vim.org/scripts/script.php?script_id=1462 Check the beginning of that file for usage details. The script requires perl and: - perlSGML: http://savannah.nongnu.org/projects/perlsgml + perlSGML: https://savannah.nongnu.org/projects/perlsgml Commands diff --git a/runtime/doc/intro.txt b/runtime/doc/intro.txt index ae80935032..6bf6850ccf 100644 --- a/runtime/doc/intro.txt +++ b/runtime/doc/intro.txt @@ -308,7 +308,7 @@ These names for keys are used in the documentation. They can also be used with the ":map" command. notation meaning equivalent decimal value(s) ~ ------------------------------------------------------------------------ +----------------------------------------------------------------------- ~ <Nul> zero CTRL-@ 0 (stored as 10) *<Nul>* <BS> backspace CTRL-H 8 *backspace* <Tab> tab CTRL-I 9 *tab* *Tab* @@ -373,7 +373,7 @@ notation meaning equivalent decimal value(s) ~ <M-…> alt-key or meta-key *META* *ALT* *<M-* <A-…> same as <M-…> *<A-* <D-…> command-key or "super" key *<D-* ------------------------------------------------------------------------ +----------------------------------------------------------------------- ~ Note: @@ -408,14 +408,18 @@ the ":map" command. The rules are: The <> notation uses <lt> to escape the special meaning of key names. Using a backslash also works, but only when 'cpoptions' does not include the 'B' flag. -Examples for mapping CTRL-H to the six characters "<Home>": > +Examples for mapping CTRL-H to the six characters "<Home>": >vim :imap <C-H> \<Home> :imap <C-H> <lt>Home> The first one only works when the 'B' flag is not in 'cpoptions'. The second one always works. -To get a literal "<lt>" in a mapping: > +To get a literal "<lt>" in a mapping: >vim :map <C-L> <lt>lt> +The notation can be used in a double quoted strings, using "\<" at the start, +e.g. "\<C-Space>". This results in a special key code. To convert this back +to readable text use `keytrans()`. + ============================================================================== Modes, introduction *vim-modes-intro* *vim-modes* @@ -516,39 +520,39 @@ CTRL-O in Insert mode you get a beep but you are still in Insert mode, type TO mode ~ Normal Visual Select Insert Replace Cmd-line Ex ~ FROM mode ~ -Normal v V ^V *4 *1 R gR : / ? ! Q -Visual *2 ^G c C -- : -- -Select *5 ^O ^G *6 -- -- -- +Normal v V ^V `*4` *1 R gR : / ? ! Q +Visual `*2` ^G c C -- : -- +Select `*5` ^O ^G `*6` -- -- -- Insert <Esc> -- -- <Insert> -- -- Replace <Esc> -- -- <Insert> -- -- -Command-line *3 -- -- :start -- -- +Command-line `*3` -- -- :start -- -- Ex :vi -- -- -- -- -- -- not possible -*1 Go from Normal mode to Insert mode by giving the command "i", "I", "a", - "A", "o", "O", "c", "C", "s" or S". -*2 Go from Visual mode to Normal mode by giving a non-movement command, which - causes the command to be executed, or by hitting <Esc> "v", "V" or "CTRL-V" - (see |v_v|), which just stops Visual mode without side effects. -*3 Go from Command-line mode to Normal mode by: - - Hitting <CR> or <NL>, which causes the entered command to be executed. - - Deleting the complete line (e.g., with CTRL-U) and giving a final <BS>. - - Hitting CTRL-C or <Esc>, which quits the command-line without executing - the command. - In the last case <Esc> may be the character defined with the 'wildchar' - option, in which case it will start command-line completion. You can - ignore that and type <Esc> again. -*4 Go from Normal to Select mode by: - - use the mouse to select text while 'selectmode' contains "mouse" - - use a non-printable command to move the cursor while keeping the Shift - key pressed, and the 'selectmode' option contains "key" - - use "v", "V" or "CTRL-V" while 'selectmode' contains "cmd" - - use "gh", "gH" or "g CTRL-H" |g_CTRL-H| -*5 Go from Select mode to Normal mode by using a non-printable command to move - the cursor, without keeping the Shift key pressed. -*6 Go from Select mode to Insert mode by typing a printable character. The - selection is deleted and the character is inserted. +* 1 Go from Normal mode to Insert mode by giving the command "i", "I", "a", + "A", "o", "O", "c", "C", "s" or S". +* 2 Go from Visual mode to Normal mode by giving a non-movement command, which + causes the command to be executed, or by hitting <Esc> "v", "V" or "CTRL-V" + (see |v_v|), which just stops Visual mode without side effects. +* 3 Go from Command-line mode to Normal mode by: + - Hitting <CR> or <NL>, which causes the entered command to be executed. + - Deleting the complete line (e.g., with CTRL-U) and giving a final <BS>. + - Hitting CTRL-C or <Esc>, which quits the command-line without executing + the command. + In the last case <Esc> may be the character defined with the 'wildchar' + option, in which case it will start command-line completion. You can + ignore that and type <Esc> again. +* 4 Go from Normal to Select mode by: + - use the mouse to select text while 'selectmode' contains "mouse" + - use a non-printable command to move the cursor while keeping the Shift + key pressed, and the 'selectmode' option contains "key" + - use "v", "V" or "CTRL-V" while 'selectmode' contains "cmd" + - use "gh", "gH" or "g CTRL-H" |g_CTRL-H| +* 5 Go from Select mode to Normal mode by using a non-printable command to move + the cursor, without keeping the Shift key pressed. +* 6 Go from Select mode to Insert mode by typing a printable character. The + selection is deleted and the character is inserted. *CTRL-\_CTRL-N* *i_CTRL-\_CTRL-N* *c_CTRL-\_CTRL-N* *v_CTRL-\_CTRL-N* *t_CTRL-\_CTRL-N* @@ -585,26 +589,26 @@ Lines longer than the window width will wrap, unless the 'wrap' option is off If the window has room after the last line of the buffer, Vim will show '~' in the first column of the last lines in the window, like this: - +> +-----------------------+ |some line | |last line | |~ | |~ | +-----------------------+ - +< Thus the '~' lines indicate that the end of the buffer was reached. If the last line in a window doesn't fit, Vim will indicate this with a '@' in the first column of the last lines in the window, like this: - +> +-----------------------+ |first line | |second line | |@ | |@ | +-----------------------+ - +< Thus the '@' lines indicate that there is a line that doesn't fit in the window. @@ -612,14 +616,14 @@ When the "lastline" flag is present in the 'display' option, you will not see '@' characters at the left side of window. If the last line doesn't fit completely, only the part that fits is shown, and the last three characters of the last line are replaced with "@@@", like this: - +> +-----------------------+ |first line | |second line | |a very long line that d| |oesn't fit in the wi@@@| +-----------------------+ - +< If there is a single line that is too long to fit in the window, this is a special situation. Vim will show only part of the line, around where the cursor is. There are no special characters shown, so that you can edit all @@ -700,9 +704,9 @@ Definitions *definitions* *jargon* A screen contains one or more windows, separated by status lines and with the command line at the bottom. - +> +-------------------------------+ -screen | window 1 | window 2 | + screen | window 1 | window 2 | | | | | | | |= status line =|= status line =| @@ -712,7 +716,7 @@ screen | window 1 | window 2 | |==== status line ==============| |command line | +-------------------------------+ - +< The command line is also used for messages. It scrolls up the screen when there is not enough room in the command line. diff --git a/runtime/doc/job_control.txt b/runtime/doc/job_control.txt index 6a9d865c40..37a4e2ebb1 100644 --- a/runtime/doc/job_control.txt +++ b/runtime/doc/job_control.txt @@ -30,7 +30,7 @@ Usage *job-control-usage* To control jobs, use the "job…" family of functions: |jobstart()|, |jobstop()|, etc. -Example: > +Example: >vim function! s:OnEvent(job_id, data, event) dict if a:event == 'stdout' @@ -51,7 +51,7 @@ Example: > let job1 = jobstart(['bash'], extend({'shell': 'shell 1'}, s:callbacks)) let job2 = jobstart(['bash', '-c', 'for i in {1..10}; do echo hello $i!; sleep 1; done'], extend({'shell': 'shell 2'}, s:callbacks)) -To test the above script, copy it to a file ~/foo.vim and run it: > +To test the above script, copy it to a file ~/foo.vim and run it: >bash nvim -u ~/foo.vim < Description of what happens: @@ -75,7 +75,7 @@ Arguments passed to on_exit callback: will not trigger the on_stdout/on_stderr callback (but if the process ends, the on_exit callback will be invoked). For example, "ruby -e" buffers output, so small strings will be - buffered unless "auto-flushing" ($stdout.sync=true) is enabled. > + buffered unless "auto-flushing" ($stdout.sync=true) is enabled. >vim function! Receive(job_id, data, event) echom printf('%s: %s',a:event,string(a:data)) endfunction @@ -92,7 +92,7 @@ Arguments passed to on_exit callback: - `abc\nefg` may arrive as `['abc', '']`, `['efg']` or `['abc']`, `['','efg']`, or even `['ab']`, `['c','efg']`. Easy way to deal with this: initialize a list as `['']`, then append - to it as follows: > + to it as follows: >vim let s:chunks = [''] func! s:on_stdout(job_id, data, event) dict let s:chunks[-1] .= a:data[0] @@ -101,7 +101,7 @@ Arguments passed to on_exit callback: < The |jobstart-options| dictionary is passed as |self| to the callback. -The above example could be written in this "object-oriented" style: > +The above example could be written in this "object-oriented" style: >vim let Shell = {} @@ -129,16 +129,16 @@ The above example could be written in this "object-oriented" style: > let instance = Shell.new('bomb', \ 'for i in $(seq 9 -1 1); do echo $i 1>&$((i % 2 + 1)); sleep 1; done') < -To send data to the job's stdin, use |chansend()|: > +To send data to the job's stdin, use |chansend()|: >vim :call chansend(job1, "ls\n") :call chansend(job1, "invalid-command\n") :call chansend(job1, "exit\n") < -A job may be killed with |jobstop()|: > +A job may be killed with |jobstop()|: >vim :call jobstop(job1) < A job may be killed at any time with the |jobstop()| function: -> +>vim :call jobstop(job1) < Individual streams can be closed without killing the job, see |chanclose()|. diff --git a/runtime/doc/lsp-extension.txt b/runtime/doc/lsp-extension.txt index 6e9ad940c7..fe72e9eb18 100644 --- a/runtime/doc/lsp-extension.txt +++ b/runtime/doc/lsp-extension.txt @@ -6,7 +6,7 @@ The `vim.lsp` Lua module is a framework for building LSP plugins. 1. Start with |vim.lsp.start_client()| and |vim.lsp.buf_attach_client()|. - 2. Peek at the API: > + 2. Peek at the API: >vim :lua print(vim.inspect(vim.lsp)) < 3. See |lsp-extension-example| for a full example. @@ -30,7 +30,7 @@ The example will: 3. Create a new LSP for that root directory if one doesn't exist. 4. Attach the buffer to the client for that root directory. -> +>lua -- Some path manipulation utilities local function is_dir(filename) local stat = vim.loop.fs_stat(filename) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 7fc0daa0ca..215515a2d9 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -33,40 +33,40 @@ Follow these steps to get LSP features: 2. Configure the LSP client per language server. A minimal example: -> +>lua vim.lsp.start({ name = 'my-server-name', cmd = {'name-of-language-server-executable'}, root_dir = vim.fs.dirname(vim.fs.find({'setup.py', 'pyproject.toml'}, { upward = true })[1]), }) < - See |vim.lsp.start| for details. + See |vim.lsp.start()| for details. 3. Configure keymaps and autocmds to utilize LSP features. See |lsp-config|. -< + *lsp-config* Starting a LSP client will automatically report diagnostics via -|vim.diagnostic|. Read |vim.diagnostic.config| to learn how to customize the +|vim.diagnostic|. Read |vim.diagnostic.config()| to learn how to customize the display. It also sets some buffer options if the options are otherwise empty and if the language server supports the functionality. -- |omnifunc| is set to |vim.lsp.omnifunc|. This allows to trigger completion - using |i_CTRL-X_CTRL-o| -- |tagfunc| is set to |vim.lsp.tagfunc|. This enables features like +- 'omnifunc' is set to |vim.lsp.omnifunc()|. This allows to trigger completion + using |i_CTRL-X_CTRL-O| +- 'tagfunc' is set to |vim.lsp.tagfunc()|. This enables features like go-to-definition, |:tjump|, and keymaps like |CTRL-]|, |CTRL-W_]|, |CTRL-W_}| to utilize the language server. -- |formatexpr| is set to |vim.lsp.formatexpr| if both |formatprg| and - |formatexpr| are empty. This allows to format lines via |gq| if the language +- 'formatexpr' is set to |vim.lsp.formatexpr()| if both 'formatprg' and + 'formatexpr' are empty. This allows to format lines via |gq| if the language server supports it. To use other LSP features like hover, rename, etc. you can setup some additional keymaps. It's recommended to setup them in a |LspAttach| autocmd to ensure they're only active if there is a LSP client running. An example: -> +>lua vim.api.nvim_create_autocmd('LspAttach', { callback = function(args) vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf }) @@ -86,7 +86,7 @@ The most used functions are: Not all language servers provide the same capabilities. To ensure you only set keymaps if the language server supports a feature, you can guard the keymap calls behind capability checks: -> +>lua vim.api.nvim_create_autocmd('LspAttach', { callback = function(args) local client = vim.lsp.get_client_by_id(args.data.client_id) @@ -100,7 +100,7 @@ calls behind capability checks: To learn what capabilities are available you can run the following command in a buffer with a started LSP client: -> +>vim :lua =vim.lsp.get_active_clients()[1].server_capabilities < @@ -110,14 +110,14 @@ Full list of features provided by default can be found in |lsp-buf|. FAQ *lsp-faq* - Q: How to force-reload LSP? - A: Stop all clients, then reload the buffer. > + A: Stop all clients, then reload the buffer. >vim :lua vim.lsp.stop_client(vim.lsp.get_active_clients()) :edit - Q: Why isn't completion working? A: In the buffer where you want to use LSP, check that 'omnifunc' is set to - "v:lua.vim.lsp.omnifunc": > + "v:lua.vim.lsp.omnifunc": >vim :verbose set omnifunc? @@ -126,13 +126,14 @@ FAQ *lsp-faq* "after/ftplugin/python.vim". - Q: How do I run a request synchronously (e.g. for formatting on file save)? - A: Use the `_sync` variant of the function provided by |lsp-buf|, if it - exists. + A: Check if the function has an `async` parameter and set the value to + false. - E.g. code formatting: > + E.g. code formatting: >vim " Auto-format *.rs (rust) files prior to saving them - autocmd BufWritePre *.rs lua vim.lsp.buf.formatting_sync(nil, 1000) + " (async = false is the default for format) + autocmd BufWritePre *.rs lua vim.lsp.buf.format({ async = false }) < *lsp-vs-treesitter* @@ -161,7 +162,7 @@ to the given buffer. |lsp-buf| LSP request/response handlers are implemented as Lua functions (see |lsp-handler|). The |vim.lsp.handlers| table defines default handlers used -when creating a new client. Keys are LSP method names: > +when creating a new client. Keys are LSP method names: >vim :lua print(vim.inspect(vim.tbl_keys(vim.lsp.handlers))) < @@ -189,6 +190,7 @@ specification. These LSP requests/notifications are defined by default: textDocument/typeDefinition* window/logMessage window/showMessage + window/showDocument window/showMessageRequest workspace/applyEdit workspace/symbol @@ -244,7 +246,7 @@ For |lsp-request|, each |lsp-handler| has this signature: > Where `err` must be shaped like an RPC error: `{ code, message, data? }` - You can use |vim.lsp.rpc_response_error()| to create this object. + You can use |vim.lsp.rpc.rpc_response_error()| to create this object. For |lsp-notification|, each |lsp-handler| has this signature: > @@ -289,7 +291,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method To configure the behavior of |vim.lsp.diagnostic.on_publish_diagnostics()|, consider the following example, where a new |lsp-handler| is created using - |vim.lsp.with()| that no longer generates signs for the diagnostics: > + |vim.lsp.with()| that no longer generates signs for the diagnostics: >lua vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { @@ -299,7 +301,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method ) < To enable signs, use |vim.lsp.with()| again to create and assign a new - |lsp-handler| to |vim.lsp.handlers| for the associated method: > + |lsp-handler| to |vim.lsp.handlers| for the associated method: >lua vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { @@ -309,7 +311,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method ) < To configure a handler on a per-server basis, you can use the {handlers} key - for |vim.lsp.start_client()| > + for |vim.lsp.start_client()| >lua vim.lsp.start_client { ..., -- Other configuration omitted. @@ -323,7 +325,8 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method }, } < - or if using 'nvim-lspconfig', you can use the {handlers} key of `setup()`: > + or if using "nvim-lspconfig", you can use the {handlers} key of `setup()`: + >lua require('lspconfig').rust_analyzer.setup { handlers = { @@ -337,8 +340,8 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method } < Some handlers do not have an explicitly named handler function (such as - |on_publish_diagnostics()|). To override these, first create a reference - to the existing handler: > + ||vim.lsp.diagnostic.on_publish_diagnostics()|). To override these, first + create a reference to the existing handler: >lua local on_references = vim.lsp.handlers["textDocument/references"] vim.lsp.handlers["textDocument/references"] = vim.lsp.with( @@ -355,14 +358,14 @@ Handlers can be set by: vim.lsp.handlers is a global table that contains the default mapping of |lsp-method| names to |lsp-handlers|. - To override the handler for the `"textDocument/definition"` method: > + To override the handler for the `"textDocument/definition"` method: >lua vim.lsp.handlers["textDocument/definition"] = my_custom_default_definition < -- The {handlers} parameter for |vim.lsp.start_client|. +- The {handlers} parameter for |vim.lsp.start_client()|. This will set the |lsp-handler| as the default handler for this server. - For example: > + For example: >lua vim.lsp.start_client { ..., -- Other configuration omitted. @@ -374,7 +377,7 @@ Handlers can be set by: - The {handler} parameter for |vim.lsp.buf_request()|. This will set the |lsp-handler| ONLY for the current request. - For example: > + For example: >lua vim.lsp.buf_request( 0, @@ -401,7 +404,7 @@ and helper functions for creating protocol-related objects. https://github.com/microsoft/language-server-protocol/raw/gh-pages/_specifications/specification-3-14.md For example `vim.lsp.protocol.ErrorCodes` allows reverse lookup by number or -name: > +name: >lua vim.lsp.protocol.TextDocumentSyncKind.Full == 1 vim.lsp.protocol.TextDocumentSyncKind[1] == "Full" @@ -424,7 +427,7 @@ For the format of the notification message, see: - `context` table|nil. `ctx` from |lsp-handler| This table can be used with vim.fn.setqflist or vim.fn.setloclist. E.g.: -> +>lua local function on_list(options) vim.fn.setqflist({}, ' ', options) vim.api.nvim_command('cfirst') @@ -434,7 +437,7 @@ This table can be used with vim.fn.setqflist or vim.fn.setloclist. E.g.: vim.lsp.buf.references(nil, {on_list=on_list}) < If you prefer loclist do something like this: -> +>lua local function on_list(options) vim.fn.setloclist(0, {}, ' ', options) vim.api.nvim_command('lopen') @@ -468,7 +471,7 @@ LspCodeLens |nvim_buf_set_extmark()|. LspCodeLensSeparator *hl-LspCodeLensSeparator* - Used to color the separator between two or more code lens. + Used to color the separator between two or more code lenses. *lsp-highlight-signature* @@ -485,7 +488,7 @@ EVENTS *lsp-events* *LspAttach* After an LSP client attaches to a buffer. The |autocmd-pattern| is the name of the buffer. When used from Lua, the client ID is passed to the -callback in the "data" table. Example: > +callback in the "data" table. Example: >lua vim.api.nvim_create_autocmd("LspAttach", { callback = function(args) @@ -503,7 +506,7 @@ callback in the "data" table. Example: > *LspDetach* Just before an LSP client detaches from a buffer. The |autocmd-pattern| is the name of the buffer. When used from Lua, the client ID is passed to the -callback in the "data" table. Example: > +callback in the "data" table. Example: >lua vim.api.nvim_create_autocmd("LspDetach", { callback = function(args) @@ -513,7 +516,7 @@ callback in the "data" table. Example: > end, }) < -In addition, the following |User| |autocommands| are provided: +Also the following |User| |autocommand|s are provided: LspProgressUpdate *LspProgressUpdate* Upon receipt of a progress notification from the server. See @@ -523,7 +526,7 @@ LspRequest *LspRequest* After a change to the active set of pending LSP requests. See {requests} in |vim.lsp.client|. -Example: > +Example: >vim autocmd User LspProgressUpdate redrawstatus autocmd User LspRequest redrawstatus < @@ -538,8 +541,8 @@ buf_attach_client({bufnr}, {client_id}) *vim.lsp.buf_attach_client()* Without calling this, the server won't be notified of changes to a buffer. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current - {client_id} (number) Client id + • {bufnr} (number) Buffer handle, or 0 for current + • {client_id} (number) Client id buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()* Detaches client from the specified buffer. Note: While the server is @@ -547,23 +550,23 @@ buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()* send notifications should it ignore this notification. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current - {client_id} (number) Client id + • {bufnr} (number) Buffer handle, or 0 for current + • {client_id} (number) Client id buf_is_attached({bufnr}, {client_id}) *vim.lsp.buf_is_attached()* Checks if a buffer is attached for a particular client. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current - {client_id} (number) the client id + • {bufnr} (number) Buffer handle, or 0 for current + • {client_id} (number) the client id buf_notify({bufnr}, {method}, {params}) *vim.lsp.buf_notify()* Send a notification to a server Parameters: ~ - {bufnr} [number] (optional): The number of the buffer - {method} [string]: Name of the request method - {params} [string]: Arguments to send to the server + • {bufnr} (number|nil) The number of the buffer + • {method} (string) Name of the request method + • {params} (any) Arguments to send to the server Return: ~ true if any client returns true; false otherwise @@ -575,10 +578,10 @@ buf_request_all({bufnr}, {method}, {params}, {callback}) |vim.lsp.buf_request()| but the return result and callback are different. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current. - {method} (string) LSP method name - {params} (optional, table) Parameters to send to the server - {callback} (function) The callback to call when all requests are + • {bufnr} (number) Buffer handle, or 0 for current. + • {method} (string) LSP method name + • {params} (table|nil) Parameters to send to the server + • {callback} (function) The callback to call when all requests are finished. Return: ~ @@ -594,11 +597,11 @@ buf_request_sync({bufnr}, {method}, {params}, {timeout_ms}) result is different. Wait maximum of {timeout_ms} (default 1000) ms. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current. - {method} (string) LSP method name - {params} (optional, table) Parameters to send to the server - {timeout_ms} (optional, number, default=1000) Maximum time in - milliseconds to wait for a result. + • {bufnr} (number) Buffer handle, or 0 for current. + • {method} (string) LSP method name + • {params} (table|nil) Parameters to send to the server + • {timeout_ms} (number|nil) Maximum time in milliseconds to wait for a + result. Defaults to 1000 Return: ~ Map of client_id:request_result. On timeout, cancel or error, returns @@ -665,7 +668,7 @@ client_is_stopped({client_id}) *vim.lsp.client_is_stopped()* Checks whether a client is stopped. Parameters: ~ - {client_id} (Number) + • {client_id} (number) Return: ~ true if client is stopped, false otherwise. @@ -675,10 +678,10 @@ for_each_buffer_client({bufnr}, {fn}) Invokes a function for each LSP client attached to a buffer. Parameters: ~ - {bufnr} (number) Buffer number - {fn} (function) Function to run on each client attached to buffer + • {bufnr} (number) Buffer number + • {fn} (function) Function to run on each client attached to buffer {bufnr}. The function takes the client, client ID, and buffer - number as arguments. Example: > + number as arguments. Example: >lua vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr) print(vim.inspect(client)) @@ -695,7 +698,7 @@ formatexpr({opts}) *vim.lsp.formatexpr()* 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')`. Parameters: ~ - {opts} (table) options for customizing the formatting expression + • {opts} (table) options for customizing the formatting expression which takes the following optional keys: • timeout_ms (default 500ms). The timeout period for the formatting request. @@ -704,7 +707,7 @@ get_active_clients({filter}) *vim.lsp.get_active_clients()* Get active clients. Parameters: ~ - {filter} (table|nil) A table with key-value pairs used to filter the + • {filter} (table|nil) A table with key-value pairs used to filter the returned clients. The available keys are: • id (number): Only return clients with the given id • bufnr (number): Only return clients attached to this @@ -719,17 +722,17 @@ get_buffers_by_client_id({client_id}) Returns list of buffers attached to client_id. Parameters: ~ - {client_id} (number) client id + • {client_id} (number) client id Return: ~ - list of buffer ids + (list) of buffer ids get_client_by_id({client_id}) *vim.lsp.get_client_by_id()* Gets a client by id, or nil if the id is invalid. The returned client may not yet be fully initialized. Parameters: ~ - {client_id} (number) client id + • {client_id} (number) client id Return: ~ |vim.lsp.client| object, or nil @@ -744,8 +747,8 @@ omnifunc({findstart}, {base}) *vim.lsp.omnifunc()* Implements 'omnifunc' compatible LSP completion. Parameters: ~ - {findstart} 0 or 1, decides behavior - {base} If findstart=0, text to match against + • {findstart} (number) 0 or 1, decides behavior + • {base} (number) findstart=0, text to match against Return: ~ (number) Decided by {findstart}: @@ -767,7 +770,7 @@ set_log_level({level}) *vim.lsp.set_log_level()* Use `lsp.log_levels` for reverse lookup. Parameters: ~ - {level} [number|string] the case insensitive level name or number + • {level} (number|string) the case insensitive level name or number See also: ~ |vim.lsp.log_levels| @@ -777,173 +780,170 @@ start({config}, {opts}) *vim.lsp.start()* running client if one is found matching `name` and `root_dir`. Attaches the current buffer to the client. - Example: -> + Example: >lua - vim.lsp.start({ - name = 'my-server-name', - cmd = {'name-of-language-server-executable'}, - root_dir = vim.fs.dirname(vim.fs.find({'pyproject.toml', 'setup.py'}, { upward = true })[1]), - }) + vim.lsp.start({ + name = 'my-server-name', + cmd = {'name-of-language-server-executable'}, + root_dir = vim.fs.dirname(vim.fs.find({'pyproject.toml', 'setup.py'}, { upward = true })[1]), + }) < - See |lsp.start_client| for all available options. The most important are: - - `name` is an arbitrary name for the LSP client. It should be unique per - language server. - - `cmd` the command as list - used to start the language server. The command must - be present in the `$PATH` environment variable or an absolute path to the executable. Shell - constructs like `~` are NOT expanded. - - `root_dir` path to the project root. By default this is used to decide if - an existing client should be re-used. The example above uses |vim.fs.find| - and |vim.fs.dirname| to detect the root by traversing the file system - upwards starting from the current directory until either a - `pyproject.toml` or `setup.py` file is found. - - `workspace_folders` a list of { uri:string, name: string } tables. The - project root folders used by the language server. If `nil` the property is - derived from the `root_dir` for convenience. + See |vim.lsp.start_client()| for all available options. The most important + are: + + • `name` arbitrary name for the LSP client. Should be unique per language + server. + • `cmd` command (in list form) used to start the language server. Must be + absolute, or found on `$PATH`. Shell constructs like `~` are not + expanded. + • `root_dir` path to the project root. By default this is used to decide + if an existing client should be re-used. The example above uses + |vim.fs.find()| and |vim.fs.dirname()| to detect the root by traversing + the file system upwards starting from the current directory until either + a `pyproject.toml` or `setup.py` file is found. + • `workspace_folders` list of `{ uri:string, name: string }` tables + specifying the project root folders used by the language server. If + `nil` the property is derived from `root_dir` for convenience. Language servers use this information to discover metadata like the dependencies of your project and they tend to index the contents within the project folder. To ensure a language server is only started for languages it can handle, - make sure to call |vim.lsp.start| within a |FileType| autocmd. Either use - |:au|, |nvim_create_autocmd()| or put the call in a + make sure to call |vim.lsp.start()| within a |FileType| autocmd. Either + use |:au|, |nvim_create_autocmd()| or put the call in a `ftplugin/<filetype_name>.lua` (See |ftplugin-name|) Parameters: ~ - {config} (table) Same configuration as documented in - |lsp.start_client()| - {opts} nil|table Optional keyword arguments: + • {config} (table) Same configuration as documented in + |vim.lsp.start_client()| + • {opts} nil|table Optional keyword arguments: • reuse_client (fun(client: client, config: table): boolean) Predicate used to decide if a client should be re-used. Used on all running clients. The default implementation re-uses a client if name and root_dir matches. + • bufnr (number) Buffer handle to attach to if starting or + re-using a client (0 for current). Return: ~ - (number) client_id + (number|nil) client_id start_client({config}) *vim.lsp.start_client()* Starts and initializes a client with the given configuration. - Parameter `cmd` is required. - - The following parameters describe fields in the {config} table. - - Parameters: ~ - {cmd} (required, string or list treated like - |jobstart()|) Base command that initiates the LSP - client. - {cmd_cwd} (string, default=|getcwd()|) Directory to launch - the `cmd` process. Not related to `root_dir`. - {cmd_env} (table) Environment flags to pass to the LSP on - spawn. Can be specified using keys like a map or - as a list with `k=v` pairs or both. Non-string values are coerced to - string. Example: > - - { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } + Field `cmd` in {config} is required. + + Parameters: ~ + • {config} (table) Configuration for the server: + • cmd: (table|string|fun(dispatchers: table):table) command + string or list treated like |jobstart()|. The command must + launch the language server process. `cmd` can also be a + function that creates an RPC client. The function receives + a dispatchers table and must return a table with the + functions `request`, `notify`, `is_closing` and + `terminate` See |vim.lsp.rpc.request()| and + |vim.lsp.rpc.notify()| For TCP there is a built-in rpc + client factory: |vim.lsp.rpc.connect()| + • cmd_cwd: (string, default=|getcwd()|) Directory to launch + the `cmd` process. Not related to `root_dir`. + • cmd_env: (table) Environment flags to pass to the LSP on + spawn. Can be specified using keys like a map or as a list + with `k=v` pairs or both. Non-string values are coerced to string. + Example: > + + { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } < - {detached} (boolean, default true) Daemonize the server - process so that it runs in a separate process - group from Nvim. Nvim will shutdown the process - on exit, but if Nvim fails to exit cleanly this - could leave behind orphaned server processes. - {workspace_folders} (table) List of workspace folders passed to the - language server. For backwards compatibility - rootUri and rootPath will be derived from the - first workspace folder in this list. See - `workspaceFolders` in the LSP spec. - {capabilities} Map overriding the default capabilities defined - by |vim.lsp.protocol.make_client_capabilities()|, - passed to the language server on initialization. - Hint: use make_client_capabilities() and modify - its result. - • Note: To send an empty dictionary use - `{[vim.type_idx]=vim.types.dictionary}`, else - it will be encoded as an array. - {handlers} Map of language server method names to - |lsp-handler| - {settings} Map with language server specific settings. These - are returned to the language server if requested - via `workspace/configuration`. Keys are - case-sensitive. - {commands} (table) Table that maps string of clientside - commands to user-defined functions. Commands - passed to start_client take precedence over the - global command registry. Each key must be a - unique command name, and the value is a function - which is called if any LSP action (code action, - code lenses, ...) triggers the command. - {init_options} Values to pass in the initialization request as - `initializationOptions`. See `initialize` in the - LSP spec. - {name} (string, default=client-id) Name in log messages. - {get_language_id} function(bufnr, filetype) -> language ID as - string. Defaults to the filetype. - {offset_encoding} (default="utf-16") One of "utf-8", "utf-16", or - "utf-32" which is the encoding that the LSP - server expects. Client does not verify this is - correct. - {on_error} Callback with parameters (code, ...), invoked - when the client operation throws an error. `code` - is a number describing the error. Other arguments - may be passed depending on the error kind. See - |vim.lsp.rpc.client_errors| for possible errors. - Use `vim.lsp.rpc.client_errors[code]` to get - human-friendly name. - {before_init} Callback with parameters (initialize_params, - config) invoked before the LSP "initialize" - phase, where `params` contains the parameters - being sent to the server and `config` is the - config that was passed to - |vim.lsp.start_client()|. You can use this to - modify parameters before they are sent. - {on_init} Callback (client, initialize_result) invoked - after LSP "initialize", where `result` is a table - of `capabilities` and anything else the server - may send. For example, clangd sends - `initialize_result.offsetEncoding` if - `capabilities.offsetEncoding` was sent to it. You - can only modify the `client.offset_encoding` here - before any notifications are sent. Most language - servers expect to be sent client specified - settings after initialization. Neovim does not - make this assumption. A - `workspace/didChangeConfiguration` notification - should be sent to the server during on_init. - {on_exit} Callback (code, signal, client_id) invoked on - client exit. - • code: exit code of the process - • signal: number describing the signal used to - terminate (if any) - • client_id: client handle - {on_attach} Callback (client, bufnr) invoked when client - attaches to a buffer. - {trace} "off" | "messages" | "verbose" | nil passed - directly to the language server in the initialize - request. Invalid/empty values will default to - "off" - {flags} A table with flags for the client. The current - (experimental) flags are: - • allow_incremental_sync (bool, default true): - Allow using incremental sync for buffer edits - • debounce_text_changes (number, default 150): - Debounce didChange notifications to the server - by the given number in milliseconds. No - debounce occurs if nil - • exit_timeout (number|boolean, default false): - Milliseconds to wait for server to exit cleanly - after sending the 'shutdown' request before - sending kill -15. If set to false, nvim exits - immediately after sending the 'shutdown' - request to the server. - {root_dir} (string) Directory where the LSP server will base - its workspaceFolders, rootUri, and rootPath on - initialization. + • detached: (boolean, default true) Daemonize the server + process so that it runs in a separate process group from + Nvim. Nvim will shutdown the process on exit, but if Nvim + fails to exit cleanly this could leave behind orphaned + server processes. + • workspace_folders: (table) List of workspace folders + passed to the language server. For backwards compatibility + rootUri and rootPath will be derived from the first + workspace folder in this list. See `workspaceFolders` in + the LSP spec. + • capabilities: Map overriding the default capabilities + defined by |vim.lsp.protocol.make_client_capabilities()|, + passed to the language server on initialization. Hint: use + make_client_capabilities() and modify its result. + • Note: To send an empty dictionary use + `{[vim.type_idx]=vim.types.dictionary}`, else it will be + encoded as an array. + + • handlers: Map of language server method names to + |lsp-handler| + • settings: Map with language server specific settings. + These are returned to the language server if requested via + `workspace/configuration`. Keys are case-sensitive. + • commands: table Table that maps string of clientside + commands to user-defined functions. Commands passed to + start_client take precedence over the global command + registry. Each key must be a unique command name, and the + value is a function which is called if any LSP action + (code action, code lenses, ...) triggers the command. + • init_options Values to pass in the initialization request + as `initializationOptions`. See `initialize` in the LSP + spec. + • name: (string, default=client-id) Name in log messages. + • get_language_id: function(bufnr, filetype) -> language ID + as string. Defaults to the filetype. + • offset_encoding: (default="utf-16") One of "utf-8", + "utf-16", or "utf-32" which is the encoding that the LSP + server expects. Client does not verify this is correct. + • on_error: Callback with parameters (code, ...), invoked + when the client operation throws an error. `code` is a + number describing the error. Other arguments may be passed + depending on the error kind. See + `vim.lsp.rpc.client_errors` for possible errors. Use + `vim.lsp.rpc.client_errors[code]` to get human-friendly + name. + • before_init: Callback with parameters (initialize_params, + config) invoked before the LSP "initialize" phase, where + `params` contains the parameters being sent to the server + and `config` is the config that was passed to + |vim.lsp.start_client()|. You can use this to modify + parameters before they are sent. + • on_init: Callback (client, initialize_result) invoked + after LSP "initialize", where `result` is a table of + `capabilities` and anything else the server may send. For + example, clangd sends `initialize_result.offsetEncoding` + if `capabilities.offsetEncoding` was sent to it. You can + only modify the `client.offset_encoding` here before any + notifications are sent. Most language servers expect to be + sent client specified settings after initialization. + Neovim does not make this assumption. A + `workspace/didChangeConfiguration` notification should be + sent to the server during on_init. + • on_exit Callback (code, signal, client_id) invoked on + client exit. + • code: exit code of the process + • signal: number describing the signal used to terminate + (if any) + • client_id: client handle + + • on_attach: Callback (client, bufnr) invoked when client + attaches to a buffer. + • trace: ("off" | "messages" | "verbose" | nil) passed + directly to the language server in the initialize request. + Invalid/empty values will default to "off" + • flags: A table with flags for the client. The current + (experimental) flags are: + • allow_incremental_sync (bool, default true): Allow using + incremental sync for buffer edits + • debounce_text_changes (number, default 150): Debounce + didChange notifications to the server by the given + number in milliseconds. No debounce occurs if nil + • exit_timeout (number|boolean, default false): + Milliseconds to wait for server to exit cleanly after + sending the "shutdown" request before sending kill -15. + If set to false, nvim exits immediately after sending + the "shutdown" request to the server. + + • root_dir: (string) Directory where the LSP server will + base its workspaceFolders, rootUri, and rootPath on + initialization. Return: ~ Client id. |vim.lsp.get_client_by_id()| Note: client may not be fully @@ -953,19 +953,18 @@ start_client({config}) *vim.lsp.start_client()* stop_client({client_id}, {force}) *vim.lsp.stop_client()* Stops a client(s). - You can also use the `stop()` function on a |vim.lsp.client| object. To - stop all clients: -> + You can also use the `stop()` function on a |vim.lsp.client| object. To stop all clients: >lua - vim.lsp.stop_client(vim.lsp.get_active_clients()) + vim.lsp.stop_client(vim.lsp.get_active_clients()) < By default asks the server to shutdown, unless stop was requested already for this client, then force-shutdown is attempted. Parameters: ~ - {client_id} client id or |vim.lsp.client| object, or list thereof - {force} (boolean) (optional) shutdown forcefully + • {client_id} number|table id or |vim.lsp.client| object, or list + thereof + • {force} (boolean|nil) shutdown forcefully tagfunc({...}) *vim.lsp.tagfunc()* Provides an interface between the built-in client and 'tagfunc'. @@ -976,8 +975,8 @@ tagfunc({...}) *vim.lsp.tagfunc()* LSP servers, falls back to using built-in tags. Parameters: ~ - {pattern} Pattern used to find a workspace symbol - {flags} See |tag-function| + • {pattern} (string) Pattern used to find a workspace symbol + • {flags} (string) See |tag-function| Return: ~ A list of matching tags @@ -986,8 +985,8 @@ with({handler}, {override_config}) *vim.lsp.with()* Function to manage overriding defaults for LSP handlers. Parameters: ~ - {handler} (function) See |lsp-handler| - {override_config} (table) Table containing the keys to override + • {handler} (function) See |lsp-handler| + • {override_config} (table) Table containing the keys to override behavior of the {handler} @@ -1006,13 +1005,15 @@ code_action({options}) *vim.lsp.buf.code_action()* Selects a code action available at the current cursor position. Parameters: ~ - {options} (table|nil) Optional table which holds the following + • {options} (table|nil) Optional table which holds the following optional fields: • context: (table|nil) Corresponds to `CodeActionContext` of the LSP specification: • diagnostics (table|nil): LSP`Diagnostic[]` . Inferred from the current position if not provided. • only (table|nil): List of LSP `CodeActionKind`s used to filter the code actions. Most language servers support values like `refactor` or `quickfix`. + • triggerKind (number|nil): The reason why code actions + were requested. • filter: (function|nil) Predicate taking an `CodeAction` and returning a boolean. @@ -1027,19 +1028,20 @@ code_action({options}) *vim.lsp.buf.code_action()* See also: ~ https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction + vim.lsp.protocol.constants.CodeActionTriggerKind completion({context}) *vim.lsp.buf.completion()* Retrieves the completion items at the current cursor position. Can only be called in Insert mode. Parameters: ~ - {context} (context support not yet implemented) Additional + • {context} (context support not yet implemented) Additional information about the context in which a completion was triggered (how it was triggered, and by which trigger character, if applicable) See also: ~ - |vim.lsp.protocol.constants.CompletionTriggerKind| + vim.lsp.protocol.constants.CompletionTriggerKind declaration({options}) *vim.lsp.buf.declaration()* Jumps to the declaration of the symbol under the cursor. @@ -1048,7 +1050,7 @@ declaration({options}) *vim.lsp.buf.declaration()* |vim.lsp.buf.definition()| instead. Parameters: ~ - {options} (table|nil) additional options + • {options} (table|nil) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) handler for list results. See @@ -1058,7 +1060,7 @@ definition({options}) *vim.lsp.buf.definition()* Jumps to the definition of the symbol under the cursor. Parameters: ~ - {options} (table|nil) additional options + • {options} (table|nil) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) handler for list results. See @@ -1067,22 +1069,22 @@ definition({options}) *vim.lsp.buf.definition()* document_highlight() *vim.lsp.buf.document_highlight()* Send request to the server to resolve document highlights for the current text document position. This request can be triggered by a key mapping or - by events such as `CursorHold`, e.g.: -> - autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() - autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() - autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() + by events such as `CursorHold` , e.g.: >vim + autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() + autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() + autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() < Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups to be defined or you won't be able to see the actual - highlights. |LspReferenceText| |LspReferenceRead| |LspReferenceWrite| + highlights. |hl-LspReferenceText| |hl-LspReferenceRead| + |hl-LspReferenceWrite| document_symbol({options}) *vim.lsp.buf.document_symbol()* Lists all symbols in the current buffer in the quickfix window. Parameters: ~ - {options} (table|nil) additional options + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1090,7 +1092,7 @@ execute_command({command_params}) *vim.lsp.buf.execute_command()* Executes an LSP server command. Parameters: ~ - {command_params} (table) A valid `ExecuteCommandParams` object + • {command_params} (table) A valid `ExecuteCommandParams` object See also: ~ https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand @@ -1100,7 +1102,7 @@ format({options}) *vim.lsp.buf.format()* server clients. Parameters: ~ - {options} table|nil Optional table which holds the following optional + • {options} table|nil Optional table which holds the following optional fields: • formatting_options (table|nil): Can be used to specify FormattingOptions. Some unspecified options will be @@ -1114,12 +1116,12 @@ format({options}) *vim.lsp.buf.format()* buffer (0). • filter (function|nil): Predicate used to filter clients. Receives a client as argument and must return a boolean. - Clients matching the predicate are included. Example: • > + Clients matching the predicate are included. Example: • >lua - -- Never request typescript-language-server for formatting - vim.lsp.buf.format { - filter = function(client) return client.name ~= "tsserver" end - } + -- Never request typescript-language-server for formatting + vim.lsp.buf.format { + filter = function(client) return client.name ~= "tsserver" end + } < • async boolean|nil If true the method won't block. Defaults to false. Editing the buffer while formatting @@ -1128,59 +1130,11 @@ format({options}) *vim.lsp.buf.format()* ID (client.id) matching this field. • name (string|nil): Restrict formatting to the client with name (client.name) matching this field. - -formatting({options}) *vim.lsp.buf.formatting()* - Formats the current buffer. - - Parameters: ~ - {options} (table|nil) Can be used to specify FormattingOptions. Some - unspecified options will be automatically derived from the - current Neovim options. - - See also: ~ - https://microsoft.github.io/language-server-protocol/specification#textDocument_formatting - - *vim.lsp.buf.formatting_seq_sync()* -formatting_seq_sync({options}, {timeout_ms}, {order}) - Formats the current buffer by sequentially requesting formatting from - attached clients. - - Useful when multiple clients with formatting capability are attached. - - Since it's synchronous, can be used for running on save, to make sure - buffer is formatted prior to being saved. {timeout_ms} is passed on to the - |vim.lsp.client| `request_sync` method. Example: > - - vim.api.nvim_command[[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_seq_sync()]] -< - - Parameters: ~ - {options} (table|nil) `FormattingOptions` entries - {timeout_ms} (number|nil) Request timeout - {order} (table|nil) List of client names. Formatting is - requested from clients in the following order: first all - clients that are not in the `order` list, then the - remaining clients in the order as they occur in the - `order` list. - - *vim.lsp.buf.formatting_sync()* -formatting_sync({options}, {timeout_ms}) - Performs |vim.lsp.buf.formatting()| synchronously. - - Useful for running on save, to make sure buffer is formatted prior to - being saved. {timeout_ms} is passed on to |vim.lsp.buf_request_sync()|. - Example: -> - - autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync() -< - - Parameters: ~ - {options} (table|nil) with valid `FormattingOptions` entries - {timeout_ms} (number) Request timeout - - See also: ~ - |vim.lsp.buf.formatting_seq_sync| + • range (table|nil) Range to format. Table must contain + `start` and `end` keys with {row, col} tuples using (1,0) + indexing. Defaults to current selection in visual mode + Defaults to `nil` in other modes, formatting the full + buffer hover() *vim.lsp.buf.hover()* Displays hover information about the symbol under the cursor in a floating @@ -1191,14 +1145,14 @@ implementation({options}) *vim.lsp.buf.implementation()* quickfix window. Parameters: ~ - {options} (table|nil) additional options + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| incoming_calls() *vim.lsp.buf.incoming_calls()* Lists all the call sites of the symbol under the cursor in the |quickfix| window. If the symbol can resolve to multiple items, the user can pick one - in the |inputlist|. + in the |inputlist()|. list_workspace_folders() *vim.lsp.buf.list_workspace_folders()* List workspace folders. @@ -1206,41 +1160,15 @@ list_workspace_folders() *vim.lsp.buf.list_workspace_folders()* outgoing_calls() *vim.lsp.buf.outgoing_calls()* Lists all the items that are called by the symbol under the cursor in the |quickfix| window. If the symbol can resolve to multiple items, the user - can pick one in the |inputlist|. - - *vim.lsp.buf.range_code_action()* -range_code_action({context}, {start_pos}, {end_pos}) - Performs |vim.lsp.buf.code_action()| for a given range. - - Parameters: ~ - {context} (table|nil) `CodeActionContext` of the LSP specification: - • diagnostics: (table|nil) LSP`Diagnostic[]` . Inferred from the current position if not provided. - • only: (table|nil) List of LSP `CodeActionKind`s used to - filter the code actions. Most language servers support - values like `refactor` or `quickfix`. - {start_pos} ({number, number}, optional) mark-indexed position. - Defaults to the start of the last visual selection. - {end_pos} ({number, number}, optional) mark-indexed position. - Defaults to the end of the last visual selection. - - *vim.lsp.buf.range_formatting()* -range_formatting({options}, {start_pos}, {end_pos}) - Formats a given range. - - Parameters: ~ - {options} Table with valid `FormattingOptions` entries. - {start_pos} ({number, number}, optional) mark-indexed position. - Defaults to the start of the last visual selection. - {end_pos} ({number, number}, optional) mark-indexed position. - Defaults to the end of the last visual selection. + can pick one in the |inputlist()|. references({context}, {options}) *vim.lsp.buf.references()* Lists all the references to the symbol under the cursor in the quickfix window. Parameters: ~ - {context} (table) Context for the request - {options} (table|nil) additional options + • {context} (table|nil) Context for the request + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1256,9 +1184,9 @@ rename({new_name}, {options}) *vim.lsp.buf.rename()* Renames all references to the symbol under the cursor. Parameters: ~ - {new_name} (string|nil) If not provided, the user will be prompted + • {new_name} (string|nil) If not provided, the user will be prompted for a new name using |vim.ui.input()|. - {options} (table|nil) additional options + • {options} (table|nil) additional options • filter (function|nil): Predicate used to filter clients. Receives a client as argument and must return a boolean. Clients matching the predicate are included. @@ -1280,7 +1208,7 @@ type_definition({options}) *vim.lsp.buf.type_definition()* Jumps to the definition of the type of the symbol under the cursor. Parameters: ~ - {options} (table|nil) additional options + • {options} (table|nil) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) handler for list results. See @@ -1294,8 +1222,8 @@ workspace_symbol({query}, {options}) *vim.lsp.buf.workspace_symbol()* string means no filtering is done. Parameters: ~ - {query} (string, optional) - {options} (table|nil) additional options + • {query} (string, optional) + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1308,14 +1236,14 @@ get_namespace({client_id}) *vim.lsp.diagnostic.get_namespace()* |vim.diagnostic|. Parameters: ~ - {client_id} (number) The id of the LSP client + • {client_id} (number) The id of the LSP client *vim.lsp.diagnostic.on_publish_diagnostics()* on_publish_diagnostics({_}, {result}, {ctx}, {config}) |lsp-handler| for the method "textDocument/publishDiagnostics" See |vim.diagnostic.config()| for configuration options. Handler-specific - configuration can be set using |vim.lsp.with()|: > + configuration can be set using |vim.lsp.with()|: >lua vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { @@ -1337,25 +1265,32 @@ on_publish_diagnostics({_}, {result}, {ctx}, {config}) < Parameters: ~ - {config} (table) Configuration table (see |vim.diagnostic.config()|). + • {config} (table) Configuration table (see |vim.diagnostic.config()|). ============================================================================== Lua module: vim.lsp.codelens *lsp-codelens* +clear({client_id}, {bufnr}) *vim.lsp.codelens.clear()* + Clear the lenses + + Parameters: ~ + • {client_id} (number|nil) filter by client_id. All clients if nil + • {bufnr} (number|nil) filter by buffer. All buffers if nil + display({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.display()* Display the lenses using virtual text Parameters: ~ - {lenses} (table) of lenses to display (`CodeLens[] | null`) - {bufnr} (number) - {client_id} (number) + • {lenses} (table) of lenses to display (`CodeLens[] | null`) + • {bufnr} (number) + • {client_id} (number) get({bufnr}) *vim.lsp.codelens.get()* Return all lenses for the given buffer Parameters: ~ - {bufnr} (number) Buffer number. 0 can be used for the current buffer. + • {bufnr} (number) Buffer number. 0 can be used for the current buffer. Return: ~ (table) (`CodeLens[]`) @@ -1368,8 +1303,9 @@ refresh() *vim.lsp.codelens.refresh()* Refresh the codelens for the current buffer It is recommended to trigger this using an autocmd or via keymap. -> - autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() + + Example: >vim + autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() < run() *vim.lsp.codelens.run()* @@ -1379,27 +1315,89 @@ save({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.save()* Store lenses for a specific buffer and client Parameters: ~ - {lenses} (table) of lenses to store (`CodeLens[] | null`) - {bufnr} (number) - {client_id} (number) + • {lenses} (table) of lenses to store (`CodeLens[] | null`) + • {bufnr} (number) + • {client_id} (number) + + +============================================================================== +Lua module: vim.lsp.semantic_tokens *lsp-semantic_tokens* + +force_refresh({bufnr}) *vim.lsp.semantic_tokens.force_refresh()* + Force a refresh of all semantic tokens + + Only has an effect if the buffer is currently active for semantic token + highlighting (|vim.lsp.semantic_tokens.start()| has been called for it) + + Parameters: ~ + • {bufnr} (nil|number) default: current buffer + + *vim.lsp.semantic_tokens.get_at_pos()* +get_at_pos({bufnr}, {row}, {col}) + Return the semantic token(s) at the given position. If called without + arguments, returns the token under the cursor. + + Parameters: ~ + • {bufnr} (number|nil) Buffer number (0 for current buffer, default) + • {row} (number|nil) Position row (default cursor position) + • {col} (number|nil) Position column (default cursor position) + + Return: ~ + (table|nil) List of tokens at position + +start({bufnr}, {client_id}, {opts}) *vim.lsp.semantic_tokens.start()* + Start the semantic token highlighting engine for the given buffer with the + given client. The client must already be attached to the buffer. + + NOTE: This is currently called automatically by + |vim.lsp.buf_attach_client()|. To opt-out of semantic highlighting with a + server that supports it, you can delete the semanticTokensProvider table + from the {server_capabilities} of your client in your |LspAttach| callback + or your configuration's `on_attach` callback: >lua + + client.server_capabilities.semanticTokensProvider = nil +< + + Parameters: ~ + • {bufnr} (number) + • {client_id} (number) + • {opts} (nil|table) Optional keyword arguments + • debounce (number, default: 200): Debounce token + requests to the server by the given number in + milliseconds + +stop({bufnr}, {client_id}) *vim.lsp.semantic_tokens.stop()* + Stop the semantic token highlighting engine for the given buffer with the + given client. + + NOTE: This is automatically called by a |LspDetach| autocmd that is set up + as part of `start()`, so you should only need this function to manually + disengage the semantic token engine without fully detaching the LSP client + from the buffer. + + Parameters: ~ + • {bufnr} (number) + • {client_id} (number) ============================================================================== Lua module: vim.lsp.handlers *lsp-handlers* hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* - |lsp-handler| for the method "textDocument/hover" > - - vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( - vim.lsp.handlers.hover, { - -- Use a sharp border with `FloatBorder` highlights - border = "single" - } - ) + |lsp-handler| for the method "textDocument/hover" >lua + + vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( + vim.lsp.handlers.hover, { + -- Use a sharp border with `FloatBorder` highlights + border = "single", + -- add the title in hover float window + title = "hover" + } + ) < Parameters: ~ - {config} (table) Configuration table. + • {config} (table) Configuration table. • border: (default=nil) • Add borders to the floating window • See |nvim_open_win()| @@ -1407,21 +1405,21 @@ hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* *vim.lsp.handlers.signature_help()* signature_help({_}, {result}, {ctx}, {config}) |lsp-handler| for the method "textDocument/signatureHelp". The active - parameter is highlighted with |hl-LspSignatureActiveParameter|. > - - vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( - vim.lsp.handlers.signature_help, { - -- Use a sharp border with `FloatBorder` highlights - border = "single" - } - ) + parameter is highlighted with |hl-LspSignatureActiveParameter|. >lua + + vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( + vim.lsp.handlers.signature_help, { + -- Use a sharp border with `FloatBorder` highlights + border = "single" + } + ) < Parameters: ~ - {config} (table) Configuration table. + • {config} (table) Configuration table. • border: (default=nil) • Add borders to the floating window - • See |vim.api.nvim_open_win()| + • See |nvim_open_win()| ============================================================================== @@ -1433,8 +1431,8 @@ apply_text_document_edit({text_document_edit}, {index}, {offset_encoding}) document. Parameters: ~ - {text_document_edit} table: a `TextDocumentEdit` object - {index} number: Optional index of the edit, if from a + • {text_document_edit} (table) a `TextDocumentEdit` object + • {index} (number) Optional index of the edit, if from a list of edits (or nil, if not from a list) See also: ~ @@ -1445,9 +1443,9 @@ apply_text_edits({text_edits}, {bufnr}, {offset_encoding}) Applies a list of text edits to a buffer. Parameters: ~ - {text_edits} (table) list of `TextEdit` objects - {bufnr} (number) Buffer id - {offset_encoding} (string) utf-8|utf-16|utf-32 + • {text_edits} (table) list of `TextEdit` objects + • {bufnr} (number) Buffer id + • {offset_encoding} (string) utf-8|utf-16|utf-32 See also: ~ https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit @@ -1457,37 +1455,37 @@ apply_workspace_edit({workspace_edit}, {offset_encoding}) Applies a `WorkspaceEdit`. Parameters: ~ - {workspace_edit} (table) `WorkspaceEdit` - {offset_encoding} (string) utf-8|utf-16|utf-32 (required) + • {workspace_edit} (table) `WorkspaceEdit` + • {offset_encoding} (string) utf-8|utf-16|utf-32 (required) buf_clear_references({bufnr}) *vim.lsp.util.buf_clear_references()* Removes document highlights from a buffer. Parameters: ~ - {bufnr} (number) Buffer id + • {bufnr} (number) Buffer id *vim.lsp.util.buf_highlight_references()* buf_highlight_references({bufnr}, {references}, {offset_encoding}) Shows a list of document highlights for a certain buffer. Parameters: ~ - {bufnr} (number) Buffer id - {references} (table) List of `DocumentHighlight` objects to + • {bufnr} (number) Buffer id + • {references} (table) List of `DocumentHighlight` objects to highlight - {offset_encoding} (string) One of "utf-8", "utf-16", "utf-32". + • {offset_encoding} (string) One of "utf-8", "utf-16", "utf-32". See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#documentHighlight + https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent *vim.lsp.util.character_offset()* character_offset({buf}, {row}, {col}, {offset_encoding}) Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. Parameters: ~ - {buf} (number) buffer number (0 for current) - {row} 0-indexed line - {col} 0-indexed byte offset in line - {offset_encoding} (string) utf-8|utf-16|utf-32|nil defaults to + • {buf} (number) buffer number (0 for current) + • {row} 0-indexed line + • {col} 0-indexed byte offset in line + • {offset_encoding} (string) utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of `buf` Return: ~ @@ -1502,9 +1500,9 @@ convert_input_to_markdown_lines({input}, {contents}) `textDocument/signatureHelp`, and potentially others. Parameters: ~ - {input} (`MarkedString` | `MarkedString[]` | `MarkupContent`) - {contents} (table, optional, default `{}`) List of strings to extend - with converted lines + • {input} (`MarkedString` | `MarkedString[]` | `MarkupContent`) + • {contents} (table|nil) List of strings to extend with converted + lines. Defaults to {}. Return: ~ {contents}, extended with lines of converted markdown. @@ -1517,14 +1515,14 @@ convert_signature_help_to_markdown_lines({signature_help}, {ft}, {triggers}) Converts `textDocument/SignatureHelp` response to markdown lines. Parameters: ~ - {signature_help} Response of `textDocument/SignatureHelp` - {ft} optional filetype that will be use as the `lang` for + • {signature_help} Response of `textDocument/SignatureHelp` + • {ft} optional filetype that will be use as the `lang` for the label markdown code block - {triggers} optional list of trigger characters from the lsp + • {triggers} optional list of trigger characters from the lsp server. used to better determine parameter offsets Return: ~ - list of lines of converted markdown. + (list) of lines of converted markdown. See also: ~ https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp @@ -1534,7 +1532,7 @@ extract_completion_items({result}) Can be used to extract the completion items from a `textDocument/completion` request, which may return one of `CompletionItem[]` , `CompletionList` or null. Parameters: ~ - {result} (table) The result of a `textDocument/completion` request + • {result} (table) The result of a `textDocument/completion` request Return: ~ (table) List of completion items @@ -1546,26 +1544,26 @@ get_effective_tabstop({bufnr}) *vim.lsp.util.get_effective_tabstop()* Returns indentation size. Parameters: ~ - {bufnr} (number|nil): Buffer handle, defaults to current + • {bufnr} (number|nil) Buffer handle, defaults to current Return: ~ (number) indentation size See also: ~ - |shiftwidth| + 'shiftwidth' *vim.lsp.util.jump_to_location()* jump_to_location({location}, {offset_encoding}, {reuse_win}) Jumps to a location. Parameters: ~ - {location} (table) (`Location`|`LocationLink`) - {offset_encoding} (string) utf-8|utf-16|utf-32 (required) - {reuse_win} (boolean) Jump to existing window if buffer is - already opened. + • {location} (table) (`Location`|`LocationLink`) + • {offset_encoding} "utf-8" | "utf-16" | "utf-32" + • {reuse_win} (boolean|nil) Jump to existing window if buffer is + already open. Return: ~ - `true` if the jump succeeded + (boolean) `true` if the jump succeeded *vim.lsp.util.locations_to_items()* locations_to_items({locations}, {offset_encoding}) @@ -1576,8 +1574,8 @@ locations_to_items({locations}, {offset_encoding}) |setloclist()|. Parameters: ~ - {locations} (table) list of `Location`s or `LocationLink`s - {offset_encoding} (string) offset_encoding for locations + • {locations} (table) list of `Location`s or `LocationLink`s + • {offset_encoding} (string) offset_encoding for locations utf-8|utf-16|utf-32 Return: ~ @@ -1587,8 +1585,8 @@ lookup_section({settings}, {section}) *vim.lsp.util.lookup_section()* Helper function to return nested values in language server settings Parameters: ~ - {settings} a table of language server settings - {section} a string indicating the field of the settings table + • {settings} a table of language server settings + • {section} a string indicating the field of the settings table Return: ~ (table or string) The value of settings accessed via section @@ -1599,14 +1597,15 @@ make_floating_popup_options({width}, {height}, {opts}) table can be passed to |nvim_open_win()|. Parameters: ~ - {width} (number) window width (in character cells) - {height} (number) window height (in character cells) - {opts} (table, optional) + • {width} (number) window width (in character cells) + • {height} (number) window height (in character cells) + • {opts} (table, optional) • offset_x (number) offset to add to `col` • offset_y (number) offset to add to `row` • border (string or table) override `border` • focusable (string or table) override `focusable` • zindex (string or table) override `zindex`, defaults to 50 + • relative ("mouse"|"cursor") defaults to "cursor" Return: ~ (table) Options @@ -1617,7 +1616,7 @@ make_formatting_params({options}) cursor position. Parameters: ~ - {options} (table|nil) with valid `FormattingOptions` entries + • {options} (table|nil) with valid `FormattingOptions` entries Return: ~ `DocumentFormattingParams` object @@ -1631,13 +1630,13 @@ make_given_range_params({start_pos}, {end_pos}, {bufnr}, {offset_encoding}) similar to |vim.lsp.util.make_range_params()|. Parameters: ~ - {start_pos} number[]|nil {row, col} mark-indexed position. + • {start_pos} number[]|nil {row, col} mark-indexed position. Defaults to the start of the last visual selection. - {end_pos} number[]|nil {row, col} mark-indexed position. + • {end_pos} number[]|nil {row, col} mark-indexed position. Defaults to the end of the last visual selection. - {bufnr} (number|nil) buffer handle or 0 for current, + • {bufnr} (number|nil) buffer handle or 0 for current, defaults to current - {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to + • {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of `bufnr` Return: ~ @@ -1650,9 +1649,9 @@ make_position_params({window}, {offset_encoding}) cursor position. Parameters: ~ - {window} number|nil: window handle or 0 for current, + • {window} (number|nil) window handle or 0 for current, defaults to current - {offset_encoding} (string) utf-8|utf-16|utf-32|nil defaults to + • {offset_encoding} (string|nil) utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` @@ -1670,9 +1669,9 @@ make_range_params({window}, {offset_encoding}) `textDocument/rangeFormatting`. Parameters: ~ - {window} number|nil: window handle or 0 for current, + • {window} (number|nil) window handle or 0 for current, defaults to current - {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to + • {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of buffer of `window` @@ -1685,7 +1684,7 @@ make_text_document_params({bufnr}) Creates a `TextDocumentIdentifier` object for the current buffer. Parameters: ~ - {bufnr} number|nil: Buffer handle, defaults to current + • {bufnr} (number|nil) Buffer handle, defaults to current Return: ~ `TextDocumentIdentifier` @@ -1698,18 +1697,18 @@ make_workspace_params({added}, {removed}) Create the workspace params Parameters: ~ - {added} - {removed} + • {added} + • {removed} *vim.lsp.util.open_floating_preview()* open_floating_preview({contents}, {syntax}, {opts}) Shows contents in a floating window. Parameters: ~ - {contents} (table) of lines to show in window - {syntax} (string) of syntax to set for opened buffer - {opts} (table) with optional fields (additional keys are passed - on to |vim.api.nvim_open_win()|) + • {contents} (table) of lines to show in window + • {syntax} (string) of syntax to set for opened buffer + • {opts} (table) with optional fields (additional keys are passed + on to |nvim_open_win()|) • height: (number) height of floating window • width: (number) width of floating window • wrap: (boolean, default true) wrap long lines @@ -1737,7 +1736,7 @@ parse_snippet({input}) *vim.lsp.util.parse_snippet()* Parses snippets in a completion entry. Parameters: ~ - {input} (string) unparsed snippet + • {input} (string) unparsed snippet Return: ~ (string) parsed snippet @@ -1751,7 +1750,7 @@ preview_location({location}, {opts}) *vim.lsp.util.preview_location()* definition) Parameters: ~ - {location} a single `Location` or `LocationLink` + • {location} a single `Location` or `LocationLink` Return: ~ (bufnr,winnr) buffer and window number of floating window or nil @@ -1760,7 +1759,7 @@ rename({old_fname}, {new_fname}, {opts}) *vim.lsp.util.rename()* Rename old_fname to new_fname Parameters: ~ - {opts} (table) + • {opts} (table) set_lines({lines}, {A}, {B}, {new_lines}) *vim.lsp.util.set_lines()* Replaces text in a range with new text. @@ -1768,14 +1767,30 @@ set_lines({lines}, {A}, {B}, {new_lines}) *vim.lsp.util.set_lines()* CAUTION: Changes in-place! Parameters: ~ - {lines} (table) Original list of strings - {A} (table) Start position; a 2-tuple of {line, col} numbers - {B} (table) End position; a 2-tuple of {line, col} numbers - {new_lines} A list of strings to replace the original + • {lines} (table) Original list of strings + • {A} (table) Start position; a 2-tuple of {line, col} numbers + • {B} (table) End position; a 2-tuple of {line, col} numbers + • {new_lines} A list of strings to replace the original Return: ~ (table) The modified {lines} object + *vim.lsp.util.show_document()* +show_document({location}, {offset_encoding}, {opts}) + Shows document and optionally jumps to the location. + + Parameters: ~ + • {location} (table) (`Location`|`LocationLink`) + • {offset_encoding} "utf-8" | "utf-16" | "utf-32" + • {opts} (table|nil) options + • reuse_win (boolean) Jump to existing window if + buffer is already open. + • focus (boolean) Whether to focus/jump to location + if possible. Defaults to true. + + Return: ~ + (boolean) `true` if succeeded + *vim.lsp.util.stylize_markdown()* stylize_markdown({bufnr}, {contents}, {opts}) Converts markdown into syntax highlighted regions by stripping the code @@ -1789,8 +1804,8 @@ stylize_markdown({bufnr}, {contents}, {opts}) `open_floating_preview` instead Parameters: ~ - {contents} (table) of lines to show in window - {opts} dictionary with optional fields + • {contents} (table) of lines to show in window + • {opts} dictionary with optional fields • height of floating window • width of floating window • wrap_at character to wrap at for computing height @@ -1807,7 +1822,7 @@ symbols_to_items({symbols}, {bufnr}) *vim.lsp.util.symbols_to_items()* Converts symbols to quickfix list items. Parameters: ~ - {symbols} DocumentSymbol[] or SymbolInformation[] + • {symbols} DocumentSymbol[] or SymbolInformation[] *vim.lsp.util.text_document_completion_list_to_complete_items()* text_document_completion_list_to_complete_items({result}, {prefix}) @@ -1815,10 +1830,10 @@ text_document_completion_list_to_complete_items({result}, {prefix}) vim-compatible |complete-items|. Parameters: ~ - {result} The result of a `textDocument/completion` call, e.g. from + • {result} The result of a `textDocument/completion` call, e.g. from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, `CompletionList` or `null` - {prefix} (string) the prefix to filter the completion items + • {prefix} (string) the prefix to filter the completion items Return: ~ { matches = complete-items table, incomplete = bool } @@ -1830,7 +1845,7 @@ trim_empty_lines({lines}) *vim.lsp.util.trim_empty_lines()* Removes empty lines from the beginning and end. Parameters: ~ - {lines} (table) list of lines to trim + • {lines} (table) list of lines to trim Return: ~ (table) trimmed list of lines @@ -1843,10 +1858,10 @@ try_trim_markdown_code_blocks({lines}) CAUTION: Modifies the input in-place! Parameters: ~ - {lines} (table) list of lines + • {lines} (table) list of lines Return: ~ - (string) filetype or 'markdown' if it was unchanged. + (string) filetype or "markdown" if it was unchanged. ============================================================================== @@ -1868,20 +1883,20 @@ set_format_func({handle}) *vim.lsp.log.set_format_func()* Sets formatting function used to format logs Parameters: ~ - {handle} (function) function to apply to logging arguments, pass + • {handle} (function) function to apply to logging arguments, pass vim.inspect for multi-line formatting set_level({level}) *vim.lsp.log.set_level()* Sets the current log level. Parameters: ~ - {level} (string or number) One of `vim.lsp.log.levels` + • {level} (string|number) One of `vim.lsp.log.levels` should_log({level}) *vim.lsp.log.should_log()* Checks whether the level is sufficient for logging. Parameters: ~ - {level} (number) log level + • {level} (number) log level Return: ~ (bool) true if would log, false if not @@ -1890,11 +1905,22 @@ should_log({level}) *vim.lsp.log.should_log()* ============================================================================== Lua module: vim.lsp.rpc *lsp-rpc* +connect({host}, {port}) *vim.lsp.rpc.connect()* + Create a LSP RPC client factory that connects via TCP to the given host + and port + + Parameters: ~ + • {host} (string) + • {port} (number) + + Return: ~ + (function) + format_rpc_error({err}) *vim.lsp.rpc.format_rpc_error()* Constructs an error message from an LSP error object. Parameters: ~ - {err} (table) The error object + • {err} (table) The error object Return: ~ (string) The formatted error message @@ -1903,8 +1929,8 @@ notify({method}, {params}) *vim.lsp.rpc.notify()* Sends a notification to the LSP server. Parameters: ~ - {method} (string) The invoked LSP method - {params} (table): Parameters for the invoked LSP method + • {method} (string) The invoked LSP method + • {params} (table|nil) Parameters for the invoked LSP method Return: ~ (bool) `true` if notification could be sent, `false` if not @@ -1914,10 +1940,11 @@ request({method}, {params}, {callback}, {notify_reply_callback}) Sends a request to the LSP server and runs {callback} upon response. Parameters: ~ - {method} (string) The invoked LSP method - {params} (table) Parameters for the invoked LSP method - {callback} (function) Callback to invoke - {notify_reply_callback} (function|nil) Callback to invoke as soon as + • {method} (string) The invoked LSP method + • {params} (table|nil) Parameters for the invoked LSP + method + • {callback} (function) Callback to invoke + • {notify_reply_callback} (function|nil) Callback to invoke as soon as a request is no longer pending Return: ~ @@ -1929,28 +1956,29 @@ rpc_response_error({code}, {message}, {data}) Creates an RPC response object/table. Parameters: ~ - {code} (number) RPC error code defined in + • {code} (number) RPC error code defined in `vim.lsp.protocol.ErrorCodes` - {message} (string|nil) arbitrary message to send to server - {data} any|nil arbitrary data to send to server + • {message} (string|nil) arbitrary message to send to server + • {data} any|nil arbitrary data to send to server *vim.lsp.rpc.start()* start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) Starts an LSP server process and create an LSP RPC client object to - interact with it. Communication with the server is currently limited to - stdio. + interact with it. Communication with the spawned process happens via + stdio. For communication via TCP, spawn a process manually and use + |vim.lsp.rpc.connect()| Parameters: ~ - {cmd} (string) Command to start the LSP server. - {cmd_args} (table) List of additional string arguments to + • {cmd} (string) Command to start the LSP server. + • {cmd_args} (table) List of additional string arguments to pass to {cmd}. - {dispatchers} (table|nil) Dispatchers for LSP message types. + • {dispatchers} (table|nil) Dispatchers for LSP message types. Valid dispatcher names are: • `"notification"` • `"server_request"` • `"on_error"` • `"on_exit"` - {extra_spawn_params} (table|nil) Additional context for the LSP + • {extra_spawn_params} (table|nil) Additional context for the LSP server process. May contain: • {cwd} (string) Working directory for the LSP server process @@ -1962,11 +1990,8 @@ start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) Methods: • `notify()` |vim.lsp.rpc.notify()| • `request()` |vim.lsp.rpc.request()| - - Members: - • {pid} (number) The LSP server's PID. - • {handle} A handle for low-level interaction with the LSP server - process |vim.loop|. + • `is_closing()` returns a boolean indicating if the RPC is closing. + • `terminate()` terminates the RPC client. ============================================================================== @@ -1977,17 +2002,17 @@ compute_diff({___MissingCloseParenHere___}) Returns the range table for the difference between prev and curr lines Parameters: ~ - {prev_lines} (table) list of lines - {curr_lines} (table) list of lines - {firstline} (number) line to begin search for first difference - {lastline} (number) line to begin search in old_lines for last + • {prev_lines} (table) list of lines + • {curr_lines} (table) list of lines + • {firstline} (number) line to begin search for first difference + • {lastline} (number) line to begin search in old_lines for last difference - {new_lastline} (number) line to begin search in new_lines for last + • {new_lastline} (number) line to begin search in new_lines for last difference - {offset_encoding} (string) encoding requested by language server + • {offset_encoding} (string) encoding requested by language server Return: ~ - (table) TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentContentChangeEvent + (table) TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent ============================================================================== @@ -2003,7 +2028,7 @@ resolve_capabilities({server_capabilities}) Creates a normalized object describing LSP server capabilities. Parameters: ~ - {server_capabilities} (table) Table of capabilities supported by the + • {server_capabilities} (table) Table of capabilities supported by the server Return: ~ diff --git a/runtime/doc/lua-guide.txt b/runtime/doc/lua-guide.txt new file mode 100644 index 0000000000..b971a7d2ad --- /dev/null +++ b/runtime/doc/lua-guide.txt @@ -0,0 +1,757 @@ +*lua-guide.txt* Nvim + + NVIM REFERENCE MANUAL + + Guide to using Lua in Nvim + + + Type |gO| to see the table of contents. + +============================================================================== +Introduction *lua-guide* + +This guide will go through the basics of using Lua in Neovim. It is not meant +to be a comprehensive encyclopedia of all available features, nor will it +detail all intricacies. Think of it as a survival kit -- the bare minimum +needed to know to comfortably get started on using Lua in Neovim. + +An important thing to note is that this isn't a guide to the Lua language +itself. Rather, this is a guide on how to configure and modify Neovim through +the Lua language and the functions we provide to help with this. Take a look +at |luaref| and |lua-concepts| if you'd like to learn more about Lua itself. +Similarly, this guide assumes some familiarity with the basics of Neovim +(commands, options, mappings, autocommands), which are covered in the +|user-manual|. + +------------------------------------------------------------------------------ +Some words on the API *lua-guide-api* + +The purpose of this guide is to introduce the different ways of interacting +with Neovim through Lua (the "API"). This API consists of three different +layers: + +1. The "Vim API" inherited from Vim: |ex-commands| and |builtin-functions| as +well as |user-function|s in Vimscript. These are accessed through |vim.cmd()| +and |vim.fn| respectively, which are discussed under |lua-guide-vimscript| +below. + +2. The "Neovim API" written in C for use in remote plugins and GUIs; see |api|. +These functions are accessed through |vim.api|. + +3. The "Lua API" written in and specifically for Lua. These are any other +functions accessible through `vim.*` not mentioned already; see |lua-stdlib|. + +This distinction is important, as API functions inherit behavior from their +original layer: For example, Neovim API functions always need all arguments to +be specified even if Lua itself allows omitting arguments (which are then +passed as `nil`); and Vim API functions can use 0-based indexing even if Lua +arrays are 1-indexed by default. + +Through this, any possible interaction can be done through Lua without writing +a complete new API from scratch. For this reason, functions are usually not +duplicated between layers unless there is a significant benefit in +functionality or performance (e.g., you can map Lua functions directly through +|nvim_create_autocmd()| but not through |:autocmd|). In case there are multiple +ways of achieving the same thing, this guide will only cover what is most +convenient to use from Lua. + +============================================================================== +Using Lua *lua-guide-using-Lua* + +To run Lua code from the Neovim command line, use the |:lua| command: +>vim + :lua print("Hello!") +< +Note: each |:lua| command has its own scope and variables declared with the +local keyword are not accessible outside of the command. This won't work: +>vim + :lua local foo = 1 + :lua print(foo) + " prints "nil" instead of "1" +< +You can also use `:lua=`, which is the same as `:lua vim.pretty_print(...)`, +to conveniently check the value of a variable or a table: +>lua + :lua=package +< +To run a Lua script in an external file, you can use the |:source| command +exactly like for a Vimscript file: +>vim + :source ~/programs/baz/myluafile.lua +< +Finally, you can include Lua code in a Vimscript file by putting it inside a +|lua-heredoc| block: +>vim + lua << EOF + local tbl = {1, 2, 3} + for k, v in ipairs(tbl) do + print(v) + end + EOF +< +------------------------------------------------------------------------------ +Using Lua files on startup *lua-guide-config* + +Neovim supports using `init.vim` or `init.lua` as the configuration file, but +not both at the same time. This should be placed in your |config| directory, +which is typically `~/.config/nvim` for Linux, BSD, or macOS, and +`~/AppData/Local/nvim/` for Windows. Note that you can use Lua in `init.vim` +and Vimscript in `init.lua`, which will be covered below. + +If you'd like to run any other Lua script on |startup| automatically, then you +can simply put it in `plugin/` in your |'runtimepath'|. + +------------------------------------------------------------------------------ +Lua modules *lua-guide-modules* + +If you want to load Lua files on demand, you can place them in the `lua/` +directory in your |'runtimepath'| and load them with `require`. (This is the +Lua equivalent of Vimscript's |autoload| mechanism.) + +Let's assume you have the following directory structure: +> + ~/.config/nvim + |-- after/ + |-- ftplugin/ + |-- lua/ + | |-- myluamodule.lua + | |-- other_modules/ + | |-- anothermodule.lua + | |-- init.lua + |-- plugin/ + |-- syntax/ + |-- init.vim +< + +Then the following Lua code will load `myluamodule.lua`: +>lua + require("myluamodule") +< +Note the absence of a `.lua` extension. + +Similarly, loading `other_modules/anothermodule.lua` is done via +>lua + require('other_modules/anothermodule') + -- or + require('other_modules.anothermodule') +< + +Note how "submodules" are just subdirectories; the `.` is equivalent to the +path separator `/` (even on Windows). + +A folder containing an |init.lua| file can be required directly, without +having to specify the name of the file: +>lua + require('other_modules') -- loads other_modules/init.lua +< +Requiring a nonexistent module or a module which contains syntax errors aborts +the currently executing script. `pcall()` may be used to catch such errors. The +following example tries to load the `module_with_error` and only calls one of +its functions if this succeeds and prints an error message otherwise: +>lua + local ok, mymod = pcall(require, 'module_with_error') + if not ok then + print("Module had an error") + else + mymod.function() + end +< +In contrast to |:source|, |require()| not only searches through all `lua/` directories +under |'runtimepath'|, it also cache the module on first use. Calling +`require()` a second time will therefore _not_ execute the script again and +instead return the cached file. To rerun the file, you need to remove it from +the cache manually first: +>lua + package.loaded['myluamodule'] = nil + require('myluamodule') -- read and execute the module again from disk +< +------------------------------------------------------------------------------ +See also: +• |lua-require| +• |luaref-pcall()| + +============================================================================== +Using Vim commands and functions from Lua *lua-guide-vimscript* + +All Vim commands and functions are accessible from Lua. + +------------------------------------------------------------------------------ +Vim commands *lua-guide-vim-commands* + +To run an arbitrary Vim command from Lua, pass it as a string to |vim.cmd()|: +>lua + vim.cmd("colorscheme habamax") +< +Note that special characters will need to be escaped with backslashes: +>lua + vim.cmd("%s/\\Vfoo/bar/g") +< +An alternative is to use a literal string (see |luaref-literal|) delimited by +double brackets `[[ ]]` as in +>lua + vim.cmd([[%s/\Vfoo/bar/g]]) +< +Another benefit of using literal strings is that they can be multiple lines; +this allows you to pass multiple commands to a single call of |vim.cmd()|: +>lua + vim.cmd([[ + highlight Error guibg=red + highlight link Warning Error + ]]) +< +This is the converse of |lua-heredoc| and allows you to include Vimscript code in +your `init.lua`. + +If you want to build your Vim command programmatically, the following form can +be useful (all these are equivalent to the corresponding line above): +>lua + vim.cmd.colorscheme("habamax") + vim.cmd.highlight({ "Error", "guibg=red" }) + vim.cmd.highlight({ "link", "Warning", "Error" }) +< +------------------------------------------------------------------------------ +Vimscript functions *lua-guide-vim-functions* + +Use |vim.fn| to call Vimscript functions from Lua. Data types between Lua and +Vimscript are automatically converted: +>lua + print(vim.fn.printf('Hello from %s', 'Lua')) + + local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' }) + print(vim.inspect(reversed_list)) -- { "c", "b", "a" } + + local function print_stdout(chan_id, data, name) + print(data[1]) + end + + vim.fn.jobstart('ls', { on_stdout = print_stdout }) + print(vim.fn.printf('Hello from %s', 'Lua')) +< +This works for both |builtin-functions| and |user-function|s. + +Note that hashes (`#`) are not valid characters for identifiers in Lua, so, +e.g., |autoload| functions have to be called with this syntax: +>lua + vim.fn['my#autoload#function']() +< +------------------------------------------------------------------------------ +See also: +• |builtin-functions|: alphabetic list of all Vimscript functions +• |function-list|: list of all Vimscript functions grouped by topic +• |:runtime|: run all Lua scripts matching a pattern in |'runtimepath'| +• |package.path|: list of all paths searched by `require()` + +============================================================================== +Variables *lua-guide-variables* + +Variables can be set and read using the following wrappers, which directly +correspond to their |variable-scope|: + +• |vim.g|: global variables (|g:|) +• |vim.b|: variables for the current buffer (|b:|) +• |vim.w|: variables for the current window (|w:|) +• |vim.t|: variables for the current tabpage (|t:|) +• |vim.v|: predefined Vim variables (|v:|) +• |vim.env|: environment variables defined in the editor session + +Data types are converted automatically. For example: +>lua + vim.g.some_global_variable = { + key1 = "value", + key2 = 300 + } + + print(vim.inspect(vim.g.some_global_variable)) + --> { key1 = "value", key2 = 300 } +< +You can target specific buffers (via number), windows (via |window-ID|), or +tabpages by indexing the wrappers: +>lua + vim.b[2].myvar = 1 -- set myvar for buffer number 2 + vim.w[1005].myothervar = true -- set myothervar for window ID 1005 +< +Some variable names may contain characters that cannot be used for identifiers +in Lua. You can still manipulate these variables by using the syntax +>lua + vim.g['my#variable'] = 1 +< +Note that you cannot directly change fields of array variables. This won't +work: +>lua + vim.g.some_global_variable.key2 = 400 + vim.pretty_print(vim.g.some_global_variable) + --> { key1 = "value", key2 = 300 } +< +Instead, you need to create an intermediate Lua table and change this: +>lua + local temp_table = vim.g.some_global_variable + temp_table.key2 = 400 + vim.g.some_global_variable = temp_table + vim.pretty_print(vim.g.some_global_variable) + --> { key1 = "value", key2 = 400 } +< +To delete a variable, simply set it to `nil`: +>lua + vim.g.myvar = nil +< +------------------------------------------------------------------------------ +See also: +• |lua-vim-variables| + +============================================================================== +Options *lua-guide-options* + +There are two complementary ways of setting |options| via Lua. + +------------------------------------------------------------------------------ +vim.opt + +The most convenient way for setting global and local options, e.g., in `init.lua`, +is through `vim.opt` and friends: + +• |vim.opt|: behaves like |:set| +• |vim.opt_global|: behaves like |:setglobal| +• |vim.opt_local|: behaves like |:setlocal| + +For example, the Vimscript commands +>vim + set smarttab + set nosmarttab +< +are equivalent to +>lua + vim.opt.smarttab = true + vim.opt.smarttab = false +< +In particular, they allow an easy way to working with list-like, map-like, and +set-like options through Lua tables: Instead of +>vim + set wildignore=*.o,*.a,__pycache__ + set listchars=space:_,tab:>~ + set formatoptions=njt +< +you can use +>lua + vim.opt.wildignore = { '*.o', '*.a', '__pycache__' } + vim.opt.listchars = { space = '_', tab = '>~' } + vim.opt.formatoptions = { n = true, j = true, t = true } +< +These wrappers also come with methods that work similarly to their |:set+=|, +|:set^=| and |:set-=| counterparts in Vimscript: +>lua + vim.opt.shortmess:append({ I = true }) + vim.opt.wildignore:prepend('*.o') + vim.opt.whichwrap:remove({ 'b', 's' }) +< +The price to pay is that you cannot access the option values directly but must +use |vim.opt:get()|: +>lua + print(vim.opt.smarttab) + --> {...} (big table) + print(vim.opt.smarttab:get()) + --> false + vim.pretty_print(vim.opt.listchars:get()) + --> { space = '_', tab = '>~' } +< +------------------------------------------------------------------------------ +vim.o + +For this reason, there exists a more direct variable-like access using `vim.o` +and friends, similarly to how you can get and set options via `:echo &number` +and `:let &listchars='space:_,tab:>~'`: + +• |vim.o|: behaves like |:set| +• |vim.go|: behaves like |:setglobal| +• |vim.bo|: for buffer-scoped options +• |vim.wo|: for window-scoped options + +For example: +>lua + vim.o.smarttab = false -- :set nosmarttab + print(vim.o.smarttab) + --> false + vim.o.listchars = 'space:_,tab:>~' -- :set listchars='space:_,tab:>~' + print(vim.o.listchars) + --> 'space:_,tab:>~' + vim.o.isfname = vim.o.isfname .. ',@-@' -- :set isfname+=@-@ + print(vim.o.isfname) + --> '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@' + vim.bo.shiftwidth = 4 -- :setlocal shiftwidth=4 + print(vim.bo.shiftwidth) + --> 4 +< +Just like variables, you can specify a buffer number or |window-ID| for buffer +and window options, respectively. If no number is given, the current buffer or +window is used: +>lua + vim.bo[4].expandtab = true -- sets expandtab to true in buffer 4 + vim.wo.number = true -- sets number to true in current window + print(vim.wo[0].number) --> true +< +------------------------------------------------------------------------------ +See also: +• |lua-options| + +============================================================================== +Mappings *lua-guide-mappings* + +You can map either Vim commands or Lua functions to key sequences. + +------------------------------------------------------------------------------ +Creating mappings *lua-guide-mappings-set* + +Mappings can be created using |vim.keymap.set()|. This function takes three +mandatory arguments: +• {mode} is a string or a table of strings containing the mode + prefix for which the mapping will take effect. The prefixes are the ones + listed in |:map-modes|, or "!" for |:map!|, or empty string for |:map|. +• {lhs} is a string with the key sequences that should trigger the mapping. +• {rhs} is either a string with a Vim command or a Lua function that should + be executed when the {lhs} is entered. + An empty string is equivalent to |<Nop>|, which disables a key. + +Examples: +>lua + -- Normal mode mapping for Vim command + vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>') + -- Normal and Command-line mode mapping for Vim command + vim.keymap.set({'n', 'c'}, '<Leader>ex2', '<cmd>echo "Example 2"<cr>') + -- Normal mode mapping for Lua function + vim.keymap.set('n', '<Leader>ex3', vim.treesitter.start) + -- Normal mode mapping for Lua function with arguments + vim.keymap.set('n', '<Leader>ex4', function() print('Example 4') end) +< +You can map functions from Lua modules via +>lua + vim.keymap.set('n', '<Leader>pl1', require('plugin').action) +< +Note that this loads the plugin at the time the mapping is defined. If you +want to defer the loading to the time when the mapping is executed (as for +|autoload| functions), wrap it in `function() end`: +>lua + vim.keymap.set('n', '<Leader>pl2', function() require('plugin').action() end) +< +The fourth, optional, argument is a table with keys that modify the behavior +of the mapping such as those from |:map-arguments|. The following are the most +useful options: +• `buffer`: If given, only set the mapping for the buffer with the specified + number; `0` or `true` means the current buffer. >lua + -- set mapping for the current buffer + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = true }) + -- set mapping for the buffer number 4 + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = 4 }) +< +• `silent`: If set to `true`, suppress output such as error messages. >lua + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { silent = true }) +< +• `expr`: If set to `true`, do not execute the {rhs} but use the return value + as input. Special |keycodes| are converted automatically. For example, the following + mapping replaces <down> with <c-n> in the popupmenu only: >lua + vim.keymap.set('c', '<down>', function() + if vim.fn.pumvisible() == 1 then return '<c-n>' end + return '<down>' + end, { expr = true }) +< +• `desc`: A string that is shown when listing mappings with, e.g., |:map|. + This is useful since Lua functions as {rhs} are otherwise only listed as + `Lua: <number> <source file>:<line>`. Plugins should therefore always use this + for mappings they create. >lua + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, + { desc = 'Execute action from plugin' }) +< +• `remap`: By default, all mappings are nonrecursive by default (i.e., + |vim.keymap.set()| behaves like |:noremap|). If the {rhs} is itself a mapping + that should be executed, set `remap = true`: >lua + vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>') + -- add a shorter mapping + vim.keymap.set('n', 'e', '<Leader>ex1', { remap = true }) +< + Note: |<Plug>| mappings are always expanded even with the default `remap = false`: >lua + vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)') +< +------------------------------------------------------------------------------ +Removing mappings *lua-guide-mappings-del* + +A specific mapping can be removed with |vim.keymap.del()|: +>lua + vim.keymap.del('n', '<Leader>ex1') + vim.keymap.del({'n', 'c'}, '<Leader>ex2', {buffer = true}) +< +------------------------------------------------------------------------------ +See also: +• `vim.api.`|nvim_get_keymap()|: return all global mapping +• `vim.api.`|nvim_buf_get_keymap()|: return all mappings for buffer + +============================================================================== +Autocommands *lua-guide-autocommands* + +An |autocommand| is a Vim command or a Lua function that is automatically +executed whenever one or more |events| are triggered, e.g., when a file is +read or written, or when a window is created. These are accessible from Lua +through the Neovim API. + +------------------------------------------------------------------------------ +Creating autocommands *lua-guide-autocommand-create* + +Autocommands are created using `vim.api.`|nvim_create_autocmd()|, which takes +two mandatory arguments: +• {event}: a string or table of strings containing the event(s) which should + trigger the command or function. +• {opts}: a table with keys that control what should happen when the event(s) + are triggered. + +The most important options are: + +• `pattern`: A string or table of strings containing the |autocmd-pattern|. + Note: Environment variable like `$HOME` and `~` are not automatically + expanded; you need to explicitly use `vim.fn.`|expand()| for this. +• `command`: A string containing a Vim command. +• `callback`: A Lua function. + +You must specify one and only one of `command` and `callback`. If `pattern` is +omitted, it defaults to `pattern = '*'`. +Examples: +>lua + vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { + pattern = {"*.c", "*.h"}, + command = "echo 'Entering a C or C++ file'", + }) + + -- Same autocommand written with a Lua function instead + vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { + pattern = {"*.c", "*.h"}, + callback = function() print("Entering a C or C++ file") end, + }) + + -- User event triggered by MyPlugin + vim.api.nvim_create_autocmd("User", { + pattern = "MyPlugin", + callback = function() print("My Plugin Works!") end, + }) +< + +Neovim will always call a Lua function with a single table containing information +about the triggered autocommand. The most useful keys are +• `match`: a string that matched the `pattern` (see |<amatch>|) +• `buf`: the number of the buffer the event was triggered in (see |<abuf>|) +• `file`: the file name of the buffer the event was triggered in (see |<afile>|) +• `data`: a table with other relevant data that is passed for some events + +For example, this allows you to set buffer-local mappings for some filetypes: +>lua + vim.api.nvim.create_autocmd("FileType", { + pattern = "lua", + callback = function(args) + vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf }) + end + }) +< +This means that if your callback itself takes an (even optional) argument, you +must wrap it in `function() end` to avoid an error: +>lua + vim.api.nvim_create_autocmd('TextYankPost', { + callback = function() vim.highlight.on_yank() end + }) +< +(Since unused arguments can be omitted in Lua function definitions, this is +equivalent to `function(args) ... end`.) + +Instead of using a pattern, you can create a buffer-local autocommand (see +|autocmd-buflocal|) with `buffer`; in this case, `pattern` cannot be used: +>lua + -- set autocommand for current buffer + vim.api.nvim_create_autocmd("CursorHold", { + buffer = 0, + callback = function() print("hold") end, + }) + + -- set autocommand for buffer number 33 + vim.api.nvim_create_autocmd("CursorHold", { + buffer = 33, + callback = function() print("hold") end, + }) +< +Similarly to mappings, you can (and should) add a description using `desc`: +>lua + vim.api.nvim_create_autocmd('TextYankPost', { + callback = function() vim.highlight.on_yank() end, + desc = "Briefly highlight yanked text" + }) +< +Finally, you can group autocommands using the `group` key; this will be +covered in detail in the next section. + +------------------------------------------------------------------------------ +Grouping autocommands *lua-guide-autocommands-group* + +Autocommand groups can be used to group related autocommands together; see +|autocmd-groups|. This is useful for organizing autocommands and especially +for preventing autocommands to be set multiple times. + +Groups can be created with `vim.api.`|nvim_create_augroup()|. This function +takes two mandatory arguments: a string with the name of a group and a table +determining whether the group should be cleared (i.e., all grouped +autocommands removed) if it already exists. The function returns a number that +is the internal identifier of the group. Groups can be specified either by +this identifier or by the name (but only if the group has been created first). + +For example, a common Vimscript pattern for autocommands defined in files that +may be reloaded is +>vim + augroup vimrc + " Remove all vimrc autocommands + autocmd! + au BufNewFile,BufRead *.html set shiftwidth=4 + au BufNewFile,BufRead *.html set expandtab + augroup END +< +This is equivalent to the following Lua code: +>lua + local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = true }) + vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, { + pattern = '*.html', + group = mygroup, + command = 'set shiftwidth=4', + }) + vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, { + pattern = '*.html', + group = 'vimrc', -- equivalent to group=mygroup + command = 'set expandtab', + }) +< +Autocommand groups are unique for a given name, so you can reuse them, e.g., +in a different file: +>lua + local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = false }) + vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, { + pattern = '*.html', + group = mygroup, + command = 'set shiftwidth=4', + }) +< +------------------------------------------------------------------------------ +Deleting autocommands *lua-guide-autocommands-delete* + +You can use `vim.api.`|nvim_clear_autocmds()| to remove autocommands. This +function takes a single mandatory argument that is a table of keys describing +the autocommands that are to be removed: +>lua + -- Delete all BufEnter and InsertLeave autocommands + vim.api.nvim_clear_autocmds({event = {"BufEnter", "InsertLeave"}}) + + -- Delete all autocommands that uses "*.py" pattern + vim.api.nvim_clear_autocmds({pattern = "*.py"}) + + -- Delete all autocommands in group "scala" + vim.api.nvim_clear_autocmds({group = "scala"}) + + -- Delete all ColorScheme autocommands in current buffer + vim.api.nvim_clear_autocmds({event = "ColorScheme", buffer = 0 }) +< +Note: Autocommands in groups will only be removed if the `group` key is +specified, even if another option matches it. + +------------------------------------------------------------------------------ +See also +• |nvim_get_autocmds()|: return all matching autocommands +• |nvim_exec_autocmds()|: execute all matching autocommands + +============================================================================== +User commands *lua-guide-usercommands* + +|user-commands| are custom Vim commands that call a Vimscript or Lua function. +Just like built-in commands, they can have arguments, act on ranges, or have +custom completion of arguments. As these are most useful for plugins, we will +cover only the basics of this advanced topic. + +------------------------------------------------------------------------------ +Creating user commands *lua-guide-usercommands-create* + +User commands can be created through the Neovim API with +`vim.api.`|nvim_create_user_command()|. This function takes three mandatory +arguments: +• a string that is the name of the command (which must start with an uppercase + letter to distinguish it from builtin commands); +• a string containing Vim commands or a Lua function that is executed when the + command is invoked; +• a table with |command-attributes|; in addition, it can contain the keys + `desc` (a string describing the command); `force` (set to `false` to avoid + replacing an already existing command with the same name), and `preview` (a + Lua function that is used for |:command-preview|). + +Example: +>lua + vim.api.nvim_create_user_command('Test', 'echo "It works!"', {}) + vim.cmd.Test() + --> It works! +< +(Note that the third argument is mandatory even if no attributes are given.) + +Lua functions are called with a single table argument containing arguments and +modifiers. The most important are: +• `name`: a string with the command name +• `fargs`: a table containing the command arguments split by whitespace (see |<f-args>|) +• `bang`: `true` if the command was executed with a `!` modifier (see |<bang>|) +• `line1`: the starting line number of the command range (see |<line1>|) +• `line2`: the final line number of the command range (see |<line2>|) +• `range`: the number of items in the command range: 0, 1, or 2 (see |<range>|) +• `count`: any count supplied (see |<count>|) +• `smods`: a table containing the command modifiers (see |<mods>|) + +For example: +>lua + vim.api.nvim_create_user_command('Upper', + function(opts) + print(string.upper(opts.fargs[1])) + end, + { nargs = 1 }) + + vim.cmd.Upper('foo') + --> FOO +< +The `complete` attribute can take a Lua function in addition to the +attributes listed in |:command-complete|. >lua + + vim.api.nvim_create_user_command('Upper', + function(opts) + print(string.upper(opts.fargs[1])) + end, + { nargs = 1, + complete = function(ArgLead, CmdLine, CursorPos) + -- return completion candidates as a list-like table + return { "foo", "bar", "baz" } + end, + }) +< +Buffer-local user commands are created with `vim.api.`|nvim_buf_create_user_command()|. +Here the first argument is the buffer number (`0` being the current buffer); +the remaining arguments are the same as for |nvim_create_user_command()|: +>lua + vim.api.nvim_buf_create_user_command(0, 'Upper', + function(opts) + print(string.upper(opts.fargs[1])) + end, + { nargs = 1 }) +< +------------------------------------------------------------------------------ +Deleting user commands *lua-guide-usercommands-delete* + +User commands can be deleted with `vim.api.`|nvim_del_user_command()|. The only +argument is the name of the command: +>lua + vim.api.nvim_del_user_command('Upper') +< +To delete buffer-local user commands use `vim.api.`|nvim_buf_del_user_command()|. +Here the first argument is the buffer number (`0` being the current buffer), +and second is command name: +>lua + vim.api.nvim_buf_del_user_command(4, 'Upper') +< +============================================================================== +Credits *lua-guide-credits* +This guide is in large part taken from nanotee's Lua guide: +https://github.com/nanotee/nvim-lua-guide + +Thank you @nanotee! + +vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 42f3a5e432..47249a484b 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -11,30 +11,119 @@ Lua engine *lua* *Lua* ============================================================================== INTRODUCTION *lua-intro* -The Lua 5.1 language is builtin and always available. Try this command to get -an idea of what lurks beneath: > +The Lua 5.1 script engine is builtin and always available. Try this command to +get an idea of what lurks beneath: >vim :lua print(vim.inspect(package.loaded)) + +Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the +"editor stdlib" (|builtin-functions| and |Ex-commands|) and the |API|, all of +which can be used from Lua code (|lua-vimscript| |vim.api|). Together these +"namespaces" form the Nvim programming interface. + +Lua plugins and user config are automatically discovered and loaded, just like +Vimscript. See |lua-guide| for practical guidance. + +You can also run Lua scripts from your shell using the |-l| argument: > + nvim -l foo.lua [args...] +< + *lua-compat* +Lua 5.1 is the permanent interface for Nvim Lua. Plugins need only consider +Lua 5.1, not worry about forward-compatibility with future Lua versions. If +Nvim ever ships with Lua 5.4+, a Lua 5.1 compatibility shim will be provided +so that old plugins continue to work transparently. + +============================================================================== +LUA CONCEPTS AND IDIOMS *lua-concepts* + +Lua is very simple: this means that, while there are some quirks, once you +internalize those quirks, everything works the same everywhere. Scopes +(closures) in particular are very consistent, unlike JavaScript or most other +languages. + +Lua has three fundamental mechanisms—one for "each major aspect of +programming": tables, closures, and coroutines. +https://www.lua.org/doc/cacm2018.pdf +- Tables are the "object" or container datastructure: they represent both + lists and maps, you can extend them to represent your own datatypes and + change their behavior using |luaref-metatable| (like Python's "datamodel"). +- EVERY scope in Lua is a closure: a function is a closure, a module is + a closure, a `do` block (|luaref-do|) is a closure--and they all work the + same. A Lua module is literally just a big closure discovered on the "path" + (where your modules are found: |package.cpath|). +- Stackful coroutines enable cooperative multithreading, generators, and + versatile control for both Lua and its host (Nvim). + + *lua-call-function* +Lua functions can be called in multiple ways. Consider the function: >lua + local foo = function(a, b) + print("A: ", a) + print("B: ", b) + end + +The first way to call this function is: >lua + foo(1, 2) + -- ==== Result ==== + -- A: 1 + -- B: 2 + +This way of calling a function is familiar from most scripting languages. +In Lua, any missing arguments are passed as `nil`. Example: >lua + foo(1) + -- ==== Result ==== + -- A: 1 + -- B: nil + +Furthermore it is not an error if extra parameters are passed, they are just +discarded. + + *kwargs* +When calling a function, you can omit the parentheses if the function takes +exactly one string literal (`"foo"`) or table literal (`{1,2,3}`). The latter +is often used to approximate "named parameters" ("kwargs" or "keyword args") +as in languages like Python and C#. Example: >lua + local func_with_opts = function(opts) + local will_do_foo = opts.foo + local filename = opts.filename + ... + end + + func_with_opts { foo = true, filename = "hello.world" } < -Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the -"editor stdlib" (|builtin-functions| and Ex commands) and the |API|, all of -which can be used from Lua code. A good overview of using Lua in neovim is -given by https://github.com/nanotee/nvim-lua-guide. +There's nothing special going on here except that parentheses are treated as +whitespace. But visually, this small bit of sugar gets reasonably close to +a "keyword args" interface. + +It is of course also valid to call the function with parentheses: >lua + func_with_opts({ foo = true, filename = "hello.world" }) +< +Nvim tends to prefer the keyword args style. + +------------------------------------------------------------------------------ +LUA PATTERNS *lua-patterns* -The |:source| and |:runtime| commands can run Lua scripts as well as Vim -scripts. Lua modules can be loaded with `require('name')`, which -conventionally returns a table but can return any value. +Lua intentionally does not support regular expressions, instead it has limited +"patterns" |luaref-patterns| which avoid the performance pitfalls of extended +regex. Lua scripts can also use Vim regex via |vim.regex()|. -See |lua-require| for details on how Nvim finds and loads Lua modules. -See |lua-require-example| for an example of how to write and use a module. +These examples use |string.match()| to demonstrate Lua patterns: >lua + + print(string.match("foo123bar123", "%d+")) + -- 123 + print(string.match("foo123bar123", "[^%d]+")) + -- foo + print(string.match("foo123bar123", "[abc]+")) + -- ba + print(string.match("foo.bar", "%.bar")) + -- .bar ============================================================================== -IMPORTING LUA MODULES *lua-require* +IMPORTING LUA MODULES *require()* *lua-require* Modules are searched for under the directories specified in 'runtimepath', in -the order they appear. Any `.` in the module name is treated as a directory -separator when searching. For a module `foo.bar`, each directory is searched -for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found, +the order they appear. Any "." in the module name is treated as a directory +separator when searching. For a module `foo.bar`, each directory is searched +for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found, the directories are searched again for a shared library with a name matching `lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from the initial value of |package.cpath|. If still no files are found, Nvim falls @@ -43,13 +132,11 @@ back to Lua's default search mechanism. The first script found is run and The return value is cached after the first call to `require()` for each module, with subsequent calls returning the cached value without searching for, or -executing any script. For further details on `require()`, see the Lua -documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require. +executing any script. For further details on `require()`, see |luaref-require()|. For example, if 'runtimepath' is `foo,bar` and |package.cpath| was `./?.so;./?.dll` at startup, `require('mod')` searches these paths in order -and loads the first module found: - +and loads the first module found ("first wins"): > foo/lua/mod.lua foo/lua/mod/init.lua bar/lua/mod.lua @@ -58,10 +145,11 @@ and loads the first module found: foo/lua/mod.dll bar/lua/mod.so bar/lua/mod.dll - +< + *lua-package-path* Nvim automatically adjusts |package.path| and |package.cpath| according to the effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is -changed. |package.path| is adjusted by simply appending `/lua/?.lua` and +changed. `package.path` is adjusted by simply appending `/lua/?.lua` and `/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the first character of `package.config`). @@ -70,37 +158,33 @@ added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and `/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of the existing |package.cpath| are used. Example: -1. Given that +- 1. Given that - 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`; - - initial (defined at compile-time or derived from - `$LUA_CPATH`/`$LUA_INIT`) |package.cpath| contains - `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`. -2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in - order: parts of the path starting from the first path component containing - question mark and preceding path separator. -3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same - as the suffix of the first path from |package.path| (i.e. `./?.so`). Which - leaves `/?.so` and `/a?d/j/g.elf`, in this order. -4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The - second one contains a semicolon which is a paths separator so it is out, - leaving only `/foo/bar` and `/abc`, in order. -5. The cartesian product of paths from 4. and suffixes from 3. is taken, - giving four variants. In each variant, a `/lua` path segment is inserted - between path and suffix, leaving: - - - `/foo/bar/lua/?.so` - - `/foo/bar/lua/a?d/j/g.elf` - - `/abc/lua/?.so` - - `/abc/lua/a?d/j/g.elf` - -6. New paths are prepended to the original |package.cpath|. - -The result will look like this: - - `/foo/bar,/xxx;yyy/baz,/abc` ('runtimepath') - × `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so` (`package.cpath`) - - = `/foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.so` + - initial |package.cpath| (defined at compile-time or derived from + `$LUA_CPATH` / `$LUA_INIT`) contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`. +- 2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in + order: parts of the path starting from the first path component containing + question mark and preceding path separator. +- 3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same + as the suffix of the first path from |package.path| (i.e. `./?.so`). Which + leaves `/?.so` and `/a?d/j/g.elf`, in this order. +- 4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The + second one contains a semicolon which is a paths separator so it is out, + leaving only `/foo/bar` and `/abc`, in order. +- 5. The cartesian product of paths from 4. and suffixes from 3. is taken, + giving four variants. In each variant a `/lua` path segment is inserted + between path and suffix, leaving: + - `/foo/bar/lua/?.so` + - `/foo/bar/lua/a?d/j/g.elf` + - `/abc/lua/?.so` + - `/abc/lua/a?d/j/g.elf` +- 6. New paths are prepended to the original |package.cpath|. + +The result will look like this: > + + /foo/bar,/xxx;yyy/baz,/abc ('runtimepath') + × ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so (package.cpath) + = /foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.so Note: @@ -113,7 +197,7 @@ Note: - Although adjustments happen automatically, Nvim does not track current values of |package.path| or |package.cpath|. If you happen to delete some - paths from there you can set 'runtimepath' to trigger an update: > + paths from there you can set 'runtimepath' to trigger an update: >vim let &runtimepath = &runtimepath - Skipping paths from 'runtimepath' which contain semicolons applies both to @@ -122,170 +206,13 @@ Note: it is better to not have them in 'runtimepath' at all. ============================================================================== -Lua Syntax Information *lua-syntax-help* - -While Lua has a simple syntax, there are a few things to understand, -particularly when looking at the documentation above. - - *lua-syntax-call-function* - -Lua functions can be called in multiple ways. Consider the function: > - - local example_func = function(a, b) - print("A is: ", a) - print("B is: ", b) - end -< -The first way to call this function is: > - - example_func(1, 2) - -- ==== Result ==== - -- A is: 1 - -- B is: 2 -< -This way of calling a function is familiar from most scripting languages. -In Lua, it's important to understand that any function arguments that are -not supplied are automatically set to `nil`. For example: > - - example_func(1) - -- ==== Result ==== - -- A is: 1 - -- B is: nil -< -Additionally, if any extra parameters are passed, they are discarded -completely. - -In Lua, it is also possible to omit the parentheses (only) if the function -takes a single string or table literal (`"foo"` or "`{1,2,3}`", respectively). -The latter is most often used to approximate "keyword-style" arguments with a -single dictionary, for example: > - - local func_with_opts = function(opts) - local will_do_foo = opts.foo - local filename = opts.filename - - ... - end - - func_with_opts { foo = true, filename = "hello.world" } -< -In this style, each "parameter" is passed via keyword. It is still valid -to call the function in the standard style: > - - func_with_opts({ foo = true, filename = "hello.world" }) -< -But often in the documentation, you will see the former rather than the -latter style due to its brevity. - -============================================================================== -Lua Patterns *lua-patterns* - -For performance reasons, Lua does not support regular expressions natively. -Instead, the Lua `string` standard library allows manipulations using a -restricted set of "patterns", see |luaref-patterns|. - -Examples (`string.match` extracts the first match): > - - print(string.match("foo123bar123", "%d+")) - -- -> 123 - - print(string.match("foo123bar123", "[^%d]+")) - -- -> foo - - print(string.match("foo123bar123", "[abc]+")) - -- -> ba - - print(string.match("foo.bar", "%.bar")) - -- -> .bar - -For more complex matching, Vim regular expressions can be used from Lua -through |vim.regex()|. - ------------------------------------------------------------------------------- -LUA PLUGIN EXAMPLE *lua-require-example* - -The following example plugin adds a command `:MakeCharBlob` which transforms -current buffer into a long `unsigned char` array. Lua contains transformation -function in a module `lua/charblob.lua` which is imported in -`autoload/charblob.vim` (`require("charblob")`). Example plugin is supposed -to be put into any directory from 'runtimepath', e.g. `~/.config/nvim` (in -this case `lua/charblob.lua` means `~/.config/nvim/lua/charblob.lua`). - -autoload/charblob.vim: > - - function charblob#encode_buffer() - call setline(1, luaeval( - \ 'require("charblob").encode(unpack(_A))', - \ [getline(1, '$'), &textwidth, ' '])) - endfunction -< -plugin/charblob.vim: > - - if exists('g:charblob_loaded') - finish - endif - let g:charblob_loaded = 1 - - command MakeCharBlob :call charblob#encode_buffer() -< -lua/charblob.lua: > - - local function charblob_bytes_iter(lines) - local init_s = { - next_line_idx = 1, - next_byte_idx = 1, - lines = lines, - } - local function next(s, _) - if lines[s.next_line_idx] == nil then - return nil - end - if s.next_byte_idx > #(lines[s.next_line_idx]) then - s.next_line_idx = s.next_line_idx + 1 - s.next_byte_idx = 1 - return ('\n'):byte() - end - local ret = lines[s.next_line_idx]:byte(s.next_byte_idx) - if ret == ('\n'):byte() then - ret = 0 -- See :h NL-used-for-NUL. - end - s.next_byte_idx = s.next_byte_idx + 1 - return ret - end - return next, init_s, nil - end - - local function charblob_encode(lines, textwidth, indent) - local ret = { - 'const unsigned char blob[] = {', - indent, - } - for byte in charblob_bytes_iter(lines) do - -- .- space + number (width 3) + comma - if #(ret[#ret]) + 5 > textwidth then - ret[#ret + 1] = indent - else - ret[#ret] = ret[#ret] .. ' ' - end - ret[#ret] = ret[#ret] .. (('%3u,'):format(byte)) - end - ret[#ret + 1] = '};' - return ret - end - - return { - bytes_iter = charblob_bytes_iter, - encode = charblob_encode, - } -< -============================================================================== 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 has its own scope (closure), so only global variables are shared between command calls. The |lua-stdlib| modules, user modules, and anything else on -|lua-package-path| are available. +|package.path| are available. The Lua print() function redirects its output to the Nvim message area, with arguments separated by " " (space) instead of "\t" (tab). @@ -296,11 +223,11 @@ arguments separated by " " (space) instead of "\t" (tab). chunk is evaluated as an expression and printed. `:lua =expr` is equivalent to `:lua print(vim.inspect(expr))` - Examples: > + Examples: >vim :lua vim.api.nvim_command('echo "Hello, Nvim!"') -< To see the Lua version: > +< To see the Lua version: >vim :lua print(_VERSION) -< To see the LuaJIT version: > +< To see the LuaJIT version: >vim :lua =jit.version < *:lua-heredoc* @@ -311,7 +238,7 @@ arguments separated by " " (space) instead of "\t" (tab). be preceded by whitespace. You can omit [endmarker] after the "<<" and use a dot "." after {script} (similar to |:append|, |:insert|). - Example: > + Example: >vim function! CurrentLineInfo() lua << EOF local linenr = vim.api.nvim_win_get_cursor(0)[1] @@ -333,13 +260,13 @@ arguments separated by " " (space) instead of "\t" (tab). that becomes the text of the corresponding buffer line. Default [range] is the whole file: "1,$". - Examples: > + Examples: >vim :luado return string.format("%s\t%d", line:reverse(), #line) :lua require"lpeg" :lua -- balanced parenthesis grammar: :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" } - :luado if bp:match(line) then return "-->\t" .. line end + :luado if bp:match(line) then return "=>\t" .. line end < *:luafile* :luafile {file} @@ -347,7 +274,7 @@ arguments separated by " " (space) instead of "\t" (tab). The whole argument is used as the filename (like |:edit|), spaces do not need to be escaped. Alternatively you can |:source| Lua files. - Examples: > + Examples: >vim :luafile script.lua :luafile % < @@ -358,7 +285,7 @@ luaeval() *lua-eval* *luaeval()* The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is "luaeval". "luaeval" takes an expression string and an optional argument used for _A inside expression and returns the result of the expression. It is -semantically equivalent in Lua to: > +semantically equivalent in Lua to: >lua local chunkheader = "local _A = select(1, ...) return " function luaeval (expstr, arg) @@ -372,11 +299,11 @@ converted to a |Blob|. Conversion of other Lua types is an error. The magic global "_A" contains the second argument to luaeval(). -Example: > +Example: >vim :echo luaeval('_A[1] + _A[2]', [40, 2]) - 42 + " 42 :echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123') - foo + " foo < Lua tables are used as both dictionaries and lists, so it is impossible to determine whether empty table is meant to be empty list or empty dictionary. @@ -408,7 +335,7 @@ cases there is the following agreement: form a 1-step sequence from 1 to N are ignored, as well as all non-integral keys. -Examples: > +Examples: >vim :echo luaeval('math.pi') :function Rand(x,y) " random uniform between x and y @@ -425,29 +352,29 @@ treated specially. Vimscript v:lua interface *v:lua-call* From Vimscript the special `v:lua` prefix can be used to call Lua functions -which are global or accessible from global tables. The expression > - v:lua.func(arg1, arg2) -is equivalent to the Lua chunk > +which are global or accessible from global tables. The expression >vim + call v:lua.func(arg1, arg2) +is equivalent to the Lua chunk >lua return func(...) -where the args are converted to Lua values. The expression > - v:lua.somemod.func(args) -is equivalent to the Lua chunk > +where the args are converted to Lua values. The expression >vim + call v:lua.somemod.func(args) +is equivalent to the Lua chunk >lua return somemod.func(...) -In addition, functions of packages can be accessed like > - v:lua.require'mypack'.func(arg1, arg2) - v:lua.require'mypack.submod'.func(arg1, arg2) +In addition, functions of packages can be accessed like >vim + call v:lua.require'mypack'.func(arg1, arg2) + call v:lua.require'mypack.submod'.func(arg1, arg2) Note: Only single quote form without parens is allowed. Using `require"mypack"` or `require('mypack')` as prefixes do NOT work (the latter is still valid as a function call of itself, in case require returns a useful value). The `v:lua` prefix may be used to call Lua functions as |method|s. For -example: > - arg1->v:lua.somemod.func(arg2) +example: >vim + :eval arg1->v:lua.somemod.func(arg2) < You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc. -For example consider the following Lua omnifunc handler: > +For example consider the following Lua omnifunc handler: >lua function mymod.omnifunc(findstart, base) if findstart == 1 then @@ -459,10 +386,10 @@ For example consider the following Lua omnifunc handler: > vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.mymod.omnifunc') Note: The module ("mymod" in the above example) must either be a Lua global, -or use the require syntax as specified above to access it from a package. +or use require() as shown above to access it from a package. Note: `v:lua` without a call is not allowed in a Vimscript expression: -|Funcref|s cannot represent Lua functions. The following are errors: > +|Funcref|s cannot represent Lua functions. The following are errors: >vim let g:Myvar = v:lua.myfunc " Error call SomeFunc(v:lua.mycallback) " Error @@ -476,7 +403,7 @@ The Nvim Lua "standard library" (stdlib) is the `vim` module, which exposes various functions and sub-modules. It is always loaded, thus `require("vim")` is unnecessary. -You can peek at the module properties: > +You can peek at the module properties: >vim :lua print(vim.inspect(vim)) @@ -496,7 +423,7 @@ Result is something like this: > ... } -To find documentation on e.g. the "deepcopy" function: > +To find documentation on e.g. the "deepcopy" function: >vim :help vim.deepcopy() @@ -508,7 +435,7 @@ VIM.LOOP *lua-loop* *vim.loop* `vim.loop` exposes all features of the Nvim event-loop. This is a low-level API that provides functionality for networking, filesystem, and process -management. Try this command to see available functions: > +management. Try this command to see available functions: >vim :lua print(vim.inspect(vim.loop)) < @@ -517,14 +444,14 @@ see |luv-intro| for a full reference manual. *E5560* *lua-loop-callbacks* It is an error to directly invoke `vim.api` functions (except |api-fast|) in -`vim.loop` callbacks. For example, this is an error: > +`vim.loop` callbacks. For example, this is an error: >lua local timer = vim.loop.new_timer() timer:start(1000, 0, function() vim.api.nvim_command('echomsg "test"') end) < -To avoid the error use |vim.schedule_wrap()| to defer the callback: > +To avoid the error use |vim.schedule_wrap()| to defer the callback: >lua local timer = vim.loop.new_timer() timer:start(1000, 0, vim.schedule_wrap(function() @@ -536,7 +463,7 @@ wrapping.) Example: repeating timer 1. Save this code to a file. - 2. Execute it with ":luafile %". > + 2. Execute it with ":luafile %". >lua -- Create a timer handle (implementation detail: uv_timer_t). local timer = vim.loop.new_timer() @@ -557,7 +484,7 @@ Example: File-change detection *watch-file* 3. Use ":Watch %" to watch any file. 4. Try editing the file from another text editor. 5. Observe that the file reloads in Nvim (because on_change() calls - |:checktime|). > + |:checktime|). >lua local w = vim.loop.new_fs_event() local function on_change(err, fname, status) @@ -580,7 +507,7 @@ Example: TCP echo-server *tcp-server* 1. Save this code to a file. 2. Execute it with ":luafile %". 3. Note the port number. - 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): > + 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >lua local function create_server(host, port, on_connect) local server = vim.loop.new_tcp() @@ -617,7 +544,7 @@ A subset of the `vim.*` API is available in threads. This includes: - `vim.loop` with a separate event loop per thread. - `vim.mpack` and `vim.json` (useful for serializing messages between threads) -- `require` in threads can use lua packages from the global |lua-package-path| +- `require` in threads can use lua packages from the global |package.path| - `print()` and `vim.inspect` - `vim.diff` - most utility functions in `vim.*` for working with pure lua values @@ -629,16 +556,16 @@ VIM.HIGHLIGHT *lua-highlight* Nvim includes a function for highlighting a selection on yank (see for example https://github.com/machakann/vim-highlightedyank). To enable it, add -> +>vim au TextYankPost * silent! lua vim.highlight.on_yank() < to your `init.vim`. You can customize the highlight group and the duration of the highlight via -> +>vim au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} < If you want to exclude visual selections from highlighting on yank, use -> +>vim au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} < vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* @@ -656,14 +583,14 @@ vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts}) Apply highlight group to range of text. Parameters: ~ - {bufnr} buffer number - {ns} namespace for highlights - {hlgroup} highlight group name - {start} starting position (tuple {line,col}) - {finish} finish position (tuple {line,col}) - {opts} optional parameters: + • {bufnr} buffer number + • {ns} namespace for highlights + • {hlgroup} highlight group name + • {start} starting position (tuple {line,col}) + • {finish} finish position (tuple {line,col}) + • {opts} optional parameters: • `regtype`: type of range (characterwise, linewise, - or blockwise, see |setreg|), default `'v'` + or blockwise, see |setreg()|), default `'v'` • `inclusive`: range includes end position, default `false` • `priority`: priority of highlight, default @@ -674,6 +601,7 @@ vim.highlight.priorities *vim.highlight.priorities* Table with default priorities used for highlighting: • `syntax`: `50`, used for standard syntax highlighting • `treesitter`: `100`, used for tree-sitter-based highlighting + • `semantic_tokens`: `125`, used for LSP semantic token highlighting • `diagnostics`: `150`, used for code analysis such as diagnostics • `user`: `200`, used for user-triggered highlights such as LSP document symbols or `on_yank` autocommands @@ -711,25 +639,24 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* Run diff on strings {a} and {b}. Any indices returned by this function, either directly or via callback arguments, are 1-based. - Examples: > - + Examples: >lua vim.diff('a\n', 'b\nc\n') - --> - @@ -1 +1,2 @@ - -a - +b - +c + -- => + -- @@ -1 +1,2 @@ + -- -a + -- +b + -- +c vim.diff('a\n', 'b\nc\n', {result_type = 'indices'}) - --> - { - {1, 1, 1, 2} - } + -- => + -- { + -- {1, 1, 1, 2} + -- } < Parameters: ~ - {a} First string to compare - {b} Second string to compare - {opts} Optional parameters: + • {a} First string to compare + • {b} Second string to compare + • {opts} Optional parameters: • `on_hunk` (callback): Invoked for each hunk in the diff. Return a negative number to cancel the callback for any remaining hunks. @@ -742,6 +669,9 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* • "unified": (default) String in unified format. • "indices": Array of hunk locations. Note: This option is ignored if `on_hunk` is used. + • `linematch` (boolean): Run linematch on the resulting hunks + from xdiff. Requires `result_type = indices`, ignored + otherwise. • `algorithm` (string): Diff algorithm to use. Values: • "myers" the default algorithm @@ -782,6 +712,22 @@ vim.mpack.decode({str}) *vim.mpack.decode* Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. ------------------------------------------------------------------------------ +VIM.JSON *lua-json* + +The *vim.json* module provides encoding and decoding of Lua objects to and +from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. + +vim.json.encode({obj}) *vim.json.encode* + Encodes (or "packs") Lua object {obj} as JSON in a Lua string. + +vim.json.decode({str}[, {opts}]) *vim.json.decode* + Decodes (or "unpacks") the JSON-encoded {str} to a Lua object. + + {opts} is a table with the key `luanil = { object: bool, array: bool }` + that controls whether `null` in JSON objects or arrays should be converted + to Lua `nil` instead of `vim.NIL`. + +------------------------------------------------------------------------------ VIM.SPELL *lua-spell* vim.spell.check({str}) *vim.spell.check()* @@ -792,16 +738,15 @@ vim.spell.check({str}) *vim.spell.check()* 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to the buffer. Consider calling this with |nvim_buf_call()|. - Example: > - + Example: >lua vim.spell.check("the quik brown fox") - --> - { - {'quik', 'bad', 4} - } + -- => + -- { + -- {'quik', 'bad', 5} + -- } < Parameters: ~ - {str} String to spell check. + • {str} String to spell check. Return: ~ List of tuples with three items: @@ -818,7 +763,7 @@ VIM *lua-builtin* vim.api.{func}({...}) *vim.api* Invokes Nvim |API| function {func} with arguments {...}. - Example: call the "nvim_get_current_line()" API function: > + Example: call the "nvim_get_current_line()" API function: >lua print(tostring(vim.api.nvim_get_current_line())) vim.version() *vim.version* @@ -881,6 +826,22 @@ vim.str_byteindex({str}, {index} [, {use_utf16}]) *vim.str_byteindex()* An {index} in the middle of a UTF-16 sequence is rounded upwards to the end of that sequence. +vim.iconv({str}, {from}, {to}[, {opts}]) *vim.iconv()* + The result is a String, which is the text {str} converted from + encoding {from} to encoding {to}. When the conversion fails `nil` is + returned. When some characters could not be converted they + are replaced with "?". + The encoding names are whatever the iconv() library function + can accept, see ":Man 3 iconv". + + Parameters: ~ + • {str} (string) Text to convert + • {from} (string) Encoding of {str} + • {to} (string) Target encoding + + Returns: ~ + Converted string if conversion succeeds, `nil` otherwise. + vim.schedule({callback}) *vim.schedule()* Schedules {callback} to be invoked soon by the main event-loop. Useful to avoid |textlock| or other temporary restrictions. @@ -890,12 +851,12 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn* Defers calling {fn} until {timeout} ms passes. Use to do a one-shot timer that calls {fn}. - Note: The {fn} is |schedule_wrap|ped automatically, so API functions are + Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are safe to call. Parameters: ~ - {fn} Callback to call once {timeout} expires - {timeout} Time in ms to wait before calling {fn} + • {fn} Callback to call once {timeout} expires + • {timeout} Time in ms to wait before calling {fn} Returns: ~ |vim.loop|.new_timer() object @@ -908,10 +869,10 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* 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. + • {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`. @@ -927,7 +888,7 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* If {callback} errors, the error is raised. - Examples: > + Examples: >lua --- -- Wait for 100 ms, allowing other events to process @@ -951,6 +912,43 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* end < +vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* + Attach to ui events, similar to |nvim_ui_attach()| but receive events + as lua callback. Can be used to implement screen elements like + popupmenu or message handling in lua. + + {options} should be a dictionary-like table, where `ext_...` options should + be set to true to receive events for the respective external element. + + {callback} receives event name plus additional parameters. See |ui-popupmenu| + and the sections below for event format for respective events. + + WARNING: This api is considered experimental. Usability will vary for + different screen elements. In particular `ext_messages` behavior is subject + to further changes and usability improvements. This is expected to be + used to handle messages when setting 'cmdheight' to zero (which is + likewise experimental). + + Example (stub for a |ui-popupmenu| implementation): >lua + + ns = vim.api.nvim_create_namespace('my_fancy_pum') + + vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...) + if event == "popupmenu_show" then + local items, selected, row, col, grid = ... + print("display pum ", #items) + elseif event == "popupmenu_select" then + local selected = ... + print("selected", selected) + elseif event == "popupmenu_hide" then + print("FIN") + end + end) + +vim.ui_detach({ns}) *vim.ui_detach()* + Detach a callback previously attached with |vim.ui_attach()| for the + given namespace {ns}. + 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 unclear whether empty Lua @@ -959,7 +957,7 @@ vim.type_idx *vim.type_idx* vim.val_idx *vim.val_idx* Value index for tables representing |Float|s. A table representing - floating-point value 1.0 looks like this: > + floating-point value 1.0 looks like this: >lua { [vim.type_idx] = vim.types.float, [vim.val_idx] = 1.0, @@ -1000,12 +998,13 @@ LUA-VIMSCRIPT BRIDGE *lua-vimscript* Nvim Lua provides an interface to Vimscript variables and functions, and editor commands and options. + See also https://github.com/nanotee/nvim-lua-guide. vim.call({func}, {...}) *vim.call()* Invokes |vim-function| or |user-function| {func} with arguments {...}. See also |vim.fn|. - Equivalent to: > + Equivalent to: >lua vim.fn[func]({...}) vim.cmd({command}) @@ -1013,7 +1012,7 @@ vim.cmd({command}) vim.fn.{func}({...}) *vim.fn* Invokes |vim-function| or |user-function| {func} with arguments {...}. - To call autoload functions, use the syntax: > + To call autoload functions, use the syntax: >lua vim.fn['some#function']({...}) < Unlike vim.api.|nvim_call_function()| this converts directly between Vim @@ -1036,13 +1035,27 @@ 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. -Example: > +Example: >lua 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.b[2].foo = 6 -- Set b:foo for buffer 2 < + +Note that setting dictionary fields directly will not write them back into +Nvim. This is because the index into the namespace simply returns a copy. +Instead the whole dictionary must be written as one. This can be achieved by +creating a short-lived temporary. + +Example: >lua + + vim.g.my_dict.field1 = 'value' -- Does not work + + local my_dict = vim.g.my_dict -- + my_dict.field1 = 'value' -- Instead do + vim.g.my_dict = my_dict -- + vim.g *vim.g* Global (|g:|) editor variables. Key with no value returns `nil`. @@ -1070,86 +1083,153 @@ 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: > + Example: >lua vim.env.FOO = 'bar' print(vim.env.TERM) < + *lua-options* *lua-vim-options* - *lua-vim-opt* *lua-vim-set* - *lua-vim-optlocal* *lua-vim-setlocal* -In Vimscript, there is a way to set options |set-option|. In Lua, the -corresponding method is `vim.opt`. - -`vim.opt` provides several conveniences for setting and controlling options -from within Lua. +Vim options can be accessed through |vim.o|, which behaves like Vimscript +|:set|. Examples: ~ To set a boolean toggle: - In Vimscript: - `set number` + Vimscript: `set number` + Lua: `vim.o.number = true` - In Lua: - `vim.opt.number = true` + To set a string value: + Vimscript: `set wildignore=*.o,*.a,__pycache__` + Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'` - To set an array of values: - In Vimscript: - `set wildignore=*.o,*.a,__pycache__` +Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and +window-scoped options. Note that this must NOT be confused with +|local-options| and |:setlocal|. There is also |vim.go| that only accesses the +global value of a |global-local| option, see |:setglobal|. - In Lua, there are two ways you can do this now. One is very similar to - the Vimscript form: - `vim.opt.wildignore = '*.o,*.a,__pycache__'` +vim.o *vim.o* + Get or set |options|. Like `:set`. Invalid key is an error. - However, vim.opt also supports a more elegent way of setting - list-style options by using lua tables: - `vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }` + Note: this works on both buffer-scoped and window-scoped options using the + current buffer and window. - To replicate the behavior of |:set+=|, use: > + Example: >lua + vim.o.cmdheight = 4 + print(vim.o.columns) + print(vim.o.foo) -- error: invalid key +< +vim.go *vim.go* + Get or set global |options|. Like `:setglobal`. Invalid key is + an error. - -- vim.opt supports appending options via the "+" operator - vim.opt.wildignore = vim.opt.wildignore + { "*.pyc", "node_modules" } + Note: this is different from |vim.o| because this accesses the global + option value and thus is mostly useful for use with |global-local| + options. - -- or using the `:append(...)` method - vim.opt.wildignore:append { "*.pyc", "node_modules" } + Example: >lua + vim.go.cmdheight = 4 + print(vim.go.columns) + print(vim.go.bar) -- error: invalid key < - To replicate the behavior of |:set^=|, use: > +vim.bo[{bufnr}] *vim.bo* + Get or set buffer-scoped |options| for the buffer with number {bufnr}. + Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current + buffer is used. Invalid {bufnr} or key is an error. - -- vim.opt supports prepending options via the "^" operator - vim.opt.wildignore = vim.opt.wildignore ^ { "new_first_value" } + Note: this is equivalent to both `:set` and `:setlocal`. - -- or using the `:prepend(...)` method - vim.opt.wildignore:prepend { "new_first_value" } + Example: >lua + local bufnr = vim.api.nvim_get_current_buf() + vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true + print(vim.bo.comments) + print(vim.bo.baz) -- error: invalid key < - To replicate the behavior of |:set-=|, use: > +vim.wo[{winid}] *vim.wo* + Get or set window-scoped |options| for the window with handle {winid}. + Like `:set`. If [{winid}] is omitted then the current window is used. + Invalid {winid} or key is an error. - -- vim.opt supports removing options via the "-" operator - vim.opt.wildignore = vim.opt.wildignore - { "node_modules" } + Note: this does not access |local-options| (`:setlocal`) instead use: >lua + nvim_get_option_value(OPTION, { scope = 'local', win = winid }) + nvim_set_option_value(OPTION, VALUE, { scope = 'local', win = winid } +< + Example: >lua + local winid = vim.api.nvim_get_current_win() + vim.wo[winid].number = true -- same as vim.wo.number = true + print(vim.wo.foldmarker) + print(vim.wo.quux) -- error: invalid key +< - -- or using the `:remove(...)` method - vim.opt.wildignore:remove { "node_modules" } + + + *vim.opt_local* + *vim.opt_global* + *vim.opt* + + +A special interface |vim.opt| exists for conveniently interacting with list- +and map-style option from Lua: It allows accessing them as Lua tables and +offers object-oriented method for adding and removing entries. + + Examples: ~ + + The following methods of setting a list-style option are equivalent: + In Vimscript: >vim + set wildignore=*.o,*.a,__pycache__ +< + In Lua using `vim.o`: >lua + vim.o.wildignore = '*.o,*.a,__pycache__' +< + In Lua using `vim.opt`: >lua + vim.opt.wildignore = { '*.o', '*.a', '__pycache__' } +< + To replicate the behavior of |:set+=|, use: >lua + + vim.opt.wildignore:append { "*.pyc", "node_modules" } < - To set a map of values: - In Vimscript: - `set listchars=space:_,tab:>~` + To replicate the behavior of |:set^=|, use: >lua - In Lua: - `vim.opt.listchars = { space = '_', tab = '>~' }` + vim.opt.wildignore:prepend { "new_first_value" } +< + To replicate the behavior of |:set-=|, use: >lua + vim.opt.wildignore:remove { "node_modules" } +< + The following methods of setting a map-style option are equivalent: + In Vimscript: >vim + set listchars=space:_,tab:>~ +< + In Lua using `vim.o`: >lua + vim.o.listchars = 'space:_,tab:>~' +< + In Lua using `vim.opt`: >lua + vim.opt.listchars = { space = '_', tab = '>~' } +< -In any of the above examples, to replicate the behavior |setlocal|, use -`vim.opt_local`. Additionally, to replicate the behavior of |setglobal|, use -`vim.opt_global`. - *vim.opt* +Note that |vim.opt| returns an `Option` object, not the value of the option, +which is accessed through |vim.opt:get()|: -|vim.opt| returns an Option object. + Examples: ~ -For example: `local listchar_object = vim.opt.listchars` + The following methods of getting a list-style option are equivalent: + In Vimscript: >vim + echo wildignore +< + In Lua using `vim.o`: >lua + print(vim.o.wildignore) +< + In Lua using `vim.opt`: >lua + vim.pretty_print(vim.opt.wildignore:get()) +< + +In any of the above examples, to replicate the behavior |:setlocal|, use +`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use +`vim.opt_global`. -An `Option` has the following methods: *vim.opt:get()* @@ -1159,10 +1239,10 @@ Option:get() values will be returned in exactly the same fashion. For values that are comma-separated lists, an array will be returned with - the values as entries in the array: > + the values as entries in the array: >lua vim.cmd [[set wildignore=*.pyc,*.o]] - print(vim.inspect(vim.opt.wildignore:get())) + vim.pretty_print(vim.opt.wildignore:get()) -- { "*.pyc", "*.o", } for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do @@ -1172,21 +1252,21 @@ Option:get() -- Will ignore: *.o < For values that are comma-separated maps, a table will be returned with - the names as keys and the values as entries: > + the names as keys and the values as entries: >lua vim.cmd [[set listchars=space:_,tab:>~]] - print(vim.inspect(vim.opt.listchars:get())) + vim.pretty_print(vim.opt.listchars:get()) -- { space = "_", tab = ">~", } for char, representation in pairs(vim.opt.listchars:get()) do - print(char, "->", representation) + print(char, "=>", representation) end < For values that are lists of flags, a set will be returned with the flags - as keys and `true` as entries. > + as keys and `true` as entries. >lua vim.cmd [[set formatoptions=njtcroql]] - print(vim.inspect(vim.opt.formatoptions:get())) + vim.pretty_print(vim.opt.formatoptions:get()) -- { n = true, j = true, c = true, ... } local format_opts = vim.opt.formatoptions:get() @@ -1199,94 +1279,29 @@ Option:append(value) Append a value to string-style options. See |:set+=| - These are equivalent: - `vim.opt.formatoptions:append('j')` - `vim.opt.formatoptions = vim.opt.formatoptions + 'j'` - + These are equivalent: >lua + vim.opt.formatoptions:append('j') + vim.opt.formatoptions = vim.opt.formatoptions + 'j' +< *vim.opt:prepend()* Option:prepend(value) Prepend a value to string-style options. See |:set^=| - These are equivalent: - `vim.opt.wildignore:prepend('*.o')` - `vim.opt.wildignore = vim.opt.wildignore ^ '*.o'` - + These are equivalent: >lua + vim.opt.wildignore:prepend('*.o') + vim.opt.wildignore = vim.opt.wildignore ^ '*.o' +< *vim.opt:remove()* Option:remove(value) Remove a value from string-style options. See |:set-=| - These are equivalent: - `vim.opt.wildignore:remove('*.pyc')` - `vim.opt.wildignore = vim.opt.wildignore - '*.pyc'` - - -In general, using `vim.opt` will provide the expected result when the user is -used to interacting with editor |options| via `set`. There are still times -where the user may want to set particular options via a shorthand in Lua, -which is where |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| come into play. - -The behavior of |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| is designed to -follow that of |:set|, |:setlocal|, and |:setglobal| which can be seen in the -table below: - - lua command global_value local_value ~ -vim.o :set set set -vim.bo/vim.wo :setlocal - set -vim.go :setglobal set - - -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) - print(vim.o.foo) -- error: invalid key -< -vim.go *vim.go* - Get or set an |option|. Invalid key is an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()|. - - NOTE: This is different from |vim.o| because this ONLY sets the global - option, which generally produces confusing behavior for options with - |global-local| values. - - Example: > - vim.go.cmdheight = 4 - print(vim.go.columns) - print(vim.go.bar) -- error: invalid key -< -vim.bo[{bufnr}] *vim.bo* - Get or set buffer-scoped |local-options| for the buffer with number {bufnr}. - If [{bufnr}] is omitted, use the current buffer. Invalid {bufnr} or key is - an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()| with `opts = {scope = local, buf = bufnr}` . - - Example: > - local bufnr = vim.api.nvim_get_current_buf() - vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true - print(vim.bo.comments) - print(vim.bo.baz) -- error: invalid key + These are equivalent: >lua + vim.opt.wildignore:remove('*.pyc') + vim.opt.wildignore = vim.opt.wildignore - '*.pyc' < -vim.wo[{winid}] *vim.wo* - Get or set window-scoped |local-options| for the window with handle {winid}. - If [{winid}] is omitted, use the current window. Invalid {winid} or key - is an error. - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()| with `opts = {scope = local, win = winid}` . - - Example: > - local winid = vim.api.nvim_get_current_win() - vim.wo[winid].number = true -- same as vim.wo.number = true - print(vim.wo.foldmarker) - print(vim.wo.quux) -- error: invalid key -< ============================================================================== Lua module: vim *lua-vim* @@ -1296,7 +1311,7 @@ cmd({command}) *vim.cmd()* Note that `vim.cmd` can be indexed with a command name to return a callable function to the command. - Example: > + Example: >lua vim.cmd('echo 42') vim.cmd([[ @@ -1325,7 +1340,7 @@ cmd({command}) *vim.cmd()* < Parameters: ~ - {command} string|table Command(s) to execute. If a string, executes + • {command} string|table Command(s) to execute. If a string, executes multiple lines of Vim script at once. In this case, it is an alias to |nvim_exec()|, where `output` is set to false. Thus it works identical to |:source|. If a table, executes @@ -1342,31 +1357,31 @@ connection_failure_errmsg({consequence}) defer_fn({fn}, {timeout}) *vim.defer_fn()* Defers calling `fn` until `timeout` ms passes. - Use to do a one-shot timer that calls `fn` Note: The {fn} is |schedule_wrap|ped automatically, so API functions are - safe to call. + Use to do a one-shot timer that calls `fn` Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions + are safe to call. Parameters: ~ - {fn} Callback to call once `timeout` expires - {timeout} Number of milliseconds to wait before calling `fn` + • {fn} (function) Callback to call once `timeout` expires + • {timeout} integer Number of milliseconds to wait before calling `fn` Return: ~ - timer luv timer object + (table) timer luv timer object *vim.deprecate()* deprecate({name}, {alternative}, {version}, {plugin}, {backtrace}) Display a deprecation notification to the user. Parameters: ~ - {name} string Deprecated function. - {alternative} (string|nil) Preferred alternative function. - {version} string Version in which the deprecated function will be + • {name} string Deprecated function. + • {alternative} (string|nil) Preferred alternative function. + • {version} string Version in which the deprecated function will be removed. - {plugin} string|nil Plugin name that the function will be + • {plugin} string|nil Plugin name that the function will be removed from. Defaults to "Nvim". - {backtrace} boolean|nil Prints backtrace. Defaults to true. + • {backtrace} boolean|nil Prints backtrace. Defaults to true. inspect({object}, {options}) *vim.inspect()* - Return a human-readable representation of the given object. + Gets a human-readable representation of the given object. See also: ~ https://github.com/kikito/inspect.lua @@ -1380,9 +1395,9 @@ notify({msg}, {level}, {opts}) *vim.notify()* writes to |:messages|. Parameters: ~ - {msg} (string) Content of the notification to show to the user. - {level} (number|nil) One of the values from |vim.log.levels|. - {opts} (table|nil) Optional parameters. Unused by default. + • {msg} (string) Content of the notification to show to the user. + • {level} (number|nil) One of the values from |vim.log.levels|. + • {opts} (table|nil) Optional parameters. Unused by default. notify_once({msg}, {level}, {opts}) *vim.notify_once()* Display a notification only one time. @@ -1391,9 +1406,9 @@ notify_once({msg}, {level}, {opts}) *vim.notify_once()* display a notification. Parameters: ~ - {msg} (string) Content of the notification to show to the user. - {level} (number|nil) One of the values from |vim.log.levels|. - {opts} (table|nil) Optional parameters. Unused by default. + • {msg} (string) Content of the notification to show to the user. + • {level} (number|nil) One of the values from |vim.log.levels|. + • {opts} (table|nil) Optional parameters. Unused by default. Return: ~ (boolean) true if message was displayed, else false @@ -1412,11 +1427,11 @@ on_key({fn}, {ns_id}) *vim.on_key()* {fn} will receive the keys after mappings have been evaluated Parameters: ~ - {fn} function: Callback function. It should take one string + • {fn} (function) Callback function. It should take one string argument. On each key press, Nvim passes the key char to fn(). |i_CTRL-V| If {fn} is nil, it removes the callback for the associated {ns_id} - {ns_id} number? Namespace ID. If nil or 0, generates and returns a + • {ns_id} number? Namespace ID. If nil or 0, generates and returns a new |nvim_create_namespace()| id. Return: ~ @@ -1430,7 +1445,7 @@ paste({lines}, {phase}) *vim.paste()* Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the |TUI|) pastes text into the editor. - Example: To remove ANSI color codes when pasting: > + Example: To remove ANSI color codes when pasting: >lua vim.paste = (function(overridden) return function(lines, phase) @@ -1444,27 +1459,28 @@ paste({lines}, {phase}) *vim.paste()* < Parameters: ~ - {lines} |readfile()|-style list of lines to paste. |channel-lines| - {phase} -1: "non-streaming" paste: the call contains all lines. If - paste is "streamed", `phase` indicates the stream state: + • {lines} string[] # |readfile()|-style list of lines to paste. + |channel-lines| + • {phase} paste_phase -1: "non-streaming" paste: the call contains all + lines. If paste is "streamed", `phase` indicates the stream state: • 1: starts the paste (exactly once) • 2: continues the paste (zero or more times) • 3: ends the paste (exactly once) Return: ~ - false if client should cancel the paste. + (boolean) # false if client should cancel the paste. See also: ~ - |paste| + |paste| @alias paste_phase -1 | 1 | 2 | 3 pretty_print({...}) *vim.pretty_print()* - Prints given arguments in human-readable format. Example: > + Prints given arguments in human-readable format. Example: >lua -- Print highlight group Normal and store it's contents in a variable. local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true)) < Return: ~ - given arguments. + any # given arguments. See also: ~ |vim.inspect()| @@ -1474,25 +1490,82 @@ region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()* points Parameters: ~ - {bufnr} (number) of buffer - {pos1} (line, column) tuple marking beginning of region - {pos2} (line, column) tuple marking end of region - {regtype} type of selection (:help setreg) - {inclusive} (boolean) indicating whether the selection is + • {bufnr} (number) of buffer + • {pos1} integer[] (line, column) tuple marking beginning of + region + • {pos2} integer[] (line, column) tuple marking end of region + • {regtype} (string) type of selection, see |setreg()| + • {inclusive} (boolean) indicating whether the selection is end-inclusive Return: ~ - region lua table of the form {linenr = {startcol,endcol}} + (table) region Table of the form `{linenr = {startcol,endcol}}` schedule_wrap({cb}) *vim.schedule_wrap()* Defers callback `cb` until the Nvim API is safe to call. + Parameters: ~ + • {cb} (function) + + Return: ~ + (function) + See also: ~ |lua-loop-callbacks| |vim.schedule()| |vim.in_fast_event()| +============================================================================== +Lua module: inspector *lua-inspector* + +inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()* + Get all the items at a given buffer position. + + Can also be pretty-printed with `:Inspect!`. *:Inspect!* + + Parameters: ~ + • {bufnr} (number|nil) defaults to the current buffer + • {row} (number|nil) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (number|nil) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (table|nil) a table with key-value pairs to filter the items + • syntax (boolean): include syntax based highlight groups + (defaults to true) + • treesitter (boolean): include treesitter based highlight + groups (defaults to true) + • extmarks (boolean|"all"): include extmarks. When `all`, + then extmarks without a `hl_group` will also be included + (defaults to true) + • semantic_tokens (boolean): include semantic tokens + (defaults to true) + + Return: ~ + (table) a table with the following key-value pairs. Items are in + "traversal order": + • treesitter: a list of treesitter captures + • syntax: a list of syntax groups + • semantic_tokens: a list of semantic tokens + • extmarks: a list of extmarks + • buffer: the buffer used to get the items + • row: the row used to get the items + • col: the col used to get the items + +show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()* + Show all the items at a given buffer position. + + Can also be shown with `:Inspect`. *:Inspect* + + Parameters: ~ + • {bufnr} (number|nil) defaults to the current buffer + • {row} (number|nil) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (number|nil) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (table|nil) see |vim.inspect_pos()| + + deep_equal({a}, {b}) *vim.deep_equal()* @@ -1501,8 +1574,8 @@ deep_equal({a}, {b}) *vim.deep_equal()* Tables are compared recursively unless they both provide the `eq` metamethod. All other types are compared using the equality `==` operator. Parameters: ~ - {a} any First value - {b} any Second value + • {a} any First value + • {b} any Second value Return: ~ (boolean) `true` if values are equals, else `false` @@ -1515,17 +1588,40 @@ deepcopy({orig}) *vim.deepcopy()* not copied and will throw an error. Parameters: ~ - {orig} (table) Table to copy + • {orig} (table) Table to copy Return: ~ (table) Table of copied keys and (nested) values. +defaulttable({create}) *vim.defaulttable()* + Creates a table whose members are automatically created when accessed, if + they don't already exist. + + They mimic defaultdict in python. + + If {create} is `nil`, this will create a defaulttable whose constructor + function is this function, effectively allowing to create nested tables on + the fly: + + >lua + + local a = vim.defaulttable() + a.b.c = 1 +< + + Parameters: ~ + • {create} (function|nil) The function called to create a missing + value. + + Return: ~ + (table) Empty table with metamethod + endswith({s}, {suffix}) *vim.endswith()* Tests if `s` ends with `suffix`. Parameters: ~ - {s} (string) String - {suffix} (string) Suffix to match + • {s} (string) String + • {suffix} (string) Suffix to match Return: ~ (boolean) `true` if `suffix` is a suffix of `s` @@ -1534,9 +1630,9 @@ gsplit({s}, {sep}, {plain}) *vim.gsplit()* Splits a string at each instance of a separator. Parameters: ~ - {s} (string) String to split - {sep} (string) Separator or pattern - {plain} (boolean) If `true` use `sep` literally (passed to + • {s} (string) String to split + • {sep} (string) Separator or pattern + • {plain} (boolean|nil) If `true` use `sep` literally (passed to string.find) Return: ~ @@ -1544,6 +1640,7 @@ gsplit({s}, {sep}, {plain}) *vim.gsplit()* See also: ~ |vim.split()| + |luaref-patterns| https://www.lua.org/pil/20.2.html http://lua-users.org/wiki/StringLibraryTutorial @@ -1551,7 +1648,7 @@ is_callable({f}) *vim.is_callable()* Returns true if object `f` can be called as a function. Parameters: ~ - {f} any Any object + • {f} any Any object Return: ~ (boolean) `true` if `f` is callable, else `false` @@ -1562,10 +1659,10 @@ list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()* NOTE: This mutates dst! Parameters: ~ - {dst} (table) List which will be modified and appended to - {src} (table) List from which values will be inserted - {start} (number) Start index on src. Defaults to 1 - {finish} (number) Final index on src. Defaults to `#src` + • {dst} (table) List which will be modified and appended to + • {src} (table) List from which values will be inserted + • {start} (number|nil) Start index on src. Defaults to 1 + • {finish} (number|nil) Final index on src. Defaults to `#src` Return: ~ (table) dst @@ -1578,18 +1675,18 @@ list_slice({list}, {start}, {finish}) *vim.list_slice()* (inclusive) Parameters: ~ - {list} (table) Table - {start} (number) Start range of slice - {finish} (number) End range of slice + • {list} (list) Table + • {start} (number|nil) Start range of slice + • {finish} (number|nil) End range of slice Return: ~ - (table) Copy of table sliced from start to finish (inclusive) + (list) Copy of table sliced from start to finish (inclusive) pesc({s}) *vim.pesc()* Escapes magic chars in |lua-patterns|. Parameters: ~ - {s} (string) String to escape + • {s} (string) String to escape Return: ~ (string) %-escaped pattern string @@ -1597,28 +1694,40 @@ pesc({s}) *vim.pesc()* See also: ~ https://github.com/rxi/lume +spairs({t}) *vim.spairs()* + Enumerate a table sorted by its keys. + + Parameters: ~ + • {t} (table) List-like table + + Return: ~ + iterator over sorted keys and their values + + See also: ~ + Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua + split({s}, {sep}, {kwargs}) *vim.split()* Splits a string at each instance of a separator. - Examples: > + Examples: >lua - split(":aa::b:", ":") --> {'','aa','','b',''} - split("axaby", "ab?") --> {'','x','y'} - split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} + split(":aa::b:", ":") --> {'','aa','','b',''} + split("axaby", "ab?") --> {'','x','y'} + split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} < Parameters: ~ - {s} (string) String to split - {sep} (string) Separator or pattern - {kwargs} (table) Keyword arguments: + • {s} (string) String to split + • {sep} (string) Separator or pattern + • {kwargs} (table|nil) Keyword arguments: • plain: (boolean) If `true` use `sep` literally (passed to string.find) • trimempty: (boolean) If `true` remove empty items from the front and back of the list Return: ~ - (table) List of split components + string[] List of split components See also: ~ |vim.gsplit()| @@ -1627,8 +1736,8 @@ startswith({s}, {prefix}) *vim.startswith()* Tests if `s` starts with `prefix`. Parameters: ~ - {s} (string) String - {prefix} (string) Prefix to match + • {s} (string) String + • {prefix} (string) Prefix to match Return: ~ (boolean) `true` if `prefix` is a prefix of `s` @@ -1640,7 +1749,7 @@ tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()* Note that this modifies the input. Parameters: ~ - {o} (table) Table to add the reverse to + • {o} (table) Table to add the reverse to Return: ~ (table) o @@ -1649,22 +1758,23 @@ tbl_contains({t}, {value}) *vim.tbl_contains()* Checks if a list-like (vector) table contains `value`. Parameters: ~ - {t} (table) Table to check - {value} any Value to compare + • {t} (table) Table to check + • {value} any Value to compare Return: ~ (boolean) `true` if `t` contains `value` tbl_count({t}) *vim.tbl_count()* Counts the number of non-nil values in table `t`. -> - vim.tbl_count({ a=1, b=2 }) => 2 - vim.tbl_count({ 1, 2 }) => 2 + >lua + + vim.tbl_count({ a=1, b=2 }) --> 2 + vim.tbl_count({ 1, 2 }) --> 2 < Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ (number) Number of non-nil values in table @@ -1676,29 +1786,29 @@ tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()* Merges recursively two or more map-like tables. Parameters: ~ - {behavior} (string) Decides what to do if a key is found in more than + • {behavior} (string) Decides what to do if a key is found in more than one map: • "error": raise an error • "keep": use value from the leftmost map • "force": use value from the rightmost map - {...} (table) Two or more map-like tables + • {...} (table) Two or more map-like tables Return: ~ (table) Merged table See also: ~ - |tbl_extend()| + |vim.tbl_extend()| tbl_extend({behavior}, {...}) *vim.tbl_extend()* Merges two or more map-like tables. Parameters: ~ - {behavior} (string) Decides what to do if a key is found in more than + • {behavior} (string) Decides what to do if a key is found in more than one map: • "error": raise an error • "keep": use value from the leftmost map • "force": use value from the rightmost map - {...} (table) Two or more map-like tables + • {...} (table) Two or more map-like tables Return: ~ (table) Merged table @@ -1710,8 +1820,8 @@ tbl_filter({func}, {t}) *vim.tbl_filter()* Filter a table using a predicate function Parameters: ~ - {func} function|table Function or callable table - {t} (table) Table + • {func} (function) Function + • {t} (table) Table Return: ~ (table) Table of filtered values @@ -1721,7 +1831,7 @@ tbl_flatten({t}) *vim.tbl_flatten()* "unrolled" and appended to the result. Parameters: ~ - {t} (table) List-like table + • {t} (table) List-like table Return: ~ (table) Flattened copy of the given list-like table @@ -1733,15 +1843,15 @@ tbl_get({o}, {...}) *vim.tbl_get()* Index into a table (first argument) via string keys passed as subsequent arguments. Return `nil` if the key does not exist. - Examples: > + Examples: >lua vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil < Parameters: ~ - {o} (table) Table to index - {...} (string) Optional strings (0 or more, variadic) via which to + • {o} (table) Table to index + • {...} (string) Optional strings (0 or more, variadic) via which to index the table Return: ~ @@ -1751,7 +1861,7 @@ tbl_isempty({t}) *vim.tbl_isempty()* Checks if a table is empty. Parameters: ~ - {t} (table) Table to check + • {t} (table) Table to check Return: ~ (boolean) `true` if `t` is empty @@ -1767,7 +1877,7 @@ tbl_islist({t}) *vim.tbl_islist()* for example from |rpcrequest()| or |vim.fn|. Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ (boolean) `true` if array-like table, else `false` @@ -1777,10 +1887,10 @@ tbl_keys({t}) *vim.tbl_keys()* return table of keys is not guaranteed. Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ - (table) List of keys + (list) List of keys See also: ~ From https://github.com/premake/premake-core/blob/master/src/base/table.lua @@ -1789,8 +1899,8 @@ tbl_map({func}, {t}) *vim.tbl_map()* Apply a function to all values of a table. Parameters: ~ - {func} function|table Function or callable table - {t} (table) Table + • {func} (function) Function + • {t} (table) Table Return: ~ (table) Table of transformed values @@ -1800,27 +1910,28 @@ tbl_values({t}) *vim.tbl_values()* return table of values is not guaranteed. Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ - (table) List of values + (list) List of values trim({s}) *vim.trim()* Trim whitespace (Lua pattern "%s") from both sides of a string. Parameters: ~ - {s} (string) String to trim + • {s} (string) String to trim Return: ~ (string) String with whitespace removed from its beginning and end See also: ~ + |luaref-patterns| https://www.lua.org/pil/20.2.html validate({opt}) *vim.validate()* Validates a parameter specification (types and values). - Usage example: > + Usage example: >lua function user.new(name, age, hobbies) vim.validate{ @@ -1832,29 +1943,29 @@ validate({opt}) *vim.validate()* end < - Examples with explicit argument values (can be run directly): > + Examples with explicit argument values (can be run directly): >lua vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} - => NOP (success) + --> NOP (success) vim.validate{arg1={1, 'table'}} - => error('arg1: expected table, got number') + --> error('arg1: expected table, got number') vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} - => error('arg1: expected even number, got 3') + --> error('arg1: expected even number, got 3') < - If multiple types are valid they can be given as a list. > + If multiple types are valid they can be given as a list. >lua vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} - => NOP (success) + --> NOP (success) vim.validate{arg1={1, {'string', table'}}} - => error('arg1: expected string|table, got number') + --> error('arg1: expected string|table, got number') < Parameters: ~ - {opt} (table) Names of parameters to validate. Each key is a + • {opt} (table) Names of parameters to validate. Each key is a parameter name; each value is a tuple in one of these forms: 1. (arg_value, type_name, optional) • arg_value: argument value @@ -1879,7 +1990,7 @@ uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()* Get a URI from a bufnr Parameters: ~ - {bufnr} (number) + • {bufnr} (number) Return: ~ (string) URI @@ -1888,7 +1999,7 @@ uri_from_fname({path}) *vim.uri_from_fname()* Get a URI from a file path. Parameters: ~ - {path} (string) Path to file + • {path} (string) Path to file Return: ~ (string) URI @@ -1898,7 +2009,7 @@ uri_to_bufnr({uri}) *vim.uri_to_bufnr()* the uri already exists. Parameters: ~ - {uri} (string) + • {uri} (string) Return: ~ (number) bufnr @@ -1907,7 +2018,7 @@ uri_to_fname({uri}) *vim.uri_to_fname()* Get a filename from a URI Parameters: ~ - {uri} (string) + • {uri} (string) Return: ~ (string) filename or unchanged URI for non-file URIs @@ -1919,7 +2030,7 @@ Lua module: ui *lua-ui* input({opts}, {on_confirm}) *vim.ui.input()* Prompts the user for input - Example: > + Example: >lua vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) vim.o.shiftwidth = tonumber(input) @@ -1927,7 +2038,7 @@ input({opts}, {on_confirm}) *vim.ui.input()* < Parameters: ~ - {opts} (table) Additional options. See |input()| + • {opts} (table) Additional options. See |input()| • prompt (string|nil) Text of the prompt • default (string|nil) Default reply to the input • completion (string|nil) Specifies type of completion @@ -1936,14 +2047,15 @@ input({opts}, {on_confirm}) *vim.ui.input()* "-complete=" argument. See |:command-completion| • highlight (function) Function that will be used for highlighting user inputs. - {on_confirm} (function) ((input|nil) -> ()) Called once the user + • {on_confirm} (function) ((input|nil) -> ()) Called once the user confirms or abort the input. `input` is what the user - typed. `nil` if the user aborted the dialog. + typed (it might be an empty string if nothing was + entered), or `nil` if the user aborted the dialog. select({items}, {opts}, {on_choice}) *vim.ui.select()* Prompts the user to pick a single item from a collection of entries - Example: > + Example: >lua vim.ui.select({ 'tabs', 'spaces' }, { prompt = 'Select tabs or spaces:', @@ -1960,8 +2072,8 @@ select({items}, {opts}, {on_choice}) *vim.ui.select()* < Parameters: ~ - {items} (table) Arbitrary items - {opts} (table) Additional options + • {items} (table) Arbitrary items + • {opts} (table) Additional options • prompt (string|nil) Text of the prompt. Defaults to `Select one of:` • format_item (function item -> text) Function to format @@ -1971,7 +2083,7 @@ select({items}, {opts}, {on_choice}) *vim.ui.select()* item shape. Plugins reimplementing `vim.ui.select` may wish to use this to infer the structure or semantics of `items`, or the context in which select() was called. - {on_choice} (function) ((item|nil, idx|nil) -> ()) Called once the + • {on_choice} (function) ((item|nil, idx|nil) -> ()) Called once the user made a choice. `idx` is the 1-based index of `item` within `items`. `nil` if the user aborted the dialog. @@ -1999,14 +2111,14 @@ add({filetypes}) *vim.filetype.add()* Filename patterns can specify an optional priority to resolve cases when a file path matches multiple patterns. Higher priorities are matched first. - When omitted, the priority defaults to 0. + When omitted, the priority defaults to 0. A pattern can contain + environment variables of the form "${SOME_VAR}" that will be automatically + expanded. If the environment variable is not set, the pattern won't be + matched. See $VIMRUNTIME/lua/vim/filetype.lua for more examples. - Note that Lua filetype detection is disabled when |g:do_legacy_filetype| - is set. - - Example: > + Example: >lua vim.filetype.add({ extension = { @@ -2029,6 +2141,8 @@ add({filetypes}) *vim.filetype.add()* ['.*/etc/foo/.*'] = 'fooscript', -- Using an optional priority ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, + -- A pattern containing an environment variable + ['${XDG_CONFIG_HOME}/foo/git'] = 'git', ['README.(a+)$'] = function(path, bufnr, ext) if ext == 'md' then return 'markdown' @@ -2040,7 +2154,7 @@ add({filetypes}) *vim.filetype.add()* }) < - To add a fallback match on contents (see |new-filetype-scripts|), use > + To add a fallback match on contents, use >lua vim.filetype.add { pattern = { @@ -2060,7 +2174,7 @@ add({filetypes}) *vim.filetype.add()* < Parameters: ~ - {filetypes} (table) A table containing new filetype maps (see + • {filetypes} (table) A table containing new filetype maps (see example). match({args}) *vim.filetype.match()* @@ -2079,23 +2193,24 @@ match({args}) *vim.filetype.match()* Each of the three options is specified using a key to the single argument of this function. Example: -> - -- Using a buffer number - vim.filetype.match({ buf = 42 }) + >lua + + -- Using a buffer number + vim.filetype.match({ buf = 42 }) - -- Override the filename of the given buffer - vim.filetype.match({ buf = 42, filename = 'foo.c' }) + -- Override the filename of the given buffer + vim.filetype.match({ buf = 42, filename = 'foo.c' }) - -- Using a filename without a buffer - vim.filetype.match({ filename = 'main.lua' }) + -- Using a filename without a buffer + vim.filetype.match({ filename = 'main.lua' }) - -- Using file contents - vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) + -- Using file contents + vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) < Parameters: ~ - {args} (table) Table specifying which matching strategy to use. + • {args} (table) Table specifying which matching strategy to use. Accepted keys are: • buf (number): Buffer number to use for matching. Mutually exclusive with {contents} @@ -2121,7 +2236,7 @@ match({args}) *vim.filetype.match()* Lua module: keymap *lua-keymap* del({modes}, {lhs}, {opts}) *vim.keymap.del()* - Remove an existing mapping. Examples: > + Remove an existing mapping. Examples: >lua vim.keymap.del('n', 'lhs') @@ -2129,7 +2244,7 @@ del({modes}, {lhs}, {opts}) *vim.keymap.del()* < Parameters: ~ - {opts} (table) A table of optional arguments: + • {opts} (table|nil) A table of optional arguments: • buffer: (number or boolean) Remove a mapping from the given buffer. When "true" or 0, use the current buffer. @@ -2137,7 +2252,7 @@ del({modes}, {lhs}, {opts}) *vim.keymap.del()* |vim.keymap.set()| set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* - Add a new |mapping|. Examples: > + Add a new |mapping|. Examples: >lua -- Can add mapping to Lua functions vim.keymap.set('n', 'lhs', function() print("real lua function") end) @@ -2156,25 +2271,25 @@ set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)') < - Note that in a mapping like: > + Note that in a mapping like: >lua vim.keymap.set('n', 'asdf', require('jkl').my_fun) < the `require('jkl')` gets evaluated during this call in order to access the function. If you want to avoid this cost at startup you can wrap it in a function, for - example: > + example: >lua vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end) < Parameters: ~ - {mode} string|table Same mode short names as |nvim_set_keymap()|. Can + • {mode} string|table Same mode short names as |nvim_set_keymap()|. Can also be list of modes to create mapping on multiple modes. - {lhs} (string) Left-hand side |{lhs}| of the mapping. - {rhs} string|function Right-hand side |{rhs}| of the mapping. Can + • {lhs} (string) Left-hand side |{lhs}| of the mapping. + • {rhs} string|function Right-hand side |{rhs}| of the mapping. Can also be a Lua function. - {opts} (table) A table of |:map-arguments|. + • {opts} (table|nil) A table of |:map-arguments|. • Accepts options accepted by the {opts} parameter in |nvim_set_keymap()|, with the following notable differences: • replace_keycodes: Defaults to `true` if "expr" is `true`. @@ -2200,18 +2315,23 @@ basename({file}) *vim.fs.basename()* Return the basename of the given file or directory Parameters: ~ - {file} (string) File or directory + • {file} (string) File or directory Return: ~ (string) Basename of {file} -dir({path}) *vim.fs.dir()* +dir({path}, {opts}) *vim.fs.dir()* Return an iterator over the files and directories located in {path} Parameters: ~ - {path} (string) An absolute or relative path to the directory to + • {path} (string) An absolute or relative path to the directory to iterate over. The path is first normalized |vim.fs.normalize()|. + • {opts} table|nil Optional keyword arguments: + • depth: integer|nil How deep the traverse (default 1) + • skip: (fun(dir_name: string): boolean)|nil Predicate to + control traversal. Return false to stop searching the + current directory. Only useful when depth > 1 Return: ~ Iterator over files and directories in {path}. Each iteration yields @@ -2222,7 +2342,7 @@ dirname({file}) *vim.fs.dirname()* Return the parent directory of the given file or directory Parameters: ~ - {file} (string) File or directory + • {file} (string) File or directory Return: ~ (string) Parent directory of {file} @@ -2236,15 +2356,18 @@ find({names}, {opts}) *vim.fs.find()* searches are recursive and may search through many directories! If {stop} is non-nil, then the search stops when the directory given in {stop} is reached. The search terminates when {limit} (default 1) matches are found. - The search can be narrowed to find only files or or only directories by + The search can be narrowed to find only files or only directories by specifying {type} to be "file" or "directory", respectively. Parameters: ~ - {names} (string|table) Names of the files and directories to find. - Must be base names, paths and globs are not supported. - {opts} (table) Optional keyword arguments: + • {names} (string|table|fun(name: string): boolean) Names of the files + and directories to find. Must be base names, paths and globs + are not supported. The function is called per file and + directory within the traversed directories to test if they + match {names}. + • {opts} (table) Optional keyword arguments: • path (string): Path to begin searching from. If omitted, - the current working directory is used. + the |current-directory| is used. • upward (boolean, default false): If true, search upward through parent directories. Otherwise, search through child directories (recursively). @@ -2252,13 +2375,14 @@ find({names}, {opts}) *vim.fs.find()* reached. The directory itself is not searched. • type (string): Find only files ("file") or directories ("directory"). If omitted, both files and directories that - match {name} are included. + match {names} are included. • limit (number, default 1): Stop the search after finding this many matches. Use `math.huge` to place no limit on the number of matches. Return: ~ - (table) The paths of all matching files or directories + (table) Normalized paths |vim.fs.normalize()| of all matching files or + directories normalize({path}) *vim.fs.normalize()* Normalize a path to a standard format. A tilde (~) character at the @@ -2266,20 +2390,20 @@ normalize({path}) *vim.fs.normalize()* backslash (\) characters are converted to forward slashes (/). Environment variables are also expanded. - Example: > + Examples: >lua - vim.fs.normalize('C:\Users\jdoe') - => 'C:/Users/jdoe' + vim.fs.normalize('C:\\Users\\jdoe') + --> 'C:/Users/jdoe' - vim.fs.normalize('~/src/neovim') - => '/home/jdoe/src/neovim' + vim.fs.normalize('~/src/neovim') + --> '/home/jdoe/src/neovim' - vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') - => '/Users/jdoe/.config/nvim/init.vim' + vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') + --> '/Users/jdoe/.config/nvim/init.vim' < Parameters: ~ - {path} (string) Path to normalize + • {path} (string) Path to normalize Return: ~ (string) Normalized path @@ -2287,7 +2411,7 @@ normalize({path}) *vim.fs.normalize()* parents({start}) *vim.fs.parents()* Iterate over all the parents of the given file or directory. - Example: > + Example: >lua local root_dir for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do @@ -2303,9 +2427,49 @@ parents({start}) *vim.fs.parents()* < Parameters: ~ - {start} (string) Initial file or directory. + • {start} (string) Initial file or directory. Return: ~ (function) Iterator + +============================================================================== +Lua module: secure *lua-secure* + +read({path}) *vim.secure.read()* + Attempt to read the file at {path} prompting the user if the file should + be trusted. The user's choice is persisted in a trust database at + $XDG_STATE_HOME/nvim/trust. + + Parameters: ~ + • {path} (string) Path to a file to read. + + Return: ~ + (string|nil) The contents of the given file if it exists and is + trusted, or nil otherwise. + + See also: ~ + |:trust| + +trust({opts}) *vim.secure.trust()* + Manage the trust database. + + The trust database is located at |$XDG_STATE_HOME|/nvim/trust. + + Parameters: ~ + • {opts} (table) + • action (string): "allow" to add a file to the trust database + and trust it, "deny" to add a file to the trust database and + deny it, "remove" to remove file from the trust database + • path (string|nil): Path to a file to update. Mutually + exclusive with {bufnr}. Cannot be used when {action} is + "allow". + • bufnr (number|nil): Buffer number to update. Mutually + exclusive with {path}. + + Return: ~ + (boolean, string) success, msg: + • true and full path of target file if operation was successful + • false and error message on failure + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/luaref.txt b/runtime/doc/luaref.txt index 9dbd2d4de5..aafdd5c43e 100644 --- a/runtime/doc/luaref.txt +++ b/runtime/doc/luaref.txt @@ -20,76 +20,10 @@ See |luaref-copyright| for copyright and licenses. - CONTENTS - ============ - - 1 INTRODUCTION........................|luaref-intro| - - 2 THE LANGUAGE........................|luaref-language| - 2.1 Lexical Conventions...............|luaref-langLexConv| - 2.2 Values and Types..................|luaref-langValTypes| - 2.2.1 Coercion........................|luaref-langCoercion| - 2.3 Variables.........................|luaref-langVariables| - 2.4 Statements........................|luaref-langStats| - 2.4.1 Chunks..........................|luaref-langChunks| - 2.4.2 Blocks..........................|luaref-langBlocks| - 2.4.3 Assignment......................|luaref-langAssign| - 2.4.4 Control Structures..............|luaref-langContStructs| - 2.4.5 For Statement...................|luaref-langForStat| - 2.4.6 Function Calls as Statements....|luaref-langFuncStat| - 2.4.7 Local Declarations..............|luaref-langLocalDec| - 2.5 Expressions.......................|luaref-langExpressions| - 2.5.1 Arithmetic Operators............|luaref-langArithOp| - 2.5.2 Relational Operators............|luaref-langRelOp| - 2.5.3 Logical Operators...............|luaref-langLogOp| - 2.5.4 Concatenation...................|luaref-langConcat| - 2.5.5 The Length Operator.............|luaref-langLength| - 2.5.6 Precedence......................|luaref-langPrec| - 2.5.7 Table Constructors..............|luaref-langTableConst| - 2.5.8 Function Calls..................|luaref-langFuncCalls| - 2.5.9 Function Definitions............|luaref-langFuncDefs| - 2.6 Visibility Rules..................|luaref-langVisibRules| - 2.7 Error Handling....................|luaref-langError| - 2.8 Metatables........................|luaref-langMetatables| - 2.9 Environments......................|luaref-langEnvironments| - 2.10 Garbage Collection...............|luaref-langGC| - 2.10.1 Garbage-Collection Metamethods.|luaref-langGCMeta| - 2.10.2 Weak Tables....................|luaref-langWeaktables| - 2.11 Coroutines.......................|luaref-langCoro| - - 3 THE APPLICATION PROGRAM INTERFACE...|luaref-api| - 3.1 The Stack.........................|luaref-apiStack| - 3.2 Stack Size........................|luaref-apiStackSize| - 3.3 Pseudo-Indices....................|luaref-apiPseudoIndices| - 3.4 C Closures........................|luaref-apiCClosures| - 3.5 Registry..........................|luaref-apiRegistry| - 3.6 Error Handling in C...............|luaref-apiError| - 3.7 Functions and Types...............|luaref-apiFunctions| - 3.8 The Debug Interface...............|luaref-apiDebug| - - 4 THE AUXILIARY LIBRARY...............|luaref-aux| - 4.1 Functions and Types...............|luaref-auxFunctions| - - 5 STANDARD LIBRARIES..................|luaref-lib| - 5.1 Basic Functions...................|luaref-libBasic| - 5.2 Coroutine Manipulation............|luaref-libCoro| - 5.3 Modules...........................|luaref-libModule| - 5.4 String Manipulation...............|luaref-libString| - 5.4.1 Patterns........................|luaref-libStringPat| - 5.5 Table Manipulation................|luaref-libTable| - 5.6 Mathematical Functions............|luaref-libMath| - 5.7 Input and Output Facilities.......|luaref-libIO| - 5.8 Operating System Facilities.......|luaref-libOS| - 5.9 The Debug Library.................|luaref-libDebug| - - A BIBLIOGRAPHY........................|luaref-bibliography| - B COPYRIGHT & LICENSES................|luaref-copyright| - C LUAREF DOC..........................|luaref-doc| - +Type |gO| to see the table of contents. ============================================================================== 1 INTRODUCTION *luaref-intro* -============================================================================== Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good @@ -120,14 +54,13 @@ Lua means "moon" in Portuguese and is pronounced LOO-ah. ============================================================================== 2 THE LANGUAGE *luaref-language* -============================================================================== This section describes the lexis, the syntax, and the semantics of Lua. In other words, this section describes which tokens are valid, how they can be combined, and what their combinations mean. The language constructs will be explained using the usual extended BNF -notation, in which { `a` } means 0 or more `a`'s, and [ `a` ] means an optional `a`. +notation, in which `{ a }` means 0 or more `a`'s, and `[ a ]` means an optional `a`. ============================================================================== 2.1 Lexical Conventions *luaref-langLexConv* @@ -203,7 +136,7 @@ For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string. As an example, in a system using ASCII (in which `a` is coded as 97, newline is coded as 10, and `1` is coded as 49), the five literals below denote the same string: -> +>lua a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' @@ -292,7 +225,7 @@ parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy. The library function `type` returns a string describing the type of a given -value (see |luaref-type|). +value (see |luaref-type()|). ------------------------------------------------------------------------------ 2.2.1 Coercion *luaref-langCoercion* @@ -303,7 +236,7 @@ string to a number, following the usual conversion rules. Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format. For complete control of how numbers are converted to strings, use the `format` function from the string library (see -|luaref-string.format|). +|string.format()|). ============================================================================== 2.3 Variables *luaref-langVariables* @@ -344,13 +277,13 @@ has its own reference to an environment, so that all global variables in this function will refer to this environment table. When a function is created, it inherits the environment from the function that created it. To get the environment table of a Lua function, you call `getfenv` (see -|luaref-getfenv|). To replace it, you call `setfenv` (see |luaref-setfenv|). +|lua_getfenv()|). To replace it, you call `setfenv` (see |luaref-setfenv()|). (You can only manipulate the environment of C functions through the debug library; see |luaref-libDebug|.) An access to a global variable `x` is equivalent to `_env.x`, which in turn is equivalent to -> +>lua gettable_event(_env, "x") < where `_env` is the environment of the running function. (The `_env` variable is @@ -433,13 +366,13 @@ before the adjustment (except when the call is enclosed in parentheses; see The assignment statement first evaluates all its expressions and only then are the assignments performed. Thus the code -> +>lua i = 3 i, a[i] = i+1, 20 < sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to 3) before it is assigned 4. Similarly, the line -> +>lua x, y = y, x < exchanges the values of `x` and `y`. @@ -452,7 +385,7 @@ defined or callable in Lua. We use it here only for explanatory purposes.) An assignment to a global variable `x = val` is equivalent to the assignment `_env.x = val`, which in turn is equivalent to -> +>lua settable_event(_env, "x", val) < where `_env` is the environment of the running function. (The `_env` variable is @@ -517,19 +450,20 @@ The `block` is repeated for `name` starting at the value of the first `exp`, unt it passes the second `exp` by steps of the third `exp`. More precisely, a `for` statement like - `for var =` `e1, e2, e3` `do` `block` `end` + `for var = e1, e2, e3 do block end` -is equivalent to the code: +is equivalent to the code: >lua - `do` - `local` `var, limit, step` `= tonumber(e1), tonumber(e2), tonumber(e3)` - `if not (` `var` `and` `limit` `and` `step` `) then error() end` - `while (` `step` `>0 and` `var` `<=` `limit` `)` - `or (` `step` `<=0 and` `var` `>=` `limit` `) do` - `block` - `var` `=` `var` `+` `step` - `end` - `end` + do + local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) + if not ( var and limit and step ) then error() end + while ( step >0 and var <= limit ) + or ( step <=0 and var >= limit ) do + block + var = var + step + end + end +< Note the following: @@ -555,18 +489,18 @@ A `for` statement like `for` `var1, ..., varn` `in` `explist` `do` `block` `end` -is equivalent to the code: - - `do` - `local` `f, s, var` `=` `explist` - `while true do` - `local` `var1, ..., varn` `=` `f(s, var)` - `var` `=` `var1` - `if` `var` `== nil then break end` - `block` - `end` - `end` +is equivalent to the code: >lua + do + local f, s, var = explist + while true do + local var1, ..., varn = f(s, var) + var = var1 + if var == nil then break end + block + end + end +< Note the following: - `explist` is evaluated only once. Its results are an iterator function, @@ -634,7 +568,7 @@ they are explained in |luaref-langFuncDefs|. Binary operators comprise arithmetic operators (see |luaref-langArithOp|), relational operators (see |luaref-langRelOp|), logical operators (see |luaref-langLogOp|), and the concatenation operator (see |luaref-langConcat|). -Unary operators comprise the unary minus (see |luaref-labgArithOp|), the unary +Unary operators comprise the unary minus (see |luaref-langArithOp|), the unary `not` (see |luaref-langLogOp|), and the unary length operator (see |luaref-langLength|). @@ -648,7 +582,7 @@ adjusts the result list to one element, discarding all values except the first one. Here are some examples: -> +>lua f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result g(x, f()) -- g gets x plus all results from f() @@ -681,7 +615,7 @@ or strings that can be converted to numbers (see |luaref-langCoercion|), then al operations have the usual meaning. Exponentiation works for any exponent. For instance, `x^(-0.5)` computes the inverse of the square root of `x`. Modulo is defined as -> +>lua a % b == a - math.floor(a/b)*b < That is, it is the remainder of a division that rounds the quotient towards @@ -808,11 +742,11 @@ key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to `["name"] = exp`. Finally, fields of the form `exp` are equivalent to `[i] = exp`, where `i` are consecutive numerical integers, starting with 1. Fields in the other formats do not affect this counting. For example, -> +>lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } < is equivalent to -> +>lua do local t = {} t[f(1)] = g @@ -868,7 +802,7 @@ argument list is a single new table. A call of the form `f'` `string` `'` As an exception to the free-format syntax of Lua, you cannot put a line break before the `(` in a function call. This restriction avoids some ambiguities in the language. If you write -> +>lua a = f (g).x(a) < @@ -886,7 +820,7 @@ function. Note that a tail call only happens with a particular syntax, where the `return` has one single function call as argument; this syntax makes the calling function return exactly the returns of the called function. So, none of the following examples are tail calls: -> +>lua return (f(x)) -- results adjusted to 1 return 2 * f(x) return x, f(x) -- additional results @@ -967,7 +901,7 @@ expression is used as the last element of a list of expressions, then no adjustment is made (unless the call is enclosed in parentheses). As an example, consider the following definitions: -> +>lua function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end @@ -1008,7 +942,7 @@ is syntactic sugar for Lua is a lexically scoped language. The scope of variables begins at the first statement after their declaration and lasts until the end of the innermost block that includes the declaration. Consider the following example: -> +>lua x = 10 -- global variable do -- new block local x = x -- new `x`, with value 10 @@ -1033,7 +967,7 @@ function. Notice that each execution of a local statement defines new local variables. Consider the following example: -> +>lua a = {} local x = 20 for i=1,10 do @@ -1050,13 +984,13 @@ them share the same `x`. Because Lua is an embedded extension language, all Lua actions start from C code in the host program calling a function from the Lua library (see -|luaref-lua_pcall|). Whenever an error occurs during Lua compilation or +|lua_pcall()|). Whenever an error occurs during Lua compilation or execution, control returns to C, which can take appropriate measures (such as print an error message). Lua code can explicitly generate an error by calling the `error` function (see -|luaref-error|). If you need to catch errors in Lua, you can use -the `pcall` function (see |luaref-pcall|). +|luaref-error()|). If you need to catch errors in Lua, you can use +the `pcall` function (see |luaref-pcall()|). ============================================================================== 2.8 Metatables *luaref-metatable* *luaref-langMetatables* @@ -1074,10 +1008,10 @@ previous example, the event is "add" and the metamethod is the function that performs the addition. You can query the metatable of any value through the `getmetatable` function -(see |luaref-getmetatable|). +(see |luaref-getmetatable()|). You can replace the metatable of tables through the `setmetatable` function (see -|luaref-setmetatable|). You cannot change the metatable of other types from Lua +|luaref-setmetatable()|). You cannot change the metatable of other types from Lua (except using the debug library); you must use the C API for that. Tables and userdata have individual metatables (although multiple tables and @@ -1109,7 +1043,7 @@ given object, we use the expression metatable(obj)[event] < This should be read as -> +>lua rawget(metatable(obj) or {}, event) < That is, the access to a metamethod does not invoke other metamethods, and the @@ -1123,13 +1057,13 @@ the `+` operation. The function `getbinhandler` below defines how Lua chooses a handler for a binary operation. First, Lua tries the first operand. If its type does not define a handler for the operation, then Lua tries the second operand. -> +>lua function getbinhandler (op1, op2, event) return metatable(op1)[event] or metatable(op2)[event] end < By using this function, the behavior of the `op1 + op2` is -> +>lua function add_event (op1, op2) local o1, o2 = tonumber(op1), tonumber(op2) if o1 and o2 then -- both operands are numeric? @@ -1170,7 +1104,7 @@ with the function `pow` (from the C math library) as the primitive operation. "unm": *__unm()* ------ the unary `-` operation. -> +>lua function unm_event (op) local o = tonumber(op) if o then -- operand is numeric? @@ -1190,7 +1124,7 @@ the unary `-` operation. "concat": *__concat()* --------- the `..` (concatenation) operation. -> +>lua function concat_event (op1, op2) if (type(op1) == "string" or type(op1) == "number") and (type(op2) == "string" or type(op2) == "number") then @@ -1208,7 +1142,7 @@ the `..` (concatenation) operation. "len": *__len()* ------ the `#` operation. -> +>lua function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length @@ -1233,7 +1167,7 @@ The function `getcomphandler` defines how Lua chooses a metamethod for comparison operators. A metamethod only is selected when both objects being compared have the same type and the same metamethod for the selected operation. -> +>lua function getcomphandler (op1, op2, event) if type(op1) ~= type(op2) then return nil end local mm1 = metatable(op1)[event] @@ -1242,7 +1176,7 @@ operation. end < The "eq" event is defined as follows: -> +>lua function eq_event (op1, op2) if type(op1) ~= type(op2) then -- different types? return false -- different objects @@ -1264,7 +1198,7 @@ The "eq" event is defined as follows: "lt": *__lt()* ----- the `<` operation. -> +>lua function lt_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 < op2 -- numeric comparison @@ -1285,7 +1219,7 @@ the `<` operation. "le": *__le()* ----- the `<=` operation. -> +>lua function le_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 <= op2 -- numeric comparison @@ -1313,7 +1247,7 @@ to `not (b < a)`. "index": *__index()* -------- The indexing access `table[key]`. -> +>lua function gettable_event (table, key) local h if type(table) == "table" then @@ -1335,7 +1269,7 @@ The indexing access `table[key]`. "newindex": *__newindex()* ----------- The indexing assignment `table[key] = value`. -> +>lua function settable_event (table, key, value) local h if type(table) == "table" then @@ -1357,7 +1291,7 @@ The indexing assignment `table[key] = value`. "call": *__call()* ------- called when Lua calls a value. -> +>lua function function_event (func, ...) if type(func) == "function" then return func(...) -- primitive call @@ -1385,8 +1319,8 @@ convenience feature for programmers to associate a table to a userdata. Environments associated with threads are called global environments. They are used as the default environment for their threads and non-nested functions -created by the thread (through `loadfile` |luaref-loadfile|, `loadstring` -|luaref-loadstring| or `load` |luaref-load|) and can be directly accessed by C +created by the thread (through `loadfile` |luaref-loadfile()|, `loadstring` +|luaref-loadstring()| or `load` |luaref-load()|) and can be directly accessed by C code (see |luaref-apiPseudoIndices|). Environments associated with C functions can be directly accessed by C code @@ -1399,10 +1333,10 @@ used as the default environment for other Lua functions created by the function. You can change the environment of a Lua function or the running thread by -calling `setfenv` (see |luaref-setenv|). You can get the environment of a Lua -function or the running thread by calling `getfenv` (see |luaref-getfenv|). To -manipulate the environment of other objects (userdata, C functions, other -threads) you must use the C API. +calling `setfenv`. You can get the environment of a Lua function or the +running thread by calling `getfenv` (see |lua_getfenv()|). To manipulate the +environment of other objects (userdata, C functions, other threads) you must +use the C API. ============================================================================== 2.10 Garbage Collection *luaref-langGC* @@ -1432,8 +1366,8 @@ collector too slow and may result in the collector never finishing a cycle. The default, 2, means that the collector runs at "twice" the speed of memory allocation. -You can change these numbers by calling `lua_gc` (see |luaref-lua_gc|) in C or -`collectgarbage` (see |luaref-collectgarbage|) in Lua. Both get percentage +You can change these numbers by calling `lua_gc` (see |lua_gc()|) in C or +`collectgarbage` (see |luaref-collectgarbage()|) in Lua. Both get percentage points as arguments (so an argument of 100 means a real value of 1). With these functions you can also control the collector directly (e.g., stop and restart it). @@ -1452,7 +1386,7 @@ Garbage userdata with a field `__gc` in their metatables are not collected immediately by the garbage collector. Instead, Lua puts them in a list. After the collection, Lua does the equivalent of the following function for each userdata in that list: -> +>lua function gc_event (udata) local h = metatable(udata).__gc if h then @@ -1496,12 +1430,12 @@ multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function. You create a coroutine with a call to `coroutine.create` (see -|luaref-coroutine.create|). Its sole argument is a function that is the main +|coroutine.create()|). Its sole argument is a function that is the main function of the coroutine. The `create` function only creates a new coroutine and returns a handle to it (an object of type `thread`); it does not start the coroutine execution. -When you first call `coroutine.resume` (see |luaref-coroutine.resume|), +When you first call `coroutine.resume` (see |coroutine.resume()|), passing as its first argument the thread returned by `coroutine.create`, the coroutine starts its execution, at the first line of its main function. Extra arguments passed to `coroutine.resume` are passed on to the coroutine main @@ -1516,7 +1450,7 @@ main function. In case of errors, `coroutine.resume` returns `false` plus an error message. A coroutine yields by calling `coroutine.yield` (see -|luaref-coroutine.yield|). When a coroutine yields, the corresponding +|coroutine.yield()|). When a coroutine yields, the corresponding `coroutine.resume` returns immediately, even if the yield happens inside nested function calls (that is, not in the main function, but in a function directly or indirectly called by the main function). In the case of a yield, @@ -1526,7 +1460,7 @@ its execution from the point where it yielded, with the call to `coroutine.yield` returning any extra arguments passed to `coroutine.resume`. Like `coroutine.create`, the `coroutine.wrap` function (see -|luaref-coroutine.wrap|) also creates a coroutine, but instead of returning +|coroutine.wrap()|) also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. Any arguments passed to this function go as extra arguments to `coroutine.resume`. `coroutine.wrap` returns all the values returned by @@ -1535,7 +1469,7 @@ coroutine. Any arguments passed to this function go as extra arguments to propagated to the caller. As an example, consider the next code: -> +>lua function foo1 (a) print("foo", a) return coroutine.yield(2*a) @@ -1569,7 +1503,6 @@ When you run it, it produces the following output: ============================================================================== 3 THE APPLICATION PROGRAM INTERFACE *luaref-API* -============================================================================== This section describes the C API for Lua, that is, the set of C functions available to the host program to communicate with Lua. All API functions and @@ -1595,7 +1528,7 @@ Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active. This stack initially contains any arguments to the C function and it is where the C function pushes its results to be returned to the caller (see -|luaref-lua_CFunction|). +|lua_CFunction()|). *luaref-stackindex* For convenience, most query operations in the API do not follow a strict stack @@ -1615,7 +1548,7 @@ if `1 <= abs(index) <= top`). When you interact with Lua API, you are responsible for ensuring consistency. In particular, you are responsible for controlling stack overflow. You can use the function `lua_checkstack` to grow the stack size (see -|luaref-lua_checkstack|). +|lua_checkstack()|). Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions are available. `LUA_MINSTACK` is defined as 20, so that usually you do not @@ -1626,7 +1559,7 @@ Most query functions accept as indices any value inside the available stack space, that is, indices up to the maximum stack size you have set through `lua_checkstack`. Such indices are called acceptable indices. More formally, we define an acceptable index as follows: -> +>lua (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace) < Note that 0 is never an acceptable index. @@ -1647,7 +1580,7 @@ pseudo-index `LUA_ENVIRONINDEX`. To access and change the value of global variables, you can use regular table operations over an environment table. For instance, to access the value of a global variable, do -> +>c lua_getfield(L, LUA_GLOBALSINDEX, varname); < @@ -1656,14 +1589,14 @@ global variable, do When a C function is created, it is possible to associate some values with it, thus creating a C closure; these values are called upvalues and are accessible -to the function whenever it is called (see |luaref-lua_pushcclosure|). +to the function whenever it is called (see |lua_pushcclosure()|). Whenever a C function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro -`lua_upvalueindex` (see |luaref-lua_upvalueindex|). The first value associated -with a function is at position `lua_upvalueindex(1)`, and so on. Any access to -`lua_upvalueindex(` `n` `)`, where `n` is greater than the number of upvalues of -the current function, produces an acceptable (but invalid) index. +`lua_upvalueindex`. The first value associated with a function is at position +`lua_upvalueindex(1)`, and so on. Any access to `lua_upvalueindex(` `n` `)`, +where `n` is greater than the number of upvalues of the current function, +produces an acceptable (but invalid) index. ============================================================================== 3.5 Registry *luaref-registry* *luaref-apiRegistry* @@ -1694,11 +1627,11 @@ Almost any function in the API may raise an error, for instance due to a memory allocation error. The following functions run in protected mode (that is, they create a protected environment to run), so they never raise an error: `lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see -|luaref-lua_newstate|, |luaref-lua_close|, |luaref-lua_load|, -|luaref-lua_pcall|, and |luaref-lua_cpcall|). +|lua_newstate()|, |lua_close()|, |lua_load()|, +|lua_pcall()|, and |lua_cpcall()|). Inside a C function you can raise an error by calling `lua_error` (see -|luaref-lua_error|). +|lua_error()|). ============================================================================== 3.7 Functions and Types *luaref-apiFunctions* @@ -1706,7 +1639,7 @@ Inside a C function you can raise an error by calling `lua_error` (see Here we list all functions and types from the C API in alphabetical order. lua_Alloc *lua_Alloc()* -> +>c typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, @@ -1715,7 +1648,7 @@ lua_Alloc *lua_Alloc()* The type of the memory-allocation function used by Lua states. The allocator function must provide a functionality similar to `realloc`, but not exactly the same. Its arguments are `ud`, an opaque pointer - passed to `lua_newstate` (see |luaref-lua_newstate|); `ptr`, a pointer + passed to `lua_newstate` (see |lua_newstate()|); `ptr`, a pointer to the block being allocated/reallocated/freed; `osize`, the original size of the block; `nsize`, the new size of the block. `ptr` is `NULL` if and only if `osize` is zero. When `nsize` is zero, the allocator @@ -1729,8 +1662,8 @@ lua_Alloc *lua_Alloc()* Here is a simple implementation for the allocator function. It is used in the auxiliary library by `luaL_newstate` (see - |luaref-luaL_newstate|). -> + |luaL_newstate()|). +>c static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ @@ -1747,7 +1680,7 @@ lua_Alloc *lua_Alloc()* behaviors. lua_atpanic *lua_atpanic()* -> +>c lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf); < Sets a new panic function and returns the old one. @@ -1761,7 +1694,7 @@ lua_atpanic *lua_atpanic()* stack. lua_call *lua_call()* -> +>c void lua_call (lua_State *L, int nargs, int nresults); < Calls a function. @@ -1785,11 +1718,11 @@ lua_call *lua_call()* The following example shows how the host program may do the equivalent to this Lua code: -> +>lua a = f("how", t.x, 14) < Here it is in C: -> +>c lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called lua_pushstring(L, "how"); // 1st argument lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed @@ -1804,7 +1737,7 @@ lua_call *lua_call()* practice. lua_CFunction *luaref-cfunction* *lua_CFunction()* -> +>c typedef int (*lua_CFunction) (lua_State *L); < Type for C functions. @@ -1813,7 +1746,7 @@ lua_CFunction *luaref-cfunction* *lua_CFunction()* following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the - function starts, `lua_gettop(L)` (see |luaref-lua_gettop|) returns the + function starts, `lua_gettop(L)` (see |lua_gettop()|) returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index `lua_gettop(L)`. To return values to Lua, a C function just pushes them onto the stack, @@ -1825,7 +1758,7 @@ lua_CFunction *luaref-cfunction* *lua_CFunction()* *luaref-cfunctionexample* As an example, the following function receives a variable number of numerical arguments and returns their average and sum: -> +>c static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0; @@ -1844,7 +1777,7 @@ lua_CFunction *luaref-cfunction* *lua_CFunction()* < lua_checkstack *lua_checkstack()* -> +>c int lua_checkstack (lua_State *L, int extra); < Ensures that there are at least `extra` free stack slots in the stack. @@ -1853,7 +1786,7 @@ lua_checkstack *lua_checkstack()* the new size, it is left unchanged. lua_close *lua_close()* -> +>c void lua_close (lua_State *L); < Destroys all objects in the given Lua state (calling the corresponding @@ -1865,7 +1798,7 @@ lua_close *lua_close()* are not needed, to avoid growing too large. lua_concat *lua_concat()* -> +>c void lua_concat (lua_State *L, int n); < Concatenates the `n` values at the top of the stack, pops them, and @@ -1875,35 +1808,35 @@ lua_concat *lua_concat()* usual semantics of Lua (see |luaref-langConcat|). lua_cpcall *lua_cpcall()* -> +>c int lua_cpcall (lua_State *L, lua_CFunction func, void *ud); < Calls the C function `func` in protected mode. `func` starts with only one element in its stack, a light userdata containing `ud`. In case of errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see - |luaref-lua_pcall|), plus the error object on the top of the stack; + |lua_pcall()|), plus the error object on the top of the stack; otherwise, it returns zero, and does not change the stack. All values returned by `func` are discarded. lua_createtable *lua_createtable()* -> +>c void lua_createtable (lua_State *L, int narr, int nrec); < Creates a new empty table and pushes it onto the stack. The new table has space pre-allocated for `narr` array elements and `nrec` non-array elements. This pre-allocation is useful when you know exactly how many elements the table will have. Otherwise you can use the function - `lua_newtable` (see |luaref-lua_newtable|). + `lua_newtable` (see |lua_newtable()|). lua_dump *lua_dump()* -> +>c int lua_dump (lua_State *L, lua_Writer writer, void *data); < Dumps a function as a binary chunk. Receives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, `lua_dump` calls function `writer` (see - |luaref-lua_Writer|) with the given `data` to write them. + |lua_Writer()|) with the given `data` to write them. The value returned is the error code returned by the last call to the writer; 0 means no errors. @@ -1911,7 +1844,7 @@ lua_dump *lua_dump()* This function does not pop the Lua function from the stack. lua_equal *lua_equal()* -> +>c int lua_equal (lua_State *L, int index1, int index2); < Returns 1 if the two values in acceptable indices `index1` and @@ -1920,15 +1853,15 @@ lua_equal *lua_equal()* if any of the indices is non valid. lua_error *lua_error()* -> +>c int lua_error (lua_State *L); < Generates a Lua error. The error message (which can actually be a Lua value of any type) must be on the stack top. This function does a long - jump, and therefore never returns (see |luaref-luaL_error|). + jump, and therefore never returns (see |luaL_error()|). lua_gc *lua_gc()* -> +>c int lua_gc (lua_State *L, int what, int data); < Controls the garbage collector. @@ -1936,46 +1869,46 @@ lua_gc *lua_gc()* This function performs several tasks, according to the value of the parameter `what`: - `LUA_GCSTOP` stops the garbage collector. - `LUA_GCRESTART` restarts the garbage collector. - `LUA_GCCOLLECT` performs a full garbage-collection cycle. - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in + - `LUA_GCSTOP` stops the garbage collector. + - `LUA_GCRESTART` restarts the garbage collector. + - `LUA_GCCOLLECT` performs a full garbage-collection cycle. + - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in use by Lua. - `LUA_GCCOUNTB` returns the remainder of dividing the current + - `LUA_GCCOUNTB` returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024. - `LUA_GCSTEP` performs an incremental step of garbage collection. + - `LUA_GCSTEP` performs an incremental step of garbage collection. The step "size" is controlled by `data` (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of `data`. The function returns 1 if the step finished a garbage-collection cycle. - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the + - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the `pause` of the collector (see |luaref-langGC|). The function returns the previous value of the pause. - `LUA_GCSETSTEPMUL` sets `data` /100 as the new value for the + - `LUA_GCSETSTEPMUL`sets `data` /100 as the new value for the `step` `multiplier` of the collector (see |luaref-langGC|). The function returns the previous value of the step multiplier. lua_getallocf *lua_getallocf()* -> +>c lua_Alloc lua_getallocf (lua_State *L, void **ud); < Returns the memory-allocation function of a given state. If `ud` is not `NULL`, Lua stores in `*ud` the opaque pointer passed to - `lua_newstate` (see |luaref-lua_newstate|). + `lua_newstate` (see |lua_newstate()|). lua_getfenv *lua_getfenv()* -> +>c void lua_getfenv (lua_State *L, int index); < Pushes onto the stack the environment table of the value at the given index. lua_getfield *lua_getfield()* -> +>c void lua_getfield (lua_State *L, int index, const char *k); < Pushes onto the stack the value `t[k]`, where `t` is the value at the @@ -1983,17 +1916,17 @@ lua_getfield *lua_getfield()* metamethod for the "index" event (see |luaref-langMetatables|). lua_getglobal *lua_getglobal()* -> +>c void lua_getglobal (lua_State *L, const char *name); < Pushes onto the stack the value of the global `name`. It is defined as a macro: -> +>c #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s) < lua_getmetatable *lua_getmetatable()* -> +>c int lua_getmetatable (lua_State *L, int index); < Pushes onto the stack the metatable of the value at the given @@ -2002,7 +1935,7 @@ lua_getmetatable *lua_getmetatable()* stack. lua_gettable *lua_gettable()* -> +>c void lua_gettable (lua_State *L, int index); < Pushes onto the stack the value `t[k]`, where `t` is the value at the @@ -2014,7 +1947,7 @@ lua_gettable *lua_gettable()* the "index" event (see |luaref-langMetatables|). lua_gettop *lua_gettop()* -> +>c int lua_gettop (lua_State *L); < Returns the index of the top element in the stack. Because indices @@ -2023,7 +1956,7 @@ lua_gettop *lua_gettop()* 0 means an empty stack). lua_insert *lua_insert()* -> +>c void lua_insert (lua_State *L, int index); < Moves the top element into the given valid index, shifting up the @@ -2031,7 +1964,7 @@ lua_insert *lua_insert()* pseudo-index, because a pseudo-index is not an actual stack position. lua_Integer *lua_Integer()* -> +>c typedef ptrdiff_t lua_Integer; < The type used by the Lua API to represent integral values. @@ -2040,77 +1973,77 @@ lua_Integer *lua_Integer()* type the machine handles "comfortably". lua_isboolean *lua_isboolean()* -> +>c int lua_isboolean (lua_State *L, int index); < Returns 1 if the value at the given acceptable index has type boolean, and 0 otherwise. lua_iscfunction *lua_iscfunction()* -> +>c int lua_iscfunction (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a C function, and 0 otherwise. lua_isfunction *lua_isfunction()* -> +>c int lua_isfunction (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a function (either C or Lua), and 0 otherwise. lua_islightuserdata *lua_islightuserdata()* -> +>c int lua_islightuserdata (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a light userdata, and 0 otherwise. lua_isnil *lua_isnil()* -> +>c int lua_isnil (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is `nil`, and 0 otherwise. lua_isnumber *lua_isnumber()* -> +>c int lua_isnumber (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a number or a string convertible to a number, and 0 otherwise. lua_isstring *lua_isstring()* -> +>c int lua_isstring (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a string or a number (which is always convertible to a string), and 0 otherwise. lua_istable *lua_istable()* -> +>c int lua_istable (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a table, and 0 otherwise. lua_isthread *lua_isthread()* -> +>c int lua_isthread (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a thread, and 0 otherwise. lua_isuserdata *lua_isuserdata()* -> +>c int lua_isuserdata (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a userdata (either full or light), and 0 otherwise. lua_lessthan *lua_lessthan()* -> +>c int lua_lessthan (lua_State *L, int index1, int index2); < Returns 1 if the value at acceptable index `index1` is smaller than @@ -2119,7 +2052,7 @@ lua_lessthan *lua_lessthan()* Also returns 0 if any of the indices is non valid. lua_load *lua_load()* -> +>c int lua_load (lua_State *L, lua_Reader reader, void *data, @@ -2136,17 +2069,17 @@ lua_load *lua_load()* This function only loads a chunk; it does not run it. `lua_load` automatically detects whether the chunk is text or binary, - and loads it accordingly (see program `luac`, |luaref-luac|). + and loads it accordingly (see program `luac`). The `lua_load` function uses a user-supplied `reader` function to read - the chunk (see |luaref-lua_Reader|). The `data` argument is an opaque + the chunk (see |lua_Reader()|). The `data` argument is an opaque value passed to the reader function. The `chunkname` argument gives a name to the chunk, which is used for error messages and in debug information (see |luaref-apiDebug|). lua_newstate *lua_newstate()* -> +>c lua_State *lua_newstate (lua_Alloc f, void *ud); < Creates a new, independent state. Returns `NULL` if cannot create the @@ -2156,19 +2089,19 @@ lua_newstate *lua_newstate()* simply passes to the allocator in every call. lua_newtable *lua_newtable()* -> +>c void lua_newtable (lua_State *L); < Creates a new empty table and pushes it onto the stack. It is equivalent to `lua_createtable(L, 0, 0)` (see - |luaref-lua_createtable|). + |lua_createtable()|). lua_newthread *lua_newthread()* -> +>c lua_State *lua_newthread (lua_State *L); < Creates a new thread, pushes it on the stack, and returns a pointer to - a `lua_State` (see |luaref-lua_State|) that represents this new + a `lua_State` (see |lua_State()|) that represents this new thread. The new state returned by this function shares with the original state all global objects (such as tables), but has an independent execution stack. @@ -2177,7 +2110,7 @@ lua_newthread *lua_newthread()* are subject to garbage collection, like any Lua object. lua_newuserdata *lua_newuserdata()* -> +>c void *lua_newuserdata (lua_State *L, size_t size); < This function allocates a new block of memory with the given size, @@ -2195,7 +2128,7 @@ lua_newuserdata *lua_newuserdata()* is collected again then Lua frees its corresponding memory. lua_next *lua_next()* -> +>c int lua_next (lua_State *L, int index); < Pops a key from the stack, and pushes a key-value pair from the table @@ -2205,7 +2138,7 @@ lua_next *lua_next()* *luaref-tabletraversal* A typical traversal looks like this: -> +>c /* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { @@ -2218,12 +2151,12 @@ lua_next *lua_next()* } < While traversing a table, do not call `lua_tolstring` (see - |luaref-lua_tolstring|) directly on a key, unless you know that the + |lua_tolstring()|) directly on a key, unless you know that the key is actually a string. Recall that `lua_tolstring` `changes` the value at the given index; this confuses the next call to `lua_next`. lua_Number *lua_Number()* -> +>c typedef double lua_Number; < The type of numbers in Lua. By default, it is double, but that can be @@ -2233,7 +2166,7 @@ lua_Number *lua_Number()* another type for numbers (e.g., float or long). lua_objlen *lua_objlen()* -> +>c size_t lua_objlen (lua_State *L, int index); < Returns the "length" of the value at the given acceptable index: for @@ -2242,13 +2175,13 @@ lua_objlen *lua_objlen()* block of memory allocated for the userdata; for other values, it is 0. lua_pcall *lua_pcall()* -> +>c lua_pcall (lua_State *L, int nargs, int nresults, int errfunc); < Calls a function in protected mode. Both `nargs` and `nresults` have the same meaning as in `lua_call` - (see |luaref-lua_call|). If there are no errors during the call, + (see |lua_call()|). If there are no errors during the call, `lua_pcall` behaves exactly like `lua_call`. However, if there is any error, `lua_pcall` catches it, pushes a single value on the stack (the error message), and returns an error code. Like `lua_call`, @@ -2277,19 +2210,19 @@ lua_pcall *lua_pcall()* - `LUA_ERRERR` error while running the error handler function. lua_pop *lua_pop()* -> +>c void lua_pop (lua_State *L, int n); < Pops `n` elements from the stack. lua_pushboolean *lua_pushboolean()* -> +>c void lua_pushboolean (lua_State *L, int b); < Pushes a boolean value with value `b` onto the stack. lua_pushcclosure *lua_pushcclosure()* -> +>c void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); < Pushes a new C closure onto the stack. @@ -2305,7 +2238,7 @@ lua_pushcclosure *lua_pushcclosure()* pops these values from the stack. lua_pushcfunction *lua_pushcfunction()* -> +>c void lua_pushcfunction (lua_State *L, lua_CFunction f); < Pushes a C function onto the stack. This function receives a pointer @@ -2314,15 +2247,15 @@ lua_pushcfunction *lua_pushcfunction()* Any function to be registered in Lua must follow the correct protocol to receive its parameters and return its results (see - |luaref-lua_CFunction|). + |lua_CFunction()|). `lua_pushcfunction` is defined as a macro: -> +>c #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0) < lua_pushfstring *lua_pushfstring()* -> +>c const char *lua_pushfstring (lua_State *L, const char *fmt, ...); < Pushes onto the stack a formatted string and returns a pointer to this @@ -2341,13 +2274,13 @@ lua_pushfstring *lua_pushfstring()* character). lua_pushinteger *lua_pushinteger()* -> +>c void lua_pushinteger (lua_State *L, lua_Integer n); < Pushes a number with value `n` onto the stack. lua_pushlightuserdata *lua_pushlightuserdata()* -> +>c void lua_pushlightuserdata (lua_State *L, void *p); < Pushes a light userdata onto the stack. @@ -2359,7 +2292,7 @@ lua_pushlightuserdata *lua_pushlightuserdata()* same C address. lua_pushlstring *lua_pushlstring()* -> +>c void lua_pushlstring (lua_State *L, const char *s, size_t len); < Pushes the string pointed to by `s` with size `len` onto the stack. @@ -2368,19 +2301,19 @@ lua_pushlstring *lua_pushlstring()* returns. The string can contain embedded zeros. lua_pushnil *lua_pushnil()* -> +>c void lua_pushnil (lua_State *L); < Pushes a nil value onto the stack. lua_pushnumber *lua_pushnumber()* -> +>c void lua_pushnumber (lua_State *L, lua_Number n); < Pushes a number with value `n` onto the stack. lua_pushstring *lua_pushstring()* -> +>c void lua_pushstring (lua_State *L, const char *s); < Pushes the zero-terminated string pointed to by `s` onto the stack. @@ -2390,30 +2323,30 @@ lua_pushstring *lua_pushstring()* end at the first zero. lua_pushthread *lua_pushthread()* -> +>c int lua_pushthread (lua_State *L); < Pushes the thread represented by `L` onto the stack. Returns 1 if this thread is the main thread of its state. lua_pushvalue *lua_pushvalue()* -> +>c void lua_pushvalue (lua_State *L, int index); < Pushes a copy of the element at the given valid index onto the stack. lua_pushvfstring *lua_pushvfstring()* -> +>c const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp); < - Equivalent to `lua_pushfstring` (see |luaref-pushfstring|), except + Equivalent to `lua_pushfstring` (see |lua_pushfstring()|), except that it receives a `va_list` instead of a variable number of arguments. lua_rawequal *lua_rawequal()* -> +>c int lua_rawequal (lua_State *L, int index1, int index2); < Returns 1 if the two values in acceptable indices `index1` and @@ -2422,14 +2355,14 @@ lua_rawequal *lua_rawequal()* valid. lua_rawget *lua_rawget()* -> +>c void lua_rawget (lua_State *L, int index); < - Similar to `lua_gettable` (see |luaref-lua_gettable|), but does a raw + Similar to `lua_gettable` (see |lua_gettable()|), but does a raw access (i.e., without metamethods). lua_rawgeti *lua_rawgeti()* -> +>c void lua_rawgeti (lua_State *L, int index, int n); < Pushes onto the stack the value `t[n]`, where `t` is the value at the @@ -2437,14 +2370,14 @@ lua_rawgeti *lua_rawgeti()* invoke metamethods. lua_rawset *lua_rawset()* -> +>c void lua_rawset (lua_State *L, int index); < - Similar to `lua_settable` (see |luaref-lua_settable|), but does a raw + Similar to `lua_settable` (see |lua_settable()|), but does a raw assignment (i.e., without metamethods). lua_rawseti *lua_rawseti()* -> +>c void lua_rawseti (lua_State *L, int index, int n); < Does the equivalent of `t[n] = v`, where `t` is the value at the given @@ -2454,12 +2387,12 @@ lua_rawseti *lua_rawseti()* that is, it does not invoke metamethods. lua_Reader *lua_Reader()* -> +>c typedef const char * (*lua_Reader) (lua_State *L, void *data, size_t *size); < - The reader function used by `lua_load` (see |luaref-lua_load|). Every + The reader function used by `lua_load` (see |lua_load()|). Every time it needs another piece of the chunk, `lua_load` calls the reader, passing along its `data` parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set `size` to @@ -2469,20 +2402,20 @@ lua_Reader *lua_Reader()* zero. lua_register *lua_register()* -> +>c void lua_register (lua_State *L, const char *name, lua_CFunction f); < Sets the C function `f` as the new value of global `name`. It is defined as a macro: -> +>c #define lua_register(L,n,f) \ (lua_pushcfunction(L, f), lua_setglobal(L, n)) < lua_remove *lua_remove()* -> +>c void lua_remove (lua_State *L, int index); < Removes the element at the given valid index, shifting down the @@ -2490,7 +2423,7 @@ lua_remove *lua_remove()* pseudo-index, because a pseudo-index is not an actual stack position. lua_replace *lua_replace()* -> +>c void lua_replace (lua_State *L, int index); < Moves the top element into the given position (and pops it), without @@ -2498,35 +2431,35 @@ lua_replace *lua_replace()* position). lua_resume *lua_resume()* -> +>c int lua_resume (lua_State *L, int narg); < Starts and resumes a coroutine in a given thread. To start a coroutine, you first create a new thread (see - |luaref-lua_newthread|); then you push onto its stack the main + |lua_newthread()|); then you push onto its stack the main function plus any arguments; then you call `lua_resume` (see - |luaref-lua_resume|) with `narg` being the number of arguments. This + |lua_resume()|) with `narg` being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed to `lua_yield` - (see |luaref-lua_yield|), or all values returned by the body function. + (see |lua_yield()|), or all values returned by the body function. `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the coroutine finishes its execution without errors, or an error code in - case of errors (see |luaref-lua_pcall|). In case of errors, the stack + case of errors (see |lua_pcall()|). In case of errors, the stack is not unwound, so you can use the debug API over it. The error message is on the top of the stack. To restart a coroutine, you put on its stack only the values to be passed as results from `lua_yield`, and then call `lua_resume`. lua_setallocf *lua_setallocf()* -> +>c void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); < Changes the allocator function of a given state to `f` with user data `ud`. lua_setfenv *lua_setfenv()* -> +>c int lua_setfenv (lua_State *L, int index); < Pops a table from the stack and sets it as the new environment for the @@ -2535,7 +2468,7 @@ lua_setfenv *lua_setfenv()* Otherwise it returns 1. lua_setfield *lua_setfield()* -> +>c void lua_setfield (lua_State *L, int index, const char *k); < Does the equivalent to `t[k] = v`, where `t` is the value at the given @@ -2546,24 +2479,24 @@ lua_setfield *lua_setfield()* |luaref-langMetatables|). lua_setglobal *lua_setglobal()* -> +>c void lua_setglobal (lua_State *L, const char *name); < Pops a value from the stack and sets it as the new value of global `name`. It is defined as a macro: -> +>c #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s) < lua_setmetatable *lua_setmetatable()* -> +>c int lua_setmetatable (lua_State *L, int index); < Pops a table from the stack and sets it as the new metatable for the value at the given acceptable index. lua_settable *lua_settable()* -> +>c void lua_settable (lua_State *L, int index); < Does the equivalent to `t[k] = v`, where `t` is the value at the given @@ -2575,7 +2508,7 @@ lua_settable *lua_settable()* (see |luaref-langMetatables|). lua_settop *lua_settop()* -> +>c void lua_settop (lua_State *L, int index); < Accepts any acceptable index, or 0, and sets the stack top to this @@ -2584,7 +2517,7 @@ lua_settop *lua_settop()* elements are removed. lua_State *lua_State()* -> +>c typedef struct lua_State lua_State; < Opaque structure that keeps the whole state of a Lua interpreter. The @@ -2593,10 +2526,10 @@ lua_State *lua_State()* A pointer to this state must be passed as the first argument to every function in the library, except to `lua_newstate` (see - |luaref-lua_newstate|), which creates a Lua state from scratch. + |lua_newstate()|), which creates a Lua state from scratch. lua_status *lua_status()* -> +>c int lua_status (lua_State *L); < Returns the status of the thread `L`. @@ -2606,7 +2539,7 @@ lua_status *lua_status()* suspended. lua_toboolean *lua_toboolean()* -> +>c int lua_toboolean (lua_State *L, int index); < Converts the Lua value at the given acceptable index to a C boolean @@ -2614,21 +2547,21 @@ lua_toboolean *lua_toboolean()* any Lua value different from `false` and `nil`; otherwise it returns 0. It also returns 0 when called with a non-valid index. (If you want to accept only actual boolean values, use `lua_isboolean` - |luaref-lua_isboolean| to test the value's type.) + |lua_isboolean()| to test the value's type.) lua_tocfunction *lua_tocfunction()* -> +>c lua_CFunction lua_tocfunction (lua_State *L, int index); < Converts a value at the given acceptable index to a C function. That value must be a C function; otherwise it returns `NULL`. lua_tointeger *lua_tointeger()* -> +>c lua_Integer lua_tointeger (lua_State *L, int idx); < Converts the Lua value at the given acceptable index to the signed - integral type `lua_Integer` (see |luaref-lua_Integer|). The Lua value + integral type `lua_Integer` (see |lua_Integer()|). The Lua value must be a number or a string convertible to a number (see |luaref-langCoercion|); otherwise, `lua_tointeger` returns 0. @@ -2636,7 +2569,7 @@ lua_tointeger *lua_tointeger()* way. lua_tolstring *lua_tolstring()* -> +>c const char *lua_tolstring (lua_State *L, int index, size_t *len); < Converts the Lua value at the given acceptable index to a C string. If @@ -2644,7 +2577,7 @@ lua_tolstring *lua_tolstring()* Lua value must be a string or a number; otherwise, the function returns `NULL`. If the value is a number, then `lua_tolstring` also `changes the actual value in the stack to a` `string`. (This change - confuses `lua_next` |luaref-lua_next| when `lua_tolstring` is applied + confuses `lua_next` |lua_next()| when `lua_tolstring` is applied to keys during a table traversal.) `lua_tolstring` returns a fully aligned pointer to a string inside the @@ -2655,16 +2588,16 @@ lua_tolstring *lua_tolstring()* value is removed from the stack. lua_tonumber *lua_tonumber()* -> +>c lua_Number lua_tonumber (lua_State *L, int index); < Converts the Lua value at the given acceptable index to the C type - `lua_Number` (see |luaref-lua_Number|). The Lua value must be a number + `lua_Number` (see |lua_Number()|). The Lua value must be a number or a string convertible to a number (see |luaref-langCoercion|); otherwise, `lua_tonumber` returns 0. lua_topointer *lua_topointer()* -> +>c const void *lua_topointer (lua_State *L, int index); < Converts the value at the given acceptable index to a generic C @@ -2676,22 +2609,22 @@ lua_topointer *lua_topointer()* Typically this function is used only for debug information. lua_tostring *lua_tostring()* -> +>c const char *lua_tostring (lua_State *L, int index); < - Equivalent to `lua_tolstring` (see |luaref-lua_tolstring|) with `len` + Equivalent to `lua_tolstring` (see |lua_tolstring()|) with `len` equal to `NULL`. lua_tothread *lua_tothread()* -> +>c lua_State *lua_tothread (lua_State *L, int index); < Converts the value at the given acceptable index to a Lua thread - (represented as `lua_State*` |luaref-lua_State|). This value must be a + (represented as `lua_State*` |lua_State()|). This value must be a thread; otherwise, the function returns `NULL`. lua_touserdata *lua_touserdata()* -> +>c void *lua_touserdata (lua_State *L, int index); < If the value at the given acceptable index is a full userdata, returns @@ -2699,7 +2632,7 @@ lua_touserdata *lua_touserdata()* pointer. Otherwise, it returns `NULL`. lua_type *lua_type()* -> +>c int lua_type (lua_State *L, int index); < Returns the type of the value in the given acceptable index, or @@ -2710,20 +2643,20 @@ lua_type *lua_type()* `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`. lua_typename *lua_typename()* -> +>c const char *lua_typename (lua_State *L, int tp); < Returns the name of the type encoded by the value `tp`, which must be one the values returned by `lua_type`. lua_Writer *lua_Writer()* -> +>c typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); < - The writer function used by `lua_dump` (see |luaref-lua_dump|). Every + The writer function used by `lua_dump` (see |lua_dump()|). Every time it produces another piece of chunk, `lua_dump` calls the writer, passing along the buffer to be written (`p`), its size (`sz`), and the `data` parameter supplied to `lua_dump`. @@ -2732,7 +2665,7 @@ lua_Writer *lua_Writer()* means an error and stops `lua_dump` from calling the writer again. lua_xmove *lua_xmove()* -> +>c void lua_xmove (lua_State *from, lua_State *to, int n); < Exchange values between different threads of the `same` global state. @@ -2741,19 +2674,19 @@ lua_xmove *lua_xmove()* onto the stack `to`. lua_yield *lua_yield()* -> +>c int lua_yield (lua_State *L, int nresults); < Yields a coroutine. This function should only be called as the return expression of a C function, as follows: -> +>c return lua_yield (L, nresults); < When a C function calls `lua_yield` in that way, the running coroutine suspends its execution, and the call to `lua_resume` (see - |luaref-lua_resume|) that started this coroutine returns. The + |lua_resume()|) that started this coroutine returns. The parameter `nresults` is the number of values from the stack that are passed as results to `lua_resume`. @@ -2782,50 +2715,52 @@ need "inside information" from the interpreter. lua_Debug *lua_Debug()* - `typedef struct lua_Debug {` - `int event;` - `const char *name; /* (n) */` - `const char *namewhat; /* (n) */` - `const char *what; /* (S) */` - `const char *source; /* (S) */` - `int currentline; /* (l) */` - `int nups; /* (u) number of upvalues */` - `int linedefined; /* (S) */` - `int lastlinedefined; /* (S) */` - `char short_src[LUA_IDSIZE]; /* (S) */` - `/* private part */` - `other fields` - `} lua_Debug;` +>c + typedef struct lua_Debug { + int event; + const char *name; /* (n) */ + const char *namewhat; /* (n) */ + const char *what; /* (S) */ + const char *source; /* (S) */ + int currentline; /* (l) */ + int nups; /* (u) number of upvalues */ + int linedefined; /* (S) */ + int lastlinedefined; /* (S) */ + char short_src[LUA_IDSIZE]; /* (S) */ + /* private part */ + other fields + } lua_Debug; +< A structure used to carry different pieces of information about an active -function. `lua_getstack` (see |luaref-lua_getstack|) fills only the private part +function. `lua_getstack` (see |lua_getstack()|) fills only the private part of this structure, for later use. To fill the other fields of `lua_Debug` with -useful information, call `lua_getinfo` (see |luaref-lua_getinfo|). +useful information, call `lua_getinfo` (see |lua_getinfo()|). The fields of `lua_Debug` have the following meaning: - `source` If the function was defined in a string, then `source` is +- `source` If the function was defined in a string, then `source` is that string. If the function was defined in a file, then `source` starts with a `@` followed by the file name. - `short_src` a "printable" version of `source`, to be used in error messages. - `linedefined` the line number where the definition of the function starts. - `lastlinedefined` the line number where the definition of the function ends. - `what` the string `"Lua"` if the function is a Lua function, +- `short_src` a "printable" version of `source`, to be used in error messages. +- `linedefined` the line number where the definition of the function starts. +- `lastlinedefined` the line number where the definition of the function ends. +- `what` the string `"Lua"` if the function is a Lua function, `"C"` if it is a C function, `"main"` if it is the main part of a chunk, and `"tail"` if it was a function that did a tail call. In the latter case, Lua has no other information about the function. - `currentline` the current line where the given function is executing. +- `currentline` the current line where the given function is executing. When no line information is available, `currentline` is set to -1. - `name` a reasonable name for the given function. Because +- `name` a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions may be the value of multiple global variables, while others may be stored only in a table field. The `lua_getinfo` function checks how the function was called to find a suitable name. If it cannot find a name, then `name` is set to `NULL`. - `namewhat` explains the `name` field. The value of `namewhat` can be +- `namewhat` explains the `name` field. The value of `namewhat` can be `"global"`, `"local"`, `"method"`, `"field"`, `"upvalue"`, or `""` (the empty string), according to how the function was called. (Lua uses the empty string when @@ -2833,40 +2768,40 @@ The fields of `lua_Debug` have the following meaning: upvalues of the function. lua_gethook *lua_gethook()* -> +>c lua_Hook lua_gethook (lua_State *L); < Returns the current hook function. lua_gethookcount *lua_gethookcount()* -> +>c int lua_gethookcount (lua_State *L); < Returns the current hook count. lua_gethookmask *lua_gethookmask()* -> +>c int lua_gethookmask (lua_State *L); < Returns the current hook mask. lua_getinfo *lua_getinfo()* -> +>c int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); < Returns information about a specific function or function invocation. To get information about a function invocation, the parameter `ar` must be a valid activation record that was filled by a previous call - to `lua_getstack` (see |luaref-lua_getstack|) or given as argument to - a hook (see |luaref-lua_Hook|). + to `lua_getstack` (see |lua_getstack()|) or given as argument to + a hook (see |lua_Hook()|). To get information about a function you push it onto the stack and start the `what` string with the character `>`. (In that case, `lua_getinfo` pops the function in the top of the stack.) For instance, to know in which line a function `f` was defined, you can write the following code: -> +>c lua_Debug ar; lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */ lua_getinfo(L, ">S", &ar); @@ -2891,13 +2826,13 @@ lua_getinfo *lua_getinfo()* `what`). lua_getlocal *lua_getlocal()* -> +>c const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n); < Gets information about a local variable of a given activation record. The parameter `ar` must be a valid activation record that was filled - by a previous call to `lua_getstack` (see |luaref-lua_getstack|) or - given as argument to a hook (see |luaref-lua_Hook|). The index `n` + by a previous call to `lua_getstack` (see |lua_getstack()|) or + given as argument to a hook (see |lua_Hook()|). The index `n` selects which local variable to inspect (1 is the first parameter or active local variable, and so on, until the last active local variable). `lua_getlocal` pushes the variable's value onto the stack @@ -2911,12 +2846,12 @@ lua_getlocal *lua_getlocal()* number of active local variables. lua_getstack *lua_getstack()* -> +>c int lua_getstack (lua_State *L, int level, lua_Debug *ar); < Gets information about the interpreter runtime stack. - This function fills parts of a `lua_Debug` (see |luaref-lua_Debug|) + This function fills parts of a `lua_Debug` (see |lua_Debug()|) structure with an identification of the `activation record` of the function executing at a given level. Level 0 is the current running function, whereas level `n+1` is the function that has called level @@ -2924,7 +2859,7 @@ lua_getstack *lua_getstack()* with a level greater than the stack depth, it returns 0. lua_getupvalue *lua_getupvalue()* -> +>c const char *lua_getupvalue (lua_State *L, int funcindex, int n); < Gets information about a closure's upvalue. (For Lua functions, @@ -2940,7 +2875,7 @@ lua_getupvalue *lua_getupvalue()* string `""` as a name for all upvalues. lua_Hook *lua_Hook()* -> +>c typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); < Type for debugging hook functions. @@ -2951,7 +2886,7 @@ lua_Hook *lua_Hook()* `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for line events, the field `currentline` is also set. To get the value of any other field in `ar`, the hook must call `lua_getinfo` (see - |luaref-lua_getinfo|). For return events, `event` may be + |lua_getinfo()|). For return events, `event` may be `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter case, Lua is simulating a return from a function that did a tail call; in this case, it is useless to call `lua_getinfo`. @@ -2962,7 +2897,7 @@ lua_Hook *lua_Hook()* lua_sethook *lua_sethook()* -> +>c int lua_sethook (lua_State *L, lua_Hook f, int mask, int count); < Sets the debugging hook function. @@ -2991,12 +2926,12 @@ lua_sethook *lua_sethook()* A hook is disabled by setting `mask` to zero. lua_setlocal *lua_setlocal()* -> +>c const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n); < Sets the value of a local variable of a given activation record. Parameters `ar` and `n` are as in `lua_getlocal` (see - |luaref-lua_getlocal|). `lua_setlocal` assigns the value at the top of + |lua_getlocal()|). `lua_setlocal` assigns the value at the top of the stack to the variable and returns its name. It also pops the value from the stack. @@ -3004,13 +2939,13 @@ lua_setlocal *lua_setlocal()* number of active local variables. lua_setupvalue *lua_setupvalue()* -> +>c const char *lua_setupvalue (lua_State *L, int funcindex, int n); < Sets the value of a closure's upvalue. It assigns the value at the top of the stack to the upvalue and returns its name. It also pops the value from the stack. Parameters `funcindex` and `n` are as in the - `lua_getupvalue` (see |luaref-lua_getupvalue|). + `lua_getupvalue` (see |lua_getupvalue()|). Returns `NULL` (and pops nothing) when the index is greater than the number of upvalues. @@ -3018,7 +2953,7 @@ lua_setupvalue *lua_setupvalue()* *luaref-debugexample* As an example, the following function lists the names of all local variables and upvalues for a function at a given level of the stack: -> +>c int listvars (lua_State *L, int level) { lua_Debug ar; int i; @@ -3042,7 +2977,6 @@ lua_setupvalue *lua_setupvalue()* ============================================================================== 4 THE AUXILIARY LIBRARY *luaref-aux* -============================================================================== The auxiliary library provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all @@ -3068,46 +3002,46 @@ Here we list all functions and types from the auxiliary library in alphabetical order. luaL_addchar *luaL_addchar()* -> +>c void luaL_addchar (luaL_Buffer *B, char c); < - Adds the character `c` to the buffer `B` (see |luaref-luaL_Buffer|). + Adds the character `c` to the buffer `B` (see |luaL_Buffer()|). luaL_addlstring *luaL_addlstring()* -> +>c void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); < Adds the string pointed to by `s` with length `l` to the buffer `B` - (see |luaref-luaL_Buffer|). The string may contain embedded zeros. + (see |luaL_Buffer()|). The string may contain embedded zeros. luaL_addsize *luaL_addsize()* -> +>c void luaL_addsize (luaL_Buffer *B, size_t n); < - Adds to the buffer `B` (see |luaref-luaL_Buffer|) a string of length + Adds to the buffer `B` (see |luaL_Buffer()|) a string of length `n` previously copied to the buffer area (see - |luaref-luaL_prepbuffer|). + |luaL_prepbuffer()|). luaL_addstring *luaL_addstring()* -> +>c void luaL_addstring (luaL_Buffer *B, const char *s); < Adds the zero-terminated string pointed to by `s` to the buffer `B` - (see |luaref-luaL_Buffer|). The string may not contain embedded zeros. + (see |luaL_Buffer()|). The string may not contain embedded zeros. luaL_addvalue *luaL_addvalue()* -> +>c void luaL_addvalue (luaL_Buffer *B); < Adds the value at the top of the stack to the buffer `B` (see - |luaref-luaL_Buffer|). Pops the value. + |luaL_Buffer()|). Pops the value. This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer. luaL_argcheck *luaL_argcheck()* -> +>c void luaL_argcheck (lua_State *L, int cond, int narg, @@ -3120,7 +3054,7 @@ luaL_argcheck *luaL_argcheck()* < luaL_argerror *luaL_argerror()* -> +>c int luaL_argerror (lua_State *L, int narg, const char *extramsg); < Raises an error with the following message, where `func` is retrieved @@ -3132,7 +3066,7 @@ luaL_argerror *luaL_argerror()* functions as `return luaL_argerror(` `args` `)`. luaL_Buffer *luaL_Buffer()* -> +>c typedef struct luaL_Buffer luaL_Buffer; < Type for a `string buffer`. @@ -3142,11 +3076,11 @@ luaL_Buffer *luaL_Buffer()* - First you declare a variable `b` of type `luaL_Buffer`. - Then you initialize it with a call `luaL_buffinit(L, &b)` (see - |luaref-luaL_buffinit|). + |luaL_buffinit()|). - Then you add string pieces to the buffer calling any of the `luaL_add*` functions. - You finish by calling `luaL_pushresult(&b)` (see - |luaref-luaL_pushresult|). This call leaves the final string on the + |luaL_pushresult()|). This call leaves the final string on the top of the stack. During its normal operation, a string buffer uses a variable number of @@ -3156,19 +3090,19 @@ luaL_Buffer *luaL_Buffer()* that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is `luaL_addvalue` - |luaref-luaL_addvalue|.) After calling `luaL_pushresult` the stack is + |luaL_addvalue()|.) After calling `luaL_pushresult` the stack is back to its level when the buffer was initialized, plus the final string on its top. luaL_buffinit *luaL_buffinit()* -> +>c void luaL_buffinit (lua_State *L, luaL_Buffer *B); < Initializes a buffer `B`. This function does not allocate any space; - the buffer must be declared as a variable (see |luaref-luaL_Buffer|). + the buffer must be declared as a variable (see |luaL_Buffer()|). luaL_callmeta *luaL_callmeta()* -> +>c int luaL_callmeta (lua_State *L, int obj, const char *e); < Calls a metamethod. @@ -3181,49 +3115,49 @@ luaL_callmeta *luaL_callmeta()* 0 (without pushing any value on the stack). luaL_checkany *luaL_checkany()* -> +>c void luaL_checkany (lua_State *L, int narg); < Checks whether the function has an argument of any type (including `nil`) at position `narg`. luaL_checkint *luaL_checkint()* -> +>c int luaL_checkint (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns this number cast to an `int`. luaL_checkinteger *luaL_checkinteger()* -> +>c lua_Integer luaL_checkinteger (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns - this number cast to a `lua_Integer` (see |luaref-lua_Integer|). + this number cast to a `lua_Integer` (see |lua_Integer()|). luaL_checklong *luaL_checklong()* -> +>c long luaL_checklong (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns this number cast to a `long`. luaL_checklstring *luaL_checklstring()* -> +>c const char *luaL_checklstring (lua_State *L, int narg, size_t *l); < Checks whether the function argument `narg` is a string and returns this string; if `l` is not `NULL` fills `*l` with the string's length. luaL_checknumber *luaL_checknumber()* -> +>c lua_Number luaL_checknumber (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns - this number (see |luaref-lua_Number|). + this number (see |lua_Number()|). luaL_checkoption *luaL_checkoption()* -> +>c int luaL_checkoption (lua_State *L, int narg, const char *def, @@ -3243,7 +3177,7 @@ luaL_checkoption *luaL_checkoption()* select options.) luaL_checkstack *luaL_checkstack()* -> +>c void luaL_checkstack (lua_State *L, int sz, const char *msg); < Grows the stack size to `top + sz` elements, raising an error if the @@ -3251,53 +3185,53 @@ luaL_checkstack *luaL_checkstack()* the error message. luaL_checkstring *luaL_checkstring()* -> +>c const char *luaL_checkstring (lua_State *L, int narg); < Checks whether the function argument `narg` is a string and returns this string. luaL_checktype *luaL_checktype()* -> +>c void luaL_checktype (lua_State *L, int narg, int t); < Checks whether the function argument `narg` has type `t` (see - |luaref-lua_type|). + |lua_type()|). luaL_checkudata *luaL_checkudata()* -> +>c void *luaL_checkudata (lua_State *L, int narg, const char *tname); < Checks whether the function argument `narg` is a userdata of the type - `tname` (see |luaref-luaL_newmetatable|). + `tname` (see |luaL_newmetatable()|). luaL_dofile *luaL_dofile()* -> +>c int luaL_dofile (lua_State *L, const char *filename); < Loads and runs the given file. It is defined as the following macro: -> +>c (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) < It returns 0 if there are no errors or 1 in case of errors. luaL_dostring *luaL_dostring()* -> +>c int luaL_dostring (lua_State *L, const char *str); < Loads and runs the given string. It is defined as the following macro: -> +>c (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) < It returns 0 if there are no errors or 1 in case of errors. luaL_error *luaL_error()* -> +>c int luaL_error (lua_State *L, const char *fmt, ...); < Raises an error. The error message format is given by `fmt` plus any extra arguments, following the same rules of `lua_pushfstring` (see - |luaref-lua_pushfstring|). It also adds at the beginning of the + |lua_pushfstring()|). It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available. @@ -3305,7 +3239,7 @@ luaL_error *luaL_error()* functions as `return luaL_error(` `args` `)`. luaL_getmetafield *luaL_getmetafield()* -> +>c int luaL_getmetafield (lua_State *L, int obj, const char *e); < Pushes onto the stack the field `e` from the metatable of the object @@ -3313,14 +3247,14 @@ luaL_getmetafield *luaL_getmetafield()* metatable does not have this field, returns 0 and pushes nothing. luaL_getmetatable *luaL_getmetatable()* -> +>c void luaL_getmetatable (lua_State *L, const char *tname); < Pushes onto the stack the metatable associated with name `tname` in - the registry (see |luaref-luaL_newmetatable|). + the registry (see |luaL_newmetatable()|). luaL_gsub *luaL_gsub()* -> +>c const char *luaL_gsub (lua_State *L, const char *s, const char *p, @@ -3331,25 +3265,25 @@ luaL_gsub *luaL_gsub()* returns it. luaL_loadbuffer *luaL_loadbuffer()* -> +>c int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name); < Loads a buffer as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the buffer pointed to by + |lua_load()|) to load the chunk in the buffer pointed to by `buff` with size `sz`. This function returns the same results as `lua_load`. `name` is the chunk name, used for debug information and error messages. luaL_loadfile *luaL_loadfile()* -> +>c int luaL_loadfile (lua_State *L, const char *filename); < Loads a file as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the file named `filename`. If + |lua_load()|) to load the chunk in the file named `filename`. If `filename` is `NULL`, then it loads from the standard input. The first line in the file is ignored if it starts with a `#`. @@ -3359,11 +3293,11 @@ luaL_loadfile *luaL_loadfile()* As `lua_load`, this function only loads the chunk; it does not run it. luaL_loadstring *luaL_loadstring()* -> +>c int luaL_loadstring (lua_State *L, const char *s); < Loads a string as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the zero-terminated string + |lua_load()|) to load the chunk in the zero-terminated string `s`. This function returns the same results as `lua_load`. @@ -3372,7 +3306,7 @@ luaL_loadstring *luaL_loadstring()* run it. luaL_newmetatable *luaL_newmetatable()* -> +>c int luaL_newmetatable (lua_State *L, const char *tname); < If the registry already has the key `tname`, returns 0. Otherwise, @@ -3383,27 +3317,27 @@ luaL_newmetatable *luaL_newmetatable()* `tname` in the registry. luaL_newstate *luaL_newstate()* -> +>c lua_State *luaL_newstate (void); < Creates a new Lua state. It calls `lua_newstate` (see - |luaref-lua_newstate|) with an allocator based on the standard C + |lua_newstate()|) with an allocator based on the standard C `realloc` function and then sets a panic function (see - |luaref-lua_atpanic|) that prints an error message to the standard + |lua_atpanic()|) that prints an error message to the standard error output in case of fatal errors. Returns the new state, or `NULL` if there is a memory allocation error. luaL_openlibs *luaL_openlibs()* -> +>c void luaL_openlibs (lua_State *L); < Opens all standard Lua libraries into the given state. See also |luaref-openlibs| for details on how to open individual libraries. luaL_optint *luaL_optint()* -> +>c int luaL_optint (lua_State *L, int narg, int d); < If the function argument `narg` is a number, returns this number cast @@ -3411,17 +3345,17 @@ luaL_optint *luaL_optint()* Otherwise, raises an error. luaL_optinteger *luaL_optinteger()* -> +>c lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d); < If the function argument `narg` is a number, returns this number cast - to a `lua_Integer` (see |luaref-lua_Integer|). If this argument is + to a `lua_Integer` (see |lua_Integer()|). If this argument is absent or is `nil`, returns `d`. Otherwise, raises an error. luaL_optlong *luaL_optlong()* -> +>c long luaL_optlong (lua_State *L, int narg, long d); < If the function argument `narg` is a number, returns this number cast @@ -3429,7 +3363,7 @@ luaL_optlong *luaL_optlong()* Otherwise, raises an error. luaL_optlstring *luaL_optlstring()* -> +>c const char *luaL_optlstring (lua_State *L, int narg, const char *d, @@ -3442,7 +3376,7 @@ luaL_optlstring *luaL_optlstring()* If `l` is not `NULL`, fills the position `*l` with the results' length. luaL_optnumber *luaL_optnumber()* -> +>c lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d); < If the function argument `narg` is a number, returns this number. If @@ -3450,7 +3384,7 @@ luaL_optnumber *luaL_optnumber()* error. luaL_optstring *luaL_optstring()* -> +>c const char *luaL_optstring (lua_State *L, int narg, const char *d); @@ -3460,24 +3394,24 @@ luaL_optstring *luaL_optstring()* error. luaL_prepbuffer *luaL_prepbuffer()* -> +>c char *luaL_prepbuffer (luaL_Buffer *B); < Returns an address to a space of size `LUAL_BUFFERSIZE` where you can - copy a string to be added to buffer `B` (see |luaref-luaL_Buffer|). + copy a string to be added to buffer `B` (see |luaL_Buffer()|). After copying the string into this space you must call `luaL_addsize` - (see |luaref-luaL_addsize|) with the size of the string to actually + (see |luaL_addsize()|) with the size of the string to actually add it to the buffer. luaL_pushresult *luaL_pushresult()* -> +>c void luaL_pushresult (luaL_Buffer *B); < Finishes the use of buffer `B` leaving the final string on the top of the stack. luaL_ref *luaL_ref()* -> +>c int luaL_ref (lua_State *L, int t); < Creates and returns a `reference`, in the table at index `t`, for the @@ -3486,8 +3420,8 @@ luaL_ref *luaL_ref()* A reference is a unique integer key. As long as you do not manually add integer keys into table `t`, `luaL_ref` ensures the uniqueness of the key it returns. You can retrieve an object referred by reference - `r` by calling `lua_rawgeti(L, t, r)` (see |luaref-lua_rawgeti|). - Function `luaL_unref` (see |luaref-luaL_unref|) frees a reference and + `r` by calling `lua_rawgeti(L, t, r)` (see |lua_rawgeti()|). + Function `luaL_unref` (see |luaL_unref()|) frees a reference and its associated object. If the object at the top of the stack is `nil`, `luaL_ref` returns the @@ -3495,19 +3429,19 @@ luaL_ref *luaL_ref()* different from any reference returned by `luaL_ref`. luaL_Reg *luaL_Reg()* -> +>c typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg; < Type for arrays of functions to be registered by `luaL_register` (see - |luaref-luaL_register|). `name` is the function name and `func` is a + |luaL_register()|). `name` is the function name and `func` is a pointer to the function. Any array of `luaL_Reg` must end with a sentinel entry in which both `name` and `func` are `NULL`. luaL_register *luaL_register()* -> +>c void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l); @@ -3515,7 +3449,7 @@ luaL_register *luaL_register()* Opens a library. When called with `libname` equal to `NULL`, it simply registers all - functions in the list `l` (see |luaref-luaL_Reg|) into the table on + functions in the list `l` (see |luaL_Reg()|) into the table on the top of the stack. When called with a non-null `libname`, `luaL_register` creates a new @@ -3528,13 +3462,13 @@ luaL_register *luaL_register()* In any case the function leaves the table on the top of the stack. luaL_typename *luaL_typename()* -> +>c const char *luaL_typename (lua_State *L, int idx); < Returns the name of the type of the value at index `idx`. luaL_typerror *luaL_typerror()* -> +>c int luaL_typerror (lua_State *L, int narg, const char *tname); < Generates an error with a message like the following: @@ -3543,22 +3477,22 @@ luaL_typerror *luaL_typerror()* `expected, got` `rt` `)` where `location` is produced by `luaL_where` (see - |luaref-luaL_where|), `func` is the name of the current function, and + |luaL_where()|), `func` is the name of the current function, and `rt` is the type name of the actual argument. luaL_unref *luaL_unref()* -> +>c void luaL_unref (lua_State *L, int t, int ref); < Releases reference `ref` from the table at index `t` (see - |luaref-luaL_ref|). The entry is removed from the table, so that the + |luaL_ref()|). The entry is removed from the table, so that the referred object can be collected. The reference `ref` is also freed to be used again. If `ref` is `LUA_NOREF` or `LUA_REFNIL`, `luaL_unref` does nothing. luaL_where *luaL_where()* -> +>c void luaL_where (lua_State *L, int lvl); < Pushes onto the stack a string identifying the current position of the @@ -3574,7 +3508,6 @@ luaL_where *luaL_where()* ============================================================================== 5 STANDARD LIBRARIES *luaref-Lib* -============================================================================== The standard libraries provide useful functions that are implemented directly through the C API. Some of these functions provide essential services to the @@ -3601,14 +3534,14 @@ functions as fields of a global table or as methods of its objects. *luaref-openlibs* To have access to these libraries, the C host program should call the `luaL_openlibs` function, which opens all standard libraries (see -|luaref-luaL_openlibs|). Alternatively, the host program can open the libraries +|luaL_openlibs()|). Alternatively, the host program can open the libraries individually by calling `luaopen_base` (for the basic library), `luaopen_package` (for the package library), `luaopen_string` (for the string library), `luaopen_table` (for the table library), `luaopen_math` (for the mathematical library), `luaopen_io` (for the I/O and the Operating System libraries), and `luaopen_debug` (for the debug library). These functions are declared in `lualib.h` and should not be called directly: you must call them -like any other Lua C function, e.g., by using `lua_call` (see |luaref-lua_call|). +like any other Lua C function, e.g., by using `lua_call` (see |lua_call()|). ============================================================================== 5.1 Basic Functions *luaref-libBasic* @@ -3700,15 +3633,15 @@ load({func} [, {chunkname}]) *luaref-load()* information. loadfile([{filename}]) *luaref-loadfile()* - Similar to `load` (see |luaref-load|), but gets the chunk from file + Similar to `load` (see |luaref-load()|), but gets the chunk from file {filename} or from the standard input, if no file name is given. loadstring({string} [, {chunkname}]) *luaref-loadstring()* - Similar to `load` (see |luaref-load|), but gets the chunk from the + Similar to `load` (see |luaref-load()|), but gets the chunk from the given {string}. To load and run a given string, use the idiom -> +>lua assert(loadstring(s))() < @@ -3724,14 +3657,14 @@ next({table} [, {index}]) *luaref-next()* The order in which the indices are enumerated is not specified, `even for` `numeric indices`. (To traverse a table in numeric order, use a - numerical `for` or the `ipairs` |luaref-ipairs| function.) + numerical `for` or the `ipairs` |luaref-ipairs()| function.) The behavior of `next` is `undefined` if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields. pairs({t}) *luaref-pairs()* - Returns three values: the `next` |luaref-next| function, the table + Returns three values: the `next` |luaref-next()| function, the table {t}, and `nil`, so that the construction `for k,v in pairs(t) do` `body` `end` @@ -3749,10 +3682,10 @@ pcall({f}, {arg1}, {...}) *luaref-pcall()* print({...}) *luaref-print()* Receives any number of arguments, and prints their values to `stdout`, - using the `tostring` |luaref-tostring| function to convert them to + using the `tostring` |luaref-tostring()| function to convert them to strings. `print` is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted - output, use `string.format` (see |luaref-string.format|). + output, use `string.format` (see |string.format()|). rawequal({v1}, {v2}) *luaref-rawequal()* Checks whether {v1} is equal to {v2}, without invoking any metamethod. @@ -3807,7 +3740,7 @@ tonumber({e} [, {base}]) *luaref-tonumber()* tostring({e}) *luaref-tostring()* Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, - use `string.format` (see |luaref-string.format|). + use `string.format` (see |string.format()|). *__tostring* If the metatable of {e} has a `"__tostring"` field, `tostring` calls @@ -3823,7 +3756,7 @@ type({v}) *luaref-type()* unpack({list} [, {i} [, {j}]]) *luaref-unpack()* Returns the elements from the given table. This function is equivalent to -> +>lua return list[i], list[i+1], ..., list[j] < except that the above code can be written only for a fixed number of @@ -3836,7 +3769,7 @@ _VERSION *luaref-_VERSION()* `"Lua 5.1"` . xpcall({f}, {err}) *luaref-xpcall()* - This function is similar to `pcall` (see |luaref-pcall|), except that + This function is similar to `pcall` (see |luaref-pcall()|), except that you can set a new error handler. `xpcall` calls function {f} in protected mode, using {err} as the @@ -3901,7 +3834,7 @@ coroutine.yield({...}) *coroutine.yield()* The package library provides basic facilities for loading and building modules in Lua. It exports two of its functions directly in the global environment: -`require` and `module` (see |luaref-require| and |luaref-module|). Everything else is +`require` and `module` (see |luaref-require()| and |luaref-module()|). Everything else is exported in a table `package`. module({name} [, {...}]) *luaref-module()* @@ -3914,7 +3847,7 @@ module({name} [, {...}]) *luaref-module()* `t._PACKAGE` with the package name (the full module name minus last component; see below). Finally, `module` sets `t` as the new environment of the current function and the new value of - `package.loaded[name]`, so that `require` (see |luaref-require|) + `package.loaded[name]`, so that `require` (see |luaref-require()|) returns `t`. If {name} is a compound name (that is, one with components separated @@ -3968,7 +3901,7 @@ require({modname}) *luaref-require()* If there is any error loading or running the module, or if it cannot find any loader for the module, then `require` signals an error. -package.cpath *package.cpath()* +package.cpath *package.cpath* The path used by `require` to search for a C loader. Lua initializes the C path `package.cpath` in the same way it @@ -3985,7 +3918,7 @@ package.loadlib({libname}, {funcname}) *package.loadlib()* Dynamically links the host program with the C library {libname}. Inside this library, looks for a function {funcname} and returns this function as a C function. (So, {funcname} must follow the protocol - (see |luaref-lua_CFunction|)). + (see |lua_CFunction()|)). This is a low-level function. It completely bypasses the package and module system. Unlike `require`, it does not perform any path @@ -3998,7 +3931,7 @@ package.loadlib({libname}, {funcname}) *package.loadlib()* available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the `dlfcn` standard). -package.path *package.path()* +package.path *package.path* The path used by `require` to search for a Lua loader. At start-up, Lua initializes this variable with the value of the @@ -4019,7 +3952,7 @@ package.path *package.path()* order. package.preload *package.preload()* - A table to store loaders for specific modules (see |luaref-require|). + A table to store loaders for specific modules (see |luaref-require()|). package.seeall({module}) *package.seeall()* Sets a metatable for {module} with its `__index` field referring to @@ -4059,7 +3992,7 @@ string.char({...}) *string.char()* string.dump({function}) *string.dump()* Returns a string containing a binary representation of the given - function, so that a later |luaref-loadstring| on this string returns a + function, so that a later |luaref-loadstring()| on this string returns a copy of the function. {function} must be a Lua function without upvalues. @@ -4088,11 +4021,11 @@ string.format({formatstring}, {...}) *string.format()* interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call -> +>lua string.format('%q', 'a string with "quotes" and \n new line') < will produce the string: -> +>lua "a string with \"quotes\" and \ new line" < @@ -4110,7 +4043,7 @@ string.gmatch({s}, {pattern}) *string.gmatch()* in each call. As an example, the following loop -> +>lua s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) @@ -4119,7 +4052,7 @@ string.gmatch({s}, {pattern}) *string.gmatch()* will iterate over all the words from string {s}, printing one per line. The next example collects all pairs `key=value` from the given string into a table: -> +>lua t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do @@ -4127,7 +4060,7 @@ string.gmatch({s}, {pattern}) *string.gmatch()* end < -string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsu{b}()* +string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsub()* Returns a copy of {s} in which all occurrences of the {pattern} have been replaced by a replacement string specified by {repl}, which may be a string, a table, or a function. `gsub` also returns, as its @@ -4158,7 +4091,7 @@ string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsu{b}()* occurrence of `pattern` is replaced. Here are some examples: -> +>lua x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" @@ -4341,7 +4274,7 @@ table.foreach({table}, {f}) *table.foreach()* returns a non-`nil` value, then the loop is broken, and this value is returned as the final value of `table.foreach`. - See |luaref-next| for extra information about table traversals. + See |luaref-next()| for extra information about table traversals. table.foreachi({table}, {f}) *table.foreachi()* Executes the given {f} over the numerical indices of {table}. For each @@ -4658,7 +4591,7 @@ file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* immediately. `"full"` full buffering; output operation is performed only when the buffer is full (or when you explicitly `flush` the file - (see |luaref-io.flush|). + (see |io.flush()|). `"line"` line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device). @@ -4669,7 +4602,7 @@ file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* file:write({...}) *luaref-file:write()* Writes the value of each of its arguments to `file`. The arguments must be strings or numbers. To write other values, use `tostring` - |luaref-tostring| or `string.format` |luaref-string.format| before + |luaref-tostring()| or `string.format` |string.format()| before `write`. ============================================================================== @@ -4686,7 +4619,7 @@ os.date([{format} [, {time}]]) *os.date()* according to the given string {format}. If the {time} argument is present, this is the time to be formatted - (see the `os.time` function |luaref-os.time| for a description of this + (see the `os.time` function |os.time()| for a description of this value). Otherwise, `date` formats the current time. If {format} starts with `!`, then the date is formatted in @@ -4744,7 +4677,7 @@ os.time([{table}]) *os.time()* representing the date and time specified by the given table. This table must have fields `year`, `month`, and `day`, and may have fields `hour`, `min`, `sec`, and `isdst` (for a description of these fields, - see the `os.date` function |luaref-os.date|). + see the `os.date` function |os.date()|). The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the @@ -4802,7 +4735,7 @@ debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()* functions, then `getinfo` returns `nil`. The returned table may contain all the fields returned by - `lua_getinfo` (see |luaref-lua_getinfo|), with the string {what} + `lua_getinfo` (see |lua_getinfo()|), with the string {what} describing which fields to fill in. The default for {what} is to get all information available, except the table of valid lines. If present, the option `f` adds a field named `func` with the function @@ -4821,7 +4754,7 @@ debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()* last active local variable.) The function returns `nil` if there is no local variable with the given index, and raises an error when called with a {level} out of range. (You can call `debug.getinfo` - |luaref-debug.getinfo| to check whether the level is valid.) + |debug.getinfo()| to check whether the level is valid.) Variable names starting with `(` (open parentheses) represent internal variables (loop control variables, temporaries, and C @@ -4894,12 +4827,11 @@ debug.traceback([{thread},] [{message}] [,{level}]) *debug.traceback()* ============================================================================== A BIBLIOGRAPHY *luaref-bibliography* -============================================================================== This help file is a minor adaptation from this main reference: - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., - "Lua: 5.1 reference manual", http://www.lua.org/manual/5.1/manual.html + "Lua: 5.1 reference manual", https://www.lua.org/manual/5.1/manual.html Lua is discussed in these references: @@ -4920,8 +4852,7 @@ Lua is discussed in these references: "Proc. of V Brazilian Symposium on Programming Languages" (2001) B-14-B-28. ============================================================================== -B COPYRIGHT & LICENSES *luaref-copyright* -============================================================================== +B COPYRIGHT AND LICENSES *luaref-copyright* This help file has the same copyright and license as Lua 5.1 and the Lua 5.1 manual: @@ -4938,29 +4869,28 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. ============================================================================== C LUAREF DOC *luarefvim* *luarefvimdoc* *luaref-help* *luaref-doc* -============================================================================== This is a Vim help file containing a reference for Lua 5.1, and it is -- with a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual (see |luaref-bibliography|). For usage information, refer to -|luaref-docUsage|. For copyright information, see |luaref-copyright|. +|luaref-doc|. For copyright information, see |luaref-copyright|. The main ideas and concepts on how to implement this reference were taken from Christian Habermann's CRefVim project -(http://www.vim.org/scripts/script.php?script_id=614). +(https://www.vim.org/scripts/script.php?script_id=614). Adapted for bundled Nvim documentation; the original plugin can be found at -http://www.vim.org/scripts/script.php?script_id=1291 +https://www.vim.org/scripts/script.php?script_id=1291 ------------------------------------------------------------------------------ vi:tw=78:ts=4:ft=help:norl:et diff --git a/runtime/doc/luvref.txt b/runtime/doc/luvref.txt index ee45444b42..859e75e4af 100644 --- a/runtime/doc/luvref.txt +++ b/runtime/doc/luvref.txt @@ -3,7 +3,7 @@ LUV REFERENCE MANUAL - + *luvref* This file documents the Lua bindings for the LibUV library which is used for Nvim's event-loop and is accessible from Lua via |vim.loop| (e.g., |uv.version()| is exposed as `vim.loop.version()`). @@ -28,7 +28,7 @@ TCP Echo Server Example~ Here is a small example showing a TCP echo server: - > + >lua local uv = vim.loop local server = uv.new_tcp() @@ -97,7 +97,7 @@ used here to facilitate documenting consistent behavior: CONTENTS *luv-contents* This documentation is mostly a retelling of the libuv API documentation -(http://docs.libuv.org/en/v1.x/api.html) within the context of luv's Lua API. +(https://docs.libuv.org/en/v1.x/api.html) within the context of luv's Lua API. Low-level implementation details and unexposed C functions and types are not documented here except for when they are relevant to behavior seen in the Lua module. @@ -250,7 +250,7 @@ uv.loop_configure({option}, {...}) *uv.loop_configure()* An example of a valid call to this function is: - > + >lua uv.loop_configure("block_signal", "sigprof") < @@ -343,7 +343,7 @@ uv.walk({callback}) *uv.walk()* Returns: Nothing. - > + >lua -- Example usage of uv.walk to close all handles that -- aren't already closing. uv.walk(function (handle) @@ -613,7 +613,7 @@ uv.new_timer() *uv.new_timer()* Returns: `uv_timer_t userdata` or `fail` - > + >lua -- Creating a simple setTimeout wrapper local function setTimeout(timeout, callback) local timer = uv.new_timer() @@ -737,7 +737,7 @@ uv.timer_get_due_in({timer}) *uv.timer_get_due_in()* Prepare handles will run the given callback once per loop iteration, right before polling for I/O. - > + >lua local prepare = uv.new_prepare() prepare:start(function() print("Before I/O polling") @@ -782,7 +782,7 @@ uv.prepare_stop({prepare}) *uv.prepare_stop()* Check handles will run the given callback once per loop iteration, right after polling for I/O. - > + >lua local check = uv.new_check() check:start(function() print("After I/O polling") @@ -834,7 +834,7 @@ blocking for I/O. WARNING: Despite the name, idle handles will get their callbacks called on every loop iteration, not when the loop is actually "idle". - > + >lua local idle = uv.new_idle() idle:start(function() print("Before I/O polling, no blocking") @@ -879,7 +879,7 @@ uv.idle_stop({check}) *uv.idle_stop()* Async handles allow the user to "wakeup" the event loop and get a callback called from another thread. - > + >lua local async async = uv.new_async(function() print("async operation ran") @@ -933,7 +933,7 @@ uv.async_send({async}, {...}) *uv.async_send()* Poll handles are used to watch file descriptors for readability and writability, similar to the purpose of poll(2) -(http://linux.die.net/man/2/poll). +(https://linux.die.net/man/2/poll). The purpose of poll handles is to enable integrating external libraries that rely on the event loop to signal it about the socket status changes, like @@ -1062,7 +1062,7 @@ Unix Notes: will lead to unpredictable behavior and is strongly discouraged. Future versions of libuv may simply reject them. - > + >lua -- Create a new signal handler local signal = uv.new_signal() -- Define a handler function @@ -1164,7 +1164,7 @@ uv.spawn({path}, {options}, {on_exit}) *uv.spawn()* permissions to use the setuid or setgid specified, or not having enough memory to allocate for the new process. - > + >lua local stdin = uv.new_pipe() local stdout = uv.new_pipe() local stderr = uv.new_pipe() @@ -1358,7 +1358,7 @@ uv.accept({stream}, {client_stream}) *uv.accept()* Returns: `0` or `fail` - > + >lua server:listen(128, function (err) local client = uv.new_tcp() server:accept(client) @@ -1382,7 +1382,7 @@ uv.read_start({stream}, {callback}) *uv.read_start()* Returns: `0` or `fail` - > + >lua stream:read_start(function (err, chunk) if err then -- handle read error @@ -1690,7 +1690,7 @@ uv.tcp_connect({tcp}, {host}, {port}, {callback}) *uv.tcp_connect()* Returns: `uv_connect_t userdata` or `fail` - > + >lua local client = uv.new_tcp() client:connect("127.0.0.1", 8080, function (err) -- check error and carry on. @@ -1755,7 +1755,7 @@ uv.socketpair([{socktype}, [{protocol}, [{flags1}, [{flags2}]]]]) Returns: `table` or `fail` - `[1, 2]` : `integer` (file descriptor) - > + >lua -- Simple read/write with tcp local fds = uv.socketpair(nil, nil, {nonblock=true}, {nonblock=true}) @@ -1780,7 +1780,7 @@ uv.socketpair([{socktype}, [{protocol}, [{flags1}, [{flags2}]]]]) Pipe handles provide an abstraction over local domain sockets on Unix and named pipes on Windows. - > + >lua local pipe = uv.new_pipe(false) pipe:bind('/tmp/sock.test') @@ -1959,7 +1959,7 @@ uv.pipe({read_flags}, {write_flags}) *uv.pipe()* - `read` : `integer` (file descriptor) - `write` : `integer` (file descriptor) - > + >lua -- Simple read/write with pipe_open local fds = uv.pipe({nonblock=true}, {nonblock=true}) @@ -1983,7 +1983,7 @@ uv.pipe({read_flags}, {write_flags}) *uv.pipe()* TTY handles represent a stream for the console. - > + >lua -- Simple echo program local stdin = uv.new_tty(0, true) local stdout = uv.new_tty(1, false) @@ -2537,7 +2537,7 @@ FS call. Synchronous and asynchronous versions of `readFile` (with naive error handling) are implemented below as an example: - > + >lua local function readFileSync(path) local fd = assert(uv.fs_open(path, "r", 438)) local stat = assert(uv.fs_fstat(fd)) @@ -2550,7 +2550,7 @@ handling) are implemented below as an example: print("synchronous read", data) < - > + >lua local function readFile(path, callback) uv.fs_open(path, "r", 438, function(err, fd) assert(not err, err) @@ -2626,7 +2626,7 @@ uv.fs_read({fd}, {size} [, {offset} [, {callback}]]) *uv.fs_read()* indicates EOF. If `offset` is nil or omitted, it will default to `-1`, which - indicates 'use and update the current file offset.' + indicates "use and update the current file offset." Note: When `offset` is >= 0, the current file offset will not be updated by the read. @@ -2665,7 +2665,7 @@ uv.fs_write({fd}, {data} [, {offset} [, {callback}]]) *uv.fs_write()* written. If `offset` is nil or omitted, it will default to `-1`, which - indicates 'use and update the current file offset.' + indicates "use and update the current file offset." Note: When `offset` is >= 0, the current file offset will not be updated by the write. @@ -3253,7 +3253,7 @@ Libuv provides a threadpool which can be used to run user code and get notified in the loop thread. This threadpool is internally used to run all file system operations, as well as `getaddrinfo` and `getnameinfo` requests. - > + >lua local function work_callback(a, b) return a + b end @@ -3355,7 +3355,7 @@ uv.getnameinfo({address} [, {callback}]) *uv.getnameinfo()* - `family`: `string` or `integer` or `nil` - `callback`: `callable` (async version) or `nil` (sync version) - - `err`: `nil` or `sring` + - `err`: `nil` or `string` - `host`: `string` or `nil` - `service`: `string` or `nil` diff --git a/runtime/doc/makehtml.awk b/runtime/doc/makehtml.awk deleted file mode 100644 index 50f5611fa7..0000000000 --- a/runtime/doc/makehtml.awk +++ /dev/null @@ -1,788 +0,0 @@ -BEGIN { - # some initialization variables - asciiart="no"; - wasset="no"; - lineset=0; - sample="no"; - while ( getline ti <"tags.ref" > 0 ) { - nf=split(ti,tag," "); - # as help.txt renders into index.html and index.txt -> vimindex.html, - # this hack is needed to get the links right to those pages. - if ( tag[2] == "index.txt" ) { - tag[2] = "vimindex.txt" - } else if ( tag[2] == "help.txt" ) { - tag[2] = "index.txt" - } - tagkey[tag[1]]="yes";tagref[tag[1]]=tag[2]; - } - skip_word["and"]="yes"; - skip_word["backspace"]="yes"; - skip_word["beep"]="yes"; - skip_word["bugs"]="yes"; - skip_word["da"]="yes"; - skip_word["end"]="yes"; - skip_word["ftp"]="yes"; - skip_word["go"]="yes"; - skip_word["help"]="yes"; - skip_word["home"]="yes"; - skip_word["news"]="yes"; - skip_word["index"]="yes"; - skip_word["insert"]="yes"; - skip_word["into"]="yes"; - skip_word["put"]="yes"; - skip_word["reference"]="yes"; - skip_word["section"]="yes"; - skip_word["space"]="yes"; - skip_word["starting"]="yes"; - skip_word["toggle"]="yes"; - skip_word["various"]="yes"; - skip_word["version"]="yes"; - skip_word["is"]="yes"; -} -# -# protect special chars -# -/[><&]/ {gsub(/&/,"\\&");gsub(/>/,"\\>");gsub(/</,"\\<");gsub("","\\á");} -# -# end of sample lines by non-blank in first column -# -sample == "yes" && substr($0,1,4) == "<" { sample = "no"; gsub(/^</, " "); } -sample == "yes" && substr($0,1,1) != " " && substr($0,1,1) != " " && length($0) > 0 { sample = "no" } -# -# sample lines printed bold unless empty... -# -sample == "yes" && $0 =="" { print ""; next; } -sample == "yes" && $0 !="" { print "<B>" $0 "</B>"; next; } -# -# start of sample lines in next line -# -$0 == ">" { sample = "yes"; print ""; next; } -substr($0,length($0)-4,5) == " >" { sample = "yes"; gsub(/ >$/, ""); } -# -# header lines printed bold, colored -# -substr($0,length($0),1) == "~" { print "<B><FONT COLOR=\"PURPLE\">" substr($0,1,length($0)-1) "</FONT></B>"; next; } -# -#ad hoc code -# -/^"\|& / {gsub(/\|/,"\\|"); } -/ = b / {gsub(/ b /," \\b "); } -# -# one letter tag -# -/[ ]\*.\*[ ]/ {gsub(/\*/,"ZWWZ"); } -# -# isolated "*" -# -/[ ]\*[ ]/ {gsub(/ \* /," \\* "); - gsub(/ \* /," \\* "); - gsub(/ \* /," \\* "); - gsub(/ \* /," \\* "); } -# -# tag start -# -/[ ]\*[^ ]/ {gsub(/ \*/," ZWWZ");gsub(/ \*/," ZWWZ");} -/^\*[^ ]/ {gsub(/^\*/,"ZWWZ");} -# -# tag end -# -/[^ ]\*$/ {gsub(/\*$/,"ZWWZ");} -/[^ \/ ]\*[ ]/ {gsub(/\*/,"ZWWZ");} -# -# isolated "|" -# -/[ ]\|[ ]/ {gsub(/ \| /," \\| "); - gsub(/ \| /," \\| "); - gsub(/ \| /," \\| "); - gsub(/ \| /," \\| "); } -/'\|'/ { gsub(/'\|'/,"'\\|'"); } -/\^V\|/ {gsub(/\^V\|/,"^V\\|");} -/ \\\| / {gsub(/\|/,"\\|");} -# -# one letter pipes and "||" false pipe (digraphs) -# -/[ ]\|.\|[ ]/ && asciiart == "no" {gsub(/\|/,"YXXY"); } -/^\|.\|[ ]/ {gsub(/\|/,"YXXY"); } -/\|\|/ {gsub(/\|\|/,"\\|\\|"); } -/^shellpipe/ {gsub(/\|/,"\\|"); } -# -# pipe start -# -/[ ]\|[^ ]/ && asciiart == "no" {gsub(/ \|/," YXXY"); - gsub(/ \|/," YXXY");} -/^\|[^ ]/ {gsub(/^\|/,"YXXY");} -# -# pipe end -# -/[^ ]\|$/ && asciiart == "no" {gsub(/\|$/,"YXXY");} -/[^ ]\|[s ,.); ]/ && asciiart == "no" {gsub(/\|/,"YXXY");} -/[^ ]\|]/ && asciiart == "no" {gsub(/\|/,"YXXY");} -# -# various -# -/'"/ {gsub(/'"/,"\\'\\"'");} -/"/ {gsub(/"/,"\\"");} -/%/ {gsub(/%/,"\\%");} - -NR == 1 { nf=split(FILENAME,f,".") - print "<HTML>"; - - print "<HEAD>" - if ( FILENAME == "mbyte.txt" ) { - # needs utf-8 as uses many languages - print "<META HTTP-EQUIV=\"Content-type\" content=\"text/html; charset=UTF-8\">"; - } else { - # common case - Latin1 - print "<META HTTP-EQUIV=\"Content-type\" content=\"text/html; charset=ISO-8859-1\">"; - } - print "<TITLE>Nvim documentation: " f[1] "</TITLE>"; - print "</HEAD>"; - - print "<BODY BGCOLOR=\"#ffffff\">"; - print "<H1>Nvim documentation: " f[1] "</H1>"; - print "<A NAME=\"top\"></A>"; - if ( FILENAME != "help.txt" ) { - print "<A HREF=\"index.html\">main help file</A>\n"; - } - print "<HR>"; - print "<PRE>"; - filename=f[1]".html"; -} - -# set to a low value to test for few lines of text -# NR == 99999 { exit; } - -# ignore underlines and tags -substr($0,1,5) == " vim:" { next; } -substr($0,1,4) == "vim:" { next; } -# keep just whole lines of "-", "=" -substr($0,1,3) == "===" && substr($0,75,1) != "=" { next; } -substr($0,1,3) == "---" && substr($0,75,1) != "-" { next; } - -{ - nstar = split($0,s,"ZWWZ"); - for ( i=2 ; i <= nstar ; i=i+2 ) { - nbla=split(s[i],blata,"[ ]"); - if ( nbla > 1 ) { - gsub("ZWWZ","*"); - nstar = split($0,s,"ZWWZ"); - } - } - npipe = split($0,p,"YXXY"); - for ( i=2 ; i <= npipe ; i=i+2 ) { - nbla=split(p[i],blata,"[ ]"); - if ( nbla > 1 ) { - gsub("YXXY","|"); - ntabs = split($0,p,"YXXY"); - } - } -} - - -FILENAME == "gui.txt" && asciiart == "no" \ - && $0 ~ /\+----/ && $0 ~ /----\+/ { - asciiart= "yes"; - asciicnt=0; - } - -FILENAME == "usr_20.txt" && asciiart == "no" \ - && $0 ~ /an empty line at the end:/ { - asciiart= "yes"; - asciicnt=0; - } - -asciiart == "yes" && $0=="" { asciicnt++; } - -asciiart == "yes" && asciicnt == 2 { asciiart = "no"; } - -asciiart == "yes" { npipe = 1; } -# { print NR " <=> " asciiart; } - -# -# line contains "*" -# -nstar > 2 && npipe < 3 { - printf("\n"); - for ( i=1; i <= nstar ; i=i+2 ) { - this=s[i]; - put_this(); - ii=i+1; - nbla = split(s[ii],blata," "); - if ( ii <= nstar ) { - if ( nbla == 1 && substr(s[ii],length(s[ii]),1) != " " ) { - printf("*<A NAME=\"%s\"></A>",s[ii]); - printf("<B>%s</B>*",s[ii]); - } else { - printf("*%s*",s[ii]); - } - } - } - printf("\n"); - next; - } -# -# line contains "|" -# -npipe > 2 && nstar < 3 { - if ( npipe%2 == 0 ) { - for ( i=1; i < npipe ; i++ ) { - gsub("ZWWZ","*",p[i]); - printf("%s|",p[i]); - } - printf("%s\n",p[npipe]); - next; - } - for ( i=1; i <= npipe ; i++ ) - { - if ( i % 2 == 1 ) { - gsub("ZWWZ","*",p[i]); - this=p[i]; - put_this(); - } - else { - nfn=split(p[i],f,"."); - if ( nfn == 1 || f[2] == "" || f[1] == "" || length(f[2]) < 3 ) { - find_tag1(); - } - else { - if ( f[1] == "index" ) { - printf "|<A HREF=\"vimindex.html\">" p[i] "</A>|"; - } else { - if ( f[1] == "help" ) { - printf "|<A HREF=\"index.html\">" p[i] "</A>|"; - } else { - printf "|<A HREF=\"" f[1] ".html\">" p[i] "</A>|"; - } - } - } - } - } - printf("\n"); - next; - } -# -# line contains both "|" and "*" -# -npipe > 2 && nstar > 2 { - printf("\n"); - for ( j=1; j <= nstar ; j=j+2 ) { - npipe = split(s[j],p,"YXXY"); - if ( npipe > 1 ) { - for ( np=1; np<=npipe; np=np+2 ) { - this=p[np]; - put_this(); - i=np+1;find_tag1(); - } - } else { - this=s[j]; - put_this(); - } - jj=j+1; - nbla = split(s[jj],blata," "); - if ( jj <= nstar && nbla == 1 && s[jj] != "" ) { - printf("*<A NAME=\"%s\"></A>",s[jj]); - printf("<B>%s</B>*",s[jj]); - } else { - if ( s[jj] != "" ) { - printf("*%s*",s[jj]); - } - } - } - printf("\n"); - next; - } -# -# line contains e-mail address john.doe@some.place.edu -# -$0 ~ /@/ && $0 ~ /[a-zA-Z0-9]@[a-z]/ \ - { - nemail=split($0,em," "); - if ( substr($0,1,1) == " " ) { printf(" "); } - for ( i=1; i <= nemail; i++ ) { - if ( em[i] ~ /@/ ) { - if ( substr(em[i],2,3) == "lt;" && substr(em[i],length(em[i])-2,3) == "gt;" ) { - mailaddr=substr(em[i],5,length(em[i])-8); - printf("<A HREF=\"mailto:%s\"><%s></A> ",mailaddr,mailaddr); - } else { - if ( substr(em[i],2,3) == "lt;" && substr(em[i],length(em[i])-3,3) == "gt;" ) { - mailaddr=substr(em[i],5,length(em[i])-9); - printf("<A HREF=\"mailto:%s\"><%s></A>%s ",mailaddr,mailaddr,substr(em[i],length(em[i]),1)); - } else { - printf("<A HREF=\"mailto:%s\">%s</A> ",em[i],em[i]); - } - } - } else { - printf("%s ",em[i]); - } - } - #print "*** " NR " " FILENAME " - possible mail ref"; - printf("\n"); - next; - } -# -# line contains http / ftp reference -# -$0 ~ /http:\/\// || $0 ~ /ftp:\/\// { - gsub("URL:",""); - gsub("<",""); - gsub(">",""); - gsub("\\(",""); - gsub("\\)",""); - nemail=split($0,em," "); - for ( i=1; i <= nemail; i++ ) { - if ( substr(em[i],1,5) == "http:" || - substr(em[i],1,4) == "ftp:" ) { - if ( substr(em[i],length(em[i]),1) != "." ) { - printf(" <A HREF=\"%s\">%s</A>",em[i],em[i]); - } else { - em[i]=substr(em[i],1,length(em[i])-1); - printf(" <A HREF=\"%s\">%s</A>.",em[i],em[i]); - } - } else { - printf(" %s",em[i]); - } - } - #print "*** " NR " " FILENAME " - possible http ref"; - printf("\n"); - next; - } -# -# some lines contains just one "almost regular" "*"... -# -nstar == 2 { - this=s[1]; - put_this(); - printf("*"); - this=s[2]; - put_this(); - printf("\n"); - next; - } -# -# regular line -# - { ntabs = split($0,tb," "); - for ( i=1; i < ntabs ; i++) { - this=tb[i]; - put_this(); - printf(" "); - } - this=tb[ntabs]; - put_this(); - printf("\n"); - } - - -asciiart == "yes" && $0 ~ /\+-\+--/ \ - && $0 ~ "scrollbar" { asciiart = "no"; } - -END { - topback(); - print "</PRE>\n</BODY>\n\n\n</HTML>"; } - -# -# as main we keep index.txt (by default) -# -function topback () { - if ( FILENAME != "tags" ) { - if ( FILENAME != "help.txt" ) { - printf("<A HREF=\"#top\">top</A> - "); - printf("<A HREF=\"index.html\">main help file</A>\n"); - } else { - printf("<A HREF=\"#top\">top</A>\n"); - } - } -} - -function find_tag1() { - if ( p[i] == "" ) { return; } - if ( tagkey[p[i]] == "yes" ) { - which=tagref[p[i]]; - put_href(); - return; - } - # if not found, then we have a problem - print "============================================" >>"errors.log"; - print FILENAME ", line " NR ", pointer: >>" p[i] "<<" >>"errors.log"; - print $0 >>"errors.log"; - which="intro.html"; - put_href(); -} - -function see_tag() { -# ad-hoc code: -if ( atag == "\"--" || atag == "--\"" ) { return; } -if_already(); -if ( already == "yes" ) { - printf("%s",aword); - return; - } -allow_one_char="no"; -find_tag2(); -if ( done == "yes" ) { return; } -rightchar=substr(atag,length(atag),1); -if ( rightchar == "." \ - || rightchar == "," \ - || rightchar == ":" \ - || rightchar == ";" \ - || rightchar == "!" \ - || rightchar == "?" \ - || rightchar == ")" ) { - atag=substr(atag,1,length(atag)-1); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - find_tag2(); - if ( done == "yes" ) { printf("%s",rightchar);return; } - leftchar=substr(atag,1,1); - lastbut1=substr(atag,length(atag),1); - if ( leftchar == "'" && lastbut1 == "'" ) { - allow_one_char="yes"; - atag=substr(atag,2,length(atag)-2); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",leftchar); - aword=substr(atag,1,length(atag))""lastbut1""rightchar; - find_tag2(); - if ( done == "yes" ) { printf("%s%s",lastbut1,rightchar);return; } - } - } -atag=aword; -leftchar=substr(atag,1,1); -if ( leftchar == "'" && rightchar == "'" ) { - allow_one_char="yes"; - atag=substr(atag,2,length(atag)-2); - if ( atag == "<" ) { printf(" |%s|%s| ",atag,p[2]); } - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",leftchar); - find_tag2(); - if ( done == "yes" ) { printf("%s",rightchar);return; } - printf("%s%s",atag,rightchar); - return; - } -last2=substr(atag,length(atag)-1,2); -first2=substr(atag,1,2); -if ( first2 == "('" && last2 == "')" ) { - allow_one_char="yes"; - atag=substr(atag,3,length(atag)-4); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first2); - find_tag2(); - if ( done == "yes" ) { printf("%s",last2);return; } - printf("%s%s",atag,last2); - return; - } -if ( last2 == ".)" ) { - atag=substr(atag,1,length(atag)-2); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - find_tag2(); - if ( done == "yes" ) { printf("%s",last2);return; } - printf("%s%s",atag,last2); - return; - } -if ( last2 == ")." ) { - atag=substr(atag,1,length(atag)-2); - find_tag2(); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - if ( done == "yes" ) { printf("%s",last2);return; } - printf("%s%s",atag,last2); - return; - } -first6=substr(atag,1,6); -last6=substr(atag,length(atag)-5,6); -if ( last6 == atag ) { - printf("%s",aword); - return; - } -last6of7=substr(atag,length(atag)-6,6); -if ( first6 == """ && last6of7 == """ && length(atag) > 12 ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-13); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { printf(""%s",rightchar); return; } - printf("%s"%s",atag,rightchar); - return; - } -if ( first6 == """ && last6 != """ ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-6); - if ( atag == "[" ) { printf(""%s",atag); return; } - if ( atag == "." ) { printf(""%s",atag); return; } - if ( atag == ":" ) { printf(""%s",atag); return; } - if ( atag == "a" ) { printf(""%s",atag); return; } - if ( atag == "A" ) { printf(""%s",atag); return; } - if ( atag == "g" ) { printf(""%s",atag); return; } - if_already(); - if ( already == "yes" ) { - printf(""%s",atag); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { return; } - printf("%s",atag); - return; - } -if ( last6 == """ && first6 == """ ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-12); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { printf("%s",last6);return; } - printf("%s%s",atag,last6); - return; - } -last6of7=substr(atag,length(atag)-6,6); -if ( last6of7 == """ && first6 == """ ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-13); - #printf("\natag=%s,aword=%s\n",atag,aword); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { printf("%s%s",last6of7,rightchar);return; } - printf("%s%s%s",atag,last6of7,rightchar); - return; - } -printf("%s",aword); -} - -function find_tag2() { - done="no"; - # no blanks present in a tag... - ntags=split(atag,blata,"[ ]"); - if ( ntags > 1 ) { return; } - if ( ( allow_one_char == "no" ) && \ - ( index("!#$%&'()+,-./0:;=?@ACINX\\[\\]^_`at\\{\\}~",atag) !=0 ) ) { - return; - } - if ( skip_word[atag] == "yes" ) { return; } - if ( wasset == "yes" && lineset == NR ) { - wasset="no"; - see_opt(); - if ( done_opt == "yes" ) {return;} - } - if ( wasset == "yes" && lineset != NR ) { - wasset="no"; - } - if ( atag == ":set" ) { - wasset="yes"; - lineset=NR; - } - if ( tagkey[atag] == "yes" ) { - which=tagref[atag]; - put_href2(); - done="yes"; - } -} - -function find_tag3() { - done="no"; - # no blanks present in a tag... - ntags=split(btag,blata,"[ ]"); - if ( ntags > 1 ) { return; } - if ( ( allow_one_char == "no" ) && \ - ( index("!#$%&'()+,-./0:;=?@ACINX\\[\\]^_`at\\{\\}~",btag) !=0 ) ) { - return; - } - if ( skip_word[btag] == "yes" ) { return; } - if ( tagkey[btag] == "yes" ) { - which=tagref[btag]; - put_href3(); - done="yes"; - } -} - -function put_href() { - if ( p[i] == "" ) { return; } - if ( which == FILENAME ) { - printf("|<A HREF=\"#%s\">%s</A>|",p[i],p[i]); - } - else { - nz=split(which,zz,"."); - if ( zz[2] == "txt" || zz[1] == "tags" ) { - printf("|<A HREF=\"%s.html#%s\">%s</A>|",zz[1],p[i],p[i]); - } - else { - printf("|<A HREF=\"intro.html#%s\">%s</A>|",p[i],p[i]); - } - } -} - -function put_href2() { - if ( atag == "" ) { return; } - if ( which == FILENAME ) { - printf("<A HREF=\"#%s\">%s</A>",atag,atag); - } - else { - nz=split(which,zz,"."); - if ( zz[2] == "txt" || zz[1] == "tags" ) { - printf("<A HREF=\"%s.html#%s\">%s</A>",zz[1],atag,atag); - } - else { - printf("<A HREF=\"intro.html#%s\">%s</A>",atag,atag); - } - } -} - -function put_href3() { - if ( btag == "" ) { return; } - if ( which == FILENAME ) { - printf("<A HREF=\"#%s\">%s</A>",btag,btag2); - } - else { - nz=split(which,zz,"."); - if ( zz[2] == "txt" || zz[1] == "tags" ) { - printf("<A HREF=\"%s.html#%s\">%s</A>",zz[1],btag,btag2); - } - else { - printf("<A HREF=\"intro.html#%s\">%s</A>",btag,btag2); - } - } -} - -function put_this() { - ntab=split(this,ta," "); - for ( nta=1 ; nta <= ntab ; nta++ ) { - ata=ta[nta]; - lata=length(ata); - aword=""; - for ( iata=1 ; iata <=lata ; iata++ ) { - achar=substr(ata,iata,1); - if ( achar != " " ) { aword=aword""achar; } - else { - if ( aword != "" ) { atag=aword; - see_tag(); - aword=""; - printf(" "); } - else { - printf(" "); - } - } - } - if ( aword != "" ) { atag=aword; - see_tag(); - } - if ( nta != ntab ) { printf(" "); } - } -} - -function if_already() { - already="no"; - if ( npipe < 2 ) { return; } - if ( atag == ":au" && p[2] == ":autocmd" ) { already="yes";return; } - for ( npp=2 ; npp <= npipe ; npp=npp+2 ) { - if ( ( (index(p[npp],atag)) != 0 \ - && length(p[npp]) > length(atag) \ - && length(atag) >= 1 \ - ) \ - || (p[npp] == atag) \ - ) { - # printf("p=|%s|,tag=|%s| ",p[npp],atag); - already="yes"; return; } - } -} - -function see_opt() { - done_opt="no"; - stag=atag; - nfields = split(atag,tae,"="); - if ( nfields > 1 ) { - btag="'"tae[1]"'"; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - for ( ntae=2 ; ntae <= nfields ; ntae++ ) { - printf("=%s",tae[ntae]); - } - atag=stag; - done_opt="yes"; - return; - } - btag=tae[1]; - btag2=tae[1]; - find_tag3(); - if ( done=="yes" ) { - for ( ntae=2 ; ntae <= nfields ; ntae++ ) { - printf("=%s",tae[ntae]); - } - atag=stag; - done_opt="yes"; - return; - } - } - nfields = split(atag,tae,"""); - if ( nfields > 1 ) { - btag="'"tae[1]"'"; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - printf("""); - atag=stag; - done_opt="yes"; - return; - } - btag=tae[1]; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - printf("""); - atag=stag; - done_opt="yes"; - return; - } - } - btag="'"tae[1]"'"; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - atag=stag; - done_opt="yes"; - return; - } - btag=tae[1]; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - atag=stag; - done_opt="yes"; - return; - } - atag=stag; -} diff --git a/runtime/doc/maketags.awk b/runtime/doc/maketags.awk deleted file mode 100644 index c6b2cd91f3..0000000000 --- a/runtime/doc/maketags.awk +++ /dev/null @@ -1,42 +0,0 @@ -BEGIN { FS=" "; } - -NR == 1 { nf=split(FILENAME,f,".") - print "<HTML>"; - print "<HEAD><TITLE>" f[1] "</TITLE></HEAD>"; - print "<BODY BGCOLOR=\"#ffffff\">"; - print "<H1>Vim Documentation: " f[1] "</H1>"; - print "<A NAME=\"top\"></A>"; - print "<HR>"; - print "<PRE>"; -} - -{ - # - # protect special chars - # - gsub(/&/,"\\&"); - gsub(/>/,"\\>"); - gsub(/</,"\\<"); - gsub(/"/,"\\""); - gsub(/%/,"\\%"); - - nf=split($0,tag," "); - tagkey[t]=tag[1];tagref[t]=tag[2];tagnum[t]=NR; - print $1 " " $2 " line " NR >"tags.ref" - n=split($2,w,"."); - printf ("|<A HREF=\"%s.html#%s\">%s</A>| %s\n",w[1],$1,$1,$2); -} - -END { - topback(); - print "</PRE>\n</BODY>\n\n\n</HTML>"; - } - -# -# as main we keep index.txt (by default) -# other candidate, help.txt -# -function topback () { - printf("<A HREF=\"#top\">top</A> - "); - printf("<A HREF=\"help.html\">back to help</A>\n"); -} diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt index ca1ddaabd4..cb8b162eb6 100644 --- a/runtime/doc/map.txt +++ b/runtime/doc/map.txt @@ -215,6 +215,9 @@ The search string will not be echoed when using this mapping. Messages from the executed command are still given though. To shut them up too, add a ":silent" in the executed command: > :map <silent> ,h :exe ":silent normal /Header\r"<CR> +Note that the effect of a command might also be silenced, e.g., when the +mapping selects another entry for command line completion it won't be +displayed. Prompts will still be given, e.g., for inputdialog(). Using "<silent>" for an abbreviation is possible, but will cause redrawing of the command line to fail. @@ -648,6 +651,10 @@ The special key name "<Plug>" can be used for an internal mapping, which is not to be matched with any key sequence. This is useful in plugins |using-<Plug>|. + *<MouseMove>* +The special key name "<MouseMove>" can be used to handle mouse movement. It +needs to be enabled with 'mousemoveevent'. + *<Char>* *<Char->* To map a character by its decimal, octal or hexadecimal number the <Char> construct can be used: @@ -659,9 +666,9 @@ This is useful to specify a (multibyte) character in a 'keymap' file. Upper and lowercase differences are ignored. *map-comments* -It is not possible to put a comment after these commands, because the '"' +It is not possible to put a comment after these commands, because the `"` character is considered to be part of the {lhs} or {rhs}. However, one can -use |", since this starts a new, empty command with a comment. +use `|"`, since this starts a new, empty command with a comment. *map_bar* *map-bar* Since the '|' character is used to separate a map command from the next @@ -691,8 +698,8 @@ To avoid mapping of the characters you type in insert or Command-line mode, type a CTRL-V first. The mapping in Insert mode is disabled if the 'paste' option is on. *map-error* -Note that when an error is encountered (that causes an error message or beep) -the rest of the mapping is not executed. This is Vi-compatible. +Note that when an error is encountered (that causes an error message or might +cause a beep) the rest of the mapping is not executed. This is Vi-compatible. Note that the second character (argument) of the commands @zZtTfF[]rm'`"v and CTRL-X is not mapped. This was done to be able to use all the named @@ -865,28 +872,56 @@ Here is an example that counts the number of spaces with <F4>: > " doubling <F4> works on a line nnoremap <expr> <F4><F4> CountSpaces() .. '_' - function CountSpaces(type = '') abort + function CountSpaces(context = {}, type = '') abort if a:type == '' - set opfunc=CountSpaces + let context = #{ + \ dot_command: v:false, + \ extend_block: '', + \ virtualedit: [&l:virtualedit, &g:virtualedit], + \ } + let &operatorfunc = function('CountSpaces', [context]) + set virtualedit=block return 'g@' endif - let sel_save = &selection - let reg_save = getreginfo('"') - let cb_save = &clipboard - let visual_marks_save = [getpos("'<"), getpos("'>")] + let save = #{ + \ clipboard: &clipboard, + \ selection: &selection, + \ virtualedit: [&l:virtualedit, &g:virtualedit], + \ register: getreginfo('"'), + \ visual_marks: [getpos("'<"), getpos("'>")], + \ } try - set clipboard= selection=inclusive - let commands = #{line: "'[V']y", char: "`[v`]y", block: "`[\<c-v>`]y"} - silent exe 'noautocmd keepjumps normal! ' .. get(commands, a:type, '') - echom count(getreg('"'), ' ') + set clipboard= selection=inclusive virtualedit= + let commands = #{ + \ line: "'[V']", + \ char: "`[v`]", + \ block: "`[\<C-V>`]", + \ }[a:type] + let [_, _, col, off] = getpos("']") + if off != 0 + let vcol = getline("'[")->strpart(0, col + off)->strdisplaywidth() + if vcol >= [line("'["), '$']->virtcol() - 1 + let a:context.extend_block = '$' + else + let a:context.extend_block = vcol .. '|' + endif + endif + if a:context.extend_block != '' + let commands ..= 'oO' .. a:context.extend_block + endif + let commands ..= 'y' + execute 'silent noautocmd keepjumps normal! ' .. commands + echomsg getreg('"')->count(' ') finally - call setreg('"', reg_save) - call setpos("'<", visual_marks_save[0]) - call setpos("'>", visual_marks_save[1]) - let &clipboard = cb_save - let &selection = sel_save + call setreg('"', save.register) + call setpos("'<", save.visual_marks[0]) + call setpos("'>", save.visual_marks[1]) + let &clipboard = save.clipboard + let &selection = save.selection + let [&l:virtualedit, &g:virtualedit] = get(a:context.dot_command ? save : a:context, 'virtualedit') + let a:context.dot_command = v:true endtry endfunction @@ -1336,7 +1371,6 @@ completion can be enabled: -complete=color color schemes -complete=command Ex command (and arguments) -complete=compiler compilers - -complete=cscope |:cscope| suboptions -complete=dir directory names -complete=environment environment variable names -complete=event autocommand events @@ -1398,9 +1432,11 @@ The function arguments are: The function may use these for determining context. For the "custom" argument, it is not necessary to filter candidates against the (implicit pattern in) ArgLead. Vim will filter the candidates with its regexp engine -after function return, and this is probably more efficient in most cases. For -the "customlist" argument, Vim will not filter the returned completion -candidates and the user supplied function should filter the candidates. +after function return, and this is probably more efficient in most cases. If +'wildoptions' contains "fuzzy", then the candidates will be filtered using +|fuzzy-matching|. For the "customlist" argument, Vim will not +filter the returned completion candidates and the user supplied function +should filter the candidates. The following example lists user names to a Finger command > :com -complete=custom,ListUsers -nargs=1 Finger !finger <args> @@ -1437,7 +1473,7 @@ Possible attributes are: number. -count=N A count (default N) which is specified either in the line number position, or as an initial argument (like |:Next|). - Specifying -count (without a default) acts like -count=0 + -count Acts like -count=0 Note that -range=N and -count=N are mutually exclusive - only one should be specified. @@ -1448,14 +1484,16 @@ which by default correspond to the current line, last line and the whole buffer, relate to arguments, (loaded) buffers, windows or tab pages. Possible values are (second column is the short name used in listing): - -addr=lines line Range of lines (this is the default) + -addr=lines Range of lines (this is the default for -range) -addr=arguments arg Range for arguments -addr=buffers buf Range for buffers (also not loaded buffers) -addr=loaded_buffers load Range for loaded buffers -addr=windows win Range for windows -addr=tabs tab Range for tab pages -addr=quickfix qf Range for quickfix entries - -addr=other ? other kind of range + -addr=other ? Other kind of range; can use ".", "$" and "%" + as with "lines" (this is the default for + -count) Incremental preview ~ @@ -1623,11 +1661,11 @@ The valid escape sequences are *<mods>* *<q-mods>* *:command-modifiers* <mods> The command modifiers, if specified. Otherwise, expands to nothing. Supported modifiers are |:aboveleft|, |:belowright|, - |:botright|, |:browse|, |:confirm|, |:hide|, |:keepalt|, - |:keepjumps|, |:keepmarks|, |:keeppatterns|, |:leftabove|, - |:lockmarks|, |:noautocmd|, |:noswapfile| |:rightbelow|, - |:sandbox|, |:silent|, |:tab|, |:topleft|, |:unsilent|, - |:verbose|, and |:vertical|. + |:botright|, |:browse|, |:confirm|, |:hide|, |:horizontal|, + |:keepalt|, |:keepjumps|, |:keepmarks|, |:keeppatterns|, + |:leftabove|, |:lockmarks|, |:noautocmd|, |:noswapfile| + |:rightbelow|, |:sandbox|, |:silent|, |:tab|, |:topleft|, + |:unsilent|, |:verbose|, and |:vertical|. Note that |:filter| is not supported. Examples: > command! -nargs=+ -complete=file MyEdit @@ -1660,7 +1698,8 @@ The valid escape sequences are If the first two characters of an escape sequence are "q-" (for example, <q-args>) then the value is quoted in such a way as to make it a valid value for use in an expression. This uses the argument as one single value. -When there is no argument <q-args> is an empty string. +When there is no argument <q-args> is an empty string. See the +|q-args-example| below. *<f-args>* To allow commands to pass their arguments on to a user-defined function, there is a special form <f-args> ("function args"). This splits the command @@ -1670,10 +1709,10 @@ See the Mycmd example below. If no arguments are given <f-args> is removed. To embed whitespace into an argument of <f-args>, prepend a backslash. <f-args> replaces every pair of backslashes (\\) with one backslash. A backslash followed by a character other than white space or a backslash -remains unmodified. Overview: +remains unmodified. Also see |f-args-example| below. Overview: command <f-args> ~ - XX ab 'ab' + XX ab "ab" XX a\b 'a\b' XX a\ b 'a b' XX a\ b 'a ', 'b' @@ -1684,7 +1723,8 @@ remains unmodified. Overview: XX a\\\\b 'a\\b' XX a\\\\ b 'a\\', 'b' -Examples > + +Examples for user commands: > " Delete everything after here to the end :com Ddel +,$d @@ -1700,7 +1740,8 @@ Examples > " Count the number of lines in the range :com! -range -nargs=0 Lines echo <line2> - <line1> + 1 "lines" - " Call a user function (example of <f-args>) +< *f-args-example* +Call a user function (example of <f-args>) > :com -nargs=* Mycmd call Myfunc(<f-args>) When executed as: > @@ -1708,7 +1749,8 @@ When executed as: > This will invoke: > :call Myfunc("arg1","arg2") - :" A more substantial example +< *q-args-example* +A more substantial example: > :function Allargs(command) : let i = 0 : while i < argc() diff --git a/runtime/doc/mbyte.txt b/runtime/doc/mbyte.txt index 2aa49cee1e..99dfa54218 100644 --- a/runtime/doc/mbyte.txt +++ b/runtime/doc/mbyte.txt @@ -86,9 +86,8 @@ You can also set 'guifont' alone, the Nvim GUI will try to find a matching INPUT There are several ways to enter multibyte characters: -- For X11 XIM can be used. See |XIM|. -- For MS-Windows IME can be used. See |IME|. -- For all systems keymaps can be used. See |mbyte-keymap|. +- Your system IME can be used. +- Keymaps can be used. See |mbyte-keymap|. The options 'iminsert', 'imsearch' and 'imcmdline' can be used to choose the different input methods or disable them temporarily. @@ -335,41 +334,14 @@ Vim will automatically convert from one to another encoding in several places: "utf-8" (requires a gettext version that supports this). - When reading a Vim script where |:scriptencoding| is different from "utf-8". -Most of these require the |+iconv| feature. Conversion for reading and -writing files may also be specified with the 'charconvert' option. +Most of these require iconv. Conversion for reading and writing files may +also be specified with the 'charconvert' option. Useful utilities for converting the charset: All: iconv GNU iconv can convert most encodings. Unicode is used as the intermediate encoding, which allows conversion from and to all other - encodings. See http://www.gnu.org/directory/libiconv.html. - - Japanese: nkf - Nkf is "Network Kanji code conversion Filter". One of the most unique - facility of nkf is the guess of the input Kanji code. So, you don't - need to know what the inputting file's |charset| is. When convert to - EUC-JP from ISO-2022-JP or Shift_JIS, simply do the following command - in Vim: - :%!nkf -e - Nkf can be found at: - http://www.sfc.wide.ad.jp/~max/FreeBSD/ports/distfiles/nkf-1.62.tar.gz - - Chinese: hc - Hc is "Hanzi Converter". Hc convert a GB file to a Big5 file, or Big5 - file to GB file. Hc can be found at: - ftp://ftp.cuhk.hk/pub/chinese/ifcss/software/unix/convert/hc-30.tar.gz - - Korean: hmconv - Hmconv is Korean code conversion utility especially for E-mail. It can - convert between EUC-KR and ISO-2022-KR. Hmconv can be found at: - ftp://ftp.kaist.ac.kr/pub/hangul/code/hmconv/ - - Multilingual: lv - Lv is a Powerful Multilingual File Viewer. And it can be worked as - |charset| converter. Supported |charset|: ISO-2022-CN, ISO-2022-JP, - ISO-2022-KR, EUC-CN, EUC-JP, EUC-KR, EUC-TW, UTF-7, UTF-8, ISO-8859 - series, Shift_JIS, Big5 and HZ. Lv can be found at: - http://www.ff.iij4u.or.jp/~nrt/lv/index.html + encodings. See https://directory.fsf.org/wiki/Libiconv. *mbyte-conversion* @@ -405,17 +377,6 @@ is suitable for complex input, such as CJK. large overhead in communication, but it provides safe synchronization with no restrictions on applications. - For example, there are xwnmo and kinput2 Japanese |IM-server|, both are - FrontEnd system. Xwnmo is distributed with Wnn (see below), kinput2 can be - found at: ftp://ftp.sra.co.jp/pub/x11/kinput2/ - - For Chinese, there's a great XIM server named "xcin", you can input both - Traditional and Simplified Chinese characters. And it can accept other - locale if you make a correct input table. Xcin can be found at: - http://cle.linux.org.tw/xcin/ - Others are scim: http://scim.freedesktop.org/ and fcitx: - http://www.fcitx.org/ - - Conversion Server *conversion-server* Some system needs additional server: conversion server. Most of Japanese @@ -664,7 +625,7 @@ and what the keymaps are to get those characters: glyph encoding keymap ~ Char UTF-8 cp1255 hebrew hebrewp name ~ -א 0x5d0 0xe0 t a 'alef +א 0x5d0 0xe0 t a ´alef ב 0x5d1 0xe1 c b bet ג 0x5d2 0xe2 d g gimel ד 0x5d3 0xe3 s d dalet @@ -745,7 +706,7 @@ Char UTF-8 hebrew name Combining forms: ﬠ 0xfb20 X` Alternative `ayin -ﬡ 0xfb21 X' Alternative 'alef +ﬡ 0xfb21 X' Alternative ´alef ﬢ 0xfb22 X-d Alternative dalet ﬣ 0xfb23 X-h Alternative he ﬤ 0xfb24 X-k Alternative kaf diff --git a/runtime/doc/message.txt b/runtime/doc/message.txt index dac4df5ee9..dffdb5950f 100644 --- a/runtime/doc/message.txt +++ b/runtime/doc/message.txt @@ -573,9 +573,7 @@ when using ":w"), therefore Vim requires using a ! after the command, e.g.: VirtualBinding Messages like this appear when starting up. This is not a Vim problem, your -X11 configuration is wrong. You can find a hint on how to solve this here: -http://groups.yahoo.com/group/solarisonintel/message/12179. -[this URL is no longer valid] +X11 configuration is wrong. *W10* > Warning: Changing a readonly file @@ -603,6 +601,7 @@ probably means that some other program changed the file. You will have to find out what happened, and decide which version of the file you want to keep. Set the 'autoread' option if you want to do this automatically. This message is not given when 'buftype' is not empty. +Also see the |FileChangedShell| autocommand. There is one situation where you get this message even though there is nothing wrong: If you save a file in Windows on the day the daylight saving time @@ -821,7 +820,7 @@ Type effect ~ the clipboard ("* and "+ registers) {menu-entry} what the menu is defined to in Cmdline-mode. - <LeftMouse> (*) next page + <LeftMouse> next page (*) Any other key causes the meaning of the keys to be displayed. diff --git a/runtime/doc/mlang.txt b/runtime/doc/mlang.txt index 9d3a51302d..84b8498d39 100644 --- a/runtime/doc/mlang.txt +++ b/runtime/doc/mlang.txt @@ -92,27 +92,10 @@ use of "-" and "_". :lang mes en < -MS-WINDOWS MESSAGE TRANSLATIONS *win32-gettext* - -If you used the self-installing .exe file, message translations should work -already. Otherwise get the libintl.dll file if you don't have it yet: - - http://sourceforge.net/projects/gettext -Or: - https://mlocati.github.io/gettext-iconv-windows/ - -This also contains tools xgettext, msgformat and others. - -libintl.dll should be placed in same directory as (g)vim.exe, or one of the -directories listed in the PATH environment value. Vim also looks for the -alternate names "libintl-8.dll" and "intl.dll". - Message files (vim.mo) have to be placed in "$VIMRUNTIME/lang/xx/LC_MESSAGES", -where "xx" is the abbreviation of the language (mostly two letters). - -If you write your own translations you need to generate the .po file and -convert it to a .mo file. You need to get the source distribution and read -the file "src/po/README.txt". +where "xx" is the abbreviation of the language (mostly two letters). If you +write your own translations you need to generate the .po file and convert it +to a .mo file. To overrule the automatic choice of the language, set the $LANG variable to the language of your choice. use "en" to disable translations. > diff --git a/runtime/doc/motion.txt b/runtime/doc/motion.txt index 511b1bd7b2..929efee19f 100644 --- a/runtime/doc/motion.txt +++ b/runtime/doc/motion.txt @@ -309,10 +309,10 @@ g<Down> [count] display lines downward. |exclusive| motion. an operator, because it's not linewise. *-* -- <minus> [count] lines upward, on the first non-blank +`-` <minus> [count] lines upward, on the first non-blank character |linewise|. -+ or *+* +`+` or *+* CTRL-M or *CTRL-M* *<CR>* <CR> [count] lines downward, on the first non-blank character |linewise|. @@ -438,9 +438,9 @@ between Vi and Vim. } [count] |paragraph|s forward. |exclusive| motion. *]]* -]] [count] |section|s forward or to the next '{' in the +]] [count] |section|s forward or to the next "{" in the first column. When used after an operator, then also - stops below a '}' in the first column. |exclusive| + stops below a "}" in the first column. |exclusive| Note that |exclusive-linewise| often applies. *][* @@ -449,12 +449,12 @@ between Vi and Vim. Note that |exclusive-linewise| often applies. *[[* -[[ [count] |section|s backward or to the previous '{' in +[[ [count] |section|s backward or to the previous "{" in the first column. |exclusive| Note that |exclusive-linewise| often applies. *[]* -[] [count] |section|s backward or to the previous '}' in +[] [count] |section|s backward or to the previous "}" in the first column. |exclusive| Note that |exclusive-linewise| often applies. @@ -831,12 +831,12 @@ deletes the lines from the cursor position to mark 't'. Hint: Use mark 't' for Top, 'b' for Bottom, etc.. Lowercase marks are restored when using undo and redo. -Uppercase marks 'A to 'Z include the file name. -You can use them to jump from file to file. You can only use an uppercase -mark with an operator if the mark is in the current file. The line number of -the mark remains correct, even if you insert/delete lines or edit another file -for a moment. When the 'shada' option is not empty, uppercase marks are -kept in the .shada file. See |shada-file-marks|. +Uppercase marks 'A to 'Z include the file name. You can use them to jump from +file to file. You can only use an uppercase mark with an operator if the mark +is in the current file. The line number of the mark remains correct, even if +you insert/delete lines or edit another file for a moment. When the 'shada' +option is not empty, uppercase marks are kept in the .shada file. See +|shada-file-marks|. Numbered marks '0 to '9 are quite different. They can not be set directly. They are only present when using a shada file |shada-file|. Basically '0 @@ -1004,8 +1004,8 @@ These commands are not marks themselves, but jump to a mark: Note that ":keepjumps" must be used for every command. When invoking a function the commands in that function can still change the jumplist. Also, for - ":keepjumps exe 'command '" the "command" won't keep - jumps. Instead use: ":exe 'keepjumps command'" + `:keepjumps exe 'command '` the "command" won't keep + jumps. Instead use: `:exe 'keepjumps command'` ============================================================================== 8. Jumps *jump-motions* @@ -1172,7 +1172,7 @@ g; Go to [count] older position in change list. (not a motion command) *g,* *E663* -g, Go to [count] newer cursor position in change list. +g, Go to [count] newer position in change list. Just like |g;| but in the opposite direction. (not a motion command) diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt new file mode 100644 index 0000000000..5c234677ef --- /dev/null +++ b/runtime/doc/news.txt @@ -0,0 +1,194 @@ +*news.txt* Nvim + + + NVIM REFERENCE MANUAL + + +Notable changes in Nvim 0.9 from 0.8 *news* + + Type |gO| to see the table of contents. + +============================================================================== +BREAKING CHANGES *news-breaking* + +The following changes may require adaptations in user config or plugins. + +• Cscope support is now removed (see |cscope| and |nvim-features-removed|): + - Commands removed: + - `:cscope` + - `:lcscope` + - `:scscope` + - `:cstag` + - Options removed: + - `cscopepathcomp` + - `cscopeprg` + - `cscopequickfix` + - `cscoperelative` + - `cscopetag` + - `cscopetagorder` + - `cscopeverbose` + - Eval functions removed: + - `cscope_connection()` + + Note: support for |ctags| remains with no plans to remove. + + See https://github.com/neovim/neovim/pull/20545 for more information. + +• `:hardcopy` is now removed (see |hardcopy| and |nvim-features-removed|): + - Commands removed: + - `:hardcopy` + - Options removed: + - `printdevice` + - `printencoding` + - `printexpr` + - `printfont` + - `printheader` + - `printmbcharset` + +• libiconv is now a required build dependency. + +============================================================================== +NEW FEATURES *news-features* + +The following new APIs or features were added. + +• |nvim_open_win()| now accepts a relative `mouse` option to open a floating win + relative to the mouse. Note that the mouse doesn't update frequently without + setting `vim.o.mousemoveevent = true` + +• EditorConfig support is now builtin. This is enabled by default and happens + automatically. To disable it, users should add >lua + + vim.g.editorconfig = false +< + (or the Vimscript equivalent) to their |config| file. + +• Run Lua scripts from your shell using |-l|. > + nvim -l foo.lua --arg1 --arg2 +< Also works with stdin: > + echo "print(42)" | nvim -l - + +• Added a |vim.lsp.codelens.clear()| function to clear codelenses. + +• |vim.inspect_pos()|, |vim.show_pos()| and |:Inspect| allow a user to get or show items + at a given buffer position. Currently this includes treesitter captures, + semantic tokens, syntax groups and extmarks. + +• Added support for semantic token highlighting to the LSP client. This + functionality is enabled by default when a client that supports this feature + is attached to a buffer. Opt-out can be performed by deleting the + `semanticTokensProvider` from the LSP client's {server_capabilities} in the + `LspAttach` callback. + + See |lsp-semantic_tokens| for more information. + +• |vim.treesitter.show_tree()| opens a split window showing a text + representation of the nodes in a language tree for the current buffer. + +• Added support for the `willSave` and `willSaveWaitUntil` capabilities to the + LSP client. `willSaveWaitUntil` allows a server to modify a document before it + gets saved. Example use-cases by language servers include removing unused + imports, or formatting the file. + +• Treesitter syntax highlighting for `help` files now supports highlighted + code examples. To enable, create a `.config/nvim/ftplugin/help.lua` with + the contents >lua + vim.treesitter.start() +< + Note: Highlighted code examples are only available in the Nvim manual, not + in help files taken from Vim. The treesitter `help` parser is also work in + progress and not guaranteed to correctly highlight every help file in the + wild. + +• |vim.secure.trust()|, |:trust| allows the user to manage files in trust + database. + +• |vim.diagnostic.open_float()| (and therefore |vim.diagnostic.config()|) now + accepts a `suffix` option which, by default, renders LSP error codes. + Similarly, the `virtual_text` configuration in |vim.diagnostic.config()| now + has a `suffix` option which does nothing by default. + +• |vim.fs.dir()| now has a `opts` argument with a depth field to allow + recursively searching a directory tree. + +• |vim.secure.read()| reads a file and prompts the user if it should be + trusted and, if so, returns the file's contents. + +• When using Nvim inside tmux 3.2 or later, the default clipboard provider + will now copy to the system clipboard. |provider-clipboard| + +• |'showcmdloc'| option to display the 'showcmd' information in the + status line or tab line. A new %S statusline item is available to place + the 'showcmd' text in a custom 'statusline'. Useful for when |'cmdheight'| + is set to 0. + +• |'splitkeep'| option to control the scroll behavior of horizontal splits. + +• |'statuscolumn'| option to customize the area to the side of a window, + normally containing the fold, sign and number columns. This new option follows + the 'statusline' syntax and can be used to transform the line numbers, create + mouse click callbacks for |signs|, introduce a custom margin or separator etc. + +• |nvim_select_popupmenu_item()| now supports |cmdline-completion| popup menu. + +• |'diffopt'| now includes a `linematch` option to enable a second-stage diff + on individual hunks to provide much more accurate diffs. This option is also + available to |vim.diff()| + + See https://github.com/neovim/neovim/pull/14537. + +• |vim.diagnostic.is_disabled()| checks if diagnostics are disabled in a given + buffer or namespace. + +• |--remote-ui| option was added to connect to a remote instance and display + in it in a |TUI| in the local terminal. This can be used run a headless nvim + instance in the background and display its UI on demand, which previously + only was possible using an external UI implementation. + +• Several improvements were made to make the code generation scripts more + deterministic, and a `LUA_GEN_PRG` build parameter has been introduced to + allow for a workaround for some remaining reproducibility problems. + +• |:highlight| now supports an additional attribute "altfont". + +============================================================================== +CHANGED FEATURES *news-changes* + +The following changes to existing APIs or features add new behavior. + +• 'exrc' now supports `.nvim.lua` file. +• 'exrc' is no longer marked deprecated. + +• The |TUI| is changed to run in a separate process (previously, a separate + thread was used). This is not supposed to be a visible change to the user, + but might be the cause of subtle changes of behavior and bugs. + + Previously, the TUI could be disabled as a build time feature (+tui/-tui), + resulting in a nvim binary which only could be run headless or embedded + in an external process. As of this version, TUI is always available. + +• API calls now show more information about where an exception happened. + +============================================================================== +REMOVED FEATURES *news-removed* + +The following deprecated functions or APIs were removed. + +• It is no longer possible to scroll the whole screen when showing messages + longer than 'cmdheight'. |msgsep| is now always enabled even if 'display' + doesn't contain the "msgsep" flag. + +• `filetype.vim` is removed in favor of |lua-filetype| + (Note that filetype logic and tests still align with Vim, so additions or + changes need to be contributed there first.) + See https://github.com/neovim/neovim/pull/20674. + +============================================================================== +DEPRECATIONS *news-deprecations* + +The following functions are now deprecated and will be removed in the next +release. + + + + vim:tw=78:ts=8:sw=2:et:ft=help:norl: diff --git a/runtime/doc/nvim.txt b/runtime/doc/nvim.txt index 513d27ccad..ef407922da 100644 --- a/runtime/doc/nvim.txt +++ b/runtime/doc/nvim.txt @@ -1,33 +1,33 @@ *nvim.txt* Nvim - NVIM REFERENCE MANUAL + NVIM REFERENCE MANUAL -Nvim *nvim* *nvim-intro* +Nvim *nvim* *nvim-intro* Nvim is based on Vim by Bram Moolenaar. If you already use Vim see |nvim-from-vim| for a quickstart. -If you are new to Vim, try the 30-minute tutorial: > +If you are new to Vim, try the 30-minute tutorial: >vim :Tutor<Enter> Nvim is emphatically a fork of Vim, not a clone: compatibility with Vim -(especially editor and VimL features) is maintained where possible. See +(especially editor and Vimscript features) is maintained where possible. See |vim-differences| for the complete reference of differences from Vim. - Type |gO| to see the table of contents. + Type |gO| to see the table of contents. ============================================================================== -Transitioning from Vim *nvim-from-vim* +Transitioning from Vim *nvim-from-vim* -1. To start the transition, create your |init.vim| (user config) file: > +1. To start the transition, create your |init.vim| (user config) file: >vim - :call mkdir(stdpath('config'), 'p') :exe 'edit '.stdpath('config').'/init.vim' + :write ++p -2. Add these contents to the file: > +2. Add these contents to the file: >vim set runtimepath^=~/.vim runtimepath+=~/.vim/after let &packpath = &runtimepath @@ -38,32 +38,37 @@ Transitioning from Vim *nvim-from-vim* See |provider-python| and |provider-clipboard| for additional software you might need to use some features. -Your Vim configuration might not be entirely Nvim-compatible. -See |vim-differences| for the full list of changes. - -The |'ttymouse'| option, for example, was removed from Nvim (mouse support -should work without it). If you use the same |vimrc| for Vim and Nvim, -consider guarding |'ttymouse'| in your configuration like so: -> +Your Vim configuration might not be entirely Nvim-compatible (see +|vim-differences|). For example the |'ttymouse'| option was removed from Nvim, +because mouse support is always enabled if possible. If you use the same +|vimrc| for Vim and Nvim you could guard |'ttymouse'| in your configuration +like so: +>vim if !has('nvim') set ttymouse=xterm2 endif -< -Conversely, if you have Nvim specific configuration items, you could do -this: -> + +And for Nvim-specific configuration, you can do this: +>vim if has('nvim') tnoremap <Esc> <C-\><C-n> endif -< + For a more granular approach use |exists()|: -> +>vim if exists(':tnoremap') tnoremap <Esc> <C-\><C-n> endif -< + Now you should be able to explore Nvim more comfortably. Check |nvim-features| for more information. + *portable-config* +Because Nvim follows the XDG |base-directories| standard, configuration on +Windows is stored in ~/AppData instead of ~/.config. But you can still share +the same Nvim configuration on all of your machines, by creating +~/AppData/Local/nvim/init.vim containing just this line: >vim + source ~/.config/nvim/init.vim + ============================================================================== - vim:tw=78:ts=8:noet:ft=help:norl: + vim:tw=78:ts=8:et:ft=help:norl: diff --git a/runtime/doc/nvim_terminal_emulator.txt b/runtime/doc/nvim_terminal_emulator.txt index 546f92e92f..96f99528ed 100644 --- a/runtime/doc/nvim_terminal_emulator.txt +++ b/runtime/doc/nvim_terminal_emulator.txt @@ -27,12 +27,12 @@ There are several ways to create a terminal buffer: - Run the |:terminal| command. - Call the |nvim_open_term()| or |termopen()| function. -- Edit a "term://" buffer. Examples: > +- Edit a "term://" buffer. Examples: >vim :edit term://bash :vsplit term://top < Note: To open a "term://" buffer from an autocmd, the |autocmd-nested| - modifier is required. > + modifier is required. >vim autocmd VimEnter * ++nested split term://sh < (This is only mentioned for reference; use |:terminal| instead.) @@ -62,13 +62,13 @@ Terminal-mode forces these local options: Terminal-mode has its own |:tnoremap| namespace for mappings, this can be used to automate any terminal interaction. -To map <Esc> to exit terminal-mode: > +To map <Esc> to exit terminal-mode: >vim :tnoremap <Esc> <C-\><C-n> -To simulate |i_CTRL-R| in terminal-mode: > +To simulate |i_CTRL-R| in terminal-mode: >vim :tnoremap <expr> <C-R> '<C-\><C-N>"'.nr2char(getchar()).'pi' -To use `ALT+{h,j,k,l}` to navigate windows from any mode: > +To use `ALT+{h,j,k,l}` to navigate windows from any mode: >vim :tnoremap <A-h> <C-\><C-N><C-w>h :tnoremap <A-j> <C-\><C-N><C-w>j :tnoremap <A-k> <C-\><C-N><C-w>k @@ -109,7 +109,7 @@ global configuration. - 'list' is disabled - 'wrap' is disabled -You can change the defaults with a TermOpen autocommand: > +You can change the defaults with a TermOpen autocommand: >vim au TermOpen * setlocal list TERMINAL COLORS ~ @@ -117,7 +117,7 @@ TERMINAL COLORS ~ The `{g,b}:terminal_color_x` variables control the terminal color palette, where `x` is the color index between 0 and 255 inclusive. The variables are read during |TermOpen|. The value must be a color name or hexadecimal string. -Example: > +Example: >vim let g:terminal_color_4 = '#ff0000' let g:terminal_color_5 = 'green' Only works for RGB UIs (see 'termguicolors'); for 256-color terminals the @@ -131,7 +131,7 @@ Status Variables *terminal-status* Terminal buffers maintain some buffer-local variables and options. The values are initialized before TermOpen, so you can use them in a local 'statusline'. -Example: > +Example: >vim :autocmd TermOpen * setlocal statusline=%{b:term_title} - *b:term_title* Terminal title (user-writable), typically displayed in the @@ -141,10 +141,10 @@ Example: > input to the terminal. - The |TermClose| event gives the terminal job exit code in the |v:event| "status" field. For example, this autocmd closes terminal buffers if the job - exited without error: > + exited without error: >vim autocmd TermClose * if !v:event.status | exe 'bdelete! '..expand('<abuf>') | endif -Use |jobwait()| to check if the terminal job has finished: > +Use |jobwait()| to check if the terminal job has finished: >vim let running = jobwait([&channel], 0)[0] == -1 ============================================================================== @@ -156,11 +156,11 @@ Vim this also works remotely over an ssh connection. Starting ~ *termdebug-starting* -Load the plugin with this command: > +Load the plugin with this command: >vim packadd termdebug < *:Termdebug* To start debugging use `:Termdebug` or `:TermdebugCommand` followed by the -command name, for example: > +command name, for example: >vim :Termdebug vim This opens two windows: @@ -189,16 +189,16 @@ Only one debugger can be active at a time. *:TermdebugCommand* If you want to give specific commands to the command being debugged, you can use the `:TermdebugCommand` command followed by the command name and -additional parameters. > +additional parameters. >vim :TermdebugCommand vim --clean -c ':set nu' Both the `:Termdebug` and `:TermdebugCommand` support an optional "!" bang argument to start the command right away, without pausing at the gdb window -(and cursor will be in the debugged window). For example: > +(and cursor will be in the debugged window). For example: >vim :TermdebugCommand! vim --clean To attach gdb to an already running executable or use a core file, pass extra -arguments. E.g.: > +arguments. E.g.: >vim :Termdebug vim core :Termdebug vim 98343 @@ -212,7 +212,7 @@ Start in the Vim "src" directory and build Vim: > % make Start Vim: > % ./vim -Load the termdebug plugin and start debugging Vim: > +Load the termdebug plugin and start debugging Vim: >vim :packadd termdebug :Termdebug vim You should now have three windows: @@ -223,7 +223,7 @@ You should now have three windows: Put focus on the gdb window and type: > break ex_help run -Vim will start running in the program window. Put focus there and type: > +Vim will start running in the program window. Put focus there and type: >vim :help gui Gdb will run into the ex_help breakpoint. The source window now shows the ex_cmds.c file. A red "1 " marker will appear in the signcolumn where the @@ -329,7 +329,7 @@ Other commands ~ Events ~ *termdebug-events* -Four autocommands can be used: > +Four autocommands can be used: >vim au User TermdebugStartPre echomsg 'debugging starting' au User TermdebugStartPost echomsg 'debugging started' au User TermdebugStopPre echomsg 'debugging stopping' @@ -355,6 +355,20 @@ TermdebugStopPost After debugging has ended, gdb-related windows the state before the debugging was restored. +Customizing ~ + *termdebug-customizing* *g:termdebug_config* +In the past several global variables were used for configuration. These are +deprecated and using the g:termdebug_config dictionary is preferred. When +g:termdebug_config exists the other global variables will NOT be used. +The recommended way is to start with an empty dictionary: >vim + let g:termdebug_config = {} + +Then you can add entries to the dictionary as mentioned below. The +deprecated global variable names are mentioned for completeness. If you are +switching over to using g:termdebug_config you can find the old variable name +and take over the value, then delete the deprecated variable. + + Prompt mode ~ *termdebug-prompt* When on MS-Windows, gdb will run in a buffer with 'buftype' set to "prompt". @@ -366,23 +380,23 @@ This works slightly differently: - A separate :terminal window will be opened to run the debugged program in. *termdebug_use_prompt* -Prompt mode can be used with: > +Prompt mode can be used with: >vim let g:termdebug_config['use_prompt'] = 1 -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_use_prompt = 1 < *termdebug_map_K* -The K key is normally mapped to :Evaluate. If you do not want this use: > +The K key is normally mapped to :Evaluate. If you do not want this use: >vim let g:termdebug_config['map_K'] = 0 -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_map_K = 0 < *termdebug_disasm_window* If you want the Asm window shown by default, set the flag to 1. -the "disasm_window_height" entry can be used to set the window height: > +the "disasm_window_height" entry can be used to set the window height: >vim let g:termdebug_config['disasm_window'] = 1 let g:termdebug_config['disasm_window_height'] = 15 -or, if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_disasm_window = 15 Any value greater than 1 will set the Asm window height to that value. @@ -400,45 +414,38 @@ interrupt the running program. But after using the MI command communication channel. -Customizing ~ - *termdebug-customizing* *g:termdebug_config* -In the past several global variables were used for configuration. These are -deprecated, using the g:termdebug_config dictionary is preferred. When -g:termdebug_config exists the other global variables will not be used. - - GDB command ~ *g:termdebugger* To change the name of the gdb command, set "debugger" entry in g:termdebug_config or the "g:termdebugger" variable before invoking -`:Termdebug`: > +`:Termdebug`: >vim let g:termdebug_config['command'] = "mygdb" -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebugger = "mygdb" -If the command needs an argument use a List: > +If the command needs an argument use a List: >vim let g:termdebug_config['command'] = ['rr', 'replay', '--'] -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebugger = ['rr', 'replay', '--'] To not use neovim floating windows for previewing variable evaluation, set the -`g:termdebug_useFloatingHover` variable like this: > +`g:termdebug_useFloatingHover` variable like this: >vim let g:termdebug_useFloatingHover = 0 If you are a mouse person, you can also define a mapping using your right click to one of the terminal command like evaluate the variable under the -cursor: > +cursor: >vim nnoremap <RightMouse> :Evaluate<CR> -or set/unset a breakpoint: > +or set/unset a breakpoint: >vim nnoremap <RightMouse> :Break<CR> Several arguments will be added to make gdb work well for the debugger. -If you want to modify them, add a function to filter the argument list: > +If you want to modify them, add a function to filter the argument list: >vim let g:termdebug_config['command_filter'] = MyDebugFilter If you do not want the arguments to be added, but you do need to set the -"pty", use a function to add the necessary arguments: > +"pty", use a function to add the necessary arguments: >vim let g:termdebug_config['command_add_args'] = MyAddArguments The function will be called with the list of arguments so far, and a second argument that is the name of the pty. @@ -451,7 +458,7 @@ Then your gdb is too old. Colors ~ - *hl-debugPC* *hl-debugBreakpoint* + *hl-debugPC* *hl-debugBreakpoint* The color of the signs can be adjusted with these highlight groups: - debugPC the current position - debugBreakpoint a breakpoint @@ -467,34 +474,31 @@ When 'background' is "dark": Shortcuts ~ *termdebug_shortcuts* - You can define your own shortcuts (mappings) to control gdb, that can work in -any window, using the TermDebugSendCommand() function. Example: > +any window, using the TermDebugSendCommand() function. Example: >vim map ,w :call TermDebugSendCommand('where')<CR> The argument is the gdb command. Popup menu ~ *termdebug_popup* - By default the Termdebug plugin sets 'mousemodel' to "popup_setpos" and adds these entries to the popup menu: Set breakpoint `:Break` Clear breakpoint `:Clear` Evaluate `:Evaluate` -If you don't want this then disable it with: > +If you don't want this then disable it with: >vim let g:termdebug_config['popup'] = 0 -or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_popup = 0 Vim window width ~ *termdebug_wide* - To change the width of the Vim window when debugging starts and use a vertical -split: > +split: >vim let g:termdebug_config['wide'] = 163 -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_wide = 163 This will set 'columns' to 163 when `:Termdebug` is used. The value is diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 2e0c1f8cc4..b1af90a604 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -145,7 +145,7 @@ This sets the 'titlestring' option to "hi" and 'iconstring' to "there": > Similarly, the double quote character starts a comment. To include the '"' in the option value, use '\"' instead. This example sets the 'titlestring' -option to 'hi "there"': > +option to "hi "there"": > :set titlestring=hi\ \"there\" For Win32 backslashes in file names are mostly not removed. More precise: For @@ -163,7 +163,7 @@ halved and when you expect the backslashes to be kept. The third gives a result which is probably not what you want. Avoid it. *add-option-flags* *remove-option-flags* - *E539* *E550* *E551* *E552* + *E539* Some options are a list of flags. When you want to add a flag to such an option, without changing the existing ones, you can do it like this: > :set guioptions+=a @@ -313,14 +313,23 @@ Note: In the future more global options can be made |global-local|. Using *option-value-function* -Some options ('completefunc', 'imactivatefunc', 'imstatusfunc', 'omnifunc', -'operatorfunc', 'quickfixtextfunc' and 'tagfunc') are set to a function name -or a function reference or a lambda function. Examples: +Some options ('completefunc', 'omnifunc', 'operatorfunc', 'quickfixtextfunc', +'tagfunc' and 'thesaurusfunc') are set to a function name or a function +reference or a lambda function. When using a lambda it will be converted to +the name, e.g. "<lambda>123". Examples: > set opfunc=MyOpFunc - set opfunc=function("MyOpFunc") - set opfunc=funcref("MyOpFunc") - set opfunc={t\ ->\ MyOpFunc(t)} + set opfunc=function('MyOpFunc') + set opfunc=funcref('MyOpFunc') + set opfunc={a\ ->\ MyOpFunc(a)} + " set using a funcref variable + let Fn = function('MyTagFunc') + let &tagfunc = Fn + " set using a lambda expression + let &tagfunc = {t -> MyTagFunc(t)} + " set using a variable with lambda expression + let L = {a, b, c -> MyTagFunc(a, b , c)} + let &tagfunc = L < Setting the filetype @@ -440,9 +449,9 @@ se[t] the string "set " or "se " (note the space); When : a colon [text] any text or empty -Examples: - /* vim: set ai tw=75: */ ~ - /* Vim: set ai tw=75: */ ~ +Examples: > + /* vim: set ai tw=75: */ + /* Vim: set ai tw=75: */ The white space before {vi:|vim:|Vim:|ex:} is required. This minimizes the chance that a normal word like "lex:" is caught. There is one exception: @@ -479,10 +488,10 @@ number can be specified where "vim:" or "Vim:" is used: vim={vers}: version {vers} vim>{vers}: version after {vers} {vers} is 700 for Vim 7.0 (hundred times the major version plus minor). -For example, to use a modeline only for Vim 7.0: - /* vim700: set foldmethod=marker */ ~ -To use a modeline for Vim after version 7.2: - /* vim>702: set cole=2: */ ~ +For example, to use a modeline only for Vim 7.0: > + /* vim700: set foldmethod=marker */ +To use a modeline for Vim after version 7.2: > + /* vim>702: set cole=2: */ There can be no blanks between "vim" and the ":". The modeline is ignored if {vers} does not fit in an integer. @@ -491,16 +500,16 @@ The number of lines that are checked can be set with the 'modelines' option. If 'modeline' is off or 'modelines' is 0 no lines are checked. Note that for the first form all of the rest of the line is used, thus a line -like: - /* vi:ts=4: */ ~ -will give an error message for the trailing "*/". This line is OK: - /* vi:set ts=4: */ ~ +like: > + /* vi:ts=4: */ +will give an error message for the trailing "*/". This line is OK: > + /* vi:set ts=4: */ If an error is detected the rest of the line is skipped. If you want to include a ':' in a set command precede it with a '\'. The -backslash in front of the ':' will be removed. Example: - /* vi:set fillchars=stl\:^,vert\:\|: */ ~ +backslash in front of the ':' will be removed. Example: > + /* vi:set fillchars=stl\:^,vert\:\|: */ This sets the 'fillchars' option to "stl:^,vert:\|". Only a single backslash before the ':' is removed. Thus to include "\:" you have to specify "\\:". *E992* @@ -621,7 +630,7 @@ A jump table for the options with a short description can be found at |Q_op|. by Vim with the width of glyphs in the font. Perhaps it also has to be set to "double" under CJK MS-Windows when the system locale is set to one of CJK locales. See Unicode Standard Annex #11 - (http://www.unicode.org/reports/tr11). + (https://www.unicode.org/reports/tr11). *'autochdir'* *'acd'* *'noautochdir'* *'noacd'* 'autochdir' 'acd' boolean (default off) @@ -1053,19 +1062,26 @@ A jump table for the options with a short description can be found at |Q_op|. text should normally be narrower. This prevents text indented almost to the right window border occupying lot of vertical space when broken. + (default: 20) shift:{n} After applying 'breakindent', the wrapped line's beginning will be shifted by the given number of characters. It permits dynamic French paragraph indentation (negative) or emphasizing the line continuation (positive). + (default: 0) sbr Display the 'showbreak' value before applying the additional indent. + (default: off) list:{n} Adds an additional indent for lines that match a numbered or bulleted list (using the 'formatlistpat' setting). list:-1 Uses the length of a match with 'formatlistpat' for indentation. - The default value for min is 20, shift and list is 0. + (default: 0) + column:{n} Indent at column {n}. Will overrule the other + sub-options. Note: an additional indent may be + added for the 'showbreak' setting. + (default: off) *'browsedir'* *'bsdir'* 'browsedir' 'bsdir' string (default: "last") @@ -1309,7 +1325,7 @@ A jump table for the options with a short description can be found at |Q_op|. These names are recognized: *clipboard-unnamed* - unnamed When included, Vim will use the clipboard register '*' + unnamed When included, Vim will use the clipboard register "*" for all yank, delete, change and put operations which would normally go to the unnamed register. When a register is explicitly specified, it will always be @@ -1320,8 +1336,8 @@ A jump table for the options with a short description can be found at |Q_op|. *clipboard-unnamedplus* unnamedplus A variant of the "unnamed" flag which uses the - clipboard register '+' (|quoteplus|) instead of - register '*' for all yank, delete, change and put + clipboard register "+" (|quoteplus|) instead of + register "*" for all yank, delete, change and put operations which would normally go to the unnamed register. When "unnamed" is also included to the option, yank and delete operations (but not put) @@ -1337,9 +1353,14 @@ A jump table for the options with a short description can be found at |Q_op|. page can have a different value. When 'cmdheight' is zero, there is no command-line unless it is being - used. Some informative messages will not be displayed, any other - messages will cause the |hit-enter| prompt. Expect some other - unexpected behavior too. + used. The command-line will cover the last line of the screen when + shown. + + WARNING: `cmdheight=0` is considered experimental. Expect some + unwanted behaviour. Some 'shortmess' flags and similar + mechanism might fail to take effect, causing unwanted hit-enter + prompts. Some informative messages, both from Nvim itself and + plugins, will not be displayed. *'cmdwinheight'* *'cwh'* 'cmdwinheight' 'cwh' number (default 7) @@ -1434,7 +1455,9 @@ A jump table for the options with a short description can be found at |Q_op|. This option specifies a function to be used for Insert mode completion with CTRL-X CTRL-U. |i_CTRL-X_CTRL-U| See |complete-functions| for an explanation of how the function is - invoked and what it should return. + invoked and what it should return. The value can be the name of a + function, a |lambda| or a |Funcref|. See |option-value-function| for + more information. This option cannot be set from a |modeline| or in the |sandbox|, for security reasons. @@ -1787,43 +1810,6 @@ A jump table for the options with a short description can be found at |Q_op|. _ When using |cw| on a word, do not include the whitespace following the word in the motion. - *'cscopepathcomp'* *'cspc'* -'cscopepathcomp' 'cspc' number (default 0) - global - Determines how many components of the path to show in a list of tags. - See |cscopepathcomp|. - - *'cscopeprg'* *'csprg'* -'cscopeprg' 'csprg' string (default "cscope") - global - Specifies the command to execute cscope. See |cscopeprg|. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - - *'cscopequickfix'* *'csqf'* -'cscopequickfix' 'csqf' string (default "") - global - Specifies whether to use quickfix window to show cscope results. - See |cscopequickfix|. - - *'cscoperelative'* *'csre'* *'nocscoperelative'* *'nocsre'* -'cscoperelative' 'csre' boolean (default off) - global - In the absence of a prefix (-P) for cscope. setting this option enables - to use the basename of cscope.out path as the prefix. - See |cscoperelative|. - - *'cscopetag'* *'cst'* *'nocscopetag'* *'nocst'* -'cscopetag' 'cst' boolean (default off) - global - Use cscope for tag commands. See |cscope-options|. - - *'cscopetagorder'* *'csto'* -'cscopetagorder' 'csto' number (default 0) - global - Determines the order in which ":cstag" performs a search. See - |cscopetagorder|. - *'cursorbind'* *'crb'* *'nocursorbind'* *'nocrb'* 'cursorbind' 'crb' boolean (default off) local to window @@ -1904,9 +1890,9 @@ A jump table for the options with a short description can be found at |Q_op|. ^\(#\s*define\|[a-z]*\s*const\s*[a-z]*\) < You can also use "\ze" just before the name and continue the pattern to check what is following. E.g. for Javascript, if a function is - defined with "func_name = function(args)": > + defined with `func_name = function(args)`: > ^\s*\ze\i\+\s*=\s*function( -< If the function is defined with "func_name : function() {...": > +< If the function is defined with `func_name : function() {...`: > ^\s*\ze\i\+\s*[:]\s*(*function\s*( < When using the ":set" command, you need to double the backslashes! To avoid that use `:let` with a single quote string: > @@ -2049,6 +2035,16 @@ A jump table for the options with a short description can be found at |Q_op|. Use the indent heuristic for the internal diff library. + linematch:{n} Enable a second stage diff on each generated + hunk in order to align lines. When the total + number of lines in a hunk exceeds {n}, the + second stage diff will not be performed as + very large hunks can cause noticeable lag. A + recommended setting is "linematch:60", as this + will enable alignment for a 2 buffer diff with + hunks of up to 30 lines each, or a 3 buffer + diff with hunks of up to 20 lines each. + algorithm:{text} Use the specified diff algorithm with the internal diff engine. Currently supported algorithms are: @@ -2123,9 +2119,9 @@ A jump table for the options with a short description can be found at |Q_op|. security reasons. *'display'* *'dy'* -'display' 'dy' string (default "lastline,msgsep") +'display' 'dy' string (default "lastline") global - Change the way text is displayed. This is comma-separated list of + Change the way text is displayed. This is a comma-separated list of flags: lastline When included, as much as possible of the last line in a window will be displayed. "@@@" is put in the @@ -2135,14 +2131,14 @@ A jump table for the options with a short description can be found at |Q_op|. column of the last screen line. Overrules "lastline". uhex Show unprintable characters hexadecimal as <xx> instead of using ^C and ~C. - msgsep When showing messages longer than 'cmdheight', only - scroll the message lines, not the entire screen. The - separator line is decorated by |hl-MsgSeparator| and - the "msgsep" flag of 'fillchars'. + msgsep Obsolete flag. Allowed but takes no effect. |msgsep| When neither "lastline" nor "truncate" is included, a last line that doesn't fit is replaced with "@" lines. + The "@" character can be changed by setting the "lastline" item in + 'fillchars'. The character is highlighted with |hl-NonText|. + *'eadirection'* *'ead'* 'eadirection' 'ead' string (default "both") global @@ -2167,6 +2163,16 @@ A jump table for the options with a short description can be found at |Q_op|. See 'fileencoding' to control file-content encoding. + *'endoffile'* *'eof'* *'noendoffile'* *'noeof'* +'endoffile' 'eof' boolean (default off) + local to buffer + Indicates that a CTRL-Z character was found at the end of the file + when reading it. Normally only happens when 'fileformat' is "dos". + When writing a file and this option is off and the 'binary' option + is on, or 'fixeol' option is off, no CTRL-Z will be written at the + end of the file. + See |eol-and-eof| for example settings. + *'endofline'* *'eol'* *'noendofline'* *'noeol'* 'endofline' 'eol' boolean (default on) local to buffer @@ -2181,6 +2187,7 @@ A jump table for the options with a short description can be found at |Q_op|. to remember the presence of a <EOL> for the last line in the file, so that when you write the file the situation from the original file can be kept. But you can change it if you want to. + See |eol-and-eof| for example settings. *'equalalways'* *'ea'* *'noequalalways'* *'noea'* 'equalalways' 'ea' boolean (default on) @@ -2257,6 +2264,22 @@ A jump table for the options with a short description can be found at |Q_op|. This option is reset when the 'paste' option is set and restored when the 'paste' option is reset. + *'exrc'* *'ex'* *'noexrc'* *'noex'* +'exrc' 'ex' boolean (default off) + global + Enables the reading of .nvim.lua, .nvimrc, and .exrc files in the current + directory. + + The file is only sourced if the user indicates the file is trusted. If + it is, the SHA256 hash of the file contents and the full path of the + file are persisted to a trust database. The user is only prompted + again if the file contents change. See |vim.secure.read()|. + + Use |:trust| to manage the trusted file database. + + This option cannot be set from a |modeline| or in the |sandbox|, for + security reasons. + *'fileencoding'* *'fenc'* *E213* 'fileencoding' 'fenc' string (default: "") local to buffer @@ -2438,13 +2461,13 @@ A jump table for the options with a short description can be found at |Q_op|. this use the ":filetype on" command. |:filetype| Setting this option to a different value is most useful in a modeline, for a file for which the file type is not automatically recognized. - Example, for in an IDL file: - /* vim: set filetype=idl : */ ~ - |FileType| |filetypes| + Example, for in an IDL file: > + /* vim: set filetype=idl : */ +< |FileType| |filetypes| When a dot appears in the value then this separates two filetype - names. Example: - /* vim: set filetype=c.doxygen : */ ~ - This will use the "c" filetype first, then the "doxygen" filetype. + names. Example: > + /* vim: set filetype=c.doxygen : */ +< This will use the "c" filetype first, then the "doxygen" filetype. This works both for filetype plugins and for syntax files. More than one dot may appear. This option is not copied to another buffer, independent of the 's' or @@ -2454,28 +2477,31 @@ A jump table for the options with a short description can be found at |Q_op|. *'fillchars'* *'fcs'* 'fillchars' 'fcs' string (default "") global or local to window |global-local| - Characters to fill the statuslines and vertical separators. - It is a comma-separated list of items: + Characters to fill the statuslines, vertical separators and special + lines in the window. + It is a comma-separated list of items. Each item has a name, a colon + and the value of that item: item default Used for ~ - stl:c ' ' or '^' statusline of the current window - stlnc:c ' ' or '=' statusline of the non-current windows - wbr:c ' ' window bar - horiz:c '─' or '-' horizontal separators |:split| - horizup:c '┴' or '-' upwards facing horizontal separator - horizdown:c '┬' or '-' downwards facing horizontal separator - vert:c '│' or '|' vertical separators |:vsplit| - vertleft:c '┤' or '|' left facing vertical separator - vertright:c '├' or '|' right facing vertical separator - verthoriz:c '┼' or '+' overlapping vertical and horizontal + stl ' ' or '^' statusline of the current window + stlnc ' ' or '=' statusline of the non-current windows + wbr ' ' window bar + horiz '─' or '-' horizontal separators |:split| + horizup '┴' or '-' upwards facing horizontal separator + horizdown '┬' or '-' downwards facing horizontal separator + vert '│' or '|' vertical separators |:vsplit| + vertleft '┤' or '|' left facing vertical separator + vertright '├' or '|' right facing vertical separator + verthoriz '┼' or '+' overlapping vertical and horizontal separator - fold:c '·' or '-' filling 'foldtext' - foldopen:c '-' mark the beginning of a fold - foldclose:c '+' show a closed fold - foldsep:c '│' or '|' open fold middle marker - diff:c '-' deleted lines of the 'diff' option - msgsep:c ' ' message separator 'display' - eob:c '~' empty lines at the end of a buffer + fold '·' or '-' filling 'foldtext' + foldopen '-' mark the beginning of a fold + foldclose '+' show a closed fold + foldsep '│' or '|' open fold middle marker + diff '-' deleted lines of the 'diff' option + msgsep ' ' message separator 'display' + eob '~' empty lines at the end of a buffer + lastline '@' 'display' contains lastline/truncate Any one that is omitted will fall back to the default. For "stl" and "stlnc" the space will be used when there is highlighting, '^' or '=' @@ -2500,29 +2526,31 @@ A jump table for the options with a short description can be found at |Q_op|. The highlighting used for these items: item highlight group ~ - stl:c StatusLine |hl-StatusLine| - stlnc:c StatusLineNC |hl-StatusLineNC| - wbr:c WinBar |hl-WinBar| or |hl-WinBarNC| - horiz:c WinSeparator |hl-WinSeparator| - horizup:c WinSeparator |hl-WinSeparator| - horizdown:c WinSeparator |hl-WinSeparator| - vert:c WinSeparator |hl-WinSeparator| - vertleft:c WinSeparator |hl-WinSeparator| - vertright:c WinSeparator |hl-WinSeparator| - verthoriz:c WinSeparator |hl-WinSeparator| - fold:c Folded |hl-Folded| - diff:c DiffDelete |hl-DiffDelete| - eob:c EndOfBuffer |hl-EndOfBuffer| + stl StatusLine |hl-StatusLine| + stlnc StatusLineNC |hl-StatusLineNC| + wbr WinBar |hl-WinBar| or |hl-WinBarNC| + horiz WinSeparator |hl-WinSeparator| + horizup WinSeparator |hl-WinSeparator| + horizdown WinSeparator |hl-WinSeparator| + vert WinSeparator |hl-WinSeparator| + vertleft WinSeparator |hl-WinSeparator| + vertright WinSeparator |hl-WinSeparator| + verthoriz WinSeparator |hl-WinSeparator| + fold Folded |hl-Folded| + diff DiffDelete |hl-DiffDelete| + eob EndOfBuffer |hl-EndOfBuffer| + lastline NonText |hl-NonText| *'fixendofline'* *'fixeol'* *'nofixendofline'* *'nofixeol'* 'fixendofline' 'fixeol' boolean (default on) local to buffer When writing a file and this option is on, <EOL> at the end of file - will be restored if missing. Turn this option off if you want to + will be restored if missing. Turn this option off if you want to preserve the situation from the original file. When the 'binary' option is set the value of this option doesn't matter. See the 'endofline' option. + See |eol-and-eof| for example settings. *'foldclose'* *'fcl'* 'foldclose' 'fcl' string (default "") @@ -2710,6 +2738,11 @@ A jump table for the options with a short description can be found at |Q_op|. When the expression evaluates to non-zero Vim will fall back to using the internal format mechanism. + If the expression starts with s: or |<SID>|, then it is replaced with + the script ID (|local-function|). Example: > + set formatexpr=s:MyFormatExpr() + set formatexpr=<SID>SomeFormatExpr() +< The expression will be evaluated in the |sandbox| when set from a modeline, see |sandbox-option|. That stops the option from working, since changing the buffer text is not allowed. @@ -3323,13 +3356,22 @@ A jump table for the options with a short description can be found at |Q_op|. local to buffer Expression to be used to transform the string found with the 'include' option to a file name. Mostly useful to change "." to "/" for Java: > - :set includeexpr=substitute(v:fname,'\\.','/','g') + :setlocal includeexpr=substitute(v:fname,'\\.','/','g') < The "v:fname" variable will be set to the file name that was detected. - + Note the double backslash: the `:set` command first halves them, then + one remains in the value, where "\." matches a dot literally. For + simple character replacements `tr()` avoids the need for escaping: > + :setlocal includeexpr=tr(v:fname,'.','/') +< Also used for the |gf| command if an unmodified file name can't be found. Allows doing "gf" on the name after an 'include' statement. Also used for |<cfile>|. + If the expression starts with s: or |<SID>|, then it is replaced with + the script ID (|local-function|). Example: > + set includeexpr=s:MyIncludeExpr(v:fname) + set includeexpr=<SID>SomeIncludeExpr(v:fname) +< The expression will be evaluated in the |sandbox| when set from a modeline, see |sandbox-option|. This option cannot be set in a modeline when 'modelineexpr' is off. @@ -3380,11 +3422,16 @@ A jump table for the options with a short description can be found at |Q_op|. in Insert mode as specified with the 'indentkeys' option. When this option is not empty, it overrules the 'cindent' and 'smartindent' indenting. When 'lisp' is set, this option is - overridden by the Lisp indentation algorithm. + is only used when 'lispoptions' contains "expr:1". When 'paste' is set this option is not used for indenting. The expression is evaluated with |v:lnum| set to the line number for which the indent is to be computed. The cursor is also in this line when the expression is evaluated (but it may be moved around). + If the expression starts with s: or |<SID>|, then it is replaced with + the script ID (|local-function|). Example: > + set indentexpr=s:MyIndentExpr() + set indentexpr=<SID>SomeIndentExpr() +< The expression must return the number of spaces worth of indent. It can return "-1" to keep the current indent (this means 'autoindent' is used for the indent). @@ -3747,6 +3794,17 @@ A jump table for the options with a short description can be found at |Q_op|. calling an external program if 'equalprg' is empty. This option is not used when 'paste' is set. + *'lispoptions'* *'lop'* +'lispoptions' 'lop' string (default "") + local to buffer + Comma-separated list of items that influence the Lisp indenting when + enabled with the |'lisp'| option. Currently only one item is + supported: + expr:1 use 'indentexpr' for Lisp indenting when it is set + expr:0 do not use 'indentexpr' for Lisp indenting (default) + Note that when using 'indentexpr' the `=` operator indents all the + lines, otherwise the first line is not indented (Vi-compatible). + *'lispwords'* *'lw'* 'lispwords' 'lw' string (default is very long) global or local to buffer |global-local| @@ -3785,21 +3843,21 @@ A jump table for the options with a short description can be found at |Q_op|. The third character is optional. tab:xy The 'x' is always used, then 'y' as many times as will - fit. Thus "tab:>-" displays: + fit. Thus "tab:>-" displays: > > >- >-- etc. - +< tab:xyz The 'z' is always used, then 'x' is prepended, and then 'y' is used as many times as will fit. Thus - "tab:<->" displays: + "tab:<->" displays: > > <> <-> <--> etc. - +< When "tab:" is omitted, a tab is shown as ^I. *lcs-space* space:c Character to show for a space. When omitted, spaces @@ -3811,22 +3869,25 @@ A jump table for the options with a short description can be found at |Q_op|. setting, except for single spaces. When omitted, the "space" setting is used. For example, `:set listchars=multispace:---+` shows ten consecutive - spaces as: - ---+---+-- ~ + spaces as: > + ---+---+-- +< *lcs-lead* lead:c Character to show for leading spaces. When omitted, leading spaces are blank. Overrides the "space" and "multispace" settings for leading spaces. You can combine it with "tab:", for example: > :set listchars+=tab:>-,lead:. -< *lcs-leadmultispace* +< + *lcs-leadmultispace* leadmultispace:c... Like the |lcs-multispace| value, but for leading spaces only. Also overrides |lcs-lead| for leading multiple spaces. `:set listchars=leadmultispace:---+` shows ten - consecutive leading spaces as: - ---+---+--XXX ~ + consecutive leading spaces as: > + ---+---+--XXX +< Where "XXX" denotes the first non-blank characters in the line. *lcs-trail* @@ -3911,9 +3972,9 @@ A jump table for the options with a short description can be found at |Q_op|. `:lgrepadd`, `:cfile`, `:cgetfile`, `:caddfile`, `:lfile`, `:lgetfile`, and `:laddfile`. - This would be mostly useful when you use MS-Windows. If |+iconv| is - enabled and GNU libiconv is used, setting 'makeencoding' to "char" has - the same effect as setting to the system locale encoding. Example: > + This would be mostly useful when you use MS-Windows. If iconv is + enabled, setting 'makeencoding' to "char" has the same effect as + setting to the system locale encoding. Example: > :set makeencoding=char " system locale is used < *'makeprg'* *'mp'* @@ -4065,7 +4126,8 @@ A jump table for the options with a short description can be found at |Q_op|. checked for set commands. If 'modeline' is off or 'modelines' is zero no lines are checked. See |modeline|. - *'modifiable'* *'ma'* *'nomodifiable'* *'noma'* *E21* + *'modifiable'* *'ma'* *'nomodifiable'* *'noma'* + *E21* 'modifiable' 'ma' boolean (default on) local to buffer When off the buffer contents cannot be changed. The 'fileformat' and @@ -4229,6 +4291,15 @@ A jump table for the options with a short description can be found at |Q_op|. The 'mousemodel' option is set by the |:behave| command. + *'mousemoveevent'* *'mousemev'* +'mousemoveevent' 'mousemev' boolean (default off) + global + When on, mouse move events are delivered to the input queue and are + available for mapping. The default, off, avoids the mouse movement + overhead except when needed. + Warning: Setting this option can make pending mappings to be aborted + when the mouse is moved. + *'mousescroll'* 'mousescroll' string (default "ver:3,hor:6") global @@ -4289,7 +4360,7 @@ A jump table for the options with a short description can be found at |Q_op|. w x updown up-down sizing arrows w x leftright left-right sizing arrows w x busy The system's usual busy pointer - w x no The system's usual 'no input' pointer + w x no The system's usual "no input" pointer x udsizing indicates up-down resizing x lrsizing indicates left-right resizing x crosshair like a big thin + @@ -4366,12 +4437,12 @@ A jump table for the options with a short description can be found at |Q_op|. 'nonu' 'nu' 'nonu' 'nu' 'nornu' 'nornu' 'rnu' 'rnu' - +> |apple | 1 apple | 2 apple | 2 apple |pear | 2 pear | 1 pear | 1 pear |nobody | 3 nobody | 0 nobody |3 nobody |there | 4 there | 1 there | 1 there - +< *'numberwidth'* *'nuw'* 'numberwidth' 'nuw' number (default: 4) local to window @@ -4392,7 +4463,9 @@ A jump table for the options with a short description can be found at |Q_op|. This option specifies a function to be used for Insert mode omni completion with CTRL-X CTRL-O. |i_CTRL-X_CTRL-O| See |complete-functions| for an explanation of how the function is - invoked and what it should return. + invoked and what it should return. The value can be the name of a + function, a |lambda| or a |Funcref|. See |option-value-function| for + more information. This option is usually set by a filetype plugin: |:filetype-plugin-on| This option cannot be set from a |modeline| or in the |sandbox|, for @@ -4555,7 +4628,7 @@ A jump table for the options with a short description can be found at |Q_op|. < - A directory name may end in a ':' or '/'. - Environment variables are expanded |:set_env|. - When using |netrw.vim| URLs can be used. For example, adding - "http://www.vim.org" will make ":find index.html" work. + "https://www.vim.org" will make ":find index.html" work. - Search upwards and downwards in a directory tree using "*", "**" and ";". See |file-searching| for info and syntax. - Careful with '\' characters, type two to get one in the option: > @@ -4611,58 +4684,6 @@ A jump table for the options with a short description can be found at |Q_op|. set. It's normally not set directly, but by using one of the commands |:ptag|, |:pedit|, etc. - *'printdevice'* *'pdev'* -'printdevice' 'pdev' string (default empty) - global - The name of the printer to be used for |:hardcopy|. - See |pdev-option|. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - - *'printencoding'* *'penc'* -'printencoding' 'penc' string (default empty, except for some systems) - global - Sets the character encoding used when printing. - See |penc-option|. - - *'printexpr'* *'pexpr'* -'printexpr' 'pexpr' string (default: see below) - global - Expression used to print the PostScript produced with |:hardcopy|. - See |pexpr-option|. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - - *'printfont'* *'pfn'* -'printfont' 'pfn' string (default "courier") - global - The name of the font that will be used for |:hardcopy|. - See |pfn-option|. - - *'printheader'* *'pheader'* -'printheader' 'pheader' string (default "%<%f%h%m%=Page %N") - global - The format of the header produced in |:hardcopy| output. - See |pheader-option|. - - *'printmbcharset'* *'pmbcs'* -'printmbcharset' 'pmbcs' string (default "") - global - The CJK character set to be used for CJK output from |:hardcopy|. - See |pmbcs-option|. - - *'printmbfont'* *'pmbfn'* -'printmbfont' 'pmbfn' string (default "") - global - List of font names to be used for CJK output from |:hardcopy|. - See |pmbfn-option|. - - *'printoptions'* *'popt'* -'printoptions' 'popt' string (default "") - global - List of items that control the format of the output of |:hardcopy|. - See |popt-option|. - *'pumblend'* *'pb'* 'pumblend' 'pb' number (default 0) global @@ -4920,8 +4941,7 @@ A jump table for the options with a short description can be found at |Q_op|. $XDG_CONFIG_HOME/nvim/after") global List of directories to be searched for these runtime files: - filetype.vim filetypes by file name |new-filetype| - scripts.vim filetypes by file contents |new-filetype-scripts| + filetype.lua filetypes |new-filetype| autoload/ automatically loaded scripts |autoload-functions| colors/ color scheme files |:colorscheme| compiler/ compiler files |:compiler| @@ -4930,10 +4950,12 @@ A jump table for the options with a short description can be found at |Q_op|. indent/ indent scripts |indent-expression| keymap/ key mapping files |mbyte-keymap| lang/ menu translations |:menutrans| + lua/ |Lua| plugins menu.vim GUI menus |menu.vim| pack/ packages |:packadd| + parser/ |treesitter| syntax parsers plugin/ plugin scripts |write-plugin| - print/ files for printing |postscript-print-encoding| + query/ |treesitter| queries rplugin/ |remote-plugin| scripts spell/ spell checking files |spell| syntax/ syntax files |mysyntaxfile| @@ -4954,20 +4976,20 @@ A jump table for the options with a short description can be found at |Q_op|. but are not part of the Nvim distribution. XDG_DATA_DIRS defaults to /usr/local/share/:/usr/share/, so system administrators are expected to install site plugins to /usr/share/nvim/site. - 5. Applications state home directory, for files that contain your - session state (eg. backupdir, viewdir, undodir, etc). + 5. Session state directory, for state data such as swap, backupdir, + viewdir, undodir, etc. Given by `stdpath("state")`. |$XDG_STATE_HOME| - 6. $VIMRUNTIME, for files distributed with Neovim. + 6. $VIMRUNTIME, for files distributed with Nvim. *after-directory* 7, 8, 9, 10. In after/ subdirectories of 1, 2, 3 and 4, with reverse - ordering. This is for preferences to overrule or add to the + ordering. This is for preferences to overrule or add to the distributed defaults or system-wide settings (rarely needed). - *rtp-packages* - "start" packages will additionally be used to search for runtime files - after these, but package entries are not visible in `:set rtp`. - See |runtime-search-path| for more information. "opt" packages - will be explicitly added to &rtp when |:packadd| is used. + *packages-runtimepath* + "start" packages will also be searched (|runtime-search-path|) for + runtime files after these, though such packages are not explicitly + reported in &runtimepath. But "opt" packages are explicitly added to + &runtimepath by |:packadd|. Note that, unlike 'path', no wildcards like "**" are allowed. Normal wildcards are allowed, but can significantly slow down searching for @@ -4977,18 +4999,13 @@ A jump table for the options with a short description can be found at |Q_op|. Example: > :set runtimepath=~/vimruntime,/mygroup/vim,$VIMRUNTIME < This will use the directory "~/vimruntime" first (containing your - personal Vim runtime files), then "/mygroup/vim" (shared between a - group of people) and finally "$VIMRUNTIME" (the distributed runtime - files). - You probably should always include $VIMRUNTIME somewhere, to use the - distributed runtime files. You can put a directory before $VIMRUNTIME - to find files which replace a distributed runtime files. You can put - a directory after $VIMRUNTIME to find files which add to distributed - runtime files. - When Vim is started with |--clean| the home directory entries are not - included. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. + personal Nvim runtime files), then "/mygroup/vim", and finally + "$VIMRUNTIME" (the default runtime files). + You can put a directory before $VIMRUNTIME to find files which replace + distributed runtime files. You can put a directory after $VIMRUNTIME + to find files which add to distributed runtime files. + + With |--clean| the home directory entries are not included. *'scroll'* *'scr'* 'scroll' 'scr' number (default: half the window height) @@ -5084,19 +5101,6 @@ A jump table for the options with a short description can be found at |Q_op|. two letters (See |object-motions|). The default makes a section start at the nroff macros ".SH", ".NH", ".H", ".HU", ".nh" and ".sh". - *'secure'* *'nosecure'* *E523* -'secure' boolean (default off) - global - When on, ":autocmd", shell and write commands are not allowed in - ".nvimrc" and ".exrc" in the current directory and map commands are - displayed. Switch it off only if you know that you will not run into - problems, or when the 'exrc' option is off. On Unix this option is - only used if the ".nvimrc" or ".exrc" is not owned by you. This can be - dangerous if the systems allows users to do a "chown". You better set - 'secure' at the end of your |init.vim| then. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - *'selection'* *'sel'* 'selection' 'sel' string (default "inclusive") global @@ -5341,7 +5345,7 @@ A jump table for the options with a short description can be found at |Q_op|. To use PowerShell: > let &shell = executable('pwsh') ? 'pwsh' : 'powershell' let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;' - let &shellredir = '-RedirectStandardOutput %s -NoNewWindow -Wait' + let &shellredir = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' let &shellpipe = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' set shellquote= shellxquote= @@ -5509,42 +5513,48 @@ A jump table for the options with a short description can be found at |Q_op|. messages, for example with CTRL-G, and to avoid some other messages. It is a list of flags: flag meaning when present ~ - f use "(3 of 5)" instead of "(file 3 of 5)" - i use "[noeol]" instead of "[Incomplete last line]" - l use "999L, 888B" instead of "999 lines, 888 bytes" - m use "[+]" instead of "[Modified]" - n use "[New]" instead of "[New File]" - r use "[RO]" instead of "[readonly]" - w use "[w]" instead of "written" for file write message + f use "(3 of 5)" instead of "(file 3 of 5)" *shm-f* + i use "[noeol]" instead of "[Incomplete last line]" *shm-i* + l use "999L, 888B" instead of "999 lines, 888 bytes" *shm-l* + m use "[+]" instead of "[Modified]" *shm-m* + n use "[New]" instead of "[New File]" *shm-n* + r use "[RO]" instead of "[readonly]" *shm-r* + w use "[w]" instead of "written" for file write message *shm-w* and "[a]" instead of "appended" for ':w >> file' command - x use "[dos]" instead of "[dos format]", "[unix]" instead of - "[unix format]" and "[mac]" instead of "[mac format]". - a all of the above abbreviations - - o overwrite message for writing a file with subsequent message - for reading a file (useful for ":wn" or when 'autowrite' on) - O message for reading a file overwrites any previous message. - Also for quickfix message (e.g., ":cn"). - s don't give "search hit BOTTOM, continuing at TOP" or "search - hit TOP, continuing at BOTTOM" messages; when using the search - count do not show "W" after the count message (see S below) - t truncate file message at the start if it is too long to fit - on the command-line, "<" will appear in the left most column. - Ignored in Ex mode. - T truncate other messages in the middle if they are too long to - fit on the command line. "..." will appear in the middle. - Ignored in Ex mode. - W don't give "written" or "[w]" when writing a file - A don't give the "ATTENTION" message when an existing swap file - is found. - I don't give the intro message when starting Vim |:intro|. - c don't give |ins-completion-menu| messages. For example, - "-- XXX completion (YYY)", "match 1 of 2", "The only match", - "Pattern not found", "Back at original", etc. - q use "recording" instead of "recording @a" - F don't give the file info when editing a file, like `:silent` - was used for the command - S do not show search count message when searching, e.g. + x use "[dos]" instead of "[dos format]", "[unix]" *shm-x* + instead of "[unix format]" and "[mac]" instead of "[mac + format]" + a all of the above abbreviations *shm-a* + + o overwrite message for writing a file with subsequent *shm-o* + message for reading a file (useful for ":wn" or when + 'autowrite' on) + O message for reading a file overwrites any previous *shm-O* + message; also for quickfix message (e.g., ":cn") + s don't give "search hit BOTTOM, continuing at TOP" or *shm-s* + "search hit TOP, continuing at BOTTOM" messages; when using + the search count do not show "W" after the count message (see + S below) + t truncate file message at the start if it is too long *shm-t* + to fit on the command-line, "<" will appear in the left most + column; ignored in Ex mode + T truncate other messages in the middle if they are too *shm-T* + long to fit on the command line; "..." will appear in the + middle; ignored in Ex mode + W don't give "written" or "[w]" when writing a file *shm-W* + A don't give the "ATTENTION" message when an existing *shm-A* + swap file is found + I don't give the intro message when starting Vim, *shm-I* + see |:intro| + c don't give |ins-completion-menu| messages; for *shm-c* + example, "-- XXX completion (YYY)", "match 1 of 2", "The only + match", "Pattern not found", "Back at original", etc. + C don't give messages while scanning for ins-completion *shm-C* + items, for instance "scanning tags" + q use "recording" instead of "recording @a" *shm-q* + F don't give the file info when editing a file, like *shm-F* + `:silent` was used for the command + S do not show search count message when searching, e.g. *shm-S* "[1/5]" This gives you the opportunity to avoid that a change between buffers @@ -5581,7 +5591,6 @@ A jump table for the options with a short description can be found at |Q_op|. global Show (partial) command in the last line of the screen. Set this option off if your terminal is slow. - The option has no effect when 'cmdheight' is zero. In Visual mode the size of the selected area is shown: - When selecting characters within a line, the number of characters. If the number of bytes is different it is also displayed: "2-6" @@ -5589,6 +5598,23 @@ A jump table for the options with a short description can be found at |Q_op|. - When selecting more than one line, the number of lines. - When selecting a block, the size in screen characters: {lines}x{columns}. + This information can be displayed in an alternative location using the + 'showcmdloc' option, useful when 'cmdheight' is 0. + + *'showcmdloc'* *'sloc'* +'showcmdloc' 'sloc' string (default "last") + global + This option can be used to display the (partially) entered command in + another location. Possible values are: + last Last line of the screen (default). + statusline Status line of the current window. + tabline First line of the screen if 'showtabline' is enabled. + Setting this option to "statusline" or "tabline" means that these will + be redrawn whenever the command changes, which can be on every key + pressed. + The %S 'statusline' item can be used in 'statusline' or 'tabline' to + place the text. Without a custom 'statusline' or 'tabline' it will be + displayed in a convenient location. *'showfulltag'* *'sft'* *'noshowfulltag'* *'nosft'* 'showfulltag' 'sft' boolean (default off) @@ -5692,9 +5718,9 @@ A jump table for the options with a short description can be found at |Q_op|. "yes:[1-9]" always, with fixed space for signs up to the given number (maximum 9), e.g. "yes:3" "number" display signs in the 'number' column. If the number - column is not present, then behaves like 'auto'. + column is not present, then behaves like "auto". - Note regarding 'orphaned signs': with signcolumn numbers higher than + Note regarding "orphaned signs": with signcolumn numbers higher than 1, deleting lines will also remove the associated signs automatically, in contrast to the default Vim behavior of keeping and grouping them. This is done in order for the signcolumn appearance not appear weird @@ -5722,11 +5748,11 @@ A jump table for the options with a short description can be found at |Q_op|. alternative. Normally 'autoindent' should also be on when using 'smartindent'. An indent is automatically inserted: - - After a line ending in '{'. + - After a line ending in "{". - After a line starting with a keyword from 'cinwords'. - - Before a line starting with '}' (only with the "O" command). + - Before a line starting with "}" (only with the "O" command). When typing '}' as the first character in a new line, that line is - given the same indent as the matching '{'. + given the same indent as the matching "{". When typing '#' as the first character in a new line, the indent for that line is removed, the '#' is put in the first column. The indent is restored for the next line. If you don't want this, use this @@ -5860,10 +5886,14 @@ A jump table for the options with a short description can be found at |Q_op|. 'spelloptions' 'spo' string (default "") local to buffer A comma-separated list of options for spell checking: - camel When a word is CamelCased, assume "Cased" is a + camel When a word is CamelCased, assume "Cased" is a separate word: every upper-case character in a word that comes after a lower case character indicates the start of a new word. + noplainbuffer Only spellcheck a buffer when 'syntax' is enabled, + or when extmarks are set within the buffer. Only + designated regions of the buffer are spellchecked in + this case. *'spellsuggest'* *'sps'* 'spellsuggest' 'sps' string (default "best") @@ -5939,6 +5969,22 @@ A jump table for the options with a short description can be found at |Q_op|. When on, splitting a window will put the new window below the current one. |:split| + *'splitkeep'* *'spk'* +'splitkeep' 'spk' string (default "cursor") + global + The value of this option determines the scroll behavior when opening, + closing or resizing horizontal splits. + + Possible values are: + cursor Keep the same relative cursor position. + screen Keep the text on the same screen line. + topline Keep the topline the same. + + For the "screen" and "topline" values, the cursor position will be + changed when necessary. In this case, the jumplist will be populated + with the previous cursor position. For "screen", the text cannot always + be kept on the same screen line when 'wrap' is enabled. + *'splitright'* *'spr'* *'nosplitright'* *'nospr'* 'splitright' 'spr' boolean (default off) global @@ -5958,6 +6004,60 @@ A jump table for the options with a short description can be found at |Q_op|. In case of buffer changing commands the cursor is placed at the column where it was the last time the buffer was edited. + *'statuscolumn'* *'stc'* +'statuscolumn' 'stc' string (default: empty) + local to window + EXPERIMENTAL + When non-empty, this option determines the content of the area to the + side of a window, normally containing the fold, sign and number columns. + The format of this option is like that of 'statusline'. + + Some of the items from the 'statusline' format are different for + 'statuscolumn': + + %l line number of currently drawn line + %r relative line number of currently drawn line + %s sign column for currently drawn line + %C fold column for currently drawn line + + NOTE: To draw the sign and fold columns, their items must be included in + 'statuscolumn'. Even when they are not included, the status column width + will adapt to the 'signcolumn' and 'foldcolumn' width. + + The |v:lnum| variable holds the line number to be drawn. + The |v:relnum| variable holds the relative line number to be drawn. + The |v:virtnum| variable is negative when drawing virtual lines, zero + when drawing the actual buffer line, and positive when + drawing the wrapped part of a buffer line. + + NOTE: The %@ click execute function item is supported as well but the + specified function will be the same for each row in the same column. + It cannot be switched out through a dynamic 'statuscolumn' format, the + handler should be written with this in mind. + + Examples: >vim + " Relative number with bar separator and click handlers: + :set statuscolumn=%@SignCb@%s%=%T%@NumCb@%r│%T + + " Right aligned relative cursor line number: + :let &stc='%=%{v:relnum?v:relnum:v:lnum} ' + + " Line numbers in hexadecimal for non wrapped part of lines: + :let &stc='%=%{v:virtnum>0?"":printf("%x",v:lnum)} ' + + " Human readable line numbers with thousands separator: + :let &stc='%{substitute(v:lnum,"\\d\\zs\\ze\\' + . '%(\\d\\d\\d\\)\\+$",",","g")}' + + " Both relative and absolute line numbers with different + " highlighting for odd and even relative numbers: + :let &stc='%#NonText#%{&nu?v:lnum:""}' . + '%=%{&rnu&&(v:lnum%2)?"\ ".v:relnum:""}' . + '%#LineNr#%{&rnu&&!(v:lnum%2)?"\ ".v:relnum:""}' + +< WARNING: this expression is evaluated for each screen line so defining + an expensive expression can negatively affect render performance. + *'statusline'* *'stl'* *E540* *E542* 'statusline' 'stl' string (default empty) global or local to window |global-local| @@ -5982,6 +6082,8 @@ A jump table for the options with a short description can be found at |Q_op|. When there is error while evaluating the option then it will be made empty to avoid further errors. Otherwise screen updating would loop. + When the result contains unprintable characters the result is + unpredictable. Note that the only effect of 'ruler' when this option is set (and 'laststatus' is 2 or 3) is controlling the output of |CTRL-G|. @@ -5989,12 +6091,12 @@ A jump table for the options with a short description can be found at |Q_op|. field meaning ~ - Left justify the item. The default is right justified when minwid is larger than the length of the item. - 0 Leading zeroes in numeric items. Overridden by '-'. - minwid Minimum width of the item, padding as set by '-' & '0'. + 0 Leading zeroes in numeric items. Overridden by "-". + minwid Minimum width of the item, padding as set by "-" & "0". Value must be 50 or less. - maxwid Maximum width of the item. Truncation occurs with a '<' + maxwid Maximum width of the item. Truncation occurs with a "<" on the left for text items. Numeric items will be - shifted down to maxwid-2 digits followed by '>'number + shifted down to maxwid-2 digits followed by ">"number where number is the amount of missing digits, much like an exponential notation. item A one letter code as described below. @@ -6030,7 +6132,6 @@ A jump table for the options with a short description can be found at |Q_op|. o N Byte number in file of byte under cursor, first byte is 1. Mnemonic: Offset from start of file (with one added) O N As above, in hexadecimal. - N N Printer page number. (Only works in the 'printheader' option.) l N Line number. L N Number of lines in buffer. c N Column number (byte index). @@ -6040,24 +6141,25 @@ A jump table for the options with a short description can be found at |Q_op|. P S Percentage through file of displayed window. This is like the percentage described for 'ruler'. Always 3 in length, unless translated. + S S 'showcmd' content, see 'showcmdloc'. a S Argument list status as in default title. ({current} of {max}) Empty if the argument file count is zero or one. - { NF Evaluate expression between '%{' and '}' and substitute result. - Note that there is no '%' before the closing '}'. The - expression cannot contain a '}' character, call a function to + { NF Evaluate expression between "%{" and "}" and substitute result. + Note that there is no "%" before the closing "}". The + expression cannot contain a "}" character, call a function to work around that. See |stl-%{| below. - {% - This is almost same as { except the result of the expression is + `{%` - This is almost same as "{" except the result of the expression is re-evaluated as a statusline format string. Thus if the - return value of expr contains % items they will get expanded. - The expression can contain the } character, the end of - expression is denoted by %}. + return value of expr contains "%" items they will get expanded. + The expression can contain the "}" character, the end of + expression is denoted by "%}". For example: > func! Stl_filename() abort return "%t" endfunc < `stl=%{Stl_filename()}` results in `"%t"` `stl=%{%Stl_filename()%}` results in `"Name of current file"` - %} - End of `{%` expression + %} - End of "{%" expression ( - Start of item group. Can be used for setting the width and alignment of a section. Must be followed by %) somewhere. ) - End of item group. No width fields allowed. @@ -6252,12 +6354,12 @@ A jump table for the options with a short description can be found at |Q_op|. Otherwise this option does not always reflect the current syntax (the b:current_syntax variable does). This option is most useful in a modeline, for a file which syntax is - not automatically recognized. Example, in an IDL file: - /* vim: set syntax=idl : */ ~ - When a dot appears in the value then this separates two filetype - names. Example: - /* vim: set syntax=c.doxygen : */ ~ - This will use the "c" syntax first, then the "doxygen" syntax. + not automatically recognized. Example, in an IDL file: > + /* vim: set syntax=idl : */ +< When a dot appears in the value then this separates two filetype + names. Example: > + /* vim: set syntax=c.doxygen : */ +< This will use the "c" syntax first, then the "doxygen" syntax. Note that the second one must be prepared to be loaded as an addition, otherwise it will be skipped. More than one dot may appear. To switch off syntax highlighting for the current file, use: > @@ -6310,7 +6412,7 @@ A jump table for the options with a short description can be found at |Q_op|. the |:retab| command, and the 'softtabstop' option. Note: Setting 'tabstop' to any other value than 8 can make your file - appear wrong in many places, e.g., when printing it. + appear wrong in many places. The value must be more than 0 and less than 10000. There are four main ways to use tabs in Vim: @@ -6403,7 +6505,9 @@ A jump table for the options with a short description can be found at |Q_op|. This option specifies a function to be used to perform tag searches. The function gets the tag pattern and should return a List of matching tags. See |tag-function| for an explanation of how to write the - function and an example. + function and an example. The value can be the name of a function, a + |lambda| or a |Funcref|. See |option-value-function| for more + information. *'taglength'* *'tl'* 'taglength' 'tl' number (default 0) @@ -6465,7 +6569,7 @@ A jump table for the options with a short description can be found at |Q_op|. 'termguicolors' 'tgc' boolean (default off) global Enables 24-bit RGB color in the |TUI|. Uses "gui" |:highlight| - attributes instead of "cterm" attributes. |highlight-guifg| + attributes instead of "cterm" attributes. |guifg| Requires an ISO-8613-3 compatible terminal. *'termpastefilter'* *'tpf'* @@ -6526,6 +6630,8 @@ A jump table for the options with a short description can be found at |Q_op|. global or local to buffer |global-local| This option specifies a function to be used for thesaurus completion with CTRL-X CTRL-T. |i_CTRL-X_CTRL-T| See |compl-thesaurusfunc|. + The value can be the name of a function, a |lambda| or a |Funcref|. + See |option-value-function| for more information. This option cannot be set from a |modeline| or in the |sandbox|, for security reasons. @@ -6732,11 +6838,11 @@ A jump table for the options with a short description can be found at |Q_op|. final value applying to all subsequent tabs. For example, when editing assembly language files where statements - start in the 8th column and comments in the 40th, it may be useful + start in the 9th column and comments in the 41st, it may be useful to use the following: > :set varsofttabstop=8,32,8 -< This will set soft tabstops at the 8th and 40th columns, and at every - 8th column thereafter. +< This will set soft tabstops with 8 and 8 + 32 spaces, and 8 more + for every column thereafter. Note that the value of |'softtabstop'| will be ignored while 'varsofttabstop' is set. @@ -6757,28 +6863,31 @@ A jump table for the options with a short description can be found at |Q_op|. *'verbose'* *'vbs'* 'verbose' 'vbs' number (default 0) global - When bigger than zero, Vim will give messages about what it is doing. - Currently, these messages are given: - >= 1 Lua assignments to options, mappings, etc. - >= 2 When a file is ":source"'ed and when the shada file is read or written.. - >= 3 UI info, terminal capabilities - >= 4 Shell commands. - >= 5 Every searched tags file and include file. - >= 8 Files for which a group of autocommands is executed. - >= 9 Every executed autocommand. - >= 11 Finding items in a path - >= 12 Every executed function. - >= 13 When an exception is thrown, caught, finished, or discarded. - >= 14 Anything pending in a ":finally" clause. - >= 15 Every executed Ex command from a script (truncated at 200 - characters). - >= 16 Every executed Ex command. - - This option can also be set with the "-V" argument. See |-V|. - This option is also set by the |:verbose| command. - - When the 'verbosefile' option is set then the verbose messages are not - displayed. + Sets the verbosity level. Also set by |-V| and |:verbose|. + + Tracing of options in Lua scripts is activated at level 1; Lua scripts + are not traced with verbose=0, for performance. + + If greater than or equal to a given level, Nvim produces the following + messages: + + Level Messages ~ + ---------------------------------------------------------------------- + 1 Lua assignments to options, mappings, etc. + 2 When a file is ":source"'ed, or |shada| file is read or written. + 3 UI info, terminal capabilities. + 4 Shell commands. + 5 Every searched tags file and include file. + 8 Files for which a group of autocommands is executed. + 9 Executed autocommands. + 11 Finding items in a path. + 12 Vimscript function calls. + 13 When an exception is thrown, caught, finished, or discarded. + 14 Anything pending in a ":finally" clause. + 15 Ex commands from a script (truncated at 200 characters). + 16 Ex commands. + + If 'verbosefile' is set then the verbose messages are not displayed. *'verbosefile'* *'vfile'* 'verbosefile' 'vfile' string (default empty) @@ -6938,15 +7047,18 @@ A jump table for the options with a short description can be found at |Q_op|. *'wildmenu'* *'wmnu'* *'nowildmenu'* *'nowmnu'* 'wildmenu' 'wmnu' boolean (default on) global - Enables "enhanced mode" of command-line completion. When user hits - <Tab> (or 'wildchar') to invoke completion, the possible matches are - shown in a menu just above the command-line (see 'wildoptions'), with - the first match highlighted (overwriting the statusline). Keys that - show the previous/next match (<Tab>/CTRL-P/CTRL-N) highlight the - match. + When 'wildmenu' is on, command-line completion operates in an enhanced + mode. On pressing 'wildchar' (usually <Tab>) to invoke completion, + the possible matches are shown. + When 'wildoptions' contains "pum", then the completion matches are + shown in a popup menu. Otherwise they are displayed just above the + command line, with the first match highlighted (overwriting the status + line, if there is one). + Keys that show the previous/next match, such as <Tab> or + CTRL-P/CTRL-N, cause the highlight to move to the appropriate match. 'wildmode' must specify "full": "longest" and "list" do not start 'wildmenu' mode. You can check the current mode with |wildmenumode()|. - The menu is canceled when a key is hit that is not used for selecting + The menu is cancelled when a key is hit that is not used for selecting a completion. While the menu is active these keys have special meanings: @@ -7022,6 +7134,14 @@ A jump table for the options with a short description can be found at |Q_op|. global A list of words that change how |cmdline-completion| is done. The following values are supported: + fuzzy Use |fuzzy-matching| to find completion matches. When + this value is specified, wildcard expansion will not + be used for completion. The matches will be sorted by + the "best match" rather than alphabetically sorted. + This will find more matches than the wildcard + expansion. Currently fuzzy matching based completion + is not supported for file and directory names and + instead wildcard expansion is used. pum Display the completion matches using the popup menu in the same style as the |ins-completion-menu|. tagfile When using CTRL-D to list matching tags, the kind of @@ -7117,7 +7237,7 @@ A jump table for the options with a short description can be found at |Q_op|. the window. Note: highlight namespaces take precedence over 'winhighlight'. - See |nvim_win_set_hl_ns| and |nvim_set_hl|. + See |nvim_win_set_hl_ns()| and |nvim_set_hl()|. Highlights of vertical separators are determined by the window to the left of the separator. The 'tabline' highlight of a tabpage is diff --git a/runtime/doc/pattern.txt b/runtime/doc/pattern.txt index 371a210847..5357aaa3f1 100644 --- a/runtime/doc/pattern.txt +++ b/runtime/doc/pattern.txt @@ -372,7 +372,7 @@ Vim includes two regexp engines: 1. An old, backtracking engine that supports everything. 2. A new, NFA engine that works much faster on some patterns, possibly slower on some patterns. - + *E1281* Vim will automatically select the right engine for you. However, if you run into a problem or want to specifically select one engine or the other, you can prepend one of the following to the pattern: diff --git a/runtime/doc/pi_health.txt b/runtime/doc/pi_health.txt index 04e04b5165..5ba5d1beef 100644 --- a/runtime/doc/pi_health.txt +++ b/runtime/doc/pi_health.txt @@ -7,11 +7,12 @@ Author: TJ DeVries <devries.timothyj@gmail.com> ============================================================================== Introduction *health* -health.vim is a minimal framework to help with troubleshooting user -configuration. Nvim ships with healthchecks for configuration, performance, -python support, ruby support, clipboard support, and more. +health.vim is a minimal framework to help users troubleshoot configuration and +any other environment conditions that a plugin might care about. Nvim ships +with healthchecks for configuration, performance, python support, ruby +support, clipboard support, and more. -To run the healthchecks, use this command: > +To run all healthchecks, use: > :checkhealth < @@ -20,8 +21,8 @@ Plugin authors are encouraged to write new healthchecks. |health-dev| ============================================================================== Commands *health-commands* - *:checkhealth* *:CheckHealth* -:checkhealth Run all healthchecks. + *:che* *:checkhealth* *:CheckHealth* +:che[ckhealth] Run all healthchecks. *E5009* Nvim depends on |$VIMRUNTIME|, 'runtimepath' and 'packpath' to find the standard "runtime files" for syntax highlighting, @@ -29,29 +30,27 @@ Commands *health-commands* :checkhealth). If the runtime files cannot be found then those features will not work. -:checkhealth {plugins} +:che[ckhealth] {plugins} Run healthcheck(s) for one or more plugins. E.g. to run only the standard Nvim healthcheck: > :checkhealth nvim < To run the healthchecks for the "foo" and "bar" plugins - (assuming these plugins are on 'runtimepath' or 'packpath' and - they have implemented the Lua or Vimscript interface - require("foo.health").check() and health#bar#check(), - respectively): > + (assuming they are on 'runtimepath' and they have implemented + the Lua `require("foo.health").check()` interface): > :checkhealth foo bar < - To run healthchecks for lua submodules, use dot notation or - "*" to refer to all submodules. For example nvim provides - `vim.lsp` and `vim.treesitter` > + To run healthchecks for Lua submodules, use dot notation or + "*" to refer to all submodules. For example Nvim provides + `vim.lsp` and `vim.treesitter`: > :checkhealth vim.lsp vim.treesitter :checkhealth vim* < ============================================================================== -Lua Functions *health-functions-lua* *health-lua* *vim.health* +Functions *health-functions* *vim.health* -The Lua "health" module can be used to create new healthchecks (see also -|health-functions-vim|). To get started, simply use: +The Lua "health" module can be used to create new healthchecks. To get started +see |health-dev|. vim.health.report_start({name}) *vim.health.report_start()* Starts a new report. Most plugins should call this only once, but if @@ -65,36 +64,43 @@ vim.health.report_ok({msg}) *vim.health.report_ok()* Reports a "success" message. vim.health.report_warn({msg} [, {advice}]) *vim.health.report_warn()* - Reports a warning. {advice} is an optional List of suggestions. + Reports a warning. {advice} is an optional list of suggestions to + present to the user. vim.health.report_error({msg} [, {advice}]) *vim.health.report_error()* - Reports an error. {advice} is an optional List of suggestions. + Reports an error. {advice} is an optional list of suggestions to + present to the user. ============================================================================== -Create a Lua healthcheck *health-dev-lua* - -Healthchecks are functions that check the user environment, configuration, -etc. Nvim has built-in healthchecks in $VIMRUNTIME/autoload/health/. - -To add a new healthcheck for your own plugin, simply define a Lua module in -your plugin that returns a table with a "check()" function. |:checkhealth| -will automatically find and invoke this function. - -If your plugin is named "foo", then its healthcheck module should be a file in -one of these locations on 'runtimepath' or 'packpath': +Create a healthcheck *health-dev* + +Healthchecks are functions that check the user environment, configuration, or +any other prerequisites that a plugin cares about. Nvim ships with +healthchecks in: + - $VIMRUNTIME/autoload/health/ + - $VIMRUNTIME/lua/vim/lsp/health.lua + - $VIMRUNTIME/lua/vim/treesitter/health.lua + - and more... + +To add a new healthcheck for your own plugin, simply create a "health.lua" +module on 'runtimepath' that returns a table with a "check()" function. Then +|:checkhealth| will automatically find and invoke the function. + +For example if your plugin is named "foo", define your healthcheck module at +one of these locations (on 'runtimepath'): - lua/foo/health/init.lua - lua/foo/health.lua -If your plugin provides a submodule named "bar" for which you want a separate -healthcheck, define the healthcheck at one of these locations on 'runtimepath' -or 'packpath': +If your plugin also provides a submodule named "bar" for which you want +a separate healthcheck, define the healthcheck at one of these locations: - lua/foo/bar/health/init.lua - lua/foo/bar/health.lua -All submodules should return a Lua table containing the method `check()`. +All such health modules must return a Lua table containing a `check()` +function. -Copy this sample code into `lua/foo/health/init.lua` or `lua/foo/health.lua`, -replacing "foo" in the path with your plugin name: > +Copy this sample code into `lua/foo/health.lua`, replacing "foo" in the path +with your plugin name: > local M = {} @@ -102,9 +108,9 @@ replacing "foo" in the path with your plugin name: > vim.health.report_start("my_plugin report") -- make sure setup function parameters are ok if check_setup() then - vim.health.report_ok("Setup function is correct") + vim.health.report_ok("Setup is correct") else - vim.health.report_error("Setup function is incorrect") + vim.health.report_error("Setup is incorrect") end -- do some more checking -- ... @@ -112,67 +118,5 @@ replacing "foo" in the path with your plugin name: > return M -============================================================================== -Vimscript Functions *health-functions-vimscript* *health-vimscript* - -health.vim functions are for creating new healthchecks. (See also -|health-functions-lua|) - -health#report_start({name}) *health#report_start* - Starts a new report. Most plugins should call this only once, but if - you want different sections to appear in your report, call this once - per section. - -health#report_info({msg}) *health#report_info* - Reports an informational message. - -health#report_ok({msg}) *health#report_ok* - Reports a "success" message. - -health#report_warn({msg} [, {advice}]) *health#report_warn* - Reports a warning. {advice} is an optional List of suggestions. - -health#report_error({msg} [, {advice}]) *health#report_error* - Reports an error. {advice} is an optional List of suggestions. - -health#{plugin}#check() *health.user_checker* - Healthcheck function for {plugin}. Called by |:checkhealth| - automatically. Example: > - - function! health#my_plug#check() abort - silent call s:check_environment_vars() - silent call s:check_python_configuration() - endfunction -< -============================================================================== -Create a healthcheck *health-dev-vim* - -Healthchecks are functions that check the user environment, configuration, -etc. Nvim has built-in healthchecks in $VIMRUNTIME/autoload/health/. - -To add a new healthcheck for your own plugin, simply define a -health#{plugin}#check() function in autoload/health/{plugin}.vim. -|:checkhealth| automatically finds and invokes such functions. - -If your plugin is named "foo", then its healthcheck function must be > - health#foo#check() - -defined in this file on 'runtimepath' or 'packpath': - - autoload/health/foo.vim - -Copy this sample code into autoload/health/foo.vim and replace "foo" with your -plugin name: > - function! health#foo#check() abort - call health#report_start('sanity checks') - " perform arbitrary checks - " ... - - if looks_good - call health#report_ok('found required dependencies') - else - call health#report_error('cannot find foo', - \ ['npm install --save foo']) - endif - endfunction vim:et:tw=78:ts=8:ft=help:fdm=marker diff --git a/runtime/doc/pi_msgpack.txt b/runtime/doc/pi_msgpack.txt index 801c56e49f..24a31f1de7 100644 --- a/runtime/doc/pi_msgpack.txt +++ b/runtime/doc/pi_msgpack.txt @@ -63,16 +63,16 @@ msgpack#is_uint({msgpack-value}) *msgpack#is_uint()* *msgpack#strftime* msgpack#strftime({format}, {msgpack-integer}) *msgpack#strftime()* Same as |strftime()|, but second argument may be - |msgpack-special-dict|. Requires |+python| or |+python3| to really - work with |msgpack-special-dict|s. + |msgpack-special-dict|. Requires |Python| to really work with + |msgpack-special-dict|s. *msgpack#strptime* msgpack#strptime({format}, {time}) *msgpack#strptime()* Reverse of |msgpack#strftime()|: for any time and format |msgpack#equal|( |msgpack#strptime|(format, |msgpack#strftime|(format, - time)), time) be true. Requires |+python| or |+python3|, without it - only supports non-|msgpack-special-dict| nonnegative times and format - equal to `%Y-%m-%dT%H:%M:%S`. + time)), time) be true. Requires ||Python|, without it only supports + non-|msgpack-special-dict| nonnegative times and format equal to + `%Y-%m-%dT%H:%M:%S`. msgpack#int_dict_to_str({msgpack-special-int}) *msgpack#int_dict_to_str()* Function which converts |msgpack-special-dict| integer value to diff --git a/runtime/doc/pi_netrw.txt b/runtime/doc/pi_netrw.txt index 1eaa76264f..5167b4baf7 100644 --- a/runtime/doc/pi_netrw.txt +++ b/runtime/doc/pi_netrw.txt @@ -2353,7 +2353,7 @@ MARKED FILES: DIFF *netrw-md* {{{2 (See |netrw-mf| and |netrw-mr| for how to mark files) (uses the global marked file list) -Use |vimdiff| to visualize difference between selected files (two or +Use vimdiff to visualize difference between selected files (two or three may be selected for this). Uses the global marked file list. MARKED FILES: EDITING *netrw-me* {{{2 @@ -2419,15 +2419,6 @@ from the current window (where one does the mf) to the target. Associated setting variable: |g:netrw_localmovecmd| |g:netrw_ssh_cmd| -MARKED FILES: PRINTING *netrw-mp* {{{2 - (See |netrw-mf| and |netrw-mr| for how to mark files) - (uses the local marked file list) - -When "mp" is used, netrw will apply the |:hardcopy| command to marked files. -What netrw does is open each file in a one-line window, execute hardcopy, then -close the one-line window. - - MARKED FILES: SOURCING *netrw-ms* {{{2 (See |netrw-mf| and |netrw-mr| for how to mark files) (uses the local marked file list) @@ -2782,7 +2773,7 @@ your browsing preferences. (see also: |netrw-settings|) history are saved (as .netrwbook and .netrwhist). Netrw uses |expand()| on the string. - default: stdpath('data') (see |stdpath()|) + default: stdpath("data") (see |stdpath()|) *g:netrw_keepdir* =1 (default) keep current directory immune from the browsing directory. @@ -2821,12 +2812,12 @@ your browsing preferences. (see also: |netrw-settings|) function 'netrw_gitignore#Hide() automatically hiding all gitignored files. For more details see |netrw-gitignore|. + default: "" - Examples: - let g:netrw_list_hide= '.*\.swp$' - let g:netrw_list_hide= netrw_gitignore#Hide() .. '.*\.swp$' - default: "" - + Examples: > + let g:netrw_list_hide= '.*\.swp$' + let g:netrw_list_hide= netrw_gitignore#Hide() .. '.*\.swp$' +< *g:netrw_localcopycmd* ="cp" Linux/Unix/MacOS/Cygwin =expand("$COMSPEC") Windows Copies marked files (|netrw-mf|) to target @@ -3268,7 +3259,7 @@ If there are marked files: (see |netrw-mf|) mr [query: reply with *.c] R [query: reply with s/^\(.*\)\.c$/\1.cpp/] < - This example will mark all *.c files and then rename them to *.cpp + This example will mark all "*.c" files and then rename them to "*.cpp" files. Netrw will protect you from overwriting local files without confirmation, but not remote ones. @@ -3280,7 +3271,7 @@ If there are marked files: (see |netrw-mf|) <c-x><c-x> : a pair of contiguous ctrl-x's tells netrw to ignore any portion of the string preceding the double ctrl-x's. < - WARNING:~ + WARNING: ~ Note that moving files is a dangerous operation; copies are safer. That's because a "move" for remote files is actually a copy + delete -- and if @@ -3469,7 +3460,7 @@ Example: Clear netrw's marked file list via a mapping on gu > *netrw-p4* P4. I would like long listings to be the default. {{{2 - Put the following statement into your |.vimrc|: > + Put the following statement into your |vimrc|: > let g:netrw_liststyle= 1 < @@ -3482,7 +3473,7 @@ Example: Clear netrw's marked file list via a mapping on gu > Does your system's strftime() accept the "%c" to yield dates such as "Sun Apr 27 11:49:23 1997"? If not, do a "man strftime" and find out what option should be used. Then - put it into your |.vimrc|: > + put it into your |vimrc|: > let g:netrw_timefmt= "%X" (where X is the option) < @@ -3490,7 +3481,7 @@ Example: Clear netrw's marked file list via a mapping on gu > P6. I want my current directory to track my browsing. {{{2 How do I do that? - Put the following line in your |.vimrc|: + Put the following line in your |vimrc|: > let g:netrw_keepdir= 0 < @@ -3569,7 +3560,7 @@ Example: Clear netrw's marked file list via a mapping on gu > http://www.chiark.greenend.org.uk/~sgtatham/putty/0.60/htmldoc/Chapter8.html#pubkey-gettingready (8.3 Getting ready for public key authentication) < - How to use a private key with 'pscp': > + How to use a private key with "pscp": > http://www.chiark.greenend.org.uk/~sgtatham/putty/0.60/htmldoc/Chapter5.html (5.2.4 Using public key authentication with PSCP) @@ -3776,9 +3767,9 @@ Example: Clear netrw's marked file list via a mapping on gu > < *netrw-P22* P22. I get an error message when I try to copy or move a file: {{{2 - +> **error** (netrw) tried using g:netrw_localcopycmd<cp>; it doesn't work! - +< What's wrong? Netrw uses several system level commands to do things (see @@ -3839,7 +3830,7 @@ netrw: or http://vim.sourceforge.net/scripts/script.php?script_id=120 - Decho.vim is provided as a "vimball"; see |vimball-intro|. You + Decho.vim is provided as a "vimball". You should edit the Decho.vba.gz file and source it in: > vim Decho.vba.gz @@ -3917,7 +3908,7 @@ netrw: * Installed |g:netrw_clipboard| setting * Installed option bypass for |'guioptions'| a/A settings - * Changed popup_beval() to |popup_atcursor()| + * Changed popup_beval() to popup_atcursor() in netrw#ErrorMsg (lacygoill). Apparently popup_beval doesn't reliably close the popup when the mouse is moved. @@ -3943,7 +3934,7 @@ netrw: did not restore options correctly that had a single quote in the option string. Apr 13, 2020 * implemented error handling via popup - windows (see |popup_beval()|) + windows (see popup_beval()) Apr 30, 2020 * (reported by Manatsu Takahashi) while using Lexplore, a modified file could be overwritten. Sol'n: will not overwrite, @@ -4001,9 +3992,9 @@ netrw: Nov 22, 2016 * (glacambre) reported that files containing spaces weren't being obtained properly via scp. Fix: apparently using single quotes - such as with 'file name' wasn't enough; the + such as with "file name" wasn't enough; the spaces inside the quotes also had to be - escaped (ie. 'file\ name'). + escaped (ie. "file\ name"). * Also fixed obtain (|netrw-O|) to be able to obtain files with spaces in their names Dec 20, 2016 * (xc1427) Reported that using "I" (|netrw-I|) diff --git a/runtime/doc/pi_spec.txt b/runtime/doc/pi_spec.txt index 6d45a0f064..d485d6ad49 100644 --- a/runtime/doc/pi_spec.txt +++ b/runtime/doc/pi_spec.txt @@ -34,8 +34,8 @@ also check if the name, version and release matches. The plugin is smart enough to ask you if it should update the package release, if you have not done so. +------------------------------------------------------------------------------ Setting a map *spec-setting-a-map* -------------- As you should know, you can easily set a map to access any Vim command (or anything, for that matter). If you don't like the default map of @@ -54,8 +54,8 @@ This command will add a map only in the spec file buffers. ============================================================================== 2. Customizing *spec-customizing* +------------------------------------------------------------------------------ The format string *spec_chglog_format* ------------------ You can easily customize how your spec file entry will look like. To do this just set the variable "spec_chglog_format" in your vimrc file like @@ -72,8 +72,8 @@ address once. To discover which format options you can use, take a look at the strftime() function man page. +------------------------------------------------------------------------------ Where to insert new items *spec_chglog_prepend* -------------------------- The plugin will usually insert new %changelog entry items (note that it's not the entry itself) after the existing ones. If you set the @@ -83,8 +83,8 @@ spec_chglog_prepend variable > it will insert new items before the existing ones. +------------------------------------------------------------------------------ Inserting release info *spec_chglog_release_info* ----------------------- If you want, the plugin may automatically insert release information on each changelog entry. One advantage of turning this feature on is diff --git a/runtime/doc/pi_tar.txt b/runtime/doc/pi_tar.txt index c6c0596ea0..2230b82dec 100644 --- a/runtime/doc/pi_tar.txt +++ b/runtime/doc/pi_tar.txt @@ -80,25 +80,25 @@ Copyright 2005-2017: *tar-copyright* These options are variables that one may change, typically in one's <.vimrc> file. - Default - Variable Value Explanation - *g:tar_browseoptions* "Ptf" used to get a list of contents - *g:tar_readoptions* "OPxf" used to extract a file from a tarball - *g:tar_cmd* "tar" the name of the tar program - *g:tar_nomax* 0 if true, file window will not be maximized - *g:tar_secure* undef if exists: + Default + Variable Value Explanation + *g:tar_browseoptions* "Ptf" used to get a list of contents + *g:tar_readoptions* "OPxf" used to extract a file from a tarball + *g:tar_cmd* "tar" the name of the tar program + *g:tar_nomax* 0 if true, file window will not be maximized + *g:tar_secure* undef if exists: "--"s will be used to prevent unwanted option expansion in tar commands. Please be sure that your tar command accepts "--"; Posix compliant tar utilities do accept them. if not exists: - The tar plugin will reject any tar + The tar plugin will reject any tar files or member files that begin with "-" Not all tar's support the "--" which is why it isn't default. - *g:tar_writeoptions* "uf" used to update/replace a file + *g:tar_writeoptions* "uf" used to update/replace a file ============================================================================== diff --git a/runtime/doc/pi_zip.txt b/runtime/doc/pi_zip.txt index 2bbd6eea06..9b531d78b4 100644 --- a/runtime/doc/pi_zip.txt +++ b/runtime/doc/pi_zip.txt @@ -39,7 +39,7 @@ Copyright: Copyright (C) 2005-2015 Charles E Campbell *zip-copyright* OPTIONS~ - *g:zip_nomax* + *g:zip_nomax* If this variable exists and is true, the file window will not be automatically maximized when opened. @@ -54,21 +54,21 @@ Copyright: Copyright (C) 2005-2015 Charles E Campbell *zip-copyright* under Windows ("). If you'd rather have no quotes, simply set g:zip_shq to the empty string (let g:zip_shq= "") in your <.vimrc>. - *g:zip_unzipcmd* + *g:zip_unzipcmd* Use this option to specify the program which does the duty of "unzip". It's used during browsing. By default: > - let g:zip_unzipcmd= "unzip" + let g:zip_unzipcmd= "unzip" < *g:zip_zipcmd* Use this option to specify the program which does the duty of "zip". It's used during the writing (updating) of a file already in a zip file; by default: > - let g:zip_zipcmd= "zip" + let g:zip_zipcmd= "zip" < *g:zip_extractcmd* This option specifies the program (and any options needed) used to extract a file from a zip archive. By default, > - let g:zip_extractcmd= g:zip_unzipcmd + let g:zip_extractcmd= g:zip_unzipcmd < PREVENTING LOADING~ @@ -103,14 +103,14 @@ Copyright: Copyright (C) 2005-2015 Charles E Campbell *zip-copyright* ============================================================================== 4. History *zip-history* {{{1 v32 Oct 22, 2021 * to avoid an issue with a vim 8.2 patch, zipfile: has - been changed to zipfile:// . This often shows up + been changed to zipfile:// . This often shows up as zipfile:/// with zipped files that are root-based. v29 Apr 02, 2017 * (Klartext) reported that an encrypted zip file could - opened but the swapfile held unencrypted contents. + opened but the swapfile held unencrypted contents. The solution is to edit the contents of a zip file using the |:noswapfile| modifier. v28 Oct 08, 2014 * changed the sanity checks for executables to reflect - the command actually to be attempted in zip#Read() + the command actually to be attempted in zip#Read() and zip#Write() * added the extraction of a file capability Nov 30, 2015 * added *.epub to the |g:zipPlugin_ext| list diff --git a/runtime/doc/print.txt b/runtime/doc/print.txt deleted file mode 100644 index 924fab175e..0000000000 --- a/runtime/doc/print.txt +++ /dev/null @@ -1,721 +0,0 @@ -*print.txt* Nvim - - - VIM REFERENCE MANUAL by Bram Moolenaar - - -Printing *printing* - - Type |gO| to see the table of contents. - -============================================================================== -1. Introduction *print-intro* - -On MS-Windows Vim can print your text on any installed printer. On other -systems a PostScript file is produced. This can be directly sent to a -PostScript printer. For other printers a program like ghostscript needs to be -used. - -Note: If you have problems printing with |:hardcopy|, an alternative is to use -|:TOhtml| and print the resulting html file from a browser. - - *:ha* *:hardcopy* *E237* *E238* *E324* -:[range]ha[rdcopy][!] [arguments] - Send [range] lines (default whole file) to the - printer. - - On MS-Windows a dialog is displayed to allow selection - of printer, paper size etc. To skip the dialog, use - the [!]. In this case the printer defined by - 'printdevice' is used, or, if 'printdevice' is empty, - the system default printer. - - For systems other than MS-Windows, PostScript is - written in a temp file and 'printexpr' is used to - actually print it. Then [arguments] can be used by - 'printexpr' through |v:cmdarg|. Otherwise [arguments] - is ignored. 'printoptions' can be used to specify - paper size, duplex, etc. - Note: If you want PDF, there are tools such as - "ps2pdf" that can convert the PostScript to PDF. - -:[range]ha[rdcopy][!] >{filename} - As above, but write the resulting PostScript in file - {filename}. - Things like "%" are expanded |cmdline-special| - Careful: An existing file is silently overwritten. - On MS-Windows use the "print to file" feature of the - printer driver. - -Progress is displayed during printing as a page number and a percentage. To -abort printing use the interrupt key (CTRL-C or, on MS-systems, CTRL-Break). - -Printer output is controlled by the 'printfont' and 'printoptions' options. -'printheader' specifies the format of a page header. - -The printed file is always limited to the selected margins, irrespective of -the current window's 'wrap' or 'linebreak' settings. The "wrap" item in -'printoptions' can be used to switch wrapping off. -The current highlighting colors are used in the printout, with the following -considerations: -1) The normal background is always rendered as white (i.e. blank paper). -2) White text or the default foreground is rendered as black, so that it shows - up! -3) If 'background' is "dark", then the colours are darkened to compensate for - the fact that otherwise they would be too bright to show up clearly on - white paper. - -============================================================================== -2. Print options *print-options* - -Here are the details for the options that change the way printing is done. -For generic info about setting options see |options.txt|. - - *pdev-option* -'printdevice' 'pdev' string (default empty) - global -This defines the name of the printer to be used when the |:hardcopy| command -is issued with a bang (!) to skip the printer selection dialog. On Win32, it -should be the printer name exactly as it appears in the standard printer -dialog. -If the option is empty, then vim will use the system default printer for -":hardcopy!" - - *penc-option* *E620* -'printencoding' 'penc' String (default empty, except for: - Windows: cp1252, - Macintosh: mac-roman, - HPUX: hp-roman8) - global -Sets the character encoding used when printing. This option tells Vim which -print character encoding file from the "print" directory in 'runtimepath' to -use. - -This option will accept any value from |encoding-names|. Any recognized names -are converted to Vim standard names - see 'encoding' for more details. Names -not recognized by Vim will just be converted to lower case and underscores -replaced with '-' signs. - -If 'printencoding' is empty or Vim cannot find the file then it will use -'encoding' (if it is set an 8-bit encoding) to find the print character -encoding file. If Vim is unable to find a character encoding file then it -will use the "latin1" print character encoding file. - -When 'encoding' is set to a multibyte encoding, Vim will try to convert -characters to the printing encoding for printing (if 'printencoding' is empty -then the conversion will be to latin1). If no conversion is possible then -printing will fail. Any characters that cannot be converted will be replaced -with upside down question marks. - -Two print character encoding files are provided to support default Mac and -HPUX character encodings and are used by default on these platforms. Code page -1252 print character encoding is used by default on the Windows platform. - - *pexpr-option* -'printexpr' 'pexpr' String (default: see below) - global -Expression that is evaluated to print the PostScript produced with -|:hardcopy|. -The file name to be printed is in |v:fname_in|. -The arguments to the ":hardcopy" command are in |v:cmdarg|. -The expression must take care of deleting the file after printing it. -When there is an error, the expression must return a non-zero number. -If there is no error, return zero or an empty string. -The default for non MS-Windows systems is to simply use "lpr" to print the -file: > - - system(['lpr'] - + (empty(&printdevice)?[]:['-P', &printdevice]) - + [v:fname_in]) - .. delete(v:fname_in) - + v:shell_error - -On MS-Dos and MS-Windows machines the default is to copy the file to the -currently specified printdevice: > - - system(['copy', v:fname_in, empty(&printdevice)?'LPT1':&printdevice]) - .. delete(v:fname_in) - -If you change this option, using a function is an easy way to avoid having to -escape all the spaces. Example: > - - :set printexpr=PrintFile(v:fname_in) - :function PrintFile(fname) - : call system("ghostview " .. a:fname) - : call delete(a:fname) - : return v:shell_error - :endfunc - -Be aware that some print programs return control before they have read the -file. If you delete the file too soon it will not be printed. These programs -usually offer an option to have them remove the file when printing is done. - *E365* -If evaluating the expression fails or it results in a non-zero number, you get -an error message. In that case Vim will delete the file. In the default -value for non-MS-Windows a trick is used: Adding "v:shell_error" will result -in a non-zero number when the system() call fails. - -This option cannot be set from a |modeline| or in the |sandbox|, for security -reasons. - - *pfn-option* *E613* -'printfont' 'pfn' string (default "courier") - global -This is the name of the font that will be used for the |:hardcopy| command's -output. It has the same format as the 'guifont' option, except that only one -font may be named, and the special "guifont=*" syntax is not available. - -In the Win32 GUI version this specifies a font name with its extra attributes, -as with the 'guifont' option. - -For other systems, only ":h11" is recognized, where "11" is the point size of -the font. When omitted, the point size is 10. - - *pheader-option* -'printheader' 'pheader' string (default "%<%f%h%m%=Page %N") - global -This defines the format of the header produced in |:hardcopy| output. The -option is defined in the same way as the 'statusline' option. The same simple -header is used when this option is empty. - - *pmbcs-option* -'printmbcharset' 'pmbcs' string (default "") - global -Sets the CJK character set to be used when generating CJK output from -|:hardcopy|. The following predefined values are currently recognised by Vim: - - Value Description ~ - Chinese GB_2312-80 - (Simplified) GBT_12345-90 - MAC Apple Mac Simplified Chinese - GBT-90_MAC GB/T 12345-90 Apple Mac Simplified - Chinese - GBK GBK (GB 13000.1-93) - ISO10646 ISO 10646-1:1993 - - Chinese CNS_1993 CNS 11643-1993, Planes 1 & 2 - (Traditional) BIG5 - ETEN Big5 with ETen extensions - ISO10646 ISO 10646-1:1993 - - Japanese JIS_C_1978 - JIS_X_1983 - JIS_X_1990 - MSWINDOWS Win3.1/95J (JIS X 1997 + NEC + - IBM extensions) - KANJITALK6 Apple Mac KanjiTalk V6.x - KANJITALK7 Apple Mac KanjiTalk V7.x - - Korean KS_X_1992 - MAC Apple Macintosh Korean - MSWINDOWS KS X 1992 with MS extensions - ISO10646 ISO 10646-1:1993 - -Only certain combinations of the above values and 'printencoding' are -possible. The following tables show the valid combinations: - - euc-cn gbk ucs-2 utf-8 ~ - Chinese GB_2312-80 x - (Simplified) GBT_12345-90 x - MAC x - GBT-90_MAC x - GBK x - ISO10646 x x - - euc-tw big5 ucs-2 utf-8 ~ - Chinese CNS_1993 x - (Traditional) BIG5 x - ETEN x - ISO10646 x x - - euc-jp sjis ucs-2 utf-8 ~ - Japanese JIS_C_1978 x x - JIS_X_1983 x x - JIS_X_1990 x x x - MSWINDOWS x - KANJITALK6 x - KANJITALK7 x - - euc-kr cp949 ucs-2 utf-8 ~ - Korean KS_X_1992 x - MAC x - MSWINDOWS x - ISO10646 x x - -To set up the correct encoding and character set for printing some -Japanese text you would do the following; > - :set printencoding=euc-jp - :set printmbcharset=JIS_X_1983 - -If 'printmbcharset' is not one of the above values then it is assumed to -specify a custom multibyte character set and no check will be made that it is -compatible with the value for 'printencoding'. Vim will look for a file -defining the character set in the "print" directory in 'runtimepath'. - - *pmbfn-option* -'printmbfont' 'pmbfn' string (default "") - global -This is a comma-separated list of fields for font names to be used when -generating CJK output from |:hardcopy|. Each font name has to be preceded -with a letter indicating the style the font is to be used for as follows: - - r:{font-name} font to use for normal characters - b:{font-name} font to use for bold characters - i:{font-name} font to use for italic characters - o:{font-name} font to use for bold-italic characters - -A field with the r: prefix must be specified when doing CJK printing. The -other fontname specifiers are optional. If a specifier is missing then -another font will be used as follows: - - if b: is missing, then use r: - if i: is missing, then use r: - if o: is missing, then use b: - -Some CJK fonts do not contain characters for codes in the ASCII code range. -Also, some characters in the CJK ASCII code ranges differ in a few code points -from traditional ASCII characters. There are two additional fields to control -printing of characters in the ASCII code range. - - c:yes Use Courier font for characters in the ASCII - c:no (default) code range. - - a:yes Use ASCII character set for codes in the ASCII - a:no (default) code range. - -The following is an example of specifying two multibyte fonts, one for normal -and italic printing and one for bold and bold-italic printing, and using -Courier to print codes in the ASCII code range but using the national -character set: > - :set printmbfont=r:WadaMin-Regular,b:WadaMin-Bold,c:yes -< - *popt-option* -'printoptions' 'popt' string (default "") - global -This is a comma-separated list of items that control the format of the output -of |:hardcopy|: - - left:{spec} left margin (default: 10pc) - right:{spec} right margin (default: 5pc) - top:{spec} top margin (default: 5pc) - bottom:{spec} bottom margin (default: 5pc) - {spec} is a number followed by "in" for inches, "pt" - for points (1 point is 1/72 of an inch), "mm" for - millimeters or "pc" for a percentage of the media - size. - Weird example: - left:2in,top:30pt,right:16mm,bottom:3pc - If the unit is not recognized there is no error and - the default value is used. - - header:{nr} Number of lines to reserve for the header. - Only the first line is actually filled, thus when {nr} - is 2 there is one empty line. The header is formatted - according to 'printheader'. - header:0 Do not print a header. - header:2 (default) Use two lines for the header - - syntax:n Do not use syntax highlighting. This is faster and - thus useful when printing large files. - syntax:y Do syntax highlighting. - syntax:a (default) Use syntax highlighting if the printer appears to be - able to print color or grey. - - number:y Include line numbers in the printed output. - number:n (default) No line numbers. - - wrap:y (default) Wrap long lines. - wrap:n Truncate long lines. - - duplex:off Print on one side. - duplex:long (default) Print on both sides (when possible), bind on long - side. - duplex:short Print on both sides (when possible), bind on short - side. - - collate:y (default) Collating: 1 2 3, 1 2 3, 1 2 3 - collate:n No collating: 1 1 1, 2 2 2, 3 3 3 - - jobsplit:n (default) Do all copies in one print job - jobsplit:y Do each copy as a separate print job. Useful when - doing N-up postprocessing. - - portrait:y (default) Orientation is portrait. - portrait:n Orientation is landscape. - *a4* *letter* - paper:A4 (default) Paper size: A4 - paper:{name} Paper size from this table: - {name} size in cm size in inch ~ - 10x14 25.4 x 35.57 10 x 14 - A3 29.7 x 42 11.69 x 16.54 - A4 21 x 29.7 8.27 x 11.69 - A5 14.8 x 21 5.83 x 8.27 - B4 25 x 35.3 10.12 x 14.33 - B5 17.6 x 25 7.17 x 10.12 - executive 18.42 x 26.67 7.25 x 10.5 - folio 21 x 33 8.27 x 13 - ledger 43.13 x 27.96 17 x 11 - legal 21.59 x 35.57 8.5 x 14 - letter 21.59 x 27.96 8.5 x 11 - quarto 21.59 x 27.5 8.5 x 10.83 - statement 13.97 x 21.59 5.5 x 8.5 - tabloid 27.96 x 43.13 11 x 17 - - formfeed:n (default) Treat form feed characters (0x0c) as a normal print - character. - formfeed:y When a form feed character is encountered, continue - printing of the current line at the beginning of the - first line on a new page. - -The item indicated with (default) is used when the item is not present. The -values are not always used, especially when using a dialog to select the -printer and options. -Example: > - :set printoptions=paper:letter,duplex:off - -============================================================================== -3. PostScript Printing *postscript-printing* - *E455* *E456* *E457* *E624* -Provided you have enough disk space there should be no problems generating a -PostScript file. You need to have the runtime files correctly installed (if -you can find the help files, they probably are). - -There are currently a number of limitations with PostScript printing: - -- 'printfont' - The font name is ignored (the Courier family is always used - - it should be available on all PostScript printers) but the font size is - used. - -- 'printoptions' - The duplex setting is used when generating PostScript - output, but it is up to the printer to take notice of the setting. If the - printer does not support duplex printing then it should be silently ignored. - Some printers, however, don't print at all. - -- 8-bit support - While a number of 8-bit print character encodings are - supported it is possible that some characters will not print. Whether a - character will print depends on the font in the printer knowing the - character. Missing characters will be replaced with an upside down question - mark, or a space if that character is also not known by the font. It may be - possible to get all the characters in an encoding to print by installing a - new version of the Courier font family. - -- Multi-byte support - Currently Vim will try to convert multibyte characters - to the 8-bit encoding specified by 'printencoding' (or latin1 if it is - empty). Any characters that are not successfully converted are shown as - unknown characters. Printing will fail if Vim cannot convert the multibyte - to the 8-bit encoding. - -============================================================================== -4. Custom 8-bit Print Character Encodings *postscript-print-encoding* - *E618* *E619* -To use your own print character encoding when printing 8-bit character data -you need to define your own PostScript font encoding vector. Details on how -to define a font encoding vector is beyond the scope of this help file, but -you can find details in the PostScript Language Reference Manual, 3rd Edition, -published by Addison-Wesley and available in PDF form at -http://www.adobe.com/. The following describes what you need to do for Vim to -locate and use your print character encoding. - -i. Decide on a unique name for your encoding vector, one that does not clash - with any of the recognized or standard encoding names that Vim uses (see - |encoding-names| for a list), and that no one else is likely to use. -ii. Copy $VIMRUNTIME/print/latin1.ps to the print subdirectory in your - 'runtimepath' and rename it with your unique name. -iii. Edit your renamed copy of latin1.ps, replacing all occurrences of latin1 - with your unique name (don't forget the line starting %%Title:), and - modify the array of glyph names to define your new encoding vector. The - array must have exactly 256 entries or you will not be able to print! -iv. Within Vim, set 'printencoding' to your unique encoding name and then - print your file. Vim will now use your custom print character encoding. - -Vim will report an error with the resource file if you change the order or -content of the first 3 lines, other than the name of the encoding on the line -starting %%Title: or the version number on the line starting %%Version:. - -[Technical explanation for those that know PostScript - Vim looks for a file -with the same name as the encoding it will use when printing. The file -defines a new PostScript Encoding resource called /VIM-name, where name is the -print character encoding Vim will use.] - -============================================================================== -5. PostScript CJK Printing *postscript-cjk-printing* - *E673* *E674* *E675* - -Vim supports printing of Chinese, Japanese, and Korean files. Setting up Vim -to correctly print CJK files requires setting up a few more options. - -Each of these countries has many standard character sets and encodings which -require that both be specified when printing. In addition, CJK fonts normally -do not have the concept of italic glyphs and use different weight or stroke -style to achieve emphasis when printing. This in turn requires a different -approach to specifying fonts to use when printing. - -The encoding and character set are specified with the 'printencoding' and -'printmbcharset' options. If 'printencoding' is not specified then 'encoding' -is used as normal. If 'printencoding' is specified then characters will be -translated to this encoding for printing. You should ensure that the encoding -is compatible with the character set needed for the file contents or some -characters may not appear when printed. - -The fonts to use for CJK printing are specified with 'printmbfont'. This -option allows you to specify different fonts to use when printing characters -which are syntax highlighted with the font styles normal, italic, bold and -bold-italic. - -No CJK fonts are supplied with Vim. There are some free Korean, Japanese, and -Traditional Chinese fonts available at: - - http://examples.oreilly.com/cjkvinfo/adobe/samples/ - -You can find descriptions of the various fonts in the read me file at - - http://examples.oreilly.de/english_examples/cjkvinfo/adobe/00README - -Please read your printer documentation on how to install new fonts. - -CJK fonts can be large containing several thousand glyphs, and it is not -uncommon to find that they only contain a subset of a national standard. It -is not unusual to find the fonts to not include characters for codes in the -ASCII code range. If you find half-width Roman characters are not appearing -in your printout then you should configure Vim to use the Courier font the -half-width ASCII characters with 'printmbfont'. If your font does not include -other characters then you will need to find another font that does. - -Another issue with ASCII characters, is that the various national character -sets specify a couple of different glyphs in the ASCII code range. If you -print ASCII text using the national character set you may see some unexpected -characters. If you want true ASCII code printing then you need to configure -Vim to output ASCII characters for the ASCII code range with 'printmbfont'. - -It is possible to define your own multibyte character set although this -should not be attempted lightly. A discussion on the process if beyond the -scope of these help files. You can find details on CMap (character map) files -in the document 'Adobe CMap and CIDFont Files Specification, Version 1.0', -available from http://www.adobe.com as a PDF file. - -============================================================================== -6. PostScript Printing Troubleshooting *postscript-print-trouble* - *E621* -Usually the only sign of a problem when printing with PostScript is that your -printout does not appear. If you are lucky you may get a printed page that -tells you the PostScript operator that generated the error that prevented the -print job completing. - -There are a number of possible causes as to why the printing may have failed: - -- Wrong version of the prolog resource file. The prolog resource file - contains some PostScript that Vim needs to be able to print. Each version - of Vim needs one particular version. Make sure you have correctly installed - the runtime files, and don't have any old versions of a file called prolog - in the print directory in your 'runtimepath' directory. - -- Paper size. Some PostScript printers will abort printing a file if they do - not support the requested paper size. By default Vim uses A4 paper. Find - out what size paper your printer normally uses and set the appropriate paper - size with 'printoptions'. If you cannot find the name of the paper used, - measure a sheet and compare it with the table of supported paper sizes listed - for 'printoptions', using the paper that is closest in both width AND height. - Note: The dimensions of actual paper may vary slightly from the ones listed. - If there is no paper listed close enough, then you may want to try psresize - from PSUtils, discussed below. - -- Two-sided printing (duplex). Normally a PostScript printer that does not - support two-sided printing will ignore any request to do it. However, some - printers may abort the job altogether. Try printing with duplex turned off. - Note: Duplex prints can be achieved manually using PS utils - see below. - -- Collated printing. As with Duplex printing, most PostScript printers that - do not support collating printouts will ignore a request to do so. Some may - not. Try printing with collation turned off. - -- Syntax highlighting. Some print management code may prevent the generated - PostScript file from being printed on a black and white printer when syntax - highlighting is turned on, even if solid black is the only color used. Try - printing with syntax highlighting turned off. - -A safe printoptions setting to try is: > - - :set printoptions=paper:A4,duplex:off,collate:n,syntax:n - -Replace "A4" with the paper size that best matches your printer paper. - -============================================================================== -7. PostScript Utilities *postscript-print-util* - -7.1 Ghostscript - -Ghostscript is a PostScript and PDF interpreter that can be used to display -and print on non-PostScript printers PostScript and PDF files. It can also -generate PDF files from PostScript. - -Ghostscript will run on a wide variety of platforms. - -There are three available versions: - -- AFPL Ghostscript (formerly Aladdin Ghostscript) which is free for - non-commercial use. It can be obtained from: - - http://www.cs.wisc.edu/~ghost/ - -- GNU Ghostscript which is available under the GNU General Public License. It - can be obtained from: - - ftp://mirror.cs.wisc.edu/pub/mirrors/ghost/gnu/ - -- A commercial version for inclusion in commercial products. - -Additional information on Ghostscript can also be found at: - - http://www.ghostscript.com/ - -Support for a number of non PostScript printers is provided in the -distribution as standard, but if you cannot find support for your printer -check the Ghostscript site for other printers not included by default. - - -7.2 Ghostscript Previewers. - -The interface to Ghostscript is very primitive so a number of graphical front -ends have been created. These allow easier PostScript file selection, -previewing at different zoom levels, and printing. Check supplied -documentation for full details. - -X11 - -- Ghostview. Obtainable from: - - http://www.cs.wisc.edu/~ghost/gv/ - -- gv. Derived from Ghostview. Obtainable from: - - http://wwwthep.physik.uni-mainz.de/~plass/gv/ - - Copies (possibly not the most recent) can be found at: - - http://www.cs.wisc.edu/~ghost/gv/ - -MS-Windows - -- GSview. Obtainable from: - - http://www.cs.wisc.edu/~ghost/gsview/ - -Linux - -- GSview. Linux version of the popular MS-Windows previewer. - Obtainable from: - - http://www.cs.wisc.edu/~ghost/gsview/ - -- BMV. Different from Ghostview and gv in that it doesn't use X but svgalib. - Obtainable from: - - ftp://sunsite.unc.edu/pub/Linux/apps/graphics/viewers/svga/bmv-1.2.tgz - - -7.3 PSUtils - -PSUtils is a collection of utility programs for manipulating PostScript -documents. Binary distributions are available for many platforms, as well as -the full source. PSUtils can be found at: - - http://knackered.org/angus/psutils - -The utilities of interest include: - -- psnup. Convert PS files for N-up printing. -- psselect. Select page range and order of printing. -- psresize. Change the page size. -- psbook. Reorder and lay out pages ready for making a book. - -The output of one program can be used as the input to the next, allowing for -complex print document creation. - - -N-UP PRINTING - -The psnup utility takes an existing PostScript file generated from Vim and -convert it to an n-up version. The simplest way to create a 2-up printout is -to first create a PostScript file with: > - - :hardcopy > test.ps - -Then on your command line execute: > - - psnup -n 2 test.ps final.ps - -Note: You may get warnings from some Ghostscript previewers for files produced -by psnup - these may safely be ignored. - -Finally print the file final.ps to your PostScript printer with your -platform's print command. (You will need to delete the two PostScript files -afterwards yourself.) 'printexpr' could be modified to perform this extra -step before printing. - - -ALTERNATE DUPLEX PRINTING - -It is possible to achieve a poor man's version of duplex printing using the PS -utility psselect. This utility has options -e and -o for printing just the -even or odd pages of a PS file respectively. - -First generate a PS file with the 'hardcopy' command, then generate new -files with all the odd and even numbered pages with: > - - psselect -o test.ps odd.ps - psselect -e test.ps even.ps - -Next print odd.ps with your platform's normal print command. Then take the -print output, turn it over and place it back in the paper feeder. Now print -even.ps with your platform's print command. All the even pages should now -appear on the back of the odd pages. - -There are a couple of points to bear in mind: - -1. Position of the first page. If the first page is on top of the printout - when printing the odd pages then you need to reverse the order that the odd - pages are printed. This can be done with the -r option to psselect. This - will ensure page 2 is printed on the back of page 1. - Note: it is better to reverse the odd numbered pages rather than the even - numbered in case there are an odd number of pages in the original PS file. - -2. Paper flipping. When turning over the paper with the odd pages printed on - them you may have to either flip them horizontally (along the long edge) or - vertically (along the short edge), as well as possibly rotating them 180 - degrees. All this depends on the printer - it will be more obvious for - desktop ink jets than for small office laser printers where the paper path - is hidden from view. - - -============================================================================== -8. Formfeed Characters *printing-formfeed* - -By default Vim does not do any special processing of formfeed control -characters. Setting the 'printoptions' formfeed item will make Vim recognize -formfeed characters and continue printing the current line at the beginning -of the first line on a new page. The use of formfeed characters provides -rudimentary print control but there are certain things to be aware of. - -Vim will always start printing a line (including a line number if enabled) -containing a formfeed character, even if it is the first character on the -line. This means if a line starting with a formfeed character is the first -line of a page then Vim will print a blank page. - -Since the line number is printed at the start of printing the line containing -the formfeed character, the remainder of the line printed on the new page -will not have a line number printed for it (in the same way as the wrapped -lines of a long line when wrap in 'printoptions' is enabled). - -If the formfeed character is the last character on a line, then printing will -continue on the second line of the new page, not the first. This is due to -Vim processing the end of the line after the formfeed character and moving -down a line to continue printing. - -Due to the points made above it is recommended that when formfeed character -processing is enabled, printing of line numbers is disabled, and that form -feed characters are not the last character on a line. Even then you may need -to adjust the number of lines before a formfeed character to prevent -accidental blank pages. - -============================================================================== - vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/provider.txt b/runtime/doc/provider.txt index 9fd35f19c5..5375d971f0 100644 --- a/runtime/doc/provider.txt +++ b/runtime/doc/provider.txt @@ -36,7 +36,7 @@ itself). For Python 3 plugins: 1. Make sure Python 3.4+ is available in your $PATH. -2. Install the module (try "python" if "python3" is missing): > +2. Install the module (try "python" if "python3" is missing): >bash python3 -m pip install --user --upgrade pynvim The pip `--upgrade` flag ensures that you get the latest version even if @@ -46,7 +46,7 @@ See also |python-virtualenv|. Note: The old "neovim" module was renamed to "pynvim". https://github.com/neovim/neovim/wiki/Following-HEAD#20181118 -If you run into problems, uninstall _both_ then install "pynvim" again: > +If you run into problems, uninstall _both_ then install "pynvim" again: >bash python -m pip uninstall neovim pynvim python -m pip install --user --upgrade pynvim @@ -55,11 +55,11 @@ PYTHON PROVIDER CONFIGURATION ~ *g:python3_host_prog* Command to start Python 3 (executable, not directory). Setting this makes startup faster. Useful for working with virtualenvs. Must be set before any -check for has("python3"). > +check for has("python3"). >vim let g:python3_host_prog = '/path/to/python3' < *g:loaded_python3_provider* -To disable Python 3 support: > +To disable Python 3 support: >vim let g:loaded_python3_provider = 0 @@ -70,13 +70,13 @@ virtualenv for Neovim and hard-code the interpreter path via |g:python3_host_prog| so that the "pynvim" package is not required for each virtualenv. -Example using pyenv: > +Example using pyenv: >bash pyenv install 3.4.4 pyenv virtualenv 3.4.4 py3nvim pyenv activate py3nvim python3 -m pip install pynvim pyenv which python # Note the path -The last command reports the interpreter path, add it to your init.vim: > +The last command reports the interpreter path, add it to your init.vim: >vim let g:python3_host_prog = '/path/to/py3nvim/bin/python' See also: https://github.com/zchee/deoplete-jedi/wiki/Setting-up-Python-for-Neovim @@ -90,7 +90,7 @@ Nvim supports Ruby |remote-plugin|s and the Vim legacy |ruby-vim| interface RUBY QUICKSTART ~ -To use Ruby plugins with Nvim, install the latest "neovim" RubyGem: > +To use Ruby plugins with Nvim, install the latest "neovim" RubyGem: >bash gem install neovim Run |:checkhealth| to see if your system is up-to-date. @@ -98,7 +98,7 @@ Run |:checkhealth| to see if your system is up-to-date. RUBY PROVIDER CONFIGURATION ~ *g:loaded_ruby_provider* -To disable Ruby support: > +To disable Ruby support: >vim let g:loaded_ruby_provider = 0 < *g:ruby_host_prog* @@ -106,10 +106,10 @@ Command to start the Ruby host. By default this is "neovim-ruby-host". With project-local Ruby versions (via tools like RVM or rbenv) setting this can avoid the need to install the "neovim" gem in every project. -To use an absolute path (e.g. to an rbenv installation): > +To use an absolute path (e.g. to an rbenv installation): >vim let g:ruby_host_prog = '~/.rbenv/versions/2.4.1/bin/neovim-ruby-host' -To use the RVM "system" Ruby installation: > +To use the RVM "system" Ruby installation: >vim let g:ruby_host_prog = 'rvm system do neovim-ruby-host' ============================================================================== @@ -125,7 +125,7 @@ Note: Only perl versions from 5.22 onward are supported. PERL QUICKSTART~ -To use perl remote-plugins with Nvim, install the "Neovim::Ext" cpan package: > +To use perl remote-plugins with Nvim, install the "Neovim::Ext" cpan package: >bash cpanm -n Neovim::Ext Run |:checkhealth| to see if your system is up-to-date. @@ -133,12 +133,12 @@ Run |:checkhealth| to see if your system is up-to-date. PERL PROVIDER CONFIGURATION~ *g:loaded_perl_provider* -To disable Perl support: > +To disable Perl support: >vim :let g:loaded_perl_provider = 0 < *g:perl_host_prog* Command to start the Perl executable. Must be set before any -check for has("perl"). > +check for has("perl"). >vim let g:perl_host_prog = '/path/to/perl' < ============================================================================== @@ -150,7 +150,7 @@ https://github.com/neovim/node-client/ NODEJS QUICKSTART~ -To use javascript remote-plugins with Nvim, install the "neovim" npm package: > +To use javascript remote-plugins with Nvim, install the "neovim" npm package: >bash npm install -g neovim Run |:checkhealth| to see if your system is up-to-date. @@ -158,14 +158,14 @@ Run |:checkhealth| to see if your system is up-to-date. NODEJS PROVIDER CONFIGURATION~ *g:loaded_node_provider* -To disable Node.js support: > +To disable Node.js support: >vim :let g:loaded_node_provider = 0 < *g:node_host_prog* Command to start the Node.js host. Setting this makes startup faster. By default, Nvim searches for "neovim-node-host" using "npm root -g", which -can be slow. To avoid this, set g:node_host_prog to the host path: > +can be slow. To avoid this, set g:node_host_prog to the host path: >vim let g:node_host_prog = '/usr/local/bin/neovim-node-host' < ============================================================================== @@ -176,7 +176,7 @@ a |provider| which transparently uses shell commands to communicate with the system clipboard or any other clipboard "backend". To ALWAYS use the clipboard for ALL operations (instead of interacting with -the '+' and/or '*' registers explicitly): > +the "+" and/or "*" registers explicitly): >vim set clipboard+=unnamedplus See 'clipboard' for details and options. @@ -188,17 +188,18 @@ registers. Nvim looks for these clipboard tools, in order of priority: - |g:clipboard| - pbcopy, pbpaste (macOS) - wl-copy, wl-paste (if $WAYLAND_DISPLAY is set) + - waycopy, waypaste (if $WAYLAND_DISPLAY is set) - xclip (if $DISPLAY is set) - xsel (if $DISPLAY is set) - lemonade (for SSH) https://github.com/pocke/lemonade - - doitclient (for SSH) http://www.chiark.greenend.org.uk/~sgtatham/doit/ + - doitclient (for SSH) https://www.chiark.greenend.org.uk/~sgtatham/doit/ - win32yank (Windows) - termux (via termux-clipboard-set, termux-clipboard-set) - tmux (if $TMUX is set) *g:clipboard* To configure a custom clipboard tool, set g:clipboard to a dictionary. -For example this configuration integrates the tmux clipboard: > +For example this configuration integrates the tmux clipboard: >vim let g:clipboard = { \ 'name': 'myClipboard', @@ -218,7 +219,8 @@ the selection until the copy command process dies. When pasting, if the copy process has not died the cached selection is applied. g:clipboard can also use functions (see |lambda|) instead of strings. -For example this configuration uses the g:foo variable as a fake clipboard: > +For example this configuration uses the g:foo variable as a fake clipboard: +>vim let g:clipboard = { \ 'name': 'myClipboard', @@ -236,11 +238,27 @@ The "copy" function stores a list of lines and the register type. The "paste" function returns the clipboard as a `[lines, regtype]` list, where `lines` is a list of lines and `regtype` is a register type conforming to |setreg()|. + *clipboard-wsl* +For Windows WSL, try this g:clipboard definition: +>vim + let g:clipboard = { + \ 'name': 'WslClipboard', + \ 'copy': { + \ '+': 'clip.exe', + \ '*': 'clip.exe', + \ }, + \ 'paste': { + \ '+': 'powershell.exe -c [Console]::Out.Write($(Get-Clipboard -Raw).tostring().replace("`r", ""))', + \ '*': 'powershell.exe -c [Console]::Out.Write($(Get-Clipboard -Raw).tostring().replace("`r", ""))', + \ }, + \ 'cache_enabled': 0, + \ } + ============================================================================== Paste *provider-paste* *paste* "Paste" is a separate concept from |clipboard|: paste means "dump a bunch of -text to the editor", whereas clipboard provides features like |quote-+| to get +text to the editor", whereas clipboard provides features like |quote+| to get and set the OS clipboard directly. For example, middle-click or CTRL-SHIFT-v (macOS: CMD-v) in your terminal is "paste", not "clipboard": the terminal application (Nvim) just gets a stream of text, it does not interact with the @@ -266,7 +284,7 @@ many commands. Use the |cmdline-window| if you really want to paste multiple lines to the cmdline. You can implement a custom paste handler by redefining |vim.paste()|. -Example: > +Example: >lua vim.paste = (function(lines, phase) vim.api.nvim_put(lines, 'c', true, true) diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt index dab3bfa280..b1f7c927cc 100644 --- a/runtime/doc/quickfix.txt +++ b/runtime/doc/quickfix.txt @@ -466,7 +466,7 @@ You can parse a list of lines using 'errorformat' without creating or modifying a quickfix list using the |getqflist()| function. Examples: > echo getqflist({'lines' : ["F1:10:Line10", "F2:20:Line20"]}) echo getqflist({'lines' : systemlist('grep -Hn quickfix *')}) -This returns a dictionary where the 'items' key contains the list of quickfix +This returns a dictionary where the "items" key contains the list of quickfix entries parsed from lines. The following shows how to use a custom 'errorformat' to parse the lines without modifying the 'errorformat' option: > echo getqflist({'efm' : '%f#%l#%m', 'lines' : ['F1#10#Line']}) @@ -585,7 +585,7 @@ can go back to the unfiltered list using the |:colder|/|:lolder| command. quickfix command or function, the |b:changedtick| variable is incremented. You can get the number of this buffer using the getqflist() and getloclist() - functions by passing the 'qfbufnr' item. For a + functions by passing the "qfbufnr" item. For a location list, this buffer is wiped out when the location list is removed. @@ -916,7 +916,7 @@ To get the number of the current list in the stack: > screen). 5. The errorfile is read using 'errorformat'. 6. All relevant |QuickFixCmdPost| autocommands are - executed. See example below. + executed. See example below. 7. If [!] is not given the first error is jumped to. 8. The errorfile is deleted. 9. You can now move through the errors with commands @@ -1259,6 +1259,21 @@ not "b:current_compiler". What the command actually does is the following: For writing a compiler plugin, see |write-compiler-plugin|. +DOTNET *compiler-dotnet* + +The .NET CLI compiler outputs both errors and warnings by default. The output +may be limited to include only errors, by setting the g:dotnet_errors_only +variable to |v:true|. + +The associated project name is included in each error and warning. To suppress +the project name, set the g:dotnet_show_project_file variable to |v:false|. + +Example: limit output to only display errors, and suppress the project name: > + let dotnet_errors_only = v:true + let dotnet_show_project_file = v:false + compiler dotnet +< + GCC *quickfix-gcc* *compiler-gcc* There's one variable you can set for the GCC compiler: @@ -1287,7 +1302,7 @@ PYUNIT COMPILER *compiler-pyunit* This is not actually a compiler, but a unit testing framework for the Python language. It is included into standard Python distribution starting from version 2.0. For older versions, you can get it from -http://pyunit.sourceforge.net. +https://pyunit.sourceforge.net. When you run your tests with the help of the framework, possible errors are parsed by Vim and presented for you in quick-fix mode. @@ -1298,8 +1313,6 @@ Useful values for the 'makeprg' options therefore are: setlocal makeprg=./alltests.py " Run a testsuite setlocal makeprg=python\ %:S " Run a single testcase -Also see http://vim.sourceforge.net/tip_view.php?tip_id=280. - TEX COMPILER *compiler-tex* @@ -1572,8 +1585,9 @@ A call of |:clist| writes them accordingly with their correct filenames: Unlike the other prefixes that all match against whole lines, %P, %Q and %O can be used to match several patterns in the same line. Thus it is possible -to parse even nested files like in the following line: +to parse even nested files like in the following line: > {"file1" {"file2" error1} error2 {"file3" error3 {"file4" error4 error5}}} +< The %O then parses over strings that do not contain any push/pop file name information. See |errorformat-LaTeX| for an extended example. @@ -1823,7 +1837,7 @@ In English, that sed script: it as a "continuation of a multi-line message." *errorformat-ant* -For ant (http://jakarta.apache.org/) the above errorformat has to be modified +For ant (https://jakarta.apache.org/) the above errorformat has to be modified to honour the leading [javac] in front of each javac output line: > :set efm=%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%# @@ -1933,13 +1947,13 @@ by Vim. The default format for the lines displayed in the quickfix window and location list window is: - +> <filename>|<lnum> col <col>|<text> - +< The values displayed in each line correspond to the "bufnr", "lnum", "col" and "text" fields returned by the |getqflist()| function. -For some quickfix/location lists, the displayed text need to be customized. +For some quickfix/location lists, the displayed text needs to be customized. For example, if only the filename is present for a quickfix entry, then the two "|" field separator characters after the filename are not needed. Another use case is to customize the path displayed for a filename. By default, the @@ -1965,7 +1979,7 @@ The function should return a single line of text to display in the quickfix window for each entry from start_idx to end_idx. The function can obtain information about the entries using the |getqflist()| function and specifying the quickfix list identifier "id". For a location list, getloclist() function -can be used with the 'winid' argument. If an empty list is returned, then the +can be used with the "winid" argument. If an empty list is returned, then the default format is used to display all the entries. If an item in the returned list is an empty string, then the default format is used to display the corresponding entry. diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt index 6f16db5cc2..d17df3cd61 100644 --- a/runtime/doc/quickref.txt +++ b/runtime/doc/quickref.txt @@ -3,7 +3,8 @@ VIM REFERENCE MANUAL by Bram Moolenaar - Quick reference guide +============================================================================== +Quick reference guide *quickref* *Contents* tag subject tag subject ~ @@ -30,10 +31,10 @@ |Q_fo| Folding ------------------------------------------------------------------------------ -N is used to indicate an optional count that can be given before the command. ------------------------------------------------------------------------------- *Q_lr* Left-right motions +N is used to indicate an optional count that can be given before the command. + |h| N h left (also: CTRL-H, <BS>, or <Left> key) |l| N l right (also: <Space> or <Right> key) |0| 0 to first character in the line (also: <Home> key) @@ -56,6 +57,7 @@ N is used to indicate an optional count that can be given before the command. |;| N ; repeat the last "f", "F", "t", or "T" N times |,| N , repeat the last "f", "F", "t", or "T" N times in opposite direction + ------------------------------------------------------------------------------ *Q_ud* Up-down motions @@ -73,6 +75,7 @@ N is used to indicate an optional count that can be given before the command. given, otherwise it is the |%| command |gk| N gk up N screen lines (differs from "k" when line wraps) |gj| N gj down N screen lines (differs from "j" when line wraps) + ------------------------------------------------------------------------------ *Q_tm* Text object motions @@ -105,6 +108,7 @@ N is used to indicate an optional count that can be given before the command. |]#| N ]# N times forward to unclosed "#else" or "#endif" |[star| N [* N times back to start of comment "/*" |]star| N ]* N times forward to end of comment "*/" + ------------------------------------------------------------------------------ *Q_pa* Pattern searches @@ -168,6 +172,7 @@ N is used to indicate an optional count that can be given before the command. b[+num] [num] identical to s[+num] above (mnemonic: begin) b[-num] [num] identical to s[-num] above (mnemonic: begin) ;{search-command} execute {search-command} next + ------------------------------------------------------------------------------ *Q_ma* Marks and motions @@ -188,6 +193,7 @@ N is used to indicate an optional count that can be given before the command. |CTRL-O| N CTRL-O go to Nth older position in jump list |CTRL-I| N CTRL-I go to Nth newer position in jump list |:ju| :ju[mps] print the jump list + ------------------------------------------------------------------------------ *Q_vm* Various motions @@ -202,6 +208,7 @@ N is used to indicate an optional count that can be given before the command. |go| N go go to Nth byte in the buffer |:go| :[range]go[to] [off] go to [off] byte in the buffer + ------------------------------------------------------------------------------ *Q_ta* Using tags @@ -229,6 +236,7 @@ N is used to indicate an optional count that can be given before the command. |:ptjump| :ptj[ump] like ":tjump" but show tag in preview window |:pclose| :pc[lose] close tag preview window |CTRL-W_z| CTRL-W z close tag preview window + ------------------------------------------------------------------------------ *Q_sc* Scrolling @@ -247,6 +255,7 @@ These only work when 'wrap' is off: |zl| N zl scroll screen N characters to the left |zH| N zH scroll screen half a screenwidth to the right |zL| N zL scroll screen half a screenwidth to the left + ------------------------------------------------------------------------------ *Q_in* Inserting text @@ -263,6 +272,7 @@ These only work when 'wrap' is off: in Visual block mode: |v_b_I| I insert the same text in front of all the selected lines |v_b_A| A append the same text after all the selected lines + ------------------------------------------------------------------------------ *Q_ai* Insert mode keys @@ -279,6 +289,7 @@ moving around: |i_<S-Up>| shift-up/down one screenful backward/forward |i_<End>| <End> cursor after last character in the line |i_<Home>| <Home> cursor to first character in the line + ------------------------------------------------------------------------------ *Q_ss* Special keys in Insert mode @@ -313,6 +324,7 @@ moving around: |i_0_CTRL-D| 0 CTRL-D delete all indent in the current line |i_^_CTRL-D| ^ CTRL-D delete all indent in the current line, restore indent in next line + ------------------------------------------------------------------------------ *Q_di* Digraphs @@ -325,12 +337,14 @@ In Insert or Command-line mode: enter digraph |i_digraph| {char1} <BS> {char2} enter digraph if 'digraph' option set + ------------------------------------------------------------------------------ *Q_si* Special inserts |:r| :r [file] insert the contents of [file] below the cursor |:r!| :r! {command} insert the standard output of {command} below the cursor + ------------------------------------------------------------------------------ *Q_de* Deleting text @@ -346,6 +360,7 @@ In Insert or Command-line mode: |gJ| N gJ like "J", but without inserting spaces |v_gJ| {visual}gJ like "{visual}J", but without inserting spaces |:d| :[range]d [x] delete [range] lines [into register x] + ------------------------------------------------------------------------------ *Q_cm* Copying and moving text @@ -363,6 +378,7 @@ In Insert or Command-line mode: |[p| N [p like P, but adjust indent to current line |gp| N gp like p, but leave cursor after the new text |gP| N gP like P, but leave cursor after the new text + ------------------------------------------------------------------------------ *Q_ch* Changing text @@ -418,6 +434,7 @@ In Insert or Command-line mode: left-align the lines in [range] (with [indent]) |:ri| :[range]ri[ght] [width] right-align the lines in [range] + ------------------------------------------------------------------------------ *Q_co* Complex changes @@ -444,6 +461,7 @@ In Insert or Command-line mode: |:ret| :[range]ret[ab][!] [tabstop] set 'tabstop' to new value and adjust white space accordingly + ------------------------------------------------------------------------------ *Q_vi* Visual mode @@ -457,6 +475,7 @@ In Insert or Command-line mode: |v_v| v highlight characters or stop highlighting |v_V| V highlight linewise or stop highlighting |v_CTRL-V| CTRL-V highlight blockwise or stop highlighting + ------------------------------------------------------------------------------ *Q_to* Text objects (only in Visual mode or after an operator) @@ -509,6 +528,7 @@ In Insert or Command-line mode: |:sl| :sl[eep] [sec] don't do anything for [sec] seconds |gs| N gs goto Sleep for N seconds + ------------------------------------------------------------------------------ *Q_km* Key mapping @@ -556,6 +576,7 @@ In Insert or Command-line mode: like ":mkvimrc", but store current files, windows, etc. too, to be able to continue this session later + ------------------------------------------------------------------------------ *Q_ab* Abbreviations @@ -570,6 +591,7 @@ In Insert or Command-line mode: |:abclear| :abc[lear] remove all abbreviations |:cabclear| :cabc[lear] remove all abbr's for Cmdline mode |:iabclear| :iabc[lear] remove all abbr's for Insert mode + ------------------------------------------------------------------------------ *Q_op* Options @@ -615,10 +637,6 @@ Short explanation of each option: *option-list* 'backupdir' 'bdir' list of directories for the backup file 'backupext' 'bex' extension used for the backup file 'backupskip' 'bsk' no backup for files that match these patterns -'balloondelay' 'bdlay' delay in mS before a balloon may pop up -'ballooneval' 'beval' switch on balloon evaluation in the GUI -'balloonevalterm' 'bevalterm' switch on balloon evaluation in the terminal -'balloonexpr' 'bexpr' expression to show in balloon 'belloff' 'bo' do not ring the bell for these reasons 'binary' 'bin' read/write/edit file in binary mode 'bomb' prepend a Byte Order Mark to the file @@ -649,17 +667,12 @@ Short explanation of each option: *option-list* 'complete' 'cpt' specify how Insert mode completion works 'completefunc' 'cfu' function to be used for Insert mode completion 'completeopt' 'cot' options for Insert mode completion +'completeslash' 'csl' like 'shellslash' for completion 'concealcursor' 'cocu' whether concealable text is hidden in cursor line 'conceallevel' 'cole' whether concealable text is shown or hidden 'confirm' 'cf' ask what to do about unsaved/read-only files 'copyindent' 'ci' make 'autoindent' use existing indent structure 'cpoptions' 'cpo' flags for Vi-compatible behavior -'cscopepathcomp' 'cspc' how many components of the path to show -'cscopeprg' 'csprg' command to execute cscope -'cscopequickfix' 'csqf' use quickfix window for cscope results -'cscoperelative' 'csre' Use cscope.out path basename as prefix -'cscopetag' 'cst' use cscope for tag commands -'cscopetagorder' 'csto' determines ":cstag" search order 'cursorbind' 'crb' move cursor in window as it moves in other windows 'cursorcolumn' 'cuc' highlight the screen column of the cursor 'cursorline' 'cul' highlight the screen line of the cursor @@ -676,6 +689,7 @@ Short explanation of each option: *option-list* 'display' 'dy' list of flags for how to display text 'eadirection' 'ead' in which direction 'equalalways' works 'encoding' 'enc' encoding used internally +'endoffile' 'eof' write CTRL-Z at end of the file 'endofline' 'eol' write <EOL> for last line in file 'equalalways' 'ea' windows are automatically made the same size 'equalprg' 'ep' external program to use for "=" command @@ -684,7 +698,7 @@ Short explanation of each option: *option-list* 'errorformat' 'efm' description of the lines in the error file 'eventignore' 'ei' autocommand events that are ignored 'expandtab' 'et' use spaces when <Tab> is inserted -'exrc' 'ex' read .nvimrc and .exrc in the current directory +'exrc' 'ex' read init files in the current directory 'fileencoding' 'fenc' file encoding for multibyte text 'fileencodings' 'fencs' automatically detected character encodings 'fileformat' 'ff' file format used for file I/O @@ -759,6 +773,7 @@ Short explanation of each option: *option-list* 'lines' number of lines in the display 'linespace' 'lsp' number of pixel lines to use between characters 'lisp' automatic indenting for Lisp +'lispoptions' 'lop' changes how Lisp indenting is done 'lispwords' 'lw' words that change how lisp indenting works 'list' show <Tab> and <EOL> 'listchars' 'lcs' characters for displaying in list mode @@ -785,6 +800,7 @@ Short explanation of each option: *option-list* 'mousefocus' 'mousef' keyboard focus follows the mouse 'mousehide' 'mh' hide mouse pointer while typing 'mousemodel' 'mousem' changes meaning of mouse buttons +'mousemoveevent' 'mousemev' report mouse moves with <MouseMove> 'mousescroll' amount to scroll by when scrolling with a mouse 'mouseshape' 'mouses' shape of the mouse pointer in different modes 'mousetime' 'mouset' max time between mouse double-click @@ -801,23 +817,12 @@ Short explanation of each option: *option-list* 'patchexpr' 'pex' expression used to patch a file 'patchmode' 'pm' keep the oldest version of a file 'path' 'pa' list of directories searched with "gf" et.al. -'perldll' name of the Perl dynamic library 'preserveindent' 'pi' preserve the indent structure when reindenting 'previewheight' 'pvh' height of the preview window 'previewpopup' 'pvp' use popup window for preview 'previewwindow' 'pvw' identifies the preview window -'printdevice' 'pdev' name of the printer to be used for :hardcopy -'printencoding' 'penc' encoding to be used for printing -'printexpr' 'pexpr' expression used to print PostScript for :hardcopy -'printfont' 'pfn' name of the font to be used for :hardcopy -'printheader' 'pheader' format of the header used for :hardcopy -'printmbcharset' 'pmbcs' CJK character set to be used for :hardcopy -'printmbfont' 'pmbfn' font names to be used for CJK output of :hardcopy -'printoptions' 'popt' controls the format of :hardcopy output -'pumheight' 'ph' maximum height of the popup menu +'pumheight' 'ph' maximum number of items to show in the popup menu 'pumwidth' 'pw' minimum width of the popup menu -'pythondll' name of the Python 2 dynamic library -'pythonthreedll' name of the Python 3 dynamic library 'pyxversion' 'pyx' Python version used for pyx* commands 'quoteescape' 'qe' escape characters used in a string 'readonly' 'ro' disallow writing the buffer @@ -828,7 +833,6 @@ Short explanation of each option: *option-list* 'revins' 'ri' inserting characters will work backwards 'rightleft' 'rl' window is right-to-left oriented 'rightleftcmd' 'rlc' commands for which editing works right-to-left -'rubydll' name of the Ruby dynamic library 'ruler' 'ru' show cursor line and column in the status line 'rulerformat' 'ruf' custom format for the ruler 'runtimepath' 'rtp' list of directories used for runtime files @@ -856,7 +860,8 @@ Short explanation of each option: *option-list* 'shiftwidth' 'sw' number of spaces to use for (auto)indent step 'shortmess' 'shm' list of flags, reduce length of messages 'showbreak' 'sbr' string to use at the start of wrapped lines -'showcmd' 'sc' show (partial) command in status line +'showcmd' 'sc' show (partial) command somewhere +'showcmdloc' 'sloc' where to show (partial) command 'showfulltag' 'sft' show full tag pattern when completing tag 'showmatch' 'sm' briefly jump to matching bracket if insert one 'showmode' 'smd' message on status line to show current mode @@ -875,8 +880,10 @@ Short explanation of each option: *option-list* 'spelloptions' 'spo' options for spell checking 'spellsuggest' 'sps' method(s) used to suggest spelling corrections 'splitbelow' 'sb' new window from split is below the current one +'splitkeep' 'spk' determines scroll behavior for split windows 'splitright' 'spr' new window is put right of the current one 'startofline' 'sol' commands move cursor to first non-blank in line +'statuscolumn' 'stc' custom format for the status column 'statusline' 'stl' custom format for the status line 'suffixes' 'su' suffixes that are ignored with multiple match 'suffixesadd' 'sua' suffixes added when searching for a file @@ -889,6 +896,7 @@ Short explanation of each option: *option-list* 'tabstop' 'ts' number of spaces that <Tab> in file uses 'tagbsearch' 'tbs' use binary searching in tags files 'tagcase' 'tc' how to handle case when searching in tags files +'tagfunc' 'tfu' function to get list of tag matches 'taglength' 'tl' number of significant characters for a tag 'tagrelative' 'tr' file names in tag file are relative 'tags' 'tag' list of file names used by the tag command @@ -947,18 +955,21 @@ Short explanation of each option: *option-list* 'writeany' 'wa' write to file with no need for "!" override 'writebackup' 'wb' make a backup before overwriting a file 'writedelay' 'wd' delay this many msec for each char (for debug) + ------------------------------------------------------------------------------ *Q_ur* Undo/Redo commands |u| N u undo last N changes |CTRL-R| N CTRL-R redo last N undone changes |U| U restore last changed line + ------------------------------------------------------------------------------ *Q_et* External commands |:!| :!{command} execute {command} with a shell |K| K lookup keyword under the cursor with 'keywordprg' program (default: "man") + ------------------------------------------------------------------------------ *Q_qf* Quickfix commands @@ -982,6 +993,7 @@ Short explanation of each option: *option-list* error |:grep| :gr[ep] [args] execute 'grepprg' to find matches and jump to the first one + ------------------------------------------------------------------------------ *Q_vc* Various commands @@ -1007,6 +1019,7 @@ Short explanation of each option: *option-list* unsaved changes or read-only files |:browse| :browse {command} open/read/write file, using a file selection dialog + ------------------------------------------------------------------------------ *Q_ce* Command-line editing @@ -1053,6 +1066,7 @@ Context-sensitive completion on the command-line: to next match |c_CTRL-P| CTRL-P after 'wildchar' with multiple matches: go to previous match + ------------------------------------------------------------------------------ *Q_ra* Ex ranges @@ -1073,6 +1087,7 @@ Context-sensitive completion on the command-line: (default: 1) |:range| -[num] subtract [num] from the preceding line number (default: 1) + ------------------------------------------------------------------------------ *Q_ex* Special Ex characters @@ -1105,6 +1120,7 @@ Context-sensitive completion on the command-line: |::r| :r root (extension removed) |::e| :e extension |::s| :s/{pat}/{repl}/ substitute {pat} with {repl} + ------------------------------------------------------------------------------ *Q_st* Starting Vim @@ -1141,6 +1157,7 @@ Context-sensitive completion on the command-line: |--help| --help show list of arguments and exit |--version| --version show version info and exit |--| - read file from stdin + ------------------------------------------------------------------------------ *Q_ed* Editing a file @@ -1160,6 +1177,7 @@ Context-sensitive completion on the command-line: position |:file| :f[ile] {name} set the current file name to {name} |:files| :files show alternate file names + ------------------------------------------------------------------------------ *Q_fl* Using the argument list |argument-list| @@ -1180,6 +1198,7 @@ Context-sensitive completion on the command-line: |:Next| :N[ext] :sN[ext] edit previous file |:first| :fir[st] :sfir[st] edit first file |:last| :la[st] :sla[st] edit last file + ------------------------------------------------------------------------------ *Q_wq* Writing and quitting @@ -1217,6 +1236,7 @@ Context-sensitive completion on the command-line: |:stop| :st[op][!] suspend Vim or start new shell; if 'aw' option is set and [!] not given write the buffer |CTRL-Z| CTRL-Z same as ":stop" + ------------------------------------------------------------------------------ *Q_ac* Automatic Commands @@ -1248,6 +1268,7 @@ Context-sensitive completion on the command-line: with {pat} |:autocmd| :au! {event} {pat} {cmd} remove all autocommands for {event} with {pat} and enter new one + ------------------------------------------------------------------------------ *Q_wi* Multi-window commands @@ -1293,6 +1314,7 @@ Context-sensitive completion on the command-line: |CTRL-W_>| CTRL-W > increase current window width |CTRL-W_bar| CTRL-W | set current window width (default: widest possible) + ------------------------------------------------------------------------------ *Q_bu* Buffer list commands @@ -1314,6 +1336,7 @@ Context-sensitive completion on the command-line: |:bfirst| :bfirst :sbfirst to first arg/buf |:blast| :blast :sblast to last arg/buf |:bmodified| :[N]bmod [N] :[N]sbmod [N] to Nth modified buf + ------------------------------------------------------------------------------ *Q_sy* Syntax Highlighting @@ -1340,6 +1363,7 @@ Context-sensitive completion on the command-line: |:filetype| :filetype plugin indent on switch on file type detection, with automatic indenting and settings + ------------------------------------------------------------------------------ *Q_gu* GUI commands @@ -1352,6 +1376,7 @@ Context-sensitive completion on the command-line: add toolbar item, giving {rhs} |:tmenu| :tmenu {mpath} {text} add tooltip to menu {mpath} |:unmenu| :unmenu {mpath} remove menu {mpath} + ------------------------------------------------------------------------------ *Q_fo* Folding diff --git a/runtime/doc/remote.txt b/runtime/doc/remote.txt index 0c1e3438de..4610088ab0 100644 --- a/runtime/doc/remote.txt +++ b/runtime/doc/remote.txt @@ -52,6 +52,10 @@ The following command line arguments are available: *--remote-expr* --remote-expr {expr} Evaluate {expr} in server and print the result on stdout. + *--remote-ui* + --remote-ui Display the UI of the server in the terminal. + Fully interactive: keyboard and mouse input + are forwarded to the server. *--server* --server {addr} Connect to the named pipe or socket at the given address for executing remote commands. diff --git a/runtime/doc/repeat.txt b/runtime/doc/repeat.txt index 508565dea4..1bbd20702b 100644 --- a/runtime/doc/repeat.txt +++ b/runtime/doc/repeat.txt @@ -83,7 +83,8 @@ pattern and do not match another pattern: > This first finds all lines containing "found", but only executes {cmd} when there is no match for "notfound". -To execute a non-Ex command, you can use the `:normal` command: > +Any Ex command can be used, see |ex-cmd-index|. To execute a Normal mode +command, you can use the `:normal` command: > :g/pat/normal {commands} Make sure that {commands} ends with a whole command, otherwise Vim will wait for you to type the rest of the command for each match. The screen will not @@ -288,7 +289,7 @@ For writing a Vim script, see chapter 41 of the user manual |usr_41.txt|. how this can be useful. This is normally done automatically during startup, - after loading your .vimrc file. With this command it + after loading your |vimrc| file. With this command it can be done earlier. Packages will be loaded only once. Using @@ -470,7 +471,7 @@ flag when defining the function, it is not relevant when executing it. > :set cpo-=C < *line-continuation-comment* -To add a comment in between the lines start with '"\ '. Notice the space +To add a comment in between the lines start with `'"\ '`. Notice the space after the backslash. Example: > let array = [ "\ first entry comment @@ -490,29 +491,40 @@ Rationale: continuation lines to be part of the comment. Since it was like this for a long time, when making it possible to add a comment halfway a sequence of continuation lines, it was not possible to use \", since - that was a valid continuation line. Using '"\ ' comes closest, even + that was a valid continuation line. Using `'"\ '` comes closest, even though it may look a bit weird. Requiring the space after the backslash is to make it very unlikely this is a normal comment line. ============================================================================== Using Vim packages *packages* -A Vim package is a directory that contains one or more plugins. The -advantages over normal plugins: -- A package can be downloaded as an archive and unpacked in its own directory. - Thus the files are not mixed with files of other plugins. That makes it - easy to update and remove. -- A package can be a git, mercurial, etc. repository. That makes it really - easy to update. -- A package can contain multiple plugins that depend on each other. -- A package can contain plugins that are automatically loaded on startup and - ones that are only loaded when needed with `:packadd`. +A Vim "package" is a directory that contains |plugin|s. Compared to normal +plugins, a package can... +- be downloaded as an archive and unpacked in its own directory, so the files + are not mixed with files of other plugins. +- be a git, mercurial, etc. repository, thus easy to update. +- contain multiple plugins that depend on each other. +- contain plugins that are automatically loaded on startup ("start" packages, + located in "pack/*/start/*") and ones that are only loaded when needed with + |:packadd| ("opt" packages, located in "pack/*/opt/*"). + *runtime-search-path* +Nvim searches for |:runtime| files in: + 1. all paths in 'runtimepath' + 2. all "pack/*/start/*" dirs + +Note that the "pack/*/start/*" paths are not explicitly included in +'runtimepath', so they will not be reported by ":set rtp" or "echo &rtp". +Scripts can use |nvim_list_runtime_paths()| to list all used directories, and +|nvim_get_runtime_file()| to query for specific files or sub-folders within +the runtime path. Example: > + " List all runtime dirs and packages with Lua paths. + :echo nvim_get_runtime_file("lua/", v:true) Using a package and loading automatically ~ -Let's assume your Vim files are in the "~/.local/share/nvim/site" directory -and you want to add a package from a zip archive "/tmp/foopack.zip": +Let's assume your Nvim files are in "~/.local/share/nvim/site" and you want to +add a package from a zip archive "/tmp/foopack.zip": % mkdir -p ~/.local/share/nvim/site/pack/foo % cd ~/.local/share/nvim/site/pack/foo % unzip /tmp/foopack.zip @@ -525,28 +537,22 @@ You would now have these files under ~/.local/share/nvim/site: pack/foo/start/foobar/syntax/some.vim pack/foo/opt/foodebug/plugin/debugger.vim - *runtime-search-path* -When runtime files are searched for, first all paths in 'runtimepath' are -searched, then all "pack/*/start/*" dirs are searched. However, package entries -are not visible in `:set rtp` or `echo &rtp`, as the final concatenated path -would be too long and get truncated. To list all used directories, use -|nvim_list_runtime_paths()|. In addition |nvim_get_runtime_file()| can be used -to query for specific files or sub-folders within the runtime path. For -instance to list all runtime dirs and packages with lua paths, use > - - :echo nvim_get_runtime_file("lua/", v:true) +On startup after processing your |config|, Nvim scans all directories in +'packpath' for plugins in "pack/*/start/*", then loads the plugins. -<When Vim starts up, after processing your .vimrc, it scans all directories in -'packpath' for plugins under the "pack/*/start" directory, and all the plugins -are loaded. +To allow for calling into package functionality while parsing your |vimrc|, +|:colorscheme| and |autoload| will both automatically search under 'packpath' +as well in addition to 'runtimepath'. See the documentation for each for +details. -In the example Vim will find "pack/foo/start/foobar/plugin/foo.vim" and load it. +In the example Nvim will find "pack/foo/start/foobar/plugin/foo.vim" and load +it. -If the "foobar" plugin kicks in and sets the 'filetype' to "some", Vim will +If the "foobar" plugin kicks in and sets the 'filetype' to "some", Nvim will find the syntax/some.vim file, because its directory is in the runtime search path. -Vim will also load ftdetect files, if there are any. +Nvim will also load ftdetect files, if there are any. Note that the files under "pack/foo/opt" are not loaded automatically, only the ones under "pack/foo/start". See |pack-add| below for how the "opt" directory @@ -588,12 +594,12 @@ This searches for "pack/*/opt/foodebug" in 'packpath' and will find it. This could be done if some conditions are met. For example, depending on -whether Vim supports a feature or a dependency is missing. +whether Nvim supports a feature or a dependency is missing. You can also load an optional plugin at startup, by putting this command in -your |.vimrc|: > +your |config|: > :packadd! foodebug -The extra "!" is so that the plugin isn't loaded if Vim was started with +The extra "!" is so that the plugin isn't loaded if Nvim was started with |--noplugin|. It is perfectly normal for a package to only have files in the "opt" @@ -605,7 +611,7 @@ Where to put what ~ Since color schemes, loaded with `:colorscheme`, are found below "pack/*/start" and "pack/*/opt", you could put them anywhere. We recommend you put them below "pack/*/opt", for example -".vim/pack/mycolors/opt/dark/colors/very_dark.vim". +"~/.config/nvim/pack/mycolors/opt/dark/colors/very_dark.vim". Filetype plugins should go under "pack/*/start", so that they are always found. Unless you have more than one plugin for a file type and want to @@ -683,8 +689,8 @@ found automatically. Your package would have these files: < pack/foo/start/lib/autoload/foolib.vim > func foolib#getit() -This works, because start packages will be used to look for autoload files, -when sourcing the plugins. +This works, because start packages will be searched for autoload files, when +sourcing the plugins. ============================================================================== Debugging scripts *debug-scripts* diff --git a/runtime/doc/rileft.txt b/runtime/doc/rileft.txt index aa11462595..4f68ab562c 100644 --- a/runtime/doc/rileft.txt +++ b/runtime/doc/rileft.txt @@ -12,8 +12,9 @@ These functions were originally created by Avner Lottem: E-mail: alottem@iil.intel.com Phone: +972-4-8307322 +------------------------------------------------------------------------------ Introduction ------------- + Some languages such as Arabic, Farsi, Hebrew (among others) require the ability to display their text from right-to-left. Files in those languages are stored conventionally and the right-to-left requirement is only a @@ -32,8 +33,9 @@ as this kind of support is out of the scope of a simple addition to an existing editor (and it's not sanctioned by Unicode either). +------------------------------------------------------------------------------ Highlights ----------- + o Editing left-to-right files as in the original Vim, no change. o Viewing and editing files in right-to-left windows. File orientation @@ -56,11 +58,11 @@ o Many languages use and require right-to-left support. These languages current supported languages include - |arabic.txt| and |hebrew.txt|. +------------------------------------------------------------------------------ Of Interest... --------------- o Invocations - ----------- + + 'rightleft' ('rl') sets window orientation to right-to-left. + 'delcombine' ('deco'), boolean, if editing UTF-8 encoded languages, allows one to remove a composing character which gets superimposed @@ -69,7 +71,7 @@ o Invocations (such as search) to be utilized in right-to-left orientation as well. o Typing backwards *ins-reverse* - ---------------- + In lieu of using the full-fledged 'rightleft' option, one can opt for reverse insertion. When the 'revins' (reverse insert) option is set, inserting happens backwards. This can be used to type right-to-left @@ -85,15 +87,16 @@ o Typing backwards *ins-reverse* in the status line when reverse Insert mode is active. o Pasting when in a rightleft window - ---------------------------------- + When cutting text with the mouse and pasting it in a rightleft window the text will be reversed, because the characters come from the cut buffer from the left to the right, while inserted in the file from the right to the left. In order to avoid it, toggle 'revins' before pasting. +------------------------------------------------------------------------------ Bugs ----- + o Does not handle CTRL-A and CTRL-X commands (add and subtract) correctly when in rightleft window. diff --git a/runtime/doc/russian.txt b/runtime/doc/russian.txt index a2bc9f3b5e..8d3ed360c8 100644 --- a/runtime/doc/russian.txt +++ b/runtime/doc/russian.txt @@ -45,7 +45,7 @@ If you wish to use messages, help files, menus and other items translated to Russian, you will need to install the RuVim Language Pack, available in different codepages from - http://www.sourceforge.net/projects/ruvim/ + https://www.sourceforge.net/projects/ruvim/ After downloading an archive from RuVim project, unpack it into your $VIMRUNTIME directory. We recommend using UTF-8 archive. diff --git a/runtime/doc/sign.txt b/runtime/doc/sign.txt index a2a5645baa..d09d0f226f 100644 --- a/runtime/doc/sign.txt +++ b/runtime/doc/sign.txt @@ -334,8 +334,10 @@ See |sign_getplaced()| for the equivalent Vim script function. :sign place group=* buffer={nr} List signs in all the groups placed in buffer {nr}. +:sign place List placed signs in the global group in all files. + :sign place group={group} - List placed signs in all sign groups in all the files. + List placed signs with sign group {group} in all files. :sign place group=* List placed signs in all sign groups in all files. @@ -381,15 +383,14 @@ sign_define({list}) icon full path to the bitmap file for the sign. linehl highlight group used for the whole line the sign is placed in. + numhl highlight group used for the line number where + the sign is placed. text text that is displayed when there is no icon or the GUI is not being used. texthl highlight group used for the text item culhl highlight group used for the text item when the cursor is on the same line as the sign and 'cursorline' is enabled. - numhl highlight group used for 'number' column at the - associated line. Overrides |hl-LineNr|, - |hl-CursorLineNr|. If the sign named {name} already exists, then the attributes of the sign are updated. @@ -431,6 +432,8 @@ sign_getdefined([{name}]) *sign_getdefined()* linehl highlight group used for the whole line the sign is placed in; not present if not set. name name of the sign + numhl highlight group used for the line number where + the sign is placed; not present if not set. text text that is displayed when there is no icon or the GUI is not being used. texthl highlight group used for the text item; not @@ -439,9 +442,6 @@ sign_getdefined([{name}]) *sign_getdefined()* the cursor is on the same line as the sign and 'cursorline' is enabled; not present if not set. - numhl highlight group used for 'number' column at the - associated line. Overrides |hl-LineNr|, - |hl-CursorLineNr|; not present if not set. Returns an empty List if there are no signs and when {name} is not found. @@ -606,9 +606,9 @@ sign_placelist({list}) then a new unique identifier is allocated. Otherwise the specified number is used. See |sign-identifier| for more information. - lnum line number in the buffer {buf} where the - sign is to be placed. For the accepted values, - see |line()|. + lnum line number in the buffer where the sign is to + be placed. For the accepted values, see + |line()|. name name of the sign to place. See |sign_define()| for more information. priority priority of the sign. When multiple signs are diff --git a/runtime/doc/spell.txt b/runtime/doc/spell.txt index 23d5905ec3..98a6af1b8b 100644 --- a/runtime/doc/spell.txt +++ b/runtime/doc/spell.txt @@ -482,7 +482,7 @@ You can create a Vim spell file from the .aff and .dic files that Myspell uses. Myspell is used by OpenOffice.org and Mozilla. The OpenOffice .oxt files are zip files which contain the .aff and .dic files. You should be able to find them here: - http://extensions.services.openoffice.org/dictionary + https://extensions.services.openoffice.org/dictionary The older, OpenOffice 2 files may be used if this doesn't work: http://wiki.services.openoffice.org/wiki/Dictionaries You can also use a plain word list. The results are the same, the choice @@ -764,13 +764,13 @@ them before the Vim word list is made. The tools for this can be found in the The format for the affix and word list files is based on what Myspell uses (the spell checker of Mozilla and OpenOffice.org). A description can be found here: - http://lingucomponent.openoffice.org/affix.readme ~ + https://lingucomponent.openoffice.org/affix.readme ~ Note that affixes are case sensitive, this isn't obvious from the description. Vim supports quite a few extras. They are described below |spell-affix-vim|. Attempts have been made to keep this compatible with other spell checkers, so that the same files can often be used. One other project that offers more -than Myspell is Hunspell ( http://hunspell.sf.net ). +than Myspell is Hunspell ( https://hunspell.github.io ). WORD LIST FORMAT *spell-dic-format* @@ -886,7 +886,7 @@ right encoding. *spell-AUTHOR* *spell-EMAIL* *spell-COPYRIGHT* NAME Name of the language VERSION 1.0.1 with fixes - HOME http://www.myhome.eu + HOME https://www.example.com AUTHOR John Doe EMAIL john AT Doe DOT net COPYRIGHT LGPL @@ -992,8 +992,8 @@ Note: even when using "num" or "long" the number of flags available to compounding and prefixes is limited to about 250. -AFFIXES - *spell-PFX* *spell-SFX* +AFFIXES *spell-PFX* *spell-SFX* + The usual PFX (prefix) and SFX (suffix) lines are supported (see the Myspell documentation or the Aspell manual: http://aspell.net/man-html/Affix-Compression.html). @@ -1583,7 +1583,7 @@ CHECKCOMPOUNDTRIPLE (Hunspell) *spell-CHECKCOMPOUNDTRIPLE* Forbid three identical characters when compounding. Not supported. -CHECKSHARPS (Hunspell)) *spell-CHECKSHARPS* +CHECKSHARPS (Hunspell) *spell-CHECKSHARPS* SS letter pair in uppercased (German) words may be upper case sharp s (ß). Not supported. diff --git a/runtime/doc/starting.txt b/runtime/doc/starting.txt index d57a85423c..179bacdb24 100644 --- a/runtime/doc/starting.txt +++ b/runtime/doc/starting.txt @@ -9,7 +9,7 @@ Starting Vim *starting* Type |gO| to see the table of contents. ============================================================================== -Nvim arguments *vim-arguments* +Nvim arguments *cli-arguments* Most often, Nvim is started to edit a single file with the command: > @@ -31,11 +31,11 @@ filename One or more file names. The first one will be the current To avoid a file name starting with a '-' being interpreted as an option, precede the arglist with "--", e.g.: > nvim -- -filename -< All arguments after the "--" will be interpreted as file names, - no other options or "+command" argument can follow. +< All arguments after "--" are interpreted as file names, no + other options or "+command" arguments can follow. *--* -- Alias for stdin (standard input). +`-` Alias for stdin (standard input). Example: > echo text | nvim - file < "text" is read into buffer 1, "file" is opened as buffer 2. @@ -82,12 +82,10 @@ argument. --help *-h* *--help* *-?* -? -h Give usage (help) message and exit. - See |info-message| about capturing the text. --version *-v* *--version* -v Print version information and exit. Same output as for |:version| command. - See |info-message| about capturing the text. *--clean* --clean Mimics a fresh install of Nvim: @@ -145,15 +143,12 @@ argument. these commands, independently from "-c" commands. *-S* --S {file} The {file} will be sourced after the first file has been read. - This is an easy way to do the equivalent of: > +-S [file] Executes Vimscript or Lua (".lua") [file] after the first file + has been read. See also |:source|. If [file] is not given, + defaults to "Session.vim". Equivalent to: > -c "source {file}" -< It can be mixed with "-c" arguments and repeated like "-c". - The limit of 10 "-c" arguments applies here as well. - {file} cannot start with a "-". - --S Works like "-S Session.vim". Only when used as the last - argument or when another "-" option follows. +< Can be repeated like "-c", subject to the same limit of 10 + "-c" arguments. {file} cannot start with a "-". -L *-L* *-r* -r Recovery mode. Without a file name argument, a list of @@ -195,8 +190,9 @@ argument. -E reads stdin as text (into buffer 1). -es *-es* *-Es* *-s-ex* *silent-mode* --Es Silent mode (no UI), for scripting. Unrelated to |-s|. - Disables most prompts, messages, warnings and errors. +-Es Script mode, aka "silent mode", aka "batch mode". No UI, + disables most prompts and messages. Unrelated to |-s|. + See also |-S| to run script files. -es reads/executes stdin as Ex commands. > printf "put ='foo'\n%%print\n" | nvim -es @@ -205,18 +201,44 @@ argument. send commands. > printf "foo\n" | nvim -Es +"%print" -< Output of these commands is displayed (to stdout): - :print +< These commands display on stdout: :list :number - :set (to display option values) - When 'verbose' is set messages are printed to stderr. > - echo foo | nvim -V1 -es + :print + :set + With |:verbose| or 'verbose', other commands display on stderr: > + nvim -es +":verbose echo 'foo'" + nvim -V1 -es +foo -< User |config| is skipped (unless given with |-u|). +< User |config| is skipped unless |-u| was given. Swap file is skipped (like |-n|). User |shada| is loaded (unless "-i NONE" is given). + *-l* +-l {script} [args] + Executes Lua {script} non-interactively (no UI) with optional + [args] after processing any preceding Nvim |cli-arguments|, + then exits. Exits 1 on Lua error. See |-S| to run multiple Lua + scripts without args, with a UI. + *lua-args* + All [args] are treated as {script} arguments and stored in the + Lua `_G.arg` global table, thus "-l" ends processing of Nvim + arguments. The {script} name is stored at `_G.arg[0]`. + + Sets 'verbose' to 1 (like "-V1"), so Lua `print()` writes to + output. + + Arguments before "-l" are processed before executing {script}. + This example quits before executing "foo.lua": > + nvim +q -l foo.lua +< This loads Lua module "bar" before executing "foo.lua": > + nvim +"lua require('bar')" -l foo.lua +< + Skips user |config| unless |-u| was given. + Disables plugins unless 'loadplugins' was set. + Disables |shada| unless |-i| was given. + Disables swapfile (like |-n|). + *-b* -b Binary mode. File I/O will only recognize <NL> to separate lines. The 'expandtab' option will be reset. The 'textwidth' @@ -224,9 +246,6 @@ argument. is set. This is done after reading the |vimrc| but before reading any file in the arglist. See also |edit-binary|. - *-l* --l Lisp mode. Sets the 'lisp' and 'showmatch' options on. - *-A* -A Arabic mode. Sets the 'arabic' option on. @@ -241,10 +260,10 @@ argument. Example: > nvim -V8 --V[N]{filename} - Like -V and set 'verbosefile' to {filename}. Messages are not - displayed; instead they are written to the file {filename}. - {filename} must not start with a digit. +-V[N]{file} + Like -V and sets 'verbosefile' to {file} (must not start with + a digit). Messages are not displayed, instead they are + written to {file}. Example: > nvim -V20vimlog < @@ -403,18 +422,20 @@ accordingly, proceeding as follows: The |-V| argument can be used to display or log what happens next, useful for debugging the initializations. -3. Wait for UI to connect. +3. Start a server (unless |--listen| was given) and set |v:servername|. + +4. Wait for UI to connect. Nvim started with |--embed| waits for the UI to connect before proceeding to load user configuration. -4. Setup |default-mappings| and |default-autocmds|. Create |popup-menu|. +5. Setup |default-mappings| and |default-autocmds|. Create |popup-menu|. -5. Enable filetype and indent plugins. +6. Enable filetype and indent plugins. This does the same as the command: > :runtime! ftplugin.vim indent.vim < Skipped if the "-u NONE" command line argument was given. -6. Load user config (execute Ex commands from files, environment, …). +7. Load user config (execute Ex commands from files, environment, …). $VIMINIT environment variable is read as one Ex command line (separate multiple commands with '|' or <NL>). *config* *init.vim* *init.lua* *vimrc* *exrc* @@ -445,32 +466,33 @@ accordingly, proceeding as follows: *VIMINIT* *EXINIT* *$MYVIMRC* b. Locations searched for initializations, in order of preference: - $VIMINIT environment variable (Ex command line). - - User |config|: $XDG_CONFIG_HOME/nvim/init.vim. - - Other config: {dir}/nvim/init.vim where {dir} is any directory - in $XDG_CONFIG_DIRS. + - User |config|: $XDG_CONFIG_HOME/nvim/init.vim (or init.lua). + - Other config: {dir}/nvim/init.vim (or init.lua) where {dir} is any + directory in $XDG_CONFIG_DIRS. - $EXINIT environment variable (Ex command line). |$MYVIMRC| is set to the first valid location unless it was already set or when using $VIMINIT. c. If the 'exrc' option is on (which is NOT the default), the current - directory is searched for two files. The first that exists is used, - the others are ignored. - - The file ".nvimrc" - - The file ".exrc" + directory is searched for the following files, in order of precedence: + - ".nvim.lua" + - ".nvimrc" + - ".exrc" + The first that exists is used, the others are ignored. -7. Enable filetype detection. +8. Enable filetype detection. This does the same as the command: > - :runtime! filetype.lua filetype.vim + :runtime! filetype.lua < Skipped if ":filetype off" was called or if the "-u NONE" command line argument was given. -8. Enable syntax highlighting. +9. Enable syntax highlighting. This does the same as the command: > :runtime! syntax/syntax.vim < Skipped if ":syntax off" was called or if the "-u NONE" command line argument was given. -9. Load the plugin scripts. *load-plugins* +10. Load the plugin scripts. *load-plugins* This does the same as the command: > :runtime! plugin/**/*.vim :runtime! plugin/**/*.lua @@ -482,13 +504,13 @@ accordingly, proceeding as follows: However, directories in 'runtimepath' ending in "after" are skipped here and only loaded after packages, see below. Loading plugins won't be done when: - - The 'loadplugins' option was reset in a vimrc file. + - The |'loadplugins'| option was reset in a vimrc file. - The |--noplugin| command line argument is used. - The |--clean| command line argument is used. - The "-u NONE" command line argument is used |-u|. - Note that using "-c 'set noloadplugins'" doesn't work, because the + Note that using `-c 'set noloadplugins'` doesn't work, because the commands from the command line have not been executed yet. You can - use "--cmd 'set noloadplugins'" or "--cmd 'set loadplugins'" |--cmd|. + use `--cmd 'set noloadplugins'` or `--cmd 'set loadplugins'` |--cmd|. Packages are loaded. These are plugins, as above, but found in the "start" directory of each entry in 'packpath'. Every plugin directory @@ -500,21 +522,21 @@ accordingly, proceeding as follows: if packages have been found, but that should not add a directory ending in "after". -10. Set 'shellpipe' and 'shellredir' +11. Set 'shellpipe' and 'shellredir' The 'shellpipe' and 'shellredir' options are set according to the value of the 'shell' option, unless they have been set before. This means that Nvim will figure out the values of 'shellpipe' and 'shellredir' for you, unless you have set them yourself. -11. Set 'updatecount' to zero, if "-n" command argument used +12. Set 'updatecount' to zero, if "-n" command argument used -12. Set binary options if the |-b| flag was given. +13. Set binary options if the |-b| flag was given. -13. Read the |shada-file|. +14. Read the |shada-file|. -14. Read the quickfix file if the |-q| flag was given, or exit on failure. +15. Read the quickfix file if the |-q| flag was given, or exit on failure. -15. Open all windows +16. Open all windows When the |-o| flag was given, windows will be opened (but not displayed yet). When the |-p| flag was given, tab pages will be created (but not @@ -524,7 +546,7 @@ accordingly, proceeding as follows: Buffers for all windows will be loaded, without triggering |BufAdd| autocommands. -16. Execute startup commands +17. Execute startup commands If a |-t| flag was given, the tag is jumped to. Commands given with |-c| and |+cmd| are executed. The starting flag is reset, has("vim_starting") will now return zero. @@ -1184,7 +1206,7 @@ exactly four MessagePack objects: encoding Binary, effective 'encoding' value. max_kbyte Integer, effective |shada-s| limit value. pid Integer, instance process ID. - * It is allowed to have any number of + `*` It is allowed to have any number of additional keys with any data. 2 (SearchPattern) Map containing data describing last used search or substitute pattern. Normally ShaDa file contains two @@ -1215,7 +1237,7 @@ exactly four MessagePack objects: sp Binary N/A Actual pattern. Required. sb Boolean false True if search direction is backward. - * any none Other keys are allowed for + `*` any none Other keys are allowed for compatibility reasons, see |shada-compatibility|. 3 (SubString) Array containing last |:substitute| replacement string. @@ -1286,7 +1308,7 @@ exactly four MessagePack objects: GlobalMark and LocalMark entries. f Binary N/A File name. Required. - * any none Other keys are allowed for + `*` any none Other keys are allowed for compatibility reasons, see |shada-compatibility|. 9 (BufferList) Array containing maps. Each map in the array @@ -1296,10 +1318,10 @@ exactly four MessagePack objects: greater then zero. c UInteger 0 Position column number. f Binary N/A File name. Required. - * any none Other keys are allowed for + `*` any none Other keys are allowed for compatibility reasons, see |shada-compatibility|. - * (Unknown) Any other entry type is allowed for compatibility + `*` (Unknown) Any other entry type is allowed for compatibility reasons, see |shada-compatibility|. *E575* *E576* @@ -1359,7 +1381,7 @@ LOG FILE *$NVIM_LOG_FILE* *E5430* Besides 'debug' and 'verbose', Nvim keeps a general log file for internal debugging, plugins and RPC clients. > :echo $NVIM_LOG_FILE -By default, the file is located at stdpath('log')/log unless that path +By default, the file is located at stdpath("log")/log unless that path is inaccessible or if $NVIM_LOG_FILE was set before |startup|. diff --git a/runtime/doc/support.txt b/runtime/doc/support.txt new file mode 100644 index 0000000000..481959d8f1 --- /dev/null +++ b/runtime/doc/support.txt @@ -0,0 +1,52 @@ +*support.txt* Nvim + + + NVIM REFERENCE MANUAL + + +Support *support* + + Type |gO| to see the table of contents. + +============================================================================== +Supported platforms *supported-platforms* + +`System` `Tier` `Versions` `Tested versions` +Linux 1 >= 2.6.32, glibc >= 2.12 Ubuntu 22.04 +macOS (Intel) 1 >= 10.15 macOS 12 +Windows 64-bit 1 >= 8 Windows Server 2019 +FreeBSD 1 >= 10 FreeBSD 13 +macOS (M1) 2 >= 10.15 +OpenBSD 2 >= 7 +MinGW 2 MinGW-w64 + +Support types ~ + +* Tier 1: Officially supported and tested with CI. Any contributed patch + MUST NOT break such systems. + +* Tier 2: Officially supported, but not necessarily tested with CI. These + systems are maintained to the best of our ability, without being a top + priority. + +* Tier 3: Not tested and no guarantees, but may work. + +Adding support for a new platform ~ + +IMPORTANT: Before attempting to add support for a new platform please open +an issue about it for discussion. + + +============================================================================== +Common + +Some common notes when adding support for new platforms: + +Cmake is the only supported build system. The platform must be buildable with cmake. + +All functionality related to the new platform must be implemented in its own +file inside `src/nvim/os` unless it's already done in a common file, in which +case adding an `#ifdef` is fine. + + + vim:tw=78:ts=8:et:ft=help:norl: diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index b74611633f..bd5a4f1926 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -181,16 +181,16 @@ Vim will only load the first syntax file found, assuming that it sets b:current_syntax. -NAMING CONVENTIONS *group-name* *{group-name}* *E669* *W18* +NAMING CONVENTIONS *group-name* *{group-name}* *E669* *E5248* A syntax group name is to be used for syntax items that match the same kind of thing. These are then linked to a highlight group that specifies the color. A syntax group name doesn't specify any color or attributes itself. -The name for a highlight or syntax group must consist of ASCII letters, digits -and the underscore. As a regexp: "[a-zA-Z0-9_]*". However, Vim does not give -an error when using other characters. The maximum length of a group name is -about 200 bytes. *E1249* +The name for a highlight or syntax group must consist of ASCII letters, +digits, underscores, periods and `@` characters. As a regexp it is +`[a-zA-Z0-9_.@]*`. The maximum length of a group name is about 200 bytes. +*E1249* To be able to allow each user to pick their favorite set of colors, there must be preferred names for highlight groups that are common for many languages. @@ -464,7 +464,7 @@ Force to omit the line numbers: > Go back to the default to use 'number' by deleting the variable: > :unlet g:html_number_lines < - *g:html_line_ids* + *g:html_line_ids* Default: 1 if |g:html_number_lines| is set, 0 otherwise. When 1, adds an HTML id attribute to each line number, or to an empty <span> inserted for that purpose if no line numbers are shown. This ID attribute @@ -656,6 +656,22 @@ the rendered page generated by 2html.vim. > :let g:html_no_pre = 1 < + *g:html_no_doc* +Default: 0. +When 1 it doesn't generate a full HTML document with a DOCTYPE, <head>, +<body>, etc. If |g:html_use_css| is enabled (the default) you'll have to +define the CSS manually. The |g:html_dynamic_folds| and |g:html_line_ids| +settings (off by default) also insert some JavaScript. + + + *g:html_no_links* +Default: 0. +Don't generate <a> tags for text that looks like an URL. + + *g:html_no_modeline* +Default: 0. +Don't generate a modeline disabling folding. + *g:html_expand_tabs* Default: 0 if 'tabstop' is 8, 'expandtab' is 0, 'vartabstop' is not in use, and no fold column or line numbers occur in the generated HTML; @@ -687,13 +703,13 @@ Automatic detection works for the encodings mentioned specifically by name in |encoding-names|, but TOhtml will only automatically use those encodings with wide browser support. However, you can override this to support specific encodings that may not be automatically detected by default (see options -below). See http://www.iana.org/assignments/character-sets for the IANA names. +below). See https://www.iana.org/assignments/character-sets for the IANA names. Note: By default all Unicode encodings are converted to UTF-8 with no BOM in the generated HTML, as recommended by W3C: - http://www.w3.org/International/questions/qa-choosing-encodings - http://www.w3.org/International/questions/qa-byte-order-mark + https://www.w3.org/International/questions/qa-choosing-encodings + https://www.w3.org/International/questions/qa-byte-order-mark *g:html_use_encoding* Default: none, uses IANA name for current 'fileencoding' as above. @@ -832,7 +848,7 @@ files are included: asm68k Motorola 680x0 assembly asmh8300 Hitachi H-8300 version of GNU assembly ia64 Intel Itanium 64 - fasm Flat assembly (http://flatassembler.net) + fasm Flat assembly (https://flatassembler.net) masm Microsoft assembly (probably works for any 80x86) nasm Netwide assembly tasm Turbo Assembly (with opcodes 80x86 up to Pentium, and @@ -1393,9 +1409,9 @@ Two syntax highlighting files exist for Euphoria. One for Euphoria version 3.1.1, which is the default syntax highlighting file, and one for Euphoria version 4.0.5 or later. -Euphoria version 3.1.1 (http://www.rapideuphoria.com/) is still necessary +Euphoria version 3.1.1 (https://www.rapideuphoria.com/) is still necessary for developing applications for the DOS platform, which Euphoria version 4 -(http://www.openeuphoria.org/) does not support. +(https://www.openeuphoria.org/) does not support. The following file extensions are auto-detected as Euphoria file type: @@ -1452,7 +1468,7 @@ Elixir. FLEXWIKI *flexwiki.vim* *ft-flexwiki-syntax* -FlexWiki is an ASP.NET-based wiki package available at http://www.flexwiki.com +FlexWiki is an ASP.NET-based wiki package available at https://www.flexwiki.com NOTE: This site currently doesn't work, on Wikipedia is mentioned that development stopped in 2009. @@ -1808,7 +1824,7 @@ are read during initialization) > :let html_my_rendering=1 If you'd like to see an example download mysyntax.vim at -http://www.fleiner.com/vim/download.html +https://www.fleiner.com/vim/download.html You can also disable this rendering by adding the following line to your vimrc file: > @@ -1838,6 +1854,16 @@ following two lines to the syntax coloring file for that language Now you just need to make sure that you add all regions that contain the preprocessor language to the cluster htmlPreproc. + *html-folding* +The HTML syntax file provides syntax |folding| (see |:syn-fold|) between start +and end tags. This can be turned on by > + + :let g:html_syntax_folding = 1 + :set foldmethod=syntax + +Note: Syntax folding might slow down syntax highlighting significantly, +especially for large files. + HTML/OS (by Aestiva) *htmlos.vim* *ft-htmlos-syntax* @@ -1936,7 +1962,7 @@ highlight them use: > :let java_highlight_java_lang_ids=1 You can also highlight identifiers of most standard Java packages if you -download the javaid.vim script at http://www.fleiner.com/vim/download.html. +download the javaid.vim script at https://www.fleiner.com/vim/download.html. If you prefer to only highlight identifiers of a certain package, say java.io use the following: > :let java_highlight_java_io=1 @@ -2057,7 +2083,7 @@ The g:lisp_rainbow option provides 10 levels of individual colorization for the parentheses and backquoted parentheses. Because of the quantity of colorization levels, unlike non-rainbow highlighting, the rainbow mode specifies its highlighting using ctermfg and guifg, thereby bypassing the -usual colorscheme control using standard highlighting groups. The actual +usual color scheme control using standard highlighting groups. The actual highlighting used depends on the dark/bright setting (see |'bg'|). @@ -2365,7 +2391,7 @@ you set the variable: > :let papp_include_html=1 -in your startup file it will try to syntax-hilight html code inside phtml +in your startup file it will try to syntax-highlight html code inside phtml sections, but this is relatively slow and much too colourful to be able to edit sensibly. ;) @@ -2449,7 +2475,7 @@ from the rest of the name (like 'PkgName::' in '$PkgName::VarName'): > (In Vim 6.x it was the other way around: "perl_want_scope_in_variables" enabled it.) -If you do not want complex things like '@{${"foo"}}' to be parsed: > +If you do not want complex things like `@{${"foo"}}` to be parsed: > :let perl_no_extended_vars = 1 @@ -2897,7 +2923,7 @@ Default folding is rather detailed, i.e., small syntax units like "if", "do", You can set "ruby_foldable_groups" to restrict which groups are foldable: > - :let ruby_foldable_groups = 'if case %' + :let ruby_foldable_groups = 'if case %' < The value is a space-separated list of keywords: @@ -2905,22 +2931,22 @@ The value is a space-separated list of keywords: -------- ------------------------------------- ~ ALL Most block syntax (default) NONE Nothing - if "if" or "unless" block + if "if" or "unless" block def "def" block class "class" block module "module" block - do "do" block + do "do" block begin "begin" block case "case" block for "for", "while", "until" loops - { Curly bracket block or hash literal - [ Array literal - % Literal with "%" notation, e.g.: %w(STRING), %!STRING! - / Regexp + { Curly bracket block or hash literal + [ Array literal + % Literal with "%" notation, e.g.: %w(STRING), %!STRING! + / Regexp string String and shell command output (surrounded by ', ", `) - : Symbol - # Multiline comment - << Here documents + : Symbol + # Multiline comment + << Here documents __END__ Source code after "__END__" directive *ruby_no_expensive* @@ -2986,16 +3012,25 @@ satisfied with it for my own projects. SED *sed.vim* *ft-sed-syntax* To make tabs stand out from regular blanks (accomplished by using Todo -highlighting on the tabs), define "highlight_sedtabs" by putting > - - :let highlight_sedtabs = 1 +highlighting on the tabs), define "g:sed_highlight_tabs" by putting > + :let g:sed_highlight_tabs = 1 +< in the vimrc file. (This special highlighting only applies for tabs inside search patterns, replacement texts, addresses or text included by an Append/Change/Insert command.) If you enable this option, it is also a good idea to set the tab width to one character; by doing that, you can easily count the number of tabs in a string. +GNU sed allows comments after text on the same line. BSD sed only allows +comments where "#" is the first character of the line. To enforce BSD-style +comments, i.e. mark end-of-line comments as errors, use: > + + :let g:sed_dialect = "bsd" +< +Note that there are other differences between GNU sed and BSD sed which are +not (yet) affected by this setting. + Bugs: The transform command (y) is treated exactly like the substitute @@ -3118,7 +3153,7 @@ The default is to use the twice sh_minlines. Set it to a smaller number to speed up displaying. The disadvantage is that highlight errors may appear. syntax/sh.vim tries to flag certain problems as errors; usually things like -extra ']'s, 'done's, 'fi's, etc. If you find the error handling problematic +unmatched "]", "done", "fi", etc. If you find the error handling problematic for your purposes, you may suppress such error highlighting by putting the following line in your .vimrc: > @@ -3353,13 +3388,11 @@ of specialized LaTeX commands, syntax, and fonts. If you're using such a package you'll often wish that the distributed syntax/tex.vim would support it. However, clearly this is impractical. So please consider using the techniques in |mysyntaxfile-add| to extend or modify the highlighting provided -by syntax/tex.vim. Please consider uploading any extensions that you write, -which typically would go in $HOME/after/syntax/tex/[pkgname].vim, to -http://vim.sf.net/. +by syntax/tex.vim. I've included some support for various popular packages on my website: > - http://www.drchip.org/astronaut/vim/index.html#LATEXPKGS + https://www.drchip.org/astronaut/vim/index.html#LATEXPKGS < The syntax files there go into your .../after/syntax/tex/ directory. @@ -3538,6 +3571,14 @@ highlighting is to put the following line in your |vimrc|: > < +WDL *wdl.vim* *wdl-syntax* + +The Workflow Description Language is a way to specify data processing workflows +with a human-readable and writeable syntax. This is used a lot in +bioinformatics. More info on the spec can be found here: +https://github.com/openwdl/wdl + + XF86CONFIG *xf86conf.vim* *ft-xf86conf-syntax* The syntax of XF86Config file differs in XFree86 v3.x and v4.x. Both @@ -3690,12 +3731,13 @@ DEFINING CASE *:syn-case* *E390* items until the next ":syntax case" command are affected. :sy[ntax] case - Show either "syntax case match" or "syntax case ignore" (translated). + Show either "syntax case match" or "syntax case ignore". DEFINING FOLDLEVEL *:syn-foldlevel* -:sy[ntax] foldlevel [start | minimum] +:sy[ntax] foldlevel start +:sy[ntax] foldlevel minimum This defines how the foldlevel of a line is computed when using foldmethod=syntax (see |fold-syntax| and |:syn-fold|): @@ -3708,11 +3750,14 @@ DEFINING FOLDLEVEL *:syn-foldlevel* may close and open horizontally within a line. :sy[ntax] foldlevel - Show either "syntax foldlevel start" or "syntax foldlevel minimum". + Show the current foldlevel method, either "syntax foldlevel start" or + "syntax foldlevel minimum". SPELL CHECKING *:syn-spell* -:sy[ntax] spell [toplevel | notoplevel | default] +:sy[ntax] spell toplevel +:sy[ntax] spell notoplevel +:sy[ntax] spell default This defines where spell checking is to be done for text that is not in a syntax item: @@ -3727,8 +3772,8 @@ SPELL CHECKING *:syn-spell* To activate spell checking the 'spell' option must be set. :sy[ntax] spell - Show either "syntax spell toplevel", "syntax spell notoplevel" or - "syntax spell default" (translated). + Show the current syntax spell checking method, either "syntax spell + toplevel", "syntax spell notoplevel" or "syntax spell default". SYNTAX ISKEYWORD SETTING *:syn-iskeyword* @@ -3739,7 +3784,7 @@ SYNTAX ISKEYWORD SETTING *:syn-iskeyword* clear: Syntax specific iskeyword setting is disabled and the buffer-local 'iskeyword' setting is used. - {option} Set the syntax 'iskeyword' option to a new value. + {option} Set the syntax 'iskeyword' option to a new value. Example: > :syntax iskeyword @,48-57,192-255,$,_ @@ -4326,7 +4371,7 @@ IMPLICIT CONCEAL *:syn-conceal-implicit* given explicitly. :sy[ntax] conceal - Show either "syntax conceal on" or "syntax conceal off" (translated). + Show either "syntax conceal on" or "syntax conceal off". ============================================================================== 8. Syntax patterns *:syn-pattern* *E401* *E402* @@ -4806,7 +4851,7 @@ Note that the ":syntax" command can be abbreviated to ":sy", although ":syn" is mostly used, because it looks better. ============================================================================== -12. Highlight command *:highlight* *:hi* *E28* *E411* *E415* +13. Highlight command *:highlight* *:hi* *E28* *E411* *E415* There are two types of highlight groups: - The built-in |highlight-groups|. @@ -4838,7 +4883,7 @@ in their own color. To customize a color scheme use another name, e.g. "~/.config/nvim/colors/mine.vim", and use `:runtime` to - load the original colorscheme: > + load the original color scheme: > runtime colors/evening.vim hi Statement ctermfg=Blue guifg=Blue @@ -4846,7 +4891,7 @@ in their own color. |ColorSchemePre| autocommand event is triggered. After the color scheme has been loaded the |ColorScheme| autocommand event is triggered. - For info about writing a colorscheme file: > + For info about writing a color scheme file: > :edit $VIMRUNTIME/colors/README.txt :hi[ghlight] List all the current highlight groups that have @@ -4857,7 +4902,7 @@ in their own color. *highlight-clear* *:hi-clear* :hi[ghlight] clear Reset all highlighting to the defaults. Removes all - highlighting for groups added by the user! + highlighting for groups added by the user. Uses the current value of 'background' to decide which default colors to use. If there was a default link, restore it. |:hi-link| @@ -4913,7 +4958,8 @@ the same syntax file on all UIs. *bold* *underline* *undercurl* *underdouble* *underdotted* *underdashed* *inverse* *italic* - *standout* *nocombine* *strikethrough* + *standout* *strikethrough* *altfont* + *nocombine* cterm={attr-list} *attr-list* *highlight-cterm* *E418* attr-list is a comma-separated list (without spaces) of the following items (in any order): @@ -4928,6 +4974,7 @@ cterm={attr-list} *attr-list* *highlight-cterm* *E418* inverse same as reverse italic standout + altfont nocombine override attributes instead of combining them NONE no attributes used (used to reset it) @@ -4935,7 +4982,7 @@ cterm={attr-list} *attr-list* *highlight-cterm* *E418* have the same effect. "undercurl", "underdouble", "underdotted", and "underdashed" fall back to "underline" in a terminal that does not support them. The color is - set using |highlight-guisp|. + set using |guisp|. start={term-list} *highlight-start* *E422* stop={term-list} *term-list* *highlight-stop* @@ -4956,8 +5003,8 @@ stop={term-list} *term-list* *highlight-stop* like "<Esc>" and "<Space>". Example: start=<Esc>[27h;<Esc>[<Space>r; -ctermfg={color-nr} *highlight-ctermfg* *E421* -ctermbg={color-nr} *highlight-ctermbg* +ctermfg={color-nr} *ctermfg* *E421* +ctermbg={color-nr} *ctermbg* The {color-nr} argument is a color number. Its range is zero to (not including) the number of |tui-colors| available. The actual color with this number depends on the type of terminal @@ -4997,7 +5044,7 @@ ctermbg={color-nr} *highlight-ctermbg* a number instead of a color name. Note that for 16 color ansi style terminals (including xterms), the - numbers in the NR-8 column is used. Here '*' means 'add 8' so that + numbers in the NR-8 column is used. Here "*" means "add 8" so that Blue is 12, DarkGray is 8 etc. Note that for some color terminals these names may result in the wrong @@ -5016,7 +5063,7 @@ ctermbg={color-nr} *highlight-ctermbg* explicitly. This causes the highlight groups that depend on 'background' to change! This means you should set the colors for Normal first, before setting other colors. - When a colorscheme is being used, changing 'background' causes it to + When a color scheme is being used, changing 'background' causes it to be reloaded, which may reset all colors (including Normal). First delete the "g:colors_name" variable when you don't want this. @@ -5064,9 +5111,9 @@ font={font-name} *highlight-font* Example: > :hi comment font='Monospace 10' -guifg={color-name} *highlight-guifg* -guibg={color-name} *highlight-guibg* -guisp={color-name} *highlight-guisp* +guifg={color-name} *guifg* +guibg={color-name} *guibg* +guisp={color-name} *guisp* These give the foreground (guifg), background (guibg) and special (guisp) color to use in the GUI. "guisp" is used for various underlines. @@ -5099,7 +5146,7 @@ guisp={color-name} *highlight-guisp* "gg" is the Green value "bb" is the Blue value All values are hexadecimal, range from "00" to "ff". Examples: > - :highlight Comment guifg=#11f0c3 guibg=#ff00ff + :highlight Comment guifg=#11f0c3 guibg=#ff00ff < blend={integer} *highlight-blend* Override the blend level for a highlight group within the popupmenu @@ -5123,7 +5170,7 @@ Cursor Character under the cursor. lCursor Character under the cursor when |language-mapping| is used (see 'guicursor'). *hl-CursorIM* -CursorIM Like Cursor, but used when in IME mode. |CursorIM| +CursorIM Like Cursor, but used when in IME mode. *CursorIM* *hl-CursorColumn* CursorColumn Screen-column at the cursor, when 'cursorcolumn' is set. *hl-CursorLine* @@ -5174,10 +5221,10 @@ LineNrBelow Line number for when the 'relativenumber' *hl-CursorLineNr* CursorLineNr Like LineNr when 'cursorline' is set and 'cursorlineopt' contains "number" or is "both", for the cursor line. - *hl-CursorLineSign* -CursorLineSign Like SignColumn when 'cursorline' is set for the cursor line. *hl-CursorLineFold* CursorLineFold Like FoldColumn when 'cursorline' is set for the cursor line. + *hl-CursorLineSign* +CursorLineSign Like SignColumn when 'cursorline' is set for the cursor line. *hl-MatchParen* MatchParen Character under the cursor or just before it, if it is a paired bracket, and its match. |pi_paren.txt| @@ -5187,7 +5234,7 @@ ModeMsg 'showmode' message (e.g., "-- INSERT --"). *hl-MsgArea* MsgArea Area for messages and cmdline. *hl-MsgSeparator* -MsgSeparator Separator for scrolled messages, `msgsep` flag of 'display'. +MsgSeparator Separator for scrolled messages |msgsep|. *hl-MoreMsg* MoreMsg |more-prompt| *hl-NonText* @@ -5288,7 +5335,7 @@ Tooltip Current font, background and foreground of the tooltips. Applicable highlight arguments: font, guibg, guifg. ============================================================================== -13. Linking groups *:hi-link* *:highlight-link* *E412* *E413* +14. Linking groups *:hi-link* *:highlight-link* *E412* *E413* When you want to use the same highlighting for several syntax groups, you can do this more easily by linking the groups into one common highlight @@ -5397,8 +5444,7 @@ WARNING: The longer the tags file, the slower this will be, and the more memory Vim will consume. Only highlighting typedefs, unions and structs can be done too. For this you -must use Universal Ctags (found at https://ctags.io) or Exuberant ctags (found -at http://ctags.sf.net). +must use Universal Ctags (https://ctags.io) or Exuberant ctags. Put these lines in your Makefile: @@ -5448,7 +5494,7 @@ is loaded into that window or the file is reloaded. When splitting the window, the new window will use the original syntax. ============================================================================== -17. Color xterms *xterm-color* *color-xterm* +18. Color xterms *xterm-color* *color-xterm* *colortest.vim* To test your color setup, a file has been included in the Vim distribution. @@ -5458,7 +5504,7 @@ To use it, execute this command: > Nvim uses 256-color and |true-color| terminal capabilities wherever possible. ============================================================================== -18. When syntax is slow *:syntime* +19. When syntax is slow *:syntime* This is aimed at authors of a syntax file. diff --git a/runtime/doc/tabpage.txt b/runtime/doc/tabpage.txt index 9197710819..49b2773253 100644 --- a/runtime/doc/tabpage.txt +++ b/runtime/doc/tabpage.txt @@ -186,8 +186,8 @@ gt *i_CTRL-<PageDown>* *i_<C-PageDown>* :+2tabnext " go to the two next tab page :1tabnext " go to the first tab page :$tabnext " go to the last tab page - :tabnext # " go to the last accessed tab page :tabnext $ " as above + :tabnext # " go to the last accessed tab page :tabnext - " go to the previous tab page :tabnext -1 " as above :tabnext + " go to the next tab page diff --git a/runtime/doc/tagsrch.txt b/runtime/doc/tagsrch.txt index 2485290667..0f785dd1eb 100644 --- a/runtime/doc/tagsrch.txt +++ b/runtime/doc/tagsrch.txt @@ -59,9 +59,9 @@ CTRL-] Jump to the definition of the keyword under the CTRL-] is the default telnet escape key. When you type CTRL-] to jump to a tag, you will get the telnet prompt instead. Most versions of telnet allow changing or disabling the default escape key. See the telnet man page. You -can 'telnet -E {Hostname}' to disable the escape character, or 'telnet -e -{EscapeCharacter} {Hostname}' to specify another escape character. If -possible, try to use "ssh" instead of "telnet" to avoid this problem. +can `telnet -E {Hostname}` to disable the escape character, or +`telnet -e {EscapeCharacter} {Hostname}` to specify another escape character. +If possible, try to use "ssh" instead of "telnet" to avoid this problem. *tag-priority* When there are multiple matches for a tag, this priority is used: @@ -404,7 +404,7 @@ is added to the command and on the 'autowrite' option: tag in file autowrite ~ current file changed ! option action ~ ------------------------------------------------------------------------------ + --------------------------------------------------------------------------- yes x x x goto tag no no x x read other file, goto tag no yes yes x abandon current file, read other file, goto @@ -412,7 +412,7 @@ current file changed ! option action ~ no yes no on write current file, read other file, goto tag no yes no off fail ------------------------------------------------------------------------------ + --------------------------------------------------------------------------- - If the tag is in the current file, the command will always work. - If the tag is in another file and the current file was not changed, the @@ -514,18 +514,13 @@ ctags As found on most Unix systems. Only supports C. Only universal ctags A maintained version of ctags based on exuberant ctags. See https://ctags.io. *Exuberant_ctags* -exuberant ctags This is a very good one. It works for C, C++, Java, - Fortran, Eiffel and others. It can generate tags for - many items. See http://ctags.sourceforge.net. - No new version since 2009. +exuberant ctags Works for C, C++, Java, Fortran, Eiffel and others. + See https://ctags.sourceforge.net. No new version + since 2009. JTags For Java, in Java. It can be found at - http://www.fleiner.com/jtags/. + https://www.fleiner.com/jtags/. ptags.py For Python, in Python. Found in your Python source directory at Tools/scripts/ptags.py. -ptags For Perl, in Perl. It can be found at - http://www.eleves.ens.fr:8080/home/nthiery/Tags/. -gnatxref For Ada. See http://www.gnuada.org/. gnatxref is - part of the gnat package. The lines in the tags file must have one of these two formats: @@ -566,8 +561,8 @@ ctags). with Vi, it ignores the following fields. Example: APP file /^static int APP;$/;" v When {tagaddress} is not a line number or search pattern, then - {term} must be |;". Here the bar ends the command (excluding - the bar) and ;" is used to have Vi ignore the rest of the + {term} must be `|;"`. Here the bar ends the command (excluding + the bar) and `;"` is used to have Vi ignore the rest of the line. Example: APP file.c call cursor(3, 4)|;" v @@ -629,8 +624,7 @@ If the command is a normal search command (it starts and ends with "/" or "?"), some special handling is done: - Searching starts on line 1 of the file. The direction of the search is forward for "/", backward for "?". - Note that 'wrapscan' does not matter, the whole file is always searched. (Vi - does use 'wrapscan', which caused tags sometimes not be found.) + Note that 'wrapscan' does not matter, the whole file is always searched. - If the search fails, another try is done ignoring case. If that fails too, a search is done for: "^tagname[ \t]*(" @@ -834,10 +828,10 @@ CTRL-W d Open a new window, with the cursor on the first (default: whole file). See |:search-args| for [/] and [!]. - *:che* *:chec* *:check* *:checkpath* -:che[ckpath] List all the included files that could not be found. + *:checkp* *:checkpath* +:checkp[ath] List all the included files that could not be found. -:che[ckpath]! List all the included files. +:checkp[ath]! List all the included files. *:search-args* Common arguments for the commands above: @@ -854,9 +848,9 @@ Common arguments for the commands above: a comment (even though syntax highlighting does recognize it). Note: Since a macro definition mostly doesn't look like a comment, the [!] makes no difference for ":dlist", ":dsearch" and ":djump". -[/] A pattern can be surrounded by '/'. Without '/' only whole words are - matched, using the pattern "\<pattern\>". Only after the second '/' a - next command can be appended with '|'. Example: > +[/] A pattern can be surrounded by "/". Without "/" only whole words are + matched, using the pattern "\<pattern\>". Only after the second "/" a + next command can be appended with "|". Example: > :isearch /string/ | echo "the last one" < For a ":djump", ":dsplit", ":dlist" and ":dsearch" command the pattern is used as a literal string, not as a search pattern. @@ -870,13 +864,15 @@ like |CTRL-]|. The function used for generating the taglist is specified by setting the 'tagfunc' option. The function will be called with three arguments: - a:pattern The tag identifier or pattern used during the tag search. - a:flags String containing flags to control the function behavior. - a:info Dict containing the following entries: + pattern The tag identifier or pattern used during the tag search. + flags String containing flags to control the function behavior. + info Dict containing the following entries: buf_ffname Full filename which can be used for priority. user_data Custom data String, if stored in the tag stack previously by tagfunc. +Note that "a:" needs to be prepended to the argument name when using it. + Currently up to three flags may be passed to the tag function: 'c' The function was invoked by a normal command being processed (mnemonic: the tag function may use the context around the @@ -912,6 +908,8 @@ If the function returns |v:null| instead of a List, a standard tag lookup will be performed instead. It is not allowed to change the tagstack from inside 'tagfunc'. *E986* +It is not allowed to close a window or change window from inside 'tagfunc'. +*E1299* The following is a hypothetical example of a function used for 'tagfunc'. It uses the output of |taglist()| to generate the result: a list of tags in the diff --git a/runtime/doc/term.txt b/runtime/doc/term.txt index cd6798a5de..847b4b6112 100644 --- a/runtime/doc/term.txt +++ b/runtime/doc/term.txt @@ -29,7 +29,7 @@ whole. Building your own terminfo is usually as simple as running this as a non-superuser: > - curl -LO http://invisible-island.net/datafiles/current/terminfo.src.gz + curl -LO https://invisible-island.net/datafiles/current/terminfo.src.gz gunzip terminfo.src.gz tic terminfo.src < @@ -76,7 +76,7 @@ supplying an external one with entries for the terminal type. Settings depending on terminal *term-dependent-settings* If you want to set terminal-dependent options or mappings, you can do this in -your init.vim. Example: > +your init.vim. Example: >vim if $TERM =~ '^\(rxvt\|screen\|interix\|putty\)\(-.*\)\?$' set notermguicolors @@ -222,9 +222,9 @@ are not in terminfo you must add them by setting "terminal-overrides" in ~/.tmux.conf . See the tmux(1) manual page for the details of how and what to do in the tmux -configuration file. It will look something like: > +configuration file. It will look something like: >bash set -ga terminal-overrides '*:Ss=\E[%p1%d q:Se=\E[ q' -<or (alas!) for Konsole 18.07.70 or older, something more complex like: > +<or (alas!) for Konsole 18.07.70 or older, something more complex like: >bash set -ga terminal-overrides 'xterm*:\E]50;CursorShape=%?%p1%{3}%<%t%{0}%e%{1}%;%d\007' < ============================================================================== @@ -262,7 +262,7 @@ See the "Options" chapter |options|. If you are using a color terminal that is slow when displaying lines beyond the end of a buffer, this is because Nvim is drawing the whitespace twice, in -two sets of colours and attributes. To prevent this, use this command: > +two sets of colours and attributes. To prevent this, use this command: >vim hi NonText cterm=NONE ctermfg=NONE This draws the spaces with the default colours and attributes, which allows the second pass of drawing to be optimized away. Note: Although in theory the @@ -372,7 +372,7 @@ that has a match selects until that match (like using "v%"). If the match is an #if/#else/#endif block, the selection becomes linewise. For MS-Windows and xterm the time for double clicking can be set with the 'mousetime' option. For the other systems this time is defined outside of Vim. -An example, for using a double click to jump to the tag under the cursor: > +An example, for using a double click to jump to the tag under the cursor: >vim :map <2-LeftMouse> :exe "tag " .. expand("<cword>")<CR> Dragging the mouse with a double click (button-down, button-up, button-down @@ -380,6 +380,8 @@ and then drag) will result in whole words to be selected. This continues until the button is released, at which point the selection is per character again. +For scrolling with the mouse see |scroll-mouse-wheel|. + In Insert mode, when a selection is started, Vim goes into Normal mode temporarily. When Visual or Select mode ends, it returns to Insert mode. This is like using CTRL-O in Insert mode. Select mode is used when the @@ -408,23 +410,23 @@ The X1 and X2 buttons refer to the extra buttons found on some mice. The 'Microsoft Explorer' mouse has these buttons available to the right thumb. Currently X1 and X2 only work on Win32 and X11 environments. -Examples: > +Examples: >vim :noremap <MiddleMouse> <LeftMouse><MiddleMouse> Paste at the position of the middle mouse button click (otherwise the paste -would be done at the cursor position). > +would be done at the cursor position). >vim :noremap <LeftRelease> <LeftRelease>y Immediately yank the selection, when using Visual mode. Note the use of ":noremap" instead of "map" to avoid a recursive mapping. -> +>vim :map <X1Mouse> <C-O> :map <X2Mouse> <C-I> Map the X1 and X2 buttons to go forwards and backwards in the jump list, see |CTRL-O| and |CTRL-I|. *mouse-swap-buttons* -To swap the meaning of the left and right mouse buttons: > +To swap the meaning of the left and right mouse buttons: >vim :noremap <LeftMouse> <RightMouse> :noremap <LeftDrag> <RightDrag> :noremap <LeftRelease> <RightRelease> diff --git a/runtime/doc/testing.txt b/runtime/doc/testing.txt index 4e4a908d0f..ef5e179c86 100644 --- a/runtime/doc/testing.txt +++ b/runtime/doc/testing.txt @@ -20,17 +20,11 @@ and for testing plugins. Vim can be tested after building it, usually with "make test". The tests are located in the directory "src/testdir". -There are several types of tests added over time: - test33.in oldest, don't add any of these - test_something.in old style tests - test_something.vim new style tests - *new-style-testing* -New tests should be added as new style tests. These use functions such as -|assert_equal()| to keep the test commands and the expected result in one -place. - *old-style-testing* -In some cases an old style test needs to be used. +New tests should be added as new style tests. The test scripts are named +test_<feature>.vim (replace <feature> with the feature under test). These use +functions such as |assert_equal()| to keep the test commands and the expected +result in one place. Find more information in the file src/testdir/README.txt. @@ -98,18 +92,46 @@ assert_exception({error} [, {msg}]) *assert_exception()* catch call assert_exception('E492:') endtry - -assert_fails({cmd} [, {error} [, {msg}]]) *assert_fails()* +< + *assert_fails()* +assert_fails({cmd} [, {error} [, {msg} [, {lnum} [, {context}]]]]) Run {cmd} and add an error message to |v:errors| if it does - NOT produce an error. Also see |assert-return|. - When {error} is given it must match in |v:errmsg|. + NOT produce an error or when {error} is not found in the + error message. Also see |assert-return|. + + When {error} is a string it must be found literally in the + first reported error. Most often this will be the error code, + including the colon, e.g. "E123:". > + assert_fails('bad cmd', 'E987:') +< + When {error} is a |List| with one or two strings, these are + used as patterns. The first pattern is matched against the + first reported error: > + assert_fails('cmd', ['E987:.*expected bool']) +< The second pattern, if present, is matched against the last + reported error. To only match the last error use an empty + string for the first error: > + assert_fails('cmd', ['', 'E987:']) +< + If {msg} is empty then it is not used. Do this to get the + default message when passing the {lnum} argument. + + When {lnum} is present and not negative, and the {error} + argument is present and matches, then this is compared with + the line number at which the error was reported. That can be + the line number in a function or in a script. + + When {context} is present it is used as a pattern and matched + against the context (script name or function name) where + {lnum} is located in. + Note that beeping is not considered an error, and some failing commands only beep. Use |assert_beeps()| for those. Can also be used as a |method|: > GetCmd()->assert_fails('E99:') -assert_false({actual} [, {msg}]) *assert_false()* +assert_false({actual} [, {msg}]) *assert_false()* When {actual} is not false an error message is added to |v:errors|, like with |assert_equal()|. Also see |assert-return|. @@ -134,7 +156,7 @@ assert_match({pattern}, {actual} [, {msg}]) When {pattern} does not match {actual} an error message is added to |v:errors|. Also see |assert-return|. - {pattern} is used as with |=~|: The matching is always done + {pattern} is used as with |expr-=~|: The matching is always done like 'magic' was set and 'cpoptions' is empty, no matter what the actual value of 'magic' or 'cpoptions' is. diff --git a/runtime/doc/tips.txt b/runtime/doc/tips.txt index d913b53c6b..5d5e89da77 100644 --- a/runtime/doc/tips.txt +++ b/runtime/doc/tips.txt @@ -8,7 +8,7 @@ Tips and ideas for using Vim *tips* These are just a few that we thought would be helpful for many users. You can find many more tips on the wiki. The URL can be found on -http://www.vim.org +https://www.vim.org Don't forget to browse the user manual, it also contains lots of useful tips |usr_toc.txt|. @@ -297,7 +297,7 @@ be able to give comments to the parts of the mapping. > (<> notation |<>|. Note that this is all typed literally. ^W is "^" "W", not CTRL-W.) -Note that the last comment starts with |", because the ":execute" command +Note that the last comment starts with `|"`, because the ":execute" command doesn't accept a comment directly. You also need to set 'textwidth' to a non-zero value, e.g., > @@ -454,7 +454,7 @@ the current window, try this custom `:HelpCurwin` command: > command -bar -nargs=? -complete=help HelpCurwin execute s:HelpCurwin(<q-args>) let s:did_open_help = v:false - + function s:HelpCurwin(subject) abort let mods = 'silent noautocmd keepalt' if !s:did_open_help diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index 52531a1525..917863eef8 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -4,77 +4,75 @@ NVIM REFERENCE MANUAL -Tree-sitter integration *treesitter* +Treesitter integration *treesitter* - Type |gO| to see the table of contents. - ------------------------------------------------------------------------------- -VIM.TREESITTER *lua-treesitter* - -Nvim integrates the tree-sitter library for incremental parsing of buffers. +Nvim integrates the `tree-sitter` library for incremental parsing of buffers: +https://tree-sitter.github.io/tree-sitter/ - *vim.treesitter.language_version* -The latest parser ABI version that is supported by the bundled tree-sitter -library. +WARNING: Treesitter support is still experimental and subject to frequent +changes. This documentation may also not fully reflect the latest changes. - *vim.treesitter.minimum_language_version* -The earliest parser ABI version that is supported by the bundled tree-sitter -library. + Type |gO| to see the table of contents. -Parser files *treesitter-parsers* +============================================================================== +PARSER FILES *treesitter-parsers* Parsers are the heart of tree-sitter. They are libraries that tree-sitter will -search for in the `parser` runtime directory. 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: > +search for in the `parser` runtime directory. By default, Nvim bundles only +parsers for C, Lua, and Vimscript, but parsers can be installed manually or +via a plugin like https://github.com/nvim-treesitter/nvim-treesitter. +Parsers are searched for as `parser/{lang}.*` in any 'runtimepath' directory. +If multiple parsers for the same language are found, the first one is used. +(This typically implies the priority "user config > plugins > bundled". +A parser can also be loaded manually using a full path: >lua vim.treesitter.require_language("python", "/path/to/python.so") +< +============================================================================== +LANGUAGE TREES *treesitter-languagetree* + *LanguageTree* -<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 > +As buffers can contain multiple languages (e.g., Vimscript commands in a Lua +file), multiple parsers may be needed to parse the full buffer. These are +combined in a |LanguageTree| object. - parser = vim.treesitter.get_parser(bufnr, lang) +To create a LanguageTree (parser object) for a buffer and a given language, +use >lua -<`bufnr=0` can be used for current buffer. `lang` will default to 'filetype'. + tsparser = vim.treesitter.get_parser(bufnr, lang) +< +`bufnr=0` can be used for current buffer. `lang` will default to 'filetype'. 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. +Whenever you need to access the current syntax tree, parse the buffer: >lua -Parser methods *lua-treesitter-parser* - -tsparser:parse() *tsparser:parse()* -Whenever you need to access the current syntax tree, parse the buffer: > + tstree = tsparser:parse() +< +This will return a table of immutable |treesitter-tree|s that represent 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. - tstree = parser:parse() +Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback, +you must call |vim.treesitter.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. -<This will return a table of immutable trees that represent 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. +See |lua-treesitter-languagetree| for the list of available methods. -Note: 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. +============================================================================== +TREESITTER TREES *treesitter-tree* + *tstree* -tsparser:set_included_regions({region_list}) *tsparser:set_included_regions()* - Changes the regions the parser should consider. This is used for language - injection. {region_list} should be of the form (all zero-based): > - { - {node1, node2}, - ... - } -< - `node1` and `node2` are both considered part of the same region and will - be parsed together with the parser in the same context. +A "treesitter tree" represents the parsed contents of a buffer, which can be +used to perform further analysis. It is a |luaref-userdata| reference to an +object held by the tree-sitter library. -Tree methods *lua-treesitter-tree* +An instance `tstree` of a treesitter tree supports the following methods. tstree:root() *tstree:root()* Return the root node of this tree. @@ -82,8 +80,15 @@ tstree:root() *tstree:root()* tstree:copy() *tstree:copy()* Returns a copy of the `tstree`. +============================================================================== +TREESITTER NODES *treesitter-node* + *tsnode* + +A "treesitter node" represents one specific element of the parsed contents of +a buffer, which can be captured by a |Query| for, e.g., highlighting. It is a +|luaref-userdata| reference to an object held by the tree-sitter library. -Node methods *lua-treesitter-node* +An instance `tsnode` of a treesitter node supports the following methods. tsnode:parent() *tsnode:parent()* Get the node's immediate parent. @@ -160,10 +165,10 @@ tsnode:id() *tsnode:id()* Get an unique identifier for the node inside its own tree. No guarantees are made about this identifier's internal representation, - except for being a primitive lua type with value equality (so not a + except for being a primitive Lua type with value equality (so not a table). Presently it is a (non-printable) string. - Note: the id is not guaranteed to be unique for nodes from different + Note: The `id` is not guaranteed to be unique for nodes from different trees. *tsnode:descendant_for_range()* @@ -176,90 +181,93 @@ tsnode:named_descendant_for_range({start_row}, {start_col}, {end_row}, {end_col} Get the smallest named node within this node that spans the given range of (row, column) positions -Query *lua-treesitter-query* +============================================================================== +TREESITTER QUERIES *treesitter-query* + +Treesitter queries are a way to extract information about a parsed |tstree|, +e.g., for the purpose of highlighting. Briefly, a `query` consists of one or +more patterns. A `pattern` is defined over node types in the syntax tree. A +`match` corresponds to specific elements of the syntax tree which match a +pattern. Patterns may optionally define captures and predicates. A `capture` +allows you to associate names with a specific node in a pattern. A `predicate` +adds arbitrary metadata and conditional data to a match. + +Queries are written in a lisp-like language documented in +https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax +Note: The predicates listed there page differ from those Nvim supports. See +|treesitter-predicates| for a complete list of predicates supported by Nvim. -Tree-sitter queries are supported, they are a way to do pattern-matching over -a tree, using a simple to write lisp-like format. See -https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax for more -information on how to write queries. +Nvim looks for queries as `*.scm` files in a `queries` directory under +`runtimepath`, where each file contains queries for a specific language and +purpose, e.g., `queries/lua/highlights.scm` for highlighting Lua files. +By default, the first query on `runtimepath` is used (which usually implies +that user config takes precedence over plugins, which take precedence over +queries bundled with Neovim). If a query should extend other queries instead +of replacing them, use |treesitter-query-modeline-extends|. -Note: The predicates listed in the web page above differ from those Neovim -supports. See |lua-treesitter-predicates| for a complete list of predicates -supported by Neovim. +See |lua-treesitter-query| for the list of available methods for working with +treesitter queries from Lua. -A `query` consists of one or more patterns. A `pattern` is defined over node -types in the syntax tree. A `match` corresponds to specific elements of the -syntax tree which match a pattern. Patterns may optionally define captures -and predicates. A `capture` allows you to associate names with a specific -node in a pattern. A `predicate` adds arbitrary metadata and conditional data -to a match. -Treesitter Query Predicates *lua-treesitter-predicates* +TREESITTER QUERY PREDICATES *treesitter-predicates* + +Predicates are special scheme nodes that are evaluated to conditionally capture +nodes. For example, the `eq?` predicate can be used as follows: > -When writing queries for treesitter, one might use `predicates`, that is, -special scheme nodes that are evaluated to verify things on a captured node -for example, the |eq?| predicate : > ((identifier) @foo (#eq? @foo "foo")) +< +to only match identifier corresponding to the `"foo"` text. -This will only match identifier corresponding to the `"foo"` text. -Here is a list of built-in predicates : +The following predicates are built in: - `eq?` *ts-predicate-eq?* - This predicate will check text correspondence between nodes or - strings: > + `eq?` *treesitter-predicate-eq?* + Match a string against the text corresponding to a node: > ((identifier) @foo (#eq? @foo "foo")) ((node1) @left (node2) @right (#eq? @left @right)) < - `match?` *ts-predicate-match?* - `vim-match?` *ts-predicate-vim-match?* - This will match if the provided vim regex matches the text - corresponding to a node: > + `match?` *treesitter-predicate-match?* + `vim-match?` *treesitter-predicate-vim-match?* + Match a |regexp| against the text corresponding to a node: > ((identifier) @constant (#match? @constant "^[A-Z_]+$")) -< Note: the `^` and `$` anchors will respectively match the start and - end of the node's text. +< Note: The `^` and `$` anchors will match the start and end of the + node's text. - `lua-match?` *ts-predicate-lua-match?* - This will match the same way than |match?| but using lua regexes. + `lua-match?` *treesitter-predicate-lua-match?* + Match |lua-patterns| against the text corresponding to a node, + similar to `match?` - `contains?` *ts-predicate-contains?* - Will check if any of the following arguments appears in the text - corresponding to the node: > + `contains?` *treesitter-predicate-contains?* + Match a string against parts of the text corresponding to a node: > ((identifier) @foo (#contains? @foo "foo")) - ((identifier) @foo-bar (#contains @foo-bar "foo" "bar")) + ((identifier) @foo-bar (#contains? @foo-bar "foo" "bar")) < - `any-of?` *ts-predicate-any-of?* - Will check if the text is the same as any of the following arguments: > + `any-of?` *treesitter-predicate-any-of?* + Match any of the given strings against the text corresponding to + a node: > ((identifier) @foo (#any-of? @foo "foo" "bar")) < This is the recommended way to check if the node matches one of many - keywords for example, as it has been optimized for this. -< + keywords, as it has been optimized for this. + *lua-treesitter-not-predicate* Each predicate has a `not-` prefixed predicate that is just the negation of the predicate. - *vim.treesitter.query.add_predicate()* -vim.treesitter.query.add_predicate({name}, {handler}) +Further predicates can be added via |vim.treesitter.query.add_predicate()|. +Use |vim.treesitter.query.list_predicates()| to list all available +predicates. -This adds a predicate with the name {name} to be used in queries. -{handler} should be a function whose signature will be : > - handler(match, pattern, bufnr, predicate) -< - *vim.treesitter.query.list_predicates()* -vim.treesitter.query.list_predicates() -This lists the currently available predicates to use in queries. +TREESITTER QUERY DIRECTIVES *treesitter-directives* -Treesitter Query Directive *lua-treesitter-directives* +Treesitter directives store metadata for a node or match and perform side +effects. For example, the `set!` directive sets metadata on the match or node: > -Treesitter queries can also contain `directives`. Directives store metadata -for a node or match and perform side effects. For example, the |set!| -predicate sets metadata on the match or node : > ((identifier) @foo (#set! "type" "parameter")) +< +The following directives are built in: -Built-in directives: - - `set!` *ts-directive-set!* + `set!` *treesitter-directive-set!* Sets key/value metadata for a specific match or capture. Value is accessible as either `metadata[key]` (match specific) or `metadata[capture_id][key]` (capture specific). @@ -273,7 +281,7 @@ Built-in directives: ((identifier) @foo (#set! @foo "kind" "parameter")) ((node1) @left (node2) @right (#set! "type" "pair")) < - `offset!` *ts-directive-offset!* + `offset!` *treesitter-directive-offset!* Takes the range of the captured node and applies an offset. This will generate a new range object for the captured node as `metadata[capture_id].range`. @@ -289,120 +297,408 @@ Built-in directives: ((identifier) @constant (#offset! @constant 0 1 0 -1)) < -Treesitter syntax highlighting (WIP) *lua-treesitter-highlight* +Further directives can be added via |vim.treesitter.query.add_directive()|. +Use |vim.treesitter.query.list_directives()| to list all available +directives. -NOTE: This is a partially implemented feature, and not usable as a default -solution yet. What is documented here is a temporary interface intended -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, with some limitations and additions. Set a highlight query -for a buffer with this code: > +TREESITTER QUERY MODELINES *treesitter-query-modeline* - local query = [[ - "for" @keyword - "if" @keyword - "return" @keyword +Neovim supports to customize the behavior of the queries using a set of +"modelines", that is comments in the queries starting with `;`. Here are the +currently supported modeline alternatives: - (string_literal) @string - (number_literal) @number - (comment) @comment + `inherits: {lang}...` *treesitter-query-modeline-inherits* + Specifies that this query should inherit the queries from {lang}. + This will recursively descend in the queries of {lang} unless wrapped + in parentheses: `({lang})`. + Note: This is meant to be used to include queries from another + language. If you want your query to extend the queries of the same + language, use `extends`. + + `extends` *treesitter-query-modeline-extends* + Specifies that this query should be used as an extension for the + query, i.e. that it should be merged with the others. + Note: The order of the extensions, and the query that will be used as + a base depends on your 'runtimepath' value. + +Note: These modeline comments must be at the top of the query, but can be +repeated, for example, the following two modeline blocks are both valid: > + + ;; inherits: foo,bar + ;; extends + + ;; extends + ;; + ;; inherits: baz +< +============================================================================== +TREESITTER SYNTAX HIGHLIGHTING *treesitter-highlight* + +Syntax highlighting is specified through queries named `highlights.scm`, +which match a |tsnode| in the parsed |tstree| to a `capture` that can be +assigned a highlight group. For example, the query > + + (parameters (identifier) @parameter) +< +matches any `identifier` node inside a function `parameter` node (e.g., the +`bar` in `foo(bar)`) to the capture named `@parameter`. It is also possible to +match literal expressions (provided the parser returns them): > - (preproc_function_def name: (identifier) @function) + "return" @keyword.return +< +Assuming a suitable parser and `highlights.scm` query is found in runtimepath, +treesitter highlighting for the current buffer can be enabled simply via +|vim.treesitter.start()|. + + *treesitter-highlight-groups* +The capture names, with `@` included, are directly usable as highlight groups. +For many commonly used captures, the corresponding highlight groups are linked +to Nvim's standard |highlight-groups| by default but can be overridden in +colorschemes. + +A fallback system is implemented, so that more specific groups fallback to +more generic ones. For instance, in a language that has separate doc comments, +`@comment.doc` could be used. If this group is not defined, the highlighting +for an ordinary `@comment` is used. This way, existing color schemes already +work out of the box, but it is possible to add more specific variants for +queries that make them available. + +As an additional rule, capture highlights can always be specialized by +language, by appending the language name after an additional dot. For +instance, to highlight comments differently per language: >vim + + hi @comment.c guifg=Blue + hi @comment.lua guifg=DarkBlue + hi link @comment.doc.java String +< +The following captures are linked by default to standard |group-name|s: +> + @text.literal Comment + @text.reference Identifier + @text.title Title + @text.uri Underlined + @text.underline Underlined + @text.todo Todo + + @comment Comment + @punctuation Delimiter + + @constant Constant + @constant.builtin Special + @constant.macro Define + @define Define + @macro Macro + @string String + @string.escape SpecialChar + @string.special SpecialChar + @character Character + @character.special SpecialChar + @number Number + @boolean Boolean + @float Float + + @function Function + @function.builtin Special + @function.macro Macro + @parameter Identifier + @method Function + @field Identifier + @property Identifier + @constructor Special + + @conditional Conditional + @repeat Repeat + @label Label + @operator Operator + @keyword Keyword + @exception Exception + + @variable Identifier + @type Type + @type.definition Typedef + @storageclass StorageClass + @structure Structure + @namespace Identifier + @include Include + @preproc PreProc + @debug Debug + @tag Tag +< + *treesitter-highlight-spell* +The special `@spell` capture can be used to indicate that a node should be +spell checked by Nvim's builtin |spell| checker. For example, the following +capture marks comments as to be checked: > - ; ... more definitions - ]] + (comment) @spell +< - highlighter = vim.treesitter.TSHighlighter.new(query, bufnr, lang) - -- alternatively, to use the current buffer and its filetype: - -- highlighter = vim.treesitter.TSHighlighter.new(query) +There is also `@nospell` which disables spellchecking regions with `@spell`. - -- Don't recreate the highlighter for the same buffer, instead - -- modify the query like this: - local query2 = [[ ... ]] - highlighter:set_query(query2) + *treesitter-highlight-conceal* +Treesitter highlighting supports |conceal| via the `conceal` metadata. By +convention, nodes to be concealed are captured as `@conceal`, but any capture +can be used. For example, the following query can be used to hide code block +delimiters in Markdown: > -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|: > + (fenced_code_block_delimiter) @conceal (#set! conceal "") +< +It is also possible to replace a node with a single character, which (unlike +legacy syntax) can be given a custom highlight. For example, the following +(ill-advised) query replaces the `!=` operator by a Unicode glyph, which is +still highlighted the same as other operators: > - ((binary_expression left: (identifier) @WarningMsg.left right: (identifier) @WarningMsg.right) - (eq? @WarningMsg.left @WarningMsg.right)) + "!=" @operator (#set! conceal "≠") < -Treesitter Highlighting Priority *lua-treesitter-highlight-priority* +Conceals specified in this way respect 'conceallevel'. -Tree-sitter uses |nvim_buf_set_extmark()| to set highlights with a default + *treesitter-highlight-priority* +Treesitter uses |nvim_buf_set_extmark()| to set highlights with a default priority of 100. This enables plugins to set a highlighting priority lower or higher than tree-sitter. It is also possible to change the priority of an individual query pattern manually by setting its `"priority"` metadata attribute: > - ( - (super_important_node) @ImportantHighlight - ; Give the whole query highlight priority higher than the default (100) - (set! "priority" 105) - ) + (super_important_node) @ImportantHighlight (#set! "priority" 105) < +============================================================================== +VIM.TREESITTER *lua-treesitter* + +The remainder of this document is a reference manual for the `vim.treesitter` +Lua module, which is the main interface for Nvim's tree-sitter integration. +Most of the following content is automatically generated from the function +documentation. + + + *vim.treesitter.language_version* +The latest parser ABI version that is supported by the bundled tree-sitter +library. + + *vim.treesitter.minimum_language_version* +The earliest parser ABI version that is supported by the bundled tree-sitter +library. ============================================================================== Lua module: vim.treesitter *lua-treesitter-core* -get_parser({bufnr}, {lang}, {opts}) *get_parser()* - Gets the parser for this bufnr / ft combination. + *vim.treesitter.get_captures_at_cursor()* +get_captures_at_cursor({winnr}) + Returns a list of highlight capture names under the cursor + + Parameters: ~ + • {winnr} (number|nil) Window handle or 0 for current window (default) + + Return: ~ + string[] List of capture names + + *vim.treesitter.get_captures_at_pos()* +get_captures_at_pos({bufnr}, {row}, {col}) + Returns a list of highlight captures at the given position + + Each capture is represented by a table containing the capture name as a + string as well as a table of metadata (`priority`, `conceal`, ...; empty + if none are defined). + + Parameters: ~ + • {bufnr} (number) Buffer number (0 for current buffer) + • {row} (number) Position row + • {col} (number) Position column + + Return: ~ + table[] List of captures `{ capture = "capture name", metadata = { ... + } }` + +get_node_at_cursor({winnr}) *vim.treesitter.get_node_at_cursor()* + Returns the smallest named node under the cursor + + Parameters: ~ + • {winnr} (number|nil) Window handle or 0 for current window (default) + + Return: ~ + (string) Name of node under the cursor + + *vim.treesitter.get_node_at_pos()* +get_node_at_pos({bufnr}, {row}, {col}, {opts}) + Returns the smallest named node at the given position + + Parameters: ~ + • {bufnr} (number) Buffer number (0 for current buffer) + • {row} (number) Position row + • {col} (number) Position column + • {opts} (table) Optional keyword arguments: + • lang string|nil Parser language + • ignore_injections boolean Ignore injected languages + (default true) + + Return: ~ + userdata|nil |tsnode| under the cursor + +get_node_range({node_or_range}) *vim.treesitter.get_node_range()* + Returns the node's range or an unpacked range table + + Parameters: ~ + • {node_or_range} (userdata|table) |tsnode| or table of positions + + Return: ~ + (table) `{ start_row, start_col, end_row, end_col }` + +get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()* + Returns the parser for a specific buffer and filetype and attaches it to + the buffer + + If needed, this will create the parser. + + Parameters: ~ + • {bufnr} (number|nil) Buffer the parser should be tied to (default: + current buffer) + • {lang} (string|nil) Filetype of this parser (default: buffer + filetype) + • {opts} (table|nil) Options to pass to the created language tree + + Return: ~ + LanguageTree |LanguageTree| object to use for parsing + + *vim.treesitter.get_string_parser()* +get_string_parser({str}, {lang}, {opts}) + Returns a string parser - If needed this will create the parser. Unconditionally attach the provided - callback + Parameters: ~ + • {str} (string) Text to parse + • {lang} (string) Language of this string + • {opts} (table|nil) Options to pass to the created language tree + + Return: ~ + LanguageTree |LanguageTree| object to use for parsing + +is_ancestor({dest}, {source}) *vim.treesitter.is_ancestor()* + Determines whether a node is the ancestor of another + + Parameters: ~ + • {dest} userdata Possible ancestor |tsnode| + • {source} userdata Possible descendant |tsnode| + + Return: ~ + (boolean) True if {dest} is an ancestor of {source} + + *vim.treesitter.is_in_node_range()* +is_in_node_range({node}, {line}, {col}) + Determines whether (line, col) position is in node range Parameters: ~ - {bufnr} The buffer the parser should be tied to - {lang} The filetype of this parser - {opts} Options object to pass to the created language tree + • {node} userdata |tsnode| defining the range + • {line} (number) Line (0-based) + • {col} (number) Column (0-based) Return: ~ - The parser + (boolean) True if the position is in node range -get_string_parser({str}, {lang}, {opts}) *get_string_parser()* - Gets a string parser +node_contains({node}, {range}) *vim.treesitter.node_contains()* + Determines if a node contains a range Parameters: ~ - {str} The string to parse - {lang} The language of this string - {opts} Options to pass to the created language tree + • {node} userdata |tsnode| + • {range} (table) + + Return: ~ + (boolean) True if the {node} contains the {range} + +show_tree({opts}) *vim.treesitter.show_tree()* + Open a window that displays a textual representation of the nodes in the + language tree. + + While in the window, press "a" to toggle display of anonymous nodes, "I" + to toggle the display of the source language of each node, and press + <Enter> to jump to the node under the cursor in the source buffer. + + Parameters: ~ + • {opts} (table|nil) Optional options table with the following possible + keys: + • lang (string|nil): The language of the source buffer. If + omitted, the filetype of the source buffer is used. + • bufnr (number|nil): Buffer to draw the tree into. If + omitted, a new buffer is created. + • winid (number|nil): Window id to display the tree buffer in. + If omitted, a new window is created with {command}. + • command (string|nil): Vimscript command to create the + window. Default value is "topleft 60vnew". Only used when + {winid} is nil. + • title (string|fun(bufnr:number):string|nil): Title of the + window. If a function, it accepts the buffer number of the + source buffer as its only argument and should return a + string. + +start({bufnr}, {lang}) *vim.treesitter.start()* + Starts treesitter highlighting for a buffer + + Can be used in an ftplugin or FileType autocommand. + + Note: By default, disables regex syntax highlighting, which may be + required for some plugins. In this case, add `vim.bo.syntax = 'on'` after + the call to `start`. + + Example: >lua + + vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', + callback = function(args) + vim.treesitter.start(args.buf, 'latex') + vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed + end + }) +< + + Parameters: ~ + • {bufnr} (number|nil) Buffer to be highlighted (default: current + buffer) + • {lang} (string|nil) Language of the parser (default: buffer + filetype) + +stop({bufnr}) *vim.treesitter.stop()* + Stops treesitter highlighting for a buffer + + Parameters: ~ + • {bufnr} (number|nil) Buffer to stop highlighting (default: current + buffer) ============================================================================== -Lua module: vim.treesitter.language *treesitter-language* +Lua module: vim.treesitter.language *lua-treesitter-language* -inspect_language({lang}) *inspect_language()* +inspect_language({lang}) *vim.treesitter.language.inspect_language()* Inspects the provided language. Inspecting provides some useful information on the language like node names, ... Parameters: ~ - {lang} The language. + • {lang} (string) Language + + Return: ~ + (table) -require_language({lang}, {path}, {silent}) *require_language()* - Asserts that the provided language is installed, and optionally provide a - path for the parser + *vim.treesitter.language.require_language()* +require_language({lang}, {path}, {silent}, {symbol_name}) + Asserts that a parser for the language {lang} is installed. - Parsers are searched in the `parser` runtime directory. + Parsers are searched in the `parser` runtime directory, or the provided + {path} Parameters: ~ - {lang} The language the parser should parse - {path} Optional path the parser is located at - {silent} Don't throw an error if language not found + • {lang} (string) Language the parser should parse + • {path} (string|nil) Optional path the parser is located at + • {silent} (boolean|nil) Don't throw an error if language not + found + • {symbol_name} (string|nil) Internal symbol name for the language to + load + + Return: ~ + (boolean) If the specified language is installed ============================================================================== -Lua module: vim.treesitter.query *treesitter-query* +Lua module: vim.treesitter.query *lua-treesitter-query* -add_directive({name}, {handler}, {force}) *add_directive()* + *vim.treesitter.query.add_directive()* +add_directive({name}, {handler}, {force}) Adds a new directive to be used in queries Handlers can set match level data by setting directly on the metadata @@ -411,61 +707,85 @@ add_directive({name}, {handler}, {force}) *add_directive()* `metadata[capture_id].key = value` Parameters: ~ - {name} the name of the directive, without leading # - {handler} the handler function to be used signature will be (match, - pattern, bufnr, predicate, metadata) - -add_predicate({name}, {handler}, {force}) *add_predicate()* + • {name} (string) Name of the directive, without leading # + • {handler} function(match:table, pattern:string, bufnr:number, + predicate:string[], metadata:table) + • match: see |treesitter-query| + • node-level data are accessible via `match[capture_id]` + + • pattern: see |treesitter-query| + • predicate: list of strings containing the full directive + being called, e.g. `(node (#set! conceal "-"))` would get + the predicate `{ "#set!", "conceal", "-" }` + + *vim.treesitter.query.add_predicate()* +add_predicate({name}, {handler}, {force}) Adds a new predicate to be used in queries Parameters: ~ - {name} the name of the predicate, without leading # - {handler} the handler function to be used signature will be (match, - pattern, bufnr, predicate) - -get_node_text({node}, {source}) *get_node_text()* + • {name} (string) Name of the predicate, without leading # + • {handler} function(match:table, pattern:string, bufnr:number, + predicate:string[]) + • see |vim.treesitter.query.add_directive()| for argument + meanings + + *vim.treesitter.query.get_node_text()* +get_node_text({node}, {source}, {opts}) Gets the text corresponding to a given node Parameters: ~ - {node} the node - {source} The buffer or string from which the node is extracted + • {node} userdata |tsnode| + • {source} (number|string) Buffer or string from which the {node} is + extracted + • {opts} (table|nil) Optional parameters. + • concat: (boolean) Concatenate result in a string (default + true) + + Return: ~ + (string[]|string) -get_query({lang}, {query_name}) *get_query()* +get_query({lang}, {query_name}) *vim.treesitter.query.get_query()* Returns the runtime query {query_name} for {lang}. Parameters: ~ - {lang} The language to use for the query - {query_name} The name of the query (i.e. "highlights") + • {lang} (string) Language to use for the query + • {query_name} (string) Name of the query (e.g. "highlights") Return: ~ - The corresponding query, parsed. + Query Parsed query - *get_query_files()* + *vim.treesitter.query.get_query_files()* get_query_files({lang}, {query_name}, {is_included}) Gets the list of files used to make up a query Parameters: ~ - {lang} The language - {query_name} The name of the query to load - {is_included} Internal parameter, most of the time left as `nil` + • {lang} (string) Language to get query for + • {query_name} (string) Name of the query to load (e.g., "highlights") + • {is_included} (boolean|nil) Internal parameter, most of the time left + as `nil` -list_directives() *list_directives()* + Return: ~ + string[] query_files List of files to load for given query and + language + +list_directives() *vim.treesitter.query.list_directives()* Lists the currently available directives to use in queries. Return: ~ - The list of supported directives. + string[] List of supported directives. + +list_predicates() *vim.treesitter.query.list_predicates()* + Lists the currently available predicates to use in queries. -list_predicates() *list_predicates()* Return: ~ - The list of supported predicates. + string[] List of supported predicates. -parse_query({lang}, {query}) *parse_query()* +parse_query({lang}, {query}) *vim.treesitter.query.parse_query()* Parse {query} as a string. (If the query is in a file, the caller should read the contents into a string before calling). - Returns a `Query` (see |lua-treesitter-query|) object which can be used to - search nodes in the syntax tree for the patterns defined in {query} using - `iter_*` methods below. + Returns a `Query` (see |lua-treesitter-query|) object which can be used to search nodes in + the syntax tree for the patterns defined in {query} using `iter_*` methods below. Exposes `info` and `captures` with additional context about {query}. • `captures` contains the list of unique capture names defined in {query}. @@ -473,208 +793,214 @@ parse_query({lang}, {query}) *parse_query()* • `info.patterns` contains information about predicates. Parameters: ~ - {lang} (string) The language - {query} (string) A string containing the query (s-expr syntax) + • {lang} (string) Language to use for the query + • {query} (string) Query in s-expr syntax Return: ~ - The query + Query Parsed query *Query:iter_captures()* Query:iter_captures({self}, {node}, {source}, {start}, {stop}) Iterate over all captures from all matches inside {node} - {source} is needed if the query contains predicates, then the caller must + {source} 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 (if relevant). {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). When - omitted the start and end row values are used from the given node. + {node}, i.e., to get syntax highlight matches in the current viewport). + When omitted, the {start} and {end} row values are used from the given + node. - The iterator returns three values, a numeric id identifying the capture, + The iterator returns three values: a numeric id identifying the capture, the captured node, and metadata from any directives processing the match. - The following example shows how to get captures by name: -> - - for id, node, metadata 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 + The following example shows how to get captures by name: >lua + + for id, node, metadata 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 < Parameters: ~ - {node} The node under which the search will occur - {source} The source buffer or string to extract text from - {start} The starting line of the search - {stop} The stopping line of the search (end-exclusive) - {self} + • {node} userdata |tsnode| under which the search will occur + • {source} (number|string) Source buffer or string to extract text from + • {start} (number) Starting line for the search + • {stop} (number) Stopping line for the search (end-exclusive) + • {self} Return: ~ - The matching capture id - The captured node + (number) capture Matching capture id + (table) capture_node Capture for {node} + (table) metadata for the {capture} *Query:iter_matches()* Query:iter_matches({self}, {node}, {source}, {start}, {stop}) Iterates the matches of self on a given range. - Iterate over all matches within a node. The arguments are the same as for - |query:iter_captures()| but the iterated values are different: an + 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, a table mapping capture indices to nodes, and metadata from any directives processing the match. - If the query has more than one pattern the capture table might be sparse, - and e.g. `pairs()` method should be used over `ipairs`. Here an example - iterating over all captures in every match: -> + If the query has more than one pattern, the capture table might be sparse + and e.g. `pairs()` method should be used over `ipairs` . Here is an example iterating over all captures in every match: >lua - for pattern, match, metadata 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 + for pattern, match, metadata 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 - local node_data = metadata[id] -- Node level metadata + local node_data = metadata[id] -- Node level metadata - ... use the info here ... - end - end + ... use the info here ... + end + end < Parameters: ~ - {node} The node under which the search will occur - {source} The source buffer or string to search - {start} The starting line of the search - {stop} The stopping line of the search (end-exclusive) - {self} + • {node} userdata |tsnode| under which the search will occur + • {source} (number|string) Source buffer or string to search + • {start} (number) Starting line for the search + • {stop} (number) Stopping line for the search (end-exclusive) + • {self} Return: ~ - The matching pattern id - The matching match + (number) pattern id + (table) match + (table) metadata -set_query({lang}, {query_name}, {text}) *set_query()* - Sets the runtime query {query_name} for {lang} + *vim.treesitter.query.set_query()* +set_query({lang}, {query_name}, {text}) + Sets the runtime query named {query_name} for {lang} This allows users to override any runtime files and/or configuration set by plugins. Parameters: ~ - {lang} string: The language to use for the query - {query_name} string: The name of the query (i.e. "highlights") - {text} string: The query text (unparsed). + • {lang} (string) Language to use for the query + • {query_name} (string) Name of the query (e.g., "highlights") + • {text} (string) Query text (unparsed). ============================================================================== -Lua module: vim.treesitter.highlighter *treesitter-highlighter* +Lua module: vim.treesitter.highlighter *lua-treesitter-highlighter* -new({tree}, {opts}) *highlighter.new()* +new({tree}, {opts}) *vim.treesitter.highlighter.new()* Creates a new highlighter using Parameters: ~ - {tree} The language tree to use for highlighting - {opts} Table used to configure the highlighter - • queries: Table to overwrite queries used by the highlighter + • {tree} LanguageTree |LanguageTree| parser object to use for highlighting + • {opts} (table|nil) Configuration of the highlighter: + • queries table overwrite queries used by the highlighter + + Return: ~ + TSHighlighter Created highlighter object TSHighlighter:destroy({self}) *TSHighlighter:destroy()* Removes all internal references to the highlighter Parameters: ~ - {self} - -TSHighlighter:get_query({self}, {lang}) *TSHighlighter:get_query()* - Gets the query used for - - Parameters: ~ - {lang} A language used by the highlighter. - {self} + • {self} ============================================================================== -Lua module: vim.treesitter.languagetree *treesitter-languagetree* - -LanguageTree:add_child({self}, {lang}) *LanguageTree:add_child()* - Adds a child language to this tree. - - If the language already exists as a child, it will first be removed. - - Parameters: ~ - {lang} The language to add. - {self} +Lua module: vim.treesitter.languagetree *lua-treesitter-languagetree* LanguageTree:children({self}) *LanguageTree:children()* Returns a map of language to child tree. Parameters: ~ - {self} + • {self} LanguageTree:contains({self}, {range}) *LanguageTree:contains()* - Determines whether {range} is contained in this language tree + Determines whether {range} is contained in the |LanguageTree|. Parameters: ~ - {range} A range, that is a `{ start_line, start_col, end_line, - end_col }` table. - {self} + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {self} + + Return: ~ + (boolean) LanguageTree:destroy({self}) *LanguageTree:destroy()* - Destroys this language tree and all its children. + Destroys this |LanguageTree| and all its children. Any cleanup logic should be performed here. Note: This DOES NOT remove this tree from a parent. Instead, `remove_child` must be called on the parent to remove it. Parameters: ~ - {self} + • {self} *LanguageTree:for_each_child()* LanguageTree:for_each_child({self}, {fn}, {include_self}) - Invokes the callback for each LanguageTree and it's children recursively + Invokes the callback for each |LanguageTree| and its children recursively Parameters: ~ - {fn} The function to invoke. This is invoked with arguments - (tree: LanguageTree, lang: string) - {include_self} Whether to include the invoking tree in the results. - {self} + • {fn} function(tree: LanguageTree, lang: string) + • {include_self} (boolean) Whether to include the invoking tree in the + results + • {self} LanguageTree:for_each_tree({self}, {fn}) *LanguageTree:for_each_tree()* - Invokes the callback for each treesitter trees recursively. + Invokes the callback for each |LanguageTree| recursively. - Note, this includes the invoking language tree's trees as well. + Note: This includes the invoking tree's child trees as well. Parameters: ~ - {fn} The callback to invoke. The callback is invoked with arguments - (tree: TSTree, languageTree: LanguageTree) - {self} + • {fn} function(tree: TSTree, languageTree: LanguageTree) + • {self} LanguageTree:included_regions({self}) *LanguageTree:included_regions()* Gets the set of included regions Parameters: ~ - {self} + • {self} LanguageTree:invalidate({self}, {reload}) *LanguageTree:invalidate()* Invalidates this parser and all its children Parameters: ~ - {self} + • {self} LanguageTree:is_valid({self}) *LanguageTree:is_valid()* Determines whether this tree is valid. If the tree is invalid, call `parse()` . This will return the updated tree. Parameters: ~ - {self} + • {self} LanguageTree:lang({self}) *LanguageTree:lang()* Gets the language of this tree node. Parameters: ~ - {self} + • {self} *LanguageTree:language_for_range()* LanguageTree:language_for_range({self}, {range}) - Gets the appropriate language that contains {range} + Gets the appropriate language that contains {range}. Parameters: ~ - {range} A text range, see |LanguageTree:contains| - {self} + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {self} + + Return: ~ + LanguageTree Managing {range} + + *LanguageTree:named_node_for_range()* +LanguageTree:named_node_for_range({self}, {range}, {opts}) + Gets the smallest named node that contains {range}. + + Parameters: ~ + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {opts} (table|nil) Optional keyword arguments: + • ignore_injections boolean Ignore injected languages + (default true) + • {self} + + Return: ~ + userdata|nil Found |tsnode| LanguageTree:parse({self}) *LanguageTree:parse()* Parses all defined regions using a treesitter parser for the language this @@ -682,14 +1008,18 @@ LanguageTree:parse({self}) *LanguageTree:parse()* determine if any child languages should be created. Parameters: ~ - {self} + • {self} + + Return: ~ + userdata[] Table of parsed |tstree| + (table) Change list LanguageTree:register_cbs({self}, {cbs}) *LanguageTree:register_cbs()* - Registers callbacks for the parser. + Registers callbacks for the |LanguageTree|. Parameters: ~ - {cbs} (table) An |nvim_buf_attach()|-like table argument with the - following keys : + • {cbs} (table) An |nvim_buf_attach()|-like table argument with the + following handlers: • `on_bytes` : see |nvim_buf_attach()|, but this will be called after the parsers callback. • `on_changedtree` : a callback that will be called every time the tree has syntactical changes. It will only be passed one @@ -699,61 +1029,50 @@ LanguageTree:register_cbs({self}, {cbs}) *LanguageTree:register_cbs()* tree. • `on_child_removed` : emitted when a child is removed from the tree. - {self} + • {self} -LanguageTree:remove_child({self}, {lang}) *LanguageTree:remove_child()* - Removes a child language from this tree. +LanguageTree:source({self}) *LanguageTree:source()* + Returns the source content of the language tree (bufnr or string). Parameters: ~ - {lang} The language to remove. - {self} - - *LanguageTree:set_included_regions()* -LanguageTree:set_included_regions({self}, {regions}) - Sets the included regions that should be parsed by this parser. A region - is a set of nodes and/or ranges that will be parsed in the same context. - - For example, `{ { node1 }, { node2} }` is two separate regions. This will - be parsed by the parser in two different contexts... thus resulting in two - separate trees. + • {self} - `{ { node1, node2 } }` is a single region consisting of two nodes. This - will be parsed by the parser in a single context... thus resulting in a - single tree. - - This allows for embedded languages to be parsed together across different - nodes, which is useful for templating languages like ERB and EJS. - - Note, this call invalidates the tree and requires it to be parsed again. + *LanguageTree:tree_for_range()* +LanguageTree:tree_for_range({self}, {range}, {opts}) + Gets the tree that contains {range}. Parameters: ~ - {regions} (table) list of regions this tree should manage and parse. - {self} - -LanguageTree:source({self}) *LanguageTree:source()* - Returns the source content of the language tree (bufnr or string). + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {opts} (table|nil) Optional keyword arguments: + • ignore_injections boolean Ignore injected languages + (default true) + • {self} - Parameters: ~ - {self} + Return: ~ + userdata|nil Contained |tstree| LanguageTree:trees({self}) *LanguageTree:trees()* Returns all trees this language tree contains. Does not include child languages. Parameters: ~ - {self} + • {self} -new({source}, {lang}, {opts}) *languagetree.new()* - Represents a single treesitter parser for a language. The language can - contain child languages with in its range, hence the tree. +new({source}, {lang}, {opts}) *vim.treesitter.languagetree.new()* + A |LanguageTree| holds the treesitter parser for a given language {lang} + used to parse a buffer. As the buffer may contain injected languages, the LanguageTree needs to store parsers for these child languages as well (which in turn + may contain child languages themselves, hence the name). Parameters: ~ - {source} Can be a bufnr or a string of text to parse - {lang} The language this tree represents - {opts} Options table - {opts.injections} A table of language to injection query strings. - This is useful for overriding the built-in runtime - file searching for the injection language query per - language. + • {source} (number|string) Buffer or a string of text to parse + • {lang} (string) Root language this tree represents + • {opts} (table|nil) Optional keyword arguments: + • injections table Mapping language to injection query + strings. This is useful for overriding the built-in + runtime file searching for the injection language query + per language. + + Return: ~ + LanguageTree |LanguageTree| parser object vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/uganda.txt b/runtime/doc/uganda.txt index 23dfa082a0..d8fc26ad17 100644 --- a/runtime/doc/uganda.txt +++ b/runtime/doc/uganda.txt @@ -11,9 +11,9 @@ Vim is Charityware. You can use and copy it as much as you like, but you are encouraged to make a donation for needy children in Uganda. Please see |kcc| below or visit the ICCF web site, available at these URLs: - http://iccf-holland.org/ - http://www.vim.org/iccf/ - http://www.iccf.nl/ + https://iccf-holland.org/ + https://www.vim.org/iccf/ + https://www.iccf.nl/ You can also sponsor the development of Vim. Vim sponsors can vote for features. See |sponsor|. The money goes to Uganda anyway. @@ -166,10 +166,11 @@ households are stimulated to build a proper latrine. I helped setting up a production site for cement slabs. These are used to build a good latrine. They are sold below cost price. -There is a small clinic at the project, which provides children and their -family with medical help. When needed, transport to a hospital is offered. -Immunization programs are carried out and help is provided when an epidemic is -breaking out (measles and cholera have been a problem). +There is a clinic at the project, which provides children and their family +medical help. Since 2020 a maternity ward was added and 24/7 service is +available. When needed, transport to a hospital is offered. Immunization +programs are carried out and help is provided when an epidemic is breaking out +(measles and cholera have been a problem). *donate* Summer 1994 to summer 1995 I spent a whole year at the centre, working as a volunteer. I have helped to expand the centre and worked in the area of water @@ -211,44 +212,29 @@ Check the ICCF web site for the latest information! See |iccf| for the URL. USA: The methods mentioned below can be used. - Sending a check to the Nehemiah Group Outreach Society (NGOS) - is no longer possible, unfortunately. We are looking for - another way to get you an IRS tax receipt. - For sponsoring a child contact KCF in Canada (see below). US - checks can be sent to them to lower banking costs. - -Canada: Contact Kibaale Children's Fund (KCF) in Surrey, Canada. They - take care of the Canadian sponsors for the children in - Kibaale. KCF forwards 100% of the money to the project in - Uganda. You can send them a one time donation directly. + If you must send a check send it to our Canadian partner: + https://www.kuwasha.net/ + +Canada: Contact Kuwasha in Surrey, Canada. They take care of the + Canadian sponsors for the children in Kibaale. Kuwasha + forwards 100% of the money to the project in Uganda. You can + send them a one time donation directly. Please send me a note so that I know what has been donated - because of Vim. Ask KCF for information about sponsorship. - Kibaale Children's Fund c/o Pacific Academy - 10238-168 Street - Surrey, B.C. V4N 1Z4 - Canada - Phone: 604-581-5353 - If you make a donation to Kibaale Children's Fund (KCF) you - will receive a tax receipt which can be submitted with your - tax return. - -Holland: Transfer to the account of "Stichting ICCF Holland" in Lisse. - This will allow for tax deduction if you live in Holland. - Postbank, nr. 4548774 - IBAN: NL95 INGB 0004 5487 74 + because of Vim. Look on their site for information about + sponsorship: https://www.kuwasha.net/ + If you make a donation to Kuwasha you will receive a tax + receipt which can be submitted with your tax return. + +Holland: Transfer to the account of "Stichting ICCF Holland" in + Amersfoort. This will allow for tax deduction if you live in + Holland. ING bank, IBAN: NL95 INGB 0004 5487 74 Germany: It is possible to make donations that allow for a tax return. Check the ICCF web site for the latest information: - http://iccf-holland.org/germany.html - -World: Use a postal money order. That should be possible from any - country, mostly from the post office. Use this name (which is - in my passport): "Abraham Moolenaar". Use Euro for the - currency if possible. + https://iccf-holland.org/germany.html -Europe: Use a bank transfer if possible. Your bank should have a form - that you can use for this. See "Others" below for the swift - code and IBAN number. +Europe: Use a bank transfer if possible. See "Others" below for the + swift code and IBAN number. Any other method should work. Ask for information about sponsorship. @@ -258,28 +244,12 @@ Credit Card: You can use PayPal to send money with a Credit card. This is https://www.paypal.com/en_US/mrb/pal=XAC62PML3GF8Q The e-mail address for sending the money to is: Bram@iccf-holland.org - For amounts above 400 Euro ($500) sending a check is - preferred. - -Others: Transfer to one of these accounts if possible: - Postbank, account 4548774 - Swift code: INGB NL 2A - IBAN: NL95 INGB 0004 5487 74 - under the name "stichting ICCF Holland", Lisse - If that doesn't work: - Rabobank Lisse, account 3765.05.117 - Swift code: RABO NL 2U - under the name "Bram Moolenaar", Lisse - Otherwise, send a check in euro or US dollars to the address - below. Minimal amount: $70 (my bank does not accept smaller - amounts for foreign check, sorry) - -Address to send checks to: - Bram Moolenaar - Finsterruetihof 1 - 8134 Adliswil - Switzerland - -This address is expected to be valid for a long time. + +Others: Transfer to this account if possible: + ING bank: IBAN: NL95 INGB 0004 5487 74 + Swift code: INGBNL2A + under the name "stichting ICCF Holland", Amersfoort + Checks are not accepted. + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt index 3fb9ed1125..3110d0817c 100644 --- a/runtime/doc/ui.txt +++ b/runtime/doc/ui.txt @@ -23,40 +23,41 @@ screen grid with a size of width × height cells. This is typically done by an embedder at startup (see |ui-startup|), but UIs can also connect to a running Nvim instance and invoke nvim_ui_attach(). The `options` parameter is a map with these (optional) keys: + *ui-rgb* - `rgb` Decides the color format. - true: (default) 24-bit RGB colors - false: Terminal colors (8-bit, max 256) - *ui-override* - `override` Decides how UI capabilities are resolved. - true: Enable requested UI capabilities, even - if not supported by all connected UIs - (including |TUI|). - false: (default) Disable UI capabilities not - supported by all connected UIs - (including TUI). - *ui-ext-options* - `ext_cmdline` Externalize the cmdline. |ui-cmdline| - `ext_hlstate` Detailed highlight state. |ui-hlstate| - Sets `ext_linegrid` implicitly. - `ext_linegrid` Line-based grid events. |ui-linegrid| - Deactivates |ui-grid-old| implicitly. - `ext_messages` Externalize messages. |ui-messages| - Sets `ext_linegrid` and `ext_cmdline` implicitly. - `ext_multigrid` Per-window grid events. |ui-multigrid| - Sets `ext_linegrid` implicitly. - `ext_popupmenu` Externalize |popupmenu-completion| and - 'wildmenu'. |ui-popupmenu| - `ext_tabline` Externalize the tabline. |ui-tabline| - `ext_termcolors` Use external default colors. - `term_name` Sets the name of the terminal 'term'. - `term_colors` Sets the number of supported colors 't_Co'. - `term_background` Sets the default value of 'background'. - `stdin_fd` Read buffer from `fd` as if it was a stdin pipe - This option can only used by |--embed| ui, - see |ui-startup-stdin|. +- `rgb` Decides the color format. + - true: (default) 24-bit RGB colors + - false: Terminal colors (8-bit, max 256) + *ui-override* +- `override` Decides how UI capabilities are resolved. + - true: Enable requested UI capabilities, even if not + supported by all connected UIs (including |TUI|). + - false: (default) Disable UI capabilities not + supported by all connected UIs (including TUI). + *ui-ext-options* +- `ext_cmdline` Externalize the cmdline. |ui-cmdline| +- `ext_hlstate` Detailed highlight state. |ui-hlstate| + Sets `ext_linegrid` implicitly. +- `ext_linegrid` Line-based grid events. |ui-linegrid| + Deactivates |ui-grid-old| implicitly. +- `ext_messages` Externalize messages. |ui-messages| + Sets `ext_linegrid` and `ext_cmdline` implicitly. +- `ext_multigrid` Per-window grid events. |ui-multigrid| + Sets `ext_linegrid` implicitly. +- `ext_popupmenu` Externalize |popupmenu-completion| and + 'wildmenu'. |ui-popupmenu| +- `ext_tabline` Externalize the tabline. |ui-tabline| +- `ext_termcolors` Use external default colors. +- `term_name` Sets the name of the terminal 'term'. +- `term_colors` Sets the number of supported colors 't_Co'. +- `term_background` Sets the default value of 'background'. +- `stdin_fd` Read buffer from `fd` as if it was a stdin pipe + This option can only used by |--embed| ui, + see |ui-startup-stdin|. + `stdin_tty` Tells if `stdin` is a `tty` or not. + `stdout_tty` Tells if `stdout` is a `tty` or not. Specifying an unknown option is an error; UIs can check the |api-metadata| `ui_options` key for supported options. @@ -120,7 +121,7 @@ for forward-compatibility. |api-contract| UI startup *ui-startup* UI embedders (clients that start Nvim with |--embed| and later call -|nvim_ui_attach()|) must start Nvim without |--headless|: > +|nvim_ui_attach()|) must start Nvim without |--headless|: >bash nvim --embed Nvim will pause before loading startup files and reading buffers, so the UI has a chance to invoke requests and do early initialization. Startup will @@ -133,14 +134,18 @@ procedure: 1. Invoke |nvim_get_api_info()|, if needed to setup the client library and/or to get the list of supported UI extensions. + 2. Do any configuration that should be happen before user config is loaded. Buffers and windows are not available at this point, but this could be used to set |g:| variables visible to init.vim + 3. If the UI wants to do additional setup after user config is loaded, - register a VimEnter autocmd: > + register a VimEnter autocmd: >vim nvim_command("autocmd VimEnter * call rpcrequest(1, 'vimenter')") -<4. Now invoke |nvim_ui_attach()|. The UI must handle user input by now: + +4. Now invoke |nvim_ui_attach()|. The UI must handle user input by now: sourcing init.vim and loading buffers might lead to blocking prompts. + 5. If step 3 was used, Nvim will send a blocking "vimenter" request to the UI. Inside this request handler, the UI can safely do any initialization before entering normal mode, for example reading variables set by init.vim. @@ -164,13 +169,13 @@ Global Events *ui-global* The following UI events are always emitted, and describe global state of the editor. -["set_title", title] -["set_icon", icon] +["set_title", title] ~ +["set_icon", icon] ~ Set the window title, and icon (minimized) window title, respectively. In windowing systems not distinguishing between the two, "set_icon" can be ignored. -["mode_info_set", cursor_style_enabled, mode_info] +["mode_info_set", cursor_style_enabled, mode_info] ~ `cursor_style_enabled` is a boolean indicating if the UI should set the cursor style. `mode_info` is a list of mode property maps. The current mode is given by the `mode_idx` field of the `mode_change` @@ -197,20 +202,21 @@ the editor. `hl_id`: Use `attr_id` instead. `hl_lm`: Use `attr_id_lm` instead. -["option_set", name, value] +["option_set", name, value] ~ UI-related option changed, where `name` is one of: - 'arabicshape' - 'ambiwidth' - 'emoji' - 'guifont' - 'guifontwide' - 'linespace' - 'mousefocus' - 'pumblend' - 'showtabline' - 'termguicolors' - "ext_*" (all |ui-ext-options|) + - 'arabicshape' + - 'ambiwidth' + - 'emoji' + - 'guifont' + - 'guifontwide' + - 'linespace' + - 'mousefocus' + - 'mousemoveevent' + - 'pumblend' + - 'showtabline' + - 'termguicolors' + - "ext_*" (all |ui-ext-options|) Triggered when the UI first connects to Nvim, and whenever an option is changed by the user or a plugin. @@ -223,7 +229,7 @@ the editor. however a UI might still use such options when rendering raw text sent from Nvim, like for |ui-cmdline|. -["mode_change", mode, mode_idx] +["mode_change", mode, mode_idx] ~ Editor mode changed. The `mode` parameter is a string representing the current mode. `mode_idx` is an index into the array emitted in the `mode_info_set` event. UIs should change the cursor style @@ -232,30 +238,30 @@ the editor. instance more submodes and temporary states might be represented as separate modes. -["mouse_on"] -["mouse_off"] +["mouse_on"] ~ +["mouse_off"] ~ 'mouse' was enabled/disabled in the current editor mode. Useful for a terminal UI, or embedding into an application where Nvim mouse would conflict with other usages of the mouse. Other UI:s may ignore this event. -["busy_start"] -["busy_stop"] +["busy_start"] ~ +["busy_stop"] ~ Indicates to the UI that it must stop rendering the cursor. This event is misnamed and does not actually have anything to do with busyness. -["suspend"] +["suspend"] ~ |:suspend| command or |CTRL-Z| mapping is used. A terminal client (or another client where it makes sense) could suspend itself. Other clients can safely ignore it. -["update_menu"] +["update_menu"] ~ The menu mappings changed. -["bell"] -["visual_bell"] +["bell"] ~ +["visual_bell"] ~ Notify the user with an audible or visual bell, respectively. -["flush"] +["flush"] ~ Nvim is done redrawing the screen. For an implementation that renders to an internal buffer, this is the time to display the redrawn parts to the user. @@ -278,11 +284,11 @@ be created; to enable per-window grids, activate |ui-multigrid|. Highlight attribute groups are predefined. UIs should maintain a table to map numerical highlight ids to the actual attributes. -["grid_resize", grid, width, height] +["grid_resize", grid, width, height] ~ Resize a `grid`. If `grid` wasn't seen by the client before, a new grid is being created with this size. -["default_colors_set", rgb_fg, rgb_bg, rgb_sp, cterm_fg, cterm_bg] +["default_colors_set", rgb_fg, rgb_bg, rgb_sp, cterm_fg, cterm_bg] ~ The first three arguments set the default foreground, background and special colors respectively. `cterm_fg` and `cterm_bg` specifies the default color codes to use in a 256-color terminal. @@ -299,7 +305,7 @@ numerical highlight ids to the actual attributes. screen with changed background color itself. *ui-event-hl_attr_define* -["hl_attr_define", id, rgb_attr, cterm_attr, info] +["hl_attr_define", id, rgb_attr, cterm_attr, info] ~ Add a highlight with `id` to the highlight table, with the attributes specified by the `rgb_attr` and `cterm_attr` dicts, with the following (all optional) keys. @@ -318,6 +324,7 @@ numerical highlight ids to the actual attributes. `underdouble`: double underlined text. The lines have `special` color. `underdotted`: underdotted text. The dots have `special` color. `underdashed`: underdashed text. The dashes have `special` color. + `altfont`: alternative font. `blend`: Blend level (0-100). Could be used by UIs to support blending floating windows to the background or to signal a transparent cursor. @@ -345,7 +352,7 @@ numerical highlight ids to the actual attributes. `info` is an empty array by default, and will be used by the |ui-hlstate| extension explained below. -["hl_group_set", name, hl_id] +["hl_group_set", name, hl_id] ~ The bulitin highlight group `name` was set to use the attributes `hl_id` defined by a previous `hl_attr_define` call. This event is not needed to render the grids which use attribute ids directly, but is useful @@ -354,7 +361,7 @@ numerical highlight ids to the actual attributes. use the |hl-Pmenu| family of builtin highlights. *ui-event-grid_line* -["grid_line", grid, row, col_start, cells] +["grid_line", grid, row, col_start, cells] ~ Redraw a continuous part of a `row` on a `grid`, starting at the column `col_start`. `cells` is an array of arrays each with 1 to 3 items: `[text(, hl_id, repeat)]` . `text` is the UTF-8 text that should be put in @@ -373,19 +380,19 @@ numerical highlight ids to the actual attributes. enough to cover the remaining line, will be sent when the rest of the line should be cleared. -["grid_clear", grid] +["grid_clear", grid] ~ Clear a `grid`. -["grid_destroy", grid] +["grid_destroy", grid] ~ `grid` will not be used anymore and the UI can free any data associated with it. -["grid_cursor_goto", grid, row, column] +["grid_cursor_goto", grid, row, column] ~ Makes `grid` the current grid and `row, column` the cursor position on this grid. This event will be sent at most once in a `redraw` batch and indicates the visible cursor position. -["grid_scroll", grid, top, bot, left, right, rows, cols] +["grid_scroll", grid, top, bot, left, right, rows, cols] ~ Scroll a region of `grid`. This is semantically unrelated to editor |scrolling|, rather this is an optimized way to say "copy these screen cells". @@ -438,30 +445,30 @@ Grid Events (cell-based) *ui-grid-old* This is the legacy representation of the screen grid, emitted if |ui-linegrid| is not active. New UIs should implement |ui-linegrid| instead. -["resize", width, height] +["resize", width, height] ~ The grid is resized to `width` and `height` cells. -["clear"] +["clear"] ~ Clear the grid. -["eol_clear"] +["eol_clear"] ~ Clear from the cursor position to the end of the current line. -["cursor_goto", row, col] +["cursor_goto", row, col] ~ Move the cursor to position (row, col). Currently, the same cursor is used to define the position for text insertion and the visible cursor. However, only the last cursor position, after processing the entire array in the "redraw" event, is intended to be a visible cursor position. -["update_fg", color] -["update_bg", color] -["update_sp", color] +["update_fg", color] ~ +["update_bg", color] ~ +["update_sp", color] ~ Set the default foreground, background and special colors respectively. *ui-event-highlight_set* -["highlight_set", attrs] +["highlight_set", attrs] ~ Set the attributes that the next text put on the grid will have. `attrs` is a dict with the keys below. Any absent key is reset to its default value. Color defaults are set by the `update_fg` etc @@ -481,18 +488,18 @@ is not active. New UIs should implement |ui-linegrid| instead. `underdotted`: underdotted text. The dots have `special` color. `underdashed`: underdashed text. The dashes have `special` color. -["put", text] +["put", text] ~ The (utf-8 encoded) string `text` is put at the cursor position (and the cursor is advanced), with the highlights as set by the last `highlight_set` update. -["set_scroll_region", top, bot, left, right] +["set_scroll_region", top, bot, left, right] ~ Define the scroll region used by `scroll` below. Note: ranges are end-inclusive, which is inconsistent with API conventions. -["scroll", count] +["scroll", count] ~ Scroll the text in the scroll region. The diagrams below illustrate what will happen, depending on the scroll direction. "=" is used to represent the SR(scroll region) boundaries and "-" the moved rectangles. @@ -575,7 +582,7 @@ The multigrid extension gives UIs more control over how windows are displayed: per-window. Or reserve space around the border of the window for its own elements, such as scrollbars from the UI toolkit. - A dedicated grid is used for messages, which may scroll over the window - area. (Alternatively |ext_messages| can be used). + area. (Alternatively |ui-messages| can be used). By default, the grid size is handled by Nvim and set to the outer grid size (i.e. the size of the window frame in Nvim) whenever the split is created. @@ -587,46 +594,46 @@ A window can be hidden and redisplayed without its grid being deallocated. This can happen multiple times for the same window, for instance when switching tabs. -["win_pos", grid, win, start_row, start_col, width, height] +["win_pos", grid, win, start_row, start_col, width, height] ~ Set the position and size of the grid in Nvim (i.e. the outer grid size). If the window was previously hidden, it should now be shown again. -["win_float_pos", grid, win, anchor, anchor_grid, anchor_row, anchor_col, focusable] +["win_float_pos", grid, win, anchor, anchor_grid, anchor_row, anchor_col, focusable] ~ Display or reconfigure floating window `win`. The window should be displayed above another grid `anchor_grid` at the specified position `anchor_row` and `anchor_col`. For the meaning of `anchor` and more details of positioning, see |nvim_open_win()|. -["win_external_pos", grid, win] +["win_external_pos", grid, win] ~ Display or reconfigure external window `win`. The window should be displayed as a separate top-level window in the desktop environment, or something similar. -["win_hide", grid] +["win_hide", grid] ~ Stop displaying the window. The window can be shown again later. -["win_close", grid] +["win_close", grid] ~ Close the window. -["msg_set_pos", grid, row, scrolled, sep_char] - Display messages on `grid`. The grid will be displayed at `row` on the - default grid (grid=1), covering the full column width. `scrolled` +["msg_set_pos", grid, row, scrolled, sep_char] ~ + Display messages on `grid`. The grid will be displayed at `row` on + the default grid (grid=1), covering the full column width. `scrolled` indicates whether the message area has been scrolled to cover other - grids. It can be useful to draw a separator then ('display' msgsep - flag). The Builtin TUI draws a full line filled with `sep_char` and - |hl-MsgSeparator| highlight. + grids. It can be useful to draw a separator then |msgsep|. The Builtin + TUI draws a full line filled with `sep_char` ('fillchars' msgsep + field) and |hl-MsgSeparator| highlight. - When |ext_messages| is active, no message grid is used, and this event + When |ui-messages| is active, no message grid is used, and this event will not be sent. -["win_viewport", grid, win, topline, botline, curline, curcol] +["win_viewport", grid, win, topline, botline, curline, curcol] ~ Indicates the range of buffer text displayed in the window, as well as the cursor position in the buffer. All positions are zero-based. `botline` is set to one more than the line count of the buffer, if there are filler lines past the end. -["win_extmark", grid, win, ns_id, mark_id, row, col] +["win_extmark", grid, win, ns_id, mark_id, row, col] ~ Updates the position of an extmark which is currently visible in a window. Only emitted if the mark has the `ui_watched` attribute. @@ -638,7 +645,7 @@ Activated by the `ext_popupmenu` |ui-option|. This UI extension delegates presentation of the |popupmenu-completion| and command-line 'wildmenu'. -["popupmenu_show", items, selected, row, col, grid] +["popupmenu_show", items, selected, row, col, grid] ~ Show |popupmenu-completion|. `items` is an array of completion items to show; each item is an array of the form [word, kind, menu, info] as defined at |complete-items|, except that `word` is replaced by `abbr` @@ -650,12 +657,12 @@ command-line 'wildmenu'. set to -1 to indicate the popupmenu should be anchored to the external cmdline. Then `col` will be a byte position in the cmdline text. -["popupmenu_select", selected] +["popupmenu_select", selected] ~ Select an item in the current popupmenu. `selected` is a zero-based index into the array of items from the last popupmenu_show event, or -1 if no item is selected. -["popupmenu_hide"] +["popupmenu_hide"] ~ Hide the popupmenu. ============================================================================== @@ -663,7 +670,7 @@ Tabline Events *ui-tabline* Activated by the `ext_tabline` |ui-option|. -["tabline_update", curtab, tabs, curbuf, buffers] +["tabline_update", curtab, tabs, curbuf, buffers] ~ Tabline was updated. UIs should present this data in a custom tabline widget. Note: options `curbuf` + `buffers` were added in API7. curtab: Current Tabpage @@ -679,7 +686,7 @@ Activated by the `ext_cmdline` |ui-option|. This UI extension delegates presentation of the |cmdline| (except 'wildmenu'). For command-line 'wildmenu' UI events, activate |ui-popupmenu|. -["cmdline_show", content, pos, firstc, prompt, indent, level] +["cmdline_show", content, pos, firstc, prompt, indent, level] ~ content: List of [attrs, string] [[{}, "t"], [attrs, "est"], ...] @@ -702,10 +709,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. prompt has level 2. A command line invoked from the |cmdline-window| has a higher level than than the edited command line. -["cmdline_pos", pos, level] +["cmdline_pos", pos, level] ~ Change the cursor position in the cmdline. -["cmdline_special_char", c, shift, level] +["cmdline_special_char", c, shift, level] ~ Display a special char in the cmdline at the cursor position. This is typically used to indicate a pending state, e.g. after |c_CTRL-V|. If `shift` is true the text after the cursor should be shifted, otherwise @@ -713,12 +720,12 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. Should be hidden at next cmdline_show. -["cmdline_hide"] +["cmdline_hide"] ~ Hide the cmdline. -["cmdline_block_show", lines] +["cmdline_block_show", lines] ~ Show a block of context to the current command line. For example if - the user defines a |:function| interactively: > + the user defines a |:function| interactively: >vim :function Foo() : echo "foo" : @@ -726,10 +733,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. `lines` is a list of lines of highlighted chunks, in the same form as the "cmdline_show" `contents` parameter. -["cmdline_block_append", line] +["cmdline_block_append", line] ~ Append a line at the end of the currently shown block. -["cmdline_block_hide"] +["cmdline_block_hide"] ~ Hide the block. ============================================================================== @@ -746,7 +753,7 @@ Nvim will not allocate screen space for the cmdline or messages, and 'cmdheight' will be forced zero. Cmdline state is emitted as |ui-cmdline| events, which the UI must handle. -["msg_show", kind, content, replace_last] +["msg_show", kind, content, replace_last] ~ Display a message to the user. kind @@ -780,25 +787,25 @@ events, which the UI must handle. true: Replace the message in the most-recent `msg_show` call, but any other visible message should still remain. -["msg_clear"] +["msg_clear"] ~ Clear all messages currently displayed by "msg_show". (Messages sent by other "msg_" events below will not be affected). -["msg_showmode", content] +["msg_showmode", content] ~ Shows 'showmode' and |recording| messages. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_showcmd", content] +["msg_showcmd", content] ~ Shows 'showcmd' messages. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_ruler", content] +["msg_ruler", content] ~ Used to display 'ruler' when there is no space for the ruler in a statusline. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_history_show", entries] +["msg_history_show", entries] ~ Sent when |:messages| command is invoked. History is sent as a list of entries, where each entry is a `[kind, content]` tuple. diff --git a/runtime/doc/userfunc.txt b/runtime/doc/userfunc.txt new file mode 100644 index 0000000000..9c428175bb --- /dev/null +++ b/runtime/doc/userfunc.txt @@ -0,0 +1,440 @@ +*userfunc.txt* Nvim + + + VIM REFERENCE MANUAL by Bram Moolenaar + + +Defining and using functions. + +This is introduced in section |41.7| of the user manual. + + Type |gO| to see the table of contents. + +============================================================================== + +1. Defining a function ~ + *define-function* +New functions can be defined. These can be called just like builtin +functions. The function executes a sequence of Ex commands. Normal mode +commands can be executed with the |:normal| command. + +The function name must start with an uppercase letter, to avoid confusion with +builtin functions. To prevent from using the same name in different scripts +make them script-local. If you do use a global function then avoid obvious, +short names. A good habit is to start the function name with the name of the +script, e.g., "HTMLcolor()". + +It is also possible to use curly braces, see |curly-braces-names|. + +The |autoload| facility is useful to define a function only when it's called. + + *local-function* +A function local to a script must start with "s:". A local script function +can only be called from within the script and from functions, user commands +and autocommands defined in the script. It is also possible to call the +function from a mapping defined in the script, but then |<SID>| must be used +instead of "s:" when the mapping is expanded outside of the script. +There are only script-local functions, no buffer-local or window-local +functions. + + *:fu* *:function* *E128* *E129* *E123* +:fu[nction] List all functions and their arguments. + +:fu[nction][!] {name} List function {name}, annotated with line numbers + unless "!" is given. + {name} may be a |Dictionary| |Funcref| entry: > + :function dict.init + +:fu[nction] /{pattern} List functions with a name matching {pattern}. + Example that lists all functions ending with "File": > + :function /File$ +< + *:function-verbose* +When 'verbose' is non-zero, listing a function will also display where it was +last defined. Example: > + + :verbose function SetFileTypeSH + function SetFileTypeSH(name) + Last set from /usr/share/vim/vim-7.0/filetype.vim +< +See |:verbose-cmd| for more information. + + *E124* *E125* *E853* *E884* +:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure] + Define a new function by the name {name}. The body of + the function follows in the next lines, until the + matching |:endfunction|. + + The name must be made of alphanumeric characters and + '_', and must start with a capital or "s:" (see + above). Note that using "b:" or "g:" is not allowed. + (since patch 7.4.260 E884 is given if the function + name has a colon in the name, e.g. for "foo:bar()". + Before that patch no error was given). + + {name} can also be a |Dictionary| entry that is a + |Funcref|: > + :function dict.init(arg) +< "dict" must be an existing dictionary. The entry + "init" is added if it didn't exist yet. Otherwise [!] + is required to overwrite an existing function. The + result is a |Funcref| to a numbered function. The + function can only be used with a |Funcref| and will be + deleted if there are no more references to it. + *E127* *E122* + When a function by this name already exists and [!] is + not used an error message is given. There is one + exception: When sourcing a script again, a function + that was previously defined in that script will be + silently replaced. + When [!] is used, an existing function is silently + replaced. Unless it is currently being executed, that + is an error. + NOTE: Use ! wisely. If used without care it can cause + an existing function to be replaced unexpectedly, + which is hard to debug. + + For the {arguments} see |function-argument|. + + *:func-range* *a:firstline* *a:lastline* + When the [range] argument is added, the function is + expected to take care of a range itself. The range is + passed as "a:firstline" and "a:lastline". If [range] + is excluded, ":{range}call" will call the function for + each line in the range, with the cursor on the start + of each line. See |function-range-example|. + The cursor is still moved to the first line of the + range, as is the case with all Ex commands. + *:func-abort* + When the [abort] argument is added, the function will + abort as soon as an error is detected. + *:func-dict* + When the [dict] argument is added, the function must + be invoked through an entry in a |Dictionary|. The + local variable "self" will then be set to the + dictionary. See |Dictionary-function|. + *:func-closure* *E932* + When the [closure] argument is added, the function + can access variables and arguments from the outer + scope. This is usually called a closure. In this + example Bar() uses "x" from the scope of Foo(). It + remains referenced even after Foo() returns: > + :function! Foo() + : let x = 0 + : function! Bar() closure + : let x += 1 + : return x + : endfunction + : return funcref('Bar') + :endfunction + + :let F = Foo() + :echo F() +< 1 > + :echo F() +< 2 > + :echo F() +< 3 + + *function-search-undo* + The last used search pattern and the redo command "." + will not be changed by the function. This also + implies that the effect of |:nohlsearch| is undone + when the function returns. + + *:endf* *:endfunction* *E126* *E193* *W22* +:endf[unction] [argument] + The end of a function definition. Best is to put it + on a line by its own, without [argument]. + + [argument] can be: + | command command to execute next + \n command command to execute next + " comment always ignored + anything else ignored, warning given when + 'verbose' is non-zero + The support for a following command was added in Vim + 8.0.0654, before that any argument was silently + ignored. + + To be able to define a function inside an `:execute` + command, use line breaks instead of |:bar|: > + :exe "func Foo()\necho 'foo'\nendfunc" +< + *:delf* *:delfunction* *E131* *E933* +:delf[unction][!] {name} + Delete function {name}. + {name} can also be a |Dictionary| entry that is a + |Funcref|: > + :delfunc dict.init +< This will remove the "init" entry from "dict". The + function is deleted if there are no more references to + it. + With the ! there is no error if the function does not + exist. + *:retu* *:return* *E133* +:retu[rn] [expr] Return from a function. When "[expr]" is given, it is + evaluated and returned as the result of the function. + If "[expr]" is not given, the number 0 is returned. + When a function ends without an explicit ":return", + the number 0 is returned. + Note that there is no check for unreachable lines, + thus there is no warning if commands follow ":return". + Also, there is no check if the following + line contains a valid command. Forgetting the line + continuation backslash may go unnoticed: > + return 'some text' + .. ' some more text' +< Will happily return "some text" without an error. It + should have been: > + return 'some text' + \ .. ' some more text' +< + If the ":return" is used after a |:try| but before the + matching |:finally| (if present), the commands + following the ":finally" up to the matching |:endtry| + are executed first. This process applies to all + nested ":try"s inside the function. The function + returns at the outermost ":endtry". + + *function-argument* *a:var* +An argument can be defined by giving its name. In the function this can then +be used as "a:name" ("a:" for argument). + *a:0* *a:1* *a:000* *E740* *...* +Up to 20 arguments can be given, separated by commas. After the named +arguments an argument "..." can be specified, which means that more arguments +may optionally be following. In the function the extra arguments can be used +as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which +can be 0). "a:000" is set to a |List| that contains these arguments. Note +that "a:1" is the same as "a:000[0]". + *E742* +The a: scope and the variables in it cannot be changed, they are fixed. +However, if a composite type is used, such as |List| or |Dictionary| , you can +change their contents. Thus you can pass a |List| to a function and have the +function add an item to it. If you want to make sure the function cannot +change a |List| or |Dictionary| use |:lockvar|. + +It is also possible to define a function without any arguments. You must +still supply the () then. + +It is allowed to define another function inside a function body. + + *optional-function-argument* +You can provide default values for positional named arguments. This makes +them optional for function calls. When a positional argument is not +specified at a call, the default expression is used to initialize it. +This only works for functions declared with `:function`, not for +lambda expressions |expr-lambda|. + +Example: > + function Something(key, value = 10) + echo a:key .. ": " .. a:value + endfunction + call Something('empty') "empty: 10" + call Something('key', 20) "key: 20" + +The argument default expressions are evaluated at the time of the function +call, not definition. Thus it is possible to use an expression which is +invalid the moment the function is defined. The expressions are also only +evaluated when arguments are not specified during a call. + + *E989* +Optional arguments with default expressions must occur after any mandatory +arguments. You can use "..." after all optional named arguments. + +It is possible for later argument defaults to refer to prior arguments, +but not the other way around. They must be prefixed with "a:", as with all +arguments. + +Example that works: > + :function Okay(mandatory, optional = a:mandatory) + :endfunction +Example that does NOT work: > + :function NoGood(first = a:second, second = 10) + :endfunction +< +When not using "...", the number of arguments in a function call must be at +least equal to the number of mandatory named arguments. When using "...", the +number of arguments may be larger than the total of mandatory and optional +arguments. + + *local-variables* +Inside a function local variables can be used. These will disappear when the +function returns. Global variables need to be accessed with "g:". Inside +functions local variables are accessed without prepending anything. But you +can also prepend "l:" if you like. This is required for some reserved names, +such as "version". + +Example: > + :function Table(title, ...) + : echohl Title + : echo a:title + : echohl None + : echo a:0 .. " items:" + : for s in a:000 + : echon ' ' .. s + : endfor + :endfunction + +This function can then be called with: > + call Table("Table", "line1", "line2") + call Table("Empty Table") + +To return more than one value, return a |List|: > + :function Compute(n1, n2) + : if a:n2 == 0 + : return ["fail", 0] + : endif + : return ["ok", a:n1 / a:n2] + :endfunction + +This function can then be called with: > + :let [success, div] = Compute(102, 6) + :if success == "ok" + : echo div + :endif +< +============================================================================== + +2. Calling a function ~ + *:cal* *:call* *E107* *E117* +:[range]cal[l] {name}([arguments]) + Call a function. The name of the function and its arguments + are as specified with `:function`. Up to 20 arguments can be + used. The returned value is discarded. + Without a range and for functions that accept a range, the + function is called once. When a range is given the cursor is + positioned at the start of the first line before executing the + function. + When a range is given and the function doesn't handle it + itself, the function is executed for each line in the range, + with the cursor in the first column of that line. The cursor + is left at the last line (possibly moved by the last function + call). The arguments are re-evaluated for each line. Thus + this works: + *function-range-example* > + :function Mynumber(arg) + : echo line(".") .. " " .. a:arg + :endfunction + :1,5call Mynumber(getline(".")) +< + The "a:firstline" and "a:lastline" are defined anyway, they + can be used to do something different at the start or end of + the range. + + Example of a function that handles the range itself: > + + :function Cont() range + : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ ' + :endfunction + :4,8call Cont() +< + This function inserts the continuation character "\" in front + of all the lines in the range, except the first one. + + When the function returns a composite value it can be further + dereferenced, but the range will not be used then. Example: > + :4,8call GetDict().method() +< Here GetDict() gets the range but method() does not. + + *E132* +The recursiveness of user functions is restricted with the |'maxfuncdepth'| +option. + +It is also possible to use `:eval`. It does not support a range, but does +allow for method chaining, e.g.: > + eval GetList()->Filter()->append('$') + +A function can also be called as part of evaluating an expression or when it +is used as a method: > + let x = GetList() + let y = GetList()->Filter() + + +============================================================================== +3. Automatically loading functions ~ + *autoload-functions* +When using many or large functions, it's possible to automatically define them +only when they are used. There are two methods: with an autocommand and with +the "autoload" directory in 'runtimepath'. + + +Using an autocommand ~ + +This is introduced in the user manual, section |41.14|. + +The autocommand is useful if you have a plugin that is a long Vim script file. +You can define the autocommand and quickly quit the script with `:finish`. +That makes Vim startup faster. The autocommand should then load the same file +again, setting a variable to skip the `:finish` command. + +Use the FuncUndefined autocommand event with a pattern that matches the +function(s) to be defined. Example: > + + :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim + +The file "~/vim/bufnetfuncs.vim" should then define functions that start with +"BufNet". Also see |FuncUndefined|. + + +Using an autoload script ~ + *autoload* *E746* +This is introduced in the user manual, section |41.15|. + +Using a script in the "autoload" directory is simpler, but requires using +exactly the right file name. A function that can be autoloaded has a name +like this: > + + :call filename#funcname() + +When such a function is called, and it is not defined yet, Vim will search the +"autoload" directories in 'runtimepath' for a script file called +"filename.vim". For example "~/.config/nvim/autoload/filename.vim". That +file should then define the function like this: > + + function filename#funcname() + echo "Done!" + endfunction + +If the file doesn't exist, Vim will also search in 'packpath' (under "start") +to allow calling packages' functions from your |vimrc| when the packages have +not been added to 'runtimepath' yet (see |packages|). + +The file name and the name used before the # in the function must match +exactly, and the defined function must have the name exactly as it will be +called. + +It is possible to use subdirectories. Every # in the function name works like +a path separator. Thus when calling a function: > + + :call foo#bar#func() + +Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'. + +This also works when reading a variable that has not been set yet: > + + :let l = foo#bar#lvar + +However, when the autoload script was already loaded it won't be loaded again +for an unknown variable. + +When assigning a value to such a variable nothing special happens. This can +be used to pass settings to the autoload script before it's loaded: > + + :let foo#bar#toggle = 1 + :call foo#bar#func() + +Note that when you make a mistake and call a function that is supposed to be +defined in an autoload script, but the script doesn't actually define the +function, you will get an error message for the missing function. If you fix +the autoload script it won't be automatically loaded again. Either restart +Vim or manually source the script. + +Also note that if you have two script files, and one calls a function in the +other and vice versa, before the used function is defined, it won't work. +Avoid using the autoload functionality at the toplevel. + +Hint: If you distribute a bunch of scripts read |distribute-script|. + + + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/usr_01.txt b/runtime/doc/usr_01.txt index 52fbf06ec4..f0e2462fae 100644 --- a/runtime/doc/usr_01.txt +++ b/runtime/doc/usr_01.txt @@ -85,7 +85,7 @@ The Vim user manual and reference manual are Copyright (c) 1988-2003 by Bram Moolenaar. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later. The latest version is presently available at: - http://www.opencontent.org/openpub/ + https://www.opencontent.org/openpub/ People who contribute to the manuals must agree with the above copyright notice. diff --git a/runtime/doc/usr_02.txt b/runtime/doc/usr_02.txt index f822e7d4b8..11afe39742 100644 --- a/runtime/doc/usr_02.txt +++ b/runtime/doc/usr_02.txt @@ -33,7 +33,7 @@ On Unix you can type this at any command prompt. If you are running Microsoft Windows, open a Command Prompt and enter the command. In either case, Vim starts editing a file called file.txt. Because this is a new file, you get a blank window. This is what your screen will look like: - +> +---------------------------------------+ |# | |~ | @@ -43,7 +43,7 @@ blank window. This is what your screen will look like: |"file.txt" [New file] | +---------------------------------------+ ('#' is the cursor position.) - +< The tilde (~) lines indicate lines not in the file. In other words, when Vim runs out of file to display, it displays tilde lines. At the bottom of the screen, a message line indicates the file is named file.txt and shows that you @@ -83,7 +83,7 @@ limerick, this is what you type: > After typing "turtle" you press the <Enter> key to start a new line. Finally you press the <Esc> key to stop Insert mode and go back to Normal mode. You now have two lines of text in your Vim window: - +> +---------------------------------------+ |A very intelligent turtle | |Found programming Unix a hurdle | @@ -91,7 +91,7 @@ now have two lines of text in your Vim window: |~ | | | +---------------------------------------+ - +< WHAT IS THE MODE? @@ -105,7 +105,7 @@ with a colon). Finish this command by pressing the <Enter> key (all commands that start with a colon are finished this way). Now, if you type the "i" command Vim will display --INSERT-- at the bottom of the window. This indicates you are in Insert mode. - +> +---------------------------------------+ |A very intelligent turtle | |Found programming Unix a hurdle | @@ -113,7 +113,7 @@ of the window. This indicates you are in Insert mode. |~ | |-- INSERT -- | +---------------------------------------+ - +< If you press <Esc> to go back to Normal mode the last line will be made blank. @@ -182,7 +182,7 @@ throwback to the old days of the typewriter, when you deleted things by typing xxxx over them.) Move the cursor to the beginning of the first line, for example, and type xxxxxxx (seven x's) to delete "A very ". The result should look like this: - +> +---------------------------------------+ |intelligent turtle | |Found programming Unix a hurdle | @@ -190,14 +190,14 @@ look like this: |~ | | | +---------------------------------------+ - +< Now you can insert new text, for example by typing: > iA young <Esc> This begins an insert (the i), inserts the words "A young", and then exits insert mode (the final <Esc>). The result: - +> +---------------------------------------+ |A young intelligent turtle | |Found programming Unix a hurdle | @@ -205,13 +205,13 @@ insert mode (the final <Esc>). The result: |~ | | | +---------------------------------------+ - +< DELETING A LINE To delete a whole line use the "dd" command. The following line will then move up to fill the gap: - +> +---------------------------------------+ |Found programming Unix a hurdle | |~ | @@ -219,7 +219,7 @@ then move up to fill the gap: |~ | | | +---------------------------------------+ - +< DELETING A LINE BREAK diff --git a/runtime/doc/usr_03.txt b/runtime/doc/usr_03.txt index 74674fdb42..2b0d40ba32 100644 --- a/runtime/doc/usr_03.txt +++ b/runtime/doc/usr_03.txt @@ -224,7 +224,7 @@ you can see? This figure shows the three commands you can use: +---------------------------+ Hints: "H" stands for Home, "M" for Middle and "L" for Last. Alternatively, -"H" for high, "M" for Middle and "L" for low. +"H" for High, "M" for Middle and "L" for Low. ============================================================================== *03.6* Telling where you are diff --git a/runtime/doc/usr_05.txt b/runtime/doc/usr_05.txt index 0e94d9a1b1..24d6185eae 100644 --- a/runtime/doc/usr_05.txt +++ b/runtime/doc/usr_05.txt @@ -107,7 +107,7 @@ Display an incomplete command in the lower right corner of the Vim window, left of the ruler. For example, when you type "2f", Vim is waiting for you to type the character to find and "2f" is displayed. When you press "w" next, the "2fw" command is executed and the displayed "2f" is removed. - +> +-------------------------------------------------+ |text in the Vim window | |~ | @@ -119,7 +119,7 @@ the "2fw" command is executed and the displayed "2f" is removed. > set incsearch - +< Display matches for a search pattern while you type. > @@ -127,8 +127,8 @@ Display matches for a search pattern while you type. This defines a key mapping. More about that in the next section. This defines the "Q" command to do formatting with the "gq" operator. This is how -it worked before Vim 5.0. Otherwise the "Q" command starts Ex mode, but you -will not need it. +it worked before Vim 5.0. Otherwise the "Q" command repeats the last recorded +register. > vnoremap _g y:exe "grep /" .. escape(@", '\\/') .. "/ *.c *.h"<CR> @@ -320,7 +320,7 @@ Where can you find plugins? - Some are always loaded, you can see them in the directory $VIMRUNTIME/plugin. - Some come with Vim. You can find them in the directory $VIMRUNTIME/macros and its sub-directories and under $VIM/vimfiles/pack/dist/opt/. -- Download from the net. There is a large collection on http://www.vim.org. +- Download from the net. There is a large collection on https://www.vim.org. - They are sometimes posted in a Vim maillist. - You could write one yourself, see |write-plugin|. diff --git a/runtime/doc/usr_06.txt b/runtime/doc/usr_06.txt index 8eda33b4f0..755e6e816a 100644 --- a/runtime/doc/usr_06.txt +++ b/runtime/doc/usr_06.txt @@ -14,8 +14,7 @@ screen. |06.2| No or wrong colors? |06.3| Different colors |06.4| With colors or without colors -|06.5| Printing with colors -|06.6| Further reading +|06.5| Further reading Next chapter: |usr_07.txt| Editing more than one file Previous chapter: |usr_05.txt| Set your settings @@ -191,59 +190,7 @@ buffer, set the 'syntax' option: > :set syntax=ON < ============================================================================== -*06.5* Printing with colors *syntax-printing* - -In the MS-Windows version you can print the current file with this command: > - - :hardcopy - -You will get the usual printer dialog, where you can select the printer and a -few settings. If you have a color printer, the paper output should look the -same as what you see inside Vim. But when you use a dark background the -colors will be adjusted to look good on white paper. - -There are several options that change the way Vim prints: - 'printdevice' - 'printheader' - 'printfont' - 'printoptions' - -To print only a range of lines, use Visual mode to select the lines and then -type the command: > - - v100j:hardcopy - -"v" starts Visual mode. "100j" moves a hundred lines down, they will be -highlighted. Then ":hardcopy" will print those lines. You can use other -commands to move in Visual mode, of course. - -This also works on Unix, if you have a PostScript printer. Otherwise, you -will have to do a bit more work. You need to convert the text to HTML first, -and then print it from a web browser. - -Convert the current file to HTML with this command: > - - :TOhtml - -In case that doesn't work: > - - :source $VIMRUNTIME/syntax/2html.vim - -You will see it crunching away, this can take quite a while for a large file. -Some time later another window shows the HTML code. Now write this somewhere -(doesn't matter where, you throw it away later): -> - :write main.c.html - -Open this file in your favorite browser and print it from there. If all goes -well, the output should look exactly as it does in Vim. See |2html.vim| for -details. Don't forget to delete the HTML file when you are done with it. - -Instead of printing, you could also put the HTML file on a web server, and let -others look at the colored text. - -============================================================================== -*06.6* Further reading +*06.5* Further reading |usr_44.txt| Your own syntax highlighted. |syntax| All the details. diff --git a/runtime/doc/usr_08.txt b/runtime/doc/usr_08.txt index 1d20913a14..0ba03a4861 100644 --- a/runtime/doc/usr_08.txt +++ b/runtime/doc/usr_08.txt @@ -32,7 +32,7 @@ The easiest way to open a new window is to use the following command: > This command splits the screen into two windows and leaves the cursor in the top one: - +> +----------------------------------+ |/* file one.c */ | |~ | @@ -43,7 +43,7 @@ top one: |one.c=============================| | | +----------------------------------+ - +< What you see here is two windows on the same file. The line with "====" is the status line. It displays information about the window above it. (In practice the status line will be in reverse video.) @@ -87,7 +87,7 @@ The following command opens a second window and starts editing the given file: :split two.c If you were editing one.c, then the result looks like this: - +> +----------------------------------+ |/* file two.c */ | |~ | @@ -98,7 +98,7 @@ If you were editing one.c, then the result looks like this: |one.c=============================| | | +----------------------------------+ - +< To open a window on a new, empty file, use this: > :new @@ -170,7 +170,7 @@ or: > :vsplit two.c The result looks something like this: - +> +--------------------------------------+ |/* file two.c */ |/* file one.c */ | |~ |~ | @@ -179,7 +179,7 @@ The result looks something like this: |two.c===============one.c=============| | | +--------------------------------------+ - +< Actually, the | lines in the middle will be in reverse video. This is called the vertical separator. It separates the two windows left and right of it. @@ -218,7 +218,7 @@ cursor keys can also be used, if you like. You have split a few windows, but now they are in the wrong place. Then you need a command to move the window somewhere else. For example, you have three windows like this: - +> +----------------------------------+ |/* file two.c */ | |~ | @@ -233,7 +233,7 @@ windows like this: |one.c=============================| | | +----------------------------------+ - +< Clearly the last one should be at the top. Go to that window (using CTRL-W w) and then type this command: > @@ -244,7 +244,7 @@ the very top. You will notice that K is again used for moving upwards. When you have vertical splits, CTRL-W K will move the current window to the top and make it occupy the full width of the Vim window. If this is your layout: - +> +-------------------------------------------+ |/* two.c */ |/* three.c */ |/* one.c */ | |~ |~ |~ | @@ -255,9 +255,9 @@ layout: |two.c=========three.c=========one.c========| | | +-------------------------------------------+ - +< Then using CTRL-W K in the middle window (three.c) will result in: - +> +-------------------------------------------+ |/* three.c */ | |~ | @@ -268,7 +268,7 @@ Then using CTRL-W K in the middle window (three.c) will result in: |two.c==================one.c===============| | | +-------------------------------------------+ - +< The other three similar commands (you can probably guess these now): CTRL-W H move window to the far left @@ -316,7 +316,7 @@ To make Vim open a window for each file, start it with the "-o" argument: > vim -o one.txt two.txt three.txt This results in: - +> +-------------------------------+ |file one.txt | |~ | @@ -329,7 +329,7 @@ This results in: |three.txt======================| | | +-------------------------------+ - +< The "-O" argument is used to get vertically split windows. When Vim is already running, the ":all" command opens a window for each file in the argument list. ":vertical all" does it with vertical splits. @@ -347,7 +347,7 @@ Type this command in a shell to start Nvim in diff mode: > Vim will start, with two windows side by side. You will only see the line in which you added characters, and a few lines above and below it. - +> VV VV +-----------------------------------------+ |+ +--123 lines: /* a|+ +--123 lines: /* a| <- fold @@ -366,7 +366,7 @@ in which you added characters, and a few lines above and below it. |main.c~==============main.c==============| | | +-----------------------------------------+ - +< (This picture doesn't show the highlighting, use "nvim -d" for that.) The lines that were not modified have been collapsed into one line. This is @@ -519,7 +519,7 @@ Assume you are editing "thisfile". To create a new tab page use this command: > This will edit the file "thatfile" in a window that occupies the whole Vim window. And you will notice a bar at the top with the two file names: - +> +----------------------------------+ | thisfile | /thatfile/ __________X| (thatfile is bold) |/* thatfile */ | @@ -530,13 +530,13 @@ window. And you will notice a bar at the top with the two file names: |~ | | | +----------------------------------+ - +< You now have two tab pages. The first one has a window for "thisfile" and the second one a window for "thatfile". It's like two pages that are on top of each other, with a tab sticking out of each page showing the file name. Now use the mouse to click on "thisfile" in the top line. The result is - +> +----------------------------------+ | /thisfile/ | thatfile __________X| (thisfile is bold) |/* thisfile */ | @@ -547,7 +547,7 @@ Now use the mouse to click on "thisfile" in the top line. The result is |~ | | | +----------------------------------+ - +< Thus you can switch between tab pages by clicking on the label in the top line. If you don't have a mouse or don't want to use it, you can use the "gt" command. Mnemonic: Goto Tab. @@ -558,7 +558,7 @@ Now let's create another tab page with the command: > This makes a new tab page with one window that is editing the same buffer as the window we were in: - +> +-------------------------------------+ | thisfile | /thisfile/ | thatfile __X| (thisfile is bold) |/* thisfile */ | @@ -569,7 +569,7 @@ the window we were in: |~ | | | +-------------------------------------+ - +< You can put ":tab" before any Ex command that opens a window. The window will be opened in a new tab page. Another example: > diff --git a/runtime/doc/usr_10.txt b/runtime/doc/usr_10.txt index 8844671e01..3e45fda882 100644 --- a/runtime/doc/usr_10.txt +++ b/runtime/doc/usr_10.txt @@ -813,10 +813,10 @@ REDRAWING THE SCREEN If the external command produced an error message, the display may have been messed up. Vim is very efficient and only redraws those parts of the screen that it knows need redrawing. But it can't know about what another program -has written. To tell Vim to redraw the screen: > - +has written. To tell Vim to redraw the screen: +> CTRL-L - +< ============================================================================== Next chapter: |usr_11.txt| Recovering from a crash diff --git a/runtime/doc/usr_20.txt b/runtime/doc/usr_20.txt index 6a8836c8e8..2b69862fe1 100644 --- a/runtime/doc/usr_20.txt +++ b/runtime/doc/usr_20.txt @@ -338,7 +338,7 @@ Open the command line window with this command: > Vim now opens a (small) window at the bottom. It contains the command line history, and an empty line at the end: - +> +-------------------------------------+ |other window | |~ | @@ -353,7 +353,7 @@ history, and an empty line at the end: |command-line=========================| | | +-------------------------------------+ - +< You are now in Normal mode. You can use the "hjkl" keys to move around. For example, move up with "5k" to the ":e config.h.in" line. Type "$h" to go to the "i" of "in" and type "cwout". Now you have changed the line to: diff --git a/runtime/doc/usr_21.txt b/runtime/doc/usr_21.txt index add5d48073..191d333f3d 100644 --- a/runtime/doc/usr_21.txt +++ b/runtime/doc/usr_21.txt @@ -255,7 +255,8 @@ well stand for "source"). The windows that were open are restored, with the same position and size as before. Mappings and option values are like before. What exactly is restored depends on the 'sessionoptions' option. The -default value is "blank,buffers,curdir,folds,help,options,winsize". +default value is: +"blank,buffers,curdir,folds,help,options,tabpages,winsize,terminal". blank keep empty windows buffers all buffers, not only the ones in a window @@ -263,7 +264,9 @@ default value is "blank,buffers,curdir,folds,help,options,winsize". folds folds, also manually created ones help the help window options all options and mappings + tabpages all tab pages winsize window sizes + terminal include terminal windows Change this to your liking. To also restore the size of the Vim window, for example, use: > @@ -299,7 +302,7 @@ session file as a starting point. use, and save this in a session. Then you can go back to this layout whenever you want. For example, this is a nice layout to use: - +> +----------------------------------------+ | VIM - main help file | | | @@ -315,7 +318,7 @@ you want. |~/=========|[No File]===================| | | +----------------------------------------+ - +< This has a help window at the top, so that you can read this text. The narrow vertical window on the left contains a file explorer. This is a Vim plugin that lists the contents of a directory. You can select files to edit there. @@ -451,7 +454,7 @@ Use this format for the modeline: The "any-text" indicates that you can put any text before and after the part that Vim will use. This allows making it look like a comment, like what was -done above with /* and */. +done above with "/*" and "*/". The " vim:" part is what makes Vim recognize this line. There must be white space before "vim", or "vim" must be at the start of the line. Thus using something like "gvim:" will not work. diff --git a/runtime/doc/usr_22.txt b/runtime/doc/usr_22.txt index f53d578456..539bda3980 100644 --- a/runtime/doc/usr_22.txt +++ b/runtime/doc/usr_22.txt @@ -220,7 +220,7 @@ a tab page share this directory except for windows with a window-local directory. Any new windows opened in this tab page will use this directory as the current working directory. Using a `:cd` command in a tab page will not change the working directory of tab pages which have a tab local directory. -When the global working directory is changed using the ":cd" command in a tab +When the global working directory is changed using the `:cd` command in a tab page, it will also change the current tab page working directory. diff --git a/runtime/doc/usr_25.txt b/runtime/doc/usr_25.txt index 2efb67e55f..955d2ae5f0 100644 --- a/runtime/doc/usr_25.txt +++ b/runtime/doc/usr_25.txt @@ -325,16 +325,16 @@ Let's attempt to show this with one line of text. The cursor is on the "w" of currently visible. The "window"s below the text indicate the text that is visible after the command left of it. - |<-- current window -->| + `|<-- current window -->|` some long text, part of which is visible in the window ~ - ze |<-- window -->| - zH |<-- window -->| - 4zh |<-- window -->| - zh |<-- window -->| - zl |<-- window -->| - 4zl |<-- window -->| - zL |<-- window -->| - zs |<-- window -->| + ze `|<-- window -->|` + zH `|<-- window -->|` + 4zh `|<-- window -->|` + zh `|<-- window -->|` + zl `|<-- window -->|` + 4zl `|<-- window -->|` + zL `|<-- window -->|` + zs `|<-- window -->|` MOVING WITH WRAP OFF @@ -350,7 +350,7 @@ scroll: gM to middle of the text in this line g$ to last visible character in this line - |<-- window -->| + `|<-- window -->|` some long text, part of which is visible in one line ~ g0 g^ gm gM g$ @@ -365,7 +365,7 @@ broken halfway, which makes them hard to read. 'linebreak' option. Vim then breaks lines at an appropriate place when displaying the line. The text in the file remains unchanged. Without 'linebreak' text might look like this: - +> +---------------------------------+ |letter generation program for a b| |ank. They wanted to send out a s| @@ -373,12 +373,13 @@ displaying the line. The text in the file remains unchanged. |eir richest 1000 customers. Unfo| |rtunately for the programmer, he | +---------------------------------+ +< After: > :set linebreak it looks like this: - +> +---------------------------------+ |letter generation program for a | |bank. They wanted to send out a | @@ -386,7 +387,7 @@ it looks like this: |their richest 1000 customers. | |Unfortunately for the programmer,| +---------------------------------+ - +< Related options: 'breakat' specifies the characters where a break can be inserted. 'showbreak' specifies a string to show at the start of broken line. @@ -425,7 +426,7 @@ That looks complicated. Let's break it up in pieces: into one line. Starting with this text, containing eight lines broken at column 30: - +> +----------------------------------+ |A letter generation program | |for a bank. They wanted to | @@ -436,9 +437,9 @@ Starting with this text, containing eight lines broken at column 30: |customers. Unfortunately for | |the programmer, | +----------------------------------+ - +< You end up with two lines: - +> +----------------------------------+ |A letter generation program for a | |bank. They wanted to send out a s| @@ -446,7 +447,7 @@ You end up with two lines: |To their richest 1000 customers. | |Unfortunately for the programmer, | +----------------------------------+ - +< Note that this doesn't work when the separating line is blank but not empty; when it contains spaces and/or tabs. This command does work with blank lines: > diff --git a/runtime/doc/usr_29.txt b/runtime/doc/usr_29.txt index d8c556c281..751cb9a902 100644 --- a/runtime/doc/usr_29.txt +++ b/runtime/doc/usr_29.txt @@ -33,9 +33,8 @@ following command: > ctags *.c "ctags" is a separate program. Most Unix systems already have it installed. -If you do not have it yet, you can find Universal/Exuberant ctags at: - http://ctags.io ~ - http://ctags.sf.net ~ +If you do not have it yet, you can find Universal ctags at: + https://ctags.io ~ Universal ctags is preferred, Exuberant ctags is no longer being developed. @@ -54,7 +53,7 @@ function. The "write_line" function calls "write_char". You need to figure out what it does. So you position the cursor over the call to "write_char" and press CTRL-]. Now you are at the definition of "write_char". - +> +-------------------------------------+ |void write_block(char **s; int cnt) | |{ | @@ -80,7 +79,7 @@ CTRL-]. Now you are at the definition of "write_char". | putchar((int)(unsigned char)c); | |} | +------------------------------------+ - +< The ":tags" command shows the list of tags that you traversed through: :tags @@ -268,9 +267,6 @@ doesn't work if the tags file isn't sorted. The 'taglength' option can be used to tell Vim the number of significant characters in a tag. -Cscope is a free program. It does not only find places where an identifier is -declared, but also where it is used. See |cscope|. - ============================================================================== *29.2* The preview window @@ -429,7 +425,7 @@ MOVING IN COMMENTS To move back to the start of a comment use "[/". Move forward to the end of a comment with "]/". This only works for /* - */ comments. - +> +-> +-> /* | [/ | * A comment about --+ [/ | +-- * wonderful life. | ]/ @@ -438,7 +434,7 @@ comment with "]/". This only works for /* - */ comments. +-- foo = bar * 3; --+ | ]/ /* a short comment */ <-+ - +< ============================================================================== *29.4* Finding global identifiers @@ -579,7 +575,7 @@ and jump to the first place where the word under the cursor is used: > Hint: Goto Definition. This command is very useful to find a variable or function that was declared locally ("static", in C terms). Example (cursor on "counter"): - +> +-> static int counter = 0; | | int get_counter(void) @@ -587,7 +583,7 @@ function that was declared locally ("static", in C terms). Example (cursor on | ++counter; +-- return counter; } - +< To restrict the search even further, and look only in the current function, use this command: > @@ -597,7 +593,7 @@ This will go back to the start of the current function and find the first occurrence of the word under the cursor. Actually, it searches backwards to an empty line above a "{" in the first column. From there it searches forward for the identifier. Example (cursor on "idx"): - +> int find_entry(char *name) { +-> int idx; @@ -606,7 +602,7 @@ for the identifier. Example (cursor on "idx"): | if (strcmp(table[idx].name, name) == 0) +-- return idx; } - +< ============================================================================== Next chapter: |usr_30.txt| Editing programs diff --git a/runtime/doc/usr_30.txt b/runtime/doc/usr_30.txt index 98d1780cc4..7e7b3b21f4 100644 --- a/runtime/doc/usr_30.txt +++ b/runtime/doc/usr_30.txt @@ -56,7 +56,7 @@ From this you can see that you have errors in the file "main.c". When you press <Enter>, Vim displays the file "main.c", with the cursor positioned on line 6, the first line with an error. You did not need to specify the file or the line number, Vim knew where to go by looking in the error messages. - +> +---------------------------------------------------+ |int main() | |{ | @@ -69,7 +69,7 @@ the line number, Vim knew where to go by looking in the error messages. | ~ | |(3 of 12): too many arguments to function 'do_sub' | +---------------------------------------------------+ - +< The following command goes to where the next error occurs: > :cnext diff --git a/runtime/doc/usr_32.txt b/runtime/doc/usr_32.txt index 8b489ea1e0..324efccf25 100644 --- a/runtime/doc/usr_32.txt +++ b/runtime/doc/usr_32.txt @@ -169,10 +169,10 @@ To travel forward in time again use the |:later| command: > The arguments are "s", "m" and "h", just like with |:earlier|. If you want even more details, or want to manipulate the information, you can -use the |undotree()| function. To see what it returns: > - +use the |undotree()| function. To see what it returns: +> :echo undotree() - +< ============================================================================== Next chapter: |usr_40.txt| Make new commands diff --git a/runtime/doc/usr_40.txt b/runtime/doc/usr_40.txt index f47c933124..8befb15528 100644 --- a/runtime/doc/usr_40.txt +++ b/runtime/doc/usr_40.txt @@ -226,7 +226,7 @@ When using a space inside a mapping, use <Space> (seven characters): > This makes the spacebar move a blank-separated word forward. It is not possible to put a comment directly after a mapping, because the " -character is considered to be part of the mapping. You can use |", this +character is considered to be part of the mapping. You can use `|"`, this starts a new, empty command with a comment. Example: > :map <Space> W| " Use spacebar to move forward a word @@ -657,10 +657,10 @@ To ignore all events, use the following command: > :set eventignore=all -To set it back to the normal behavior, make 'eventignore' empty: > - +To set it back to the normal behavior, make 'eventignore' empty: +> :set eventignore= - +< ============================================================================== Next chapter: |usr_41.txt| Write a Vim script diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 0c907bfb68..910aebae70 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -604,6 +604,8 @@ String manipulation: *string-functions* fnameescape() escape a file name for use with a Vim command tr() translate characters from one set to another strtrans() translate a string to make it printable + keytrans() translate internal keycodes to a form that + can be used by |:map| tolower() turn a string to lowercase toupper() turn a string to uppercase charclass() class of a character @@ -617,10 +619,12 @@ String manipulation: *string-functions* stridx() first index of a short string in a long string strridx() last index of a short string in a long string strlen() length of a string in bytes - strchars() length of a string in characters + strcharlen() length of a string in characters + strchars() number of characters in a string strwidth() size of string when displayed strdisplaywidth() size of string when displayed, deals with tabs setcellwidths() set character cell width overrides + getcellwidths() get character cell width overrides substitute() substitute a pattern match with a string submatch() get a specific match in ":s" and substitute() strpart() get part of a string using byte index @@ -637,6 +641,7 @@ String manipulation: *string-functions* execute() execute an Ex command and get the output win_execute() like execute() but in a specified window trim() trim characters from a string + gettext() lookup message translation List manipulation: *list-functions* get() get an item without error for wrong index @@ -745,6 +750,7 @@ Cursor and mark position: *cursor-functions* *mark-functions* screencol() get screen column of the cursor screenrow() get screen row of the cursor screenpos() screen row and col of a text character + virtcol2col() byte index of a text character on screen getcurpos() get position of the cursor getpos() get position of cursor, mark, etc. setpos() set position of cursor, mark, etc. @@ -780,6 +786,13 @@ Working with text in the current buffer: *text-functions* getcharsearch() return character search information setcharsearch() set character search information +Working with text in another buffer: + getbufline() get a list of lines from the specified buffer + getbufoneline() get a one line from the specified buffer + setbufline() replace a line in the specified buffer + appendbufline() append a list of lines in the specified buffer + deletebufline() delete lines from a specified buffer + *system-functions* *file-functions* System functions and manipulation of files: glob() expand wildcards @@ -814,6 +827,7 @@ System functions and manipulation of files: setenv() set an environment variable hostname() name of the system readfile() read a file into a List of lines + readblob() read a file into a Blob readdir() get a List of file names in a directory writefile() write a List of lines or Blob into a file @@ -832,8 +846,10 @@ Buffers, windows and the argument list: argidx() current position in the argument list arglistid() get id of the argument list argv() get one entry from the argument list + bufadd() add a file to the list of buffers bufexists() check if a buffer exists buflisted() check if a buffer exists and is listed + bufload() ensure a buffer is loaded bufloaded() check if a buffer exists and is loaded bufname() get the name of a specific buffer bufnr() get the buffer number of a specific buffer @@ -844,10 +860,6 @@ Buffers, windows and the argument list: bufwinid() get the window ID of a specific buffer bufwinnr() get the window number of a specific buffer winbufnr() get the buffer number of a specific window - getbufline() get a list of lines from the specified buffer - setbufline() replace a line in the specified buffer - appendbufline() append a list of lines in the specified buffer - deletebufline() delete lines from a specified buffer win_findbuf() find windows containing a buffer win_getid() get window ID of a window win_gettype() get type of window @@ -872,6 +884,7 @@ Command line: *command-line-functions* getcmdpos() get position of the cursor in the command line getcmdscreenpos() get screen position of the cursor in the command line + setcmdline() set the current command line setcmdpos() set position of the cursor in the command line getcmdtype() return the current command-line type getcmdwintype() return the current command-line window type @@ -1012,6 +1025,7 @@ Testing: *test-functions* assert_beeps() assert that a command beeps assert_nobeep() assert that a command does not cause a beep assert_fails() assert that a command fails + assert_report() report a test failure Timers: *timer-functions* timer_start() create a timer @@ -1046,7 +1060,6 @@ Various: *various-functions* exists() check if a variable, function, etc. exists has() check if a feature is supported in Vim changenr() return number of most recent change - cscope_connection() check if a cscope connection exists did_filetype() check if a FileType autocommand was used eventhandler() check if invoked by an event handler getpid() get process ID of Vim @@ -1069,8 +1082,8 @@ Various: *various-functions* wordcount() get byte/word/char count of buffer luaeval() evaluate |Lua| expression - py3eval() evaluate Python expression (|+python3|) - pyeval() evaluate Python expression (|+python|) + py3eval() evaluate |Python| expression + pyeval() evaluate |Python| expression pyxeval() evaluate |python_x| expression rubyeval() evaluate |Ruby| expression @@ -1706,7 +1719,7 @@ There is a little "catch" with comments for some commands. Examples: > :execute cmd " do it :!ls *.c " list C files -The abbreviation 'dev' will be expanded to 'development " shorthand'. The +The abbreviation "dev" will be expanded to 'development " shorthand'. The mapping of <F3> will actually be the whole line after the 'o# ....' including the '" insert include'. The "execute" command will give an error. The "!" command will send everything after it to the shell, causing an error for an @@ -1757,7 +1770,7 @@ does not exist as a mapped sequence. An error will be issued, which is very hard to identify, because the ending whitespace character in ":unmap ,ab " is not visible. -And this is the same as what happens when one uses a comment after an 'unmap' +And this is the same as what happens when one uses a comment after an "unmap" command: > :unmap ,ab " comment @@ -2619,7 +2632,7 @@ Further reading: |autoload|. ============================================================================== *41.16* Distributing Vim scripts *distribute-script* -Vim users will look for scripts on the Vim website: http://www.vim.org. +Vim users will look for scripts on the Vim website: https://www.vim.org. If you made something that is useful for others, share it! Vim scripts can be used on any system. There might not be a tar or gzip diff --git a/runtime/doc/usr_42.txt b/runtime/doc/usr_42.txt index 470f4e0fe5..9c5e3db72c 100644 --- a/runtime/doc/usr_42.txt +++ b/runtime/doc/usr_42.txt @@ -81,7 +81,7 @@ the far right. The second number (340) determines the location of the item within the pull-down menu. Lower numbers go on top, higher number on the bottom. These are the priorities in the File menu: - +> +-----------------+ 10.310 |Open... | 10.320 |Split-Open... | @@ -99,7 +99,7 @@ are the priorities in the File menu: 10.610 |Save-Exit | 10.620 |Exit | +-----------------+ - +< Notice that there is room in between the numbers. This is where you can insert your own items, if you really want to (it's often better to leave the standard menus alone and add a new menu for your own items). @@ -168,11 +168,11 @@ inserts a CTRL-C or CTRL-O for you. For example, if you use this command: Then the resulting menu commands will be: - Normal mode: * - Visual mode: CTRL-C * - Operator-pending mode: CTRL-C * - Insert mode: CTRL-O * - Command-line mode: CTRL-C * + Normal mode: `*` + Visual mode: CTRL-C `*` + Operator-pending mode: CTRL-C `*` + Insert mode: CTRL-O `*` + Command-line mode: CTRL-C `*` When in Command-line mode the CTRL-C will abandon the command typed so far. In Visual and Operator-pending mode CTRL-C will stop the mode. The CTRL-O in diff --git a/runtime/doc/usr_45.txt b/runtime/doc/usr_45.txt index 3199c4d8ea..95a2bc8f79 100644 --- a/runtime/doc/usr_45.txt +++ b/runtime/doc/usr_45.txt @@ -71,8 +71,8 @@ directory src/po/README.txt. programmer. You must know both English and the language you are translating to, of course. When you are satisfied with the translation, consider making it available -to others. Upload it at vim-online (http://vim.sf.net) or e-mail it to -the Vim maintainer <maintainer@vim.org>. Or both. +to others. Upload it to https://github.com/vim/vim or e-mail it to the Vim +maintainer <maintainer@vim.org>. Or both. ============================================================================== *45.2* Language for Menus @@ -166,10 +166,7 @@ script files, etc. You can regard 'encoding' as the setting for the internals of Vim. This example assumes you have this font on your system. The name in the example is for the X Window System. This font is in a package that is used to -enhance xterm with Unicode support. If you don't have this font, you might -find it here: - - http://www.cl.cam.ac.uk/~mgk25/download/ucs-fonts.tar.gz ~ +enhance xterm with Unicode support. For MS-Windows, some fonts have a limited number of Unicode characters. Try using the "Courier New" font. You can use the Edit/Select Font... menu to @@ -178,10 +175,7 @@ though. Example: > :set guifont=courier_new:h12 -If it doesn't work well, try getting a fontpack. If Microsoft didn't move it, -you can find it here: - - http://www.microsoft.com/typography/fonts/default.aspx ~ +If it doesn't work well, try getting a fontpack. Now you have told Vim to use Unicode internally and display text with a Unicode font. @@ -300,8 +294,7 @@ can use digraphs. This was already explained in |24.9|. keyboard, you will want to use an Input Method (IM). This requires learning the translation from typed keys to resulting character. When you need an IM you probably already have one on your system. It should work with Vim like -with other programs. For details see |mbyte-XIM| for the X Window system and -|mbyte-IME| for MS-Windows. +with other programs. KEYMAPS diff --git a/runtime/doc/usr_toc.txt b/runtime/doc/usr_toc.txt index bf9c02882c..dd0d5784f5 100644 --- a/runtime/doc/usr_toc.txt +++ b/runtime/doc/usr_toc.txt @@ -5,7 +5,7 @@ Table Of Contents *user-manual* ============================================================================== -Overview ~ +Overview Getting Started |usr_01.txt| About the manuals @@ -52,7 +52,7 @@ The user manual is online: https://neovim.io/doc/user ============================================================================== -Getting Started ~ +Getting Started Read this from start to end to learn the essential commands. @@ -111,8 +111,7 @@ Read this from start to end to learn the essential commands. |06.2| No or wrong colors? |06.3| Different colors |06.4| With colors or without colors - |06.5| Printing with colors - |06.6| Further reading + |06.5| Further reading |usr_07.txt| Editing more than one file |07.1| Edit another file @@ -167,7 +166,7 @@ Read this from start to end to learn the essential commands. |12.8| Find where a word is used ============================================================================== -Editing Effectively ~ +Editing Effectively Subjects that can be read independently. @@ -275,7 +274,7 @@ Subjects that can be read independently. |32.4| Time travelling ============================================================================== -Tuning Vim ~ +Tuning Vim Make Vim work as you like it. diff --git a/runtime/doc/various.txt b/runtime/doc/various.txt index cae9c76030..e13d892fd6 100644 --- a/runtime/doc/various.txt +++ b/runtime/doc/various.txt @@ -102,9 +102,7 @@ g8 Print the hex values of the bytes used in the *:p* *:pr* *:print* *E749* :[range]p[rint] [flags] Print [range] lines (default current line). - Note: If you are looking for a way to print your text - on paper see |:hardcopy|. In the GUI you can use the - File.Print menu entry. + In the GUI you can use the File.Print menu entry. See |ex-flags| for [flags]. The |:filter| command can be used to only show lines matching a pattern. @@ -260,6 +258,10 @@ g8 Print the hex values of the bytes used in the Use |jobstart()| instead. > :call jobstart('foo', {'detach':1}) < + For powershell, chaining a stringed executable path + requires using the call operator (&). > + :!Write-Output "1`n2" | & "C:\Windows\System32\sort.exe" /r +< *E34* Any "!" in {cmd} is replaced with the previous external command (see also 'cpoptions'), unless diff --git a/runtime/doc/vi_diff.txt b/runtime/doc/vi_diff.txt index cef2859eb5..afabddb7f9 100644 --- a/runtime/doc/vi_diff.txt +++ b/runtime/doc/vi_diff.txt @@ -337,10 +337,6 @@ Viminfo. The 'viminfo' option can be set to select which items to store in the .viminfo file. This is off by default. -Printing. |printing| - The |:hardcopy| command sends text to the printer. This can include - syntax highlighting. - Mouse support. |mouse-using| The mouse is supported in the GUI version, in an xterm for Unix, for BSDs with sysmouse, for Linux with gpm, and for Win32. It can be used diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index 53effa1443..bb3b670b24 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -36,9 +36,8 @@ centralized reference of the differences. - 'belloff' defaults to "all" - 'compatible' is always disabled - 'complete' excludes "i" -- 'cscopeverbose' is enabled - 'directory' defaults to ~/.local/state/nvim/swap// (|xdg|), auto-created -- 'display' defaults to "lastline,msgsep" +- 'display' defaults to "lastline" - 'encoding' is UTF-8 (cf. 'fileencoding' for file-content encoding) - 'fillchars' defaults (in effect) to "vert:│,fold:·,sep:│" - 'formatoptions' defaults to "tcqj" @@ -73,42 +72,41 @@ centralized reference of the differences. - 'wildmenu' is enabled - 'wildoptions' defaults to "pum,tagfile" -- |man.vim| plugin is enabled, so |:Man| is available by default. -- |matchit| plugin is enabled. To disable it in your config: > +- |man.lua| plugin is enabled, so |:Man| is available by default. +- |matchit| plugin is enabled. To disable it in your config: >vim :let loaded_matchit = 1 - |g:vimsyn_embed| defaults to "l" to enable Lua highlighting - Default Mouse ~ *default-mouse* *disable-mouse* -By default the mouse is enabled. The right button click opens |popup-menu| -with standard actions, such as "Cut", "Copy" and "Paste". - -If you don't like this you can add to your |config| any of the following: - -- ignore mouse completely > +By default the mouse is enabled, and <RightMouse> opens a |popup-menu| with +standard actions ("Cut", "Copy", "Paste", …). Mouse is NOT enabled in +|command-mode| or the |more-prompt|, so you can temporarily disable it just by +typing ":". + +If you don't like this you can disable the mouse in your |config| using any of +the following: +- Disable mouse completely by unsetting the 'mouse' option: >vim set mouse= -< -- no |popup-menu| but the right button extends selection > +- Pressing <RightMouse> extends selection instead of showing popup-menu: >vim set mousemodel=extend -> -- pressing ALT+LeftMouse releases mouse until main cursor moves > - nnoremap <M-LeftMouse> <Cmd> +- Pressing <A-LeftMouse> releases mouse until the cursor moves: >vim + nnoremap <A-LeftMouse> <Cmd> \ set mouse=<Bar> \ echo 'mouse OFF until next cursor-move'<Bar> \ autocmd CursorMoved * ++once set mouse&<Bar> \ echo 'mouse ON'<CR> < -Also, mouse is not in use in |command-mode| or at |more-prompt|. So if you -need to copy/paste with your terminal then just pressing ':' makes Nvim to -release the mouse cursor temporarily. - +To remove the "How-to disable mouse" menu item and the separator above it: >vim + aunmenu PopUp.How-to\ disable\ mouse + aunmenu PopUp.-1- +< Default Mappings ~ *default-mappings* Nvim creates the following default mappings at |startup|. You can disable any of these in your config by simply removing the mapping, e.g. ":unmap Y". -> +>vim nnoremap Y y$ nnoremap <C-L> <Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR> inoremap <C-U> <C-G>u<C-U> @@ -131,7 +129,7 @@ nvim_cmdwin: ============================================================================== 3. New Features *nvim-features* -MAJOR COMPONENTS ~ +MAJOR COMPONENTS API |API| Job control |job-control| @@ -149,7 +147,7 @@ Terminal emulator |terminal| Vimscript parser |nvim_parse_expression()| XDG base directories |xdg| -USER EXPERIENCE ~ +USER EXPERIENCE Working intuitively and consistently is a major goal of Nvim. @@ -162,7 +160,7 @@ Working intuitively and consistently is a major goal of Nvim. - Nvim avoids features that cannot be provided on all platforms; instead that is delegated to external plugins/extensions. E.g. the `-X` platform-specific option is "sometimes" available in Vim (with potential surprises: - http://stackoverflow.com/q/14635295). + https://stackoverflow.com/q/14635295). - Vim's internal test functions (test_autochdir(), test_settime(), etc.) are not exposed (nor implemented); instead Nvim has a robust API. @@ -180,7 +178,7 @@ Some features are built in that otherwise required external plugins: - Highlighting the yanked region, see |lua-highlight|. -ARCHITECTURE ~ +ARCHITECTURE External plugins run in separate processes. |remote-plugin| This improves stability and allows those plugins to work without blocking the editor. Even @@ -191,7 +189,7 @@ Platform and I/O facilities are built upon libuv. Nvim benefits from libuv features and bug fixes, and other projects benefit from improvements to libuv by Nvim developers. -FEATURES ~ +FEATURES Command-line highlighting: The expression prompt (|@=|, |c_CTRL-R_=|, |i_CTRL-R_=|) is highlighted @@ -210,6 +208,7 @@ Commands: |:match| can be invoked before highlight group is defined |:source| works with Lua User commands can support |:command-preview| to show results as you type + |:write| with "++p" flag creates parent directories. Events: |RecordingEnter| @@ -230,6 +229,7 @@ Functions: |stdpath()| |system()|, |systemlist()| can run {cmd} directly (without 'shell') |matchadd()| can be called before highlight group is defined + |writefile()| with "p" flag creates parent directories. Highlight groups: |highlight-blend| controls blend level for a highlight group @@ -256,9 +256,8 @@ Normal commands: Options: 'cpoptions' flags: |cpo-_| - 'display' flags: "msgsep" minimizes scrolling when showing messages 'guicursor' works in the terminal - 'fillchars' flags: "msgsep" (see 'display'), "horiz", "horizup", + 'fillchars' flags: "msgsep", "horiz", "horizup", "horizdown", "vertleft", "vertright", "verthoriz" 'foldcolumn' supports up to 9 dynamic/fixed columns 'inccommand' shows interactive results for |:substitute|-like commands @@ -272,6 +271,7 @@ Options: 'tabline' %@Func@foo%X can call any function on mouse-click 'winblend' pseudo-transparency in floating windows |api-floatwin| 'winhighlight' window-local highlights + 'diffopt' has the option `linematch`. Signs: Signs are removed if the associated line is deleted. @@ -281,7 +281,20 @@ Variables: |v:windowid| is always available (for use by external UIs) ============================================================================== -4. Changed features *nvim-features-changed* +4. Upstreamed features *nvim-upstreamed* + +These Nvim features were later integrated into Vim. + +- 'fillchars' flags: "eob" +- 'wildoptions' flags: "pum" enables popupmenu for wildmode completion +- |<Cmd>| +- |WinClosed| +- |WinScrolled| +- |:sign-define| "numhl" argument +- |:source| works with anonymous (no file) scripts + +============================================================================== +5. Changed features *nvim-features-changed* Nvim always builds with all features, in contrast to Vim which may have certain features removed/added at compile-time. |feature-compile| @@ -306,7 +319,7 @@ are always available and may be used simultaneously. See |provider-python|. structures. 2. |string()| fails immediately on nested containers, not when recursion limit was exceeded. -2. When |:echo| encounters duplicate containers like > +2. When |:echo| encounters duplicate containers like >vim let l = [] echo [l, l] @@ -372,6 +385,7 @@ Lua interface (|lua.txt|): Commands: |:doautocmd| does not warn about "No matching autocommands". |:wincmd| accepts a count. + `:write!` does not show a prompt if the file was updated externally. Command line completion: The meanings of arrow keys do not change depending on 'wildoptions'. @@ -390,6 +404,9 @@ Highlight groups: using |n| or |N| |hl-CursorLine| is low-priority unless foreground color is set |hl-VertSplit| superseded by |hl-WinSeparator| + Highlight groups names are allowed to contain the characters `.` and `@`. + It is an error to define a highlight group with a name that doesn't match + the regexp `[a-zA-Z0-9_.@]*` (see |group-name|). Macro/|recording| behavior Replay of a macro recorded during :lmap produces the same actions as when it @@ -413,10 +430,12 @@ Normal commands: Options: 'ttimeout', 'ttimeoutlen' behavior was simplified - |jumpoptions| "stack" behavior - |jumpoptions| "view" tries to restore the |mark-view| when moving through + 'jumpoptions' "stack" behavior + 'jumpoptions' "view" tries to restore the |mark-view| when moving through the |jumplist|, |changelist|, |alternate-file| or using |mark-motions|. 'shortmess' the "F" flag does not affect output from autocommands + 'exrc' searches for ".nvim.lua", ".nvimrc", or ".exrc" files. The user is + prompted whether to trust the file. Shell: Shell output (|:!|, |:make|, …) is always routed through the UI, so it @@ -460,7 +479,7 @@ TUI: < *'term'* *E529* *E530* *E531* 'term' reflects the terminal type derived from |$TERM| and other environment - checks. For debugging only; not reliable during startup. > + checks. For debugging only; not reliable during startup. >vim :echo &term < "builtin_x" means one of the |builtin-terms| was chosen, because the expected terminfo file was not found on the system. @@ -475,6 +494,11 @@ TUI: UI/Display: |Visual| selection highlights the character at cursor. |visual-use| + messages: When showing messages longer than 'cmdheight', only + scroll the message lines, not the entire screen. The + separator line is decorated by |hl-MsgSeparator| and + the "msgsep" flag of 'fillchars'. *msgsep* + Vimscript compatibility: `count` does not alias to |v:count| `errmsg` does not alias to |v:errmsg| @@ -492,17 +516,20 @@ Working directory (Vim implemented some of these later than Nvim): working directory. Use `getcwd(-1, -1)` to get the global working directory. ============================================================================== -5. Missing legacy features *nvim-features-missing* +6. Missing legacy features *nvim-features-missing* -Some legacy Vim features are not implemented: +Some legacy Vim features are not yet implemented: -- |if_lua|: Nvim Lua API is not compatible with Vim's "if_lua" +- *if_lua* : Nvim |Lua| API is not compatible with Vim's "if_lua" - *if_mzscheme* -- |if_py|: *python-bindeval* *python-Function* are not supported +- |if_pyth|: *python-bindeval* *python-Function* are not supported - *if_tcl* +*:gui* +*:gvim* + ============================================================================== -6. Removed features *nvim-features-removed* +7. Removed features *nvim-features-removed* These Vim features were intentionally removed from Nvim. @@ -522,6 +549,7 @@ Aliases: Commands: :fixdel + :hardcopy :helpfind :mode (no longer accepts an argument) :open @@ -533,6 +561,10 @@ Commands: :sleep! (does not hide the cursor; same as :sleep) :smile :tearoff + :cstag + :cscope + :lcscope + :scscope Compile-time features: Emacs tags support @@ -540,6 +572,7 @@ Compile-time features: Eval: Vim9script + *cscope_connection()* *js_encode()* *js_decode()* *v:none* (used by Vim to represent JavaScript "undefined"); use |v:null| instead. @@ -553,7 +586,7 @@ Events: Highlight groups: *hl-StatusLineTerm* *hl-StatusLineTermNC* are unnecessary because Nvim supports 'winhighlight' window-local highlights. - For example, to mimic Vim's StatusLineTerm: > + For example, to mimic Vim's StatusLineTerm: >vim hi StatusLineTerm ctermfg=black ctermbg=green hi StatusLineTermNC ctermfg=green autocmd TermOpen,WinEnter * if &buftype=='terminal' @@ -562,18 +595,25 @@ Highlight groups: < Options: - 'antialias' + antialias *'balloondelay'* *'bdlay'* *'ballooneval'* *'beval'* *'noballooneval'* *'nobeval'* *'balloonexpr'* *'bexpr'* - 'bioskey' (MS-DOS) - 'conskey' (MS-DOS) + bioskey (MS-DOS) + conskey (MS-DOS) *'cp'* *'nocompatible'* *'nocp'* *'compatible'* (Nvim is always "nocompatible".) 'cpoptions' (gjkHw<*- and all POSIX flags were removed) *'cryptmethod'* *'cm'* *'key'* (Vim encryption implementation) + cscopepathcomp + cscopeprg + cscopequickfix + cscoperelative + cscopetag + cscopetagorder + cscopeverbose *'ed'* *'edcompatible'* *'noed'* *'noedcompatible'* 'encoding' ("utf-8" is always used) - 'esckeys' + esckeys 'guioptions' "t" flag was removed *'guifontset'* *'gfs'* (Use 'guifont' instead.) *'guipty'* (Nvim uses pipes and PTYs consistently on all platforms.) @@ -582,7 +622,7 @@ Options: *'imactivatekey'* *'imak'* *'imstatusfunc'* *'imsf'* *'insertmode'* *'im'* Use the following script to emulate 'insertmode': -> +>vim autocmd BufWinEnter * startinsert inoremap <Esc> <C-X><C-Z><C-]> inoremap <C-C> <C-X><C-Z> @@ -614,18 +654,27 @@ Options: Nvim always displays up to 6 combining characters. You can still edit text with more than 6 combining characters, you just can't see them. Use |g8| or |ga|. See |mbyte-combining|. - 'maxmem' Nvim delegates memory-management to the OS. - 'maxmemtot' Nvim delegates memory-management to the OS. + *'maxmem'* Nvim delegates memory-management to the OS. + *'maxmemtot'* Nvim delegates memory-management to the OS. + *'printdevice'* + *'printencoding'* + *'printexpr'* + *'printfont'* + *'printheader'* + *'printmbcharset'* *'prompt'* *'noprompt'* *'remap'* *'noremap'* *'restorescreen'* *'rs'* *'norestorescreen'* *'nors'* - 'shelltype' + *'secure'* + Everything is allowed in 'exrc' files since they must be explicitly marked + trusted. + *'shelltype'* *'shortname'* *'sn'* *'noshortname'* *'nosn'* *'swapsync'* *'sws'* *'termencoding'* *'tenc'* (Vim 7.4.852 also removed this for Windows) *'terse'* *'noterse'* (Add "s" to 'shortmess' instead) - 'textauto' - 'textmode' + textauto + textmode *'toolbar'* *'tb'* *'toolbariconsize'* *'tbis'* *'ttybuiltin'* *'tbi'* *'nottybuiltin'* *'notbi'* @@ -633,7 +682,10 @@ Options: *'ttymouse'* *'ttym'* *'ttyscroll'* *'tsl'* *'ttytype'* *'tty'* - 'weirdinvert' + weirdinvert + +Performance: + Folds are not updated during insert-mode. Startup: --literal (file args are always literal; to expand wildcards on Windows, use @@ -683,5 +735,14 @@ TUI: at how the terminal is sending CSI. Nvim does not issue such a sequence and always uses 7-bit control sequences. +Cscope: + *cscope* + Cscope support has been removed in favour of LSP based solutions. + +Hardcopy: + *hardcopy* + `:hardcopy` was removed. Instead, use `:TOhtml` and print the resulting HTML + using a web browser or some other HTML viewer. + ============================================================================== vim:tw=78:ts=8:sw=2:et:ft=help:norl: diff --git a/runtime/doc/visual.txt b/runtime/doc/visual.txt index 5383ea4f72..0c6bd4f3a1 100644 --- a/runtime/doc/visual.txt +++ b/runtime/doc/visual.txt @@ -103,7 +103,7 @@ gn Search forward for the last used search pattern, like E.g., "dgn" deletes the text of the next match. If Visual mode is active, extends the selection until the end of the next match. - 'wrapscan' applies + 'wrapscan' applies. Note: Unlike `n` the search direction does not depend on the previous search command. @@ -501,11 +501,11 @@ mode Vim automatically switches to Visual mode, so that the same behavior as in Visual mode is effective. If you don't want this use |:xmap| or |:smap|. One particular edge case: > - :vnoremap <C-K> <Esc> + :vnoremap <C-K> <Esc> This ends Visual mode when in Visual mode, but in Select mode it does not work, because Select mode is restored after executing the mapped keys. You need to use: > - :snoremap <C-K> <Esc> + :snoremap <C-K> <Esc> < Users will expect printable characters to replace the selected area. Therefore avoid mapping printable characters in Select mode. Or use diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 7355cec522..61f5013f47 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -119,7 +119,7 @@ windows. *filler-lines* The lines after the last buffer line in a window are called filler lines. By -default, these lines start with a tilde (~) character. The 'eob' item in the +default, these lines start with a tilde (~) character. The "eob" item in the 'fillchars' option can be used to change this character. By default, these characters are highlighted as NonText (|hl-NonText|). The EndOfBuffer highlight group (|hl-EndOfBuffer|) can be used to change the highlighting of @@ -148,7 +148,7 @@ CTRL-W CTRL-S *CTRL-W_CTRL-S* Note: CTRL-S does not work on all terminals and might block further input, use CTRL-Q to get going again. Also see |++opt| and |+cmd|. - *E242* + *E242* *E1159* Be careful when splitting a window in an autocommand, it may mess up the window layout if this happens while making other window layout changes. @@ -163,6 +163,8 @@ CTRL-W v *CTRL-W_v* 3. 'eadirection' isn't "ver", and 4. one of the other windows is wider than the current or new window. + If N was given make the new window N columns wide, if + possible. Note: In other places CTRL-Q does the same as CTRL-V, but here it doesn't! @@ -233,9 +235,16 @@ and 'winminwidth' are relevant. *:vert* *:vertical* :vert[ical] {cmd} Execute {cmd}. If it contains a command that splits a window, - it will be split vertically. + it will be split vertically. For `vertical wincmd =` windows + will be equalized only vertically. Doesn't work for |:execute| and |:normal|. + *:hor* *:horizontal* +:hor[izontal] {cmd} + Execute {cmd}. Currently only makes a difference for + `horizontal wincmd =`, which will equalize windows only + horizontally. + :lefta[bove] {cmd} *:lefta* *:leftabove* :abo[veleft] {cmd} *:abo* *:aboveleft* Execute {cmd}. If it contains a command that splits a window, @@ -275,16 +284,15 @@ Opens a vertically split, full-height window on the "tags" file at the far left of the Vim window. +------------------------------------------------------------------------------ Closing a window ----------------- :q[uit] :{count}q[uit] *:count_quit* CTRL-W q *CTRL-W_q* CTRL-W CTRL-Q *CTRL-W_CTRL-Q* - Without {count}: Quit the current window. If {count} is - given quit the {count} window - + Without {count}: Quit the current window. If {count} is + given quit the {count} window. *edit-window* When quitting the last edit window (not counting help or preview windows), exit Vim. @@ -343,7 +351,7 @@ CTRL-W CTRL-C *CTRL-W_CTRL-C* window, but that does not work, because the CTRL-C cancels the command. - *:hide* + *:hide* :hid[e] :{count}hid[e] Without {count}: Quit the current window, unless it is the @@ -528,6 +536,10 @@ CTRL-W = Make all windows (almost) equally high and wide, but use 'winheight' and 'winwidth' for the current window. Windows with 'winfixheight' set keep their height and windows with 'winfixwidth' set keep their width. + To equalize only vertically (make window equally high) use + `vertical wincmd =` . + To equalize only horizontally (make window equally wide) use + `horizontal wincmd =` . :res[ize] -N *:res* *:resize* *CTRL-W_-* CTRL-W - Decrease current window height by N (default 1). @@ -595,6 +607,53 @@ it). The minimal height and width of a window is set with 'winminheight' and 'winminwidth'. These are hard values, a window will never become smaller. + +WinScrolled and WinResized autocommands ~ + *win-scrolled-resized* +If you want to get notified of changes in window sizes, the |WinResized| +autocommand event can be used. +If you want to get notified of text in windows scrolling vertically or +horizontally, the |WinScrolled| autocommand event can be used. This will also +trigger in window size changes. +Exception: the events will not be triggered when the text scrolls for +'incsearch'. + *WinResized-event* +The |WinResized| event is triggered after updating the display, several +windows may have changed size then. A list of the IDs of windows that changed +since last time is provided in the v:event.windows variable, for example: + [1003, 1006] + *WinScrolled-event* +The |WinScrolled| event is triggered after |WinResized|, and also if a window +was scrolled. That can be vertically (the text at the top of the window +changed) or horizontally (when 'wrap' is off or when the first displayed part +of the first line changes). Note that |WinScrolled| will trigger many more +times than |WinResized|, it may slow down editing a bit. + +The information provided by |WinScrolled| is a dictionary for each window that +has changes, using the window ID as the key, and a total count of the changes +with the key "all". Example value for |v:event|: + { + all: {width: 0, height: 2, leftcol: 0, skipcol: 0, topline: 1, topfill: 0}, + 1003: {width: 0, height: -1, leftcol: 0, skipcol: 0, topline: 0, topfill: 0}, + 1006: {width: 0, height: 1, leftcol: 0, skipcol: 0, topline: 1, topfill: 0}, + } + +Note that the "all" entry has the absolute values of the individual windows +accumulated. + +If you need more information about what changed, or you want to "debounce" the +events (not handle every event to avoid doing too much work), you may want to +use the `winlayout()` and `getwininfo()` functions. + +|WinScrolled| and |WinResized| do not trigger when the first autocommand is +added, only after the first scroll or resize. They may trigger when switching +to another tab page. + +The commands executed are expected to not cause window size or scroll changes. +If this happens anyway, the event will trigger again very soon. In other +words: Just before triggering the event, the current sizes and scroll +positions are stored and used to decide whether there was a change. + ============================================================================== 7. Argument and buffer list commands *buffer-list* @@ -634,8 +693,8 @@ Note: ":next" is an exception, because it must accept a list of file names for compatibility with Vi. +------------------------------------------------------------------------------ The argument list and multiple windows --------------------------------------- The current position in the argument list can be different for each window. Remember that when doing ":e file", the position in the argument list stays @@ -738,6 +797,7 @@ can also get to them with the buffer list commands, like ":bnext". the current window. {cmd} can contain '|' to concatenate several commands. {cmd} must not open or close windows or reorder them. + Also see |:tabdo|, |:argdo|, |:bufdo|, |:cdo|, |:ldo|, |:cfdo| and |:lfdo|. @@ -765,6 +825,7 @@ can also get to them with the buffer list commands, like ":bnext". autocommand event is disabled by adding it to 'eventignore'. This considerably speeds up editing each buffer. + Also see |:tabdo|, |:argdo|, |:windo|, |:cdo|, |:ldo|, |:cfdo| and |:lfdo|. |