docs: add language annotation to Nvim manual

This commit is contained in:
Christian Clason
2022-11-22 18:41:00 +01:00
parent 5093f38c9f
commit 952f19ba38
21 changed files with 528 additions and 525 deletions

View File

@@ -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 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 |api-client|. Here's a Ruby script that prints "hello world!" in the current
Nvim instance: Nvim instance:
> >ruby
#!/usr/bin/env ruby #!/usr/bin/env ruby
# Requires msgpack-rpc: gem install msgpack-rpc # Requires msgpack-rpc: gem install msgpack-rpc
# #
@@ -79,7 +79,7 @@ functions can be called interactively:
< <
You can also embed Nvim via |jobstart()|, and communicate using |rpcrequest()| You can also embed Nvim via |jobstart()|, and communicate using |rpcrequest()|
and |rpcnotify()|: and |rpcnotify()|:
> >vim
let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true}) let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true})
echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"') echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"')
call jobstop(nvim) call jobstop(nvim)
@@ -201,9 +201,9 @@ any of these approaches:
Example (requires Python "pyyaml" and "msgpack-python" modules): > 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)' 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())) :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') :new|put =map(filter(api_info().functions, '!has_key(v:val,''deprecated_since'')'), 'v:val.name')
============================================================================== ==============================================================================
@@ -361,10 +361,10 @@ callbacks. These callbacks are called frequently in various contexts;
receive parameters ("lines", {buf}, {changedtick}, {firstline}, {lastline}, receive parameters ("lines", {buf}, {changedtick}, {firstline}, {lastline},
{new_lastline}, {old_byte_size} [, {old_utf32_size}, {old_utf16_size}]). {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 Unlike remote channel events the text contents are not passed. The new text can
be accessed inside the callback as be accessed inside the callback as >lua
`vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true)`
vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true)
<
{old_byte_size} is the total size of the replaced region {firstline} to {old_byte_size} is the total size of the replaced region {firstline} to
{lastline} in bytes, including the final newline after {lastline}. if {lastline} in bytes, including the final newline after {lastline}. if
`utf_sizes` is set to true in |nvim_buf_attach()| keyword args, then the `utf_sizes` is set to true in |nvim_buf_attach()| keyword args, then the
@@ -400,7 +400,7 @@ performance can be improved by calling |nvim_buf_add_highlight()| as an
asynchronous notification, after first (synchronously) requesting a source id. asynchronous notification, after first (synchronously) requesting a source id.
Example using the Python API client (|pynvim|): Example using the Python API client (|pynvim|):
> >python
src = vim.new_highlight_source() src = vim.new_highlight_source()
buf = vim.current.buffer buf = vim.current.buffer
for i in range(5): for i in range(5):
@@ -414,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 entire buffer by passing in the line range 0, -1 (the latter is the default in
python as used above). 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"]) call nvim_buf_set_lines(0, 0, 0, v:true, ["test text"])
let src = nvim_buf_add_highlight(0, 0, "String", 1, 0, 4) let src = nvim_buf_add_highlight(0, 0, "String", 1, 0, 4)
@@ -438,7 +438,7 @@ Two ways to create a floating window:
To close it use |nvim_win_close()| or a command such as |:close|. 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 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 if vim.api.nvim_win_get_config(window_id).relative ~= '' then
-- window with this window_id is floating -- window with this window_id is floating
@@ -456,7 +456,7 @@ Currently, floating windows don't support some widgets like scrollbar.
The output of |:mksession| does not include commands for restoring floating The output of |:mksession| does not include commands for restoring floating
windows. 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) let buf = nvim_create_buf(v:false, v:true)
call nvim_buf_set_lines(buf, 0, -1, v:true, ["test", "text"]) call nvim_buf_set_lines(buf, 0, -1, v:true, ["test", "text"])
@@ -510,19 +510,20 @@ Let's set an extmark at the first row (row=0) and third column (column=2).
01 2345678 01 2345678
0 ex|ample.. 0 ex|ample..
^ extmark position ^ extmark position
<
>vim
let g:mark_ns = nvim_create_namespace('myplugin') let g:mark_ns = nvim_create_namespace('myplugin')
let g:mark_id = nvim_buf_set_extmark(0, g:mark_ns, 0, 2, {}) 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, {}) 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, {}) 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 Deleting all surrounding text does NOT remove an extmark! To remove extmarks
use |nvim_buf_del_extmark()|. Deleting "x" in our example: > use |nvim_buf_del_extmark()|. Deleting "x" in our example: >
@@ -530,9 +531,10 @@ use |nvim_buf_del_extmark()|. Deleting "x" in our example: >
0 12345678 0 12345678
0 e|ample.. 0 e|ample..
^ extmark position ^ extmark position
<
>vim
echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {}) 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. Note: Extmark "gravity" decides how it will shift after a text edit.
See |nvim_buf_set_extmark()| See |nvim_buf_set_extmark()|

View File

@@ -91,7 +91,7 @@ only bytes can be written to Nvim's own stderr.
There are two ways to deal with this: There are two ways to deal with this:
- 1. To wait for the entire output, use |channel-buffered| mode. - 1. To wait for the entire output, use |channel-buffered| mode.
- 2. To read line-by-line, use the following code: > - 2. To read line-by-line, use the following code: >vim
let s:lines = [''] let s:lines = ['']
func! s:on_event(job_id, data, event) dict func! s:on_event(job_id, data, event) dict
let eof = (a:data == ['']) let eof = (a:data == [''])
@@ -108,7 +108,7 @@ callbacks.
Data can be sent to the channel using the |chansend()| function. Here is a Data can be sent to the channel using the |chansend()| function. Here is a
simple example, echoing some data through a cat-process: simple example, echoing some data through a cat-process:
> >vim
function! s:OnEvent(id, data, event) dict function! s:OnEvent(id, data, event) dict
let str = join(a:data, "\n") let str = join(a:data, "\n")
echomsg str echomsg str
@@ -119,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 Here is a example of setting a buffer to the result of grep, but only after
all data has been processed: all data has been processed:
> >vim
function! s:OnEvent(id, data, event) dict function! s:OnEvent(id, data, event) dict
call nvim_buf_set_lines(2, 0, -1, v:true, a:data) call nvim_buf_set_lines(2, 0, -1, v:true, a:data)
endfunction endfunction
@@ -142,7 +142,7 @@ However, change of PTY size can be signaled to the slave using |jobresize()|.
See also |terminal-emulator|. See also |terminal-emulator|.
Terminal characteristics (termios) for |:terminal| and PTY channels are copied 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') :echo system('nvim --headless +"te stty -a" +"sleep 1" +"1,/^$/print" +q')
============================================================================== ==============================================================================
@@ -163,7 +163,7 @@ used as a channel. See also |--embed|.
Call |stdioopen()| during |startup| to open the stdio channel as |channel-id| 1. 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. Nvim's stderr is always available as |v:stderr|, a write-only bytes channel.
Example: > Example: >vim
func! OnEvent(id, data, event) func! OnEvent(id, data, event)
if a:data == [""] if a:data == [""]
quit quit
@@ -172,7 +172,7 @@ Example: >
endfunc endfunc
call stdioopen({'on_stdin': 'OnEvent'}) 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" nvim --headless --cmd "source uppercase.vim"
============================================================================== ==============================================================================
@@ -223,7 +223,7 @@ start of the line.
Here is an example for Unix. It starts a shell in the background and prompts 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 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. " Function handling a line of text that has been typed.
func TextEntered(text) func TextEntered(text)

View File

@@ -30,7 +30,7 @@ ENVIRONMENT VARIABLES
- detect a parent Nvim (use |$NVIM| instead) - detect a parent Nvim (use |$NVIM| instead)
- Ignored if --listen is given. - Ignored if --listen is given.
- Unset by |terminal| and |jobstart()| unless explicitly given by the "env" - Unset by |terminal| and |jobstart()| unless explicitly given by the "env"
option. Example: > option. Example: >vim
call jobstart(['foo'], { 'env': { 'NVIM_LISTEN_ADDRESS': v:servername } }) call jobstart(['foo'], { 'env': { 'NVIM_LISTEN_ADDRESS': v:servername } })
< <

View File

