This repository has been archived by the owner on Dec 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 211
/
nvim-lua-guide.txt
1735 lines (1329 loc) · 52.2 KB
/
nvim-lua-guide.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
*nvim-lua-guide.txt* Getting started using Lua in Neovim
==============================================================================
INTRODUCTION
*luaguide-introduction*
The integration of Lua: https://www.youtube.com/watch?v=IP3J56sKtn0
as a first-class language inside Neovim:
https://github.com/neovim/neovim/wiki/FAQ#why-embed-lua-instead-of-x
is shaping up to be one of its killer features.
However, the amount of teaching material for learning how to write
plugins in Lua is not as large as what you would find for writing them
in Vimscript. This is an attempt at providing some basic information to
get people started.
This guide assumes you are using at least version 0.5 of Neovim.
Learning Lua~
If you are not already familiar with the language, there are plenty of
resources to get started:
- The Learn X in Y minutes page about Lua:
https://learnxinyminutes.com/docs/lua/ should give you a quick overview
of the basics
- This guide:
https://github.com/medwatt/Notes/blob/main/Lua/Lua_Quick_Guide.ipynb
is also a good resource for getting started quickly
- If videos are more to your liking, Derek Banas has a 1-hour tutorial
on the language: https://www.youtube.com/watch?v=iMacxZQMPXs
- Want something a little more interactive with runnable examples? Try
the LuaScript tutorial: https://www.luascript.dev/learn
- The lua-users wiki: http://lua-users.org/wiki/LuaDirectory is full
of useful information on all kinds of Lua-related topics
- The official reference manual for Lua: https://www.lua.org/manual/5.1/
should give you the most comprehensive tour of the language exists as
a Vimdoc plugin if you want to read it from the comfort of your editor:
milisims/nvim-luaref: https://github.com/milisims/nvim-luaref
It should also be noted that Lua is a very clean and simple language. It
is easy to learn, especially if you have experience with similar scripting
languages like JavaScript. You may already know more Lua than you realise!
Note: the version of Lua that Neovim embeds is LuaJIT:
https://staff.fnwi.uva.nl/h.vandermeer/docs/lua/luajit/luajit_intro.html
2.1.0, which maintains compatibility with Lua 5.1.
Existing tutorials for writing Lua in Neovim~
A few tutorials have already been written to help people write plugins
in Lua. Some of them helped quite a bit when writing this guide. Many
thanks to their authors.
- teukka.tech - From init.vim to init.lua:
https://teukka.tech/luanvim.html
- dev.to - How to write neovim plugins in Lua:
https://dev.to/2nit/how-to-write-neovim-plugins-in-lua-5cca
- dev.to - How to make UI for neovim plugins in Lua:
https://dev.to/2nit/how-to-make-ui-for-neovim-plugins-in-lua-3b6e
- ms-jpq - Neovim Async Tutorial:
https://github.com/ms-jpq/neovim-async-tutorial
- oroques.dev - Neovim 0.5 features and the switch to init.lua:
https://oroques.dev/notes/neovim-init/
- Building A Vim Statusline from Scratch - jdhao's blog:
https://jdhao.github.io/2019/11/03/vim_custom_statusline/
- Configuring Neovim using Lua: https://icyphox.sh/blog/nvim-lua/
- Devlog | Everything you need to know to configure neovim using lua:
https://vonheikemen.github.io/devlog/tools/configuring-neovim-using-lua/
Companion plugins~
- Vimpeccable: https://github.com/svermeulen/vimpeccable - Plugin to
help write your .vimrc in Lua
- plenary.nvim: https://github.com/nvim-lua/plenary.nvim - All the
lua functions I don't want to write twice
- popup.nvim: https://github.com/nvim-lua/popup.nvim - An implementation
of the Popup API from vim in Neovim
- nvim_utils: https://github.com/norcalli/nvim_utils
- nvim-luadev: https://github.com/bfredl/nvim-luadev - REPL/debug
console for nvim lua plugins
- nvim-luapad: https://github.com/rafcamlet/nvim-luapad - Interactive
real time neovim scratchpad for embedded lua engine
- nlua.nvim: https://github.com/tjdevries/nlua.nvim - Lua Development
for Neovim
- BetterLua.vim: https://github.com/euclidianAce/BetterLua.vim -
Better Lua syntax highlighting in Vim/NeoVim
==============================================================================
WHERE TO PUT LUA FILES
*luaguide-where-to-put-lua-files*
init.lua~
Neovim supports loading an `init.lua` file for configuration instead of
the usual `init.vim`.
Note: `init.lua` is of course _completely_ optional. Support
for `init.vim` is not going away and is still a valid option for
configuration. Do keep in mind that some features are not 100% exposed
to Lua yet.
See also:
- |config|
Modules~
Lua modules are found inside a `lua/` folder in your `'runtimepath'`
(for most users, this will mean `~/.config/nvim/lua` on \*nix systems
and `~/AppData/Local/nvim/lua` on Windows). You can `require()` files
in this folder as Lua modules.
Let's take the following folder structure as an example:
>
📂 ~/.config/nvim
├── 📁 after
├── 📁 ftplugin
├── 📂 lua
│ ├── 🌑 myluamodule.lua
│ └── 📂 other_modules
│ ├── 🌑 anothermodule.lua
│ └── 🌑 init.lua
├── 📁 pack
├── 📁 plugin
├── 📁 syntax
└── 🇻 init.vim
<
The following Lua code will load `myluamodule.lua`:
>
require('myluamodule')
<
Notice the absence of a `.lua` extension.
Similarly, loading `other_modules/anothermodule.lua` is done like so:
>
require('other_modules.anothermodule')
-- or
require('other_modules/anothermodule')
<
Path separators are denoted by either a dot `.` or a slash `/`.
A folder containing an `init.lua` file can be required directly, without
having to specify the name of the file.
>
require('other_modules') -- loads other_modules/init.lua
<
Requiring a nonexistent module or a module which contains syntax errors
aborts the currently executing script.
`pcall()` may be used to prevent errors.
>
local ok, _ = pcall(require, 'module_with_error')
if not ok then
-- not loaded
end
<
See also:
- |lua-require|
Tips~
Several Lua plugins might have identical filenames in their `lua/`
folder. This could lead to namespace clashes.
If two different plugins have a `lua/main.lua` file, then doing
`require('main')` is ambiguous: which file do we want to source?
It might be a good idea to namespace your config or your plugin with a
top-level folder, like so: `lua/plugin_name/main.lua`
Runtime files~
Much like Vimscript files, Lua files can be loaded automatically from
special folders in your `runtimepath`. Currently, the following folders
are supported:
- `colors/`
- `compiler/`
- `ftplugin/`
- `ftdetect/`
- `indent/`
- `plugin/`
- `syntax/`
Note: in a runtime directory, all `*.vim` files are sourced before
`*.lua` files.
See also:
- |'runtimepath'|
- |load-plugins|
Tips~
Since runtime files aren't based on the Lua module system, two plugins
can have a `plugin/main.lua` file without it being an issue.
==============================================================================
USING LUA FROM VIMSCRIPT
*luaguide-using-lua-from-vimscript*
:lua~
This command executes a chunk of Lua code.
>
:lua require('myluamodule')
<
Multi-line scripts are possible using heredoc syntax:
>
echo "Here's a bigger chunk of Lua code"
lua << EOF
local mod = require('mymodule')
local tbl = {1, 2, 3}
for k, v in ipairs(tbl) do
mod.method(v)
end
print(tbl)
EOF
<
Note: each `:lua` command has its own scope and variables declared with
the `local` keyword are not accessible outside of the command. This
won't work:
>
:lua local foo = 1
:lua print(foo)
" prints 'nil' instead of '1'
<
Note 2: the `print()` function in Lua behaves similarly to the `:echomsg`
command. Its output is saved in the message-history and can be suppressed
by the `:silent` command.
See also:
- |:lua|
- |:lua-heredoc|
:luado~
This command executes a chunk of Lua code that acts on a range of lines
in the current buffer. If no range is specified, the whole buffer is
used instead. Whatever string is `return`ed from the chunk is used to
determine what each line should be replaced with.
The following command would replace every line in the current buffer
with the text `hello world`:
>
:luado return 'hello world'
<
Two implicit `line` and `linenr` variables are also provided. `line`
is the text of the line being iterated upon whereas `linenr` is its
number. The following command would make every line whose number is
divisible by 2 uppercase:
>
:luado if linenr % 2 == 0 then return line:upper() end
<
See also:
- |:luado|
Sourcing Lua files~
Neovim provides 3 Ex commands to source Lua files
- `:luafile`
- `:source`
- `:runtime`
`:luafile` and `:source` are very similar:
>
:luafile ~/foo/bar/baz/myluafile.lua
:luafile %
:source ~/foo/bar/baz/myluafile.lua
:source %
<
`:source` also supports ranges, which can be useful to only execute part
of a script:
>
:1,10source
<
`:runtime` is a little different: it uses the `'runtimepath'` option to
determine which files to source. See |:runtime| for more details.
See also:
- |:luafile|
- |:source|
- |:runtime|
Sourcing a lua file vs calling require():~
You might be wondering what the difference between calling the `require()`
function and sourcing a Lua file is and whether you should prefer one
way over the other. They have different use cases:
- `require()`:
- is a built-in Lua function. It allows you to take advantage of
Lua's module system
- searches for modules in `lua/` folders in your `'runtimepath'`
- keeps track of what modules have been loaded and prevents a script
from being parsed and executed a second time. If you change the file
containing the code for a module and try to `require()` it a second
time while Neovim is running, the module will not actually update
- `:luafile`, `:source` and `:runtime`:
- are Ex commands. They do not support modules
- execute the contents of a script regardless of whether it has been
executed before
- `:luafile` and `:source` take a path that is either absolute or
relative to the working directory of the current window
- `:runtime` uses the `'runtimepath'` option to find files
Files sourced via `:source`, `:runtime` or automatically from runtime
directories will also show up in `:scriptnames` and `--startuptime`
luaeval()~
This built-in Vimscript function evaluates a Lua expression string
and returns its value. Lua data types are automatically converted to
Vimscript types (and vice versa).
>
" You can store the result in a variable
let variable = luaeval('1 + 1')
echo variable
" 2
let concat = luaeval('"Lua".." is ".."awesome"')
echo concat
" 'Lua is awesome'
" List-like tables are converted to Vim lists
let list = luaeval('{1, 2, 3, 4}')
echo list[0]
" 1
echo list[1]
" 2
" Note that unlike Lua tables, Vim lists are 0-indexed
" Dict-like tables are converted to Vim dictionaries
let dict = luaeval('{foo = "bar", baz = "qux"}')
echo dict.foo
" 'bar'
" Same thing for booleans and nil
echo luaeval('true')
" v:true
echo luaeval('nil')
" v:null
" You can create Vimscript aliases for Lua functions
let LuaMathPow = luaeval('math.pow')
echo LuaMathPow(2, 2)
" 4
let LuaModuleFunction = luaeval('require("mymodule").myfunction')
call LuaModuleFunction()
" It is also possible to pass Lua functions as values to Vim functions
lua X = function(k, v) return string.format("%s:%s", k, v) end
echo map([1, 2, 3], luaeval("X"))
<
`luaeval()` takes an optional second argument that allows you to pass
data to the expression. You can then access that data from Lua using
the magic global `_A`:
>
echo luaeval('_A[1] + _A[2]', [1, 1])
" 2
echo luaeval('string.format("Lua is %s", _A)', 'awesome')
" 'Lua is awesome'
<
See also:
- |luaeval()|
v:lua~
This global Vim variable allows you to call Lua functions in the global
namespace `_G`: https://www.lua.org/manual/5.1/manual.html#pdf-_G
directly from Vimscript. Again, Vim data types are converted to Lua
types and vice versa.
>
call v:lua.print('Hello from Lua!')
" 'Hello from Lua!'
let scream = v:lua.string.rep('A', 10)
echo scream
" 'AAAAAAAAAA'
" How about a nice statusline?
lua << EOF
function _G.statusline()
local filepath = '%f'
local align_section = '%='
local percentage_through_file = '%p%%'
return string.format(
'%s%s%s',
filepath,
align_section,
percentage_through_file
)
end
EOF
set statusline=%!v:lua.statusline()
" Also works in expression mappings
lua << EOF
function _G.check_back_space()
local col = vim.api.nvim_win_get_cursor(0)[2]
return (col == 0 or vim.api.nvim_get_current_line():sub(col,
col):match('%s')) and true
end
EOF
inoremap <silent> <expr> <Tab>
\ pumvisible() ? "\<C-N>" :
\ v:lua.check_back_space() ? "\<Tab>" :
\ completion#trigger_completion()
" Call a function from a Lua module by using single quotes and
omitting parentheses:
call v:lua.require'module'.foo()
<
See also:
- |v:lua|
- |v:lua-call|
Caveats~
This variable can only be used to call functions. The following will
always throw an error:
>
" Aliasing functions doesn't work
let LuaPrint = v:lua.print
" Accessing dictionaries doesn't work
echo v:lua.some_global_dict['key']
" Using a function as a value doesn't work
echo map([1, 2, 3], v:lua.global_callback)
<
Tips~
You can get Lua syntax highlighting inside .vim files by putting `let
g:vimsyn_embed = 'l'` in your configuration file. See |g:vimsyn_embed|
for more on this option.
==============================================================================
THE VIM NAMESPACE
*luaguide-the-vim-namespace*
Neovim exposes a global `vim` variable which serves as an entry point
to interact with its APIs from Lua. It provides users with an extended
"standard library" of functions as well as various sub-modules.
Some notable functions and modules include:
- `vim.inspect`: transform Lua objects into human-readable strings
(useful for inspecting tables)
- `vim.regex`: use Vim regexes from Lua
- `vim.api`: module that exposes API functions (the same API used by
remote plugins)
- `vim.ui`: overridable UI functions that can be leveraged by plugins
- `vim.loop`: module that exposes the functionality of Neovim's event-loop
(using LibUV)
- `vim.lsp`: module that controls the built-in LSP client
- `vim.treesitter`: module that exposes the functionality of the
tree-sitter library
This list is by no means comprehensive. If you wish to know more about what's
made available by the `vim` variable, |lua-stdlib| and |lua-vim| are the way
to go. Alternatively, you can do `:lua print(vim.inspect(vim))` to get a list
of every module. API functions are documented under |api-global|.
Tips~
Writing `print(vim.inspect(x))` every time you want to inspect the
contents of an object can get pretty tedious. It might be worthwhile
to have a global wrapper function somewhere in your configuration (in
Neovim 0.7.0+, this function is built-in, see |vim.pretty_print()|:
>
function _G.put(...)
local objects = {}
for i = 1, select('#', ...) do
local v = select(i, ...)
table.insert(objects, vim.inspect(v))
end
print(table.concat(objects, '\n'))
return ...
end
<
You can then inspect the contents of an object very quickly in your code
or from the command-line:
>
put({1, 2, 3})
<
>
:lua put(vim.loop)
<
Alternatively, you can use the `:lua` command to pretty-print a Lua
expression by prefixing it with `=` (Neovim 0.7+ only):
>
:lua =vim.loop
<
Additionally, you may find that built-in Lua functions are sometimes
lacking compared to what you would find in other languages (for example
`os.clock()` only returns a value in seconds, not milliseconds). Be
sure to look at the Neovim stdlib (and `vim.fn`, more on that later),
it probably has what you're looking for.
==============================================================================
USING VIMSCRIPT FROM LUA
*luaguide-using-vimscript-from-lua*
vim.api.nvim_eval()~
This function evaluates a Vimscript expression string and returns its
value. Vimscript data types are automatically converted to Lua types
(and vice versa).
It is the Lua equivalent of the `luaeval()` function in Vimscript
>
-- Data types are converted correctly
print(vim.api.nvim_eval('1 + 1')) -- 2
print(vim.inspect(vim.api.nvim_eval('[1, 2, 3]'))) -- { 1, 2, 3 }
print(vim.inspect(vim.api.nvim_eval('{"foo": "bar", "baz": "qux"}')))
-- { baz = "qux", foo = "bar" }
print(vim.api.nvim_eval('v:true')) -- true
print(vim.api.nvim_eval('v:null')) -- nil
<
Caveats~
Unlike `luaeval()`, `vim.api.nvim_eval()` does not provide an implicit
`_A` variable to pass data to the expression.
vim.api.nvim_exec()~
This function evaluates a chunk of Vimscript code. It takes in a string
containing the source code to execute and a boolean to determine whether
the output of the code should be returned by the function (you can then
store the output in a variable, for example).
>
local result = vim.api.nvim_exec(
[[
let s:mytext = 'hello world'
function! s:MyFunction(text)
echo a:text
endfunction
call s:MyFunction(s:mytext)
]],
true)
print(result) -- 'hello world'
<
Caveats~
`nvim_exec` does not support script-local variables (`s:`) prior to
Neovim 0.6.0
vim.api.nvim_command()~
This function executes an ex command. It takes in a string containing
the command to execute.
>
vim.api.nvim_command('new')
vim.api.nvim_command('wincmd H')
vim.api.nvim_command('set nonumber')
vim.api.nvim_command('%s/foo/bar/g')
<
vim.cmd()~
Alias for `vim.api.nvim_exec()`. Only the command argument is needed,
`output` is always set to `false`.
>
vim.cmd('buffers')
vim.cmd([[
let g:multiline_list = [
\ 1,
\ 2,
\ 3,
\ ]
echo g:multiline_list
]])
<
Tips~
Since you have to pass strings to these functions, you often end up
having to escape backslashes:
>
vim.cmd('%s/\\Vfoo/bar/g')
<
Double bracketed strings are easier to use as they do not require
escaping characters:
>
vim.cmd([[%s/\Vfoo/bar/g]])
<
vim.api.nvim_replace_termcodes()~
This API function allows you to escape terminal codes and Vim keycodes.
You may have come across mappings like this one:
>
inoremap <expr> <Tab> pumvisible() ? "\<C-N>" : "\<Tab>"
<
Trying to do the same in Lua can prove to be a challenge. You might be
tempted to do it like this:
>
function _G.smart_tab()
return vim.fn.pumvisible() == 1 and [[\<C-N>]] or [[\<Tab>]]
end
vim.api.nvim_set_keymap('i', '<Tab>', 'v:lua.smart_tab()', {expr =
true, noremap = true})
<
only to find out that the mapping inserts `\<Tab>` and `\<C-N>`
literally...
Being able to escape keycodes is actually a Vimscript feature. Aside
from the usual escape sequences like `\r`, `\42` or `\x10` that are
common to many programming languages, Vimscript `expr-quotes` (strings
surrounded with double quotes) allow you to escape the human-readable
representation of Vim keycodes.
Lua doesn't have such a feature built-in. Fortunately, Neovim
has an API function for escaping terminal codes and keycodes:
`nvim_replace_termcodes()`
>
print(vim.api.nvim_replace_termcodes('<Tab>', true, true, true))
<
This is a little verbose. Making a reusable wrapper can help:
>
-- The function is called `t` for `termcodes`.
-- You don't have to call it that, but I find the terseness convenient
local function t(str)
-- Adjust boolean arguments as needed
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
print(t'<Tab>')
<
Coming back to our earlier example, this should now work as expected:
>
local function t(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
function _G.smart_tab()
return vim.fn.pumvisible() == 1 and t'<C-N>' or t'<Tab>'
end
vim.api.nvim_set_keymap('i', '<Tab>', 'v:lua.smart_tab()', {expr =
true, noremap = true})
<
This is not necessary with `vim.keymap.set()` as it automatically
transforms vim keycodes returned by Lua functions in `expr` mappings
by default:
>
vim.keymap.set('i', '<Tab>', function()
return vim.fn.pumvisible() == 1 and '<C-N>' or '<Tab>'
end, {expr = true})
<
See also:
- |keycodes|
- |expr-quote|
- |nvim_replace_termcodes()|
==============================================================================
MANAGING VIM OPTIONS
*luaguide-managing-vim-options*
Using api functions~
Neovim provides a set of API functions to either set an option or get
its current value:
- Global options:
- |nvim_set_option()|
- |nvim_get_option()|
- Buffer-local options:
- |nvim_buf_set_option()|
- |nvim_buf_get_option()|
- Window-local options:
- |nvim_win_set_option()|
- |nvim_win_get_option()|
They take a string containing the name of the option to set/get as well
as the value you want to set it to.
Boolean options (like `(no)number`) have to be set to either `true` or
`false`:
>
vim.api.nvim_set_option('smarttab', false)
print(vim.api.nvim_get_option('smarttab')) -- false
<
Unsurprisingly, string options have to be set to a string:
>
vim.api.nvim_set_option('selection', 'exclusive')
print(vim.api.nvim_get_option('selection')) -- 'exclusive'
<
Number options accept a number:
>
vim.api.nvim_set_option('updatetime', 3000)
print(vim.api.nvim_get_option('updatetime')) -- 3000
<
Buffer-local and window-local options also need a buffer number or
a window number (using `0` will set/get the option for the current
buffer/window):
>
vim.api.nvim_win_set_option(0, 'number', true)
vim.api.nvim_buf_set_option(10, 'shiftwidth', 4)
print(vim.api.nvim_win_get_option(0, 'number')) -- true
print(vim.api.nvim_buf_get_option(10, 'shiftwidth')) -- 4
<
Using meta-accessors~
A few meta-accessors are available if you want to set options in a more
"idiomatic" way. They essentially wrap the above API functions and allow
you to manipulate options as if they were variables:
- |vim.o|: behaves like `:let &{option-name}`
- |vim.go|: behaves like `:let &g:{option-name}`
- |vim.bo|: behaves like `:let &l:{option-name}` for buffer-local options
- |vim.wo|: behaves like `:let &l:{option-name}` for window-local options
>
vim.o.smarttab = false -- let &smarttab = v:false
print(vim.o.smarttab) -- false
vim.o.isfname = vim.o.isfname .. ',@-@' -- on Linux: let &isfname =
&isfname .. ',@-@'
print(vim.o.isfname) -- '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@'
vim.bo.shiftwidth = 4
print(vim.bo.shiftwidth) -- 4
<
You can specify a number for buffer-local and window-local options. If
no number is given, the current buffer/window is used:
>
vim.bo[4].expandtab = true -- same as vim.api.nvim_buf_set_option(4,
'expandtab', true)
vim.wo.number = true -- same as vim.api.nvim_win_set_option(0,
'number', true)
<
These wrappers also have more sophisticated `vim.opt*` variants that
provide convenient mechanisms for setting options in Lua. They're similar
to what you might be used to in your `init.vim`:
- `vim.opt`: behaves like `:set`
- `vim.opt_global`: behaves like `:setglobal`
- `vim.opt_local`: behaves like `:setlocal`
>
vim.opt.smarttab = false
print(vim.opt.smarttab:get()) -- false
<
Some options can be set using Lua tables:
>
vim.opt.completeopt = {'menuone', 'noselect'}
print(vim.inspect(vim.opt.completeopt:get())) -- { "menuone",
"noselect" }
<
Wrappers for list-like, map-like and set-like options also come with
methods and metamethods that work similarly to their `:set+=`, `:set^=`
and `:set-=` counterparts in Vimscript.
>
vim.opt.shortmess:append({ I = true })
-- alternative form:
vim.opt.shortmess = vim.opt.shortmess + { I = true }
vim.opt.whichwrap:remove({ 'b', 's' })
-- alternative form:
vim.opt.whichwrap = vim.opt.whichwrap - { 'b', 's' }
<
Be sure to look at |vim.opt| for more information.
See also:
- |lua-vim-options|
==============================================================================
MANAGING VIM INTERNAL VARIABLES
*luaguide-managing-vim-internal-variables*
Using api functions~
Much like options, internal variables have their own set of API functions:
- Global variables (`g:`):
- |nvim_set_var()|
- |nvim_get_var()|
- |nvim_del_var()|
- Buffer variables (`b:`):
- |nvim_buf_set_var()|
- |nvim_buf_get_var()|
- |nvim_buf_del_var()|
- Window variables (`w:`):
- |nvim_win_set_var()|
- |nvim_win_get_var()|
- |nvim_win_del_var()|
- Tabpage variables (`t:`):
- |nvim_tabpage_set_var()|
- |nvim_tabpage_get_var()|
- |nvim_tabpage_del_var()|
- Predefined Vim variables (`v:`):
- |nvim_set_vvar()|
- |nvim_get_vvar()|
With the exception of predefined Vim variables, they can also be deleted
(the `:unlet` command is the equivalent in Vimscript). Local variables
(`l:`), script variables (`s:`) and function arguments (`a:`) cannot
be manipulated as they only make sense in the context of a Vim script,
Lua has its own scoping rules.
If you are unfamiliar with what these variables do, |internal-variables|
describes them in detail.
These functions take a string containing the name of the variable to
set/get/delete as well as the value you want to set it to.
>
vim.api.nvim_set_var('some_global_variable', { key1 = 'value', key2 =
300 })
print(vim.inspect(vim.api.nvim_get_var('some_global_variable'))) --
{ key1 = "value", key2 = 300 }
vim.api.nvim_del_var('some_global_variable')
<
Variables that are scoped to a buffer, a window or a tabpage also
receive a number (using `0` will set/get/delete the variable for the
current buffer/window/tabpage):
>
vim.api.nvim_win_set_var(0, 'some_window_variable', 2500)
vim.api.nvim_tab_set_var(3, 'some_tabpage_variable', 'hello world')
print(vim.api.nvim_win_get_var(0, 'some_window_variable')) -- 2500
print(vim.api.nvim_buf_get_var(3, 'some_tabpage_variable')) --
'hello world'
vim.api.nvim_win_del_var(0, 'some_window_variable')
vim.api.nvim_buf_del_var(3, 'some_tabpage_variable')
<
Using meta-accessors~
Internal variables can be manipulated more intuitively using these
meta-accessors:
- |vim.g|: global variables
- |vim.b|: buffer variables
- |vim.w|: window variables
- |vim.t|: tabpage variables
- |vim.v|: predefined Vim variables
- |vim.env|: environment variables
>
vim.g.some_global_variable = {
key1 = 'value',
key2 = 300
}
print(vim.inspect(vim.g.some_global_variable)) -- { key1 = "value",
key2 = 300 }
-- target a specific buffer/window/tabpage (Neovim 0.6+)
vim.b[2].myvar = 1
<
Some variable names may contain characters that cannot be used for
identifiers in Lua. You can still manipulate these variables by using
this syntax: `vim.g['my#variable']`.
To delete one of these variables, simply assign `nil` to it:
>
vim.g.some_global_variable = nil
<
See also:
- |lua-vim-variables|
Caveats~
You cannot add/update/delete keys from a dictionary stored in one of
these variables. For example, this snippet of Vimscript code does not
work as expected:
>
let g:variable = {}
lua vim.g.variable.key = 'a'
echo g:variable
" {}
<
You can use a temporary variable as a workaround:
>
let g:variable = {}
lua << EOF
local tmp = vim.g.variable
tmp.key = 'a'
vim.g.variable = tmp
EOF
echo g:variable
" {'key': 'a'}
<
This is a known issue:
- Issue #12544: https://github.com/neovim/neovim/issues/12544
==============================================================================
CALLING VIMSCRIPT FUNCTIONS
*luaguide-calling-vimscript-functions*
vim.fn.{function}()~
`vim.fn` can be used to call a Vimscript function. Data types are
converted back and forth from Lua to Vimscript.
>
print(vim.fn.printf('Hello from %s', 'Lua'))
local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' })
print(vim.inspect(reversed_list)) -- { "c", "b", "a" }