forked from L3MON4D3/LuaSnip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathluasnip.txt
2996 lines (2395 loc) · 117 KB
/
luasnip.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
*luasnip.txt* For NVIM v0.8.0 Last change: 2023 March 27
==============================================================================
Table of Contents *luasnip-table-of-contents*
1. Basics |luasnip-basics|
- Jump-Index |luasnip-basics-jump-index|
- Adding Snippets |luasnip-basics-adding-snippets|
2. Node |luasnip-node|
- Api |luasnip-node-api|
3. Snippets |luasnip-snippets|
- Data |luasnip-snippets-data|
- Api |luasnip-snippets-api|
4. TextNode |luasnip-textnode|
5. InsertNode |luasnip-insertnode|
6. FunctionNode |luasnip-functionnode|
7. Node Reference |luasnip-node-reference|
8. ChoiceNode |luasnip-choicenode|
9. SnippetNode |luasnip-snippetnode|
10. IndentSnippetNode |luasnip-indentsnippetnode|
11. DynamicNode |luasnip-dynamicnode|
12. RestoreNode |luasnip-restorenode|
13. Absolute Indexer |luasnip-absolute-indexer|
14. MultiSnippet |luasnip-multisnippet|
15. Extras |luasnip-extras|
- Lambda |luasnip-extras-lambda|
- Match |luasnip-extras-match|
- Repeat |luasnip-extras-repeat|
- Partial |luasnip-extras-partial|
- Nonempty |luasnip-extras-nonempty|
- Dynamic Lambda |luasnip-extras-dynamic-lambda|
- FMT |luasnip-extras-fmt|
- Conditions |luasnip-extras-conditions|
- On The Fly-Snippets |luasnip-extras-on-the-fly-snippets|
- select_choice |luasnip-extras-select_choice|
- Filetype-Functions |luasnip-extras-filetype-functions|
- Postfix-Snippet |luasnip-extras-postfix-snippet|
- Snippet List |luasnip-extras-snippet-list|
16. Extend Decorator |luasnip-extend-decorator|
17. LSP-Snippets |luasnip-lsp-snippets|
- Snipmate Parser |luasnip-lsp-snippets-snipmate-parser|
- Transformations |luasnip-lsp-snippets-transformations|
18. Variables |luasnip-variables|
- Environment Namespaces |luasnip-variables-environment-namespaces|
- LSP-Variables |luasnip-variables-lsp-variables|
19. Loaders |luasnip-loaders|
- Troubleshooting |luasnip-loaders-troubleshooting|
- VS-Code |luasnip-loaders-vs-code|
- SNIPMATE |luasnip-loaders-snipmate|
- Lua |luasnip-loaders-lua|
- edit_snippets |luasnip-loaders-edit_snippets|
20. SnippetProxy |luasnip-snippetproxy|
21. ext_opts |luasnip-ext_opts|
22. Docstrings |luasnip-docstrings|
23. Docstring-Cache |luasnip-docstring-cache|
24. Events |luasnip-events|
25. Cleanup |luasnip-cleanup|
26. Logging |luasnip-logging|
27. Config-Options |luasnip-config-options|
28. API |luasnip-api|
>
__ ____
/\ \ /\ _`\ __
\ \ \ __ __ __ \ \,\L\_\ ___ /\_\ _____
\ \ \ __/\ \/\ \ /'__`\\/_\__ \ /' _ `\/\ \/\ '__`\
\ \ \L\ \ \ \_\ \/\ \L\.\_/\ \L\ \/\ \/\ \ \ \ \ \L\ \
\ \____/\ \____/\ \__/.\_\ `\____\ \_\ \_\ \_\ \ ,__/
\/___/ \/___/ \/__/\/_/\/_____/\/_/\/_/\/_/\ \ \/
\ \_\
\/_/
<
LuaSnip is a snippet engine written entirely in Lua. It has some great features
like inserting text (`luasnip-function-node`) or nodes (`luasnip-dynamic-node`)
based on user input, parsing LSP syntax and switching nodes
(`luasnip-choice-node`). For basic setup like mappings and installing, check
the README.
All code snippets in this help assume the following:
>lua
local ls = require("luasnip")
local s = ls.snippet
local sn = ls.snippet_node
local isn = ls.indent_snippet_node
local t = ls.text_node
local i = ls.insert_node
local f = ls.function_node
local c = ls.choice_node
local d = ls.dynamic_node
local r = ls.restore_node
local events = require("luasnip.util.events")
local ai = require("luasnip.nodes.absolute_indexer")
local extras = require("luasnip.extras")
local l = extras.lambda
local rep = extras.rep
local p = extras.partial
local m = extras.match
local n = extras.nonempty
local dl = extras.dynamic_lambda
local fmt = require("luasnip.extras.fmt").fmt
local fmta = require("luasnip.extras.fmt").fmta
local conds = require("luasnip.extras.expand_conditions")
local postfix = require("luasnip.extras.postfix").postfix
local types = require("luasnip.util.types")
local parse = require("luasnip.util.parser").parse_snippet
local ms = ls.multi_snippet
<
As noted in the |luasnip-loaders-lua|-section:
By default, the names from `luasnip.config.snip_env`
<https://github.com/L3MON4D3/LuaSnip/blob/master/lua/luasnip/config.lua#L122-L147>
will be used, but it’s possible to customize them by setting `snip_env` in
`setup`.
Furthermore, note that while this document assumes you have defined `ls` to be
`require("luasnip")`, it is **not** provided in the default set of variables.
==============================================================================
1. Basics *luasnip-basics*
In LuaSnip, snippets are made up of `nodes`. These can contain either
- static text (`textNode`)
- text that can be edited (`insertNode`)
- text that can be generated from the contents of other nodes (`functionNode`)
- other nodes
- `choiceNode`: allows choosing between two nodes (which might contain more
nodes)
- `restoreNode`: store and restore input to nodes
- or nodes that can be generated based on input (`dynamicNode`).
Snippets are always created using the `s(trigger:string,
nodes:table)`-function. It is explained in more detail in |luasnip-snippets|,
but the gist is that it creates a snippet that contains the nodes specified in
`nodes`, which will be inserted into a buffer if the text before the cursor
matches `trigger` when `ls.expand` is called.
JUMP-INDEX *luasnip-basics-jump-index*
Nodes that can be jumped to (`insertNode`, `choiceNode`, `dynamicNode`,
`restoreNode`, `snippetNode`) all require a "jump-index" so luasnip knows the
order in which these nodes are supposed to be visited ("jumped to").
>lua
s("trig", {
i(1), t"text", i(2), t"text again", i(3)
})
<
These indices don’t "run" through the entire snippet, like they do in
textmate-snippets (`"$1 ${2: $3 $4}"`), they restart at 1 in each nested
snippetNode:
>lua
s("trig", {
i(1), t" ", sn(2, {
t" ", i(1), t" ", i(2)
})
})
<
(roughly equivalent to the given textmate-snippet).
ADDING SNIPPETS *luasnip-basics-adding-snippets*
The snippets for a given filetype have to be added to luasnip via
`ls.add_snippets(filetype, snippets)`. Snippets that should be accessible
globally (in all filetypes) have to be added to the special filetype `all`.
>lua
ls.add_snippets("all", {
s("ternary", {
-- equivalent to "${1:cond} ? ${2:then} : ${3:else}"
i(1, "cond"), t(" ? "), i(2, "then"), t(" : "), i(3, "else")
})
})
<
It is possible to make snippets from one filetype available to another using
`ls.filetype_extend`, more info on that in the section |luasnip-api|.
==============================================================================
2. Node *luasnip-node*
Every node accepts, as its last parameter, an optional table of arguments.
There are some common ones (e.g. `node_ext_opts`, described in
|luasnip-ext_opts|), and some that only apply to some nodes (`user_args` for
both function and dynamicNode). These `opts` are only mentioned if they accept
options that are not common to all nodes.
API *luasnip-node-api*
- `get_jump_index()`: this method returns the jump-index of a node. If a node
doesn’t have a jump-index, this method returns `nil` instead.
- `get_buf_position(opts) -> {from_position, to_position}`:
Determines the range of the buffer occupied by this node. `from`- and
`to_position` are `row,column`-tuples, `0,0`-indexed (first line is 0, first
column is 0) and end-inclusive (see `:h api-indexing`, this is extmarks
indexing).
- `opts`: `table|nil`, options, valid keys are:
- `raw`: `bool`, default `true`. This can be used to switch between
byte-columns (`raw=true`) and visual columns (`raw=false`). This makes a
difference if the line contains characters represented by multiple bytes
in UTF, for example `ÿ`.
==============================================================================
3. Snippets *luasnip-snippets*
The most direct way to define snippets is `s`:
>lua
s({trig="trigger"}, {})
<
(This snippet is useless beyond serving as a minimal example)
`s(context, nodes, opts) -> snippet`
- `context`: Either table or a string. Passing a string is equivalent to passing
>lua
{
trig = context
}
<
The following keys are valid:
- `trig`: string, plain text by default. The only entry that must be given.
- `name`: string, can be used by e.g. `nvim-compe` to identify the snippet.
- `dscr`: string, description of the snippet, -separated or table
for multiple lines.
- `wordTrig`: boolean, if true, the snippet is only expanded if the word
(`[%w_]+`) before the cursor matches the trigger entirely.
True by default.
- `regTrig`: boolean, whether the trigger should be interpreted as a
lua pattern. False by default.
- `docstring`: string, textual representation of the snippet, specified like
`dscr`. Overrides docstrings loaded from json.
- `docTrig`: string, for snippets triggered using a lua pattern: define the
trigger that is used during docstring-generation.
- `hidden`: boolean, hint for completion-engines.
If set, the snippet should not show up when querying snippets.
- `priority`: positive number, Priority of the snippet, 1000 by default.
Snippets with high priority will be matched to a trigger before those with a
lower one.
The priority for multiple snippets can also be set in `add_snippets`.
- `snippetType`: string, should be either `snippet` or `autosnippet` (ATTENTION:
singular form is used), decides whether this snippet has to be triggered by
`ls.expand()` or whether is triggered automatically (don’t forget to set
`ls.config.setup({ enable_autosnippets = true })` if you want to use this
feature). If unset it depends on how the snippet is added of which type the
snippet will be.
- `condition`: `fn(line_to_cursor, matched_trigger, captures) -> bool`, where
- `line_to_cursor`: `string`, the line up to the cursor.
- `matched_trigger`: `string`, the fully matched trigger (can be retrieved
from `line_to_cursor`, but we already have that info here :D)
- `captures`: if the trigger is pattern, this list contains the
capture-groups. Again, could be computed from `line_to_cursor`, but we
already did so.
- `show_condition`: `f(line_to_cursor) -> bool`.
- `line_to_cursor`: `string`, the line up to the cursor.
This function is (should be) evaluated by completion engines, indicating
whether the snippet should be included in current completion candidates.
Defaults to a function returning `true`.
This is different from `condition` because `condition` is evaluated by
LuaSnip on snippet expansion (and thus has access to the matched trigger and
captures), while `show_condition` is (should be) evaluated by the
completion engines when scanning for available snippet candidates.
- `nodes`: A single node or a list of nodes. The nodes that make up the snippet.
- `opts`: A table with the following valid keys:
- `callbacks`: Contains functions that are called upon entering/leaving a node of
this snippet. For example: to print text upon entering the _second_ node of a
snippet, `callbacks` should be set as follows:
>lua
{
-- position of the node, not the jump-index!!
-- s("trig", {t"first node", t"second node", i(1, "third node")}).
[2] = {
[events.enter] = function(node, _event_args) print("2!") end
}
}
<
To register a callback for the snippets’ own events, the key `[-1]` may be
used. More info on events in |luasnip-events|
- `child_ext_opts`, `merge_child_ext_opts`: Control `ext_opts` applied to the
children of this snippet. More info on those in the |luasnip-ext_opts|-section.
The `opts`-table, as described here, can also be passed to e.g. `snippetNode`
and `indentSnippetNode`. It is also possible to set `condition` and
`show_condition` (described in the documentation of the `context`-table) from
`opts`. They should, however, not be set from both.
DATA *luasnip-snippets-data*
Snippets contain some interesting tables during runtime:
- `snippet.env`: Contains variables used in the LSP-protocol, for example
`TM_CURRENT_LINE` or `TM_FILENAME`. It’s possible to add customized variables
here too, check |luasnip-variables-environment-namespaces|
- `snippet.captures`: If the snippet was triggered by a pattern (`regTrig`), and
the pattern contained capture-groups, they can be retrieved here.
- `snippet.trigger`: The string that triggered this snippet. Again, only
interesting if the snippet was triggered through `regTrig`, for getting the
full match.
These variables/tables primarily come in handy in `dynamic/functionNodes`,
where the snippet can be accessed through the immediate parent
(`parent.snippet`), which is passed to the function. (in most cases `parent ==
parent.snippet`, but the `parent` of the dynamicNode is not always the
surrounding snippet, it could be a `snippetNode`).
API *luasnip-snippets-api*
- `invalidate()`: call this method to effectively remove the snippet. The
snippet will no longer be able to expand via `expand` or `expand_auto`. It
will also be hidden from lists (at least if the plugin creating the list
respects the `hidden`-key), but it might be necessary to call
`ls.refresh_notify(ft)` after invalidating snippets.
==============================================================================
4. TextNode *luasnip-textnode*
The most simple kind of node; just text.
>lua
s("trigger", { t("Wow! Text!") })
<
This snippet expands to
>
Wow! Text!⎵
<
where ⎵ is the cursor.
Multiline strings can be defined by passing a table of lines rather than a
string:
>lua
s("trigger", {
t({"Wow! Text!", "And another line."})
})
<
`t(text, node_opts)`:
- `text`: `string` or `string[]`
- `node_opts`: `table`, see |luasnip-node|
==============================================================================
5. InsertNode *luasnip-insertnode*
These Nodes contain editable text and can be jumped to- and from (e.g.
traditional placeholders and tabstops, like `$1` in textmate-snippets).
The functionality is best demonstrated with an example:
>lua
s("trigger", {
t({"After expanding, the cursor is here ->"}), i(1),
t({"", "After jumping forward once, cursor is here ->"}), i(2),
t({"", "After jumping once more, the snippet is exited there ->"}), i(0),
})
<
The Insert Nodes are visited in order `1,2,3,..,n,0`. (The jump-index 0 also
_has_ to belong to an `insertNode`!) So the order of InsertNode-jumps is as
follows:
1. After expansion, the cursor is at InsertNode 1,2. after jumping forward once at InsertNode 2,3. and after jumping forward again at InsertNode 0.
If no 0-th InsertNode is found in a snippet, one is automatically inserted
after all other nodes.
The jump-order doesn’t have to follow the "textual" order of the nodes:
>lua
s("trigger", {
t({"After jumping forward once, cursor is here ->"}), i(2),
t({"", "After expanding, the cursor is here ->"}), i(1),
t({"", "After jumping once more, the snippet is exited there ->"}), i(0),
})
<
The above snippet will behave as follows:
1. After expansion, we will be at InsertNode 1.2. After jumping forward, we will be at InsertNode 2.3. After jumping forward again, we will be at InsertNode 0.
An **important** (because here Luasnip differs from other snippet engines)
detail is that the jump-indices restart at 1 in nested snippets:
>lua
s("trigger", {
i(1, "First jump"),
t(" :: "),
sn(2, {
i(1, "Second jump"),
t" : ",
i(2, "Third jump")
})
})
<
as opposed to e.g. the textmate syntax, where tabstops are snippet-global:
>snippet
${1:First jump} :: ${2: ${3:Third jump} : ${4:Fourth jump}}
<
(this is not exactly the same snippet of course, but as close as possible) (the
restart-rule only applies when defining snippets in lua, the above
textmate-snippet will expand correctly when parsed).
`i(jump_index, text, node_opts)`
- `jump_index`: `number`, this determines when this node will be jumped to (see
|luasnip-basics-jump-index|).
- `text`: `string|string[]`, a single string for just one line, a list with >1
entries for multiple lines.
This text will be SELECTed when the `insertNode` is jumped into.
- `node_opts`: `table`, described in |luasnip-node|
If the `jump_index` is `0`, replacing its’ `text` will leave it outside the
`insertNode` (for reasons, check out Luasnip#110).
==============================================================================
6. FunctionNode *luasnip-functionnode*
Function Nodes insert text based on the content of other nodes using a
user-defined function:
>lua
local function fn(
args, -- text from i(2) in this example i.e. { { "456" } }
parent, -- parent snippet or parent node
user_args -- user_args from opts.user_args
)
return '[' .. args[1][1] .. user_args .. ']'
end
s("trig", {
i(1), t '<-i(1) ',
f(fn, -- callback (args, parent, user_args) -> string
{2}, -- node indice(s) whose text is passed to fn, i.e. i(2)
{ user_args = { "user_args_value" }} -- opts
),
t ' i(2)->', i(2), t '<-i(2) i(0)->', i(0)
})
<
`f(fn, argnode_references, node_opts)`: - `fn`: `function(argnode_text, parent,
user_args1,...,user_argsn) -> text` - `argnode_text`: `string[][]`, the text
currently contained in the argnodes (e.g. `{{line1}, {line1, line2}}`). The
snippet indent will be removed from all lines following the first.
- `parent`: The immediate parent of the `functionNode`. It is included here as it
allows easy access to some information that could be useful in functionNodes
(see |luasnip-snippets-data| for some examples). Many snippets access the
surrounding snippet just as `parent`, but if the `functionNode` is nested
within a `snippetNode`, the immediate parent is a `snippetNode`, not the
surrounding snippet (only the surrounding snippet contains data like `env` or
`captures`).
- `user_args`: The `user_args` passed in `opts`. Note that there may be multiple
user_args (e.g. `user_args1, ..., user_argsn`).
`fn` shall return a string, which will be inserted as is, or a table of strings
for multiline strings, where all lines following the first will be prefixed
with the snippets’ indentation.
- `argnode_references`: `node_reference[]|node_refernce|nil`. Either no, a
single, or multiple |luasnip-node-reference|s. Changing any of these will
trigger a re-evaluation of `fn`, and insertion of the updated text. If no node
reference is passed, the `functionNode` is evaluated once upon expansion.
- `node_opts`: `table`, see |luasnip-node|. One additional key is supported:
- `user_args`: `any[]`, these will be passed to `fn` as `user_arg1`-`user_argn`.
These make it easier to reuse similar functions, for example a functionNode
that wraps some text in different delimiters (`()`, `[]`, …).
>lua
local function reused_func(_,_, user_arg1)
return user_arg1
end
s("trig", {
f(reused_func, {}, {
user_args = {"text"}
}),
f(reused_func, {}, {
user_args = {"different text"}
}),
})
<
**Examples**:
- Use captures from the regex trigger using a functionNode:
>lua
s({trig = "b(%d)", regTrig = true},
f(function(args, snip) return
"Captured Text: " .. snip.captures[1] .. "." end, {})
)
<
- `argnodes_text` during function evaluation:
>lua
s("trig", {
i(1, "text_of_first"),
i(2, {"first_line_of_second", "second_line_of_second"}),
f(function(args, snip)
--here
-- order is 2,1, not 1,2!!
end, {2, 1} )})
<
At `--here`, `args` would look as follows (provided no text was changed after
expansion):
>lua
args = {
{"first_line_of_second", "second_line_of_second"},
{"text_of_first"}
}
<
- |luasnip-absolute-indexer|:
>lua
s("trig", {
i(1, "text_of_first"),
i(2, {"first_line_of_second", "second_line_of_second"}),
f(function(args, snip)
-- just concat first lines of both.
return args[1][1] .. args[2][1]
end, {ai[2], ai[1]} )})
<
If the function only performs simple operations on text, consider using the
`lambda` from `luasnip.extras` (See |luasnip-extras-lambda|)
==============================================================================
7. Node Reference *luasnip-node-reference*
Node references are used to refer to other nodes in various parts of
luasnip’s API. For example, argnodes in functionNode, dynamicNode or lambda
are node references. These references can be either of: - `number`: the
jump-index of the node. This will be resolved relative to the parent of the
node this is passed to. (So, only nodes with the same parent can be referenced.
This is very easy to grasp, but also limiting) - `absolute_indexer`: the
absolute position of the node. This will come in handy if the node that is
being referred to is not in the same snippet/snippetNode as the one the node
reference is passed to (More in |luasnip-absolute-indexer|). - `node`: just the
node. Usage of this is discouraged since it can lead to subtle errors (for
example, if the node passed here is captured in a closure and therefore not
copied with the remaining tables in the snippet; there’s a big comment about
just this in commit 8bfbd61).
==============================================================================
8. ChoiceNode *luasnip-choicenode*
ChoiceNodes allow choosing between multiple nodes.
>lua
s("trig", c(1, {
t("Ugh boring, a text node"),
i(nil, "At least I can edit something now..."),
f(function(args) return "Still only counts as text!!" end, {})
}))
<
`c(jump_index, choices, node_opts)`
- `jump_index`: `number`, since choiceNodes can be jumped to, they need a
jump-index (Info in |luasnip-basics-jump-index|).
- `choices`: `node[]|node`, the choices. The first will be initialliy active.
A list of nodes will be turned into a `snippetNode`.
- `node_opts`: `table`. `choiceNode` supports the keys common to all nodes
described in |luasnip-node|, and one additional key:
- `restore_cursor`: `false` by default. If it is set, and the node that was being
edited also appears in the switched to choice (can be the case if a
`restoreNode` is present in both choice) the cursor is restored relative to
that node. The default is `false` as enabling might lead to decreased
performance. It’s possible to override the default by wrapping the
`choiceNode` constructor in another function that sets `opts.restore_cursor` to
`true` and then using that to construct `choiceNode`s:
>lua
local function restore_cursor_choice(pos, choices, opts)
if opts then
opts.restore_cursor = true
else
opts = {restore_cursor = true}
end
return c(pos, choices, opts)
end
<
Jumpable nodes that normally expect an index as their first parameter don’t
need one inside a choiceNode; their jump-index is the same as the
choiceNodes’.
As it is only possible (for now) to change choices from within the choiceNode,
make sure that all of the choices have some place for the cursor to stop at!
This means that in `sn(nil, {...nodes...})` `nodes` has to contain e.g. an
`i(1)`, otherwise luasnip will just "jump through" the nodes, making it
impossible to change the choice.
>lua
c(1, {
t"some text", -- textNodes are just stopped at.
i(nil, "some text"), -- likewise.
sn(nil, {t"some text"}) -- this will not work!
sn(nil, {i(1), t"some text"}) -- this will.
})
<
The active choice for a choiceNode can be changed by either calling one of
`ls.change_choice(1)` (forwards) or `ls.change_choice(-1)` (backwards), or by
calling `ls.set_choice(choice_indx)`.
One way to easily interact with choiceNodes is binding `change_choice(1/-1)` to
keys:
>lua
-- set keybinds for both INSERT and VISUAL.
vim.api.nvim_set_keymap("i", "<C-n>", "<Plug>luasnip-next-choice", {})
vim.api.nvim_set_keymap("s", "<C-n>", "<Plug>luasnip-next-choice", {})
vim.api.nvim_set_keymap("i", "<C-p>", "<Plug>luasnip-prev-choice", {})
vim.api.nvim_set_keymap("s", "<C-p>", "<Plug>luasnip-prev-choice", {})
<
Apart from this, there is also a picker (see |luasnip-select_choice| where no
cycling is necessary and any choice can be selected right away, via
`vim.ui.select`.
==============================================================================
9. SnippetNode *luasnip-snippetnode*
SnippetNodes directly insert their contents into the surrounding snippet. This
is useful for `choiceNode`s, which only accept one child, or `dynamicNode`s,
where nodes are created at runtime and inserted as a `snippetNode`.
Their syntax is similar to `s`, however, where snippets require a table
specifying when to expand, `snippetNode`s, similar to `insertNode`s, expect a
jump-index.
>lua
s("trig", sn(1, {
t("basically just text "),
i(1, "And an insertNode.")
}))
<
`sn(jump_index, nodes, node_opts)`
- `jump_index`: `number`, the usual |luasnip-jump-index|.
- `nodes`: `node[]|node`, just like for `s`.
Note that `snippetNode`s don’t accept an `i(0)`, so the jump-indices of the nodes
inside them have to be in `1,2,...,n`.
- `node_opts`: `table`: again, the keys common to all nodes (documented in
|luasnip-node|) are supported, but also
- `callbacks`,
- `child_ext_opts` and
- `merge_child_ext_opts`,
which are further explained in |luasnip-snippets|.
==============================================================================
10. IndentSnippetNode *luasnip-indentsnippetnode*
By default, all nodes are indented at least as deep as the trigger. With these
nodes it’s possible to override that behaviour:
>lua
s("isn", {
isn(1, {
t({"This is indented as deep as the trigger",
"and this is at the beginning of the next line"})
}, "")
})
<
(Note the empty string passed to isn).
Indent is only applied after linebreaks, so it’s not possible to remove
indent on the line where the snippet was triggered using `ISN` (That is
possible via regex triggers where the entire line before the trigger is
matched).
Another nice use case for `ISN` is inserting text, e.g. `//` or some other
comment string before the nodes of the snippet:
>lua
s("isn2", {
isn(1, t({"//This is", "A multiline", "comment"}), "$PARENT_INDENT//")
})
<
Here the `//` before `This is` is important, once again, because indent is only
applied after linebreaks.
To enable such usage, `$PARENT_INDENT` in the indentstring is replaced by the
parent’s indent.
`isn(jump_index, nodes, indentstring, node_opts)`
All of these parameters except `indentstring` are exactly the same as in
|luasnip-snippetnode|.
- `indentstring`: `string`, will be used to indent the nodes inside this
`snippetNode`.
All occurences of `"$PARENT_INDENT"` are replaced with the actual indent of
the parent.
==============================================================================
11. DynamicNode *luasnip-dynamicnode*
Very similar to functionNode, but returns a snippetNode instead of just text,
which makes them very powerful as parts of the snippet can be changed based on
user input.
`d(jump_index, function, node-references, opts)`:
- `jump_index`: `number`, just like all jumpable nodes, its’ position in the
jump-list (|luasnip-basics-jump-index|).
- `function`: `fn(args, parent, old_state, user_args) -> snippetNode` This
function is called when the argnodes’ text changes. It should generate and
return (wrapped inside a `snippetNode`) nodes, which will be inserted at the
dynamicNode’s place. `args`, `parent` and `user_args` are also explained in
|luasnip-functionnode|
- `args`: `table of text` (`{{"node1line1", "node1line2"}, {"node2line1"}}`)
from nodes the `dynamicNode` depends on.
- `parent`: the immediate parent of the `dynamicNode`.
- `old_state`: a user-defined table. This table may contain anything; its
intended usage is to preserve information from the previously generated
`snippetNode`. If the `dynamicNode` depends on other nodes, it may be
reconstructed, which means all user input (text inserted in `insertNodes`,
changed choices) to the previous `dynamicNode` is lost.
The `old_state` table must be stored in `snippetNode` returned by
the function (`snippetNode.old_state`).
The second example below illustrates the usage of `old_state`.
- `user_args`: passed through from `dynamicNode`-opts; may have more than one
argument.
- `node_references`: `node_reference[]|node_references|nil`,
|luasnip-node-references| to the nodes the dynamicNode depends on: if any of
these trigger an update (for example, if the text inside them changes), the
`dynamicNode`s’ function will be executed, and the result inserted at the
`dynamicNode`s place. (`dynamicNode` behaves exactly the same as `functionNode`
in this regard).
- `opts`: In addition to the common |luasnip-node|-keys, there is, again,
- `user_args`, which is described in |luasnip-functionnode|.
**Examples**:
This `dynamicNode` inserts an `insertNode` which copies the text inside the
first `insertNode`.
>lua
s("trig", {
t"text: ", i(1), t{"", "copy: "},
d(2, function(args)
-- the returned snippetNode doesn't need a position; it's inserted
-- "inside" the dynamicNode.
return sn(nil, {
-- jump-indices are local to each snippetNode, so restart at 1.
i(1, args[1])
})
end,
{1})
})
<
This snippet makes use of `old_state` to count the number of updates.
To store/restore values generated by the `dynamicNode` or entered into
`insert/choiceNode`, consider using the shortly-introduced `restoreNode`
instead of `old_state`.
>lua
local function count(_, _, old_state)
old_state = old_state or {
updates = 0
}
old_state.updates = old_state.updates + 1
local snip = sn(nil, {
t(tostring(old_state.updates))
})
snip.old_state = old_state
return snip
end
...
ls.add_snippets("all",
s("trig", {
i(1, "change to update"),
d(2, count, {1})
})
)
<
As with `functionNode`, `user_args` can be used to reuse similar `dynamicNode`-
functions.
==============================================================================
12. RestoreNode *luasnip-restorenode*
This node can store and restore a snippetNode as is. This includes changed
choices and changed text. Its’ usage is best demonstrated by an example:
>lua
s("paren_change", {
c(1, {
sn(nil, { t("("), r(1, "user_text"), t(")") }),
sn(nil, { t("["), r(1, "user_text"), t("]") }),
sn(nil, { t("{"), r(1, "user_text"), t("}") }),
}),
}, {
stored = {
-- key passed to restoreNodes.
["user_text"] = i(1, "default_text")
}
})
<
Here the text entered into `user_text` is preserved upon changing choice.
`r(jump_index, key, nodes, node_opts)`:
- `jump_index`, when to jump to this node.
- `key`, `string`: `restoreNode`s with the same key share their content.
- `nodes`, `node[]|node`: the content of the `restoreNode`.
Can either be a single node, or a table of nodes (both of which will be
wrapped inside a `snippetNode`, except if the single node already is a
`snippetNode`).
The content for a given key may be defined multiple times, but if the
contents differ, it’s undefined which will actually be used.
If a key’s content is defined in a `dynamicNode`, it will not be initially
used for `restoreNodes` outside that `dynamicNode`. A way around this
limitation is defining the content in the `restoreNode` outside the
`dynamicNode`.
The content for a key may also be defined in the `opts`-parameter of the
snippet-constructor, as seen in the example above. The `stored`-table accepts
the same values as the `nodes`-parameter passed to `r`. If no content is
defined for a key, it defaults to the empty `insertNode`.
An important-to-know limitation of `restoreNode` is that, for a given key, only
one may be visible at a time. See this issue
<https://github.com/L3MON4D3/LuaSnip/issues/234> for details.
The `restoreNode` is especially useful for storing input across updates of a
`dynamicNode`. Consider this:
>lua
local function simple_restore(args, _)
return sn(nil, {i(1, args[1]), i(2, "user_text")})
end
s("rest", {
i(1, "preset"), t{"",""},
d(2, simple_restore, 1)
}),
<
Every time the `i(1)` in the outer snippet is changed, the text inside the
`dynamicNode` is reset to `"user_text"`. This can be prevented by using a
`restoreNode`:
>lua
local function simple_restore(args, _)
return sn(nil, {i(1, args[1]), r(2, "dyn", i(nil, "user_text"))})
end
s("rest", {
i(1, "preset"), t{"",""},
d(2, simple_restore, 1)
}),
<
Now the entered text is stored.
`restoreNode`s indent is not influenced by `indentSnippetNodes` right now. If
that really bothers you feel free to open an issue.
==============================================================================
13. Absolute Indexer *luasnip-absolute-indexer*
The most capable way of referencing nodes (|luasnip-node-reference|). Using
only a |luasnip-jump-index|, accessing an outer `i(1)` isn’t possible from
inside e.g. a snippetNode, since only nodes with the same parent can be
referenced (jump indices are interpreted relative to the parent of the node
that’s passed the reference). The `absolute_indexer` can be used to reference
nodes based on their absolute position in the snippet, which lifts this
restriction.
>lua
s("trig", {
i(1), c(2, {
sn(nil, {
t"cannot access the argnode :(", f(function(args) return args[1] end, {???})
}),
t"sample_text"
})
})
<
Using `absolute_indexer`, it’s possible to do so:
>lua
s("trig", {
i(1), c(2, {
sn(nil, { i(1),
t"can access the argnode :)", f(function(args) return args[1] end, ai[1])
}),
t"sample_text"
})
})
<
There are some quirks in addressing nodes:
>lua
s("trig", {
i(2), -- ai[2]: indices based on jump-index, not position.
sn(1, { -- ai[1]
i(1), -- ai[1][1]
t"lel", -- not addressable.
i(2) -- ai[1][2]
}),
c(3, { -- ai[3]
i(nil), -- ai[3][1]
t"lel", -- ai[3][2]: choices are always addressable.
}),
d(4, function() -- ai[4]
return sn(nil, { -- ai[4][0]
i(1), -- ai[4][0][1]
})
end, {})
}))
r(5, "restore_key", -- ai[5]
i(1) -- ai[5][0][1]: restoreNodes always store snippetNodes.
)
r(6, "restore_key_2", -- ai[6]
sn(nil, { -- ai[6][0]
i(1) -- ai[6][0][1]
})
)
}))
})
<
Note specifically that the index of a dynamicNode differs from that of the
generated snippetNode, and that restoreNodes (internally) always store a
snippetNode, so even if the restoreNode only contains one node, that node has
to be accessed as `ai[restoreNodeIndx][0][1]`.
`absolute_indexer`s’ can be constructed in different ways:
>lua
ai[1][2][3] == ai(1, 2, 3) == ai{1, 2, 3}
<
==============================================================================
14. MultiSnippet *luasnip-multisnippet*
There are situations where it might be comfortable to access a snippet in
different ways. For example, one might want to enable auto-triggering in