@@ -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`. The format of the symbol name should be `NVIM_<DIRECTORY>_<FILE>_H`.
In foo/bar.h: In foo/bar.h:
> >c
#ifndef NVIM_FOO_BAR_H #ifndef NVIM_FOO_BAR_H
#define 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 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 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 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; int i;
i = f(); // BAD: initialization separate from declaration. i = f(); // BAD: initialization separate from declaration.
@@ -110,7 +110,7 @@ Variable-length arrays can cause hard to detect stack overflows.
Postincrement and Postdecrement ~ Postincrement and Postdecrement ~
Use postfix form (`i++`) in statements. > Use postfix form (`i++`) in statements. >c
for (int i = 0; i < 3; i++) { } for (int i = 0; i < 3; i++) { }
int j = ++i; // OK: ++i is used as an expression. 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`). before the "noun" (`int`).
That said, while we encourage putting `const` first, we do not require it. 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); void foo(const char *p, int i);
} }
@@ -176,14 +176,14 @@ Type unsigned signed
Booleans ~ Booleans ~
Use `bool` to represent boolean values. > Use `bool` to represent boolean values. >c
int loaded = 1; // BAD: loaded should have type bool. int loaded = 1; // BAD: loaded should have type bool.
Conditions ~ 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) { if (1 == x) {
@@ -196,7 +196,7 @@ Function declarations ~
Every function must not have a separate declaration. 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); static void f(void);
@@ -209,7 +209,7 @@ Function declarations are created by the gendeclarations.lua script. >
General translation unit layout ~ General translation unit layout ~
The definitions of public functions precede the definitions of static The definitions of public functions precede the definitions of static
functions. > functions. >c
<HEADER> <HEADER>
@@ -230,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 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 the directory name relative to src/nvim. Name of the file containing static
functions declarations ends with `.c.generated.h`, `*.h.generated.h` files 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 // src/nvim/foo.c file
#include <stddef.h> #include <stddef.h>
@@ -274,7 +274,7 @@ comparisons, and structure alignment.
`#pragma pack()` and `__declspec(align())`. `#pragma pack()` and `__declspec(align())`.
- Use the `LL` or `ULL` suffixes as needed to create 64-bit constants. For - Use the `LL` or `ULL` suffixes as needed to create 64-bit constants. For
example: > example: >c
int64_t my_value = 0x123456789LL; int64_t my_value = 0x123456789LL;
uint64_t my_mask = 3ULL << 48; uint64_t my_mask = 3ULL << 48;
@@ -288,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 `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 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 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; Struct data;
memset(&data, 0, sizeof(data)); memset(&data, 0, sizeof(data));
@@ -324,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 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 immediately understandable by a new reader. Do not use abbreviations that are
ambiguous or unfamiliar to readers outside your project, and do not abbreviate 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 price_count_reader; // No abbreviation.
int num_errors; // "num" is a widespread convention. int num_errors; // "num" is a widespread convention.
@@ -361,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`. letter for each new word, with no underscores: `MyExcitingStruct`.
Non-Typedef-ed structs and enums are all lowercase with underscores between 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 { struct my_struct {
... ...
@@ -376,7 +376,7 @@ instance: `my_exciting_local_variable`.
Common Variable names ~ Common Variable names ~
For example: > For example: >c
string table_name; // OK: uses underscore. string table_name; // OK: uses underscore.
string tablename; // OK: all lowercase. string tablename; // OK: all lowercase.
@@ -386,7 +386,7 @@ instance: `my_exciting_local_variable`.
Struct Variables ~ 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 { struct url_table_properties {
string name; string name;
@@ -406,7 +406,7 @@ Use a `k` followed by mixed case: `kDaysInAWeek`.
All compile-time constants, whether they are declared locally or globally, All compile-time constants, whether they are declared locally or globally,
follow a slightly different naming convention from other variables. Use a `k` 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; const int kDaysInAWeek = 7;
@@ -416,7 +416,7 @@ Function names are all lowercase, with underscores between words. For
instance: `my_exceptional_function()`. All functions in the same header file instance: `my_exceptional_function()`. All functions in the same header file
should have a common prefix. should have a common prefix.
In `os_unix.h`: > In `os_unix.h`: >c
void unix_open(const char *path); void unix_open(const char *path);
void unix_user_id(void); void unix_user_id(void);
@@ -429,7 +429,7 @@ normal operation.
Enumerator Names ~ Enumerator Names ~
Enumerators should be named like constants: `kEnumName`. > Enumerators should be named like constants: `kEnumName`. >c
enum url_table_errors { enum url_table_errors {
kOK = 0, kOK = 0,
@@ -440,7 +440,7 @@ Enumerators should be named like constants: `kEnumName`. >
Macro Names ~ 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 ROUND(x) ...
#define PI_ROUNDED 5.0 #define PI_ROUNDED 5.0
@@ -461,7 +461,7 @@ Nvim uses Doxygen comments.
Comment Style ~ Comment Style ~
Use the `//`-style syntax only. > Use the `//`-style syntax only. >c
// This is a comment spanning // This is a comment spanning
// multiple lines // multiple lines
@@ -489,7 +489,7 @@ Start each file with a description of its contents.
mention in the `.c` that the documentation is in the `.h` file. mention in the `.c` that the documentation is in the `.h` file.
Do not duplicate comments in both the `.h` and the `.c`. Duplicated Do not duplicate comments in both the `.h` and the `.c`. Duplicated
comments diverge. > comments diverge. >c
/// A brief description of this file. /// A brief description of this file.
/// ///
@@ -500,7 +500,7 @@ Start each file with a description of its contents.
Struct Comments ~ Struct Comments ~
Every struct definition should have accompanying comments that describes what 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. /// Window info stored with a buffer.
/// ///
@@ -522,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 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 { struct wininfo_S {
WinInfo *wi_next; ///< Next entry or NULL for last entry. WinInfo *wi_next; ///< Next entry or NULL for last entry.
@@ -560,8 +560,7 @@ of a function describe operation.
- If the function allocates memory that the caller must free. - If the function allocates memory that the caller must free.
- Whether any of the arguments can be a null pointer. - Whether any of the arguments can be a null pointer.
- If there are any performance implications of how a function is used. - 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. /// Brief description of the function.
/// ///
/// Detailed description. /// Detailed description.
@@ -589,7 +588,7 @@ of a function describe operation.
Note you should not just repeat the comments given with the function Note you should not just repeat the comments given with the function
declaration, in the `.h` file or wherever. It's okay to recapitulate 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 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. // Note that we don't use Doxygen comments here.
Iterator *get_iterator(void *arg1, void *arg2) Iterator *get_iterator(void *arg1, void *arg2)
@@ -607,7 +606,7 @@ comments are required.
Global Variables ~ Global Variables ~
All global variables should have a comment describing what they are and 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 /// The total number of tests cases that we run
/// through in this regression test. /// through in this regression test.
@@ -623,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 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 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. // If we have enough memory, mmap the data portion too.
mmap_budget = max<int64>(0, mmap_budget - index_->length()); mmap_budget = max<int64>(0, mmap_budget - index_->length());
@@ -636,7 +635,7 @@ interesting, or important parts of your code.
function returns. function returns.
If you have several comments on subsequent lines, it can often be more 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(); // Comment here so the comments line up.
do_something_else_that_is_longer(); // Comment here so there are two spaces between do_something_else_that_is_longer(); // Comment here so there are two spaces between
@@ -652,7 +651,7 @@ interesting, or important parts of your code.
When you pass in a null pointer, boolean, or literal integer values to 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 functions, you should consider adding a comment about what they are, or
make your code self-documenting by using constants. For example, compare: make your code self-documenting by using constants. For example, compare:
> >c
bool success = calculate_something(interesting_value, bool success = calculate_something(interesting_value,
10, 10,
@@ -660,7 +659,7 @@ interesting, or important parts of your code.
NULL); // What are these arguments?? NULL); // What are these arguments??
< <
versus: > versus: >c
bool success = calculate_something(interesting_value, bool success = calculate_something(interesting_value,
10, // Default base value. 10, // Default base value.
@@ -668,7 +667,7 @@ interesting, or important parts of your code.
NULL); // No callback. NULL); // No callback.
< <
Or alternatively, constants or self-describing variables: > Or alternatively, constants or self-describing variables: >c
const int kDefaultBaseValue = 10; const int kDefaultBaseValue = 10;
const bool kFirstTimeCalling = false; const bool kFirstTimeCalling = false;
@@ -683,7 +682,7 @@ interesting, or important parts of your code.
Note that you should never describe the code itself. Assume that the 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 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, // Now go through the b array and make sure that if i occurs,
// the next element is i+1. // the next element is i+1.
@@ -718,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 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 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 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(kl@gmail.com): Use a "*" here for concatenation operator.
// TODO(Zeke): change this to use relations. // TODO(Zeke): change this to use relations.
@@ -786,19 +785,19 @@ Function Calls ~
On one line if it fits; otherwise, wrap arguments at the parenthesis. 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); bool retval = do_something(argument1, argument2, argument3);
If the arguments do not all fit on one line, they should be broken up onto 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 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, bool retval = do_something(averyveryveryverylongargument1,
argument2, argument3); argument2, argument3);
If the function has many arguments, consider having one per line if this makes 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, bool retval = do_something(argument1,
argument2, argument2,
@@ -806,7 +805,7 @@ the code more readable: >
argument4); argument4);
Arguments may optionally all be placed on subsequent lines, with one line per Arguments may optionally all be placed on subsequent lines, with one line per
argument: > argument: >c
if (...) { if (...) {
... ...
@@ -830,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 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 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 {. struct my_struct m = { // Here, you could also break before {.
superlongvariablename1, superlongvariablename1,
@@ -847,7 +846,7 @@ Annotate non-trivial fall-through between cases.
If not conditional on an enumerated value, switch statements should always 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 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 warn you if any values are not handled). If the default case should never
execute, simply `assert`: > execute, simply `assert`: >c
switch (var) { switch (var) {
case 0: case 0:
@@ -865,7 +864,7 @@ Return Values ~
Do not needlessly surround the `return` expression with parentheses. Do not needlessly surround the `return` expression with parentheses.
Use parentheses in `return expr`; only where you would use them in `x = Use parentheses in `return expr`; only where you would use them in `x =
expr;`. > expr;`. >c
return result; return result;
return (some_long_condition && another_condition); return (some_long_condition && another_condition);
@@ -879,12 +878,12 @@ Horizontal Whitespace ~
Use of horizontal whitespace depends on location. Use of horizontal whitespace depends on location.
General ~ General ~
> >c
int x[] = { 0 }; // Spaces inside braces for braced-init-list. int x[] = { 0 }; // Spaces inside braces for braced-init-list.
< <
Variables ~ Variables ~
> >c
int long_variable = 0; // Don't align assignments. int long_variable = 0; // Don't align assignments.
int i = 1; int i = 1;
@@ -901,7 +900,7 @@ Use of horizontal whitespace depends on location.
Operators ~ Operators ~
> >c
x = 0; // Assignment operators always have spaces around x = 0; // Assignment operators always have spaces around
// them. // them.
x = -5; // No spaces separating unary operators and their x = -5; // No spaces separating unary operators and their

View File

@@ -119,7 +119,7 @@ reflects whether Python support is working.
*provider-reload* *provider-reload*
Sometimes a GUI or other application may want to force a provider to Sometimes a GUI or other application may want to force a provider to
"reload". To reload a provider, undefine its "loaded" flag, then use "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 :unlet g:loaded_clipboard_provider
:runtime autoload/provider/clipboard.vim :runtime autoload/provider/clipboard.vim

View File

@@ -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. Functions that take a severity as an optional parameter (e.g.
|vim.diagnostic.get()|) accept one of two forms: |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 }) 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 } }) 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* *diagnostic-handlers-example*
The example below creates a new handler that notifies the user of diagnostics 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 -- It's good practice to namespace custom handlers to avoid collisions
vim.diagnostic.handlers["my/notify"] = { 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. omit the "hide" function.
Existing handlers can be overridden. For example, use the following to only 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 -- Create a custom namespace. This will aggregate signs from all other
-- namespaces and only show the one with the highest severity on a -- 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 For example, the default highlighting for |hl-DiagnosticSignError| is linked
to |hl-DiagnosticError|. To change the default (and therefore the 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" highlight DiagnosticError guifg="BrightRed"
< <
@@ -279,7 +279,7 @@ SIGNS *diagnostic-signs*
Signs are defined for each diagnostic severity. The default text for each sign 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 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 DiagnosticSignError text=E texthl=DiagnosticSignError linehl= numhl=
sign define DiagnosticSignWarn text=W texthl=DiagnosticSignWarn linehl= numhl= sign define DiagnosticSignWarn text=W texthl=DiagnosticSignWarn linehl= numhl=
@@ -299,7 +299,7 @@ DiagnosticChanged After diagnostics have changed. When used from Lua,
the new diagnostics are passed to the autocmd the new diagnostics are passed to the autocmd
callback in the "data" table. callback in the "data" table.
Example: > Example: >lua
vim.api.nvim_create_autocmd('DiagnosticChanged', { vim.api.nvim_create_autocmd('DiagnosticChanged', {
callback = function(args) callback = function(args)

View File

@@ -16,7 +16,7 @@ Commands *python-commands*
*:python* *:py* *E263* *E264* *E887* *:python* *:py* *E263* *E264* *E887*
:[range]py[thon] {stmt} :[range]py[thon] {stmt}
Execute Python statement {stmt}. A simple check if Execute Python statement {stmt}. A simple check if
the `:python` command is working: > the `:python` command is working: >vim
:python print "Hello" :python print "Hello"
:[range]py[thon] << [endmarker] :[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 If [endmarker] is omitted from after the "<<", a dot '.' must be used after
{script}, like for the |:append| and |:insert| commands. {script}, like for the |:append| and |:insert| commands.
Example: > Example: >vim
function! IcecreamInitialize() function! IcecreamInitialize()
python << EOF python << EOF
class StrawberryIcecream: class StrawberryIcecream:
@@ -40,7 +40,7 @@ Example: >
EOF EOF
endfunction endfunction
To see what version of Python you have: > To see what version of Python you have: >vim
:python print(sys.version) :python print(sys.version)
There is no need to "import sys", it's done by default. 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,$". is the whole file: "1,$".
Examples: Examples:
> >vim
:pydo return "%s\t%d" % (line[::-1], len(line)) :pydo return "%s\t%d" % (line[::-1], len(line))
:pydo if line: return "%4d: %s" % (linenr, line) :pydo if line: return "%4d: %s" % (linenr, line)
< <
One can use `:pydo` in possible conjunction with `:py` to filter a range using One can use `:pydo` in possible conjunction with `:py` to filter a range using
python. For example: > python. For example: >vim
:py3 << EOF :py3 << EOF
needle = vim.eval('@a') 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|. 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"] :python sys.argv = ["foo", "bar"]
:pyfile myscript.py :pyfile myscript.py
Here are some examples *python-examples* > Here are some examples *python-examples*
>vim
:python from vim import * :python from vim import *
:python from string import upper :python from string import upper
@@ -113,7 +114,7 @@ to the next, just like the Python REPL.
*script-here* *script-here*
When using a script language in-line, you might want to skip this when the 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: language isn't supported. Note that this mechanism doesn't work:
> >vim
if has('python') if has('python')
python << EOF python << EOF
this will NOT work! this will NOT work!
@@ -121,7 +122,7 @@ language isn't supported. Note that this mechanism doesn't work:
endif endif
Instead, put the Python command in a function and call that function: Instead, put the Python command in a function and call that function:
> >vim
if has('python') if has('python')
function DefPython() function DefPython()
python << EOF 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 code gets all of its access to vim (with one exception - see
|python-output| below) via the "vim" module. The vim module implements two |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 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 :python import vim
Overview > Overview >vim
:py print "Hello" # displays a message :py print "Hello" # displays a message
:py vim.command(cmd) # execute an Ex command :py vim.command(cmd) # execute an Ex command
:py w = vim.windows[n] # gets window "n" :py w = vim.windows[n] # gets window "n"
@@ -166,10 +167,10 @@ Methods of the "vim" module
vim.command(str) *python-command* vim.command(str) *python-command*
Executes the vim (ex-mode) command str. Returns None. Executes the vim (ex-mode) command str. Returns None.
Examples: > Examples: >vim
:py vim.command("set tw=72") :py vim.command("set tw=72")
:py vim.command("%s/aaa/bbb/g") :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): def normal(str):
vim.command("normal "+str) vim.command("normal "+str)
# Note the use of single quotes to delimit a string containing # Note the use of single quotes to delimit a string containing
@@ -177,7 +178,7 @@ vim.command(str) *python-command*
normal('"a2dd"aP') normal('"a2dd"aP')
< *E659* < *E659*
The ":python" command cannot be used recursively with Python 2.2 and 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'") :py vim.command("python print 'Hello again Python'")
vim.eval(str) *python-eval* 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 list if the Vim expression evaluates to a Vim list
- a dictionary if the Vim expression evaluates to a Vim dictionary - a dictionary if the Vim expression evaluates to a Vim dictionary
Dictionaries and lists are recursively expanded. Dictionaries and lists are recursively expanded.
Examples: > Examples: >vim
:py text_width = vim.eval("&tw") :py text_width = vim.eval("&tw")
:py str = vim.eval("12+12") # NB result is a string! Use :py str = vim.eval("12+12") # NB result is a string! Use
# string.atoi() to convert to # string.atoi() to convert to
@@ -215,7 +216,7 @@ Error object of the "vim" module
vim.error *python-error* vim.error *python-error*
Upon encountering a Vim error, Python raises an exception of type Upon encountering a Vim error, Python raises an exception of type
vim.error. vim.error.
Example: > Example: >python
try: try:
vim.command("put a") vim.command("put a")
except vim.error: except vim.error:
@@ -229,7 +230,7 @@ Constants of the "vim" module
vim.buffers *python-buffers* vim.buffers *python-buffers*
A mapping object providing access to the list of vim buffers. The 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 = vim.buffers[i] # Indexing (read-only)
:py b in vim.buffers # Membership test :py b in vim.buffers # Membership test
:py n = len(vim.buffers) # Number of elements :py n = len(vim.buffers) # Number of elements
@@ -237,7 +238,7 @@ vim.buffers *python-buffers*
< <
vim.windows *python-windows* vim.windows *python-windows*
A sequence object providing access to the list of vim windows. The 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 = vim.windows[i] # Indexing (read-only)
:py w in vim.windows # Membership test :py w in vim.windows # Membership test
:py n = len(vim.windows) # Number of elements :py n = len(vim.windows) # Number of elements
@@ -251,7 +252,7 @@ vim.windows *python-windows*
vim.tabpages *python-tabpages* vim.tabpages *python-tabpages*
A sequence object providing access to the list of vim tab pages. The 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 = vim.tabpages[i] # Indexing (read-only)
:py t in vim.tabpages # Membership test :py t in vim.tabpages # Membership test
:py n = len(vim.tabpages) # Number of elements :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 switching to given buffer, window or tab page. It is the only way to
switch UI objects in python: you can't assign to switch UI objects in python: you can't assign to
|python-tabpage|.window attribute. To switch without triggering |python-tabpage|.window attribute. To switch without triggering
autocommands use > autocommands use >vim
py << EOF py << EOF
saved_eventignore = vim.options['eventignore'] saved_eventignore = vim.options['eventignore']
vim.options['eventignore'] = 'all' 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 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'. {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 from imp import find_module, load_module
import vim import vim
@@ -461,12 +462,12 @@ The buffer object methods are:
numbers s and e |inclusive|. numbers s and e |inclusive|.
Note that when adding a line it must not contain a line break character '\n'. 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()) :py b.append(f.readlines())
Buffer object type is available using "Buffer" attribute of vim module. 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 print b.name # write the buffer file name
:py b[0] = "hello!!!" # replace the top line :py b[0] = "hello!!!" # replace the top line
:py b[:] = None # delete the whole buffer :py b[:] = None # delete the whole buffer
@@ -605,10 +606,10 @@ variants explicitly if Python 3 is required.
{script} {script}
{endmarker} {endmarker}
The `:py3` and `:python3` commands work similar to `:python`. A 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") :py3 print("Hello")
< <
To see what version of Python you have: > To see what version of Python you have: >vim
:py3 import sys :py3 import sys
:py3 print(sys.version) :py3 print(sys.version)
< *:py3file* < *:py3file*
@@ -619,11 +620,12 @@ variants explicitly if Python 3 is required.
The `:py3do` command works similar to `:pydo`. The `:py3do` command works similar to `:pydo`.
*E880* *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!") :py vim.command("qall!")
< <
*has-python* *has-python*
You can test if Python is available with: > You can test if Python is available with: >vim
if has('pythonx') if has('pythonx')
echo 'there is Python' echo 'there is Python'
endif 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. all these commands are now synonymous to their "python3" equivalents.
*:pyx* *:pythonx* *: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") :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 import sys
:pyx print(sys.version) :pyx print(sys.version)
< <
@@ -656,7 +658,7 @@ To see what version of Python is being used: >
`:pyxdo` works the same as `:py3do`. `:pyxdo` works the same as `:py3do`.
*has-pythonx* *has-pythonx*
To check if `pyx*` functions and commands are available: > To check if `pyx*` functions and commands are available: >vim
if has('pythonx') if has('pythonx')
echo 'pyx* commands are available. (Python ' .. &pyx .. ')' echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
endif endif

View File

@@ -408,12 +408,12 @@ the ":map" command. The rules are:
The <> notation uses <lt> to escape the special meaning of key names. Using a 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. 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> \<Home>
:imap <C-H> <lt>Home> :imap <C-H> <lt>Home>
The first one only works when the 'B' flag is not in 'cpoptions'. The second The first one only works when the 'B' flag is not in 'cpoptions'. The second
one always works. 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> :map <C-L> <lt>lt>
The notation can be used in a double quoted strings, using "\<" at the start, The notation can be used in a double quoted strings, using "\<" at the start,

View File

@@ -30,7 +30,7 @@ Usage *job-control-usage*
To control jobs, use the "job…" family of functions: |jobstart()|, To control jobs, use the "job…" family of functions: |jobstart()|,
|jobstop()|, etc. |jobstop()|, etc.
Example: > Example: >vim
function! s:OnEvent(job_id, data, event) dict function! s:OnEvent(job_id, data, event) dict
if a:event == 'stdout' if a:event == 'stdout'
@@ -51,7 +51,7 @@ Example: >
let job1 = jobstart(['bash'], extend({'shell': 'shell 1'}, s:callbacks)) 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)) 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 nvim -u ~/foo.vim
< <
Description of what happens: 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 will not trigger the on_stdout/on_stderr callback (but if the process
ends, the on_exit callback will be invoked). ends, the on_exit callback will be invoked).
For example, "ruby -e" buffers output, so small strings will be 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) function! Receive(job_id, data, event)
echom printf('%s: %s',a:event,string(a:data)) echom printf('%s: %s',a:event,string(a:data))
endfunction endfunction
@@ -92,7 +92,7 @@ Arguments passed to on_exit callback:
- `abc\nefg` may arrive as `['abc', '']`, `['efg']` or `['abc']`, - `abc\nefg` may arrive as `['abc', '']`, `['efg']` or `['abc']`,
`['','efg']`, or even `['ab']`, `['c','efg']`. `['','efg']`, or even `['ab']`, `['c','efg']`.
Easy way to deal with this: initialize a list as `['']`, then append Easy way to deal with this: initialize a list as `['']`, then append
to it as follows: > to it as follows: >vim
let s:chunks = [''] let s:chunks = ['']
func! s:on_stdout(job_id, data, event) dict func! s:on_stdout(job_id, data, event) dict
let s:chunks[-1] .= a:data[0] 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 |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 = {} let Shell = {}
@@ -129,16 +129,16 @@ The above example could be written in this "object-oriented" style: >
let instance = Shell.new('bomb', let instance = Shell.new('bomb',
\ 'for i in $(seq 9 -1 1); do echo $i 1>&$((i % 2 + 1)); sleep 1; done') \ '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, "ls\n")
:call chansend(job1, "invalid-command\n") :call chansend(job1, "invalid-command\n")
:call chansend(job1, "exit\n") :call chansend(job1, "exit\n")
< <
A job may be killed with |jobstop()|: > A job may be killed with |jobstop()|: >vim
:call jobstop(job1) :call jobstop(job1)
< <
A job may be killed at any time with the |jobstop()| function: A job may be killed at any time with the |jobstop()| function:
> >vim
:call jobstop(job1) :call jobstop(job1)
< <
Individual streams can be closed without killing the job, see |chanclose()|. Individual streams can be closed without killing the job, see |chanclose()|.

View File

@@ -6,7 +6,7 @@
The `vim.lsp` Lua module is a framework for building LSP plugins. 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()|. 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)) :lua print(vim.inspect(vim.lsp))
< 3. See |lsp-extension-example| for a full example. < 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. 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. 4. Attach the buffer to the client for that root directory.
> >lua
-- Some path manipulation utilities -- Some path manipulation utilities
local function is_dir(filename) local function is_dir(filename)
local stat = vim.loop.fs_stat(filename) local stat = vim.loop.fs_stat(filename)

View File

@@ -33,7 +33,7 @@ Follow these steps to get LSP features:
2. Configure the LSP client per language server. 2. Configure the LSP client per language server.
A minimal example: A minimal example:
> >lua
vim.lsp.start({ vim.lsp.start({
name = 'my-server-name', name = 'my-server-name',
cmd = {'name-of-language-server-executable'}, cmd = {'name-of-language-server-executable'},
@@ -44,7 +44,7 @@ Follow these steps to get LSP features:
3. Configure keymaps and autocmds to utilize LSP features. 3. Configure keymaps and autocmds to utilize LSP features.
See |lsp-config|. See |lsp-config|.
<
*lsp-config* *lsp-config*
Starting a LSP client will automatically report diagnostics via Starting a LSP client will automatically report diagnostics via
@@ -66,7 +66,7 @@ language server supports the functionality.
To use other LSP features like hover, rename, etc. you can setup some 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 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: ensure they're only active if there is a LSP client running. An example:
> >lua
vim.api.nvim_create_autocmd('LspAttach', { vim.api.nvim_create_autocmd('LspAttach', {
callback = function(args) callback = function(args)
vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf }) 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 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 keymaps if the language server supports a feature, you can guard the keymap
calls behind capability checks: calls behind capability checks:
> >lua
vim.api.nvim_create_autocmd('LspAttach', { vim.api.nvim_create_autocmd('LspAttach', {
callback = function(args) callback = function(args)
local client = vim.lsp.get_client_by_id(args.data.client_id) 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 To learn what capabilities are available you can run the following command in
a buffer with a started LSP client: a buffer with a started LSP client:
> >vim
:lua =vim.lsp.get_active_clients()[1].server_capabilities :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* FAQ *lsp-faq*
- Q: How to force-reload LSP? - 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()) :lua vim.lsp.stop_client(vim.lsp.get_active_clients())
:edit :edit
- Q: Why isn't completion working? - Q: Why isn't completion working?
A: In the buffer where you want to use LSP, check that 'omnifunc' is set to 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? :verbose set omnifunc?
@@ -129,7 +129,7 @@ FAQ *lsp-faq*
A: Check if the function has an `async` parameter and set the value to A: Check if the function has an `async` parameter and set the value to
false. false.
E.g. code formatting: > E.g. code formatting: >vim
" Auto-format *.rs (rust) files prior to saving them " Auto-format *.rs (rust) files prior to saving them
" (async = false is the default for format) " (async = false is the default for format)
@@ -162,7 +162,7 @@ to the given buffer. |lsp-buf|
LSP request/response handlers are implemented as Lua functions (see LSP request/response handlers are implemented as Lua functions (see
|lsp-handler|). The |vim.lsp.handlers| table defines default handlers used |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))) :lua print(vim.inspect(vim.tbl_keys(vim.lsp.handlers)))
< <
@@ -291,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()|, To configure the behavior of |vim.lsp.diagnostic.on_publish_diagnostics()|,
consider the following example, where a new |lsp-handler| is created using 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.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
vim.lsp.diagnostic.on_publish_diagnostics, { vim.lsp.diagnostic.on_publish_diagnostics, {
@@ -301,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 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.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
vim.lsp.diagnostic.on_publish_diagnostics, { vim.lsp.diagnostic.on_publish_diagnostics, {
@@ -311,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 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 { vim.lsp.start_client {
..., -- Other configuration omitted. ..., -- Other configuration omitted.
@@ -325,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 { require('lspconfig').rust_analyzer.setup {
handlers = { handlers = {
@@ -340,7 +341,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method
< <
Some handlers do not have an explicitly named handler function (such as Some handlers do not have an explicitly named handler function (such as
||vim.lsp.diagnostic.on_publish_diagnostics()|). To override these, first ||vim.lsp.diagnostic.on_publish_diagnostics()|). To override these, first
create a reference to the existing handler: > create a reference to the existing handler: >lua
local on_references = vim.lsp.handlers["textDocument/references"] local on_references = vim.lsp.handlers["textDocument/references"]
vim.lsp.handlers["textDocument/references"] = vim.lsp.with( vim.lsp.handlers["textDocument/references"] = vim.lsp.with(
@@ -357,14 +358,14 @@ Handlers can be set by:
vim.lsp.handlers is a global table that contains the default mapping of vim.lsp.handlers is a global table that contains the default mapping of
|lsp-method| names to |lsp-handlers|. |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 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. This will set the |lsp-handler| as the default handler for this server.
For example: > For example: >lua
vim.lsp.start_client { vim.lsp.start_client {
..., -- Other configuration omitted. ..., -- Other configuration omitted.
@@ -376,7 +377,7 @@ Handlers can be set by:
- The {handler} parameter for |vim.lsp.buf_request()|. - The {handler} parameter for |vim.lsp.buf_request()|.
This will set the |lsp-handler| ONLY for the current request. This will set the |lsp-handler| ONLY for the current request.
For example: > For example: >lua
vim.lsp.buf_request( vim.lsp.buf_request(
0, 0,
@@ -403,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 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 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.Full == 1
vim.lsp.protocol.TextDocumentSyncKind[1] == "Full" vim.lsp.protocol.TextDocumentSyncKind[1] == "Full"
@@ -426,7 +427,7 @@ For the format of the notification message, see:
- `context` table|nil. `ctx` from |lsp-handler| - `context` table|nil. `ctx` from |lsp-handler|
This table can be used with vim.fn.setqflist or vim.fn.setloclist. E.g.: This table can be used with vim.fn.setqflist or vim.fn.setloclist. E.g.:
> >lua
local function on_list(options) local function on_list(options)
vim.fn.setqflist({}, ' ', options) vim.fn.setqflist({}, ' ', options)
vim.api.nvim_command('cfirst') vim.api.nvim_command('cfirst')
@@ -436,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}) vim.lsp.buf.references(nil, {on_list=on_list})
< <
If you prefer loclist do something like this: If you prefer loclist do something like this:
> >lua
local function on_list(options) local function on_list(options)
vim.fn.setloclist(0, {}, ' ', options) vim.fn.setloclist(0, {}, ' ', options)
vim.api.nvim_command('lopen') vim.api.nvim_command('lopen')
@@ -487,7 +488,7 @@ EVENTS *lsp-events*
*LspAttach* *LspAttach*
After an LSP client attaches to a buffer. The |autocmd-pattern| is the 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 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", { vim.api.nvim_create_autocmd("LspAttach", {
callback = function(args) callback = function(args)
@@ -505,7 +506,7 @@ callback in the "data" table. Example: >
*LspDetach* *LspDetach*
Just before an LSP client detaches from a buffer. The |autocmd-pattern| is the 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 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", { vim.api.nvim_create_autocmd("LspDetach", {
callback = function(args) callback = function(args)
@@ -525,7 +526,7 @@ LspRequest *LspRequest*
After a change to the active set of pending LSP requests. See {requests} After a change to the active set of pending LSP requests. See {requests}
in |vim.lsp.client|. in |vim.lsp.client|.
Example: > Example: >vim
autocmd User LspProgressUpdate redrawstatus autocmd User LspProgressUpdate redrawstatus
autocmd User LspRequest redrawstatus autocmd User LspRequest redrawstatus
< <

View File

@@ -361,17 +361,17 @@ Vimscript v:lua interface *v:lua-call*
From Vimscript the special `v:lua` prefix can be used to call Lua functions From Vimscript the special `v:lua` prefix can be used to call Lua functions
which are global or accessible from global tables. The expression >vim which are global or accessible from global tables. The expression >vim
v:lua.func(arg1, arg2) call v:lua.func(arg1, arg2)
is equivalent to the Lua chunk >lua is equivalent to the Lua chunk >lua
return func(...) return func(...)
where the args are converted to Lua values. The expression >vim where the args are converted to Lua values. The expression >vim
v:lua.somemod.func(args) call v:lua.somemod.func(args)
is equivalent to the Lua chunk >lua is equivalent to the Lua chunk >lua
return somemod.func(...) return somemod.func(...)
In addition, functions of packages can be accessed like >vim In addition, functions of packages can be accessed like >vim
v:lua.require'mypack'.func(arg1, arg2) call v:lua.require'mypack'.func(arg1, arg2)
v:lua.require'mypack.submod'.func(arg1, arg2) call v:lua.require'mypack.submod'.func(arg1, arg2)
Note: Only single quote form without parens is allowed. Using Note: Only single quote form without parens is allowed. Using
`require"mypack"` or `require('mypack')` as prefixes do NOT work (the latter `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 is still valid as a function call of itself, in case require returns a useful
@@ -379,7 +379,7 @@ value).
The `v:lua` prefix may be used to call Lua functions as |method|s. For The `v:lua` prefix may be used to call Lua functions as |method|s. For
example: >vim example: >vim
arg1->v:lua.somemod.func(arg2) :eval arg1->v:lua.somemod.func(arg2)
< <
You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc. You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc.
For example consider the following Lua omnifunc handler: >lua For example consider the following Lua omnifunc handler: >lua
@@ -646,20 +646,19 @@ vim.diff({a}, {b}, {opts}) *vim.diff()*
Run diff on strings {a} and {b}. Any indices returned by this function, Run diff on strings {a} and {b}. Any indices returned by this function,
either directly or via callback arguments, are 1-based. either directly or via callback arguments, are 1-based.
Examples: > Examples: >lua
vim.diff('a\n', 'b\nc\n') vim.diff('a\n', 'b\nc\n')
=> -- =>
@@ -1 +1,2 @@ -- @@ -1 +1,2 @@
-a -- -a
+b -- +b
+c -- +c
vim.diff('a\n', 'b\nc\n', {result_type = 'indices'}) vim.diff('a\n', 'b\nc\n', {result_type = 'indices'})
=> -- =>
{ -- {
{1, 1, 1, 2} -- {1, 1, 1, 2}
} -- }
< <
Parameters: ~ Parameters: ~
• {a} First string to compare • {a} First string to compare
@@ -730,13 +729,12 @@ vim.spell.check({str}) *vim.spell.check()*
'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to
the buffer. Consider calling this with |nvim_buf_call()|. the buffer. Consider calling this with |nvim_buf_call()|.
Example: > Example: >lua
vim.spell.check("the quik brown fox") vim.spell.check("the quik brown fox")
=> -- =>
{ -- {
{'quik', 'bad', 4} -- {'quik', 'bad', 4}
} -- }
< <
Parameters: ~ Parameters: ~
• {str} String to spell check. • {str} String to spell check.
@@ -1171,37 +1169,37 @@ offers object-oriented method for adding and removing entries.
Examples: ~ Examples: ~
The following methods of setting a list-style option are equivalent: The following methods of setting a list-style option are equivalent:
In Vimscript: In Vimscript: >vim
`set wildignore=*.o,*.a,__pycache__` set wildignore=*.o,*.a,__pycache__
<
In Lua using `vim.o`: In Lua using `vim.o`: >lua
`vim.o.wildignore = '*.o,*.a,__pycache__'` vim.o.wildignore = '*.o,*.a,__pycache__'
<
In Lua using `vim.opt`: In Lua using `vim.opt`: >lua
`vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }` vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
<
To replicate the behavior of |:set+=|, use: > To replicate the behavior of |:set+=|, use: >lua
vim.opt.wildignore:append { "*.pyc", "node_modules" } vim.opt.wildignore:append { "*.pyc", "node_modules" }
< <
To replicate the behavior of |:set^=|, use: > To replicate the behavior of |:set^=|, use: >lua
vim.opt.wildignore:prepend { "new_first_value" } vim.opt.wildignore:prepend { "new_first_value" }
< <
To replicate the behavior of |:set-=|, use: > To replicate the behavior of |:set-=|, use: >lua
vim.opt.wildignore:remove { "node_modules" } vim.opt.wildignore:remove { "node_modules" }
< <
The following methods of setting a map-style option are equivalent: The following methods of setting a map-style option are equivalent:
In Vimscript: In Vimscript: >vim
`set listchars=space:_,tab:>~` set listchars=space:_,tab:>~
<
In Lua using `vim.o`: In Lua using `vim.o`: >lua
`vim.o.listchars = 'space:_,tab:>~'` vim.o.listchars = 'space:_,tab:>~'
<
In Lua using `vim.opt`: In Lua using `vim.opt`: >lua
`vim.opt.listchars = { space = '_', tab = '>~' }` vim.opt.listchars = { space = '_', tab = '>~' }
<
Note that |vim.opt| returns an `Option` object, not the value of the option, Note that |vim.opt| returns an `Option` object, not the value of the option,
which is accessed through |vim.opt:get()|: which is accessed through |vim.opt:get()|:
@@ -1209,15 +1207,15 @@ which is accessed through |vim.opt:get()|:
Examples: ~ Examples: ~
The following methods of getting a list-style option are equivalent: The following methods of getting a list-style option are equivalent:
In Vimscript: In Vimscript: >vim
`echo wildignore` echo wildignore
<
In Lua using `vim.o`: In Lua using `vim.o`: >lua
`print(vim.o.wildignore)` print(vim.o.wildignore)
<
In Lua using `vim.opt`: In Lua using `vim.opt`: >lua
`vim.pretty_print(vim.opt.wildignore:get())` vim.pretty_print(vim.opt.wildignore:get())
<
In any of the above examples, to replicate the behavior |:setlocal|, use 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_local`. Additionally, to replicate the behavior of |:setglobal|, use
@@ -1272,28 +1270,28 @@ Option:append(value)
Append a value to string-style options. See |:set+=| Append a value to string-style options. See |:set+=|
These are equivalent: These are equivalent: >lua
`vim.opt.formatoptions:append('j')` vim.opt.formatoptions:append('j')
`vim.opt.formatoptions = vim.opt.formatoptions + 'j'` vim.opt.formatoptions = vim.opt.formatoptions + 'j'
<
*vim.opt:prepend()* *vim.opt:prepend()*
Option:prepend(value) Option:prepend(value)
Prepend a value to string-style options. See |:set^=| Prepend a value to string-style options. See |:set^=|
These are equivalent: These are equivalent: >lua
`vim.opt.wildignore:prepend('*.o')` vim.opt.wildignore:prepend('*.o')
`vim.opt.wildignore = vim.opt.wildignore ^ '*.o'` vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
<
*vim.opt:remove()* *vim.opt:remove()*
Option:remove(value) Option:remove(value)
Remove a value from string-style options. See |:set-=| Remove a value from string-style options. See |:set-=|
These are equivalent: These are equivalent: >lua
`vim.opt.wildignore:remove('*.pyc')` vim.opt.wildignore:remove('*.pyc')
`vim.opt.wildignore = vim.opt.wildignore - '*.pyc'` vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
<
============================================================================== ==============================================================================
Lua module: vim *lua-vim* Lua module: vim *lua-vim*

File diff suppressed because it is too large Load Diff

View File

@@ -28,7 +28,7 @@ TCP Echo Server Example~
Here is a small example showing a TCP echo server: Here is a small example showing a TCP echo server:
> >lua
local uv = vim.loop local uv = vim.loop
local server = uv.new_tcp() local server = uv.new_tcp()
@@ -250,7 +250,7 @@ uv.loop_configure({option}, {...}) *uv.loop_configure()*
An example of a valid call to this function is: An example of a valid call to this function is:
> >lua
uv.loop_configure("block_signal", "sigprof") uv.loop_configure("block_signal", "sigprof")
< <
@@ -343,7 +343,7 @@ uv.walk({callback}) *uv.walk()*
Returns: Nothing. Returns: Nothing.
> >lua
-- Example usage of uv.walk to close all handles that -- Example usage of uv.walk to close all handles that
-- aren't already closing. -- aren't already closing.
uv.walk(function (handle) uv.walk(function (handle)
@@ -613,7 +613,7 @@ uv.new_timer() *uv.new_timer()*
Returns: `uv_timer_t userdata` or `fail` Returns: `uv_timer_t userdata` or `fail`
> >lua
-- Creating a simple setTimeout wrapper -- Creating a simple setTimeout wrapper
local function setTimeout(timeout, callback) local function setTimeout(timeout, callback)
local timer = uv.new_timer() 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 Prepare handles will run the given callback once per loop iteration, right
before polling for I/O. before polling for I/O.
> >lua
local prepare = uv.new_prepare() local prepare = uv.new_prepare()
prepare:start(function() prepare:start(function()
print("Before I/O polling") 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 Check handles will run the given callback once per loop iteration, right after
polling for I/O. polling for I/O.
> >lua
local check = uv.new_check() local check = uv.new_check()
check:start(function() check:start(function()
print("After I/O polling") 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 WARNING: Despite the name, idle handles will get their callbacks called on
every loop iteration, not when the loop is actually "idle". every loop iteration, not when the loop is actually "idle".
> >lua
local idle = uv.new_idle() local idle = uv.new_idle()
idle:start(function() idle:start(function()
print("Before I/O polling, no blocking") 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 Async handles allow the user to "wakeup" the event loop and get a callback
called from another thread. called from another thread.
> >lua
local async local async
async = uv.new_async(function() async = uv.new_async(function()
print("async operation ran") print("async operation ran")
@@ -1062,7 +1062,7 @@ Unix Notes:
will lead to unpredictable behavior and is strongly discouraged. Future will lead to unpredictable behavior and is strongly discouraged. Future
versions of libuv may simply reject them. versions of libuv may simply reject them.
> >lua
-- Create a new signal handler -- Create a new signal handler
local signal = uv.new_signal() local signal = uv.new_signal()
-- Define a handler function -- 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 permissions to use the setuid or setgid specified, or not
having enough memory to allocate for the new process. having enough memory to allocate for the new process.
> >lua
local stdin = uv.new_pipe() local stdin = uv.new_pipe()
local stdout = uv.new_pipe() local stdout = uv.new_pipe()
local stderr = uv.new_pipe() local stderr = uv.new_pipe()
@@ -1358,7 +1358,7 @@ uv.accept({stream}, {client_stream}) *uv.accept()*
Returns: `0` or `fail` Returns: `0` or `fail`
> >lua
server:listen(128, function (err) server:listen(128, function (err)
local client = uv.new_tcp() local client = uv.new_tcp()
server:accept(client) server:accept(client)
@@ -1382,7 +1382,7 @@ uv.read_start({stream}, {callback}) *uv.read_start()*
Returns: `0` or `fail` Returns: `0` or `fail`
> >lua
stream:read_start(function (err, chunk) stream:read_start(function (err, chunk)
if err then if err then
-- handle read error -- handle read error
@@ -1690,7 +1690,7 @@ uv.tcp_connect({tcp}, {host}, {port}, {callback}) *uv.tcp_connect()*
Returns: `uv_connect_t userdata` or `fail` Returns: `uv_connect_t userdata` or `fail`
> >lua
local client = uv.new_tcp() local client = uv.new_tcp()
client:connect("127.0.0.1", 8080, function (err) client:connect("127.0.0.1", 8080, function (err)
-- check error and carry on. -- check error and carry on.
@@ -1755,7 +1755,7 @@ uv.socketpair([{socktype}, [{protocol}, [{flags1}, [{flags2}]]]])
Returns: `table` or `fail` Returns: `table` or `fail`
- `[1, 2]` : `integer` (file descriptor) - `[1, 2]` : `integer` (file descriptor)
> >lua
-- Simple read/write with tcp -- Simple read/write with tcp
local fds = uv.socketpair(nil, nil, {nonblock=true}, {nonblock=true}) 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 Pipe handles provide an abstraction over local domain sockets on Unix and
named pipes on Windows. named pipes on Windows.
> >lua
local pipe = uv.new_pipe(false) local pipe = uv.new_pipe(false)
pipe:bind('/tmp/sock.test') pipe:bind('/tmp/sock.test')
@@ -1959,7 +1959,7 @@ uv.pipe({read_flags}, {write_flags}) *uv.pipe()*
- `read` : `integer` (file descriptor) - `read` : `integer` (file descriptor)
- `write` : `integer` (file descriptor) - `write` : `integer` (file descriptor)
> >lua
-- Simple read/write with pipe_open -- Simple read/write with pipe_open
local fds = uv.pipe({nonblock=true}, {nonblock=true}) 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. TTY handles represent a stream for the console.
> >lua
-- Simple echo program -- Simple echo program
local stdin = uv.new_tty(0, true) local stdin = uv.new_tty(0, true)
local stdout = uv.new_tty(1, false) local stdout = uv.new_tty(1, false)
@@ -2537,7 +2537,7 @@ FS call.
Synchronous and asynchronous versions of `readFile` (with naive error Synchronous and asynchronous versions of `readFile` (with naive error
handling) are implemented below as an example: handling) are implemented below as an example:
> >lua
local function readFileSync(path) local function readFileSync(path)
local fd = assert(uv.fs_open(path, "r", 438)) local fd = assert(uv.fs_open(path, "r", 438))
local stat = assert(uv.fs_fstat(fd)) local stat = assert(uv.fs_fstat(fd))
@@ -2550,7 +2550,7 @@ handling) are implemented below as an example:
print("synchronous read", data) print("synchronous read", data)
< <
> >lua
local function readFile(path, callback) local function readFile(path, callback)
uv.fs_open(path, "r", 438, function(err, fd) uv.fs_open(path, "r", 438, function(err, fd)
assert(not err, err) assert(not err, err)
@@ -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 notified in the loop thread. This threadpool is internally used to run all
file system operations, as well as `getaddrinfo` and `getnameinfo` requests. file system operations, as well as `getaddrinfo` and `getnameinfo` requests.
> >lua
local function work_callback(a, b) local function work_callback(a, b)
return a + b return a + b
end end

View File

@@ -9,7 +9,7 @@ Nvim *nvim* *nvim-intro*
Nvim is based on Vim by Bram Moolenaar. Nvim is based on Vim by Bram Moolenaar.
If you already use Vim see |nvim-from-vim| for a quickstart. 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> :Tutor<Enter>
@@ -22,12 +22,12 @@ Nvim is emphatically a fork of Vim, not a clone: compatibility with Vim
============================================================================== ==============================================================================
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') :call mkdir(stdpath('config'), 'p')
:exe 'edit '.stdpath('config').'/init.vim' :exe 'edit '.stdpath('config').'/init.vim'
2. Add these contents to the file: > 2. Add these contents to the file: >vim
set runtimepath^=~/.vim runtimepath+=~/.vim/after set runtimepath^=~/.vim runtimepath+=~/.vim/after
let &packpath = &runtimepath let &packpath = &runtimepath
@@ -43,19 +43,19 @@ Your Vim configuration might not be entirely Nvim-compatible (see
because mouse support is always enabled if possible. If you use the same 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 |vimrc| for Vim and Nvim you could guard |'ttymouse'| in your configuration
like so: like so:
> >vim
if !has('nvim') if !has('nvim')
set ttymouse=xterm2 set ttymouse=xterm2
endif endif
And for Nvim-specific configuration, you can do this: And for Nvim-specific configuration, you can do this:
> >vim
if has('nvim') if has('nvim')
tnoremap <Esc> <C-\><C-n> tnoremap <Esc> <C-\><C-n>
endif endif
For a more granular approach use |exists()|: For a more granular approach use |exists()|:
> >vim
if exists(':tnoremap') if exists(':tnoremap')
tnoremap <Esc> <C-\><C-n> tnoremap <Esc> <C-\><C-n>
endif endif
@@ -67,7 +67,7 @@ for more information.
Because Nvim follows the XDG |base-directories| standard, configuration on Because Nvim follows the XDG |base-directories| standard, configuration on
Windows is stored in ~/AppData instead of ~/.config. But you can still share Windows is stored in ~/AppData instead of ~/.config. But you can still share
the same Nvim configuration on all of your machines, by creating the same Nvim configuration on all of your machines, by creating
~/AppData/Local/nvim/init.vim containing just this line: > ~/AppData/Local/nvim/init.vim containing just this line: >vim
source ~/.config/nvim/init.vim source ~/.config/nvim/init.vim
============================================================================== ==============================================================================

View File

@@ -27,12 +27,12 @@ There are several ways to create a terminal buffer:
- Run the |:terminal| command. - Run the |:terminal| command.
- Call the |nvim_open_term()| or |termopen()| function. - Call the |nvim_open_term()| or |termopen()| function.
- Edit a "term://" buffer. Examples: > - Edit a "term://" buffer. Examples: >vim
:edit term://bash :edit term://bash
:vsplit term://top :vsplit term://top
< Note: To open a "term://" buffer from an autocmd, the |autocmd-nested| < 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 autocmd VimEnter * ++nested split term://sh
< (This is only mentioned for reference; use |:terminal| instead.) < (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 Terminal-mode has its own |:tnoremap| namespace for mappings, this can be used
to automate any terminal interaction. 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> :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' :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-h> <C-\><C-N><C-w>h
:tnoremap <A-j> <C-\><C-N><C-w>j :tnoremap <A-j> <C-\><C-N><C-w>j
:tnoremap <A-k> <C-\><C-N><C-w>k :tnoremap <A-k> <C-\><C-N><C-w>k
@@ -109,7 +109,7 @@ global configuration.
- 'list' is disabled - 'list' is disabled
- 'wrap' 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 au TermOpen * setlocal list
TERMINAL COLORS ~ TERMINAL COLORS ~
@@ -117,7 +117,7 @@ TERMINAL COLORS ~
The `{g,b}:terminal_color_x` variables control the terminal color palette, 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 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. 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_4 = '#ff0000'
let g:terminal_color_5 = 'green' let g:terminal_color_5 = 'green'
Only works for RGB UIs (see 'termguicolors'); for 256-color terminals the 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 Terminal buffers maintain some buffer-local variables and options. The values
are initialized before TermOpen, so you can use them in a local 'statusline'. are initialized before TermOpen, so you can use them in a local 'statusline'.
Example: > Example: >vim
:autocmd TermOpen * setlocal statusline=%{b:term_title} :autocmd TermOpen * setlocal statusline=%{b:term_title}
- *b:term_title* Terminal title (user-writable), typically displayed in the - *b:term_title* Terminal title (user-writable), typically displayed in the
@@ -141,10 +141,10 @@ Example: >
input to the terminal. input to the terminal.
- The |TermClose| event gives the terminal job exit code in the |v:event| - 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 "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 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 let running = jobwait([&channel], 0)[0] == -1
============================================================================== ==============================================================================
@@ -156,11 +156,11 @@ Vim this also works remotely over an ssh connection.
Starting ~ Starting ~
*termdebug-starting* *termdebug-starting*
Load the plugin with this command: > Load the plugin with this command: >vim
packadd termdebug packadd termdebug
< *:Termdebug* < *:Termdebug*
To start debugging use `:Termdebug` or `:TermdebugCommand` followed by the To start debugging use `:Termdebug` or `:TermdebugCommand` followed by the
command name, for example: > command name, for example: >vim
:Termdebug vim :Termdebug vim
This opens two windows: This opens two windows:
@@ -189,16 +189,16 @@ Only one debugger can be active at a time.
*:TermdebugCommand* *:TermdebugCommand*
If you want to give specific commands to the command being debugged, you can If you want to give specific commands to the command being debugged, you can
use the `:TermdebugCommand` command followed by the command name and use the `:TermdebugCommand` command followed by the command name and
additional parameters. > additional parameters. >vim
:TermdebugCommand vim --clean -c ':set nu' :TermdebugCommand vim --clean -c ':set nu'
Both the `:Termdebug` and `:TermdebugCommand` support an optional "!" bang Both the `:Termdebug` and `:TermdebugCommand` support an optional "!" bang
argument to start the command right away, without pausing at the gdb window 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 :TermdebugCommand! vim --clean
To attach gdb to an already running executable or use a core file, pass extra 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 core
:Termdebug vim 98343 :Termdebug vim 98343
@@ -212,7 +212,7 @@ Start in the Vim "src" directory and build Vim: >
% make % make
Start Vim: > Start Vim: >
% ./vim % ./vim
Load the termdebug plugin and start debugging Vim: > Load the termdebug plugin and start debugging Vim: >vim
:packadd termdebug :packadd termdebug
:Termdebug vim :Termdebug vim
You should now have three windows: You should now have three windows:
@@ -223,7 +223,7 @@ You should now have three windows:
Put focus on the gdb window and type: > Put focus on the gdb window and type: >
break ex_help break ex_help
run 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 :help gui
Gdb will run into the ex_help breakpoint. The source window now shows the 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 ex_cmds.c file. A red "1 " marker will appear in the signcolumn where the
@@ -329,7 +329,7 @@ Other commands ~
Events ~ Events ~
*termdebug-events* *termdebug-events*
Four autocommands can be used: > Four autocommands can be used: >vim
au User TermdebugStartPre echomsg 'debugging starting' au User TermdebugStartPre echomsg 'debugging starting'
au User TermdebugStartPost echomsg 'debugging started' au User TermdebugStartPost echomsg 'debugging started'
au User TermdebugStopPre echomsg 'debugging stopping' au User TermdebugStopPre echomsg 'debugging stopping'
@@ -360,7 +360,7 @@ Customizing ~
In the past several global variables were used for configuration. These are In the past several global variables were used for configuration. These are
deprecated and using the g:termdebug_config dictionary is preferred. When deprecated and using the g:termdebug_config dictionary is preferred. When
g:termdebug_config exists the other global variables will NOT be used. g:termdebug_config exists the other global variables will NOT be used.
The recommended way is to start with an empty dictionary: > The recommended way is to start with an empty dictionary: >vim
let g:termdebug_config = {} let g:termdebug_config = {}
Then you can add entries to the dictionary as mentioned below. The Then you can add entries to the dictionary as mentioned below. The
@@ -380,23 +380,23 @@ This works slightly differently:
- A separate :terminal window will be opened to run the debugged program in. - A separate :terminal window will be opened to run the debugged program in.
*termdebug_use_prompt* *termdebug_use_prompt*
Prompt mode can be used with: > Prompt mode can be used with: >vim
let g:termdebug_config['use_prompt'] = 1 let g:termdebug_config['use_prompt'] = 1
If there is no g:termdebug_config you can use: > If there is no g:termdebug_config you can use: >vim
let g:termdebug_use_prompt = 1 let g:termdebug_use_prompt = 1
< <
*termdebug_map_K* *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 let g:termdebug_config['map_K'] = 0
If there is no g:termdebug_config you can use: > If there is no g:termdebug_config you can use: >vim
let g:termdebug_map_K = 0 let g:termdebug_map_K = 0
< <
*termdebug_disasm_window* *termdebug_disasm_window*
If you want the Asm window shown by default, set the flag to 1. 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'] = 1
let g:termdebug_config['disasm_window_height'] = 15 let g:termdebug_config['disasm_window_height'] = 15
If there is no g:termdebug_config you can use: > If there is no g:termdebug_config you can use: >vim
let g:termdebug_disasm_window = 15 let g:termdebug_disasm_window = 15
Any value greater than 1 will set the Asm window height to that value. Any value greater than 1 will set the Asm window height to that value.
@@ -418,34 +418,34 @@ GDB command ~
*g:termdebugger* *g:termdebugger*
To change the name of the gdb command, set "debugger" entry in To change the name of the gdb command, set "debugger" entry in
g:termdebug_config or the "g:termdebugger" variable before invoking g:termdebug_config or the "g:termdebugger" variable before invoking
`:Termdebug`: > `:Termdebug`: >vim
let g:termdebug_config['command'] = "mygdb" let g:termdebug_config['command'] = "mygdb"
If there is no g:termdebug_config you can use: > If there is no g:termdebug_config you can use: >vim
let g:termdebugger = "mygdb" 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', '--'] let g:termdebug_config['command'] = ['rr', 'replay', '--']
If there is no g:termdebug_config you can use: > If there is no g:termdebug_config you can use: >vim
let g:termdebugger = ['rr', 'replay', '--'] let g:termdebugger = ['rr', 'replay', '--']
To not use neovim floating windows for previewing variable evaluation, set the 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 let g:termdebug_useFloatingHover = 0
If you are a mouse person, you can also define a mapping using your right 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 click to one of the terminal command like evaluate the variable under the
cursor: > cursor: >vim
nnoremap <RightMouse> :Evaluate<CR> nnoremap <RightMouse> :Evaluate<CR>
or set/unset a breakpoint: > or set/unset a breakpoint: >vim
nnoremap <RightMouse> :Break<CR> nnoremap <RightMouse> :Break<CR>
Several arguments will be added to make gdb work well for the debugger. 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 let g:termdebug_config['command_filter'] = MyDebugFilter
If you do not want the arguments to be added, but you do need to set the 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 let g:termdebug_config['command_add_args'] = MyAddArguments
The function will be called with the list of arguments so far, and a second The function will be called with the list of arguments so far, and a second
argument that is the name of the pty. argument that is the name of the pty.
@@ -475,7 +475,7 @@ When 'background' is "dark":
Shortcuts ~ Shortcuts ~
*termdebug_shortcuts* *termdebug_shortcuts*
You can define your own shortcuts (mappings) to control gdb, that can work in 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> map ,w :call TermDebugSendCommand('where')<CR>
The argument is the gdb command. The argument is the gdb command.
@@ -487,18 +487,18 @@ these entries to the popup menu:
Set breakpoint `:Break` Set breakpoint `:Break`
Clear breakpoint `:Clear` Clear breakpoint `:Clear`
Evaluate `:Evaluate` 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 let g:termdebug_config['popup'] = 0
If there is no g:termdebug_config you can use: > If there is no g:termdebug_config you can use: >vim
let g:termdebug_popup = 0 let g:termdebug_popup = 0
Vim window width ~ Vim window width ~
*termdebug_wide* *termdebug_wide*
To change the width of the Vim window when debugging starts and use a vertical To change the width of the Vim window when debugging starts and use a vertical
split: > split: >vim
let g:termdebug_config['wide'] = 163 let g:termdebug_config['wide'] = 163
If there is no g:termdebug_config you can use: > If there is no g:termdebug_config you can use: >vim
let g:termdebug_wide = 163 let g:termdebug_wide = 163
This will set 'columns' to 163 when `:Termdebug` is used. The value is This will set 'columns' to 163 when `:Termdebug` is used. The value is

View File

@@ -36,7 +36,7 @@ itself).
For Python 3 plugins: For Python 3 plugins:
1. Make sure Python 3.4+ is available in your $PATH. 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 python3 -m pip install --user --upgrade pynvim
The pip `--upgrade` flag ensures that you get the latest version even if 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". Note: The old "neovim" module was renamed to "pynvim".
https://github.com/neovim/neovim/wiki/Following-HEAD#20181118 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 uninstall neovim pynvim
python -m pip install --user --upgrade pynvim python -m pip install --user --upgrade pynvim
@@ -55,11 +55,11 @@ PYTHON PROVIDER CONFIGURATION ~
*g:python3_host_prog* *g:python3_host_prog*
Command to start Python 3 (executable, not directory). Setting this makes Command to start Python 3 (executable, not directory). Setting this makes
startup faster. Useful for working with virtualenvs. Must be set before any 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' let g:python3_host_prog = '/path/to/python3'
< <
*g:loaded_python3_provider* *g:loaded_python3_provider*
To disable Python 3 support: > To disable Python 3 support: >vim
let g:loaded_python3_provider = 0 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 |g:python3_host_prog| so that the "pynvim" package is not required
for each virtualenv. for each virtualenv.
Example using pyenv: > Example using pyenv: >bash
pyenv install 3.4.4 pyenv install 3.4.4
pyenv virtualenv 3.4.4 py3nvim pyenv virtualenv 3.4.4 py3nvim
pyenv activate py3nvim pyenv activate py3nvim
python3 -m pip install pynvim python3 -m pip install pynvim
pyenv which python # Note the path 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' let g:python3_host_prog = '/path/to/py3nvim/bin/python'
See also: https://github.com/zchee/deoplete-jedi/wiki/Setting-up-Python-for-Neovim 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 ~ 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 gem install neovim
Run |:checkhealth| to see if your system is up-to-date. 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 ~ RUBY PROVIDER CONFIGURATION ~
*g:loaded_ruby_provider* *g:loaded_ruby_provider*
To disable Ruby support: > To disable Ruby support: >vim
let g:loaded_ruby_provider = 0 let g:loaded_ruby_provider = 0
< <
*g:ruby_host_prog* *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 project-local Ruby versions (via tools like RVM or rbenv) setting this can
avoid the need to install the "neovim" gem in every project. 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' 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' 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~ 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 cpanm -n Neovim::Ext
Run |:checkhealth| to see if your system is up-to-date. 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~ PERL PROVIDER CONFIGURATION~
*g:loaded_perl_provider* *g:loaded_perl_provider*
To disable Perl support: > To disable Perl support: >vim
:let g:loaded_perl_provider = 0 :let g:loaded_perl_provider = 0
< <
*g:perl_host_prog* *g:perl_host_prog*
Command to start the Perl executable. Must be set before any 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' let g:perl_host_prog = '/path/to/perl'
< <
============================================================================== ==============================================================================
@@ -150,7 +150,7 @@ https://github.com/neovim/node-client/
NODEJS QUICKSTART~ 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 npm install -g neovim
Run |:checkhealth| to see if your system is up-to-date. 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~ NODEJS PROVIDER CONFIGURATION~
*g:loaded_node_provider* *g:loaded_node_provider*
To disable Node.js support: > To disable Node.js support: >vim
:let g:loaded_node_provider = 0 :let g:loaded_node_provider = 0
< <
*g:node_host_prog* *g:node_host_prog*
Command to start the Node.js host. Setting this makes startup faster. 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 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' 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". system clipboard or any other clipboard "backend".
To ALWAYS use the clipboard for ALL operations (instead of interacting with 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 set clipboard+=unnamedplus
See 'clipboard' for details and options. See 'clipboard' for details and options.
@@ -199,7 +199,7 @@ registers. Nvim looks for these clipboard tools, in order of priority:
*g:clipboard* *g:clipboard*
To configure a custom clipboard tool, set g:clipboard to a dictionary. 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 = { let g:clipboard = {
\ 'name': 'myClipboard', \ 'name': 'myClipboard',
@@ -219,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. process has not died the cached selection is applied.
g:clipboard can also use functions (see |lambda|) instead of strings. 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 = { let g:clipboard = {
\ 'name': 'myClipboard', \ 'name': 'myClipboard',
@@ -239,7 +240,7 @@ a list of lines and `regtype` is a register type conforming to |setreg()|.
*clipboard-wsl* *clipboard-wsl*
For Windows WSL, try this g:clipboard definition: For Windows WSL, try this g:clipboard definition:
> >vim
let g:clipboard = { let g:clipboard = {
\ 'name': 'WslClipboard', \ 'name': 'WslClipboard',
\ 'copy': { \ 'copy': {
@@ -283,7 +284,7 @@ many commands. Use the |cmdline-window| if you really want to paste multiple
lines to the cmdline. lines to the cmdline.
You can implement a custom paste handler by redefining |vim.paste()|. You can implement a custom paste handler by redefining |vim.paste()|.
Example: > Example: >lua
vim.paste = (function(lines, phase) vim.paste = (function(lines, phase)
vim.api.nvim_put(lines, 'c', true, true) vim.api.nvim_put(lines, 'c', true, true)

View File

@@ -76,7 +76,7 @@ supplying an external one with entries for the terminal type.
Settings depending on terminal *term-dependent-settings* Settings depending on terminal *term-dependent-settings*
If you want to set terminal-dependent options or mappings, you can do this in 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\)\(-.*\)\?$' if $TERM =~ '^\(rxvt\|screen\|interix\|putty\)\(-.*\)\?$'
set notermguicolors set notermguicolors
@@ -222,9 +222,9 @@ are not in terminfo you must add them by setting "terminal-overrides" in
~/.tmux.conf . ~/.tmux.conf .
See the tmux(1) manual page for the details of how and what to do in the tmux 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' 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' 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 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 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 hi NonText cterm=NONE ctermfg=NONE
This draws the spaces with the default colours and attributes, which allows the 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 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. an #if/#else/#endif block, the selection becomes linewise.
For MS-Windows and xterm the time for double clicking can be set with the 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. '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> :map <2-LeftMouse> :exe "tag " .. expand("<cword>")<CR>
Dragging the mouse with a double click (button-down, button-up, button-down Dragging the mouse with a double click (button-down, button-up, button-down
@@ -410,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. 'Microsoft Explorer' mouse has these buttons available to the right thumb.
Currently X1 and X2 only work on Win32 and X11 environments. Currently X1 and X2 only work on Win32 and X11 environments.
Examples: > Examples: >vim
:noremap <MiddleMouse> <LeftMouse><MiddleMouse> :noremap <MiddleMouse> <LeftMouse><MiddleMouse>
Paste at the position of the middle mouse button click (otherwise the paste 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 :noremap <LeftRelease> <LeftRelease>y
Immediately yank the selection, when using Visual mode. Immediately yank the selection, when using Visual mode.
Note the use of ":noremap" instead of "map" to avoid a recursive mapping. Note the use of ":noremap" instead of "map" to avoid a recursive mapping.
> >vim
:map <X1Mouse> <C-O> :map <X1Mouse> <C-O>
:map <X2Mouse> <C-I> :map <X2Mouse> <C-I>
Map the X1 and X2 buttons to go forwards and backwards in the jump list, see Map the X1 and X2 buttons to go forwards and backwards in the jump list, see
|CTRL-O| and |CTRL-I|. |CTRL-O| and |CTRL-I|.
*mouse-swap-buttons* *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 <LeftMouse> <RightMouse>
:noremap <LeftDrag> <RightDrag> :noremap <LeftDrag> <RightDrag>
:noremap <LeftRelease> <RightRelease> :noremap <LeftRelease> <RightRelease>

View File

@@ -24,7 +24,7 @@ via a plugin like https://github.com/nvim-treesitter/nvim-treesitter.
Parsers are searched for as `parser/{lang}.*` in any 'runtimepath' directory. 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. If multiple parsers for the same language are found, the first one is used.
(This typically implies the priority "user config > plugins > bundled". (This typically implies the priority "user config > plugins > bundled".
A parser can also be loaded manually using a full path: > A parser can also be loaded manually using a full path: >lua
vim.treesitter.require_language("python", "/path/to/python.so") vim.treesitter.require_language("python", "/path/to/python.so")
< <
@@ -37,7 +37,7 @@ file), multiple parsers may be needed to parse the full buffer. These are
combined in a |LanguageTree| object. combined in a |LanguageTree| object.
To create a LanguageTree (parser object) for a buffer and a given language, To create a LanguageTree (parser object) for a buffer and a given language,
use > use >lua
tsparser = vim.treesitter.get_parser(bufnr, lang) tsparser = vim.treesitter.get_parser(bufnr, lang)
< <
@@ -46,7 +46,7 @@ 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 is subject to change. A plugin should keep a reference to the parser object as
long as it wants incremental updates. long as it wants incremental updates.
Whenever you need to access the current syntax tree, parse the buffer: > Whenever you need to access the current syntax tree, parse the buffer: >lua
tstree = tsparser:parse() tstree = tsparser:parse()
< <
@@ -366,10 +366,10 @@ queries that make them available.
As an additional rule, capture highlights can always be specialized by As an additional rule, capture highlights can always be specialized by
language, by appending the language name after an additional dot. For language, by appending the language name after an additional dot. For
instance, to highlight comments differently per language: > instance, to highlight comments differently per language: >vim
hi @comment.c guifg=Blue hi @comment.c guifg=Blue
hi @comment.lua @guifg=DarkBlue hi @comment.lua guifg=DarkBlue
hi link @comment.doc.java String hi link @comment.doc.java String
< <
The following captures are linked by default to standard |group-name|s: The following captures are linked by default to standard |group-name|s:

View File

@@ -119,7 +119,7 @@ for forward-compatibility. |api-contract|
UI startup *ui-startup* UI startup *ui-startup*
UI embedders (clients that start Nvim with |--embed| and later call 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 --embed
Nvim will pause before loading startup files and reading buffers, so the UI 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 has a chance to invoke requests and do early initialization. Startup will
@@ -138,7 +138,7 @@ procedure:
to set |g:| variables visible to init.vim to set |g:| variables visible to init.vim
3. If the UI wants to do additional setup after user config is loaded, 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')") 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:
@@ -722,7 +722,7 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|.
["cmdline_block_show", lines] ~ ["cmdline_block_show", lines] ~
Show a block of context to the current command line. For example if 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() :function Foo()
: echo "foo" : echo "foo"
: :

View File

@@ -73,7 +73,7 @@ centralized reference of the differences.
- 'wildoptions' defaults to "pum,tagfile" - 'wildoptions' defaults to "pum,tagfile"
- |man.lua| plugin is enabled, so |:Man| is available by default. - |man.lua| plugin is enabled, so |:Man| is available by default.
- |matchit| plugin is enabled. To disable it in your config: > - |matchit| plugin is enabled. To disable it in your config: >vim
:let loaded_matchit = 1 :let loaded_matchit = 1
- |g:vimsyn_embed| defaults to "l" to enable Lua highlighting - |g:vimsyn_embed| defaults to "l" to enable Lua highlighting
@@ -88,11 +88,11 @@ typing ":".
If you don't like this you can disable the mouse in your |config| using any of If you don't like this you can disable the mouse in your |config| using any of
the following: the following:
- Disable mouse completely by unsetting the 'mouse' option: > - Disable mouse completely by unsetting the 'mouse' option: >vim
set mouse= set mouse=
- Pressing <RightMouse> extends selection instead of showing popup-menu: > - Pressing <RightMouse> extends selection instead of showing popup-menu: >vim
set mousemodel=extend set mousemodel=extend
- Pressing <A-LeftMouse> releases mouse until the cursor moves: > - Pressing <A-LeftMouse> releases mouse until the cursor moves: >vim
nnoremap <A-LeftMouse> <Cmd> nnoremap <A-LeftMouse> <Cmd>
\ set mouse=<Bar> \ set mouse=<Bar>
\ echo 'mouse OFF until next cursor-move'<Bar> \ echo 'mouse OFF until next cursor-move'<Bar>
@@ -104,7 +104,7 @@ Default Mappings ~
*default-mappings* *default-mappings*
Nvim creates the following default mappings at |startup|. You can disable any 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". of these in your config by simply removing the mapping, e.g. ":unmap Y".
> >vim
nnoremap Y y$ nnoremap Y y$
nnoremap <C-L> <Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR> nnoremap <C-L> <Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR>
inoremap <C-U> <C-G>u<C-U> inoremap <C-U> <C-G>u<C-U>
@@ -302,7 +302,7 @@ are always available and may be used simultaneously. See |provider-python|.
structures. structures.
2. |string()| fails immediately on nested containers, not when recursion limit 2. |string()| fails immediately on nested containers, not when recursion limit
was exceeded. was exceeded.
2. When |:echo| encounters duplicate containers like > 2. When |:echo| encounters duplicate containers like >vim
let l = [] let l = []
echo [l, l] echo [l, l]
@@ -462,7 +462,7 @@ TUI:
< <
*'term'* *E529* *E530* *E531* *'term'* *E529* *E530* *E531*
'term' reflects the terminal type derived from |$TERM| and other environment '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 :echo &term
< "builtin_x" means one of the |builtin-terms| was chosen, because the expected < "builtin_x" means one of the |builtin-terms| was chosen, because the expected
terminfo file was not found on the system. terminfo file was not found on the system.
@@ -568,7 +568,7 @@ Events:
Highlight groups: Highlight groups:
*hl-StatusLineTerm* *hl-StatusLineTermNC* are unnecessary because Nvim *hl-StatusLineTerm* *hl-StatusLineTermNC* are unnecessary because Nvim
supports 'winhighlight' window-local highlights. 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 StatusLineTerm ctermfg=black ctermbg=green
hi StatusLineTermNC ctermfg=green hi StatusLineTermNC ctermfg=green
autocmd TermOpen,WinEnter * if &buftype=='terminal' autocmd TermOpen,WinEnter * if &buftype=='terminal'
@@ -604,7 +604,7 @@ Options:
*'imactivatekey'* *'imak'* *'imactivatekey'* *'imak'*
*'imstatusfunc'* *'imsf'* *'imstatusfunc'* *'imsf'*
*'insertmode'* *'im'* Use the following script to emulate 'insertmode': *'insertmode'* *'im'* Use the following script to emulate 'insertmode':
> >vim
autocmd BufWinEnter * startinsert autocmd BufWinEnter * startinsert
inoremap <Esc> <C-X><C-Z><C-]> inoremap <Esc> <C-X><C-Z><C-]>
inoremap <C-C> <C-X><C-Z> inoremap <C-C> <C-X><C-Z>