-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathapi.txt
3654 lines (2888 loc) · 151 KB
/
api.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
*api.txt* Nvim
NVIM REFERENCE MANUAL by Thiago de Arruda
Nvim API *API* *api*
Nvim exposes a powerful API that can be used by plugins and external processes
via |RPC|, |Lua| and Vimscript (|eval-api|).
Applications can also embed libnvim to work with the C API directly.
Type |gO| to see the table of contents.
==============================================================================
API Usage *api-rpc* *RPC* *rpc*
*msgpack-rpc*
RPC is the main way to control Nvim programmatically. Nvim implements the
MessagePack-RPC protocol with these extra (out-of-spec) constraints:
1. Responses must be given in reverse order of requests (like "unwinding
a stack").
2. Nvim processes all messages (requests and notifications) in the order they
are received.
MessagePack-RPC specification:
https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
https://github.com/msgpack/msgpack/blob/0b8f5ac/spec.md
Many clients use the API: user interfaces (GUIs), remote plugins, scripts like
"nvr" (https://github.com/mhinz/neovim-remote). Even Nvim itself can control
other Nvim instances. API clients can:
- Call any API function
- Listen for events
- Receive remote calls from Nvim
The RPC API is like a more powerful version of Vim's "clientserver" feature.
CONNECTING *rpc-connecting*
See |channel-intro| for various ways to open a channel. Channel-opening
functions take an `rpc` key in the options dict. RPC channels can also be
opened by other processes connecting to TCP/IP sockets or named pipes listened
to by Nvim.
Nvim creates a default RPC socket at |startup|, given by |v:servername|. To
start with a TCP/IP socket instead, use |--listen| with a TCP-style address: >
nvim --listen 127.0.0.1:6666
More endpoints can be started with |serverstart()|.
Note that localhost TCP sockets are generally less secure than named pipes,
and can lead to vulnerabilities like remote code execution.
Connecting to the socket is the easiest way a programmer can test the API,
which can be done through any msgpack-rpc client library or full-featured
|api-client|. Here's a Ruby script that prints "hello world!" in the current
Nvim instance:
>ruby
#!/usr/bin/env ruby
# Requires msgpack-rpc: gem install msgpack-rpc
#
# To run this script, execute it from a running Nvim instance (notice the
# trailing '&' which is required since Nvim won't process events while
# running a blocking command):
#
# :!./hello.rb &
#
# Or from another shell by setting NVIM_LISTEN_ADDRESS:
# $ NVIM_LISTEN_ADDRESS=[address] ./hello.rb
require 'msgpack/rpc'
require 'msgpack/rpc/transport/unix'
nvim = MessagePack::RPC::Client.new(MessagePack::RPC::UNIXTransport.new, ENV['NVIM_LISTEN_ADDRESS'])
result = nvim.call(:nvim_command, 'echo "hello world!"')
<
A better way is to use the Python REPL with the "pynvim" package, where API
functions can be called interactively:
>
>>> from pynvim import attach
>>> nvim = attach('socket', path='[address]')
>>> nvim.command('echo "hello world!"')
<
You can also embed Nvim via |jobstart()|, and communicate using |rpcrequest()|
and |rpcnotify()|:
>vim
let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true})
echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"')
call jobstop(nvim)
<
==============================================================================
API Definitions *api-definitions*
*api-types*
The Nvim C API defines custom types for all function parameters. Some are just
typedefs around C99 standard types, others are Nvim-defined data structures.
Basic types ~
>
API Type C type
------------------------------------------------------------------------
Nil
Boolean bool
Integer (signed 64-bit integer) int64_t
Float (IEEE 754 double precision) double
String {char* data, size_t size} struct
Array kvec
Dict (msgpack: map) kvec
Object any of the above
<
Note:
- Empty Array is accepted as a valid Dictionary parameter.
- Functions cannot cross RPC boundaries. But API functions (e.g.
|nvim_create_autocmd()|) may support Lua function parameters for non-RPC
invocations.
Special types (msgpack EXT) ~
These are integer typedefs discriminated as separate Object subtypes. They
can be treated as opaque integers, but are mutually incompatible: Buffer may
be passed as an integer but not as Window or Tabpage.
The EXT object data is the (integer) object handle. The EXT type codes given
in the |api-metadata| `types` key are stable: they will not change and are
thus forward-compatible.
>
EXT Type C type Data
------------------------------------------------------------------------
Buffer enum value kObjectTypeBuffer |bufnr()|
Window enum value kObjectTypeWindow |window-ID|
Tabpage enum value kObjectTypeTabpage internal handle
<
*api-indexing*
Most of the API uses 0-based indices, and ranges are end-exclusive. For the
end of a range, -1 denotes the last line/column.
Exception: the following API functions use "mark-like" indexing (1-based
lines, 0-based columns):
- |nvim_get_mark()|
- |nvim_buf_get_mark()|
- |nvim_buf_set_mark()|
- |nvim_win_get_cursor()|
- |nvim_win_set_cursor()|
Exception: the following API functions use |extmarks| indexing (0-based
indices, end-inclusive):
- |nvim_buf_del_extmark()|
- |nvim_buf_get_extmark_by_id()|
- |nvim_buf_get_extmarks()|
- |nvim_buf_set_extmark()|
*api-fast*
Most API functions are "deferred": they are queued on the main loop and
processed sequentially with normal input. So if the editor is waiting for
user input in a "modal" fashion (e.g. the |hit-enter-prompt|), the request
will block. Non-deferred (fast) functions such as |nvim_get_mode()| and
|nvim_input()| are served immediately (i.e. without waiting in the input
queue). Lua code can use |vim.in_fast_event()| to detect a fast context.
==============================================================================
API metadata *api-metadata*
The Nvim C API is automatically exposed to RPC by the build system, which
parses headers in src/nvim/api/* and generates dispatch-functions mapping RPC
API method names to public C API functions, converting/validating arguments
and return values.
Nvim exposes its API metadata as a Dictionary with these items:
- version Nvim version, API level/compatibility
- version.api_level API version integer *api-level*
- version.api_compatible API is backwards-compatible with this level
- version.api_prerelease Declares the API as unstable/unreleased
`(version.api_prerelease && fn.since == version.api_level)`
- functions API function signatures, containing |api-types| info
describing the return value and parameters.
- ui_events |UI| event signatures
- ui_options Supported |ui-option|s
- {fn}.since API level where function {fn} was introduced
- {fn}.deprecated_since API level where function {fn} was deprecated
- types Custom handle types defined by Nvim
- error_types Possible error types returned by API functions
About the `functions` map:
- Container types may be decorated with type/size constraints, e.g.
ArrayOf(Buffer) or ArrayOf(Integer, 2).
- Functions considered to be methods that operate on instances of Nvim
special types (msgpack EXT) have the "method=true" flag. The receiver type
is that of the first argument. Method names are prefixed with `nvim_` plus
a type name, e.g. `nvim_buf_get_lines` is the `get_lines` method of
a Buffer instance. |dev-api|
- Global functions have the "method=false" flag and are prefixed with just
`nvim_`, e.g. `nvim_list_bufs`.
*api-mapping*
External programs (clients) can use the metadata to discover the API, using
any of these approaches:
1. Connect to a running Nvim instance and call |nvim_get_api_info()| via
msgpack-RPC. This is best for clients written in dynamic languages which
can define functions at runtime.
2. Start Nvim with |--api-info|. Useful for statically-compiled clients.
Example (requires Python "pyyaml" and "msgpack-python" modules): >
nvim --api-info | python -c 'import msgpack, sys, yaml; yaml.dump(msgpack.unpackb(sys.stdin.buffer.read()), sys.stdout)'
<
3. Use the |api_info()| Vimscript function. >vim
:lua vim.print(vim.fn.api_info())
< 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')
==============================================================================
API contract *api-contract*
The Nvim API is composed of functions and events.
- Clients call functions like those described at |api-global|.
- Clients can subscribe to |ui-events|, |api-buffer-updates|, etc.
- API function names are prefixed with "nvim_".
- API event names are prefixed with "nvim_" and suffixed with "_event".
As Nvim evolves the API may change in compliance with this CONTRACT:
- New functions and events may be added.
- Any such extensions are OPTIONAL: old clients may ignore them.
- Function signatures will NOT CHANGE (after release).
- Functions introduced in the development (unreleased) version MAY CHANGE.
(Clients can dynamically check `api_prerelease`, etc. |api-metadata|)
- Event parameters will not be removed or reordered (after release).
- Events may be EXTENDED: new parameters may be added.
- New items may be ADDED to map/list parameters/results of functions and
events.
- Any such new items are OPTIONAL: old clients may ignore them.
- Existing items will not be removed (after release).
- Deprecated functions will not be removed until Nvim version 2.0
"Private" interfaces are NOT covered by this contract:
- Undocumented (not in :help) functions or events of any kind
- nvim__x ("double underscore") functions
The idea is "versionless evolution", in the words of Rich Hickey:
- Relaxing a requirement should be a compatible change.
- Strengthening a promise should be a compatible change.
==============================================================================
Global events *api-global-events*
When a client invokes an API request as an async notification, it is not
possible for Nvim to send an error response. Instead, in case of error, the
following notification will be sent to the client:
*nvim_error_event*
nvim_error_event[{type}, {message}]
{type} is a numeric id as defined by `api_info().error_types`, and {message} is
a string with the error message.
==============================================================================
Buffer update events *api-buffer-updates*
API clients can "attach" to Nvim buffers to subscribe to buffer update events.
This is similar to |TextChanged| but more powerful and granular.
Call |nvim_buf_attach()| to receive these events on the channel:
*nvim_buf_lines_event*
nvim_buf_lines_event[{buf}, {changedtick}, {firstline}, {lastline}, {linedata}, {more}]
When the buffer text between {firstline} and {lastline} (end-exclusive,
zero-indexed) were changed to the new text in the {linedata} list. The
granularity is a line, i.e. if a single character is changed in the
editor, the entire line is sent.
When {changedtick} is |v:null| this means the screen lines (display)
changed but not the buffer contents. {linedata} contains the changed
screen lines. This happens when 'inccommand' shows a buffer preview.
Properties: ~
{buf} API buffer handle (buffer number)
{changedtick} value of |b:changedtick| for the buffer. If you send an
API command back to nvim you can check the value of |b:changedtick| as
part of your request to ensure that no other changes have been made.
{firstline} integer line number of the first line that was replaced.
Zero-indexed: if line 1 was replaced then {firstline} will be 0, not
1. {firstline} is always less than or equal to the number of lines
that were in the buffer before the lines were replaced.
{lastline} integer line number of the first line that was not replaced
(i.e. the range {firstline}, {lastline} is end-exclusive).
Zero-indexed: if line numbers 2 to 5 were replaced, this will be 5
instead of 6. {lastline} is always be less than or equal to the number
of lines that were in the buffer before the lines were replaced.
{lastline} will be -1 if the event is part of the initial update after
attaching.
{linedata} list of strings containing the contents of the new buffer
lines. Newline characters are omitted; empty lines are sent as empty
strings.
{more} boolean, true for a "multipart" change notification: the
current change was chunked into multiple |nvim_buf_lines_event|
notifications (e.g. because it was too big).
nvim_buf_changedtick_event[{buf}, {changedtick}] *nvim_buf_changedtick_event*
When |b:changedtick| was incremented but no text was changed. Relevant for
undo/redo.
Properties: ~
{buf} API buffer handle (buffer number)
{changedtick} new value of |b:changedtick| for the buffer
nvim_buf_detach_event[{buf}] *nvim_buf_detach_event*
When buffer is detached (i.e. updates are disabled). Triggered explicitly by
|nvim_buf_detach()| or implicitly in these cases:
- Buffer was |abandon|ed and 'hidden' is not set.
- Buffer was reloaded, e.g. with |:edit| or an external change triggered
|:checktime| or 'autoread'.
- Generally: whenever the buffer contents are unloaded from memory.
Properties: ~
{buf} API buffer handle (buffer number)
EXAMPLE ~
Calling |nvim_buf_attach()| with send_buffer=true on an empty buffer, emits: >
nvim_buf_lines_event[{buf}, {changedtick}, 0, -1, [""], v:false]
User adds two lines to the buffer, emits: >
nvim_buf_lines_event[{buf}, {changedtick}, 0, 0, ["line1", "line2"], v:false]
User moves to a line containing the text "Hello world" and inserts "!", emits: >
nvim_buf_lines_event[{buf}, {changedtick}, {linenr}, {linenr} + 1,
["Hello world!"], v:false]
User moves to line 3 and deletes 20 lines using "20dd", emits: >
nvim_buf_lines_event[{buf}, {changedtick}, 2, 22, [], v:false]
User selects lines 3-5 using |linewise-visual| mode and then types "p" to
paste a block of 6 lines, emits: >
nvim_buf_lines_event[{buf}, {changedtick}, 2, 5,
['pasted line 1', 'pasted line 2', 'pasted line 3', 'pasted line 4',
'pasted line 5', 'pasted line 6'],
v:false
]
User reloads the buffer with ":edit", emits: >
nvim_buf_detach_event[{buf}]
<
LUA ~
*api-buffer-updates-lua*
In-process Lua plugins can receive buffer updates in the form of Lua
callbacks. These callbacks are called frequently in various contexts;
|textlock| prevents changing buffer contents and window layout (use
|vim.schedule()| to defer such operations to the main loop instead).
Moving the cursor is allowed, but it is restored afterwards.
|nvim_buf_attach()| will take keyword args for the callbacks. "on_lines" will
receive parameters ("lines", {buf}, {changedtick}, {firstline}, {lastline},
{new_lastline}, {old_byte_size} [, {old_utf32_size}, {old_utf16_size}]).
Unlike remote channel events the text contents are not passed. The new text can
be accessed inside the callback as >lua
vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true)
<
{old_byte_size} is the total size of the replaced region {firstline} to
{lastline} in bytes, including the final newline after {lastline}. if
`utf_sizes` is set to true in |nvim_buf_attach()| keyword args, then the
UTF-32 and UTF-16 sizes of the deleted region is also passed as additional
arguments {old_utf32_size} and {old_utf16_size}.
"on_changedtick" is invoked when |b:changedtick| was incremented but no text
was changed. The parameters received are ("changedtick", {buf}, {changedtick}).
*api-lua-detach*
In-process Lua callbacks can detach by returning `true`. This will detach all
callbacks attached with the same |nvim_buf_attach()| call.
==============================================================================
Buffer highlighting *api-highlights*
Nvim allows plugins to add position-based highlights to buffers. This is
similar to |matchaddpos()| but with some key differences. The added highlights
are associated with a buffer and adapts to line insertions and deletions,
similar to signs. It is also possible to manage a set of highlights as a group
and delete or replace all at once.
The intended use case are linter or semantic highlighter plugins that monitor
a buffer for changes, and in the background compute highlights to the buffer.
Another use case are plugins that show output in an append-only buffer, and
want to add highlights to the outputs. Highlight data cannot be preserved
on writing and loading a buffer to file, nor in undo/redo cycles.
Highlights are registered using the |nvim_buf_set_extmark()| function, which
adds highlights as |extmarks|. If highlights need to be tracked or manipulated
after adding them, the returned |extmark| id can be used. >lua
-- create the highlight through an extmark
extid = vim.api.nvim_buf_set_extmark(buf, ns_id, line, col_start, {end_col = col_end, hl_group = hl_group})
-- example: modify the extmark's highlight group
vim.api.nvim_buf_set_extmark(buf, ns_id, line, col_start, {end_col = col_end, hl_group = NEW_HL_GROUP, id = extid})
-- example: change the highlight's position
vim.api.nvim_buf_set_extmark(buf, ns_id, NEW_LINE, col_start, {end_col = col_end, hl_group = NEW_HL_GROUP, id = extid})
<
See also |vim.hl.range()|.
==============================================================================
Floating windows *api-floatwin* *floating-windows*
Floating windows ("floats") are displayed on top of normal windows. This is
useful to implement simple widgets, such as tooltips displayed next to the
cursor. Floats are fully functional windows supporting user editing, common
|api-window| calls, and most window options (except 'statusline').
Two ways to create a floating window:
- |nvim_open_win()| creates a new window (needs a buffer, see |nvim_create_buf()|)
- |nvim_win_set_config()| reconfigures a normal window into a float
To close it use |nvim_win_close()| or a command such as |:close|.
To check whether a window is floating, check whether the `relative` option in
its config is non-empty: >lua
if vim.api.nvim_win_get_config(window_id).relative ~= '' then
-- window with this window_id is floating
end
<
Buffer text can be highlighted by typical mechanisms (syntax highlighting,
|api-highlights|). The |hl-NormalFloat| group highlights normal text;
'winhighlight' can be used as usual to override groups locally. Floats inherit
options from the current window; specify `style=minimal` in |nvim_open_win()|
to disable various visual features such as the 'number' column.
Other highlight groups specific to floating windows:
- |hl-FloatBorder| for window's border
- |hl-FloatTitle| for window's title
- |hl-FloatFooter| for window's footer
Currently, floating windows don't support some widgets like scrollbar.
The output of |:mksession| does not include commands for restoring floating
windows.
Example: create a float with scratch buffer: >vim
let buf = nvim_create_buf(v:false, v:true)
call nvim_buf_set_lines(buf, 0, -1, v:true, ["test", "text"])
let opts = {'relative': 'cursor', 'width': 10, 'height': 2, 'col': 0,
\ 'row': 1, 'anchor': 'NW', 'style': 'minimal'}
let win = nvim_open_win(buf, 0, opts)
" optional: change highlight, otherwise Pmenu is used
call nvim_set_option_value('winhl', 'Normal:MyHighlight', {'win': win})
<
==============================================================================
Extended marks *api-extended-marks* *extmarks* *extmark*
Extended marks (extmarks) represent buffer annotations that track text changes
in the buffer. They can represent cursors, folds, misspelled words, anything
that needs to track a logical location in the buffer over time. |api-indexing|
Extmark position works like a "vertical bar" cursor: it exists between
characters. Thus, the maximum extmark index on a line is 1 more than the
character index: >
f o o b a r line contents
0 1 2 3 4 5 character positions (0-based)
0 1 2 3 4 5 6 extmark positions (0-based)
Extmarks have "forward gravity": if you place the cursor directly on an
extmark position and enter some text, the extmark migrates forward. >
f o o|b a r line (| = cursor)
3 extmark
f o o z|b a r line (| = cursor)
4 extmark (after typing "z")
If an extmark is on the last index of a line and you input a newline at that
point, the extmark will accordingly migrate to the next line: >
f o o z b a r| line (| = cursor)
7 extmark
f o o z b a r first line
extmarks (none present)
| second line (| = cursor)
0 extmark (after typing <CR>)
Example:
Let's set an extmark at the first row (row=0) and third column (column=2).
|api-indexing| Passing id=0 creates a new mark and returns the id: >
01 2345678
0 ex|ample..
^ extmark position
<
>vim
let g:mark_ns = nvim_create_namespace('myplugin')
let g:mark_id = nvim_buf_set_extmark(0, g:mark_ns, 0, 2, {})
<
We can get the mark by its id: >vim
echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {})
" => [0, 2]
We can get all marks in a buffer by |namespace| (or by a range): >vim
echo nvim_buf_get_extmarks(0, g:mark_ns, 0, -1, {})
" => [[1, 0, 2]]
Deleting all surrounding text does NOT remove an extmark! To remove extmarks
use |nvim_buf_del_extmark()|. Deleting "x" in our example: >
0 12345678
0 e|ample..
^ extmark position
<
>vim
echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {})
" => [0, 1]
<
Note: Extmark "gravity" decides how it will shift after a text edit.
See |nvim_buf_set_extmark()|
Namespaces allow any plugin to manage only its own extmarks, ignoring those
created by another plugin.
Extmark positions changed by an edit will be restored on undo/redo. Creating
and deleting extmarks is not a buffer change, thus new undo states are not
created for extmark changes.
==============================================================================
Global Functions *api-global*
nvim_chan_send({chan}, {data}) *nvim_chan_send()*
Send data to channel `id`. For a job, it writes it to the stdin of the
process. For the stdio channel |channel-stdio|, it writes to Nvim's
stdout. For an internal terminal instance (|nvim_open_term()|) it writes
directly to terminal output. See |channel-bytes| for more information.
This function writes raw data, not RPC messages. If the channel was
created with `rpc=true` then the channel expects RPC messages, use
|vim.rpcnotify()| and |vim.rpcrequest()| instead.
Attributes: ~
|RPC| only
Lua |vim.api| only
Parameters: ~
• {chan} id of the channel
• {data} data to write. 8-bit clean: can contain NUL bytes.
nvim_create_buf({listed}, {scratch}) *nvim_create_buf()*
Creates a new, empty, unnamed buffer.
Parameters: ~
• {listed} Sets 'buflisted'
• {scratch} Creates a "throwaway" |scratch-buffer| for temporary work
(always 'nomodified'). Also sets 'nomodeline' on the
buffer.
Return: ~
Buffer handle, or 0 on error
See also: ~
• buf_open_scratch
nvim_del_current_line() *nvim_del_current_line()*
Deletes the current line.
Attributes: ~
not allowed when |textlock| is active
nvim_del_keymap({mode}, {lhs}) *nvim_del_keymap()*
Unmaps a global |mapping| for the given mode.
To unmap a buffer-local mapping, use |nvim_buf_del_keymap()|.
See also: ~
• |nvim_set_keymap()|
nvim_del_mark({name}) *nvim_del_mark()*
Deletes an uppercase/file named mark. See |mark-motions|.
Note: ~
• Lowercase name (or other buffer-local mark) is an error.
Parameters: ~
• {name} Mark name
Return: ~
true if the mark was deleted, else false.
See also: ~
• |nvim_buf_del_mark()|
• |nvim_get_mark()|
nvim_del_var({name}) *nvim_del_var()*
Removes a global (g:) variable.
Parameters: ~
• {name} Variable name
nvim_echo({chunks}, {history}, {opts}) *nvim_echo()*
Prints a message given by a list of `[text, hl_group]` "chunks".
Example: >lua
vim.api.nvim_echo({ { 'chunk1-line1\nchunk1-line2\n' }, { 'chunk2-line1' } }, true, {})
<
Parameters: ~
• {chunks} List of `[text, hl_group]` pairs, where each is a `text`
string highlighted by the (optional) name or ID `hl_group`.
• {history} if true, add to |message-history|.
• {opts} Optional parameters.
• err: Treat the message like `:echoerr`. Sets `hl_group`
to |hl-ErrorMsg| by default.
• verbose: Message is controlled by the 'verbose' option.
Nvim invoked with `-V3log` will write the message to the
"log" file instead of standard output.
nvim_eval_statusline({str}, {opts}) *nvim_eval_statusline()*
Evaluates statusline string.
Attributes: ~
|api-fast|
Parameters: ~
• {str} Statusline string (see 'statusline').
• {opts} Optional parameters.
• winid: (number) |window-ID| of the window to use as context
for statusline.
• maxwidth: (number) Maximum width of statusline.
• fillchar: (string) Character to fill blank spaces in the
statusline (see 'fillchars'). Treated as single-width even
if it isn't.
• highlights: (boolean) Return highlight information.
• use_winbar: (boolean) Evaluate winbar instead of statusline.
• use_tabline: (boolean) Evaluate tabline instead of
statusline. When true, {winid} is ignored. Mutually
exclusive with {use_winbar}.
• use_statuscol_lnum: (number) Evaluate statuscolumn for this
line number instead of statusline.
Return: ~
Dict containing statusline information, with these keys:
• str: (string) Characters that will be displayed on the statusline.
• width: (number) Display width of the statusline.
• highlights: Array containing highlight information of the
statusline. Only included when the "highlights" key in {opts} is
true. Each element of the array is a |Dict| with these keys:
• start: (number) Byte index (0-based) of first character that uses
the highlight.
• group: (string) Name of highlight group. May be removed in the
future, use `groups` instead.
• groups: (array) Names of stacked highlight groups (highest
priority last).
nvim_exec_lua({code}, {args}) *nvim_exec_lua()*
Execute Lua code. Parameters (if any) are available as `...` inside the
chunk. The chunk can return a value.
Only statements are executed. To evaluate an expression, prefix it with
`return`: return my_function(...)
Attributes: ~
|RPC| only
Parameters: ~
• {code} Lua code to execute
• {args} Arguments to the code
Return: ~
Return value of Lua code if present or NIL.
nvim_feedkeys({keys}, {mode}, {escape_ks}) *nvim_feedkeys()*
Sends input-keys to Nvim, subject to various quirks controlled by `mode`
flags. This is a blocking call, unlike |nvim_input()|.
On execution error: does not fail, but updates v:errmsg.
To input sequences like <C-o> use |nvim_replace_termcodes()| (typically
with escape_ks=false) to replace |keycodes|, then pass the result to
nvim_feedkeys().
Example: >vim
:let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true)
:call nvim_feedkeys(key, 'n', v:false)
<
Parameters: ~
• {keys} to be typed
• {mode} behavior flags, see |feedkeys()|
• {escape_ks} If true, escape K_SPECIAL bytes in `keys`. This should be
false if you already used |nvim_replace_termcodes()|, and
true otherwise.
See also: ~
• feedkeys()
• vim_strsave_escape_ks
nvim_get_api_info() *nvim_get_api_info()*
Returns a 2-tuple (Array), where item 0 is the current channel id and item
1 is the |api-metadata| map (Dict).
Attributes: ~
|api-fast|
|RPC| only
Return: ~
2-tuple `[{channel-id}, {api-metadata}]`
nvim_get_chan_info({chan}) *nvim_get_chan_info()*
Gets information about a channel.
See |nvim_list_uis()| for an example of how to get channel info.
Parameters: ~
• {chan} channel_id, or 0 for current channel
Return: ~
Channel info dict with these keys:
• "id" Channel id.
• "argv" (optional) Job arguments list.
• "stream" Stream underlying the channel.
• "stdio" stdin and stdout of this Nvim instance
• "stderr" stderr of this Nvim instance
• "socket" TCP/IP socket or named pipe
• "job" Job with communication over its stdio.
• "mode" How data received on the channel is interpreted.
• "bytes" Send and receive raw bytes.
• "terminal" |terminal| instance interprets ASCII sequences.
• "rpc" |RPC| communication on the channel is active.
• "pty" (optional) Name of pseudoterminal. On a POSIX system this is a
device path like "/dev/pts/1". If unknown, the key will still be
present if a pty is used (e.g. for conpty on Windows).
• "buffer" (optional) Buffer connected to |terminal| instance.
• "client" (optional) Info about the peer (client on the other end of
the channel), as set by |nvim_set_client_info()|.
nvim_get_color_by_name({name}) *nvim_get_color_by_name()*
Returns the 24-bit RGB value of a |nvim_get_color_map()| color name or
"#rrggbb" hexadecimal string.
Example: >vim
:echo nvim_get_color_by_name("Pink")
:echo nvim_get_color_by_name("#cbcbcb")
<
Parameters: ~
• {name} Color name or "#rrggbb" string
Return: ~
24-bit RGB value, or -1 for invalid argument.
nvim_get_color_map() *nvim_get_color_map()*
Returns a map of color names and RGB values.
Keys are color names (e.g. "Aqua") and values are 24-bit RGB color values
(e.g. 65535).
Return: ~
Map of color names and RGB values.
nvim_get_context({opts}) *nvim_get_context()*
Gets a map of the current editor state.
Parameters: ~
• {opts} Optional parameters.
• types: List of |context-types| ("regs", "jumps", "bufs",
"gvars", …) to gather, or empty for "all".
Return: ~
map of global |context|.
nvim_get_current_buf() *nvim_get_current_buf()*
Gets the current buffer.
Return: ~
Buffer handle
nvim_get_current_line() *nvim_get_current_line()*
Gets the current line.
Return: ~
Current line string
nvim_get_current_tabpage() *nvim_get_current_tabpage()*
Gets the current tabpage.
Return: ~
Tabpage handle
nvim_get_current_win() *nvim_get_current_win()*
Gets the current window.
Return: ~
Window handle
nvim_get_hl({ns_id}, {opts}) *nvim_get_hl()*
Gets all or specific highlight groups in a namespace.
Note: ~
• When the `link` attribute is defined in the highlight definition map,
other attributes will not be taking effect (see |:hi-link|).
Parameters: ~
• {ns_id} Get highlight groups for namespace ns_id
|nvim_get_namespaces()|. Use 0 to get global highlight groups
|:highlight|.
• {opts} Options dict:
• name: (string) Get a highlight definition by name.
• id: (integer) Get a highlight definition by id.
• link: (boolean, default true) Show linked group name
instead of effective definition |:hi-link|.
• create: (boolean, default true) When highlight group
doesn't exist create it.
Return: ~
Highlight groups as a map from group name to a highlight definition
map as in |nvim_set_hl()|, or only a single highlight definition map
if requested by name or id.
nvim_get_hl_id_by_name({name}) *nvim_get_hl_id_by_name()*
Gets a highlight group by name
similar to |hlID()|, but allocates a new ID if not present.
nvim_get_hl_ns({opts}) *nvim_get_hl_ns()*
Gets the active highlight namespace.
Parameters: ~
• {opts} Optional parameters
• winid: (number) |window-ID| for retrieving a window's
highlight namespace. A value of -1 is returned when
|nvim_win_set_hl_ns()| has not been called for the window
(or was called with a namespace of -1).
Return: ~
Namespace id, or -1
nvim_get_keymap({mode}) *nvim_get_keymap()*
Gets a list of global (non-buffer-local) |mapping| definitions.
Parameters: ~
• {mode} Mode short-name ("n", "i", "v", ...)
Return: ~
Array of |maparg()|-like dictionaries describing mappings. The
"buffer" key is always zero.
nvim_get_mark({name}, {opts}) *nvim_get_mark()*
Returns a `(row, col, buffer, buffername)` tuple representing the position
of the uppercase/file named mark. "End of line" column position is
returned as |v:maxcol| (big number). See |mark-motions|.
Marks are (1,0)-indexed. |api-indexing|
Note: ~
• Lowercase name (or other buffer-local mark) is an error.
Parameters: ~
• {name} Mark name
• {opts} Optional parameters. Reserved for future use.
Return: ~
4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if the mark is
not set.
See also: ~
• |nvim_buf_set_mark()|
• |nvim_del_mark()|
nvim_get_mode() *nvim_get_mode()*
Gets the current mode. |mode()| "blocking" is true if Nvim is waiting for
input.
Attributes: ~
|api-fast|
Return: ~
Dict { "mode": String, "blocking": Boolean }
nvim_get_proc({pid}) *nvim_get_proc()*
Gets info describing process `pid`.
Return: ~
Map of process properties, or NIL if process not found.
nvim_get_proc_children({pid}) *nvim_get_proc_children()*
Gets the immediate children of process `pid`.
Return: ~
Array of child process ids, empty if process not found.
nvim_get_runtime_file({name}, {all}) *nvim_get_runtime_file()*
Finds files in runtime directories, in 'runtimepath' order.
"name" can contain wildcards. For example
`nvim_get_runtime_file("colors/*.{vim,lua}", true)` will return all color
scheme files. Always use forward slashes (/) in the search pattern for
subdirectories regardless of platform.
It is not an error to not find any files. An empty array is returned then.
Attributes: ~
|api-fast|
Parameters: ~
• {name} pattern of files to search for
• {all} whether to return all matches or only the first
Return: ~
list of absolute paths to the found files
nvim_get_var({name}) *nvim_get_var()*
Gets a global (g:) variable.
Parameters: ~
• {name} Variable name
Return: ~
Variable value
nvim_get_vvar({name}) *nvim_get_vvar()*
Gets a v: variable.
Parameters: ~
• {name} Variable name
Return: ~
Variable value
nvim_input({keys}) *nvim_input()*
Queues raw user-input. Unlike |nvim_feedkeys()|, this uses a low-level
input buffer and the call is non-blocking (input is processed
asynchronously by the eventloop).
To input blocks of text, |nvim_paste()| is much faster and should be
preferred.
On execution error: does not fail, but updates v:errmsg.
Note: ~
• |keycodes| like <CR> are translated, so "<" is special. To input a
literal "<", send <LT>.
• For mouse events use |nvim_input_mouse()|. The pseudokey form
`<LeftMouse><col,row>` is deprecated since |api-level| 6.
Attributes: ~
|api-fast|
Parameters: ~
• {keys} to be typed
Return: ~
Number of bytes actually written (can be fewer than requested if the
buffer becomes full).
*nvim_input_mouse()*
nvim_input_mouse({button}, {action}, {modifier}, {grid}, {row}, {col})
Send mouse event from GUI.
Non-blocking: does not wait on any result, but queues the event to be
processed soon by the event loop.
Note: ~
• Currently this doesn't support "scripting" multiple mouse events by
calling it multiple times in a loop: the intermediate mouse positions
will be ignored. It should be used to implement real-time mouse input
in a GUI. The deprecated pseudokey form (`<LeftMouse><col,row>`) of
|nvim_input()| has the same limitation.
Attributes: ~
|api-fast|
Parameters: ~
• {button} Mouse button: one of "left", "right", "middle", "wheel",
"move", "x1", "x2".